VirtualBox

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

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

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 214.3 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 96407 2022-08-22 17:43:14Z 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 Locks this object for reading.
3478 */
3479BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, const Utf8Str &aKey, const Utf8Str &aValue, Bstr &aError)
3480{
3481 LogFlowThisFunc(("machine={%RTuuid} aKey={%s} aValue={%s}\n", aId.raw(), aKey.c_str(), aValue.c_str()));
3482
3483 AutoCaller autoCaller(this);
3484 AssertComRCReturn(autoCaller.rc(), FALSE);
3485
3486 ComPtr<IEvent> ptrEvent;
3487 HRESULT hrc = ::CreateExtraDataCanChangeEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aKey, aValue);
3488 AssertComRCReturn(hrc, TRUE);
3489
3490 VBoxEventDesc EvtDesc(ptrEvent, m->pEventSource);
3491 BOOL fDelivered = EvtDesc.fire(3000); /* Wait up to 3 secs for delivery */
3492 //Assert(fDelivered);
3493 BOOL fAllowChange = TRUE;
3494 if (fDelivered)
3495 {
3496 ComPtr<IExtraDataCanChangeEvent> ptrCanChangeEvent = ptrEvent;
3497 Assert(ptrCanChangeEvent);
3498
3499 BOOL fVetoed = FALSE;
3500 ptrCanChangeEvent->IsVetoed(&fVetoed);
3501 fAllowChange = !fVetoed;
3502
3503 if (!fAllowChange)
3504 {
3505 SafeArray<BSTR> aVetos;
3506 ptrCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
3507 if (aVetos.size() > 0)
3508 aError = aVetos[0];
3509 }
3510 }
3511
3512 LogFlowThisFunc(("fAllowChange=%RTbool\n", fAllowChange));
3513 return fAllowChange;
3514}
3515
3516/**
3517 * @note Doesn't lock any object.
3518 */
3519void VirtualBox::i_onExtraDataChanged(const Guid &aId, const Utf8Str &aKey, const Utf8Str &aValue)
3520{
3521 ComPtr<IEvent> ptrEvent;
3522 HRESULT hrc = ::CreateExtraDataChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aKey, aValue);
3523 AssertComRCReturnVoid(hrc);
3524 i_postEvent(new AsyncEvent(this, ptrEvent));
3525}
3526
3527/**
3528 * @note Doesn't lock any object.
3529 */
3530void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
3531{
3532 ComPtr<IEvent> ptrEvent;
3533 HRESULT hrc = ::CreateMachineRegisteredEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aRegistered);
3534 AssertComRCReturnVoid(hrc);
3535 i_postEvent(new AsyncEvent(this, ptrEvent));
3536}
3537
3538/**
3539 * @note Doesn't lock any object.
3540 */
3541void VirtualBox::i_onSessionStateChanged(const Guid &aId, SessionState_T aState)
3542{
3543 ComPtr<IEvent> ptrEvent;
3544 HRESULT hrc = ::CreateSessionStateChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aState);
3545 AssertComRCReturnVoid(hrc);
3546 i_postEvent(new AsyncEvent(this, ptrEvent));
3547}
3548
3549/**
3550 * @note Doesn't lock any object.
3551 */
3552void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
3553{
3554 ComPtr<IEvent> ptrEvent;
3555 HRESULT hrc = ::CreateSnapshotTakenEvent(ptrEvent.asOutParam(), m->pEventSource,
3556 aMachineId.toString(), aSnapshotId.toString());
3557 AssertComRCReturnVoid(hrc);
3558 i_postEvent(new AsyncEvent(this, ptrEvent));
3559}
3560
3561/**
3562 * @note Doesn't lock any object.
3563 */
3564void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
3565{
3566 ComPtr<IEvent> ptrEvent;
3567 HRESULT hrc = ::CreateSnapshotDeletedEvent(ptrEvent.asOutParam(), m->pEventSource,
3568 aMachineId.toString(), aSnapshotId.toString());
3569 AssertComRCReturnVoid(hrc);
3570 i_postEvent(new AsyncEvent(this, ptrEvent));
3571}
3572
3573/**
3574 * @note Doesn't lock any object.
3575 */
3576void VirtualBox::i_onSnapshotRestored(const Guid &aMachineId, const Guid &aSnapshotId)
3577{
3578 ComPtr<IEvent> ptrEvent;
3579 HRESULT hrc = ::CreateSnapshotRestoredEvent(ptrEvent.asOutParam(), m->pEventSource,
3580 aMachineId.toString(), aSnapshotId.toString());
3581 AssertComRCReturnVoid(hrc);
3582 i_postEvent(new AsyncEvent(this, ptrEvent));
3583}
3584
3585/**
3586 * @note Doesn't lock any object.
3587 */
3588void VirtualBox::i_onSnapshotChanged(const Guid &aMachineId, const Guid &aSnapshotId)
3589{
3590 ComPtr<IEvent> ptrEvent;
3591 HRESULT hrc = ::CreateSnapshotChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
3592 aMachineId.toString(), aSnapshotId.toString());
3593 AssertComRCReturnVoid(hrc);
3594 i_postEvent(new AsyncEvent(this, ptrEvent));
3595}
3596
3597/**
3598 * @note Doesn't lock any object.
3599 */
3600void VirtualBox::i_onGuestPropertyChanged(const Guid &aMachineId, const Utf8Str &aName, const Utf8Str &aValue,
3601 const Utf8Str &aFlags, const BOOL fWasDeleted)
3602{
3603 ComPtr<IEvent> ptrEvent;
3604 HRESULT hrc = ::CreateGuestPropertyChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
3605 aMachineId.toString(), aName, aValue, aFlags, fWasDeleted);
3606 AssertComRCReturnVoid(hrc);
3607 i_postEvent(new AsyncEvent(this, ptrEvent));
3608}
3609
3610/**
3611 * @note Doesn't lock any object.
3612 */
3613void VirtualBox::i_onNatRedirectChanged(const Guid &aMachineId, ULONG ulSlot, bool fRemove, const Utf8Str &aName,
3614 NATProtocol_T aProto, const Utf8Str &aHostIp, uint16_t aHostPort,
3615 const Utf8Str &aGuestIp, uint16_t aGuestPort)
3616{
3617 ::FireNATRedirectEvent(m->pEventSource, aMachineId.toString(), ulSlot, fRemove, aName, aProto, aHostIp,
3618 aHostPort, aGuestIp, aGuestPort);
3619}
3620
3621/** @todo Unused!! */
3622void VirtualBox::i_onNATNetworkChanged(const Utf8Str &aName)
3623{
3624 ::FireNATNetworkChangedEvent(m->pEventSource, aName);
3625}
3626
3627void VirtualBox::i_onNATNetworkStartStop(const Utf8Str &aName, BOOL fStart)
3628{
3629 ::FireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
3630}
3631
3632void VirtualBox::i_onNATNetworkSetting(const Utf8Str &aNetworkName, BOOL aEnabled,
3633 const Utf8Str &aNetwork, const Utf8Str &aGateway,
3634 BOOL aAdvertiseDefaultIpv6RouteEnabled,
3635 BOOL fNeedDhcpServer)
3636{
3637 ::FireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled, aNetwork, aGateway,
3638 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
3639}
3640
3641void VirtualBox::i_onNATNetworkPortForward(const Utf8Str &aNetworkName, BOOL create, BOOL fIpv6,
3642 const Utf8Str &aRuleName, NATProtocol_T proto,
3643 const Utf8Str &aHostIp, LONG aHostPort,
3644 const Utf8Str &aGuestIp, LONG aGuestPort)
3645{
3646 ::FireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create, fIpv6, aRuleName, proto,
3647 aHostIp, aHostPort, aGuestIp, aGuestPort);
3648}
3649
3650
3651void VirtualBox::i_onHostNameResolutionConfigurationChange()
3652{
3653 if (m->pEventSource)
3654 ::FireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
3655}
3656
3657
3658int VirtualBox::i_natNetworkRefInc(const Utf8Str &aNetworkName)
3659{
3660 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3661
3662 if (!sNatNetworkNameToRefCount[aNetworkName])
3663 {
3664 ComPtr<INATNetwork> nat;
3665 HRESULT rc = findNATNetworkByName(aNetworkName, nat);
3666 if (FAILED(rc)) return -1;
3667
3668 rc = nat->Start();
3669 if (SUCCEEDED(rc))
3670 LogRel(("Started NAT network '%s'\n", aNetworkName.c_str()));
3671 else
3672 LogRel(("Error %Rhrc starting NAT network '%s'\n", rc, aNetworkName.c_str()));
3673 AssertComRCReturn(rc, -1);
3674 }
3675
3676 sNatNetworkNameToRefCount[aNetworkName]++;
3677
3678 return sNatNetworkNameToRefCount[aNetworkName];
3679}
3680
3681
3682int VirtualBox::i_natNetworkRefDec(const Utf8Str &aNetworkName)
3683{
3684 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3685
3686 if (!sNatNetworkNameToRefCount[aNetworkName])
3687 return 0;
3688
3689 sNatNetworkNameToRefCount[aNetworkName]--;
3690
3691 if (!sNatNetworkNameToRefCount[aNetworkName])
3692 {
3693 ComPtr<INATNetwork> nat;
3694 HRESULT rc = findNATNetworkByName(aNetworkName, nat);
3695 if (FAILED(rc)) return -1;
3696
3697 rc = nat->Stop();
3698 if (SUCCEEDED(rc))
3699 LogRel(("Stopped NAT network '%s'\n", aNetworkName.c_str()));
3700 else
3701 LogRel(("Error %Rhrc stopping NAT network '%s'\n", rc, aNetworkName.c_str()));
3702 AssertComRCReturn(rc, -1);
3703 }
3704
3705 return sNatNetworkNameToRefCount[aNetworkName];
3706}
3707
3708
3709/*
3710 * Export this to NATNetwork so that its setters can refuse to change
3711 * essential network settings when an VBoxNatNet instance is running.
3712 */
3713RWLockHandle *VirtualBox::i_getNatNetLock() const
3714{
3715 return spMtxNatNetworkNameToRefCountLock;
3716}
3717
3718
3719/*
3720 * Export this to NATNetwork so that its setters can refuse to change
3721 * essential network settings when an VBoxNatNet instance is running.
3722 * The caller is expected to hold a read lock on i_getNatNetLock().
3723 */
3724bool VirtualBox::i_isNatNetStarted(const Utf8Str &aNetworkName) const
3725{
3726 return sNatNetworkNameToRefCount[aNetworkName] > 0;
3727}
3728
3729
3730void VirtualBox::i_onCloudProviderListChanged(BOOL aRegistered)
3731{
3732 ::FireCloudProviderListChangedEvent(m->pEventSource, aRegistered);
3733}
3734
3735
3736void VirtualBox::i_onCloudProviderRegistered(const Utf8Str &aProviderId, BOOL aRegistered)
3737{
3738 ::FireCloudProviderRegisteredEvent(m->pEventSource, aProviderId, aRegistered);
3739}
3740
3741
3742void VirtualBox::i_onCloudProviderUninstall(const Utf8Str &aProviderId)
3743{
3744 HRESULT hrc;
3745
3746 ComPtr<IEvent> pEvent;
3747 hrc = CreateCloudProviderUninstallEvent(pEvent.asOutParam(),
3748 m->pEventSource, aProviderId);
3749 if (FAILED(hrc))
3750 return;
3751
3752 BOOL fDelivered = FALSE;
3753 hrc = m->pEventSource->FireEvent(pEvent, /* :timeout */ 10000, &fDelivered);
3754 if (FAILED(hrc))
3755 return;
3756}
3757
3758void VirtualBox::i_onLanguageChanged(const Utf8Str &aLanguageId)
3759{
3760 ComPtr<IEvent> ptrEvent;
3761 HRESULT hrc = ::CreateLanguageChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aLanguageId);
3762 AssertComRCReturnVoid(hrc);
3763 i_postEvent(new AsyncEvent(this, ptrEvent));
3764}
3765
3766void VirtualBox::i_onProgressCreated(const Guid &aId, BOOL aCreated)
3767{
3768 ::FireProgressCreatedEvent(m->pEventSource, aId.toString(), aCreated);
3769}
3770
3771#ifdef VBOX_WITH_UPDATE_AGENT
3772/**
3773 * @note Doesn't lock any object.
3774 */
3775void VirtualBox::i_onUpdateAgentAvailable(IUpdateAgent *aAgent,
3776 const Utf8Str &aVer, UpdateChannel_T aChannel, UpdateSeverity_T aSev,
3777 const Utf8Str &aDownloadURL, const Utf8Str &aWebURL, const Utf8Str &aReleaseNotes)
3778{
3779 ::FireUpdateAgentAvailableEvent(m->pEventSource, aAgent, aVer, aChannel, aSev,
3780 aDownloadURL, aWebURL, aReleaseNotes);
3781}
3782
3783/**
3784 * @note Doesn't lock any object.
3785 */
3786void VirtualBox::i_onUpdateAgentError(IUpdateAgent *aAgent, const Utf8Str &aErrMsg, LONG aRc)
3787{
3788 ::FireUpdateAgentErrorEvent(m->pEventSource, aAgent, aErrMsg, aRc);
3789}
3790
3791/**
3792 * @note Doesn't lock any object.
3793 */
3794void VirtualBox::i_onUpdateAgentStateChanged(IUpdateAgent *aAgent, UpdateState_T aState)
3795{
3796 ::FireUpdateAgentStateChangedEvent(m->pEventSource, aAgent, aState);
3797}
3798
3799/**
3800 * @note Doesn't lock any object.
3801 */
3802void VirtualBox::i_onUpdateAgentSettingsChanged(IUpdateAgent *aAgent, const Utf8Str &aAttributeHint)
3803{
3804 ::FireUpdateAgentSettingsChangedEvent(m->pEventSource, aAgent, aAttributeHint);
3805}
3806#endif /* VBOX_WITH_UPDATE_AGENT */
3807
3808/**
3809 * @note Locks the list of other objects for reading.
3810 */
3811ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
3812{
3813 ComObjPtr<GuestOSType> type;
3814
3815 /* unknown type must always be the first */
3816 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
3817
3818 return m->allGuestOSTypes.front();
3819}
3820
3821/**
3822 * Returns the list of opened machines (machines having VM sessions opened,
3823 * ignoring other sessions) and optionally the list of direct session controls.
3824 *
3825 * @param aMachines Where to put opened machines (will be empty if none).
3826 * @param aControls Where to put direct session controls (optional).
3827 *
3828 * @note The returned lists contain smart pointers. So, clear it as soon as
3829 * it becomes no more necessary to release instances.
3830 *
3831 * @note It can be possible that a session machine from the list has been
3832 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
3833 * when accessing unprotected data directly.
3834 *
3835 * @note Locks objects for reading.
3836 */
3837void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
3838 InternalControlList *aControls /*= NULL*/)
3839{
3840 AutoCaller autoCaller(this);
3841 AssertComRCReturnVoid(autoCaller.rc());
3842
3843 aMachines.clear();
3844 if (aControls)
3845 aControls->clear();
3846
3847 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3848
3849 for (MachinesOList::iterator it = m->allMachines.begin();
3850 it != m->allMachines.end();
3851 ++it)
3852 {
3853 ComObjPtr<SessionMachine> sm;
3854 ComPtr<IInternalSessionControl> ctl;
3855 if ((*it)->i_isSessionOpenVM(sm, &ctl))
3856 {
3857 aMachines.push_back(sm);
3858 if (aControls)
3859 aControls->push_back(ctl);
3860 }
3861 }
3862}
3863
3864/**
3865 * Gets a reference to the machine list. This is the real thing, not a copy,
3866 * so bad things will happen if the caller doesn't hold the necessary lock.
3867 *
3868 * @returns reference to machine list
3869 *
3870 * @note Caller must hold the VirtualBox object lock at least for reading.
3871 */
3872VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
3873{
3874 return m->allMachines;
3875}
3876
3877/**
3878 * Searches for a machine object with the given ID in the collection
3879 * of registered machines.
3880 *
3881 * @param aId Machine UUID to look for.
3882 * @param fPermitInaccessible If true, inaccessible machines will be found;
3883 * if false, this will fail if the given machine is inaccessible.
3884 * @param aSetError If true, set errorinfo if the machine is not found.
3885 * @param aMachine Returned machine, if found.
3886 * @return
3887 */
3888HRESULT VirtualBox::i_findMachine(const Guid &aId,
3889 bool fPermitInaccessible,
3890 bool aSetError,
3891 ComObjPtr<Machine> *aMachine /* = NULL */)
3892{
3893 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3894
3895 AutoCaller autoCaller(this);
3896 AssertComRCReturnRC(autoCaller.rc());
3897
3898 {
3899 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3900
3901 for (MachinesOList::iterator it = m->allMachines.begin();
3902 it != m->allMachines.end();
3903 ++it)
3904 {
3905 ComObjPtr<Machine> pMachine = *it;
3906
3907 if (!fPermitInaccessible)
3908 {
3909 // skip inaccessible machines
3910 AutoCaller machCaller(pMachine);
3911 if (FAILED(machCaller.rc()))
3912 continue;
3913 }
3914
3915 if (pMachine->i_getId() == aId)
3916 {
3917 rc = S_OK;
3918 if (aMachine)
3919 *aMachine = pMachine;
3920 break;
3921 }
3922 }
3923 }
3924
3925 if (aSetError && FAILED(rc))
3926 rc = setError(rc,
3927 tr("Could not find a registered machine with UUID {%RTuuid}"),
3928 aId.raw());
3929
3930 return rc;
3931}
3932
3933/**
3934 * Searches for a machine object with the given name or location in the
3935 * collection of registered machines.
3936 *
3937 * @param aName Machine name or location to look for.
3938 * @param aSetError If true, set errorinfo if the machine is not found.
3939 * @param aMachine Returned machine, if found.
3940 * @return
3941 */
3942HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
3943 bool aSetError,
3944 ComObjPtr<Machine> *aMachine /* = NULL */)
3945{
3946 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3947
3948 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3949 for (MachinesOList::iterator it = m->allMachines.begin();
3950 it != m->allMachines.end();
3951 ++it)
3952 {
3953 ComObjPtr<Machine> &pMachine = *it;
3954 AutoCaller machCaller(pMachine);
3955 if (!machCaller.isOk())
3956 continue; // we can't ask inaccessible machines for their names
3957
3958 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
3959 if (pMachine->i_getName() == aName)
3960 {
3961 rc = S_OK;
3962 if (aMachine)
3963 *aMachine = pMachine;
3964 break;
3965 }
3966 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
3967 {
3968 rc = S_OK;
3969 if (aMachine)
3970 *aMachine = pMachine;
3971 break;
3972 }
3973 }
3974
3975 if (aSetError && FAILED(rc))
3976 rc = setError(rc,
3977 tr("Could not find a registered machine named '%s'"), aName.c_str());
3978
3979 return rc;
3980}
3981
3982static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
3983{
3984 /* empty strings are invalid */
3985 if (aGroup.isEmpty())
3986 return E_INVALIDARG;
3987 /* the toplevel group is valid */
3988 if (aGroup == "/")
3989 return S_OK;
3990 /* any other strings of length 1 are invalid */
3991 if (aGroup.length() == 1)
3992 return E_INVALIDARG;
3993 /* must start with a slash */
3994 if (aGroup.c_str()[0] != '/')
3995 return E_INVALIDARG;
3996 /* must not end with a slash */
3997 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3998 return E_INVALIDARG;
3999 /* check the group components */
4000 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
4001 while (pStr)
4002 {
4003 char *pSlash = RTStrStr(pStr, "/");
4004 if (pSlash)
4005 {
4006 /* no empty components (or // sequences in other words) */
4007 if (pSlash == pStr)
4008 return E_INVALIDARG;
4009 /* check if the machine name rules are violated, because that means
4010 * the group components are too close to the limits. */
4011 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
4012 Utf8Str tmp2(tmp);
4013 sanitiseMachineFilename(tmp);
4014 if (tmp != tmp2)
4015 return E_INVALIDARG;
4016 if (fPrimary)
4017 {
4018 HRESULT rc = pVirtualBox->i_findMachineByName(tmp,
4019 false /* aSetError */);
4020 if (SUCCEEDED(rc))
4021 return VBOX_E_VM_ERROR;
4022 }
4023 pStr = pSlash + 1;
4024 }
4025 else
4026 {
4027 /* check if the machine name rules are violated, because that means
4028 * the group components is too close to the limits. */
4029 Utf8Str tmp(pStr);
4030 Utf8Str tmp2(tmp);
4031 sanitiseMachineFilename(tmp);
4032 if (tmp != tmp2)
4033 return E_INVALIDARG;
4034 pStr = NULL;
4035 }
4036 }
4037 return S_OK;
4038}
4039
4040/**
4041 * Validates a machine group.
4042 *
4043 * @param aGroup Machine group.
4044 * @param fPrimary Set if this is the primary group.
4045 *
4046 * @return S_OK or E_INVALIDARG
4047 */
4048HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
4049{
4050 HRESULT rc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
4051 if (FAILED(rc))
4052 {
4053 if (rc == VBOX_E_VM_ERROR)
4054 rc = setError(E_INVALIDARG,
4055 tr("Machine group '%s' conflicts with a virtual machine name"),
4056 aGroup.c_str());
4057 else
4058 rc = setError(rc,
4059 tr("Invalid machine group '%s'"),
4060 aGroup.c_str());
4061 }
4062 return rc;
4063}
4064
4065/**
4066 * Takes a list of machine groups, and sanitizes/validates it.
4067 *
4068 * @param aMachineGroups Array with the machine groups.
4069 * @param pllMachineGroups Pointer to list of strings for the result.
4070 *
4071 * @return S_OK or E_INVALIDARG
4072 */
4073HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
4074{
4075 pllMachineGroups->clear();
4076 if (aMachineGroups.size())
4077 {
4078 for (size_t i = 0; i < aMachineGroups.size(); i++)
4079 {
4080 Utf8Str group(aMachineGroups[i]);
4081 if (group.length() == 0)
4082 group = "/";
4083
4084 HRESULT rc = i_validateMachineGroup(group, i == 0);
4085 if (FAILED(rc))
4086 return rc;
4087
4088 /* no duplicates please */
4089 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
4090 == pllMachineGroups->end())
4091 pllMachineGroups->push_back(group);
4092 }
4093 if (pllMachineGroups->size() == 0)
4094 pllMachineGroups->push_back("/");
4095 }
4096 else
4097 pllMachineGroups->push_back("/");
4098
4099 return S_OK;
4100}
4101
4102/**
4103 * Searches for a Medium object with the given ID in the list of registered
4104 * hard disks.
4105 *
4106 * @param aId ID of the hard disk. Must not be empty.
4107 * @param aSetError If @c true , the appropriate error info is set in case
4108 * when the hard disk is not found.
4109 * @param aHardDisk Where to store the found hard disk object (can be NULL).
4110 *
4111 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4112 *
4113 * @note Locks the media tree for reading.
4114 */
4115HRESULT VirtualBox::i_findHardDiskById(const Guid &aId,
4116 bool aSetError,
4117 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
4118{
4119 AssertReturn(!aId.isZero(), E_INVALIDARG);
4120
4121 // we use the hard disks map, but it is protected by the
4122 // hard disk _list_ lock handle
4123 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4124
4125 HardDiskMap::const_iterator it = m->mapHardDisks.find(aId);
4126 if (it != m->mapHardDisks.end())
4127 {
4128 if (aHardDisk)
4129 *aHardDisk = (*it).second;
4130 return S_OK;
4131 }
4132
4133 if (aSetError)
4134 return setError(VBOX_E_OBJECT_NOT_FOUND,
4135 tr("Could not find an open hard disk with UUID {%RTuuid}"),
4136 aId.raw());
4137
4138 return VBOX_E_OBJECT_NOT_FOUND;
4139}
4140
4141/**
4142 * Searches for a Medium object with the given ID or location in the list of
4143 * registered hard disks. If both ID and location are specified, the first
4144 * object that matches either of them (not necessarily both) is returned.
4145 *
4146 * @param strLocation Full location specification. Must not be empty.
4147 * @param aSetError If @c true , the appropriate error info is set in case
4148 * when the hard disk is not found.
4149 * @param aHardDisk Where to store the found hard disk object (can be NULL).
4150 *
4151 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4152 *
4153 * @note Locks the media tree for reading.
4154 */
4155HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
4156 bool aSetError,
4157 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
4158{
4159 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
4160
4161 // we use the hard disks map, but it is protected by the
4162 // hard disk _list_ lock handle
4163 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4164
4165 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
4166 it != m->mapHardDisks.end();
4167 ++it)
4168 {
4169 const ComObjPtr<Medium> &pHD = (*it).second;
4170
4171 AutoCaller autoCaller(pHD);
4172 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4173 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
4174
4175 Utf8Str strLocationFull = pHD->i_getLocationFull();
4176
4177 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
4178 {
4179 if (aHardDisk)
4180 *aHardDisk = pHD;
4181 return S_OK;
4182 }
4183 }
4184
4185 if (aSetError)
4186 return setError(VBOX_E_OBJECT_NOT_FOUND,
4187 tr("Could not find an open hard disk with location '%s'"),
4188 strLocation.c_str());
4189
4190 return VBOX_E_OBJECT_NOT_FOUND;
4191}
4192
4193/**
4194 * Searches for a Medium object with the given ID or location in the list of
4195 * registered DVD or floppy images, depending on the @a mediumType argument.
4196 * If both ID and file path are specified, the first object that matches either
4197 * of them (not necessarily both) is returned.
4198 *
4199 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
4200 * @param aId ID of the image file (unused when NULL).
4201 * @param aLocation Full path to the image file (unused when NULL).
4202 * @param aSetError If @c true, the appropriate error info is set in case when
4203 * the image is not found.
4204 * @param aImage Where to store the found image object (can be NULL).
4205 *
4206 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4207 *
4208 * @note Locks the media tree for reading.
4209 */
4210HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
4211 const Guid *aId,
4212 const Utf8Str &aLocation,
4213 bool aSetError,
4214 ComObjPtr<Medium> *aImage /* = NULL */)
4215{
4216 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
4217
4218 Utf8Str location;
4219 if (!aLocation.isEmpty())
4220 {
4221 int vrc = i_calculateFullPath(aLocation, location);
4222 if (RT_FAILURE(vrc))
4223 return setError(VBOX_E_FILE_ERROR,
4224 tr("Invalid image file location '%s' (%Rrc)"),
4225 aLocation.c_str(),
4226 vrc);
4227 }
4228
4229 MediaOList *pMediaList;
4230
4231 switch (mediumType)
4232 {
4233 case DeviceType_DVD:
4234 pMediaList = &m->allDVDImages;
4235 break;
4236
4237 case DeviceType_Floppy:
4238 pMediaList = &m->allFloppyImages;
4239 break;
4240
4241 default:
4242 return E_INVALIDARG;
4243 }
4244
4245 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
4246
4247 bool found = false;
4248
4249 for (MediaList::const_iterator it = pMediaList->begin();
4250 it != pMediaList->end();
4251 ++it)
4252 {
4253 // no AutoCaller, registered image life time is bound to this
4254 Medium *pMedium = *it;
4255 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
4256 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
4257
4258 found = ( aId
4259 && pMedium->i_getId() == *aId)
4260 || ( !aLocation.isEmpty()
4261 && RTPathCompare(location.c_str(),
4262 strLocationFull.c_str()) == 0);
4263 if (found)
4264 {
4265 if (pMedium->i_getDeviceType() != mediumType)
4266 {
4267 if (mediumType == DeviceType_DVD)
4268 return setError(E_INVALIDARG,
4269 tr("Cannot mount DVD medium '%s' as floppy"), strLocationFull.c_str());
4270 else
4271 return setError(E_INVALIDARG,
4272 tr("Cannot mount floppy medium '%s' as DVD"), strLocationFull.c_str());
4273 }
4274
4275 if (aImage)
4276 *aImage = pMedium;
4277 break;
4278 }
4279 }
4280
4281 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
4282
4283 if (aSetError && !found)
4284 {
4285 if (aId)
4286 setError(rc,
4287 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
4288 aId->raw(),
4289 m->strSettingsFilePath.c_str());
4290 else
4291 setError(rc,
4292 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
4293 aLocation.c_str(),
4294 m->strSettingsFilePath.c_str());
4295 }
4296
4297 return rc;
4298}
4299
4300/**
4301 * Searches for an IMedium object that represents the given UUID.
4302 *
4303 * If the UUID is empty (indicating an empty drive), this sets pMedium
4304 * to NULL and returns S_OK.
4305 *
4306 * If the UUID refers to a host drive of the given device type, this
4307 * sets pMedium to the object from the list in IHost and returns S_OK.
4308 *
4309 * If the UUID is an image file, this sets pMedium to the object that
4310 * findDVDOrFloppyImage() returned.
4311 *
4312 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
4313 *
4314 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
4315 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
4316 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
4317 * @param aSetError
4318 * @param pMedium out: IMedium object found.
4319 * @return
4320 */
4321HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
4322 const Guid &uuid,
4323 bool fRefresh,
4324 bool aSetError,
4325 ComObjPtr<Medium> &pMedium)
4326{
4327 if (uuid.isZero())
4328 {
4329 // that's easy
4330 pMedium.setNull();
4331 return S_OK;
4332 }
4333 else if (!uuid.isValid())
4334 {
4335 /* handling of case invalid GUID */
4336 return setError(VBOX_E_OBJECT_NOT_FOUND,
4337 tr("Guid '%s' is invalid"),
4338 uuid.toString().c_str());
4339 }
4340
4341 // first search for host drive with that UUID
4342 HRESULT rc = m->pHost->i_findHostDriveById(mediumType,
4343 uuid,
4344 fRefresh,
4345 pMedium);
4346 if (rc == VBOX_E_OBJECT_NOT_FOUND)
4347 // then search for an image with that UUID
4348 rc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
4349
4350 return rc;
4351}
4352
4353/* Look for a GuestOSType object */
4354HRESULT VirtualBox::i_findGuestOSType(const Utf8Str &strOSType,
4355 ComObjPtr<GuestOSType> &guestOSType)
4356{
4357 guestOSType.setNull();
4358
4359 AssertMsg(m->allGuestOSTypes.size() != 0,
4360 ("Guest OS types array must be filled"));
4361
4362 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4363 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4364 it != m->allGuestOSTypes.end();
4365 ++it)
4366 {
4367 const Utf8Str &typeId = (*it)->i_id();
4368 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
4369 if (strOSType.compare(typeId, Utf8Str::CaseInsensitive) == 0)
4370 {
4371 guestOSType = *it;
4372 return S_OK;
4373 }
4374 }
4375
4376 return setError(VBOX_E_OBJECT_NOT_FOUND,
4377 tr("'%s' is not a valid Guest OS type"),
4378 strOSType.c_str());
4379}
4380
4381/**
4382 * Returns the constant pseudo-machine UUID that is used to identify the
4383 * global media registry.
4384 *
4385 * Starting with VirtualBox 4.0 each medium remembers in its instance data
4386 * in which media registry it is saved (if any): this can either be a machine
4387 * UUID, if it's in a per-machine media registry, or this global ID.
4388 *
4389 * This UUID is only used to identify the VirtualBox object while VirtualBox
4390 * is running. It is a compile-time constant and not saved anywhere.
4391 *
4392 * @return
4393 */
4394const Guid& VirtualBox::i_getGlobalRegistryId() const
4395{
4396 return m->uuidMediaRegistry;
4397}
4398
4399const ComObjPtr<Host>& VirtualBox::i_host() const
4400{
4401 return m->pHost;
4402}
4403
4404SystemProperties* VirtualBox::i_getSystemProperties() const
4405{
4406 return m->pSystemProperties;
4407}
4408
4409CloudProviderManager *VirtualBox::i_getCloudProviderManager() const
4410{
4411 return m->pCloudProviderManager;
4412}
4413
4414#ifdef VBOX_WITH_EXTPACK
4415/**
4416 * Getter that SystemProperties and others can use to talk to the extension
4417 * pack manager.
4418 */
4419ExtPackManager* VirtualBox::i_getExtPackManager() const
4420{
4421 return m->ptrExtPackManager;
4422}
4423#endif
4424
4425/**
4426 * Getter that machines can talk to the autostart database.
4427 */
4428AutostartDb* VirtualBox::i_getAutostartDb() const
4429{
4430 return m->pAutostartDb;
4431}
4432
4433#ifdef VBOX_WITH_RESOURCE_USAGE_API
4434const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
4435{
4436 return m->pPerformanceCollector;
4437}
4438#endif /* VBOX_WITH_RESOURCE_USAGE_API */
4439
4440/**
4441 * Returns the default machine folder from the system properties
4442 * with proper locking.
4443 * @return
4444 */
4445void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
4446{
4447 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
4448 str = m->pSystemProperties->m->strDefaultMachineFolder;
4449}
4450
4451/**
4452 * Returns the default hard disk format from the system properties
4453 * with proper locking.
4454 * @return
4455 */
4456void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
4457{
4458 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
4459 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
4460}
4461
4462const Utf8Str& VirtualBox::i_homeDir() const
4463{
4464 return m->strHomeDir;
4465}
4466
4467/**
4468 * Calculates the absolute path of the given path taking the VirtualBox home
4469 * directory as the current directory.
4470 *
4471 * @param strPath Path to calculate the absolute path for.
4472 * @param aResult Where to put the result (used only on success, can be the
4473 * same Utf8Str instance as passed in @a aPath).
4474 * @return IPRT result.
4475 *
4476 * @note Doesn't lock any object.
4477 */
4478int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
4479{
4480 AutoCaller autoCaller(this);
4481 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
4482
4483 /* no need to lock since strHomeDir is const */
4484
4485 char szFolder[RTPATH_MAX];
4486 size_t cbFolder = sizeof(szFolder);
4487 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
4488 strPath.c_str(),
4489 RTPATH_STR_F_STYLE_HOST,
4490 szFolder,
4491 &cbFolder);
4492 if (RT_SUCCESS(vrc))
4493 aResult = szFolder;
4494
4495 return vrc;
4496}
4497
4498/**
4499 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
4500 * if it is a subdirectory thereof, or simply copying it otherwise.
4501 *
4502 * @param strSource Path to evalue and copy.
4503 * @param strTarget Buffer to receive target path.
4504 */
4505void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
4506 Utf8Str &strTarget)
4507{
4508 AutoCaller autoCaller(this);
4509 AssertComRCReturnVoid(autoCaller.rc());
4510
4511 // no need to lock since mHomeDir is const
4512
4513 // use strTarget as a temporary buffer to hold the machine settings dir
4514 strTarget = m->strHomeDir;
4515 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
4516 // is relative: then append what's left
4517 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
4518 else
4519 // is not relative: then overwrite
4520 strTarget = strSource;
4521}
4522
4523// private methods
4524/////////////////////////////////////////////////////////////////////////////
4525
4526/**
4527 * Checks if there is a hard disk, DVD or floppy image with the given ID or
4528 * location already registered.
4529 *
4530 * On return, sets @a aConflict to the string describing the conflicting medium,
4531 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
4532 * either case. A failure is unexpected.
4533 *
4534 * @param aId UUID to check.
4535 * @param aLocation Location to check.
4536 * @param aConflict Where to return parameters of the conflicting medium.
4537 * @param ppMedium Medium reference in case this is simply a duplicate.
4538 *
4539 * @note Locks the media tree and media objects for reading.
4540 */
4541HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
4542 const Utf8Str &aLocation,
4543 Utf8Str &aConflict,
4544 ComObjPtr<Medium> *ppMedium)
4545{
4546 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
4547 AssertReturn(ppMedium, E_INVALIDARG);
4548
4549 aConflict.setNull();
4550 ppMedium->setNull();
4551
4552 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4553
4554 HRESULT rc = S_OK;
4555
4556 ComObjPtr<Medium> pMediumFound;
4557 const char *pcszType = NULL;
4558
4559 if (aId.isValid() && !aId.isZero())
4560 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4561 if (FAILED(rc) && !aLocation.isEmpty())
4562 rc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
4563 if (SUCCEEDED(rc))
4564 pcszType = tr("hard disk");
4565
4566 if (!pcszType)
4567 {
4568 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
4569 if (SUCCEEDED(rc))
4570 pcszType = tr("CD/DVD image");
4571 }
4572
4573 if (!pcszType)
4574 {
4575 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
4576 if (SUCCEEDED(rc))
4577 pcszType = tr("floppy image");
4578 }
4579
4580 if (pcszType && pMediumFound)
4581 {
4582 /* Note: no AutoCaller since bound to this */
4583 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
4584
4585 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
4586 Guid idFound = pMediumFound->i_getId();
4587
4588 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
4589 && (idFound == aId)
4590 )
4591 *ppMedium = pMediumFound;
4592
4593 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
4594 pcszType,
4595 strLocFound.c_str(),
4596 idFound.raw());
4597 }
4598
4599 return S_OK;
4600}
4601
4602/**
4603 * Checks whether the given UUID is already in use by one medium for the
4604 * given device type.
4605 *
4606 * @returns true if the UUID is already in use
4607 * fale otherwise
4608 * @param aId The UUID to check.
4609 * @param deviceType The device type the UUID is going to be checked for
4610 * conflicts.
4611 */
4612bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
4613{
4614 /* A zero UUID is invalid here, always claim that it is already used. */
4615 AssertReturn(!aId.isZero(), true);
4616
4617 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4618
4619 HRESULT rc = S_OK;
4620 bool fInUse = false;
4621
4622 ComObjPtr<Medium> pMediumFound;
4623
4624 switch (deviceType)
4625 {
4626 case DeviceType_HardDisk:
4627 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4628 break;
4629 case DeviceType_DVD:
4630 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4631 break;
4632 case DeviceType_Floppy:
4633 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4634 break;
4635 default:
4636 AssertMsgFailed(("Invalid device type %d\n", deviceType));
4637 }
4638
4639 if (SUCCEEDED(rc) && pMediumFound)
4640 fInUse = true;
4641
4642 return fInUse;
4643}
4644
4645/**
4646 * Called from Machine::prepareSaveSettings() when it has detected
4647 * that a machine has been renamed. Such renames will require
4648 * updating the global media registry during the
4649 * VirtualBox::i_saveSettings() that follows later.
4650*
4651 * When a machine is renamed, there may well be media (in particular,
4652 * diff images for snapshots) in the global registry that will need
4653 * to have their paths updated. Before 3.2, Machine::saveSettings
4654 * used to call VirtualBox::i_saveSettings implicitly, which was both
4655 * unintuitive and caused locking order problems. Now, we remember
4656 * such pending name changes with this method so that
4657 * VirtualBox::i_saveSettings() can process them properly.
4658 */
4659void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
4660 const Utf8Str &strNewConfigDir)
4661{
4662 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4663
4664 Data::PendingMachineRename pmr;
4665 pmr.strConfigDirOld = strOldConfigDir;
4666 pmr.strConfigDirNew = strNewConfigDir;
4667 m->llPendingMachineRenames.push_back(pmr);
4668}
4669
4670static DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4671
4672class SaveMediaRegistriesDesc : public ThreadTask
4673{
4674
4675public:
4676 SaveMediaRegistriesDesc()
4677 {
4678 m_strTaskName = "SaveMediaReg";
4679 }
4680 virtual ~SaveMediaRegistriesDesc(void) { }
4681
4682private:
4683 void handler()
4684 {
4685 try
4686 {
4687 fntSaveMediaRegistries(this);
4688 }
4689 catch(...)
4690 {
4691 LogRel(("Exception in the function fntSaveMediaRegistries()\n"));
4692 }
4693 }
4694
4695 MediaList llMedia;
4696 ComObjPtr<VirtualBox> pVirtualBox;
4697
4698 friend DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4699 friend void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4700 const Guid &uuidRegistry,
4701 const Utf8Str &strMachineFolder);
4702};
4703
4704DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser)
4705{
4706 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
4707 if (!pDesc)
4708 {
4709 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
4710 return VERR_INVALID_PARAMETER;
4711 }
4712
4713 for (MediaList::const_iterator it = pDesc->llMedia.begin();
4714 it != pDesc->llMedia.end();
4715 ++it)
4716 {
4717 Medium *pMedium = *it;
4718 pMedium->i_markRegistriesModified();
4719 }
4720
4721 pDesc->pVirtualBox->i_saveModifiedRegistries();
4722
4723 pDesc->llMedia.clear();
4724 pDesc->pVirtualBox.setNull();
4725
4726 return VINF_SUCCESS;
4727}
4728
4729/**
4730 * Goes through all known media (hard disks, floppies and DVDs) and saves
4731 * those into the given settings::MediaRegistry structures whose registry
4732 * ID match the given UUID.
4733 *
4734 * Before actually writing to the structures, all media paths (not just the
4735 * ones for the given registry) are updated if machines have been renamed
4736 * since the last call.
4737 *
4738 * This gets called from two contexts:
4739 *
4740 * -- VirtualBox::i_saveSettings() with the UUID of the global registry
4741 * (VirtualBox::Data.uuidRegistry); this will save those media
4742 * which had been loaded from the global registry or have been
4743 * attached to a "legacy" machine which can't save its own registry;
4744 *
4745 * -- Machine::saveSettings() with the UUID of a machine, if a medium
4746 * has been attached to a machine created with VirtualBox 4.0 or later.
4747 *
4748 * Media which have only been temporarily opened without having been
4749 * attached to a machine have a NULL registry UUID and therefore don't
4750 * get saved.
4751 *
4752 * This locks the media tree. Throws HRESULT on errors!
4753 *
4754 * @param mediaRegistry Settings structure to fill.
4755 * @param uuidRegistry The UUID of the media registry; either a machine UUID
4756 * (if machine registry) or the UUID of the global registry.
4757 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
4758 */
4759void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4760 const Guid &uuidRegistry,
4761 const Utf8Str &strMachineFolder)
4762{
4763 // lock all media for the following; use a write lock because we're
4764 // modifying the PendingMachineRenamesList, which is protected by this
4765 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4766
4767 // if a machine was renamed, then we'll need to refresh media paths
4768 if (m->llPendingMachineRenames.size())
4769 {
4770 // make a single list from the three media lists so we don't need three loops
4771 MediaList llAllMedia;
4772 // with hard disks, we must use the map, not the list, because the list only has base images
4773 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
4774 llAllMedia.push_back(it->second);
4775 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
4776 llAllMedia.push_back(*it);
4777 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
4778 llAllMedia.push_back(*it);
4779
4780 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
4781 for (MediaList::iterator it = llAllMedia.begin();
4782 it != llAllMedia.end();
4783 ++it)
4784 {
4785 Medium *pMedium = *it;
4786 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
4787 it2 != m->llPendingMachineRenames.end();
4788 ++it2)
4789 {
4790 const Data::PendingMachineRename &pmr = *it2;
4791 HRESULT rc = pMedium->i_updatePath(pmr.strConfigDirOld,
4792 pmr.strConfigDirNew);
4793 if (SUCCEEDED(rc))
4794 {
4795 // Remember which medium objects has been changed,
4796 // to trigger saving their registries later.
4797 pDesc->llMedia.push_back(pMedium);
4798 } else if (rc == VBOX_E_FILE_ERROR)
4799 /* nothing */;
4800 else
4801 AssertComRC(rc);
4802 }
4803 }
4804 // done, don't do it again until we have more machine renames
4805 m->llPendingMachineRenames.clear();
4806
4807 if (pDesc->llMedia.size())
4808 {
4809 // Handle the media registry saving in a separate thread, to
4810 // avoid giant locking problems and passing up the list many
4811 // levels up to whoever triggered saveSettings, as there are
4812 // lots of places which would need to handle saving more settings.
4813 pDesc->pVirtualBox = this;
4814
4815 //the function createThread() takes ownership of pDesc
4816 //so there is no need to use delete operator for pDesc
4817 //after calling this function
4818 HRESULT hr = pDesc->createThread();
4819 pDesc = NULL;
4820
4821 if (FAILED(hr))
4822 {
4823 // failure means that settings aren't saved, but there isn't
4824 // much we can do besides avoiding memory leaks
4825 LogRelFunc(("Failed to create thread for saving media registries (%Rhr)\n", hr));
4826 }
4827 }
4828 else
4829 delete pDesc;
4830 }
4831
4832 struct {
4833 MediaOList &llSource;
4834 settings::MediaList &llTarget;
4835 } s[] =
4836 {
4837 // hard disks
4838 { m->allHardDisks, mediaRegistry.llHardDisks },
4839 // CD/DVD images
4840 { m->allDVDImages, mediaRegistry.llDvdImages },
4841 // floppy images
4842 { m->allFloppyImages, mediaRegistry.llFloppyImages }
4843 };
4844
4845 HRESULT rc;
4846
4847 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
4848 {
4849 MediaOList &llSource = s[i].llSource;
4850 settings::MediaList &llTarget = s[i].llTarget;
4851 llTarget.clear();
4852 for (MediaList::const_iterator it = llSource.begin();
4853 it != llSource.end();
4854 ++it)
4855 {
4856 Medium *pMedium = *it;
4857 AutoCaller autoCaller(pMedium);
4858 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
4859 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4860
4861 if (pMedium->i_isInRegistry(uuidRegistry))
4862 {
4863 llTarget.push_back(settings::Medium::Empty);
4864 rc = pMedium->i_saveSettings(llTarget.back(), strMachineFolder); // this recurses into child hard disks
4865 if (FAILED(rc))
4866 {
4867 llTarget.pop_back();
4868 throw rc;
4869 }
4870 }
4871 }
4872 }
4873}
4874
4875/**
4876 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
4877 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
4878 * places internally when settings need saving.
4879 *
4880 * @note Caller must have locked the VirtualBox object for writing and must not hold any
4881 * other locks since this locks all kinds of member objects and trees temporarily,
4882 * which could cause conflicts.
4883 */
4884HRESULT VirtualBox::i_saveSettings()
4885{
4886 AutoCaller autoCaller(this);
4887 AssertComRCReturnRC(autoCaller.rc());
4888
4889 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
4890 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
4891
4892 i_unmarkRegistryModified(i_getGlobalRegistryId());
4893
4894 HRESULT rc = S_OK;
4895
4896 try
4897 {
4898 // machines
4899 m->pMainConfigFile->llMachines.clear();
4900 {
4901 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4902 for (MachinesOList::iterator it = m->allMachines.begin();
4903 it != m->allMachines.end();
4904 ++it)
4905 {
4906 Machine *pMachine = *it;
4907 // save actual machine registry entry
4908 settings::MachineRegistryEntry mre;
4909 rc = pMachine->i_saveRegistryEntry(mre);
4910 m->pMainConfigFile->llMachines.push_back(mre);
4911 }
4912 }
4913
4914 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
4915 m->uuidMediaRegistry, // global media registry ID
4916 Utf8Str::Empty); // strMachineFolder
4917
4918 m->pMainConfigFile->llDhcpServers.clear();
4919 {
4920 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4921 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4922 it != m->allDHCPServers.end();
4923 ++it)
4924 {
4925 settings::DHCPServer d;
4926 rc = (*it)->i_saveSettings(d);
4927 if (FAILED(rc)) throw rc;
4928 m->pMainConfigFile->llDhcpServers.push_back(d);
4929 }
4930 }
4931
4932#ifdef VBOX_WITH_NAT_SERVICE
4933 /* Saving NAT Network configuration */
4934 m->pMainConfigFile->llNATNetworks.clear();
4935 {
4936 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4937 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4938 it != m->allNATNetworks.end();
4939 ++it)
4940 {
4941 settings::NATNetwork n;
4942 rc = (*it)->i_saveSettings(n);
4943 if (FAILED(rc)) throw rc;
4944 m->pMainConfigFile->llNATNetworks.push_back(n);
4945 }
4946 }
4947#endif
4948
4949#ifdef VBOX_WITH_VMNET
4950 m->pMainConfigFile->llHostOnlyNetworks.clear();
4951 {
4952 AutoReadLock hostOnlyNetworkLock(m->allHostOnlyNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4953 for (HostOnlyNetworksOList::const_iterator it = m->allHostOnlyNetworks.begin();
4954 it != m->allHostOnlyNetworks.end();
4955 ++it)
4956 {
4957 settings::HostOnlyNetwork n;
4958 rc = (*it)->i_saveSettings(n);
4959 if (FAILED(rc)) throw rc;
4960 m->pMainConfigFile->llHostOnlyNetworks.push_back(n);
4961 }
4962 }
4963#endif /* VBOX_WITH_VMNET */
4964
4965#ifdef VBOX_WITH_CLOUD_NET
4966 m->pMainConfigFile->llCloudNetworks.clear();
4967 {
4968 AutoReadLock cloudNetworkLock(m->allCloudNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4969 for (CloudNetworksOList::const_iterator it = m->allCloudNetworks.begin();
4970 it != m->allCloudNetworks.end();
4971 ++it)
4972 {
4973 settings::CloudNetwork n;
4974 rc = (*it)->i_saveSettings(n);
4975 if (FAILED(rc)) throw rc;
4976 m->pMainConfigFile->llCloudNetworks.push_back(n);
4977 }
4978 }
4979#endif /* VBOX_WITH_CLOUD_NET */
4980 // leave extra data alone, it's still in the config file
4981
4982 // host data (USB filters)
4983 rc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
4984 if (FAILED(rc)) throw rc;
4985
4986 rc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
4987 if (FAILED(rc)) throw rc;
4988
4989 // and write out the XML, still under the lock
4990 m->pMainConfigFile->write(m->strSettingsFilePath);
4991 }
4992 catch (HRESULT err)
4993 {
4994 /* we assume that error info is set by the thrower */
4995 rc = err;
4996 }
4997 catch (...)
4998 {
4999 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
5000 }
5001
5002 return rc;
5003}
5004
5005/**
5006 * Helper to register the machine.
5007 *
5008 * When called during VirtualBox startup, adds the given machine to the
5009 * collection of registered machines. Otherwise tries to mark the machine
5010 * as registered, and, if succeeded, adds it to the collection and
5011 * saves global settings.
5012 *
5013 * @note The caller must have added itself as a caller of the @a aMachine
5014 * object if calls this method not on VirtualBox startup.
5015 *
5016 * @param aMachine machine to register
5017 *
5018 * @note Locks objects!
5019 */
5020HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
5021{
5022 ComAssertRet(aMachine, E_INVALIDARG);
5023
5024 AutoCaller autoCaller(this);
5025 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5026
5027 HRESULT rc = S_OK;
5028
5029 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5030
5031 {
5032 ComObjPtr<Machine> pMachine;
5033 rc = i_findMachine(aMachine->i_getId(),
5034 true /* fPermitInaccessible */,
5035 false /* aDoSetError */,
5036 &pMachine);
5037 if (SUCCEEDED(rc))
5038 {
5039 /* sanity */
5040 AutoLimitedCaller machCaller(pMachine);
5041 AssertComRC(machCaller.rc());
5042
5043 return setError(E_INVALIDARG,
5044 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
5045 aMachine->i_getId().raw(),
5046 pMachine->i_getSettingsFileFull().c_str());
5047 }
5048
5049 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
5050 rc = S_OK;
5051 }
5052
5053 if (getObjectState().getState() != ObjectState::InInit)
5054 {
5055 rc = aMachine->i_prepareRegister();
5056 if (FAILED(rc)) return rc;
5057 }
5058
5059 /* add to the collection of registered machines */
5060 m->allMachines.addChild(aMachine);
5061
5062 if (getObjectState().getState() != ObjectState::InInit)
5063 rc = i_saveSettings();
5064
5065 return rc;
5066}
5067
5068/**
5069 * Remembers the given medium object by storing it in either the global
5070 * medium registry or a machine one.
5071 *
5072 * @note Caller must hold the media tree lock for writing; in addition, this
5073 * locks @a pMedium for reading
5074 *
5075 * @param pMedium Medium object to remember.
5076 * @param ppMedium Actually stored medium object. Can be different if due
5077 * to an unavoidable race there was a duplicate Medium object
5078 * created.
5079 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
5080 * lock, necessary to release it in the right spot.
5081 * @param fCalledFromMediumInit Flag whether this is called from Medium::init().
5082 * @return
5083 */
5084HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
5085 ComObjPtr<Medium> *ppMedium,
5086 AutoWriteLock &mediaTreeLock,
5087 bool fCalledFromMediumInit)
5088{
5089 AssertReturn(pMedium != NULL, E_INVALIDARG);
5090 AssertReturn(ppMedium != NULL, E_INVALIDARG);
5091
5092 // caller must hold the media tree write lock
5093 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5094
5095 AutoCaller autoCaller(this);
5096 AssertComRCReturnRC(autoCaller.rc());
5097
5098 AutoCaller mediumCaller(pMedium);
5099 AssertComRCReturnRC(mediumCaller.rc());
5100
5101 bool fAddToGlobalRegistry = false;
5102 const char *pszDevType = NULL;
5103 Guid regId;
5104 ObjectsList<Medium> *pall = NULL;
5105 DeviceType_T devType;
5106 {
5107 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5108 devType = pMedium->i_getDeviceType();
5109
5110 if (!pMedium->i_getFirstRegistryMachineId(regId))
5111 fAddToGlobalRegistry = true;
5112 }
5113 switch (devType)
5114 {
5115 case DeviceType_HardDisk:
5116 pall = &m->allHardDisks;
5117 pszDevType = tr("hard disk");
5118 break;
5119 case DeviceType_DVD:
5120 pszDevType = tr("DVD image");
5121 pall = &m->allDVDImages;
5122 break;
5123 case DeviceType_Floppy:
5124 pszDevType = tr("floppy image");
5125 pall = &m->allFloppyImages;
5126 break;
5127 default:
5128 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
5129 }
5130
5131 Guid id;
5132 Utf8Str strLocationFull;
5133 ComObjPtr<Medium> pParent;
5134 {
5135 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5136 id = pMedium->i_getId();
5137 strLocationFull = pMedium->i_getLocationFull();
5138 pParent = pMedium->i_getParent();
5139 }
5140
5141 HRESULT rc;
5142
5143 Utf8Str strConflict;
5144 ComObjPtr<Medium> pDupMedium;
5145 rc = i_checkMediaForConflicts(id,
5146 strLocationFull,
5147 strConflict,
5148 &pDupMedium);
5149 if (FAILED(rc)) return rc;
5150
5151 if (pDupMedium.isNull())
5152 {
5153 if (strConflict.length())
5154 return setError(E_INVALIDARG,
5155 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
5156 pszDevType,
5157 strLocationFull.c_str(),
5158 id.raw(),
5159 strConflict.c_str(),
5160 m->strSettingsFilePath.c_str());
5161
5162 // add to the collection if it is a base medium
5163 if (pParent.isNull())
5164 pall->getList().push_back(pMedium);
5165
5166 // store all hard disks (even differencing images) in the map
5167 if (devType == DeviceType_HardDisk)
5168 m->mapHardDisks[id] = pMedium;
5169
5170 mediumCaller.release();
5171 mediaTreeLock.release();
5172 *ppMedium = pMedium;
5173 }
5174 else
5175 {
5176 // pMedium may be the last reference to the Medium object, and the
5177 // caller may have specified the same ComObjPtr as the output parameter.
5178 // In this case the assignment will uninit the object, and we must not
5179 // have a caller pending.
5180 mediumCaller.release();
5181 // release media tree lock, must not be held at uninit time.
5182 mediaTreeLock.release();
5183 // must not hold the media tree write lock any more
5184 Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5185 *ppMedium = pDupMedium;
5186 }
5187
5188 if (fAddToGlobalRegistry)
5189 {
5190 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5191 if ( fCalledFromMediumInit
5192 ? (*ppMedium)->i_addRegistryNoCallerCheck(m->uuidMediaRegistry)
5193 : (*ppMedium)->i_addRegistry(m->uuidMediaRegistry))
5194 i_markRegistryModified(m->uuidMediaRegistry);
5195 }
5196
5197 // Restore the initial lock state, so that no unexpected lock changes are
5198 // done by this method, which would need adjustments everywhere.
5199 mediaTreeLock.acquire();
5200
5201 return rc;
5202}
5203
5204/**
5205 * Removes the given medium from the respective registry.
5206 *
5207 * @param pMedium Hard disk object to remove.
5208 *
5209 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
5210 */
5211HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
5212{
5213 AssertReturn(pMedium != NULL, E_INVALIDARG);
5214
5215 AutoCaller autoCaller(this);
5216 AssertComRCReturnRC(autoCaller.rc());
5217
5218 AutoCaller mediumCaller(pMedium);
5219 AssertComRCReturnRC(mediumCaller.rc());
5220
5221 // caller must hold the media tree write lock
5222 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5223
5224 Guid id;
5225 ComObjPtr<Medium> pParent;
5226 DeviceType_T devType;
5227 {
5228 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5229 id = pMedium->i_getId();
5230 pParent = pMedium->i_getParent();
5231 devType = pMedium->i_getDeviceType();
5232 }
5233
5234 ObjectsList<Medium> *pall = NULL;
5235 switch (devType)
5236 {
5237 case DeviceType_HardDisk:
5238 pall = &m->allHardDisks;
5239 break;
5240 case DeviceType_DVD:
5241 pall = &m->allDVDImages;
5242 break;
5243 case DeviceType_Floppy:
5244 pall = &m->allFloppyImages;
5245 break;
5246 default:
5247 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
5248 }
5249
5250 // remove from the collection if it is a base medium
5251 if (pParent.isNull())
5252 pall->getList().remove(pMedium);
5253
5254 // remove all hard disks (even differencing images) from map
5255 if (devType == DeviceType_HardDisk)
5256 {
5257 size_t cnt = m->mapHardDisks.erase(id);
5258 Assert(cnt == 1);
5259 NOREF(cnt);
5260 }
5261
5262 return S_OK;
5263}
5264
5265/**
5266 * Unregisters all Medium objects which belong to the given machine registry.
5267 * Gets called from Machine::uninit() just before the machine object dies
5268 * and must only be called with a machine UUID as the registry ID.
5269 *
5270 * Locks the media tree.
5271 *
5272 * @param uuidMachine Medium registry ID (always a machine UUID)
5273 * @return
5274 */
5275HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
5276{
5277 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
5278
5279 LogFlowFuncEnter();
5280
5281 AutoCaller autoCaller(this);
5282 AssertComRCReturnRC(autoCaller.rc());
5283
5284 MediaList llMedia2Close;
5285
5286 {
5287 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5288
5289 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
5290 it != m->allHardDisks.getList().end();
5291 ++it)
5292 {
5293 ComObjPtr<Medium> pMedium = *it;
5294 AutoCaller medCaller(pMedium);
5295 if (FAILED(medCaller.rc())) return medCaller.rc();
5296 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
5297 Log(("Looking at medium %RTuuid\n", pMedium->i_getId().raw()));
5298
5299 /* If the medium is still in the registry then either some code is
5300 * seriously buggy (unregistering a VM removes it automatically),
5301 * or the reference to a Machine object is destroyed without ever
5302 * being registered. The second condition checks if a medium is
5303 * in no registry, which indicates (set by unregistering) that a
5304 * medium is not used by any other VM and thus can be closed. */
5305 Guid dummy;
5306 if ( pMedium->i_isInRegistry(uuidMachine)
5307 || !pMedium->i_getFirstRegistryMachineId(dummy))
5308 {
5309 /* Collect all medium objects into llMedia2Close,
5310 * in right order for closing. */
5311 MediaList llMediaTodo;
5312 llMediaTodo.push_back(pMedium);
5313
5314 while (llMediaTodo.size() > 0)
5315 {
5316 ComObjPtr<Medium> pCurrent = llMediaTodo.front();
5317 llMediaTodo.pop_front();
5318
5319 /* Add to front, order must be children then parent. */
5320 Log(("Pushing medium %RTuuid (front)\n", pCurrent->i_getId().raw()));
5321 llMedia2Close.push_front(pCurrent);
5322
5323 /* process all children */
5324 MediaList::const_iterator itBegin = pCurrent->i_getChildren().begin();
5325 MediaList::const_iterator itEnd = pCurrent->i_getChildren().end();
5326 for (MediaList::const_iterator it2 = itBegin; it2 != itEnd; ++it2)
5327 llMediaTodo.push_back(*it2);
5328 }
5329 }
5330 }
5331 }
5332
5333 for (MediaList::iterator it = llMedia2Close.begin();
5334 it != llMedia2Close.end();
5335 ++it)
5336 {
5337 ComObjPtr<Medium> pMedium = *it;
5338 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
5339 AutoCaller mac(pMedium);
5340 pMedium->i_close(mac);
5341 }
5342
5343 LogFlowFuncLeave();
5344
5345 return S_OK;
5346}
5347
5348/**
5349 * Removes the given machine object from the internal list of registered machines.
5350 * Called from Machine::Unregister().
5351 * @param pMachine
5352 * @param aCleanupMode How to handle medium attachments. For
5353 * CleanupMode_UnregisterOnly the associated medium objects will be
5354 * closed when the Machine object is uninitialized, otherwise they will
5355 * go to the global registry if no better registry is found.
5356 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
5357 * @return
5358 */
5359HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
5360 CleanupMode_T aCleanupMode,
5361 const Guid &id)
5362{
5363 // remove from the collection of registered machines
5364 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5365 m->allMachines.removeChild(pMachine);
5366 // save the global registry
5367 HRESULT rc = i_saveSettings();
5368 alock.release();
5369
5370 /*
5371 * Now go over all known media and checks if they were registered in the
5372 * media registry of the given machine. Each such medium is then moved to
5373 * a different media registry to make sure it doesn't get lost since its
5374 * media registry is about to go away.
5375 *
5376 * This fixes the following use case: Image A.vdi of machine A is also used
5377 * by machine B, but registered in the media registry of machine A. If machine
5378 * A is deleted, A.vdi must be moved to the registry of B, or else B will
5379 * become inaccessible.
5380 */
5381 {
5382 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5383 // iterate over the list of *base* images
5384 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
5385 it != m->allHardDisks.getList().end();
5386 ++it)
5387 {
5388 ComObjPtr<Medium> &pMedium = *it;
5389 AutoCaller medCaller(pMedium);
5390 if (FAILED(medCaller.rc())) return medCaller.rc();
5391 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
5392
5393 if (pMedium->i_removeRegistryAll(id))
5394 {
5395 // machine ID was found in base medium's registry list:
5396 // move this base image and all its children to another registry then
5397 // 1) first, find a better registry to add things to
5398 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref(id);
5399 if (puuidBetter)
5400 {
5401 // 2) better registry found: then use that
5402 pMedium->i_addRegistryAll(*puuidBetter);
5403 // 3) and make sure the registry is saved below
5404 mlock.release();
5405 tlock.release();
5406 i_markRegistryModified(*puuidBetter);
5407 tlock.acquire();
5408 mlock.acquire();
5409 }
5410 else if (aCleanupMode != CleanupMode_UnregisterOnly)
5411 {
5412 pMedium->i_addRegistryAll(i_getGlobalRegistryId());
5413 mlock.release();
5414 tlock.release();
5415 i_markRegistryModified(i_getGlobalRegistryId());
5416 tlock.acquire();
5417 mlock.acquire();
5418 }
5419 }
5420 }
5421 }
5422
5423 i_saveModifiedRegistries();
5424
5425 /* fire an event */
5426 i_onMachineRegistered(id, FALSE);
5427
5428 return rc;
5429}
5430
5431/**
5432 * Marks the registry for @a uuid as modified, so that it's saved in a later
5433 * call to saveModifiedRegistries().
5434 *
5435 * @param uuid
5436 */
5437void VirtualBox::i_markRegistryModified(const Guid &uuid)
5438{
5439 if (uuid == i_getGlobalRegistryId())
5440 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
5441 else
5442 {
5443 ComObjPtr<Machine> pMachine;
5444 HRESULT rc = i_findMachine(uuid,
5445 false /* fPermitInaccessible */,
5446 false /* aSetError */,
5447 &pMachine);
5448 if (SUCCEEDED(rc))
5449 {
5450 AutoCaller machineCaller(pMachine);
5451 if (SUCCEEDED(machineCaller.rc()) && pMachine->i_isAccessible())
5452 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
5453 }
5454 }
5455}
5456
5457/**
5458 * Marks the registry for @a uuid as unmodified, so that it's not saved in
5459 * a later call to saveModifiedRegistries().
5460 *
5461 * @param uuid
5462 */
5463void VirtualBox::i_unmarkRegistryModified(const Guid &uuid)
5464{
5465 uint64_t uOld;
5466 if (uuid == i_getGlobalRegistryId())
5467 {
5468 for (;;)
5469 {
5470 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5471 if (!uOld)
5472 break;
5473 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5474 break;
5475 ASMNopPause();
5476 }
5477 }
5478 else
5479 {
5480 ComObjPtr<Machine> pMachine;
5481 HRESULT rc = i_findMachine(uuid,
5482 false /* fPermitInaccessible */,
5483 false /* aSetError */,
5484 &pMachine);
5485 if (SUCCEEDED(rc))
5486 {
5487 AutoCaller machineCaller(pMachine);
5488 if (SUCCEEDED(machineCaller.rc()))
5489 {
5490 for (;;)
5491 {
5492 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5493 if (!uOld)
5494 break;
5495 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5496 break;
5497 ASMNopPause();
5498 }
5499 }
5500 }
5501 }
5502}
5503
5504/**
5505 * Saves all settings files according to the modified flags in the Machine
5506 * objects and in the VirtualBox object.
5507 *
5508 * This locks machines and the VirtualBox object as necessary, so better not
5509 * hold any locks before calling this.
5510 *
5511 * @return
5512 */
5513void VirtualBox::i_saveModifiedRegistries()
5514{
5515 HRESULT rc = S_OK;
5516 bool fNeedsGlobalSettings = false;
5517 uint64_t uOld;
5518
5519 {
5520 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5521 for (MachinesOList::iterator it = m->allMachines.begin();
5522 it != m->allMachines.end();
5523 ++it)
5524 {
5525 const ComObjPtr<Machine> &pMachine = *it;
5526
5527 for (;;)
5528 {
5529 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5530 if (!uOld)
5531 break;
5532 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5533 break;
5534 ASMNopPause();
5535 }
5536 if (uOld)
5537 {
5538 AutoCaller autoCaller(pMachine);
5539 if (FAILED(autoCaller.rc()))
5540 continue;
5541 /* object is already dead, no point in saving settings */
5542 if (getObjectState().getState() != ObjectState::Ready)
5543 continue;
5544 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
5545 rc = pMachine->i_saveSettings(&fNeedsGlobalSettings, mlock,
5546 Machine::SaveS_Force); // caller said save, so stop arguing
5547 }
5548 }
5549 }
5550
5551 for (;;)
5552 {
5553 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5554 if (!uOld)
5555 break;
5556 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5557 break;
5558 ASMNopPause();
5559 }
5560 if (uOld || fNeedsGlobalSettings)
5561 {
5562 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5563 rc = i_saveSettings();
5564 }
5565 NOREF(rc); /* XXX */
5566}
5567
5568
5569/* static */
5570const com::Utf8Str &VirtualBox::i_getVersionNormalized()
5571{
5572 return sVersionNormalized;
5573}
5574
5575/**
5576 * Checks if the path to the specified file exists, according to the path
5577 * information present in the file name. Optionally the path is created.
5578 *
5579 * Note that the given file name must contain the full path otherwise the
5580 * extracted relative path will be created based on the current working
5581 * directory which is normally unknown.
5582 *
5583 * @param strFileName Full file name which path is checked/created.
5584 * @param fCreate Flag if the path should be created if it doesn't exist.
5585 *
5586 * @return Extended error information on failure to check/create the path.
5587 */
5588/* static */
5589HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
5590{
5591 Utf8Str strDir(strFileName);
5592 strDir.stripFilename();
5593 if (!RTDirExists(strDir.c_str()))
5594 {
5595 if (fCreate)
5596 {
5597 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
5598 if (RT_FAILURE(vrc))
5599 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, vrc,
5600 tr("Could not create the directory '%s' (%Rrc)"),
5601 strDir.c_str(),
5602 vrc);
5603 }
5604 else
5605 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, VERR_FILE_NOT_FOUND,
5606 tr("Directory '%s' does not exist"), strDir.c_str());
5607 }
5608
5609 return S_OK;
5610}
5611
5612const Utf8Str& VirtualBox::i_settingsFilePath()
5613{
5614 return m->strSettingsFilePath;
5615}
5616
5617/**
5618 * Returns the lock handle which protects the machines list. As opposed
5619 * to version 3.1 and earlier, these lists are no longer protected by the
5620 * VirtualBox lock, but by this more specialized lock. Mind the locking
5621 * order: always request this lock after the VirtualBox object lock but
5622 * before the locks of any machine object. See AutoLock.h.
5623 */
5624RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
5625{
5626 return m->lockMachines;
5627}
5628
5629/**
5630 * Returns the lock handle which protects the media trees (hard disks,
5631 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
5632 * are no longer protected by the VirtualBox lock, but by this more
5633 * specialized lock. Mind the locking order: always request this lock
5634 * after the VirtualBox object lock but before the locks of the media
5635 * objects contained in these lists. See AutoLock.h.
5636 */
5637RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
5638{
5639 return m->lockMedia;
5640}
5641
5642/**
5643 * Thread function that handles custom events posted using #i_postEvent().
5644 */
5645// static
5646DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
5647{
5648 LogFlowFuncEnter();
5649
5650 AssertReturn(pvUser, VERR_INVALID_POINTER);
5651
5652 HRESULT hr = com::Initialize();
5653 if (FAILED(hr))
5654 return VERR_COM_UNEXPECTED;
5655
5656 int rc = VINF_SUCCESS;
5657
5658 try
5659 {
5660 /* Create an event queue for the current thread. */
5661 EventQueue *pEventQueue = new EventQueue();
5662 AssertPtr(pEventQueue);
5663
5664 /* Return the queue to the one who created this thread. */
5665 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
5666
5667 /* signal that we're ready. */
5668 RTThreadUserSignal(thread);
5669
5670 /*
5671 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
5672 * we must not stop processing events and delete the pEventQueue object. This must
5673 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
5674 * See @bugref{5724}.
5675 */
5676 for (;;)
5677 {
5678 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
5679 if (rc == VERR_INTERRUPTED)
5680 {
5681 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
5682 rc = VINF_SUCCESS; /* Set success when exiting. */
5683 break;
5684 }
5685 }
5686
5687 delete pEventQueue;
5688 }
5689 catch (std::bad_alloc &ba)
5690 {
5691 rc = VERR_NO_MEMORY;
5692 NOREF(ba);
5693 }
5694
5695 com::Shutdown();
5696
5697 LogFlowFuncLeaveRC(rc);
5698 return rc;
5699}
5700
5701
5702////////////////////////////////////////////////////////////////////////////////
5703
5704#if 0 /* obsoleted by AsyncEvent */
5705/**
5706 * Prepare the event using the overwritten #prepareEventDesc method and fire.
5707 *
5708 * @note Locks the managed VirtualBox object for reading but leaves the lock
5709 * before iterating over callbacks and calling their methods.
5710 */
5711void *VirtualBox::CallbackEvent::handler()
5712{
5713 if (!mVirtualBox)
5714 return NULL;
5715
5716 AutoCaller autoCaller(mVirtualBox);
5717 if (!autoCaller.isOk())
5718 {
5719 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
5720 mVirtualBox->getObjectState().getState()));
5721 /* We don't need mVirtualBox any more, so release it */
5722 mVirtualBox = NULL;
5723 return NULL;
5724 }
5725
5726 {
5727 VBoxEventDesc evDesc;
5728 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
5729
5730 evDesc.fire(/* don't wait for delivery */0);
5731 }
5732
5733 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
5734 return NULL;
5735}
5736#endif
5737
5738/**
5739 * Called on the event handler thread.
5740 *
5741 * @note Locks the managed VirtualBox object for reading but leaves the lock
5742 * before iterating over callbacks and calling their methods.
5743 */
5744void *VirtualBox::AsyncEvent::handler()
5745{
5746 if (mVirtualBox)
5747 {
5748 AutoCaller autoCaller(mVirtualBox);
5749 if (autoCaller.isOk())
5750 {
5751 VBoxEventDesc EvtDesc(mEvent, mVirtualBox->m->pEventSource);
5752 EvtDesc.fire(/* don't wait for delivery */0);
5753 }
5754 else
5755 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
5756 mVirtualBox->getObjectState().getState()));
5757 mVirtualBox = NULL; /* Old code did this, not really necessary, but whatever. */
5758 }
5759 mEvent.setNull();
5760 return NULL;
5761}
5762
5763//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
5764//{
5765// return E_NOTIMPL;
5766//}
5767
5768HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
5769 ComPtr<IDHCPServer> &aServer)
5770{
5771 ComObjPtr<DHCPServer> dhcpServer;
5772 dhcpServer.createObject();
5773 HRESULT rc = dhcpServer->init(this, aName);
5774 if (FAILED(rc)) return rc;
5775
5776 rc = i_registerDHCPServer(dhcpServer, true);
5777 if (FAILED(rc)) return rc;
5778
5779 dhcpServer.queryInterfaceTo(aServer.asOutParam());
5780
5781 return rc;
5782}
5783
5784HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
5785 ComPtr<IDHCPServer> &aServer)
5786{
5787 HRESULT rc = S_OK;
5788 ComPtr<DHCPServer> found;
5789
5790 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5791
5792 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5793 it != m->allDHCPServers.end();
5794 ++it)
5795 {
5796 Bstr bstrNetworkName;
5797 rc = (*it)->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
5798 if (FAILED(rc)) return rc;
5799
5800 if (Utf8Str(bstrNetworkName) == aName)
5801 {
5802 found = *it;
5803 break;
5804 }
5805 }
5806
5807 if (!found)
5808 return E_INVALIDARG;
5809
5810 rc = found.queryInterfaceTo(aServer.asOutParam());
5811
5812 return rc;
5813}
5814
5815HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
5816{
5817 IDHCPServer *aP = aServer;
5818
5819 HRESULT rc = i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
5820
5821 return rc;
5822}
5823
5824/**
5825 * Remembers the given DHCP server in the settings.
5826 *
5827 * @param aDHCPServer DHCP server object to remember.
5828 * @param aSaveSettings @c true to save settings to disk (default).
5829 *
5830 * When @a aSaveSettings is @c true, this operation may fail because of the
5831 * failed #i_saveSettings() method it calls. In this case, the dhcp server object
5832 * will not be remembered. It is therefore the responsibility of the caller to
5833 * call this method as the last step of some action that requires registration
5834 * in order to make sure that only fully functional dhcp server objects get
5835 * registered.
5836 *
5837 * @note Locks this object for writing and @a aDHCPServer for reading.
5838 */
5839HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
5840 bool aSaveSettings /*= true*/)
5841{
5842 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5843
5844 AutoCaller autoCaller(this);
5845 AssertComRCReturnRC(autoCaller.rc());
5846
5847 // Acquire a lock on the VirtualBox object early to avoid lock order issues
5848 // when we call i_saveSettings() later on.
5849 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5850 // need it below, in findDHCPServerByNetworkName (reading) and in
5851 // m->allDHCPServers.addChild, so need to get it here to avoid lock
5852 // order trouble with dhcpServerCaller
5853 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5854
5855 AutoCaller dhcpServerCaller(aDHCPServer);
5856 AssertComRCReturnRC(dhcpServerCaller.rc());
5857
5858 Bstr bstrNetworkName;
5859 HRESULT rc = S_OK;
5860 rc = aDHCPServer->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
5861 if (FAILED(rc)) return rc;
5862
5863 ComPtr<IDHCPServer> existing;
5864 rc = findDHCPServerByNetworkName(Utf8Str(bstrNetworkName), existing);
5865 if (SUCCEEDED(rc))
5866 return E_INVALIDARG;
5867 rc = S_OK;
5868
5869 m->allDHCPServers.addChild(aDHCPServer);
5870 // we need to release the list lock before we attempt to acquire locks
5871 // on other objects in i_saveSettings (see @bugref{7500})
5872 alock.release();
5873
5874 if (aSaveSettings)
5875 {
5876 // we acquired the lock on 'this' earlier to avoid lock order issues
5877 rc = i_saveSettings();
5878
5879 if (FAILED(rc))
5880 {
5881 alock.acquire();
5882 m->allDHCPServers.removeChild(aDHCPServer);
5883 }
5884 }
5885
5886 return rc;
5887}
5888
5889/**
5890 * Removes the given DHCP server from the settings.
5891 *
5892 * @param aDHCPServer DHCP server object to remove.
5893 *
5894 * This operation may fail because of the failed #i_saveSettings() method it
5895 * calls. In this case, the DHCP server will NOT be removed from the settings
5896 * when this method returns.
5897 *
5898 * @note Locks this object for writing.
5899 */
5900HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
5901{
5902 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5903
5904 AutoCaller autoCaller(this);
5905 AssertComRCReturnRC(autoCaller.rc());
5906
5907 AutoCaller dhcpServerCaller(aDHCPServer);
5908 AssertComRCReturnRC(dhcpServerCaller.rc());
5909
5910 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5911 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5912 m->allDHCPServers.removeChild(aDHCPServer);
5913 // we need to release the list lock before we attempt to acquire locks
5914 // on other objects in i_saveSettings (see @bugref{7500})
5915 alock.release();
5916
5917 HRESULT rc = i_saveSettings();
5918
5919 // undo the changes if we failed to save them
5920 if (FAILED(rc))
5921 {
5922 alock.acquire();
5923 m->allDHCPServers.addChild(aDHCPServer);
5924 }
5925
5926 return rc;
5927}
5928
5929
5930/**
5931 * NAT Network
5932 */
5933HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
5934 ComPtr<INATNetwork> &aNetwork)
5935{
5936#ifdef VBOX_WITH_NAT_SERVICE
5937 ComObjPtr<NATNetwork> natNetwork;
5938 natNetwork.createObject();
5939 HRESULT rc = natNetwork->init(this, aNetworkName);
5940 if (FAILED(rc)) return rc;
5941
5942 rc = i_registerNATNetwork(natNetwork, true);
5943 if (FAILED(rc)) return rc;
5944
5945 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
5946
5947 ::FireNATNetworkCreationDeletionEvent(m->pEventSource, aNetworkName, TRUE);
5948
5949 return rc;
5950#else
5951 NOREF(aNetworkName);
5952 NOREF(aNetwork);
5953 return E_NOTIMPL;
5954#endif
5955}
5956
5957HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
5958 ComPtr<INATNetwork> &aNetwork)
5959{
5960#ifdef VBOX_WITH_NAT_SERVICE
5961
5962 HRESULT rc = S_OK;
5963 ComPtr<NATNetwork> found;
5964
5965 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5966
5967 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
5968 it != m->allNATNetworks.end();
5969 ++it)
5970 {
5971 Bstr bstrNATNetworkName;
5972 rc = (*it)->COMGETTER(NetworkName)(bstrNATNetworkName.asOutParam());
5973 if (FAILED(rc)) return rc;
5974
5975 if (Utf8Str(bstrNATNetworkName) == aNetworkName)
5976 {
5977 found = *it;
5978 break;
5979 }
5980 }
5981
5982 if (!found)
5983 return E_INVALIDARG;
5984 found.queryInterfaceTo(aNetwork.asOutParam());
5985 return rc;
5986#else
5987 NOREF(aNetworkName);
5988 NOREF(aNetwork);
5989 return E_NOTIMPL;
5990#endif
5991}
5992
5993HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
5994{
5995#ifdef VBOX_WITH_NAT_SERVICE
5996 Bstr name;
5997 HRESULT rc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
5998 if (FAILED(rc))
5999 return rc;
6000 INATNetwork *p = aNetwork;
6001 NATNetwork *network = static_cast<NATNetwork *>(p);
6002 rc = i_unregisterNATNetwork(network, true);
6003 ::FireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
6004 return rc;
6005#else
6006 NOREF(aNetwork);
6007 return E_NOTIMPL;
6008#endif
6009
6010}
6011/**
6012 * Remembers the given NAT network in the settings.
6013 *
6014 * @param aNATNetwork NAT Network object to remember.
6015 * @param aSaveSettings @c true to save settings to disk (default).
6016 *
6017 *
6018 * @note Locks this object for writing and @a aNATNetwork for reading.
6019 */
6020HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
6021 bool aSaveSettings /*= true*/)
6022{
6023#ifdef VBOX_WITH_NAT_SERVICE
6024 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
6025
6026 AutoCaller autoCaller(this);
6027 AssertComRCReturnRC(autoCaller.rc());
6028
6029 AutoCaller natNetworkCaller(aNATNetwork);
6030 AssertComRCReturnRC(natNetworkCaller.rc());
6031
6032 Bstr name;
6033 HRESULT rc;
6034 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
6035 AssertComRCReturnRC(rc);
6036
6037 /* returned value isn't 0 and aSaveSettings is true
6038 * means that we create duplicate, otherwise we just load settings.
6039 */
6040 if ( sNatNetworkNameToRefCount[name]
6041 && aSaveSettings)
6042 AssertComRCReturnRC(E_INVALIDARG);
6043
6044 rc = S_OK;
6045
6046 sNatNetworkNameToRefCount[name] = 0;
6047
6048 m->allNATNetworks.addChild(aNATNetwork);
6049
6050 if (aSaveSettings)
6051 {
6052 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6053 rc = i_saveSettings();
6054 vboxLock.release();
6055
6056 if (FAILED(rc))
6057 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
6058 }
6059
6060 return rc;
6061#else
6062 NOREF(aNATNetwork);
6063 NOREF(aSaveSettings);
6064 /* No panic please (silently ignore) */
6065 return S_OK;
6066#endif
6067}
6068
6069/**
6070 * Removes the given NAT network from the settings.
6071 *
6072 * @param aNATNetwork NAT network object to remove.
6073 * @param aSaveSettings @c true to save settings to disk (default).
6074 *
6075 * When @a aSaveSettings is @c true, this operation may fail because of the
6076 * failed #i_saveSettings() method it calls. In this case, the DHCP server
6077 * will NOT be removed from the settingsi when this method returns.
6078 *
6079 * @note Locks this object for writing.
6080 */
6081HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
6082 bool aSaveSettings /*= true*/)
6083{
6084#ifdef VBOX_WITH_NAT_SERVICE
6085 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
6086
6087 AutoCaller autoCaller(this);
6088 AssertComRCReturnRC(autoCaller.rc());
6089
6090 AutoCaller natNetworkCaller(aNATNetwork);
6091 AssertComRCReturnRC(natNetworkCaller.rc());
6092
6093 Bstr name;
6094 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
6095 /* Hm, there're still running clients. */
6096 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
6097 AssertComRCReturnRC(E_INVALIDARG);
6098
6099 m->allNATNetworks.removeChild(aNATNetwork);
6100
6101 if (aSaveSettings)
6102 {
6103 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6104 rc = i_saveSettings();
6105 vboxLock.release();
6106
6107 if (FAILED(rc))
6108 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
6109 }
6110
6111 return rc;
6112#else
6113 NOREF(aNATNetwork);
6114 NOREF(aSaveSettings);
6115 return E_NOTIMPL;
6116#endif
6117}
6118
6119
6120HRESULT VirtualBox::findProgressById(const com::Guid &aId,
6121 ComPtr<IProgress> &aProgressObject)
6122{
6123 if (!aId.isValid())
6124 return setError(E_INVALIDARG,
6125 tr("The provided progress object GUID is invalid"));
6126
6127 /* protect mProgressOperations */
6128 AutoReadLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
6129
6130 ProgressMap::const_iterator it = m->mapProgressOperations.find(aId);
6131 if (it != m->mapProgressOperations.end())
6132 {
6133 aProgressObject = it->second;
6134 return S_OK;
6135 }
6136 return setError(E_INVALIDARG,
6137 tr("The progress object with the given GUID could not be found"));
6138}
6139
6140
6141/**
6142 * Retains a reference to the default cryptographic interface.
6143 *
6144 * @returns COM status code.
6145 * @param ppCryptoIf Where to store the pointer to the cryptographic interface on success.
6146 *
6147 * @note Locks this object for writing.
6148 */
6149HRESULT VirtualBox::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
6150{
6151 AssertReturn(ppCryptoIf != NULL, E_INVALIDARG);
6152
6153 AutoCaller autoCaller(this);
6154 AssertComRCReturnRC(autoCaller.rc());
6155
6156 /*
6157 * No object lock due to some lock order fun with Machine objects.
6158 * There is a dedicated critical section to protect against concurrency
6159 * issues when loading the module.
6160 */
6161 RTCritSectEnter(&m->CritSectModCrypto);
6162
6163 /* Try to load the extension pack module if it isn't currently. */
6164 HRESULT hrc = S_OK;
6165 if (m->hLdrModCrypto == NIL_RTLDRMOD)
6166 {
6167#ifdef VBOX_WITH_EXTPACK
6168 /*
6169 * Check that a crypto extension pack name is set and resolve it into a
6170 * library path.
6171 */
6172 Utf8Str strExtPack;
6173 hrc = m->pSystemProperties->getDefaultCryptoExtPack(strExtPack);
6174 if (FAILED(hrc))
6175 return hrc;
6176 if (strExtPack.isEmpty())
6177 return setError(VBOX_E_OBJECT_NOT_FOUND,
6178 tr("Ńo extension pack providing a cryptographic support module could be found"));
6179
6180 Utf8Str strCryptoLibrary;
6181 int vrc = m->ptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
6182 if (RT_SUCCESS(vrc))
6183 {
6184 RTERRINFOSTATIC ErrInfo;
6185 vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &m->hLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
6186 if (RT_SUCCESS(vrc))
6187 {
6188 /* Resolve the entry point and query the pointer to the cryptographic interface. */
6189 PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
6190 vrc = RTLdrGetSymbol(m->hLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
6191 if (RT_SUCCESS(vrc))
6192 {
6193 vrc = pfnCryptoEntry(&m->pCryptoIf);
6194 if (RT_FAILURE(vrc))
6195 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6196 tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
6197 strCryptoLibrary.c_str(), strExtPack.c_str());
6198 }
6199 else
6200 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6201 tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
6202 strCryptoLibrary.c_str(), strExtPack.c_str());
6203 }
6204 else
6205 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6206 tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
6207 strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
6208 }
6209 else
6210 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6211 tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
6212 strExtPack.c_str());
6213#else
6214 hrc = setError(VBOX_E_NOT_SUPPORTED,
6215 tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
6216#endif
6217 }
6218
6219 if (SUCCEEDED(hrc))
6220 {
6221 ASMAtomicIncU32(&m->cRefsCrypto);
6222 *ppCryptoIf = m->pCryptoIf;
6223 }
6224
6225 RTCritSectLeave(&m->CritSectModCrypto);
6226
6227 return hrc;
6228}
6229
6230
6231/**
6232 * Releases the reference of the given cryptographic interface.
6233 *
6234 * @returns COM status code.
6235 * @param pCryptoIf Pointer to the cryptographic interface to release.
6236 *
6237 * @note Locks this object for writing.
6238 */
6239HRESULT VirtualBox::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
6240{
6241 AutoCaller autoCaller(this);
6242 AssertComRCReturnRC(autoCaller.rc());
6243
6244 AssertReturn(pCryptoIf == m->pCryptoIf, E_INVALIDARG);
6245
6246 ASMAtomicDecU32(&m->cRefsCrypto);
6247 return S_OK;
6248}
6249
6250
6251/**
6252 * Tries to unload any loaded cryptographic support module if it is not in use currently.
6253 *
6254 * @returns COM status code.
6255 *
6256 * @note Locks this object for writing.
6257 */
6258HRESULT VirtualBox::i_unloadCryptoIfModule(void)
6259{
6260 AutoCaller autoCaller(this);
6261 AssertComRCReturnRC(autoCaller.rc());
6262
6263 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
6264
6265 if (m->cRefsCrypto)
6266 return setError(E_ACCESSDENIED,
6267 tr("The cryptographic support module is in use and can't be unloaded"));
6268
6269 RTCritSectEnter(&m->CritSectModCrypto);
6270 if (m->hLdrModCrypto != NIL_RTLDRMOD)
6271 {
6272 int vrc = RTLdrClose(m->hLdrModCrypto);
6273 AssertRC(vrc);
6274 m->hLdrModCrypto = NIL_RTLDRMOD;
6275 }
6276 RTCritSectLeave(&m->CritSectModCrypto);
6277
6278 return S_OK;
6279}
6280
6281
6282#ifdef RT_OS_WINDOWS
6283#include <psapi.h>
6284
6285/**
6286 * Report versions of installed drivers to release log.
6287 */
6288void VirtualBox::i_reportDriverVersions()
6289{
6290 /** @todo r=klaus this code is very confusing, as it uses TCHAR (and
6291 * randomly also _TCHAR, which sounds to me like asking for trouble),
6292 * the "sz" variable prefix but "%ls" for the format string - so the whole
6293 * thing is better compiled with UNICODE and _UNICODE defined. Would be
6294 * far easier to read if it would be coded explicitly for the unicode
6295 * case, as it won't work otherwise. */
6296 DWORD err;
6297 HRESULT hrc;
6298 LPVOID aDrivers[1024];
6299 LPVOID *pDrivers = aDrivers;
6300 UINT cNeeded = 0;
6301 TCHAR szSystemRoot[MAX_PATH];
6302 TCHAR *pszSystemRoot = szSystemRoot;
6303 LPVOID pVerInfo = NULL;
6304 DWORD cbVerInfo = 0;
6305
6306 do
6307 {
6308 cNeeded = GetWindowsDirectory(szSystemRoot, RT_ELEMENTS(szSystemRoot));
6309 if (cNeeded == 0)
6310 {
6311 err = GetLastError();
6312 hrc = HRESULT_FROM_WIN32(err);
6313 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
6314 hrc, hrc, err));
6315 break;
6316 }
6317 else if (cNeeded > RT_ELEMENTS(szSystemRoot))
6318 {
6319 /* The buffer is too small, allocate big one. */
6320 pszSystemRoot = (TCHAR *)RTMemTmpAlloc(cNeeded * sizeof(_TCHAR));
6321 if (!pszSystemRoot)
6322 {
6323 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cNeeded));
6324 break;
6325 }
6326 if (GetWindowsDirectory(pszSystemRoot, 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 }
6335
6336 DWORD cbNeeded = 0;
6337 if (!EnumDeviceDrivers(aDrivers, sizeof(aDrivers), &cbNeeded) || cbNeeded > sizeof(aDrivers))
6338 {
6339 pDrivers = (LPVOID *)RTMemTmpAlloc(cbNeeded);
6340 if (!EnumDeviceDrivers(pDrivers, cbNeeded, &cbNeeded))
6341 {
6342 err = GetLastError();
6343 hrc = HRESULT_FROM_WIN32(err);
6344 AssertLogRelMsgFailed(("EnumDeviceDrivers failed, hr=%Rhrc (0x%x) err=%u\n",
6345 hrc, hrc, err));
6346 break;
6347 }
6348 }
6349
6350 LogRel(("Installed Drivers:\n"));
6351
6352 TCHAR szDriver[1024];
6353 int cDrivers = cbNeeded / sizeof(pDrivers[0]);
6354 for (int i = 0; i < cDrivers; i++)
6355 {
6356 if (GetDeviceDriverBaseName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
6357 {
6358 if (_tcsnicmp(TEXT("vbox"), szDriver, 4))
6359 continue;
6360 }
6361 else
6362 continue;
6363 if (GetDeviceDriverFileName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
6364 {
6365 _TCHAR szTmpDrv[1024];
6366 _TCHAR *pszDrv = szDriver;
6367 if (!_tcsncmp(TEXT("\\SystemRoot"), szDriver, 11))
6368 {
6369 _tcscpy_s(szTmpDrv, pszSystemRoot);
6370 _tcsncat_s(szTmpDrv, szDriver + 11, sizeof(szTmpDrv) / sizeof(szTmpDrv[0]) - _tclen(pszSystemRoot));
6371 pszDrv = szTmpDrv;
6372 }
6373 else if (!_tcsncmp(TEXT("\\??\\"), szDriver, 4))
6374 pszDrv = szDriver + 4;
6375
6376 /* Allocate a buffer for version info. Reuse if large enough. */
6377 DWORD cbNewVerInfo = GetFileVersionInfoSize(pszDrv, NULL);
6378 if (cbNewVerInfo > cbVerInfo)
6379 {
6380 if (pVerInfo)
6381 RTMemTmpFree(pVerInfo);
6382 cbVerInfo = cbNewVerInfo;
6383 pVerInfo = RTMemTmpAlloc(cbVerInfo);
6384 if (!pVerInfo)
6385 {
6386 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cbVerInfo));
6387 break;
6388 }
6389 }
6390
6391 if (GetFileVersionInfo(pszDrv, NULL, cbVerInfo, pVerInfo))
6392 {
6393 UINT cbSize = 0;
6394 LPBYTE lpBuffer = NULL;
6395 if (VerQueryValue(pVerInfo, TEXT("\\"), (VOID FAR* FAR*)&lpBuffer, &cbSize))
6396 {
6397 if (cbSize)
6398 {
6399 VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
6400 if (pFileInfo->dwSignature == 0xfeef04bd)
6401 {
6402 LogRel((" %ls (Version: %d.%d.%d.%d)\n", pszDrv,
6403 (pFileInfo->dwFileVersionMS >> 16) & 0xffff,
6404 (pFileInfo->dwFileVersionMS >> 0) & 0xffff,
6405 (pFileInfo->dwFileVersionLS >> 16) & 0xffff,
6406 (pFileInfo->dwFileVersionLS >> 0) & 0xffff));
6407 }
6408 }
6409 }
6410 }
6411 }
6412 }
6413
6414 }
6415 while (0);
6416
6417 if (pVerInfo)
6418 RTMemTmpFree(pVerInfo);
6419
6420 if (pDrivers != aDrivers)
6421 RTMemTmpFree(pDrivers);
6422
6423 if (pszSystemRoot != szSystemRoot)
6424 RTMemTmpFree(pszSystemRoot);
6425}
6426#else /* !RT_OS_WINDOWS */
6427void VirtualBox::i_reportDriverVersions(void)
6428{
6429}
6430#endif /* !RT_OS_WINDOWS */
6431
6432#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
6433
6434# include <psapi.h> /* for GetProcessImageFileNameW */
6435
6436/**
6437 * Callout from the wrapper.
6438 */
6439void VirtualBox::i_callHook(const char *a_pszFunction)
6440{
6441 RT_NOREF(a_pszFunction);
6442
6443 /*
6444 * Let'see figure out who is calling.
6445 * Note! Requires Vista+, so skip this entirely on older systems.
6446 */
6447 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
6448 {
6449 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
6450 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
6451 if ( rcRpc == RPC_S_OK
6452 && CallAttribs.ClientPID != 0)
6453 {
6454 RTPROCESS const pidClient = (RTPROCESS)(uintptr_t)CallAttribs.ClientPID;
6455 if (pidClient != RTProcSelf())
6456 {
6457 /** @todo LogRel2 later: */
6458 LogRel(("i_callHook: %Rfn [ClientPID=%#zx/%zu IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6459 a_pszFunction, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
6460 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6461 &CallAttribs.InterfaceUuid));
6462
6463 /*
6464 * Do we know this client PID already?
6465 */
6466 RTCritSectRwEnterShared(&m->WatcherCritSect);
6467 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(pidClient);
6468 if (It != m->WatchedProcesses.end())
6469 RTCritSectRwLeaveShared(&m->WatcherCritSect); /* Known process, nothing to do. */
6470 else
6471 {
6472 /* This is a new client process, start watching it. */
6473 RTCritSectRwLeaveShared(&m->WatcherCritSect);
6474 i_watchClientProcess(pidClient, a_pszFunction);
6475 }
6476 }
6477 }
6478 else
6479 LogRel(("i_callHook: %Rfn - rcRpc=%#x ClientPID=%#zx/%zu !! [IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6480 a_pszFunction, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
6481 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6482 &CallAttribs.InterfaceUuid));
6483 }
6484}
6485
6486
6487/**
6488 * Watches @a a_pidClient for termination.
6489 *
6490 * @returns true if successfully enabled watching of it, false if not.
6491 * @param a_pidClient The PID to watch.
6492 * @param a_pszFunction The function we which we detected the client in.
6493 */
6494bool VirtualBox::i_watchClientProcess(RTPROCESS a_pidClient, const char *a_pszFunction)
6495{
6496 RT_NOREF_PV(a_pszFunction);
6497
6498 /*
6499 * Open the client process.
6500 */
6501 HANDLE hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE /*fInherit*/, a_pidClient);
6502 if (hClient == NULL)
6503 hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE , a_pidClient);
6504 if (hClient == NULL)
6505 hClient = OpenProcess(SYNCHRONIZE, FALSE , a_pidClient);
6506 AssertLogRelMsgReturn(hClient != NULL, ("pidClient=%d (%#x) err=%d\n", a_pidClient, a_pidClient, GetLastError()),
6507 m->fWatcherIsReliable = false);
6508
6509 /*
6510 * Create a new watcher structure and try add it to the map.
6511 */
6512 bool fRet = true;
6513 WatchedClientProcess *pWatched = new (std::nothrow) WatchedClientProcess(a_pidClient, hClient);
6514 if (pWatched)
6515 {
6516 RTCritSectRwEnterExcl(&m->WatcherCritSect);
6517
6518 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(a_pidClient);
6519 if (It == m->WatchedProcesses.end())
6520 {
6521 try
6522 {
6523 m->WatchedProcesses.insert(WatchedClientProcessMap::value_type(a_pidClient, pWatched));
6524 }
6525 catch (std::bad_alloc &)
6526 {
6527 fRet = false;
6528 }
6529 if (fRet)
6530 {
6531 /*
6532 * Schedule it on a watcher thread.
6533 */
6534 /** @todo later. */
6535 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6536 }
6537 else
6538 {
6539 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6540 delete pWatched;
6541 LogRel(("VirtualBox::i_watchClientProcess: out of memory inserting into client map!\n"));
6542 }
6543 }
6544 else
6545 {
6546 /*
6547 * Someone raced us here, we lost.
6548 */
6549 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6550 delete pWatched;
6551 }
6552 }
6553 else
6554 {
6555 LogRel(("VirtualBox::i_watchClientProcess: out of memory!\n"));
6556 CloseHandle(hClient);
6557 m->fWatcherIsReliable = fRet = false;
6558 }
6559 return fRet;
6560}
6561
6562
6563/** Logs the RPC caller info to the release log. */
6564/*static*/ void VirtualBox::i_logCaller(const char *a_pszFormat, ...)
6565{
6566 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
6567 {
6568 char szTmp[80];
6569 va_list va;
6570 va_start(va, a_pszFormat);
6571 RTStrPrintfV(szTmp, sizeof(szTmp), a_pszFormat, va);
6572 va_end(va);
6573
6574 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
6575 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
6576
6577 RTUTF16 wszProcName[256];
6578 wszProcName[0] = '\0';
6579 if (rcRpc == 0 && CallAttribs.ClientPID != 0)
6580 {
6581 HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)(uintptr_t)CallAttribs.ClientPID);
6582 if (hProcess)
6583 {
6584 RT_ZERO(wszProcName);
6585 GetProcessImageFileNameW(hProcess, wszProcName, RT_ELEMENTS(wszProcName) - 1);
6586 CloseHandle(hProcess);
6587 }
6588 }
6589 LogRel(("%s [rcRpc=%#x ClientPID=%#zx/%zu (%ls) IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6590 szTmp, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, wszProcName, CallAttribs.IsClientLocal,
6591 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6592 &CallAttribs.InterfaceUuid));
6593 }
6594}
6595
6596#endif /* RT_OS_WINDOWS && VBOXSVC_WITH_CLIENT_WATCHER */
6597
6598
6599/* 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