VirtualBox

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

Last change on this file since 100841 was 100737, checked in by vboxsync, 17 months ago

API/FE/Qt: bugref:10466. bugref:10465. Adding a new event to signal successful uninstallation of extension pack. And GUI side of the code to handl this event.

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