VirtualBox

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

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

NatNetwork: reference counting. intoroduces natNetworkRef{Inc,Dec},
if counter is 0 on Inc, corresponding network service is starting.
on Dec exceeding counter 0 network service is stoppping.

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