VirtualBox

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

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

Main: Added IPlatformProperties::supportedGuestOSTypes() getter to return supported guest OS types for a specific platform. The IVirtualBox::guestOSTypes() getter in turn will return all guest OS types for all platforms. bugref:10384

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