VirtualBox

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

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

ThreadTask: split createThread up into three methods to avoid having to pass NULL all the time when the type needs specifying. Also, explictly marked the racy variant.

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