VirtualBoxImpl.cpp revision 200cc6562c6e5cec617903ea827cfb22083f5325
/* $Id$ */
/** @file
* Implementation of IVirtualBox in VBoxSVC.
*/
/*
* Copyright (C) 2006-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <iprt/buildconfig.h>
#include "VBox/com/EventQueue.h"
#include <VBox/settings.h>
#include <package-generated.h>
#include <version-generated.h>
#include <algorithm>
#include <set>
#include <vector>
#include <memory> // for auto_ptr
#include "VirtualBoxImpl.h"
#include "Global.h"
#include "MachineImpl.h"
#include "MediumImpl.h"
#include "SharedFolderImpl.h"
#include "ProgressImpl.h"
#include "ProgressProxyImpl.h"
#include "HostImpl.h"
#include "USBControllerImpl.h"
#include "SystemPropertiesImpl.h"
#include "GuestOSTypeImpl.h"
#include "DHCPServerRunner.h"
#include "DHCPServerImpl.h"
#ifdef VBOX_WITH_RESOURCE_USAGE_API
# include "PerformanceImpl.h"
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
#include "EventImpl.h"
#include "VBoxEvents.h"
#ifdef VBOX_WITH_EXTPACK
# include "ExtPackManagerImpl.h"
#endif
#include "AutostartDb.h"
#include "AutoCaller.h"
#include "Logging.h"
#include "objectslist.h"
#ifdef RT_OS_WINDOWS
# include "win/VBoxComEvents.h"
#endif
////////////////////////////////////////////////////////////////////////////////
//
// Definitions
//
////////////////////////////////////////////////////////////////////////////////
#define VBOX_GLOBAL_SETTINGS_FILE "VirtualBox.xml"
////////////////////////////////////////////////////////////////////////////////
//
// Global variables
//
////////////////////////////////////////////////////////////////////////////////
// static
// static
// static
// static
////////////////////////////////////////////////////////////////////////////////
//
// CallbackEvent class
//
////////////////////////////////////////////////////////////////////////////////
/**
* Abstract callback event class to asynchronously call VirtualBox callbacks
* on a dedicated event thread. Subclasses reimplement #handleCallback()
* to call appropriate IVirtualBoxCallback methods depending on the event
* to be dispatched.
*
* @note The VirtualBox instance passed to the constructor is strongly
* referenced, so that the VirtualBox singleton won't be released until the
* event gets handled by the event thread.
*/
{
public:
{
}
void *handler();
private:
/**
* Note that this is a weak ref -- the CallbackEvent handler thread
* is bound to the lifetime of the VirtualBox instance, so it's safe.
*/
protected:
};
////////////////////////////////////////////////////////////////////////////////
//
// VirtualBox private member data definition
//
////////////////////////////////////////////////////////////////////////////////
#if defined(RT_OS_WINDOWS)
#define UPDATEREQARG NULL
#define UPDATEREQTYPE HANDLE
#define UPDATEREQARG NIL_RTSEMEVENT
#define UPDATEREQTYPE RTSEMEVENT
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
#define UPDATEREQARG
#define UPDATEREQTYPE RTSEMEVENT
#else
# error "Port me!"
#endif
/**
* Main VirtualBox data structure.
* @note |const| members are persistent during lifetime so can be accessed
* without locking.
*/
struct VirtualBox::Data
{
Data()
: pMainConfigFile(NULL),
uuidMediaRegistry("48024e5c-fdd9-470f-93af-ec29f7ea518c"),
{
}
~Data()
{
if (pMainConfigFile)
{
delete pMainConfigFile;
}
};
// const data members not requiring locking
const Utf8Str strHomeDir;
// VirtualBox main settings file
const Utf8Str strSettingsFilePath;
// constant pseudo-machine ID for global media registry
const Guid uuidMediaRegistry;
// counter if global media registry needs saving, updated using atomic
// operations, without requiring any locks
// const objects not requiring locking
#ifdef VBOX_WITH_RESOURCE_USAGE_API
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
// Each of the following lists use a particular lock handle that protects the
// list as a whole. As opposed to version 3.1 and earlier, these lists no
// longer need the main VirtualBox object lock, but only the respective list
// lock. In each case, the locking order is defined that the list must be
// requested before object locks of members of the lists (see the order definitions
// in AutoLock.h; e.g. LOCKCLASS_LISTOFMACHINES before LOCKCLASS_MACHINEOBJECT).
// All the media lists are protected by the following locking handle:
// the hard disks map is an additional map sorted by UUID for quick lookup
// and contains ALL hard disks (base and differencing); it is protected by
// the same lock as the other media lists above
// list of pending machine renames (also protected by media tree lock;
// see VirtualBox::rememberMachineNameChangeForMedia())
struct PendingMachineRename
{
};
// the following are data for the client watcher thread
const UPDATEREQTYPE updateReq;
const RTTHREAD threadClientWatcher;
// the following are data for the async event thread
const RTTHREAD threadAsyncEvent;
EventQueue * const pAsyncEventQ;
#ifdef VBOX_WITH_EXTPACK
/** The extension pack manager object lives here. */
#endif
/** The global autostart database for the user. */
AutostartDb * const pAutostartDb;
/** Settings secret */
bool fSettingsCipherKeySet;
};
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
{}
VirtualBox::~VirtualBox()
{}
{
LogFlowThisFunc(("\n"));
return rc;
}
void VirtualBox::FinalRelease()
{
LogFlowThisFunc(("\n"));
uninit();
}
// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////
/**
* Initializes the VirtualBox object.
*
* @return COM result code
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* Locking this object for writing during init sounds a bit paradoxical,
* but in the current locking mess this avoids that some code gets a
* read lock and later calls code which wants the same write lock. */
// allocate our instance data
m = new Data;
LogFlow(("===========================================================\n"));
sVersion = RTBldCfgVersion();
if (sPackageType.isEmpty())
if (sAPIVersion.isEmpty())
LogFlowThisFunc(("Version: %ls, Package: %ls, API Version: %ls\n", sVersion.raw(), sPackageType.raw(), sAPIVersion.raw()));
/* Get the VirtualBox home directory. */
{
char szHomeDir[RTPATH_MAX];
if (RT_FAILURE(vrc))
tr("Could not create the VirtualBox home directory '%s' (%Rrc)"),
}
/* compose the VirtualBox.xml file name */
m->strHomeDir.c_str(),
bool fCreate = false;
try
{
// load and parse VirtualBox.xml; this will throw on XML or logic errors
try
{
}
catch (xml::EIPRTFailure &e)
{
// this is thrown by the XML backend if the RTOpen() call fails;
// only if the main settings file does not exist, create it,
// if there's something more serious, then do fail!
if (e.rc() == VERR_FILE_NOT_FOUND)
fCreate = true;
else
throw;
}
if (fCreate)
#ifdef VBOX_WITH_RESOURCE_USAGE_API
/* create the performance collector object BEFORE host */
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/* create the host object early, machines will need it */
/*
* Create autostart database object early, because the system properties
* might need it.
*/
/* create the system properties object, someone may need it too */
/* guest OS type objects, needed by machines */
{
{
}
}
/* all registered media, needed by machines */
throw rc;
/* machines */
throw rc;
#ifdef DEBUG
LogFlowThisFunc(("Dumping media backreferences\n"));
#endif
/* net services */
++it)
{
}
/* events */
#ifdef VBOX_WITH_EXTPACK
/* extension manager */
throw rc;
#endif
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
{
/* start the client watcher thread */
#if defined(RT_OS_WINDOWS)
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
#else
# error "Port me!"
#endif
(void *)this,
0,
"Watcher");
if (RT_FAILURE(vrc))
}
{
try
{
/* start the async event handler thread */
&unconst(m->pAsyncEventQ),
0,
"EventHandler");
/* wait until the thread sets m->pAsyncEventQ */
}
{
}
}
/* Confirm a successful initialization when it's the case */
#ifdef VBOX_WITH_EXTPACK
/* Let the extension packs have a go at things. */
{
}
#endif
LogFlow(("===========================================================\n"));
return rc;
}
{
++it)
{
{
&uuid);
return rc;
}
}
return S_OK;
}
/**
* Loads a media registry from XML and adds the media contained therein to
* the global lists of known media.
*
* This now (4.0) gets called from two locations:
*
* -- VirtualBox::init(), to load the global media registry from VirtualBox.xml;
*
* -- Machine::loadMachineDataFromSettings(), to load the per-machine registry
* from machine XML, for machines created with VirtualBox 4.0 or later.
*
* In both cases, the media found are added to the global lists so the
* global arrays of media (including the GUI's virtual media manager)
* continue to work as before.
*
* @param uuidMachineRegistry The UUID of the media registry. This is either the
* transient UUID created at VirtualBox startup for the global registry or
* a machine ID.
* @param mediaRegistry The XML settings structure to load, either from VirtualBox.xml
* or a machine XML.
* @return
*/
const Utf8Str &strMachineFolder)
{
LogFlow(("VirtualBox::initMedia ENTERING, uuidRegistry=%s, strMachineFolder=%s\n",
strMachineFolder.c_str()));
++it)
{
NULL, // parent
xmlHD, // XML data; this recurses to processes the children
}
++it)
{
NULL,
}
++it)
{
NULL,
}
LogFlow(("VirtualBox::initMedia LEAVING\n"));
return S_OK;
}
void VirtualBox::uninit()
{
Assert(!m->uRegistryNeedsSaving);
if (m->uRegistryNeedsSaving)
saveSettings();
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
LogFlow(("===========================================================\n"));
/* tell all our child objects we've been uninitialized */
if (m->pHost)
{
/* It is necessary to hold the VirtualBox and Host locks here because
we may have to uninitialize SessionMachines. */
m->allMachines.uninitAll();
}
else
m->allMachines.uninitAll();
m->allFloppyImages.uninitAll();
m->allDVDImages.uninitAll();
m->allHardDisks.uninitAll();
m->allDHCPServers.uninitAll();
m->mapProgressOperations.clear();
m->allGuestOSTypes.uninitAll();
/* Note that we release singleton children after we've all other children.
* In some cases this is important because these other children may use
* some resources of the singletons which would prevent them from
* uninitializing (as for example, mSystemProperties which owns
* MediumFormat objects which Medium objects refer to) */
if (m->pSystemProperties)
{
m->pSystemProperties->uninit();
}
if (m->pHost)
{
}
#ifdef VBOX_WITH_RESOURCE_USAGE_API
if (m->pPerformanceCollector)
{
m->pPerformanceCollector->uninit();
}
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
LogFlowThisFunc(("Terminating the async event handler...\n"));
if (m->threadAsyncEvent != NIL_RTTHREAD)
{
/* signal to exit the event loop */
{
/*
* Wait for thread termination (only after we've successfully
* interrupted the event queue processing!)
*/
if (RT_FAILURE(vrc))
LogWarningFunc(("RTThreadWait(%RTthrd) -> %Rrc\n",
m->threadAsyncEvent, vrc));
}
else
{
AssertMsgFailed(("interruptEventQueueProcessing() failed\n"));
}
}
LogFlowThisFunc(("Releasing event source...\n"));
if (m->pEventSource)
{
// we don't perform uninit() as it's possible that some pending event refers to this source
}
LogFlowThisFunc(("Terminating the client watcher...\n"));
if (m->threadClientWatcher != NIL_RTTHREAD)
{
/* signal the client watcher thread */
/* wait for the termination */
}
m->llProcesses.clear();
#if defined(RT_OS_WINDOWS)
{
::CloseHandle(m->updateReq);
}
if (m->updateReq != NIL_RTSEMEVENT)
{
}
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (m->updateReq != NIL_RTSEMEVENT)
{
}
#else
# error "Port me!"
#endif
delete m->pAutostartDb;
// clean up our instance data
delete m;
/* Unload hard disk plugin backends. */
VDShutdown();
LogFlow(("===========================================================\n"));
}
// IVirtualBox properties
/////////////////////////////////////////////////////////////////////////////
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
/* mHomeDir is const and doesn't need a lock */
return S_OK;
}
{
AutoCaller autoCaller(this);
/* mCfgFile.mName is const and doesn't need a lock */
return S_OK;
}
{
AutoCaller autoCaller(this);
/* mHost is const, no need to lock */
return S_OK;
}
{
AutoCaller autoCaller(this);
/* mSystemProperties is const, no need to lock */
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
/* get copy of all machine references, to avoid holding the list lock */
{
}
++it)
{
continue;
if (pMachine->isAccessible())
{
continue;
}
}
/* throw out any duplicates */
size_t i = 0;
++it, i++)
{
}
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
/* protect mProgressOperations */
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
#ifndef RT_OS_WINDOWS
#endif /* RT_OS_WINDOWS */
AutoCaller autoCaller(this);
}
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
AutoCaller autoCaller(this);
/* mPerformanceCollector is const, no need to lock */
return S_OK;
#else /* !VBOX_WITH_RESOURCE_USAGE_API */
#endif /* !VBOX_WITH_RESOURCE_USAGE_API */
}
{
AutoCaller autoCaller(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
/* event source is const, no need to lock */
return S_OK;
}
{
AutoCaller autoCaller(this);
{
#ifdef VBOX_WITH_EXTPACK
/* The extension pack manager is const, no need to lock. */
#else
#endif
}
return hrc;
}
{
AutoCaller autoCaller(this);
/* get copy of all machine references, to avoid holding the list lock */
{
}
++it)
{
continue;
if (pMachine->isAccessible())
{
for (ULONG i = 0; i < cNetworkAdapters; i++)
{
continue;
continue;
}
}
}
/* throw out any duplicates */
size_t i = 0;
++it, i++)
{
}
return S_OK;
}
STDMETHODIMP VirtualBox::COMGETTER(GenericNetworkDrivers)(ComSafeArrayOut(BSTR, aGenericNetworkDrivers))
{
AutoCaller autoCaller(this);
/* get copy of all machine references, to avoid holding the list lock */
{
}
++it)
{
continue;
if (pMachine->isAccessible())
{
for (ULONG i = 0; i < cNetworkAdapters; i++)
{
continue;
continue;
}
}
}
/* throw out any duplicates */
size_t i = 0;
++it, i++)
{
}
return S_OK;
}
{
AutoCaller autoCaller(this);
static const struct
{
const char* fileName;
const char* url;
}
firmwareDesc[] =
{
{
/* compiled-in firmware */
},
{
},
{
},
{
}
};
{
continue;
/* compiled-in firmware */
{
break;
}
firmwareDesc[i].fileName);
{
if (aFile)
break;
}
char pszVBoxPath[RTPATH_MAX];
firmwareDesc[i].fileName);
{
if (aFile)
break;
}
/** @todo: account for version in the URL */
{
}
/* Assume single record per firmware type */
break;
}
return S_OK;
}
// IVirtualBox methods
/////////////////////////////////////////////////////////////////////////////
/* Helper for VirtualBox::ComposeMachineFilename */
{
AutoCaller autoCaller(this);
strGroup = "/";
return rc;
/* Compose the settings file name using the following scheme:
*
* <base_folder><group>/<machine_name>/<machine_name>.xml
*
* If a non-null and non-empty base folder is specified, the default
* machine folder will be used as a base folder.
* We sanitise the machine name to a safe white list of characters before
* using it.
*/
/* we use the non-full folder value below to keep the path relative */
/* eliminate toplevel group to avoid // in the result */
if (strGroup == "/")
return S_OK;
}
/**
* Remove characters from a machine file name which can be problematic on
* particular systems.
* @param strName The file name to sanitise.
*/
{
/** Set of characters which should be safe for use in filenames: some basic
* ASCII, Unicode from Latin-1 alphabetic to the end of Hangul. We try to
* skip anything that could count as a control character in Windows or
* *nix, or be otherwise difficult for shells to handle (I would have
* preferred to remove the space and brackets too). We also remove all
* characters which need UTF-16 surrogate pairs for Windows's benefit. */
#ifdef RT_STRICT
{ ' ', ' ', '(', ')', '-', '.', '0', '9', 'A', 'Z', 'a', 'z', '_', '_',
0xa0, 0xd7af, '\0' };
#endif
/* No leading dot or dash. */
pszName[0] = '_';
/* No trailing dot. */
/* Mangle leading and trailing spaces. */
pszName[i] = '_';
pszName[i] = '_';
}
#ifdef DEBUG
static unsigned testSanitiseMachineFilename(void (*pfnPrintf)(const char *, ...))
{
unsigned cErrors = 0;
/** Expected results of sanitising given file names. */
static struct
{
/** The test file name to be sanitised (Utf-8). */
const char *pcszIn;
/** The expected sanitised output (Utf-8). */
const char *pcszOutExpected;
} aTest[] =
{
{ "OS/2 2.1", "OS_2 2.1" },
{ "-!My VM!-", "__My VM_-" },
{ "\xF0\x90\x8C\xB0", "____" },
{ " My VM ", "__My VM__" },
{ ".My VM.", "_My VM_" },
{ "My VM", "My VM" }
};
for (unsigned i = 0; i < RT_ELEMENTS(aTest); ++i)
{
{
++cErrors;
pfnPrintf("%s: line %d, expected %s, actual %s\n",
}
}
return cErrors;
}
/** @todo Proper testcase. */
/** @todo Do we have a better method of doing init functions? */
namespace
{
{
public:
{
}
};
}
#endif
/** @note Locks mSystemProperties object for reading. */
{
LogFlowThisFunc(("aSettingsFile=\"%ls\", aName=\"%ls\", aOsTypeId =\"%ls\"\n", aSettingsFile, aName, aOsTypeId));
/** @todo tighten checks on aId? */
AutoCaller autoCaller(this);
return rc;
/* NULL settings file means compose automatically */
if (bstrSettingsFile.isEmpty())
{
NULL /* aBaseFolder */,
}
/* create a new object */
/* Create UUID if an empty one was specified. */
/* initialize the machine object */
id,
!!forceOverwrite);
{
/* set the return value */
#ifdef VBOX_WITH_EXTPACK
/* call the extension pack hooks */
#endif
}
return rc;
}
{
AutoCaller autoCaller(this);
/* create a new object */
{
/* initialize the machine object */
NULL); /* const Guid *aId */
{
/* set the return value */
}
}
return rc;
}
/** @note Locks objects! */
{
AutoCaller autoCaller(this);
/* We can safely cast child to Machine * here because only Machine
* implementations of IMachine can be among our children. */
/* fire an event */
return rc;
}
/** @note Locks this object for reading, then some machine objects for reading. */
{
AutoCaller autoCaller(this);
/* start with not found */
true /* fPermitInaccessible */,
true /* setError */,
// returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
else
{
++it)
{
if (machCaller.rc())
continue; // we can't ask inaccessible machines for their names
{
break;
}
{
break;
}
}
if (!pMachineFound)
}
/* this will set (*machine) to NULL if machineObj is null */
return rc;
}
STDMETHODIMP VirtualBox::GetMachineStates(ComSafeArrayIn(IMachine *, aMachines), ComSafeArrayOut(MachineState_T, aStates))
{
{
{
if (rc == E_ACCESSDENIED)
}
}
return S_OK;
}
{
AutoCaller autoCaller(this);
/* we don't access non-const data members so no need to lock */
return rc;
}
{
AutoCaller autoCaller(this);
// in one critical section, otherwise there are races which can lead to
// multiple Medium objects with the same content
// check if the device type is correct, and see if a medium for the
// given path has already initialized; if so, return that
switch (deviceType)
{
case DeviceType_HardDisk:
false, /* aSetError */
&pMedium);
break;
case DeviceType_Floppy:
case DeviceType_DVD:
NULL, /* guid */
false, /* aSetError */
&pMedium);
// enforce read-only for DVDs even if caller specified ReadWrite
if (deviceType == DeviceType_DVD)
break;
default:
}
{
{
/* Note that it's important to call uninit() on failure to register
* because the differencing hard disk would have been already associated
* with the parent and this association needs to be broken. */
{
}
}
else
}
return rc;
}
/** @note Locks this object for reading. */
{
AutoCaller autoCaller(this);
++it)
{
{
break;
}
}
tr("'%ls' is not a valid Guest OS type"),
aId);
}
{
AutoCaller autoCaller(this);
}
{
AutoCaller autoCaller(this);
}
/**
* @note Locks this object for reading.
*/
{
using namespace settings;
AutoCaller autoCaller(this);
int i = 0;
++it, ++i)
{
}
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller(this);
/* start with nothing found */
// found:
/* return the result to caller (may be empty) */
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
// locking note: we only hold the read lock briefly to look up the old value,
// then release it and call the onExtraCanChange callbacks. There is a small
// chance of a race insofar as the callback might be called twice if two callers
// change the same key at the same time, but that's a much better solution
// than the deadlock we had here before. The actual changing of the extradata
// is then performed under the write lock and race-free.
// look up the old value first; if nothing has changed then we need not do anything
{
}
bool fChanged;
{
// ask for permission from all listeners outside the locks;
// onExtraDataCanChange() only briefly requests the VirtualBox
// lock to copy the list of callbacks to invoke
{
LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
return setError(E_ACCESSDENIED,
tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
aKey,
sep,
err);
}
// data is changing and change not vetoed: then write it out under the lock
else
// creates a new key if needed
/* save settings on success */
}
// fire notification outside the lock
if (fChanged)
return S_OK;
}
/**
*
*/
{
return S_OK;
}
{
bstrCipher.asOutParam());
{
if (RT_SUCCESS(rc))
}
}
/**
* Decrypt all encrypted settings.
*
* So far we only have encrypted iSCSI initiator secrets so we just go through
* all hard disk mediums and determine the plain 'InitiatorSecret' from
* 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
* properties need to be null-terminated strings.
*/
void VirtualBox::decryptSettings()
{
++mt)
{
continue;
}
}
/**
* Encode.
*
* @param aPlaintext plaintext to be encrypted
* @param aCiphertext resulting ciphertext (base64-encoded)
*/
{
char szCipherBase64[128];
if (RT_SUCCESS(rc))
{
szCipherBase64, sizeof(szCipherBase64),
if (RT_SUCCESS(rc))
}
return rc;
}
/**
* Decode.
*
* @param aPlaintext resulting plaintext
* @param aCiphertext ciphertext (base64-encoded) to decrypt
*/
{
abCiphertext, sizeof(abCiphertext),
&cbCiphertext, NULL);
if (RT_SUCCESS(rc))
{
if (RT_SUCCESS(rc))
{
/* check if this is really a Null-terminated string. */
for (unsigned i = 0; i < cbCiphertext; i++)
{
if (abPlaintext[i] == '\0')
{
return VINF_SUCCESS;
}
}
}
}
return rc;
}
/**
* Encrypt secret bytes. Use the m->SettingsCipherKey as key.
*
* @param aPlaintext clear text to be encrypted
* @param aCiphertext resulting encrypted text
* @param aPlaintextSize size of the plaintext
* @param aCiphertextSize size of the ciphertext
*/
{
unsigned i, j;
if (!m->fSettingsCipherKeySet)
return VERR_INVALID_STATE;
if (aCiphertextSize > sizeof(aBytes))
return VERR_BUFFER_OVERFLOW;
for (i = 0, j = 0; i < aPlaintextSize && i < aCiphertextSize; i++)
{
if (++j >= sizeof(m->SettingsCipherKey))
j = 0;
}
/* fill with random data to have a minimal length */
if (i < aCiphertextSize)
{
for (; i < aCiphertextSize; i++)
{
if (++j >= sizeof(m->SettingsCipherKey))
j = 0;
}
}
return VINF_SUCCESS;
}
/**
* Decrypt secret bytes. Use the m->SettingsCipherKey as key.
*
* @param aPlaintext resulting plaintext
* @param aCiphertext ciphertext to be decrypted
* @param aCiphertextSize size of the ciphertext == size of the plaintext
*/
{
if (!m->fSettingsCipherKeySet)
return VERR_INVALID_STATE;
for (unsigned i = 0, j = 0; i < aCiphertextSize; i++)
{
if (++j >= sizeof(m->SettingsCipherKey))
j = 0;
}
return VINF_SUCCESS;
}
/**
* Store a settings key.
*
* @param aKey the key to store
*/
{
m->fSettingsCipherKeySet = true;
}
// public methods only for internal purposes
/////////////////////////////////////////////////////////////////////////////
#ifdef DEBUG
void VirtualBox::dumpAllBackRefs()
{
{
++mt)
{
pMedium->dumpBackRefs();
}
}
{
++mt)
{
pMedium->dumpBackRefs();
}
}
}
#endif
/**
* Posts an event to the event queue that is processed asynchronously
* on a dedicated thread.
*
* Posting events to the dedicated event queue is useful to perform secondary
* actions outside any object locks -- for example, to iterate over a list
* of callbacks and inform them about some change caused by some object's
* method call.
*
* @param event event to post; must have been allocated using |new|, will
* be deleted automatically by the event thread after processing
*
* @note Doesn't lock any object.
*/
{
AutoCaller autoCaller(this);
{
LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
autoCaller.state()));
// return S_OK
else if ( (m->pAsyncEventQ)
)
return S_OK;
else
}
// in any event of failure, we must clean up here, or we'll leak;
// the caller has allocated the object using new()
delete event;
return rc;
}
/**
* Adds a progress to the global collection of pending operations.
* Usually gets called upon progress object initialization.
*
* @param aProgress Operation to add to the collection.
*
* @note Doesn't lock objects.
*/
{
AutoCaller autoCaller(this);
/* protect mProgressOperations */
return S_OK;
}
/**
* Removes the progress from the global collection of pending operations.
* Usually gets called upon progress completion.
*
* @param aId UUID of the progress operation to remove
*
* @note Doesn't lock objects.
*/
{
AutoCaller autoCaller(this);
/* protect mProgressOperations */
return S_OK;
}
#ifdef RT_OS_WINDOWS
struct StartSVCHelperClientData
{
bool privileged;
void *user;
};
/**
* Helper method that starts a worker thread that:
* - creates a pipe communication channel using SVCHlpClient;
* - starts an SVC Helper process that will inherit this channel;
* - executes the supplied function by passing it the created SVCHlpClient
* and opened instance to communicate to the Helper process and the given
* Progress object.
*
* The user function is supposed to communicate to the helper process
* using the \a aClient argument to do the requested job and optionally expose
* the progress through the \a aProgress object. The user function should never
* call notifyComplete() on it: this will be done automatically using the
* result code returned by the function.
*
* Before the user function is started, the communication channel passed to
* the \a aClient argument is fully set up, the function should start using
* its write() and read() methods directly.
*
* The \a aVrc parameter of the user function may be used to return an error
* code if it is related to communication errors (for example, returned by
* the SVCHlpClient members when they fail). In this case, the correct error
* message using this value will be reported to the caller. Note that the
* value of \a aVrc is inspected only if the user function itself returns
* success.
*
* If a failure happens anywhere before the user function would be normally
* called, it will be called anyway in special "cleanup only" mode indicated
* by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
* all the function is supposed to do is to cleanup its aUser argument if
* necessary (it's assumed that the ownership of this argument is passed to
* the user function once #startSVCHelperClient() returns a success, thus
* making it responsible for the cleanup).
*
* After the user function returns, the thread will send the SVCHlpMsg::Null
* message to indicate a process termination.
*
* @param aPrivileged |true| to start the SVC Helper process as a privileged
* user that can perform administrative tasks
* @param aFunc user function to run
* @param aUser argument to the user function
* @param aProgress progress object that will track operation completion
*
* @note aPrivileged is currently ignored (due to some unsolved problems in
* Vista) and the process will be started as a normal (unprivileged)
* process.
*
* @note Doesn't lock anything.
*/
{
AutoCaller autoCaller(this);
/* create the SVCHelperClientThread() argument */
d(new StartSVCHelperClientData());
d->that = this;
d->privileged = aPrivileged;
static_cast <void *>(d.get()),
RTTHREADFLAGS_WAITABLE, "SVCHelper");
if (RT_FAILURE(vrc))
/* d is now owned by SVCHelperClientThread(), so release it */
d.release();
return S_OK;
}
/**
* Worker thread for startSVCHelperClient().
*/
/* static */
DECLCALLBACK(int)
{
d(static_cast<StartSVCHelperClientData*>(aUser));
bool userFuncCalled = false;
do
{
/* protect VirtualBox from uninitialization */
if (!autoCaller.isOk())
{
/* it's too late */
break;
}
int vrc = VINF_SUCCESS;
if (RT_FAILURE(vrc))
{
break;
}
/* get the path to the executable */
char exePathBuf[RTPATH_MAX];
if (!exePath)
{
break;
}
if (d->privileged)
{
/* Attempt to start a privileged process using the Run As dialog */
if (!ShellExecuteEx(&shExecInfo))
{
/* hide excessive details in case of a frequent error
* (pressing the Cancel button to close the Run As dialog) */
if (vrc2 == VERR_CANCELLED)
tr("Operation canceled by the user"));
else
tr("Could not launch a privileged process '%s' (%Rrc)"),
break;
}
}
else
{
if (RT_FAILURE(vrc))
{
break;
}
}
/* wait for the client to connect */
if (RT_SUCCESS(vrc))
{
/* start the user supplied function */
userFuncCalled = true;
}
/* send the termination signal to the process anyway */
{
if (RT_SUCCESS(vrc))
}
{
break;
}
}
while (0);
{
/* call the user function in the "cleanup only" mode
* to let it free resources passed to in aUser */
}
return 0;
}
#endif /* RT_OS_WINDOWS */
/**
* Sends a signal to the client watcher thread to rescan the set of machines
* that have open sessions.
*
* @note Doesn't lock anything.
*/
void VirtualBox::updateClientWatcher()
{
AutoCaller autoCaller(this);
/* sent an update request */
#if defined(RT_OS_WINDOWS)
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
#else
# error "Port me!"
#endif
}
/**
* Adds the given child process ID to the list of processes to be reaped.
* This call should be followed by #updateClientWatcher() to take the effect.
*/
{
AutoCaller autoCaller(this);
/// @todo (dmik) Win32?
#ifndef RT_OS_WINDOWS
#endif
}
/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
{
{ }
{}
{
switch (mWhat)
{
break;
break;
break;
default:
}
return S_OK;
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
AutoCaller autoCaller(this);
//Assert(fDelivered);
if (fDelivered)
{
allowChange = !fVetoed;
if (!allowChange)
{
}
}
else
allowChange = TRUE;
return allowChange;
}
/** Event for onExtraDataChange() */
{
{}
{
return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onSessionStateChange() */
{
{}
{
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onSnapshotTaken(), onSnapshotDeleted() and onSnapshotChange() */
{
{}
{
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onGuestPropertyChange() */
{
{}
{
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onMachineUninit(), this is not a CallbackEvent */
class MachineUninitEvent : public Event
{
public:
{
}
void *handler()
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
/* Handle unregistering metrics here, as it is not vital to get
* it done immediately. It reduces the number of locks needed and
* the lock contention in SessionMachine::uninit. */
{
}
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
return NULL;
}
private:
/**
* Note that this is a weak ref -- the CallbackEvent handler thread
* is bound to the lifetime of the VirtualBox instance, so it's safe.
*/
/** Reference to the machine object. */
};
/**
* Trigger internal event. This isn't meant to be signalled to clients.
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
void VirtualBox::onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
{
fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller(this);
/* unknown type must always be the first */
return m->allGuestOSTypes.front();
}
/**
* Returns the list of opened machines (machines having direct sessions opened
* by client processes) and optionally the list of direct session controls.
*
* @param aMachines Where to put opened machines (will be empty if none).
* @param aControls Where to put direct session controls (optional).
*
* @note The returned lists contain smart pointers. So, clear it as soon as
* it becomes no more necessary to release instances.
*
* @note It can be possible that a session machine from the list has been
* already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
* when accessing unprotected data directly.
*
* @note Locks objects for reading.
*/
{
AutoCaller autoCaller(this);
if (aControls)
++it)
{
{
if (aControls)
}
}
}
/**
* Searches for a machine object with the given ID in the collection
* of registered machines.
*
* @param aId Machine UUID to look for.
* @param aPermitInaccessible If true, inaccessible machines will be found;
* if false, this will fail if the given machine is inaccessible.
* @param aSetError If true, set errorinfo if the machine is not found.
* @param aMachine Returned machine, if found.
* @return
*/
bool fPermitInaccessible,
bool aSetError,
{
AutoCaller autoCaller(this);
{
++it)
{
if (!fPermitInaccessible)
{
// skip inaccessible machines
continue;
}
{
if (aMachine)
break;
}
}
}
tr("Could not find a registered machine with UUID {%RTuuid}"),
return rc;
}
{
/* empty strings are invalid */
return E_INVALIDARG;
/* the toplevel group is valid */
if (aGroup == "/")
return S_OK;
/* any other strings of length 1 are invalid */
return E_INVALIDARG;
/* must start with a slash */
return E_INVALIDARG;
/* must not end with a slash */
return E_INVALIDARG;
/* check the group components */
while (pStr)
{
if (pSlash)
{
/* no empty components (or // sequences in other words) */
return E_INVALIDARG;
/* check if the machine name rules are violated, because that means
* the group components is too close to the limits. */
return E_INVALIDARG;
}
else
{
/* check if the machine name rules are violated, because that means
* the group components is too close to the limits. */
return E_INVALIDARG;
}
}
return S_OK;
}
/**
* Validates a machine group.
*
* @param aMachineGroup Machine group.
*
* @return S_OK or E_INVALIDARG
*/
{
tr("Invalid machine group '%s'"),
return rc;
}
/**
*
* @param aMachineGroups Safearray with the machine groups.
* @param pllMachineGroups Pointer to list of strings for the result.
*
* @return S_OK or E_INVALIDARG
*/
HRESULT VirtualBox::convertMachineGroups(ComSafeArrayIn(IN_BSTR, aMachineGroups), StringsList *pllMachineGroups)
{
if (aMachineGroups)
{
{
group = "/";
return rc;
/* no duplicates please */
== pllMachineGroups->end())
}
if (pllMachineGroups->size() == 0)
}
else
return S_OK;
}
/**
* Searches for a Medium object with the given ID in the list of registered
* hard disks.
*
* @param aId ID of the hard disk. Must not be empty.
* @param aSetError If @c true , the appropriate error info is set in case
* when the hard disk is not found.
* @param aHardDisk Where to store the found hard disk object (can be NULL).
*
* @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
*
* @note Locks the media tree for reading.
*/
bool aSetError,
{
// we use the hard disks map, but it is protected by the
// hard disk _list_ lock handle
{
if (aHardDisk)
return S_OK;
}
if (aSetError)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find an open hard disk with UUID {%RTuuid}"),
return VBOX_E_OBJECT_NOT_FOUND;
}
/**
* Searches for a Medium object with the given ID or location in the list of
* registered hard disks. If both ID and location are specified, the first
* object that matches either of them (not necessarily both) is returned.
*
* @param aLocation Full location specification. Must not be empty.
* @param aSetError If @c true , the appropriate error info is set in case
* when the hard disk is not found.
* @param aHardDisk Where to store the found hard disk object (can be NULL).
*
* @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
*
* @note Locks the media tree for reading.
*/
bool aSetError,
{
// we use the hard disks map, but it is protected by the
// hard disk _list_ lock handle
++it)
{
{
if (aHardDisk)
return S_OK;
}
}
if (aSetError)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find an open hard disk with location '%s'"),
strLocation.c_str());
return VBOX_E_OBJECT_NOT_FOUND;
}
/**
* Searches for a Medium object with the given ID or location in the list of
* registered DVD or floppy images, depending on the @a mediumType argument.
* If both ID and file path are specified, the first object that matches either
* of them (not necessarily both) is returned.
*
* @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
* @param aId ID of the image file (unused when NULL).
* @param aLocation Full path to the image file (unused when NULL).
* @param aSetError If @c true, the appropriate error info is set in case when
* the image is not found.
* @param aImage Where to store the found image object (can be NULL).
*
* @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
*
* @note Locks the media tree for reading.
*/
bool aSetError,
{
{
if (RT_FAILURE(vrc))
return setError(VBOX_E_FILE_ERROR,
tr("Invalid image file location '%s' (%Rrc)"),
vrc);
}
switch (mediumType)
{
case DeviceType_DVD:
pMediaList = &m->allDVDImages;
break;
case DeviceType_Floppy:
pMediaList = &m->allFloppyImages;
break;
default:
return E_INVALIDARG;
}
bool found = false;
++it)
{
// no AutoCaller, registered image life time is bound to this
strLocationFull.c_str()) == 0);
if (found)
{
{
if (mediumType == DeviceType_DVD)
return setError(E_INVALIDARG,
else
return setError(E_INVALIDARG,
}
if (aImage)
break;
}
}
{
if (aId)
tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
m->strSettingsFilePath.c_str());
else
tr("Could not find an image file with location '%s' in the media registry ('%s')"),
m->strSettingsFilePath.c_str());
}
return rc;
}
/**
* Searches for an IMedium object that represents the given UUID.
*
* If the UUID is empty (indicating an empty drive), this sets pMedium
* to NULL and returns S_OK.
*
* If the UUID refers to a host drive of the given device type, this
* sets pMedium to the object from the list in IHost and returns S_OK.
*
* If the UUID is an image file, this sets pMedium to the object that
* findDVDOrFloppyImage() returned.
*
* If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
*
* @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
* @param uuid UUID to search for; must refer to a host drive or an image file or be null.
* @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
* @param pMedium out: IMedium object found.
* @return
*/
bool fRefresh,
bool aSetError,
{
{
// that's easy
return S_OK;
}
// first search for host drive with that UUID
uuid,
pMedium);
if (rc == VBOX_E_OBJECT_NOT_FOUND)
// then search for an image with that UUID
return rc;
}
{
/* Look for a GuestOSType object */
("Guest OS types array must be filled"));
if (bstrOSType.isEmpty())
{
pGuestOSType = NULL;
return S_OK;
}
++it)
{
{
pGuestOSType = *it;
return S_OK;
}
}
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Guest OS type '%ls' is invalid"),
bstrOSType.raw());
}
/**
* Returns the constant pseudo-machine UUID that is used to identify the
* global media registry.
*
* Starting with VirtualBox 4.0 each medium remembers in its instance data
* in which media registry it is saved (if any): this can either be a machine
* UUID, if it's in a per-machine media registry, or this global ID.
*
* This UUID is only used to identify the VirtualBox object while VirtualBox
* is running. It is a compile-time constant and not saved anywhere.
*
* @return
*/
{
return m->uuidMediaRegistry;
}
{
return m->pHost;
}
{
return m->pSystemProperties;
}
#ifdef VBOX_WITH_EXTPACK
/**
* Getter that SystemProperties and others can use to talk to the extension
* pack manager.
*/
{
return m->ptrExtPackManager;
}
#endif
/**
* Getter that machines can talk to the autostart database.
*/
{
return m->pAutostartDb;
}
#ifdef VBOX_WITH_RESOURCE_USAGE_API
{
return m->pPerformanceCollector;
}
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/**
* Returns the default machine folder from the system properties
* with proper locking.
* @return
*/
{
}
/**
* Returns the default hard disk format from the system properties
* with proper locking.
* @return
*/
{
}
{
return m->strHomeDir;
}
/**
* Calculates the absolute path of the given path taking the VirtualBox home
* directory as the current directory.
*
* @param aPath Path to calculate the absolute path for.
* @param aResult Where to put the result (used only on success, can be the
* same Utf8Str instance as passed in @a aPath).
* @return IPRT result.
*
* @note Doesn't lock any object.
*/
{
AutoCaller autoCaller(this);
/* no need to lock since mHomeDir is const */
char folder[RTPATH_MAX];
sizeof(folder));
if (RT_SUCCESS(vrc))
return vrc;
}
/**
* Copies strSource to strTarget, making it relative to the VirtualBox config folder
* if it is a subdirectory thereof, or simply copying it otherwise.
*
* @param strSource Path to evalue and copy.
* @param strTarget Buffer to receive target path.
*/
{
AutoCaller autoCaller(this);
// no need to lock since mHomeDir is const
// use strTarget as a temporary buffer to hold the machine settings dir
strTarget = m->strHomeDir;
// is relative: then append what's left
else
// is not relative: then overwrite
}
// private methods
/////////////////////////////////////////////////////////////////////////////
/**
* Checks if there is a hard disk, DVD or floppy image with the given ID or
* location already registered.
*
* On return, sets @a aConflict to the string describing the conflicting medium,
* or sets it to @c Null if no conflicting media is found. Returns S_OK in
* either case. A failure is unexpected.
*
* @param aId UUID to check.
* @param aLocation Location to check.
* @param aConflict Where to return parameters of the conflicting medium.
* @param ppMedium Medium reference in case this is simply a duplicate.
*
* @note Locks the media tree and media objects for reading.
*/
{
if (!pcszType)
{
}
if (!pcszType)
{
rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
}
if (pcszType && pMediumFound)
{
/* Note: no AutoCaller since bound to this */
)
*ppMedium = pMediumFound;
strLocFound.c_str(),
}
return S_OK;
}
/**
* Called from Machine::prepareSaveSettings() when it has detected
* that a machine has been renamed. Such renames will require
* updating the global media registry during the
* VirtualBox::saveSettings() that follows later.
*
* When a machine is renamed, there may well be media (in particular,
* diff images for snapshots) in the global registry that will need
* to have their paths updated. Before 3.2, Machine::saveSettings
* used to call VirtualBox::saveSettings implicitly, which was both
* unintuitive and caused locking order problems. Now, we remember
* such pending name changes with this method so that
* VirtualBox::saveSettings() can process them properly.
*/
const Utf8Str &strNewConfigDir)
{
}
struct SaveMediaRegistriesDesc
{
};
{
if (!pDesc)
{
LogRelFunc(("Thread for saving media registries lacks parameters\n"));
return VERR_INVALID_PARAMETER;
}
++it)
{
}
delete pDesc;
return VINF_SUCCESS;
}
/**
* Goes through all known media (hard disks, floppies and DVDs) and saves
* those into the given settings::MediaRegistry structures whose registry
* ID match the given UUID.
*
* Before actually writing to the structures, all media paths (not just the
* ones for the given registry) are updated if machines have been renamed
* since the last call.
*
* This gets called from two contexts:
*
* -- VirtualBox::saveSettings() with the UUID of the global registry
* (VirtualBox::Data.uuidRegistry); this will save those media
* which had been loaded from the global registry or have been
* attached to a "legacy" machine which can't save its own registry;
*
* -- Machine::saveSettings() with the UUID of a machine, if a medium
* has been attached to a machine created with VirtualBox 4.0 or later.
*
* Media which have only been temporarily opened without having been
* attached to a machine have a NULL registry UUID and therefore don't
* get saved.
*
* This locks the media tree. Throws HRESULT on errors!
*
* @param mediaRegistry Settings structure to fill.
* @param uuidRegistry The UUID of the media registry; either a machine UUID (if machine registry) or the UUID of the global registry.
* @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
*/
const Guid &uuidRegistry,
const Utf8Str &strMachineFolder)
{
// lock all media for the following; use a write lock because we're
// modifying the PendingMachineRenamesList, which is protected by this
// if a machine was renamed, then we'll need to refresh media paths
if (m->llPendingMachineRenames.size())
{
// make a single list from the three media lists so we don't need three loops
// with hard disks, we must use the map, not the list, because the list only has base images
++it)
{
++it2)
{
{
// Remember which medium objects has been changed,
// to trigger saving their registries later.
} else if (rc == VBOX_E_FILE_ERROR)
/* nothing */;
else
}
}
// done, don't do it again until we have more machine renames
m->llPendingMachineRenames.clear();
{
// Handle the media registry saving in a separate thread, to
// avoid giant locking problems and passing up the list many
// levels up to whoever triggered saveSettings, as there are
// lots of places which would need to handle saving more settings.
pDesc->pVirtualBox = this;
(void *)pDesc,
0, // cbStack (default)
0, // flags
"SaveMediaReg");
// failure means that settings aren't saved, but there isn't
// much we can do besides avoiding memory leaks
if (RT_FAILURE(vrc))
{
delete pDesc;
}
}
else
delete pDesc;
}
struct {
} s[] =
{
// hard disks
// floppy images
};
for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
{
++it)
{
{
}
}
}
}
/**
* Helper function which actually writes out VirtualBox.xml, the main configuration file.
* Gets called from the public VirtualBox::SaveSettings() as well as from various other
* places internally when settings need saving.
*
* @note Caller must have locked the VirtualBox object for writing and must not hold any
* other locks since this locks all kinds of member objects and trees temporarily,
* which could cause conflicts.
*/
{
AutoCaller autoCaller(this);
try
{
// machines
{
++it)
{
// save actual machine registry entry
}
}
m->uuidMediaRegistry, // global media registry ID
{
++it)
{
settings::DHCPServer d;
}
}
// leave extra data alone, it's still in the config file
// host data (USB filters)
// and write out the XML, still under the lock
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
return rc;
}
/**
* Helper to register the machine.
*
* When called during VirtualBox startup, adds the given machine to the
* collection of registered machines. Otherwise tries to mark the machine
* as registered, and, if succeeded, adds it to the collection and
* saves global settings.
*
* @note The caller must have added itself as a caller of the @a aMachine
* object if calls this method not on VirtualBox startup.
*
* @param aMachine machine to register
*
* @note Locks objects!
*/
{
AutoCaller autoCaller(this);
{
true /* fPermitInaccessible */,
false /* aDoSetError */,
&pMachine);
{
/* sanity */
return setError(E_INVALIDARG,
tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
}
}
{
}
/* add to the collection of registered machines */
rc = saveSettings();
return rc;
}
/**
* Remembers the given medium object by storing it in either the global
* medium registry or a machine one.
*
* @note Caller must hold the media tree lock for writing; in addition, this
* locks @a pMedium for reading
*
* @param pMedium Medium object to remember.
* @param ppMedium Actually stored medium object. Can be different if due
* to an unavoidable race there was a duplicate Medium object
* created.
* @param argType Either DeviceType_HardDisk, DeviceType_DVD or DeviceType_Floppy.
* @return
*/
{
AutoCaller autoCaller(this);
const char *pszDevType = NULL;
switch (argType)
{
case DeviceType_HardDisk:
pall = &m->allHardDisks;
break;
case DeviceType_DVD:
pall = &m->allDVDImages;
break;
case DeviceType_Floppy:
pall = &m->allFloppyImages;
break;
default:
}
// caller must hold the media tree write lock
{
}
&pDupMedium);
if (pDupMedium.isNull())
{
if (strConflict.length())
return setError(E_INVALIDARG,
tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
strConflict.c_str(),
m->strSettingsFilePath.c_str());
// add to the collection if it is a base medium
// store all hard disks (even differencing images) in the map
if (argType == DeviceType_HardDisk)
}
else
{
// pMedium may be the last reference to the Medium object, and the
// caller may have specified the same ComObjPtr as the output parameter.
// In this case the assignment will uninit the object, and we must not
// have a caller pending.
*ppMedium = pDupMedium;
}
return rc;
}
/**
* Removes the given medium from the respective registry.
*
* @param pMedium Hard disk object to remove.
*
* @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
*/
{
AutoCaller autoCaller(this);
// caller must hold the media tree write lock
{
}
switch (devType)
{
case DeviceType_HardDisk:
pall = &m->allHardDisks;
break;
case DeviceType_DVD:
pall = &m->allDVDImages;
break;
case DeviceType_Floppy:
pall = &m->allFloppyImages;
break;
default:
}
// remove from the collection if it is a base medium
// remove all hard disks (even differencing images) from map
if (devType == DeviceType_HardDisk)
{
}
return S_OK;
}
/**
* Little helper called from unregisterMachineMedia() to recursively add media to the given list,
* with children appearing before their parents.
* @param llMedia
* @param pMedium
*/
{
// recurse first, then add ourselves; this way children end up on the
// list before their parents
++it)
{
}
}
/**
* Unregisters all Medium objects which belong to the given machine registry.
* Gets called from Machine::uninit() just before the machine object dies
* and must only be called with a machine UUID as the registry ID.
*
* Locks the media tree.
*
* @param uuidMachine Medium registry ID (always a machine UUID)
* @return
*/
{
AutoCaller autoCaller(this);
{
++it)
{
// recursively with children first
}
}
++it)
{
}
return S_OK;
}
/**
* Removes the given machine object from the internal list of registered machines.
* Called from Machine::Unregister().
* @param pMachine
* @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
* @return
*/
{
// remove from the collection of registered machines
// save the global registry
/*
* Now go over all known media and checks if they were registered in the
* media registry of the given machine. Each such medium is then moved to
* a different media registry to make sure it doesn't get lost since its
* media registry is about to go away.
*
* This fixes the following use case: Image A.vdi of machine A is also used
* by machine B, but registered in the media registry of machine A. If machine
* A is deleted, A.vdi must be moved to the registry of B, or else B will
* become inaccessible.
*/
{
// iterate over the list of *base* images
++it)
{
{
// machine ID was found in base medium's registry list:
// move this base image and all its children to another registry then
// 1) first, find a better registry to add things to
if (puuidBetter)
{
// 2) better registry found: then use that
// 3) and make sure the registry is saved below
}
}
}
}
/* fire an event */
return rc;
}
/**
* Marks the registry for @a uuid as modified, so that it's saved in a later
* call to saveModifiedRegistries().
*
* @param uuid
*/
{
if (uuid == getGlobalRegistryId())
else
{
false /* fPermitInaccessible */,
false /* aSetError */,
&pMachine);
{
}
}
}
/**
* Saves all settings files according to the modified flags in the Machine
* objects and in the VirtualBox object.
*
* This locks machines and the VirtualBox object as necessary, so better not
* hold any locks before calling this.
*
* @return
*/
void VirtualBox::saveModifiedRegistries()
{
bool fNeedsGlobalSettings = false;
++it)
{
for (;;)
{
if (!uOld)
break;
break;
ASMNopPause();
}
if (uOld)
{
}
}
for (;;)
{
if (!uOld)
break;
break;
ASMNopPause();
}
if (uOld || fNeedsGlobalSettings)
{
rc = saveSettings();
}
}
/**
* Checks if the path to the specified file exists, according to the path
* information present in the file name. Optionally the path is created.
*
* Note that the given file name must contain the full path otherwise the
* extracted relative path will be created based on the current working
* directory which is normally unknown.
*
* @param aCreate Flag if the path should be created if it doesn't exist.
*
*/
/* static */
{
{
if (fCreate)
{
if (RT_FAILURE(vrc))
return setErrorStatic(VBOX_E_IPRT_ERROR,
vrc));
}
else
return setErrorStatic(VBOX_E_IPRT_ERROR,
}
return S_OK;
}
{
return m->strSettingsFilePath;
}
/**
* Returns the lock handle which protects the media trees (hard disks,
* DVDs, floppies). As opposed to version 3.1 and earlier, these lists
* are no longer protected by the VirtualBox lock, but by this more
* specialized lock. Mind the locking order: always request this lock
* after the VirtualBox object lock but before the locks of the media
* objects contained in these lists. See AutoLock.h.
*/
{
return m->lockMedia;
}
/**
* Thread function that watches the termination of all client processes
* that have opened sessions using IMachine::LockMachine()
*/
// static
{
size_t cntSpawned = 0;
#if defined(RT_OS_WINDOWS)
/// @todo (dmik) processes reaping!
do
{
/* VirtualBox has been early uninitialized, terminate */
if (!autoCaller.isOk())
break;
do
{
/* release the caller to let uninit() ever proceed */
INFINITE);
/* Restore the caller before using VirtualBox. If it fails, this
* means VirtualBox is being uninitialized and we must terminate. */
autoCaller.add();
if (!autoCaller.isOk())
break;
bool update = false;
if (rc == WAIT_OBJECT_0)
{
/* update event is signaled */
update = true;
}
{
/* machine mutex is released */
update = true;
}
{
/* machine mutex is abandoned due to client process termination */
update = true;
}
{
/* spawned VM process has terminated (normally or abnormally) */
update = true;
}
if (update)
{
/* close old process handles */
CloseHandle(handles[i]);
// lock the machines list for reading
/* obtain a new set of opened machines */
cnt = 0;
++it)
{
/// @todo handle situations with more than 64 objects
("MAXIMUM_WAIT_OBJECTS reached"));
{
++cnt;
}
}
/* obtain a new set of spawned machines */
cntSpawned = 0;
++it)
{
/// @todo handle situations with more than 64 objects
("MAXIMUM_WAIT_OBJECTS reached"));
{
pid, GetLastError()));
if (rc == 0)
{
++cntSpawned;
}
}
}
// machines lock unwinds here
}
}
while (true);
}
while (0);
/* close old process handles */
CloseHandle(handles[i]);
/* release sets of machines if any */
::CoUninitialize();
/// @todo (dmik) processes reaping!
/* according to PMREF, 64 is the maximum for the muxwait list */
do
{
/* VirtualBox has been early uninitialized, terminate */
if (!autoCaller.isOk())
break;
do
{
/* release the caller to let uninit() ever proceed */
/* Restore the caller before using VirtualBox. If it fails, this
* means VirtualBox is being uninitialized and we must terminate. */
autoCaller.add();
if (!autoCaller.isOk())
break;
bool update = false;
bool updateSpawned = false;
if (RT_SUCCESS(vrc))
{
/* update event is signaled */
update = true;
updateSpawned = true;
}
else
{
("RTSemEventWait returned %Rrc\n", vrc));
/* are there any mutexes? */
if (cnt > 0)
{
/* figure out what's going on with machines */
unsigned long semId = 0;
{
/* machine mutex is normally released */
{
#if 0//def DEBUG
{
LogFlowFunc(("released mutex: machine='%ls'\n",
}
#endif
}
update = true;
}
else if (arc == ERROR_SEM_OWNER_DIED)
{
/* machine mutex is abandoned due to client process
* termination; find which mutex is in the Owner Died
* state */
{
unsigned long reqCnt;
if (arc == ERROR_SEM_OWNER_DIED)
{
/* close the dead mutex as asked by PMREF */
if (i >= 0 && i < cnt)
{
#if 0//def DEBUG
{
LogFlowFunc(("mutex owner dead: machine='%ls'\n",
}
#endif
machines[i]->checkForDeath();
}
}
}
update = true;
}
else
("DosWaitMuxWaitSem returned %d\n", arc));
}
/* are there any spawning sessions? */
if (cntSpawned > 0)
{
for (size_t i = 0; i < cntSpawned; ++ i)
updateSpawned |= (spawnedMachines[i])->
}
}
if (update || updateSpawned)
{
if (update)
{
/* close the old muxsem */
if (muxSem != NULLHANDLE)
/* obtain a new set of opened machines */
cnt = 0;
{
/// @todo handle situations with more than 64 objects
("maximum of 64 mutex semaphores reached (%d)",
cnt));
{
++ cnt;
}
}
if (cnt > 0)
{
/* create a new muxsem */
("DosCreateMuxWaitSem returned %d\n", arc));
}
}
if (updateSpawned)
{
/* obtain a new set of spawned machines */
{
if ((*it)->isSessionSpawning())
}
}
}
}
while (true);
}
while (0);
/* close the muxsem */
if (muxSem != NULLHANDLE)
/* release sets of machines if any */
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
bool update = false;
bool updateSpawned = false;
do
{
if (!autoCaller.isOk())
break;
do
{
/* release the caller to let uninit() ever proceed */
/*
* Restore the caller before using VirtualBox. If it fails, this
* means VirtualBox is being uninitialized and we must terminate.
*/
autoCaller.add();
if (!autoCaller.isOk())
break;
{
/* RT_SUCCESS(rc) means an update event is signaled */
// lock the machines list for reading
{
/* obtain a new set of opened machines */
++it)
{
}
}
{
/* obtain a new set of spawned machines */
++it)
{
if ((*it)->isSessionSpawning())
}
}
// machines lock unwinds here
}
update = false;
updateSpawned = false;
for (size_t i = 0; i < cntSpawned; ++ i)
/* reap child processes */
{
{
LogFlowFunc(("UPDATE: child process count = %d\n",
{
if (vrc == VINF_SUCCESS)
{
LogFlowFunc(("pid %d (%x) was reaped, status=%d, reason=%d\n",
}
else
{
LogFlowFunc(("pid %d (%x) was NOT reaped, vrc=%Rrc\n",
if (vrc != VERR_PROCESS_RUNNING)
{
/* remove the process if it is not already running */
}
else
++ it;
}
}
}
}
}
while (true);
}
while (0);
/* release sets of machines if any */
#else
# error "Port me!"
#endif
return 0;
}
/**
* Thread function that handles custom events posted using #postEvent().
*/
// static
{
com::Initialize();
// create an event queue for the current thread
// return the queue to the one who created this thread
// signal that we're ready
/*
* we must not stop processing events and delete the "eventQ" object. This must
* be done ONLY when we stop this loop via interruptEventQueueProcessing().
* See @bugref{5724}.
*/
/* nothing */ ;
delete eventQ;
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Takes the current list of registered callbacks of the managed VirtualBox
* instance, and calls #handleCallback() for every callback item from the
* list, passing the item as an argument.
*
* @note Locks the managed VirtualBox object for reading but leaves the lock
* before iterating over callbacks and calling their methods.
*/
{
if (!mVirtualBox)
return NULL;
if (!autoCaller.isOk())
{
LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
autoCaller.state()));
/* We don't need mVirtualBox any more, so release it */
mVirtualBox = NULL;
return NULL;
}
{
}
return NULL;
}
//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
//{
// return E_NOTIMPL;
//}
{
AutoCaller autoCaller(this);
return rc;
}
{
AutoCaller autoCaller(this);
++it)
{
{
break;
}
}
if (!found)
return E_INVALIDARG;
}
{
AutoCaller autoCaller(this);
return rc;
}
/**
* Remembers the given DHCP server in the settings.
*
* @param aDHCPServer DHCP server object to remember.
* @param aSaveSettings @c true to save settings to disk (default).
*
* When @a aSaveSettings is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the dhcp server object
* will not be remembered. It is therefore the responsibility of the caller to
* call this method as the last step of some action that requires registration
* in order to make sure that only fully functional dhcp server objects get
* registered.
*
* @note Locks this object for writing and @a aDHCPServer for reading.
*/
bool aSaveSettings /*= true*/)
{
AutoCaller autoCaller(this);
return E_INVALIDARG;
if (aSaveSettings)
{
rc = saveSettings();
}
return rc;
}
/**
* Removes the given DHCP server from the settings.
*
* @param aDHCPServer DHCP server object to remove.
* @param aSaveSettings @c true to save settings to disk (default).
*
* When @a aSaveSettings is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the DHCP server
* will NOT be removed from the settingsi when this method returns.
*
* @note Locks this object for writing.
*/
bool aSaveSettings /*= true*/)
{
AutoCaller autoCaller(this);
if (aSaveSettings)
{
rc = saveSettings();
}
return rc;
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */