VirtualBox

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

Last change on this file since 107402 was 107239, checked in by vboxsync, 6 weeks ago

bugref: 10806. Added new parameters to IVirtualBox::getTrackedObject(). Added new TrackedObjectState enum. jiraref: VBP-1187.

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