VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/VirtualBoxImpl.cpp@ 42208

Last change on this file since 42208 was 42208, checked in by vboxsync, 13 years ago

Main: properly initialize fSettingsCipherKeySet; don't ignore errors during encryption

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 162.7 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 42208 2012-07-18 13:22:38Z vboxsync $ */
2/** @file
3 * Implementation of IVirtualBox in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <iprt/asm.h>
19#include <iprt/base64.h>
20#include <iprt/buildconfig.h>
21#include <iprt/cpp/utils.h>
22#include <iprt/dir.h>
23#include <iprt/env.h>
24#include <iprt/file.h>
25#include <iprt/path.h>
26#include <iprt/process.h>
27#include <iprt/rand.h>
28#include <iprt/sha.h>
29#include <iprt/string.h>
30#include <iprt/stream.h>
31#include <iprt/thread.h>
32#include <iprt/uuid.h>
33#include <iprt/cpp/xml.h>
34
35#include <VBox/com/com.h>
36#include <VBox/com/array.h>
37#include "VBox/com/EventQueue.h"
38
39#include <VBox/err.h>
40#include <VBox/param.h>
41#include <VBox/settings.h>
42
43#include <package-generated.h>
44#include <version-generated.h>
45
46#include <algorithm>
47#include <set>
48#include <vector>
49#include <memory> // for auto_ptr
50
51#include "VirtualBoxImpl.h"
52
53#include "Global.h"
54#include "MachineImpl.h"
55#include "MediumImpl.h"
56#include "SharedFolderImpl.h"
57#include "ProgressImpl.h"
58#include "ProgressProxyImpl.h"
59#include "HostImpl.h"
60#include "USBControllerImpl.h"
61#include "SystemPropertiesImpl.h"
62#include "GuestOSTypeImpl.h"
63#include "DHCPServerRunner.h"
64#include "DHCPServerImpl.h"
65#ifdef VBOX_WITH_RESOURCE_USAGE_API
66# include "PerformanceImpl.h"
67#endif /* VBOX_WITH_RESOURCE_USAGE_API */
68#include "EventImpl.h"
69#include "VBoxEvents.h"
70#ifdef VBOX_WITH_EXTPACK
71# include "ExtPackManagerImpl.h"
72#endif
73#include "AutostartDb.h"
74
75#include "AutoCaller.h"
76#include "Logging.h"
77#include "objectslist.h"
78
79#ifdef RT_OS_WINDOWS
80# include "win/svchlp.h"
81# include "win/VBoxComEvents.h"
82#endif
83
84////////////////////////////////////////////////////////////////////////////////
85//
86// Definitions
87//
88////////////////////////////////////////////////////////////////////////////////
89
90#define VBOX_GLOBAL_SETTINGS_FILE "VirtualBox.xml"
91
92////////////////////////////////////////////////////////////////////////////////
93//
94// Global variables
95//
96////////////////////////////////////////////////////////////////////////////////
97
98// static
99Bstr VirtualBox::sVersion;
100
101// static
102ULONG VirtualBox::sRevision;
103
104// static
105Bstr VirtualBox::sPackageType;
106
107// static
108Bstr VirtualBox::sAPIVersion;
109
110////////////////////////////////////////////////////////////////////////////////
111//
112// CallbackEvent class
113//
114////////////////////////////////////////////////////////////////////////////////
115
116/**
117 * Abstract callback event class to asynchronously call VirtualBox callbacks
118 * on a dedicated event thread. Subclasses reimplement #handleCallback()
119 * to call appropriate IVirtualBoxCallback methods depending on the event
120 * to be dispatched.
121 *
122 * @note The VirtualBox instance passed to the constructor is strongly
123 * referenced, so that the VirtualBox singleton won't be released until the
124 * event gets handled by the event thread.
125 */
126class VirtualBox::CallbackEvent : public Event
127{
128public:
129
130 CallbackEvent(VirtualBox *aVirtualBox, VBoxEventType_T aWhat)
131 : mVirtualBox(aVirtualBox), mWhat(aWhat)
132 {
133 Assert(aVirtualBox);
134 }
135
136 void *handler();
137
138 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc) = 0;
139
140private:
141
142 /**
143 * Note that this is a weak ref -- the CallbackEvent handler thread
144 * is bound to the lifetime of the VirtualBox instance, so it's safe.
145 */
146 VirtualBox *mVirtualBox;
147protected:
148 VBoxEventType_T mWhat;
149};
150
151////////////////////////////////////////////////////////////////////////////////
152//
153// VirtualBox private member data definition
154//
155////////////////////////////////////////////////////////////////////////////////
156
157#if defined(RT_OS_WINDOWS)
158 #define UPDATEREQARG NULL
159 #define UPDATEREQTYPE HANDLE
160#elif defined(RT_OS_OS2)
161 #define UPDATEREQARG NIL_RTSEMEVENT
162 #define UPDATEREQTYPE RTSEMEVENT
163#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
164 #define UPDATEREQARG
165 #define UPDATEREQTYPE RTSEMEVENT
166#else
167# error "Port me!"
168#endif
169
170typedef ObjectsList<Machine> MachinesOList;
171typedef ObjectsList<Medium> MediaOList;
172typedef ObjectsList<GuestOSType> GuestOSTypesOList;
173typedef ObjectsList<SharedFolder> SharedFoldersOList;
174typedef ObjectsList<DHCPServer> DHCPServersOList;
175
176typedef std::map<Guid, ComPtr<IProgress> > ProgressMap;
177typedef std::map<Guid, ComObjPtr<Medium> > HardDiskMap;
178
179/**
180 * Main VirtualBox data structure.
181 * @note |const| members are persistent during lifetime so can be accessed
182 * without locking.
183 */
184struct VirtualBox::Data
185{
186 Data()
187 : pMainConfigFile(NULL),
188 uuidMediaRegistry("48024e5c-fdd9-470f-93af-ec29f7ea518c"),
189 uRegistryNeedsSaving(0),
190 lockMachines(LOCKCLASS_LISTOFMACHINES),
191 allMachines(lockMachines),
192 lockGuestOSTypes(LOCKCLASS_LISTOFOTHEROBJECTS),
193 allGuestOSTypes(lockGuestOSTypes),
194 lockMedia(LOCKCLASS_LISTOFMEDIA),
195 allHardDisks(lockMedia),
196 allDVDImages(lockMedia),
197 allFloppyImages(lockMedia),
198 lockSharedFolders(LOCKCLASS_LISTOFOTHEROBJECTS),
199 allSharedFolders(lockSharedFolders),
200 lockDHCPServers(LOCKCLASS_LISTOFOTHEROBJECTS),
201 allDHCPServers(lockDHCPServers),
202 mtxProgressOperations(LOCKCLASS_PROGRESSLIST),
203 updateReq(UPDATEREQARG),
204 threadClientWatcher(NIL_RTTHREAD),
205 threadAsyncEvent(NIL_RTTHREAD),
206 pAsyncEventQ(NULL),
207 pAutostartDb(NULL),
208 fSettingsCipherKeySet(false)
209 {
210 }
211
212 ~Data()
213 {
214 if (pMainConfigFile)
215 {
216 delete pMainConfigFile;
217 pMainConfigFile = NULL;
218 }
219 };
220
221 // const data members not requiring locking
222 const Utf8Str strHomeDir;
223
224 // VirtualBox main settings file
225 const Utf8Str strSettingsFilePath;
226 settings::MainConfigFile *pMainConfigFile;
227
228 // constant pseudo-machine ID for global media registry
229 const Guid uuidMediaRegistry;
230
231 // counter if global media registry needs saving, updated using atomic
232 // operations, without requiring any locks
233 uint64_t uRegistryNeedsSaving;
234
235 // const objects not requiring locking
236 const ComObjPtr<Host> pHost;
237 const ComObjPtr<SystemProperties> pSystemProperties;
238#ifdef VBOX_WITH_RESOURCE_USAGE_API
239 const ComObjPtr<PerformanceCollector> pPerformanceCollector;
240#endif /* VBOX_WITH_RESOURCE_USAGE_API */
241
242 // Each of the following lists use a particular lock handle that protects the
243 // list as a whole. As opposed to version 3.1 and earlier, these lists no
244 // longer need the main VirtualBox object lock, but only the respective list
245 // lock. In each case, the locking order is defined that the list must be
246 // requested before object locks of members of the lists (see the order definitions
247 // in AutoLock.h; e.g. LOCKCLASS_LISTOFMACHINES before LOCKCLASS_MACHINEOBJECT).
248 RWLockHandle lockMachines;
249 MachinesOList allMachines;
250
251 RWLockHandle lockGuestOSTypes;
252 GuestOSTypesOList allGuestOSTypes;
253
254 // All the media lists are protected by the following locking handle:
255 RWLockHandle lockMedia;
256 MediaOList allHardDisks, // base images only!
257 allDVDImages,
258 allFloppyImages;
259 // the hard disks map is an additional map sorted by UUID for quick lookup
260 // and contains ALL hard disks (base and differencing); it is protected by
261 // the same lock as the other media lists above
262 HardDiskMap mapHardDisks;
263
264 // list of pending machine renames (also protected by media tree lock;
265 // see VirtualBox::rememberMachineNameChangeForMedia())
266 struct PendingMachineRename
267 {
268 Utf8Str strConfigDirOld;
269 Utf8Str strConfigDirNew;
270 };
271 typedef std::list<PendingMachineRename> PendingMachineRenamesList;
272 PendingMachineRenamesList llPendingMachineRenames;
273
274 RWLockHandle lockSharedFolders;
275 SharedFoldersOList allSharedFolders;
276
277 RWLockHandle lockDHCPServers;
278 DHCPServersOList allDHCPServers;
279
280 RWLockHandle mtxProgressOperations;
281 ProgressMap mapProgressOperations;
282
283 // the following are data for the client watcher thread
284 const UPDATEREQTYPE updateReq;
285 const RTTHREAD threadClientWatcher;
286 typedef std::list<RTPROCESS> ProcessList;
287 ProcessList llProcesses;
288
289 // the following are data for the async event thread
290 const RTTHREAD threadAsyncEvent;
291 EventQueue * const pAsyncEventQ;
292 const ComObjPtr<EventSource> pEventSource;
293
294#ifdef VBOX_WITH_EXTPACK
295 /** The extension pack manager object lives here. */
296 const ComObjPtr<ExtPackManager> ptrExtPackManager;
297#endif
298
299 /** The global autostart database for the user. */
300 AutostartDb * const pAutostartDb;
301
302 /** Settings secret */
303 bool fSettingsCipherKeySet;
304 uint8_t SettingsCipherKey[RTSHA512_HASH_SIZE];
305};
306
307
308// constructor / destructor
309/////////////////////////////////////////////////////////////////////////////
310
311VirtualBox::VirtualBox()
312{}
313
314VirtualBox::~VirtualBox()
315{}
316
317HRESULT VirtualBox::FinalConstruct()
318{
319 LogFlowThisFunc(("\n"));
320
321 HRESULT rc = init();
322
323 BaseFinalConstruct();
324
325 return rc;
326}
327
328void VirtualBox::FinalRelease()
329{
330 LogFlowThisFunc(("\n"));
331
332 uninit();
333
334 BaseFinalRelease();
335}
336
337// public initializer/uninitializer for internal purposes only
338/////////////////////////////////////////////////////////////////////////////
339
340/**
341 * Initializes the VirtualBox object.
342 *
343 * @return COM result code
344 */
345HRESULT VirtualBox::init()
346{
347 /* Enclose the state transition NotReady->InInit->Ready */
348 AutoInitSpan autoInitSpan(this);
349 AssertReturn(autoInitSpan.isOk(), E_FAIL);
350
351 /* Locking this object for writing during init sounds a bit paradoxical,
352 * but in the current locking mess this avoids that some code gets a
353 * read lock and later calls code which wants the same write lock. */
354 AutoWriteLock lock(this COMMA_LOCKVAL_SRC_POS);
355
356 // allocate our instance data
357 m = new Data;
358
359 LogFlow(("===========================================================\n"));
360 LogFlowThisFuncEnter();
361
362 if (sVersion.isEmpty())
363 sVersion = RTBldCfgVersion();
364 sRevision = RTBldCfgRevision();
365 if (sPackageType.isEmpty())
366 sPackageType = VBOX_PACKAGE_STRING;
367 if (sAPIVersion.isEmpty())
368 sAPIVersion = VBOX_API_VERSION_STRING;
369 LogFlowThisFunc(("Version: %ls, Package: %ls, API Version: %ls\n", sVersion.raw(), sPackageType.raw(), sAPIVersion.raw()));
370
371 /* Get the VirtualBox home directory. */
372 {
373 char szHomeDir[RTPATH_MAX];
374 int vrc = com::GetVBoxUserHomeDirectory(szHomeDir, sizeof(szHomeDir));
375 if (RT_FAILURE(vrc))
376 return setError(E_FAIL,
377 tr("Could not create the VirtualBox home directory '%s' (%Rrc)"),
378 szHomeDir, vrc);
379
380 unconst(m->strHomeDir) = szHomeDir;
381 }
382
383 /* compose the VirtualBox.xml file name */
384 unconst(m->strSettingsFilePath) = Utf8StrFmt("%s%c%s",
385 m->strHomeDir.c_str(),
386 RTPATH_DELIMITER,
387 VBOX_GLOBAL_SETTINGS_FILE);
388 HRESULT rc = S_OK;
389 bool fCreate = false;
390 try
391 {
392 // load and parse VirtualBox.xml; this will throw on XML or logic errors
393 try
394 {
395 m->pMainConfigFile = new settings::MainConfigFile(&m->strSettingsFilePath);
396 }
397 catch (xml::EIPRTFailure &e)
398 {
399 // this is thrown by the XML backend if the RTOpen() call fails;
400 // only if the main settings file does not exist, create it,
401 // if there's something more serious, then do fail!
402 if (e.rc() == VERR_FILE_NOT_FOUND)
403 fCreate = true;
404 else
405 throw;
406 }
407
408 if (fCreate)
409 m->pMainConfigFile = new settings::MainConfigFile(NULL);
410
411#ifdef VBOX_WITH_RESOURCE_USAGE_API
412 /* create the performance collector object BEFORE host */
413 unconst(m->pPerformanceCollector).createObject();
414 rc = m->pPerformanceCollector->init();
415 ComAssertComRCThrowRC(rc);
416#endif /* VBOX_WITH_RESOURCE_USAGE_API */
417
418 /* create the host object early, machines will need it */
419 unconst(m->pHost).createObject();
420 rc = m->pHost->init(this);
421 ComAssertComRCThrowRC(rc);
422
423 rc = m->pHost->loadSettings(m->pMainConfigFile->host);
424 if (FAILED(rc)) throw rc;
425
426 /*
427 * Create autostart database object early, because the system properties
428 * might need it.
429 */
430 unconst(m->pAutostartDb) = new AutostartDb;
431
432 /* create the system properties object, someone may need it too */
433 unconst(m->pSystemProperties).createObject();
434 rc = m->pSystemProperties->init(this);
435 ComAssertComRCThrowRC(rc);
436
437 rc = m->pSystemProperties->loadSettings(m->pMainConfigFile->systemProperties);
438 if (FAILED(rc)) throw rc;
439
440 /* guest OS type objects, needed by machines */
441 for (size_t i = 0; i < Global::cOSTypes; ++i)
442 {
443 ComObjPtr<GuestOSType> guestOSTypeObj;
444 rc = guestOSTypeObj.createObject();
445 if (SUCCEEDED(rc))
446 {
447 rc = guestOSTypeObj->init(Global::sOSTypes[i]);
448 if (SUCCEEDED(rc))
449 m->allGuestOSTypes.addChild(guestOSTypeObj);
450 }
451 ComAssertComRCThrowRC(rc);
452 }
453
454 /* all registered media, needed by machines */
455 if (FAILED(rc = initMedia(m->uuidMediaRegistry,
456 m->pMainConfigFile->mediaRegistry,
457 Utf8Str::Empty))) // const Utf8Str &machineFolder
458 throw rc;
459
460 /* machines */
461 if (FAILED(rc = initMachines()))
462 throw rc;
463
464#ifdef DEBUG
465 LogFlowThisFunc(("Dumping media backreferences\n"));
466 dumpAllBackRefs();
467#endif
468
469 /* net services */
470 for (settings::DHCPServersList::const_iterator it = m->pMainConfigFile->llDhcpServers.begin();
471 it != m->pMainConfigFile->llDhcpServers.end();
472 ++it)
473 {
474 const settings::DHCPServer &data = *it;
475
476 ComObjPtr<DHCPServer> pDhcpServer;
477 if (SUCCEEDED(rc = pDhcpServer.createObject()))
478 rc = pDhcpServer->init(this, data);
479 if (FAILED(rc)) throw rc;
480
481 rc = registerDHCPServer(pDhcpServer, false /* aSaveRegistry */);
482 if (FAILED(rc)) throw rc;
483 }
484
485 /* events */
486 if (SUCCEEDED(rc = unconst(m->pEventSource).createObject()))
487 rc = m->pEventSource->init(static_cast<IVirtualBox*>(this));
488 if (FAILED(rc)) throw rc;
489
490#ifdef VBOX_WITH_EXTPACK
491 /* extension manager */
492 rc = unconst(m->ptrExtPackManager).createObject();
493 if (SUCCEEDED(rc))
494 rc = m->ptrExtPackManager->initExtPackManager(this, VBOXEXTPACKCTX_PER_USER_DAEMON);
495 if (FAILED(rc))
496 throw rc;
497#endif
498 }
499 catch (HRESULT err)
500 {
501 /* we assume that error info is set by the thrower */
502 rc = err;
503 }
504 catch (...)
505 {
506 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
507 }
508
509 if (SUCCEEDED(rc))
510 {
511 /* start the client watcher thread */
512#if defined(RT_OS_WINDOWS)
513 unconst(m->updateReq) = ::CreateEvent(NULL, FALSE, FALSE, NULL);
514#elif defined(RT_OS_OS2)
515 RTSemEventCreate(&unconst(m->updateReq));
516#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
517 RTSemEventCreate(&unconst(m->updateReq));
518#else
519# error "Port me!"
520#endif
521 int vrc = RTThreadCreate(&unconst(m->threadClientWatcher),
522 ClientWatcher,
523 (void *)this,
524 0,
525 RTTHREADTYPE_MAIN_WORKER,
526 RTTHREADFLAGS_WAITABLE,
527 "Watcher");
528 ComAssertRC(vrc);
529 if (RT_FAILURE(vrc))
530 rc = E_FAIL;
531 }
532
533 if (SUCCEEDED(rc))
534 {
535 try
536 {
537 /* start the async event handler thread */
538 int vrc = RTThreadCreate(&unconst(m->threadAsyncEvent),
539 AsyncEventHandler,
540 &unconst(m->pAsyncEventQ),
541 0,
542 RTTHREADTYPE_MAIN_WORKER,
543 RTTHREADFLAGS_WAITABLE,
544 "EventHandler");
545 ComAssertRCThrow(vrc, E_FAIL);
546
547 /* wait until the thread sets m->pAsyncEventQ */
548 RTThreadUserWait(m->threadAsyncEvent, RT_INDEFINITE_WAIT);
549 ComAssertThrow(m->pAsyncEventQ, E_FAIL);
550 }
551 catch (HRESULT aRC)
552 {
553 rc = aRC;
554 }
555 }
556
557 /* Confirm a successful initialization when it's the case */
558 if (SUCCEEDED(rc))
559 autoInitSpan.setSucceeded();
560
561#ifdef VBOX_WITH_EXTPACK
562 /* Let the extension packs have a go at things. */
563 if (SUCCEEDED(rc))
564 {
565 lock.release();
566 m->ptrExtPackManager->callAllVirtualBoxReadyHooks();
567 }
568#endif
569
570 LogFlowThisFunc(("rc=%08X\n", rc));
571 LogFlowThisFuncLeave();
572 LogFlow(("===========================================================\n"));
573 return rc;
574}
575
576HRESULT VirtualBox::initMachines()
577{
578 for (settings::MachinesRegistry::const_iterator it = m->pMainConfigFile->llMachines.begin();
579 it != m->pMainConfigFile->llMachines.end();
580 ++it)
581 {
582 HRESULT rc = S_OK;
583 const settings::MachineRegistryEntry &xmlMachine = *it;
584 Guid uuid = xmlMachine.uuid;
585
586 ComObjPtr<Machine> pMachine;
587 if (SUCCEEDED(rc = pMachine.createObject()))
588 {
589 rc = pMachine->init(this,
590 xmlMachine.strSettingsFile,
591 &uuid);
592 if (SUCCEEDED(rc))
593 rc = registerMachine(pMachine);
594 if (FAILED(rc))
595 return rc;
596 }
597 }
598
599 return S_OK;
600}
601
602/**
603 * Loads a media registry from XML and adds the media contained therein to
604 * the global lists of known media.
605 *
606 * This now (4.0) gets called from two locations:
607 *
608 * -- VirtualBox::init(), to load the global media registry from VirtualBox.xml;
609 *
610 * -- Machine::loadMachineDataFromSettings(), to load the per-machine registry
611 * from machine XML, for machines created with VirtualBox 4.0 or later.
612 *
613 * In both cases, the media found are added to the global lists so the
614 * global arrays of media (including the GUI's virtual media manager)
615 * continue to work as before.
616 *
617 * @param uuidMachineRegistry The UUID of the media registry. This is either the
618 * transient UUID created at VirtualBox startup for the global registry or
619 * a machine ID.
620 * @param mediaRegistry The XML settings structure to load, either from VirtualBox.xml
621 * or a machine XML.
622 * @return
623 */
624HRESULT VirtualBox::initMedia(const Guid &uuidRegistry,
625 const settings::MediaRegistry mediaRegistry,
626 const Utf8Str &strMachineFolder)
627{
628 LogFlow(("VirtualBox::initMedia ENTERING, uuidRegistry=%s, strMachineFolder=%s\n",
629 uuidRegistry.toString().c_str(),
630 strMachineFolder.c_str()));
631
632 AutoWriteLock treeLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
633
634 HRESULT rc = S_OK;
635 settings::MediaList::const_iterator it;
636 for (it = mediaRegistry.llHardDisks.begin();
637 it != mediaRegistry.llHardDisks.end();
638 ++it)
639 {
640 const settings::Medium &xmlHD = *it;
641
642 ComObjPtr<Medium> pHardDisk;
643 if (SUCCEEDED(rc = pHardDisk.createObject()))
644 rc = pHardDisk->init(this,
645 NULL, // parent
646 DeviceType_HardDisk,
647 uuidRegistry,
648 xmlHD, // XML data; this recurses to processes the children
649 strMachineFolder);
650 if (FAILED(rc)) return rc;
651
652 rc = registerMedium(pHardDisk, &pHardDisk, DeviceType_HardDisk);
653 if (FAILED(rc)) return rc;
654 }
655
656 for (it = mediaRegistry.llDvdImages.begin();
657 it != mediaRegistry.llDvdImages.end();
658 ++it)
659 {
660 const settings::Medium &xmlDvd = *it;
661
662 ComObjPtr<Medium> pImage;
663 if (SUCCEEDED(pImage.createObject()))
664 rc = pImage->init(this,
665 NULL,
666 DeviceType_DVD,
667 uuidRegistry,
668 xmlDvd,
669 strMachineFolder);
670 if (FAILED(rc)) return rc;
671
672 rc = registerMedium(pImage, &pImage, DeviceType_DVD);
673 if (FAILED(rc)) return rc;
674 }
675
676 for (it = mediaRegistry.llFloppyImages.begin();
677 it != mediaRegistry.llFloppyImages.end();
678 ++it)
679 {
680 const settings::Medium &xmlFloppy = *it;
681
682 ComObjPtr<Medium> pImage;
683 if (SUCCEEDED(pImage.createObject()))
684 rc = pImage->init(this,
685 NULL,
686 DeviceType_Floppy,
687 uuidRegistry,
688 xmlFloppy,
689 strMachineFolder);
690 if (FAILED(rc)) return rc;
691
692 rc = registerMedium(pImage, &pImage, DeviceType_Floppy);
693 if (FAILED(rc)) return rc;
694 }
695
696 LogFlow(("VirtualBox::initMedia LEAVING\n"));
697
698 return S_OK;
699}
700
701void VirtualBox::uninit()
702{
703 Assert(!m->uRegistryNeedsSaving);
704 if (m->uRegistryNeedsSaving)
705 saveSettings();
706
707 /* Enclose the state transition Ready->InUninit->NotReady */
708 AutoUninitSpan autoUninitSpan(this);
709 if (autoUninitSpan.uninitDone())
710 return;
711
712 LogFlow(("===========================================================\n"));
713 LogFlowThisFuncEnter();
714 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
715
716 /* tell all our child objects we've been uninitialized */
717
718 LogFlowThisFunc(("Uninitializing machines (%d)...\n", m->allMachines.size()));
719 if (m->pHost)
720 {
721 /* It is necessary to hold the VirtualBox and Host locks here because
722 we may have to uninitialize SessionMachines. */
723 AutoMultiWriteLock2 multilock(this, m->pHost COMMA_LOCKVAL_SRC_POS);
724 m->allMachines.uninitAll();
725 }
726 else
727 m->allMachines.uninitAll();
728 m->allFloppyImages.uninitAll();
729 m->allDVDImages.uninitAll();
730 m->allHardDisks.uninitAll();
731 m->allDHCPServers.uninitAll();
732
733 m->mapProgressOperations.clear();
734
735 m->allGuestOSTypes.uninitAll();
736
737 /* Note that we release singleton children after we've all other children.
738 * In some cases this is important because these other children may use
739 * some resources of the singletons which would prevent them from
740 * uninitializing (as for example, mSystemProperties which owns
741 * MediumFormat objects which Medium objects refer to) */
742 if (m->pSystemProperties)
743 {
744 m->pSystemProperties->uninit();
745 unconst(m->pSystemProperties).setNull();
746 }
747
748 if (m->pHost)
749 {
750 m->pHost->uninit();
751 unconst(m->pHost).setNull();
752 }
753
754#ifdef VBOX_WITH_RESOURCE_USAGE_API
755 if (m->pPerformanceCollector)
756 {
757 m->pPerformanceCollector->uninit();
758 unconst(m->pPerformanceCollector).setNull();
759 }
760#endif /* VBOX_WITH_RESOURCE_USAGE_API */
761
762 LogFlowThisFunc(("Terminating the async event handler...\n"));
763 if (m->threadAsyncEvent != NIL_RTTHREAD)
764 {
765 /* signal to exit the event loop */
766 if (RT_SUCCESS(m->pAsyncEventQ->interruptEventQueueProcessing()))
767 {
768 /*
769 * Wait for thread termination (only after we've successfully
770 * interrupted the event queue processing!)
771 */
772 int vrc = RTThreadWait(m->threadAsyncEvent, 60000, NULL);
773 if (RT_FAILURE(vrc))
774 LogWarningFunc(("RTThreadWait(%RTthrd) -> %Rrc\n",
775 m->threadAsyncEvent, vrc));
776 }
777 else
778 {
779 AssertMsgFailed(("interruptEventQueueProcessing() failed\n"));
780 RTThreadWait(m->threadAsyncEvent, 0, NULL);
781 }
782
783 unconst(m->threadAsyncEvent) = NIL_RTTHREAD;
784 unconst(m->pAsyncEventQ) = NULL;
785 }
786
787 LogFlowThisFunc(("Releasing event source...\n"));
788 if (m->pEventSource)
789 {
790 // we don't perform uninit() as it's possible that some pending event refers to this source
791 unconst(m->pEventSource).setNull();
792 }
793
794 LogFlowThisFunc(("Terminating the client watcher...\n"));
795 if (m->threadClientWatcher != NIL_RTTHREAD)
796 {
797 /* signal the client watcher thread */
798 updateClientWatcher();
799 /* wait for the termination */
800 RTThreadWait(m->threadClientWatcher, RT_INDEFINITE_WAIT, NULL);
801 unconst(m->threadClientWatcher) = NIL_RTTHREAD;
802 }
803 m->llProcesses.clear();
804#if defined(RT_OS_WINDOWS)
805 if (m->updateReq != NULL)
806 {
807 ::CloseHandle(m->updateReq);
808 unconst(m->updateReq) = NULL;
809 }
810#elif defined(RT_OS_OS2)
811 if (m->updateReq != NIL_RTSEMEVENT)
812 {
813 RTSemEventDestroy(m->updateReq);
814 unconst(m->updateReq) = NIL_RTSEMEVENT;
815 }
816#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
817 if (m->updateReq != NIL_RTSEMEVENT)
818 {
819 RTSemEventDestroy(m->updateReq);
820 unconst(m->updateReq) = NIL_RTSEMEVENT;
821 }
822#else
823# error "Port me!"
824#endif
825
826 delete m->pAutostartDb;
827
828 // clean up our instance data
829 delete m;
830
831 /* Unload hard disk plugin backends. */
832 VDShutdown();
833
834 LogFlowThisFuncLeave();
835 LogFlow(("===========================================================\n"));
836}
837
838// IVirtualBox properties
839/////////////////////////////////////////////////////////////////////////////
840
841STDMETHODIMP VirtualBox::COMGETTER(Version)(BSTR *aVersion)
842{
843 CheckComArgNotNull(aVersion);
844
845 AutoCaller autoCaller(this);
846 if (FAILED(autoCaller.rc())) return autoCaller.rc();
847
848 sVersion.cloneTo(aVersion);
849 return S_OK;
850}
851
852STDMETHODIMP VirtualBox::COMGETTER(Revision)(ULONG *aRevision)
853{
854 CheckComArgNotNull(aRevision);
855
856 AutoCaller autoCaller(this);
857 if (FAILED(autoCaller.rc())) return autoCaller.rc();
858
859 *aRevision = sRevision;
860 return S_OK;
861}
862
863STDMETHODIMP VirtualBox::COMGETTER(PackageType)(BSTR *aPackageType)
864{
865 CheckComArgNotNull(aPackageType);
866
867 AutoCaller autoCaller(this);
868 if (FAILED(autoCaller.rc())) return autoCaller.rc();
869
870 sPackageType.cloneTo(aPackageType);
871 return S_OK;
872}
873
874STDMETHODIMP VirtualBox::COMGETTER(APIVersion)(BSTR *aAPIVersion)
875{
876 CheckComArgNotNull(aAPIVersion);
877
878 AutoCaller autoCaller(this);
879 if (FAILED(autoCaller.rc())) return autoCaller.rc();
880
881 sAPIVersion.cloneTo(aAPIVersion);
882 return S_OK;
883}
884
885STDMETHODIMP VirtualBox::COMGETTER(HomeFolder)(BSTR *aHomeFolder)
886{
887 CheckComArgNotNull(aHomeFolder);
888
889 AutoCaller autoCaller(this);
890 if (FAILED(autoCaller.rc())) return autoCaller.rc();
891
892 /* mHomeDir is const and doesn't need a lock */
893 m->strHomeDir.cloneTo(aHomeFolder);
894 return S_OK;
895}
896
897STDMETHODIMP VirtualBox::COMGETTER(SettingsFilePath)(BSTR *aSettingsFilePath)
898{
899 CheckComArgNotNull(aSettingsFilePath);
900
901 AutoCaller autoCaller(this);
902 if (FAILED(autoCaller.rc())) return autoCaller.rc();
903
904 /* mCfgFile.mName is const and doesn't need a lock */
905 m->strSettingsFilePath.cloneTo(aSettingsFilePath);
906 return S_OK;
907}
908
909STDMETHODIMP VirtualBox::COMGETTER(Host)(IHost **aHost)
910{
911 CheckComArgOutPointerValid(aHost);
912
913 AutoCaller autoCaller(this);
914 if (FAILED(autoCaller.rc())) return autoCaller.rc();
915
916 /* mHost is const, no need to lock */
917 m->pHost.queryInterfaceTo(aHost);
918 return S_OK;
919}
920
921STDMETHODIMP
922VirtualBox::COMGETTER(SystemProperties)(ISystemProperties **aSystemProperties)
923{
924 CheckComArgOutPointerValid(aSystemProperties);
925
926 AutoCaller autoCaller(this);
927 if (FAILED(autoCaller.rc())) return autoCaller.rc();
928
929 /* mSystemProperties is const, no need to lock */
930 m->pSystemProperties.queryInterfaceTo(aSystemProperties);
931 return S_OK;
932}
933
934STDMETHODIMP
935VirtualBox::COMGETTER(Machines)(ComSafeArrayOut(IMachine *, aMachines))
936{
937 CheckComArgOutSafeArrayPointerValid(aMachines);
938
939 AutoCaller autoCaller(this);
940 if (FAILED(autoCaller.rc())) return autoCaller.rc();
941
942 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
943 SafeIfaceArray<IMachine> machines(m->allMachines.getList());
944 machines.detachTo(ComSafeArrayOutArg(aMachines));
945
946 return S_OK;
947}
948
949STDMETHODIMP
950VirtualBox::COMGETTER(MachineGroups)(ComSafeArrayOut(BSTR, aMachineGroups))
951{
952 CheckComArgOutSafeArrayPointerValid(aMachineGroups);
953
954 AutoCaller autoCaller(this);
955 if (FAILED(autoCaller.rc())) return autoCaller.rc();
956
957 std::list<Bstr> allGroups;
958
959 /* get copy of all machine references, to avoid holding the list lock */
960 MachinesOList::MyList allMachines;
961 {
962 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
963 allMachines = m->allMachines.getList();
964 }
965 for (MachinesOList::MyList::const_iterator it = allMachines.begin();
966 it != allMachines.end();
967 ++it)
968 {
969 const ComObjPtr<Machine> &pMachine = *it;
970 AutoCaller autoMachineCaller(pMachine);
971 if (FAILED(autoMachineCaller.rc()))
972 continue;
973 AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
974
975 if (pMachine->isAccessible())
976 {
977 SafeArray<BSTR> thisGroups;
978 HRESULT rc = pMachine->COMGETTER(Groups)(ComSafeArrayAsOutParam(thisGroups));
979 if (FAILED(rc))
980 continue;
981
982 for (size_t i = 0; i < thisGroups.size(); i++)
983 allGroups.push_back(thisGroups[i]);
984 }
985 }
986
987 /* throw out any duplicates */
988 allGroups.sort();
989 allGroups.unique();
990 com::SafeArray<BSTR> machineGroups(allGroups.size());
991 size_t i = 0;
992 for (std::list<Bstr>::const_iterator it = allGroups.begin();
993 it != allGroups.end();
994 ++it, i++)
995 {
996 const Bstr &tmp = *it;
997 tmp.cloneTo(&machineGroups[i]);
998 }
999 machineGroups.detachTo(ComSafeArrayOutArg(aMachineGroups));
1000
1001 return S_OK;
1002}
1003
1004STDMETHODIMP VirtualBox::COMGETTER(HardDisks)(ComSafeArrayOut(IMedium *, aHardDisks))
1005{
1006 CheckComArgOutSafeArrayPointerValid(aHardDisks);
1007
1008 AutoCaller autoCaller(this);
1009 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1010
1011 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1012 SafeIfaceArray<IMedium> hardDisks(m->allHardDisks.getList());
1013 hardDisks.detachTo(ComSafeArrayOutArg(aHardDisks));
1014
1015 return S_OK;
1016}
1017
1018STDMETHODIMP VirtualBox::COMGETTER(DVDImages)(ComSafeArrayOut(IMedium *, aDVDImages))
1019{
1020 CheckComArgOutSafeArrayPointerValid(aDVDImages);
1021
1022 AutoCaller autoCaller(this);
1023 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1024
1025 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1026 SafeIfaceArray<IMedium> images(m->allDVDImages.getList());
1027 images.detachTo(ComSafeArrayOutArg(aDVDImages));
1028
1029 return S_OK;
1030}
1031
1032STDMETHODIMP VirtualBox::COMGETTER(FloppyImages)(ComSafeArrayOut(IMedium *, aFloppyImages))
1033{
1034 CheckComArgOutSafeArrayPointerValid(aFloppyImages);
1035
1036 AutoCaller autoCaller(this);
1037 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1038
1039 AutoReadLock al(m->allFloppyImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1040 SafeIfaceArray<IMedium> images(m->allFloppyImages.getList());
1041 images.detachTo(ComSafeArrayOutArg(aFloppyImages));
1042
1043 return S_OK;
1044}
1045
1046STDMETHODIMP VirtualBox::COMGETTER(ProgressOperations)(ComSafeArrayOut(IProgress *, aOperations))
1047{
1048 CheckComArgOutPointerValid(aOperations);
1049
1050 AutoCaller autoCaller(this);
1051 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1052
1053 /* protect mProgressOperations */
1054 AutoReadLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
1055 SafeIfaceArray<IProgress> progress(m->mapProgressOperations);
1056 progress.detachTo(ComSafeArrayOutArg(aOperations));
1057
1058 return S_OK;
1059}
1060
1061STDMETHODIMP VirtualBox::COMGETTER(GuestOSTypes)(ComSafeArrayOut(IGuestOSType *, aGuestOSTypes))
1062{
1063 CheckComArgOutSafeArrayPointerValid(aGuestOSTypes);
1064
1065 AutoCaller autoCaller(this);
1066 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1067
1068 AutoReadLock al(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1069 SafeIfaceArray<IGuestOSType> ostypes(m->allGuestOSTypes.getList());
1070 ostypes.detachTo(ComSafeArrayOutArg(aGuestOSTypes));
1071
1072 return S_OK;
1073}
1074
1075STDMETHODIMP VirtualBox::COMGETTER(SharedFolders)(ComSafeArrayOut(ISharedFolder *, aSharedFolders))
1076{
1077#ifndef RT_OS_WINDOWS
1078 NOREF(aSharedFoldersSize);
1079#endif /* RT_OS_WINDOWS */
1080
1081 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
1082
1083 AutoCaller autoCaller(this);
1084 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1085
1086 return setError(E_NOTIMPL, "Not yet implemented");
1087}
1088
1089STDMETHODIMP
1090VirtualBox::COMGETTER(PerformanceCollector)(IPerformanceCollector **aPerformanceCollector)
1091{
1092#ifdef VBOX_WITH_RESOURCE_USAGE_API
1093 CheckComArgOutPointerValid(aPerformanceCollector);
1094
1095 AutoCaller autoCaller(this);
1096 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1097
1098 /* mPerformanceCollector is const, no need to lock */
1099 m->pPerformanceCollector.queryInterfaceTo(aPerformanceCollector);
1100
1101 return S_OK;
1102#else /* !VBOX_WITH_RESOURCE_USAGE_API */
1103 ReturnComNotImplemented();
1104#endif /* !VBOX_WITH_RESOURCE_USAGE_API */
1105}
1106
1107STDMETHODIMP
1108VirtualBox::COMGETTER(DHCPServers)(ComSafeArrayOut(IDHCPServer *, aDHCPServers))
1109{
1110 CheckComArgOutSafeArrayPointerValid(aDHCPServers);
1111
1112 AutoCaller autoCaller(this);
1113 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1114
1115 AutoReadLock al(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1116 SafeIfaceArray<IDHCPServer> svrs(m->allDHCPServers.getList());
1117 svrs.detachTo(ComSafeArrayOutArg(aDHCPServers));
1118
1119 return S_OK;
1120}
1121
1122STDMETHODIMP
1123VirtualBox::COMGETTER(EventSource)(IEventSource ** aEventSource)
1124{
1125 CheckComArgOutPointerValid(aEventSource);
1126
1127 AutoCaller autoCaller(this);
1128 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1129
1130 /* event source is const, no need to lock */
1131 m->pEventSource.queryInterfaceTo(aEventSource);
1132
1133 return S_OK;
1134}
1135
1136STDMETHODIMP
1137VirtualBox::COMGETTER(ExtensionPackManager)(IExtPackManager **aExtPackManager)
1138{
1139 CheckComArgOutPointerValid(aExtPackManager);
1140
1141 AutoCaller autoCaller(this);
1142 HRESULT hrc = autoCaller.rc();
1143 if (SUCCEEDED(hrc))
1144 {
1145#ifdef VBOX_WITH_EXTPACK
1146 /* The extension pack manager is const, no need to lock. */
1147 hrc = m->ptrExtPackManager.queryInterfaceTo(aExtPackManager);
1148#else
1149 hrc = E_NOTIMPL;
1150#endif
1151 }
1152
1153 return hrc;
1154}
1155
1156STDMETHODIMP VirtualBox::COMGETTER(InternalNetworks)(ComSafeArrayOut(BSTR, aInternalNetworks))
1157{
1158 CheckComArgOutSafeArrayPointerValid(aInternalNetworks);
1159
1160 AutoCaller autoCaller(this);
1161 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1162
1163 std::list<Bstr> allInternalNetworks;
1164
1165 /* get copy of all machine references, to avoid holding the list lock */
1166 MachinesOList::MyList allMachines;
1167 {
1168 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1169 allMachines = m->allMachines.getList();
1170 }
1171 for (MachinesOList::MyList::const_iterator it = allMachines.begin();
1172 it != allMachines.end();
1173 ++it)
1174 {
1175 const ComObjPtr<Machine> &pMachine = *it;
1176 AutoCaller autoMachineCaller(pMachine);
1177 if (FAILED(autoMachineCaller.rc()))
1178 continue;
1179 AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
1180
1181 if (pMachine->isAccessible())
1182 {
1183 uint32_t cNetworkAdapters = Global::getMaxNetworkAdapters(pMachine->getChipsetType());
1184 for (ULONG i = 0; i < cNetworkAdapters; i++)
1185 {
1186 ComPtr<INetworkAdapter> pNet;
1187 HRESULT rc = pMachine->GetNetworkAdapter(i, pNet.asOutParam());
1188 if (FAILED(rc) || pNet.isNull())
1189 continue;
1190 Bstr strInternalNetwork;
1191 rc = pNet->COMGETTER(InternalNetwork)(strInternalNetwork.asOutParam());
1192 if (FAILED(rc) || strInternalNetwork.isEmpty())
1193 continue;
1194
1195 allInternalNetworks.push_back(strInternalNetwork);
1196 }
1197 }
1198 }
1199
1200 /* throw out any duplicates */
1201 allInternalNetworks.sort();
1202 allInternalNetworks.unique();
1203 com::SafeArray<BSTR> internalNetworks(allInternalNetworks.size());
1204 size_t i = 0;
1205 for (std::list<Bstr>::const_iterator it = allInternalNetworks.begin();
1206 it != allInternalNetworks.end();
1207 ++it, i++)
1208 {
1209 const Bstr &tmp = *it;
1210 tmp.cloneTo(&internalNetworks[i]);
1211 }
1212 internalNetworks.detachTo(ComSafeArrayOutArg(aInternalNetworks));
1213
1214 return S_OK;
1215}
1216
1217STDMETHODIMP VirtualBox::COMGETTER(GenericNetworkDrivers)(ComSafeArrayOut(BSTR, aGenericNetworkDrivers))
1218{
1219 CheckComArgOutSafeArrayPointerValid(aGenericNetworkDrivers);
1220
1221 AutoCaller autoCaller(this);
1222 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1223
1224 std::list<Bstr> allGenericNetworkDrivers;
1225
1226 /* get copy of all machine references, to avoid holding the list lock */
1227 MachinesOList::MyList allMachines;
1228 {
1229 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1230 allMachines = m->allMachines.getList();
1231 }
1232 for (MachinesOList::MyList::const_iterator it = allMachines.begin();
1233 it != allMachines.end();
1234 ++it)
1235 {
1236 const ComObjPtr<Machine> &pMachine = *it;
1237 AutoCaller autoMachineCaller(pMachine);
1238 if (FAILED(autoMachineCaller.rc()))
1239 continue;
1240 AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
1241
1242 if (pMachine->isAccessible())
1243 {
1244 uint32_t cNetworkAdapters = Global::getMaxNetworkAdapters(pMachine->getChipsetType());
1245 for (ULONG i = 0; i < cNetworkAdapters; i++)
1246 {
1247 ComPtr<INetworkAdapter> pNet;
1248 HRESULT rc = pMachine->GetNetworkAdapter(i, pNet.asOutParam());
1249 if (FAILED(rc) || pNet.isNull())
1250 continue;
1251 Bstr strGenericNetworkDriver;
1252 rc = pNet->COMGETTER(GenericDriver)(strGenericNetworkDriver.asOutParam());
1253 if (FAILED(rc) || strGenericNetworkDriver.isEmpty())
1254 continue;
1255
1256 allGenericNetworkDrivers.push_back(strGenericNetworkDriver);
1257 }
1258 }
1259 }
1260
1261 /* throw out any duplicates */
1262 allGenericNetworkDrivers.sort();
1263 allGenericNetworkDrivers.unique();
1264 com::SafeArray<BSTR> genericNetworks(allGenericNetworkDrivers.size());
1265 size_t i = 0;
1266 for (std::list<Bstr>::const_iterator it = allGenericNetworkDrivers.begin();
1267 it != allGenericNetworkDrivers.end();
1268 ++it, i++)
1269 {
1270 const Bstr &tmp = *it;
1271 tmp.cloneTo(&genericNetworks[i]);
1272 }
1273 genericNetworks.detachTo(ComSafeArrayOutArg(aGenericNetworkDrivers));
1274
1275 return S_OK;
1276}
1277
1278STDMETHODIMP
1279VirtualBox::CheckFirmwarePresent(FirmwareType_T aFirmwareType,
1280 IN_BSTR aVersion,
1281 BSTR *aUrl,
1282 BSTR *aFile,
1283 BOOL *aResult)
1284{
1285 CheckComArgNotNull(aResult);
1286
1287 AutoCaller autoCaller(this);
1288 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1289
1290 NOREF(aVersion);
1291
1292 static const struct
1293 {
1294 FirmwareType_T type;
1295 const char* fileName;
1296 const char* url;
1297 }
1298 firmwareDesc[] =
1299 {
1300 {
1301 /* compiled-in firmware */
1302 FirmwareType_BIOS, NULL, NULL
1303 },
1304 {
1305 FirmwareType_EFI32, "VBoxEFI32.fd", "http://virtualbox.org/firmware/VBoxEFI32.fd"
1306 },
1307 {
1308 FirmwareType_EFI64, "VBoxEFI64.fd", "http://virtualbox.org/firmware/VBoxEFI64.fd"
1309 },
1310 {
1311 FirmwareType_EFIDUAL, "VBoxEFIDual.fd", "http://virtualbox.org/firmware/VBoxEFIDual.fd"
1312 }
1313 };
1314
1315 for (size_t i = 0; i < sizeof(firmwareDesc) / sizeof(firmwareDesc[0]); i++)
1316 {
1317 if (aFirmwareType != firmwareDesc[i].type)
1318 continue;
1319
1320 /* compiled-in firmware */
1321 if (firmwareDesc[i].fileName == NULL)
1322 {
1323 *aResult = TRUE;
1324 break;
1325 }
1326
1327 Utf8Str shortName, fullName;
1328
1329 shortName = Utf8StrFmt("Firmware%c%s",
1330 RTPATH_DELIMITER,
1331 firmwareDesc[i].fileName);
1332 int rc = calculateFullPath(shortName, fullName);
1333 AssertRCReturn(rc, rc);
1334 if (RTFileExists(fullName.c_str()))
1335 {
1336 *aResult = TRUE;
1337 if (aFile)
1338 Utf8Str(fullName).cloneTo(aFile);
1339 break;
1340 }
1341
1342 char pszVBoxPath[RTPATH_MAX];
1343 rc = RTPathExecDir(pszVBoxPath, RTPATH_MAX);
1344 AssertRCReturn(rc, rc);
1345 fullName = Utf8StrFmt("%s%c%s",
1346 pszVBoxPath,
1347 RTPATH_DELIMITER,
1348 firmwareDesc[i].fileName);
1349 if (RTFileExists(fullName.c_str()))
1350 {
1351 *aResult = TRUE;
1352 if (aFile)
1353 Utf8Str(fullName).cloneTo(aFile);
1354 break;
1355 }
1356
1357 /** @todo: account for version in the URL */
1358 if (aUrl != NULL)
1359 {
1360 Utf8Str strUrl(firmwareDesc[i].url);
1361 strUrl.cloneTo(aUrl);
1362 }
1363 *aResult = FALSE;
1364
1365 /* Assume single record per firmware type */
1366 break;
1367 }
1368
1369 return S_OK;
1370}
1371// IVirtualBox methods
1372/////////////////////////////////////////////////////////////////////////////
1373
1374/* Helper for VirtualBox::ComposeMachineFilename */
1375static void sanitiseMachineFilename(Utf8Str &aName);
1376
1377STDMETHODIMP VirtualBox::ComposeMachineFilename(IN_BSTR aName,
1378 IN_BSTR aGroup,
1379 IN_BSTR aBaseFolder,
1380 BSTR *aFilename)
1381{
1382 LogFlowThisFuncEnter();
1383 LogFlowThisFunc(("aName=\"%ls\",aBaseFolder=\"%ls\"\n", aName, aBaseFolder));
1384
1385 CheckComArgStrNotEmptyOrNull(aName);
1386 CheckComArgOutPointerValid(aFilename);
1387
1388 AutoCaller autoCaller(this);
1389 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1390
1391 Utf8Str strGroup(aGroup);
1392 if (strGroup.isEmpty())
1393 strGroup = "/";
1394 HRESULT rc = validateMachineGroup(strGroup);
1395 if (FAILED(rc))
1396 return rc;
1397
1398 /* Compose the settings file name using the following scheme:
1399 *
1400 * <base_folder><group>/<machine_name>/<machine_name>.xml
1401 *
1402 * If a non-null and non-empty base folder is specified, the default
1403 * machine folder will be used as a base folder.
1404 * We sanitise the machine name to a safe white list of characters before
1405 * using it.
1406 */
1407 Utf8Str strBase = aBaseFolder;
1408 Utf8Str strName = aName;
1409 sanitiseMachineFilename(strName);
1410
1411 if (strBase.isEmpty())
1412 /* we use the non-full folder value below to keep the path relative */
1413 getDefaultMachineFolder(strBase);
1414
1415 calculateFullPath(strBase, strBase);
1416
1417 /* eliminate toplevel group to avoid // in the result */
1418 if (strGroup == "/")
1419 strGroup.setNull();
1420 Bstr bstrSettingsFile = BstrFmt("%s%s%c%s%c%s.vbox",
1421 strBase.c_str(),
1422 strGroup.c_str(),
1423 RTPATH_DELIMITER,
1424 strName.c_str(),
1425 RTPATH_DELIMITER,
1426 strName.c_str());
1427
1428 bstrSettingsFile.detachTo(aFilename);
1429
1430 return S_OK;
1431}
1432
1433/**
1434 * Remove characters from a machine file name which can be problematic on
1435 * particular systems.
1436 * @param strName The file name to sanitise.
1437 */
1438void sanitiseMachineFilename(Utf8Str &strName)
1439{
1440 /** Set of characters which should be safe for use in filenames: some basic
1441 * ASCII, Unicode from Latin-1 alphabetic to the end of Hangul. We try to
1442 * skip anything that could count as a control character in Windows or
1443 * *nix, or be otherwise difficult for shells to handle (I would have
1444 * preferred to remove the space and brackets too). We also remove all
1445 * characters which need UTF-16 surrogate pairs for Windows's benefit. */
1446#ifdef RT_STRICT
1447 RTUNICP aCpSet[] =
1448 { ' ', ' ', '(', ')', '-', '.', '0', '9', 'A', 'Z', 'a', 'z', '_', '_',
1449 0xa0, 0xd7af, '\0' };
1450#endif
1451 char *pszName = strName.mutableRaw();
1452 Assert(RTStrPurgeComplementSet(pszName, aCpSet, '_') >= 0);
1453 /* No leading dot or dash. */
1454 if (pszName[0] == '.' || pszName[0] == '-')
1455 pszName[0] = '_';
1456 /* No trailing dot. */
1457 if (pszName[strName.length() - 1] == '.')
1458 pszName[strName.length() - 1] = '_';
1459 /* Mangle leading and trailing spaces. */
1460 for (size_t i = 0; pszName[i] == ' '; ++i)
1461 pszName[i] = '_';
1462 for (size_t i = strName.length() - 1; i && pszName[i] == ' '; --i)
1463 pszName[i] = '_';
1464}
1465
1466#ifdef DEBUG
1467/** Simple unit test/operation examples for sanitiseMachineFilename(). */
1468static unsigned testSanitiseMachineFilename(void (*pfnPrintf)(const char *, ...))
1469{
1470 unsigned cErrors = 0;
1471
1472 /** Expected results of sanitising given file names. */
1473 static struct
1474 {
1475 /** The test file name to be sanitised (Utf-8). */
1476 const char *pcszIn;
1477 /** The expected sanitised output (Utf-8). */
1478 const char *pcszOutExpected;
1479 } aTest[] =
1480 {
1481 { "OS/2 2.1", "OS_2 2.1" },
1482 { "-!My VM!-", "__My VM_-" },
1483 { "\xF0\x90\x8C\xB0", "____" },
1484 { " My VM ", "__My VM__" },
1485 { ".My VM.", "_My VM_" },
1486 { "My VM", "My VM" }
1487 };
1488 for (unsigned i = 0; i < RT_ELEMENTS(aTest); ++i)
1489 {
1490 Utf8Str str(aTest[i].pcszIn);
1491 sanitiseMachineFilename(str);
1492 if (str.compare(aTest[i].pcszOutExpected))
1493 {
1494 ++cErrors;
1495 pfnPrintf("%s: line %d, expected %s, actual %s\n",
1496 __PRETTY_FUNCTION__, i, aTest[i].pcszOutExpected,
1497 str.c_str());
1498 }
1499 }
1500 return cErrors;
1501}
1502
1503/** @todo Proper testcase. */
1504/** @todo Do we have a better method of doing init functions? */
1505namespace
1506{
1507 class TestSanitiseMachineFilename
1508 {
1509 public:
1510 TestSanitiseMachineFilename(void)
1511 {
1512 Assert(!testSanitiseMachineFilename(RTAssertMsg2));
1513 }
1514 };
1515 TestSanitiseMachineFilename s_TestSanitiseMachineFilename;
1516}
1517#endif
1518
1519/** @note Locks mSystemProperties object for reading. */
1520STDMETHODIMP VirtualBox::CreateMachine(IN_BSTR aSettingsFile,
1521 IN_BSTR aName,
1522 ComSafeArrayIn(IN_BSTR, aGroups),
1523 IN_BSTR aOsTypeId,
1524 IN_BSTR aId,
1525 BOOL forceOverwrite,
1526 IMachine **aMachine)
1527{
1528 LogFlowThisFuncEnter();
1529 LogFlowThisFunc(("aSettingsFile=\"%ls\", aName=\"%ls\", aOsTypeId =\"%ls\"\n", aSettingsFile, aName, aOsTypeId));
1530
1531 CheckComArgStrNotEmptyOrNull(aName);
1532 /** @todo tighten checks on aId? */
1533 CheckComArgOutPointerValid(aMachine);
1534
1535 AutoCaller autoCaller(this);
1536 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1537
1538 StringsList llGroups;
1539 HRESULT rc = convertMachineGroups(ComSafeArrayInArg(aGroups), &llGroups);
1540 if (FAILED(rc))
1541 return rc;
1542
1543 /* NULL settings file means compose automatically */
1544 Bstr bstrSettingsFile(aSettingsFile);
1545 if (bstrSettingsFile.isEmpty())
1546 {
1547 rc = ComposeMachineFilename(aName,
1548 Bstr(llGroups.front()).raw(),
1549 NULL /* aBaseFolder */,
1550 bstrSettingsFile.asOutParam());
1551 if (FAILED(rc)) return rc;
1552 }
1553
1554 /* create a new object */
1555 ComObjPtr<Machine> machine;
1556 rc = machine.createObject();
1557 if (FAILED(rc)) return rc;
1558
1559 /* Create UUID if an empty one was specified. */
1560 Guid id(aId);
1561 if (id.isEmpty())
1562 id.create();
1563
1564 GuestOSType *osType = NULL;
1565 rc = findGuestOSType(Bstr(aOsTypeId), osType);
1566 if (FAILED(rc)) return rc;
1567
1568 /* initialize the machine object */
1569 rc = machine->init(this,
1570 Utf8Str(bstrSettingsFile),
1571 Utf8Str(aName),
1572 llGroups,
1573 osType,
1574 id,
1575 !!forceOverwrite);
1576 if (SUCCEEDED(rc))
1577 {
1578 /* set the return value */
1579 rc = machine.queryInterfaceTo(aMachine);
1580 AssertComRC(rc);
1581
1582#ifdef VBOX_WITH_EXTPACK
1583 /* call the extension pack hooks */
1584 m->ptrExtPackManager->callAllVmCreatedHooks(machine);
1585#endif
1586 }
1587
1588 LogFlowThisFuncLeave();
1589
1590 return rc;
1591}
1592
1593STDMETHODIMP VirtualBox::OpenMachine(IN_BSTR aSettingsFile,
1594 IMachine **aMachine)
1595{
1596 CheckComArgStrNotEmptyOrNull(aSettingsFile);
1597 CheckComArgOutPointerValid(aMachine);
1598
1599 AutoCaller autoCaller(this);
1600 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1601
1602 HRESULT rc = E_FAIL;
1603
1604 /* create a new object */
1605 ComObjPtr<Machine> machine;
1606 rc = machine.createObject();
1607 if (SUCCEEDED(rc))
1608 {
1609 /* initialize the machine object */
1610 rc = machine->init(this,
1611 aSettingsFile,
1612 NULL); /* const Guid *aId */
1613 if (SUCCEEDED(rc))
1614 {
1615 /* set the return value */
1616 rc = machine.queryInterfaceTo(aMachine);
1617 ComAssertComRC(rc);
1618 }
1619 }
1620
1621 return rc;
1622}
1623
1624/** @note Locks objects! */
1625STDMETHODIMP VirtualBox::RegisterMachine(IMachine *aMachine)
1626{
1627 CheckComArgNotNull(aMachine);
1628
1629 AutoCaller autoCaller(this);
1630 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1631
1632 HRESULT rc;
1633
1634 Bstr name;
1635 rc = aMachine->COMGETTER(Name)(name.asOutParam());
1636 if (FAILED(rc)) return rc;
1637
1638 /* We can safely cast child to Machine * here because only Machine
1639 * implementations of IMachine can be among our children. */
1640 Machine *pMachine = static_cast<Machine*>(aMachine);
1641
1642 AutoCaller machCaller(pMachine);
1643 ComAssertComRCRetRC(machCaller.rc());
1644
1645 rc = registerMachine(pMachine);
1646 /* fire an event */
1647 if (SUCCEEDED(rc))
1648 onMachineRegistered(pMachine->getId(), TRUE);
1649
1650 return rc;
1651}
1652
1653/** @note Locks this object for reading, then some machine objects for reading. */
1654STDMETHODIMP VirtualBox::FindMachine(IN_BSTR aNameOrId, IMachine **aMachine)
1655{
1656 LogFlowThisFuncEnter();
1657 LogFlowThisFunc(("aName=\"%ls\", aMachine={%p}\n", aNameOrId, aMachine));
1658
1659 CheckComArgStrNotEmptyOrNull(aNameOrId);
1660 CheckComArgOutPointerValid(aMachine);
1661
1662 AutoCaller autoCaller(this);
1663 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1664
1665 /* start with not found */
1666 HRESULT rc = S_OK;
1667 ComObjPtr<Machine> pMachineFound;
1668
1669 Guid id(aNameOrId);
1670 if (!id.isEmpty())
1671 rc = findMachine(id,
1672 true /* fPermitInaccessible */,
1673 true /* setError */,
1674 &pMachineFound);
1675 // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
1676 else
1677 {
1678 Utf8Str strName(aNameOrId);
1679 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1680 for (MachinesOList::iterator it = m->allMachines.begin();
1681 it != m->allMachines.end();
1682 ++it)
1683 {
1684 ComObjPtr<Machine> &pMachine2 = *it;
1685 AutoCaller machCaller(pMachine2);
1686 if (machCaller.rc())
1687 continue; // we can't ask inaccessible machines for their names
1688
1689 AutoReadLock machLock(pMachine2 COMMA_LOCKVAL_SRC_POS);
1690 if (pMachine2->getName() == strName)
1691 {
1692 pMachineFound = pMachine2;
1693 break;
1694 }
1695 if (!RTPathCompare(pMachine2->getSettingsFileFull().c_str(), strName.c_str()))
1696 {
1697 pMachineFound = pMachine2;
1698 break;
1699 }
1700 }
1701
1702 if (!pMachineFound)
1703 rc = setError(VBOX_E_OBJECT_NOT_FOUND,
1704 tr("Could not find a registered machine named '%ls'"), aNameOrId);
1705 }
1706
1707 /* this will set (*machine) to NULL if machineObj is null */
1708 pMachineFound.queryInterfaceTo(aMachine);
1709
1710 LogFlowThisFunc(("aName=\"%ls\", aMachine=%p, rc=%08X\n", aNameOrId, *aMachine, rc));
1711 LogFlowThisFuncLeave();
1712
1713 return rc;
1714}
1715
1716STDMETHODIMP VirtualBox::GetMachineStates(ComSafeArrayIn(IMachine *, aMachines), ComSafeArrayOut(MachineState_T, aStates))
1717{
1718 CheckComArgSafeArrayNotNull(aMachines);
1719 CheckComArgOutSafeArrayPointerValid(aStates);
1720
1721 com::SafeIfaceArray<IMachine> saMachines(ComSafeArrayInArg(aMachines));
1722 com::SafeArray<MachineState_T> saStates(saMachines.size());
1723 for (size_t i = 0; i < saMachines.size(); i++)
1724 {
1725 ComPtr<IMachine> pMachine = saMachines[i];
1726 MachineState_T state = MachineState_Null;
1727 if (!pMachine.isNull())
1728 {
1729 HRESULT rc = pMachine->COMGETTER(State)(&state);
1730 if (rc == E_ACCESSDENIED)
1731 rc = S_OK;
1732 AssertComRC(rc);
1733 }
1734 saStates[i] = state;
1735 }
1736 saStates.detachTo(ComSafeArrayOutArg(aStates));
1737
1738 return S_OK;
1739}
1740
1741STDMETHODIMP VirtualBox::CreateHardDisk(IN_BSTR aFormat,
1742 IN_BSTR aLocation,
1743 IMedium **aHardDisk)
1744{
1745 CheckComArgOutPointerValid(aHardDisk);
1746
1747 AutoCaller autoCaller(this);
1748 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1749
1750 /* we don't access non-const data members so no need to lock */
1751
1752 Utf8Str format(aFormat);
1753 if (format.isEmpty())
1754 getDefaultHardDiskFormat(format);
1755
1756 ComObjPtr<Medium> hardDisk;
1757 hardDisk.createObject();
1758 HRESULT rc = hardDisk->init(this,
1759 format,
1760 aLocation,
1761 Guid::Empty /* media registry: none yet */);
1762
1763 if (SUCCEEDED(rc))
1764 hardDisk.queryInterfaceTo(aHardDisk);
1765
1766 return rc;
1767}
1768
1769STDMETHODIMP VirtualBox::OpenMedium(IN_BSTR aLocation,
1770 DeviceType_T deviceType,
1771 AccessMode_T accessMode,
1772 BOOL fForceNewUuid,
1773 IMedium **aMedium)
1774{
1775 HRESULT rc = S_OK;
1776 CheckComArgStrNotEmptyOrNull(aLocation);
1777 CheckComArgOutPointerValid(aMedium);
1778
1779 AutoCaller autoCaller(this);
1780 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1781
1782 ComObjPtr<Medium> pMedium;
1783
1784 // have to get write lock as the whole find/update sequence must be done
1785 // in one critical section, otherwise there are races which can lead to
1786 // multiple Medium objects with the same content
1787 AutoWriteLock treeLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1788
1789 // check if the device type is correct, and see if a medium for the
1790 // given path has already initialized; if so, return that
1791 switch (deviceType)
1792 {
1793 case DeviceType_HardDisk:
1794 rc = findHardDiskByLocation(aLocation,
1795 false, /* aSetError */
1796 &pMedium);
1797 break;
1798
1799 case DeviceType_Floppy:
1800 case DeviceType_DVD:
1801 rc = findDVDOrFloppyImage(deviceType,
1802 NULL, /* guid */
1803 aLocation,
1804 false, /* aSetError */
1805 &pMedium);
1806
1807 // enforce read-only for DVDs even if caller specified ReadWrite
1808 if (deviceType == DeviceType_DVD)
1809 accessMode = AccessMode_ReadOnly;
1810 break;
1811
1812 default:
1813 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy %d", deviceType);
1814 }
1815
1816
1817 if (pMedium.isNull())
1818 {
1819 pMedium.createObject();
1820 treeLock.release();
1821 rc = pMedium->init(this,
1822 aLocation,
1823 (accessMode == AccessMode_ReadWrite) ? Medium::OpenReadWrite : Medium::OpenReadOnly,
1824 !!fForceNewUuid,
1825 deviceType);
1826 treeLock.acquire();
1827
1828 if (SUCCEEDED(rc))
1829 {
1830 rc = registerMedium(pMedium, &pMedium, deviceType);
1831
1832 treeLock.release();
1833
1834 /* Note that it's important to call uninit() on failure to register
1835 * because the differencing hard disk would have been already associated
1836 * with the parent and this association needs to be broken. */
1837
1838 if (FAILED(rc))
1839 {
1840 pMedium->uninit();
1841 rc = VBOX_E_OBJECT_NOT_FOUND;
1842 }
1843 }
1844 else
1845 rc = VBOX_E_OBJECT_NOT_FOUND;
1846 }
1847
1848 if (SUCCEEDED(rc))
1849 pMedium.queryInterfaceTo(aMedium);
1850
1851 return rc;
1852}
1853
1854
1855/** @note Locks this object for reading. */
1856STDMETHODIMP VirtualBox::GetGuestOSType(IN_BSTR aId, IGuestOSType **aType)
1857{
1858 CheckComArgNotNull(aType);
1859
1860 AutoCaller autoCaller(this);
1861 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1862
1863 *aType = NULL;
1864
1865 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1866 for (GuestOSTypesOList::iterator it = m->allGuestOSTypes.begin();
1867 it != m->allGuestOSTypes.end();
1868 ++it)
1869 {
1870 const Bstr &typeId = (*it)->id();
1871 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
1872 if (typeId.compare(aId, Bstr::CaseInsensitive) == 0)
1873 {
1874 (*it).queryInterfaceTo(aType);
1875 break;
1876 }
1877 }
1878
1879 return (*aType) ? S_OK :
1880 setError(E_INVALIDARG,
1881 tr("'%ls' is not a valid Guest OS type"),
1882 aId);
1883}
1884
1885STDMETHODIMP VirtualBox::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath,
1886 BOOL /* aWritable */, BOOL /* aAutoMount */)
1887{
1888 CheckComArgStrNotEmptyOrNull(aName);
1889 CheckComArgStrNotEmptyOrNull(aHostPath);
1890
1891 AutoCaller autoCaller(this);
1892 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1893
1894 return setError(E_NOTIMPL, "Not yet implemented");
1895}
1896
1897STDMETHODIMP VirtualBox::RemoveSharedFolder(IN_BSTR aName)
1898{
1899 CheckComArgStrNotEmptyOrNull(aName);
1900
1901 AutoCaller autoCaller(this);
1902 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1903
1904 return setError(E_NOTIMPL, "Not yet implemented");
1905}
1906
1907/**
1908 * @note Locks this object for reading.
1909 */
1910STDMETHODIMP VirtualBox::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
1911{
1912 using namespace settings;
1913
1914 CheckComArgOutSafeArrayPointerValid(aKeys);
1915
1916 AutoCaller autoCaller(this);
1917 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1918
1919 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1920
1921 com::SafeArray<BSTR> saKeys(m->pMainConfigFile->mapExtraDataItems.size());
1922 int i = 0;
1923 for (StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.begin();
1924 it != m->pMainConfigFile->mapExtraDataItems.end();
1925 ++it, ++i)
1926 {
1927 const Utf8Str &strName = it->first; // the key
1928 strName.cloneTo(&saKeys[i]);
1929 }
1930 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
1931
1932 return S_OK;
1933}
1934
1935/**
1936 * @note Locks this object for reading.
1937 */
1938STDMETHODIMP VirtualBox::GetExtraData(IN_BSTR aKey,
1939 BSTR *aValue)
1940{
1941 CheckComArgStrNotEmptyOrNull(aKey);
1942 CheckComArgNotNull(aValue);
1943
1944 AutoCaller autoCaller(this);
1945 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1946
1947 /* start with nothing found */
1948 Utf8Str strKey(aKey);
1949 Bstr bstrResult;
1950
1951 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1952 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1953 // found:
1954 bstrResult = it->second; // source is a Utf8Str
1955
1956 /* return the result to caller (may be empty) */
1957 bstrResult.cloneTo(aValue);
1958
1959 return S_OK;
1960}
1961
1962/**
1963 * @note Locks this object for writing.
1964 */
1965STDMETHODIMP VirtualBox::SetExtraData(IN_BSTR aKey,
1966 IN_BSTR aValue)
1967{
1968 CheckComArgStrNotEmptyOrNull(aKey);
1969
1970 AutoCaller autoCaller(this);
1971 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1972
1973 Utf8Str strKey(aKey);
1974 Utf8Str strValue(aValue);
1975 Utf8Str strOldValue; // empty
1976
1977 // locking note: we only hold the read lock briefly to look up the old value,
1978 // then release it and call the onExtraCanChange callbacks. There is a small
1979 // chance of a race insofar as the callback might be called twice if two callers
1980 // change the same key at the same time, but that's a much better solution
1981 // than the deadlock we had here before. The actual changing of the extradata
1982 // is then performed under the write lock and race-free.
1983
1984 // look up the old value first; if nothing has changed then we need not do anything
1985 {
1986 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
1987 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1988 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1989 strOldValue = it->second;
1990 }
1991
1992 bool fChanged;
1993 if ((fChanged = (strOldValue != strValue)))
1994 {
1995 // ask for permission from all listeners outside the locks;
1996 // onExtraDataCanChange() only briefly requests the VirtualBox
1997 // lock to copy the list of callbacks to invoke
1998 Bstr error;
1999 Bstr bstrValue(aValue);
2000
2001 if (!onExtraDataCanChange(Guid::Empty, aKey, bstrValue.raw(), error))
2002 {
2003 const char *sep = error.isEmpty() ? "" : ": ";
2004 CBSTR err = error.raw();
2005 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
2006 sep, err));
2007 return setError(E_ACCESSDENIED,
2008 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
2009 aKey,
2010 bstrValue.raw(),
2011 sep,
2012 err);
2013 }
2014
2015 // data is changing and change not vetoed: then write it out under the lock
2016
2017 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2018
2019 if (strValue.isEmpty())
2020 m->pMainConfigFile->mapExtraDataItems.erase(strKey);
2021 else
2022 m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
2023 // creates a new key if needed
2024
2025 /* save settings on success */
2026 HRESULT rc = saveSettings();
2027 if (FAILED(rc)) return rc;
2028 }
2029
2030 // fire notification outside the lock
2031 if (fChanged)
2032 onExtraDataChange(Guid::Empty, aKey, aValue);
2033
2034 return S_OK;
2035}
2036
2037/**
2038 *
2039 */
2040STDMETHODIMP VirtualBox::SetSettingsSecret(IN_BSTR aValue)
2041{
2042 storeSettingsKey(aValue);
2043 decryptSettings();
2044 return S_OK;
2045}
2046
2047void VirtualBox::decryptMediumSettings(Medium *pMedium)
2048{
2049 Bstr bstrCipher;
2050 HRESULT hrc = pMedium->GetProperty(Bstr("InitiatorSecretEncrypted").raw(),
2051 bstrCipher.asOutParam());
2052 if (SUCCEEDED(hrc))
2053 {
2054 Bstr bstrName;
2055 pMedium->COMGETTER(Name)(bstrName.asOutParam());
2056 Utf8Str strPlaintext;
2057 int rc = decryptSetting(&strPlaintext, bstrCipher);
2058 if (RT_SUCCESS(rc))
2059 pMedium->setPropertyDirect("InitiatorSecret", strPlaintext);
2060 }
2061}
2062
2063/**
2064 * Decrypt all encrypted settings.
2065 *
2066 * So far we only have encrypted iSCSI initiator secrets so we just go through
2067 * all hard disk mediums and determine the plain 'InitiatorSecret' from
2068 * 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
2069 * properties need to be null-terminated strings.
2070 */
2071void VirtualBox::decryptSettings()
2072{
2073 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2074 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2075 mt != m->allHardDisks.end();
2076 ++mt)
2077 {
2078 ComObjPtr<Medium> pMedium = *mt;
2079 AutoCaller medCaller(pMedium);
2080 if (FAILED(medCaller.rc()))
2081 continue;
2082 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2083 decryptMediumSettings(pMedium);
2084 }
2085}
2086
2087/**
2088 * Encode.
2089 *
2090 * @param aPlaintext plaintext to be encrypted
2091 * @param aCiphertext resulting ciphertext (base64-encoded)
2092 */
2093int VirtualBox::encryptSetting(const Utf8Str &aPlaintext, Utf8Str *aCiphertext)
2094{
2095 uint8_t abCiphertext[32];
2096 char szCipherBase64[128];
2097 size_t cchCipherBase64;
2098 int rc = encryptSettingBytes((uint8_t*)aPlaintext.c_str(), abCiphertext,
2099 aPlaintext.length()+1, sizeof(abCiphertext));
2100 if (RT_SUCCESS(rc))
2101 {
2102 rc = RTBase64Encode(abCiphertext, sizeof(abCiphertext),
2103 szCipherBase64, sizeof(szCipherBase64),
2104 &cchCipherBase64);
2105 if (RT_SUCCESS(rc))
2106 *aCiphertext = szCipherBase64;
2107 }
2108 return rc;
2109}
2110
2111/**
2112 * Decode.
2113 *
2114 * @param aPlaintext resulting plaintext
2115 * @param aCiphertext ciphertext (base64-encoded) to decrypt
2116 */
2117int VirtualBox::decryptSetting(Utf8Str *aPlaintext, const Utf8Str &aCiphertext)
2118{
2119 uint8_t abPlaintext[64];
2120 uint8_t abCiphertext[64];
2121 size_t cbCiphertext;
2122 int rc = RTBase64Decode(aCiphertext.c_str(),
2123 abCiphertext, sizeof(abCiphertext),
2124 &cbCiphertext, NULL);
2125 if (RT_SUCCESS(rc))
2126 {
2127 rc = decryptSettingBytes(abPlaintext, abCiphertext, cbCiphertext);
2128 if (RT_SUCCESS(rc))
2129 {
2130 /* check if this is really a Null-terminated string. */
2131 for (unsigned i = 0; i < cbCiphertext; i++)
2132 {
2133 if (abPlaintext[i] == '\0')
2134 {
2135 *aPlaintext = Utf8Str((const char*)abPlaintext);
2136 return VINF_SUCCESS;
2137 }
2138 }
2139 rc = VERR_INVALID_PARAMETER;
2140 }
2141 }
2142 return rc;
2143}
2144
2145/**
2146 * Encrypt secret bytes. Use the m->SettingsCipherKey as key.
2147 *
2148 * @param aPlaintext clear text to be encrypted
2149 * @param aCiphertext resulting encrypted text
2150 * @param aPlaintextSize size of the plaintext
2151 * @param aCiphertextSize size of the ciphertext
2152 */
2153int VirtualBox::encryptSettingBytes(const uint8_t *aPlaintext, uint8_t *aCiphertext,
2154 size_t aPlaintextSize, size_t aCiphertextSize) const
2155{
2156 unsigned i, j;
2157 uint8_t aBytes[64];
2158
2159 if (!m->fSettingsCipherKeySet)
2160 return VERR_INVALID_STATE;
2161
2162 if (aCiphertextSize > sizeof(aBytes))
2163 return VERR_BUFFER_OVERFLOW;
2164
2165 for (i = 0, j = 0; i < aPlaintextSize && i < aCiphertextSize; i++)
2166 {
2167 aCiphertext[i] = (aPlaintext[i] ^ m->SettingsCipherKey[j]);
2168 if (++j >= sizeof(m->SettingsCipherKey))
2169 j = 0;
2170 }
2171
2172 /* fill with random data to have a minimal length (salt) */
2173 if (i < aCiphertextSize)
2174 {
2175 RTRandBytes(aBytes, aCiphertextSize - i);
2176 for (; i < aCiphertextSize; i++)
2177 {
2178 aCiphertext[i] = aBytes[i] ^ m->SettingsCipherKey[j];
2179 if (++j >= sizeof(m->SettingsCipherKey))
2180 j = 0;
2181 }
2182 }
2183
2184 return VINF_SUCCESS;
2185}
2186
2187/**
2188 * Decrypt secret bytes. Use the m->SettingsCipherKey as key.
2189 *
2190 * @param aPlaintext resulting plaintext
2191 * @param aCiphertext ciphertext to be decrypted
2192 * @param aCiphertextSize size of the ciphertext == size of the plaintext
2193 */
2194int VirtualBox::decryptSettingBytes(uint8_t *aPlaintext,
2195 const uint8_t *aCiphertext, size_t aCiphertextSize) const
2196{
2197 if (!m->fSettingsCipherKeySet)
2198 return VERR_INVALID_STATE;
2199
2200 for (unsigned i = 0, j = 0; i < aCiphertextSize; i++)
2201 {
2202 aPlaintext[i] = aCiphertext[i] ^ m->SettingsCipherKey[j];
2203 if (++j >= sizeof(m->SettingsCipherKey))
2204 j = 0;
2205 }
2206
2207 return VINF_SUCCESS;
2208}
2209
2210/**
2211 * Store a settings key.
2212 *
2213 * @param aKey the key to store
2214 */
2215void VirtualBox::storeSettingsKey(const Utf8Str &aKey)
2216{
2217 RTSha512(aKey.c_str(), aKey.length(), m->SettingsCipherKey);
2218 m->fSettingsCipherKeySet = true;
2219}
2220
2221// public methods only for internal purposes
2222/////////////////////////////////////////////////////////////////////////////
2223
2224#ifdef DEBUG
2225void VirtualBox::dumpAllBackRefs()
2226{
2227 {
2228 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2229 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2230 mt != m->allHardDisks.end();
2231 ++mt)
2232 {
2233 ComObjPtr<Medium> pMedium = *mt;
2234 pMedium->dumpBackRefs();
2235 }
2236 }
2237 {
2238 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2239 for (MediaList::const_iterator mt = m->allDVDImages.begin();
2240 mt != m->allDVDImages.end();
2241 ++mt)
2242 {
2243 ComObjPtr<Medium> pMedium = *mt;
2244 pMedium->dumpBackRefs();
2245 }
2246 }
2247}
2248#endif
2249
2250/**
2251 * Posts an event to the event queue that is processed asynchronously
2252 * on a dedicated thread.
2253 *
2254 * Posting events to the dedicated event queue is useful to perform secondary
2255 * actions outside any object locks -- for example, to iterate over a list
2256 * of callbacks and inform them about some change caused by some object's
2257 * method call.
2258 *
2259 * @param event event to post; must have been allocated using |new|, will
2260 * be deleted automatically by the event thread after processing
2261 *
2262 * @note Doesn't lock any object.
2263 */
2264HRESULT VirtualBox::postEvent(Event *event)
2265{
2266 AssertReturn(event, E_FAIL);
2267
2268 HRESULT rc;
2269 AutoCaller autoCaller(this);
2270 if (SUCCEEDED((rc = autoCaller.rc())))
2271 {
2272 if (autoCaller.state() != Ready)
2273 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
2274 autoCaller.state()));
2275 // return S_OK
2276 else if ( (m->pAsyncEventQ)
2277 && (m->pAsyncEventQ->postEvent(event))
2278 )
2279 return S_OK;
2280 else
2281 rc = E_FAIL;
2282 }
2283
2284 // in any event of failure, we must clean up here, or we'll leak;
2285 // the caller has allocated the object using new()
2286 delete event;
2287 return rc;
2288}
2289
2290/**
2291 * Adds a progress to the global collection of pending operations.
2292 * Usually gets called upon progress object initialization.
2293 *
2294 * @param aProgress Operation to add to the collection.
2295 *
2296 * @note Doesn't lock objects.
2297 */
2298HRESULT VirtualBox::addProgress(IProgress *aProgress)
2299{
2300 CheckComArgNotNull(aProgress);
2301
2302 AutoCaller autoCaller(this);
2303 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2304
2305 Bstr id;
2306 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
2307 AssertComRCReturnRC(rc);
2308
2309 /* protect mProgressOperations */
2310 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2311
2312 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
2313 return S_OK;
2314}
2315
2316/**
2317 * Removes the progress from the global collection of pending operations.
2318 * Usually gets called upon progress completion.
2319 *
2320 * @param aId UUID of the progress operation to remove
2321 *
2322 * @note Doesn't lock objects.
2323 */
2324HRESULT VirtualBox::removeProgress(IN_GUID aId)
2325{
2326 AutoCaller autoCaller(this);
2327 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2328
2329 ComPtr<IProgress> progress;
2330
2331 /* protect mProgressOperations */
2332 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2333
2334 size_t cnt = m->mapProgressOperations.erase(aId);
2335 Assert(cnt == 1);
2336 NOREF(cnt);
2337
2338 return S_OK;
2339}
2340
2341#ifdef RT_OS_WINDOWS
2342
2343struct StartSVCHelperClientData
2344{
2345 ComObjPtr<VirtualBox> that;
2346 ComObjPtr<Progress> progress;
2347 bool privileged;
2348 VirtualBox::SVCHelperClientFunc func;
2349 void *user;
2350};
2351
2352/**
2353 * Helper method that starts a worker thread that:
2354 * - creates a pipe communication channel using SVCHlpClient;
2355 * - starts an SVC Helper process that will inherit this channel;
2356 * - executes the supplied function by passing it the created SVCHlpClient
2357 * and opened instance to communicate to the Helper process and the given
2358 * Progress object.
2359 *
2360 * The user function is supposed to communicate to the helper process
2361 * using the \a aClient argument to do the requested job and optionally expose
2362 * the progress through the \a aProgress object. The user function should never
2363 * call notifyComplete() on it: this will be done automatically using the
2364 * result code returned by the function.
2365 *
2366 * Before the user function is started, the communication channel passed to
2367 * the \a aClient argument is fully set up, the function should start using
2368 * its write() and read() methods directly.
2369 *
2370 * The \a aVrc parameter of the user function may be used to return an error
2371 * code if it is related to communication errors (for example, returned by
2372 * the SVCHlpClient members when they fail). In this case, the correct error
2373 * message using this value will be reported to the caller. Note that the
2374 * value of \a aVrc is inspected only if the user function itself returns
2375 * success.
2376 *
2377 * If a failure happens anywhere before the user function would be normally
2378 * called, it will be called anyway in special "cleanup only" mode indicated
2379 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
2380 * all the function is supposed to do is to cleanup its aUser argument if
2381 * necessary (it's assumed that the ownership of this argument is passed to
2382 * the user function once #startSVCHelperClient() returns a success, thus
2383 * making it responsible for the cleanup).
2384 *
2385 * After the user function returns, the thread will send the SVCHlpMsg::Null
2386 * message to indicate a process termination.
2387 *
2388 * @param aPrivileged |true| to start the SVC Helper process as a privileged
2389 * user that can perform administrative tasks
2390 * @param aFunc user function to run
2391 * @param aUser argument to the user function
2392 * @param aProgress progress object that will track operation completion
2393 *
2394 * @note aPrivileged is currently ignored (due to some unsolved problems in
2395 * Vista) and the process will be started as a normal (unprivileged)
2396 * process.
2397 *
2398 * @note Doesn't lock anything.
2399 */
2400HRESULT VirtualBox::startSVCHelperClient(bool aPrivileged,
2401 SVCHelperClientFunc aFunc,
2402 void *aUser, Progress *aProgress)
2403{
2404 AssertReturn(aFunc, E_POINTER);
2405 AssertReturn(aProgress, E_POINTER);
2406
2407 AutoCaller autoCaller(this);
2408 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2409
2410 /* create the SVCHelperClientThread() argument */
2411 std::auto_ptr <StartSVCHelperClientData>
2412 d(new StartSVCHelperClientData());
2413 AssertReturn(d.get(), E_OUTOFMEMORY);
2414
2415 d->that = this;
2416 d->progress = aProgress;
2417 d->privileged = aPrivileged;
2418 d->func = aFunc;
2419 d->user = aUser;
2420
2421 RTTHREAD tid = NIL_RTTHREAD;
2422 int vrc = RTThreadCreate(&tid, SVCHelperClientThread,
2423 static_cast <void *>(d.get()),
2424 0, RTTHREADTYPE_MAIN_WORKER,
2425 RTTHREADFLAGS_WAITABLE, "SVCHelper");
2426 if (RT_FAILURE(vrc))
2427 return setError(E_FAIL, "Could not create SVCHelper thread (%Rrc)", vrc);
2428
2429 /* d is now owned by SVCHelperClientThread(), so release it */
2430 d.release();
2431
2432 return S_OK;
2433}
2434
2435/**
2436 * Worker thread for startSVCHelperClient().
2437 */
2438/* static */
2439DECLCALLBACK(int)
2440VirtualBox::SVCHelperClientThread(RTTHREAD aThread, void *aUser)
2441{
2442 LogFlowFuncEnter();
2443
2444 std::auto_ptr<StartSVCHelperClientData>
2445 d(static_cast<StartSVCHelperClientData*>(aUser));
2446
2447 HRESULT rc = S_OK;
2448 bool userFuncCalled = false;
2449
2450 do
2451 {
2452 AssertBreakStmt(d.get(), rc = E_POINTER);
2453 AssertReturn(!d->progress.isNull(), E_POINTER);
2454
2455 /* protect VirtualBox from uninitialization */
2456 AutoCaller autoCaller(d->that);
2457 if (!autoCaller.isOk())
2458 {
2459 /* it's too late */
2460 rc = autoCaller.rc();
2461 break;
2462 }
2463
2464 int vrc = VINF_SUCCESS;
2465
2466 Guid id;
2467 id.create();
2468 SVCHlpClient client;
2469 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2470 id.raw()).c_str());
2471 if (RT_FAILURE(vrc))
2472 {
2473 rc = d->that->setError(E_FAIL,
2474 tr("Could not create the communication channel (%Rrc)"), vrc);
2475 break;
2476 }
2477
2478 /* get the path to the executable */
2479 char exePathBuf[RTPATH_MAX];
2480 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2481 if (!exePath)
2482 {
2483 rc = d->that->setError(E_FAIL, tr("Cannot get executable name"));
2484 break;
2485 }
2486
2487 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2488
2489 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2490
2491 RTPROCESS pid = NIL_RTPROCESS;
2492
2493 if (d->privileged)
2494 {
2495 /* Attempt to start a privileged process using the Run As dialog */
2496
2497 Bstr file = exePath;
2498 Bstr parameters = argsStr;
2499
2500 SHELLEXECUTEINFO shExecInfo;
2501
2502 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2503
2504 shExecInfo.fMask = NULL;
2505 shExecInfo.hwnd = NULL;
2506 shExecInfo.lpVerb = L"runas";
2507 shExecInfo.lpFile = file.raw();
2508 shExecInfo.lpParameters = parameters.raw();
2509 shExecInfo.lpDirectory = NULL;
2510 shExecInfo.nShow = SW_NORMAL;
2511 shExecInfo.hInstApp = NULL;
2512
2513 if (!ShellExecuteEx(&shExecInfo))
2514 {
2515 int vrc2 = RTErrConvertFromWin32(GetLastError());
2516 /* hide excessive details in case of a frequent error
2517 * (pressing the Cancel button to close the Run As dialog) */
2518 if (vrc2 == VERR_CANCELLED)
2519 rc = d->that->setError(E_FAIL,
2520 tr("Operation canceled by the user"));
2521 else
2522 rc = d->that->setError(E_FAIL,
2523 tr("Could not launch a privileged process '%s' (%Rrc)"),
2524 exePath, vrc2);
2525 break;
2526 }
2527 }
2528 else
2529 {
2530 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2531 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2532 if (RT_FAILURE(vrc))
2533 {
2534 rc = d->that->setError(E_FAIL,
2535 tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2536 break;
2537 }
2538 }
2539
2540 /* wait for the client to connect */
2541 vrc = client.connect();
2542 if (RT_SUCCESS(vrc))
2543 {
2544 /* start the user supplied function */
2545 rc = d->func(&client, d->progress, d->user, &vrc);
2546 userFuncCalled = true;
2547 }
2548
2549 /* send the termination signal to the process anyway */
2550 {
2551 int vrc2 = client.write(SVCHlpMsg::Null);
2552 if (RT_SUCCESS(vrc))
2553 vrc = vrc2;
2554 }
2555
2556 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2557 {
2558 rc = d->that->setError(E_FAIL,
2559 tr("Could not operate the communication channel (%Rrc)"), vrc);
2560 break;
2561 }
2562 }
2563 while (0);
2564
2565 if (FAILED(rc) && !userFuncCalled)
2566 {
2567 /* call the user function in the "cleanup only" mode
2568 * to let it free resources passed to in aUser */
2569 d->func(NULL, NULL, d->user, NULL);
2570 }
2571
2572 d->progress->notifyComplete(rc);
2573
2574 LogFlowFuncLeave();
2575 return 0;
2576}
2577
2578#endif /* RT_OS_WINDOWS */
2579
2580/**
2581 * Sends a signal to the client watcher thread to rescan the set of machines
2582 * that have open sessions.
2583 *
2584 * @note Doesn't lock anything.
2585 */
2586void VirtualBox::updateClientWatcher()
2587{
2588 AutoCaller autoCaller(this);
2589 AssertComRCReturnVoid(autoCaller.rc());
2590
2591 AssertReturnVoid(m->threadClientWatcher != NIL_RTTHREAD);
2592
2593 /* sent an update request */
2594#if defined(RT_OS_WINDOWS)
2595 ::SetEvent(m->updateReq);
2596#elif defined(RT_OS_OS2)
2597 RTSemEventSignal(m->updateReq);
2598#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
2599 RTSemEventSignal(m->updateReq);
2600#else
2601# error "Port me!"
2602#endif
2603}
2604
2605/**
2606 * Adds the given child process ID to the list of processes to be reaped.
2607 * This call should be followed by #updateClientWatcher() to take the effect.
2608 */
2609void VirtualBox::addProcessToReap(RTPROCESS pid)
2610{
2611 AutoCaller autoCaller(this);
2612 AssertComRCReturnVoid(autoCaller.rc());
2613
2614 /// @todo (dmik) Win32?
2615#ifndef RT_OS_WINDOWS
2616 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2617 m->llProcesses.push_back(pid);
2618#endif
2619}
2620
2621/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2622struct MachineEvent : public VirtualBox::CallbackEvent
2623{
2624 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
2625 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2626 , mBool(aBool)
2627 { }
2628
2629 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
2630 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2631 , mState(aState)
2632 {}
2633
2634 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2635 {
2636 switch (mWhat)
2637 {
2638 case VBoxEventType_OnMachineDataChanged:
2639 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2640 break;
2641
2642 case VBoxEventType_OnMachineStateChanged:
2643 aEvDesc.init(aSource, mWhat, id.raw(), mState);
2644 break;
2645
2646 case VBoxEventType_OnMachineRegistered:
2647 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2648 break;
2649
2650 default:
2651 AssertFailedReturn(S_OK);
2652 }
2653 return S_OK;
2654 }
2655
2656 Bstr id;
2657 MachineState_T mState;
2658 BOOL mBool;
2659};
2660
2661/**
2662 * @note Doesn't lock any object.
2663 */
2664void VirtualBox::onMachineStateChange(const Guid &aId, MachineState_T aState)
2665{
2666 postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
2667}
2668
2669/**
2670 * @note Doesn't lock any object.
2671 */
2672void VirtualBox::onMachineDataChange(const Guid &aId, BOOL aTemporary)
2673{
2674 postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
2675}
2676
2677/**
2678 * @note Locks this object for reading.
2679 */
2680BOOL VirtualBox::onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
2681 Bstr &aError)
2682{
2683 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
2684 aId.toString().c_str(), aKey, aValue));
2685
2686 AutoCaller autoCaller(this);
2687 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2688
2689 BOOL allowChange = TRUE;
2690 Bstr id = aId.toUtf16();
2691
2692 VBoxEventDesc evDesc;
2693 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
2694 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
2695 //Assert(fDelivered);
2696 if (fDelivered)
2697 {
2698 ComPtr<IEvent> aEvent;
2699 evDesc.getEvent(aEvent.asOutParam());
2700 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
2701 Assert(aCanChangeEvent);
2702 BOOL fVetoed = FALSE;
2703 aCanChangeEvent->IsVetoed(&fVetoed);
2704 allowChange = !fVetoed;
2705
2706 if (!allowChange)
2707 {
2708 SafeArray<BSTR> aVetos;
2709 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
2710 if (aVetos.size() > 0)
2711 aError = aVetos[0];
2712 }
2713 }
2714 else
2715 allowChange = TRUE;
2716
2717 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
2718 return allowChange;
2719}
2720
2721/** Event for onExtraDataChange() */
2722struct ExtraDataEvent : public VirtualBox::CallbackEvent
2723{
2724 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
2725 IN_BSTR aKey, IN_BSTR aVal)
2726 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
2727 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
2728 {}
2729
2730 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2731 {
2732 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
2733 }
2734
2735 Bstr machineId, key, val;
2736};
2737
2738/**
2739 * @note Doesn't lock any object.
2740 */
2741void VirtualBox::onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
2742{
2743 postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
2744}
2745
2746/**
2747 * @note Doesn't lock any object.
2748 */
2749void VirtualBox::onMachineRegistered(const Guid &aId, BOOL aRegistered)
2750{
2751 postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
2752}
2753
2754/** Event for onSessionStateChange() */
2755struct SessionEvent : public VirtualBox::CallbackEvent
2756{
2757 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2758 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
2759 , machineId(aMachineId.toUtf16()), sessionState(aState)
2760 {}
2761
2762 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2763 {
2764 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
2765 }
2766 Bstr machineId;
2767 SessionState_T sessionState;
2768};
2769
2770/**
2771 * @note Doesn't lock any object.
2772 */
2773void VirtualBox::onSessionStateChange(const Guid &aId, SessionState_T aState)
2774{
2775 postEvent(new SessionEvent(this, aId, aState));
2776}
2777
2778/** Event for onSnapshotTaken(), onSnapshotDeleted() and onSnapshotChange() */
2779struct SnapshotEvent : public VirtualBox::CallbackEvent
2780{
2781 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2782 VBoxEventType_T aWhat)
2783 : CallbackEvent(aVB, aWhat)
2784 , machineId(aMachineId), snapshotId(aSnapshotId)
2785 {}
2786
2787 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2788 {
2789 return aEvDesc.init(aSource, VBoxEventType_OnSnapshotTaken,
2790 machineId.toUtf16().raw(), snapshotId.toUtf16().raw());
2791 }
2792
2793 Guid machineId;
2794 Guid snapshotId;
2795};
2796
2797/**
2798 * @note Doesn't lock any object.
2799 */
2800void VirtualBox::onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
2801{
2802 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2803 VBoxEventType_OnSnapshotTaken));
2804}
2805
2806/**
2807 * @note Doesn't lock any object.
2808 */
2809void VirtualBox::onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
2810{
2811 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2812 VBoxEventType_OnSnapshotDeleted));
2813}
2814
2815/**
2816 * @note Doesn't lock any object.
2817 */
2818void VirtualBox::onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
2819{
2820 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2821 VBoxEventType_OnSnapshotChanged));
2822}
2823
2824/** Event for onGuestPropertyChange() */
2825struct GuestPropertyEvent : public VirtualBox::CallbackEvent
2826{
2827 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
2828 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
2829 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
2830 machineId(aMachineId),
2831 name(aName),
2832 value(aValue),
2833 flags(aFlags)
2834 {}
2835
2836 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2837 {
2838 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
2839 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
2840 }
2841
2842 Guid machineId;
2843 Bstr name, value, flags;
2844};
2845
2846/**
2847 * @note Doesn't lock any object.
2848 */
2849void VirtualBox::onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
2850 IN_BSTR aValue, IN_BSTR aFlags)
2851{
2852 postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
2853}
2854
2855/** Event for onMachineUninit(), this is not a CallbackEvent */
2856class MachineUninitEvent : public Event
2857{
2858public:
2859
2860 MachineUninitEvent(VirtualBox *aVirtualBox, Machine *aMachine)
2861 : mVirtualBox(aVirtualBox), mMachine(aMachine)
2862 {
2863 Assert(aVirtualBox);
2864 Assert(aMachine);
2865 }
2866
2867 void *handler()
2868 {
2869#ifdef VBOX_WITH_RESOURCE_USAGE_API
2870 /* Handle unregistering metrics here, as it is not vital to get
2871 * it done immediately. It reduces the number of locks needed and
2872 * the lock contention in SessionMachine::uninit. */
2873 {
2874 AutoWriteLock mLock(mMachine COMMA_LOCKVAL_SRC_POS);
2875 mMachine->unregisterMetrics(mVirtualBox->performanceCollector(), mMachine);
2876 }
2877#endif /* VBOX_WITH_RESOURCE_USAGE_API */
2878
2879 return NULL;
2880 }
2881
2882private:
2883
2884 /**
2885 * Note that this is a weak ref -- the CallbackEvent handler thread
2886 * is bound to the lifetime of the VirtualBox instance, so it's safe.
2887 */
2888 VirtualBox *mVirtualBox;
2889
2890 /** Reference to the machine object. */
2891 ComObjPtr<Machine> mMachine;
2892};
2893
2894/**
2895 * Trigger internal event. This isn't meant to be signalled to clients.
2896 * @note Doesn't lock any object.
2897 */
2898void VirtualBox::onMachineUninit(Machine *aMachine)
2899{
2900 postEvent(new MachineUninitEvent(this, aMachine));
2901}
2902
2903/**
2904 * @note Doesn't lock any object.
2905 */
2906void VirtualBox::onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
2907 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
2908 IN_BSTR aGuestIp, uint16_t aGuestPort)
2909{
2910 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
2911 aHostPort, aGuestIp, aGuestPort);
2912}
2913
2914/**
2915 * @note Locks this object for reading.
2916 */
2917ComObjPtr<GuestOSType> VirtualBox::getUnknownOSType()
2918{
2919 ComObjPtr<GuestOSType> type;
2920 AutoCaller autoCaller(this);
2921 AssertComRCReturn(autoCaller.rc(), type);
2922
2923 /* unknown type must always be the first */
2924 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
2925
2926 return m->allGuestOSTypes.front();
2927}
2928
2929/**
2930 * Returns the list of opened machines (machines having direct sessions opened
2931 * by client processes) and optionally the list of direct session controls.
2932 *
2933 * @param aMachines Where to put opened machines (will be empty if none).
2934 * @param aControls Where to put direct session controls (optional).
2935 *
2936 * @note The returned lists contain smart pointers. So, clear it as soon as
2937 * it becomes no more necessary to release instances.
2938 *
2939 * @note It can be possible that a session machine from the list has been
2940 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
2941 * when accessing unprotected data directly.
2942 *
2943 * @note Locks objects for reading.
2944 */
2945void VirtualBox::getOpenedMachines(SessionMachinesList &aMachines,
2946 InternalControlList *aControls /*= NULL*/)
2947{
2948 AutoCaller autoCaller(this);
2949 AssertComRCReturnVoid(autoCaller.rc());
2950
2951 aMachines.clear();
2952 if (aControls)
2953 aControls->clear();
2954
2955 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2956
2957 for (MachinesOList::iterator it = m->allMachines.begin();
2958 it != m->allMachines.end();
2959 ++it)
2960 {
2961 ComObjPtr<SessionMachine> sm;
2962 ComPtr<IInternalSessionControl> ctl;
2963 if ((*it)->isSessionOpen(sm, &ctl))
2964 {
2965 aMachines.push_back(sm);
2966 if (aControls)
2967 aControls->push_back(ctl);
2968 }
2969 }
2970}
2971
2972/**
2973 * Searches for a machine object with the given ID in the collection
2974 * of registered machines.
2975 *
2976 * @param aId Machine UUID to look for.
2977 * @param aPermitInaccessible If true, inaccessible machines will be found;
2978 * if false, this will fail if the given machine is inaccessible.
2979 * @param aSetError If true, set errorinfo if the machine is not found.
2980 * @param aMachine Returned machine, if found.
2981 * @return
2982 */
2983HRESULT VirtualBox::findMachine(const Guid &aId,
2984 bool fPermitInaccessible,
2985 bool aSetError,
2986 ComObjPtr<Machine> *aMachine /* = NULL */)
2987{
2988 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
2989
2990 AutoCaller autoCaller(this);
2991 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2992
2993 {
2994 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2995
2996 for (MachinesOList::iterator it = m->allMachines.begin();
2997 it != m->allMachines.end();
2998 ++it)
2999 {
3000 ComObjPtr<Machine> pMachine2 = *it;
3001
3002 if (!fPermitInaccessible)
3003 {
3004 // skip inaccessible machines
3005 AutoCaller machCaller(pMachine2);
3006 if (FAILED(machCaller.rc()))
3007 continue;
3008 }
3009
3010 if (pMachine2->getId() == aId)
3011 {
3012 rc = S_OK;
3013 if (aMachine)
3014 *aMachine = pMachine2;
3015 break;
3016 }
3017 }
3018 }
3019
3020 if (aSetError && FAILED(rc))
3021 rc = setError(rc,
3022 tr("Could not find a registered machine with UUID {%RTuuid}"),
3023 aId.raw());
3024
3025 return rc;
3026}
3027
3028static HRESULT validateMachineGroupHelper(const Utf8Str &aGroup)
3029{
3030 /* empty strings are invalid */
3031 if (aGroup.isEmpty())
3032 return E_INVALIDARG;
3033 /* the toplevel group is valid */
3034 if (aGroup == "/")
3035 return S_OK;
3036 /* any other strings of length 1 are invalid */
3037 if (aGroup.length() == 1)
3038 return E_INVALIDARG;
3039 /* must start with a slash */
3040 if (aGroup.c_str()[0] != '/')
3041 return E_INVALIDARG;
3042 /* must not end with a slash */
3043 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3044 return E_INVALIDARG;
3045 /* check the group components */
3046 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3047 while (pStr)
3048 {
3049 char *pSlash = RTStrStr(pStr, "/");
3050 if (pSlash)
3051 {
3052 /* no empty components (or // sequences in other words) */
3053 if (pSlash == pStr)
3054 return E_INVALIDARG;
3055 /* check if the machine name rules are violated, because that means
3056 * the group components is too close to the limits. */
3057 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3058 Utf8Str tmp2(tmp);
3059 sanitiseMachineFilename(tmp);
3060 if (tmp != tmp2)
3061 return E_INVALIDARG;
3062 pStr = pSlash + 1;
3063 }
3064 else
3065 {
3066 /* check if the machine name rules are violated, because that means
3067 * the group components is too close to the limits. */
3068 Utf8Str tmp(pStr);
3069 Utf8Str tmp2(tmp);
3070 sanitiseMachineFilename(tmp);
3071 if (tmp != tmp2)
3072 return E_INVALIDARG;
3073 pStr = NULL;
3074 }
3075 }
3076 return S_OK;
3077}
3078
3079/**
3080 * Validates a machine group.
3081 *
3082 * @param aMachineGroup Machine group.
3083 *
3084 * @return S_OK or E_INVALIDARG
3085 */
3086HRESULT VirtualBox::validateMachineGroup(const Utf8Str &aGroup)
3087{
3088 HRESULT rc = validateMachineGroupHelper(aGroup);
3089 if (FAILED(rc))
3090 rc = setError(rc,
3091 tr("Invalid machine group '%s'"),
3092 aGroup.c_str());
3093 return rc;
3094}
3095
3096/**
3097 * Takes a list of machine groups, and sanitizes/validates it.
3098 *
3099 * @param aMachineGroups Safearray with the machine groups.
3100 * @param pllMachineGroups Pointer to list of strings for the result.
3101 *
3102 * @return S_OK or E_INVALIDARG
3103 */
3104HRESULT VirtualBox::convertMachineGroups(ComSafeArrayIn(IN_BSTR, aMachineGroups), StringsList *pllMachineGroups)
3105{
3106 pllMachineGroups->clear();
3107 if (aMachineGroups)
3108 {
3109 com::SafeArray<IN_BSTR> machineGroups(ComSafeArrayInArg(aMachineGroups));
3110 for (size_t i = 0; i < machineGroups.size(); i++)
3111 {
3112 Utf8Str group(machineGroups[i]);
3113 if (group.length() == 0)
3114 group = "/";
3115
3116 HRESULT rc = validateMachineGroup(group);
3117 if (FAILED(rc))
3118 return rc;
3119
3120 /* no duplicates please */
3121 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3122 == pllMachineGroups->end())
3123 pllMachineGroups->push_back(group);
3124 }
3125 if (pllMachineGroups->size() == 0)
3126 pllMachineGroups->push_back("/");
3127 }
3128 else
3129 pllMachineGroups->push_back("/");
3130
3131 return S_OK;
3132}
3133
3134/**
3135 * Searches for a Medium object with the given ID in the list of registered
3136 * hard disks.
3137 *
3138 * @param aId ID of the hard disk. Must not be empty.
3139 * @param aSetError If @c true , the appropriate error info is set in case
3140 * when the hard disk is not found.
3141 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3142 *
3143 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3144 *
3145 * @note Locks the media tree for reading.
3146 */
3147HRESULT VirtualBox::findHardDiskById(const Guid &id,
3148 bool aSetError,
3149 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3150{
3151 AssertReturn(!id.isEmpty(), E_INVALIDARG);
3152
3153 // we use the hard disks map, but it is protected by the
3154 // hard disk _list_ lock handle
3155 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3156
3157 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
3158 if (it != m->mapHardDisks.end())
3159 {
3160 if (aHardDisk)
3161 *aHardDisk = (*it).second;
3162 return S_OK;
3163 }
3164
3165 if (aSetError)
3166 return setError(VBOX_E_OBJECT_NOT_FOUND,
3167 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3168 id.raw());
3169
3170 return VBOX_E_OBJECT_NOT_FOUND;
3171}
3172
3173/**
3174 * Searches for a Medium object with the given ID or location in the list of
3175 * registered hard disks. If both ID and location are specified, the first
3176 * object that matches either of them (not necessarily both) is returned.
3177 *
3178 * @param aLocation Full location specification. Must not be empty.
3179 * @param aSetError If @c true , the appropriate error info is set in case
3180 * when the hard disk is not found.
3181 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3182 *
3183 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3184 *
3185 * @note Locks the media tree for reading.
3186 */
3187HRESULT VirtualBox::findHardDiskByLocation(const Utf8Str &strLocation,
3188 bool aSetError,
3189 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3190{
3191 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3192
3193 // we use the hard disks map, but it is protected by the
3194 // hard disk _list_ lock handle
3195 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3196
3197 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3198 it != m->mapHardDisks.end();
3199 ++it)
3200 {
3201 const ComObjPtr<Medium> &pHD = (*it).second;
3202
3203 AutoCaller autoCaller(pHD);
3204 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3205 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3206
3207 Utf8Str strLocationFull = pHD->getLocationFull();
3208
3209 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3210 {
3211 if (aHardDisk)
3212 *aHardDisk = pHD;
3213 return S_OK;
3214 }
3215 }
3216
3217 if (aSetError)
3218 return setError(VBOX_E_OBJECT_NOT_FOUND,
3219 tr("Could not find an open hard disk with location '%s'"),
3220 strLocation.c_str());
3221
3222 return VBOX_E_OBJECT_NOT_FOUND;
3223}
3224
3225/**
3226 * Searches for a Medium object with the given ID or location in the list of
3227 * registered DVD or floppy images, depending on the @a mediumType argument.
3228 * If both ID and file path are specified, the first object that matches either
3229 * of them (not necessarily both) is returned.
3230 *
3231 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3232 * @param aId ID of the image file (unused when NULL).
3233 * @param aLocation Full path to the image file (unused when NULL).
3234 * @param aSetError If @c true, the appropriate error info is set in case when
3235 * the image is not found.
3236 * @param aImage Where to store the found image object (can be NULL).
3237 *
3238 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3239 *
3240 * @note Locks the media tree for reading.
3241 */
3242HRESULT VirtualBox::findDVDOrFloppyImage(DeviceType_T mediumType,
3243 const Guid *aId,
3244 const Utf8Str &aLocation,
3245 bool aSetError,
3246 ComObjPtr<Medium> *aImage /* = NULL */)
3247{
3248 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3249
3250 Utf8Str location;
3251 if (!aLocation.isEmpty())
3252 {
3253 int vrc = calculateFullPath(aLocation, location);
3254 if (RT_FAILURE(vrc))
3255 return setError(VBOX_E_FILE_ERROR,
3256 tr("Invalid image file location '%s' (%Rrc)"),
3257 aLocation.c_str(),
3258 vrc);
3259 }
3260
3261 MediaOList *pMediaList;
3262
3263 switch (mediumType)
3264 {
3265 case DeviceType_DVD:
3266 pMediaList = &m->allDVDImages;
3267 break;
3268
3269 case DeviceType_Floppy:
3270 pMediaList = &m->allFloppyImages;
3271 break;
3272
3273 default:
3274 return E_INVALIDARG;
3275 }
3276
3277 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3278
3279 bool found = false;
3280
3281 for (MediaList::const_iterator it = pMediaList->begin();
3282 it != pMediaList->end();
3283 ++it)
3284 {
3285 // no AutoCaller, registered image life time is bound to this
3286 Medium *pMedium = *it;
3287 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3288 const Utf8Str &strLocationFull = pMedium->getLocationFull();
3289
3290 found = ( aId
3291 && pMedium->getId() == *aId)
3292 || ( !aLocation.isEmpty()
3293 && RTPathCompare(location.c_str(),
3294 strLocationFull.c_str()) == 0);
3295 if (found)
3296 {
3297 if (pMedium->getDeviceType() != mediumType)
3298 {
3299 if (mediumType == DeviceType_DVD)
3300 return setError(E_INVALIDARG,
3301 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3302 else
3303 return setError(E_INVALIDARG,
3304 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3305 }
3306
3307 if (aImage)
3308 *aImage = pMedium;
3309 break;
3310 }
3311 }
3312
3313 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3314
3315 if (aSetError && !found)
3316 {
3317 if (aId)
3318 setError(rc,
3319 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3320 aId->raw(),
3321 m->strSettingsFilePath.c_str());
3322 else
3323 setError(rc,
3324 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3325 aLocation.c_str(),
3326 m->strSettingsFilePath.c_str());
3327 }
3328
3329 return rc;
3330}
3331
3332/**
3333 * Searches for an IMedium object that represents the given UUID.
3334 *
3335 * If the UUID is empty (indicating an empty drive), this sets pMedium
3336 * to NULL and returns S_OK.
3337 *
3338 * If the UUID refers to a host drive of the given device type, this
3339 * sets pMedium to the object from the list in IHost and returns S_OK.
3340 *
3341 * If the UUID is an image file, this sets pMedium to the object that
3342 * findDVDOrFloppyImage() returned.
3343 *
3344 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3345 *
3346 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3347 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3348 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3349 * @param pMedium out: IMedium object found.
3350 * @return
3351 */
3352HRESULT VirtualBox::findRemoveableMedium(DeviceType_T mediumType,
3353 const Guid &uuid,
3354 bool fRefresh,
3355 bool aSetError,
3356 ComObjPtr<Medium> &pMedium)
3357{
3358 if (uuid.isEmpty())
3359 {
3360 // that's easy
3361 pMedium.setNull();
3362 return S_OK;
3363 }
3364
3365 // first search for host drive with that UUID
3366 HRESULT rc = m->pHost->findHostDriveById(mediumType,
3367 uuid,
3368 fRefresh,
3369 pMedium);
3370 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3371 // then search for an image with that UUID
3372 rc = findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3373
3374 return rc;
3375}
3376
3377HRESULT VirtualBox::findGuestOSType(const Bstr &bstrOSType,
3378 GuestOSType*& pGuestOSType)
3379{
3380 /* Look for a GuestOSType object */
3381 AssertMsg(m->allGuestOSTypes.size() != 0,
3382 ("Guest OS types array must be filled"));
3383
3384 if (bstrOSType.isEmpty())
3385 {
3386 pGuestOSType = NULL;
3387 return S_OK;
3388 }
3389
3390 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3391 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3392 it != m->allGuestOSTypes.end();
3393 ++it)
3394 {
3395 if ((*it)->id() == bstrOSType)
3396 {
3397 pGuestOSType = *it;
3398 return S_OK;
3399 }
3400 }
3401
3402 return setError(VBOX_E_OBJECT_NOT_FOUND,
3403 tr("Guest OS type '%ls' is invalid"),
3404 bstrOSType.raw());
3405}
3406
3407/**
3408 * Returns the constant pseudo-machine UUID that is used to identify the
3409 * global media registry.
3410 *
3411 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3412 * in which media registry it is saved (if any): this can either be a machine
3413 * UUID, if it's in a per-machine media registry, or this global ID.
3414 *
3415 * This UUID is only used to identify the VirtualBox object while VirtualBox
3416 * is running. It is a compile-time constant and not saved anywhere.
3417 *
3418 * @return
3419 */
3420const Guid& VirtualBox::getGlobalRegistryId() const
3421{
3422 return m->uuidMediaRegistry;
3423}
3424
3425const ComObjPtr<Host>& VirtualBox::host() const
3426{
3427 return m->pHost;
3428}
3429
3430SystemProperties* VirtualBox::getSystemProperties() const
3431{
3432 return m->pSystemProperties;
3433}
3434
3435#ifdef VBOX_WITH_EXTPACK
3436/**
3437 * Getter that SystemProperties and others can use to talk to the extension
3438 * pack manager.
3439 */
3440ExtPackManager* VirtualBox::getExtPackManager() const
3441{
3442 return m->ptrExtPackManager;
3443}
3444#endif
3445
3446/**
3447 * Getter that machines can talk to the autostart database.
3448 */
3449AutostartDb* VirtualBox::getAutostartDb() const
3450{
3451 return m->pAutostartDb;
3452}
3453
3454#ifdef VBOX_WITH_RESOURCE_USAGE_API
3455const ComObjPtr<PerformanceCollector>& VirtualBox::performanceCollector() const
3456{
3457 return m->pPerformanceCollector;
3458}
3459#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3460
3461/**
3462 * Returns the default machine folder from the system properties
3463 * with proper locking.
3464 * @return
3465 */
3466void VirtualBox::getDefaultMachineFolder(Utf8Str &str) const
3467{
3468 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3469 str = m->pSystemProperties->m->strDefaultMachineFolder;
3470}
3471
3472/**
3473 * Returns the default hard disk format from the system properties
3474 * with proper locking.
3475 * @return
3476 */
3477void VirtualBox::getDefaultHardDiskFormat(Utf8Str &str) const
3478{
3479 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3480 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3481}
3482
3483const Utf8Str& VirtualBox::homeDir() const
3484{
3485 return m->strHomeDir;
3486}
3487
3488/**
3489 * Calculates the absolute path of the given path taking the VirtualBox home
3490 * directory as the current directory.
3491 *
3492 * @param aPath Path to calculate the absolute path for.
3493 * @param aResult Where to put the result (used only on success, can be the
3494 * same Utf8Str instance as passed in @a aPath).
3495 * @return IPRT result.
3496 *
3497 * @note Doesn't lock any object.
3498 */
3499int VirtualBox::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3500{
3501 AutoCaller autoCaller(this);
3502 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3503
3504 /* no need to lock since mHomeDir is const */
3505
3506 char folder[RTPATH_MAX];
3507 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3508 strPath.c_str(),
3509 folder,
3510 sizeof(folder));
3511 if (RT_SUCCESS(vrc))
3512 aResult = folder;
3513
3514 return vrc;
3515}
3516
3517/**
3518 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3519 * if it is a subdirectory thereof, or simply copying it otherwise.
3520 *
3521 * @param strSource Path to evalue and copy.
3522 * @param strTarget Buffer to receive target path.
3523 */
3524void VirtualBox::copyPathRelativeToConfig(const Utf8Str &strSource,
3525 Utf8Str &strTarget)
3526{
3527 AutoCaller autoCaller(this);
3528 AssertComRCReturnVoid(autoCaller.rc());
3529
3530 // no need to lock since mHomeDir is const
3531
3532 // use strTarget as a temporary buffer to hold the machine settings dir
3533 strTarget = m->strHomeDir;
3534 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3535 // is relative: then append what's left
3536 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3537 else
3538 // is not relative: then overwrite
3539 strTarget = strSource;
3540}
3541
3542// private methods
3543/////////////////////////////////////////////////////////////////////////////
3544
3545/**
3546 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3547 * location already registered.
3548 *
3549 * On return, sets @a aConflict to the string describing the conflicting medium,
3550 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3551 * either case. A failure is unexpected.
3552 *
3553 * @param aId UUID to check.
3554 * @param aLocation Location to check.
3555 * @param aConflict Where to return parameters of the conflicting medium.
3556 * @param ppMedium Medium reference in case this is simply a duplicate.
3557 *
3558 * @note Locks the media tree and media objects for reading.
3559 */
3560HRESULT VirtualBox::checkMediaForConflicts(const Guid &aId,
3561 const Utf8Str &aLocation,
3562 Utf8Str &aConflict,
3563 ComObjPtr<Medium> *ppMedium)
3564{
3565 AssertReturn(!aId.isEmpty() && !aLocation.isEmpty(), E_FAIL);
3566 AssertReturn(ppMedium, E_INVALIDARG);
3567
3568 aConflict.setNull();
3569 ppMedium->setNull();
3570
3571 AutoReadLock alock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3572
3573 HRESULT rc = S_OK;
3574
3575 ComObjPtr<Medium> pMediumFound;
3576 const char *pcszType = NULL;
3577
3578 if (!aId.isEmpty())
3579 rc = findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3580 if (FAILED(rc) && !aLocation.isEmpty())
3581 rc = findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3582 if (SUCCEEDED(rc))
3583 pcszType = tr("hard disk");
3584
3585 if (!pcszType)
3586 {
3587 rc = findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3588 if (SUCCEEDED(rc))
3589 pcszType = tr("CD/DVD image");
3590 }
3591
3592 if (!pcszType)
3593 {
3594 rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3595 if (SUCCEEDED(rc))
3596 pcszType = tr("floppy image");
3597 }
3598
3599 if (pcszType && pMediumFound)
3600 {
3601 /* Note: no AutoCaller since bound to this */
3602 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3603
3604 Utf8Str strLocFound = pMediumFound->getLocationFull();
3605 Guid idFound = pMediumFound->getId();
3606
3607 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3608 && (idFound == aId)
3609 )
3610 *ppMedium = pMediumFound;
3611
3612 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3613 pcszType,
3614 strLocFound.c_str(),
3615 idFound.raw());
3616 }
3617
3618 return S_OK;
3619}
3620
3621/**
3622 * Called from Machine::prepareSaveSettings() when it has detected
3623 * that a machine has been renamed. Such renames will require
3624 * updating the global media registry during the
3625 * VirtualBox::saveSettings() that follows later.
3626*
3627 * When a machine is renamed, there may well be media (in particular,
3628 * diff images for snapshots) in the global registry that will need
3629 * to have their paths updated. Before 3.2, Machine::saveSettings
3630 * used to call VirtualBox::saveSettings implicitly, which was both
3631 * unintuitive and caused locking order problems. Now, we remember
3632 * such pending name changes with this method so that
3633 * VirtualBox::saveSettings() can process them properly.
3634 */
3635void VirtualBox::rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3636 const Utf8Str &strNewConfigDir)
3637{
3638 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3639
3640 Data::PendingMachineRename pmr;
3641 pmr.strConfigDirOld = strOldConfigDir;
3642 pmr.strConfigDirNew = strNewConfigDir;
3643 m->llPendingMachineRenames.push_back(pmr);
3644}
3645
3646struct SaveMediaRegistriesDesc
3647{
3648 MediaList llMedia;
3649 ComObjPtr<VirtualBox> pVirtualBox;
3650};
3651
3652static int fntSaveMediaRegistries(RTTHREAD ThreadSelf, void *pvUser)
3653{
3654 NOREF(ThreadSelf);
3655 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
3656 if (!pDesc)
3657 {
3658 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
3659 return VERR_INVALID_PARAMETER;
3660 }
3661
3662 for (MediaList::const_iterator it = pDesc->llMedia.begin();
3663 it != pDesc->llMedia.end();
3664 ++it)
3665 {
3666 Medium *pMedium = *it;
3667 pMedium->markRegistriesModified();
3668 }
3669
3670 pDesc->pVirtualBox->saveModifiedRegistries();
3671
3672 pDesc->llMedia.clear();
3673 pDesc->pVirtualBox.setNull();
3674 delete pDesc;
3675
3676 return VINF_SUCCESS;
3677}
3678
3679/**
3680 * Goes through all known media (hard disks, floppies and DVDs) and saves
3681 * those into the given settings::MediaRegistry structures whose registry
3682 * ID match the given UUID.
3683 *
3684 * Before actually writing to the structures, all media paths (not just the
3685 * ones for the given registry) are updated if machines have been renamed
3686 * since the last call.
3687 *
3688 * This gets called from two contexts:
3689 *
3690 * -- VirtualBox::saveSettings() with the UUID of the global registry
3691 * (VirtualBox::Data.uuidRegistry); this will save those media
3692 * which had been loaded from the global registry or have been
3693 * attached to a "legacy" machine which can't save its own registry;
3694 *
3695 * -- Machine::saveSettings() with the UUID of a machine, if a medium
3696 * has been attached to a machine created with VirtualBox 4.0 or later.
3697 *
3698 * Media which have only been temporarily opened without having been
3699 * attached to a machine have a NULL registry UUID and therefore don't
3700 * get saved.
3701 *
3702 * This locks the media tree. Throws HRESULT on errors!
3703 *
3704 * @param mediaRegistry Settings structure to fill.
3705 * @param uuidRegistry The UUID of the media registry; either a machine UUID (if machine registry) or the UUID of the global registry.
3706 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
3707 */
3708void VirtualBox::saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
3709 const Guid &uuidRegistry,
3710 const Utf8Str &strMachineFolder)
3711{
3712 // lock all media for the following; use a write lock because we're
3713 // modifying the PendingMachineRenamesList, which is protected by this
3714 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3715
3716 // if a machine was renamed, then we'll need to refresh media paths
3717 if (m->llPendingMachineRenames.size())
3718 {
3719 // make a single list from the three media lists so we don't need three loops
3720 MediaList llAllMedia;
3721 // with hard disks, we must use the map, not the list, because the list only has base images
3722 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
3723 llAllMedia.push_back(it->second);
3724 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
3725 llAllMedia.push_back(*it);
3726 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
3727 llAllMedia.push_back(*it);
3728
3729 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
3730 for (MediaList::iterator it = llAllMedia.begin();
3731 it != llAllMedia.end();
3732 ++it)
3733 {
3734 Medium *pMedium = *it;
3735 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
3736 it2 != m->llPendingMachineRenames.end();
3737 ++it2)
3738 {
3739 const Data::PendingMachineRename &pmr = *it2;
3740 HRESULT rc = pMedium->updatePath(pmr.strConfigDirOld,
3741 pmr.strConfigDirNew);
3742 if (SUCCEEDED(rc))
3743 {
3744 // Remember which medium objects has been changed,
3745 // to trigger saving their registries later.
3746 pDesc->llMedia.push_back(pMedium);
3747 } else if (rc == VBOX_E_FILE_ERROR)
3748 /* nothing */;
3749 else
3750 AssertComRC(rc);
3751 }
3752 }
3753 // done, don't do it again until we have more machine renames
3754 m->llPendingMachineRenames.clear();
3755
3756 if (pDesc->llMedia.size())
3757 {
3758 // Handle the media registry saving in a separate thread, to
3759 // avoid giant locking problems and passing up the list many
3760 // levels up to whoever triggered saveSettings, as there are
3761 // lots of places which would need to handle saving more settings.
3762 pDesc->pVirtualBox = this;
3763 int vrc = RTThreadCreate(NULL,
3764 fntSaveMediaRegistries,
3765 (void *)pDesc,
3766 0, // cbStack (default)
3767 RTTHREADTYPE_MAIN_WORKER,
3768 0, // flags
3769 "SaveMediaReg");
3770 ComAssertRC(vrc);
3771 // failure means that settings aren't saved, but there isn't
3772 // much we can do besides avoiding memory leaks
3773 if (RT_FAILURE(vrc))
3774 {
3775 LogRelFunc(("Failed to create thread for saving media registries (%Rrc)\n", vrc));
3776 delete pDesc;
3777 }
3778 }
3779 else
3780 delete pDesc;
3781 }
3782
3783 struct {
3784 MediaOList &llSource;
3785 settings::MediaList &llTarget;
3786 } s[] =
3787 {
3788 // hard disks
3789 { m->allHardDisks, mediaRegistry.llHardDisks },
3790 // CD/DVD images
3791 { m->allDVDImages, mediaRegistry.llDvdImages },
3792 // floppy images
3793 { m->allFloppyImages, mediaRegistry.llFloppyImages }
3794 };
3795
3796 HRESULT rc;
3797
3798 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
3799 {
3800 MediaOList &llSource = s[i].llSource;
3801 settings::MediaList &llTarget = s[i].llTarget;
3802 llTarget.clear();
3803 for (MediaList::const_iterator it = llSource.begin();
3804 it != llSource.end();
3805 ++it)
3806 {
3807 Medium *pMedium = *it;
3808 AutoCaller autoCaller(pMedium);
3809 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
3810 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
3811
3812 if (pMedium->isInRegistry(uuidRegistry))
3813 {
3814 settings::Medium med;
3815 rc = pMedium->saveSettings(med, strMachineFolder); // this recurses into child hard disks
3816 if (FAILED(rc)) throw rc;
3817 llTarget.push_back(med);
3818 }
3819 }
3820 }
3821}
3822
3823/**
3824 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
3825 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
3826 * places internally when settings need saving.
3827 *
3828 * @note Caller must have locked the VirtualBox object for writing and must not hold any
3829 * other locks since this locks all kinds of member objects and trees temporarily,
3830 * which could cause conflicts.
3831 */
3832HRESULT VirtualBox::saveSettings()
3833{
3834 AutoCaller autoCaller(this);
3835 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3836
3837 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
3838 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
3839
3840 HRESULT rc = S_OK;
3841
3842 try
3843 {
3844 // machines
3845 m->pMainConfigFile->llMachines.clear();
3846 {
3847 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3848 for (MachinesOList::iterator it = m->allMachines.begin();
3849 it != m->allMachines.end();
3850 ++it)
3851 {
3852 Machine *pMachine = *it;
3853 // save actual machine registry entry
3854 settings::MachineRegistryEntry mre;
3855 rc = pMachine->saveRegistryEntry(mre);
3856 m->pMainConfigFile->llMachines.push_back(mre);
3857 }
3858 }
3859
3860 saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
3861 m->uuidMediaRegistry, // global media registry ID
3862 Utf8Str::Empty); // strMachineFolder
3863
3864 m->pMainConfigFile->llDhcpServers.clear();
3865 {
3866 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3867 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
3868 it != m->allDHCPServers.end();
3869 ++it)
3870 {
3871 settings::DHCPServer d;
3872 rc = (*it)->saveSettings(d);
3873 if (FAILED(rc)) throw rc;
3874 m->pMainConfigFile->llDhcpServers.push_back(d);
3875 }
3876 }
3877
3878 // leave extra data alone, it's still in the config file
3879
3880 // host data (USB filters)
3881 rc = m->pHost->saveSettings(m->pMainConfigFile->host);
3882 if (FAILED(rc)) throw rc;
3883
3884 rc = m->pSystemProperties->saveSettings(m->pMainConfigFile->systemProperties);
3885 if (FAILED(rc)) throw rc;
3886
3887 // and write out the XML, still under the lock
3888 m->pMainConfigFile->write(m->strSettingsFilePath);
3889 }
3890 catch (HRESULT err)
3891 {
3892 /* we assume that error info is set by the thrower */
3893 rc = err;
3894 }
3895 catch (...)
3896 {
3897 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
3898 }
3899
3900 return rc;
3901}
3902
3903/**
3904 * Helper to register the machine.
3905 *
3906 * When called during VirtualBox startup, adds the given machine to the
3907 * collection of registered machines. Otherwise tries to mark the machine
3908 * as registered, and, if succeeded, adds it to the collection and
3909 * saves global settings.
3910 *
3911 * @note The caller must have added itself as a caller of the @a aMachine
3912 * object if calls this method not on VirtualBox startup.
3913 *
3914 * @param aMachine machine to register
3915 *
3916 * @note Locks objects!
3917 */
3918HRESULT VirtualBox::registerMachine(Machine *aMachine)
3919{
3920 ComAssertRet(aMachine, E_INVALIDARG);
3921
3922 AutoCaller autoCaller(this);
3923 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3924
3925 HRESULT rc = S_OK;
3926
3927 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3928
3929 {
3930 ComObjPtr<Machine> pMachine;
3931 rc = findMachine(aMachine->getId(),
3932 true /* fPermitInaccessible */,
3933 false /* aDoSetError */,
3934 &pMachine);
3935 if (SUCCEEDED(rc))
3936 {
3937 /* sanity */
3938 AutoLimitedCaller machCaller(pMachine);
3939 AssertComRC(machCaller.rc());
3940
3941 return setError(E_INVALIDARG,
3942 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
3943 aMachine->getId().raw(),
3944 pMachine->getSettingsFileFull().c_str());
3945 }
3946
3947 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
3948 rc = S_OK;
3949 }
3950
3951 if (autoCaller.state() != InInit)
3952 {
3953 rc = aMachine->prepareRegister();
3954 if (FAILED(rc)) return rc;
3955 }
3956
3957 /* add to the collection of registered machines */
3958 m->allMachines.addChild(aMachine);
3959
3960 if (autoCaller.state() != InInit)
3961 rc = saveSettings();
3962
3963 return rc;
3964}
3965
3966/**
3967 * Remembers the given medium object by storing it in either the global
3968 * medium registry or a machine one.
3969 *
3970 * @note Caller must hold the media tree lock for writing; in addition, this
3971 * locks @a pMedium for reading
3972 *
3973 * @param pMedium Medium object to remember.
3974 * @param ppMedium Actually stored medium object. Can be different if due
3975 * to an unavoidable race there was a duplicate Medium object
3976 * created.
3977 * @param argType Either DeviceType_HardDisk, DeviceType_DVD or DeviceType_Floppy.
3978 * @return
3979 */
3980HRESULT VirtualBox::registerMedium(const ComObjPtr<Medium> &pMedium,
3981 ComObjPtr<Medium> *ppMedium,
3982 DeviceType_T argType)
3983{
3984 AssertReturn(pMedium != NULL, E_INVALIDARG);
3985 AssertReturn(ppMedium != NULL, E_INVALIDARG);
3986
3987 AutoCaller autoCaller(this);
3988 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3989
3990 AutoCaller mediumCaller(pMedium);
3991 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
3992
3993 const char *pszDevType = NULL;
3994 ObjectsList<Medium> *pall = NULL;
3995 switch (argType)
3996 {
3997 case DeviceType_HardDisk:
3998 pall = &m->allHardDisks;
3999 pszDevType = tr("hard disk");
4000 break;
4001 case DeviceType_DVD:
4002 pszDevType = tr("DVD image");
4003 pall = &m->allDVDImages;
4004 break;
4005 case DeviceType_Floppy:
4006 pszDevType = tr("floppy image");
4007 pall = &m->allFloppyImages;
4008 break;
4009 default:
4010 AssertMsgFailedReturn(("invalid device type %d", argType), E_INVALIDARG);
4011 }
4012
4013 // caller must hold the media tree write lock
4014 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4015
4016 Guid id;
4017 Utf8Str strLocationFull;
4018 ComObjPtr<Medium> pParent;
4019 {
4020 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4021 id = pMedium->getId();
4022 strLocationFull = pMedium->getLocationFull();
4023 pParent = pMedium->getParent();
4024 }
4025
4026 HRESULT rc;
4027
4028 Utf8Str strConflict;
4029 ComObjPtr<Medium> pDupMedium;
4030 rc = checkMediaForConflicts(id,
4031 strLocationFull,
4032 strConflict,
4033 &pDupMedium);
4034 if (FAILED(rc)) return rc;
4035
4036 if (pDupMedium.isNull())
4037 {
4038 if (strConflict.length())
4039 return setError(E_INVALIDARG,
4040 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4041 pszDevType,
4042 strLocationFull.c_str(),
4043 id.raw(),
4044 strConflict.c_str(),
4045 m->strSettingsFilePath.c_str());
4046
4047 // add to the collection if it is a base medium
4048 if (pParent.isNull())
4049 pall->getList().push_back(pMedium);
4050
4051 // store all hard disks (even differencing images) in the map
4052 if (argType == DeviceType_HardDisk)
4053 m->mapHardDisks[id] = pMedium;
4054
4055 *ppMedium = pMedium;
4056 }
4057 else
4058 {
4059 // pMedium may be the last reference to the Medium object, and the
4060 // caller may have specified the same ComObjPtr as the output parameter.
4061 // In this case the assignment will uninit the object, and we must not
4062 // have a caller pending.
4063 mediumCaller.release();
4064 *ppMedium = pDupMedium;
4065 }
4066
4067 return rc;
4068}
4069
4070/**
4071 * Removes the given medium from the respective registry.
4072 *
4073 * @param pMedium Hard disk object to remove.
4074 *
4075 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4076 */
4077HRESULT VirtualBox::unregisterMedium(Medium *pMedium)
4078{
4079 AssertReturn(pMedium != NULL, E_INVALIDARG);
4080
4081 AutoCaller autoCaller(this);
4082 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4083
4084 AutoCaller mediumCaller(pMedium);
4085 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4086
4087 // caller must hold the media tree write lock
4088 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4089
4090 Guid id;
4091 ComObjPtr<Medium> pParent;
4092 DeviceType_T devType;
4093 {
4094 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4095 id = pMedium->getId();
4096 pParent = pMedium->getParent();
4097 devType = pMedium->getDeviceType();
4098 }
4099
4100 ObjectsList<Medium> *pall = NULL;
4101 switch (devType)
4102 {
4103 case DeviceType_HardDisk:
4104 pall = &m->allHardDisks;
4105 break;
4106 case DeviceType_DVD:
4107 pall = &m->allDVDImages;
4108 break;
4109 case DeviceType_Floppy:
4110 pall = &m->allFloppyImages;
4111 break;
4112 default:
4113 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4114 }
4115
4116 // remove from the collection if it is a base medium
4117 if (pParent.isNull())
4118 pall->getList().remove(pMedium);
4119
4120 // remove all hard disks (even differencing images) from map
4121 if (devType == DeviceType_HardDisk)
4122 {
4123 size_t cnt = m->mapHardDisks.erase(id);
4124 Assert(cnt == 1);
4125 NOREF(cnt);
4126 }
4127
4128 return S_OK;
4129}
4130
4131/**
4132 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4133 * with children appearing before their parents.
4134 * @param llMedia
4135 * @param pMedium
4136 */
4137void VirtualBox::pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4138{
4139 // recurse first, then add ourselves; this way children end up on the
4140 // list before their parents
4141
4142 const MediaList &llChildren = pMedium->getChildren();
4143 for (MediaList::const_iterator it = llChildren.begin();
4144 it != llChildren.end();
4145 ++it)
4146 {
4147 Medium *pChild = *it;
4148 pushMediumToListWithChildren(llMedia, pChild);
4149 }
4150
4151 Log(("Pushing medium %RTuuid\n", pMedium->getId().raw()));
4152 llMedia.push_back(pMedium);
4153}
4154
4155/**
4156 * Unregisters all Medium objects which belong to the given machine registry.
4157 * Gets called from Machine::uninit() just before the machine object dies
4158 * and must only be called with a machine UUID as the registry ID.
4159 *
4160 * Locks the media tree.
4161 *
4162 * @param uuidMachine Medium registry ID (always a machine UUID)
4163 * @return
4164 */
4165HRESULT VirtualBox::unregisterMachineMedia(const Guid &uuidMachine)
4166{
4167 Assert(!uuidMachine.isEmpty());
4168
4169 LogFlowFuncEnter();
4170
4171 AutoCaller autoCaller(this);
4172 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4173
4174 MediaList llMedia2Close;
4175
4176 {
4177 AutoWriteLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4178
4179 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4180 it != m->allHardDisks.getList().end();
4181 ++it)
4182 {
4183 ComObjPtr<Medium> pMedium = *it;
4184 AutoCaller medCaller(pMedium);
4185 if (FAILED(medCaller.rc())) return medCaller.rc();
4186 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4187
4188 if (pMedium->isInRegistry(uuidMachine))
4189 // recursively with children first
4190 pushMediumToListWithChildren(llMedia2Close, pMedium);
4191 }
4192 }
4193
4194 for (MediaList::iterator it = llMedia2Close.begin();
4195 it != llMedia2Close.end();
4196 ++it)
4197 {
4198 ComObjPtr<Medium> pMedium = *it;
4199 Log(("Closing medium %RTuuid\n", pMedium->getId().raw()));
4200 AutoCaller mac(pMedium);
4201 pMedium->close(mac);
4202 }
4203
4204 LogFlowFuncLeave();
4205
4206 return S_OK;
4207}
4208
4209/**
4210 * Removes the given machine object from the internal list of registered machines.
4211 * Called from Machine::Unregister().
4212 * @param pMachine
4213 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4214 * @return
4215 */
4216HRESULT VirtualBox::unregisterMachine(Machine *pMachine,
4217 const Guid &id)
4218{
4219 // remove from the collection of registered machines
4220 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4221 m->allMachines.removeChild(pMachine);
4222 // save the global registry
4223 HRESULT rc = saveSettings();
4224 alock.release();
4225
4226 /*
4227 * Now go over all known media and checks if they were registered in the
4228 * media registry of the given machine. Each such medium is then moved to
4229 * a different media registry to make sure it doesn't get lost since its
4230 * media registry is about to go away.
4231 *
4232 * This fixes the following use case: Image A.vdi of machine A is also used
4233 * by machine B, but registered in the media registry of machine A. If machine
4234 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4235 * become inaccessible.
4236 */
4237 {
4238 AutoReadLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4239 // iterate over the list of *base* images
4240 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4241 it != m->allHardDisks.getList().end();
4242 ++it)
4243 {
4244 ComObjPtr<Medium> &pMedium = *it;
4245 AutoCaller medCaller(pMedium);
4246 if (FAILED(medCaller.rc())) return medCaller.rc();
4247 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4248
4249 if (pMedium->removeRegistry(id, true /* fRecurse */))
4250 {
4251 // machine ID was found in base medium's registry list:
4252 // move this base image and all its children to another registry then
4253 // 1) first, find a better registry to add things to
4254 const Guid *puuidBetter = pMedium->getAnyMachineBackref();
4255 if (puuidBetter)
4256 {
4257 // 2) better registry found: then use that
4258 pMedium->addRegistry(*puuidBetter, true /* fRecurse */);
4259 // 3) and make sure the registry is saved below
4260 mlock.release();
4261 tlock.release();
4262 markRegistryModified(*puuidBetter);
4263 tlock.acquire();
4264 mlock.release();
4265 }
4266 }
4267 }
4268 }
4269
4270 saveModifiedRegistries();
4271
4272 /* fire an event */
4273 onMachineRegistered(id, FALSE);
4274
4275 return rc;
4276}
4277
4278/**
4279 * Marks the registry for @a uuid as modified, so that it's saved in a later
4280 * call to saveModifiedRegistries().
4281 *
4282 * @param uuid
4283 */
4284void VirtualBox::markRegistryModified(const Guid &uuid)
4285{
4286 if (uuid == getGlobalRegistryId())
4287 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4288 else
4289 {
4290 ComObjPtr<Machine> pMachine;
4291 HRESULT rc = findMachine(uuid,
4292 false /* fPermitInaccessible */,
4293 false /* aSetError */,
4294 &pMachine);
4295 if (SUCCEEDED(rc))
4296 {
4297 AutoCaller machineCaller(pMachine);
4298 if (SUCCEEDED(machineCaller.rc()))
4299 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4300 }
4301 }
4302}
4303
4304/**
4305 * Saves all settings files according to the modified flags in the Machine
4306 * objects and in the VirtualBox object.
4307 *
4308 * This locks machines and the VirtualBox object as necessary, so better not
4309 * hold any locks before calling this.
4310 *
4311 * @return
4312 */
4313void VirtualBox::saveModifiedRegistries()
4314{
4315 HRESULT rc = S_OK;
4316 bool fNeedsGlobalSettings = false;
4317 uint64_t uOld;
4318
4319 for (MachinesOList::iterator it = m->allMachines.begin();
4320 it != m->allMachines.end();
4321 ++it)
4322 {
4323 const ComObjPtr<Machine> &pMachine = *it;
4324
4325 for (;;)
4326 {
4327 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4328 if (!uOld)
4329 break;
4330 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4331 break;
4332 ASMNopPause();
4333 }
4334 if (uOld)
4335 {
4336 AutoCaller autoCaller(pMachine);
4337 if (FAILED(autoCaller.rc())) continue;
4338 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
4339 rc = pMachine->saveSettings(&fNeedsGlobalSettings,
4340 Machine::SaveS_Force); // caller said save, so stop arguing
4341 }
4342 }
4343
4344 for (;;)
4345 {
4346 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4347 if (!uOld)
4348 break;
4349 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4350 break;
4351 ASMNopPause();
4352 }
4353 if (uOld || fNeedsGlobalSettings)
4354 {
4355 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4356 rc = saveSettings();
4357 }
4358 NOREF(rc); /* XXX */
4359}
4360
4361/**
4362 * Checks if the path to the specified file exists, according to the path
4363 * information present in the file name. Optionally the path is created.
4364 *
4365 * Note that the given file name must contain the full path otherwise the
4366 * extracted relative path will be created based on the current working
4367 * directory which is normally unknown.
4368 *
4369 * @param aFileName Full file name which path is checked/created.
4370 * @param aCreate Flag if the path should be created if it doesn't exist.
4371 *
4372 * @return Extended error information on failure to check/create the path.
4373 */
4374/* static */
4375HRESULT VirtualBox::ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4376{
4377 Utf8Str strDir(strFileName);
4378 strDir.stripFilename();
4379 if (!RTDirExists(strDir.c_str()))
4380 {
4381 if (fCreate)
4382 {
4383 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4384 if (RT_FAILURE(vrc))
4385 return setErrorStatic(VBOX_E_IPRT_ERROR,
4386 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4387 strDir.c_str(),
4388 vrc));
4389 }
4390 else
4391 return setErrorStatic(VBOX_E_IPRT_ERROR,
4392 Utf8StrFmt(tr("Directory '%s' does not exist"),
4393 strDir.c_str()));
4394 }
4395
4396 return S_OK;
4397}
4398
4399const Utf8Str& VirtualBox::settingsFilePath()
4400{
4401 return m->strSettingsFilePath;
4402}
4403
4404/**
4405 * Returns the lock handle which protects the media trees (hard disks,
4406 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4407 * are no longer protected by the VirtualBox lock, but by this more
4408 * specialized lock. Mind the locking order: always request this lock
4409 * after the VirtualBox object lock but before the locks of the media
4410 * objects contained in these lists. See AutoLock.h.
4411 */
4412RWLockHandle& VirtualBox::getMediaTreeLockHandle()
4413{
4414 return m->lockMedia;
4415}
4416
4417/**
4418 * Thread function that watches the termination of all client processes
4419 * that have opened sessions using IMachine::LockMachine()
4420 */
4421// static
4422DECLCALLBACK(int) VirtualBox::ClientWatcher(RTTHREAD /* thread */, void *pvUser)
4423{
4424 LogFlowFuncEnter();
4425
4426 VirtualBox *that = (VirtualBox*)pvUser;
4427 Assert(that);
4428
4429 typedef std::vector< ComObjPtr<Machine> > MachineVector;
4430 typedef std::vector< ComObjPtr<SessionMachine> > SessionMachineVector;
4431
4432 SessionMachineVector machines;
4433 MachineVector spawnedMachines;
4434
4435 size_t cnt = 0;
4436 size_t cntSpawned = 0;
4437
4438 VirtualBoxBase::initializeComForThread();
4439
4440#if defined(RT_OS_WINDOWS)
4441
4442 /// @todo (dmik) processes reaping!
4443
4444 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
4445 handles[0] = that->m->updateReq;
4446
4447 do
4448 {
4449 AutoCaller autoCaller(that);
4450 /* VirtualBox has been early uninitialized, terminate */
4451 if (!autoCaller.isOk())
4452 break;
4453
4454 do
4455 {
4456 /* release the caller to let uninit() ever proceed */
4457 autoCaller.release();
4458
4459 DWORD rc = ::WaitForMultipleObjects((DWORD)(1 + cnt + cntSpawned),
4460 handles,
4461 FALSE,
4462 INFINITE);
4463
4464 /* Restore the caller before using VirtualBox. If it fails, this
4465 * means VirtualBox is being uninitialized and we must terminate. */
4466 autoCaller.add();
4467 if (!autoCaller.isOk())
4468 break;
4469
4470 bool update = false;
4471
4472 if (rc == WAIT_OBJECT_0)
4473 {
4474 /* update event is signaled */
4475 update = true;
4476 }
4477 else if (rc > WAIT_OBJECT_0 && rc <= (WAIT_OBJECT_0 + cnt))
4478 {
4479 /* machine mutex is released */
4480 (machines[rc - WAIT_OBJECT_0 - 1])->checkForDeath();
4481 update = true;
4482 }
4483 else if (rc > WAIT_ABANDONED_0 && rc <= (WAIT_ABANDONED_0 + cnt))
4484 {
4485 /* machine mutex is abandoned due to client process termination */
4486 (machines[rc - WAIT_ABANDONED_0 - 1])->checkForDeath();
4487 update = true;
4488 }
4489 else if (rc > WAIT_OBJECT_0 + cnt && rc <= (WAIT_OBJECT_0 + cntSpawned))
4490 {
4491 /* spawned VM process has terminated (normally or abnormally) */
4492 (spawnedMachines[rc - WAIT_OBJECT_0 - cnt - 1])->
4493 checkForSpawnFailure();
4494 update = true;
4495 }
4496
4497 if (update)
4498 {
4499 /* close old process handles */
4500 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++i)
4501 CloseHandle(handles[i]);
4502
4503 // lock the machines list for reading
4504 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4505
4506 /* obtain a new set of opened machines */
4507 cnt = 0;
4508 machines.clear();
4509
4510 for (MachinesOList::iterator it = that->m->allMachines.begin();
4511 it != that->m->allMachines.end();
4512 ++it)
4513 {
4514 /// @todo handle situations with more than 64 objects
4515 AssertMsgBreak((1 + cnt) <= MAXIMUM_WAIT_OBJECTS,
4516 ("MAXIMUM_WAIT_OBJECTS reached"));
4517
4518 ComObjPtr<SessionMachine> sm;
4519 HANDLE ipcSem;
4520 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4521 {
4522 machines.push_back(sm);
4523 handles[1 + cnt] = ipcSem;
4524 ++cnt;
4525 }
4526 }
4527
4528 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4529
4530 /* obtain a new set of spawned machines */
4531 cntSpawned = 0;
4532 spawnedMachines.clear();
4533
4534 for (MachinesOList::iterator it = that->m->allMachines.begin();
4535 it != that->m->allMachines.end();
4536 ++it)
4537 {
4538 /// @todo handle situations with more than 64 objects
4539 AssertMsgBreak((1 + cnt + cntSpawned) <= MAXIMUM_WAIT_OBJECTS,
4540 ("MAXIMUM_WAIT_OBJECTS reached"));
4541
4542 RTPROCESS pid;
4543 if ((*it)->isSessionSpawning(&pid))
4544 {
4545 HANDLE ph = OpenProcess(SYNCHRONIZE, FALSE, pid);
4546 AssertMsg(ph != NULL, ("OpenProcess (pid=%d) failed with %d\n",
4547 pid, GetLastError()));
4548 if (rc == 0)
4549 {
4550 spawnedMachines.push_back(*it);
4551 handles[1 + cnt + cntSpawned] = ph;
4552 ++cntSpawned;
4553 }
4554 }
4555 }
4556
4557 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4558
4559 // machines lock unwinds here
4560 }
4561 }
4562 while (true);
4563 }
4564 while (0);
4565
4566 /* close old process handles */
4567 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++ i)
4568 CloseHandle(handles[i]);
4569
4570 /* release sets of machines if any */
4571 machines.clear();
4572 spawnedMachines.clear();
4573
4574 ::CoUninitialize();
4575
4576#elif defined(RT_OS_OS2)
4577
4578 /// @todo (dmik) processes reaping!
4579
4580 /* according to PMREF, 64 is the maximum for the muxwait list */
4581 SEMRECORD handles[64];
4582
4583 HMUX muxSem = NULLHANDLE;
4584
4585 do
4586 {
4587 AutoCaller autoCaller(that);
4588 /* VirtualBox has been early uninitialized, terminate */
4589 if (!autoCaller.isOk())
4590 break;
4591
4592 do
4593 {
4594 /* release the caller to let uninit() ever proceed */
4595 autoCaller.release();
4596
4597 int vrc = RTSemEventWait(that->m->updateReq, 500);
4598
4599 /* Restore the caller before using VirtualBox. If it fails, this
4600 * means VirtualBox is being uninitialized and we must terminate. */
4601 autoCaller.add();
4602 if (!autoCaller.isOk())
4603 break;
4604
4605 bool update = false;
4606 bool updateSpawned = false;
4607
4608 if (RT_SUCCESS(vrc))
4609 {
4610 /* update event is signaled */
4611 update = true;
4612 updateSpawned = true;
4613 }
4614 else
4615 {
4616 AssertMsg(vrc == VERR_TIMEOUT || vrc == VERR_INTERRUPTED,
4617 ("RTSemEventWait returned %Rrc\n", vrc));
4618
4619 /* are there any mutexes? */
4620 if (cnt > 0)
4621 {
4622 /* figure out what's going on with machines */
4623
4624 unsigned long semId = 0;
4625 APIRET arc = ::DosWaitMuxWaitSem(muxSem,
4626 SEM_IMMEDIATE_RETURN, &semId);
4627
4628 if (arc == NO_ERROR)
4629 {
4630 /* machine mutex is normally released */
4631 Assert(semId >= 0 && semId < cnt);
4632 if (semId >= 0 && semId < cnt)
4633 {
4634#if 0//def DEBUG
4635 {
4636 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4637 LogFlowFunc(("released mutex: machine='%ls'\n",
4638 machines[semId]->name().raw()));
4639 }
4640#endif
4641 machines[semId]->checkForDeath();
4642 }
4643 update = true;
4644 }
4645 else if (arc == ERROR_SEM_OWNER_DIED)
4646 {
4647 /* machine mutex is abandoned due to client process
4648 * termination; find which mutex is in the Owner Died
4649 * state */
4650 for (size_t i = 0; i < cnt; ++ i)
4651 {
4652 PID pid; TID tid;
4653 unsigned long reqCnt;
4654 arc = DosQueryMutexSem((HMTX)handles[i].hsemCur, &pid, &tid, &reqCnt);
4655 if (arc == ERROR_SEM_OWNER_DIED)
4656 {
4657 /* close the dead mutex as asked by PMREF */
4658 ::DosCloseMutexSem((HMTX)handles[i].hsemCur);
4659
4660 Assert(i >= 0 && i < cnt);
4661 if (i >= 0 && i < cnt)
4662 {
4663#if 0//def DEBUG
4664 {
4665 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4666 LogFlowFunc(("mutex owner dead: machine='%ls'\n",
4667 machines[i]->name().raw()));
4668 }
4669#endif
4670 machines[i]->checkForDeath();
4671 }
4672 }
4673 }
4674 update = true;
4675 }
4676 else
4677 AssertMsg(arc == ERROR_INTERRUPT || arc == ERROR_TIMEOUT,
4678 ("DosWaitMuxWaitSem returned %d\n", arc));
4679 }
4680
4681 /* are there any spawning sessions? */
4682 if (cntSpawned > 0)
4683 {
4684 for (size_t i = 0; i < cntSpawned; ++ i)
4685 updateSpawned |= (spawnedMachines[i])->
4686 checkForSpawnFailure();
4687 }
4688 }
4689
4690 if (update || updateSpawned)
4691 {
4692 AutoReadLock thatLock(that COMMA_LOCKVAL_SRC_POS);
4693
4694 if (update)
4695 {
4696 /* close the old muxsem */
4697 if (muxSem != NULLHANDLE)
4698 ::DosCloseMuxWaitSem(muxSem);
4699
4700 /* obtain a new set of opened machines */
4701 cnt = 0;
4702 machines.clear();
4703
4704 for (MachinesOList::iterator it = that->m->allMachines.begin();
4705 it != that->m->allMachines.end(); ++ it)
4706 {
4707 /// @todo handle situations with more than 64 objects
4708 AssertMsg(cnt <= 64 /* according to PMREF */,
4709 ("maximum of 64 mutex semaphores reached (%d)",
4710 cnt));
4711
4712 ComObjPtr<SessionMachine> sm;
4713 HMTX ipcSem;
4714 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4715 {
4716 machines.push_back(sm);
4717 handles[cnt].hsemCur = (HSEM)ipcSem;
4718 handles[cnt].ulUser = cnt;
4719 ++ cnt;
4720 }
4721 }
4722
4723 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4724
4725 if (cnt > 0)
4726 {
4727 /* create a new muxsem */
4728 APIRET arc = ::DosCreateMuxWaitSem(NULL, &muxSem, cnt,
4729 handles,
4730 DCMW_WAIT_ANY);
4731 AssertMsg(arc == NO_ERROR,
4732 ("DosCreateMuxWaitSem returned %d\n", arc));
4733 NOREF(arc);
4734 }
4735 }
4736
4737 if (updateSpawned)
4738 {
4739 /* obtain a new set of spawned machines */
4740 spawnedMachines.clear();
4741
4742 for (MachinesOList::iterator it = that->m->allMachines.begin();
4743 it != that->m->allMachines.end(); ++ it)
4744 {
4745 if ((*it)->isSessionSpawning())
4746 spawnedMachines.push_back(*it);
4747 }
4748
4749 cntSpawned = spawnedMachines.size();
4750 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4751 }
4752 }
4753 }
4754 while (true);
4755 }
4756 while (0);
4757
4758 /* close the muxsem */
4759 if (muxSem != NULLHANDLE)
4760 ::DosCloseMuxWaitSem(muxSem);
4761
4762 /* release sets of machines if any */
4763 machines.clear();
4764 spawnedMachines.clear();
4765
4766#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
4767
4768 bool update = false;
4769 bool updateSpawned = false;
4770
4771 do
4772 {
4773 AutoCaller autoCaller(that);
4774 if (!autoCaller.isOk())
4775 break;
4776
4777 do
4778 {
4779 /* release the caller to let uninit() ever proceed */
4780 autoCaller.release();
4781
4782 int rc = RTSemEventWait(that->m->updateReq, 500);
4783
4784 /*
4785 * Restore the caller before using VirtualBox. If it fails, this
4786 * means VirtualBox is being uninitialized and we must terminate.
4787 */
4788 autoCaller.add();
4789 if (!autoCaller.isOk())
4790 break;
4791
4792 if (RT_SUCCESS(rc) || update || updateSpawned)
4793 {
4794 /* RT_SUCCESS(rc) means an update event is signaled */
4795
4796 // lock the machines list for reading
4797 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4798
4799 if (RT_SUCCESS(rc) || update)
4800 {
4801 /* obtain a new set of opened machines */
4802 machines.clear();
4803
4804 for (MachinesOList::iterator it = that->m->allMachines.begin();
4805 it != that->m->allMachines.end();
4806 ++it)
4807 {
4808 ComObjPtr<SessionMachine> sm;
4809 if ((*it)->isSessionOpenOrClosing(sm))
4810 machines.push_back(sm);
4811 }
4812
4813 cnt = machines.size();
4814 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4815 }
4816
4817 if (RT_SUCCESS(rc) || updateSpawned)
4818 {
4819 /* obtain a new set of spawned machines */
4820 spawnedMachines.clear();
4821
4822 for (MachinesOList::iterator it = that->m->allMachines.begin();
4823 it != that->m->allMachines.end();
4824 ++it)
4825 {
4826 if ((*it)->isSessionSpawning())
4827 spawnedMachines.push_back(*it);
4828 }
4829
4830 cntSpawned = spawnedMachines.size();
4831 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4832 }
4833
4834 // machines lock unwinds here
4835 }
4836
4837 update = false;
4838 for (size_t i = 0; i < cnt; ++ i)
4839 update |= (machines[i])->checkForDeath();
4840
4841 updateSpawned = false;
4842 for (size_t i = 0; i < cntSpawned; ++ i)
4843 updateSpawned |= (spawnedMachines[i])->checkForSpawnFailure();
4844
4845 /* reap child processes */
4846 {
4847 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
4848 if (that->m->llProcesses.size())
4849 {
4850 LogFlowFunc(("UPDATE: child process count = %d\n",
4851 that->m->llProcesses.size()));
4852 VirtualBox::Data::ProcessList::iterator it = that->m->llProcesses.begin();
4853 while (it != that->m->llProcesses.end())
4854 {
4855 RTPROCESS pid = *it;
4856 RTPROCSTATUS status;
4857 int vrc = ::RTProcWait(pid, RTPROCWAIT_FLAGS_NOBLOCK, &status);
4858 if (vrc == VINF_SUCCESS)
4859 {
4860 LogFlowFunc(("pid %d (%x) was reaped, status=%d, reason=%d\n",
4861 pid, pid, status.iStatus,
4862 status.enmReason));
4863 it = that->m->llProcesses.erase(it);
4864 }
4865 else
4866 {
4867 LogFlowFunc(("pid %d (%x) was NOT reaped, vrc=%Rrc\n",
4868 pid, pid, vrc));
4869 if (vrc != VERR_PROCESS_RUNNING)
4870 {
4871 /* remove the process if it is not already running */
4872 it = that->m->llProcesses.erase(it);
4873 }
4874 else
4875 ++ it;
4876 }
4877 }
4878 }
4879 }
4880 }
4881 while (true);
4882 }
4883 while (0);
4884
4885 /* release sets of machines if any */
4886 machines.clear();
4887 spawnedMachines.clear();
4888
4889#else
4890# error "Port me!"
4891#endif
4892
4893 VirtualBoxBase::uninitializeComForThread();
4894 LogFlowFuncLeave();
4895 return 0;
4896}
4897
4898/**
4899 * Thread function that handles custom events posted using #postEvent().
4900 */
4901// static
4902DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4903{
4904 LogFlowFuncEnter();
4905
4906 AssertReturn(pvUser, VERR_INVALID_POINTER);
4907
4908 com::Initialize();
4909
4910 // create an event queue for the current thread
4911 EventQueue *eventQ = new EventQueue();
4912 AssertReturn(eventQ, VERR_NO_MEMORY);
4913
4914 // return the queue to the one who created this thread
4915 *(static_cast <EventQueue **>(pvUser)) = eventQ;
4916 // signal that we're ready
4917 RTThreadUserSignal(thread);
4918
4919 /*
4920 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4921 * we must not stop processing events and delete the "eventQ" object. This must
4922 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4923 * See @bugref{5724}.
4924 */
4925 while (eventQ->processEventQueue(RT_INDEFINITE_WAIT) != VERR_INTERRUPTED)
4926 /* nothing */ ;
4927
4928 delete eventQ;
4929
4930 com::Shutdown();
4931
4932
4933 LogFlowFuncLeave();
4934
4935 return 0;
4936}
4937
4938
4939////////////////////////////////////////////////////////////////////////////////
4940
4941/**
4942 * Takes the current list of registered callbacks of the managed VirtualBox
4943 * instance, and calls #handleCallback() for every callback item from the
4944 * list, passing the item as an argument.
4945 *
4946 * @note Locks the managed VirtualBox object for reading but leaves the lock
4947 * before iterating over callbacks and calling their methods.
4948 */
4949void *VirtualBox::CallbackEvent::handler()
4950{
4951 if (!mVirtualBox)
4952 return NULL;
4953
4954 AutoCaller autoCaller(mVirtualBox);
4955 if (!autoCaller.isOk())
4956 {
4957 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4958 autoCaller.state()));
4959 /* We don't need mVirtualBox any more, so release it */
4960 mVirtualBox = NULL;
4961 return NULL;
4962 }
4963
4964 {
4965 VBoxEventDesc evDesc;
4966 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4967
4968 evDesc.fire(/* don't wait for delivery */0);
4969 }
4970
4971 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4972 return NULL;
4973}
4974
4975//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4976//{
4977// return E_NOTIMPL;
4978//}
4979
4980STDMETHODIMP VirtualBox::CreateDHCPServer(IN_BSTR aName, IDHCPServer ** aServer)
4981{
4982 CheckComArgStrNotEmptyOrNull(aName);
4983 CheckComArgNotNull(aServer);
4984
4985 AutoCaller autoCaller(this);
4986 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4987
4988 ComObjPtr<DHCPServer> dhcpServer;
4989 dhcpServer.createObject();
4990 HRESULT rc = dhcpServer->init(this, aName);
4991 if (FAILED(rc)) return rc;
4992
4993 rc = registerDHCPServer(dhcpServer, true);
4994 if (FAILED(rc)) return rc;
4995
4996 dhcpServer.queryInterfaceTo(aServer);
4997
4998 return rc;
4999}
5000
5001STDMETHODIMP VirtualBox::FindDHCPServerByNetworkName(IN_BSTR aName, IDHCPServer ** aServer)
5002{
5003 CheckComArgStrNotEmptyOrNull(aName);
5004 CheckComArgNotNull(aServer);
5005
5006 AutoCaller autoCaller(this);
5007 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5008
5009 HRESULT rc;
5010 Bstr bstr;
5011 ComPtr<DHCPServer> found;
5012
5013 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5014
5015 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5016 it != m->allDHCPServers.end();
5017 ++it)
5018 {
5019 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
5020 if (FAILED(rc)) return rc;
5021
5022 if (bstr == aName)
5023 {
5024 found = *it;
5025 break;
5026 }
5027 }
5028
5029 if (!found)
5030 return E_INVALIDARG;
5031
5032 return found.queryInterfaceTo(aServer);
5033}
5034
5035STDMETHODIMP VirtualBox::RemoveDHCPServer(IDHCPServer * aServer)
5036{
5037 CheckComArgNotNull(aServer);
5038
5039 AutoCaller autoCaller(this);
5040 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5041
5042 HRESULT rc = unregisterDHCPServer(static_cast<DHCPServer *>(aServer), true);
5043
5044 return rc;
5045}
5046
5047/**
5048 * Remembers the given DHCP server in the settings.
5049 *
5050 * @param aDHCPServer DHCP server object to remember.
5051 * @param aSaveSettings @c true to save settings to disk (default).
5052 *
5053 * When @a aSaveSettings is @c true, this operation may fail because of the
5054 * failed #saveSettings() method it calls. In this case, the dhcp server object
5055 * will not be remembered. It is therefore the responsibility of the caller to
5056 * call this method as the last step of some action that requires registration
5057 * in order to make sure that only fully functional dhcp server objects get
5058 * registered.
5059 *
5060 * @note Locks this object for writing and @a aDHCPServer for reading.
5061 */
5062HRESULT VirtualBox::registerDHCPServer(DHCPServer *aDHCPServer,
5063 bool aSaveSettings /*= true*/)
5064{
5065 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5066
5067 AutoCaller autoCaller(this);
5068 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5069
5070 AutoCaller dhcpServerCaller(aDHCPServer);
5071 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
5072
5073 Bstr name;
5074 HRESULT rc;
5075 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
5076 if (FAILED(rc)) return rc;
5077
5078 ComPtr<IDHCPServer> existing;
5079 rc = FindDHCPServerByNetworkName(name.raw(), existing.asOutParam());
5080 if (SUCCEEDED(rc))
5081 return E_INVALIDARG;
5082
5083 rc = S_OK;
5084
5085 m->allDHCPServers.addChild(aDHCPServer);
5086
5087 if (aSaveSettings)
5088 {
5089 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5090 rc = saveSettings();
5091 vboxLock.release();
5092
5093 if (FAILED(rc))
5094 unregisterDHCPServer(aDHCPServer, false /* aSaveSettings */);
5095 }
5096
5097 return rc;
5098}
5099
5100/**
5101 * Removes the given DHCP server from the settings.
5102 *
5103 * @param aDHCPServer DHCP server object to remove.
5104 * @param aSaveSettings @c true to save settings to disk (default).
5105 *
5106 * When @a aSaveSettings is @c true, this operation may fail because of the
5107 * failed #saveSettings() method it calls. In this case, the DHCP server
5108 * will NOT be removed from the settingsi when this method returns.
5109 *
5110 * @note Locks this object for writing.
5111 */
5112HRESULT VirtualBox::unregisterDHCPServer(DHCPServer *aDHCPServer,
5113 bool aSaveSettings /*= true*/)
5114{
5115 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5116
5117 AutoCaller autoCaller(this);
5118 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5119
5120 AutoCaller dhcpServerCaller(aDHCPServer);
5121 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
5122
5123 m->allDHCPServers.removeChild(aDHCPServer);
5124
5125 HRESULT rc = S_OK;
5126
5127 if (aSaveSettings)
5128 {
5129 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5130 rc = saveSettings();
5131 vboxLock.release();
5132
5133 if (FAILED(rc))
5134 registerDHCPServer(aDHCPServer, false /* aSaveSettings */);
5135 }
5136
5137 return rc;
5138}
5139
5140/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette