VirtualBox

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

Last change on this file since 101069 was 101069, checked in by vboxsync, 21 months ago

Main: Override the platform architecture in IVirtualBox::createMachine(), to only allow same-same architectures for now. See comment for details. bugref:10384

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