VirtualBox

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

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

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