VirtualBox

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

Last change on this file since 60763 was 60763, checked in by vboxsync, 9 years ago

Main/VirtualBox: cleanup

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