Пример #1
0
void ParsedRegexpFilter_base::parse (const Bstr &aFilter)
{
    /// @todo (dmik) parse "rx:<regexp>" string
    //  note, that min/max checks must not be done, when the string
    //  begins with "rx:". These limits are for exact matching only!

    // empty or null string means any match (see #isMatch() below),
    // so we don't apply Min/Max restrictions in this case

    if (!aFilter.isEmpty())
    {
        size_t len = aFilter.length();

        if (mMinLen > 0 && len < mMinLen)
        {
            mNull = mValid = false;
            mErrorPosition = len;
            return;
        }

        if (mMaxLen > 0 && len > mMaxLen)
        {
            mNull = mValid = false;
            mErrorPosition = mMaxLen;
            return;
        }
    }

    mSimple = aFilter;
    mNull = false;
    mValid = true;
    mErrorPosition = 0;
}
Пример #2
0
/**
 *  Initializes itself by fetching error information from the given error info
 *  object.
 */
HRESULT VirtualBoxErrorInfo::init(IErrorInfo *aInfo)
{
    AssertReturn(aInfo, E_FAIL);

    HRESULT rc = S_OK;

    /* We don't return a failure if talking to IErrorInfo fails below to
     * protect ourselves from bad IErrorInfo implementations (the
     * corresponding fields will simply remain null in this case). */

    m_resultCode = S_OK;
    m_resultDetail = 0;
    rc = aInfo->GetGUID(m_IID.asOutParam());
    AssertComRC(rc);
    Bstr bstrComponent;
    rc = aInfo->GetSource(bstrComponent.asOutParam());
    AssertComRC(rc);
    m_strComponent = bstrComponent;
    Bstr bstrText;
    rc = aInfo->GetDescription(bstrText.asOutParam());
    AssertComRC(rc);
    m_strText = bstrText;

    return S_OK;
}
STDMETHODIMP VRDEServer::COMGETTER(AuthLibrary) (BSTR *aLibrary)
{
    CheckComArgOutPointerValid(aLibrary);

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    Bstr bstrLibrary;

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
    bstrLibrary = mData->mAuthLibrary;
    alock.release();

    if (bstrLibrary.isEmpty())
    {
        /* Get the global setting. */
        ComPtr<ISystemProperties> systemProperties;
        HRESULT hrc = mParent->getVirtualBox()->COMGETTER(SystemProperties)(systemProperties.asOutParam());

        if (SUCCEEDED(hrc))
            hrc = systemProperties->COMGETTER(VRDEAuthLibrary)(bstrLibrary.asOutParam());

        if (FAILED(hrc))
            return setError(hrc, "failed to query the library setting\n");
    }

    bstrLibrary.cloneTo(aLibrary);

    return S_OK;
}
Пример #4
0
bool
SITree::modify(const char* _str, unsigned _len, int _val)
{
	if (_str == NULL || _len == 0)
	{
		printf("error in SITree-modify: empty string\n");
		return false;
	}
	this->CopyToTransfer(_str, _len, 1);

	this->request = 0;
	const Bstr* _key = &transfer[1];
	Bstr bstr = *_key;
	int store;
	SINode* ret = this->find(_key, &store, true);
	if (ret == NULL || store == -1 || bstr != *(ret->getKey(store)))	//tree is empty or not found
	{
		bstr.clear();
		return false;
	}
	ret->setValue(_val, store);
	ret->setDirty();
	this->TSM->request(request);
	bstr.clear();
	return true;
}
Пример #5
0
//this function is useful for search and modify, and range-query 
SINode*		//return the first key's position that >= *_key
SITree::find(const Bstr* _key, int* _store, bool ifmodify)
{											//to assign value for this->bstr, function shouldn't be const!
	if (this->root == NULL)
		return NULL;						//SITree Is Empty
	SINode* p = root;
	int i, j;
	Bstr bstr = *_key;					//local Bstr: multiple delete
	while (!p->isLeaf())
	{
		if (ifmodify)
			p->setDirty();
		//j = p->getNum();
		//for(i = 0; i < j; ++i)				//BETTER(Binary-Search)
		//if(bstr < *(p->getKey(i)))
		//break;
		i = p->searchKey_less(bstr);

		p = p->getChild(i);
		this->prepare(p);
	}

	j = p->getNum();
	//for(i = 0; i < j; ++i)
	//if(bstr <= *(p->getKey(i)))
	//break;
	i = p->searchKey_lessEqual(bstr);

	if (i == j)
		*_store = -1;	//Not Found
	else
		*_store = i;
	bstr.clear();
	return p;
}
STDMETHODIMP GuestFileEventListener::HandleEvent(VBoxEventType_T aType, IEvent *aEvent)
{
    switch (aType)
    {
    case VBoxEventType_OnGuestFileStateChanged:
    {
        HRESULT rc;
        do
        {
            ComPtr<IGuestFileStateChangedEvent> pEvent = aEvent;
            Assert(!pEvent.isNull());

            ComPtr<IGuestFile> pProcess;
            CHECK_ERROR_BREAK(pEvent, COMGETTER(File)(pProcess.asOutParam()));
            AssertBreak(!pProcess.isNull());
            FileStatus_T fileSts;
            CHECK_ERROR_BREAK(pEvent, COMGETTER(Status)(&fileSts));
            Bstr strPath;
            CHECK_ERROR_BREAK(pProcess, COMGETTER(FileName)(strPath.asOutParam()));
            ULONG uID;
            CHECK_ERROR_BREAK(pProcess, COMGETTER(Id)(&uID));

            RTPrintf("File ID=%RU32 \"%s\" changed status to [%s]\n",
                     uID, Utf8Str(strPath).c_str(), gctlFileStatusToText(fileSts));

        } while (0);
        break;
    }

    default:
        AssertFailed();
    }

    return S_OK;
}
Пример #7
0
bool
SITree::search(const char* _str, unsigned _len, int* _val)
{
	if (_str == NULL || _len == 0)
	{
		printf("error in SITree-search: empty string\n");
		*_val = -1;
		return false;
	}
	this->CopyToTransfer(_str, _len, 1);

	request = 0;
	Bstr bstr = this->transfer[1];	//not to modify its memory
	int store;
	SINode* ret = this->find(&transfer[1], &store, false);
	if (ret == NULL || store == -1 || bstr != *(ret->getKey(store)))	//tree is empty or not found
	{
		bstr.clear();
		return false;
	}
	*_val = ret->getValue(store);
	this->TSM->request(request);
	bstr.clear();
	return true;
}
Пример #8
0
/**
 * Helper function used with "VBoxManage snapshot ... dump". Called from DumpSnapshot()
 * for each hard disk attachment found in a virtual machine. This then writes out the
 * root (base) medium for that hard disk attachment and recurses into the children
 * tree of that medium, correlating it with the snapshots of the machine.
 * @param pCurrentStateMedium constant, the medium listed in the current machine data (latest diff image).
 * @param pMedium variant, initially the base medium, then a child of the base medium when recursing.
 * @param pRootSnapshot constant, the root snapshot of the machine, if any; this then looks into the child snapshots.
 * @param pCurrentSnapshot constant, the machine's current snapshot (so we can mark it in the output).
 * @param uLevel variant, the recursion level for output indentation.
 */
