VirtualBox

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

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

Main/VirtualBox: fix regression (array of empty strings instead of array of extradata keys returned) from wrapper conversion

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