VirtualBox

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

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

Main/VirtualBox: eliminate VBoxComEvents use

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

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