VirtualBox

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

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

Main: a few doxygen fixes

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