VirtualBox

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

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

Main/VirtualBox: take vbox lock before locking dhcp server list (#7500)

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