VirtualBox

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

Last change on this file since 101041 was 101035, checked in by vboxsync, 18 months ago

Initial commit (based draft v2 / on patch v5) for implementing platform architecture support for x86 and ARM. bugref:10384

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

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