VirtualBox

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

Last change on this file since 97698 was 97523, checked in by vboxsync, 2 years ago

Main: Add new OnMachineGroupsChanged event which fires when the groups of a machine change, bugref:10276

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

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