VirtualBox

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

Last change on this file since 59381 was 59087, checked in by vboxsync, 9 years ago

bugref:7179. auto_ptr was removed from the files VirtualBoxImpl.cpp and NetIf-win.cpp. The operations with network interface on Windows OS were affected.

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

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