void DumpMediumWithChildren(ComPtr<IMedium> &pCurrentStateMedium,
                            ComPtr<IMedium> &pMedium,
                            ComPtr<ISnapshot> &pRootSnapshot,
                            ComPtr<ISnapshot> &pCurrentSnapshot,
                            uint32_t uLevel)
{
    HRESULT rc;
    do
    {
        // print this medium
        Bstr bstrMediumName;
        CHECK_ERROR_BREAK(pMedium, COMGETTER(Name)(bstrMediumName.asOutParam()));
        RTPrintf("%*s  \"%ls\"%s\n",
                 uLevel * 2, "",            // indent
                 bstrMediumName.raw(),
                 (pCurrentStateMedium == pMedium) ? " (CURSTATE)" : "");

        // find and print the snapshot that uses this particular medium (diff image)
        FindAndPrintSnapshotUsingMedium(pMedium, pRootSnapshot, pCurrentSnapshot, uLevel, 0);

        // recurse into children
        SafeIfaceArray<IMedium> aChildren;
        CHECK_ERROR_BREAK(pMedium, COMGETTER(Children)(ComSafeArrayAsOutParam(aChildren)));
        for (uint32_t i = 0;
                i < aChildren.size();
                ++i)
        {
            ComPtr<IMedium> pChild(aChildren[i]);
            DumpMediumWithChildren(pCurrentStateMedium, pChild, pRootSnapshot, pCurrentSnapshot, uLevel + 1);
        }
    } while (0);
}
Пример #9
0
/**
 * @interface_method_impl{PDMIPCIRAWUP,pfnPciDeviceConstructComplete}
 */
