VirtualBox

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

Last change on this file since 40153 was 40153, 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.

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

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