VirtualBox

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

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

6219: New parameters related to file size / recording time limitation for VM Video Capture have been added (vcpmaxtime, vcpmaxsize and vcpoptions - special codec options in key=value format). EbmlWriter has been refactored. Removed some redundant code.

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

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