VirtualBox

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

Last change on this file since 49496 was 49496, checked in by vboxsync, 12 years ago

build-fix: like r90651.

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