VirtualBox

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

Last change on this file since 52004 was 51903, checked in by vboxsync, 11 years ago

Main: AutoCaller/VirtualBoxBase refactoring, cleanly splitting out the object state handling, and moving all caller synchronization to one file. Also eliminated a not so vital template (AutoCallerBase) by much simpler inheritance. Theoretically has no visible effects, the behavior should be identical. Done as a preparation for reimplementing the caller synchronization.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 161.4 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 51903 2014-07-07 13:03:49Z 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);
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);
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);
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);
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 this object for reading.
2951 */
2952ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
2953{
2954 ComObjPtr<GuestOSType> type;
2955 AutoCaller autoCaller(this);
2956 AssertComRCReturn(autoCaller.rc(), type);
2957
2958 /* unknown type must always be the first */
2959 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
2960
2961 return m->allGuestOSTypes.front();
2962}
2963
2964/**
2965 * Returns the list of opened machines (machines having direct sessions opened
2966 * by client processes) and optionally the list of direct session controls.
2967 *
2968 * @param aMachines Where to put opened machines (will be empty if none).
2969 * @param aControls Where to put direct session controls (optional).
2970 *
2971 * @note The returned lists contain smart pointers. So, clear it as soon as
2972 * it becomes no more necessary to release instances.
2973 *
2974 * @note It can be possible that a session machine from the list has been
2975 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
2976 * when accessing unprotected data directly.
2977 *
2978 * @note Locks objects for reading.
2979 */
2980void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
2981 InternalControlList *aControls /*= NULL*/)
2982{
2983 AutoCaller autoCaller(this);
2984 AssertComRCReturnVoid(autoCaller.rc());
2985
2986 aMachines.clear();
2987 if (aControls)
2988 aControls->clear();
2989
2990 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2991
2992 for (MachinesOList::iterator it = m->allMachines.begin();
2993 it != m->allMachines.end();
2994 ++it)
2995 {
2996 ComObjPtr<SessionMachine> sm;
2997 ComPtr<IInternalSessionControl> ctl;
2998 if ((*it)->i_isSessionOpen(sm, &ctl))
2999 {
3000 aMachines.push_back(sm);
3001 if (aControls)
3002 aControls->push_back(ctl);
3003 }
3004 }
3005}
3006
3007/**
3008 * Gets a reference to the machine list. This is the real thing, not a copy,
3009 * so bad things will happen if the caller doesn't hold the necessary lock.
3010 *
3011 * @returns reference to machine list
3012 *
3013 * @note Caller must hold the VirtualBox object lock at least for reading.
3014 */
3015VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
3016{
3017 return m->allMachines;
3018}
3019
3020/**
3021 * Searches for a machine object with the given ID in the collection
3022 * of registered machines.
3023 *
3024 * @param aId Machine UUID to look for.
3025 * @param aPermitInaccessible If true, inaccessible machines will be found;
3026 * if false, this will fail if the given machine is inaccessible.
3027 * @param aSetError If true, set errorinfo if the machine is not found.
3028 * @param aMachine Returned machine, if found.
3029 * @return
3030 */
3031HRESULT VirtualBox::i_findMachine(const Guid &aId,
3032 bool fPermitInaccessible,
3033 bool aSetError,
3034 ComObjPtr<Machine> *aMachine /* = NULL */)
3035{
3036 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3037
3038 AutoCaller autoCaller(this);
3039 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3040
3041 {
3042 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3043
3044 for (MachinesOList::iterator it = m->allMachines.begin();
3045 it != m->allMachines.end();
3046 ++it)
3047 {
3048 ComObjPtr<Machine> pMachine = *it;
3049
3050 if (!fPermitInaccessible)
3051 {
3052 // skip inaccessible machines
3053 AutoCaller machCaller(pMachine);
3054 if (FAILED(machCaller.rc()))
3055 continue;
3056 }
3057
3058 if (pMachine->i_getId() == aId)
3059 {
3060 rc = S_OK;
3061 if (aMachine)
3062 *aMachine = pMachine;
3063 break;
3064 }
3065 }
3066 }
3067
3068 if (aSetError && FAILED(rc))
3069 rc = setError(rc,
3070 tr("Could not find a registered machine with UUID {%RTuuid}"),
3071 aId.raw());
3072
3073 return rc;
3074}
3075
3076/**
3077 * Searches for a machine object with the given name or location in the
3078 * collection of registered machines.
3079 *
3080 * @param aName Machine name or location to look for.
3081 * @param aSetError If true, set errorinfo if the machine is not found.
3082 * @param aMachine Returned machine, if found.
3083 * @return
3084 */
3085HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
3086 bool aSetError,
3087 ComObjPtr<Machine> *aMachine /* = NULL */)
3088{
3089 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3090
3091 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3092 for (MachinesOList::iterator it = m->allMachines.begin();
3093 it != m->allMachines.end();
3094 ++it)
3095 {
3096 ComObjPtr<Machine> &pMachine = *it;
3097 AutoCaller machCaller(pMachine);
3098 if (machCaller.rc())
3099 continue; // we can't ask inaccessible machines for their names
3100
3101 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
3102 if (pMachine->i_getName() == aName)
3103 {
3104 rc = S_OK;
3105 if (aMachine)
3106 *aMachine = pMachine;
3107 break;
3108 }
3109 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
3110 {
3111 rc = S_OK;
3112 if (aMachine)
3113 *aMachine = pMachine;
3114 break;
3115 }
3116 }
3117
3118 if (aSetError && FAILED(rc))
3119 rc = setError(rc,
3120 tr("Could not find a registered machine named '%s'"), aName.c_str());
3121
3122 return rc;
3123}
3124
3125static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
3126{
3127 /* empty strings are invalid */
3128 if (aGroup.isEmpty())
3129 return E_INVALIDARG;
3130 /* the toplevel group is valid */
3131 if (aGroup == "/")
3132 return S_OK;
3133 /* any other strings of length 1 are invalid */
3134 if (aGroup.length() == 1)
3135 return E_INVALIDARG;
3136 /* must start with a slash */
3137 if (aGroup.c_str()[0] != '/')
3138 return E_INVALIDARG;
3139 /* must not end with a slash */
3140 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3141 return E_INVALIDARG;
3142 /* check the group components */
3143 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3144 while (pStr)
3145 {
3146 char *pSlash = RTStrStr(pStr, "/");
3147 if (pSlash)
3148 {
3149 /* no empty components (or // sequences in other words) */
3150 if (pSlash == pStr)
3151 return E_INVALIDARG;
3152 /* check if the machine name rules are violated, because that means
3153 * the group components are too close to the limits. */
3154 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3155 Utf8Str tmp2(tmp);
3156 sanitiseMachineFilename(tmp);
3157 if (tmp != tmp2)
3158 return E_INVALIDARG;
3159 if (fPrimary)
3160 {
3161 HRESULT rc = pVirtualBox->i_findMachineByName(tmp,
3162 false /* aSetError */);
3163 if (SUCCEEDED(rc))
3164 return VBOX_E_VM_ERROR;
3165 }
3166 pStr = pSlash + 1;
3167 }
3168 else
3169 {
3170 /* check if the machine name rules are violated, because that means
3171 * the group components is too close to the limits. */
3172 Utf8Str tmp(pStr);
3173 Utf8Str tmp2(tmp);
3174 sanitiseMachineFilename(tmp);
3175 if (tmp != tmp2)
3176 return E_INVALIDARG;
3177 pStr = NULL;
3178 }
3179 }
3180 return S_OK;
3181}
3182
3183/**
3184 * Validates a machine group.
3185 *
3186 * @param aMachineGroup Machine group.
3187 * @param fPrimary Set if this is the primary group.
3188 *
3189 * @return S_OK or E_INVALIDARG
3190 */
3191HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
3192{
3193 HRESULT rc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
3194 if (FAILED(rc))
3195 {
3196 if (rc == VBOX_E_VM_ERROR)
3197 rc = setError(E_INVALIDARG,
3198 tr("Machine group '%s' conflicts with a virtual machine name"),
3199 aGroup.c_str());
3200 else
3201 rc = setError(rc,
3202 tr("Invalid machine group '%s'"),
3203 aGroup.c_str());
3204 }
3205 return rc;
3206}
3207
3208/**
3209 * Takes a list of machine groups, and sanitizes/validates it.
3210 *
3211 * @param aMachineGroups Safearray with the machine groups.
3212 * @param pllMachineGroups Pointer to list of strings for the result.
3213 *
3214 * @return S_OK or E_INVALIDARG
3215 */
3216HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
3217{
3218 pllMachineGroups->clear();
3219 if (aMachineGroups.size())
3220 {
3221 for (size_t i = 0; i < aMachineGroups.size(); i++)
3222 {
3223 Utf8Str group(aMachineGroups[i]);
3224 if (group.length() == 0)
3225 group = "/";
3226
3227 HRESULT rc = i_validateMachineGroup(group, i == 0);
3228 if (FAILED(rc))
3229 return rc;
3230
3231 /* no duplicates please */
3232 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3233 == pllMachineGroups->end())
3234 pllMachineGroups->push_back(group);
3235 }
3236 if (pllMachineGroups->size() == 0)
3237 pllMachineGroups->push_back("/");
3238 }
3239 else
3240 pllMachineGroups->push_back("/");
3241
3242 return S_OK;
3243}
3244
3245/**
3246 * Searches for a Medium object with the given ID in the list of registered
3247 * hard disks.
3248 *
3249 * @param aId ID of the hard disk. Must not be empty.
3250 * @param aSetError If @c true , the appropriate error info is set in case
3251 * when the hard disk is not found.
3252 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3253 *
3254 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3255 *
3256 * @note Locks the media tree for reading.
3257 */
3258HRESULT VirtualBox::i_findHardDiskById(const Guid &id,
3259 bool aSetError,
3260 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3261{
3262 AssertReturn(!id.isZero(), E_INVALIDARG);
3263
3264 // we use the hard disks map, but it is protected by the
3265 // hard disk _list_ lock handle
3266 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3267
3268 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
3269 if (it != m->mapHardDisks.end())
3270 {
3271 if (aHardDisk)
3272 *aHardDisk = (*it).second;
3273 return S_OK;
3274 }
3275
3276 if (aSetError)
3277 return setError(VBOX_E_OBJECT_NOT_FOUND,
3278 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3279 id.raw());
3280
3281 return VBOX_E_OBJECT_NOT_FOUND;
3282}
3283
3284/**
3285 * Searches for a Medium object with the given ID or location in the list of
3286 * registered hard disks. If both ID and location are specified, the first
3287 * object that matches either of them (not necessarily both) is returned.
3288 *
3289 * @param aLocation Full location specification. Must not be empty.
3290 * @param aSetError If @c true , the appropriate error info is set in case
3291 * when the hard disk is not found.
3292 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3293 *
3294 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3295 *
3296 * @note Locks the media tree for reading.
3297 */
3298HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
3299 bool aSetError,
3300 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3301{
3302 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3303
3304 // we use the hard disks map, but it is protected by the
3305 // hard disk _list_ lock handle
3306 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3307
3308 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3309 it != m->mapHardDisks.end();
3310 ++it)
3311 {
3312 const ComObjPtr<Medium> &pHD = (*it).second;
3313
3314 AutoCaller autoCaller(pHD);
3315 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3316 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3317
3318 Utf8Str strLocationFull = pHD->i_getLocationFull();
3319
3320 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3321 {
3322 if (aHardDisk)
3323 *aHardDisk = pHD;
3324 return S_OK;
3325 }
3326 }
3327
3328 if (aSetError)
3329 return setError(VBOX_E_OBJECT_NOT_FOUND,
3330 tr("Could not find an open hard disk with location '%s'"),
3331 strLocation.c_str());
3332
3333 return VBOX_E_OBJECT_NOT_FOUND;
3334}
3335
3336/**
3337 * Searches for a Medium object with the given ID or location in the list of
3338 * registered DVD or floppy images, depending on the @a mediumType argument.
3339 * If both ID and file path are specified, the first object that matches either
3340 * of them (not necessarily both) is returned.
3341 *
3342 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3343 * @param aId ID of the image file (unused when NULL).
3344 * @param aLocation Full path to the image file (unused when NULL).
3345 * @param aSetError If @c true, the appropriate error info is set in case when
3346 * the image is not found.
3347 * @param aImage Where to store the found image object (can be NULL).
3348 *
3349 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3350 *
3351 * @note Locks the media tree for reading.
3352 */
3353HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
3354 const Guid *aId,
3355 const Utf8Str &aLocation,
3356 bool aSetError,
3357 ComObjPtr<Medium> *aImage /* = NULL */)
3358{
3359 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3360
3361 Utf8Str location;
3362 if (!aLocation.isEmpty())
3363 {
3364 int vrc = i_calculateFullPath(aLocation, location);
3365 if (RT_FAILURE(vrc))
3366 return setError(VBOX_E_FILE_ERROR,
3367 tr("Invalid image file location '%s' (%Rrc)"),
3368 aLocation.c_str(),
3369 vrc);
3370 }
3371
3372 MediaOList *pMediaList;
3373
3374 switch (mediumType)
3375 {
3376 case DeviceType_DVD:
3377 pMediaList = &m->allDVDImages;
3378 break;
3379
3380 case DeviceType_Floppy:
3381 pMediaList = &m->allFloppyImages;
3382 break;
3383
3384 default:
3385 return E_INVALIDARG;
3386 }
3387
3388 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3389
3390 bool found = false;
3391
3392 for (MediaList::const_iterator it = pMediaList->begin();
3393 it != pMediaList->end();
3394 ++it)
3395 {
3396 // no AutoCaller, registered image life time is bound to this
3397 Medium *pMedium = *it;
3398 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3399 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
3400
3401 found = ( aId
3402 && pMedium->i_getId() == *aId)
3403 || ( !aLocation.isEmpty()
3404 && RTPathCompare(location.c_str(),
3405 strLocationFull.c_str()) == 0);
3406 if (found)
3407 {
3408 if (pMedium->i_getDeviceType() != mediumType)
3409 {
3410 if (mediumType == DeviceType_DVD)
3411 return setError(E_INVALIDARG,
3412 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3413 else
3414 return setError(E_INVALIDARG,
3415 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3416 }
3417
3418 if (aImage)
3419 *aImage = pMedium;
3420 break;
3421 }
3422 }
3423
3424 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3425
3426 if (aSetError && !found)
3427 {
3428 if (aId)
3429 setError(rc,
3430 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3431 aId->raw(),
3432 m->strSettingsFilePath.c_str());
3433 else
3434 setError(rc,
3435 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3436 aLocation.c_str(),
3437 m->strSettingsFilePath.c_str());
3438 }
3439
3440 return rc;
3441}
3442
3443/**
3444 * Searches for an IMedium object that represents the given UUID.
3445 *
3446 * If the UUID is empty (indicating an empty drive), this sets pMedium
3447 * to NULL and returns S_OK.
3448 *
3449 * If the UUID refers to a host drive of the given device type, this
3450 * sets pMedium to the object from the list in IHost and returns S_OK.
3451 *
3452 * If the UUID is an image file, this sets pMedium to the object that
3453 * findDVDOrFloppyImage() returned.
3454 *
3455 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3456 *
3457 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3458 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3459 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3460 * @param pMedium out: IMedium object found.
3461 * @return
3462 */
3463HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
3464 const Guid &uuid,
3465 bool fRefresh,
3466 bool aSetError,
3467 ComObjPtr<Medium> &pMedium)
3468{
3469 if (uuid.isZero())
3470 {
3471 // that's easy
3472 pMedium.setNull();
3473 return S_OK;
3474 }
3475 else if (!uuid.isValid())
3476 {
3477 /* handling of case invalid GUID */
3478 return setError(VBOX_E_OBJECT_NOT_FOUND,
3479 tr("Guid '%s' is invalid"),
3480 uuid.toString().c_str());
3481 }
3482
3483 // first search for host drive with that UUID
3484 HRESULT rc = m->pHost->i_findHostDriveById(mediumType,
3485 uuid,
3486 fRefresh,
3487 pMedium);
3488 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3489 // then search for an image with that UUID
3490 rc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3491
3492 return rc;
3493}
3494
3495HRESULT VirtualBox::i_findGuestOSType(const Bstr &bstrOSType,
3496 GuestOSType*& pGuestOSType)
3497{
3498 /* Look for a GuestOSType object */
3499 AssertMsg(m->allGuestOSTypes.size() != 0,
3500 ("Guest OS types array must be filled"));
3501
3502 if (bstrOSType.isEmpty())
3503 {
3504 pGuestOSType = NULL;
3505 return S_OK;
3506 }
3507
3508 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3509 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3510 it != m->allGuestOSTypes.end();
3511 ++it)
3512 {
3513 if ((*it)->i_id() == bstrOSType)
3514 {
3515 pGuestOSType = *it;
3516 return S_OK;
3517 }
3518 }
3519
3520 return setError(VBOX_E_OBJECT_NOT_FOUND,
3521 tr("Guest OS type '%ls' is invalid"),
3522 bstrOSType.raw());
3523}
3524
3525/**
3526 * Returns the constant pseudo-machine UUID that is used to identify the
3527 * global media registry.
3528 *
3529 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3530 * in which media registry it is saved (if any): this can either be a machine
3531 * UUID, if it's in a per-machine media registry, or this global ID.
3532 *
3533 * This UUID is only used to identify the VirtualBox object while VirtualBox
3534 * is running. It is a compile-time constant and not saved anywhere.
3535 *
3536 * @return
3537 */
3538const Guid& VirtualBox::i_getGlobalRegistryId() const
3539{
3540 return m->uuidMediaRegistry;
3541}
3542
3543const ComObjPtr<Host>& VirtualBox::i_host() const
3544{
3545 return m->pHost;
3546}
3547
3548SystemProperties* VirtualBox::i_getSystemProperties() const
3549{
3550 return m->pSystemProperties;
3551}
3552
3553#ifdef VBOX_WITH_EXTPACK
3554/**
3555 * Getter that SystemProperties and others can use to talk to the extension
3556 * pack manager.
3557 */
3558ExtPackManager* VirtualBox::i_getExtPackManager() const
3559{
3560 return m->ptrExtPackManager;
3561}
3562#endif
3563
3564/**
3565 * Getter that machines can talk to the autostart database.
3566 */
3567AutostartDb* VirtualBox::i_getAutostartDb() const
3568{
3569 return m->pAutostartDb;
3570}
3571
3572#ifdef VBOX_WITH_RESOURCE_USAGE_API
3573const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
3574{
3575 return m->pPerformanceCollector;
3576}
3577#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3578
3579/**
3580 * Returns the default machine folder from the system properties
3581 * with proper locking.
3582 * @return
3583 */
3584void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
3585{
3586 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3587 str = m->pSystemProperties->m->strDefaultMachineFolder;
3588}
3589
3590/**
3591 * Returns the default hard disk format from the system properties
3592 * with proper locking.
3593 * @return
3594 */
3595void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
3596{
3597 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3598 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3599}
3600
3601const Utf8Str& VirtualBox::i_homeDir() const
3602{
3603 return m->strHomeDir;
3604}
3605
3606/**
3607 * Calculates the absolute path of the given path taking the VirtualBox home
3608 * directory as the current directory.
3609 *
3610 * @param aPath Path to calculate the absolute path for.
3611 * @param aResult Where to put the result (used only on success, can be the
3612 * same Utf8Str instance as passed in @a aPath).
3613 * @return IPRT result.
3614 *
3615 * @note Doesn't lock any object.
3616 */
3617int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3618{
3619 AutoCaller autoCaller(this);
3620 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3621
3622 /* no need to lock since mHomeDir is const */
3623
3624 char folder[RTPATH_MAX];
3625 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3626 strPath.c_str(),
3627 folder,
3628 sizeof(folder));
3629 if (RT_SUCCESS(vrc))
3630 aResult = folder;
3631
3632 return vrc;
3633}
3634
3635/**
3636 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3637 * if it is a subdirectory thereof, or simply copying it otherwise.
3638 *
3639 * @param strSource Path to evalue and copy.
3640 * @param strTarget Buffer to receive target path.
3641 */
3642void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
3643 Utf8Str &strTarget)
3644{
3645 AutoCaller autoCaller(this);
3646 AssertComRCReturnVoid(autoCaller.rc());
3647
3648 // no need to lock since mHomeDir is const
3649
3650 // use strTarget as a temporary buffer to hold the machine settings dir
3651 strTarget = m->strHomeDir;
3652 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3653 // is relative: then append what's left
3654 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3655 else
3656 // is not relative: then overwrite
3657 strTarget = strSource;
3658}
3659
3660// private methods
3661/////////////////////////////////////////////////////////////////////////////
3662
3663/**
3664 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3665 * location already registered.
3666 *
3667 * On return, sets @a aConflict to the string describing the conflicting medium,
3668 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3669 * either case. A failure is unexpected.
3670 *
3671 * @param aId UUID to check.
3672 * @param aLocation Location to check.
3673 * @param aConflict Where to return parameters of the conflicting medium.
3674 * @param ppMedium Medium reference in case this is simply a duplicate.
3675 *
3676 * @note Locks the media tree and media objects for reading.
3677 */
3678HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
3679 const Utf8Str &aLocation,
3680 Utf8Str &aConflict,
3681 ComObjPtr<Medium> *ppMedium)
3682{
3683 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
3684 AssertReturn(ppMedium, E_INVALIDARG);
3685
3686 aConflict.setNull();
3687 ppMedium->setNull();
3688
3689 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3690
3691 HRESULT rc = S_OK;
3692
3693 ComObjPtr<Medium> pMediumFound;
3694 const char *pcszType = NULL;
3695
3696 if (aId.isValid() && !aId.isZero())
3697 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3698 if (FAILED(rc) && !aLocation.isEmpty())
3699 rc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3700 if (SUCCEEDED(rc))
3701 pcszType = tr("hard disk");
3702
3703 if (!pcszType)
3704 {
3705 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3706 if (SUCCEEDED(rc))
3707 pcszType = tr("CD/DVD image");
3708 }
3709
3710 if (!pcszType)
3711 {
3712 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3713 if (SUCCEEDED(rc))
3714 pcszType = tr("floppy image");
3715 }
3716
3717 if (pcszType && pMediumFound)
3718 {
3719 /* Note: no AutoCaller since bound to this */
3720 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3721
3722 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
3723 Guid idFound = pMediumFound->i_getId();
3724
3725 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3726 && (idFound == aId)
3727 )
3728 *ppMedium = pMediumFound;
3729
3730 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3731 pcszType,
3732 strLocFound.c_str(),
3733 idFound.raw());
3734 }
3735
3736 return S_OK;
3737}
3738
3739/**
3740 * Checks whether the given UUID is already in use by one medium for the
3741 * given device type.
3742 *
3743 * @returns true if the UUID is already in use
3744 * fale otherwise
3745 * @param aId The UUID to check.
3746 * @param deviceType The device type the UUID is going to be checked for
3747 * conflicts.
3748 */
3749bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
3750{
3751 /* A zero UUID is invalid here, always claim that it is already used. */
3752 AssertReturn(!aId.isZero(), true);
3753
3754 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3755
3756 HRESULT rc = S_OK;
3757 bool fInUse = false;
3758
3759 ComObjPtr<Medium> pMediumFound;
3760
3761 switch (deviceType)
3762 {
3763 case DeviceType_HardDisk:
3764 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3765 break;
3766 case DeviceType_DVD:
3767 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3768 break;
3769 case DeviceType_Floppy:
3770 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3771 break;
3772 default:
3773 AssertMsgFailed(("Invalid device type %d\n", deviceType));
3774 }
3775
3776 if (SUCCEEDED(rc) && pMediumFound)
3777 fInUse = true;
3778
3779 return fInUse;
3780}
3781
3782/**
3783 * Called from Machine::prepareSaveSettings() when it has detected
3784 * that a machine has been renamed. Such renames will require
3785 * updating the global media registry during the
3786 * VirtualBox::saveSettings() that follows later.
3787*
3788 * When a machine is renamed, there may well be media (in particular,
3789 * diff images for snapshots) in the global registry that will need
3790 * to have their paths updated. Before 3.2, Machine::saveSettings
3791 * used to call VirtualBox::saveSettings implicitly, which was both
3792 * unintuitive and caused locking order problems. Now, we remember
3793 * such pending name changes with this method so that
3794 * VirtualBox::saveSettings() can process them properly.
3795 */
3796void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3797 const Utf8Str &strNewConfigDir)
3798{
3799 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3800
3801 Data::PendingMachineRename pmr;
3802 pmr.strConfigDirOld = strOldConfigDir;
3803 pmr.strConfigDirNew = strNewConfigDir;
3804 m->llPendingMachineRenames.push_back(pmr);
3805}
3806
3807struct SaveMediaRegistriesDesc
3808{
3809 MediaList llMedia;
3810 ComObjPtr<VirtualBox> pVirtualBox;
3811};
3812
3813static int fntSaveMediaRegistries(RTTHREAD ThreadSelf, void *pvUser)
3814{
3815 NOREF(ThreadSelf);
3816 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
3817 if (!pDesc)
3818 {
3819 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
3820 return VERR_INVALID_PARAMETER;
3821 }
3822
3823 for (MediaList::const_iterator it = pDesc->llMedia.begin();
3824 it != pDesc->llMedia.end();
3825 ++it)
3826 {
3827 Medium *pMedium = *it;
3828 pMedium->i_markRegistriesModified();
3829 }
3830
3831 pDesc->pVirtualBox->i_saveModifiedRegistries();
3832
3833 pDesc->llMedia.clear();
3834 pDesc->pVirtualBox.setNull();
3835 delete pDesc;
3836
3837 return VINF_SUCCESS;
3838}
3839
3840/**
3841 * Goes through all known media (hard disks, floppies and DVDs) and saves
3842 * those into the given settings::MediaRegistry structures whose registry
3843 * ID match the given UUID.
3844 *
3845 * Before actually writing to the structures, all media paths (not just the
3846 * ones for the given registry) are updated if machines have been renamed
3847 * since the last call.
3848 *
3849 * This gets called from two contexts:
3850 *
3851 * -- VirtualBox::saveSettings() with the UUID of the global registry
3852 * (VirtualBox::Data.uuidRegistry); this will save those media
3853 * which had been loaded from the global registry or have been
3854 * attached to a "legacy" machine which can't save its own registry;
3855 *
3856 * -- Machine::saveSettings() with the UUID of a machine, if a medium
3857 * has been attached to a machine created with VirtualBox 4.0 or later.
3858 *
3859 * Media which have only been temporarily opened without having been
3860 * attached to a machine have a NULL registry UUID and therefore don't
3861 * get saved.
3862 *
3863 * This locks the media tree. Throws HRESULT on errors!
3864 *
3865 * @param mediaRegistry Settings structure to fill.
3866 * @param uuidRegistry The UUID of the media registry; either a machine UUID
3867 * (if machine registry) or the UUID of the global registry.
3868 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
3869 */
3870void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
3871 const Guid &uuidRegistry,
3872 const Utf8Str &strMachineFolder)
3873{
3874 // lock all media for the following; use a write lock because we're
3875 // modifying the PendingMachineRenamesList, which is protected by this
3876 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3877
3878 // if a machine was renamed, then we'll need to refresh media paths
3879 if (m->llPendingMachineRenames.size())
3880 {
3881 // make a single list from the three media lists so we don't need three loops
3882 MediaList llAllMedia;
3883 // with hard disks, we must use the map, not the list, because the list only has base images
3884 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
3885 llAllMedia.push_back(it->second);
3886 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
3887 llAllMedia.push_back(*it);
3888 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
3889 llAllMedia.push_back(*it);
3890
3891 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
3892 for (MediaList::iterator it = llAllMedia.begin();
3893 it != llAllMedia.end();
3894 ++it)
3895 {
3896 Medium *pMedium = *it;
3897 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
3898 it2 != m->llPendingMachineRenames.end();
3899 ++it2)
3900 {
3901 const Data::PendingMachineRename &pmr = *it2;
3902 HRESULT rc = pMedium->i_updatePath(pmr.strConfigDirOld,
3903 pmr.strConfigDirNew);
3904 if (SUCCEEDED(rc))
3905 {
3906 // Remember which medium objects has been changed,
3907 // to trigger saving their registries later.
3908 pDesc->llMedia.push_back(pMedium);
3909 } else if (rc == VBOX_E_FILE_ERROR)
3910 /* nothing */;
3911 else
3912 AssertComRC(rc);
3913 }
3914 }
3915 // done, don't do it again until we have more machine renames
3916 m->llPendingMachineRenames.clear();
3917
3918 if (pDesc->llMedia.size())
3919 {
3920 // Handle the media registry saving in a separate thread, to
3921 // avoid giant locking problems and passing up the list many
3922 // levels up to whoever triggered saveSettings, as there are
3923 // lots of places which would need to handle saving more settings.
3924 pDesc->pVirtualBox = this;
3925 int vrc = RTThreadCreate(NULL,
3926 fntSaveMediaRegistries,
3927 (void *)pDesc,
3928 0, // cbStack (default)
3929 RTTHREADTYPE_MAIN_WORKER,
3930 0, // flags
3931 "SaveMediaReg");
3932 ComAssertRC(vrc);
3933 // failure means that settings aren't saved, but there isn't
3934 // much we can do besides avoiding memory leaks
3935 if (RT_FAILURE(vrc))
3936 {
3937 LogRelFunc(("Failed to create thread for saving media registries (%Rrc)\n", vrc));
3938 delete pDesc;
3939 }
3940 }
3941 else
3942 delete pDesc;
3943 }
3944
3945 struct {
3946 MediaOList &llSource;
3947 settings::MediaList &llTarget;
3948 } s[] =
3949 {
3950 // hard disks
3951 { m->allHardDisks, mediaRegistry.llHardDisks },
3952 // CD/DVD images
3953 { m->allDVDImages, mediaRegistry.llDvdImages },
3954 // floppy images
3955 { m->allFloppyImages, mediaRegistry.llFloppyImages }
3956 };
3957
3958 HRESULT rc;
3959
3960 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
3961 {
3962 MediaOList &llSource = s[i].llSource;
3963 settings::MediaList &llTarget = s[i].llTarget;
3964 llTarget.clear();
3965 for (MediaList::const_iterator it = llSource.begin();
3966 it != llSource.end();
3967 ++it)
3968 {
3969 Medium *pMedium = *it;
3970 AutoCaller autoCaller(pMedium);
3971 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
3972 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
3973
3974 if (pMedium->i_isInRegistry(uuidRegistry))
3975 {
3976 settings::Medium med;
3977 rc = pMedium->i_saveSettings(med, strMachineFolder); // this recurses into child hard disks
3978 if (FAILED(rc)) throw rc;
3979 llTarget.push_back(med);
3980 }
3981 }
3982 }
3983}
3984
3985/**
3986 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
3987 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
3988 * places internally when settings need saving.
3989 *
3990 * @note Caller must have locked the VirtualBox object for writing and must not hold any
3991 * other locks since this locks all kinds of member objects and trees temporarily,
3992 * which could cause conflicts.
3993 */
3994HRESULT VirtualBox::i_saveSettings()
3995{
3996 AutoCaller autoCaller(this);
3997 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3998
3999 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
4000 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
4001
4002 HRESULT rc = S_OK;
4003
4004 try
4005 {
4006 // machines
4007 m->pMainConfigFile->llMachines.clear();
4008 {
4009 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4010 for (MachinesOList::iterator it = m->allMachines.begin();
4011 it != m->allMachines.end();
4012 ++it)
4013 {
4014 Machine *pMachine = *it;
4015 // save actual machine registry entry
4016 settings::MachineRegistryEntry mre;
4017 rc = pMachine->i_saveRegistryEntry(mre);
4018 m->pMainConfigFile->llMachines.push_back(mre);
4019 }
4020 }
4021
4022 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
4023 m->uuidMediaRegistry, // global media registry ID
4024 Utf8Str::Empty); // strMachineFolder
4025
4026 m->pMainConfigFile->llDhcpServers.clear();
4027 {
4028 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4029 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4030 it != m->allDHCPServers.end();
4031 ++it)
4032 {
4033 settings::DHCPServer d;
4034 rc = (*it)->i_saveSettings(d);
4035 if (FAILED(rc)) throw rc;
4036 m->pMainConfigFile->llDhcpServers.push_back(d);
4037 }
4038 }
4039
4040#ifdef VBOX_WITH_NAT_SERVICE
4041 /* Saving NAT Network configuration */
4042 m->pMainConfigFile->llNATNetworks.clear();
4043 {
4044 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4045 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4046 it != m->allNATNetworks.end();
4047 ++it)
4048 {
4049 settings::NATNetwork n;
4050 rc = (*it)->i_saveSettings(n);
4051 if (FAILED(rc)) throw rc;
4052 m->pMainConfigFile->llNATNetworks.push_back(n);
4053 }
4054 }
4055#endif
4056
4057 // leave extra data alone, it's still in the config file
4058
4059 // host data (USB filters)
4060 rc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
4061 if (FAILED(rc)) throw rc;
4062
4063 rc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
4064 if (FAILED(rc)) throw rc;
4065
4066 // and write out the XML, still under the lock
4067 m->pMainConfigFile->write(m->strSettingsFilePath);
4068 }
4069 catch (HRESULT err)
4070 {
4071 /* we assume that error info is set by the thrower */
4072 rc = err;
4073 }
4074 catch (...)
4075 {
4076 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
4077 }
4078
4079 return rc;
4080}
4081
4082/**
4083 * Helper to register the machine.
4084 *
4085 * When called during VirtualBox startup, adds the given machine to the
4086 * collection of registered machines. Otherwise tries to mark the machine
4087 * as registered, and, if succeeded, adds it to the collection and
4088 * saves global settings.
4089 *
4090 * @note The caller must have added itself as a caller of the @a aMachine
4091 * object if calls this method not on VirtualBox startup.
4092 *
4093 * @param aMachine machine to register
4094 *
4095 * @note Locks objects!
4096 */
4097HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
4098{
4099 ComAssertRet(aMachine, E_INVALIDARG);
4100
4101 AutoCaller autoCaller(this);
4102 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4103
4104 HRESULT rc = S_OK;
4105
4106 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4107
4108 {
4109 ComObjPtr<Machine> pMachine;
4110 rc = i_findMachine(aMachine->i_getId(),
4111 true /* fPermitInaccessible */,
4112 false /* aDoSetError */,
4113 &pMachine);
4114 if (SUCCEEDED(rc))
4115 {
4116 /* sanity */
4117 AutoLimitedCaller machCaller(pMachine);
4118 AssertComRC(machCaller.rc());
4119
4120 return setError(E_INVALIDARG,
4121 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
4122 aMachine->i_getId().raw(),
4123 pMachine->i_getSettingsFileFull().c_str());
4124 }
4125
4126 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
4127 rc = S_OK;
4128 }
4129
4130 if (getObjectState().getState() != ObjectState::InInit)
4131 {
4132 rc = aMachine->i_prepareRegister();
4133 if (FAILED(rc)) return rc;
4134 }
4135
4136 /* add to the collection of registered machines */
4137 m->allMachines.addChild(aMachine);
4138
4139 if (getObjectState().getState() != ObjectState::InInit)
4140 rc = i_saveSettings();
4141
4142 return rc;
4143}
4144
4145/**
4146 * Remembers the given medium object by storing it in either the global
4147 * medium registry or a machine one.
4148 *
4149 * @note Caller must hold the media tree lock for writing; in addition, this
4150 * locks @a pMedium for reading
4151 *
4152 * @param pMedium Medium object to remember.
4153 * @param ppMedium Actually stored medium object. Can be different if due
4154 * to an unavoidable race there was a duplicate Medium object
4155 * created.
4156 * @param argType Either DeviceType_HardDisk, DeviceType_DVD or DeviceType_Floppy.
4157 * @return
4158 */
4159HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
4160 ComObjPtr<Medium> *ppMedium,
4161 DeviceType_T argType)
4162{
4163 AssertReturn(pMedium != NULL, E_INVALIDARG);
4164 AssertReturn(ppMedium != NULL, E_INVALIDARG);
4165
4166 AutoCaller autoCaller(this);
4167 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4168
4169 AutoCaller mediumCaller(pMedium);
4170 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4171
4172 const char *pszDevType = NULL;
4173 ObjectsList<Medium> *pall = NULL;
4174 switch (argType)
4175 {
4176 case DeviceType_HardDisk:
4177 pall = &m->allHardDisks;
4178 pszDevType = tr("hard disk");
4179 break;
4180 case DeviceType_DVD:
4181 pszDevType = tr("DVD image");
4182 pall = &m->allDVDImages;
4183 break;
4184 case DeviceType_Floppy:
4185 pszDevType = tr("floppy image");
4186 pall = &m->allFloppyImages;
4187 break;
4188 default:
4189 AssertMsgFailedReturn(("invalid device type %d", argType), E_INVALIDARG);
4190 }
4191
4192 // caller must hold the media tree write lock
4193 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4194
4195 Guid id;
4196 Utf8Str strLocationFull;
4197 ComObjPtr<Medium> pParent;
4198 {
4199 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4200 id = pMedium->i_getId();
4201 strLocationFull = pMedium->i_getLocationFull();
4202 pParent = pMedium->i_getParent();
4203 }
4204
4205 HRESULT rc;
4206
4207 Utf8Str strConflict;
4208 ComObjPtr<Medium> pDupMedium;
4209 rc = i_checkMediaForConflicts(id,
4210 strLocationFull,
4211 strConflict,
4212 &pDupMedium);
4213 if (FAILED(rc)) return rc;
4214
4215 if (pDupMedium.isNull())
4216 {
4217 if (strConflict.length())
4218 return setError(E_INVALIDARG,
4219 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4220 pszDevType,
4221 strLocationFull.c_str(),
4222 id.raw(),
4223 strConflict.c_str(),
4224 m->strSettingsFilePath.c_str());
4225
4226 // add to the collection if it is a base medium
4227 if (pParent.isNull())
4228 pall->getList().push_back(pMedium);
4229
4230 // store all hard disks (even differencing images) in the map
4231 if (argType == DeviceType_HardDisk)
4232 m->mapHardDisks[id] = pMedium;
4233
4234 *ppMedium = pMedium;
4235 }
4236 else
4237 {
4238 // pMedium may be the last reference to the Medium object, and the
4239 // caller may have specified the same ComObjPtr as the output parameter.
4240 // In this case the assignment will uninit the object, and we must not
4241 // have a caller pending.
4242 mediumCaller.release();
4243 *ppMedium = pDupMedium;
4244 }
4245
4246 return rc;
4247}
4248
4249/**
4250 * Removes the given medium from the respective registry.
4251 *
4252 * @param pMedium Hard disk object to remove.
4253 *
4254 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4255 */
4256HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
4257{
4258 AssertReturn(pMedium != NULL, E_INVALIDARG);
4259
4260 AutoCaller autoCaller(this);
4261 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4262
4263 AutoCaller mediumCaller(pMedium);
4264 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4265
4266 // caller must hold the media tree write lock
4267 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4268
4269 Guid id;
4270 ComObjPtr<Medium> pParent;
4271 DeviceType_T devType;
4272 {
4273 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4274 id = pMedium->i_getId();
4275 pParent = pMedium->i_getParent();
4276 devType = pMedium->i_getDeviceType();
4277 }
4278
4279 ObjectsList<Medium> *pall = NULL;
4280 switch (devType)
4281 {
4282 case DeviceType_HardDisk:
4283 pall = &m->allHardDisks;
4284 break;
4285 case DeviceType_DVD:
4286 pall = &m->allDVDImages;
4287 break;
4288 case DeviceType_Floppy:
4289 pall = &m->allFloppyImages;
4290 break;
4291 default:
4292 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4293 }
4294
4295 // remove from the collection if it is a base medium
4296 if (pParent.isNull())
4297 pall->getList().remove(pMedium);
4298
4299 // remove all hard disks (even differencing images) from map
4300 if (devType == DeviceType_HardDisk)
4301 {
4302 size_t cnt = m->mapHardDisks.erase(id);
4303 Assert(cnt == 1);
4304 NOREF(cnt);
4305 }
4306
4307 return S_OK;
4308}
4309
4310/**
4311 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4312 * with children appearing before their parents.
4313 * @param llMedia
4314 * @param pMedium
4315 */
4316void VirtualBox::i_pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4317{
4318 // recurse first, then add ourselves; this way children end up on the
4319 // list before their parents
4320
4321 const MediaList &llChildren = pMedium->i_getChildren();
4322 for (MediaList::const_iterator it = llChildren.begin();
4323 it != llChildren.end();
4324 ++it)
4325 {
4326 Medium *pChild = *it;
4327 i_pushMediumToListWithChildren(llMedia, pChild);
4328 }
4329
4330 Log(("Pushing medium %RTuuid\n", pMedium->i_getId().raw()));
4331 llMedia.push_back(pMedium);
4332}
4333
4334/**
4335 * Unregisters all Medium objects which belong to the given machine registry.
4336 * Gets called from Machine::uninit() just before the machine object dies
4337 * and must only be called with a machine UUID as the registry ID.
4338 *
4339 * Locks the media tree.
4340 *
4341 * @param uuidMachine Medium registry ID (always a machine UUID)
4342 * @return
4343 */
4344HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
4345{
4346 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
4347
4348 LogFlowFuncEnter();
4349
4350 AutoCaller autoCaller(this);
4351 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4352
4353 MediaList llMedia2Close;
4354
4355 {
4356 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4357
4358 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4359 it != m->allHardDisks.getList().end();
4360 ++it)
4361 {
4362 ComObjPtr<Medium> pMedium = *it;
4363 AutoCaller medCaller(pMedium);
4364 if (FAILED(medCaller.rc())) return medCaller.rc();
4365 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4366
4367 if (pMedium->i_isInRegistry(uuidMachine))
4368 // recursively with children first
4369 i_pushMediumToListWithChildren(llMedia2Close, pMedium);
4370 }
4371 }
4372
4373 for (MediaList::iterator it = llMedia2Close.begin();
4374 it != llMedia2Close.end();
4375 ++it)
4376 {
4377 ComObjPtr<Medium> pMedium = *it;
4378 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
4379 AutoCaller mac(pMedium);
4380 pMedium->i_close(mac);
4381 }
4382
4383 LogFlowFuncLeave();
4384
4385 return S_OK;
4386}
4387
4388/**
4389 * Removes the given machine object from the internal list of registered machines.
4390 * Called from Machine::Unregister().
4391 * @param pMachine
4392 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4393 * @return
4394 */
4395HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
4396 const Guid &id)
4397{
4398 // remove from the collection of registered machines
4399 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4400 m->allMachines.removeChild(pMachine);
4401 // save the global registry
4402 HRESULT rc = i_saveSettings();
4403 alock.release();
4404
4405 /*
4406 * Now go over all known media and checks if they were registered in the
4407 * media registry of the given machine. Each such medium is then moved to
4408 * a different media registry to make sure it doesn't get lost since its
4409 * media registry is about to go away.
4410 *
4411 * This fixes the following use case: Image A.vdi of machine A is also used
4412 * by machine B, but registered in the media registry of machine A. If machine
4413 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4414 * become inaccessible.
4415 */
4416 {
4417 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4418 // iterate over the list of *base* images
4419 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4420 it != m->allHardDisks.getList().end();
4421 ++it)
4422 {
4423 ComObjPtr<Medium> &pMedium = *it;
4424 AutoCaller medCaller(pMedium);
4425 if (FAILED(medCaller.rc())) return medCaller.rc();
4426 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4427
4428 if (pMedium->i_removeRegistry(id, true /* fRecurse */))
4429 {
4430 // machine ID was found in base medium's registry list:
4431 // move this base image and all its children to another registry then
4432 // 1) first, find a better registry to add things to
4433 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref();
4434 if (puuidBetter)
4435 {
4436 // 2) better registry found: then use that
4437 pMedium->i_addRegistry(*puuidBetter, true /* fRecurse */);
4438 // 3) and make sure the registry is saved below
4439 mlock.release();
4440 tlock.release();
4441 i_markRegistryModified(*puuidBetter);
4442 tlock.acquire();
4443 mlock.release();
4444 }
4445 }
4446 }
4447 }
4448
4449 i_saveModifiedRegistries();
4450
4451 /* fire an event */
4452 i_onMachineRegistered(id, FALSE);
4453
4454 return rc;
4455}
4456
4457/**
4458 * Marks the registry for @a uuid as modified, so that it's saved in a later
4459 * call to saveModifiedRegistries().
4460 *
4461 * @param uuid
4462 */
4463void VirtualBox::i_markRegistryModified(const Guid &uuid)
4464{
4465 if (uuid == i_getGlobalRegistryId())
4466 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4467 else
4468 {
4469 ComObjPtr<Machine> pMachine;
4470 HRESULT rc = i_findMachine(uuid,
4471 false /* fPermitInaccessible */,
4472 false /* aSetError */,
4473 &pMachine);
4474 if (SUCCEEDED(rc))
4475 {
4476 AutoCaller machineCaller(pMachine);
4477 if (SUCCEEDED(machineCaller.rc()))
4478 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4479 }
4480 }
4481}
4482
4483/**
4484 * Saves all settings files according to the modified flags in the Machine
4485 * objects and in the VirtualBox object.
4486 *
4487 * This locks machines and the VirtualBox object as necessary, so better not
4488 * hold any locks before calling this.
4489 *
4490 * @return
4491 */
4492void VirtualBox::i_saveModifiedRegistries()
4493{
4494 HRESULT rc = S_OK;
4495 bool fNeedsGlobalSettings = false;
4496 uint64_t uOld;
4497
4498 {
4499 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4500 for (MachinesOList::iterator it = m->allMachines.begin();
4501 it != m->allMachines.end();
4502 ++it)
4503 {
4504 const ComObjPtr<Machine> &pMachine = *it;
4505
4506 for (;;)
4507 {
4508 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4509 if (!uOld)
4510 break;
4511 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4512 break;
4513 ASMNopPause();
4514 }
4515 if (uOld)
4516 {
4517 AutoCaller autoCaller(pMachine);
4518 if (FAILED(autoCaller.rc()))
4519 continue;
4520 /* object is already dead, no point in saving settings */
4521 if (getObjectState().getState() != ObjectState::Ready)
4522 continue;
4523 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
4524 rc = pMachine->i_saveSettings(&fNeedsGlobalSettings,
4525 Machine::SaveS_Force); // caller said save, so stop arguing
4526 }
4527 }
4528 }
4529
4530 for (;;)
4531 {
4532 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4533 if (!uOld)
4534 break;
4535 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4536 break;
4537 ASMNopPause();
4538 }
4539 if (uOld || fNeedsGlobalSettings)
4540 {
4541 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4542 rc = i_saveSettings();
4543 }
4544 NOREF(rc); /* XXX */
4545}
4546
4547
4548/* static */
4549const com::Utf8Str &VirtualBox::i_getVersionNormalized()
4550{
4551 return sVersionNormalized;
4552}
4553
4554/**
4555 * Checks if the path to the specified file exists, according to the path
4556 * information present in the file name. Optionally the path is created.
4557 *
4558 * Note that the given file name must contain the full path otherwise the
4559 * extracted relative path will be created based on the current working
4560 * directory which is normally unknown.
4561 *
4562 * @param aFileName Full file name which path is checked/created.
4563 * @param aCreate Flag if the path should be created if it doesn't exist.
4564 *
4565 * @return Extended error information on failure to check/create the path.
4566 */
4567/* static */
4568HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4569{
4570 Utf8Str strDir(strFileName);
4571 strDir.stripFilename();
4572 if (!RTDirExists(strDir.c_str()))
4573 {
4574 if (fCreate)
4575 {
4576 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4577 if (RT_FAILURE(vrc))
4578 return i_setErrorStatic(VBOX_E_IPRT_ERROR,
4579 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4580 strDir.c_str(),
4581 vrc));
4582 }
4583 else
4584 return i_setErrorStatic(VBOX_E_IPRT_ERROR,
4585 Utf8StrFmt(tr("Directory '%s' does not exist"),
4586 strDir.c_str()));
4587 }
4588
4589 return S_OK;
4590}
4591
4592const Utf8Str& VirtualBox::i_settingsFilePath()
4593{
4594 return m->strSettingsFilePath;
4595}
4596
4597/**
4598 * Returns the lock handle which protects the machines list. As opposed
4599 * to version 3.1 and earlier, these lists are no longer protected by the
4600 * VirtualBox lock, but by this more specialized lock. Mind the locking
4601 * order: always request this lock after the VirtualBox object lock but
4602 * before the locks of any machine object. See AutoLock.h.
4603 */
4604RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
4605{
4606 return m->lockMachines;
4607}
4608
4609/**
4610 * Returns the lock handle which protects the media trees (hard disks,
4611 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4612 * are no longer protected by the VirtualBox lock, but by this more
4613 * specialized lock. Mind the locking order: always request this lock
4614 * after the VirtualBox object lock but before the locks of the media
4615 * objects contained in these lists. See AutoLock.h.
4616 */
4617RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
4618{
4619 return m->lockMedia;
4620}
4621
4622/**
4623 * Thread function that handles custom events posted using #postEvent().
4624 */
4625// static
4626DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4627{
4628 LogFlowFuncEnter();
4629
4630 AssertReturn(pvUser, VERR_INVALID_POINTER);
4631
4632 HRESULT hr = com::Initialize();
4633 if (FAILED(hr))
4634 return VERR_COM_UNEXPECTED;
4635
4636 int rc = VINF_SUCCESS;
4637
4638 try
4639 {
4640 /* Create an event queue for the current thread. */
4641 EventQueue *pEventQueue = new EventQueue();
4642 AssertPtr(pEventQueue);
4643
4644 /* Return the queue to the one who created this thread. */
4645 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
4646
4647 /* signal that we're ready. */
4648 RTThreadUserSignal(thread);
4649
4650 /*
4651 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4652 * we must not stop processing events and delete the pEventQueue object. This must
4653 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4654 * See @bugref{5724}.
4655 */
4656 for (;;)
4657 {
4658 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
4659 if (rc == VERR_INTERRUPTED)
4660 {
4661 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
4662 rc = VINF_SUCCESS; /* Set success when exiting. */
4663 break;
4664 }
4665 }
4666
4667 delete pEventQueue;
4668 }
4669 catch (std::bad_alloc &ba)
4670 {
4671 rc = VERR_NO_MEMORY;
4672 NOREF(ba);
4673 }
4674
4675 com::Shutdown();
4676
4677 LogFlowFuncLeaveRC(rc);
4678 return rc;
4679}
4680
4681
4682////////////////////////////////////////////////////////////////////////////////
4683
4684/**
4685 * Takes the current list of registered callbacks of the managed VirtualBox
4686 * instance, and calls #handleCallback() for every callback item from the
4687 * list, passing the item as an argument.
4688 *
4689 * @note Locks the managed VirtualBox object for reading but leaves the lock
4690 * before iterating over callbacks and calling their methods.
4691 */
4692void *VirtualBox::CallbackEvent::handler()
4693{
4694 if (!mVirtualBox)
4695 return NULL;
4696
4697 AutoCaller autoCaller(mVirtualBox);
4698 if (!autoCaller.isOk())
4699 {
4700 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4701 mVirtualBox->getObjectState().getState()));
4702 /* We don't need mVirtualBox any more, so release it */
4703 mVirtualBox = NULL;
4704 return NULL;
4705 }
4706
4707 {
4708 VBoxEventDesc evDesc;
4709 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4710
4711 evDesc.fire(/* don't wait for delivery */0);
4712 }
4713
4714 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4715 return NULL;
4716}
4717
4718//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4719//{
4720// return E_NOTIMPL;
4721//}
4722
4723HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
4724 ComPtr<IDHCPServer> &aServer)
4725{
4726 ComObjPtr<DHCPServer> dhcpServer;
4727 dhcpServer.createObject();
4728 HRESULT rc = dhcpServer->init(this, Bstr(aName).raw());
4729 if (FAILED(rc)) return rc;
4730
4731 rc = i_registerDHCPServer(dhcpServer, true);
4732 if (FAILED(rc)) return rc;
4733
4734 dhcpServer.queryInterfaceTo(aServer.asOutParam());
4735
4736 return rc;
4737}
4738
4739HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
4740 ComPtr<IDHCPServer> &aServer)
4741{
4742 HRESULT rc = S_OK;
4743 ComPtr<DHCPServer> found;
4744
4745 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4746
4747 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4748 it != m->allDHCPServers.end();
4749 ++it)
4750 {
4751 Bstr bstr;
4752 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4753 if (FAILED(rc)) return rc;
4754
4755 if (bstr == Bstr(aName).raw())
4756 {
4757 found = *it;
4758 break;
4759 }
4760 }
4761
4762 if (!found)
4763 return E_INVALIDARG;
4764
4765 rc = found.queryInterfaceTo(aServer.asOutParam());
4766
4767 return rc;
4768}
4769
4770HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
4771{
4772 IDHCPServer *aP = aServer;
4773
4774 HRESULT rc = i_unregisterDHCPServer(static_cast<DHCPServer *>(aP), true);
4775
4776 return rc;
4777}
4778
4779/**
4780 * Remembers the given DHCP server in the settings.
4781 *
4782 * @param aDHCPServer DHCP server object to remember.
4783 * @param aSaveSettings @c true to save settings to disk (default).
4784 *
4785 * When @a aSaveSettings is @c true, this operation may fail because of the
4786 * failed #saveSettings() method it calls. In this case, the dhcp server object
4787 * will not be remembered. It is therefore the responsibility of the caller to
4788 * call this method as the last step of some action that requires registration
4789 * in order to make sure that only fully functional dhcp server objects get
4790 * registered.
4791 *
4792 * @note Locks this object for writing and @a aDHCPServer for reading.
4793 */
4794HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
4795 bool aSaveSettings /*= true*/)
4796{
4797 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4798
4799 AutoCaller autoCaller(this);
4800 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4801
4802 AutoCaller dhcpServerCaller(aDHCPServer);
4803 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4804
4805 Bstr name;
4806 com::Utf8Str uname;
4807 HRESULT rc = S_OK;
4808 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
4809 if (FAILED(rc)) return rc;
4810 uname = Utf8Str(name);
4811
4812 ComPtr<IDHCPServer> existing;
4813 rc = findDHCPServerByNetworkName(uname, existing);
4814 if (SUCCEEDED(rc))
4815 return E_INVALIDARG;
4816 rc = S_OK;
4817
4818 m->allDHCPServers.addChild(aDHCPServer);
4819
4820 if (aSaveSettings)
4821 {
4822 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4823 rc = i_saveSettings();
4824 vboxLock.release();
4825
4826 if (FAILED(rc))
4827 i_unregisterDHCPServer(aDHCPServer, false /* aSaveSettings */);
4828 }
4829
4830 return rc;
4831}
4832
4833/**
4834 * Removes the given DHCP server from the settings.
4835 *
4836 * @param aDHCPServer DHCP server object to remove.
4837 * @param aSaveSettings @c true to save settings to disk (default).
4838 *
4839 * When @a aSaveSettings is @c true, this operation may fail because of the
4840 * failed #saveSettings() method it calls. In this case, the DHCP server
4841 * will NOT be removed from the settingsi when this method returns.
4842 *
4843 * @note Locks this object for writing.
4844 */
4845HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer,
4846 bool aSaveSettings /*= true*/)
4847{
4848 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4849
4850 AutoCaller autoCaller(this);
4851 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4852
4853 AutoCaller dhcpServerCaller(aDHCPServer);
4854 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4855
4856 m->allDHCPServers.removeChild(aDHCPServer);
4857
4858 HRESULT rc = S_OK;
4859
4860 if (aSaveSettings)
4861 {
4862 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4863 rc = i_saveSettings();
4864 vboxLock.release();
4865
4866 if (FAILED(rc))
4867 rc = i_registerDHCPServer(aDHCPServer, false /* aSaveSettings */);
4868 }
4869
4870 return rc;
4871}
4872
4873
4874/**
4875 * NAT Network
4876 */
4877HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
4878 ComPtr<INATNetwork> &aNetwork)
4879{
4880#ifdef VBOX_WITH_NAT_SERVICE
4881 ComObjPtr<NATNetwork> natNetwork;
4882 natNetwork.createObject();
4883 HRESULT rc = natNetwork->init(this, Bstr(aNetworkName).raw());
4884 if (FAILED(rc)) return rc;
4885
4886 rc = i_registerNATNetwork(natNetwork, true);
4887 if (FAILED(rc)) return rc;
4888
4889 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
4890
4891 fireNATNetworkCreationDeletionEvent(m->pEventSource, Bstr(aNetworkName).raw(), TRUE);
4892
4893 return rc;
4894#else
4895 NOREF(aName);
4896 NOREF(aNatNetwork);
4897 return E_NOTIMPL;
4898#endif
4899}
4900
4901HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
4902 ComPtr<INATNetwork> &aNetwork)
4903{
4904#ifdef VBOX_WITH_NAT_SERVICE
4905
4906 HRESULT rc = S_OK;
4907 ComPtr<NATNetwork> found;
4908
4909 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4910
4911 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4912 it != m->allNATNetworks.end();
4913 ++it)
4914 {
4915 Bstr bstr;
4916 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4917 if (FAILED(rc)) return rc;
4918
4919 if (bstr == Bstr(aNetworkName).raw())
4920 {
4921 found = *it;
4922 break;
4923 }
4924 }
4925
4926 if (!found)
4927 return E_INVALIDARG;
4928 found.queryInterfaceTo(aNetwork.asOutParam());
4929 return rc;
4930#else
4931 NOREF(aName);
4932 NOREF(aNetworkName);
4933 return E_NOTIMPL;
4934#endif
4935}
4936
4937HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
4938{
4939#ifdef VBOX_WITH_NAT_SERVICE
4940 Bstr name;
4941 HRESULT rc = S_OK;
4942 INATNetwork *iNw = aNetwork;
4943 NATNetwork *network = static_cast<NATNetwork *>(iNw);
4944 rc = network->COMGETTER(NetworkName)(name.asOutParam());
4945 rc = i_unregisterNATNetwork(network, true);
4946 fireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
4947 return rc;
4948#else
4949 NOREF(aNetwork);
4950 return E_NOTIMPL;
4951#endif
4952
4953}
4954/**
4955 * Remembers the given NAT network in the settings.
4956 *
4957 * @param aNATNetwork NAT Network object to remember.
4958 * @param aSaveSettings @c true to save settings to disk (default).
4959 *
4960 *
4961 * @note Locks this object for writing and @a aNATNetwork for reading.
4962 */
4963HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
4964 bool aSaveSettings /*= true*/)
4965{
4966#ifdef VBOX_WITH_NAT_SERVICE
4967 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
4968
4969 AutoCaller autoCaller(this);
4970 AssertComRCReturnRC(autoCaller.rc());
4971
4972 AutoCaller natNetworkCaller(aNATNetwork);
4973 AssertComRCReturnRC(natNetworkCaller.rc());
4974
4975 Bstr name;
4976 HRESULT rc;
4977 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
4978 AssertComRCReturnRC(rc);
4979
4980 /* returned value isn't 0 and aSaveSettings is true
4981 * means that we create duplicate, otherwise we just load settings.
4982 */
4983 if ( sNatNetworkNameToRefCount[name]
4984 && aSaveSettings)
4985 AssertComRCReturnRC(E_INVALIDARG);
4986
4987 rc = S_OK;
4988
4989 sNatNetworkNameToRefCount[name] = 0;
4990
4991 m->allNATNetworks.addChild(aNATNetwork);
4992
4993 if (aSaveSettings)
4994 {
4995 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4996 rc = i_saveSettings();
4997 vboxLock.release();
4998
4999 if (FAILED(rc))
5000 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
5001 }
5002
5003 return rc;
5004#else
5005 NOREF(aNATNetwork);
5006 NOREF(aSaveSettings);
5007 /* No panic please (silently ignore) */
5008 return S_OK;
5009#endif
5010}
5011
5012/**
5013 * Removes the given NAT network from the settings.
5014 *
5015 * @param aNATNetwork NAT network object to remove.
5016 * @param aSaveSettings @c true to save settings to disk (default).
5017 *
5018 * When @a aSaveSettings is @c true, this operation may fail because of the
5019 * failed #saveSettings() method it calls. In this case, the DHCP server
5020 * will NOT be removed from the settingsi when this method returns.
5021 *
5022 * @note Locks this object for writing.
5023 */
5024HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
5025 bool aSaveSettings /*= true*/)
5026{
5027#ifdef VBOX_WITH_NAT_SERVICE
5028 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5029
5030 AutoCaller autoCaller(this);
5031 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5032
5033 AutoCaller natNetworkCaller(aNATNetwork);
5034 AssertComRCReturn(natNetworkCaller.rc(), natNetworkCaller.rc());
5035
5036 Bstr name;
5037 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5038 /* Hm, there're still running clients. */
5039 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
5040 AssertComRCReturnRC(E_INVALIDARG);
5041
5042 m->allNATNetworks.removeChild(aNATNetwork);
5043
5044 if (aSaveSettings)
5045 {
5046 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5047 rc = i_saveSettings();
5048 vboxLock.release();
5049
5050 if (FAILED(rc))
5051 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
5052 }
5053
5054 return rc;
5055#else
5056 NOREF(aNATNetwork);
5057 NOREF(aSaveSettings);
5058 return E_NOTIMPL;
5059#endif
5060}
5061/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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