VirtualBox

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

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

Main/VirtualBox: fix parameter checks

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

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