VirtualBox

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

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

Main and FE/Qt: do not put slashes, control characters and a few others into VM file names by default. Policy adjustment.

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

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