VirtualBox

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

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

Main/ComposeMachineFilename: And add the success case test which should have found the bug.

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