VirtualBox

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

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

Main: Removed own debug #define. bugref:10384

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