VirtualBox

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

Last change on this file since 101164 was 101164, checked in by vboxsync, 20 months ago

doc/manual,Frontends/VBoxManage,Main/{Global,GuestOSType,VirtualBox.xidl}:
Extend the OSType struct by including a new element named 'variant'
to provide further guest OS details and aid in guest OS categorization
for the GUI when creating VMs. Populate this field in the
Global::sOSTypes[] table for Linux using the distro name and for BSD
using the BSD flavour. Include the variant information in 'VBoxManage
list ostypes' and add a new 'VBoxManage list osvariants' subcommand.
Add new IVirtualBox methods for accessing the guest OS variant
information: getGuestOSVariantsByFamilyId() and getGuestOSDescsByVariant().
bugref:5936

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

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