VirtualBox

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

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

Main: don't fire event if HostNameResolutionConfigurationChangeEvent if source isn't here.

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