DECLCALLBACK(int) PCIRawDev::drvDeviceConstructComplete(PPDMIPCIRAWCONNECTOR pInterface, const char *pcszName,
                                                        uint32_t uHostPCIAddress, uint32_t uGuestPCIAddress,
                                                        int rc)
{
    PDRVMAINPCIRAWDEV pThis = RT_FROM_CPP_MEMBER(pInterface, DRVMAINPCIRAWDEV, IConnector);
    Console *pConsole = pThis->pPCIRawDev->getParent();
    const ComPtr<IMachine>& machine = pConsole->machine();
    ComPtr<IVirtualBox> vbox;

    HRESULT hrc = machine->COMGETTER(Parent)(vbox.asOutParam());
    Assert(SUCCEEDED(hrc));

    ComPtr<IEventSource> es;
    hrc = vbox->COMGETTER(EventSource)(es.asOutParam());
    Assert(SUCCEEDED(hrc));

    Bstr bstrId;
    hrc = machine->COMGETTER(Id)(bstrId.asOutParam());
    Assert(SUCCEEDED(hrc));

    ComObjPtr<PCIDeviceAttachment> pda;
    BstrFmt bstrName(pcszName);
    pda.createObject();
    pda->init(machine, bstrName, uHostPCIAddress, uGuestPCIAddress, TRUE);

    Bstr msg("");
    if (RT_FAILURE(rc))
        msg = BstrFmt("runtime error %Rrc", rc);

    fireHostPCIDevicePlugEvent(es, bstrId.raw(), true /* plugged */, RT_SUCCESS(rc) /* success */, pda, msg.raw());

    return VINF_SUCCESS;
}
HRESULT VRDEServer::getAuthLibrary(com::Utf8Str &aLibrary)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
    aLibrary = mData->mAuthLibrary;
    alock.release();

    if (aLibrary.isEmpty())
    {
        /* Get the global setting. */
        ComPtr<ISystemProperties> systemProperties;
        HRESULT hrc = mParent->i_getVirtualBox()->COMGETTER(SystemProperties)(systemProperties.asOutParam());
        if (SUCCEEDED(hrc))
        {
            Bstr strlib;
            hrc = systemProperties->COMGETTER(VRDEAuthLibrary)(strlib.asOutParam());
            if (SUCCEEDED(hrc))
                aLibrary = Utf8Str(strlib).c_str();
        }

        if (FAILED(hrc))
            return setError(hrc, "failed to query the library setting\n");
    }

    return S_OK;
}
Пример #11
0
static RTEXITCODE handleCreate(HandlerArg *a)
{
    /*
     * Parse input.
     */
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, a->argc, a->argv, NULL, 0, 1, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
    int ch = RTGetOpt(&GetState, &ValueUnion);
    if (ch != 0)
        return errorGetOpt(USAGE_HOSTONLYIFS, ch, &ValueUnion);

    /*
     * Do the work.
     */
    ComPtr<IHost> host;
    CHECK_ERROR2I_RET(a->virtualBox, COMGETTER(Host)(host.asOutParam()), RTEXITCODE_FAILURE);

    ComPtr<IHostNetworkInterface> hif;
    ComPtr<IProgress> progress;

    CHECK_ERROR2I_RET(host, CreateHostOnlyNetworkInterface(hif.asOutParam(), progress.asOutParam()), RTEXITCODE_FAILURE);

    /*HRESULT hrc =*/ showProgress(progress);
    CHECK_PROGRESS_ERROR_RET(progress, ("Failed to create the host-only adapter"), RTEXITCODE_FAILURE);

    Bstr bstrName;
    CHECK_ERROR2I(hif, COMGETTER(Name)(bstrName.asOutParam()));

    RTPrintf("Interface '%ls' was successfully created\n", bstrName.raw());

    return RTEXITCODE_SUCCESS;
}
static void listAffectedMetrics(ComPtr<IVirtualBox> aVirtualBox,
                                ComSafeArrayIn(IPerformanceMetric*, aMetrics))
{
    HRESULT rc;
    com::SafeIfaceArray<IPerformanceMetric> metrics(ComSafeArrayInArg(aMetrics));
    if (metrics.size())
    {
        ComPtr<IUnknown> object;
        Bstr metricName;
        RTPrintf("The following metrics were modified:\n\n"
                 "Object     Metric\n"
                 "---------- --------------------\n");
        for (size_t i = 0; i < metrics.size(); i++)
        {
            CHECK_ERROR(metrics[i], COMGETTER(Object)(object.asOutParam()));
            CHECK_ERROR(metrics[i], COMGETTER(MetricName)(metricName.asOutParam()));
            RTPrintf("%-10ls %-20ls\n",
                getObjectName(aVirtualBox, object).raw(), metricName.raw());
        }
        RTPrintf("\n");
    }
    else
    {
        RTMsgError("No metrics match the specified filter!");
    }
}
Пример #13
0
static int NetIfAdpCtl(HostNetworkInterface * pIf, const char *pszAddr, const char *pszOption, const char *pszMask)
{
    Bstr interfaceName;
    pIf->COMGETTER(Name)(interfaceName.asOutParam());
    Utf8Str strName(interfaceName);
    return NetIfAdpCtl(strName.c_str(), pszAddr, pszOption, pszMask);
}
Пример #14
0
/**
 * List media information.
 *
 * @returns See produceList.
 * @param   pVirtualBox         Reference to the IVirtualBox smart pointer.
 * @param   aMedia              Medium objects to list information for.
 * @param   pszParentUUIDStr    String with the parent UUID string (or "base").
 * @param   fOptLong            Long (@c true) or short list format.
 */
static HRESULT listMedia(const ComPtr<IVirtualBox> pVirtualBox,
                         const com::SafeIfaceArray<IMedium> &aMedia,
                         const char *pszParentUUIDStr,
                         bool fOptLong)
{
    HRESULT rc = S_OK;
    for (size_t i = 0; i < aMedia.size(); ++i)
    {
        ComPtr<IMedium> pMedium = aMedia[i];

        rc = showMediumInfo(pVirtualBox, pMedium, pszParentUUIDStr, fOptLong);

        RTPrintf("\n");

        com::SafeIfaceArray<IMedium> children;
        CHECK_ERROR(pMedium, COMGETTER(Children)(ComSafeArrayAsOutParam(children)));
        if (children.size() > 0)
        {
            Bstr uuid;
            pMedium->COMGETTER(Id)(uuid.asOutParam());

            // depth first listing of child media
            rc = listMedia(pVirtualBox, children, Utf8Str(uuid).c_str(), fOptLong);
        }
    }

    return rc;
}
Пример #15
0
/**
 * Determines the maximum balloon size to set for the specified machine.
 *
 * @return  unsigned long           Balloon size (in MB) to set, 0 if no ballooning required.
 * @param   rptrMachine             Pointer to interface of specified machine.
 */
