VirtualBox

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

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

Main/VirtualBox+Medium+Snapshot: fix lock inconsistency which crept into the previous fixes

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