VirtualBox

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

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

Main/VirtualBox: very tricky fix for renaming linked clones (media registry needs saving) which avoids locking problems by using a separate thread

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

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