static unsigned long balloonGetMaxSize(const ComPtr<IMachine> &rptrMachine)
{
    /*
     * Try to retrieve the balloon maximum size via the following order:
     *  - command line parameter ("--balloon-max")
     *  Legacy (VBoxBalloonCtrl):
     *  - per-VM parameter ("VBoxInternal/Guest/BalloonSizeMax")
     *  Global:
     *  - global parameter ("VBoxInternal/Guest/BalloonSizeMax")
     *  New:
     *  - per-VM parameter ("VBoxInternal2/Watchdog/BalloonCtrl/BalloonSizeMax")
     *
     *  By default (e.g. if none of above is set), ballooning is disabled.
     */
    unsigned long ulBalloonMax = g_ulMemoryBalloonMaxMB;
    if (!ulBalloonMax)
    {
        int vrc = cfgGetValueULong(g_pVirtualBox, rptrMachine,
                                  "VBoxInternal/Guest/BalloonSizeMax", "VBoxInternal/Guest/BalloonSizeMax", &ulBalloonMax, 0 /* Ballooning disabled */);
        if (RT_FAILURE(vrc))
        {
            /* Try (new) VBoxWatch per-VM approach. */
            Bstr strValue;
            HRESULT rc = rptrMachine->GetExtraData(Bstr("VBoxInternal2/Watchdog/BalloonCtrl/BalloonSizeMax").raw(),
                                                   strValue.asOutParam());
            if (   SUCCEEDED(rc)
                && !strValue.isEmpty())
            {
                ulBalloonMax = Utf8Str(strValue).toUInt32();
            }
        }
    }

    return ulBalloonMax;
}
STDMETHODIMP VirtualBoxErrorInfo::GetGUID (GUID *guid)
{
    Bstr iid;
    HRESULT rc = COMGETTER(InterfaceID) (iid.asOutParam());
    if (SUCCEEDED(rc))
        *guid = Guid(iid).ref();
    return rc;
}
Пример #17
0
void ErrorInfo::init(IVirtualBoxErrorInfo *info)
{
    AssertReturnVoid(info);

    HRESULT rc = E_FAIL;
    bool gotSomething = false;
    bool gotAll = true;
    LONG lrc, lrd;

    rc = info->COMGETTER(ResultCode)(&lrc); mResultCode = lrc;
    gotSomething |= SUCCEEDED(rc);
    gotAll &= SUCCEEDED(rc);

    rc = info->COMGETTER(ResultDetail)(&lrd); mResultDetail = lrd;
    gotSomething |= SUCCEEDED(rc);
    gotAll &= SUCCEEDED(rc);

    Bstr iid;
    rc = info->COMGETTER(InterfaceID)(iid.asOutParam());
    gotSomething |= SUCCEEDED(rc);
    gotAll &= SUCCEEDED(rc);
    if (SUCCEEDED(rc))
    {
        mInterfaceID = iid;
        GetInterfaceNameByIID(mInterfaceID.ref(), mInterfaceName.asOutParam());
    }

    rc = info->COMGETTER(Component)(mComponent.asOutParam());
    gotSomething |= SUCCEEDED(rc);
    gotAll &= SUCCEEDED(rc);

    rc = info->COMGETTER(Text)(mText.asOutParam());
    gotSomething |= SUCCEEDED(rc);
    gotAll &= SUCCEEDED(rc);

    m_pNext = NULL;

    ComPtr<IVirtualBoxErrorInfo> next;
    rc = info->COMGETTER(Next)(next.asOutParam());
    if (SUCCEEDED(rc) && !next.isNull())
    {
        m_pNext = new ErrorInfo(next);
        Assert(m_pNext != NULL);
        if (!m_pNext)
            rc = E_OUTOFMEMORY;
    }

    gotSomething |= SUCCEEDED(rc);
    gotAll &= SUCCEEDED(rc);

    mIsBasicAvailable = gotSomething;
    mIsFullAvailable = gotAll;

    mErrorInfo = info;

    AssertMsg(gotSomething, ("Nothing to fetch!\n"));
}
HRESULT HostNetworkInterface::i_setVirtualBox(VirtualBox *pVirtualBox)
{
    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    AssertReturn(mVirtualBox != pVirtualBox, S_OK);

    unconst(mVirtualBox) = pVirtualBox;

#if !defined(RT_OS_WINDOWS)
    /* If IPv4 address hasn't been initialized */
    if (m.IPAddress == 0 && mIfType == HostNetworkInterfaceType_HostOnly)
    {
        Bstr tmpAddr, tmpMask;
        HRESULT hrc = mVirtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
                                                        mInterfaceName.c_str()).raw(),
                                                tmpAddr.asOutParam());
        if (FAILED(hrc) || tmpAddr.isEmpty())
            tmpAddr = getDefaultIPv4Address(mInterfaceName);

        hrc = mVirtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
                                                mInterfaceName.c_str()).raw(),
                                        tmpMask.asOutParam());
        if (FAILED(hrc) || tmpMask.isEmpty())
            tmpMask = Bstr(VBOXNET_IPV4MASK_DEFAULT);

        m.IPAddress = inet_addr(Utf8Str(tmpAddr).c_str());
        m.networkMask = inet_addr(Utf8Str(tmpMask).c_str());
    }

    if (m.IPV6Address.isEmpty())
    {
        Bstr bstrIPV4Addr;
        Bstr tmpPrefixLen;
        HRESULT hrc = mVirtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
                                                        mInterfaceName.c_str()).raw(),
                                                bstrIPV4Addr.asOutParam());
        if (SUCCEEDED(hrc))
        {
            m.IPV6Address = bstrIPV4Addr;
            if (!m.IPV6Address.isEmpty())
            {
                hrc = mVirtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6PrefixLen",
                                                        mInterfaceName.c_str()).raw(),
                                                tmpPrefixLen.asOutParam());
                if (SUCCEEDED(hrc) && !tmpPrefixLen.isEmpty())
                    m.IPV6NetworkMaskPrefixLength = Utf8Str(tmpPrefixLen).toUInt32();
                else
                    m.IPV6NetworkMaskPrefixLength = 64;
            }
        }
    }
#endif

    return S_OK;
}
static int vmListBuild()
{
    serviceLogVerbose(("Building VM list ...\n"));

    int rc = RTCritSectEnter(&g_csMachines);
    if (RT_SUCCESS(rc))
    {
        /*
         * Make sure the list is empty.
         */
        g_mapVM.clear();

        /*
         * Get the list of all _running_ VMs
         */
        com::SafeIfaceArray<IMachine> machines;
        HRESULT hrc = g_pVirtualBox->COMGETTER(Machines)(ComSafeArrayAsOutParam(machines));
        if (SUCCEEDED(hrc))
        {
            /*
             * Iterate through the collection
             */
            for (size_t i = 0; i < machines.size(); ++i)
            {
                if (machines[i])
                {
                    Bstr strUUID;
                    CHECK_ERROR_BREAK(machines[i], COMGETTER(Id)(strUUID.asOutParam()));

                    BOOL fAccessible;
                    CHECK_ERROR_BREAK(machines[i], COMGETTER(Accessible)(&fAccessible));
                    if (!fAccessible)
                    {
                        serviceLogVerbose(("Machine \"%ls\" is inaccessible, skipping\n",
                                           strUUID.raw()));
                        continue;
                    }

                    rc = machineAdd(strUUID);
                    if (RT_FAILURE(rc))
                        break;
                }
            }

            if (!machines.size())
                serviceLogVerbose(("No machines to add found at the moment!\n"));
        }

        int rc2 = RTCritSectLeave(&g_csMachines);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }
    return rc;
}
Пример #20
0
STDMETHODIMP Guest::COMGETTER(AdditionsVersion)(BSTR *a_pbstrAdditionsVersion)
{
    CheckComArgOutPointerValid(a_pbstrAdditionsVersion);

    AutoCaller autoCaller(this);
    HRESULT hrc = autoCaller.rc();
    if (SUCCEEDED(hrc))
    {
        AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

        /*
         * Return the ReportGuestInfo2 version info if available.
         */
        if (   !mData.mAdditionsVersionNew.isEmpty()
            || mData.mAdditionsRunLevel <= AdditionsRunLevelType_None)
            mData.mAdditionsVersionNew.cloneTo(a_pbstrAdditionsVersion);
        else
        {
            /*
             * If we're running older guest additions (< 3.2.0) try get it from
             * the guest properties.  Detected switched around Version and
             * Revision in early 3.1.x releases (see r57115).
             */
            ComPtr<IMachine> ptrMachine = mParent->machine();
            alock.release(); /* No need to hold this during the IPC fun. */

            Bstr bstr;
            hrc = ptrMachine->GetGuestPropertyValue(Bstr("/VirtualBox/GuestAdd/Version").raw(), bstr.asOutParam());
            if (   SUCCEEDED(hrc)
                && !bstr.isEmpty())
            {
                Utf8Str str(bstr);
                if (str.count('.') == 0)
                    hrc = ptrMachine->GetGuestPropertyValue(Bstr("/VirtualBox/GuestAdd/Revision").raw(), bstr.asOutParam());
                str = bstr;
                if (str.count('.') != 2)
                    hrc = E_FAIL;
            }

            if (SUCCEEDED(hrc))
                bstr.detachTo(a_pbstrAdditionsVersion);
            else
            {
                /* Returning 1.4 is better than nothing. */
                alock.acquire();
                mData.mInterfaceVersion.cloneTo(a_pbstrAdditionsVersion);
                hrc = S_OK;
            }
        }
    }
    return hrc;
}
Пример #21
0
/**
 * List host information.
 *
 * @returns See produceList.
 * @param   pVirtualBox         Reference to the IVirtualBox smart pointer.
 */
static HRESULT listHostInfo(const ComPtr<IVirtualBox> pVirtualBox)
{
    HRESULT rc;
    ComPtr<IHost> Host;
    CHECK_ERROR(pVirtualBox, COMGETTER(Host)(Host.asOutParam()));

    RTPrintf("Host Information:\n\n");

    LONG64      u64UtcTime = 0;
    CHECK_ERROR(Host, COMGETTER(UTCTime)(&u64UtcTime));
    RTTIMESPEC  timeSpec;
    char        szTime[32];
    RTPrintf("Host time: %s\n", RTTimeSpecToString(RTTimeSpecSetMilli(&timeSpec, u64UtcTime), szTime, sizeof(szTime)));

    ULONG processorOnlineCount = 0;
    CHECK_ERROR(Host, COMGETTER(ProcessorOnlineCount)(&processorOnlineCount));
    RTPrintf("Processor online count: %lu\n", processorOnlineCount);
    ULONG processorCount = 0;
    CHECK_ERROR(Host, COMGETTER(ProcessorCount)(&processorCount));
    RTPrintf("Processor count: %lu\n", processorCount);
    ULONG processorOnlineCoreCount = 0;
    CHECK_ERROR(Host, COMGETTER(ProcessorOnlineCoreCount)(&processorOnlineCoreCount));
    RTPrintf("Processor online core count: %lu\n", processorOnlineCoreCount);
    ULONG processorCoreCount = 0;
    CHECK_ERROR(Host, COMGETTER(ProcessorCoreCount)(&processorCoreCount));
    RTPrintf("Processor core count: %lu\n", processorCoreCount);
    ULONG processorSpeed = 0;
    Bstr processorDescription;
    for (ULONG i = 0; i < processorCount; i++)
    {
        CHECK_ERROR(Host, GetProcessorSpeed(i, &processorSpeed));
        if (processorSpeed)
            RTPrintf("Processor#%u speed: %lu MHz\n", i, processorSpeed);
        else
            RTPrintf("Processor#%u speed: unknown\n", i);
        CHECK_ERROR(Host, GetProcessorDescription(i, processorDescription.asOutParam()));
        RTPrintf("Processor#%u description: %ls\n", i, processorDescription.raw());
    }

    ULONG memorySize = 0;
    CHECK_ERROR(Host, COMGETTER(MemorySize)(&memorySize));
    RTPrintf("Memory size: %lu MByte\n", memorySize);

    ULONG memoryAvailable = 0;
    CHECK_ERROR(Host, COMGETTER(MemoryAvailable)(&memoryAvailable));
    RTPrintf("Memory available: %lu MByte\n", memoryAvailable);

    Bstr operatingSystem;
    CHECK_ERROR(Host, COMGETTER(OperatingSystem)(operatingSystem.asOutParam()));
    RTPrintf("Operating system: %ls\n", operatingSystem.raw());

    Bstr oSVersion;
    CHECK_ERROR(Host, COMGETTER(OSVersion)(oSVersion.asOutParam()));
    RTPrintf("Operating system version: %ls\n", oSVersion.raw());
    return rc;
}
bool HostNetworkInterface::isInConfigFile(void)
{
    /* We care about host-only adapters only */
    if (mIfType != HostNetworkInterfaceType_HostOnly)
        return true;

    Assert(mVirtualBox != NULL);
    if (mVirtualBox == NULL)
        return false; /* Trigger config update, which will fail with proper return code */
    Bstr tmpName;
    mVirtualBox->GetExtraData(Bstr(Utf8StrFmt("HostOnly/{%RTuuid}/Name", mGuid)).raw(), tmpName.asOutParam());
    return (tmpName.isNotEmpty() && tmpName == mInterfaceName);

}
Пример #23
0
/**
 * Issued by the guest when a guest user changed its state.
 *
 * @return  IPRT status code.
 * @param   aUser               Guest user name.
 * @param   aDomain             Domain of guest user account. Optional.
 * @param   enmState            New state to indicate.
 * @param   pbDetails           Pointer to state details. Optional.
 * @param   cbDetails           Size (in bytes) of state details. Pass 0 if not used.
 */
