VirtualBox

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

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

iprt/log.h,SUPDrv: Replaced the 'personal' logging groups with 6 more generic logging levels (7 thru 12) and a 'Warn' level. The 'Warn' level is enabled by 'group.e' together with level 1 logging. Modified the new RTLog[Rel][Get]DefaultInstanceEx functions to only take one 32-bit parameter to minimize call setup time and size. Major support driver version bump. LogAleksey=Log7, LogBird=Log8, LogSunlover=Log9, none of the other personal macros was used. Log*Warning got renamed to Log1*Warning so as to not confuse it with the LogWarn/LogRelWarn macros.

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