VirtualBox

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

Last change on this file since 49742 was 49742, checked in by vboxsync, 11 years ago

6813 stage 2 - Use the server side API wrapper code..

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

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