VirtualBox

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

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

More autostart service updates, work in progress

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

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