VirtualBox

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

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

Main/VirtualBox: fix race due to insufficient synchronization

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