VirtualBox

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

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

Main/ComposeMachineFilename: move sanitising code into separate function and add a test.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 154.5 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 40179 2012-02-20 15:03:06Z vboxsync $ */
2/** @file
3 * Implementation of IVirtualBox in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2011 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 };
1410 for (unsigned i = 0; i < RT_ELEMENTS(aTest); ++i)
1411 {
1412 Utf8Str str(aTest[i].pcszIn);
1413 sanitiseMachineFilename(str);
1414 if (str.compare(aTest[i].pcszOutExpected))
1415 {
1416 ++cErrors;
1417 pfnPrintf("%s: line %d, expected %s, actual %s\n",
1418 __PRETTY_FUNCTION__, i, aTest[i].pcszOutExpected,
1419 str.c_str());
1420 }
1421 }
1422 return cErrors;
1423}
1424
1425#ifdef DEBUG
1426/** @todo Proper testcase. */
1427/** @todo Do we have a better method of doing init functions? */
1428namespace
1429{
1430 class TestSanitiseMachineFilename
1431 {
1432 public:
1433 TestSanitiseMachineFilename(void)
1434 {
1435 Assert(!testSanitiseMachineFilename(RTAssertMsg2));
1436 }
1437 };
1438 TestSanitiseMachineFilename s_TestSanitiseMachineFilename;
1439}
1440#endif
1441
1442/** @note Locks mSystemProperties object for reading. */
1443STDMETHODIMP VirtualBox::CreateMachine(IN_BSTR aSettingsFile,
1444 IN_BSTR aName,
1445 IN_BSTR aOsTypeId,
1446 IN_BSTR aId,
1447 BOOL forceOverwrite,
1448 IMachine **aMachine)
1449{
1450 LogFlowThisFuncEnter();
1451 LogFlowThisFunc(("aSettingsFile=\"%ls\", aName=\"%ls\", aOsTypeId =\"%ls\"\n", aSettingsFile, aName, aOsTypeId));
1452
1453 CheckComArgStrNotEmptyOrNull(aName);
1454 /** @todo tighten checks on aId? */
1455 CheckComArgOutPointerValid(aMachine);
1456
1457 AutoCaller autoCaller(this);
1458 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1459
1460 /* NULL settings file means compose automatically */
1461 HRESULT rc;
1462 Bstr bstrSettingsFile(aSettingsFile);
1463 if (bstrSettingsFile.isEmpty())
1464 {
1465 rc = ComposeMachineFilename(aName,
1466 NULL,
1467 bstrSettingsFile.asOutParam());
1468 if (FAILED(rc)) return rc;
1469 }
1470
1471 /* create a new object */
1472 ComObjPtr<Machine> machine;
1473 rc = machine.createObject();
1474 if (FAILED(rc)) return rc;
1475
1476 /* Create UUID if an empty one was specified. */
1477 Guid id(aId);
1478 if (id.isEmpty())
1479 id.create();
1480
1481 GuestOSType *osType = NULL;
1482 rc = findGuestOSType(Bstr(aOsTypeId), osType);
1483 if (FAILED(rc)) return rc;
1484
1485 /* initialize the machine object */
1486 rc = machine->init(this,
1487 Utf8Str(bstrSettingsFile),
1488 Utf8Str(aName),
1489 osType,
1490 id,
1491 !!forceOverwrite);
1492 if (SUCCEEDED(rc))
1493 {
1494 /* set the return value */
1495 rc = machine.queryInterfaceTo(aMachine);
1496 AssertComRC(rc);
1497
1498#ifdef VBOX_WITH_EXTPACK
1499 /* call the extension pack hooks */
1500 m->ptrExtPackManager->callAllVmCreatedHooks(machine);
1501#endif
1502 }
1503
1504 LogFlowThisFuncLeave();
1505
1506 return rc;
1507}
1508
1509STDMETHODIMP VirtualBox::OpenMachine(IN_BSTR aSettingsFile,
1510 IMachine **aMachine)
1511{
1512 CheckComArgStrNotEmptyOrNull(aSettingsFile);
1513 CheckComArgOutSafeArrayPointerValid(aMachine);
1514
1515 AutoCaller autoCaller(this);
1516 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1517
1518 HRESULT rc = E_FAIL;
1519
1520 /* create a new object */
1521 ComObjPtr<Machine> machine;
1522 rc = machine.createObject();
1523 if (SUCCEEDED(rc))
1524 {
1525 /* initialize the machine object */
1526 rc = machine->init(this,
1527 aSettingsFile,
1528 NULL); /* const Guid *aId */
1529 if (SUCCEEDED(rc))
1530 {
1531 /* set the return value */
1532 rc = machine.queryInterfaceTo(aMachine);
1533 ComAssertComRC(rc);
1534 }
1535 }
1536
1537 return rc;
1538}
1539
1540/** @note Locks objects! */
1541STDMETHODIMP VirtualBox::RegisterMachine(IMachine *aMachine)
1542{
1543 CheckComArgNotNull(aMachine);
1544
1545 AutoCaller autoCaller(this);
1546 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1547
1548 HRESULT rc;
1549
1550 Bstr name;
1551 rc = aMachine->COMGETTER(Name)(name.asOutParam());
1552 if (FAILED(rc)) return rc;
1553
1554 /* We can safely cast child to Machine * here because only Machine
1555 * implementations of IMachine can be among our children. */
1556 Machine *pMachine = static_cast<Machine*>(aMachine);
1557
1558 AutoCaller machCaller(pMachine);
1559 ComAssertComRCRetRC(machCaller.rc());
1560
1561 rc = registerMachine(pMachine);
1562 /* fire an event */
1563 if (SUCCEEDED(rc))
1564 onMachineRegistered(pMachine->getId(), TRUE);
1565
1566 return rc;
1567}
1568
1569/** @note Locks this object for reading, then some machine objects for reading. */
1570STDMETHODIMP VirtualBox::FindMachine(IN_BSTR aNameOrId, IMachine **aMachine)
1571{
1572 LogFlowThisFuncEnter();
1573 LogFlowThisFunc(("aName=\"%ls\", aMachine={%p}\n", aNameOrId, aMachine));
1574
1575 CheckComArgStrNotEmptyOrNull(aNameOrId);
1576 CheckComArgOutSafeArrayPointerValid(aMachine);
1577
1578 AutoCaller autoCaller(this);
1579 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1580
1581 /* start with not found */
1582 HRESULT rc = S_OK;
1583 ComObjPtr<Machine> pMachineFound;
1584
1585 Guid id(aNameOrId);
1586 if (!id.isEmpty())
1587 rc = findMachine(id,
1588 true /* fPermitInaccessible */,
1589 true /* setError */,
1590 &pMachineFound);
1591 // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
1592 else
1593 {
1594 Utf8Str strName(aNameOrId);
1595 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1596 for (MachinesOList::iterator it = m->allMachines.begin();
1597 it != m->allMachines.end();
1598 ++it)
1599 {
1600 ComObjPtr<Machine> &pMachine2 = *it;
1601 AutoCaller machCaller(pMachine2);
1602 if (machCaller.rc())
1603 continue; // we can't ask inaccessible machines for their names
1604
1605 AutoReadLock machLock(pMachine2 COMMA_LOCKVAL_SRC_POS);
1606 if (pMachine2->getName() == strName)
1607 {
1608 pMachineFound = pMachine2;
1609 break;
1610 }
1611 if (!RTPathCompare(pMachine2->getSettingsFileFull().c_str(), strName.c_str()))
1612 {
1613 pMachineFound = pMachine2;
1614 break;
1615 }
1616 }
1617
1618 if (!pMachineFound)
1619 rc = setError(VBOX_E_OBJECT_NOT_FOUND,
1620 tr("Could not find a registered machine named '%ls'"), aNameOrId);
1621 }
1622
1623 /* this will set (*machine) to NULL if machineObj is null */
1624 pMachineFound.queryInterfaceTo(aMachine);
1625
1626 LogFlowThisFunc(("aName=\"%ls\", aMachine=%p, rc=%08X\n", aNameOrId, *aMachine, rc));
1627 LogFlowThisFuncLeave();
1628
1629 return rc;
1630}
1631
1632STDMETHODIMP VirtualBox::CreateHardDisk(IN_BSTR aFormat,
1633 IN_BSTR aLocation,
1634 IMedium **aHardDisk)
1635{
1636 CheckComArgOutPointerValid(aHardDisk);
1637
1638 AutoCaller autoCaller(this);
1639 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1640
1641 /* we don't access non-const data members so no need to lock */
1642
1643 Utf8Str format(aFormat);
1644 if (format.isEmpty())
1645 getDefaultHardDiskFormat(format);
1646
1647 ComObjPtr<Medium> hardDisk;
1648 hardDisk.createObject();
1649 HRESULT rc = hardDisk->init(this,
1650 format,
1651 aLocation,
1652 Guid::Empty, // media registry: none yet
1653 NULL /* pllRegistriesThatNeedSaving */);
1654
1655 if (SUCCEEDED(rc))
1656 hardDisk.queryInterfaceTo(aHardDisk);
1657
1658 return rc;
1659}
1660
1661STDMETHODIMP VirtualBox::OpenMedium(IN_BSTR aLocation,
1662 DeviceType_T deviceType,
1663 AccessMode_T accessMode,
1664 BOOL fForceNewUuid,
1665 IMedium **aMedium)
1666{
1667 CheckComArgStrNotEmptyOrNull(aLocation);
1668 CheckComArgOutSafeArrayPointerValid(aMedium);
1669
1670 AutoCaller autoCaller(this);
1671 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1672
1673 ComObjPtr<Medium> pMedium;
1674
1675 /* we don't access non-const data members so no need to lock */
1676
1677 // check if the device type is correct, and see if a medium for the
1678 // given path has already initialized; if so, return that
1679 switch (deviceType)
1680 {
1681 case DeviceType_HardDisk:
1682 findHardDiskByLocation(aLocation,
1683 false, /* aSetError */
1684 &pMedium);
1685 break;
1686
1687 case DeviceType_Floppy:
1688 case DeviceType_DVD:
1689 findDVDOrFloppyImage(deviceType,
1690 NULL, /* guid */
1691 aLocation,
1692 false, /* aSetError */
1693 &pMedium);
1694
1695 // enforce read-only for DVDs even if caller specified ReadWrite
1696 if (deviceType == DeviceType_DVD)
1697 accessMode = AccessMode_ReadOnly;
1698 break;
1699
1700 default:
1701 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy");
1702 }
1703
1704 HRESULT rc = S_OK;
1705
1706 if (pMedium.isNull())
1707 {
1708 pMedium.createObject();
1709 rc = pMedium->init(this,
1710 aLocation,
1711 (accessMode == AccessMode_ReadWrite) ? Medium::OpenReadWrite : Medium::OpenReadOnly,
1712 fForceNewUuid,
1713 deviceType);
1714
1715 if (SUCCEEDED(rc))
1716 {
1717 AutoWriteLock treeLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1718
1719 switch (deviceType)
1720 {
1721 case DeviceType_HardDisk:
1722 rc = registerHardDisk(pMedium, NULL /* pllRegistriesThatNeedSaving */);
1723 break;
1724
1725 case DeviceType_DVD:
1726 case DeviceType_Floppy:
1727 rc = registerImage(pMedium,
1728 deviceType,
1729 NULL /* pllRegistriesThatNeedSaving */);
1730 break;
1731 }
1732
1733 treeLock.release();
1734
1735 /* Note that it's important to call uninit() on failure to register
1736 * because the differencing hard disk would have been already associated
1737 * with the parent and this association needs to be broken. */
1738
1739 if (FAILED(rc))
1740 pMedium->uninit();
1741 }
1742 }
1743
1744 if (SUCCEEDED(rc))
1745 pMedium.queryInterfaceTo(aMedium);
1746
1747 return rc;
1748}
1749
1750STDMETHODIMP VirtualBox::FindMedium(IN_BSTR aLocation,
1751 DeviceType_T aDeviceType,
1752 IMedium **aMedium)
1753{
1754 CheckComArgStrNotEmptyOrNull(aLocation);
1755 CheckComArgOutSafeArrayPointerValid(aMedium);
1756
1757 AutoCaller autoCaller(this);
1758 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1759
1760 Guid id(aLocation);
1761 Utf8Str strLocation(aLocation);
1762
1763 HRESULT rc;
1764 ComObjPtr<Medium> pMedium;
1765
1766 switch (aDeviceType)
1767 {
1768 case DeviceType_HardDisk:
1769 if (!id.isEmpty())
1770 rc = findHardDiskById(id, true /* setError */, &pMedium);
1771 else
1772 rc = findHardDiskByLocation(strLocation, true /* setError */, &pMedium);
1773 break;
1774
1775 case DeviceType_Floppy:
1776 case DeviceType_DVD:
1777 if (!id.isEmpty())
1778 rc = findDVDOrFloppyImage(aDeviceType, &id, Utf8Str::Empty, true /* setError */, &pMedium);
1779 else
1780 rc = findDVDOrFloppyImage(aDeviceType, NULL, strLocation, true /* setError */, &pMedium);
1781 break;
1782
1783 default:
1784 return setError(E_INVALIDARG,
1785 tr("Invalid device type %d"), aDeviceType);
1786 }
1787
1788 /* the below will set *aHardDisk to NULL if hardDisk is null */
1789 pMedium.queryInterfaceTo(aMedium);
1790
1791 return rc;
1792}
1793
1794/** @note Locks this object for reading. */
1795STDMETHODIMP VirtualBox::GetGuestOSType(IN_BSTR aId, IGuestOSType **aType)
1796{
1797 CheckComArgNotNull(aType);
1798
1799 AutoCaller autoCaller(this);
1800 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1801
1802 *aType = NULL;
1803
1804 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1805 for (GuestOSTypesOList::iterator it = m->allGuestOSTypes.begin();
1806 it != m->allGuestOSTypes.end();
1807 ++it)
1808 {
1809 const Bstr &typeId = (*it)->id();
1810 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
1811 if (typeId.compare(aId, Bstr::CaseInsensitive) == 0)
1812 {
1813 (*it).queryInterfaceTo(aType);
1814 break;
1815 }
1816 }
1817
1818 return (*aType) ? S_OK :
1819 setError(E_INVALIDARG,
1820 tr("'%ls' is not a valid Guest OS type"),
1821 aId);
1822}
1823
1824STDMETHODIMP VirtualBox::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath,
1825 BOOL /* aWritable */, BOOL /* aAutoMount */)
1826{
1827 CheckComArgStrNotEmptyOrNull(aName);
1828 CheckComArgStrNotEmptyOrNull(aHostPath);
1829
1830 AutoCaller autoCaller(this);
1831 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1832
1833 return setError(E_NOTIMPL, "Not yet implemented");
1834}
1835
1836STDMETHODIMP VirtualBox::RemoveSharedFolder(IN_BSTR aName)
1837{
1838 CheckComArgStrNotEmptyOrNull(aName);
1839
1840 AutoCaller autoCaller(this);
1841 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1842
1843 return setError(E_NOTIMPL, "Not yet implemented");
1844}
1845
1846/**
1847 * @note Locks this object for reading.
1848 */
1849STDMETHODIMP VirtualBox::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
1850{
1851 using namespace settings;
1852
1853 if (ComSafeArrayOutIsNull(aKeys))
1854 return E_POINTER;
1855
1856 AutoCaller autoCaller(this);
1857 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1858
1859 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1860
1861 com::SafeArray<BSTR> saKeys(m->pMainConfigFile->mapExtraDataItems.size());
1862 int i = 0;
1863 for (StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.begin();
1864 it != m->pMainConfigFile->mapExtraDataItems.end();
1865 ++it, ++i)
1866 {
1867 const Utf8Str &strName = it->first; // the key
1868 strName.cloneTo(&saKeys[i]);
1869 }
1870 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
1871
1872 return S_OK;
1873}
1874
1875/**
1876 * @note Locks this object for reading.
1877 */
1878STDMETHODIMP VirtualBox::GetExtraData(IN_BSTR aKey,
1879 BSTR *aValue)
1880{
1881 CheckComArgStrNotEmptyOrNull(aKey);
1882 CheckComArgNotNull(aValue);
1883
1884 AutoCaller autoCaller(this);
1885 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1886
1887 /* start with nothing found */
1888 Utf8Str strKey(aKey);
1889 Bstr bstrResult;
1890
1891 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1892 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1893 // found:
1894 bstrResult = it->second; // source is a Utf8Str
1895
1896 /* return the result to caller (may be empty) */
1897 bstrResult.cloneTo(aValue);
1898
1899 return S_OK;
1900}
1901
1902/**
1903 * @note Locks this object for writing.
1904 */
1905STDMETHODIMP VirtualBox::SetExtraData(IN_BSTR aKey,
1906 IN_BSTR aValue)
1907{
1908 CheckComArgStrNotEmptyOrNull(aKey);
1909
1910 AutoCaller autoCaller(this);
1911 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1912
1913 Utf8Str strKey(aKey);
1914 Utf8Str strValue(aValue);
1915 Utf8Str strOldValue; // empty
1916
1917 // locking note: we only hold the read lock briefly to look up the old value,
1918 // then release it and call the onExtraCanChange callbacks. There is a small
1919 // chance of a race insofar as the callback might be called twice if two callers
1920 // change the same key at the same time, but that's a much better solution
1921 // than the deadlock we had here before. The actual changing of the extradata
1922 // is then performed under the write lock and race-free.
1923
1924 // look up the old value first; if nothing has changed then we need not do anything
1925 {
1926 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
1927 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1928 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1929 strOldValue = it->second;
1930 }
1931
1932 bool fChanged;
1933 if ((fChanged = (strOldValue != strValue)))
1934 {
1935 // ask for permission from all listeners outside the locks;
1936 // onExtraDataCanChange() only briefly requests the VirtualBox
1937 // lock to copy the list of callbacks to invoke
1938 Bstr error;
1939 Bstr bstrValue(aValue);
1940
1941 if (!onExtraDataCanChange(Guid::Empty, aKey, bstrValue.raw(), error))
1942 {
1943 const char *sep = error.isEmpty() ? "" : ": ";
1944 CBSTR err = error.raw();
1945 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
1946 sep, err));
1947 return setError(E_ACCESSDENIED,
1948 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
1949 aKey,
1950 bstrValue.raw(),
1951 sep,
1952 err);
1953 }
1954
1955 // data is changing and change not vetoed: then write it out under the lock
1956
1957 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1958
1959 if (strValue.isEmpty())
1960 m->pMainConfigFile->mapExtraDataItems.erase(strKey);
1961 else
1962 m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
1963 // creates a new key if needed
1964
1965 /* save settings on success */
1966 HRESULT rc = saveSettings();
1967 if (FAILED(rc)) return rc;
1968 }
1969
1970 // fire notification outside the lock
1971 if (fChanged)
1972 onExtraDataChange(Guid::Empty, aKey, aValue);
1973
1974 return S_OK;
1975}
1976
1977// public methods only for internal purposes
1978/////////////////////////////////////////////////////////////////////////////
1979
1980#ifdef DEBUG
1981void VirtualBox::dumpAllBackRefs()
1982{
1983 {
1984 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1985 for (MediaList::const_iterator mt = m->allHardDisks.begin();
1986 mt != m->allHardDisks.end();
1987 ++mt)
1988 {
1989 ComObjPtr<Medium> pMedium = *mt;
1990 pMedium->dumpBackRefs();
1991 }
1992 }
1993 {
1994 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1995 for (MediaList::const_iterator mt = m->allDVDImages.begin();
1996 mt != m->allDVDImages.end();
1997 ++mt)
1998 {
1999 ComObjPtr<Medium> pMedium = *mt;
2000 pMedium->dumpBackRefs();
2001 }
2002 }
2003}
2004#endif
2005
2006/**
2007 * Posts an event to the event queue that is processed asynchronously
2008 * on a dedicated thread.
2009 *
2010 * Posting events to the dedicated event queue is useful to perform secondary
2011 * actions outside any object locks -- for example, to iterate over a list
2012 * of callbacks and inform them about some change caused by some object's
2013 * method call.
2014 *
2015 * @param event event to post; must have been allocated using |new|, will
2016 * be deleted automatically by the event thread after processing
2017 *
2018 * @note Doesn't lock any object.
2019 */
2020HRESULT VirtualBox::postEvent(Event *event)
2021{
2022 AssertReturn(event, E_FAIL);
2023
2024 HRESULT rc;
2025 AutoCaller autoCaller(this);
2026 if (SUCCEEDED((rc = autoCaller.rc())))
2027 {
2028 if (autoCaller.state() != Ready)
2029 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
2030 autoCaller.state()));
2031 // return S_OK
2032 else if ( (m->pAsyncEventQ)
2033 && (m->pAsyncEventQ->postEvent(event))
2034 )
2035 return S_OK;
2036 else
2037 rc = E_FAIL;
2038 }
2039
2040 // in any event of failure, we must clean up here, or we'll leak;
2041 // the caller has allocated the object using new()
2042 delete event;
2043 return rc;
2044}
2045
2046/**
2047 * Adds a progress to the global collection of pending operations.
2048 * Usually gets called upon progress object initialization.
2049 *
2050 * @param aProgress Operation to add to the collection.
2051 *
2052 * @note Doesn't lock objects.
2053 */
2054HRESULT VirtualBox::addProgress(IProgress *aProgress)
2055{
2056 CheckComArgNotNull(aProgress);
2057
2058 AutoCaller autoCaller(this);
2059 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2060
2061 Bstr id;
2062 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
2063 AssertComRCReturnRC(rc);
2064
2065 /* protect mProgressOperations */
2066 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2067
2068 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
2069 return S_OK;
2070}
2071
2072/**
2073 * Removes the progress from the global collection of pending operations.
2074 * Usually gets called upon progress completion.
2075 *
2076 * @param aId UUID of the progress operation to remove
2077 *
2078 * @note Doesn't lock objects.
2079 */
2080HRESULT VirtualBox::removeProgress(IN_GUID aId)
2081{
2082 AutoCaller autoCaller(this);
2083 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2084
2085 ComPtr<IProgress> progress;
2086
2087 /* protect mProgressOperations */
2088 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2089
2090 size_t cnt = m->mapProgressOperations.erase(aId);
2091 Assert(cnt == 1);
2092 NOREF(cnt);
2093
2094 return S_OK;
2095}
2096
2097#ifdef RT_OS_WINDOWS
2098
2099struct StartSVCHelperClientData
2100{
2101 ComObjPtr<VirtualBox> that;
2102 ComObjPtr<Progress> progress;
2103 bool privileged;
2104 VirtualBox::SVCHelperClientFunc func;
2105 void *user;
2106};
2107
2108/**
2109 * Helper method that starts a worker thread that:
2110 * - creates a pipe communication channel using SVCHlpClient;
2111 * - starts an SVC Helper process that will inherit this channel;
2112 * - executes the supplied function by passing it the created SVCHlpClient
2113 * and opened instance to communicate to the Helper process and the given
2114 * Progress object.
2115 *
2116 * The user function is supposed to communicate to the helper process
2117 * using the \a aClient argument to do the requested job and optionally expose
2118 * the progress through the \a aProgress object. The user function should never
2119 * call notifyComplete() on it: this will be done automatically using the
2120 * result code returned by the function.
2121 *
2122 * Before the user function is started, the communication channel passed to
2123 * the \a aClient argument is fully set up, the function should start using
2124 * its write() and read() methods directly.
2125 *
2126 * The \a aVrc parameter of the user function may be used to return an error
2127 * code if it is related to communication errors (for example, returned by
2128 * the SVCHlpClient members when they fail). In this case, the correct error
2129 * message using this value will be reported to the caller. Note that the
2130 * value of \a aVrc is inspected only if the user function itself returns
2131 * success.
2132 *
2133 * If a failure happens anywhere before the user function would be normally
2134 * called, it will be called anyway in special "cleanup only" mode indicated
2135 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
2136 * all the function is supposed to do is to cleanup its aUser argument if
2137 * necessary (it's assumed that the ownership of this argument is passed to
2138 * the user function once #startSVCHelperClient() returns a success, thus
2139 * making it responsible for the cleanup).
2140 *
2141 * After the user function returns, the thread will send the SVCHlpMsg::Null
2142 * message to indicate a process termination.
2143 *
2144 * @param aPrivileged |true| to start the SVC Helper process as a privileged
2145 * user that can perform administrative tasks
2146 * @param aFunc user function to run
2147 * @param aUser argument to the user function
2148 * @param aProgress progress object that will track operation completion
2149 *
2150 * @note aPrivileged is currently ignored (due to some unsolved problems in
2151 * Vista) and the process will be started as a normal (unprivileged)
2152 * process.
2153 *
2154 * @note Doesn't lock anything.
2155 */
2156HRESULT VirtualBox::startSVCHelperClient(bool aPrivileged,
2157 SVCHelperClientFunc aFunc,
2158 void *aUser, Progress *aProgress)
2159{
2160 AssertReturn(aFunc, E_POINTER);
2161 AssertReturn(aProgress, E_POINTER);
2162
2163 AutoCaller autoCaller(this);
2164 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2165
2166 /* create the SVCHelperClientThread() argument */
2167 std::auto_ptr <StartSVCHelperClientData>
2168 d(new StartSVCHelperClientData());
2169 AssertReturn(d.get(), E_OUTOFMEMORY);
2170
2171 d->that = this;
2172 d->progress = aProgress;
2173 d->privileged = aPrivileged;
2174 d->func = aFunc;
2175 d->user = aUser;
2176
2177 RTTHREAD tid = NIL_RTTHREAD;
2178 int vrc = RTThreadCreate(&tid, SVCHelperClientThread,
2179 static_cast <void *>(d.get()),
2180 0, RTTHREADTYPE_MAIN_WORKER,
2181 RTTHREADFLAGS_WAITABLE, "SVCHelper");
2182 if (RT_FAILURE(vrc))
2183 return setError(E_FAIL, "Could not create SVCHelper thread (%Rrc)", vrc);
2184
2185 /* d is now owned by SVCHelperClientThread(), so release it */
2186 d.release();
2187
2188 return S_OK;
2189}
2190
2191/**
2192 * Worker thread for startSVCHelperClient().
2193 */
2194/* static */
2195DECLCALLBACK(int)
2196VirtualBox::SVCHelperClientThread(RTTHREAD aThread, void *aUser)
2197{
2198 LogFlowFuncEnter();
2199
2200 std::auto_ptr<StartSVCHelperClientData>
2201 d(static_cast<StartSVCHelperClientData*>(aUser));
2202
2203 HRESULT rc = S_OK;
2204 bool userFuncCalled = false;
2205
2206 do
2207 {
2208 AssertBreakStmt(d.get(), rc = E_POINTER);
2209 AssertReturn(!d->progress.isNull(), E_POINTER);
2210
2211 /* protect VirtualBox from uninitialization */
2212 AutoCaller autoCaller(d->that);
2213 if (!autoCaller.isOk())
2214 {
2215 /* it's too late */
2216 rc = autoCaller.rc();
2217 break;
2218 }
2219
2220 int vrc = VINF_SUCCESS;
2221
2222 Guid id;
2223 id.create();
2224 SVCHlpClient client;
2225 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2226 id.raw()).c_str());
2227 if (RT_FAILURE(vrc))
2228 {
2229 rc = d->that->setError(E_FAIL,
2230 tr("Could not create the communication channel (%Rrc)"), vrc);
2231 break;
2232 }
2233
2234 /* get the path to the executable */
2235 char exePathBuf[RTPATH_MAX];
2236 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2237 if (!exePath)
2238 {
2239 rc = d->that->setError(E_FAIL, tr("Cannot get executable name"));
2240 break;
2241 }
2242
2243 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2244
2245 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2246
2247 RTPROCESS pid = NIL_RTPROCESS;
2248
2249 if (d->privileged)
2250 {
2251 /* Attempt to start a privileged process using the Run As dialog */
2252
2253 Bstr file = exePath;
2254 Bstr parameters = argsStr;
2255
2256 SHELLEXECUTEINFO shExecInfo;
2257
2258 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2259
2260 shExecInfo.fMask = NULL;
2261 shExecInfo.hwnd = NULL;
2262 shExecInfo.lpVerb = L"runas";
2263 shExecInfo.lpFile = file.raw();
2264 shExecInfo.lpParameters = parameters.raw();
2265 shExecInfo.lpDirectory = NULL;
2266 shExecInfo.nShow = SW_NORMAL;
2267 shExecInfo.hInstApp = NULL;
2268
2269 if (!ShellExecuteEx(&shExecInfo))
2270 {
2271 int vrc2 = RTErrConvertFromWin32(GetLastError());
2272 /* hide excessive details in case of a frequent error
2273 * (pressing the Cancel button to close the Run As dialog) */
2274 if (vrc2 == VERR_CANCELLED)
2275 rc = d->that->setError(E_FAIL,
2276 tr("Operation canceled by the user"));
2277 else
2278 rc = d->that->setError(E_FAIL,
2279 tr("Could not launch a privileged process '%s' (%Rrc)"),
2280 exePath, vrc2);
2281 break;
2282 }
2283 }
2284 else
2285 {
2286 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2287 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2288 if (RT_FAILURE(vrc))
2289 {
2290 rc = d->that->setError(E_FAIL,
2291 tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2292 break;
2293 }
2294 }
2295
2296 /* wait for the client to connect */
2297 vrc = client.connect();
2298 if (RT_SUCCESS(vrc))
2299 {
2300 /* start the user supplied function */
2301 rc = d->func(&client, d->progress, d->user, &vrc);
2302 userFuncCalled = true;
2303 }
2304
2305 /* send the termination signal to the process anyway */
2306 {
2307 int vrc2 = client.write(SVCHlpMsg::Null);
2308 if (RT_SUCCESS(vrc))
2309 vrc = vrc2;
2310 }
2311
2312 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2313 {
2314 rc = d->that->setError(E_FAIL,
2315 tr("Could not operate the communication channel (%Rrc)"), vrc);
2316 break;
2317 }
2318 }
2319 while (0);
2320
2321 if (FAILED(rc) && !userFuncCalled)
2322 {
2323 /* call the user function in the "cleanup only" mode
2324 * to let it free resources passed to in aUser */
2325 d->func(NULL, NULL, d->user, NULL);
2326 }
2327
2328 d->progress->notifyComplete(rc);
2329
2330 LogFlowFuncLeave();
2331 return 0;
2332}
2333
2334#endif /* RT_OS_WINDOWS */
2335
2336/**
2337 * Sends a signal to the client watcher thread to rescan the set of machines
2338 * that have open sessions.
2339 *
2340 * @note Doesn't lock anything.
2341 */
2342void VirtualBox::updateClientWatcher()
2343{
2344 AutoCaller autoCaller(this);
2345 AssertComRCReturnVoid(autoCaller.rc());
2346
2347 AssertReturnVoid(m->threadClientWatcher != NIL_RTTHREAD);
2348
2349 /* sent an update request */
2350#if defined(RT_OS_WINDOWS)
2351 ::SetEvent(m->updateReq);
2352#elif defined(RT_OS_OS2)
2353 RTSemEventSignal(m->updateReq);
2354#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
2355 RTSemEventSignal(m->updateReq);
2356#else
2357# error "Port me!"
2358#endif
2359}
2360
2361/**
2362 * Adds the given child process ID to the list of processes to be reaped.
2363 * This call should be followed by #updateClientWatcher() to take the effect.
2364 */
2365void VirtualBox::addProcessToReap(RTPROCESS pid)
2366{
2367 AutoCaller autoCaller(this);
2368 AssertComRCReturnVoid(autoCaller.rc());
2369
2370 /// @todo (dmik) Win32?
2371#ifndef RT_OS_WINDOWS
2372 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2373 m->llProcesses.push_back(pid);
2374#endif
2375}
2376
2377/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2378struct MachineEvent : public VirtualBox::CallbackEvent
2379{
2380 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
2381 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2382 , mBool(aBool)
2383 { }
2384
2385 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
2386 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2387 , mState(aState)
2388 {}
2389
2390 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2391 {
2392 switch (mWhat)
2393 {
2394 case VBoxEventType_OnMachineDataChanged:
2395 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2396 break;
2397
2398 case VBoxEventType_OnMachineStateChanged:
2399 aEvDesc.init(aSource, mWhat, id.raw(), mState);
2400 break;
2401
2402 case VBoxEventType_OnMachineRegistered:
2403 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2404 break;
2405
2406 default:
2407 AssertFailedReturn(S_OK);
2408 }
2409 return S_OK;
2410 }
2411
2412 Bstr id;
2413 MachineState_T mState;
2414 BOOL mBool;
2415};
2416
2417/**
2418 * @note Doesn't lock any object.
2419 */
2420void VirtualBox::onMachineStateChange(const Guid &aId, MachineState_T aState)
2421{
2422 postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
2423}
2424
2425/**
2426 * @note Doesn't lock any object.
2427 */
2428void VirtualBox::onMachineDataChange(const Guid &aId, BOOL aTemporary)
2429{
2430 postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
2431}
2432
2433/**
2434 * @note Locks this object for reading.
2435 */
2436BOOL VirtualBox::onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
2437 Bstr &aError)
2438{
2439 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
2440 aId.toString().c_str(), aKey, aValue));
2441
2442 AutoCaller autoCaller(this);
2443 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2444
2445 BOOL allowChange = TRUE;
2446 Bstr id = aId.toUtf16();
2447
2448 VBoxEventDesc evDesc;
2449 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
2450 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
2451 //Assert(fDelivered);
2452 if (fDelivered)
2453 {
2454 ComPtr<IEvent> aEvent;
2455 evDesc.getEvent(aEvent.asOutParam());
2456 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
2457 Assert(aCanChangeEvent);
2458 BOOL fVetoed = FALSE;
2459 aCanChangeEvent->IsVetoed(&fVetoed);
2460 allowChange = !fVetoed;
2461
2462 if (!allowChange)
2463 {
2464 SafeArray<BSTR> aVetos;
2465 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
2466 if (aVetos.size() > 0)
2467 aError = aVetos[0];
2468 }
2469 }
2470 else
2471 allowChange = TRUE;
2472
2473 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
2474 return allowChange;
2475}
2476
2477/** Event for onExtraDataChange() */
2478struct ExtraDataEvent : public VirtualBox::CallbackEvent
2479{
2480 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
2481 IN_BSTR aKey, IN_BSTR aVal)
2482 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
2483 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
2484 {}
2485
2486 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2487 {
2488 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
2489 }
2490
2491 Bstr machineId, key, val;
2492};
2493
2494/**
2495 * @note Doesn't lock any object.
2496 */
2497void VirtualBox::onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
2498{
2499 postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
2500}
2501
2502/**
2503 * @note Doesn't lock any object.
2504 */
2505void VirtualBox::onMachineRegistered(const Guid &aId, BOOL aRegistered)
2506{
2507 postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
2508}
2509
2510/** Event for onSessionStateChange() */
2511struct SessionEvent : public VirtualBox::CallbackEvent
2512{
2513 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2514 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
2515 , machineId(aMachineId.toUtf16()), sessionState(aState)
2516 {}
2517
2518 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2519 {
2520 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
2521 }
2522 Bstr machineId;
2523 SessionState_T sessionState;
2524};
2525
2526/**
2527 * @note Doesn't lock any object.
2528 */
2529void VirtualBox::onSessionStateChange(const Guid &aId, SessionState_T aState)
2530{
2531 postEvent(new SessionEvent(this, aId, aState));
2532}
2533
2534/** Event for onSnapshotTaken(), onSnapshotDeleted() and onSnapshotChange() */
2535struct SnapshotEvent : public VirtualBox::CallbackEvent
2536{
2537 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2538 VBoxEventType_T aWhat)
2539 : CallbackEvent(aVB, aWhat)
2540 , machineId(aMachineId), snapshotId(aSnapshotId)
2541 {}
2542
2543 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2544 {
2545 return aEvDesc.init(aSource, VBoxEventType_OnSnapshotTaken,
2546 machineId.toUtf16().raw(), snapshotId.toUtf16().raw());
2547 }
2548
2549 Guid machineId;
2550 Guid snapshotId;
2551};
2552
2553/**
2554 * @note Doesn't lock any object.
2555 */
2556void VirtualBox::onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
2557{
2558 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2559 VBoxEventType_OnSnapshotTaken));
2560}
2561
2562/**
2563 * @note Doesn't lock any object.
2564 */
2565void VirtualBox::onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
2566{
2567 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2568 VBoxEventType_OnSnapshotDeleted));
2569}
2570
2571/**
2572 * @note Doesn't lock any object.
2573 */
2574void VirtualBox::onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
2575{
2576 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2577 VBoxEventType_OnSnapshotChanged));
2578}
2579
2580/** Event for onGuestPropertyChange() */
2581struct GuestPropertyEvent : public VirtualBox::CallbackEvent
2582{
2583 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
2584 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
2585 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
2586 machineId(aMachineId),
2587 name(aName),
2588 value(aValue),
2589 flags(aFlags)
2590 {}
2591
2592 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2593 {
2594 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
2595 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
2596 }
2597
2598 Guid machineId;
2599 Bstr name, value, flags;
2600};
2601
2602/**
2603 * @note Doesn't lock any object.
2604 */
2605void VirtualBox::onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
2606 IN_BSTR aValue, IN_BSTR aFlags)
2607{
2608 postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
2609}
2610
2611/** Event for onMachineUninit(), this is not a CallbackEvent */
2612class MachineUninitEvent : public Event
2613{
2614public:
2615
2616 MachineUninitEvent(VirtualBox *aVirtualBox, Machine *aMachine)
2617 : mVirtualBox(aVirtualBox), mMachine(aMachine)
2618 {
2619 Assert(aVirtualBox);
2620 Assert(aMachine);
2621 }
2622
2623 void *handler()
2624 {
2625#ifdef VBOX_WITH_RESOURCE_USAGE_API
2626 /* Handle unregistering metrics here, as it is not vital to get
2627 * it done immediately. It reduces the number of locks needed and
2628 * the lock contention in SessionMachine::uninit. */
2629 {
2630 AutoWriteLock mLock(mMachine COMMA_LOCKVAL_SRC_POS);
2631 mMachine->unregisterMetrics(mVirtualBox->performanceCollector(), mMachine);
2632 }
2633#endif /* VBOX_WITH_RESOURCE_USAGE_API */
2634
2635 return NULL;
2636 }
2637
2638private:
2639
2640 /**
2641 * Note that this is a weak ref -- the CallbackEvent handler thread
2642 * is bound to the lifetime of the VirtualBox instance, so it's safe.
2643 */
2644 VirtualBox *mVirtualBox;
2645
2646 /** Reference to the machine object. */
2647 ComObjPtr<Machine> mMachine;
2648};
2649
2650/**
2651 * Trigger internal event. This isn't meant to be signalled to clients.
2652 * @note Doesn't lock any object.
2653 */
2654void VirtualBox::onMachineUninit(Machine *aMachine)
2655{
2656 postEvent(new MachineUninitEvent(this, aMachine));
2657}
2658
2659/**
2660 * @note Doesn't lock any object.
2661 */
2662void VirtualBox::onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
2663 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
2664 IN_BSTR aGuestIp, uint16_t aGuestPort)
2665{
2666 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
2667 aHostPort, aGuestIp, aGuestPort);
2668}
2669
2670/**
2671 * @note Locks this object for reading.
2672 */
2673ComObjPtr<GuestOSType> VirtualBox::getUnknownOSType()
2674{
2675 ComObjPtr<GuestOSType> type;
2676 AutoCaller autoCaller(this);
2677 AssertComRCReturn(autoCaller.rc(), type);
2678
2679 /* unknown type must always be the first */
2680 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
2681
2682 return m->allGuestOSTypes.front();
2683}
2684
2685/**
2686 * Returns the list of opened machines (machines having direct sessions opened
2687 * by client processes) and optionally the list of direct session controls.
2688 *
2689 * @param aMachines Where to put opened machines (will be empty if none).
2690 * @param aControls Where to put direct session controls (optional).
2691 *
2692 * @note The returned lists contain smart pointers. So, clear it as soon as
2693 * it becomes no more necessary to release instances.
2694 *
2695 * @note It can be possible that a session machine from the list has been
2696 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
2697 * when accessing unprotected data directly.
2698 *
2699 * @note Locks objects for reading.
2700 */
2701void VirtualBox::getOpenedMachines(SessionMachinesList &aMachines,
2702 InternalControlList *aControls /*= NULL*/)
2703{
2704 AutoCaller autoCaller(this);
2705 AssertComRCReturnVoid(autoCaller.rc());
2706
2707 aMachines.clear();
2708 if (aControls)
2709 aControls->clear();
2710
2711 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2712
2713 for (MachinesOList::iterator it = m->allMachines.begin();
2714 it != m->allMachines.end();
2715 ++it)
2716 {
2717 ComObjPtr<SessionMachine> sm;
2718 ComPtr<IInternalSessionControl> ctl;
2719 if ((*it)->isSessionOpen(sm, &ctl))
2720 {
2721 aMachines.push_back(sm);
2722 if (aControls)
2723 aControls->push_back(ctl);
2724 }
2725 }
2726}
2727
2728/**
2729 * Searches for a machine object with the given ID in the collection
2730 * of registered machines.
2731 *
2732 * @param aId Machine UUID to look for.
2733 * @param aPermitInaccessible If true, inaccessible machines will be found;
2734 * if false, this will fail if the given machine is inaccessible.
2735 * @param aSetError If true, set errorinfo if the machine is not found.
2736 * @param aMachine Returned machine, if found.
2737 * @return
2738 */
2739HRESULT VirtualBox::findMachine(const Guid &aId,
2740 bool fPermitInaccessible,
2741 bool aSetError,
2742 ComObjPtr<Machine> *aMachine /* = NULL */)
2743{
2744 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
2745
2746 AutoCaller autoCaller(this);
2747 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2748
2749 {
2750 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2751
2752 for (MachinesOList::iterator it = m->allMachines.begin();
2753 it != m->allMachines.end();
2754 ++it)
2755 {
2756 ComObjPtr<Machine> pMachine2 = *it;
2757
2758 if (!fPermitInaccessible)
2759 {
2760 // skip inaccessible machines
2761 AutoCaller machCaller(pMachine2);
2762 if (FAILED(machCaller.rc()))
2763 continue;
2764 }
2765
2766 if (pMachine2->getId() == aId)
2767 {
2768 rc = S_OK;
2769 if (aMachine)
2770 *aMachine = pMachine2;
2771 break;
2772 }
2773 }
2774 }
2775
2776 if (aSetError && FAILED(rc))
2777 rc = setError(rc,
2778 tr("Could not find a registered machine with UUID {%RTuuid}"),
2779 aId.raw());
2780
2781 return rc;
2782}
2783
2784/**
2785 * Searches for a Medium object with the given ID in the list of registered
2786 * hard disks.
2787 *
2788 * @param aId ID of the hard disk. Must not be empty.
2789 * @param aSetError If @c true , the appropriate error info is set in case
2790 * when the hard disk is not found.
2791 * @param aHardDisk Where to store the found hard disk object (can be NULL).
2792 *
2793 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
2794 *
2795 * @note Locks the media tree for reading.
2796 */
2797HRESULT VirtualBox::findHardDiskById(const Guid &id,
2798 bool aSetError,
2799 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
2800{
2801 AssertReturn(!id.isEmpty(), E_INVALIDARG);
2802
2803 // we use the hard disks map, but it is protected by the
2804 // hard disk _list_ lock handle
2805 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2806
2807 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
2808 if (it != m->mapHardDisks.end())
2809 {
2810 if (aHardDisk)
2811 *aHardDisk = (*it).second;
2812 return S_OK;
2813 }
2814
2815 if (aSetError)
2816 return setError(VBOX_E_OBJECT_NOT_FOUND,
2817 tr("Could not find an open hard disk with UUID {%RTuuid}"),
2818 id.raw());
2819
2820 return VBOX_E_OBJECT_NOT_FOUND;
2821}
2822
2823/**
2824 * Searches for a Medium object with the given ID or location in the list of
2825 * registered hard disks. If both ID and location are specified, the first
2826 * object that matches either of them (not necessarily both) is returned.
2827 *
2828 * @param aLocation Full location specification. Must not be empty.
2829 * @param aSetError If @c true , the appropriate error info is set in case
2830 * when the hard disk is not found.
2831 * @param aHardDisk Where to store the found hard disk object (can be NULL).
2832 *
2833 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
2834 *
2835 * @note Locks the media tree for reading.
2836 */
2837HRESULT VirtualBox::findHardDiskByLocation(const Utf8Str &strLocation,
2838 bool aSetError,
2839 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
2840{
2841 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
2842
2843 // we use the hard disks map, but it is protected by the
2844 // hard disk _list_ lock handle
2845 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2846
2847 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
2848 it != m->mapHardDisks.end();
2849 ++it)
2850 {
2851 const ComObjPtr<Medium> &pHD = (*it).second;
2852
2853 AutoCaller autoCaller(pHD);
2854 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2855 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2856
2857 Utf8Str strLocationFull = pHD->getLocationFull();
2858
2859 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
2860 {
2861 if (aHardDisk)
2862 *aHardDisk = pHD;
2863 return S_OK;
2864 }
2865 }
2866
2867 if (aSetError)
2868 return setError(VBOX_E_OBJECT_NOT_FOUND,
2869 tr("Could not find an open hard disk with location '%s'"),
2870 strLocation.c_str());
2871
2872 return VBOX_E_OBJECT_NOT_FOUND;
2873}
2874
2875/**
2876 * Searches for a Medium object with the given ID or location in the list of
2877 * registered DVD or floppy images, depending on the @a mediumType argument.
2878 * If both ID and file path are specified, the first object that matches either
2879 * of them (not necessarily both) is returned.
2880 *
2881 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
2882 * @param aId ID of the image file (unused when NULL).
2883 * @param aLocation Full path to the image file (unused when NULL).
2884 * @param aSetError If @c true, the appropriate error info is set in case when
2885 * the image is not found.
2886 * @param aImage Where to store the found image object (can be NULL).
2887 *
2888 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
2889 *
2890 * @note Locks the media tree for reading.
2891 */
2892HRESULT VirtualBox::findDVDOrFloppyImage(DeviceType_T mediumType,
2893 const Guid *aId,
2894 const Utf8Str &aLocation,
2895 bool aSetError,
2896 ComObjPtr<Medium> *aImage /* = NULL */)
2897{
2898 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
2899
2900 Utf8Str location;
2901 if (!aLocation.isEmpty())
2902 {
2903 int vrc = calculateFullPath(aLocation, location);
2904 if (RT_FAILURE(vrc))
2905 return setError(VBOX_E_FILE_ERROR,
2906 tr("Invalid image file location '%s' (%Rrc)"),
2907 aLocation.c_str(),
2908 vrc);
2909 }
2910
2911 MediaOList *pMediaList;
2912
2913 switch (mediumType)
2914 {
2915 case DeviceType_DVD:
2916 pMediaList = &m->allDVDImages;
2917 break;
2918
2919 case DeviceType_Floppy:
2920 pMediaList = &m->allFloppyImages;
2921 break;
2922
2923 default:
2924 return E_INVALIDARG;
2925 }
2926
2927 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
2928
2929 bool found = false;
2930
2931 for (MediaList::const_iterator it = pMediaList->begin();
2932 it != pMediaList->end();
2933 ++it)
2934 {
2935 // no AutoCaller, registered image life time is bound to this
2936 Medium *pMedium = *it;
2937 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
2938 const Utf8Str &strLocationFull = pMedium->getLocationFull();
2939
2940 found = ( aId
2941 && pMedium->getId() == *aId)
2942 || ( !aLocation.isEmpty()
2943 && RTPathCompare(location.c_str(),
2944 strLocationFull.c_str()) == 0);
2945 if (found)
2946 {
2947 if (pMedium->getDeviceType() != mediumType)
2948 {
2949 if (mediumType == DeviceType_DVD)
2950 return setError(E_INVALIDARG,
2951 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
2952 else
2953 return setError(E_INVALIDARG,
2954 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
2955 }
2956
2957 if (aImage)
2958 *aImage = pMedium;
2959 break;
2960 }
2961 }
2962
2963 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
2964
2965 if (aSetError && !found)
2966 {
2967 if (aId)
2968 setError(rc,
2969 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
2970 aId->raw(),
2971 m->strSettingsFilePath.c_str());
2972 else
2973 setError(rc,
2974 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
2975 aLocation.c_str(),
2976 m->strSettingsFilePath.c_str());
2977 }
2978
2979 return rc;
2980}
2981
2982/**
2983 * Searches for an IMedium object that represents the given UUID.
2984 *
2985 * If the UUID is empty (indicating an empty drive), this sets pMedium
2986 * to NULL and returns S_OK.
2987 *
2988 * If the UUID refers to a host drive of the given device type, this
2989 * sets pMedium to the object from the list in IHost and returns S_OK.
2990 *
2991 * If the UUID is an image file, this sets pMedium to the object that
2992 * findDVDOrFloppyImage() returned.
2993 *
2994 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
2995 *
2996 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
2997 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
2998 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
2999 * @param pMedium out: IMedium object found.
3000 * @return
3001 */
3002HRESULT VirtualBox::findRemoveableMedium(DeviceType_T mediumType,
3003 const Guid &uuid,
3004 bool fRefresh,
3005 bool aSetError,
3006 ComObjPtr<Medium> &pMedium)
3007{
3008 if (uuid.isEmpty())
3009 {
3010 // that's easy
3011 pMedium.setNull();
3012 return S_OK;
3013 }
3014
3015 // first search for host drive with that UUID
3016 HRESULT rc = m->pHost->findHostDriveById(mediumType,
3017 uuid,
3018 fRefresh,
3019 pMedium);
3020 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3021 // then search for an image with that UUID
3022 rc = findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3023
3024 return rc;
3025}
3026
3027HRESULT VirtualBox::findGuestOSType(const Bstr &bstrOSType,
3028 GuestOSType*& pGuestOSType)
3029{
3030 /* Look for a GuestOSType object */
3031 AssertMsg(m->allGuestOSTypes.size() != 0,
3032 ("Guest OS types array must be filled"));
3033
3034 if (bstrOSType.isEmpty())
3035 {
3036 pGuestOSType = NULL;
3037 return S_OK;
3038 }
3039
3040 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3041 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3042 it != m->allGuestOSTypes.end();
3043 ++it)
3044 {
3045 if ((*it)->id() == bstrOSType)
3046 {
3047 pGuestOSType = *it;
3048 return S_OK;
3049 }
3050 }
3051
3052 return setError(VBOX_E_OBJECT_NOT_FOUND,
3053 tr("Guest OS type '%ls' is invalid"),
3054 bstrOSType.raw());
3055}
3056
3057/**
3058 * Returns the constant pseudo-machine UUID that is used to identify the
3059 * global media registry.
3060 *
3061 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3062 * in which media registry it is saved (if any): this can either be a machine
3063 * UUID, if it's in a per-machine media registry, or this global ID.
3064 *
3065 * This UUID is only used to identify the VirtualBox object while VirtualBox
3066 * is running. It is a compile-time constant and not saved anywhere.
3067 *
3068 * @return
3069 */
3070const Guid& VirtualBox::getGlobalRegistryId() const
3071{
3072 return m->uuidMediaRegistry;
3073}
3074
3075const ComObjPtr<Host>& VirtualBox::host() const
3076{
3077 return m->pHost;
3078}
3079
3080SystemProperties* VirtualBox::getSystemProperties() const
3081{
3082 return m->pSystemProperties;
3083}
3084
3085#ifdef VBOX_WITH_EXTPACK
3086/**
3087 * Getter that SystemProperties and others can use to talk to the extension
3088 * pack manager.
3089 */
3090ExtPackManager* VirtualBox::getExtPackManager() const
3091{
3092 return m->ptrExtPackManager;
3093}
3094#endif
3095
3096#ifdef VBOX_WITH_RESOURCE_USAGE_API
3097const ComObjPtr<PerformanceCollector>& VirtualBox::performanceCollector() const
3098{
3099 return m->pPerformanceCollector;
3100}
3101#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3102
3103/**
3104 * Returns the default machine folder from the system properties
3105 * with proper locking.
3106 * @return
3107 */
3108void VirtualBox::getDefaultMachineFolder(Utf8Str &str) const
3109{
3110 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3111 str = m->pSystemProperties->m->strDefaultMachineFolder;
3112}
3113
3114/**
3115 * Returns the default hard disk format from the system properties
3116 * with proper locking.
3117 * @return
3118 */
3119void VirtualBox::getDefaultHardDiskFormat(Utf8Str &str) const
3120{
3121 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3122 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3123}
3124
3125const Utf8Str& VirtualBox::homeDir() const
3126{
3127 return m->strHomeDir;
3128}
3129
3130/**
3131 * Calculates the absolute path of the given path taking the VirtualBox home
3132 * directory as the current directory.
3133 *
3134 * @param aPath Path to calculate the absolute path for.
3135 * @param aResult Where to put the result (used only on success, can be the
3136 * same Utf8Str instance as passed in @a aPath).
3137 * @return IPRT result.
3138 *
3139 * @note Doesn't lock any object.
3140 */
3141int VirtualBox::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3142{
3143 AutoCaller autoCaller(this);
3144 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3145
3146 /* no need to lock since mHomeDir is const */
3147
3148 char folder[RTPATH_MAX];
3149 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3150 strPath.c_str(),
3151 folder,
3152 sizeof(folder));
3153 if (RT_SUCCESS(vrc))
3154 aResult = folder;
3155
3156 return vrc;
3157}
3158
3159/**
3160 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3161 * if it is a subdirectory thereof, or simply copying it otherwise.
3162 *
3163 * @param strSource Path to evalue and copy.
3164 * @param strTarget Buffer to receive target path.
3165 */
3166void VirtualBox::copyPathRelativeToConfig(const Utf8Str &strSource,
3167 Utf8Str &strTarget)
3168{
3169 AutoCaller autoCaller(this);
3170 AssertComRCReturnVoid(autoCaller.rc());
3171
3172 // no need to lock since mHomeDir is const
3173
3174 // use strTarget as a temporary buffer to hold the machine settings dir
3175 strTarget = m->strHomeDir;
3176 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3177 // is relative: then append what's left
3178 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3179 else
3180 // is not relative: then overwrite
3181 strTarget = strSource;
3182}
3183
3184// private methods
3185/////////////////////////////////////////////////////////////////////////////
3186
3187/**
3188 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3189 * location already registered.
3190 *
3191 * On return, sets @a aConflict to the string describing the conflicting medium,
3192 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3193 * either case. A failure is unexpected.
3194 *
3195 * @param aId UUID to check.
3196 * @param aLocation Location to check.
3197 * @param aConflict Where to return parameters of the conflicting medium.
3198 *
3199 * @note Locks the media tree and media objects for reading.
3200 */
3201HRESULT VirtualBox::checkMediaForConflicts(const Guid &aId,
3202 const Utf8Str &aLocation,
3203 Utf8Str &aConflict,
3204 bool &fIdentical)
3205{
3206 aConflict.setNull();
3207
3208 AssertReturn(!aId.isEmpty() && !aLocation.isEmpty(), E_FAIL);
3209
3210 AutoReadLock alock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3211
3212 HRESULT rc = S_OK;
3213
3214 aConflict.setNull();
3215 fIdentical = false;
3216
3217 ComObjPtr<Medium> pMediumFound;
3218 const char *pcszType = NULL;
3219
3220 if (!aId.isEmpty())
3221 rc = findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3222 if (FAILED(rc) && !aLocation.isEmpty())
3223 rc = findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3224 if (SUCCEEDED(rc))
3225 pcszType = tr("hard disk");
3226
3227 if (!pcszType)
3228 {
3229 rc = findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3230 if (SUCCEEDED(rc))
3231 pcszType = tr("CD/DVD image");
3232 }
3233
3234 if (!pcszType)
3235 {
3236 rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3237 if (SUCCEEDED(rc))
3238 pcszType = tr("floppy image");
3239 }
3240
3241 if (pcszType && pMediumFound)
3242 {
3243 /* Note: no AutoCaller since bound to this */
3244 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3245
3246 Utf8Str strLocFound = pMediumFound->getLocationFull();
3247 Guid idFound = pMediumFound->getId();
3248
3249 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3250 && (idFound == aId)
3251 )
3252 fIdentical = true;
3253
3254 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3255 pcszType,
3256 strLocFound.c_str(),
3257 idFound.raw());
3258 }
3259
3260 return S_OK;
3261}
3262
3263/**
3264 * Called from Machine::prepareSaveSettings() when it has detected
3265 * that a machine has been renamed. Such renames will require
3266 * updating the global media registry during the
3267 * VirtualBox::saveSettings() that follows later.
3268*
3269 * When a machine is renamed, there may well be media (in particular,
3270 * diff images for snapshots) in the global registry that will need
3271 * to have their paths updated. Before 3.2, Machine::saveSettings
3272 * used to call VirtualBox::saveSettings implicitly, which was both
3273 * unintuitive and caused locking order problems. Now, we remember
3274 * such pending name changes with this method so that
3275 * VirtualBox::saveSettings() can process them properly.
3276 */
3277void VirtualBox::rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3278 const Utf8Str &strNewConfigDir)
3279{
3280 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3281
3282 Data::PendingMachineRename pmr;
3283 pmr.strConfigDirOld = strOldConfigDir;
3284 pmr.strConfigDirNew = strNewConfigDir;
3285 m->llPendingMachineRenames.push_back(pmr);
3286}
3287
3288/**
3289 * Goes through all known media (hard disks, floppies and DVDs) and saves
3290 * those into the given settings::MediaRegistry structures whose registry
3291 * ID match the given UUID.
3292 *
3293 * Before actually writing to the structures, all media paths (not just the
3294 * ones for the given registry) are updated if machines have been renamed
3295 * since the last call.
3296 *
3297 * This gets called from two contexts:
3298 *
3299 * -- VirtualBox::saveSettings() with the UUID of the global registry
3300 * (VirtualBox::Data.uuidRegistry); this will save those media
3301 * which had been loaded from the global registry or have been
3302 * attached to a "legacy" machine which can't save its own registry;
3303 *
3304 * -- Machine::saveSettings() with the UUID of a machine, if a medium
3305 * has been attached to a machine created with VirtualBox 4.0 or later.
3306 *
3307 * Media which have only been temporarily opened without having been
3308 * attached to a machine have a NULL registry UUID and therefore don't
3309 * get saved.
3310 *
3311 * This locks the media tree. Throws HRESULT on errors!
3312 *
3313 * @param mediaRegistry Settings structure to fill.
3314 * @param uuidRegistry The UUID of the media registry; either a machine UUID (if machine registry) or the UUID of the global registry.
3315 * @param hardDiskFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
3316 */
3317void VirtualBox::saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
3318 const Guid &uuidRegistry,
3319 const Utf8Str &strMachineFolder)
3320{
3321 // lock all media for the following; use a write lock because we're
3322 // modifying the PendingMachineRenamesList, which is protected by this
3323 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3324
3325 // if a machine was renamed, then we'll need to refresh media paths
3326 if (m->llPendingMachineRenames.size())
3327 {
3328 // make a single list from the three media lists so we don't need three loops
3329 MediaList llAllMedia;
3330 // with hard disks, we must use the map, not the list, because the list only has base images
3331 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
3332 llAllMedia.push_back(it->second);
3333 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
3334 llAllMedia.push_back(*it);
3335 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
3336 llAllMedia.push_back(*it);
3337
3338 for (MediaList::iterator it = llAllMedia.begin();
3339 it != llAllMedia.end();
3340 ++it)
3341 {
3342 Medium *pMedium = *it;
3343 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
3344 it2 != m->llPendingMachineRenames.end();
3345 ++it2)
3346 {
3347 const Data::PendingMachineRename &pmr = *it2;
3348 pMedium->updatePath(pmr.strConfigDirOld,
3349 pmr.strConfigDirNew);
3350 }
3351 }
3352 // done, don't do it again until we have more machine renames
3353 m->llPendingMachineRenames.clear();
3354 }
3355
3356 struct {
3357 MediaOList &llSource;
3358 settings::MediaList &llTarget;
3359 } s[] =
3360 {
3361 // hard disks
3362 { m->allHardDisks, mediaRegistry.llHardDisks },
3363 // CD/DVD images
3364 { m->allDVDImages, mediaRegistry.llDvdImages },
3365 // floppy images
3366 { m->allFloppyImages, mediaRegistry.llFloppyImages }
3367 };
3368
3369 HRESULT rc;
3370
3371 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
3372 {
3373 MediaOList &llSource = s[i].llSource;
3374 settings::MediaList &llTarget = s[i].llTarget;
3375 llTarget.clear();
3376 for (MediaList::const_iterator it = llSource.begin();
3377 it != llSource.end();
3378 ++it)
3379 {
3380 Medium *pMedium = *it;
3381 AutoCaller autoCaller(pMedium);
3382 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
3383 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
3384
3385 if (pMedium->isInRegistry(uuidRegistry))
3386 {
3387 settings::Medium med;
3388 rc = pMedium->saveSettings(med, strMachineFolder); // this recurses into child hard disks
3389 if (FAILED(rc)) throw rc;
3390 llTarget.push_back(med);
3391 }
3392 }
3393 }
3394}
3395
3396/**
3397 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
3398 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
3399 * places internally when settings need saving.
3400 *
3401 * @note Caller must have locked the VirtualBox object for writing and must not hold any
3402 * other locks since this locks all kinds of member objects and trees temporarily,
3403 * which could cause conflicts.
3404 */
3405HRESULT VirtualBox::saveSettings()
3406{
3407 AutoCaller autoCaller(this);
3408 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3409
3410 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
3411 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
3412
3413 HRESULT rc = S_OK;
3414
3415 try
3416 {
3417 // machines
3418 m->pMainConfigFile->llMachines.clear();
3419 {
3420 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3421 for (MachinesOList::iterator it = m->allMachines.begin();
3422 it != m->allMachines.end();
3423 ++it)
3424 {
3425 Machine *pMachine = *it;
3426 // save actual machine registry entry
3427 settings::MachineRegistryEntry mre;
3428 rc = pMachine->saveRegistryEntry(mre);
3429 m->pMainConfigFile->llMachines.push_back(mre);
3430 }
3431 }
3432
3433 saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
3434 m->uuidMediaRegistry, // global media registry ID
3435 Utf8Str::Empty); // strMachineFolder
3436
3437 m->pMainConfigFile->llDhcpServers.clear();
3438 {
3439 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3440 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
3441 it != m->allDHCPServers.end();
3442 ++it)
3443 {
3444 settings::DHCPServer d;
3445 rc = (*it)->saveSettings(d);
3446 if (FAILED(rc)) throw rc;
3447 m->pMainConfigFile->llDhcpServers.push_back(d);
3448 }
3449 }
3450
3451 // leave extra data alone, it's still in the config file
3452
3453 // host data (USB filters)
3454 rc = m->pHost->saveSettings(m->pMainConfigFile->host);
3455 if (FAILED(rc)) throw rc;
3456
3457 rc = m->pSystemProperties->saveSettings(m->pMainConfigFile->systemProperties);
3458 if (FAILED(rc)) throw rc;
3459
3460 // and write out the XML, still under the lock
3461 m->pMainConfigFile->write(m->strSettingsFilePath);
3462 }
3463 catch (HRESULT err)
3464 {
3465 /* we assume that error info is set by the thrower */
3466 rc = err;
3467 }
3468 catch (...)
3469 {
3470 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
3471 }
3472
3473 return rc;
3474}
3475
3476/**
3477 * Helper to register the machine.
3478 *
3479 * When called during VirtualBox startup, adds the given machine to the
3480 * collection of registered machines. Otherwise tries to mark the machine
3481 * as registered, and, if succeeded, adds it to the collection and
3482 * saves global settings.
3483 *
3484 * @note The caller must have added itself as a caller of the @a aMachine
3485 * object if calls this method not on VirtualBox startup.
3486 *
3487 * @param aMachine machine to register
3488 *
3489 * @note Locks objects!
3490 */
3491HRESULT VirtualBox::registerMachine(Machine *aMachine)
3492{
3493 ComAssertRet(aMachine, E_INVALIDARG);
3494
3495 AutoCaller autoCaller(this);
3496 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3497
3498 HRESULT rc = S_OK;
3499
3500 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3501
3502 {
3503 ComObjPtr<Machine> pMachine;
3504 rc = findMachine(aMachine->getId(),
3505 true /* fPermitInaccessible */,
3506 false /* aDoSetError */,
3507 &pMachine);
3508 if (SUCCEEDED(rc))
3509 {
3510 /* sanity */
3511 AutoLimitedCaller machCaller(pMachine);
3512 AssertComRC(machCaller.rc());
3513
3514 return setError(E_INVALIDARG,
3515 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
3516 aMachine->getId().raw(),
3517 pMachine->getSettingsFileFull().c_str());
3518 }
3519
3520 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
3521 rc = S_OK;
3522 }
3523
3524 if (autoCaller.state() != InInit)
3525 {
3526 rc = aMachine->prepareRegister();
3527 if (FAILED(rc)) return rc;
3528 }
3529
3530 /* add to the collection of registered machines */
3531 m->allMachines.addChild(aMachine);
3532
3533 if (autoCaller.state() != InInit)
3534 rc = saveSettings();
3535
3536 return rc;
3537}
3538
3539/**
3540 * Remembers the given hard disk by storing it in either the global hard disk registry
3541 * or a machine one.
3542 *
3543 * @note Caller must hold the media tree lock for writing; in addition, this locks @a aHardDisk for reading
3544 *
3545 * @param aHardDisk Hard disk object to remember.
3546 * @param uuidMachineRegistry UUID of machine whose registry should be used, or a NULL UUID for the global registry.
3547 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs of media registries that need saving.
3548 * @return
3549 */
3550HRESULT VirtualBox::registerHardDisk(Medium *pMedium,
3551 GuidList *pllRegistriesThatNeedSaving)
3552{
3553 AssertReturn(pMedium != NULL, E_INVALIDARG);
3554
3555 AutoCaller autoCaller(this);
3556 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3557
3558 AutoCaller hardDiskCaller(pMedium);
3559 AssertComRCReturn(hardDiskCaller.rc(), hardDiskCaller.rc());
3560
3561 // caller must hold the media tree write lock
3562 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3563
3564 Guid id;
3565 Utf8Str strLocationFull;
3566 ComObjPtr<Medium> pParent;
3567 {
3568 AutoReadLock hardDiskLock(pMedium COMMA_LOCKVAL_SRC_POS);
3569 id = pMedium->getId();
3570 strLocationFull = pMedium->getLocationFull();
3571 pParent = pMedium->getParent();
3572 }
3573
3574 HRESULT rc;
3575
3576 Utf8Str strConflict;
3577 bool fIdentical;
3578 rc = checkMediaForConflicts(id,
3579 strLocationFull,
3580 strConflict,
3581 fIdentical);
3582 if (FAILED(rc)) return rc;
3583
3584 if (!fIdentical)
3585 {
3586 if (strConflict.length())
3587 return setError(E_INVALIDARG,
3588 tr("Cannot register the hard disk '%s' {%RTuuid} because a %s already exists"),
3589 strLocationFull.c_str(),
3590 id.raw(),
3591 strConflict.c_str(),
3592 m->strSettingsFilePath.c_str());
3593
3594 // store base (root) hard disks in the list
3595 if (pParent.isNull())
3596 m->allHardDisks.getList().push_back(pMedium);
3597 // access the list directly because we already locked the list above
3598
3599 // store all hard disks (even differencing images) in the map
3600 m->mapHardDisks[id] = pMedium;
3601
3602 if (pllRegistriesThatNeedSaving)
3603 pMedium->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3604 }
3605
3606 return rc;
3607}
3608
3609/**
3610 * Removes the given hard disk from the hard disk registry.
3611 *
3612 * @param aHardDisk Hard disk object to remove.
3613 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3614 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3615 *
3616 * @note Caller must hold the media tree lock for writing; in addition, this locks @a aHardDisk for reading
3617 */
3618HRESULT VirtualBox::unregisterHardDisk(Medium *aHardDisk,
3619 GuidList *pllRegistriesThatNeedSaving)
3620{
3621 AssertReturn(aHardDisk != NULL, E_INVALIDARG);
3622
3623 AutoCaller autoCaller(this);
3624 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3625
3626 AutoCaller hardDiskCaller(aHardDisk);
3627 AssertComRCReturn(hardDiskCaller.rc(), hardDiskCaller.rc());
3628
3629 // caller must hold the media tree write lock
3630 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3631
3632 Guid id;
3633 ComObjPtr<Medium> pParent;
3634 {
3635 AutoReadLock hardDiskLock(aHardDisk COMMA_LOCKVAL_SRC_POS);
3636 id = aHardDisk->getId();
3637 pParent = aHardDisk->getParent();
3638 }
3639
3640 // remove base (root) hard disks from the list
3641 if (pParent.isNull())
3642 m->allHardDisks.getList().remove(aHardDisk);
3643 // access the list directly because caller must have locked the list
3644
3645 // remove all hard disks (even differencing images) from map
3646 size_t cnt = m->mapHardDisks.erase(id);
3647 Assert(cnt == 1);
3648 NOREF(cnt);
3649
3650 if (pllRegistriesThatNeedSaving)
3651 aHardDisk->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3652
3653 return S_OK;
3654}
3655
3656/**
3657 * Remembers the given image by storing it in the CD/DVD or floppy image registry.
3658 *
3659 * @param argImage Image object to remember.
3660 * @param argType Either DeviceType_DVD or DeviceType_Floppy.
3661 * @param uuidMachineRegistry UUID of machine whose registry should be used, or a NULL UUID for the global registry.
3662 *
3663 * @note Caller must hold the media tree lock for writing; in addition, this locks @a argImage for reading
3664 */
3665HRESULT VirtualBox::registerImage(Medium *pMedium,
3666 DeviceType_T argType,
3667 GuidList *pllRegistriesThatNeedSaving)
3668{
3669 AssertReturn(pMedium != NULL, E_INVALIDARG);
3670
3671 AutoCaller autoCaller(this);
3672 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3673
3674 AutoCaller imageCaller(pMedium);
3675 AssertComRCReturn(imageCaller.rc(), imageCaller.rc());
3676
3677 // caller must hold the media tree write lock
3678 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3679
3680 Guid id;
3681 Utf8Str strLocationFull;
3682 ComObjPtr<Medium> pParent;
3683 {
3684 AutoReadLock al(pMedium COMMA_LOCKVAL_SRC_POS);
3685 id = pMedium->getId();
3686 strLocationFull = pMedium->getLocationFull();
3687 pParent = pMedium->getParent();
3688 }
3689
3690 // work on DVDs or floppies list?
3691 ObjectsList<Medium> &all = (argType == DeviceType_DVD) ? m->allDVDImages : m->allFloppyImages;
3692
3693 HRESULT rc;
3694 // lock the images lists (list + map) while checking for conflicts
3695 AutoWriteLock al(all.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3696
3697 Utf8Str strConflict;
3698 bool fIdentical;
3699 rc = checkMediaForConflicts(id,
3700 strLocationFull,
3701 strConflict,
3702 fIdentical);
3703 if (FAILED(rc)) return rc;
3704
3705 if (!fIdentical)
3706 {
3707 if (strConflict.length())
3708 return setError(VBOX_E_INVALID_OBJECT_STATE,
3709 tr("Cannot register the image '%s' with UUID {%RTuuid} because a %s already exists"),
3710 strLocationFull.c_str(),
3711 id.raw(),
3712 strConflict.c_str());
3713
3714 // add to the collection
3715 all.getList().push_back(pMedium);
3716 // access the list directly because we already locked the list above
3717
3718 if (pllRegistriesThatNeedSaving)
3719 pMedium->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3720 }
3721
3722 return rc;
3723}
3724
3725/**
3726 * Removes the given image from the CD/DVD or floppy image registry.
3727 *
3728 * @param argImage Image object to remove.
3729 * @param argType Either DeviceType_DVD or DeviceType_Floppy.
3730 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3731 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3732 *
3733 * @note Caller must hold the media tree lock for writing; in addition, this locks @a argImage for reading
3734 */
3735HRESULT VirtualBox::unregisterImage(Medium *argImage,
3736 DeviceType_T argType,
3737 GuidList *pllRegistriesThatNeedSaving)
3738{
3739 AssertReturn(argImage != NULL, E_INVALIDARG);
3740
3741 AutoCaller autoCaller(this);
3742 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3743
3744 AutoCaller imageCaller(argImage);
3745 AssertComRCReturn(imageCaller.rc(), imageCaller.rc());
3746
3747 // caller must hold the media tree write lock
3748 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3749
3750 Guid id;
3751 ComObjPtr<Medium> pParent;
3752 {
3753 AutoReadLock al(argImage COMMA_LOCKVAL_SRC_POS);
3754 id = argImage->getId();
3755 pParent = argImage->getParent();
3756 }
3757
3758 // work on DVDs or floppies list?
3759 ObjectsList<Medium> &all = (argType == DeviceType_DVD) ? m->allDVDImages : m->allFloppyImages;
3760
3761 // access the list directly because the caller must have requested the lock
3762 all.getList().remove(argImage);
3763
3764 HRESULT rc = S_OK;
3765
3766 if (pllRegistriesThatNeedSaving)
3767 argImage->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3768
3769 return rc;
3770}
3771
3772/**
3773 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
3774 * with children appearing before their parents.
3775 * @param llMedia
3776 * @param pMedium
3777 */
3778void VirtualBox::pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
3779{
3780 // recurse first, then add ourselves; this way children end up on the
3781 // list before their parents
3782
3783 const MediaList &llChildren = pMedium->getChildren();
3784 for (MediaList::const_iterator it = llChildren.begin();
3785 it != llChildren.end();
3786 ++it)
3787 {
3788 Medium *pChild = *it;
3789 pushMediumToListWithChildren(llMedia, pChild);
3790 }
3791
3792 Log(("Pushing medium %RTuuid\n", pMedium->getId().raw()));
3793 llMedia.push_back(pMedium);
3794}
3795
3796/**
3797 * Unregisters all Medium objects which belong to the given machine registry.
3798 * Gets called from Machine::uninit() just before the machine object dies
3799 * and must only be called with a machine UUID as the registry ID.
3800 *
3801 * Locks the media tree.
3802 *
3803 * @param uuidMachine Medium registry ID (always a machine UUID)
3804 * @return
3805 */
3806HRESULT VirtualBox::unregisterMachineMedia(const Guid &uuidMachine)
3807{
3808 Assert(!uuidMachine.isEmpty());
3809
3810 LogFlowFuncEnter();
3811
3812 AutoCaller autoCaller(this);
3813 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3814
3815 MediaList llMedia2Close;
3816
3817 {
3818 AutoWriteLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3819
3820 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
3821 it != m->allHardDisks.getList().end();
3822 ++it)
3823 {
3824 ComObjPtr<Medium> pMedium = *it;
3825 AutoCaller medCaller(pMedium);
3826 if (FAILED(medCaller.rc())) return medCaller.rc();
3827 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
3828
3829 if (pMedium->isInRegistry(uuidMachine))
3830 // recursively with children first
3831 pushMediumToListWithChildren(llMedia2Close, pMedium);
3832 }
3833 }
3834
3835 for (MediaList::iterator it = llMedia2Close.begin();
3836 it != llMedia2Close.end();
3837 ++it)
3838 {
3839 ComObjPtr<Medium> pMedium = *it;
3840 Log(("Closing medium %RTuuid\n", pMedium->getId().raw()));
3841 AutoCaller mac(pMedium);
3842 pMedium->close(NULL /* pfNeedsGlobalSaveSettings*/, mac);
3843 }
3844
3845 LogFlowFuncLeave();
3846
3847 return S_OK;
3848}
3849
3850/**
3851 * Removes the given machine object from the internal list of registered machines.
3852 * Called from Machine::Unregister().
3853 * @param pMachine
3854 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
3855 * @return
3856 */
3857HRESULT VirtualBox::unregisterMachine(Machine *pMachine,
3858 const Guid &id)
3859{
3860 // remove from the collection of registered machines
3861 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3862 m->allMachines.removeChild(pMachine);
3863 // save the global registry
3864 HRESULT rc = saveSettings();
3865 alock.release();
3866
3867 /*
3868 * Now go over all known media and checks if they were registered in the
3869 * media registry of the given machine. Each such medium is then moved to
3870 * a different media registry to make sure it doesn't get lost since its
3871 * media registry is about to go away.
3872 *
3873 * This fixes the following use case: Image A.vdi of machine A is also used
3874 * by machine B, but registered in the media registry of machine A. If machine
3875 * A is deleted, A.vdi must be moved to the registry of B, or else B will
3876 * become inaccessible.
3877 */
3878 GuidList llRegistriesThatNeedSaving;
3879 {
3880 AutoReadLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3881 // iterate over the list of *base* images
3882 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
3883 it != m->allHardDisks.getList().end();
3884 ++it)
3885 {
3886 ComObjPtr<Medium> &pMedium = *it;
3887 AutoCaller medCaller(pMedium);
3888 if (FAILED(medCaller.rc())) return medCaller.rc();
3889 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
3890
3891 if (pMedium->removeRegistry(id, true /* fRecurse */))
3892 {
3893 // machine ID was found in base medium's registry list:
3894 // move this base image and all its children to another registry then
3895 // 1) first, find a better registry to add things to
3896 const Guid *puuidBetter = pMedium->getAnyMachineBackref();
3897 if (puuidBetter)
3898 {
3899 // 2) better registry found: then use that
3900 pMedium->addRegistry(*puuidBetter, true /* fRecurse */);
3901 // 3) and make sure the registry is saved below
3902 VirtualBox::addGuidToListUniquely(llRegistriesThatNeedSaving, *puuidBetter);
3903 }
3904 }
3905 }
3906 }
3907
3908 saveRegistries(llRegistriesThatNeedSaving);
3909
3910 /* fire an event */
3911 onMachineRegistered(id, FALSE);
3912
3913 return rc;
3914}
3915
3916/**
3917 * Adds uuid to llRegistriesThatNeedSaving unless it's already on the list.
3918 *
3919 * @todo maybe there's something in libstdc++ for this
3920 *
3921 * @param llRegistriesThatNeedSaving
3922 * @param uuid
3923 */
3924/* static */
3925void VirtualBox::addGuidToListUniquely(GuidList &llRegistriesThatNeedSaving,
3926 const Guid &uuid)
3927{
3928 for (GuidList::const_iterator it = llRegistriesThatNeedSaving.begin();
3929 it != llRegistriesThatNeedSaving.end();
3930 ++it)
3931 {
3932 if (*it == uuid)
3933 // uuid is already in list:
3934 return;
3935 }
3936
3937 llRegistriesThatNeedSaving.push_back(uuid);
3938}
3939
3940/**
3941 * Saves all settings files according to the given list of UUIDs, which are
3942 * either machine IDs (in which case Machine::saveSettings is invoked) or
3943 * the global registry UUID (in which case VirtualBox::saveSettings is invoked).
3944 *
3945 * This locks machines and the VirtualBox object as necessary, so better not
3946 * hold any locks before calling this.
3947 *
3948 * @param llRegistriesThatNeedSaving
3949 * @return
3950 */
3951HRESULT VirtualBox::saveRegistries(const GuidList &llRegistriesThatNeedSaving)
3952{
3953 bool fNeedsGlobalSettings = false;
3954 HRESULT rc = S_OK;
3955
3956 for (GuidList::const_iterator it = llRegistriesThatNeedSaving.begin();
3957 it != llRegistriesThatNeedSaving.end();
3958 ++it)
3959 {
3960 const Guid &uuid = *it;
3961
3962 if (uuid == getGlobalRegistryId())
3963 fNeedsGlobalSettings = true;
3964 else
3965 {
3966 // should be machine ID then:
3967 ComObjPtr<Machine> pMachine;
3968 rc = findMachine(uuid,
3969 false /* fPermitInaccessible */,
3970 false /* aSetError */,
3971 &pMachine);
3972 if (SUCCEEDED(rc))
3973 {
3974 AutoCaller autoCaller(pMachine);
3975 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3976 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
3977 rc = pMachine->saveSettings(&fNeedsGlobalSettings,
3978 Machine::SaveS_Force); // caller said save, so stop arguing
3979 }
3980
3981 if (FAILED(rc))
3982 return rc;
3983 }
3984 }
3985
3986 if (fNeedsGlobalSettings)
3987 {
3988 AutoWriteLock vlock(this COMMA_LOCKVAL_SRC_POS);
3989 rc = saveSettings();
3990 }
3991
3992 return S_OK;
3993}
3994
3995/**
3996 * Checks if the path to the specified file exists, according to the path
3997 * information present in the file name. Optionally the path is created.
3998 *
3999 * Note that the given file name must contain the full path otherwise the
4000 * extracted relative path will be created based on the current working
4001 * directory which is normally unknown.
4002 *
4003 * @param aFileName Full file name which path is checked/created.
4004 * @param aCreate Flag if the path should be created if it doesn't exist.
4005 *
4006 * @return Extended error information on failure to check/create the path.
4007 */
4008/* static */
4009HRESULT VirtualBox::ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4010{
4011 Utf8Str strDir(strFileName);
4012 strDir.stripFilename();
4013 if (!RTDirExists(strDir.c_str()))
4014 {
4015 if (fCreate)
4016 {
4017 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4018 if (RT_FAILURE(vrc))
4019 return setErrorStatic(VBOX_E_IPRT_ERROR,
4020 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4021 strDir.c_str(),
4022 vrc));
4023 }
4024 else
4025 return setErrorStatic(VBOX_E_IPRT_ERROR,
4026 Utf8StrFmt(tr("Directory '%s' does not exist"),
4027 strDir.c_str()));
4028 }
4029
4030 return S_OK;
4031}
4032
4033/**
4034 * Handles unexpected exceptions by turning them into COM errors in release
4035 * builds or by hitting a breakpoint in the release builds.
4036 *
4037 * Usage pattern:
4038 * @code
4039 try
4040 {
4041 // ...
4042 }
4043 catch (LaLalA)
4044 {
4045 // ...
4046 }
4047 catch (...)
4048 {
4049 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
4050 }
4051 * @endcode
4052 *
4053 * @param RT_SRC_POS_DECL "RT_SRC_POS" macro instantiation.
4054 */
4055/* static */
4056HRESULT VirtualBox::handleUnexpectedExceptions(RT_SRC_POS_DECL)
4057{
4058 try
4059 {
4060 /* re-throw the current exception */
4061 throw;
4062 }
4063 catch (const RTCError &err) // includes all XML exceptions
4064 {
4065 return setErrorStatic(E_FAIL,
4066 Utf8StrFmt(tr("%s.\n%s[%d] (%s)"),
4067 err.what(),
4068 pszFile, iLine, pszFunction).c_str());
4069 }
4070 catch (const std::exception &err)
4071 {
4072 return setErrorStatic(E_FAIL,
4073 Utf8StrFmt(tr("Unexpected exception: %s [%s]\n%s[%d] (%s)"),
4074 err.what(), typeid(err).name(),
4075 pszFile, iLine, pszFunction).c_str());
4076 }
4077 catch (...)
4078 {
4079 return setErrorStatic(E_FAIL,
4080 Utf8StrFmt(tr("Unknown exception\n%s[%d] (%s)"),
4081 pszFile, iLine, pszFunction).c_str());
4082 }
4083
4084 /* should not get here */
4085 AssertFailed();
4086 return E_FAIL;
4087}
4088
4089const Utf8Str& VirtualBox::settingsFilePath()
4090{
4091 return m->strSettingsFilePath;
4092}
4093
4094/**
4095 * Returns the lock handle which protects the media trees (hard disks,
4096 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4097 * are no longer protected by the VirtualBox lock, but by this more
4098 * specialized lock. Mind the locking order: always request this lock
4099 * after the VirtualBox object lock but before the locks of the media
4100 * objects contained in these lists. See AutoLock.h.
4101 */
4102RWLockHandle& VirtualBox::getMediaTreeLockHandle()
4103{
4104 return m->lockMedia;
4105}
4106
4107/**
4108 * Thread function that watches the termination of all client processes
4109 * that have opened sessions using IMachine::LockMachine()
4110 */
4111// static
4112DECLCALLBACK(int) VirtualBox::ClientWatcher(RTTHREAD /* thread */, void *pvUser)
4113{
4114 LogFlowFuncEnter();
4115
4116 VirtualBox *that = (VirtualBox*)pvUser;
4117 Assert(that);
4118
4119 typedef std::vector< ComObjPtr<Machine> > MachineVector;
4120 typedef std::vector< ComObjPtr<SessionMachine> > SessionMachineVector;
4121
4122 SessionMachineVector machines;
4123 MachineVector spawnedMachines;
4124
4125 size_t cnt = 0;
4126 size_t cntSpawned = 0;
4127
4128 VirtualBoxBase::initializeComForThread();
4129
4130#if defined(RT_OS_WINDOWS)
4131
4132 HRESULT hrc;
4133
4134 /// @todo (dmik) processes reaping!
4135
4136 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
4137 handles[0] = that->m->updateReq;
4138
4139 do
4140 {
4141 AutoCaller autoCaller(that);
4142 /* VirtualBox has been early uninitialized, terminate */
4143 if (!autoCaller.isOk())
4144 break;
4145
4146 do
4147 {
4148 /* release the caller to let uninit() ever proceed */
4149 autoCaller.release();
4150
4151 DWORD rc = ::WaitForMultipleObjects((DWORD)(1 + cnt + cntSpawned),
4152 handles,
4153 FALSE,
4154 INFINITE);
4155
4156 /* Restore the caller before using VirtualBox. If it fails, this
4157 * means VirtualBox is being uninitialized and we must terminate. */
4158 autoCaller.add();
4159 if (!autoCaller.isOk())
4160 break;
4161
4162 bool update = false;
4163
4164 if (rc == WAIT_OBJECT_0)
4165 {
4166 /* update event is signaled */
4167 update = true;
4168 }
4169 else if (rc > WAIT_OBJECT_0 && rc <= (WAIT_OBJECT_0 + cnt))
4170 {
4171 /* machine mutex is released */
4172 (machines[rc - WAIT_OBJECT_0 - 1])->checkForDeath();
4173 update = true;
4174 }
4175 else if (rc > WAIT_ABANDONED_0 && rc <= (WAIT_ABANDONED_0 + cnt))
4176 {
4177 /* machine mutex is abandoned due to client process termination */
4178 (machines[rc - WAIT_ABANDONED_0 - 1])->checkForDeath();
4179 update = true;
4180 }
4181 else if (rc > WAIT_OBJECT_0 + cnt && rc <= (WAIT_OBJECT_0 + cntSpawned))
4182 {
4183 /* spawned VM process has terminated (normally or abnormally) */
4184 (spawnedMachines[rc - WAIT_OBJECT_0 - cnt - 1])->
4185 checkForSpawnFailure();
4186 update = true;
4187 }
4188
4189 if (update)
4190 {
4191 /* close old process handles */
4192 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++i)
4193 CloseHandle(handles[i]);
4194
4195 // lock the machines list for reading
4196 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4197
4198 /* obtain a new set of opened machines */
4199 cnt = 0;
4200 machines.clear();
4201
4202 for (MachinesOList::iterator it = that->m->allMachines.begin();
4203 it != that->m->allMachines.end();
4204 ++it)
4205 {
4206 /// @todo handle situations with more than 64 objects
4207 AssertMsgBreak((1 + cnt) <= MAXIMUM_WAIT_OBJECTS,
4208 ("MAXIMUM_WAIT_OBJECTS reached"));
4209
4210 ComObjPtr<SessionMachine> sm;
4211 HANDLE ipcSem;
4212 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4213 {
4214 machines.push_back(sm);
4215 handles[1 + cnt] = ipcSem;
4216 ++cnt;
4217 }
4218 }
4219
4220 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4221
4222 /* obtain a new set of spawned machines */
4223 cntSpawned = 0;
4224 spawnedMachines.clear();
4225
4226 for (MachinesOList::iterator it = that->m->allMachines.begin();
4227 it != that->m->allMachines.end();
4228 ++it)
4229 {
4230 /// @todo handle situations with more than 64 objects
4231 AssertMsgBreak((1 + cnt + cntSpawned) <= MAXIMUM_WAIT_OBJECTS,
4232 ("MAXIMUM_WAIT_OBJECTS reached"));
4233
4234 RTPROCESS pid;
4235 if ((*it)->isSessionSpawning(&pid))
4236 {
4237 HANDLE ph = OpenProcess(SYNCHRONIZE, FALSE, pid);
4238 AssertMsg(ph != NULL, ("OpenProcess (pid=%d) failed with %d\n",
4239 pid, GetLastError()));
4240 if (rc == 0)
4241 {
4242 spawnedMachines.push_back(*it);
4243 handles[1 + cnt + cntSpawned] = ph;
4244 ++cntSpawned;
4245 }
4246 }
4247 }
4248
4249 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4250
4251 // machines lock unwinds here
4252 }
4253 }
4254 while (true);
4255 }
4256 while (0);
4257
4258 /* close old process handles */
4259 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++ i)
4260 CloseHandle(handles[i]);
4261
4262 /* release sets of machines if any */
4263 machines.clear();
4264 spawnedMachines.clear();
4265
4266 ::CoUninitialize();
4267
4268#elif defined(RT_OS_OS2)
4269
4270 /// @todo (dmik) processes reaping!
4271
4272 /* according to PMREF, 64 is the maximum for the muxwait list */
4273 SEMRECORD handles[64];
4274
4275 HMUX muxSem = NULLHANDLE;
4276
4277 do
4278 {
4279 AutoCaller autoCaller(that);
4280 /* VirtualBox has been early uninitialized, terminate */
4281 if (!autoCaller.isOk())
4282 break;
4283
4284 do
4285 {
4286 /* release the caller to let uninit() ever proceed */
4287 autoCaller.release();
4288
4289 int vrc = RTSemEventWait(that->m->updateReq, 500);
4290
4291 /* Restore the caller before using VirtualBox. If it fails, this
4292 * means VirtualBox is being uninitialized and we must terminate. */
4293 autoCaller.add();
4294 if (!autoCaller.isOk())
4295 break;
4296
4297 bool update = false;
4298 bool updateSpawned = false;
4299
4300 if (RT_SUCCESS(vrc))
4301 {
4302 /* update event is signaled */
4303 update = true;
4304 updateSpawned = true;
4305 }
4306 else
4307 {
4308 AssertMsg(vrc == VERR_TIMEOUT || vrc == VERR_INTERRUPTED,
4309 ("RTSemEventWait returned %Rrc\n", vrc));
4310
4311 /* are there any mutexes? */
4312 if (cnt > 0)
4313 {
4314 /* figure out what's going on with machines */
4315
4316 unsigned long semId = 0;
4317 APIRET arc = ::DosWaitMuxWaitSem(muxSem,
4318 SEM_IMMEDIATE_RETURN, &semId);
4319
4320 if (arc == NO_ERROR)
4321 {
4322 /* machine mutex is normally released */
4323 Assert(semId >= 0 && semId < cnt);
4324 if (semId >= 0 && semId < cnt)
4325 {
4326#if 0//def DEBUG
4327 {
4328 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4329 LogFlowFunc(("released mutex: machine='%ls'\n",
4330 machines[semId]->name().raw()));
4331 }
4332#endif
4333 machines[semId]->checkForDeath();
4334 }
4335 update = true;
4336 }
4337 else if (arc == ERROR_SEM_OWNER_DIED)
4338 {
4339 /* machine mutex is abandoned due to client process
4340 * termination; find which mutex is in the Owner Died
4341 * state */
4342 for (size_t i = 0; i < cnt; ++ i)
4343 {
4344 PID pid; TID tid;
4345 unsigned long reqCnt;
4346 arc = DosQueryMutexSem((HMTX)handles[i].hsemCur, &pid, &tid, &reqCnt);
4347 if (arc == ERROR_SEM_OWNER_DIED)
4348 {
4349 /* close the dead mutex as asked by PMREF */
4350 ::DosCloseMutexSem((HMTX)handles[i].hsemCur);
4351
4352 Assert(i >= 0 && i < cnt);
4353 if (i >= 0 && i < cnt)
4354 {
4355#if 0//def DEBUG
4356 {
4357 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4358 LogFlowFunc(("mutex owner dead: machine='%ls'\n",
4359 machines[i]->name().raw()));
4360 }
4361#endif
4362 machines[i]->checkForDeath();
4363 }
4364 }
4365 }
4366 update = true;
4367 }
4368 else
4369 AssertMsg(arc == ERROR_INTERRUPT || arc == ERROR_TIMEOUT,
4370 ("DosWaitMuxWaitSem returned %d\n", arc));
4371 }
4372
4373 /* are there any spawning sessions? */
4374 if (cntSpawned > 0)
4375 {
4376 for (size_t i = 0; i < cntSpawned; ++ i)
4377 updateSpawned |= (spawnedMachines[i])->
4378 checkForSpawnFailure();
4379 }
4380 }
4381
4382 if (update || updateSpawned)
4383 {
4384 AutoReadLock thatLock(that COMMA_LOCKVAL_SRC_POS);
4385
4386 if (update)
4387 {
4388 /* close the old muxsem */
4389 if (muxSem != NULLHANDLE)
4390 ::DosCloseMuxWaitSem(muxSem);
4391
4392 /* obtain a new set of opened machines */
4393 cnt = 0;
4394 machines.clear();
4395
4396 for (MachinesOList::iterator it = that->m->allMachines.begin();
4397 it != that->m->allMachines.end(); ++ it)
4398 {
4399 /// @todo handle situations with more than 64 objects
4400 AssertMsg(cnt <= 64 /* according to PMREF */,
4401 ("maximum of 64 mutex semaphores reached (%d)",
4402 cnt));
4403
4404 ComObjPtr<SessionMachine> sm;
4405 HMTX ipcSem;
4406 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4407 {
4408 machines.push_back(sm);
4409 handles[cnt].hsemCur = (HSEM)ipcSem;
4410 handles[cnt].ulUser = cnt;
4411 ++ cnt;
4412 }
4413 }
4414
4415 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4416
4417 if (cnt > 0)
4418 {
4419 /* create a new muxsem */
4420 APIRET arc = ::DosCreateMuxWaitSem(NULL, &muxSem, cnt,
4421 handles,
4422 DCMW_WAIT_ANY);
4423 AssertMsg(arc == NO_ERROR,
4424 ("DosCreateMuxWaitSem returned %d\n", arc));
4425 NOREF(arc);
4426 }
4427 }
4428
4429 if (updateSpawned)
4430 {
4431 /* obtain a new set of spawned machines */
4432 spawnedMachines.clear();
4433
4434 for (MachinesOList::iterator it = that->m->allMachines.begin();
4435 it != that->m->allMachines.end(); ++ it)
4436 {
4437 if ((*it)->isSessionSpawning())
4438 spawnedMachines.push_back(*it);
4439 }
4440
4441 cntSpawned = spawnedMachines.size();
4442 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4443 }
4444 }
4445 }
4446 while (true);
4447 }
4448 while (0);
4449
4450 /* close the muxsem */
4451 if (muxSem != NULLHANDLE)
4452 ::DosCloseMuxWaitSem(muxSem);
4453
4454 /* release sets of machines if any */
4455 machines.clear();
4456 spawnedMachines.clear();
4457
4458#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
4459
4460 bool update = false;
4461 bool updateSpawned = false;
4462
4463 do
4464 {
4465 AutoCaller autoCaller(that);
4466 if (!autoCaller.isOk())
4467 break;
4468
4469 do
4470 {
4471 /* release the caller to let uninit() ever proceed */
4472 autoCaller.release();
4473
4474 int rc = RTSemEventWait(that->m->updateReq, 500);
4475
4476 /*
4477 * Restore the caller before using VirtualBox. If it fails, this
4478 * means VirtualBox is being uninitialized and we must terminate.
4479 */
4480 autoCaller.add();
4481 if (!autoCaller.isOk())
4482 break;
4483
4484 if (RT_SUCCESS(rc) || update || updateSpawned)
4485 {
4486 /* RT_SUCCESS(rc) means an update event is signaled */
4487
4488 // lock the machines list for reading
4489 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4490
4491 if (RT_SUCCESS(rc) || update)
4492 {
4493 /* obtain a new set of opened machines */
4494 machines.clear();
4495
4496 for (MachinesOList::iterator it = that->m->allMachines.begin();
4497 it != that->m->allMachines.end();
4498 ++it)
4499 {
4500 ComObjPtr<SessionMachine> sm;
4501 if ((*it)->isSessionOpenOrClosing(sm))
4502 machines.push_back(sm);
4503 }
4504
4505 cnt = machines.size();
4506 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4507 }
4508
4509 if (RT_SUCCESS(rc) || updateSpawned)
4510 {
4511 /* obtain a new set of spawned machines */
4512 spawnedMachines.clear();
4513
4514 for (MachinesOList::iterator it = that->m->allMachines.begin();
4515 it != that->m->allMachines.end();
4516 ++it)
4517 {
4518 if ((*it)->isSessionSpawning())
4519 spawnedMachines.push_back(*it);
4520 }
4521
4522 cntSpawned = spawnedMachines.size();
4523 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4524 }
4525
4526 // machines lock unwinds here
4527 }
4528
4529 update = false;
4530 for (size_t i = 0; i < cnt; ++ i)
4531 update |= (machines[i])->checkForDeath();
4532
4533 updateSpawned = false;
4534 for (size_t i = 0; i < cntSpawned; ++ i)
4535 updateSpawned |= (spawnedMachines[i])->checkForSpawnFailure();
4536
4537 /* reap child processes */
4538 {
4539 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
4540 if (that->m->llProcesses.size())
4541 {
4542 LogFlowFunc(("UPDATE: child process count = %d\n",
4543 that->m->llProcesses.size()));
4544 VirtualBox::Data::ProcessList::iterator it = that->m->llProcesses.begin();
4545 while (it != that->m->llProcesses.end())
4546 {
4547 RTPROCESS pid = *it;
4548 RTPROCSTATUS status;
4549 int vrc = ::RTProcWait(pid, RTPROCWAIT_FLAGS_NOBLOCK, &status);
4550 if (vrc == VINF_SUCCESS)
4551 {
4552 LogFlowFunc(("pid %d (%x) was reaped, status=%d, reason=%d\n",
4553 pid, pid, status.iStatus,
4554 status.enmReason));
4555 it = that->m->llProcesses.erase(it);
4556 }
4557 else
4558 {
4559 LogFlowFunc(("pid %d (%x) was NOT reaped, vrc=%Rrc\n",
4560 pid, pid, vrc));
4561 if (vrc != VERR_PROCESS_RUNNING)
4562 {
4563 /* remove the process if it is not already running */
4564 it = that->m->llProcesses.erase(it);
4565 }
4566 else
4567 ++ it;
4568 }
4569 }
4570 }
4571 }
4572 }
4573 while (true);
4574 }
4575 while (0);
4576
4577 /* release sets of machines if any */
4578 machines.clear();
4579 spawnedMachines.clear();
4580
4581#else
4582# error "Port me!"
4583#endif
4584
4585 VirtualBoxBase::uninitializeComForThread();
4586 LogFlowFuncLeave();
4587 return 0;
4588}
4589
4590/**
4591 * Thread function that handles custom events posted using #postEvent().
4592 */
4593// static
4594DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4595{
4596 LogFlowFuncEnter();
4597
4598 AssertReturn(pvUser, VERR_INVALID_POINTER);
4599
4600 com::Initialize();
4601
4602 // create an event queue for the current thread
4603 EventQueue *eventQ = new EventQueue();
4604 AssertReturn(eventQ, VERR_NO_MEMORY);
4605
4606 // return the queue to the one who created this thread
4607 *(static_cast <EventQueue **>(pvUser)) = eventQ;
4608 // signal that we're ready
4609 RTThreadUserSignal(thread);
4610
4611 /*
4612 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4613 * we must not stop processing events and delete the "eventQ" object. This must
4614 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4615 * See #5724.
4616 */
4617 while (eventQ->processEventQueue(RT_INDEFINITE_WAIT) != VERR_INTERRUPTED)
4618 /* nothing */ ;
4619
4620 delete eventQ;
4621
4622 com::Shutdown();
4623
4624
4625 LogFlowFuncLeave();
4626
4627 return 0;
4628}
4629
4630
4631////////////////////////////////////////////////////////////////////////////////
4632
4633/**
4634 * Takes the current list of registered callbacks of the managed VirtualBox
4635 * instance, and calls #handleCallback() for every callback item from the
4636 * list, passing the item as an argument.
4637 *
4638 * @note Locks the managed VirtualBox object for reading but leaves the lock
4639 * before iterating over callbacks and calling their methods.
4640 */
4641void *VirtualBox::CallbackEvent::handler()
4642{
4643 if (!mVirtualBox)
4644 return NULL;
4645
4646 AutoCaller autoCaller(mVirtualBox);
4647 if (!autoCaller.isOk())
4648 {
4649 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4650 autoCaller.state()));
4651 /* We don't need mVirtualBox any more, so release it */
4652 mVirtualBox = NULL;
4653 return NULL;
4654 }
4655
4656 {
4657 VBoxEventDesc evDesc;
4658 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4659
4660 evDesc.fire(/* don't wait for delivery */0);
4661 }
4662
4663 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4664 return NULL;
4665}
4666
4667//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4668//{
4669// return E_NOTIMPL;
4670//}
4671
4672STDMETHODIMP VirtualBox::CreateDHCPServer(IN_BSTR aName, IDHCPServer ** aServer)
4673{
4674 CheckComArgStrNotEmptyOrNull(aName);
4675 CheckComArgNotNull(aServer);
4676
4677 AutoCaller autoCaller(this);
4678 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4679
4680 ComObjPtr<DHCPServer> dhcpServer;
4681 dhcpServer.createObject();
4682 HRESULT rc = dhcpServer->init(this, aName);
4683 if (FAILED(rc)) return rc;
4684
4685 rc = registerDHCPServer(dhcpServer, true);
4686 if (FAILED(rc)) return rc;
4687
4688 dhcpServer.queryInterfaceTo(aServer);
4689
4690 return rc;
4691}
4692
4693STDMETHODIMP VirtualBox::FindDHCPServerByNetworkName(IN_BSTR aName, IDHCPServer ** aServer)
4694{
4695 CheckComArgStrNotEmptyOrNull(aName);
4696 CheckComArgNotNull(aServer);
4697
4698 AutoCaller autoCaller(this);
4699 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4700
4701 HRESULT rc;
4702 Bstr bstr;
4703 ComPtr<DHCPServer> found;
4704
4705 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4706
4707 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4708 it != m->allDHCPServers.end();
4709 ++it)
4710 {
4711 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4712 if (FAILED(rc)) return rc;
4713
4714 if (bstr == aName)
4715 {
4716 found = *it;
4717 break;
4718 }
4719 }
4720
4721 if (!found)
4722 return E_INVALIDARG;
4723
4724 return found.queryInterfaceTo(aServer);
4725}
4726
4727STDMETHODIMP VirtualBox::RemoveDHCPServer(IDHCPServer * aServer)
4728{
4729 CheckComArgNotNull(aServer);
4730
4731 AutoCaller autoCaller(this);
4732 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4733
4734 HRESULT rc = unregisterDHCPServer(static_cast<DHCPServer *>(aServer), true);
4735
4736 return rc;
4737}
4738
4739/**
4740 * Remembers the given dhcp server by storing it in the hard disk registry.
4741 *
4742 * @param aDHCPServer Dhcp Server object to remember.
4743 * @param aSaveRegistry @c true to save hard disk registry to disk (default).
4744 *
4745 * When @a aSaveRegistry is @c true, this operation may fail because of the
4746 * failed #saveSettings() method it calls. In this case, the dhcp server object
4747 * will not be remembered. It is therefore the responsibility of the caller to
4748 * call this method as the last step of some action that requires registration
4749 * in order to make sure that only fully functional dhcp server objects get
4750 * registered.
4751 *
4752 * @note Locks this object for writing and @a aDHCPServer for reading.
4753 */
4754HRESULT VirtualBox::registerDHCPServer(DHCPServer *aDHCPServer,
4755 bool aSaveRegistry /*= true*/)
4756{
4757 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4758
4759 AutoCaller autoCaller(this);
4760 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4761
4762 AutoCaller dhcpServerCaller(aDHCPServer);
4763 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4764
4765 Bstr name;
4766 HRESULT rc;
4767 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
4768 if (FAILED(rc)) return rc;
4769
4770 ComPtr<IDHCPServer> existing;
4771 rc = FindDHCPServerByNetworkName(name.raw(), existing.asOutParam());
4772 if (SUCCEEDED(rc))
4773 return E_INVALIDARG;
4774
4775 rc = S_OK;
4776
4777 m->allDHCPServers.addChild(aDHCPServer);
4778
4779 if (aSaveRegistry)
4780 {
4781 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4782 rc = saveSettings();
4783 vboxLock.release();
4784
4785 if (FAILED(rc))
4786 unregisterDHCPServer(aDHCPServer, false /* aSaveRegistry */);
4787 }
4788
4789 return rc;
4790}
4791
4792/**
4793 * Removes the given hard disk from the hard disk registry.
4794 *
4795 * @param aHardDisk Hard disk object to remove.
4796 * @param aSaveRegistry @c true to save hard disk registry to disk (default).
4797 *
4798 * When @a aSaveRegistry is @c true, this operation may fail because of the
4799 * failed #saveSettings() method it calls. In this case, the hard disk object
4800 * will NOT be removed from the registry when this method returns. It is
4801 * therefore the responsibility of the caller to call this method as the first
4802 * step of some action that requires unregistration, before calling uninit() on
4803 * @a aHardDisk.
4804 *
4805 * @note Locks this object for writing and @a aHardDisk for reading.
4806 */
4807HRESULT VirtualBox::unregisterDHCPServer(DHCPServer *aDHCPServer,
4808 bool aSaveRegistry /*= true*/)
4809{
4810 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4811
4812 AutoCaller autoCaller(this);
4813 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4814
4815 AutoCaller dhcpServerCaller(aDHCPServer);
4816 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4817
4818 m->allDHCPServers.removeChild(aDHCPServer);
4819
4820 HRESULT rc = S_OK;
4821
4822 if (aSaveRegistry)
4823 {
4824 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4825 rc = saveSettings();
4826 vboxLock.release();
4827
4828 if (FAILED(rc))
4829 registerDHCPServer(aDHCPServer, false /* aSaveRegistry */);
4830 }
4831
4832 return rc;
4833}
4834
4835/* 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