VirtualBox

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

Last change on this file since 65314 was 65158, checked in by vboxsync, 8 years ago

Main: doxygen fixes

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