VirtualBox

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

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

Main: VirtualBox::onHostNameResolutionConfigurationChange()

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 164.9 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 48804 2013-10-02 05:10:42Z vboxsync $ */
2/** @file
3 * Implementation of IVirtualBox in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <iprt/asm.h>
19#include <iprt/base64.h>
20#include <iprt/buildconfig.h>
21#include <iprt/cpp/utils.h>
22#include <iprt/dir.h>
23#include <iprt/env.h>
24#include <iprt/file.h>
25#include <iprt/path.h>
26#include <iprt/process.h>
27#include <iprt/rand.h>
28#include <iprt/sha.h>
29#include <iprt/string.h>
30#include <iprt/stream.h>
31#include <iprt/thread.h>
32#include <iprt/uuid.h>
33#include <iprt/cpp/xml.h>
34
35#include <VBox/com/com.h>
36#include <VBox/com/array.h>
37#include "VBox/com/EventQueue.h"
38#include "VBox/com/MultiResult.h"
39
40#include <VBox/err.h>
41#include <VBox/param.h>
42#include <VBox/settings.h>
43#include <VBox/version.h>
44
45#include <package-generated.h>
46
47#include <algorithm>
48#include <set>
49#include <vector>
50#include <memory> // for auto_ptr
51
52#include "VirtualBoxImpl.h"
53
54#include "Global.h"
55#include "MachineImpl.h"
56#include "MediumImpl.h"
57#include "SharedFolderImpl.h"
58#include "ProgressImpl.h"
59#include "ProgressProxyImpl.h"
60#include "HostImpl.h"
61#include "USBControllerImpl.h"
62#include "SystemPropertiesImpl.h"
63#include "GuestOSTypeImpl.h"
64#include "NetworkServiceRunner.h"
65#include "DHCPServerImpl.h"
66#include "NATNetworkImpl.h"
67#ifdef VBOX_WITH_RESOURCE_USAGE_API
68# include "PerformanceImpl.h"
69#endif /* VBOX_WITH_RESOURCE_USAGE_API */
70#include "EventImpl.h"
71#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
3097void VirtualBox::onHostNameResolutionConfigurationChange()
3098{
3099 fireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
3100}
3101
3102
3103int VirtualBox::natNetworkRefInc(IN_BSTR aNetworkName)
3104{
3105 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3106 Bstr name(aNetworkName);
3107
3108 if (!sNatNetworkNameToRefCount[name])
3109 {
3110 ComPtr<INATNetwork> nat;
3111 HRESULT rc = FindNATNetworkByName(aNetworkName, nat.asOutParam());
3112 AssertComRCReturn(rc, -1);
3113
3114 rc = nat->Start(Bstr("whatever").raw());
3115 AssertComRCReturn(rc, -1);
3116 }
3117
3118 sNatNetworkNameToRefCount[name]++;
3119
3120 return sNatNetworkNameToRefCount[name];
3121}
3122
3123
3124int VirtualBox::natNetworkRefDec(IN_BSTR aNetworkName)
3125{
3126 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3127 Bstr name(aNetworkName);
3128
3129 if (!sNatNetworkNameToRefCount[name])
3130 return 0;
3131
3132 sNatNetworkNameToRefCount[name]--;
3133
3134 if (!sNatNetworkNameToRefCount[name])
3135 {
3136 ComPtr<INATNetwork> nat;
3137 HRESULT rc = FindNATNetworkByName(aNetworkName, nat.asOutParam());
3138 AssertComRCReturn(rc, -1);
3139
3140 rc = nat->Stop();
3141 AssertComRCReturn(rc, -1);
3142 }
3143
3144 return sNatNetworkNameToRefCount[name];
3145}
3146
3147
3148/**
3149 * @note Locks this object for reading.
3150 */
3151ComObjPtr<GuestOSType> VirtualBox::getUnknownOSType()
3152{
3153 ComObjPtr<GuestOSType> type;
3154 AutoCaller autoCaller(this);
3155 AssertComRCReturn(autoCaller.rc(), type);
3156
3157 /* unknown type must always be the first */
3158 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
3159
3160 return m->allGuestOSTypes.front();
3161}
3162
3163/**
3164 * Returns the list of opened machines (machines having direct sessions opened
3165 * by client processes) and optionally the list of direct session controls.
3166 *
3167 * @param aMachines Where to put opened machines (will be empty if none).
3168 * @param aControls Where to put direct session controls (optional).
3169 *
3170 * @note The returned lists contain smart pointers. So, clear it as soon as
3171 * it becomes no more necessary to release instances.
3172 *
3173 * @note It can be possible that a session machine from the list has been
3174 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
3175 * when accessing unprotected data directly.
3176 *
3177 * @note Locks objects for reading.
3178 */
3179void VirtualBox::getOpenedMachines(SessionMachinesList &aMachines,
3180 InternalControlList *aControls /*= NULL*/)
3181{
3182 AutoCaller autoCaller(this);
3183 AssertComRCReturnVoid(autoCaller.rc());
3184
3185 aMachines.clear();
3186 if (aControls)
3187 aControls->clear();
3188
3189 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3190
3191 for (MachinesOList::iterator it = m->allMachines.begin();
3192 it != m->allMachines.end();
3193 ++it)
3194 {
3195 ComObjPtr<SessionMachine> sm;
3196 ComPtr<IInternalSessionControl> ctl;
3197 if ((*it)->isSessionOpen(sm, &ctl))
3198 {
3199 aMachines.push_back(sm);
3200 if (aControls)
3201 aControls->push_back(ctl);
3202 }
3203 }
3204}
3205
3206/**
3207 * Gets a reference to the machine list. This is the real thing, not a copy,
3208 * so bad things will happen if the caller doesn't hold the necessary lock.
3209 *
3210 * @returns reference to machine list
3211 *
3212 * @note Caller must hold the VirtualBox object lock at least for reading.
3213 */
3214VirtualBox::MachinesOList &VirtualBox::getMachinesList(void)
3215{
3216 return m->allMachines;
3217}
3218
3219/**
3220 * Searches for a machine object with the given ID in the collection
3221 * of registered machines.
3222 *
3223 * @param aId Machine UUID to look for.
3224 * @param aPermitInaccessible If true, inaccessible machines will be found;
3225 * if false, this will fail if the given machine is inaccessible.
3226 * @param aSetError If true, set errorinfo if the machine is not found.
3227 * @param aMachine Returned machine, if found.
3228 * @return
3229 */
3230HRESULT VirtualBox::findMachine(const Guid &aId,
3231 bool fPermitInaccessible,
3232 bool aSetError,
3233 ComObjPtr<Machine> *aMachine /* = NULL */)
3234{
3235 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3236
3237 AutoCaller autoCaller(this);
3238 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3239
3240 {
3241 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3242
3243 for (MachinesOList::iterator it = m->allMachines.begin();
3244 it != m->allMachines.end();
3245 ++it)
3246 {
3247 ComObjPtr<Machine> pMachine = *it;
3248
3249 if (!fPermitInaccessible)
3250 {
3251 // skip inaccessible machines
3252 AutoCaller machCaller(pMachine);
3253 if (FAILED(machCaller.rc()))
3254 continue;
3255 }
3256
3257 if (pMachine->getId() == aId)
3258 {
3259 rc = S_OK;
3260 if (aMachine)
3261 *aMachine = pMachine;
3262 break;
3263 }
3264 }
3265 }
3266
3267 if (aSetError && FAILED(rc))
3268 rc = setError(rc,
3269 tr("Could not find a registered machine with UUID {%RTuuid}"),
3270 aId.raw());
3271
3272 return rc;
3273}
3274
3275/**
3276 * Searches for a machine object with the given name or location in the
3277 * collection of registered machines.
3278 *
3279 * @param aName Machine name or location to look for.
3280 * @param aSetError If true, set errorinfo if the machine is not found.
3281 * @param aMachine Returned machine, if found.
3282 * @return
3283 */
3284HRESULT VirtualBox::findMachineByName(const Utf8Str &aName, bool aSetError,
3285 ComObjPtr<Machine> *aMachine /* = NULL */)
3286{
3287 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3288
3289 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3290 for (MachinesOList::iterator it = m->allMachines.begin();
3291 it != m->allMachines.end();
3292 ++it)
3293 {
3294 ComObjPtr<Machine> &pMachine = *it;
3295 AutoCaller machCaller(pMachine);
3296 if (machCaller.rc())
3297 continue; // we can't ask inaccessible machines for their names
3298
3299 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
3300 if (pMachine->getName() == aName)
3301 {
3302 rc = S_OK;
3303 if (aMachine)
3304 *aMachine = pMachine;
3305 break;
3306 }
3307 if (!RTPathCompare(pMachine->getSettingsFileFull().c_str(), aName.c_str()))
3308 {
3309 rc = S_OK;
3310 if (aMachine)
3311 *aMachine = pMachine;
3312 break;
3313 }
3314 }
3315
3316 if (aSetError && FAILED(rc))
3317 rc = setError(rc,
3318 tr("Could not find a registered machine named '%s'"), aName.c_str());
3319
3320 return rc;
3321}
3322
3323static HRESULT validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
3324{
3325 /* empty strings are invalid */
3326 if (aGroup.isEmpty())
3327 return E_INVALIDARG;
3328 /* the toplevel group is valid */
3329 if (aGroup == "/")
3330 return S_OK;
3331 /* any other strings of length 1 are invalid */
3332 if (aGroup.length() == 1)
3333 return E_INVALIDARG;
3334 /* must start with a slash */
3335 if (aGroup.c_str()[0] != '/')
3336 return E_INVALIDARG;
3337 /* must not end with a slash */
3338 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3339 return E_INVALIDARG;
3340 /* check the group components */
3341 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3342 while (pStr)
3343 {
3344 char *pSlash = RTStrStr(pStr, "/");
3345 if (pSlash)
3346 {
3347 /* no empty components (or // sequences in other words) */
3348 if (pSlash == pStr)
3349 return E_INVALIDARG;
3350 /* check if the machine name rules are violated, because that means
3351 * the group components are too close to the limits. */
3352 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3353 Utf8Str tmp2(tmp);
3354 sanitiseMachineFilename(tmp);
3355 if (tmp != tmp2)
3356 return E_INVALIDARG;
3357 if (fPrimary)
3358 {
3359 HRESULT rc = pVirtualBox->findMachineByName(tmp,
3360 false /* aSetError */);
3361 if (SUCCEEDED(rc))
3362 return VBOX_E_VM_ERROR;
3363 }
3364 pStr = pSlash + 1;
3365 }
3366 else
3367 {
3368 /* check if the machine name rules are violated, because that means
3369 * the group components is too close to the limits. */
3370 Utf8Str tmp(pStr);
3371 Utf8Str tmp2(tmp);
3372 sanitiseMachineFilename(tmp);
3373 if (tmp != tmp2)
3374 return E_INVALIDARG;
3375 pStr = NULL;
3376 }
3377 }
3378 return S_OK;
3379}
3380
3381/**
3382 * Validates a machine group.
3383 *
3384 * @param aMachineGroup Machine group.
3385 * @param fPrimary Set if this is the primary group.
3386 *
3387 * @return S_OK or E_INVALIDARG
3388 */
3389HRESULT VirtualBox::validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
3390{
3391 HRESULT rc = validateMachineGroupHelper(aGroup, fPrimary, this);
3392 if (FAILED(rc))
3393 {
3394 if (rc == VBOX_E_VM_ERROR)
3395 rc = setError(E_INVALIDARG,
3396 tr("Machine group '%s' conflicts with a virtual machine name"),
3397 aGroup.c_str());
3398 else
3399 rc = setError(rc,
3400 tr("Invalid machine group '%s'"),
3401 aGroup.c_str());
3402 }
3403 return rc;
3404}
3405
3406/**
3407 * Takes a list of machine groups, and sanitizes/validates it.
3408 *
3409 * @param aMachineGroups Safearray with the machine groups.
3410 * @param pllMachineGroups Pointer to list of strings for the result.
3411 *
3412 * @return S_OK or E_INVALIDARG
3413 */
3414HRESULT VirtualBox::convertMachineGroups(ComSafeArrayIn(IN_BSTR, aMachineGroups), StringsList *pllMachineGroups)
3415{
3416 pllMachineGroups->clear();
3417 if (aMachineGroups)
3418 {
3419 com::SafeArray<IN_BSTR> machineGroups(ComSafeArrayInArg(aMachineGroups));
3420 for (size_t i = 0; i < machineGroups.size(); i++)
3421 {
3422 Utf8Str group(machineGroups[i]);
3423 if (group.length() == 0)
3424 group = "/";
3425
3426 HRESULT rc = validateMachineGroup(group, i == 0);
3427 if (FAILED(rc))
3428 return rc;
3429
3430 /* no duplicates please */
3431 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3432 == pllMachineGroups->end())
3433 pllMachineGroups->push_back(group);
3434 }
3435 if (pllMachineGroups->size() == 0)
3436 pllMachineGroups->push_back("/");
3437 }
3438 else
3439 pllMachineGroups->push_back("/");
3440
3441 return S_OK;
3442}
3443
3444/**
3445 * Searches for a Medium object with the given ID in the list of registered
3446 * hard disks.
3447 *
3448 * @param aId ID of the hard disk. Must not be empty.
3449 * @param aSetError If @c true , the appropriate error info is set in case
3450 * when the hard disk is not found.
3451 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3452 *
3453 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3454 *
3455 * @note Locks the media tree for reading.
3456 */
3457HRESULT VirtualBox::findHardDiskById(const Guid &id,
3458 bool aSetError,
3459 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3460{
3461 AssertReturn(!id.isZero(), E_INVALIDARG);
3462
3463 // we use the hard disks map, but it is protected by the
3464 // hard disk _list_ lock handle
3465 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3466
3467 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
3468 if (it != m->mapHardDisks.end())
3469 {
3470 if (aHardDisk)
3471 *aHardDisk = (*it).second;
3472 return S_OK;
3473 }
3474
3475 if (aSetError)
3476 return setError(VBOX_E_OBJECT_NOT_FOUND,
3477 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3478 id.raw());
3479
3480 return VBOX_E_OBJECT_NOT_FOUND;
3481}
3482
3483/**
3484 * Searches for a Medium object with the given ID or location in the list of
3485 * registered hard disks. If both ID and location are specified, the first
3486 * object that matches either of them (not necessarily both) is returned.
3487 *
3488 * @param aLocation Full location specification. Must not be empty.
3489 * @param aSetError If @c true , the appropriate error info is set in case
3490 * when the hard disk is not found.
3491 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3492 *
3493 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3494 *
3495 * @note Locks the media tree for reading.
3496 */
3497HRESULT VirtualBox::findHardDiskByLocation(const Utf8Str &strLocation,
3498 bool aSetError,
3499 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3500{
3501 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3502
3503 // we use the hard disks map, but it is protected by the
3504 // hard disk _list_ lock handle
3505 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3506
3507 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3508 it != m->mapHardDisks.end();
3509 ++it)
3510 {
3511 const ComObjPtr<Medium> &pHD = (*it).second;
3512
3513 AutoCaller autoCaller(pHD);
3514 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3515 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3516
3517 Utf8Str strLocationFull = pHD->getLocationFull();
3518
3519 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3520 {
3521 if (aHardDisk)
3522 *aHardDisk = pHD;
3523 return S_OK;
3524 }
3525 }
3526
3527 if (aSetError)
3528 return setError(VBOX_E_OBJECT_NOT_FOUND,
3529 tr("Could not find an open hard disk with location '%s'"),
3530 strLocation.c_str());
3531
3532 return VBOX_E_OBJECT_NOT_FOUND;
3533}
3534
3535/**
3536 * Searches for a Medium object with the given ID or location in the list of
3537 * registered DVD or floppy images, depending on the @a mediumType argument.
3538 * If both ID and file path are specified, the first object that matches either
3539 * of them (not necessarily both) is returned.
3540 *
3541 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3542 * @param aId ID of the image file (unused when NULL).
3543 * @param aLocation Full path to the image file (unused when NULL).
3544 * @param aSetError If @c true, the appropriate error info is set in case when
3545 * the image is not found.
3546 * @param aImage Where to store the found image object (can be NULL).
3547 *
3548 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3549 *
3550 * @note Locks the media tree for reading.
3551 */
3552HRESULT VirtualBox::findDVDOrFloppyImage(DeviceType_T mediumType,
3553 const Guid *aId,
3554 const Utf8Str &aLocation,
3555 bool aSetError,
3556 ComObjPtr<Medium> *aImage /* = NULL */)
3557{
3558 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3559
3560 Utf8Str location;
3561 if (!aLocation.isEmpty())
3562 {
3563 int vrc = calculateFullPath(aLocation, location);
3564 if (RT_FAILURE(vrc))
3565 return setError(VBOX_E_FILE_ERROR,
3566 tr("Invalid image file location '%s' (%Rrc)"),
3567 aLocation.c_str(),
3568 vrc);
3569 }
3570
3571 MediaOList *pMediaList;
3572
3573 switch (mediumType)
3574 {
3575 case DeviceType_DVD:
3576 pMediaList = &m->allDVDImages;
3577 break;
3578
3579 case DeviceType_Floppy:
3580 pMediaList = &m->allFloppyImages;
3581 break;
3582
3583 default:
3584 return E_INVALIDARG;
3585 }
3586
3587 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3588
3589 bool found = false;
3590
3591 for (MediaList::const_iterator it = pMediaList->begin();
3592 it != pMediaList->end();
3593 ++it)
3594 {
3595 // no AutoCaller, registered image life time is bound to this
3596 Medium *pMedium = *it;
3597 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3598 const Utf8Str &strLocationFull = pMedium->getLocationFull();
3599
3600 found = ( aId
3601 && pMedium->getId() == *aId)
3602 || ( !aLocation.isEmpty()
3603 && RTPathCompare(location.c_str(),
3604 strLocationFull.c_str()) == 0);
3605 if (found)
3606 {
3607 if (pMedium->getDeviceType() != mediumType)
3608 {
3609 if (mediumType == DeviceType_DVD)
3610 return setError(E_INVALIDARG,
3611 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3612 else
3613 return setError(E_INVALIDARG,
3614 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3615 }
3616
3617 if (aImage)
3618 *aImage = pMedium;
3619 break;
3620 }
3621 }
3622
3623 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3624
3625 if (aSetError && !found)
3626 {
3627 if (aId)
3628 setError(rc,
3629 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3630 aId->raw(),
3631 m->strSettingsFilePath.c_str());
3632 else
3633 setError(rc,
3634 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3635 aLocation.c_str(),
3636 m->strSettingsFilePath.c_str());
3637 }
3638
3639 return rc;
3640}
3641
3642/**
3643 * Searches for an IMedium object that represents the given UUID.
3644 *
3645 * If the UUID is empty (indicating an empty drive), this sets pMedium
3646 * to NULL and returns S_OK.
3647 *
3648 * If the UUID refers to a host drive of the given device type, this
3649 * sets pMedium to the object from the list in IHost and returns S_OK.
3650 *
3651 * If the UUID is an image file, this sets pMedium to the object that
3652 * findDVDOrFloppyImage() returned.
3653 *
3654 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3655 *
3656 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3657 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3658 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3659 * @param pMedium out: IMedium object found.
3660 * @return
3661 */
3662HRESULT VirtualBox::findRemoveableMedium(DeviceType_T mediumType,
3663 const Guid &uuid,
3664 bool fRefresh,
3665 bool aSetError,
3666 ComObjPtr<Medium> &pMedium)
3667{
3668 if (uuid.isZero())
3669 {
3670 // that's easy
3671 pMedium.setNull();
3672 return S_OK;
3673 }
3674 else if (!uuid.isValid())
3675 {
3676 /* handling of case invalid GUID */
3677 return setError(VBOX_E_OBJECT_NOT_FOUND,
3678 tr("Guid '%ls' is invalid"),
3679 uuid.toString().c_str());
3680 }
3681
3682 // first search for host drive with that UUID
3683 HRESULT rc = m->pHost->findHostDriveById(mediumType,
3684 uuid,
3685 fRefresh,
3686 pMedium);
3687 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3688 // then search for an image with that UUID
3689 rc = findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3690
3691 return rc;
3692}
3693
3694HRESULT VirtualBox::findGuestOSType(const Bstr &bstrOSType,
3695 GuestOSType*& pGuestOSType)
3696{
3697 /* Look for a GuestOSType object */
3698 AssertMsg(m->allGuestOSTypes.size() != 0,
3699 ("Guest OS types array must be filled"));
3700
3701 if (bstrOSType.isEmpty())
3702 {
3703 pGuestOSType = NULL;
3704 return S_OK;
3705 }
3706
3707 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3708 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3709 it != m->allGuestOSTypes.end();
3710 ++it)
3711 {
3712 if ((*it)->id() == bstrOSType)
3713 {
3714 pGuestOSType = *it;
3715 return S_OK;
3716 }
3717 }
3718
3719 return setError(VBOX_E_OBJECT_NOT_FOUND,
3720 tr("Guest OS type '%ls' is invalid"),
3721 bstrOSType.raw());
3722}
3723
3724/**
3725 * Returns the constant pseudo-machine UUID that is used to identify the
3726 * global media registry.
3727 *
3728 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3729 * in which media registry it is saved (if any): this can either be a machine
3730 * UUID, if it's in a per-machine media registry, or this global ID.
3731 *
3732 * This UUID is only used to identify the VirtualBox object while VirtualBox
3733 * is running. It is a compile-time constant and not saved anywhere.
3734 *
3735 * @return
3736 */
3737const Guid& VirtualBox::getGlobalRegistryId() const
3738{
3739 return m->uuidMediaRegistry;
3740}
3741
3742const ComObjPtr<Host>& VirtualBox::host() const
3743{
3744 return m->pHost;
3745}
3746
3747SystemProperties* VirtualBox::getSystemProperties() const
3748{
3749 return m->pSystemProperties;
3750}
3751
3752#ifdef VBOX_WITH_EXTPACK
3753/**
3754 * Getter that SystemProperties and others can use to talk to the extension
3755 * pack manager.
3756 */
3757ExtPackManager* VirtualBox::getExtPackManager() const
3758{
3759 return m->ptrExtPackManager;
3760}
3761#endif
3762
3763/**
3764 * Getter that machines can talk to the autostart database.
3765 */
3766AutostartDb* VirtualBox::getAutostartDb() const
3767{
3768 return m->pAutostartDb;
3769}
3770
3771#ifdef VBOX_WITH_RESOURCE_USAGE_API
3772const ComObjPtr<PerformanceCollector>& VirtualBox::performanceCollector() const
3773{
3774 return m->pPerformanceCollector;
3775}
3776#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3777
3778/**
3779 * Returns the default machine folder from the system properties
3780 * with proper locking.
3781 * @return
3782 */
3783void VirtualBox::getDefaultMachineFolder(Utf8Str &str) const
3784{
3785 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3786 str = m->pSystemProperties->m->strDefaultMachineFolder;
3787}
3788
3789/**
3790 * Returns the default hard disk format from the system properties
3791 * with proper locking.
3792 * @return
3793 */
3794void VirtualBox::getDefaultHardDiskFormat(Utf8Str &str) const
3795{
3796 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3797 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3798}
3799
3800const Utf8Str& VirtualBox::homeDir() const
3801{
3802 return m->strHomeDir;
3803}
3804
3805/**
3806 * Calculates the absolute path of the given path taking the VirtualBox home
3807 * directory as the current directory.
3808 *
3809 * @param aPath Path to calculate the absolute path for.
3810 * @param aResult Where to put the result (used only on success, can be the
3811 * same Utf8Str instance as passed in @a aPath).
3812 * @return IPRT result.
3813 *
3814 * @note Doesn't lock any object.
3815 */
3816int VirtualBox::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3817{
3818 AutoCaller autoCaller(this);
3819 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3820
3821 /* no need to lock since mHomeDir is const */
3822
3823 char folder[RTPATH_MAX];
3824 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3825 strPath.c_str(),
3826 folder,
3827 sizeof(folder));
3828 if (RT_SUCCESS(vrc))
3829 aResult = folder;
3830
3831 return vrc;
3832}
3833
3834/**
3835 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3836 * if it is a subdirectory thereof, or simply copying it otherwise.
3837 *
3838 * @param strSource Path to evalue and copy.
3839 * @param strTarget Buffer to receive target path.
3840 */
3841void VirtualBox::copyPathRelativeToConfig(const Utf8Str &strSource,
3842 Utf8Str &strTarget)
3843{
3844 AutoCaller autoCaller(this);
3845 AssertComRCReturnVoid(autoCaller.rc());
3846
3847 // no need to lock since mHomeDir is const
3848
3849 // use strTarget as a temporary buffer to hold the machine settings dir
3850 strTarget = m->strHomeDir;
3851 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3852 // is relative: then append what's left
3853 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3854 else
3855 // is not relative: then overwrite
3856 strTarget = strSource;
3857}
3858
3859// private methods
3860/////////////////////////////////////////////////////////////////////////////
3861
3862/**
3863 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3864 * location already registered.
3865 *
3866 * On return, sets @a aConflict to the string describing the conflicting medium,
3867 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3868 * either case. A failure is unexpected.
3869 *
3870 * @param aId UUID to check.
3871 * @param aLocation Location to check.
3872 * @param aConflict Where to return parameters of the conflicting medium.
3873 * @param ppMedium Medium reference in case this is simply a duplicate.
3874 *
3875 * @note Locks the media tree and media objects for reading.
3876 */
3877HRESULT VirtualBox::checkMediaForConflicts(const Guid &aId,
3878 const Utf8Str &aLocation,
3879 Utf8Str &aConflict,
3880 ComObjPtr<Medium> *ppMedium)
3881{
3882 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
3883 AssertReturn(ppMedium, E_INVALIDARG);
3884
3885 aConflict.setNull();
3886 ppMedium->setNull();
3887
3888 AutoReadLock alock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3889
3890 HRESULT rc = S_OK;
3891
3892 ComObjPtr<Medium> pMediumFound;
3893 const char *pcszType = NULL;
3894
3895 if (aId.isValid() && !aId.isZero())
3896 rc = findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3897 if (FAILED(rc) && !aLocation.isEmpty())
3898 rc = findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3899 if (SUCCEEDED(rc))
3900 pcszType = tr("hard disk");
3901
3902 if (!pcszType)
3903 {
3904 rc = findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3905 if (SUCCEEDED(rc))
3906 pcszType = tr("CD/DVD image");
3907 }
3908
3909 if (!pcszType)
3910 {
3911 rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3912 if (SUCCEEDED(rc))
3913 pcszType = tr("floppy image");
3914 }
3915
3916 if (pcszType && pMediumFound)
3917 {
3918 /* Note: no AutoCaller since bound to this */
3919 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3920
3921 Utf8Str strLocFound = pMediumFound->getLocationFull();
3922 Guid idFound = pMediumFound->getId();
3923
3924 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3925 && (idFound == aId)
3926 )
3927 *ppMedium = pMediumFound;
3928
3929 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3930 pcszType,
3931 strLocFound.c_str(),
3932 idFound.raw());
3933 }
3934
3935 return S_OK;
3936}
3937
3938/**
3939 * Checks whether the given UUID is already in use by one medium for the
3940 * given device type.
3941 *
3942 * @returns true if the UUID is already in use
3943 * fale otherwise
3944 * @param aId The UUID to check.
3945 * @param deviceType The device type the UUID is going to be checked for
3946 * conflicts.
3947 */
3948bool VirtualBox::isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
3949{
3950 /* A zero UUID is invalid here, always claim that it is already used. */
3951 AssertReturn(!aId.isZero(), true);
3952
3953 AutoReadLock alock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3954
3955 HRESULT rc = S_OK;
3956 bool fInUse = false;
3957
3958 ComObjPtr<Medium> pMediumFound;
3959
3960 switch (deviceType)
3961 {
3962 case DeviceType_HardDisk:
3963 rc = findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3964 break;
3965 case DeviceType_DVD:
3966 rc = findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3967 break;
3968 case DeviceType_Floppy:
3969 rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3970 break;
3971 default:
3972 AssertMsgFailed(("Invalid device type %d\n", deviceType));
3973 }
3974
3975 if (SUCCEEDED(rc) && pMediumFound)
3976 fInUse = true;
3977
3978 return fInUse;
3979}
3980
3981/**
3982 * Called from Machine::prepareSaveSettings() when it has detected
3983 * that a machine has been renamed. Such renames will require
3984 * updating the global media registry during the
3985 * VirtualBox::saveSettings() that follows later.
3986*
3987 * When a machine is renamed, there may well be media (in particular,
3988 * diff images for snapshots) in the global registry that will need
3989 * to have their paths updated. Before 3.2, Machine::saveSettings
3990 * used to call VirtualBox::saveSettings implicitly, which was both
3991 * unintuitive and caused locking order problems. Now, we remember
3992 * such pending name changes with this method so that
3993 * VirtualBox::saveSettings() can process them properly.
3994 */
3995void VirtualBox::rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3996 const Utf8Str &strNewConfigDir)
3997{
3998 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3999
4000 Data::PendingMachineRename pmr;
4001 pmr.strConfigDirOld = strOldConfigDir;
4002 pmr.strConfigDirNew = strNewConfigDir;
4003 m->llPendingMachineRenames.push_back(pmr);
4004}
4005
4006struct SaveMediaRegistriesDesc
4007{
4008 MediaList llMedia;
4009 ComObjPtr<VirtualBox> pVirtualBox;
4010};
4011
4012static int fntSaveMediaRegistries(RTTHREAD ThreadSelf, void *pvUser)
4013{
4014 NOREF(ThreadSelf);
4015 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
4016 if (!pDesc)
4017 {
4018 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
4019 return VERR_INVALID_PARAMETER;
4020 }
4021
4022 for (MediaList::const_iterator it = pDesc->llMedia.begin();
4023 it != pDesc->llMedia.end();
4024 ++it)
4025 {
4026 Medium *pMedium = *it;
4027 pMedium->markRegistriesModified();
4028 }
4029
4030 pDesc->pVirtualBox->saveModifiedRegistries();
4031
4032 pDesc->llMedia.clear();
4033 pDesc->pVirtualBox.setNull();
4034 delete pDesc;
4035
4036 return VINF_SUCCESS;
4037}
4038
4039/**
4040 * Goes through all known media (hard disks, floppies and DVDs) and saves
4041 * those into the given settings::MediaRegistry structures whose registry
4042 * ID match the given UUID.
4043 *
4044 * Before actually writing to the structures, all media paths (not just the
4045 * ones for the given registry) are updated if machines have been renamed
4046 * since the last call.
4047 *
4048 * This gets called from two contexts:
4049 *
4050 * -- VirtualBox::saveSettings() with the UUID of the global registry
4051 * (VirtualBox::Data.uuidRegistry); this will save those media
4052 * which had been loaded from the global registry or have been
4053 * attached to a "legacy" machine which can't save its own registry;
4054 *
4055 * -- Machine::saveSettings() with the UUID of a machine, if a medium
4056 * has been attached to a machine created with VirtualBox 4.0 or later.
4057 *
4058 * Media which have only been temporarily opened without having been
4059 * attached to a machine have a NULL registry UUID and therefore don't
4060 * get saved.
4061 *
4062 * This locks the media tree. Throws HRESULT on errors!
4063 *
4064 * @param mediaRegistry Settings structure to fill.
4065 * @param uuidRegistry The UUID of the media registry; either a machine UUID (if machine registry) or the UUID of the global registry.
4066 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
4067 */
4068void VirtualBox::saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4069 const Guid &uuidRegistry,
4070 const Utf8Str &strMachineFolder)
4071{
4072 // lock all media for the following; use a write lock because we're
4073 // modifying the PendingMachineRenamesList, which is protected by this
4074 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4075
4076 // if a machine was renamed, then we'll need to refresh media paths
4077 if (m->llPendingMachineRenames.size())
4078 {
4079 // make a single list from the three media lists so we don't need three loops
4080 MediaList llAllMedia;
4081 // with hard disks, we must use the map, not the list, because the list only has base images
4082 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
4083 llAllMedia.push_back(it->second);
4084 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
4085 llAllMedia.push_back(*it);
4086 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
4087 llAllMedia.push_back(*it);
4088
4089 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
4090 for (MediaList::iterator it = llAllMedia.begin();
4091 it != llAllMedia.end();
4092 ++it)
4093 {
4094 Medium *pMedium = *it;
4095 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
4096 it2 != m->llPendingMachineRenames.end();
4097 ++it2)
4098 {
4099 const Data::PendingMachineRename &pmr = *it2;
4100 HRESULT rc = pMedium->updatePath(pmr.strConfigDirOld,
4101 pmr.strConfigDirNew);
4102 if (SUCCEEDED(rc))
4103 {
4104 // Remember which medium objects has been changed,
4105 // to trigger saving their registries later.
4106 pDesc->llMedia.push_back(pMedium);
4107 } else if (rc == VBOX_E_FILE_ERROR)
4108 /* nothing */;
4109 else
4110 AssertComRC(rc);
4111 }
4112 }
4113 // done, don't do it again until we have more machine renames
4114 m->llPendingMachineRenames.clear();
4115
4116 if (pDesc->llMedia.size())
4117 {
4118 // Handle the media registry saving in a separate thread, to
4119 // avoid giant locking problems and passing up the list many
4120 // levels up to whoever triggered saveSettings, as there are
4121 // lots of places which would need to handle saving more settings.
4122 pDesc->pVirtualBox = this;
4123 int vrc = RTThreadCreate(NULL,
4124 fntSaveMediaRegistries,
4125 (void *)pDesc,
4126 0, // cbStack (default)
4127 RTTHREADTYPE_MAIN_WORKER,
4128 0, // flags
4129 "SaveMediaReg");
4130 ComAssertRC(vrc);
4131 // failure means that settings aren't saved, but there isn't
4132 // much we can do besides avoiding memory leaks
4133 if (RT_FAILURE(vrc))
4134 {
4135 LogRelFunc(("Failed to create thread for saving media registries (%Rrc)\n", vrc));
4136 delete pDesc;
4137 }
4138 }
4139 else
4140 delete pDesc;
4141 }
4142
4143 struct {
4144 MediaOList &llSource;
4145 settings::MediaList &llTarget;
4146 } s[] =
4147 {
4148 // hard disks
4149 { m->allHardDisks, mediaRegistry.llHardDisks },
4150 // CD/DVD images
4151 { m->allDVDImages, mediaRegistry.llDvdImages },
4152 // floppy images
4153 { m->allFloppyImages, mediaRegistry.llFloppyImages }
4154 };
4155
4156 HRESULT rc;
4157
4158 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
4159 {
4160 MediaOList &llSource = s[i].llSource;
4161 settings::MediaList &llTarget = s[i].llTarget;
4162 llTarget.clear();
4163 for (MediaList::const_iterator it = llSource.begin();
4164 it != llSource.end();
4165 ++it)
4166 {
4167 Medium *pMedium = *it;
4168 AutoCaller autoCaller(pMedium);
4169 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
4170 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4171
4172 if (pMedium->isInRegistry(uuidRegistry))
4173 {
4174 settings::Medium med;
4175 rc = pMedium->saveSettings(med, strMachineFolder); // this recurses into child hard disks
4176 if (FAILED(rc)) throw rc;
4177 llTarget.push_back(med);
4178 }
4179 }
4180 }
4181}
4182
4183/**
4184 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
4185 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
4186 * places internally when settings need saving.
4187 *
4188 * @note Caller must have locked the VirtualBox object for writing and must not hold any
4189 * other locks since this locks all kinds of member objects and trees temporarily,
4190 * which could cause conflicts.
4191 */
4192HRESULT VirtualBox::saveSettings()
4193{
4194 AutoCaller autoCaller(this);
4195 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4196
4197 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
4198 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
4199
4200 HRESULT rc = S_OK;
4201
4202 try
4203 {
4204 // machines
4205 m->pMainConfigFile->llMachines.clear();
4206 {
4207 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4208 for (MachinesOList::iterator it = m->allMachines.begin();
4209 it != m->allMachines.end();
4210 ++it)
4211 {
4212 Machine *pMachine = *it;
4213 // save actual machine registry entry
4214 settings::MachineRegistryEntry mre;
4215 rc = pMachine->saveRegistryEntry(mre);
4216 m->pMainConfigFile->llMachines.push_back(mre);
4217 }
4218 }
4219
4220 saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
4221 m->uuidMediaRegistry, // global media registry ID
4222 Utf8Str::Empty); // strMachineFolder
4223
4224 m->pMainConfigFile->llDhcpServers.clear();
4225 {
4226 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4227 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4228 it != m->allDHCPServers.end();
4229 ++it)
4230 {
4231 settings::DHCPServer d;
4232 rc = (*it)->saveSettings(d);
4233 if (FAILED(rc)) throw rc;
4234 m->pMainConfigFile->llDhcpServers.push_back(d);
4235 }
4236 }
4237
4238#ifdef VBOX_WITH_NAT_SERVICE
4239 /* Saving NAT Network configuration */
4240 m->pMainConfigFile->llNATNetworks.clear();
4241 {
4242 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4243 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4244 it != m->allNATNetworks.end();
4245 ++it)
4246 {
4247 settings::NATNetwork n;
4248 rc = (*it)->saveSettings(n);
4249 if (FAILED(rc)) throw rc;
4250 m->pMainConfigFile->llNATNetworks.push_back(n);
4251 }
4252 }
4253#endif
4254
4255 // leave extra data alone, it's still in the config file
4256
4257 // host data (USB filters)
4258 rc = m->pHost->saveSettings(m->pMainConfigFile->host);
4259 if (FAILED(rc)) throw rc;
4260
4261 rc = m->pSystemProperties->saveSettings(m->pMainConfigFile->systemProperties);
4262 if (FAILED(rc)) throw rc;
4263
4264 // and write out the XML, still under the lock
4265 m->pMainConfigFile->write(m->strSettingsFilePath);
4266 }
4267 catch (HRESULT err)
4268 {
4269 /* we assume that error info is set by the thrower */
4270 rc = err;
4271 }
4272 catch (...)
4273 {
4274 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
4275 }
4276
4277 return rc;
4278}
4279
4280/**
4281 * Helper to register the machine.
4282 *
4283 * When called during VirtualBox startup, adds the given machine to the
4284 * collection of registered machines. Otherwise tries to mark the machine
4285 * as registered, and, if succeeded, adds it to the collection and
4286 * saves global settings.
4287 *
4288 * @note The caller must have added itself as a caller of the @a aMachine
4289 * object if calls this method not on VirtualBox startup.
4290 *
4291 * @param aMachine machine to register
4292 *
4293 * @note Locks objects!
4294 */
4295HRESULT VirtualBox::registerMachine(Machine *aMachine)
4296{
4297 ComAssertRet(aMachine, E_INVALIDARG);
4298
4299 AutoCaller autoCaller(this);
4300 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4301
4302 HRESULT rc = S_OK;
4303
4304 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4305
4306 {
4307 ComObjPtr<Machine> pMachine;
4308 rc = findMachine(aMachine->getId(),
4309 true /* fPermitInaccessible */,
4310 false /* aDoSetError */,
4311 &pMachine);
4312 if (SUCCEEDED(rc))
4313 {
4314 /* sanity */
4315 AutoLimitedCaller machCaller(pMachine);
4316 AssertComRC(machCaller.rc());
4317
4318 return setError(E_INVALIDARG,
4319 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
4320 aMachine->getId().raw(),
4321 pMachine->getSettingsFileFull().c_str());
4322 }
4323
4324 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
4325 rc = S_OK;
4326 }
4327
4328 if (autoCaller.state() != InInit)
4329 {
4330 rc = aMachine->prepareRegister();
4331 if (FAILED(rc)) return rc;
4332 }
4333
4334 /* add to the collection of registered machines */
4335 m->allMachines.addChild(aMachine);
4336
4337 if (autoCaller.state() != InInit)
4338 rc = saveSettings();
4339
4340 return rc;
4341}
4342
4343/**
4344 * Remembers the given medium object by storing it in either the global
4345 * medium registry or a machine one.
4346 *
4347 * @note Caller must hold the media tree lock for writing; in addition, this
4348 * locks @a pMedium for reading
4349 *
4350 * @param pMedium Medium object to remember.
4351 * @param ppMedium Actually stored medium object. Can be different if due
4352 * to an unavoidable race there was a duplicate Medium object
4353 * created.
4354 * @param argType Either DeviceType_HardDisk, DeviceType_DVD or DeviceType_Floppy.
4355 * @return
4356 */
4357HRESULT VirtualBox::registerMedium(const ComObjPtr<Medium> &pMedium,
4358 ComObjPtr<Medium> *ppMedium,
4359 DeviceType_T argType)
4360{
4361 AssertReturn(pMedium != NULL, E_INVALIDARG);
4362 AssertReturn(ppMedium != NULL, E_INVALIDARG);
4363
4364 AutoCaller autoCaller(this);
4365 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4366
4367 AutoCaller mediumCaller(pMedium);
4368 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4369
4370 const char *pszDevType = NULL;
4371 ObjectsList<Medium> *pall = NULL;
4372 switch (argType)
4373 {
4374 case DeviceType_HardDisk:
4375 pall = &m->allHardDisks;
4376 pszDevType = tr("hard disk");
4377 break;
4378 case DeviceType_DVD:
4379 pszDevType = tr("DVD image");
4380 pall = &m->allDVDImages;
4381 break;
4382 case DeviceType_Floppy:
4383 pszDevType = tr("floppy image");
4384 pall = &m->allFloppyImages;
4385 break;
4386 default:
4387 AssertMsgFailedReturn(("invalid device type %d", argType), E_INVALIDARG);
4388 }
4389
4390 // caller must hold the media tree write lock
4391 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4392
4393 Guid id;
4394 Utf8Str strLocationFull;
4395 ComObjPtr<Medium> pParent;
4396 {
4397 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4398 id = pMedium->getId();
4399 strLocationFull = pMedium->getLocationFull();
4400 pParent = pMedium->getParent();
4401 }
4402
4403 HRESULT rc;
4404
4405 Utf8Str strConflict;
4406 ComObjPtr<Medium> pDupMedium;
4407 rc = checkMediaForConflicts(id,
4408 strLocationFull,
4409 strConflict,
4410 &pDupMedium);
4411 if (FAILED(rc)) return rc;
4412
4413 if (pDupMedium.isNull())
4414 {
4415 if (strConflict.length())
4416 return setError(E_INVALIDARG,
4417 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4418 pszDevType,
4419 strLocationFull.c_str(),
4420 id.raw(),
4421 strConflict.c_str(),
4422 m->strSettingsFilePath.c_str());
4423
4424 // add to the collection if it is a base medium
4425 if (pParent.isNull())
4426 pall->getList().push_back(pMedium);
4427
4428 // store all hard disks (even differencing images) in the map
4429 if (argType == DeviceType_HardDisk)
4430 m->mapHardDisks[id] = pMedium;
4431
4432 *ppMedium = pMedium;
4433 }
4434 else
4435 {
4436 // pMedium may be the last reference to the Medium object, and the
4437 // caller may have specified the same ComObjPtr as the output parameter.
4438 // In this case the assignment will uninit the object, and we must not
4439 // have a caller pending.
4440 mediumCaller.release();
4441 *ppMedium = pDupMedium;
4442 }
4443
4444 return rc;
4445}
4446
4447/**
4448 * Removes the given medium from the respective registry.
4449 *
4450 * @param pMedium Hard disk object to remove.
4451 *
4452 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4453 */
4454HRESULT VirtualBox::unregisterMedium(Medium *pMedium)
4455{
4456 AssertReturn(pMedium != NULL, E_INVALIDARG);
4457
4458 AutoCaller autoCaller(this);
4459 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4460
4461 AutoCaller mediumCaller(pMedium);
4462 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4463
4464 // caller must hold the media tree write lock
4465 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4466
4467 Guid id;
4468 ComObjPtr<Medium> pParent;
4469 DeviceType_T devType;
4470 {
4471 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4472 id = pMedium->getId();
4473 pParent = pMedium->getParent();
4474 devType = pMedium->getDeviceType();
4475 }
4476
4477 ObjectsList<Medium> *pall = NULL;
4478 switch (devType)
4479 {
4480 case DeviceType_HardDisk:
4481 pall = &m->allHardDisks;
4482 break;
4483 case DeviceType_DVD:
4484 pall = &m->allDVDImages;
4485 break;
4486 case DeviceType_Floppy:
4487 pall = &m->allFloppyImages;
4488 break;
4489 default:
4490 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4491 }
4492
4493 // remove from the collection if it is a base medium
4494 if (pParent.isNull())
4495 pall->getList().remove(pMedium);
4496
4497 // remove all hard disks (even differencing images) from map
4498 if (devType == DeviceType_HardDisk)
4499 {
4500 size_t cnt = m->mapHardDisks.erase(id);
4501 Assert(cnt == 1);
4502 NOREF(cnt);
4503 }
4504
4505 return S_OK;
4506}
4507
4508/**
4509 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4510 * with children appearing before their parents.
4511 * @param llMedia
4512 * @param pMedium
4513 */
4514void VirtualBox::pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4515{
4516 // recurse first, then add ourselves; this way children end up on the
4517 // list before their parents
4518
4519 const MediaList &llChildren = pMedium->getChildren();
4520 for (MediaList::const_iterator it = llChildren.begin();
4521 it != llChildren.end();
4522 ++it)
4523 {
4524 Medium *pChild = *it;
4525 pushMediumToListWithChildren(llMedia, pChild);
4526 }
4527
4528 Log(("Pushing medium %RTuuid\n", pMedium->getId().raw()));
4529 llMedia.push_back(pMedium);
4530}
4531
4532/**
4533 * Unregisters all Medium objects which belong to the given machine registry.
4534 * Gets called from Machine::uninit() just before the machine object dies
4535 * and must only be called with a machine UUID as the registry ID.
4536 *
4537 * Locks the media tree.
4538 *
4539 * @param uuidMachine Medium registry ID (always a machine UUID)
4540 * @return
4541 */
4542HRESULT VirtualBox::unregisterMachineMedia(const Guid &uuidMachine)
4543{
4544 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
4545
4546 LogFlowFuncEnter();
4547
4548 AutoCaller autoCaller(this);
4549 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4550
4551 MediaList llMedia2Close;
4552
4553 {
4554 AutoWriteLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4555
4556 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4557 it != m->allHardDisks.getList().end();
4558 ++it)
4559 {
4560 ComObjPtr<Medium> pMedium = *it;
4561 AutoCaller medCaller(pMedium);
4562 if (FAILED(medCaller.rc())) return medCaller.rc();
4563 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4564
4565 if (pMedium->isInRegistry(uuidMachine))
4566 // recursively with children first
4567 pushMediumToListWithChildren(llMedia2Close, pMedium);
4568 }
4569 }
4570
4571 for (MediaList::iterator it = llMedia2Close.begin();
4572 it != llMedia2Close.end();
4573 ++it)
4574 {
4575 ComObjPtr<Medium> pMedium = *it;
4576 Log(("Closing medium %RTuuid\n", pMedium->getId().raw()));
4577 AutoCaller mac(pMedium);
4578 pMedium->close(mac);
4579 }
4580
4581 LogFlowFuncLeave();
4582
4583 return S_OK;
4584}
4585
4586/**
4587 * Removes the given machine object from the internal list of registered machines.
4588 * Called from Machine::Unregister().
4589 * @param pMachine
4590 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4591 * @return
4592 */
4593HRESULT VirtualBox::unregisterMachine(Machine *pMachine,
4594 const Guid &id)
4595{
4596 // remove from the collection of registered machines
4597 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4598 m->allMachines.removeChild(pMachine);
4599 // save the global registry
4600 HRESULT rc = saveSettings();
4601 alock.release();
4602
4603 /*
4604 * Now go over all known media and checks if they were registered in the
4605 * media registry of the given machine. Each such medium is then moved to
4606 * a different media registry to make sure it doesn't get lost since its
4607 * media registry is about to go away.
4608 *
4609 * This fixes the following use case: Image A.vdi of machine A is also used
4610 * by machine B, but registered in the media registry of machine A. If machine
4611 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4612 * become inaccessible.
4613 */
4614 {
4615 AutoReadLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4616 // iterate over the list of *base* images
4617 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4618 it != m->allHardDisks.getList().end();
4619 ++it)
4620 {
4621 ComObjPtr<Medium> &pMedium = *it;
4622 AutoCaller medCaller(pMedium);
4623 if (FAILED(medCaller.rc())) return medCaller.rc();
4624 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4625
4626 if (pMedium->removeRegistry(id, true /* fRecurse */))
4627 {
4628 // machine ID was found in base medium's registry list:
4629 // move this base image and all its children to another registry then
4630 // 1) first, find a better registry to add things to
4631 const Guid *puuidBetter = pMedium->getAnyMachineBackref();
4632 if (puuidBetter)
4633 {
4634 // 2) better registry found: then use that
4635 pMedium->addRegistry(*puuidBetter, true /* fRecurse */);
4636 // 3) and make sure the registry is saved below
4637 mlock.release();
4638 tlock.release();
4639 markRegistryModified(*puuidBetter);
4640 tlock.acquire();
4641 mlock.release();
4642 }
4643 }
4644 }
4645 }
4646
4647 saveModifiedRegistries();
4648
4649 /* fire an event */
4650 onMachineRegistered(id, FALSE);
4651
4652 return rc;
4653}
4654
4655/**
4656 * Marks the registry for @a uuid as modified, so that it's saved in a later
4657 * call to saveModifiedRegistries().
4658 *
4659 * @param uuid
4660 */
4661void VirtualBox::markRegistryModified(const Guid &uuid)
4662{
4663 if (uuid == getGlobalRegistryId())
4664 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4665 else
4666 {
4667 ComObjPtr<Machine> pMachine;
4668 HRESULT rc = findMachine(uuid,
4669 false /* fPermitInaccessible */,
4670 false /* aSetError */,
4671 &pMachine);
4672 if (SUCCEEDED(rc))
4673 {
4674 AutoCaller machineCaller(pMachine);
4675 if (SUCCEEDED(machineCaller.rc()))
4676 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4677 }
4678 }
4679}
4680
4681/**
4682 * Saves all settings files according to the modified flags in the Machine
4683 * objects and in the VirtualBox object.
4684 *
4685 * This locks machines and the VirtualBox object as necessary, so better not
4686 * hold any locks before calling this.
4687 *
4688 * @return
4689 */
4690void VirtualBox::saveModifiedRegistries()
4691{
4692 HRESULT rc = S_OK;
4693 bool fNeedsGlobalSettings = false;
4694 uint64_t uOld;
4695
4696 {
4697 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4698 for (MachinesOList::iterator it = m->allMachines.begin();
4699 it != m->allMachines.end();
4700 ++it)
4701 {
4702 const ComObjPtr<Machine> &pMachine = *it;
4703
4704 for (;;)
4705 {
4706 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4707 if (!uOld)
4708 break;
4709 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4710 break;
4711 ASMNopPause();
4712 }
4713 if (uOld)
4714 {
4715 AutoCaller autoCaller(pMachine);
4716 if (FAILED(autoCaller.rc()))
4717 continue;
4718 /* object is already dead, no point in saving settings */
4719 if (autoCaller.state() != Ready)
4720 continue;
4721 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
4722 rc = pMachine->saveSettings(&fNeedsGlobalSettings,
4723 Machine::SaveS_Force); // caller said save, so stop arguing
4724 }
4725 }
4726 }
4727
4728 for (;;)
4729 {
4730 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4731 if (!uOld)
4732 break;
4733 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4734 break;
4735 ASMNopPause();
4736 }
4737 if (uOld || fNeedsGlobalSettings)
4738 {
4739 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4740 rc = saveSettings();
4741 }
4742 NOREF(rc); /* XXX */
4743}
4744
4745
4746/* static */
4747const Bstr &VirtualBox::getVersionNormalized()
4748{
4749 return sVersionNormalized;
4750}
4751
4752/**
4753 * Checks if the path to the specified file exists, according to the path
4754 * information present in the file name. Optionally the path is created.
4755 *
4756 * Note that the given file name must contain the full path otherwise the
4757 * extracted relative path will be created based on the current working
4758 * directory which is normally unknown.
4759 *
4760 * @param aFileName Full file name which path is checked/created.
4761 * @param aCreate Flag if the path should be created if it doesn't exist.
4762 *
4763 * @return Extended error information on failure to check/create the path.
4764 */
4765/* static */
4766HRESULT VirtualBox::ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4767{
4768 Utf8Str strDir(strFileName);
4769 strDir.stripFilename();
4770 if (!RTDirExists(strDir.c_str()))
4771 {
4772 if (fCreate)
4773 {
4774 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4775 if (RT_FAILURE(vrc))
4776 return setErrorStatic(VBOX_E_IPRT_ERROR,
4777 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4778 strDir.c_str(),
4779 vrc));
4780 }
4781 else
4782 return setErrorStatic(VBOX_E_IPRT_ERROR,
4783 Utf8StrFmt(tr("Directory '%s' does not exist"),
4784 strDir.c_str()));
4785 }
4786
4787 return S_OK;
4788}
4789
4790const Utf8Str& VirtualBox::settingsFilePath()
4791{
4792 return m->strSettingsFilePath;
4793}
4794
4795/**
4796 * Returns the lock handle which protects the machines list. As opposed
4797 * to version 3.1 and earlier, these lists are no longer protected by the
4798 * VirtualBox lock, but by this more specialized lock. Mind the locking
4799 * order: always request this lock after the VirtualBox object lock but
4800 * before the locks of any machine object. See AutoLock.h.
4801 */
4802RWLockHandle& VirtualBox::getMachinesListLockHandle()
4803{
4804 return m->lockMachines;
4805}
4806
4807/**
4808 * Returns the lock handle which protects the media trees (hard disks,
4809 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4810 * are no longer protected by the VirtualBox lock, but by this more
4811 * specialized lock. Mind the locking order: always request this lock
4812 * after the VirtualBox object lock but before the locks of the media
4813 * objects contained in these lists. See AutoLock.h.
4814 */
4815RWLockHandle& VirtualBox::getMediaTreeLockHandle()
4816{
4817 return m->lockMedia;
4818}
4819
4820/**
4821 * Thread function that handles custom events posted using #postEvent().
4822 */
4823// static
4824DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4825{
4826 LogFlowFuncEnter();
4827
4828 AssertReturn(pvUser, VERR_INVALID_POINTER);
4829
4830 HRESULT hr = com::Initialize();
4831 if (FAILED(hr))
4832 return VERR_COM_UNEXPECTED;
4833
4834 int rc = VINF_SUCCESS;
4835
4836 try
4837 {
4838 /* Create an event queue for the current thread. */
4839 EventQueue *pEventQueue = new EventQueue();
4840 AssertPtr(pEventQueue);
4841
4842 /* Return the queue to the one who created this thread. */
4843 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
4844
4845 /* signal that we're ready. */
4846 RTThreadUserSignal(thread);
4847
4848 /*
4849 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4850 * we must not stop processing events and delete the pEventQueue object. This must
4851 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4852 * See @bugref{5724}.
4853 */
4854 for (;;)
4855 {
4856 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
4857 if (rc == VERR_INTERRUPTED)
4858 {
4859 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
4860 rc = VINF_SUCCESS; /* Set success when exiting. */
4861 break;
4862 }
4863 }
4864
4865 delete pEventQueue;
4866 }
4867 catch (std::bad_alloc &ba)
4868 {
4869 rc = VERR_NO_MEMORY;
4870 NOREF(ba);
4871 }
4872
4873 com::Shutdown();
4874
4875 LogFlowFuncLeaveRC(rc);
4876 return rc;
4877}
4878
4879
4880////////////////////////////////////////////////////////////////////////////////
4881
4882/**
4883 * Takes the current list of registered callbacks of the managed VirtualBox
4884 * instance, and calls #handleCallback() for every callback item from the
4885 * list, passing the item as an argument.
4886 *
4887 * @note Locks the managed VirtualBox object for reading but leaves the lock
4888 * before iterating over callbacks and calling their methods.
4889 */
4890void *VirtualBox::CallbackEvent::handler()
4891{
4892 if (!mVirtualBox)
4893 return NULL;
4894
4895 AutoCaller autoCaller(mVirtualBox);
4896 if (!autoCaller.isOk())
4897 {
4898 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4899 autoCaller.state()));
4900 /* We don't need mVirtualBox any more, so release it */
4901 mVirtualBox = NULL;
4902 return NULL;
4903 }
4904
4905 {
4906 VBoxEventDesc evDesc;
4907 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4908
4909 evDesc.fire(/* don't wait for delivery */0);
4910 }
4911
4912 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4913 return NULL;
4914}
4915
4916//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4917//{
4918// return E_NOTIMPL;
4919//}
4920
4921STDMETHODIMP VirtualBox::CreateDHCPServer(IN_BSTR aName, IDHCPServer ** aServer)
4922{
4923 CheckComArgStrNotEmptyOrNull(aName);
4924 CheckComArgNotNull(aServer);
4925
4926 AutoCaller autoCaller(this);
4927 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4928
4929 ComObjPtr<DHCPServer> dhcpServer;
4930 dhcpServer.createObject();
4931 HRESULT rc = dhcpServer->init(this, aName);
4932 if (FAILED(rc)) return rc;
4933
4934 rc = registerDHCPServer(dhcpServer, true);
4935 if (FAILED(rc)) return rc;
4936
4937 dhcpServer.queryInterfaceTo(aServer);
4938
4939 return rc;
4940}
4941
4942STDMETHODIMP VirtualBox::FindDHCPServerByNetworkName(IN_BSTR aName, IDHCPServer ** aServer)
4943{
4944 CheckComArgStrNotEmptyOrNull(aName);
4945 CheckComArgNotNull(aServer);
4946
4947 AutoCaller autoCaller(this);
4948 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4949
4950 HRESULT rc;
4951 Bstr bstr;
4952 ComPtr<DHCPServer> found;
4953
4954 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4955
4956 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4957 it != m->allDHCPServers.end();
4958 ++it)
4959 {
4960 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4961 if (FAILED(rc)) return rc;
4962
4963 if (bstr == aName)
4964 {
4965 found = *it;
4966 break;
4967 }
4968 }
4969
4970 if (!found)
4971 return E_INVALIDARG;
4972
4973 return found.queryInterfaceTo(aServer);
4974}
4975
4976STDMETHODIMP VirtualBox::RemoveDHCPServer(IDHCPServer * aServer)
4977{
4978 CheckComArgNotNull(aServer);
4979
4980 AutoCaller autoCaller(this);
4981 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4982
4983 HRESULT rc = unregisterDHCPServer(static_cast<DHCPServer *>(aServer), true);
4984
4985 return rc;
4986}
4987
4988/**
4989 * Remembers the given DHCP server in the settings.
4990 *
4991 * @param aDHCPServer DHCP server object to remember.
4992 * @param aSaveSettings @c true to save settings to disk (default).
4993 *
4994 * When @a aSaveSettings is @c true, this operation may fail because of the
4995 * failed #saveSettings() method it calls. In this case, the dhcp server object
4996 * will not be remembered. It is therefore the responsibility of the caller to
4997 * call this method as the last step of some action that requires registration
4998 * in order to make sure that only fully functional dhcp server objects get
4999 * registered.
5000 *
5001 * @note Locks this object for writing and @a aDHCPServer for reading.
5002 */
5003HRESULT VirtualBox::registerDHCPServer(DHCPServer *aDHCPServer,
5004 bool aSaveSettings /*= true*/)
5005{
5006 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5007
5008 AutoCaller autoCaller(this);
5009 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5010
5011 AutoCaller dhcpServerCaller(aDHCPServer);
5012 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
5013
5014 Bstr name;
5015 HRESULT rc;
5016 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
5017 if (FAILED(rc)) return rc;
5018
5019 ComPtr<IDHCPServer> existing;
5020 rc = FindDHCPServerByNetworkName(name.raw(), existing.asOutParam());
5021 if (SUCCEEDED(rc))
5022 return E_INVALIDARG;
5023
5024 rc = S_OK;
5025
5026 m->allDHCPServers.addChild(aDHCPServer);
5027
5028 if (aSaveSettings)
5029 {
5030 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5031 rc = saveSettings();
5032 vboxLock.release();
5033
5034 if (FAILED(rc))
5035 unregisterDHCPServer(aDHCPServer, false /* aSaveSettings */);
5036 }
5037
5038 return rc;
5039}
5040
5041/**
5042 * Removes the given DHCP server from the settings.
5043 *
5044 * @param aDHCPServer DHCP server object to remove.
5045 * @param aSaveSettings @c true to save settings to disk (default).
5046 *
5047 * When @a aSaveSettings is @c true, this operation may fail because of the
5048 * failed #saveSettings() method it calls. In this case, the DHCP server
5049 * will NOT be removed from the settingsi when this method returns.
5050 *
5051 * @note Locks this object for writing.
5052 */
5053HRESULT VirtualBox::unregisterDHCPServer(DHCPServer *aDHCPServer,
5054 bool aSaveSettings /*= true*/)
5055{
5056 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5057
5058 AutoCaller autoCaller(this);
5059 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5060
5061 AutoCaller dhcpServerCaller(aDHCPServer);
5062 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
5063
5064 m->allDHCPServers.removeChild(aDHCPServer);
5065
5066 HRESULT rc = S_OK;
5067
5068 if (aSaveSettings)
5069 {
5070 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5071 rc = saveSettings();
5072 vboxLock.release();
5073
5074 if (FAILED(rc))
5075 registerDHCPServer(aDHCPServer, false /* aSaveSettings */);
5076 }
5077
5078 return rc;
5079}
5080
5081
5082/**
5083 * NAT Network
5084 */
5085
5086STDMETHODIMP VirtualBox::CreateNATNetwork(IN_BSTR aName, INATNetwork ** aNatNetwork)
5087{
5088#ifdef VBOX_WITH_NAT_SERVICE
5089 CheckComArgStrNotEmptyOrNull(aName);
5090 CheckComArgNotNull(aNatNetwork);
5091
5092 AutoCaller autoCaller(this);
5093 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5094
5095 ComObjPtr<NATNetwork> natNetwork;
5096 natNetwork.createObject();
5097 HRESULT rc = natNetwork->init(this, aName);
5098 if (FAILED(rc)) return rc;
5099
5100 rc = registerNATNetwork(natNetwork, true);
5101 if (FAILED(rc)) return rc;
5102
5103 natNetwork.queryInterfaceTo(aNatNetwork);
5104
5105 fireNATNetworkCreationDeletionEvent(m->pEventSource, aName, TRUE);
5106 return rc;
5107#else
5108 NOREF(aName);
5109 NOREF(aNatNetwork);
5110 return E_NOTIMPL;
5111#endif
5112}
5113
5114STDMETHODIMP VirtualBox::FindNATNetworkByName(IN_BSTR aName, INATNetwork ** aNetwork)
5115{
5116#ifdef VBOX_WITH_NAT_SERVICE
5117 CheckComArgStrNotEmptyOrNull(aName);
5118 CheckComArgNotNull(aNetwork);
5119
5120 AutoCaller autoCaller(this);
5121 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5122
5123 HRESULT rc;
5124 Bstr bstr;
5125 ComPtr<NATNetwork> found;
5126
5127 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5128
5129 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
5130 it != m->allNATNetworks.end();
5131 ++it)
5132 {
5133 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
5134 if (FAILED(rc)) return rc;
5135
5136 if (bstr == aName)
5137 {
5138 found = *it;
5139 break;
5140 }
5141 }
5142
5143 if (!found)
5144 return E_INVALIDARG;
5145
5146 return found.queryInterfaceTo(aNetwork);
5147#else
5148 NOREF(aName);
5149 NOREF(aNetwork);
5150 return E_NOTIMPL;
5151#endif
5152}
5153
5154STDMETHODIMP VirtualBox::RemoveNATNetwork(INATNetwork * aNetwork)
5155{
5156#ifdef VBOX_WITH_NAT_SERVICE
5157 CheckComArgNotNull(aNetwork);
5158
5159 AutoCaller autoCaller(this);
5160 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5161 Bstr name;
5162 HRESULT rc;
5163 NATNetwork *network = static_cast<NATNetwork *>(aNetwork);
5164 rc = network->COMGETTER(NetworkName)(name.asOutParam());
5165 rc = unregisterNATNetwork(network, true);
5166 fireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
5167 return rc;
5168#else
5169 NOREF(aNetwork);
5170 return E_NOTIMPL;
5171#endif
5172
5173}
5174/**
5175 * Remembers the given NAT network in the settings.
5176 *
5177 * @param aNATNetwork NAT Network object to remember.
5178 * @param aSaveSettings @c true to save settings to disk (default).
5179 *
5180 *
5181 * @note Locks this object for writing and @a aNATNetwork for reading.
5182 */
5183HRESULT VirtualBox::registerNATNetwork(NATNetwork *aNATNetwork,
5184 bool aSaveSettings /*= true*/)
5185{
5186#ifdef VBOX_WITH_NAT_SERVICE
5187 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5188
5189 AutoCaller autoCaller(this);
5190 AssertComRCReturnRC(autoCaller.rc());
5191
5192 AutoCaller natNetworkCaller(aNATNetwork);
5193 AssertComRCReturnRC(natNetworkCaller.rc());
5194
5195 Bstr name;
5196 HRESULT rc;
5197 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5198 AssertComRCReturnRC(rc);
5199
5200 /* returned value isn't 0 and aSaveSettings is true
5201 * means that we create duplicate, otherwise we just load settings.
5202 */
5203 if ( sNatNetworkNameToRefCount[name]
5204 && aSaveSettings)
5205 AssertComRCReturnRC(E_INVALIDARG);
5206
5207 rc = S_OK;
5208
5209 sNatNetworkNameToRefCount[name] = 0;
5210
5211 m->allNATNetworks.addChild(aNATNetwork);
5212
5213 if (aSaveSettings)
5214 {
5215 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5216 rc = saveSettings();
5217 vboxLock.release();
5218
5219 if (FAILED(rc))
5220 unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
5221 }
5222
5223 return rc;
5224#else
5225 NOREF(aNATNetwork);
5226 NOREF(aSaveSettings);
5227 /* No panic please (silently ignore) */
5228 return S_OK;
5229#endif
5230}
5231
5232/**
5233 * Removes the given NAT network from the settings.
5234 *
5235 * @param aNATNetwork NAT network object to remove.
5236 * @param aSaveSettings @c true to save settings to disk (default).
5237 *
5238 * When @a aSaveSettings is @c true, this operation may fail because of the
5239 * failed #saveSettings() method it calls. In this case, the DHCP server
5240 * will NOT be removed from the settingsi when this method returns.
5241 *
5242 * @note Locks this object for writing.
5243 */
5244HRESULT VirtualBox::unregisterNATNetwork(NATNetwork *aNATNetwork,
5245 bool aSaveSettings /*= true*/)
5246{
5247#ifdef VBOX_WITH_NAT_SERVICE
5248 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5249
5250 AutoCaller autoCaller(this);
5251 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5252
5253 AutoCaller natNetworkCaller(aNATNetwork);
5254 AssertComRCReturn(natNetworkCaller.rc(), natNetworkCaller.rc());
5255
5256 Bstr name;
5257 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5258 /* Hm, there're still running clients. */
5259 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
5260 AssertComRCReturnRC(E_INVALIDARG);
5261
5262 m->allNATNetworks.removeChild(aNATNetwork);
5263
5264 if (aSaveSettings)
5265 {
5266 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5267 rc = saveSettings();
5268 vboxLock.release();
5269
5270 if (FAILED(rc))
5271 registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
5272 }
5273
5274 return rc;
5275#else
5276 NOREF(aNATNetwork);
5277 NOREF(aSaveSettings);
5278 return E_NOTIMPL;
5279#endif
5280}
5281/* 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