VirtualBox

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

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

ThreadTask: Cleaning up handler() methods.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 173.2 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 63187 2016-08-08 17:49:42Z vboxsync $ */
2/** @file
3 * Implementation of IVirtualBox in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.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 VirtualBox::i_SVCHelperClientThreadTask(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 i_SVCHelperClientThreadTask() argument */
2552
2553 HRESULT hr = S_OK;
2554 StartSVCHelperClientData *pTask = NULL;
2555 try
2556 {
2557 pTask = new StartSVCHelperClientData();
2558
2559 pTask->init(this, aProgress, aPrivileged, aFunc, aUser);
2560
2561 if (!pTask->isOk())
2562 {
2563 delete pTask;
2564 LogRel(("Could not init StartSVCHelperClientData object \n"));
2565 throw E_FAIL;
2566 }
2567
2568 //this function delete pTask in case of exceptions, so there is no need in the call of delete operator
2569 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_WORKER);
2570
2571 }
2572 catch(std::bad_alloc &)
2573 {
2574 hr = setError(E_OUTOFMEMORY);
2575 }
2576 catch(...)
2577 {
2578 LogRel(("Could not create thread for StartSVCHelperClientData \n"));
2579 hr = E_FAIL;
2580 }
2581
2582 return hr;
2583}
2584
2585/**
2586 * Worker thread for startSVCHelperClient().
2587 */
2588/* static */
2589void VirtualBox::i_SVCHelperClientThreadTask(StartSVCHelperClientData *pTask)
2590{
2591 LogFlowFuncEnter();
2592 HRESULT rc = S_OK;
2593 bool userFuncCalled = false;
2594
2595 do
2596 {
2597 AssertBreakStmt(pTask, rc = E_POINTER);
2598 AssertReturnVoid(!pTask->progress.isNull());
2599
2600 /* protect VirtualBox from uninitialization */
2601 AutoCaller autoCaller(pTask->that);
2602 if (!autoCaller.isOk())
2603 {
2604 /* it's too late */
2605 rc = autoCaller.rc();
2606 break;
2607 }
2608
2609 int vrc = VINF_SUCCESS;
2610
2611 Guid id;
2612 id.create();
2613 SVCHlpClient client;
2614 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2615 id.raw()).c_str());
2616 if (RT_FAILURE(vrc))
2617 {
2618 rc = pTask->that->setError(E_FAIL, tr("Could not create the communication channel (%Rrc)"), vrc);
2619 break;
2620 }
2621
2622 /* get the path to the executable */
2623 char exePathBuf[RTPATH_MAX];
2624 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2625 if (!exePath)
2626 {
2627 rc = pTask->that->setError(E_FAIL, tr("Cannot get executable name"));
2628 break;
2629 }
2630
2631 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2632
2633 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2634
2635 RTPROCESS pid = NIL_RTPROCESS;
2636
2637 if (pTask->privileged)
2638 {
2639 /* Attempt to start a privileged process using the Run As dialog */
2640
2641 Bstr file = exePath;
2642 Bstr parameters = argsStr;
2643
2644 SHELLEXECUTEINFO shExecInfo;
2645
2646 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2647
2648 shExecInfo.fMask = NULL;
2649 shExecInfo.hwnd = NULL;
2650 shExecInfo.lpVerb = L"runas";
2651 shExecInfo.lpFile = file.raw();
2652 shExecInfo.lpParameters = parameters.raw();
2653 shExecInfo.lpDirectory = NULL;
2654 shExecInfo.nShow = SW_NORMAL;
2655 shExecInfo.hInstApp = NULL;
2656
2657 if (!ShellExecuteEx(&shExecInfo))
2658 {
2659 int vrc2 = RTErrConvertFromWin32(GetLastError());
2660 /* hide excessive details in case of a frequent error
2661 * (pressing the Cancel button to close the Run As dialog) */
2662 if (vrc2 == VERR_CANCELLED)
2663 rc = pTask->that->setError(E_FAIL, tr("Operation canceled by the user"));
2664 else
2665 rc = pTask->that->setError(E_FAIL, tr("Could not launch a privileged process '%s' (%Rrc)"), exePath, vrc2);
2666 break;
2667 }
2668 }
2669 else
2670 {
2671 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2672 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2673 if (RT_FAILURE(vrc))
2674 {
2675 rc = pTask->that->setError(E_FAIL, tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2676 break;
2677 }
2678 }
2679
2680 /* wait for the client to connect */
2681 vrc = client.connect();
2682 if (RT_SUCCESS(vrc))
2683 {
2684 /* start the user supplied function */
2685 rc = pTask->func(&client, pTask->progress, pTask->user, &vrc);
2686 userFuncCalled = true;
2687 }
2688
2689 /* send the termination signal to the process anyway */
2690 {
2691 int vrc2 = client.write(SVCHlpMsg::Null);
2692 if (RT_SUCCESS(vrc))
2693 vrc = vrc2;
2694 }
2695
2696 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2697 {
2698 rc = pTask->that->setError(E_FAIL, tr("Could not operate the communication channel (%Rrc)"), vrc);
2699 break;
2700 }
2701 }
2702 while (0);
2703
2704 if (FAILED(rc) && !userFuncCalled)
2705 {
2706 /* call the user function in the "cleanup only" mode
2707 * to let it free resources passed to in aUser */
2708 pTask->func(NULL, NULL, pTask->user, NULL);
2709 }
2710
2711 pTask->progress->i_notifyComplete(rc);
2712
2713 LogFlowFuncLeave();
2714}
2715
2716#endif /* RT_OS_WINDOWS */
2717
2718/**
2719 * Sends a signal to the client watcher to rescan the set of machines
2720 * that have open sessions.
2721 *
2722 * @note Doesn't lock anything.
2723 */
2724void VirtualBox::i_updateClientWatcher()
2725{
2726 AutoCaller autoCaller(this);
2727 AssertComRCReturnVoid(autoCaller.rc());
2728
2729 AssertPtrReturnVoid(m->pClientWatcher);
2730 m->pClientWatcher->update();
2731}
2732
2733/**
2734 * Adds the given child process ID to the list of processes to be reaped.
2735 * This call should be followed by #updateClientWatcher() to take the effect.
2736 *
2737 * @note Doesn't lock anything.
2738 */
2739void VirtualBox::i_addProcessToReap(RTPROCESS pid)
2740{
2741 AutoCaller autoCaller(this);
2742 AssertComRCReturnVoid(autoCaller.rc());
2743
2744 AssertPtrReturnVoid(m->pClientWatcher);
2745 m->pClientWatcher->addProcess(pid);
2746}
2747
2748/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2749struct MachineEvent : public VirtualBox::CallbackEvent
2750{
2751 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
2752 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2753 , mBool(aBool)
2754 { }
2755
2756 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
2757 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2758 , mState(aState)
2759 {}
2760
2761 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2762 {
2763 switch (mWhat)
2764 {
2765 case VBoxEventType_OnMachineDataChanged:
2766 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2767 break;
2768
2769 case VBoxEventType_OnMachineStateChanged:
2770 aEvDesc.init(aSource, mWhat, id.raw(), mState);
2771 break;
2772
2773 case VBoxEventType_OnMachineRegistered:
2774 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2775 break;
2776
2777 default:
2778 AssertFailedReturn(S_OK);
2779 }
2780 return S_OK;
2781 }
2782
2783 Bstr id;
2784 MachineState_T mState;
2785 BOOL mBool;
2786};
2787
2788
2789/**
2790 * VD plugin load
2791 */
2792int VirtualBox::i_loadVDPlugin(const char *pszPluginLibrary)
2793{
2794 return m->pSystemProperties->i_loadVDPlugin(pszPluginLibrary);
2795}
2796
2797/**
2798 * VD plugin unload
2799 */
2800int VirtualBox::i_unloadVDPlugin(const char *pszPluginLibrary)
2801{
2802 return m->pSystemProperties->i_unloadVDPlugin(pszPluginLibrary);
2803}
2804
2805
2806/**
2807 * @note Doesn't lock any object.
2808 */
2809void VirtualBox::i_onMachineStateChange(const Guid &aId, MachineState_T aState)
2810{
2811 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
2812}
2813
2814/**
2815 * @note Doesn't lock any object.
2816 */
2817void VirtualBox::i_onMachineDataChange(const Guid &aId, BOOL aTemporary)
2818{
2819 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
2820}
2821
2822/**
2823 * @note Locks this object for reading.
2824 */
2825BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
2826 Bstr &aError)
2827{
2828 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
2829 aId.toString().c_str(), aKey, aValue));
2830
2831 AutoCaller autoCaller(this);
2832 AssertComRCReturn(autoCaller.rc(), FALSE);
2833
2834 BOOL allowChange = TRUE;
2835 Bstr id = aId.toUtf16();
2836
2837 VBoxEventDesc evDesc;
2838 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
2839 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
2840 //Assert(fDelivered);
2841 if (fDelivered)
2842 {
2843 ComPtr<IEvent> aEvent;
2844 evDesc.getEvent(aEvent.asOutParam());
2845 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
2846 Assert(aCanChangeEvent);
2847 BOOL fVetoed = FALSE;
2848 aCanChangeEvent->IsVetoed(&fVetoed);
2849 allowChange = !fVetoed;
2850
2851 if (!allowChange)
2852 {
2853 SafeArray<BSTR> aVetos;
2854 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
2855 if (aVetos.size() > 0)
2856 aError = aVetos[0];
2857 }
2858 }
2859 else
2860 allowChange = TRUE;
2861
2862 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
2863 return allowChange;
2864}
2865
2866/** Event for onExtraDataChange() */
2867struct ExtraDataEvent : public VirtualBox::CallbackEvent
2868{
2869 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
2870 IN_BSTR aKey, IN_BSTR aVal)
2871 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
2872 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
2873 {}
2874
2875 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2876 {
2877 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
2878 }
2879
2880 Bstr machineId, key, val;
2881};
2882
2883/**
2884 * @note Doesn't lock any object.
2885 */
2886void VirtualBox::i_onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
2887{
2888 i_postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
2889}
2890
2891/**
2892 * @note Doesn't lock any object.
2893 */
2894void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
2895{
2896 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
2897}
2898
2899/** Event for onSessionStateChange() */
2900struct SessionEvent : public VirtualBox::CallbackEvent
2901{
2902 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2903 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
2904 , machineId(aMachineId.toUtf16()), sessionState(aState)
2905 {}
2906
2907 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2908 {
2909 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
2910 }
2911 Bstr machineId;
2912 SessionState_T sessionState;
2913};
2914
2915/**
2916 * @note Doesn't lock any object.
2917 */
2918void VirtualBox::i_onSessionStateChange(const Guid &aId, SessionState_T aState)
2919{
2920 i_postEvent(new SessionEvent(this, aId, aState));
2921}
2922
2923/** Event for i_onSnapshotTaken(), i_onSnapshotDeleted(), i_onSnapshotRestored() and i_onSnapshotChange() */
2924struct SnapshotEvent : public VirtualBox::CallbackEvent
2925{
2926 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2927 VBoxEventType_T aWhat)
2928 : CallbackEvent(aVB, aWhat)
2929 , machineId(aMachineId), snapshotId(aSnapshotId)
2930 {}
2931
2932 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2933 {
2934 return aEvDesc.init(aSource, mWhat, machineId.toUtf16().raw(),
2935 snapshotId.toUtf16().raw());
2936 }
2937
2938 Guid machineId;
2939 Guid snapshotId;
2940};
2941
2942/**
2943 * @note Doesn't lock any object.
2944 */
2945void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
2946{
2947 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2948 VBoxEventType_OnSnapshotTaken));
2949}
2950
2951/**
2952 * @note Doesn't lock any object.
2953 */
2954void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
2955{
2956 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2957 VBoxEventType_OnSnapshotDeleted));
2958}
2959
2960/**
2961 * @note Doesn't lock any object.
2962 */
2963void VirtualBox::i_onSnapshotRestored(const Guid &aMachineId, const Guid &aSnapshotId)
2964{
2965 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2966 VBoxEventType_OnSnapshotRestored));
2967}
2968
2969/**
2970 * @note Doesn't lock any object.
2971 */
2972void VirtualBox::i_onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
2973{
2974 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2975 VBoxEventType_OnSnapshotChanged));
2976}
2977
2978/** Event for onGuestPropertyChange() */
2979struct GuestPropertyEvent : public VirtualBox::CallbackEvent
2980{
2981 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
2982 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
2983 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
2984 machineId(aMachineId),
2985 name(aName),
2986 value(aValue),
2987 flags(aFlags)
2988 {}
2989
2990 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2991 {
2992 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
2993 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
2994 }
2995
2996 Guid machineId;
2997 Bstr name, value, flags;
2998};
2999
3000/**
3001 * @note Doesn't lock any object.
3002 */
3003void VirtualBox::i_onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
3004 IN_BSTR aValue, IN_BSTR aFlags)
3005{
3006 i_postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
3007}
3008
3009/**
3010 * @note Doesn't lock any object.
3011 */
3012void VirtualBox::i_onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
3013 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
3014 IN_BSTR aGuestIp, uint16_t aGuestPort)
3015{
3016 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
3017 aHostPort, aGuestIp, aGuestPort);
3018}
3019
3020void VirtualBox::i_onNATNetworkChange(IN_BSTR aName)
3021{
3022 fireNATNetworkChangedEvent(m->pEventSource, aName);
3023}
3024
3025void VirtualBox::i_onNATNetworkStartStop(IN_BSTR aName, BOOL fStart)
3026{
3027 fireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
3028}
3029
3030void VirtualBox::i_onNATNetworkSetting(IN_BSTR aNetworkName, BOOL aEnabled,
3031 IN_BSTR aNetwork, IN_BSTR aGateway,
3032 BOOL aAdvertiseDefaultIpv6RouteEnabled,
3033 BOOL fNeedDhcpServer)
3034{
3035 fireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled,
3036 aNetwork, aGateway,
3037 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
3038}
3039
3040void VirtualBox::i_onNATNetworkPortForward(IN_BSTR aNetworkName, BOOL create, BOOL fIpv6,
3041 IN_BSTR aRuleName, NATProtocol_T proto,
3042 IN_BSTR aHostIp, LONG aHostPort,
3043 IN_BSTR aGuestIp, LONG aGuestPort)
3044{
3045 fireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create,
3046 fIpv6, aRuleName, proto,
3047 aHostIp, aHostPort,
3048 aGuestIp, aGuestPort);
3049}
3050
3051
3052void VirtualBox::i_onHostNameResolutionConfigurationChange()
3053{
3054 if (m->pEventSource)
3055 fireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
3056}
3057
3058
3059int VirtualBox::i_natNetworkRefInc(IN_BSTR aNetworkName)
3060{
3061 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3062 Bstr name(aNetworkName);
3063
3064 if (!sNatNetworkNameToRefCount[name])
3065 {
3066 ComPtr<INATNetwork> nat;
3067 HRESULT rc = FindNATNetworkByName(aNetworkName, nat.asOutParam());
3068 if (FAILED(rc)) return -1;
3069
3070 rc = nat->Start(Bstr("whatever").raw());
3071 if (SUCCEEDED(rc))
3072 LogRel(("Started NAT network '%ls'\n", aNetworkName));
3073 else
3074 LogRel(("Error %Rhrc starting NAT network '%ls'\n", rc, aNetworkName));
3075 AssertComRCReturn(rc, -1);
3076 }
3077
3078 sNatNetworkNameToRefCount[name]++;
3079
3080 return sNatNetworkNameToRefCount[name];
3081}
3082
3083
3084int VirtualBox::i_natNetworkRefDec(IN_BSTR aNetworkName)
3085{
3086 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3087 Bstr name(aNetworkName);
3088
3089 if (!sNatNetworkNameToRefCount[name])
3090 return 0;
3091
3092 sNatNetworkNameToRefCount[name]--;
3093
3094 if (!sNatNetworkNameToRefCount[name])
3095 {
3096 ComPtr<INATNetwork> nat;
3097 HRESULT rc = FindNATNetworkByName(aNetworkName, nat.asOutParam());
3098 if (FAILED(rc)) return -1;
3099
3100 rc = nat->Stop();
3101 if (SUCCEEDED(rc))
3102 LogRel(("Stopped NAT network '%ls'\n", aNetworkName));
3103 else
3104 LogRel(("Error %Rhrc stopping NAT network '%ls'\n", rc, aNetworkName));
3105 AssertComRCReturn(rc, -1);
3106 }
3107
3108 return sNatNetworkNameToRefCount[name];
3109}
3110
3111
3112/**
3113 * @note Locks the list of other objects for reading.
3114 */
3115ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
3116{
3117 ComObjPtr<GuestOSType> type;
3118
3119 /* unknown type must always be the first */
3120 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
3121
3122 return m->allGuestOSTypes.front();
3123}
3124
3125/**
3126 * Returns the list of opened machines (machines having VM sessions opened,
3127 * ignoring other sessions) and optionally the list of direct session controls.
3128 *
3129 * @param aMachines Where to put opened machines (will be empty if none).
3130 * @param aControls Where to put direct session controls (optional).
3131 *
3132 * @note The returned lists contain smart pointers. So, clear it as soon as
3133 * it becomes no more necessary to release instances.
3134 *
3135 * @note It can be possible that a session machine from the list has been
3136 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
3137 * when accessing unprotected data directly.
3138 *
3139 * @note Locks objects for reading.
3140 */
3141void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
3142 InternalControlList *aControls /*= NULL*/)
3143{
3144 AutoCaller autoCaller(this);
3145 AssertComRCReturnVoid(autoCaller.rc());
3146
3147 aMachines.clear();
3148 if (aControls)
3149 aControls->clear();
3150
3151 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3152
3153 for (MachinesOList::iterator it = m->allMachines.begin();
3154 it != m->allMachines.end();
3155 ++it)
3156 {
3157 ComObjPtr<SessionMachine> sm;
3158 ComPtr<IInternalSessionControl> ctl;
3159 if ((*it)->i_isSessionOpenVM(sm, &ctl))
3160 {
3161 aMachines.push_back(sm);
3162 if (aControls)
3163 aControls->push_back(ctl);
3164 }
3165 }
3166}
3167
3168/**
3169 * Gets a reference to the machine list. This is the real thing, not a copy,
3170 * so bad things will happen if the caller doesn't hold the necessary lock.
3171 *
3172 * @returns reference to machine list
3173 *
3174 * @note Caller must hold the VirtualBox object lock at least for reading.
3175 */
3176VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
3177{
3178 return m->allMachines;
3179}
3180
3181/**
3182 * Searches for a machine object with the given ID in the collection
3183 * of registered machines.
3184 *
3185 * @param aId Machine UUID to look for.
3186 * @param aPermitInaccessible If true, inaccessible machines will be found;
3187 * if false, this will fail if the given machine is inaccessible.
3188 * @param aSetError If true, set errorinfo if the machine is not found.
3189 * @param aMachine Returned machine, if found.
3190 * @return
3191 */
3192HRESULT VirtualBox::i_findMachine(const Guid &aId,
3193 bool fPermitInaccessible,
3194 bool aSetError,
3195 ComObjPtr<Machine> *aMachine /* = NULL */)
3196{
3197 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3198
3199 AutoCaller autoCaller(this);
3200 AssertComRCReturnRC(autoCaller.rc());
3201
3202 {
3203 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3204
3205 for (MachinesOList::iterator it = m->allMachines.begin();
3206 it != m->allMachines.end();
3207 ++it)
3208 {
3209 ComObjPtr<Machine> pMachine = *it;
3210
3211 if (!fPermitInaccessible)
3212 {
3213 // skip inaccessible machines
3214 AutoCaller machCaller(pMachine);
3215 if (FAILED(machCaller.rc()))
3216 continue;
3217 }
3218
3219 if (pMachine->i_getId() == aId)
3220 {
3221 rc = S_OK;
3222 if (aMachine)
3223 *aMachine = pMachine;
3224 break;
3225 }
3226 }
3227 }
3228
3229 if (aSetError && FAILED(rc))
3230 rc = setError(rc,
3231 tr("Could not find a registered machine with UUID {%RTuuid}"),
3232 aId.raw());
3233
3234 return rc;
3235}
3236
3237/**
3238 * Searches for a machine object with the given name or location in the
3239 * collection of registered machines.
3240 *
3241 * @param aName Machine name or location to look for.
3242 * @param aSetError If true, set errorinfo if the machine is not found.
3243 * @param aMachine Returned machine, if found.
3244 * @return
3245 */
3246HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
3247 bool aSetError,
3248 ComObjPtr<Machine> *aMachine /* = NULL */)
3249{
3250 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3251
3252 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3253 for (MachinesOList::iterator it = m->allMachines.begin();
3254 it != m->allMachines.end();
3255 ++it)
3256 {
3257 ComObjPtr<Machine> &pMachine = *it;
3258 AutoCaller machCaller(pMachine);
3259 if (machCaller.rc())
3260 continue; // we can't ask inaccessible machines for their names
3261
3262 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
3263 if (pMachine->i_getName() == aName)
3264 {
3265 rc = S_OK;
3266 if (aMachine)
3267 *aMachine = pMachine;
3268 break;
3269 }
3270 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
3271 {
3272 rc = S_OK;
3273 if (aMachine)
3274 *aMachine = pMachine;
3275 break;
3276 }
3277 }
3278
3279 if (aSetError && FAILED(rc))
3280 rc = setError(rc,
3281 tr("Could not find a registered machine named '%s'"), aName.c_str());
3282
3283 return rc;
3284}
3285
3286static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
3287{
3288 /* empty strings are invalid */
3289 if (aGroup.isEmpty())
3290 return E_INVALIDARG;
3291 /* the toplevel group is valid */
3292 if (aGroup == "/")
3293 return S_OK;
3294 /* any other strings of length 1 are invalid */
3295 if (aGroup.length() == 1)
3296 return E_INVALIDARG;
3297 /* must start with a slash */
3298 if (aGroup.c_str()[0] != '/')
3299 return E_INVALIDARG;
3300 /* must not end with a slash */
3301 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3302 return E_INVALIDARG;
3303 /* check the group components */
3304 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3305 while (pStr)
3306 {
3307 char *pSlash = RTStrStr(pStr, "/");
3308 if (pSlash)
3309 {
3310 /* no empty components (or // sequences in other words) */
3311 if (pSlash == pStr)
3312 return E_INVALIDARG;
3313 /* check if the machine name rules are violated, because that means
3314 * the group components are too close to the limits. */
3315 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3316 Utf8Str tmp2(tmp);
3317 sanitiseMachineFilename(tmp);
3318 if (tmp != tmp2)
3319 return E_INVALIDARG;
3320 if (fPrimary)
3321 {
3322 HRESULT rc = pVirtualBox->i_findMachineByName(tmp,
3323 false /* aSetError */);
3324 if (SUCCEEDED(rc))
3325 return VBOX_E_VM_ERROR;
3326 }
3327 pStr = pSlash + 1;
3328 }
3329 else
3330 {
3331 /* check if the machine name rules are violated, because that means
3332 * the group components is too close to the limits. */
3333 Utf8Str tmp(pStr);
3334 Utf8Str tmp2(tmp);
3335 sanitiseMachineFilename(tmp);
3336 if (tmp != tmp2)
3337 return E_INVALIDARG;
3338 pStr = NULL;
3339 }
3340 }
3341 return S_OK;
3342}
3343
3344/**
3345 * Validates a machine group.
3346 *
3347 * @param aMachineGroup Machine group.
3348 * @param fPrimary Set if this is the primary group.
3349 *
3350 * @return S_OK or E_INVALIDARG
3351 */
3352HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
3353{
3354 HRESULT rc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
3355 if (FAILED(rc))
3356 {
3357 if (rc == VBOX_E_VM_ERROR)
3358 rc = setError(E_INVALIDARG,
3359 tr("Machine group '%s' conflicts with a virtual machine name"),
3360 aGroup.c_str());
3361 else
3362 rc = setError(rc,
3363 tr("Invalid machine group '%s'"),
3364 aGroup.c_str());
3365 }
3366 return rc;
3367}
3368
3369/**
3370 * Takes a list of machine groups, and sanitizes/validates it.
3371 *
3372 * @param aMachineGroups Array with the machine groups.
3373 * @param pllMachineGroups Pointer to list of strings for the result.
3374 *
3375 * @return S_OK or E_INVALIDARG
3376 */
3377HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
3378{
3379 pllMachineGroups->clear();
3380 if (aMachineGroups.size())
3381 {
3382 for (size_t i = 0; i < aMachineGroups.size(); i++)
3383 {
3384 Utf8Str group(aMachineGroups[i]);
3385 if (group.length() == 0)
3386 group = "/";
3387
3388 HRESULT rc = i_validateMachineGroup(group, i == 0);
3389 if (FAILED(rc))
3390 return rc;
3391
3392 /* no duplicates please */
3393 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3394 == pllMachineGroups->end())
3395 pllMachineGroups->push_back(group);
3396 }
3397 if (pllMachineGroups->size() == 0)
3398 pllMachineGroups->push_back("/");
3399 }
3400 else
3401 pllMachineGroups->push_back("/");
3402
3403 return S_OK;
3404}
3405
3406/**
3407 * Searches for a Medium object with the given ID in the list of registered
3408 * hard disks.
3409 *
3410 * @param aId ID of the hard disk. Must not be empty.
3411 * @param aSetError If @c true , the appropriate error info is set in case
3412 * when the hard disk is not found.
3413 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3414 *
3415 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3416 *
3417 * @note Locks the media tree for reading.
3418 */
3419HRESULT VirtualBox::i_findHardDiskById(const Guid &aId,
3420 bool aSetError,
3421 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3422{
3423 AssertReturn(!aId.isZero(), E_INVALIDARG);
3424
3425 // we use the hard disks map, but it is protected by the
3426 // hard disk _list_ lock handle
3427 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3428
3429 HardDiskMap::const_iterator it = m->mapHardDisks.find(aId);
3430 if (it != m->mapHardDisks.end())
3431 {
3432 if (aHardDisk)
3433 *aHardDisk = (*it).second;
3434 return S_OK;
3435 }
3436
3437 if (aSetError)
3438 return setError(VBOX_E_OBJECT_NOT_FOUND,
3439 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3440 aId.raw());
3441
3442 return VBOX_E_OBJECT_NOT_FOUND;
3443}
3444
3445/**
3446 * Searches for a Medium object with the given ID or location in the list of
3447 * registered hard disks. If both ID and location are specified, the first
3448 * object that matches either of them (not necessarily both) is returned.
3449 *
3450 * @param aLocation Full location specification. Must not be empty.
3451 * @param aSetError If @c true , the appropriate error info is set in case
3452 * when the hard disk is not found.
3453 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3454 *
3455 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3456 *
3457 * @note Locks the media tree for reading.
3458 */
3459HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
3460 bool aSetError,
3461 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3462{
3463 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3464
3465 // we use the hard disks map, but it is protected by the
3466 // hard disk _list_ lock handle
3467 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3468
3469 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3470 it != m->mapHardDisks.end();
3471 ++it)
3472 {
3473 const ComObjPtr<Medium> &pHD = (*it).second;
3474
3475 AutoCaller autoCaller(pHD);
3476 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3477 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3478
3479 Utf8Str strLocationFull = pHD->i_getLocationFull();
3480
3481 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3482 {
3483 if (aHardDisk)
3484 *aHardDisk = pHD;
3485 return S_OK;
3486 }
3487 }
3488
3489 if (aSetError)
3490 return setError(VBOX_E_OBJECT_NOT_FOUND,
3491 tr("Could not find an open hard disk with location '%s'"),
3492 strLocation.c_str());
3493
3494 return VBOX_E_OBJECT_NOT_FOUND;
3495}
3496
3497/**
3498 * Searches for a Medium object with the given ID or location in the list of
3499 * registered DVD or floppy images, depending on the @a mediumType argument.
3500 * If both ID and file path are specified, the first object that matches either
3501 * of them (not necessarily both) is returned.
3502 *
3503 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3504 * @param aId ID of the image file (unused when NULL).
3505 * @param aLocation Full path to the image file (unused when NULL).
3506 * @param aSetError If @c true, the appropriate error info is set in case when
3507 * the image is not found.
3508 * @param aImage Where to store the found image object (can be NULL).
3509 *
3510 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3511 *
3512 * @note Locks the media tree for reading.
3513 */
3514HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
3515 const Guid *aId,
3516 const Utf8Str &aLocation,
3517 bool aSetError,
3518 ComObjPtr<Medium> *aImage /* = NULL */)
3519{
3520 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3521
3522 Utf8Str location;
3523 if (!aLocation.isEmpty())
3524 {
3525 int vrc = i_calculateFullPath(aLocation, location);
3526 if (RT_FAILURE(vrc))
3527 return setError(VBOX_E_FILE_ERROR,
3528 tr("Invalid image file location '%s' (%Rrc)"),
3529 aLocation.c_str(),
3530 vrc);
3531 }
3532
3533 MediaOList *pMediaList;
3534
3535 switch (mediumType)
3536 {
3537 case DeviceType_DVD:
3538 pMediaList = &m->allDVDImages;
3539 break;
3540
3541 case DeviceType_Floppy:
3542 pMediaList = &m->allFloppyImages;
3543 break;
3544
3545 default:
3546 return E_INVALIDARG;
3547 }
3548
3549 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3550
3551 bool found = false;
3552
3553 for (MediaList::const_iterator it = pMediaList->begin();
3554 it != pMediaList->end();
3555 ++it)
3556 {
3557 // no AutoCaller, registered image life time is bound to this
3558 Medium *pMedium = *it;
3559 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3560 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
3561
3562 found = ( aId
3563 && pMedium->i_getId() == *aId)
3564 || ( !aLocation.isEmpty()
3565 && RTPathCompare(location.c_str(),
3566 strLocationFull.c_str()) == 0);
3567 if (found)
3568 {
3569 if (pMedium->i_getDeviceType() != mediumType)
3570 {
3571 if (mediumType == DeviceType_DVD)
3572 return setError(E_INVALIDARG,
3573 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3574 else
3575 return setError(E_INVALIDARG,
3576 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3577 }
3578
3579 if (aImage)
3580 *aImage = pMedium;
3581 break;
3582 }
3583 }
3584
3585 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3586
3587 if (aSetError && !found)
3588 {
3589 if (aId)
3590 setError(rc,
3591 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3592 aId->raw(),
3593 m->strSettingsFilePath.c_str());
3594 else
3595 setError(rc,
3596 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3597 aLocation.c_str(),
3598 m->strSettingsFilePath.c_str());
3599 }
3600
3601 return rc;
3602}
3603
3604/**
3605 * Searches for an IMedium object that represents the given UUID.
3606 *
3607 * If the UUID is empty (indicating an empty drive), this sets pMedium
3608 * to NULL and returns S_OK.
3609 *
3610 * If the UUID refers to a host drive of the given device type, this
3611 * sets pMedium to the object from the list in IHost and returns S_OK.
3612 *
3613 * If the UUID is an image file, this sets pMedium to the object that
3614 * findDVDOrFloppyImage() returned.
3615 *
3616 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3617 *
3618 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3619 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3620 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3621 * @param pMedium out: IMedium object found.
3622 * @return
3623 */
3624HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
3625 const Guid &uuid,
3626 bool fRefresh,
3627 bool aSetError,
3628 ComObjPtr<Medium> &pMedium)
3629{
3630 if (uuid.isZero())
3631 {
3632 // that's easy
3633 pMedium.setNull();
3634 return S_OK;
3635 }
3636 else if (!uuid.isValid())
3637 {
3638 /* handling of case invalid GUID */
3639 return setError(VBOX_E_OBJECT_NOT_FOUND,
3640 tr("Guid '%s' is invalid"),
3641 uuid.toString().c_str());
3642 }
3643
3644 // first search for host drive with that UUID
3645 HRESULT rc = m->pHost->i_findHostDriveById(mediumType,
3646 uuid,
3647 fRefresh,
3648 pMedium);
3649 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3650 // then search for an image with that UUID
3651 rc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3652
3653 return rc;
3654}
3655
3656HRESULT VirtualBox::i_findGuestOSType(const Bstr &bstrOSType,
3657 GuestOSType*& pGuestOSType)
3658{
3659 /* Look for a GuestOSType object */
3660 AssertMsg(m->allGuestOSTypes.size() != 0,
3661 ("Guest OS types array must be filled"));
3662
3663 if (bstrOSType.isEmpty())
3664 {
3665 pGuestOSType = NULL;
3666 return S_OK;
3667 }
3668
3669 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3670 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3671 it != m->allGuestOSTypes.end();
3672 ++it)
3673 {
3674 if ((*it)->i_id() == bstrOSType)
3675 {
3676 pGuestOSType = *it;
3677 return S_OK;
3678 }
3679 }
3680
3681 return setError(VBOX_E_OBJECT_NOT_FOUND,
3682 tr("Guest OS type '%ls' is invalid"),
3683 bstrOSType.raw());
3684}
3685
3686/**
3687 * Returns the constant pseudo-machine UUID that is used to identify the
3688 * global media registry.
3689 *
3690 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3691 * in which media registry it is saved (if any): this can either be a machine
3692 * UUID, if it's in a per-machine media registry, or this global ID.
3693 *
3694 * This UUID is only used to identify the VirtualBox object while VirtualBox
3695 * is running. It is a compile-time constant and not saved anywhere.
3696 *
3697 * @return
3698 */
3699const Guid& VirtualBox::i_getGlobalRegistryId() const
3700{
3701 return m->uuidMediaRegistry;
3702}
3703
3704const ComObjPtr<Host>& VirtualBox::i_host() const
3705{
3706 return m->pHost;
3707}
3708
3709SystemProperties* VirtualBox::i_getSystemProperties() const
3710{
3711 return m->pSystemProperties;
3712}
3713
3714#ifdef VBOX_WITH_EXTPACK
3715/**
3716 * Getter that SystemProperties and others can use to talk to the extension
3717 * pack manager.
3718 */
3719ExtPackManager* VirtualBox::i_getExtPackManager() const
3720{
3721 return m->ptrExtPackManager;
3722}
3723#endif
3724
3725/**
3726 * Getter that machines can talk to the autostart database.
3727 */
3728AutostartDb* VirtualBox::i_getAutostartDb() const
3729{
3730 return m->pAutostartDb;
3731}
3732
3733#ifdef VBOX_WITH_RESOURCE_USAGE_API
3734const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
3735{
3736 return m->pPerformanceCollector;
3737}
3738#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3739
3740/**
3741 * Returns the default machine folder from the system properties
3742 * with proper locking.
3743 * @return
3744 */
3745void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
3746{
3747 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3748 str = m->pSystemProperties->m->strDefaultMachineFolder;
3749}
3750
3751/**
3752 * Returns the default hard disk format from the system properties
3753 * with proper locking.
3754 * @return
3755 */
3756void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
3757{
3758 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3759 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3760}
3761
3762const Utf8Str& VirtualBox::i_homeDir() const
3763{
3764 return m->strHomeDir;
3765}
3766
3767/**
3768 * Calculates the absolute path of the given path taking the VirtualBox home
3769 * directory as the current directory.
3770 *
3771 * @param aPath Path to calculate the absolute path for.
3772 * @param aResult Where to put the result (used only on success, can be the
3773 * same Utf8Str instance as passed in @a aPath).
3774 * @return IPRT result.
3775 *
3776 * @note Doesn't lock any object.
3777 */
3778int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3779{
3780 AutoCaller autoCaller(this);
3781 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3782
3783 /* no need to lock since mHomeDir is const */
3784
3785 char folder[RTPATH_MAX];
3786 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3787 strPath.c_str(),
3788 folder,
3789 sizeof(folder));
3790 if (RT_SUCCESS(vrc))
3791 aResult = folder;
3792
3793 return vrc;
3794}
3795
3796/**
3797 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3798 * if it is a subdirectory thereof, or simply copying it otherwise.
3799 *
3800 * @param strSource Path to evalue and copy.
3801 * @param strTarget Buffer to receive target path.
3802 */
3803void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
3804 Utf8Str &strTarget)
3805{
3806 AutoCaller autoCaller(this);
3807 AssertComRCReturnVoid(autoCaller.rc());
3808
3809 // no need to lock since mHomeDir is const
3810
3811 // use strTarget as a temporary buffer to hold the machine settings dir
3812 strTarget = m->strHomeDir;
3813 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3814 // is relative: then append what's left
3815 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3816 else
3817 // is not relative: then overwrite
3818 strTarget = strSource;
3819}
3820
3821// private methods
3822/////////////////////////////////////////////////////////////////////////////
3823
3824/**
3825 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3826 * location already registered.
3827 *
3828 * On return, sets @a aConflict to the string describing the conflicting medium,
3829 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3830 * either case. A failure is unexpected.
3831 *
3832 * @param aId UUID to check.
3833 * @param aLocation Location to check.
3834 * @param aConflict Where to return parameters of the conflicting medium.
3835 * @param ppMedium Medium reference in case this is simply a duplicate.
3836 *
3837 * @note Locks the media tree and media objects for reading.
3838 */
3839HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
3840 const Utf8Str &aLocation,
3841 Utf8Str &aConflict,
3842 ComObjPtr<Medium> *ppMedium)
3843{
3844 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
3845 AssertReturn(ppMedium, E_INVALIDARG);
3846
3847 aConflict.setNull();
3848 ppMedium->setNull();
3849
3850 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3851
3852 HRESULT rc = S_OK;
3853
3854 ComObjPtr<Medium> pMediumFound;
3855 const char *pcszType = NULL;
3856
3857 if (aId.isValid() && !aId.isZero())
3858 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3859 if (FAILED(rc) && !aLocation.isEmpty())
3860 rc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3861 if (SUCCEEDED(rc))
3862 pcszType = tr("hard disk");
3863
3864 if (!pcszType)
3865 {
3866 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3867 if (SUCCEEDED(rc))
3868 pcszType = tr("CD/DVD image");
3869 }
3870
3871 if (!pcszType)
3872 {
3873 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3874 if (SUCCEEDED(rc))
3875 pcszType = tr("floppy image");
3876 }
3877
3878 if (pcszType && pMediumFound)
3879 {
3880 /* Note: no AutoCaller since bound to this */
3881 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3882
3883 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
3884 Guid idFound = pMediumFound->i_getId();
3885
3886 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3887 && (idFound == aId)
3888 )
3889 *ppMedium = pMediumFound;
3890
3891 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3892 pcszType,
3893 strLocFound.c_str(),
3894 idFound.raw());
3895 }
3896
3897 return S_OK;
3898}
3899
3900/**
3901 * Checks whether the given UUID is already in use by one medium for the
3902 * given device type.
3903 *
3904 * @returns true if the UUID is already in use
3905 * fale otherwise
3906 * @param aId The UUID to check.
3907 * @param deviceType The device type the UUID is going to be checked for
3908 * conflicts.
3909 */
3910bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
3911{
3912 /* A zero UUID is invalid here, always claim that it is already used. */
3913 AssertReturn(!aId.isZero(), true);
3914
3915 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3916
3917 HRESULT rc = S_OK;
3918 bool fInUse = false;
3919
3920 ComObjPtr<Medium> pMediumFound;
3921
3922 switch (deviceType)
3923 {
3924 case DeviceType_HardDisk:
3925 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3926 break;
3927 case DeviceType_DVD:
3928 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3929 break;
3930 case DeviceType_Floppy:
3931 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
3932 break;
3933 default:
3934 AssertMsgFailed(("Invalid device type %d\n", deviceType));
3935 }
3936
3937 if (SUCCEEDED(rc) && pMediumFound)
3938 fInUse = true;
3939
3940 return fInUse;
3941}
3942
3943/**
3944 * Called from Machine::prepareSaveSettings() when it has detected
3945 * that a machine has been renamed. Such renames will require
3946 * updating the global media registry during the
3947 * VirtualBox::saveSettings() that follows later.
3948*
3949 * When a machine is renamed, there may well be media (in particular,
3950 * diff images for snapshots) in the global registry that will need
3951 * to have their paths updated. Before 3.2, Machine::saveSettings
3952 * used to call VirtualBox::saveSettings implicitly, which was both
3953 * unintuitive and caused locking order problems. Now, we remember
3954 * such pending name changes with this method so that
3955 * VirtualBox::saveSettings() can process them properly.
3956 */
3957void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3958 const Utf8Str &strNewConfigDir)
3959{
3960 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3961
3962 Data::PendingMachineRename pmr;
3963 pmr.strConfigDirOld = strOldConfigDir;
3964 pmr.strConfigDirNew = strNewConfigDir;
3965 m->llPendingMachineRenames.push_back(pmr);
3966}
3967
3968struct SaveMediaRegistriesDesc
3969{
3970 MediaList llMedia;
3971 ComObjPtr<VirtualBox> pVirtualBox;
3972};
3973
3974static DECLCALLBACK(int) fntSaveMediaRegistries(RTTHREAD ThreadSelf, void *pvUser)
3975{
3976 NOREF(ThreadSelf);
3977 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
3978 if (!pDesc)
3979 {
3980 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
3981 return VERR_INVALID_PARAMETER;
3982 }
3983
3984 for (MediaList::const_iterator it = pDesc->llMedia.begin();
3985 it != pDesc->llMedia.end();
3986 ++it)
3987 {
3988 Medium *pMedium = *it;
3989 pMedium->i_markRegistriesModified();
3990 }
3991
3992 pDesc->pVirtualBox->i_saveModifiedRegistries();
3993
3994 pDesc->llMedia.clear();
3995 pDesc->pVirtualBox.setNull();
3996 delete pDesc;
3997
3998 return VINF_SUCCESS;
3999}
4000
4001/**
4002 * Goes through all known media (hard disks, floppies and DVDs) and saves
4003 * those into the given settings::MediaRegistry structures whose registry
4004 * ID match the given UUID.
4005 *
4006 * Before actually writing to the structures, all media paths (not just the
4007 * ones for the given registry) are updated if machines have been renamed
4008 * since the last call.
4009 *
4010 * This gets called from two contexts:
4011 *
4012 * -- VirtualBox::saveSettings() with the UUID of the global registry
4013 * (VirtualBox::Data.uuidRegistry); this will save those media
4014 * which had been loaded from the global registry or have been
4015 * attached to a "legacy" machine which can't save its own registry;
4016 *
4017 * -- Machine::saveSettings() with the UUID of a machine, if a medium
4018 * has been attached to a machine created with VirtualBox 4.0 or later.
4019 *
4020 * Media which have only been temporarily opened without having been
4021 * attached to a machine have a NULL registry UUID and therefore don't
4022 * get saved.
4023 *
4024 * This locks the media tree. Throws HRESULT on errors!
4025 *
4026 * @param mediaRegistry Settings structure to fill.
4027 * @param uuidRegistry The UUID of the media registry; either a machine UUID
4028 * (if machine registry) or the UUID of the global registry.
4029 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
4030 */
4031void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4032 const Guid &uuidRegistry,
4033 const Utf8Str &strMachineFolder)
4034{
4035 // lock all media for the following; use a write lock because we're
4036 // modifying the PendingMachineRenamesList, which is protected by this
4037 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4038
4039 // if a machine was renamed, then we'll need to refresh media paths
4040 if (m->llPendingMachineRenames.size())
4041 {
4042 // make a single list from the three media lists so we don't need three loops
4043 MediaList llAllMedia;
4044 // with hard disks, we must use the map, not the list, because the list only has base images
4045 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
4046 llAllMedia.push_back(it->second);
4047 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
4048 llAllMedia.push_back(*it);
4049 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
4050 llAllMedia.push_back(*it);
4051
4052 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
4053 for (MediaList::iterator it = llAllMedia.begin();
4054 it != llAllMedia.end();
4055 ++it)
4056 {
4057 Medium *pMedium = *it;
4058 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
4059 it2 != m->llPendingMachineRenames.end();
4060 ++it2)
4061 {
4062 const Data::PendingMachineRename &pmr = *it2;
4063 HRESULT rc = pMedium->i_updatePath(pmr.strConfigDirOld,
4064 pmr.strConfigDirNew);
4065 if (SUCCEEDED(rc))
4066 {
4067 // Remember which medium objects has been changed,
4068 // to trigger saving their registries later.
4069 pDesc->llMedia.push_back(pMedium);
4070 } else if (rc == VBOX_E_FILE_ERROR)
4071 /* nothing */;
4072 else
4073 AssertComRC(rc);
4074 }
4075 }
4076 // done, don't do it again until we have more machine renames
4077 m->llPendingMachineRenames.clear();
4078
4079 if (pDesc->llMedia.size())
4080 {
4081 // Handle the media registry saving in a separate thread, to
4082 // avoid giant locking problems and passing up the list many
4083 // levels up to whoever triggered saveSettings, as there are
4084 // lots of places which would need to handle saving more settings.
4085 pDesc->pVirtualBox = this;
4086 int vrc = RTThreadCreate(NULL,
4087 fntSaveMediaRegistries,
4088 (void *)pDesc,
4089 0, // cbStack (default)
4090 RTTHREADTYPE_MAIN_WORKER,
4091 0, // flags
4092 "SaveMediaReg");
4093 ComAssertRC(vrc);
4094 // failure means that settings aren't saved, but there isn't
4095 // much we can do besides avoiding memory leaks
4096 if (RT_FAILURE(vrc))
4097 {
4098 LogRelFunc(("Failed to create thread for saving media registries (%Rrc)\n", vrc));
4099 delete pDesc;
4100 }
4101 }
4102 else
4103 delete pDesc;
4104 }
4105
4106 struct {
4107 MediaOList &llSource;
4108 settings::MediaList &llTarget;
4109 } s[] =
4110 {
4111 // hard disks
4112 { m->allHardDisks, mediaRegistry.llHardDisks },
4113 // CD/DVD images
4114 { m->allDVDImages, mediaRegistry.llDvdImages },
4115 // floppy images
4116 { m->allFloppyImages, mediaRegistry.llFloppyImages }
4117 };
4118
4119 HRESULT rc;
4120
4121 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
4122 {
4123 MediaOList &llSource = s[i].llSource;
4124 settings::MediaList &llTarget = s[i].llTarget;
4125 llTarget.clear();
4126 for (MediaList::const_iterator it = llSource.begin();
4127 it != llSource.end();
4128 ++it)
4129 {
4130 Medium *pMedium = *it;
4131 AutoCaller autoCaller(pMedium);
4132 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
4133 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4134
4135 if (pMedium->i_isInRegistry(uuidRegistry))
4136 {
4137 llTarget.push_back(settings::Medium::Empty);
4138 rc = pMedium->i_saveSettings(llTarget.back(), strMachineFolder); // this recurses into child hard disks
4139 if (FAILED(rc))
4140 {
4141 llTarget.pop_back();
4142 throw rc;
4143 }
4144 }
4145 }
4146 }
4147}
4148
4149/**
4150 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
4151 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
4152 * places internally when settings need saving.
4153 *
4154 * @note Caller must have locked the VirtualBox object for writing and must not hold any
4155 * other locks since this locks all kinds of member objects and trees temporarily,
4156 * which could cause conflicts.
4157 */
4158HRESULT VirtualBox::i_saveSettings()
4159{
4160 AutoCaller autoCaller(this);
4161 AssertComRCReturnRC(autoCaller.rc());
4162
4163 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
4164 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
4165
4166 i_unmarkRegistryModified(i_getGlobalRegistryId());
4167
4168 HRESULT rc = S_OK;
4169
4170 try
4171 {
4172 // machines
4173 m->pMainConfigFile->llMachines.clear();
4174 {
4175 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4176 for (MachinesOList::iterator it = m->allMachines.begin();
4177 it != m->allMachines.end();
4178 ++it)
4179 {
4180 Machine *pMachine = *it;
4181 // save actual machine registry entry
4182 settings::MachineRegistryEntry mre;
4183 rc = pMachine->i_saveRegistryEntry(mre);
4184 m->pMainConfigFile->llMachines.push_back(mre);
4185 }
4186 }
4187
4188 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
4189 m->uuidMediaRegistry, // global media registry ID
4190 Utf8Str::Empty); // strMachineFolder
4191
4192 m->pMainConfigFile->llDhcpServers.clear();
4193 {
4194 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4195 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4196 it != m->allDHCPServers.end();
4197 ++it)
4198 {
4199 settings::DHCPServer d;
4200 rc = (*it)->i_saveSettings(d);
4201 if (FAILED(rc)) throw rc;
4202 m->pMainConfigFile->llDhcpServers.push_back(d);
4203 }
4204 }
4205
4206#ifdef VBOX_WITH_NAT_SERVICE
4207 /* Saving NAT Network configuration */
4208 m->pMainConfigFile->llNATNetworks.clear();
4209 {
4210 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4211 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4212 it != m->allNATNetworks.end();
4213 ++it)
4214 {
4215 settings::NATNetwork n;
4216 rc = (*it)->i_saveSettings(n);
4217 if (FAILED(rc)) throw rc;
4218 m->pMainConfigFile->llNATNetworks.push_back(n);
4219 }
4220 }
4221#endif
4222
4223 // leave extra data alone, it's still in the config file
4224
4225 // host data (USB filters)
4226 rc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
4227 if (FAILED(rc)) throw rc;
4228
4229 rc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
4230 if (FAILED(rc)) throw rc;
4231
4232 // and write out the XML, still under the lock
4233 m->pMainConfigFile->write(m->strSettingsFilePath);
4234 }
4235 catch (HRESULT err)
4236 {
4237 /* we assume that error info is set by the thrower */
4238 rc = err;
4239 }
4240 catch (...)
4241 {
4242 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
4243 }
4244
4245 return rc;
4246}
4247
4248/**
4249 * Helper to register the machine.
4250 *
4251 * When called during VirtualBox startup, adds the given machine to the
4252 * collection of registered machines. Otherwise tries to mark the machine
4253 * as registered, and, if succeeded, adds it to the collection and
4254 * saves global settings.
4255 *
4256 * @note The caller must have added itself as a caller of the @a aMachine
4257 * object if calls this method not on VirtualBox startup.
4258 *
4259 * @param aMachine machine to register
4260 *
4261 * @note Locks objects!
4262 */
4263HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
4264{
4265 ComAssertRet(aMachine, E_INVALIDARG);
4266
4267 AutoCaller autoCaller(this);
4268 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4269
4270 HRESULT rc = S_OK;
4271
4272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4273
4274 {
4275 ComObjPtr<Machine> pMachine;
4276 rc = i_findMachine(aMachine->i_getId(),
4277 true /* fPermitInaccessible */,
4278 false /* aDoSetError */,
4279 &pMachine);
4280 if (SUCCEEDED(rc))
4281 {
4282 /* sanity */
4283 AutoLimitedCaller machCaller(pMachine);
4284 AssertComRC(machCaller.rc());
4285
4286 return setError(E_INVALIDARG,
4287 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
4288 aMachine->i_getId().raw(),
4289 pMachine->i_getSettingsFileFull().c_str());
4290 }
4291
4292 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
4293 rc = S_OK;
4294 }
4295
4296 if (getObjectState().getState() != ObjectState::InInit)
4297 {
4298 rc = aMachine->i_prepareRegister();
4299 if (FAILED(rc)) return rc;
4300 }
4301
4302 /* add to the collection of registered machines */
4303 m->allMachines.addChild(aMachine);
4304
4305 if (getObjectState().getState() != ObjectState::InInit)
4306 rc = i_saveSettings();
4307
4308 return rc;
4309}
4310
4311/**
4312 * Remembers the given medium object by storing it in either the global
4313 * medium registry or a machine one.
4314 *
4315 * @note Caller must hold the media tree lock for writing; in addition, this
4316 * locks @a pMedium for reading
4317 *
4318 * @param pMedium Medium object to remember.
4319 * @param ppMedium Actually stored medium object. Can be different if due
4320 * to an unavoidable race there was a duplicate Medium object
4321 * created.
4322 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
4323 * lock, necessary to release it in the right spot.
4324 * @return
4325 */
4326HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
4327 ComObjPtr<Medium> *ppMedium,
4328 AutoWriteLock &mediaTreeLock)
4329{
4330 AssertReturn(pMedium != NULL, E_INVALIDARG);
4331 AssertReturn(ppMedium != NULL, E_INVALIDARG);
4332
4333 // caller must hold the media tree write lock
4334 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4335
4336 AutoCaller autoCaller(this);
4337 AssertComRCReturnRC(autoCaller.rc());
4338
4339 AutoCaller mediumCaller(pMedium);
4340 AssertComRCReturnRC(mediumCaller.rc());
4341
4342 const char *pszDevType = NULL;
4343 ObjectsList<Medium> *pall = NULL;
4344 DeviceType_T devType;
4345 {
4346 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4347 devType = pMedium->i_getDeviceType();
4348 }
4349 switch (devType)
4350 {
4351 case DeviceType_HardDisk:
4352 pall = &m->allHardDisks;
4353 pszDevType = tr("hard disk");
4354 break;
4355 case DeviceType_DVD:
4356 pszDevType = tr("DVD image");
4357 pall = &m->allDVDImages;
4358 break;
4359 case DeviceType_Floppy:
4360 pszDevType = tr("floppy image");
4361 pall = &m->allFloppyImages;
4362 break;
4363 default:
4364 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4365 }
4366
4367 Guid id;
4368 Utf8Str strLocationFull;
4369 ComObjPtr<Medium> pParent;
4370 {
4371 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4372 id = pMedium->i_getId();
4373 strLocationFull = pMedium->i_getLocationFull();
4374 pParent = pMedium->i_getParent();
4375 }
4376
4377 HRESULT rc;
4378
4379 Utf8Str strConflict;
4380 ComObjPtr<Medium> pDupMedium;
4381 rc = i_checkMediaForConflicts(id,
4382 strLocationFull,
4383 strConflict,
4384 &pDupMedium);
4385 if (FAILED(rc)) return rc;
4386
4387 if (pDupMedium.isNull())
4388 {
4389 if (strConflict.length())
4390 return setError(E_INVALIDARG,
4391 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4392 pszDevType,
4393 strLocationFull.c_str(),
4394 id.raw(),
4395 strConflict.c_str(),
4396 m->strSettingsFilePath.c_str());
4397
4398 // add to the collection if it is a base medium
4399 if (pParent.isNull())
4400 pall->getList().push_back(pMedium);
4401
4402 // store all hard disks (even differencing images) in the map
4403 if (devType == DeviceType_HardDisk)
4404 m->mapHardDisks[id] = pMedium;
4405
4406 mediumCaller.release();
4407 mediaTreeLock.release();
4408 *ppMedium = pMedium;
4409 }
4410 else
4411 {
4412 // pMedium may be the last reference to the Medium object, and the
4413 // caller may have specified the same ComObjPtr as the output parameter.
4414 // In this case the assignment will uninit the object, and we must not
4415 // have a caller pending.
4416 mediumCaller.release();
4417 // release media tree lock, must not be held at uninit time.
4418 mediaTreeLock.release();
4419 // must not hold the media tree write lock any more
4420 Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4421 *ppMedium = pDupMedium;
4422 }
4423
4424 // Restore the initial lock state, so that no unexpected lock changes are
4425 // done by this method, which would need adjustments everywhere.
4426 mediaTreeLock.acquire();
4427
4428 return rc;
4429}
4430
4431/**
4432 * Removes the given medium from the respective registry.
4433 *
4434 * @param pMedium Hard disk object to remove.
4435 *
4436 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4437 */
4438HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
4439{
4440 AssertReturn(pMedium != NULL, E_INVALIDARG);
4441
4442 AutoCaller autoCaller(this);
4443 AssertComRCReturnRC(autoCaller.rc());
4444
4445 AutoCaller mediumCaller(pMedium);
4446 AssertComRCReturnRC(mediumCaller.rc());
4447
4448 // caller must hold the media tree write lock
4449 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4450
4451 Guid id;
4452 ComObjPtr<Medium> pParent;
4453 DeviceType_T devType;
4454 {
4455 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4456 id = pMedium->i_getId();
4457 pParent = pMedium->i_getParent();
4458 devType = pMedium->i_getDeviceType();
4459 }
4460
4461 ObjectsList<Medium> *pall = NULL;
4462 switch (devType)
4463 {
4464 case DeviceType_HardDisk:
4465 pall = &m->allHardDisks;
4466 break;
4467 case DeviceType_DVD:
4468 pall = &m->allDVDImages;
4469 break;
4470 case DeviceType_Floppy:
4471 pall = &m->allFloppyImages;
4472 break;
4473 default:
4474 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4475 }
4476
4477 // remove from the collection if it is a base medium
4478 if (pParent.isNull())
4479 pall->getList().remove(pMedium);
4480
4481 // remove all hard disks (even differencing images) from map
4482 if (devType == DeviceType_HardDisk)
4483 {
4484 size_t cnt = m->mapHardDisks.erase(id);
4485 Assert(cnt == 1);
4486 NOREF(cnt);
4487 }
4488
4489 return S_OK;
4490}
4491
4492/**
4493 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4494 * with children appearing before their parents.
4495 * @param llMedia
4496 * @param pMedium
4497 */
4498void VirtualBox::i_pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4499{
4500 // recurse first, then add ourselves; this way children end up on the
4501 // list before their parents
4502
4503 const MediaList &llChildren = pMedium->i_getChildren();
4504 for (MediaList::const_iterator it = llChildren.begin();
4505 it != llChildren.end();
4506 ++it)
4507 {
4508 Medium *pChild = *it;
4509 i_pushMediumToListWithChildren(llMedia, pChild);
4510 }
4511
4512 Log(("Pushing medium %RTuuid\n", pMedium->i_getId().raw()));
4513 llMedia.push_back(pMedium);
4514}
4515
4516/**
4517 * Unregisters all Medium objects which belong to the given machine registry.
4518 * Gets called from Machine::uninit() just before the machine object dies
4519 * and must only be called with a machine UUID as the registry ID.
4520 *
4521 * Locks the media tree.
4522 *
4523 * @param uuidMachine Medium registry ID (always a machine UUID)
4524 * @return
4525 */
4526HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
4527{
4528 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
4529
4530 LogFlowFuncEnter();
4531
4532 AutoCaller autoCaller(this);
4533 AssertComRCReturnRC(autoCaller.rc());
4534
4535 MediaList llMedia2Close;
4536
4537 {
4538 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4539
4540 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4541 it != m->allHardDisks.getList().end();
4542 ++it)
4543 {
4544 ComObjPtr<Medium> pMedium = *it;
4545 AutoCaller medCaller(pMedium);
4546 if (FAILED(medCaller.rc())) return medCaller.rc();
4547 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4548
4549 if (pMedium->i_isInRegistry(uuidMachine))
4550 // recursively with children first
4551 i_pushMediumToListWithChildren(llMedia2Close, pMedium);
4552 }
4553 }
4554
4555 for (MediaList::iterator it = llMedia2Close.begin();
4556 it != llMedia2Close.end();
4557 ++it)
4558 {
4559 ComObjPtr<Medium> pMedium = *it;
4560 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
4561 AutoCaller mac(pMedium);
4562 pMedium->i_close(mac);
4563 }
4564
4565 LogFlowFuncLeave();
4566
4567 return S_OK;
4568}
4569
4570/**
4571 * Removes the given machine object from the internal list of registered machines.
4572 * Called from Machine::Unregister().
4573 * @param pMachine
4574 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4575 * @return
4576 */
4577HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
4578 const Guid &id)
4579{
4580 // remove from the collection of registered machines
4581 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4582 m->allMachines.removeChild(pMachine);
4583 // save the global registry
4584 HRESULT rc = i_saveSettings();
4585 alock.release();
4586
4587 /*
4588 * Now go over all known media and checks if they were registered in the
4589 * media registry of the given machine. Each such medium is then moved to
4590 * a different media registry to make sure it doesn't get lost since its
4591 * media registry is about to go away.
4592 *
4593 * This fixes the following use case: Image A.vdi of machine A is also used
4594 * by machine B, but registered in the media registry of machine A. If machine
4595 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4596 * become inaccessible.
4597 */
4598 {
4599 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4600 // iterate over the list of *base* images
4601 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4602 it != m->allHardDisks.getList().end();
4603 ++it)
4604 {
4605 ComObjPtr<Medium> &pMedium = *it;
4606 AutoCaller medCaller(pMedium);
4607 if (FAILED(medCaller.rc())) return medCaller.rc();
4608 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4609
4610 if (pMedium->i_removeRegistryRecursive(id))
4611 {
4612 // machine ID was found in base medium's registry list:
4613 // move this base image and all its children to another registry then
4614 // 1) first, find a better registry to add things to
4615 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref();
4616 if (puuidBetter)
4617 {
4618 // 2) better registry found: then use that
4619 pMedium->i_addRegistryRecursive(*puuidBetter);
4620 // 3) and make sure the registry is saved below
4621 mlock.release();
4622 tlock.release();
4623 i_markRegistryModified(*puuidBetter);
4624 tlock.acquire();
4625 mlock.acquire();
4626 }
4627 }
4628 }
4629 }
4630
4631 i_saveModifiedRegistries();
4632
4633 /* fire an event */
4634 i_onMachineRegistered(id, FALSE);
4635
4636 return rc;
4637}
4638
4639/**
4640 * Marks the registry for @a uuid as modified, so that it's saved in a later
4641 * call to saveModifiedRegistries().
4642 *
4643 * @param uuid
4644 */
4645void VirtualBox::i_markRegistryModified(const Guid &uuid)
4646{
4647 if (uuid == i_getGlobalRegistryId())
4648 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4649 else
4650 {
4651 ComObjPtr<Machine> pMachine;
4652 HRESULT rc = i_findMachine(uuid,
4653 false /* fPermitInaccessible */,
4654 false /* aSetError */,
4655 &pMachine);
4656 if (SUCCEEDED(rc))
4657 {
4658 AutoCaller machineCaller(pMachine);
4659 if (SUCCEEDED(machineCaller.rc()))
4660 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4661 }
4662 }
4663}
4664
4665/**
4666 * Marks the registry for @a uuid as unmodified, so that it's not saved in
4667 * a later call to saveModifiedRegistries().
4668 *
4669 * @param uuid
4670 */
4671void VirtualBox::i_unmarkRegistryModified(const Guid &uuid)
4672{
4673 uint64_t uOld;
4674 if (uuid == i_getGlobalRegistryId())
4675 {
4676 for (;;)
4677 {
4678 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4679 if (!uOld)
4680 break;
4681 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4682 break;
4683 ASMNopPause();
4684 }
4685 }
4686 else
4687 {
4688 ComObjPtr<Machine> pMachine;
4689 HRESULT rc = i_findMachine(uuid,
4690 false /* fPermitInaccessible */,
4691 false /* aSetError */,
4692 &pMachine);
4693 if (SUCCEEDED(rc))
4694 {
4695 AutoCaller machineCaller(pMachine);
4696 if (SUCCEEDED(machineCaller.rc()))
4697 {
4698 for (;;)
4699 {
4700 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4701 if (!uOld)
4702 break;
4703 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4704 break;
4705 ASMNopPause();
4706 }
4707 }
4708 }
4709 }
4710}
4711
4712/**
4713 * Saves all settings files according to the modified flags in the Machine
4714 * objects and in the VirtualBox object.
4715 *
4716 * This locks machines and the VirtualBox object as necessary, so better not
4717 * hold any locks before calling this.
4718 *
4719 * @return
4720 */
4721void VirtualBox::i_saveModifiedRegistries()
4722{
4723 HRESULT rc = S_OK;
4724 bool fNeedsGlobalSettings = false;
4725 uint64_t uOld;
4726
4727 {
4728 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4729 for (MachinesOList::iterator it = m->allMachines.begin();
4730 it != m->allMachines.end();
4731 ++it)
4732 {
4733 const ComObjPtr<Machine> &pMachine = *it;
4734
4735 for (;;)
4736 {
4737 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4738 if (!uOld)
4739 break;
4740 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4741 break;
4742 ASMNopPause();
4743 }
4744 if (uOld)
4745 {
4746 AutoCaller autoCaller(pMachine);
4747 if (FAILED(autoCaller.rc()))
4748 continue;
4749 /* object is already dead, no point in saving settings */
4750 if (getObjectState().getState() != ObjectState::Ready)
4751 continue;
4752 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
4753 rc = pMachine->i_saveSettings(&fNeedsGlobalSettings,
4754 Machine::SaveS_Force); // caller said save, so stop arguing
4755 }
4756 }
4757 }
4758
4759 for (;;)
4760 {
4761 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4762 if (!uOld)
4763 break;
4764 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4765 break;
4766 ASMNopPause();
4767 }
4768 if (uOld || fNeedsGlobalSettings)
4769 {
4770 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4771 rc = i_saveSettings();
4772 }
4773 NOREF(rc); /* XXX */
4774}
4775
4776
4777/* static */
4778const com::Utf8Str &VirtualBox::i_getVersionNormalized()
4779{
4780 return sVersionNormalized;
4781}
4782
4783/**
4784 * Checks if the path to the specified file exists, according to the path
4785 * information present in the file name. Optionally the path is created.
4786 *
4787 * Note that the given file name must contain the full path otherwise the
4788 * extracted relative path will be created based on the current working
4789 * directory which is normally unknown.
4790 *
4791 * @param aFileName Full file name which path is checked/created.
4792 * @param aCreate Flag if the path should be created if it doesn't exist.
4793 *
4794 * @return Extended error information on failure to check/create the path.
4795 */
4796/* static */
4797HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4798{
4799 Utf8Str strDir(strFileName);
4800 strDir.stripFilename();
4801 if (!RTDirExists(strDir.c_str()))
4802 {
4803 if (fCreate)
4804 {
4805 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4806 if (RT_FAILURE(vrc))
4807 return i_setErrorStatic(VBOX_E_IPRT_ERROR,
4808 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4809 strDir.c_str(),
4810 vrc));
4811 }
4812 else
4813 return i_setErrorStatic(VBOX_E_IPRT_ERROR,
4814 Utf8StrFmt(tr("Directory '%s' does not exist"),
4815 strDir.c_str()));
4816 }
4817
4818 return S_OK;
4819}
4820
4821const Utf8Str& VirtualBox::i_settingsFilePath()
4822{
4823 return m->strSettingsFilePath;
4824}
4825
4826/**
4827 * Returns the lock handle which protects the machines list. As opposed
4828 * to version 3.1 and earlier, these lists are no longer protected by the
4829 * VirtualBox lock, but by this more specialized lock. Mind the locking
4830 * order: always request this lock after the VirtualBox object lock but
4831 * before the locks of any machine object. See AutoLock.h.
4832 */
4833RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
4834{
4835 return m->lockMachines;
4836}
4837
4838/**
4839 * Returns the lock handle which protects the media trees (hard disks,
4840 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4841 * are no longer protected by the VirtualBox lock, but by this more
4842 * specialized lock. Mind the locking order: always request this lock
4843 * after the VirtualBox object lock but before the locks of the media
4844 * objects contained in these lists. See AutoLock.h.
4845 */
4846RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
4847{
4848 return m->lockMedia;
4849}
4850
4851/**
4852 * Thread function that handles custom events posted using #postEvent().
4853 */
4854// static
4855DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4856{
4857 LogFlowFuncEnter();
4858
4859 AssertReturn(pvUser, VERR_INVALID_POINTER);
4860
4861 HRESULT hr = com::Initialize();
4862 if (FAILED(hr))
4863 return VERR_COM_UNEXPECTED;
4864
4865 int rc = VINF_SUCCESS;
4866
4867 try
4868 {
4869 /* Create an event queue for the current thread. */
4870 EventQueue *pEventQueue = new EventQueue();
4871 AssertPtr(pEventQueue);
4872
4873 /* Return the queue to the one who created this thread. */
4874 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
4875
4876 /* signal that we're ready. */
4877 RTThreadUserSignal(thread);
4878
4879 /*
4880 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4881 * we must not stop processing events and delete the pEventQueue object. This must
4882 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4883 * See @bugref{5724}.
4884 */
4885 for (;;)
4886 {
4887 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
4888 if (rc == VERR_INTERRUPTED)
4889 {
4890 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
4891 rc = VINF_SUCCESS; /* Set success when exiting. */
4892 break;
4893 }
4894 }
4895
4896 delete pEventQueue;
4897 }
4898 catch (std::bad_alloc &ba)
4899 {
4900 rc = VERR_NO_MEMORY;
4901 NOREF(ba);
4902 }
4903
4904 com::Shutdown();
4905
4906 LogFlowFuncLeaveRC(rc);
4907 return rc;
4908}
4909
4910
4911////////////////////////////////////////////////////////////////////////////////
4912
4913/**
4914 * Takes the current list of registered callbacks of the managed VirtualBox
4915 * instance, and calls #handleCallback() for every callback item from the
4916 * list, passing the item as an argument.
4917 *
4918 * @note Locks the managed VirtualBox object for reading but leaves the lock
4919 * before iterating over callbacks and calling their methods.
4920 */
4921void *VirtualBox::CallbackEvent::handler()
4922{
4923 if (!mVirtualBox)
4924 return NULL;
4925
4926 AutoCaller autoCaller(mVirtualBox);
4927 if (!autoCaller.isOk())
4928 {
4929 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4930 mVirtualBox->getObjectState().getState()));
4931 /* We don't need mVirtualBox any more, so release it */
4932 mVirtualBox = NULL;
4933 return NULL;
4934 }
4935
4936 {
4937 VBoxEventDesc evDesc;
4938 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4939
4940 evDesc.fire(/* don't wait for delivery */0);
4941 }
4942
4943 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4944 return NULL;
4945}
4946
4947//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4948//{
4949// return E_NOTIMPL;
4950//}
4951
4952HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
4953 ComPtr<IDHCPServer> &aServer)
4954{
4955 ComObjPtr<DHCPServer> dhcpServer;
4956 dhcpServer.createObject();
4957 HRESULT rc = dhcpServer->init(this, Bstr(aName).raw());
4958 if (FAILED(rc)) return rc;
4959
4960 rc = i_registerDHCPServer(dhcpServer, true);
4961 if (FAILED(rc)) return rc;
4962
4963 dhcpServer.queryInterfaceTo(aServer.asOutParam());
4964
4965 return rc;
4966}
4967
4968HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
4969 ComPtr<IDHCPServer> &aServer)
4970{
4971 HRESULT rc = S_OK;
4972 ComPtr<DHCPServer> found;
4973
4974 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4975
4976 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4977 it != m->allDHCPServers.end();
4978 ++it)
4979 {
4980 Bstr bstr;
4981 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4982 if (FAILED(rc)) return rc;
4983
4984 if (bstr == Bstr(aName).raw())
4985 {
4986 found = *it;
4987 break;
4988 }
4989 }
4990
4991 if (!found)
4992 return E_INVALIDARG;
4993
4994 rc = found.queryInterfaceTo(aServer.asOutParam());
4995
4996 return rc;
4997}
4998
4999HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
5000{
5001 IDHCPServer *aP = aServer;
5002
5003 HRESULT rc = i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
5004
5005 return rc;
5006}
5007
5008/**
5009 * Remembers the given DHCP server in the settings.
5010 *
5011 * @param aDHCPServer DHCP server object to remember.
5012 * @param aSaveSettings @c true to save settings to disk (default).
5013 *
5014 * When @a aSaveSettings is @c true, this operation may fail because of the
5015 * failed #saveSettings() method it calls. In this case, the dhcp server object
5016 * will not be remembered. It is therefore the responsibility of the caller to
5017 * call this method as the last step of some action that requires registration
5018 * in order to make sure that only fully functional dhcp server objects get
5019 * registered.
5020 *
5021 * @note Locks this object for writing and @a aDHCPServer for reading.
5022 */
5023HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
5024 bool aSaveSettings /*= true*/)
5025{
5026 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5027
5028 AutoCaller autoCaller(this);
5029 AssertComRCReturnRC(autoCaller.rc());
5030
5031 // Acquire a lock on the VirtualBox object early to avoid lock order issues
5032 // when we call i_saveSettings() later on.
5033 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5034 // need it below, in findDHCPServerByNetworkName (reading) and in
5035 // m->allDHCPServers.addChild, so need to get it here to avoid lock
5036 // order trouble with dhcpServerCaller
5037 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5038
5039 AutoCaller dhcpServerCaller(aDHCPServer);
5040 AssertComRCReturnRC(dhcpServerCaller.rc());
5041
5042 Bstr name;
5043 com::Utf8Str uname;
5044 HRESULT rc = S_OK;
5045 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
5046 if (FAILED(rc)) return rc;
5047 uname = Utf8Str(name);
5048
5049 ComPtr<IDHCPServer> existing;
5050 rc = findDHCPServerByNetworkName(uname, existing);
5051 if (SUCCEEDED(rc))
5052 return E_INVALIDARG;
5053 rc = S_OK;
5054
5055 m->allDHCPServers.addChild(aDHCPServer);
5056 // we need to release the list lock before we attempt to acquire locks
5057 // on other objects in i_saveSettings (see @bugref{7500})
5058 alock.release();
5059
5060 if (aSaveSettings)
5061 {
5062 // we acquired the lock on 'this' earlier to avoid lock order issues
5063 rc = i_saveSettings();
5064
5065 if (FAILED(rc))
5066 {
5067 alock.acquire();
5068 m->allDHCPServers.removeChild(aDHCPServer);
5069 }
5070 }
5071
5072 return rc;
5073}
5074
5075/**
5076 * Removes the given DHCP server from the settings.
5077 *
5078 * @param aDHCPServer DHCP server object to remove.
5079 *
5080 * This operation may fail because of the failed #saveSettings() method it
5081 * calls. In this case, the DHCP server will NOT be removed from the settings
5082 * when this method returns.
5083 *
5084 * @note Locks this object for writing.
5085 */
5086HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
5087{
5088 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5089
5090 AutoCaller autoCaller(this);
5091 AssertComRCReturnRC(autoCaller.rc());
5092
5093 AutoCaller dhcpServerCaller(aDHCPServer);
5094 AssertComRCReturnRC(dhcpServerCaller.rc());
5095
5096 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5097 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5098 m->allDHCPServers.removeChild(aDHCPServer);
5099 // we need to release the list lock before we attempt to acquire locks
5100 // on other objects in i_saveSettings (see @bugref{7500})
5101 alock.release();
5102
5103 HRESULT rc = i_saveSettings();
5104
5105 // undo the changes if we failed to save them
5106 if (FAILED(rc))
5107 {
5108 alock.acquire();
5109 m->allDHCPServers.addChild(aDHCPServer);
5110 }
5111
5112 return rc;
5113}
5114
5115
5116/**
5117 * NAT Network
5118 */
5119HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
5120 ComPtr<INATNetwork> &aNetwork)
5121{
5122#ifdef VBOX_WITH_NAT_SERVICE
5123 ComObjPtr<NATNetwork> natNetwork;
5124 natNetwork.createObject();
5125 HRESULT rc = natNetwork->init(this, Bstr(aNetworkName).raw());
5126 if (FAILED(rc)) return rc;
5127
5128 rc = i_registerNATNetwork(natNetwork, true);
5129 if (FAILED(rc)) return rc;
5130
5131 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
5132
5133 fireNATNetworkCreationDeletionEvent(m->pEventSource, Bstr(aNetworkName).raw(), TRUE);
5134
5135 return rc;
5136#else
5137 NOREF(aName);
5138 NOREF(aNatNetwork);
5139 return E_NOTIMPL;
5140#endif
5141}
5142
5143HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
5144 ComPtr<INATNetwork> &aNetwork)
5145{
5146#ifdef VBOX_WITH_NAT_SERVICE
5147
5148 HRESULT rc = S_OK;
5149 ComPtr<NATNetwork> found;
5150
5151 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5152
5153 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
5154 it != m->allNATNetworks.end();
5155 ++it)
5156 {
5157 Bstr bstr;
5158 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
5159 if (FAILED(rc)) return rc;
5160
5161 if (bstr == Bstr(aNetworkName).raw())
5162 {
5163 found = *it;
5164 break;
5165 }
5166 }
5167
5168 if (!found)
5169 return E_INVALIDARG;
5170 found.queryInterfaceTo(aNetwork.asOutParam());
5171 return rc;
5172#else
5173 NOREF(aName);
5174 NOREF(aNetworkName);
5175 return E_NOTIMPL;
5176#endif
5177}
5178
5179HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
5180{
5181#ifdef VBOX_WITH_NAT_SERVICE
5182 Bstr name;
5183 HRESULT rc = S_OK;
5184 INATNetwork *iNw = aNetwork;
5185 NATNetwork *network = static_cast<NATNetwork *>(iNw);
5186 rc = network->COMGETTER(NetworkName)(name.asOutParam());
5187 rc = i_unregisterNATNetwork(network, true);
5188 fireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
5189 return rc;
5190#else
5191 NOREF(aNetwork);
5192 return E_NOTIMPL;
5193#endif
5194
5195}
5196/**
5197 * Remembers the given NAT network in the settings.
5198 *
5199 * @param aNATNetwork NAT Network object to remember.
5200 * @param aSaveSettings @c true to save settings to disk (default).
5201 *
5202 *
5203 * @note Locks this object for writing and @a aNATNetwork for reading.
5204 */
5205HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
5206 bool aSaveSettings /*= true*/)
5207{
5208#ifdef VBOX_WITH_NAT_SERVICE
5209 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5210
5211 AutoCaller autoCaller(this);
5212 AssertComRCReturnRC(autoCaller.rc());
5213
5214 AutoCaller natNetworkCaller(aNATNetwork);
5215 AssertComRCReturnRC(natNetworkCaller.rc());
5216
5217 Bstr name;
5218 HRESULT rc;
5219 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5220 AssertComRCReturnRC(rc);
5221
5222 /* returned value isn't 0 and aSaveSettings is true
5223 * means that we create duplicate, otherwise we just load settings.
5224 */
5225 if ( sNatNetworkNameToRefCount[name]
5226 && aSaveSettings)
5227 AssertComRCReturnRC(E_INVALIDARG);
5228
5229 rc = S_OK;
5230
5231 sNatNetworkNameToRefCount[name] = 0;
5232
5233 m->allNATNetworks.addChild(aNATNetwork);
5234
5235 if (aSaveSettings)
5236 {
5237 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5238 rc = i_saveSettings();
5239 vboxLock.release();
5240
5241 if (FAILED(rc))
5242 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
5243 }
5244
5245 return rc;
5246#else
5247 NOREF(aNATNetwork);
5248 NOREF(aSaveSettings);
5249 /* No panic please (silently ignore) */
5250 return S_OK;
5251#endif
5252}
5253
5254/**
5255 * Removes the given NAT network from the settings.
5256 *
5257 * @param aNATNetwork NAT network object to remove.
5258 * @param aSaveSettings @c true to save settings to disk (default).
5259 *
5260 * When @a aSaveSettings is @c true, this operation may fail because of the
5261 * failed #saveSettings() method it calls. In this case, the DHCP server
5262 * will NOT be removed from the settingsi when this method returns.
5263 *
5264 * @note Locks this object for writing.
5265 */
5266HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
5267 bool aSaveSettings /*= true*/)
5268{
5269#ifdef VBOX_WITH_NAT_SERVICE
5270 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5271
5272 AutoCaller autoCaller(this);
5273 AssertComRCReturnRC(autoCaller.rc());
5274
5275 AutoCaller natNetworkCaller(aNATNetwork);
5276 AssertComRCReturnRC(natNetworkCaller.rc());
5277
5278 Bstr name;
5279 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5280 /* Hm, there're still running clients. */
5281 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
5282 AssertComRCReturnRC(E_INVALIDARG);
5283
5284 m->allNATNetworks.removeChild(aNATNetwork);
5285
5286 if (aSaveSettings)
5287 {
5288 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5289 rc = i_saveSettings();
5290 vboxLock.release();
5291
5292 if (FAILED(rc))
5293 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
5294 }
5295
5296 return rc;
5297#else
5298 NOREF(aNATNetwork);
5299 NOREF(aSaveSettings);
5300 return E_NOTIMPL;
5301#endif
5302}
5303
5304
5305#ifdef RT_OS_WINDOWS
5306#include <psapi.h>
5307
5308/**
5309 * Report versions of installed drivers to release log.
5310 */
5311void VirtualBox::i_reportDriverVersions()
5312{
5313 DWORD err;
5314 HRESULT hrc;
5315 LPVOID aDrivers[1024];
5316 LPVOID *pDrivers = aDrivers;
5317 UINT cNeeded = 0;
5318 TCHAR szSystemRoot[MAX_PATH];
5319 TCHAR *pszSystemRoot = szSystemRoot;
5320 LPVOID pVerInfo = NULL;
5321 DWORD cbVerInfo = 0;
5322
5323 do
5324 {
5325 cNeeded = GetWindowsDirectory(szSystemRoot, RT_ELEMENTS(szSystemRoot));
5326 if (cNeeded == 0)
5327 {
5328 err = GetLastError();
5329 hrc = HRESULT_FROM_WIN32(err);
5330 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
5331 hrc, hrc, err));
5332 break;
5333 }
5334 else if (cNeeded > RT_ELEMENTS(szSystemRoot))
5335 {
5336 /* The buffer is too small, allocate big one. */
5337 pszSystemRoot = (TCHAR *)RTMemTmpAlloc(cNeeded * sizeof(_TCHAR));
5338 if (!pszSystemRoot)
5339 {
5340 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cNeeded));
5341 break;
5342 }
5343 if (GetWindowsDirectory(pszSystemRoot, cNeeded) == 0)
5344 {
5345 err = GetLastError();
5346 hrc = HRESULT_FROM_WIN32(err);
5347 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
5348 hrc, hrc, err));
5349 break;
5350 }
5351 }
5352
5353 DWORD cbNeeded = 0;
5354 if (!EnumDeviceDrivers(aDrivers, sizeof(aDrivers), &cbNeeded) || cbNeeded > sizeof(aDrivers))
5355 {
5356 pDrivers = (LPVOID *)RTMemTmpAlloc(cbNeeded);
5357 if (!EnumDeviceDrivers(pDrivers, cbNeeded, &cbNeeded))
5358 {
5359 err = GetLastError();
5360 hrc = HRESULT_FROM_WIN32(err);
5361 AssertLogRelMsgFailed(("EnumDeviceDrivers failed, hr=%Rhrc (0x%x) err=%u\n",
5362 hrc, hrc, err));
5363 break;
5364 }
5365 }
5366
5367 LogRel(("Installed Drivers:\n"));
5368
5369 TCHAR szDriver[1024];
5370 int cDrivers = cbNeeded / sizeof(pDrivers[0]);
5371 for (int i = 0; i < cDrivers; i++)
5372 {
5373 if (GetDeviceDriverBaseName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
5374 {
5375 if (_tcsnicmp(TEXT("vbox"), szDriver, 4))
5376 continue;
5377 }
5378 else
5379 continue;
5380 if (GetDeviceDriverFileName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
5381 {
5382 _TCHAR szTmpDrv[1024];
5383 _TCHAR *pszDrv = szDriver;
5384 if (!_tcsncmp(TEXT("\\SystemRoot"), szDriver, 11))
5385 {
5386 _tcscpy_s(szTmpDrv, pszSystemRoot);
5387 _tcsncat_s(szTmpDrv, szDriver + 11, sizeof(szTmpDrv) / sizeof(szTmpDrv[0]) - _tclen(pszSystemRoot));
5388 pszDrv = szTmpDrv;
5389 }
5390 else if (!_tcsncmp(TEXT("\\??\\"), szDriver, 4))
5391 pszDrv = szDriver + 4;
5392
5393 /* Allocate a buffer for version info. Reuse if large enough. */
5394 DWORD cbNewVerInfo = GetFileVersionInfoSize(pszDrv, NULL);
5395 if (cbNewVerInfo > cbVerInfo)
5396 {
5397 if (pVerInfo)
5398 RTMemTmpFree(pVerInfo);
5399 cbVerInfo = cbNewVerInfo;
5400 pVerInfo = RTMemTmpAlloc(cbVerInfo);
5401 if (!pVerInfo)
5402 {
5403 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cbVerInfo));
5404 break;
5405 }
5406 }
5407
5408 if (GetFileVersionInfo(pszDrv, NULL, cbVerInfo, pVerInfo))
5409 {
5410 UINT cbSize = 0;
5411 LPBYTE lpBuffer = NULL;
5412 if (VerQueryValue(pVerInfo, TEXT("\\"), (VOID FAR* FAR*)&lpBuffer, &cbSize))
5413 {
5414 if (cbSize)
5415 {
5416 VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
5417 if (pFileInfo->dwSignature == 0xfeef04bd)
5418 {
5419 LogRel((" %ls (Version: %d.%d.%d.%d)\n", pszDrv,
5420 (pFileInfo->dwFileVersionMS >> 16) & 0xffff,
5421 (pFileInfo->dwFileVersionMS >> 0) & 0xffff,
5422 (pFileInfo->dwFileVersionLS >> 16) & 0xffff,
5423 (pFileInfo->dwFileVersionLS >> 0) & 0xffff));
5424 }
5425 }
5426 }
5427 }
5428 }
5429 }
5430
5431 }
5432 while (0);
5433
5434 if (pVerInfo)
5435 RTMemTmpFree(pVerInfo);
5436
5437 if (pDrivers != aDrivers)
5438 RTMemTmpFree(pDrivers);
5439
5440 if (pszSystemRoot != szSystemRoot)
5441 RTMemTmpFree(pszSystemRoot);
5442}
5443#else /* !RT_OS_WINDOWS */
5444void VirtualBox::i_reportDriverVersions(void)
5445{
5446}
5447#endif /* !RT_OS_WINDOWS */
5448
5449/* 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