VirtualBox

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

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

R7524 - needs testing in VBoxManage.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 163.7 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 53354 2014-11-19 18:32:03Z 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 HRESULT rc = S_OK;
1755
1756 ComObjPtr<Medium> medium;
1757 medium.createObject();
1758 com::Utf8Str format = aFormat;
1759
1760 switch (aDeviceType)
1761 {
1762 case DeviceType_HardDisk:
1763 {
1764
1765 /* we don't access non-const data members so no need to lock */
1766 if (format.isEmpty())
1767 i_getDefaultHardDiskFormat(format);
1768
1769 rc = medium->init(this,
1770 format,
1771 aLocation,
1772 Guid::Empty /* media registry: none yet */,
1773 aDeviceType);
1774 }
1775 break;
1776
1777 case DeviceType_DVD:
1778 case DeviceType_Floppy:
1779 {
1780
1781 if (format.isEmpty())
1782 return setError(E_INVALIDARG, "Format must be Valid Type%s", format.c_str());
1783
1784 // enforce read-only for DVDs even if caller specified ReadWrite
1785 if (aDeviceType == DeviceType_DVD)
1786 aAccessMode = AccessMode_ReadOnly;
1787
1788 rc = medium->init(this,
1789 format,
1790 aLocation,
1791 Guid::Empty /* media registry: none yet */,
1792 aDeviceType);
1793
1794 }
1795 break;
1796
1797 default:
1798 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy %d", aDeviceType);
1799 }
1800
1801 if (SUCCEEDED(rc))
1802 medium.queryInterfaceTo(aMedium.asOutParam());
1803
1804 return rc;
1805}
1806
1807HRESULT VirtualBox::openMedium(const com::Utf8Str &aLocation,
1808 DeviceType_T aDeviceType,
1809 AccessMode_T aAccessMode,
1810 BOOL aForceNewUuid,
1811 ComPtr<IMedium> &aMedium)
1812{
1813 HRESULT rc = S_OK;
1814 Guid id(aLocation);
1815 ComObjPtr<Medium> pMedium;
1816
1817 // have to get write lock as the whole find/update sequence must be done
1818 // in one critical section, otherwise there are races which can lead to
1819 // multiple Medium objects with the same content
1820 AutoWriteLock treeLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1821
1822 // check if the device type is correct, and see if a medium for the
1823 // given path has already initialized; if so, return that
1824 switch (aDeviceType)
1825 {
1826 case DeviceType_HardDisk:
1827 if (id.isValid() && !id.isZero())
1828 rc = i_findHardDiskById(id, false /* setError */, &pMedium);
1829 else
1830 rc = i_findHardDiskByLocation(aLocation,
1831 false, /* aSetError */
1832 &pMedium);
1833 break;
1834
1835 case DeviceType_Floppy:
1836 case DeviceType_DVD:
1837 if (id.isValid() && !id.isZero())
1838 rc = i_findDVDOrFloppyImage(aDeviceType, &id, Utf8Str::Empty,
1839 false /* setError */, &pMedium);
1840 else
1841 rc = i_findDVDOrFloppyImage(aDeviceType, NULL, aLocation,
1842 false /* setError */, &pMedium);
1843
1844 // enforce read-only for DVDs even if caller specified ReadWrite
1845 if (aDeviceType == DeviceType_DVD)
1846 aAccessMode = AccessMode_ReadOnly;
1847 break;
1848
1849 default:
1850 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy %d", aDeviceType);
1851 }
1852
1853 if (pMedium.isNull())
1854 {
1855 pMedium.createObject();
1856 treeLock.release();
1857 rc = pMedium->init(this,
1858 aLocation,
1859 (aAccessMode == AccessMode_ReadWrite) ? Medium::OpenReadWrite : Medium::OpenReadOnly,
1860 !!aForceNewUuid,
1861 aDeviceType);
1862 treeLock.acquire();
1863
1864 if (SUCCEEDED(rc))
1865 {
1866 rc = i_registerMedium(pMedium, &pMedium, aDeviceType, treeLock);
1867
1868 treeLock.release();
1869
1870 /* Note that it's important to call uninit() on failure to register
1871 * because the differencing hard disk would have been already associated
1872 * with the parent and this association needs to be broken. */
1873
1874 if (FAILED(rc))
1875 {
1876 pMedium->uninit();
1877 rc = VBOX_E_OBJECT_NOT_FOUND;
1878 }
1879 }
1880 else
1881 rc = VBOX_E_OBJECT_NOT_FOUND;
1882 }
1883
1884 if (SUCCEEDED(rc))
1885 pMedium.queryInterfaceTo(aMedium.asOutParam());
1886
1887 return rc;
1888}
1889
1890
1891/** @note Locks this object for reading. */
1892HRESULT VirtualBox::getGuestOSType(const com::Utf8Str &aId,
1893 ComPtr<IGuestOSType> &aType)
1894{
1895 aType = NULL;
1896 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1897
1898 HRESULT rc = S_OK;
1899 for (GuestOSTypesOList::iterator it = m->allGuestOSTypes.begin();
1900 it != m->allGuestOSTypes.end();
1901 ++it)
1902 {
1903 const Bstr &typeId = (*it)->i_id();
1904 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
1905 if (typeId.compare(aId, Bstr::CaseInsensitive) == 0)
1906 {
1907 (*it).queryInterfaceTo(aType.asOutParam());
1908 break;
1909 }
1910 }
1911 return (aType) ? S_OK :
1912 setError(E_INVALIDARG,
1913 tr("'%s' is not a valid Guest OS type"),
1914 aId.c_str());
1915 return rc;
1916}
1917
1918HRESULT VirtualBox::createSharedFolder(const com::Utf8Str &aName,
1919 const com::Utf8Str &aHostPath,
1920 BOOL aWritable,
1921 BOOL aAutomount)
1922{
1923 NOREF(aName);
1924 NOREF(aHostPath);
1925 NOREF(aWritable);
1926 NOREF(aAutomount);
1927
1928 return setError(E_NOTIMPL, "Not yet implemented");
1929}
1930
1931HRESULT VirtualBox::removeSharedFolder(const com::Utf8Str &aName)
1932{
1933 NOREF(aName);
1934 return setError(E_NOTIMPL, "Not yet implemented");
1935}
1936
1937/**
1938 * @note Locks this object for reading.
1939 */
1940HRESULT VirtualBox::getExtraDataKeys(std::vector<com::Utf8Str> &aKeys)
1941{
1942 using namespace settings;
1943
1944 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1945
1946 aKeys.resize(m->pMainConfigFile->mapExtraDataItems.size());
1947 size_t i = 0;
1948 for (StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.begin();
1949 it != m->pMainConfigFile->mapExtraDataItems.end(); ++it, ++i)
1950 aKeys[i] = it->first;
1951
1952 return S_OK;
1953}
1954
1955/**
1956 * @note Locks this object for reading.
1957 */
1958HRESULT VirtualBox::getExtraData(const com::Utf8Str &aKey,
1959 com::Utf8Str &aValue)
1960{
1961 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(aKey);
1962 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1963 // found:
1964 aValue = it->second; // source is a Utf8Str
1965
1966 /* return the result to caller (may be empty) */
1967
1968 return S_OK;
1969}
1970
1971/**
1972 * @note Locks this object for writing.
1973 */
1974HRESULT VirtualBox::setExtraData(const com::Utf8Str &aKey,
1975 const com::Utf8Str &aValue)
1976{
1977
1978 Utf8Str strKey(aKey);
1979 Utf8Str strValue(aValue);
1980 Utf8Str strOldValue; // empty
1981 HRESULT rc = S_OK;
1982
1983 // locking note: we only hold the read lock briefly to look up the old value,
1984 // then release it and call the onExtraCanChange callbacks. There is a small
1985 // chance of a race insofar as the callback might be called twice if two callers
1986 // change the same key at the same time, but that's a much better solution
1987 // than the deadlock we had here before. The actual changing of the extradata
1988 // is then performed under the write lock and race-free.
1989
1990 // look up the old value first; if nothing has changed then we need not do anything
1991 {
1992 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
1993 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1994 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1995 strOldValue = it->second;
1996 }
1997
1998 bool fChanged;
1999 if ((fChanged = (strOldValue != strValue)))
2000 {
2001 // ask for permission from all listeners outside the locks;
2002 // onExtraDataCanChange() only briefly requests the VirtualBox
2003 // lock to copy the list of callbacks to invoke
2004 Bstr error;
2005
2006 if (!i_onExtraDataCanChange(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw(), error))
2007 {
2008 const char *sep = error.isEmpty() ? "" : ": ";
2009 CBSTR err = error.raw();
2010 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
2011 sep, err));
2012 return setError(E_ACCESSDENIED,
2013 tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
2014 strKey.c_str(),
2015 strValue.c_str(),
2016 sep,
2017 err);
2018 }
2019
2020 // data is changing and change not vetoed: then write it out under the lock
2021
2022 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2023
2024 if (strValue.isEmpty())
2025 m->pMainConfigFile->mapExtraDataItems.erase(strKey);
2026 else
2027 m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
2028 // creates a new key if needed
2029
2030 /* save settings on success */
2031 rc = i_saveSettings();
2032 if (FAILED(rc)) return rc;
2033 }
2034
2035 // fire notification outside the lock
2036 if (fChanged)
2037 i_onExtraDataChange(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw());
2038
2039 return rc;
2040}
2041
2042/**
2043 *
2044 */
2045HRESULT VirtualBox::setSettingsSecret(const com::Utf8Str &aPassword)
2046{
2047 i_storeSettingsKey(aPassword);
2048 i_decryptSettings();
2049 return S_OK;
2050}
2051
2052int VirtualBox::i_decryptMediumSettings(Medium *pMedium)
2053{
2054 Bstr bstrCipher;
2055 HRESULT hrc = pMedium->GetProperty(Bstr("InitiatorSecretEncrypted").raw(),
2056 bstrCipher.asOutParam());
2057 if (SUCCEEDED(hrc))
2058 {
2059 Utf8Str strPlaintext;
2060 int rc = i_decryptSetting(&strPlaintext, bstrCipher);
2061 if (RT_SUCCESS(rc))
2062 pMedium->i_setPropertyDirect("InitiatorSecret", strPlaintext);
2063 else
2064 return rc;
2065 }
2066 return VINF_SUCCESS;
2067}
2068
2069/**
2070 * Decrypt all encrypted settings.
2071 *
2072 * So far we only have encrypted iSCSI initiator secrets so we just go through
2073 * all hard disk mediums and determine the plain 'InitiatorSecret' from
2074 * 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
2075 * properties need to be null-terminated strings.
2076 */
2077int VirtualBox::i_decryptSettings()
2078{
2079 bool fFailure = false;
2080 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2081 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2082 mt != m->allHardDisks.end();
2083 ++mt)
2084 {
2085 ComObjPtr<Medium> pMedium = *mt;
2086 AutoCaller medCaller(pMedium);
2087 if (FAILED(medCaller.rc()))
2088 continue;
2089 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2090 int vrc = i_decryptMediumSettings(pMedium);
2091 if (RT_FAILURE(vrc))
2092 fFailure = true;
2093 }
2094 return fFailure ? VERR_INVALID_PARAMETER : VINF_SUCCESS;
2095}
2096
2097/**
2098 * Encode.
2099 *
2100 * @param aPlaintext plaintext to be encrypted
2101 * @param aCiphertext resulting ciphertext (base64-encoded)
2102 */
2103int VirtualBox::i_encryptSetting(const Utf8Str &aPlaintext, Utf8Str *aCiphertext)
2104{
2105 uint8_t abCiphertext[32];
2106 char szCipherBase64[128];
2107 size_t cchCipherBase64;
2108 int rc = i_encryptSettingBytes((uint8_t*)aPlaintext.c_str(), abCiphertext,
2109 aPlaintext.length()+1, sizeof(abCiphertext));
2110 if (RT_SUCCESS(rc))
2111 {
2112 rc = RTBase64Encode(abCiphertext, sizeof(abCiphertext),
2113 szCipherBase64, sizeof(szCipherBase64),
2114 &cchCipherBase64);
2115 if (RT_SUCCESS(rc))
2116 *aCiphertext = szCipherBase64;
2117 }
2118 return rc;
2119}
2120
2121/**
2122 * Decode.
2123 *
2124 * @param aPlaintext resulting plaintext
2125 * @param aCiphertext ciphertext (base64-encoded) to decrypt
2126 */
2127int VirtualBox::i_decryptSetting(Utf8Str *aPlaintext, const Utf8Str &aCiphertext)
2128{
2129 uint8_t abPlaintext[64];
2130 uint8_t abCiphertext[64];
2131 size_t cbCiphertext;
2132 int rc = RTBase64Decode(aCiphertext.c_str(),
2133 abCiphertext, sizeof(abCiphertext),
2134 &cbCiphertext, NULL);
2135 if (RT_SUCCESS(rc))
2136 {
2137 rc = i_decryptSettingBytes(abPlaintext, abCiphertext, cbCiphertext);
2138 if (RT_SUCCESS(rc))
2139 {
2140 for (unsigned i = 0; i < cbCiphertext; i++)
2141 {
2142 /* sanity check: null-terminated string? */
2143 if (abPlaintext[i] == '\0')
2144 {
2145 /* sanity check: valid UTF8 string? */
2146 if (RTStrIsValidEncoding((const char*)abPlaintext))
2147 {
2148 *aPlaintext = Utf8Str((const char*)abPlaintext);
2149 return VINF_SUCCESS;
2150 }
2151 }
2152 }
2153 rc = VERR_INVALID_MAGIC;
2154 }
2155 }
2156 return rc;
2157}
2158
2159/**
2160 * Encrypt secret bytes. Use the m->SettingsCipherKey as key.
2161 *
2162 * @param aPlaintext clear text to be encrypted
2163 * @param aCiphertext resulting encrypted text
2164 * @param aPlaintextSize size of the plaintext
2165 * @param aCiphertextSize size of the ciphertext
2166 */
2167int VirtualBox::i_encryptSettingBytes(const uint8_t *aPlaintext, uint8_t *aCiphertext,
2168 size_t aPlaintextSize, size_t aCiphertextSize) const
2169{
2170 unsigned i, j;
2171 uint8_t aBytes[64];
2172
2173 if (!m->fSettingsCipherKeySet)
2174 return VERR_INVALID_STATE;
2175
2176 if (aCiphertextSize > sizeof(aBytes))
2177 return VERR_BUFFER_OVERFLOW;
2178
2179 if (aCiphertextSize < 32)
2180 return VERR_INVALID_PARAMETER;
2181
2182 AssertCompile(sizeof(m->SettingsCipherKey) >= 32);
2183
2184 /* store the first 8 bytes of the cipherkey for verification */
2185 for (i = 0, j = 0; i < 8; i++, j++)
2186 aCiphertext[i] = m->SettingsCipherKey[j];
2187
2188 for (unsigned k = 0; k < aPlaintextSize && i < aCiphertextSize; i++, k++)
2189 {
2190 aCiphertext[i] = (aPlaintext[k] ^ m->SettingsCipherKey[j]);
2191 if (++j >= sizeof(m->SettingsCipherKey))
2192 j = 0;
2193 }
2194
2195 /* fill with random data to have a minimal length (salt) */
2196 if (i < aCiphertextSize)
2197 {
2198 RTRandBytes(aBytes, aCiphertextSize - i);
2199 for (int k = 0; i < aCiphertextSize; i++, k++)
2200 {
2201 aCiphertext[i] = aBytes[k] ^ m->SettingsCipherKey[j];
2202 if (++j >= sizeof(m->SettingsCipherKey))
2203 j = 0;
2204 }
2205 }
2206
2207 return VINF_SUCCESS;
2208}
2209
2210/**
2211 * Decrypt secret bytes. Use the m->SettingsCipherKey as key.
2212 *
2213 * @param aPlaintext resulting plaintext
2214 * @param aCiphertext ciphertext to be decrypted
2215 * @param aCiphertextSize size of the ciphertext == size of the plaintext
2216 */
2217int VirtualBox::i_decryptSettingBytes(uint8_t *aPlaintext,
2218 const uint8_t *aCiphertext, size_t aCiphertextSize) const
2219{
2220 unsigned i, j;
2221
2222 if (!m->fSettingsCipherKeySet)
2223 return VERR_INVALID_STATE;
2224
2225 if (aCiphertextSize < 32)
2226 return VERR_INVALID_PARAMETER;
2227
2228 /* key verification */
2229 for (i = 0, j = 0; i < 8; i++, j++)
2230 if (aCiphertext[i] != m->SettingsCipherKey[j])
2231 return VERR_INVALID_MAGIC;
2232
2233 /* poison */
2234 memset(aPlaintext, 0xff, aCiphertextSize);
2235 for (int k = 0; i < aCiphertextSize; i++, k++)
2236 {
2237 aPlaintext[k] = aCiphertext[i] ^ m->SettingsCipherKey[j];
2238 if (++j >= sizeof(m->SettingsCipherKey))
2239 j = 0;
2240 }
2241
2242 return VINF_SUCCESS;
2243}
2244
2245/**
2246 * Store a settings key.
2247 *
2248 * @param aKey the key to store
2249 */
2250void VirtualBox::i_storeSettingsKey(const Utf8Str &aKey)
2251{
2252 RTSha512(aKey.c_str(), aKey.length(), m->SettingsCipherKey);
2253 m->fSettingsCipherKeySet = true;
2254}
2255
2256// public methods only for internal purposes
2257/////////////////////////////////////////////////////////////////////////////
2258
2259#ifdef DEBUG
2260void VirtualBox::i_dumpAllBackRefs()
2261{
2262 {
2263 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2264 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2265 mt != m->allHardDisks.end();
2266 ++mt)
2267 {
2268 ComObjPtr<Medium> pMedium = *mt;
2269 pMedium->i_dumpBackRefs();
2270 }
2271 }
2272 {
2273 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2274 for (MediaList::const_iterator mt = m->allDVDImages.begin();
2275 mt != m->allDVDImages.end();
2276 ++mt)
2277 {
2278 ComObjPtr<Medium> pMedium = *mt;
2279 pMedium->i_dumpBackRefs();
2280 }
2281 }
2282}
2283#endif
2284
2285/**
2286 * Posts an event to the event queue that is processed asynchronously
2287 * on a dedicated thread.
2288 *
2289 * Posting events to the dedicated event queue is useful to perform secondary
2290 * actions outside any object locks -- for example, to iterate over a list
2291 * of callbacks and inform them about some change caused by some object's
2292 * method call.
2293 *
2294 * @param event event to post; must have been allocated using |new|, will
2295 * be deleted automatically by the event thread after processing
2296 *
2297 * @note Doesn't lock any object.
2298 */
2299HRESULT VirtualBox::i_postEvent(Event *event)
2300{
2301 AssertReturn(event, E_FAIL);
2302
2303 HRESULT rc;
2304 AutoCaller autoCaller(this);
2305 if (SUCCEEDED((rc = autoCaller.rc())))
2306 {
2307 if (getObjectState().getState() != ObjectState::Ready)
2308 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
2309 getObjectState().getState()));
2310 // return S_OK
2311 else if ( (m->pAsyncEventQ)
2312 && (m->pAsyncEventQ->postEvent(event))
2313 )
2314 return S_OK;
2315 else
2316 rc = E_FAIL;
2317 }
2318
2319 // in any event of failure, we must clean up here, or we'll leak;
2320 // the caller has allocated the object using new()
2321 delete event;
2322 return rc;
2323}
2324
2325/**
2326 * Adds a progress to the global collection of pending operations.
2327 * Usually gets called upon progress object initialization.
2328 *
2329 * @param aProgress Operation to add to the collection.
2330 *
2331 * @note Doesn't lock objects.
2332 */
2333HRESULT VirtualBox::i_addProgress(IProgress *aProgress)
2334{
2335 CheckComArgNotNull(aProgress);
2336
2337 AutoCaller autoCaller(this);
2338 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2339
2340 Bstr id;
2341 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
2342 AssertComRCReturnRC(rc);
2343
2344 /* protect mProgressOperations */
2345 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2346
2347 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
2348 return S_OK;
2349}
2350
2351/**
2352 * Removes the progress from the global collection of pending operations.
2353 * Usually gets called upon progress completion.
2354 *
2355 * @param aId UUID of the progress operation to remove
2356 *
2357 * @note Doesn't lock objects.
2358 */
2359HRESULT VirtualBox::i_removeProgress(IN_GUID aId)
2360{
2361 AutoCaller autoCaller(this);
2362 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2363
2364 ComPtr<IProgress> progress;
2365
2366 /* protect mProgressOperations */
2367 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2368
2369 size_t cnt = m->mapProgressOperations.erase(aId);
2370 Assert(cnt == 1);
2371 NOREF(cnt);
2372
2373 return S_OK;
2374}
2375
2376#ifdef RT_OS_WINDOWS
2377
2378struct StartSVCHelperClientData
2379{
2380 ComObjPtr<VirtualBox> that;
2381 ComObjPtr<Progress> progress;
2382 bool privileged;
2383 VirtualBox::SVCHelperClientFunc func;
2384 void *user;
2385};
2386
2387/**
2388 * Helper method that starts a worker thread that:
2389 * - creates a pipe communication channel using SVCHlpClient;
2390 * - starts an SVC Helper process that will inherit this channel;
2391 * - executes the supplied function by passing it the created SVCHlpClient
2392 * and opened instance to communicate to the Helper process and the given
2393 * Progress object.
2394 *
2395 * The user function is supposed to communicate to the helper process
2396 * using the \a aClient argument to do the requested job and optionally expose
2397 * the progress through the \a aProgress object. The user function should never
2398 * call notifyComplete() on it: this will be done automatically using the
2399 * result code returned by the function.
2400 *
2401 * Before the user function is started, the communication channel passed to
2402 * the \a aClient argument is fully set up, the function should start using
2403 * its write() and read() methods directly.
2404 *
2405 * The \a aVrc parameter of the user function may be used to return an error
2406 * code if it is related to communication errors (for example, returned by
2407 * the SVCHlpClient members when they fail). In this case, the correct error
2408 * message using this value will be reported to the caller. Note that the
2409 * value of \a aVrc is inspected only if the user function itself returns
2410 * success.
2411 *
2412 * If a failure happens anywhere before the user function would be normally
2413 * called, it will be called anyway in special "cleanup only" mode indicated
2414 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
2415 * all the function is supposed to do is to cleanup its aUser argument if
2416 * necessary (it's assumed that the ownership of this argument is passed to
2417 * the user function once #startSVCHelperClient() returns a success, thus
2418 * making it responsible for the cleanup).
2419 *
2420 * After the user function returns, the thread will send the SVCHlpMsg::Null
2421 * message to indicate a process termination.
2422 *
2423 * @param aPrivileged |true| to start the SVC Helper process as a privileged
2424 * user that can perform administrative tasks
2425 * @param aFunc user function to run
2426 * @param aUser argument to the user function
2427 * @param aProgress progress object that will track operation completion
2428 *
2429 * @note aPrivileged is currently ignored (due to some unsolved problems in
2430 * Vista) and the process will be started as a normal (unprivileged)
2431 * process.
2432 *
2433 * @note Doesn't lock anything.
2434 */
2435HRESULT VirtualBox::i_startSVCHelperClient(bool aPrivileged,
2436 SVCHelperClientFunc aFunc,
2437 void *aUser, Progress *aProgress)
2438{
2439 AssertReturn(aFunc, E_POINTER);
2440 AssertReturn(aProgress, E_POINTER);
2441
2442 AutoCaller autoCaller(this);
2443 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2444
2445 /* create the SVCHelperClientThread() argument */
2446 std::auto_ptr <StartSVCHelperClientData>
2447 d(new StartSVCHelperClientData());
2448 AssertReturn(d.get(), E_OUTOFMEMORY);
2449
2450 d->that = this;
2451 d->progress = aProgress;
2452 d->privileged = aPrivileged;
2453 d->func = aFunc;
2454 d->user = aUser;
2455
2456 RTTHREAD tid = NIL_RTTHREAD;
2457 int vrc = RTThreadCreate(&tid, SVCHelperClientThread,
2458 static_cast <void *>(d.get()),
2459 0, RTTHREADTYPE_MAIN_WORKER,
2460 RTTHREADFLAGS_WAITABLE, "SVCHelper");
2461 if (RT_FAILURE(vrc))
2462 return setError(E_FAIL, "Could not create SVCHelper thread (%Rrc)", vrc);
2463
2464 /* d is now owned by SVCHelperClientThread(), so release it */
2465 d.release();
2466
2467 return S_OK;
2468}
2469
2470/**
2471 * Worker thread for startSVCHelperClient().
2472 */
2473/* static */
2474DECLCALLBACK(int)
2475VirtualBox::SVCHelperClientThread(RTTHREAD aThread, void *aUser)
2476{
2477 LogFlowFuncEnter();
2478
2479 std::auto_ptr<StartSVCHelperClientData>
2480 d(static_cast<StartSVCHelperClientData*>(aUser));
2481
2482 HRESULT rc = S_OK;
2483 bool userFuncCalled = false;
2484
2485 do
2486 {
2487 AssertBreakStmt(d.get(), rc = E_POINTER);
2488 AssertReturn(!d->progress.isNull(), E_POINTER);
2489
2490 /* protect VirtualBox from uninitialization */
2491 AutoCaller autoCaller(d->that);
2492 if (!autoCaller.isOk())
2493 {
2494 /* it's too late */
2495 rc = autoCaller.rc();
2496 break;
2497 }
2498
2499 int vrc = VINF_SUCCESS;
2500
2501 Guid id;
2502 id.create();
2503 SVCHlpClient client;
2504 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2505 id.raw()).c_str());
2506 if (RT_FAILURE(vrc))
2507 {
2508 rc = d->that->setError(E_FAIL,
2509 tr("Could not create the communication channel (%Rrc)"), vrc);
2510 break;
2511 }
2512
2513 /* get the path to the executable */
2514 char exePathBuf[RTPATH_MAX];
2515 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2516 if (!exePath)
2517 {
2518 rc = d->that->setError(E_FAIL, tr("Cannot get executable name"));
2519 break;
2520 }
2521
2522 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2523
2524 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2525
2526 RTPROCESS pid = NIL_RTPROCESS;
2527
2528 if (d->privileged)
2529 {
2530 /* Attempt to start a privileged process using the Run As dialog */
2531
2532 Bstr file = exePath;
2533 Bstr parameters = argsStr;
2534
2535 SHELLEXECUTEINFO shExecInfo;
2536
2537 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2538
2539 shExecInfo.fMask = NULL;
2540 shExecInfo.hwnd = NULL;
2541 shExecInfo.lpVerb = L"runas";
2542 shExecInfo.lpFile = file.raw();
2543 shExecInfo.lpParameters = parameters.raw();
2544 shExecInfo.lpDirectory = NULL;
2545 shExecInfo.nShow = SW_NORMAL;
2546 shExecInfo.hInstApp = NULL;
2547
2548 if (!ShellExecuteEx(&shExecInfo))
2549 {
2550 int vrc2 = RTErrConvertFromWin32(GetLastError());
2551 /* hide excessive details in case of a frequent error
2552 * (pressing the Cancel button to close the Run As dialog) */
2553 if (vrc2 == VERR_CANCELLED)
2554 rc = d->that->setError(E_FAIL,
2555 tr("Operation canceled by the user"));
2556 else
2557 rc = d->that->setError(E_FAIL,
2558 tr("Could not launch a privileged process '%s' (%Rrc)"),
2559 exePath, vrc2);
2560 break;
2561 }
2562 }
2563 else
2564 {
2565 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2566 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2567 if (RT_FAILURE(vrc))
2568 {
2569 rc = d->that->setError(E_FAIL,
2570 tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2571 break;
2572 }
2573 }
2574
2575 /* wait for the client to connect */
2576 vrc = client.connect();
2577 if (RT_SUCCESS(vrc))
2578 {
2579 /* start the user supplied function */
2580 rc = d->func(&client, d->progress, d->user, &vrc);
2581 userFuncCalled = true;
2582 }
2583
2584 /* send the termination signal to the process anyway */
2585 {
2586 int vrc2 = client.write(SVCHlpMsg::Null);
2587 if (RT_SUCCESS(vrc))
2588 vrc = vrc2;
2589 }
2590
2591 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2592 {
2593 rc = d->that->setError(E_FAIL,
2594 tr("Could not operate the communication channel (%Rrc)"), vrc);
2595 break;
2596 }
2597 }
2598 while (0);
2599
2600 if (FAILED(rc) && !userFuncCalled)
2601 {
2602 /* call the user function in the "cleanup only" mode
2603 * to let it free resources passed to in aUser */
2604 d->func(NULL, NULL, d->user, NULL);
2605 }
2606
2607 d->progress->i_notifyComplete(rc);
2608
2609 LogFlowFuncLeave();
2610 return 0;
2611}
2612
2613#endif /* RT_OS_WINDOWS */
2614
2615/**
2616 * Sends a signal to the client watcher to rescan the set of machines
2617 * that have open sessions.
2618 *
2619 * @note Doesn't lock anything.
2620 */
2621void VirtualBox::i_updateClientWatcher()
2622{
2623 AutoCaller autoCaller(this);
2624 AssertComRCReturnVoid(autoCaller.rc());
2625
2626 AssertPtrReturnVoid(m->pClientWatcher);
2627 m->pClientWatcher->update();
2628}
2629
2630/**
2631 * Adds the given child process ID to the list of processes to be reaped.
2632 * This call should be followed by #updateClientWatcher() to take the effect.
2633 *
2634 * @note Doesn't lock anything.
2635 */
2636void VirtualBox::i_addProcessToReap(RTPROCESS pid)
2637{
2638 AutoCaller autoCaller(this);
2639 AssertComRCReturnVoid(autoCaller.rc());
2640
2641 AssertPtrReturnVoid(m->pClientWatcher);
2642 m->pClientWatcher->addProcess(pid);
2643}
2644
2645/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2646struct MachineEvent : public VirtualBox::CallbackEvent
2647{
2648 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
2649 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2650 , mBool(aBool)
2651 { }
2652
2653 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
2654 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2655 , mState(aState)
2656 {}
2657
2658 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2659 {
2660 switch (mWhat)
2661 {
2662 case VBoxEventType_OnMachineDataChanged:
2663 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2664 break;
2665
2666 case VBoxEventType_OnMachineStateChanged:
2667 aEvDesc.init(aSource, mWhat, id.raw(), mState);
2668 break;
2669
2670 case VBoxEventType_OnMachineRegistered:
2671 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2672 break;
2673
2674 default:
2675 AssertFailedReturn(S_OK);
2676 }
2677 return S_OK;
2678 }
2679
2680 Bstr id;
2681 MachineState_T mState;
2682 BOOL mBool;
2683};
2684
2685
2686/**
2687 * VD plugin load
2688 */
2689int VirtualBox::i_loadVDPlugin(const char *pszPluginLibrary)
2690{
2691 return m->pSystemProperties->i_loadVDPlugin(pszPluginLibrary);
2692}
2693
2694/**
2695 * VD plugin unload
2696 */
2697int VirtualBox::i_unloadVDPlugin(const char *pszPluginLibrary)
2698{
2699 return m->pSystemProperties->i_unloadVDPlugin(pszPluginLibrary);
2700}
2701
2702
2703/**
2704 * @note Doesn't lock any object.
2705 */
2706void VirtualBox::i_onMachineStateChange(const Guid &aId, MachineState_T aState)
2707{
2708 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
2709}
2710
2711/**
2712 * @note Doesn't lock any object.
2713 */
2714void VirtualBox::i_onMachineDataChange(const Guid &aId, BOOL aTemporary)
2715{
2716 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
2717}
2718
2719/**
2720 * @note Locks this object for reading.
2721 */
2722BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
2723 Bstr &aError)
2724{
2725 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
2726 aId.toString().c_str(), aKey, aValue));
2727
2728 AutoCaller autoCaller(this);
2729 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2730
2731 BOOL allowChange = TRUE;
2732 Bstr id = aId.toUtf16();
2733
2734 VBoxEventDesc evDesc;
2735 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
2736 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
2737 //Assert(fDelivered);
2738 if (fDelivered)
2739 {
2740 ComPtr<IEvent> aEvent;
2741 evDesc.getEvent(aEvent.asOutParam());
2742 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
2743 Assert(aCanChangeEvent);
2744 BOOL fVetoed = FALSE;
2745 aCanChangeEvent->IsVetoed(&fVetoed);
2746 allowChange = !fVetoed;
2747
2748 if (!allowChange)
2749 {
2750 SafeArray<BSTR> aVetos;
2751 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
2752 if (aVetos.size() > 0)
2753 aError = aVetos[0];
2754 }
2755 }
2756 else
2757 allowChange = TRUE;
2758
2759 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
2760 return allowChange;
2761}
2762
2763/** Event for onExtraDataChange() */
2764struct ExtraDataEvent : public VirtualBox::CallbackEvent
2765{
2766 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
2767 IN_BSTR aKey, IN_BSTR aVal)
2768 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
2769 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
2770 {}
2771
2772 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2773 {
2774 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
2775 }
2776
2777 Bstr machineId, key, val;
2778};
2779
2780/**
2781 * @note Doesn't lock any object.
2782 */
2783void VirtualBox::i_onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
2784{
2785 i_postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
2786}
2787
2788/**
2789 * @note Doesn't lock any object.
2790 */
2791void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
2792{
2793 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
2794}
2795
2796/** Event for onSessionStateChange() */
2797struct SessionEvent : public VirtualBox::CallbackEvent
2798{
2799 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2800 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
2801 , machineId(aMachineId.toUtf16()), sessionState(aState)
2802 {}
2803
2804 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2805 {
2806 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
2807 }
2808 Bstr machineId;
2809 SessionState_T sessionState;
2810};
2811
2812/**
2813 * @note Doesn't lock any object.
2814 */
2815void VirtualBox::i_onSessionStateChange(const Guid &aId, SessionState_T aState)
2816{
2817 i_postEvent(new SessionEvent(this, aId, aState));
2818}
2819
2820/** Event for onSnapshotTaken(), onSnapshotDeleted() and onSnapshotChange() */
2821struct SnapshotEvent : public VirtualBox::CallbackEvent
2822{
2823 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2824 VBoxEventType_T aWhat)
2825 : CallbackEvent(aVB, aWhat)
2826 , machineId(aMachineId), snapshotId(aSnapshotId)
2827 {}
2828
2829 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2830 {
2831 return aEvDesc.init(aSource, mWhat, machineId.toUtf16().raw(),
2832 snapshotId.toUtf16().raw());
2833 }
2834
2835 Guid machineId;
2836 Guid snapshotId;
2837};
2838
2839/**
2840 * @note Doesn't lock any object.
2841 */
2842void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
2843{
2844 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2845 VBoxEventType_OnSnapshotTaken));
2846}
2847
2848/**
2849 * @note Doesn't lock any object.
2850 */
2851void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
2852{
2853 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2854 VBoxEventType_OnSnapshotDeleted));
2855}
2856
2857/**
2858 * @note Doesn't lock any object.
2859 */
2860void VirtualBox::i_onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
2861{
2862 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2863 VBoxEventType_OnSnapshotChanged));
2864}
2865
2866/** Event for onGuestPropertyChange() */
2867struct GuestPropertyEvent : public VirtualBox::CallbackEvent
2868{
2869 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
2870 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
2871 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
2872 machineId(aMachineId),
2873 name(aName),
2874 value(aValue),
2875 flags(aFlags)
2876 {}
2877
2878 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2879 {
2880 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
2881 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
2882 }
2883
2884 Guid machineId;
2885 Bstr name, value, flags;
2886};
2887
2888/**
2889 * @note Doesn't lock any object.
2890 */
2891void VirtualBox::i_onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
2892 IN_BSTR aValue, IN_BSTR aFlags)
2893{
2894 i_postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
2895}
2896
2897/**
2898 * @note Doesn't lock any object.
2899 */
2900void VirtualBox::i_onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
2901 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
2902 IN_BSTR aGuestIp, uint16_t aGuestPort)
2903{
2904 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
2905 aHostPort, aGuestIp, aGuestPort);
2906}
2907
2908void VirtualBox::i_onNATNetworkChange(IN_BSTR aName)
2909{
2910 fireNATNetworkChangedEvent(m->pEventSource, aName);
2911}
2912
2913void VirtualBox::i_onNATNetworkStartStop(IN_BSTR aName, BOOL fStart)
2914{
2915 fireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
2916}
2917
2918void VirtualBox::i_onNATNetworkSetting(IN_BSTR aNetworkName, BOOL aEnabled,
2919 IN_BSTR aNetwork, IN_BSTR aGateway,
2920 BOOL aAdvertiseDefaultIpv6RouteEnabled,
2921 BOOL fNeedDhcpServer)
2922{
2923 fireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled,
2924 aNetwork, aGateway,
2925 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
2926}
2927
2928void VirtualBox::i_onNATNetworkPortForward(IN_BSTR aNetworkName, BOOL create, BOOL fIpv6,
2929 IN_BSTR aRuleName, NATProtocol_T proto,
2930 IN_BSTR aHostIp, LONG aHostPort,
2931 IN_BSTR aGuestIp, LONG aGuestPort)
2932{
2933 fireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create,
2934 fIpv6, aRuleName, proto,
2935 aHostIp, aHostPort,
2936 aGuestIp, aGuestPort);
2937}
2938
2939
2940void VirtualBox::i_onHostNameResolutionConfigurationChange()
2941{
2942 if (m->pEventSource)
2943 fireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
2944}
2945
2946
2947int VirtualBox::i_natNetworkRefInc(IN_BSTR aNetworkName)
2948{
2949 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
2950 Bstr name(aNetworkName);
2951
2952 if (!sNatNetworkNameToRefCount[name])
2953 {
2954 ComPtr<INATNetwork> nat;
2955 HRESULT rc = FindNATNetworkByName(aNetworkName, nat.asOutParam());
2956 if (FAILED(rc)) return -1;
2957
2958 rc = nat->Start(Bstr("whatever").raw());
2959 if (SUCCEEDED(rc))
2960 LogRel(("Started NAT network '%ls'\n", aNetworkName));
2961 else
2962 LogRel(("Error %Rhrc starting NAT network '%ls'\n", rc, aNetworkName));
2963 AssertComRCReturn(rc, -1);
2964 }
2965
2966 sNatNetworkNameToRefCount[name]++;
2967
2968 return sNatNetworkNameToRefCount[name];
2969}
2970
2971
2972int VirtualBox::i_natNetworkRefDec(IN_BSTR aNetworkName)
2973{
2974 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
2975 Bstr name(aNetworkName);
2976
2977 if (!sNatNetworkNameToRefCount[name])
2978 return 0;
2979
2980 sNatNetworkNameToRefCount[name]--;
2981
2982 if (!sNatNetworkNameToRefCount[name])
2983 {
2984 ComPtr<INATNetwork> nat;
2985 HRESULT rc = FindNATNetworkByName(aNetworkName, nat.asOutParam());
2986 if (FAILED(rc)) return -1;
2987
2988 rc = nat->Stop();
2989 if (SUCCEEDED(rc))
2990 LogRel(("Stopped NAT network '%ls'\n", aNetworkName));
2991 else
2992 LogRel(("Error %Rhrc stopping NAT network '%ls'\n", rc, aNetworkName));
2993 AssertComRCReturn(rc, -1);
2994 }
2995
2996 return sNatNetworkNameToRefCount[name];
2997}
2998
2999
3000/**
3001 * @note Locks the list of other objects for reading.
3002 */
3003ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
3004{
3005 ComObjPtr<GuestOSType> type;
3006
3007 /* unknown type must always be the first */
3008 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
3009
3010 return m->allGuestOSTypes.front();
3011}
3012
3013/**
3014 * Returns the list of opened machines (machines having direct sessions opened
3015 * by client processes) and optionally the list of direct session controls.
3016 *
3017 * @param aMachines Where to put opened machines (will be empty if none).
3018 * @param aControls Where to put direct session controls (optional).
3019 *
3020 * @note The returned lists contain smart pointers. So, clear it as soon as
3021 * it becomes no more necessary to release instances.
3022 *
3023 * @note It can be possible that a session machine from the list has been
3024 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
3025 * when accessing unprotected data directly.
3026 *
3027 * @note Locks objects for reading.
3028 */
3029void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
3030 InternalControlList *aControls /*= NULL*/)
3031{
3032 AutoCaller autoCaller(this);
3033 AssertComRCReturnVoid(autoCaller.rc());
3034
3035 aMachines.clear();
3036 if (aControls)
3037 aControls->clear();
3038
3039 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3040
3041 for (MachinesOList::iterator it = m->allMachines.begin();
3042 it != m->allMachines.end();
3043 ++it)
3044 {
3045 ComObjPtr<SessionMachine> sm;
3046 ComPtr<IInternalSessionControl> ctl;
3047 if ((*it)->i_isSessionOpen(sm, &ctl))
3048 {
3049 aMachines.push_back(sm);
3050 if (aControls)
3051 aControls->push_back(ctl);
3052 }
3053 }
3054}
3055
3056/**
3057 * Gets a reference to the machine list. This is the real thing, not a copy,
3058 * so bad things will happen if the caller doesn't hold the necessary lock.
3059 *
3060 * @returns reference to machine list
3061 *
3062 * @note Caller must hold the VirtualBox object lock at least for reading.
3063 */
3064VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
3065{
3066 return m->allMachines;
3067}
3068
3069/**
3070 * Searches for a machine object with the given ID in the collection
3071 * of registered machines.
3072 *
3073 * @param aId Machine UUID to look for.
3074 * @param aPermitInaccessible If true, inaccessible machines will be found;
3075 * if false, this will fail if the given machine is inaccessible.
3076 * @param aSetError If true, set errorinfo if the machine is not found.
3077 * @param aMachine Returned machine, if found.
3078 * @return
3079 */
3080HRESULT VirtualBox::i_findMachine(const Guid &aId,
3081 bool fPermitInaccessible,
3082 bool aSetError,
3083 ComObjPtr<Machine> *aMachine /* = NULL */)
3084{
3085 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3086
3087 AutoCaller autoCaller(this);
3088 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3089
3090 {
3091 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3092
3093 for (MachinesOList::iterator it = m->allMachines.begin();
3094 it != m->allMachines.end();
3095 ++it)
3096 {
3097 ComObjPtr<Machine> pMachine = *it;
3098
3099 if (!fPermitInaccessible)
3100 {
3101 // skip inaccessible machines
3102 AutoCaller machCaller(pMachine);
3103 if (FAILED(machCaller.rc()))
3104 continue;
3105 }
3106
3107 if (pMachine->i_getId() == aId)
3108 {
3109 rc = S_OK;
3110 if (aMachine)
3111 *aMachine = pMachine;
3112 break;
3113 }
3114 }
3115 }
3116
3117 if (aSetError && FAILED(rc))
3118 rc = setError(rc,
3119 tr("Could not find a registered machine with UUID {%RTuuid}"),
3120 aId.raw());
3121
3122 return rc;
3123}
3124
3125/**
3126 * Searches for a machine object with the given name or location in the
3127 * collection of registered machines.
3128 *
3129 * @param aName Machine name or location to look for.
3130 * @param aSetError If true, set errorinfo if the machine is not found.
3131 * @param aMachine Returned machine, if found.
3132 * @return
3133 */
3134HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
3135 bool aSetError,
3136 ComObjPtr<Machine> *aMachine /* = NULL */)
3137{
3138 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3139
3140 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3141 for (MachinesOList::iterator it = m->allMachines.begin();
3142 it != m->allMachines.end();
3143 ++it)
3144 {
3145 ComObjPtr<Machine> &pMachine = *it;
3146 AutoCaller machCaller(pMachine);
3147 if (machCaller.rc())
3148 continue; // we can't ask inaccessible machines for their names
3149
3150 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
3151 if (pMachine->i_getName() == aName)
3152 {
3153 rc = S_OK;
3154 if (aMachine)
3155 *aMachine = pMachine;
3156 break;
3157 }
3158 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
3159 {
3160 rc = S_OK;
3161 if (aMachine)
3162 *aMachine = pMachine;
3163 break;
3164 }
3165 }
3166
3167 if (aSetError && FAILED(rc))
3168 rc = setError(rc,
3169 tr("Could not find a registered machine named '%s'"), aName.c_str());
3170
3171 return rc;
3172}
3173
3174static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
3175{
3176 /* empty strings are invalid */
3177 if (aGroup.isEmpty())
3178 return E_INVALIDARG;
3179 /* the toplevel group is valid */
3180 if (aGroup == "/")
3181 return S_OK;
3182 /* any other strings of length 1 are invalid */
3183 if (aGroup.length() == 1)
3184 return E_INVALIDARG;
3185 /* must start with a slash */
3186 if (aGroup.c_str()[0] != '/')
3187 return E_INVALIDARG;
3188 /* must not end with a slash */
3189 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3190 return E_INVALIDARG;
3191 /* check the group components */
3192 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3193 while (pStr)
3194 {
3195 char *pSlash = RTStrStr(pStr, "/");
3196 if (pSlash)
3197 {
3198 /* no empty components (or // sequences in other words) */
3199 if (pSlash == pStr)
3200 return E_INVALIDARG;
3201 /* check if the machine name rules are violated, because that means
3202 * the group components are too close to the limits. */
3203 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3204 Utf8Str tmp2(tmp);
3205 sanitiseMachineFilename(tmp);
3206 if (tmp != tmp2)
3207 return E_INVALIDARG;
3208 if (fPrimary)
3209 {
3210 HRESULT rc = pVirtualBox->i_findMachineByName(tmp,
3211 false /* aSetError */);
3212 if (SUCCEEDED(rc))
3213 return VBOX_E_VM_ERROR;
3214 }
3215 pStr = pSlash + 1;
3216 }
3217 else
3218 {
3219 /* check if the machine name rules are violated, because that means
3220 * the group components is too close to the limits. */
3221 Utf8Str tmp(pStr);
3222 Utf8Str tmp2(tmp);
3223 sanitiseMachineFilename(tmp);
3224 if (tmp != tmp2)
3225 return E_INVALIDARG;
3226 pStr = NULL;
3227 }
3228 }
3229 return S_OK;
3230}
3231
3232/**
3233 * Validates a machine group.
3234 *
3235 * @param aMachineGroup Machine group.
3236 * @param fPrimary Set if this is the primary group.
3237 *
3238 * @return S_OK or E_INVALIDARG
3239 */
3240HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
3241{
3242 HRESULT rc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
3243 if (FAILED(rc))
3244 {
3245 if (rc == VBOX_E_VM_ERROR)
3246 rc = setError(E_INVALIDARG,
3247 tr("Machine group '%s' conflicts with a virtual machine name"),
3248 aGroup.c_str());
3249 else
3250 rc = setError(rc,
3251 tr("Invalid machine group '%s'"),
3252 aGroup.c_str());
3253 }
3254 return rc;
3255}
3256
3257/**
3258 * Takes a list of machine groups, and sanitizes/validates it.
3259 *
3260 * @param aMachineGroups Array with the machine groups.
3261 * @param pllMachineGroups Pointer to list of strings for the result.
3262 *
3263 * @return S_OK or E_INVALIDARG
3264 */
3265HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
3266{
3267 pllMachineGroups->clear();
3268 if (aMachineGroups.size())
3269 {
3270 for (size_t i = 0; i < aMachineGroups.size(); i++)
3271 {
3272 Utf8Str group(aMachineGroups[i]);
3273 if (group.length() == 0)
3274 group = "/";
3275
3276 HRESULT rc = i_validateMachineGroup(group, i == 0);
3277 if (FAILED(rc))
3278 return rc;
3279
3280 /* no duplicates please */
3281 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3282 == pllMachineGroups->end())
3283 pllMachineGroups->push_back(group);
3284 }
3285 if (pllMachineGroups->size() == 0)
3286 pllMachineGroups->push_back("/");
3287 }
3288 else
3289 pllMachineGroups->push_back("/");
3290
3291 return S_OK;
3292}
3293
3294/**
3295 * Searches for a Medium object with the given ID in the list of registered
3296 * hard disks.
3297 *
3298 * @param aId ID of the hard disk. Must not be empty.
3299 * @param aSetError If @c true , the appropriate error info is set in case
3300 * when the hard disk is not found.
3301 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3302 *
3303 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3304 *
3305 * @note Locks the media tree for reading.
3306 */
3307HRESULT VirtualBox::i_findHardDiskById(const Guid &id,
3308 bool aSetError,
3309 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3310{
3311 AssertReturn(!id.isZero(), E_INVALIDARG);
3312
3313 // we use the hard disks map, but it is protected by the
3314 // hard disk _list_ lock handle
3315 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3316
3317 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
3318 if (it != m->mapHardDisks.end())
3319 {
3320 if (aHardDisk)
3321 *aHardDisk = (*it).second;
3322 return S_OK;
3323 }
3324
3325 if (aSetError)
3326 return setError(VBOX_E_OBJECT_NOT_FOUND,
3327 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3328 id.raw());
3329
3330 return VBOX_E_OBJECT_NOT_FOUND;
3331}
3332
3333/**
3334 * Searches for a Medium object with the given ID or location in the list of
3335 * registered hard disks. If both ID and location are specified, the first
3336 * object that matches either of them (not necessarily both) is returned.
3337 *
3338 * @param aLocation Full location specification. Must not be empty.
3339 * @param aSetError If @c true , the appropriate error info is set in case
3340 * when the hard disk is not found.
3341 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3342 *
3343 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3344 *
3345 * @note Locks the media tree for reading.
3346 */
3347HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
3348 bool aSetError,
3349 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3350{
3351 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3352
3353 // we use the hard disks map, but it is protected by the
3354 // hard disk _list_ lock handle
3355 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3356
3357 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3358 it != m->mapHardDisks.end();
3359 ++it)
3360 {
3361 const ComObjPtr<Medium> &pHD = (*it).second;
3362
3363 AutoCaller autoCaller(pHD);
3364 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3365 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3366
3367 Utf8Str strLocationFull = pHD->i_getLocationFull();
3368
3369 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3370 {
3371 if (aHardDisk)
3372 *aHardDisk = pHD;
3373 return S_OK;
3374 }
3375 }
3376
3377 if (aSetError)
3378 return setError(VBOX_E_OBJECT_NOT_FOUND,
3379 tr("Could not find an open hard disk with location '%s'"),
3380 strLocation.c_str());
3381
3382 return VBOX_E_OBJECT_NOT_FOUND;
3383}
3384
3385/**
3386 * Searches for a Medium object with the given ID or location in the list of
3387 * registered DVD or floppy images, depending on the @a mediumType argument.
3388 * If both ID and file path are specified, the first object that matches either
3389 * of them (not necessarily both) is returned.
3390 *
3391 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3392 * @param aId ID of the image file (unused when NULL).
3393 * @param aLocation Full path to the image file (unused when NULL).
3394 * @param aSetError If @c true, the appropriate error info is set in case when
3395 * the image is not found.
3396 * @param aImage Where to store the found image object (can be NULL).
3397 *
3398 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3399 *
3400 * @note Locks the media tree for reading.
3401 */
3402HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
3403 const Guid *aId,
3404 const Utf8Str &aLocation,
3405 bool aSetError,
3406 ComObjPtr<Medium> *aImage /* = NULL */)
3407{
3408 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3409
3410 Utf8Str location;
3411 if (!aLocation.isEmpty())
3412 {
3413 int vrc = i_calculateFullPath(aLocation, location);
3414 if (RT_FAILURE(vrc))
3415 return setError(VBOX_E_FILE_ERROR,
3416 tr("Invalid image file location '%s' (%Rrc)"),
3417 aLocation.c_str(),
3418 vrc);
3419 }
3420
3421 MediaOList *pMediaList;
3422
3423 switch (mediumType)
3424 {
3425 case DeviceType_DVD:
3426 pMediaList = &m->allDVDImages;
3427 break;
3428
3429 case DeviceType_Floppy:
3430 pMediaList = &m->allFloppyImages;
3431 break;
3432
3433 default:
3434 return E_INVALIDARG;
3435 }
3436
3437 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3438
3439 bool found = false;
3440
3441 for (MediaList::const_iterator it = pMediaList->begin();
3442 it != pMediaList->end();
3443 ++it)
3444 {
3445 // no AutoCaller, registered image life time is bound to this
3446 Medium *pMedium = *it;
3447 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3448 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
3449
3450 found = ( aId
3451 && pMedium->i_getId() == *aId)
3452 || ( !aLocation.isEmpty()
3453 && RTPathCompare(location.c_str(),
3454 strLocationFull.c_str()) == 0);
3455 if (found)
3456 {
3457 if (pMedium->i_getDeviceType() != mediumType)
3458 {
3459 if (mediumType == DeviceType_DVD)
3460 return setError(E_INVALIDARG,
3461 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3462 else
3463 return setError(E_INVALIDARG,
3464 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3465 }
3466
3467 if (aImage)
3468 *aImage = pMedium;
3469 break;
3470 }
3471 }
3472
3473 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3474
3475 if (aSetError && !found)
3476 {
3477 if (aId)
3478 setError(rc,
3479 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3480 aId->raw(),
3481 m->strSettingsFilePath.c_str());
3482 else
3483 setError(rc,
3484 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3485 aLocation.c_str(),
3486 m->strSettingsFilePath.c_str());
3487 }
3488
3489 return rc;
3490}
3491
3492/**
3493 * Searches for an IMedium object that represents the given UUID.
3494 *
3495 * If the UUID is empty (indicating an empty drive), this sets pMedium
3496 * to NULL and returns S_OK.
3497 *
3498 * If the UUID refers to a host drive of the given device type, this
3499 * sets pMedium to the object from the list in IHost and returns S_OK.
3500 *
3501 * If the UUID is an image file, this sets pMedium to the object that
3502 * findDVDOrFloppyImage() returned.
3503 *
3504 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3505 *
3506 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3507 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3508 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3509 * @param pMedium out: IMedium object found.
3510 * @return
3511 */
3512HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
3513 const Guid &uuid,
3514 bool fRefresh,
3515 bool aSetError,
3516 ComObjPtr<Medium> &pMedium)
3517{
3518 if (uuid.isZero())
3519 {
3520 // that's easy
3521 pMedium.setNull();
3522 return S_OK;
3523 }
3524 else if (!uuid.isValid())
3525 {
3526 /* handling of case invalid GUID */
3527 return setError(VBOX_E_OBJECT_NOT_FOUND,
3528 tr("Guid '%s' is invalid"),
3529 uuid.toString().c_str());
3530 }
3531
3532 // first search for host drive with that UUID
3533 HRESULT rc = m->pHost->i_findHostDriveById(mediumType,
3534 uuid,
3535 fRefresh,
3536 pMedium);
3537 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3538 // then search for an image with that UUID
3539 rc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3540
3541 return rc;
3542}
3543
3544HRESULT VirtualBox::i_findGuestOSType(const Bstr &bstrOSType,
3545 GuestOSType*& pGuestOSType)
3546{
3547 /* Look for a GuestOSType object */
3548 AssertMsg(m->allGuestOSTypes.size() != 0,
3549 ("Guest OS types array must be filled"));
3550
3551 if (bstrOSType.isEmpty())
3552 {
3553 pGuestOSType = NULL;
3554 return S_OK;
3555 }
3556
3557 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3558 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3559 it != m->allGuestOSTypes.end();
3560 ++it)
3561 {
3562 if ((*it)->i_id() == bstrOSType)
3563 {
3564 pGuestOSType = *it;
3565 return S_OK;
3566 }
3567 }
3568
3569 return setError(VBOX_E_OBJECT_NOT_FOUND,
3570 tr("Guest OS type '%ls' is invalid"),
3571 bstrOSType.raw());
3572}
3573
3574/**
3575 * Returns the constant pseudo-machine UUID that is used to identify the
3576 * global media registry.
3577 *
3578 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3579 * in which media registry it is saved (if any): this can either be a machine
3580 * UUID, if it's in a per-machine media registry, or this global ID.
3581 *
3582 * This UUID is only used to identify the VirtualBox object while VirtualBox
3583 * is running. It is a compile-time constant and not saved anywhere.
3584 *
3585 * @return
3586 */
3587const Guid& VirtualBox::i_getGlobalRegistryId() const
3588{
3589 return m->uuidMediaRegistry;
3590}
3591
3592const ComObjPtr<Host>& VirtualBox::i_host() const
3593{
3594 return m->pHost;
3595}
3596
3597SystemProperties* VirtualBox::i_getSystemProperties() const
3598{
3599 return m->pSystemProperties;
3600}
3601
3602#ifdef VBOX_WITH_EXTPACK
3603/**
3604 * Getter that SystemProperties and others can use to talk to the extension
3605 * pack manager.
3606 */
3607ExtPackManager* VirtualBox::i_getExtPackManager() const
3608{
3609 return m->ptrExtPackManager;
3610}
3611#endif
3612
3613/**
3614 * Getter that machines can talk to the autostart database.
3615 */
3616AutostartDb* VirtualBox::i_getAutostartDb() const
3617{
3618 return m->pAutostartDb;
3619}
3620
3621#ifdef VBOX_WITH_RESOURCE_USAGE_API
3622const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
3623{
3624 return m->pPerformanceCollector;
3625}
3626#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3627
3628/**
3629 * Returns the default machine folder from the system properties
3630 * with proper locking.
3631 * @return
3632 */
3633void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
3634{
3635 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3636 str = m->pSystemProperties->m->strDefaultMachineFolder;
3637}
3638
3639/**
3640 * Returns the default hard disk format from the system properties
3641 * with proper locking.
3642 * @return
3643 */
3644void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
3645{
3646 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3647 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3648}
3649
3650const Utf8Str& VirtualBox::i_homeDir() const
3651{
3652 return m->strHomeDir;
3653}
3654
3655/**
3656 * Calculates the absolute path of the given path taking the VirtualBox home
3657 * directory as the current directory.
3658 *
3659 * @param aPath Path to calculate the absolute path for.
3660 * @param aResult Where to put the result (used only on success, can be the
3661 * same Utf8Str instance as passed in @a aPath).
3662 * @return IPRT result.
3663 *
3664 * @note Doesn't lock any object.
3665 */
3666int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3667{
3668 AutoCaller autoCaller(this);
3669 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3670
3671 /* no need to lock since mHomeDir is const */
3672
3673 char folder[RTPATH_MAX];
3674 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3675 strPath.c_str(),
3676 folder,
3677 sizeof(folder));
3678 if (RT_SUCCESS(vrc))
3679 aResult = folder;
3680
3681 return vrc;
3682}
3683
3684/**
3685 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3686 * if it is a subdirectory thereof, or simply copying it otherwise.
3687 *
3688 * @param strSource Path to evalue and copy.
3689 * @param strTarget Buffer to receive target path.
3690 */
3691void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
3692 Utf8Str &strTarget)
3693{
3694 AutoCaller autoCaller(this);
3695 AssertComRCReturnVoid(autoCaller.rc());
3696
3697 // no need to lock since mHomeDir is const
3698
3699 // use strTarget as a temporary buffer to hold the machine settings dir
3700 strTarget = m->strHomeDir;
3701 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3702 // is relative: then append what's left
3703 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3704 else
3705 // is not relative: then overwrite
3706 strTarget = strSource;
3707}
3708
3709// private methods
3710/////////////////////////////////////////////////////////////////////////////
3711
3712/**
3713 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3714 * location already registered.
3715 *
3716 * On return, sets @a aConflict to the string describing the conflicting medium,
3717 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3718 * either case. A failure is unexpected.
3719 *
3720 * @param aId UUID to check.
3721 * @param aLocation Location to check.
3722 * @param aConflict Where to return parameters of the conflicting medium.
3723 * @param ppMedium Medium reference in case this is simply a duplicate.
3724 *
3725 * @note Locks the media tree and media objects for reading.
3726 */
3727HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
3728 const Utf8Str &aLocation,
3729 Utf8Str &aConflict,
3730 ComObjPtr<Medium> *ppMedium)
3731{
3732 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
3733 AssertReturn(ppMedium, E_INVALIDARG);
3734
3735 aConflict.setNull();
3736 ppMedium->setNull();
3737
3738 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3739
3740 HRESULT rc = S_OK;
3741
3742 ComObjPtr<Medium> pMediumFound;
3743 const char *pcszType = NULL;
3744
3745 if (aId.isValid() && !aId.isZero())
3746 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3747 if (FAILED(rc) && !aLocation.isEmpty())
3748 rc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3749 if (SUCCEEDED(rc))
3750 pcszType = tr("hard disk");
3751
3752 if (!pcszType)
3753 {
3754 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3755 if (SUCCEEDED(rc))
3756 pcszType = tr("CD/DVD image");
3757 }
3758
3759 if (!pcszType)
3760 {
3761 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3762 if (SUCCEEDED(rc))
3763 pcszType = tr("floppy image");
3764 }
3765
3766 if (pcszType && pMediumFound)
3767 {
3768 /* Note: no AutoCaller since bound to this */
3769 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3770
3771 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
3772 Guid idFound = pMediumFound->i_getId();
3773
3774 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3775 && (idFound == aId)
3776 )
3777 *ppMedium = pMediumFound;
3778
3779 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3780 pcszType,
3781 strLocFound.c_str(),
3782 idFound.raw());
3783 }
3784
3785 return S_OK;
3786}
3787
3788/**
3789 * Checks whether the given UUID is already in use by one medium for the
3790 * given device type.
3791 *
3792 * @returns true if the UUID is already in use
3793 * fale otherwise
3794 * @param aId The UUID to check.
3795 * @param deviceType The device type the UUID is going to be checked for
3796 * conflicts.
3797 */
3798bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
3799{
3800 /* A zero UUID is invalid here, always claim that it is already used. */
3801 AssertReturn(!aId.isZero(), true);
3802
3803 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3804
3805 HRESULT rc = S_OK;
3806 bool fInUse = false;
3807
3808 ComObjPtr<Medium> pMediumFound;
3809
3810 switch (deviceType)
3811 {
3812 case DeviceType_HardDisk:
3813 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3814 break;
3815 case DeviceType_DVD:
3816 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3817 break;
3818 case DeviceType_Floppy:
3819 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3820 break;
3821 default:
3822 AssertMsgFailed(("Invalid device type %d\n", deviceType));
3823 }
3824
3825 if (SUCCEEDED(rc) && pMediumFound)
3826 fInUse = true;
3827
3828 return fInUse;
3829}
3830
3831/**
3832 * Called from Machine::prepareSaveSettings() when it has detected
3833 * that a machine has been renamed. Such renames will require
3834 * updating the global media registry during the
3835 * VirtualBox::saveSettings() that follows later.
3836*
3837 * When a machine is renamed, there may well be media (in particular,
3838 * diff images for snapshots) in the global registry that will need
3839 * to have their paths updated. Before 3.2, Machine::saveSettings
3840 * used to call VirtualBox::saveSettings implicitly, which was both
3841 * unintuitive and caused locking order problems. Now, we remember
3842 * such pending name changes with this method so that
3843 * VirtualBox::saveSettings() can process them properly.
3844 */
3845void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3846 const Utf8Str &strNewConfigDir)
3847{
3848 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3849
3850 Data::PendingMachineRename pmr;
3851 pmr.strConfigDirOld = strOldConfigDir;
3852 pmr.strConfigDirNew = strNewConfigDir;
3853 m->llPendingMachineRenames.push_back(pmr);
3854}
3855
3856struct SaveMediaRegistriesDesc
3857{
3858 MediaList llMedia;
3859 ComObjPtr<VirtualBox> pVirtualBox;
3860};
3861
3862static int fntSaveMediaRegistries(RTTHREAD ThreadSelf, void *pvUser)
3863{
3864 NOREF(ThreadSelf);
3865 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
3866 if (!pDesc)
3867 {
3868 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
3869 return VERR_INVALID_PARAMETER;
3870 }
3871
3872 for (MediaList::const_iterator it = pDesc->llMedia.begin();
3873 it != pDesc->llMedia.end();
3874 ++it)
3875 {
3876 Medium *pMedium = *it;
3877 pMedium->i_markRegistriesModified();
3878 }
3879
3880 pDesc->pVirtualBox->i_saveModifiedRegistries();
3881
3882 pDesc->llMedia.clear();
3883 pDesc->pVirtualBox.setNull();
3884 delete pDesc;
3885
3886 return VINF_SUCCESS;
3887}
3888
3889/**
3890 * Goes through all known media (hard disks, floppies and DVDs) and saves
3891 * those into the given settings::MediaRegistry structures whose registry
3892 * ID match the given UUID.
3893 *
3894 * Before actually writing to the structures, all media paths (not just the
3895 * ones for the given registry) are updated if machines have been renamed
3896 * since the last call.
3897 *
3898 * This gets called from two contexts:
3899 *
3900 * -- VirtualBox::saveSettings() with the UUID of the global registry
3901 * (VirtualBox::Data.uuidRegistry); this will save those media
3902 * which had been loaded from the global registry or have been
3903 * attached to a "legacy" machine which can't save its own registry;
3904 *
3905 * -- Machine::saveSettings() with the UUID of a machine, if a medium
3906 * has been attached to a machine created with VirtualBox 4.0 or later.
3907 *
3908 * Media which have only been temporarily opened without having been
3909 * attached to a machine have a NULL registry UUID and therefore don't
3910 * get saved.
3911 *
3912 * This locks the media tree. Throws HRESULT on errors!
3913 *
3914 * @param mediaRegistry Settings structure to fill.
3915 * @param uuidRegistry The UUID of the media registry; either a machine UUID
3916 * (if machine registry) or the UUID of the global registry.
3917 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
3918 */
3919void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
3920 const Guid &uuidRegistry,
3921 const Utf8Str &strMachineFolder)
3922{
3923 // lock all media for the following; use a write lock because we're
3924 // modifying the PendingMachineRenamesList, which is protected by this
3925 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3926
3927 // if a machine was renamed, then we'll need to refresh media paths
3928 if (m->llPendingMachineRenames.size())
3929 {
3930 // make a single list from the three media lists so we don't need three loops
3931 MediaList llAllMedia;
3932 // with hard disks, we must use the map, not the list, because the list only has base images
3933 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
3934 llAllMedia.push_back(it->second);
3935 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
3936 llAllMedia.push_back(*it);
3937 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
3938 llAllMedia.push_back(*it);
3939
3940 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
3941 for (MediaList::iterator it = llAllMedia.begin();
3942 it != llAllMedia.end();
3943 ++it)
3944 {
3945 Medium *pMedium = *it;
3946 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
3947 it2 != m->llPendingMachineRenames.end();
3948 ++it2)
3949 {
3950 const Data::PendingMachineRename &pmr = *it2;
3951 HRESULT rc = pMedium->i_updatePath(pmr.strConfigDirOld,
3952 pmr.strConfigDirNew);
3953 if (SUCCEEDED(rc))
3954 {
3955 // Remember which medium objects has been changed,
3956 // to trigger saving their registries later.
3957 pDesc->llMedia.push_back(pMedium);
3958 } else if (rc == VBOX_E_FILE_ERROR)
3959 /* nothing */;
3960 else
3961 AssertComRC(rc);
3962 }
3963 }
3964 // done, don't do it again until we have more machine renames
3965 m->llPendingMachineRenames.clear();
3966
3967 if (pDesc->llMedia.size())
3968 {
3969 // Handle the media registry saving in a separate thread, to
3970 // avoid giant locking problems and passing up the list many
3971 // levels up to whoever triggered saveSettings, as there are
3972 // lots of places which would need to handle saving more settings.
3973 pDesc->pVirtualBox = this;
3974 int vrc = RTThreadCreate(NULL,
3975 fntSaveMediaRegistries,
3976 (void *)pDesc,
3977 0, // cbStack (default)
3978 RTTHREADTYPE_MAIN_WORKER,
3979 0, // flags
3980 "SaveMediaReg");
3981 ComAssertRC(vrc);
3982 // failure means that settings aren't saved, but there isn't
3983 // much we can do besides avoiding memory leaks
3984 if (RT_FAILURE(vrc))
3985 {
3986 LogRelFunc(("Failed to create thread for saving media registries (%Rrc)\n", vrc));
3987 delete pDesc;
3988 }
3989 }
3990 else
3991 delete pDesc;
3992 }
3993
3994 struct {
3995 MediaOList &llSource;
3996 settings::MediaList &llTarget;
3997 } s[] =
3998 {
3999 // hard disks
4000 { m->allHardDisks, mediaRegistry.llHardDisks },
4001 // CD/DVD images
4002 { m->allDVDImages, mediaRegistry.llDvdImages },
4003 // floppy images
4004 { m->allFloppyImages, mediaRegistry.llFloppyImages }
4005 };
4006
4007 HRESULT rc;
4008
4009 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
4010 {
4011 MediaOList &llSource = s[i].llSource;
4012 settings::MediaList &llTarget = s[i].llTarget;
4013 llTarget.clear();
4014 for (MediaList::const_iterator it = llSource.begin();
4015 it != llSource.end();
4016 ++it)
4017 {
4018 Medium *pMedium = *it;
4019 AutoCaller autoCaller(pMedium);
4020 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
4021 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4022
4023 if (pMedium->i_isInRegistry(uuidRegistry))
4024 {
4025 settings::Medium med;
4026 rc = pMedium->i_saveSettings(med, strMachineFolder); // this recurses into child hard disks
4027 if (FAILED(rc)) throw rc;
4028 llTarget.push_back(med);
4029 }
4030 }
4031 }
4032}
4033
4034/**
4035 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
4036 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
4037 * places internally when settings need saving.
4038 *
4039 * @note Caller must have locked the VirtualBox object for writing and must not hold any
4040 * other locks since this locks all kinds of member objects and trees temporarily,
4041 * which could cause conflicts.
4042 */
4043HRESULT VirtualBox::i_saveSettings()
4044{
4045 AutoCaller autoCaller(this);
4046 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4047
4048 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
4049 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
4050
4051 HRESULT rc = S_OK;
4052
4053 try
4054 {
4055 // machines
4056 m->pMainConfigFile->llMachines.clear();
4057 {
4058 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4059 for (MachinesOList::iterator it = m->allMachines.begin();
4060 it != m->allMachines.end();
4061 ++it)
4062 {
4063 Machine *pMachine = *it;
4064 // save actual machine registry entry
4065 settings::MachineRegistryEntry mre;
4066 rc = pMachine->i_saveRegistryEntry(mre);
4067 m->pMainConfigFile->llMachines.push_back(mre);
4068 }
4069 }
4070
4071 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
4072 m->uuidMediaRegistry, // global media registry ID
4073 Utf8Str::Empty); // strMachineFolder
4074
4075 m->pMainConfigFile->llDhcpServers.clear();
4076 {
4077 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4078 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4079 it != m->allDHCPServers.end();
4080 ++it)
4081 {
4082 settings::DHCPServer d;
4083 rc = (*it)->i_saveSettings(d);
4084 if (FAILED(rc)) throw rc;
4085 m->pMainConfigFile->llDhcpServers.push_back(d);
4086 }
4087 }
4088
4089#ifdef VBOX_WITH_NAT_SERVICE
4090 /* Saving NAT Network configuration */
4091 m->pMainConfigFile->llNATNetworks.clear();
4092 {
4093 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4094 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4095 it != m->allNATNetworks.end();
4096 ++it)
4097 {
4098 settings::NATNetwork n;
4099 rc = (*it)->i_saveSettings(n);
4100 if (FAILED(rc)) throw rc;
4101 m->pMainConfigFile->llNATNetworks.push_back(n);
4102 }
4103 }
4104#endif
4105
4106 // leave extra data alone, it's still in the config file
4107
4108 // host data (USB filters)
4109 rc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
4110 if (FAILED(rc)) throw rc;
4111
4112 rc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
4113 if (FAILED(rc)) throw rc;
4114
4115 // and write out the XML, still under the lock
4116 m->pMainConfigFile->write(m->strSettingsFilePath);
4117 }
4118 catch (HRESULT err)
4119 {
4120 /* we assume that error info is set by the thrower */
4121 rc = err;
4122 }
4123 catch (...)
4124 {
4125 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
4126 }
4127
4128 return rc;
4129}
4130
4131/**
4132 * Helper to register the machine.
4133 *
4134 * When called during VirtualBox startup, adds the given machine to the
4135 * collection of registered machines. Otherwise tries to mark the machine
4136 * as registered, and, if succeeded, adds it to the collection and
4137 * saves global settings.
4138 *
4139 * @note The caller must have added itself as a caller of the @a aMachine
4140 * object if calls this method not on VirtualBox startup.
4141 *
4142 * @param aMachine machine to register
4143 *
4144 * @note Locks objects!
4145 */
4146HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
4147{
4148 ComAssertRet(aMachine, E_INVALIDARG);
4149
4150 AutoCaller autoCaller(this);
4151 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4152
4153 HRESULT rc = S_OK;
4154
4155 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4156
4157 {
4158 ComObjPtr<Machine> pMachine;
4159 rc = i_findMachine(aMachine->i_getId(),
4160 true /* fPermitInaccessible */,
4161 false /* aDoSetError */,
4162 &pMachine);
4163 if (SUCCEEDED(rc))
4164 {
4165 /* sanity */
4166 AutoLimitedCaller machCaller(pMachine);
4167 AssertComRC(machCaller.rc());
4168
4169 return setError(E_INVALIDARG,
4170 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
4171 aMachine->i_getId().raw(),
4172 pMachine->i_getSettingsFileFull().c_str());
4173 }
4174
4175 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
4176 rc = S_OK;
4177 }
4178
4179 if (getObjectState().getState() != ObjectState::InInit)
4180 {
4181 rc = aMachine->i_prepareRegister();
4182 if (FAILED(rc)) return rc;
4183 }
4184
4185 /* add to the collection of registered machines */
4186 m->allMachines.addChild(aMachine);
4187
4188 if (getObjectState().getState() != ObjectState::InInit)
4189 rc = i_saveSettings();
4190
4191 return rc;
4192}
4193
4194/**
4195 * Remembers the given medium object by storing it in either the global
4196 * medium registry or a machine one.
4197 *
4198 * @note Caller must hold the media tree lock for writing; in addition, this
4199 * locks @a pMedium for reading
4200 *
4201 * @param pMedium Medium object to remember.
4202 * @param ppMedium Actually stored medium object. Can be different if due
4203 * to an unavoidable race there was a duplicate Medium object
4204 * created.
4205 * @param argType Either DeviceType_HardDisk, DeviceType_DVD or DeviceType_Floppy.
4206 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
4207 * lock, necessary to release it in the right spot.
4208 * @return
4209 */
4210HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
4211 ComObjPtr<Medium> *ppMedium,
4212 DeviceType_T argType,
4213 AutoWriteLock &mediaTreeLock)
4214{
4215 AssertReturn(pMedium != NULL, E_INVALIDARG);
4216 AssertReturn(ppMedium != NULL, E_INVALIDARG);
4217
4218 // caller must hold the media tree write lock
4219 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4220
4221 AutoCaller autoCaller(this);
4222 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4223
4224 AutoCaller mediumCaller(pMedium);
4225 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4226
4227 const char *pszDevType = NULL;
4228 ObjectsList<Medium> *pall = NULL;
4229 switch (argType)
4230 {
4231 case DeviceType_HardDisk:
4232 pall = &m->allHardDisks;
4233 pszDevType = tr("hard disk");
4234 break;
4235 case DeviceType_DVD:
4236 pszDevType = tr("DVD image");
4237 pall = &m->allDVDImages;
4238 break;
4239 case DeviceType_Floppy:
4240 pszDevType = tr("floppy image");
4241 pall = &m->allFloppyImages;
4242 break;
4243 default:
4244 AssertMsgFailedReturn(("invalid device type %d", argType), E_INVALIDARG);
4245 }
4246
4247 Guid id;
4248 Utf8Str strLocationFull;
4249 ComObjPtr<Medium> pParent;
4250 {
4251 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4252 id = pMedium->i_getId();
4253 strLocationFull = pMedium->i_getLocationFull();
4254 pParent = pMedium->i_getParent();
4255 }
4256
4257 HRESULT rc;
4258
4259 Utf8Str strConflict;
4260 ComObjPtr<Medium> pDupMedium;
4261 rc = i_checkMediaForConflicts(id,
4262 strLocationFull,
4263 strConflict,
4264 &pDupMedium);
4265 if (FAILED(rc)) return rc;
4266
4267 if (pDupMedium.isNull())
4268 {
4269 if (strConflict.length())
4270 return setError(E_INVALIDARG,
4271 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4272 pszDevType,
4273 strLocationFull.c_str(),
4274 id.raw(),
4275 strConflict.c_str(),
4276 m->strSettingsFilePath.c_str());
4277
4278 // add to the collection if it is a base medium
4279 if (pParent.isNull())
4280 pall->getList().push_back(pMedium);
4281
4282 // store all hard disks (even differencing images) in the map
4283 if (argType == DeviceType_HardDisk)
4284 m->mapHardDisks[id] = pMedium;
4285
4286 mediumCaller.release();
4287 mediaTreeLock.release();
4288 *ppMedium = pMedium;
4289 }
4290 else
4291 {
4292 // pMedium may be the last reference to the Medium object, and the
4293 // caller may have specified the same ComObjPtr as the output parameter.
4294 // In this case the assignment will uninit the object, and we must not
4295 // have a caller pending.
4296 mediumCaller.release();
4297 // release media tree lock, must not be held at uninit time.
4298 mediaTreeLock.release();
4299 // must not hold the media tree write lock any more
4300 Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4301 *ppMedium = pDupMedium;
4302 }
4303
4304 // Restore the initial lock state, so that no unexpected lock changes are
4305 // done by this method, which would need adjustments everywhere.
4306 mediaTreeLock.acquire();
4307
4308 return rc;
4309}
4310
4311/**
4312 * Removes the given medium from the respective registry.
4313 *
4314 * @param pMedium Hard disk object to remove.
4315 *
4316 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4317 */
4318HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
4319{
4320 AssertReturn(pMedium != NULL, E_INVALIDARG);
4321
4322 AutoCaller autoCaller(this);
4323 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4324
4325 AutoCaller mediumCaller(pMedium);
4326 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4327
4328 // caller must hold the media tree write lock
4329 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4330
4331 Guid id;
4332 ComObjPtr<Medium> pParent;
4333 DeviceType_T devType;
4334 {
4335 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4336 id = pMedium->i_getId();
4337 pParent = pMedium->i_getParent();
4338 devType = pMedium->i_getDeviceType();
4339 }
4340
4341 ObjectsList<Medium> *pall = NULL;
4342 switch (devType)
4343 {
4344 case DeviceType_HardDisk:
4345 pall = &m->allHardDisks;
4346 break;
4347 case DeviceType_DVD:
4348 pall = &m->allDVDImages;
4349 break;
4350 case DeviceType_Floppy:
4351 pall = &m->allFloppyImages;
4352 break;
4353 default:
4354 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4355 }
4356
4357 // remove from the collection if it is a base medium
4358 if (pParent.isNull())
4359 pall->getList().remove(pMedium);
4360
4361 // remove all hard disks (even differencing images) from map
4362 if (devType == DeviceType_HardDisk)
4363 {
4364 size_t cnt = m->mapHardDisks.erase(id);
4365 Assert(cnt == 1);
4366 NOREF(cnt);
4367 }
4368
4369 return S_OK;
4370}
4371
4372/**
4373 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4374 * with children appearing before their parents.
4375 * @param llMedia
4376 * @param pMedium
4377 */
4378void VirtualBox::i_pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4379{
4380 // recurse first, then add ourselves; this way children end up on the
4381 // list before their parents
4382
4383 const MediaList &llChildren = pMedium->i_getChildren();
4384 for (MediaList::const_iterator it = llChildren.begin();
4385 it != llChildren.end();
4386 ++it)
4387 {
4388 Medium *pChild = *it;
4389 i_pushMediumToListWithChildren(llMedia, pChild);
4390 }
4391
4392 Log(("Pushing medium %RTuuid\n", pMedium->i_getId().raw()));
4393 llMedia.push_back(pMedium);
4394}
4395
4396/**
4397 * Unregisters all Medium objects which belong to the given machine registry.
4398 * Gets called from Machine::uninit() just before the machine object dies
4399 * and must only be called with a machine UUID as the registry ID.
4400 *
4401 * Locks the media tree.
4402 *
4403 * @param uuidMachine Medium registry ID (always a machine UUID)
4404 * @return
4405 */
4406HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
4407{
4408 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
4409
4410 LogFlowFuncEnter();
4411
4412 AutoCaller autoCaller(this);
4413 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4414
4415 MediaList llMedia2Close;
4416
4417 {
4418 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4419
4420 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4421 it != m->allHardDisks.getList().end();
4422 ++it)
4423 {
4424 ComObjPtr<Medium> pMedium = *it;
4425 AutoCaller medCaller(pMedium);
4426 if (FAILED(medCaller.rc())) return medCaller.rc();
4427 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4428
4429 if (pMedium->i_isInRegistry(uuidMachine))
4430 // recursively with children first
4431 i_pushMediumToListWithChildren(llMedia2Close, pMedium);
4432 }
4433 }
4434
4435 for (MediaList::iterator it = llMedia2Close.begin();
4436 it != llMedia2Close.end();
4437 ++it)
4438 {
4439 ComObjPtr<Medium> pMedium = *it;
4440 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
4441 AutoCaller mac(pMedium);
4442 pMedium->i_close(mac);
4443 }
4444
4445 LogFlowFuncLeave();
4446
4447 return S_OK;
4448}
4449
4450/**
4451 * Removes the given machine object from the internal list of registered machines.
4452 * Called from Machine::Unregister().
4453 * @param pMachine
4454 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4455 * @return
4456 */
4457HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
4458 const Guid &id)
4459{
4460 // remove from the collection of registered machines
4461 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4462 m->allMachines.removeChild(pMachine);
4463 // save the global registry
4464 HRESULT rc = i_saveSettings();
4465 alock.release();
4466
4467 /*
4468 * Now go over all known media and checks if they were registered in the
4469 * media registry of the given machine. Each such medium is then moved to
4470 * a different media registry to make sure it doesn't get lost since its
4471 * media registry is about to go away.
4472 *
4473 * This fixes the following use case: Image A.vdi of machine A is also used
4474 * by machine B, but registered in the media registry of machine A. If machine
4475 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4476 * become inaccessible.
4477 */
4478 {
4479 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4480 // iterate over the list of *base* images
4481 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4482 it != m->allHardDisks.getList().end();
4483 ++it)
4484 {
4485 ComObjPtr<Medium> &pMedium = *it;
4486 AutoCaller medCaller(pMedium);
4487 if (FAILED(medCaller.rc())) return medCaller.rc();
4488 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4489
4490 if (pMedium->i_removeRegistry(id, true /* fRecurse */))
4491 {
4492 // machine ID was found in base medium's registry list:
4493 // move this base image and all its children to another registry then
4494 // 1) first, find a better registry to add things to
4495 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref();
4496 if (puuidBetter)
4497 {
4498 // 2) better registry found: then use that
4499 pMedium->i_addRegistry(*puuidBetter, true /* fRecurse */);
4500 // 3) and make sure the registry is saved below
4501 mlock.release();
4502 tlock.release();
4503 i_markRegistryModified(*puuidBetter);
4504 tlock.acquire();
4505 mlock.release();
4506 }
4507 }
4508 }
4509 }
4510
4511 i_saveModifiedRegistries();
4512
4513 /* fire an event */
4514 i_onMachineRegistered(id, FALSE);
4515
4516 return rc;
4517}
4518
4519/**
4520 * Marks the registry for @a uuid as modified, so that it's saved in a later
4521 * call to saveModifiedRegistries().
4522 *
4523 * @param uuid
4524 */
4525void VirtualBox::i_markRegistryModified(const Guid &uuid)
4526{
4527 if (uuid == i_getGlobalRegistryId())
4528 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4529 else
4530 {
4531 ComObjPtr<Machine> pMachine;
4532 HRESULT rc = i_findMachine(uuid,
4533 false /* fPermitInaccessible */,
4534 false /* aSetError */,
4535 &pMachine);
4536 if (SUCCEEDED(rc))
4537 {
4538 AutoCaller machineCaller(pMachine);
4539 if (SUCCEEDED(machineCaller.rc()))
4540 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4541 }
4542 }
4543}
4544
4545/**
4546 * Saves all settings files according to the modified flags in the Machine
4547 * objects and in the VirtualBox object.
4548 *
4549 * This locks machines and the VirtualBox object as necessary, so better not
4550 * hold any locks before calling this.
4551 *
4552 * @return
4553 */
4554void VirtualBox::i_saveModifiedRegistries()
4555{
4556 HRESULT rc = S_OK;
4557 bool fNeedsGlobalSettings = false;
4558 uint64_t uOld;
4559
4560 {
4561 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4562 for (MachinesOList::iterator it = m->allMachines.begin();
4563 it != m->allMachines.end();
4564 ++it)
4565 {
4566 const ComObjPtr<Machine> &pMachine = *it;
4567
4568 for (;;)
4569 {
4570 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4571 if (!uOld)
4572 break;
4573 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4574 break;
4575 ASMNopPause();
4576 }
4577 if (uOld)
4578 {
4579 AutoCaller autoCaller(pMachine);
4580 if (FAILED(autoCaller.rc()))
4581 continue;
4582 /* object is already dead, no point in saving settings */
4583 if (getObjectState().getState() != ObjectState::Ready)
4584 continue;
4585 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
4586 rc = pMachine->i_saveSettings(&fNeedsGlobalSettings,
4587 Machine::SaveS_Force); // caller said save, so stop arguing
4588 }
4589 }
4590 }
4591
4592 for (;;)
4593 {
4594 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4595 if (!uOld)
4596 break;
4597 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4598 break;
4599 ASMNopPause();
4600 }
4601 if (uOld || fNeedsGlobalSettings)
4602 {
4603 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4604 rc = i_saveSettings();
4605 }
4606 NOREF(rc); /* XXX */
4607}
4608
4609
4610/* static */
4611const com::Utf8Str &VirtualBox::i_getVersionNormalized()
4612{
4613 return sVersionNormalized;
4614}
4615
4616/**
4617 * Checks if the path to the specified file exists, according to the path
4618 * information present in the file name. Optionally the path is created.
4619 *
4620 * Note that the given file name must contain the full path otherwise the
4621 * extracted relative path will be created based on the current working
4622 * directory which is normally unknown.
4623 *
4624 * @param aFileName Full file name which path is checked/created.
4625 * @param aCreate Flag if the path should be created if it doesn't exist.
4626 *
4627 * @return Extended error information on failure to check/create the path.
4628 */
4629/* static */
4630HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4631{
4632 Utf8Str strDir(strFileName);
4633 strDir.stripFilename();
4634 if (!RTDirExists(strDir.c_str()))
4635 {
4636 if (fCreate)
4637 {
4638 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4639 if (RT_FAILURE(vrc))
4640 return i_setErrorStatic(VBOX_E_IPRT_ERROR,
4641 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4642 strDir.c_str(),
4643 vrc));
4644 }
4645 else
4646 return i_setErrorStatic(VBOX_E_IPRT_ERROR,
4647 Utf8StrFmt(tr("Directory '%s' does not exist"),
4648 strDir.c_str()));
4649 }
4650
4651 return S_OK;
4652}
4653
4654const Utf8Str& VirtualBox::i_settingsFilePath()
4655{
4656 return m->strSettingsFilePath;
4657}
4658
4659/**
4660 * Returns the lock handle which protects the machines list. As opposed
4661 * to version 3.1 and earlier, these lists are no longer protected by the
4662 * VirtualBox lock, but by this more specialized lock. Mind the locking
4663 * order: always request this lock after the VirtualBox object lock but
4664 * before the locks of any machine object. See AutoLock.h.
4665 */
4666RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
4667{
4668 return m->lockMachines;
4669}
4670
4671/**
4672 * Returns the lock handle which protects the media trees (hard disks,
4673 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4674 * are no longer protected by the VirtualBox lock, but by this more
4675 * specialized lock. Mind the locking order: always request this lock
4676 * after the VirtualBox object lock but before the locks of the media
4677 * objects contained in these lists. See AutoLock.h.
4678 */
4679RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
4680{
4681 return m->lockMedia;
4682}
4683
4684/**
4685 * Thread function that handles custom events posted using #postEvent().
4686 */
4687// static
4688DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4689{
4690 LogFlowFuncEnter();
4691
4692 AssertReturn(pvUser, VERR_INVALID_POINTER);
4693
4694 HRESULT hr = com::Initialize();
4695 if (FAILED(hr))
4696 return VERR_COM_UNEXPECTED;
4697
4698 int rc = VINF_SUCCESS;
4699
4700 try
4701 {
4702 /* Create an event queue for the current thread. */
4703 EventQueue *pEventQueue = new EventQueue();
4704 AssertPtr(pEventQueue);
4705
4706 /* Return the queue to the one who created this thread. */
4707 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
4708
4709 /* signal that we're ready. */
4710 RTThreadUserSignal(thread);
4711
4712 /*
4713 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4714 * we must not stop processing events and delete the pEventQueue object. This must
4715 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4716 * See @bugref{5724}.
4717 */
4718 for (;;)
4719 {
4720 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
4721 if (rc == VERR_INTERRUPTED)
4722 {
4723 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
4724 rc = VINF_SUCCESS; /* Set success when exiting. */
4725 break;
4726 }
4727 }
4728
4729 delete pEventQueue;
4730 }
4731 catch (std::bad_alloc &ba)
4732 {
4733 rc = VERR_NO_MEMORY;
4734 NOREF(ba);
4735 }
4736
4737 com::Shutdown();
4738
4739 LogFlowFuncLeaveRC(rc);
4740 return rc;
4741}
4742
4743
4744////////////////////////////////////////////////////////////////////////////////
4745
4746/**
4747 * Takes the current list of registered callbacks of the managed VirtualBox
4748 * instance, and calls #handleCallback() for every callback item from the
4749 * list, passing the item as an argument.
4750 *
4751 * @note Locks the managed VirtualBox object for reading but leaves the lock
4752 * before iterating over callbacks and calling their methods.
4753 */
4754void *VirtualBox::CallbackEvent::handler()
4755{
4756 if (!mVirtualBox)
4757 return NULL;
4758
4759 AutoCaller autoCaller(mVirtualBox);
4760 if (!autoCaller.isOk())
4761 {
4762 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4763 mVirtualBox->getObjectState().getState()));
4764 /* We don't need mVirtualBox any more, so release it */
4765 mVirtualBox = NULL;
4766 return NULL;
4767 }
4768
4769 {
4770 VBoxEventDesc evDesc;
4771 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4772
4773 evDesc.fire(/* don't wait for delivery */0);
4774 }
4775
4776 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4777 return NULL;
4778}
4779
4780//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4781//{
4782// return E_NOTIMPL;
4783//}
4784
4785HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
4786 ComPtr<IDHCPServer> &aServer)
4787{
4788 ComObjPtr<DHCPServer> dhcpServer;
4789 dhcpServer.createObject();
4790 HRESULT rc = dhcpServer->init(this, Bstr(aName).raw());
4791 if (FAILED(rc)) return rc;
4792
4793 rc = i_registerDHCPServer(dhcpServer, true);
4794 if (FAILED(rc)) return rc;
4795
4796 dhcpServer.queryInterfaceTo(aServer.asOutParam());
4797
4798 return rc;
4799}
4800
4801HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
4802 ComPtr<IDHCPServer> &aServer)
4803{
4804 HRESULT rc = S_OK;
4805 ComPtr<DHCPServer> found;
4806
4807 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4808
4809 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4810 it != m->allDHCPServers.end();
4811 ++it)
4812 {
4813 Bstr bstr;
4814 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4815 if (FAILED(rc)) return rc;
4816
4817 if (bstr == Bstr(aName).raw())
4818 {
4819 found = *it;
4820 break;
4821 }
4822 }
4823
4824 if (!found)
4825 return E_INVALIDARG;
4826
4827 rc = found.queryInterfaceTo(aServer.asOutParam());
4828
4829 return rc;
4830}
4831
4832HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
4833{
4834 IDHCPServer *aP = aServer;
4835
4836 HRESULT rc = i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
4837
4838 return rc;
4839}
4840
4841/**
4842 * Remembers the given DHCP server in the settings.
4843 *
4844 * @param aDHCPServer DHCP server object to remember.
4845 * @param aSaveSettings @c true to save settings to disk (default).
4846 *
4847 * When @a aSaveSettings is @c true, this operation may fail because of the
4848 * failed #saveSettings() method it calls. In this case, the dhcp server object
4849 * will not be remembered. It is therefore the responsibility of the caller to
4850 * call this method as the last step of some action that requires registration
4851 * in order to make sure that only fully functional dhcp server objects get
4852 * registered.
4853 *
4854 * @note Locks this object for writing and @a aDHCPServer for reading.
4855 */
4856HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
4857 bool aSaveSettings /*= true*/)
4858{
4859 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4860
4861 AutoCaller autoCaller(this);
4862 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4863
4864 // Acquire a lock on the VirtualBox object early to avoid lock order issues
4865 // when we call i_saveSettings() later on.
4866 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4867 // need it below, in findDHCPServerByNetworkName (reading) and in
4868 // m->allDHCPServers.addChild, so need to get it here to avoid lock
4869 // order trouble with dhcpServerCaller
4870 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4871
4872 AutoCaller dhcpServerCaller(aDHCPServer);
4873 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4874
4875 Bstr name;
4876 com::Utf8Str uname;
4877 HRESULT rc = S_OK;
4878 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
4879 if (FAILED(rc)) return rc;
4880 uname = Utf8Str(name);
4881
4882 ComPtr<IDHCPServer> existing;
4883 rc = findDHCPServerByNetworkName(uname, existing);
4884 if (SUCCEEDED(rc))
4885 return E_INVALIDARG;
4886 rc = S_OK;
4887
4888 m->allDHCPServers.addChild(aDHCPServer);
4889 // we need to release the list lock before we attempt to acquire locks
4890 // on other objects in i_saveSettings (see @bugref{7500})
4891 alock.release();
4892
4893 if (aSaveSettings)
4894 {
4895 // we acquired the lock on 'this' earlier to avoid lock order issues
4896 rc = i_saveSettings();
4897
4898 if (FAILED(rc))
4899 {
4900 alock.acquire();
4901 m->allDHCPServers.removeChild(aDHCPServer);
4902 }
4903 }
4904
4905 return rc;
4906}
4907
4908/**
4909 * Removes the given DHCP server from the settings.
4910 *
4911 * @param aDHCPServer DHCP server object to remove.
4912 *
4913 * This operation may fail because of the failed #saveSettings() method it
4914 * calls. In this case, the DHCP server will NOT be removed from the settings
4915 * when this method returns.
4916 *
4917 * @note Locks this object for writing.
4918 */
4919HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
4920{
4921 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4922
4923 AutoCaller autoCaller(this);
4924 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4925
4926 AutoCaller dhcpServerCaller(aDHCPServer);
4927 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4928
4929 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4930 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4931 m->allDHCPServers.removeChild(aDHCPServer);
4932 // we need to release the list lock before we attempt to acquire locks
4933 // on other objects in i_saveSettings (see @bugref{7500})
4934 alock.release();
4935
4936 HRESULT rc = i_saveSettings();
4937
4938 // undo the changes if we failed to save them
4939 if (FAILED(rc))
4940 {
4941 alock.acquire();
4942 m->allDHCPServers.addChild(aDHCPServer);
4943 }
4944
4945 return rc;
4946}
4947
4948
4949/**
4950 * NAT Network
4951 */
4952HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
4953 ComPtr<INATNetwork> &aNetwork)
4954{
4955#ifdef VBOX_WITH_NAT_SERVICE
4956 ComObjPtr<NATNetwork> natNetwork;
4957 natNetwork.createObject();
4958 HRESULT rc = natNetwork->init(this, Bstr(aNetworkName).raw());
4959 if (FAILED(rc)) return rc;
4960
4961 rc = i_registerNATNetwork(natNetwork, true);
4962 if (FAILED(rc)) return rc;
4963
4964 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
4965
4966 fireNATNetworkCreationDeletionEvent(m->pEventSource, Bstr(aNetworkName).raw(), TRUE);
4967
4968 return rc;
4969#else
4970 NOREF(aName);
4971 NOREF(aNatNetwork);
4972 return E_NOTIMPL;
4973#endif
4974}
4975
4976HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
4977 ComPtr<INATNetwork> &aNetwork)
4978{
4979#ifdef VBOX_WITH_NAT_SERVICE
4980
4981 HRESULT rc = S_OK;
4982 ComPtr<NATNetwork> found;
4983
4984 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4985
4986 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4987 it != m->allNATNetworks.end();
4988 ++it)
4989 {
4990 Bstr bstr;
4991 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4992 if (FAILED(rc)) return rc;
4993
4994 if (bstr == Bstr(aNetworkName).raw())
4995 {
4996 found = *it;
4997 break;
4998 }
4999 }
5000
5001 if (!found)
5002 return E_INVALIDARG;
5003 found.queryInterfaceTo(aNetwork.asOutParam());
5004 return rc;
5005#else
5006 NOREF(aName);
5007 NOREF(aNetworkName);
5008 return E_NOTIMPL;
5009#endif
5010}
5011
5012HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
5013{
5014#ifdef VBOX_WITH_NAT_SERVICE
5015 Bstr name;
5016 HRESULT rc = S_OK;
5017 INATNetwork *iNw = aNetwork;
5018 NATNetwork *network = static_cast<NATNetwork *>(iNw);
5019 rc = network->COMGETTER(NetworkName)(name.asOutParam());
5020 rc = i_unregisterNATNetwork(network, true);
5021 fireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
5022 return rc;
5023#else
5024 NOREF(aNetwork);
5025 return E_NOTIMPL;
5026#endif
5027
5028}
5029/**
5030 * Remembers the given NAT network in the settings.
5031 *
5032 * @param aNATNetwork NAT Network object to remember.
5033 * @param aSaveSettings @c true to save settings to disk (default).
5034 *
5035 *
5036 * @note Locks this object for writing and @a aNATNetwork for reading.
5037 */
5038HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
5039 bool aSaveSettings /*= true*/)
5040{
5041#ifdef VBOX_WITH_NAT_SERVICE
5042 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5043
5044 AutoCaller autoCaller(this);
5045 AssertComRCReturnRC(autoCaller.rc());
5046
5047 AutoCaller natNetworkCaller(aNATNetwork);
5048 AssertComRCReturnRC(natNetworkCaller.rc());
5049
5050 Bstr name;
5051 HRESULT rc;
5052 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5053 AssertComRCReturnRC(rc);
5054
5055 /* returned value isn't 0 and aSaveSettings is true
5056 * means that we create duplicate, otherwise we just load settings.
5057 */
5058 if ( sNatNetworkNameToRefCount[name]
5059 && aSaveSettings)
5060 AssertComRCReturnRC(E_INVALIDARG);
5061
5062 rc = S_OK;
5063
5064 sNatNetworkNameToRefCount[name] = 0;
5065
5066 m->allNATNetworks.addChild(aNATNetwork);
5067
5068 if (aSaveSettings)
5069 {
5070 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5071 rc = i_saveSettings();
5072 vboxLock.release();
5073
5074 if (FAILED(rc))
5075 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
5076 }
5077
5078 return rc;
5079#else
5080 NOREF(aNATNetwork);
5081 NOREF(aSaveSettings);
5082 /* No panic please (silently ignore) */
5083 return S_OK;
5084#endif
5085}
5086
5087/**
5088 * Removes the given NAT network from the settings.
5089 *
5090 * @param aNATNetwork NAT network object to remove.
5091 * @param aSaveSettings @c true to save settings to disk (default).
5092 *
5093 * When @a aSaveSettings is @c true, this operation may fail because of the
5094 * failed #saveSettings() method it calls. In this case, the DHCP server
5095 * will NOT be removed from the settingsi when this method returns.
5096 *
5097 * @note Locks this object for writing.
5098 */
5099HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
5100 bool aSaveSettings /*= true*/)
5101{
5102#ifdef VBOX_WITH_NAT_SERVICE
5103 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5104
5105 AutoCaller autoCaller(this);
5106 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5107
5108 AutoCaller natNetworkCaller(aNATNetwork);
5109 AssertComRCReturn(natNetworkCaller.rc(), natNetworkCaller.rc());
5110
5111 Bstr name;
5112 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5113 /* Hm, there're still running clients. */
5114 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
5115 AssertComRCReturnRC(E_INVALIDARG);
5116
5117 m->allNATNetworks.removeChild(aNATNetwork);
5118
5119 if (aSaveSettings)
5120 {
5121 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5122 rc = i_saveSettings();
5123 vboxLock.release();
5124
5125 if (FAILED(rc))
5126 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
5127 }
5128
5129 return rc;
5130#else
5131 NOREF(aNATNetwork);
5132 NOREF(aSaveSettings);
5133 return E_NOTIMPL;
5134#endif
5135}
5136/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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