VirtualBox

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

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

Main/Snapshot: only update the machine state on the VM process if there is one,
and introduce a new event when a snapshot has been restored instead of abusing t
he one for deleting a snapshot.

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