void Guest::i_onUserStateChange(Bstr aUser, Bstr aDomain, VBoxGuestUserState enmState,
                                const uint8_t *pbDetails, uint32_t cbDetails)
{
    LogFlowThisFunc(("\n"));

    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.rc());

    Bstr strDetails; /** @todo Implement state details here. */

    fireGuestUserStateChangedEvent(mEventSource, aUser.raw(), aDomain.raw(),
                                   (GuestUserState_T)enmState, strDetails.raw());
    LogFlowFuncLeave();
}
static DECLCALLBACK(int) VBoxModAPIMonitorMain(void)
{
    static uint64_t uLastRun = 0;
    uint64_t uNow = RTTimeProgramMilliTS();
    uint64_t uDelta = uNow - uLastRun;
    if (uDelta < 1000) /* Only check every second (or later). */
        return VINF_SUCCESS;
    uLastRun = uNow;

    int vrc = VINF_SUCCESS;
    HRESULT rc;

#ifdef DEBUG
    serviceLogVerbose(("apimon: Checking for API heartbeat (%RU64ms) ...\n",
                       g_ulAPIMonIslnTimeoutMS));
#endif

    do
    {
        Bstr strHeartbeat;
        CHECK_ERROR_BREAK(g_pVirtualBox, GetExtraData(Bstr("Watchdog/APIMonitor/Heartbeat").raw(),
                                                      strHeartbeat.asOutParam()));
        if (   SUCCEEDED(rc)
            && !strHeartbeat.isEmpty()
            && g_strAPIMonIslnLastBeat.compare(strHeartbeat, Bstr::CaseSensitive))
        {
            serviceLogVerbose(("apimon: API heartbeat received, resetting timeout\n"));

            g_uAPIMonIslnLastBeatMS = 0;
            g_strAPIMonIslnLastBeat = strHeartbeat;
        }
        else
        {
            g_uAPIMonIslnLastBeatMS += uDelta;
            if (g_uAPIMonIslnLastBeatMS > g_ulAPIMonIslnTimeoutMS)
            {
                serviceLogVerbose(("apimon: No API heartbeat within time received (%RU64ms)\n",
                                   g_ulAPIMonIslnTimeoutMS));

                vrc = apimonTrigger(g_enmAPIMonIslnResp);
                g_uAPIMonIslnLastBeatMS = 0;
            }
        }
    } while (0);

    if (FAILED(rc))
        vrc = VERR_COM_IPRT_ERROR;

    return vrc;
}
Пример #25
0
int NetIfRemoveHostOnlyNetworkInterface(VirtualBox *pVirtualBox, IN_GUID aId,
                                        IProgress **aProgress)
{
#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
    /* create a progress object */
    ComObjPtr<Progress> progress;
    progress.createObject();
    ComPtr<IHost> host;
    int rc = VINF_SUCCESS;
    HRESULT hr = pVirtualBox->COMGETTER(Host)(host.asOutParam());
    if (SUCCEEDED(hr))
    {
        Bstr ifname;
        ComPtr<IHostNetworkInterface> iface;
        if (FAILED(host->FindHostNetworkInterfaceById(Guid(aId).toUtf16().raw(), iface.asOutParam())))
            return VERR_INVALID_PARAMETER;
        iface->COMGETTER(Name)(ifname.asOutParam());
        if (ifname.isEmpty())
            return VERR_INTERNAL_ERROR;

        rc = progress->init(pVirtualBox, host,
                            Bstr("Removing host network interface").raw(),
                            FALSE /* aCancelable */);
        if (SUCCEEDED(rc))
        {
            progress.queryInterfaceTo(aProgress);
            rc = NetIfAdpCtl(Utf8Str(ifname).c_str(), "remove", NULL, NULL);
            if (RT_FAILURE(rc))
                progress->i_notifyComplete(E_FAIL,
                                           COM_IIDOF(IHostNetworkInterface),
                                           HostNetworkInterface::getStaticComponentName(),
                                           "Failed to execute '" VBOXNETADPCTL_NAME "' (exit status: %d)", rc);
            else
                progress->i_notifyComplete(S_OK);
        }
    }
    else
    {
        progress->i_notifyComplete(hr);
        rc = VERR_INTERNAL_ERROR;
    }
    return rc;
#else
    NOREF(pVirtualBox);
    NOREF(aId);
    NOREF(aProgress);
    return VERR_NOT_IMPLEMENTED;
#endif
}
HRESULT MachineDebugger::logStringProps(PRTLOGGER pLogger, PFNLOGGETSTR pfnLogGetStr,
                                        const char *pszLogGetStr, BSTR *a_pbstrSettings)
{
    /* Make sure the VM is powered up. */
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
    Console::SafeVMPtr ptrVM(mParent);
    HRESULT hrc = ptrVM.rc();
    if (FAILED(hrc))
        return hrc;

    /* Make sure we've got a logger. */
    if (!pLogger)
    {
        Bstr bstrEmpty;
        bstrEmpty.cloneTo(a_pbstrSettings);
        return S_OK;
    }

    /* Do the job. */
    size_t cbBuf = _1K;
    for (;;)
    {
        char *pszBuf = (char *)RTMemTmpAlloc(cbBuf);
        AssertReturn(pszBuf, E_OUTOFMEMORY);

        int rc = pfnLogGetStr(pLogger, pszBuf, cbBuf);
        if (RT_SUCCESS(rc))
        {
            try
            {
                Bstr bstrRet(pszBuf);
                bstrRet.detachTo(a_pbstrSettings);
                hrc = S_OK;
            }
            catch (std::bad_alloc)
            {
                hrc = E_OUTOFMEMORY;
            }
            RTMemTmpFree(pszBuf);
            return hrc;
        }
        RTMemTmpFree(pszBuf);
        AssertReturn(rc == VERR_BUFFER_OVERFLOW, setError(VBOX_E_IPRT_ERROR, tr("%s returned %Rrc"), pszLogGetStr, rc));

        /* try again with a bigger buffer. */
        cbBuf *= 2;
        AssertReturn(cbBuf <= _256K, setError(E_FAIL, tr("%s returns too much data"), pszLogGetStr));
    }
}
Пример #27
0
RTEXITCODE handleUSBDevSource(HandlerArg *a)
{
    HRESULT rc = S_OK;

    /* at least: 0: command, 1: source id */
    if (a->argc < 2)
        return errorSyntax(USAGE_USBDEVSOURCE, "Not enough parameters");

    ComPtr<IHost> host;
    if (!strcmp(a->argv[0], "add"))
    {
        Bstr strBackend;
        Bstr strAddress;
        if (a->argc != 6)
            return errorSyntax(USAGE_USBDEVSOURCE, "Invalid number of parameters");

        for (int i = 2; i < a->argc; i++)
        {
            if (!strcmp(a->argv[i], "--backend"))
            {
                i++;
                strBackend = a->argv[i];
            }
            else if (!strcmp(a->argv[i], "--address"))
            {
                i++;
                strAddress = a->argv[i];
            }
            else
                return errorSyntax(USAGE_USBDEVSOURCE, "Parameter \"%s\" is invalid", a->argv[i]);
        }

        SafeArray<BSTR> usbSourcePropNames;
        SafeArray<BSTR> usbSourcePropValues;

        CHECK_ERROR_RET(a->virtualBox, COMGETTER(Host)(host.asOutParam()), RTEXITCODE_FAILURE);
        CHECK_ERROR_RET(host, AddUSBDeviceSource(strBackend.raw(), Bstr(a->argv[1]).raw(), strAddress.raw(),
                                                 ComSafeArrayAsInParam(usbSourcePropNames), ComSafeArrayAsInParam(usbSourcePropValues)),
                        RTEXITCODE_FAILURE);
    }
    else if (!strcmp(a->argv[0], "remove"))
    {
        CHECK_ERROR_RET(a->virtualBox, COMGETTER(Host)(host.asOutParam()), RTEXITCODE_FAILURE);
        CHECK_ERROR_RET(host, RemoveUSBDeviceSource(Bstr(a->argv[1]).raw()), RTEXITCODE_FAILURE);
    }

    return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}
