VirtualBox

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

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

Main: warnings

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

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