VirtualBox

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

Last change on this file since 54276 was 54276, checked in by vboxsync, 10 years ago

Main/src-server: unused var. warning.

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

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