Пример #28
0
/**
 * Sets the Guest Additions version information details.
 * Gets called by vmmdevUpdateGuestInfo2.
 *
 * @param aAdditionsVersion
 * @param aVersionName
 */
void Guest::setAdditionsInfo2(Bstr aAdditionsVersion, Bstr aVersionName, Bstr aRevision)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.rc());

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    if (!aVersionName.isEmpty())
        /*
         * aVersionName could be "x.y.z_BETA1_FOOBAR", so append revision manually to
         * become "x.y.z_BETA1_FOOBAR r12345".
         */
        mData.mAdditionsVersion = BstrFmt("%ls r%ls", aVersionName.raw(), aRevision.raw());
    else /* aAdditionsVersion is in x.y.zr12345 format. */
        mData.mAdditionsVersion = aAdditionsVersion;
}
Пример #29
0
/**
 * Sets the general Guest Additions information like
 * API (interface) version and OS type.  Gets called by
 * vmmdevUpdateGuestInfo.
 *
 * @param aInterfaceVersion
 * @param aOsType
 */
void Guest::setAdditionsInfo(Bstr aInterfaceVersion, VBOXOSTYPE aOsType)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.rc());

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    /*
     * Note: The Guest Additions API (interface) version is deprecated
     * and will not be used anymore!  We might need it to at least report
     * something as version number if *really* ancient Guest Additions are
     * installed (without the guest version + revision properties having set).
     */
    mData.mInterfaceVersion = aInterfaceVersion;

    /*
     * Older Additions rely on the Additions API version whether they
     * are assumed to be active or not.  Since newer Additions do report
     * the Additions version *before* calling this function (by calling
     * VMMDevReportGuestInfo2, VMMDevReportGuestStatus, VMMDevReportGuestInfo,
     * in that order) we can tell apart old and new Additions here. Old
     * Additions never would set VMMDevReportGuestInfo2 (which set mData.mAdditionsVersion)
     * so they just rely on the aInterfaceVersion string (which gets set by
     * VMMDevReportGuestInfo).
     *
     * So only mark the Additions as being active (run level = system) when we
     * don't have the Additions version set.
     */
    if (mData.mAdditionsVersion.isEmpty())
    {
        if (aInterfaceVersion.isEmpty())
            mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
        else
        {
            mData.mAdditionsRunLevel = AdditionsRunLevelType_System;

            /*
             * To keep it compatible with the old Guest Additions behavior we need to set the
             * "graphics" (feature) facility to active as soon as we got the Guest Additions
             * interface version.
             */
            facilityUpdate(VBoxGuestFacilityType_Graphics, VBoxGuestFacilityStatus_Active);
        }
    }

    /*
     * Older Additions didn't have this finer grained capability bit,
     * so enable it by default. Newer Additions will not enable this here
     * and use the setSupportedFeatures function instead.
     */
    facilityUpdate(VBoxGuestFacilityType_Graphics, facilityIsActive(VBoxGuestFacilityType_VBoxGuestDriver) ?
                   VBoxGuestFacilityStatus_Active : VBoxGuestFacilityStatus_Inactive);

    /*
     * Note! There is a race going on between setting mAdditionsRunLevel and
     * mSupportsGraphics here and disabling/enabling it later according to
     * its real status when using new(er) Guest Additions.
     */
    mData.mOSTypeId = Global::OSTypeId (aOsType);
}
Пример #30
0
void GluePrintErrorInfo(const com::ErrorInfo &info)
{
    bool haveResultCode = false;
#if defined (RT_OS_WIN)
    haveResultCode = info.isFullAvailable();
    bool haveComponent = true;
    bool haveInterfaceID = true;
#else /* defined (RT_OS_WIN) */
    haveResultCode = true;
    bool haveComponent = info.isFullAvailable();
    bool haveInterfaceID = info.isFullAvailable();
#endif

    Utf8Str str;
    RTCList<Utf8Str> comp;

    Bstr bstrDetailsText = info.getText();
    if (!bstrDetailsText.isEmpty())
        str = Utf8StrFmt("%ls\n",
                         bstrDetailsText.raw());
    if (haveResultCode)
        comp.append(Utf8StrFmt("code %Rhrc (0x%RX32)",
                               info.getResultCode(),
                               info.getResultCode()));
    if (haveComponent)
        comp.append(Utf8StrFmt("component %ls",
                               info.getComponent().raw()));
    if (haveInterfaceID)
        comp.append(Utf8StrFmt("interface %ls",
                               info.getInterfaceName().raw()));
    if (!info.getCalleeName().isEmpty())
        comp.append(Utf8StrFmt("callee %ls",
                               info.getCalleeName().raw()));

    if (comp.size() > 0)
    {
        str += "Details: ";
        for (size_t i = 0; i < comp.size() - 1; ++i)
            str += comp.at(i) + ", ";
        str += comp.last();
        str += "\n";
    }

    // print and log
    RTMsgError("%s", str.c_str());
    Log(("ERROR: %s", str.c_str()));
}