VirtualBox

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

Last change on this file since 94721 was 94721, checked in by vboxsync, 3 years ago

Main: Implement loading and unloading of the cryptographic support module from the extension pack, bugref:9955 [build fix]

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

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