VirtualBox

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

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

forward-ported r112367 (Main: santiy check for sanitiseMachineFilename())

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

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