VirtualBox

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

最後變更 在這個檔案從107552是 107539,由 vboxsync 提交於 2 月 前

src/VBox/Main/src-server/VirtualBoxImpl.cpp: Fixed warnings found by Parfait (uninitialized attributes). jiraref:VBP-1424

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 231.6 KB
 
1/* $Id: VirtualBoxImpl.cpp 107539 2025-01-08 16:26:57Z 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.alldomusa.eu.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 privileged = false;
3252 func = NULL;
3253 user = NULL;
3254 }
3255
3256 virtual ~StartSVCHelperClientData()
3257 {
3258 LogFlowFuncEnter();
3259 if (threadVoidData!=NULL)
3260 {
3261 delete threadVoidData;
3262 threadVoidData=NULL;
3263 }
3264 };
3265
3266 void handler()
3267 {
3268 VirtualBox::i_SVCHelperClientThreadTask(this);
3269 }
3270
3271 const ComPtr<Progress>& GetProgressObject() const {return progress;}
3272
3273 bool init(VirtualBox* aVbox,
3274 Progress* aProgress,
3275 bool aPrivileged,
3276 VirtualBox::PFN_SVC_HELPER_CLIENT_T aFunc,
3277 void *aUser)
3278 {
3279 LogFlowFuncEnter();
3280 that = aVbox;
3281 progress = aProgress;
3282 privileged = aPrivileged;
3283 func = aFunc;
3284 user = aUser;
3285
3286 initThreadVoidData();
3287
3288 initialized = true;
3289
3290 return initialized;
3291 }
3292
3293 bool isOk() const{ return initialized;}
3294
3295 bool initialized;
3296 ComObjPtr<VirtualBox> that;
3297 ComObjPtr<Progress> progress;
3298 bool privileged;
3299 VirtualBox::PFN_SVC_HELPER_CLIENT_T func;
3300 void *user;
3301 ThreadVoidData *threadVoidData;
3302
3303private:
3304 bool initThreadVoidData()
3305 {
3306 LogFlowFuncEnter();
3307 threadVoidData = static_cast<ThreadVoidData*>(user);
3308 return true;
3309 }
3310};
3311
3312/**
3313 * Helper method that starts a worker thread that:
3314 * - creates a pipe communication channel using SVCHlpClient;
3315 * - starts an SVC Helper process that will inherit this channel;
3316 * - executes the supplied function by passing it the created SVCHlpClient
3317 * and opened instance to communicate to the Helper process and the given
3318 * Progress object.
3319 *
3320 * The user function is supposed to communicate to the helper process
3321 * using the \a aClient argument to do the requested job and optionally expose
3322 * the progress through the \a aProgress object. The user function should never
3323 * call notifyComplete() on it: this will be done automatically using the
3324 * result code returned by the function.
3325 *
3326 * Before the user function is started, the communication channel passed to
3327 * the \a aClient argument is fully set up, the function should start using
3328 * its write() and read() methods directly.
3329 *
3330 * The \a aVrc parameter of the user function may be used to return an error
3331 * code if it is related to communication errors (for example, returned by
3332 * the SVCHlpClient members when they fail). In this case, the correct error
3333 * message using this value will be reported to the caller. Note that the
3334 * value of \a aVrc is inspected only if the user function itself returns
3335 * success.
3336 *
3337 * If a failure happens anywhere before the user function would be normally
3338 * called, it will be called anyway in special "cleanup only" mode indicated
3339 * by \a aClient, \a aProgress and \a aVrc arguments set to NULL. In this mode,
3340 * all the function is supposed to do is to cleanup its aUser argument if
3341 * necessary (it's assumed that the ownership of this argument is passed to
3342 * the user function once #startSVCHelperClient() returns a success, thus
3343 * making it responsible for the cleanup).
3344 *
3345 * After the user function returns, the thread will send the SVCHlpMsg::Null
3346 * message to indicate a process termination.
3347 *
3348 * @param aPrivileged |true| to start the SVC Helper process as a privileged
3349 * user that can perform administrative tasks
3350 * @param aFunc user function to run
3351 * @param aUser argument to the user function
3352 * @param aProgress progress object that will track operation completion
3353 *
3354 * @note aPrivileged is currently ignored (due to some unsolved problems in
3355 * Vista) and the process will be started as a normal (unprivileged)
3356 * process.
3357 *
3358 * @note Doesn't lock anything.
3359 */
3360HRESULT VirtualBox::i_startSVCHelperClient(bool aPrivileged,
3361 PFN_SVC_HELPER_CLIENT_T aFunc,
3362 void *aUser, Progress *aProgress)
3363{
3364 LogFlowFuncEnter();
3365 AssertReturn(aFunc, E_POINTER);
3366 AssertReturn(aProgress, E_POINTER);
3367
3368 AutoCaller autoCaller(this);
3369 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
3370
3371 /* create the i_SVCHelperClientThreadTask() argument */
3372
3373 HRESULT hrc = S_OK;
3374 StartSVCHelperClientData *pTask = NULL;
3375 try
3376 {
3377 pTask = new StartSVCHelperClientData();
3378
3379 pTask->init(this, aProgress, aPrivileged, aFunc, aUser);
3380
3381 if (!pTask->isOk())
3382 {
3383 delete pTask;
3384 LogRel(("Could not init StartSVCHelperClientData object \n"));
3385 throw E_FAIL;
3386 }
3387
3388 //this function delete pTask in case of exceptions, so there is no need in the call of delete operator
3389 hrc = pTask->createThreadWithType(RTTHREADTYPE_MAIN_WORKER);
3390
3391 }
3392 catch(std::bad_alloc &)
3393 {
3394 hrc = setError(E_OUTOFMEMORY);
3395 }
3396 catch(...)
3397 {
3398 LogRel(("Could not create thread for StartSVCHelperClientData \n"));
3399 hrc = E_FAIL;
3400 }
3401
3402 return hrc;
3403}
3404
3405/**
3406 * Worker thread for startSVCHelperClient().
3407 */
3408/* static */
3409void VirtualBox::i_SVCHelperClientThreadTask(StartSVCHelperClientData *pTask)
3410{
3411 LogFlowFuncEnter();
3412 HRESULT hrc = S_OK;
3413 bool userFuncCalled = false;
3414
3415 do
3416 {
3417 AssertBreakStmt(pTask, hrc = E_POINTER);
3418 AssertReturnVoid(!pTask->progress.isNull());
3419
3420 /* protect VirtualBox from uninitialization */
3421 AutoCaller autoCaller(pTask->that);
3422 if (!autoCaller.isOk())
3423 {
3424 /* it's too late */
3425 hrc = autoCaller.hrc();
3426 break;
3427 }
3428
3429 int vrc = VINF_SUCCESS;
3430
3431 Guid id;
3432 id.create();
3433 SVCHlpClient client;
3434 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
3435 id.raw()).c_str());
3436 if (RT_FAILURE(vrc))
3437 {
3438 hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not create the communication channel (%Rrc)"), vrc);
3439 break;
3440 }
3441
3442 /* get the path to the executable */
3443 char exePathBuf[RTPATH_MAX];
3444 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
3445 if (!exePath)
3446 {
3447 hrc = pTask->that->setError(E_FAIL, tr("Cannot get executable name"));
3448 break;
3449 }
3450
3451 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
3452
3453 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
3454
3455 RTPROCESS pid = NIL_RTPROCESS;
3456
3457 if (pTask->privileged)
3458 {
3459 /* Attempt to start a privileged process using the Run As dialog */
3460
3461 Bstr file = exePath;
3462 Bstr parameters = argsStr;
3463
3464 SHELLEXECUTEINFO shExecInfo;
3465
3466 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
3467
3468 shExecInfo.fMask = NULL;
3469 shExecInfo.hwnd = NULL;
3470 shExecInfo.lpVerb = L"runas";
3471 shExecInfo.lpFile = file.raw();
3472 shExecInfo.lpParameters = parameters.raw();
3473 shExecInfo.lpDirectory = NULL;
3474 shExecInfo.nShow = SW_NORMAL;
3475 shExecInfo.hInstApp = NULL;
3476
3477 if (!ShellExecuteEx(&shExecInfo))
3478 {
3479 int vrc2 = RTErrConvertFromWin32(GetLastError());
3480 /* hide excessive details in case of a frequent error
3481 * (pressing the Cancel button to close the Run As dialog) */
3482 if (vrc2 == VERR_CANCELLED)
3483 hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Operation canceled by the user"));
3484 else
3485 hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a privileged process '%s' (%Rrc)"), exePath, vrc2);
3486 break;
3487 }
3488 }
3489 else
3490 {
3491 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
3492 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
3493 if (RT_FAILURE(vrc))
3494 {
3495 hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
3496 break;
3497 }
3498 }
3499
3500 /* wait for the client to connect */
3501 vrc = client.connect();
3502 if (RT_SUCCESS(vrc))
3503 {
3504 /* start the user supplied function */
3505 hrc = pTask->func(&client, pTask->progress, pTask->user, &vrc);
3506 userFuncCalled = true;
3507 }
3508
3509 /* send the termination signal to the process anyway */
3510 {
3511 int vrc2 = client.write(SVCHlpMsg::Null);
3512 if (RT_SUCCESS(vrc))
3513 vrc = vrc2;
3514 }
3515
3516 if (SUCCEEDED(hrc) && RT_FAILURE(vrc))
3517 {
3518 hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not operate the communication channel (%Rrc)"), vrc);
3519 break;
3520 }
3521 }
3522 while (0);
3523
3524 if (FAILED(hrc) && !userFuncCalled)
3525 {
3526 /* call the user function in the "cleanup only" mode
3527 * to let it free resources passed to in aUser */
3528 pTask->func(NULL, NULL, pTask->user, NULL);
3529 }
3530
3531 pTask->progress->i_notifyComplete(hrc);
3532
3533 LogFlowFuncLeave();
3534}
3535
3536#endif /* RT_OS_WINDOWS */
3537
3538/**
3539 * Sends a signal to the client watcher to rescan the set of machines
3540 * that have open sessions.
3541 *
3542 * @note Doesn't lock anything.
3543 */
3544void VirtualBox::i_updateClientWatcher()
3545{
3546 AutoCaller autoCaller(this);
3547 AssertComRCReturnVoid(autoCaller.hrc());
3548
3549 AssertPtrReturnVoid(m->pClientWatcher);
3550 m->pClientWatcher->update();
3551}
3552
3553/**
3554 * Adds the given child process ID to the list of processes to be reaped.
3555 * This call should be followed by #i_updateClientWatcher() to take the effect.
3556 *
3557 * @note Doesn't lock anything.
3558 */
3559void VirtualBox::i_addProcessToReap(RTPROCESS pid)
3560{
3561 AutoCaller autoCaller(this);
3562 AssertComRCReturnVoid(autoCaller.hrc());
3563
3564 AssertPtrReturnVoid(m->pClientWatcher);
3565 m->pClientWatcher->addProcess(pid);
3566}
3567
3568/**
3569 * VD plugin load
3570 */
3571int VirtualBox::i_loadVDPlugin(const char *pszPluginLibrary)
3572{
3573 return m->pSystemProperties->i_loadVDPlugin(pszPluginLibrary);
3574}
3575
3576/**
3577 * VD plugin unload
3578 */
3579int VirtualBox::i_unloadVDPlugin(const char *pszPluginLibrary)
3580{
3581 return m->pSystemProperties->i_unloadVDPlugin(pszPluginLibrary);
3582}
3583
3584/**
3585 * @note Doesn't lock any object.
3586 */
3587void VirtualBox::i_onMediumRegistered(const Guid &aMediumId, const DeviceType_T aDevType, const BOOL aRegistered)
3588{
3589 ComPtr<IEvent> ptrEvent;
3590 HRESULT hrc = ::CreateMediumRegisteredEvent(ptrEvent.asOutParam(), m->pEventSource,
3591 aMediumId.toString(), aDevType, aRegistered);
3592 AssertComRCReturnVoid(hrc);
3593 i_postEvent(new AsyncEvent(this, ptrEvent));
3594}
3595
3596void VirtualBox::i_onMediumConfigChanged(IMedium *aMedium)
3597{
3598 ComPtr<IEvent> ptrEvent;
3599 HRESULT hrc = ::CreateMediumConfigChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aMedium);
3600 AssertComRCReturnVoid(hrc);
3601 i_postEvent(new AsyncEvent(this, ptrEvent));
3602}
3603
3604void VirtualBox::i_onMediumChanged(IMediumAttachment *aMediumAttachment)
3605{
3606 ComPtr<IEvent> ptrEvent;
3607 HRESULT hrc = ::CreateMediumChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aMediumAttachment);
3608 AssertComRCReturnVoid(hrc);
3609 i_postEvent(new AsyncEvent(this, ptrEvent));
3610}
3611
3612/**
3613 * @note Doesn't lock any object.
3614 */
3615void VirtualBox::i_onStorageControllerChanged(const Guid &aMachineId, const com::Utf8Str &aControllerName)
3616{
3617 ComPtr<IEvent> ptrEvent;
3618 HRESULT hrc = ::CreateStorageControllerChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
3619 aMachineId.toString(), aControllerName);
3620 AssertComRCReturnVoid(hrc);
3621 i_postEvent(new AsyncEvent(this, ptrEvent));
3622}
3623
3624void VirtualBox::i_onStorageDeviceChanged(IMediumAttachment *aStorageDevice, const BOOL fRemoved, const BOOL fSilent)
3625{
3626 ComPtr<IEvent> ptrEvent;
3627 HRESULT hrc = ::CreateStorageDeviceChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aStorageDevice, fRemoved, fSilent);
3628 AssertComRCReturnVoid(hrc);
3629 i_postEvent(new AsyncEvent(this, ptrEvent));
3630}
3631
3632/**
3633 * @note Doesn't lock any object.
3634 */
3635void VirtualBox::i_onMachineStateChanged(const Guid &aId, MachineState_T aState)
3636{
3637 ComPtr<IEvent> ptrEvent;
3638 HRESULT hrc = ::CreateMachineStateChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aState);
3639 AssertComRCReturnVoid(hrc);
3640 i_postEvent(new AsyncEvent(this, ptrEvent));
3641}
3642
3643/**
3644 * @note Doesn't lock any object.
3645 */
3646void VirtualBox::i_onMachineDataChanged(const Guid &aId, BOOL aTemporary)
3647{
3648 ComPtr<IEvent> ptrEvent;
3649 HRESULT hrc = ::CreateMachineDataChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aTemporary);
3650 AssertComRCReturnVoid(hrc);
3651 i_postEvent(new AsyncEvent(this, ptrEvent));
3652}
3653
3654/**
3655 * @note Doesn't lock any object.
3656 */
3657void VirtualBox::i_onMachineGroupsChanged(const Guid &aId)
3658{
3659 ComPtr<IEvent> ptrEvent;
3660 HRESULT hrc = ::CreateMachineGroupsChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), FALSE /*aDummy*/);
3661 AssertComRCReturnVoid(hrc);
3662 i_postEvent(new AsyncEvent(this, ptrEvent));
3663}
3664
3665/**
3666 * @note Locks this object for reading.
3667 */
3668BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, const Utf8Str &aKey, const Utf8Str &aValue, Bstr &aError)
3669{
3670 LogFlowThisFunc(("machine={%RTuuid} aKey={%s} aValue={%s}\n", aId.raw(), aKey.c_str(), aValue.c_str()));
3671
3672 AutoCaller autoCaller(this);
3673 AssertComRCReturn(autoCaller.hrc(), FALSE);
3674
3675 ComPtr<IEvent> ptrEvent;
3676 HRESULT hrc = ::CreateExtraDataCanChangeEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aKey, aValue);
3677 AssertComRCReturn(hrc, TRUE);
3678
3679 VBoxEventDesc EvtDesc(ptrEvent, m->pEventSource);
3680 BOOL fDelivered = EvtDesc.fire(3000); /* Wait up to 3 secs for delivery */
3681 //Assert(fDelivered);
3682 BOOL fAllowChange = TRUE;
3683 if (fDelivered)
3684 {
3685 ComPtr<IExtraDataCanChangeEvent> ptrCanChangeEvent = ptrEvent;
3686 Assert(ptrCanChangeEvent);
3687
3688 BOOL fVetoed = FALSE;
3689 ptrCanChangeEvent->IsVetoed(&fVetoed);
3690 fAllowChange = !fVetoed;
3691
3692 if (!fAllowChange)
3693 {
3694 SafeArray<BSTR> aVetos;
3695 ptrCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
3696 if (aVetos.size() > 0)
3697 aError = aVetos[0];
3698 }
3699 }
3700
3701 LogFlowThisFunc(("fAllowChange=%RTbool\n", fAllowChange));
3702 return fAllowChange;
3703}
3704
3705/**
3706 * @note Doesn't lock any object.
3707 */
3708void VirtualBox::i_onExtraDataChanged(const Guid &aId, const Utf8Str &aKey, const Utf8Str &aValue)
3709{
3710 ComPtr<IEvent> ptrEvent;
3711 HRESULT hrc = ::CreateExtraDataChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aKey, aValue);
3712 AssertComRCReturnVoid(hrc);
3713 i_postEvent(new AsyncEvent(this, ptrEvent));
3714}
3715
3716/**
3717 * @note Doesn't lock any object.
3718 */
3719void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
3720{
3721 ComPtr<IEvent> ptrEvent;
3722 HRESULT hrc = ::CreateMachineRegisteredEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aRegistered);
3723 AssertComRCReturnVoid(hrc);
3724 i_postEvent(new AsyncEvent(this, ptrEvent));
3725}
3726
3727/**
3728 * @note Doesn't lock any object.
3729 */
3730void VirtualBox::i_onSessionStateChanged(const Guid &aId, SessionState_T aState)
3731{
3732 ComPtr<IEvent> ptrEvent;
3733 HRESULT hrc = ::CreateSessionStateChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aState);
3734 AssertComRCReturnVoid(hrc);
3735 i_postEvent(new AsyncEvent(this, ptrEvent));
3736}
3737
3738/**
3739 * @note Doesn't lock any object.
3740 */
3741void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
3742{
3743 ComPtr<IEvent> ptrEvent;
3744 HRESULT hrc = ::CreateSnapshotTakenEvent(ptrEvent.asOutParam(), m->pEventSource,
3745 aMachineId.toString(), aSnapshotId.toString());
3746 AssertComRCReturnVoid(hrc);
3747 i_postEvent(new AsyncEvent(this, ptrEvent));
3748}
3749
3750/**
3751 * @note Doesn't lock any object.
3752 */
3753void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
3754{
3755 ComPtr<IEvent> ptrEvent;
3756 HRESULT hrc = ::CreateSnapshotDeletedEvent(ptrEvent.asOutParam(), m->pEventSource,
3757 aMachineId.toString(), aSnapshotId.toString());
3758 AssertComRCReturnVoid(hrc);
3759 i_postEvent(new AsyncEvent(this, ptrEvent));
3760}
3761
3762/**
3763 * @note Doesn't lock any object.
3764 */
3765void VirtualBox::i_onSnapshotRestored(const Guid &aMachineId, const Guid &aSnapshotId)
3766{
3767 ComPtr<IEvent> ptrEvent;
3768 HRESULT hrc = ::CreateSnapshotRestoredEvent(ptrEvent.asOutParam(), m->pEventSource,
3769 aMachineId.toString(), aSnapshotId.toString());
3770 AssertComRCReturnVoid(hrc);
3771 i_postEvent(new AsyncEvent(this, ptrEvent));
3772}
3773
3774/**
3775 * @note Doesn't lock any object.
3776 */
3777void VirtualBox::i_onSnapshotChanged(const Guid &aMachineId, const Guid &aSnapshotId)
3778{
3779 ComPtr<IEvent> ptrEvent;
3780 HRESULT hrc = ::CreateSnapshotChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
3781 aMachineId.toString(), aSnapshotId.toString());
3782 AssertComRCReturnVoid(hrc);
3783 i_postEvent(new AsyncEvent(this, ptrEvent));
3784}
3785
3786/**
3787 * @note Doesn't lock any object.
3788 */
3789void VirtualBox::i_onGuestPropertyChanged(const Guid &aMachineId, const Utf8Str &aName, const Utf8Str &aValue,
3790 const Utf8Str &aFlags, const BOOL fWasDeleted)
3791{
3792 ComPtr<IEvent> ptrEvent;
3793 HRESULT hrc = ::CreateGuestPropertyChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
3794 aMachineId.toString(), aName, aValue, aFlags, fWasDeleted);
3795 AssertComRCReturnVoid(hrc);
3796 i_postEvent(new AsyncEvent(this, ptrEvent));
3797}
3798
3799/**
3800 * @note Doesn't lock any object.
3801 */
3802void VirtualBox::i_onNatRedirectChanged(const Guid &aMachineId, ULONG ulSlot, bool fRemove, const Utf8Str &aName,
3803 NATProtocol_T aProto, const Utf8Str &aHostIp, uint16_t aHostPort,
3804 const Utf8Str &aGuestIp, uint16_t aGuestPort)
3805{
3806 ::FireNATRedirectEvent(m->pEventSource, aMachineId.toString(), ulSlot, fRemove, aName, aProto, aHostIp,
3807 aHostPort, aGuestIp, aGuestPort);
3808}
3809
3810/** @todo Unused!! */
3811void VirtualBox::i_onNATNetworkChanged(const Utf8Str &aName)
3812{
3813 ::FireNATNetworkChangedEvent(m->pEventSource, aName);
3814}
3815
3816void VirtualBox::i_onNATNetworkStartStop(const Utf8Str &aName, BOOL fStart)
3817{
3818 ::FireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
3819}
3820
3821void VirtualBox::i_onNATNetworkSetting(const Utf8Str &aNetworkName, BOOL aEnabled,
3822 const Utf8Str &aNetwork, const Utf8Str &aGateway,
3823 BOOL aAdvertiseDefaultIpv6RouteEnabled,
3824 BOOL fNeedDhcpServer)
3825{
3826 ::FireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled, aNetwork, aGateway,
3827 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
3828}
3829
3830void VirtualBox::i_onNATNetworkPortForward(const Utf8Str &aNetworkName, BOOL create, BOOL fIpv6,
3831 const Utf8Str &aRuleName, NATProtocol_T proto,
3832 const Utf8Str &aHostIp, LONG aHostPort,
3833 const Utf8Str &aGuestIp, LONG aGuestPort)
3834{
3835 ::FireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create, fIpv6, aRuleName, proto,
3836 aHostIp, aHostPort, aGuestIp, aGuestPort);
3837}
3838
3839
3840void VirtualBox::i_onHostNameResolutionConfigurationChange()
3841{
3842 if (m->pEventSource)
3843 ::FireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
3844}
3845
3846
3847int VirtualBox::i_natNetworkRefInc(const Utf8Str &aNetworkName)
3848{
3849 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3850
3851 if (!sNatNetworkNameToRefCount[aNetworkName])
3852 {
3853 ComPtr<INATNetwork> nat;
3854 HRESULT hrc = findNATNetworkByName(aNetworkName, nat);
3855 if (FAILED(hrc)) return -1;
3856
3857 hrc = nat->Start();
3858 if (SUCCEEDED(hrc))
3859 LogRel(("Started NAT network '%s'\n", aNetworkName.c_str()));
3860 else
3861 LogRel(("Error %Rhrc starting NAT network '%s'\n", hrc, aNetworkName.c_str()));
3862 AssertComRCReturn(hrc, -1);
3863 }
3864
3865 sNatNetworkNameToRefCount[aNetworkName]++;
3866
3867 return sNatNetworkNameToRefCount[aNetworkName];
3868}
3869
3870
3871int VirtualBox::i_natNetworkRefDec(const Utf8Str &aNetworkName)
3872{
3873 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3874
3875 if (!sNatNetworkNameToRefCount[aNetworkName])
3876 return 0;
3877
3878 sNatNetworkNameToRefCount[aNetworkName]--;
3879
3880 if (!sNatNetworkNameToRefCount[aNetworkName])
3881 {
3882 ComPtr<INATNetwork> nat;
3883 HRESULT hrc = findNATNetworkByName(aNetworkName, nat);
3884 if (FAILED(hrc)) return -1;
3885
3886 hrc = nat->Stop();
3887 if (SUCCEEDED(hrc))
3888 LogRel(("Stopped NAT network '%s'\n", aNetworkName.c_str()));
3889 else
3890 LogRel(("Error %Rhrc stopping NAT network '%s'\n", hrc, aNetworkName.c_str()));
3891 AssertComRCReturn(hrc, -1);
3892 }
3893
3894 return sNatNetworkNameToRefCount[aNetworkName];
3895}
3896
3897
3898/*
3899 * Export this to NATNetwork so that its setters can refuse to change
3900 * essential network settings when an VBoxNatNet instance is running.
3901 */
3902RWLockHandle *VirtualBox::i_getNatNetLock() const
3903{
3904 return spMtxNatNetworkNameToRefCountLock;
3905}
3906
3907
3908/*
3909 * Export this to NATNetwork so that its setters can refuse to change
3910 * essential network settings when an VBoxNatNet instance is running.
3911 * The caller is expected to hold a read lock on i_getNatNetLock().
3912 */
3913bool VirtualBox::i_isNatNetStarted(const Utf8Str &aNetworkName) const
3914{
3915 return sNatNetworkNameToRefCount[aNetworkName] > 0;
3916}
3917
3918
3919void VirtualBox::i_onCloudProviderListChanged(BOOL aRegistered)
3920{
3921 ::FireCloudProviderListChangedEvent(m->pEventSource, aRegistered);
3922}
3923
3924
3925void VirtualBox::i_onCloudProviderRegistered(const Utf8Str &aProviderId, BOOL aRegistered)
3926{
3927 ::FireCloudProviderRegisteredEvent(m->pEventSource, aProviderId, aRegistered);
3928}
3929
3930
3931void VirtualBox::i_onCloudProviderUninstall(const Utf8Str &aProviderId)
3932{
3933 HRESULT hrc;
3934
3935 ComPtr<IEvent> pEvent;
3936 hrc = CreateCloudProviderUninstallEvent(pEvent.asOutParam(),
3937 m->pEventSource, aProviderId);
3938 if (FAILED(hrc))
3939 return;
3940
3941 BOOL fDelivered = FALSE;
3942 hrc = m->pEventSource->FireEvent(pEvent, /* :timeout */ 10000, &fDelivered);
3943 if (FAILED(hrc))
3944 return;
3945}
3946
3947void VirtualBox::i_onLanguageChanged(const Utf8Str &aLanguageId)
3948{
3949 ComPtr<IEvent> ptrEvent;
3950 HRESULT hrc = ::CreateLanguageChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aLanguageId);
3951 AssertComRCReturnVoid(hrc);
3952 i_postEvent(new AsyncEvent(this, ptrEvent));
3953}
3954
3955void VirtualBox::i_onProgressCreated(const Guid &aId, BOOL aCreated)
3956{
3957 ::FireProgressCreatedEvent(m->pEventSource, aId.toString(), aCreated);
3958}
3959
3960#ifdef VBOX_WITH_UPDATE_AGENT
3961/**
3962 * @note Doesn't lock any object.
3963 */
3964void VirtualBox::i_onUpdateAgentAvailable(IUpdateAgent *aAgent,
3965 const Utf8Str &aVer, UpdateChannel_T aChannel, UpdateSeverity_T aSev,
3966 const Utf8Str &aDownloadURL, const Utf8Str &aWebURL, const Utf8Str &aReleaseNotes)
3967{
3968 ::FireUpdateAgentAvailableEvent(m->pEventSource, aAgent, aVer, aChannel, aSev,
3969 aDownloadURL, aWebURL, aReleaseNotes);
3970}
3971
3972/**
3973 * @note Doesn't lock any object.
3974 */
3975void VirtualBox::i_onUpdateAgentError(IUpdateAgent *aAgent, const Utf8Str &aErrMsg, LONG aRc)
3976{
3977 ::FireUpdateAgentErrorEvent(m->pEventSource, aAgent, aErrMsg, aRc);
3978}
3979
3980/**
3981 * @note Doesn't lock any object.
3982 */
3983void VirtualBox::i_onUpdateAgentStateChanged(IUpdateAgent *aAgent, UpdateState_T aState)
3984{
3985 ::FireUpdateAgentStateChangedEvent(m->pEventSource, aAgent, aState);
3986}
3987
3988/**
3989 * @note Doesn't lock any object.
3990 */
3991void VirtualBox::i_onUpdateAgentSettingsChanged(IUpdateAgent *aAgent, const Utf8Str &aAttributeHint)
3992{
3993 ::FireUpdateAgentSettingsChangedEvent(m->pEventSource, aAgent, aAttributeHint);
3994}
3995#endif /* VBOX_WITH_UPDATE_AGENT */
3996
3997#ifdef VBOX_WITH_EXTPACK
3998void VirtualBox::i_onExtPackInstalled(const Utf8Str &aExtPackName)
3999{
4000 ::FireExtPackInstalledEvent(m->pEventSource, aExtPackName);
4001}
4002
4003void VirtualBox::i_onExtPackUninstalled(const Utf8Str &aExtPackName)
4004{
4005 ::FireExtPackUninstalledEvent(m->pEventSource, aExtPackName);
4006}
4007#endif
4008
4009/**
4010 * @note Locks the list of other objects for reading.
4011 */
4012ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
4013{
4014 ComObjPtr<GuestOSType> type;
4015
4016 /* unknown type must always be the first */
4017 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
4018
4019 return m->allGuestOSTypes.front();
4020}
4021
4022/**
4023 * Returns the list of opened machines (machines having VM sessions opened,
4024 * ignoring other sessions) and optionally the list of direct session controls.
4025 *
4026 * @param aMachines Where to put opened machines (will be empty if none).
4027 * @param aControls Where to put direct session controls (optional).
4028 *
4029 * @note The returned lists contain smart pointers. So, clear it as soon as
4030 * it becomes no more necessary to release instances.
4031 *
4032 * @note It can be possible that a session machine from the list has been
4033 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
4034 * when accessing unprotected data directly.
4035 *
4036 * @note Locks objects for reading.
4037 */
4038void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
4039 InternalControlList *aControls /*= NULL*/)
4040{
4041 AutoCaller autoCaller(this);
4042 AssertComRCReturnVoid(autoCaller.hrc());
4043
4044 aMachines.clear();
4045 if (aControls)
4046 aControls->clear();
4047
4048 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4049
4050 for (MachinesOList::iterator it = m->allMachines.begin();
4051 it != m->allMachines.end();
4052 ++it)
4053 {
4054 ComObjPtr<SessionMachine> sm;
4055 ComPtr<IInternalSessionControl> ctl;
4056 if ((*it)->i_isSessionOpenVM(sm, &ctl))
4057 {
4058 aMachines.push_back(sm);
4059 if (aControls)
4060 aControls->push_back(ctl);
4061 }
4062 }
4063}
4064
4065/**
4066 * Gets a reference to the machine list. This is the real thing, not a copy,
4067 * so bad things will happen if the caller doesn't hold the necessary lock.
4068 *
4069 * @returns reference to machine list
4070 *
4071 * @note Caller must hold the VirtualBox object lock at least for reading.
4072 */
4073VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
4074{
4075 return m->allMachines;
4076}
4077
4078/**
4079 * Searches for a machine object with the given ID in the collection
4080 * of registered machines.
4081 *
4082 * @param aId Machine UUID to look for.
4083 * @param fPermitInaccessible If true, inaccessible machines will be found;
4084 * if false, this will fail if the given machine is inaccessible.
4085 * @param aSetError If true, set errorinfo if the machine is not found.
4086 * @param aMachine Returned machine, if found.
4087 * @return
4088 */
4089HRESULT VirtualBox::i_findMachine(const Guid &aId,
4090 bool fPermitInaccessible,
4091 bool aSetError,
4092 ComObjPtr<Machine> *aMachine /* = NULL */)
4093{
4094 HRESULT hrc = VBOX_E_OBJECT_NOT_FOUND;
4095
4096 AutoCaller autoCaller(this);
4097 AssertComRCReturnRC(autoCaller.hrc());
4098
4099 {
4100 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4101
4102 for (MachinesOList::iterator it = m->allMachines.begin();
4103 it != m->allMachines.end();
4104 ++it)
4105 {
4106 ComObjPtr<Machine> pMachine = *it;
4107
4108 if (!fPermitInaccessible)
4109 {
4110 // skip inaccessible machines
4111 AutoCaller machCaller(pMachine);
4112 if (FAILED(machCaller.hrc()))
4113 continue;
4114 }
4115
4116 if (pMachine->i_getId() == aId)
4117 {
4118 hrc = S_OK;
4119 if (aMachine)
4120 *aMachine = pMachine;
4121 break;
4122 }
4123 }
4124 }
4125
4126 if (aSetError && FAILED(hrc))
4127 hrc = setError(hrc, tr("Could not find a registered machine with UUID {%RTuuid}"), aId.raw());
4128
4129 return hrc;
4130}
4131
4132/**
4133 * Searches for a machine object with the given name or location in the
4134 * collection of registered machines.
4135 *
4136 * @param aName Machine name or location to look for.
4137 * @param aSetError If true, set errorinfo if the machine is not found.
4138 * @param aMachine Returned machine, if found.
4139 * @return
4140 */
4141HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
4142 bool aSetError,
4143 ComObjPtr<Machine> *aMachine /* = NULL */)
4144{
4145 HRESULT hrc = VBOX_E_OBJECT_NOT_FOUND;
4146
4147 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4148 for (MachinesOList::iterator it = m->allMachines.begin();
4149 it != m->allMachines.end();
4150 ++it)
4151 {
4152 ComObjPtr<Machine> &pMachine = *it;
4153 AutoCaller machCaller(pMachine);
4154 if (!machCaller.isOk())
4155 continue; // we can't ask inaccessible machines for their names
4156
4157 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
4158 if (pMachine->i_getName() == aName)
4159 {
4160 hrc = S_OK;
4161 if (aMachine)
4162 *aMachine = pMachine;
4163 break;
4164 }
4165 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
4166 {
4167 hrc = S_OK;
4168 if (aMachine)
4169 *aMachine = pMachine;
4170 break;
4171 }
4172 }
4173
4174 if (aSetError && FAILED(hrc))
4175 hrc = setError(hrc, tr("Could not find a registered machine named '%s'"), aName.c_str());
4176
4177 return hrc;
4178}
4179
4180static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
4181{
4182 /* empty strings are invalid */
4183 if (aGroup.isEmpty())
4184 return E_INVALIDARG;
4185 /* the toplevel group is valid */
4186 if (aGroup == "/")
4187 return S_OK;
4188 /* any other strings of length 1 are invalid */
4189 if (aGroup.length() == 1)
4190 return E_INVALIDARG;
4191 /* must start with a slash */
4192 if (aGroup.c_str()[0] != '/')
4193 return E_INVALIDARG;
4194 /* must not end with a slash */
4195 if (aGroup.c_str()[aGroup.length() - 1] == '/')
4196 return E_INVALIDARG;
4197 /* check the group components */
4198 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
4199 while (pStr)
4200 {
4201 char *pSlash = RTStrStr(pStr, "/");
4202 if (pSlash)
4203 {
4204 /* no empty components (or // sequences in other words) */
4205 if (pSlash == pStr)
4206 return E_INVALIDARG;
4207 /* check if the machine name rules are violated, because that means
4208 * the group components are too close to the limits. */
4209 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
4210 Utf8Str tmp2(tmp);
4211 sanitiseMachineFilename(tmp);
4212 if (tmp != tmp2)
4213 return E_INVALIDARG;
4214 if (fPrimary)
4215 {
4216 HRESULT hrc = pVirtualBox->i_findMachineByName(tmp, false /* aSetError */);
4217 if (SUCCEEDED(hrc))
4218 return VBOX_E_VM_ERROR;
4219 }
4220 pStr = pSlash + 1;
4221 }
4222 else
4223 {
4224 /* check if the machine name rules are violated, because that means
4225 * the group components is too close to the limits. */
4226 Utf8Str tmp(pStr);
4227 Utf8Str tmp2(tmp);
4228 sanitiseMachineFilename(tmp);
4229 if (tmp != tmp2)
4230 return E_INVALIDARG;
4231 pStr = NULL;
4232 }
4233 }
4234 return S_OK;
4235}
4236
4237/**
4238 * Validates a machine group.
4239 *
4240 * @param aGroup Machine group.
4241 * @param fPrimary Set if this is the primary group.
4242 *
4243 * @return S_OK or E_INVALIDARG
4244 */
4245HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
4246{
4247 HRESULT hrc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
4248 if (FAILED(hrc))
4249 {
4250 if (hrc == VBOX_E_VM_ERROR)
4251 hrc = setError(E_INVALIDARG, tr("Machine group '%s' conflicts with a virtual machine name"), aGroup.c_str());
4252 else
4253 hrc = setError(hrc, tr("Invalid machine group '%s'"), aGroup.c_str());
4254 }
4255 return hrc;
4256}
4257
4258/**
4259 * Takes a list of machine groups, and sanitizes/validates it.
4260 *
4261 * @param aMachineGroups Array with the machine groups.
4262 * @param pllMachineGroups Pointer to list of strings for the result.
4263 *
4264 * @return S_OK or E_INVALIDARG
4265 */
4266HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
4267{
4268 pllMachineGroups->clear();
4269 if (aMachineGroups.size())
4270 {
4271 for (size_t i = 0; i < aMachineGroups.size(); i++)
4272 {
4273 Utf8Str group(aMachineGroups[i]);
4274 if (group.length() == 0)
4275 group = "/";
4276
4277 HRESULT hrc = i_validateMachineGroup(group, i == 0);
4278 if (FAILED(hrc))
4279 return hrc;
4280
4281 /* no duplicates please */
4282 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
4283 == pllMachineGroups->end())
4284 pllMachineGroups->push_back(group);
4285 }
4286 if (pllMachineGroups->size() == 0)
4287 pllMachineGroups->push_back("/");
4288 }
4289 else
4290 pllMachineGroups->push_back("/");
4291
4292 return S_OK;
4293}
4294
4295/**
4296 * Searches for a Medium object with the given ID in the list of registered
4297 * hard disks.
4298 *
4299 * @param aId ID of the hard disk. Must not be empty.
4300 * @param aSetError If @c true , the appropriate error info is set in case
4301 * when the hard disk is not found.
4302 * @param aHardDisk Where to store the found hard disk object (can be NULL).
4303 *
4304 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4305 *
4306 * @note Locks the media tree for reading.
4307 */
4308HRESULT VirtualBox::i_findHardDiskById(const Guid &aId,
4309 bool aSetError,
4310 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
4311{
4312 AssertReturn(!aId.isZero(), E_INVALIDARG);
4313
4314 // we use the hard disks map, but it is protected by the
4315 // hard disk _list_ lock handle
4316 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4317
4318 HardDiskMap::const_iterator it = m->mapHardDisks.find(aId);
4319 if (it != m->mapHardDisks.end())
4320 {
4321 if (aHardDisk)
4322 *aHardDisk = (*it).second;
4323 return S_OK;
4324 }
4325
4326 if (aSetError)
4327 return setError(VBOX_E_OBJECT_NOT_FOUND,
4328 tr("Could not find an open hard disk with UUID {%RTuuid}"),
4329 aId.raw());
4330
4331 return VBOX_E_OBJECT_NOT_FOUND;
4332}
4333
4334/**
4335 * Searches for a Medium object with the given ID or location in the list of
4336 * registered hard disks. If both ID and location are specified, the first
4337 * object that matches either of them (not necessarily both) is returned.
4338 *
4339 * @param strLocation Full location specification. Must not be empty.
4340 * @param aSetError If @c true , the appropriate error info is set in case
4341 * when the hard disk is not found.
4342 * @param aHardDisk Where to store the found hard disk object (can be NULL).
4343 *
4344 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4345 *
4346 * @note Locks the media tree for reading.
4347 */
4348HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
4349 bool aSetError,
4350 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
4351{
4352 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
4353
4354 // we use the hard disks map, but it is protected by the
4355 // hard disk _list_ lock handle
4356 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4357
4358 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
4359 it != m->mapHardDisks.end();
4360 ++it)
4361 {
4362 const ComObjPtr<Medium> &pHD = (*it).second;
4363
4364 AutoCaller autoCaller(pHD);
4365 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
4366 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
4367
4368 Utf8Str strLocationFull = pHD->i_getLocationFull();
4369
4370 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
4371 {
4372 if (aHardDisk)
4373 *aHardDisk = pHD;
4374 return S_OK;
4375 }
4376 }
4377
4378 if (aSetError)
4379 return setError(VBOX_E_OBJECT_NOT_FOUND,
4380 tr("Could not find an open hard disk with location '%s'"),
4381 strLocation.c_str());
4382
4383 return VBOX_E_OBJECT_NOT_FOUND;
4384}
4385
4386/**
4387 * Searches for a Medium object with the given ID or location in the list of
4388 * registered DVD or floppy images, depending on the @a mediumType argument.
4389 * If both ID and file path are specified, the first object that matches either
4390 * of them (not necessarily both) is returned.
4391 *
4392 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
4393 * @param aId ID of the image file (unused when NULL).
4394 * @param aLocation Full path to the image file (unused when NULL).
4395 * @param aSetError If @c true, the appropriate error info is set in case when
4396 * the image is not found.
4397 * @param aImage Where to store the found image object (can be NULL).
4398 *
4399 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4400 *
4401 * @note Locks the media tree for reading.
4402 */
4403HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
4404 const Guid *aId,
4405 const Utf8Str &aLocation,
4406 bool aSetError,
4407 ComObjPtr<Medium> *aImage /* = NULL */)
4408{
4409 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
4410
4411 Utf8Str location;
4412 if (!aLocation.isEmpty())
4413 {
4414 int vrc = i_calculateFullPath(aLocation, location);
4415 if (RT_FAILURE(vrc))
4416 return setError(VBOX_E_FILE_ERROR,
4417 tr("Invalid image file location '%s' (%Rrc)"),
4418 aLocation.c_str(),
4419 vrc);
4420 }
4421
4422 MediaOList *pMediaList;
4423
4424 switch (mediumType)
4425 {
4426 case DeviceType_DVD:
4427 pMediaList = &m->allDVDImages;
4428 break;
4429
4430 case DeviceType_Floppy:
4431 pMediaList = &m->allFloppyImages;
4432 break;
4433
4434 default:
4435 return E_INVALIDARG;
4436 }
4437
4438 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
4439
4440 bool found = false;
4441
4442 for (MediaList::const_iterator it = pMediaList->begin();
4443 it != pMediaList->end();
4444 ++it)
4445 {
4446 // no AutoCaller, registered image life time is bound to this
4447 Medium *pMedium = *it;
4448 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
4449 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
4450
4451 found = ( aId
4452 && pMedium->i_getId() == *aId)
4453 || ( !aLocation.isEmpty()
4454 && RTPathCompare(location.c_str(),
4455 strLocationFull.c_str()) == 0);
4456 if (found)
4457 {
4458 if (pMedium->i_getDeviceType() != mediumType)
4459 {
4460 if (mediumType == DeviceType_DVD)
4461 return setError(E_INVALIDARG,
4462 tr("Cannot mount DVD medium '%s' as floppy"), strLocationFull.c_str());
4463 else
4464 return setError(E_INVALIDARG,
4465 tr("Cannot mount floppy medium '%s' as DVD"), strLocationFull.c_str());
4466 }
4467
4468 if (aImage)
4469 *aImage = pMedium;
4470 break;
4471 }
4472 }
4473
4474 HRESULT hrc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
4475
4476 if (aSetError && !found)
4477 {
4478 if (aId)
4479 setError(hrc,
4480 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
4481 aId->raw(),
4482 m->strSettingsFilePath.c_str());
4483 else
4484 setError(hrc,
4485 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
4486 aLocation.c_str(),
4487 m->strSettingsFilePath.c_str());
4488 }
4489
4490 return hrc;
4491}
4492
4493/**
4494 * Searches for an IMedium object that represents the given UUID.
4495 *
4496 * If the UUID is empty (indicating an empty drive), this sets pMedium
4497 * to NULL and returns S_OK.
4498 *
4499 * If the UUID refers to a host drive of the given device type, this
4500 * sets pMedium to the object from the list in IHost and returns S_OK.
4501 *
4502 * If the UUID is an image file, this sets pMedium to the object that
4503 * findDVDOrFloppyImage() returned.
4504 *
4505 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
4506 *
4507 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
4508 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
4509 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
4510 * @param aSetError
4511 * @param pMedium out: IMedium object found.
4512 * @return
4513 */
4514HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
4515 const Guid &uuid,
4516 bool fRefresh,
4517 bool aSetError,
4518 ComObjPtr<Medium> &pMedium)
4519{
4520 if (uuid.isZero())
4521 {
4522 // that's easy
4523 pMedium.setNull();
4524 return S_OK;
4525 }
4526 else if (!uuid.isValid())
4527 {
4528 /* handling of case invalid GUID */
4529 return setError(VBOX_E_OBJECT_NOT_FOUND,
4530 tr("Guid '%s' is invalid"),
4531 uuid.toString().c_str());
4532 }
4533
4534 // first search for host drive with that UUID
4535 HRESULT hrc = m->pHost->i_findHostDriveById(mediumType, uuid, fRefresh, pMedium);
4536 if (hrc == VBOX_E_OBJECT_NOT_FOUND)
4537 // then search for an image with that UUID
4538 hrc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
4539
4540 return hrc;
4541}
4542
4543/* Look for a GuestOSType object */
4544HRESULT VirtualBox::i_findGuestOSType(const Utf8Str &strOSType,
4545 ComObjPtr<GuestOSType> &guestOSType)
4546{
4547 guestOSType.setNull();
4548
4549 AssertMsg(m->allGuestOSTypes.size() != 0,
4550 ("Guest OS types array must be filled"));
4551
4552 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4553 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4554 it != m->allGuestOSTypes.end();
4555 ++it)
4556 {
4557 const Utf8Str &typeId = (*it)->i_id();
4558 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
4559 if (strOSType.compare(typeId, Utf8Str::CaseInsensitive) == 0)
4560 {
4561 guestOSType = *it;
4562 return S_OK;
4563 }
4564 }
4565
4566 return setError(VBOX_E_OBJECT_NOT_FOUND,
4567 tr("'%s' is not a valid Guest OS type"),
4568 strOSType.c_str());
4569}
4570
4571/**
4572 * Walk the list of GuestOSType objects and return a list of guest OS
4573 * subtypes which correspond to the supplied guest OS family ID.
4574 *
4575 * @param strOSFamily Guest OS family ID.
4576 * @param aOSSubtypes Where to store the list of guest OS subtypes.
4577 *
4578 * @note Locks the guest OS types list for reading.
4579 */
4580HRESULT VirtualBox::getGuestOSSubtypesByFamilyId(const Utf8Str &strOSFamily,
4581 std::vector<com::Utf8Str> &aOSSubtypes)
4582{
4583 std::list<com::Utf8Str> allOSSubtypes;
4584
4585 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4586
4587 bool fFoundGuestOSType = false;
4588 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4589 it != m->allGuestOSTypes.end(); ++it)
4590 {
4591 const Utf8Str &familyId = (*it)->i_familyId();
4592 AssertMsg(!familyId.isEmpty(), ("familfyId must not be NULL"));
4593 if (familyId.compare(strOSFamily, Utf8Str::CaseInsensitive) == 0)
4594 {
4595 fFoundGuestOSType = true;
4596 break;
4597 }
4598 }
4599
4600 if (!fFoundGuestOSType)
4601 return setError(VBOX_E_OBJECT_NOT_FOUND,
4602 tr("'%s' is not a valid guest OS family identifier."), strOSFamily.c_str());
4603
4604 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4605 it != m->allGuestOSTypes.end(); ++it)
4606 {
4607 const Utf8Str &familyId = (*it)->i_familyId();
4608 AssertMsg(!familyId.isEmpty(), ("familfyId must not be NULL"));
4609 if (familyId.compare(strOSFamily, Utf8Str::CaseInsensitive) == 0)
4610 {
4611 const Utf8Str &strOSSubtype = (*it)->i_subtype();
4612 if (!strOSSubtype.isEmpty())
4613 allOSSubtypes.push_back(strOSSubtype);
4614 }
4615 }
4616
4617 /* throw out any duplicates */
4618 allOSSubtypes.sort();
4619 allOSSubtypes.unique();
4620
4621 aOSSubtypes.resize(allOSSubtypes.size());
4622 size_t i = 0;
4623 for (std::list<com::Utf8Str>::const_iterator it = allOSSubtypes.begin();
4624 it != allOSSubtypes.end(); ++it, ++i)
4625 aOSSubtypes[i] = (*it);
4626
4627 return S_OK;
4628}
4629
4630/**
4631 * Walk the list of GuestOSType objects and return a list of guest OS
4632 * descriptions which correspond to the supplied guest OS subtype.
4633 *
4634 * @param strOSSubtype Guest OS subtype.
4635 * @param aGuestOSDescs Where to store the list of guest OS descriptions..
4636 *
4637 * @note Locks the guest OS types list for reading.
4638 */
4639HRESULT VirtualBox::getGuestOSDescsBySubtype(const Utf8Str &strOSSubtype,
4640 std::vector<com::Utf8Str> &aGuestOSDescs)
4641{
4642 std::list<com::Utf8Str> allOSDescs;
4643
4644 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4645
4646 bool fFoundGuestOSSubtype = false;
4647 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4648 it != m->allGuestOSTypes.end(); ++it)
4649 {
4650 const Utf8Str &guestOSSubtype = (*it)->i_subtype();
4651 /* Only some guest OS types have a populated subtype value. */
4652 if (guestOSSubtype.isNotEmpty() &&
4653 guestOSSubtype.compare(strOSSubtype, Utf8Str::CaseInsensitive) == 0)
4654 {
4655 fFoundGuestOSSubtype = true;
4656 break;
4657 }
4658 }
4659
4660 if (!fFoundGuestOSSubtype)
4661 return setError(VBOX_E_OBJECT_NOT_FOUND,
4662 tr("'%s' is not a valid guest OS subtype."), strOSSubtype.c_str());
4663
4664 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4665 it != m->allGuestOSTypes.end(); ++it)
4666 {
4667 const Utf8Str &guestOSSubtype = (*it)->i_subtype();
4668 /* Only some guest OS types have a populated subtype value. */
4669 if (guestOSSubtype.isNotEmpty() &&
4670 guestOSSubtype.compare(strOSSubtype, Utf8Str::CaseInsensitive) == 0)
4671 {
4672 const Utf8Str &strOSDesc = (*it)->i_description();
4673 allOSDescs.push_back(strOSDesc);
4674 }
4675 }
4676
4677 aGuestOSDescs.resize(allOSDescs.size());
4678 size_t i = 0;
4679 for (std::list<com::Utf8Str>::const_iterator it = allOSDescs.begin();
4680 it != allOSDescs.end(); ++it, ++i)
4681 aGuestOSDescs[i] = (*it);
4682
4683 return S_OK;
4684}
4685
4686/**
4687 * Returns the constant pseudo-machine UUID that is used to identify the
4688 * global media registry.
4689 *
4690 * Starting with VirtualBox 4.0 each medium remembers in its instance data
4691 * in which media registry it is saved (if any): this can either be a machine
4692 * UUID, if it's in a per-machine media registry, or this global ID.
4693 *
4694 * This UUID is only used to identify the VirtualBox object while VirtualBox
4695 * is running. It is a compile-time constant and not saved anywhere.
4696 *
4697 * @return
4698 */
4699const Guid& VirtualBox::i_getGlobalRegistryId() const
4700{
4701 return m->uuidMediaRegistry;
4702}
4703
4704const ComObjPtr<Host>& VirtualBox::i_host() const
4705{
4706 return m->pHost;
4707}
4708
4709SystemProperties* VirtualBox::i_getSystemProperties() const
4710{
4711 return m->pSystemProperties;
4712}
4713
4714CloudProviderManager *VirtualBox::i_getCloudProviderManager() const
4715{
4716 return m->pCloudProviderManager;
4717}
4718
4719#ifdef VBOX_WITH_EXTPACK
4720/**
4721 * Getter that SystemProperties and others can use to talk to the extension
4722 * pack manager.
4723 */
4724ExtPackManager* VirtualBox::i_getExtPackManager() const
4725{
4726 return m->ptrExtPackManager;
4727}
4728#endif
4729
4730/**
4731 * Getter that machines can talk to the autostart database.
4732 */
4733AutostartDb* VirtualBox::i_getAutostartDb() const
4734{
4735 return m->pAutostartDb;
4736}
4737
4738#ifdef VBOX_WITH_RESOURCE_USAGE_API
4739const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
4740{
4741 return m->pPerformanceCollector;
4742}
4743#endif /* VBOX_WITH_RESOURCE_USAGE_API */
4744
4745/**
4746 * Returns the default machine folder from the system properties
4747 * with proper locking.
4748 */
4749void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
4750{
4751 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
4752 str = m->pSystemProperties->m->strDefaultMachineFolder;
4753}
4754
4755/**
4756 * Returns the default hard disk format from the system properties
4757 * with proper locking.
4758 */
4759void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
4760{
4761 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
4762 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
4763}
4764
4765const Utf8Str& VirtualBox::i_homeDir() const
4766{
4767 return m->strHomeDir;
4768}
4769
4770/**
4771 * Calculates the absolute path of the given path taking the VirtualBox home
4772 * directory as the current directory.
4773 *
4774 * @param strPath Path to calculate the absolute path for.
4775 * @param aResult Where to put the result (used only on success, can be the
4776 * same Utf8Str instance as passed in @a aPath).
4777 * @return IPRT result.
4778 *
4779 * @note Doesn't lock any object.
4780 */
4781int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
4782{
4783 AutoCaller autoCaller(this);
4784 AssertComRCReturn(autoCaller.hrc(), VERR_GENERAL_FAILURE);
4785
4786 /* no need to lock since strHomeDir is const */
4787
4788 char szFolder[RTPATH_MAX];
4789 size_t cbFolder = sizeof(szFolder);
4790 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
4791 strPath.c_str(),
4792 RTPATH_STR_F_STYLE_HOST,
4793 szFolder,
4794 &cbFolder);
4795 if (RT_SUCCESS(vrc))
4796 aResult = szFolder;
4797
4798 return vrc;
4799}
4800
4801/**
4802 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
4803 * if it is a subdirectory thereof, or simply copying it otherwise.
4804 *
4805 * @param strSource Path to evalue and copy.
4806 * @param strTarget Buffer to receive target path.
4807 */
4808void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
4809 Utf8Str &strTarget)
4810{
4811 AutoCaller autoCaller(this);
4812 AssertComRCReturnVoid(autoCaller.hrc());
4813
4814 // no need to lock since mHomeDir is const
4815
4816 // use strTarget as a temporary buffer to hold the machine settings dir
4817 strTarget = m->strHomeDir;
4818 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
4819 // is relative: then append what's left
4820 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
4821 else
4822 // is not relative: then overwrite
4823 strTarget = strSource;
4824}
4825
4826// private methods
4827/////////////////////////////////////////////////////////////////////////////
4828
4829/**
4830 * Checks if there is a hard disk, DVD or floppy image with the given ID or
4831 * location already registered.
4832 *
4833 * On return, sets @a aConflict to the string describing the conflicting medium,
4834 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
4835 * either case. A failure is unexpected.
4836 *
4837 * @param aId UUID to check.
4838 * @param aLocation Location to check.
4839 * @param aConflict Where to return parameters of the conflicting medium.
4840 * @param ppMedium Medium reference in case this is simply a duplicate.
4841 *
4842 * @note Locks the media tree and media objects for reading.
4843 */
4844HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
4845 const Utf8Str &aLocation,
4846 Utf8Str &aConflict,
4847 ComObjPtr<Medium> *ppMedium)
4848{
4849 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
4850 AssertReturn(ppMedium, E_INVALIDARG);
4851
4852 aConflict.setNull();
4853 ppMedium->setNull();
4854
4855 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4856
4857 HRESULT hrc = S_OK;
4858
4859 ComObjPtr<Medium> pMediumFound;
4860 const char *pcszType = NULL;
4861
4862 if (aId.isValid() && !aId.isZero())
4863 hrc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4864 if (FAILED(hrc) && !aLocation.isEmpty())
4865 hrc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
4866 if (SUCCEEDED(hrc))
4867 pcszType = tr("hard disk");
4868
4869 if (!pcszType)
4870 {
4871 hrc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
4872 if (SUCCEEDED(hrc))
4873 pcszType = tr("CD/DVD image");
4874 }
4875
4876 if (!pcszType)
4877 {
4878 hrc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
4879 if (SUCCEEDED(hrc))
4880 pcszType = tr("floppy image");
4881 }
4882
4883 if (pcszType && pMediumFound)
4884 {
4885 /* Note: no AutoCaller since bound to this */
4886 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
4887
4888 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
4889 Guid idFound = pMediumFound->i_getId();
4890
4891 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
4892 && (idFound == aId)
4893 )
4894 *ppMedium = pMediumFound;
4895
4896 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
4897 pcszType,
4898 strLocFound.c_str(),
4899 idFound.raw());
4900 }
4901
4902 return S_OK;
4903}
4904
4905/**
4906 * Checks whether the given UUID is already in use by one medium for the
4907 * given device type.
4908 *
4909 * @returns true if the UUID is already in use
4910 * fale otherwise
4911 * @param aId The UUID to check.
4912 * @param deviceType The device type the UUID is going to be checked for
4913 * conflicts.
4914 */
4915bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
4916{
4917 /* A zero UUID is invalid here, always claim that it is already used. */
4918 AssertReturn(!aId.isZero(), true);
4919
4920 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4921
4922 bool fInUse = false;
4923
4924 ComObjPtr<Medium> pMediumFound;
4925
4926 HRESULT hrc;
4927 switch (deviceType)
4928 {
4929 case DeviceType_HardDisk:
4930 hrc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4931 break;
4932 case DeviceType_DVD:
4933 hrc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4934 break;
4935 case DeviceType_Floppy:
4936 hrc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4937 break;
4938 default:
4939 AssertMsgFailed(("Invalid device type %d\n", deviceType));
4940 hrc = S_OK;
4941 break;
4942 }
4943
4944 if (SUCCEEDED(hrc) && pMediumFound)
4945 fInUse = true;
4946
4947 return fInUse;
4948}
4949
4950/**
4951 * Called from Machine::prepareSaveSettings() when it has detected
4952 * that a machine has been renamed. Such renames will require
4953 * updating the global media registry during the
4954 * VirtualBox::i_saveSettings() that follows later.
4955*
4956 * When a machine is renamed, there may well be media (in particular,
4957 * diff images for snapshots) in the global registry that will need
4958 * to have their paths updated. Before 3.2, Machine::saveSettings
4959 * used to call VirtualBox::i_saveSettings implicitly, which was both
4960 * unintuitive and caused locking order problems. Now, we remember
4961 * such pending name changes with this method so that
4962 * VirtualBox::i_saveSettings() can process them properly.
4963 */
4964void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
4965 const Utf8Str &strNewConfigDir)
4966{
4967 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4968
4969 Data::PendingMachineRename pmr;
4970 pmr.strConfigDirOld = strOldConfigDir;
4971 pmr.strConfigDirNew = strNewConfigDir;
4972 m->llPendingMachineRenames.push_back(pmr);
4973}
4974
4975static DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4976
4977class SaveMediaRegistriesDesc : public ThreadTask
4978{
4979
4980public:
4981 SaveMediaRegistriesDesc()
4982 {
4983 m_strTaskName = "SaveMediaReg";
4984 }
4985 virtual ~SaveMediaRegistriesDesc(void) { }
4986
4987private:
4988 void handler()
4989 {
4990 try
4991 {
4992 fntSaveMediaRegistries(this);
4993 }
4994 catch(...)
4995 {
4996 LogRel(("Exception in the function fntSaveMediaRegistries()\n"));
4997 }
4998 }
4999
5000 MediaList llMedia;
5001 ComObjPtr<VirtualBox> pVirtualBox;
5002
5003 friend DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
5004 friend void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
5005 const Guid &uuidRegistry,
5006 const Utf8Str &strMachineFolder);
5007};
5008
5009DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser)
5010{
5011 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
5012 if (!pDesc)
5013 {
5014 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
5015 return VERR_INVALID_PARAMETER;
5016 }
5017
5018 for (MediaList::const_iterator it = pDesc->llMedia.begin();
5019 it != pDesc->llMedia.end();
5020 ++it)
5021 {
5022 Medium *pMedium = *it;
5023 pMedium->i_markRegistriesModified();
5024 }
5025
5026 pDesc->pVirtualBox->i_saveModifiedRegistries();
5027
5028 pDesc->llMedia.clear();
5029 pDesc->pVirtualBox.setNull();
5030
5031 return VINF_SUCCESS;
5032}
5033
5034/**
5035 * Goes through all known media (hard disks, floppies and DVDs) and saves
5036 * those into the given settings::MediaRegistry structures whose registry
5037 * ID match the given UUID.
5038 *
5039 * Before actually writing to the structures, all media paths (not just the
5040 * ones for the given registry) are updated if machines have been renamed
5041 * since the last call.
5042 *
5043 * This gets called from two contexts:
5044 *
5045 * -- VirtualBox::i_saveSettings() with the UUID of the global registry
5046 * (VirtualBox::Data.uuidRegistry); this will save those media
5047 * which had been loaded from the global registry or have been
5048 * attached to a "legacy" machine which can't save its own registry;
5049 *
5050 * -- Machine::saveSettings() with the UUID of a machine, if a medium
5051 * has been attached to a machine created with VirtualBox 4.0 or later.
5052 *
5053 * Media which have only been temporarily opened without having been
5054 * attached to a machine have a NULL registry UUID and therefore don't
5055 * get saved.
5056 *
5057 * This locks the media tree. Throws HRESULT on errors!
5058 *
5059 * @param mediaRegistry Settings structure to fill.
5060 * @param uuidRegistry The UUID of the media registry; either a machine UUID
5061 * (if machine registry) or the UUID of the global registry.
5062 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
5063 */
5064void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
5065 const Guid &uuidRegistry,
5066 const Utf8Str &strMachineFolder)
5067{
5068 // lock all media for the following; use a write lock because we're
5069 // modifying the PendingMachineRenamesList, which is protected by this
5070 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5071
5072 // if a machine was renamed, then we'll need to refresh media paths
5073 if (m->llPendingMachineRenames.size())
5074 {
5075 // make a single list from the three media lists so we don't need three loops
5076 MediaList llAllMedia;
5077 // with hard disks, we must use the map, not the list, because the list only has base images
5078 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
5079 llAllMedia.push_back(it->second);
5080 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
5081 llAllMedia.push_back(*it);
5082 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
5083 llAllMedia.push_back(*it);
5084
5085 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
5086 for (MediaList::iterator it = llAllMedia.begin();
5087 it != llAllMedia.end();
5088 ++it)
5089 {
5090 Medium *pMedium = *it;
5091 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
5092 it2 != m->llPendingMachineRenames.end();
5093 ++it2)
5094 {
5095 const Data::PendingMachineRename &pmr = *it2;
5096 HRESULT hrc = pMedium->i_updatePath(pmr.strConfigDirOld, pmr.strConfigDirNew);
5097 if (SUCCEEDED(hrc))
5098 {
5099 // Remember which medium objects has been changed,
5100 // to trigger saving their registries later.
5101 pDesc->llMedia.push_back(pMedium);
5102 } else if (hrc == VBOX_E_FILE_ERROR)
5103 /* nothing */;
5104 else
5105 AssertComRC(hrc);
5106 }
5107 }
5108 // done, don't do it again until we have more machine renames
5109 m->llPendingMachineRenames.clear();
5110
5111 if (pDesc->llMedia.size())
5112 {
5113 // Handle the media registry saving in a separate thread, to
5114 // avoid giant locking problems and passing up the list many
5115 // levels up to whoever triggered saveSettings, as there are
5116 // lots of places which would need to handle saving more settings.
5117 pDesc->pVirtualBox = this;
5118
5119 //the function createThread() takes ownership of pDesc
5120 //so there is no need to use delete operator for pDesc
5121 //after calling this function
5122 HRESULT hrc = pDesc->createThread();
5123 pDesc = NULL;
5124
5125 if (FAILED(hrc))
5126 {
5127 // failure means that settings aren't saved, but there isn't
5128 // much we can do besides avoiding memory leaks
5129 LogRelFunc(("Failed to create thread for saving media registries (%Rhr)\n", hrc));
5130 }
5131 }
5132 else
5133 delete pDesc;
5134 }
5135
5136 struct {
5137 MediaOList &llSource;
5138 settings::MediaList &llTarget;
5139 } s[] =
5140 {
5141 // hard disks
5142 { m->allHardDisks, mediaRegistry.llHardDisks },
5143 // CD/DVD images
5144 { m->allDVDImages, mediaRegistry.llDvdImages },
5145 // floppy images
5146 { m->allFloppyImages, mediaRegistry.llFloppyImages }
5147 };
5148
5149 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
5150 {
5151 MediaOList &llSource = s[i].llSource;
5152 settings::MediaList &llTarget = s[i].llTarget;
5153 llTarget.clear();
5154 for (MediaList::const_iterator it = llSource.begin();
5155 it != llSource.end();
5156 ++it)
5157 {
5158 Medium *pMedium = *it;
5159 AutoCaller autoCaller(pMedium);
5160 if (FAILED(autoCaller.hrc())) throw autoCaller.hrc();
5161 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
5162
5163 if (pMedium->i_isInRegistry(uuidRegistry))
5164 {
5165 llTarget.push_back(settings::Medium::Empty);
5166 HRESULT hrc = pMedium->i_saveSettings(llTarget.back(), strMachineFolder); // this recurses into child hard disks
5167 if (FAILED(hrc))
5168 {
5169 llTarget.pop_back();
5170 throw hrc;
5171 }
5172 }
5173 }
5174 }
5175}
5176
5177/**
5178 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
5179 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
5180 * places internally when settings need saving.
5181 *
5182 * @note Caller must have locked the VirtualBox object for writing and must not hold any
5183 * other locks since this locks all kinds of member objects and trees temporarily,
5184 * which could cause conflicts.
5185 */
5186HRESULT VirtualBox::i_saveSettings()
5187{
5188 AutoCaller autoCaller(this);
5189 AssertComRCReturnRC(autoCaller.hrc());
5190
5191 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5192 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
5193
5194 i_unmarkRegistryModified(i_getGlobalRegistryId());
5195
5196 HRESULT hrc = S_OK;
5197
5198 try
5199 {
5200 // machines
5201 m->pMainConfigFile->llMachines.clear();
5202 {
5203 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5204 for (MachinesOList::iterator it = m->allMachines.begin();
5205 it != m->allMachines.end();
5206 ++it)
5207 {
5208 Machine *pMachine = *it;
5209 // save actual machine registry entry
5210 settings::MachineRegistryEntry mre;
5211 hrc = pMachine->i_saveRegistryEntry(mre);
5212 m->pMainConfigFile->llMachines.push_back(mre);
5213 }
5214 }
5215
5216 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
5217 m->uuidMediaRegistry, // global media registry ID
5218 Utf8Str::Empty); // strMachineFolder
5219
5220 m->pMainConfigFile->llDhcpServers.clear();
5221 {
5222 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5223 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5224 it != m->allDHCPServers.end();
5225 ++it)
5226 {
5227 settings::DHCPServer d;
5228 hrc = (*it)->i_saveSettings(d);
5229 if (FAILED(hrc)) throw hrc;
5230 m->pMainConfigFile->llDhcpServers.push_back(d);
5231 }
5232 }
5233
5234#ifdef VBOX_WITH_NAT_SERVICE
5235 /* Saving NAT Network configuration */
5236 m->pMainConfigFile->llNATNetworks.clear();
5237 {
5238 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5239 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
5240 it != m->allNATNetworks.end();
5241 ++it)
5242 {
5243 settings::NATNetwork n;
5244 hrc = (*it)->i_saveSettings(n);
5245 if (FAILED(hrc)) throw hrc;
5246 m->pMainConfigFile->llNATNetworks.push_back(n);
5247 }
5248 }
5249#endif
5250
5251#ifdef VBOX_WITH_VMNET
5252 m->pMainConfigFile->llHostOnlyNetworks.clear();
5253 {
5254 AutoReadLock hostOnlyNetworkLock(m->allHostOnlyNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5255 for (HostOnlyNetworksOList::const_iterator it = m->allHostOnlyNetworks.begin();
5256 it != m->allHostOnlyNetworks.end();
5257 ++it)
5258 {
5259 settings::HostOnlyNetwork n;
5260 hrc = (*it)->i_saveSettings(n);
5261 if (FAILED(hrc)) throw hrc;
5262 m->pMainConfigFile->llHostOnlyNetworks.push_back(n);
5263 }
5264 }
5265#endif /* VBOX_WITH_VMNET */
5266
5267#ifdef VBOX_WITH_CLOUD_NET
5268 m->pMainConfigFile->llCloudNetworks.clear();
5269 {
5270 AutoReadLock cloudNetworkLock(m->allCloudNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5271 for (CloudNetworksOList::const_iterator it = m->allCloudNetworks.begin();
5272 it != m->allCloudNetworks.end();
5273 ++it)
5274 {
5275 settings::CloudNetwork n;
5276 hrc = (*it)->i_saveSettings(n);
5277 if (FAILED(hrc)) throw hrc;
5278 m->pMainConfigFile->llCloudNetworks.push_back(n);
5279 }
5280 }
5281#endif /* VBOX_WITH_CLOUD_NET */
5282 // leave extra data alone, it's still in the config file
5283
5284 // host data (USB filters)
5285 hrc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
5286 if (FAILED(hrc)) throw hrc;
5287
5288 hrc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
5289 if (FAILED(hrc)) throw hrc;
5290
5291 // and write out the XML, still under the lock
5292 m->pMainConfigFile->write(m->strSettingsFilePath);
5293 }
5294 catch (HRESULT hrcXcpt)
5295 {
5296 /* we assume that error info is set by the thrower */
5297 hrc = hrcXcpt;
5298 }
5299 catch (...)
5300 {
5301 hrc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
5302 }
5303
5304 return hrc;
5305}
5306
5307/**
5308 * Helper to register the machine.
5309 *
5310 * When called during VirtualBox startup, adds the given machine to the
5311 * collection of registered machines. Otherwise tries to mark the machine
5312 * as registered, and, if succeeded, adds it to the collection and
5313 * saves global settings.
5314 *
5315 * @note The caller must have added itself as a caller of the @a aMachine
5316 * object if calls this method not on VirtualBox startup.
5317 *
5318 * @param aMachine machine to register
5319 *
5320 * @note Locks objects!
5321 */
5322HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
5323{
5324 ComAssertRet(aMachine, E_INVALIDARG);
5325
5326 AutoCaller autoCaller(this);
5327 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
5328
5329 HRESULT hrc = S_OK;
5330
5331 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5332
5333 {
5334 ComObjPtr<Machine> pMachine;
5335 hrc = i_findMachine(aMachine->i_getId(),
5336 true /* fPermitInaccessible */,
5337 false /* aDoSetError */,
5338 &pMachine);
5339 if (SUCCEEDED(hrc))
5340 {
5341 /* sanity */
5342 AutoLimitedCaller machCaller(pMachine);
5343 AssertComRC(machCaller.hrc());
5344
5345 return setError(E_INVALIDARG,
5346 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
5347 aMachine->i_getId().raw(),
5348 pMachine->i_getSettingsFileFull().c_str());
5349 }
5350
5351 ComAssertRet(hrc == VBOX_E_OBJECT_NOT_FOUND, hrc);
5352 hrc = S_OK;
5353 }
5354
5355 if (getObjectState().getState() != ObjectState::InInit)
5356 {
5357 hrc = aMachine->i_prepareRegister();
5358 if (FAILED(hrc)) return hrc;
5359 }
5360
5361 /* add to the collection of registered machines */
5362 m->allMachines.addChild(aMachine);
5363
5364 if (getObjectState().getState() != ObjectState::InInit)
5365 hrc = i_saveSettings();
5366
5367 return hrc;
5368}
5369
5370/**
5371 * Remembers the given medium object by storing it in either the global
5372 * medium registry or a machine one.
5373 *
5374 * @note Caller must hold the media tree lock for writing; in addition, this
5375 * locks @a pMedium for reading
5376 *
5377 * @param pMedium Medium object to remember.
5378 * @param ppMedium Actually stored medium object. Can be different if due
5379 * to an unavoidable race there was a duplicate Medium object
5380 * created.
5381 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
5382 * lock, necessary to release it in the right spot.
5383 * @param fCalledFromMediumInit Flag whether this is called from Medium::init().
5384 * @return
5385 */
5386HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
5387 ComObjPtr<Medium> *ppMedium,
5388 AutoWriteLock &mediaTreeLock,
5389 bool fCalledFromMediumInit)
5390{
5391 AssertReturn(pMedium != NULL, E_INVALIDARG);
5392 AssertReturn(ppMedium != NULL, E_INVALIDARG);
5393
5394 // caller must hold the media tree write lock
5395 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5396
5397 AutoCaller autoCaller(this);
5398 AssertComRCReturnRC(autoCaller.hrc());
5399
5400 AutoCaller mediumCaller(pMedium);
5401 AssertComRCReturnRC(mediumCaller.hrc());
5402
5403 bool fAddToGlobalRegistry = false;
5404 const char *pszDevType = NULL;
5405 Guid regId;
5406 ObjectsList<Medium> *pall = NULL;
5407 DeviceType_T devType;
5408 {
5409 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5410 devType = pMedium->i_getDeviceType();
5411
5412 if (!pMedium->i_getFirstRegistryMachineId(regId))
5413 fAddToGlobalRegistry = true;
5414 }
5415 switch (devType)
5416 {
5417 case DeviceType_HardDisk:
5418 pall = &m->allHardDisks;
5419 pszDevType = tr("hard disk");
5420 break;
5421 case DeviceType_DVD:
5422 pszDevType = tr("DVD image");
5423 pall = &m->allDVDImages;
5424 break;
5425 case DeviceType_Floppy:
5426 pszDevType = tr("floppy image");
5427 pall = &m->allFloppyImages;
5428 break;
5429 default:
5430 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
5431 }
5432
5433 Guid id;
5434 Utf8Str strLocationFull;
5435 ComObjPtr<Medium> pParent;
5436 {
5437 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5438 id = pMedium->i_getId();
5439 strLocationFull = pMedium->i_getLocationFull();
5440 pParent = pMedium->i_getParent();
5441
5442 /*
5443 * If a separate thread has called Medium::close() for this medium at the same
5444 * time as this i_registerMedium() call then there is a window of opportunity in
5445 * Medium::i_close() where the media tree lock is dropped before calling
5446 * Medium::uninit() (which reacquires the lock) that we can end up here attempting
5447 * to register a medium which is in the process of being closed. In addition, if
5448 * this is a differencing medium and Medium::close() is in progress for one its
5449 * parent media then we are similarly operating on a media registry in flux. In
5450 * either case registering a medium just before calling Medium::uninit() will
5451 * lead to an inconsistent media registry so bail out here since Medium::close()
5452 * got to this medium (or one of its parents) first.
5453 */
5454 if (devType == DeviceType_HardDisk)
5455 {
5456 ComObjPtr<Medium> pTmpMedium = pMedium;
5457 while (pTmpMedium.isNotNull())
5458 {
5459 AutoCaller mediumAC(pTmpMedium);
5460 if (FAILED(mediumAC.hrc())) return mediumAC.hrc();
5461 AutoReadLock mlock(pTmpMedium COMMA_LOCKVAL_SRC_POS);
5462
5463 if (pTmpMedium->i_isClosing())
5464 return setError(E_INVALIDARG,
5465 tr("Cannot register %s '%s' {%RTuuid} because it is in the process of being closed"),
5466 pszDevType,
5467 pTmpMedium->i_getLocationFull().c_str(),
5468 pTmpMedium->i_getId().raw());
5469
5470 pTmpMedium = pTmpMedium->i_getParent();
5471 }
5472 }
5473 }
5474
5475 HRESULT hrc;
5476
5477 Utf8Str strConflict;
5478 ComObjPtr<Medium> pDupMedium;
5479 hrc = i_checkMediaForConflicts(id, strLocationFull, strConflict, &pDupMedium);
5480 if (FAILED(hrc)) return hrc;
5481
5482 if (pDupMedium.isNull())
5483 {
5484 if (strConflict.length())
5485 return setError(E_INVALIDARG,
5486 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
5487 pszDevType,
5488 strLocationFull.c_str(),
5489 id.raw(),
5490 strConflict.c_str(),
5491 m->strSettingsFilePath.c_str());
5492
5493 // add to the collection if it is a base medium
5494 if (pParent.isNull())
5495 pall->getList().push_back(pMedium);
5496
5497 // store all hard disks (even differencing images) in the map
5498 if (devType == DeviceType_HardDisk)
5499 m->mapHardDisks[id] = pMedium;
5500 }
5501
5502 /*
5503 * If we have been called from Medium::initFromSettings() then the Medium object's
5504 * AutoCaller status will be 'InInit' which means that when making the assigment to
5505 * ppMedium below the Medium object will not call Medium::uninit(). By excluding
5506 * this code path from releasing and reacquiring the media tree lock we avoid a
5507 * potential deadlock with other threads which may be operating on the
5508 * disks/DVDs/floppies in the VM's media registry at the same time such as
5509 * Machine::unregister().
5510 */
5511 if (!fCalledFromMediumInit)
5512 {
5513 // pMedium may be the last reference to the Medium object, and the
5514 // caller may have specified the same ComObjPtr as the output parameter.
5515 // In this case the assignment will uninit the object, and we must not
5516 // have a caller pending.
5517 mediumCaller.release();
5518 // release media tree lock, must not be held at uninit time.
5519 mediaTreeLock.release();
5520 // must not hold the media tree write lock any more
5521 Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5522 }
5523
5524 *ppMedium = pDupMedium.isNull() ? pMedium : pDupMedium;
5525
5526 if (fAddToGlobalRegistry)
5527 {
5528 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5529 if ( fCalledFromMediumInit
5530 ? (*ppMedium)->i_addRegistryNoCallerCheck(m->uuidMediaRegistry)
5531 : (*ppMedium)->i_addRegistry(m->uuidMediaRegistry))
5532 i_markRegistryModified(m->uuidMediaRegistry);
5533 }
5534
5535 // Restore the initial lock state, so that no unexpected lock changes are
5536 // done by this method, which would need adjustments everywhere.
5537 if (!fCalledFromMediumInit)
5538 mediaTreeLock.acquire();
5539
5540 return hrc;
5541}
5542
5543/**
5544 * Removes the given medium from the respective registry.
5545 *
5546 * @param pMedium Hard disk object to remove.
5547 *
5548 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
5549 */
5550HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
5551{
5552 AssertReturn(pMedium != NULL, E_INVALIDARG);
5553
5554 AutoCaller autoCaller(this);
5555 AssertComRCReturnRC(autoCaller.hrc());
5556
5557 AutoCaller mediumCaller(pMedium);
5558 AssertComRCReturnRC(mediumCaller.hrc());
5559
5560 // caller must hold the media tree write lock
5561 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5562
5563 Guid id;
5564 ComObjPtr<Medium> pParent;
5565 DeviceType_T devType;
5566 {
5567 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5568 id = pMedium->i_getId();
5569 pParent = pMedium->i_getParent();
5570 devType = pMedium->i_getDeviceType();
5571 }
5572
5573 ObjectsList<Medium> *pall = NULL;
5574 switch (devType)
5575 {
5576 case DeviceType_HardDisk:
5577 pall = &m->allHardDisks;
5578 break;
5579 case DeviceType_DVD:
5580 pall = &m->allDVDImages;
5581 break;
5582 case DeviceType_Floppy:
5583 pall = &m->allFloppyImages;
5584 break;
5585 default:
5586 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
5587 }
5588
5589 // remove from the collection if it is a base medium
5590 if (pParent.isNull())
5591 pall->getList().remove(pMedium);
5592
5593 // remove all hard disks (even differencing images) from map
5594 if (devType == DeviceType_HardDisk)
5595 {
5596 size_t cnt = m->mapHardDisks.erase(id);
5597 Assert(cnt == 1);
5598 NOREF(cnt);
5599 }
5600
5601 return S_OK;
5602}
5603
5604/**
5605 * Unregisters all Medium objects which belong to the given machine registry.
5606 * Gets called from Machine::uninit() just before the machine object dies
5607 * and must only be called with a machine UUID as the registry ID.
5608 *
5609 * Locks the media tree.
5610 *
5611 * @param uuidMachine Medium registry ID (always a machine UUID)
5612 * @return
5613 */
5614HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
5615{
5616 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
5617
5618 LogFlowFuncEnter();
5619
5620 AutoCaller autoCaller(this);
5621 AssertComRCReturnRC(autoCaller.hrc());
5622
5623 MediaList llMedia2Close;
5624
5625 {
5626 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5627
5628 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
5629 it != m->allHardDisks.getList().end();
5630 ++it)
5631 {
5632 ComObjPtr<Medium> pMedium = *it;
5633 AutoCaller medCaller(pMedium);
5634 if (FAILED(medCaller.hrc())) return medCaller.hrc();
5635 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
5636 Log(("Looking at medium %RTuuid\n", pMedium->i_getId().raw()));
5637
5638 /* If the medium is still in the registry then either some code is
5639 * seriously buggy (unregistering a VM removes it automatically),
5640 * or the reference to a Machine object is destroyed without ever
5641 * being registered. The second condition checks if a medium is
5642 * in no registry, which indicates (set by unregistering) that a
5643 * medium is not used by any other VM and thus can be closed. */
5644 Guid dummy;
5645 if ( pMedium->i_isInRegistry(uuidMachine)
5646 || !pMedium->i_getFirstRegistryMachineId(dummy))
5647 {
5648 /* Collect all medium objects into llMedia2Close,
5649 * in right order for closing. */
5650 MediaList llMediaTodo;
5651 llMediaTodo.push_back(pMedium);
5652
5653 while (llMediaTodo.size() > 0)
5654 {
5655 ComObjPtr<Medium> pCurrent = llMediaTodo.front();
5656 llMediaTodo.pop_front();
5657
5658 /* Add to front, order must be children then parent. */
5659 Log(("Pushing medium %RTuuid (front)\n", pCurrent->i_getId().raw()));
5660 llMedia2Close.push_front(pCurrent);
5661
5662 /* process all children */
5663 MediaList::const_iterator itBegin = pCurrent->i_getChildren().begin();
5664 MediaList::const_iterator itEnd = pCurrent->i_getChildren().end();
5665 for (MediaList::const_iterator it2 = itBegin; it2 != itEnd; ++it2)
5666 llMediaTodo.push_back(*it2);
5667 }
5668 }
5669 }
5670 }
5671
5672 for (MediaList::iterator it = llMedia2Close.begin();
5673 it != llMedia2Close.end();
5674 ++it)
5675 {
5676 ComObjPtr<Medium> pMedium = *it;
5677 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
5678 AutoCaller mac(pMedium);
5679 HRESULT hrc = pMedium->i_close(mac);
5680 if (FAILED(hrc))
5681 return hrc;
5682 }
5683
5684 LogFlowFuncLeave();
5685
5686 return S_OK;
5687}
5688
5689/**
5690 * Removes the given machine object from the internal list of registered machines.
5691 * Called from Machine::Unregister().
5692 * @param pMachine
5693 * @param aCleanupMode How to handle medium attachments. For
5694 * CleanupMode_UnregisterOnly the associated medium objects will be
5695 * closed when the Machine object is uninitialized, otherwise they will
5696 * go to the global registry if no better registry is found.
5697 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
5698 * @return
5699 */
5700HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
5701 CleanupMode_T aCleanupMode,
5702 const Guid &id)
5703{
5704 // remove from the collection of registered machines
5705 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5706 m->allMachines.removeChild(pMachine);
5707 // save the global registry
5708 HRESULT hrc = i_saveSettings();
5709 alock.release();
5710
5711 /*
5712 * Now go over all known media and checks if they were registered in the
5713 * media registry of the given machine. Each such medium is then moved to
5714 * a different media registry to make sure it doesn't get lost since its
5715 * media registry is about to go away.
5716 *
5717 * This fixes the following use case: Image A.vdi of machine A is also used
5718 * by machine B, but registered in the media registry of machine A. If machine
5719 * A is deleted, A.vdi must be moved to the registry of B, or else B will
5720 * become inaccessible.
5721 */
5722 {
5723 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5724 // iterate over the list of *base* images
5725 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
5726 it != m->allHardDisks.getList().end();
5727 ++it)
5728 {
5729 ComObjPtr<Medium> &pMedium = *it;
5730 AutoCaller medCaller(pMedium);
5731 if (FAILED(medCaller.hrc())) return medCaller.hrc();
5732 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
5733
5734 if (pMedium->i_removeRegistryAll(id))
5735 {
5736 // machine ID was found in base medium's registry list:
5737 // move this base image and all its children to another registry then
5738 // 1) first, find a better registry to add things to
5739 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref(id);
5740 if (puuidBetter)
5741 {
5742 // 2) better registry found: then use that
5743 pMedium->i_addRegistryAll(*puuidBetter);
5744 // 3) and make sure the registry is saved below
5745 mlock.release();
5746 tlock.release();
5747 i_markRegistryModified(*puuidBetter);
5748 tlock.acquire();
5749 mlock.acquire();
5750 }
5751 else if (aCleanupMode != CleanupMode_UnregisterOnly)
5752 {
5753 pMedium->i_addRegistryAll(i_getGlobalRegistryId());
5754 mlock.release();
5755 tlock.release();
5756 i_markRegistryModified(i_getGlobalRegistryId());
5757 tlock.acquire();
5758 mlock.acquire();
5759 }
5760 }
5761 }
5762 }
5763
5764 i_saveModifiedRegistries();
5765
5766 /* fire an event */
5767 i_onMachineRegistered(id, FALSE);
5768
5769 return hrc;
5770}
5771
5772/**
5773 * Marks the registry for @a uuid as modified, so that it's saved in a later
5774 * call to saveModifiedRegistries().
5775 *
5776 * @param uuid
5777 */
5778void VirtualBox::i_markRegistryModified(const Guid &uuid)
5779{
5780 if (uuid == i_getGlobalRegistryId())
5781 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
5782 else
5783 {
5784 ComObjPtr<Machine> pMachine;
5785 HRESULT hrc = i_findMachine(uuid, false /* fPermitInaccessible */, false /* aSetError */, &pMachine);
5786 if (SUCCEEDED(hrc))
5787 {
5788 AutoCaller machineCaller(pMachine);
5789 if (SUCCEEDED(machineCaller.hrc()) && pMachine->i_isAccessible())
5790 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
5791 }
5792 }
5793}
5794
5795/**
5796 * Marks the registry for @a uuid as unmodified, so that it's not saved in
5797 * a later call to saveModifiedRegistries().
5798 *
5799 * @param uuid
5800 */
5801void VirtualBox::i_unmarkRegistryModified(const Guid &uuid)
5802{
5803 uint64_t uOld;
5804 if (uuid == i_getGlobalRegistryId())
5805 {
5806 for (;;)
5807 {
5808 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5809 if (!uOld)
5810 break;
5811 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5812 break;
5813 ASMNopPause();
5814 }
5815 }
5816 else
5817 {
5818 ComObjPtr<Machine> pMachine;
5819 HRESULT hrc = i_findMachine(uuid, false /* fPermitInaccessible */, false /* aSetError */, &pMachine);
5820 if (SUCCEEDED(hrc))
5821 {
5822 AutoCaller machineCaller(pMachine);
5823 if (SUCCEEDED(machineCaller.hrc()))
5824 {
5825 for (;;)
5826 {
5827 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5828 if (!uOld)
5829 break;
5830 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5831 break;
5832 ASMNopPause();
5833 }
5834 }
5835 }
5836 }
5837}
5838
5839/**
5840 * Saves all settings files according to the modified flags in the Machine
5841 * objects and in the VirtualBox object.
5842 *
5843 * This locks machines and the VirtualBox object as necessary, so better not
5844 * hold any locks before calling this.
5845 */
5846void VirtualBox::i_saveModifiedRegistries()
5847{
5848 HRESULT hrc = S_OK;
5849 bool fNeedsGlobalSettings = false;
5850 uint64_t uOld;
5851
5852 {
5853 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5854 for (MachinesOList::iterator it = m->allMachines.begin();
5855 it != m->allMachines.end();
5856 ++it)
5857 {
5858 const ComObjPtr<Machine> &pMachine = *it;
5859
5860 for (;;)
5861 {
5862 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5863 if (!uOld)
5864 break;
5865 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5866 break;
5867 ASMNopPause();
5868 }
5869 if (uOld)
5870 {
5871 AutoCaller autoCaller(pMachine);
5872 if (FAILED(autoCaller.hrc()))
5873 continue;
5874 /* object is already dead, no point in saving settings */
5875 if (getObjectState().getState() != ObjectState::Ready)
5876 continue;
5877 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
5878 hrc = pMachine->i_saveSettings(&fNeedsGlobalSettings, mlock,
5879 Machine::SaveS_Force); // caller said save, so stop arguing
5880 }
5881 }
5882 }
5883
5884 for (;;)
5885 {
5886 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5887 if (!uOld)
5888 break;
5889 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5890 break;
5891 ASMNopPause();
5892 }
5893 if (uOld || fNeedsGlobalSettings)
5894 {
5895 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5896 hrc = i_saveSettings();
5897 }
5898 NOREF(hrc); /* XXX */
5899}
5900
5901
5902/* static */
5903const com::Utf8Str &VirtualBox::i_getVersionNormalized()
5904{
5905 return sVersionNormalized;
5906}
5907
5908/**
5909 * Checks if the path to the specified file exists, according to the path
5910 * information present in the file name. Optionally the path is created.
5911 *
5912 * Note that the given file name must contain the full path otherwise the
5913 * extracted relative path will be created based on the current working
5914 * directory which is normally unknown.
5915 *
5916 * @param strFileName Full file name which path is checked/created.
5917 * @param fCreate Flag if the path should be created if it doesn't exist.
5918 *
5919 * @return Extended error information on failure to check/create the path.
5920 */
5921/* static */
5922HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
5923{
5924 Utf8Str strDir(strFileName);
5925 strDir.stripFilename();
5926 if (!RTDirExists(strDir.c_str()))
5927 {
5928 if (fCreate)
5929 {
5930 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
5931 if (RT_FAILURE(vrc))
5932 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, vrc,
5933 tr("Could not create the directory '%s' (%Rrc)"),
5934 strDir.c_str(),
5935 vrc);
5936 }
5937 else
5938 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, VERR_FILE_NOT_FOUND,
5939 tr("Directory '%s' does not exist"), strDir.c_str());
5940 }
5941
5942 return S_OK;
5943}
5944
5945const Utf8Str& VirtualBox::i_settingsFilePath()
5946{
5947 return m->strSettingsFilePath;
5948}
5949
5950/**
5951 * Returns the lock handle which protects the machines list. As opposed
5952 * to version 3.1 and earlier, these lists are no longer protected by the
5953 * VirtualBox lock, but by this more specialized lock. Mind the locking
5954 * order: always request this lock after the VirtualBox object lock but
5955 * before the locks of any machine object. See AutoLock.h.
5956 */
5957RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
5958{
5959 return m->lockMachines;
5960}
5961
5962/**
5963 * Returns the lock handle which protects the media trees (hard disks,
5964 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
5965 * are no longer protected by the VirtualBox lock, but by this more
5966 * specialized lock. Mind the locking order: always request this lock
5967 * after the VirtualBox object lock but before the locks of the media
5968 * objects contained in these lists. See AutoLock.h.
5969 */
5970RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
5971{
5972 return m->lockMedia;
5973}
5974
5975/**
5976 * Thread function that handles custom events posted using #i_postEvent().
5977 */
5978// static
5979DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
5980{
5981 LogFlowFuncEnter();
5982
5983 AssertReturn(pvUser, VERR_INVALID_POINTER);
5984
5985 HRESULT hrc = com::Initialize();
5986 if (FAILED(hrc))
5987 return VERR_COM_UNEXPECTED;
5988
5989 int vrc = VINF_SUCCESS;
5990
5991 try
5992 {
5993 /* Create an event queue for the current thread. */
5994 EventQueue *pEventQueue = new EventQueue();
5995 AssertPtr(pEventQueue);
5996
5997 /* Return the queue to the one who created this thread. */
5998 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
5999
6000 /* signal that we're ready. */
6001 RTThreadUserSignal(thread);
6002
6003 /*
6004 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
6005 * we must not stop processing events and delete the pEventQueue object. This must
6006 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
6007 * See @bugref{5724}.
6008 */
6009 for (;;)
6010 {
6011 vrc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
6012 if (vrc == VERR_INTERRUPTED)
6013 {
6014 LogFlow(("Event queue processing ended with vrc=%Rrc\n", vrc));
6015 vrc = VINF_SUCCESS; /* Set success when exiting. */
6016 break;
6017 }
6018 }
6019
6020 delete pEventQueue;
6021 }
6022 catch (std::bad_alloc &ba)
6023 {
6024 vrc = VERR_NO_MEMORY;
6025 NOREF(ba);
6026 }
6027
6028 com::Shutdown();
6029
6030 LogFlowFuncLeaveRC(vrc);
6031 return vrc;
6032}
6033
6034
6035////////////////////////////////////////////////////////////////////////////////
6036
6037#if 0 /* obsoleted by AsyncEvent */
6038/**
6039 * Prepare the event using the overwritten #prepareEventDesc method and fire.
6040 *
6041 * @note Locks the managed VirtualBox object for reading but leaves the lock
6042 * before iterating over callbacks and calling their methods.
6043 */
6044void *VirtualBox::CallbackEvent::handler()
6045{
6046 if (!mVirtualBox)
6047 return NULL;
6048
6049 AutoCaller autoCaller(mVirtualBox);
6050 if (!autoCaller.isOk())
6051 {
6052 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
6053 mVirtualBox->getObjectState().getState()));
6054 /* We don't need mVirtualBox any more, so release it */
6055 mVirtualBox = NULL;
6056 return NULL;
6057 }
6058
6059 {
6060 VBoxEventDesc evDesc;
6061 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
6062
6063 evDesc.fire(/* don't wait for delivery */0);
6064 }
6065
6066 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
6067 return NULL;
6068}
6069#endif
6070
6071/**
6072 * Called on the event handler thread.
6073 *
6074 * @note Locks the managed VirtualBox object for reading but leaves the lock
6075 * before iterating over callbacks and calling their methods.
6076 */
6077void *VirtualBox::AsyncEvent::handler()
6078{
6079 if (mVirtualBox)
6080 {
6081 AutoCaller autoCaller(mVirtualBox);
6082 if (autoCaller.isOk())
6083 {
6084 VBoxEventDesc EvtDesc(mEvent, mVirtualBox->m->pEventSource);
6085 EvtDesc.fire(/* don't wait for delivery */0);
6086 }
6087 else
6088 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
6089 mVirtualBox->getObjectState().getState()));
6090 mVirtualBox = NULL; /* Old code did this, not really necessary, but whatever. */
6091 }
6092 mEvent.setNull();
6093 return NULL;
6094}
6095
6096//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
6097//{
6098// return E_NOTIMPL;
6099//}
6100
6101HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
6102 ComPtr<IDHCPServer> &aServer)
6103{
6104 ComObjPtr<DHCPServer> dhcpServer;
6105 dhcpServer.createObject();
6106 HRESULT hrc = dhcpServer->init(this, aName);
6107 if (FAILED(hrc)) return hrc;
6108
6109 hrc = i_registerDHCPServer(dhcpServer, true);
6110 if (FAILED(hrc)) return hrc;
6111
6112 dhcpServer.queryInterfaceTo(aServer.asOutParam());
6113
6114 return hrc;
6115}
6116
6117HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
6118 ComPtr<IDHCPServer> &aServer)
6119{
6120 ComPtr<DHCPServer> found;
6121
6122 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
6123
6124 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
6125 it != m->allDHCPServers.end();
6126 ++it)
6127 {
6128 Bstr bstrNetworkName;
6129 HRESULT hrc = (*it)->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
6130 if (FAILED(hrc)) return hrc;
6131
6132 if (Utf8Str(bstrNetworkName) == aName)
6133 {
6134 found = *it;
6135 break;
6136 }
6137 }
6138
6139 if (!found)
6140 return E_INVALIDARG;
6141 return found.queryInterfaceTo(aServer.asOutParam());
6142}
6143
6144HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
6145{
6146 IDHCPServer *aP = aServer;
6147 return i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
6148}
6149
6150/**
6151 * Remembers the given DHCP server in the settings.
6152 *
6153 * @param aDHCPServer DHCP server object to remember.
6154 * @param aSaveSettings @c true to save settings to disk (default).
6155 *
6156 * When @a aSaveSettings is @c true, this operation may fail because of the
6157 * failed #i_saveSettings() method it calls. In this case, the dhcp server object
6158 * will not be remembered. It is therefore the responsibility of the caller to
6159 * call this method as the last step of some action that requires registration
6160 * in order to make sure that only fully functional dhcp server objects get
6161 * registered.
6162 *
6163 * @note Locks this object for writing and @a aDHCPServer for reading.
6164 */
6165HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
6166 bool aSaveSettings /*= true*/)
6167{
6168 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
6169
6170 AutoCaller autoCaller(this);
6171 AssertComRCReturnRC(autoCaller.hrc());
6172
6173 // Acquire a lock on the VirtualBox object early to avoid lock order issues
6174 // when we call i_saveSettings() later on.
6175 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6176 // need it below, in findDHCPServerByNetworkName (reading) and in
6177 // m->allDHCPServers.addChild, so need to get it here to avoid lock
6178 // order trouble with dhcpServerCaller
6179 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
6180
6181 AutoCaller dhcpServerCaller(aDHCPServer);
6182 AssertComRCReturnRC(dhcpServerCaller.hrc());
6183
6184 Bstr bstrNetworkName;
6185 HRESULT hrc = aDHCPServer->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
6186 if (FAILED(hrc)) return hrc;
6187
6188 ComPtr<IDHCPServer> existing;
6189 hrc = findDHCPServerByNetworkName(Utf8Str(bstrNetworkName), existing);
6190 if (SUCCEEDED(hrc))
6191 return E_INVALIDARG;
6192 hrc = S_OK;
6193
6194 m->allDHCPServers.addChild(aDHCPServer);
6195 // we need to release the list lock before we attempt to acquire locks
6196 // on other objects in i_saveSettings (see @bugref{7500})
6197 alock.release();
6198
6199 if (aSaveSettings)
6200 {
6201 // we acquired the lock on 'this' earlier to avoid lock order issues
6202 hrc = i_saveSettings();
6203
6204 if (FAILED(hrc))
6205 {
6206 alock.acquire();
6207 m->allDHCPServers.removeChild(aDHCPServer);
6208 }
6209 }
6210
6211 return hrc;
6212}
6213
6214/**
6215 * Removes the given DHCP server from the settings.
6216 *
6217 * @param aDHCPServer DHCP server object to remove.
6218 *
6219 * This operation may fail because of the failed #i_saveSettings() method it
6220 * calls. In this case, the DHCP server will NOT be removed from the settings
6221 * when this method returns.
6222 *
6223 * @note Locks this object for writing.
6224 */
6225HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
6226{
6227 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
6228
6229 AutoCaller autoCaller(this);
6230 AssertComRCReturnRC(autoCaller.hrc());
6231
6232 AutoCaller dhcpServerCaller(aDHCPServer);
6233 AssertComRCReturnRC(dhcpServerCaller.hrc());
6234
6235 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6236 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
6237 m->allDHCPServers.removeChild(aDHCPServer);
6238 // we need to release the list lock before we attempt to acquire locks
6239 // on other objects in i_saveSettings (see @bugref{7500})
6240 alock.release();
6241
6242 HRESULT hrc = i_saveSettings();
6243
6244 // undo the changes if we failed to save them
6245 if (FAILED(hrc))
6246 {
6247 alock.acquire();
6248 m->allDHCPServers.addChild(aDHCPServer);
6249 }
6250
6251 return hrc;
6252}
6253
6254
6255/**
6256 * NAT Network
6257 */
6258HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
6259 ComPtr<INATNetwork> &aNetwork)
6260{
6261#ifdef VBOX_WITH_NAT_SERVICE
6262 ComObjPtr<NATNetwork> natNetwork;
6263 natNetwork.createObject();
6264 HRESULT hrc = natNetwork->init(this, aNetworkName);
6265 if (FAILED(hrc)) return hrc;
6266
6267 hrc = i_registerNATNetwork(natNetwork, true);
6268 if (FAILED(hrc)) return hrc;
6269
6270 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
6271
6272 ::FireNATNetworkCreationDeletionEvent(m->pEventSource, aNetworkName, TRUE);
6273
6274 return hrc;
6275#else
6276 NOREF(aNetworkName);
6277 NOREF(aNetwork);
6278 return E_NOTIMPL;
6279#endif
6280}
6281
6282HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
6283 ComPtr<INATNetwork> &aNetwork)
6284{
6285#ifdef VBOX_WITH_NAT_SERVICE
6286
6287 HRESULT hrc = S_OK;
6288 ComPtr<NATNetwork> found;
6289
6290 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
6291
6292 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
6293 it != m->allNATNetworks.end();
6294 ++it)
6295 {
6296 Bstr bstrNATNetworkName;
6297 hrc = (*it)->COMGETTER(NetworkName)(bstrNATNetworkName.asOutParam());
6298 if (FAILED(hrc)) return hrc;
6299
6300 if (Utf8Str(bstrNATNetworkName) == aNetworkName)
6301 {
6302 found = *it;
6303 break;
6304 }
6305 }
6306
6307 if (!found)
6308 return E_INVALIDARG;
6309 found.queryInterfaceTo(aNetwork.asOutParam());
6310 return hrc;
6311#else
6312 NOREF(aNetworkName);
6313 NOREF(aNetwork);
6314 return E_NOTIMPL;
6315#endif
6316}
6317
6318HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
6319{
6320#ifdef VBOX_WITH_NAT_SERVICE
6321 Bstr name;
6322 HRESULT hrc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
6323 if (FAILED(hrc))
6324 return hrc;
6325 INATNetwork *p = aNetwork;
6326 NATNetwork *network = static_cast<NATNetwork *>(p);
6327 hrc = i_unregisterNATNetwork(network, true);
6328 ::FireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
6329 return hrc;
6330#else
6331 NOREF(aNetwork);
6332 return E_NOTIMPL;
6333#endif
6334
6335}
6336/**
6337 * Remembers the given NAT network in the settings.
6338 *
6339 * @param aNATNetwork NAT Network object to remember.
6340 * @param aSaveSettings @c true to save settings to disk (default).
6341 *
6342 *
6343 * @note Locks this object for writing and @a aNATNetwork for reading.
6344 */
6345HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
6346 bool aSaveSettings /*= true*/)
6347{
6348#ifdef VBOX_WITH_NAT_SERVICE
6349 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
6350
6351 AutoCaller autoCaller(this);
6352 AssertComRCReturnRC(autoCaller.hrc());
6353
6354 AutoCaller natNetworkCaller(aNATNetwork);
6355 AssertComRCReturnRC(natNetworkCaller.hrc());
6356
6357 Bstr name;
6358 HRESULT hrc;
6359 hrc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
6360 AssertComRCReturnRC(hrc);
6361
6362 /* returned value isn't 0 and aSaveSettings is true
6363 * means that we create duplicate, otherwise we just load settings.
6364 */
6365 if ( sNatNetworkNameToRefCount[name]
6366 && aSaveSettings)
6367 AssertComRCReturnRC(E_INVALIDARG);
6368
6369 hrc = S_OK;
6370
6371 sNatNetworkNameToRefCount[name] = 0;
6372
6373 m->allNATNetworks.addChild(aNATNetwork);
6374
6375 if (aSaveSettings)
6376 {
6377 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6378 hrc = i_saveSettings();
6379 vboxLock.release();
6380
6381 if (FAILED(hrc))
6382 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
6383 }
6384
6385 return hrc;
6386#else
6387 NOREF(aNATNetwork);
6388 NOREF(aSaveSettings);
6389 /* No panic please (silently ignore) */
6390 return S_OK;
6391#endif
6392}
6393
6394/**
6395 * Removes the given NAT network from the settings.
6396 *
6397 * @param aNATNetwork NAT network object to remove.
6398 * @param aSaveSettings @c true to save settings to disk (default).
6399 *
6400 * When @a aSaveSettings is @c true, this operation may fail because of the
6401 * failed #i_saveSettings() method it calls. In this case, the DHCP server
6402 * will NOT be removed from the settingsi when this method returns.
6403 *
6404 * @note Locks this object for writing.
6405 */
6406HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
6407 bool aSaveSettings /*= true*/)
6408{
6409#ifdef VBOX_WITH_NAT_SERVICE
6410 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
6411
6412 AutoCaller autoCaller(this);
6413 AssertComRCReturnRC(autoCaller.hrc());
6414
6415 AutoCaller natNetworkCaller(aNATNetwork);
6416 AssertComRCReturnRC(natNetworkCaller.hrc());
6417
6418 Bstr name;
6419 HRESULT hrc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
6420 /* Hm, there're still running clients. */
6421 if (FAILED(hrc) || sNatNetworkNameToRefCount[name])
6422 AssertComRCReturnRC(E_INVALIDARG);
6423
6424 m->allNATNetworks.removeChild(aNATNetwork);
6425
6426 if (aSaveSettings)
6427 {
6428 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6429 hrc = i_saveSettings();
6430 vboxLock.release();
6431
6432 if (FAILED(hrc))
6433 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
6434 }
6435
6436 return hrc;
6437#else
6438 NOREF(aNATNetwork);
6439 NOREF(aSaveSettings);
6440 return E_NOTIMPL;
6441#endif
6442}
6443
6444HRESULT VirtualBox::findProgressById(const com::Guid &aId,
6445 ComPtr<IProgress> &aProgressObject)
6446{
6447 if (!aId.isValid())
6448 return setError(E_INVALIDARG,
6449 tr("The provided progress object GUID is invalid"));
6450
6451#ifdef VBOX_WITH_OBJ_TRACKER
6452 std::vector<com::Utf8Str> lObjIdMap;
6453 gTrackedObjectsCollector.getObjIdsByClassIID(IID_IProgress, lObjIdMap);
6454
6455 for (const com::Utf8Str& item : lObjIdMap)
6456 {
6457 if(gTrackedObjectsCollector.checkObj(item.c_str()))
6458 {
6459 TrackedObjectData temp;
6460 gTrackedObjectsCollector.getObj(item.c_str(), temp);
6461 Log2(("Tracked Progress Object with objectId %s was found\n", temp.objectIdStr().c_str()));
6462
6463 ComPtr<IProgress> pProgress;
6464 temp.getInterface()->QueryInterface(IID_IProgress, (void **)pProgress.asOutParam());
6465 if (pProgress.isNotNull())
6466 {
6467 Bstr reqId(aId.toString().c_str());
6468 Bstr foundId;
6469 hrc = pProgress->COMGETTER(Id)(foundId.asOutParam());
6470 if (reqId == foundId)
6471 {
6472 BOOL aCompleted;
6473 pProgress->COMGETTER(Completed)(&aCompleted);
6474
6475 BOOL aCanceled;
6476 pProgress->COMGETTER(Canceled)(&aCanceled);
6477 LogRel(("Requested progress was found:\n id %s\n completed %s\n canceled %s\n",
6478 aId.toString().c_str(),
6479 aCompleted ? "True" : "False",
6480 aCanceled ? "True" : "False"));
6481
6482 aProgressObject = pProgress;
6483 return S_OK;
6484 }
6485 }
6486 }
6487 }
6488#else
6489 /* protect mProgressOperations */
6490 AutoReadLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
6491
6492 ProgressMap::const_iterator it = m->mapProgressOperations.find(aId);
6493 if (it != m->mapProgressOperations.end())
6494 {
6495 aProgressObject = it->second;
6496 return S_OK;
6497 }
6498#endif
6499
6500 return setError(E_INVALIDARG,
6501 tr("The progress object with the given GUID could not be found"));
6502}
6503
6504HRESULT VirtualBox::getTrackedObject (const com::Utf8Str& aTrObjId,
6505 ComPtr<IUnknown> &aPIface,
6506 TrackedObjectState_T *aState,
6507 LONG64 *aCreationTime,
6508 LONG64 *aDeletionTime)
6509{
6510 TrackedObjectData trObjData;
6511 HRESULT hrc = gTrackedObjectsCollector.getObj(aTrObjId, trObjData);
6512 if (SUCCEEDED(hrc))
6513 {
6514 trObjData.getInterface().queryInterfaceTo(aPIface.asOutParam());
6515 RTTIMESPEC time = trObjData.creationTime();
6516 *aCreationTime = RTTimeSpecGetMilli(&time);
6517 *aState = trObjData.state();
6518 if (*aState != TrackedObjectState_Alive)
6519 {
6520 time = trObjData.deletionTime();
6521 *aDeletionTime = RTTimeSpecGetMilli(&time);
6522 }
6523 }
6524
6525 return hrc;
6526}
6527
6528
6529std::map <com::Utf8Str, com::Utf8Str> lMapInterfaceNameToIID = {
6530 {"IProgress", Guid(IID_IProgress).toString()},
6531 {"ISession", Guid(IID_ISession).toString()},
6532 {"IMedium", Guid(IID_IMedium).toString()},
6533 {"IMachine", Guid(IID_IMachine).toString()}
6534};
6535
6536/**
6537 * Get the tracked object Ids list by the interface name.
6538 *
6539 * @param aName Interface name (like "IProgress", "ISession", "IMedium" etc)
6540 * @param aObjIdsList The list of Ids of the found objects
6541 *
6542 * @return The list of the found objects Ids
6543 */
6544HRESULT VirtualBox::getTrackedObjectIds (const com::Utf8Str& aName,
6545 std::vector<com::Utf8Str> &aObjIdsList)
6546{
6547 HRESULT hrc = S_OK;
6548
6549 try
6550 {
6551 /* Check the supported tracked classes to avoid "out of range" exception */
6552 if (lMapInterfaceNameToIID.count(aName))
6553 {
6554 hrc = gTrackedObjectsCollector.getObjIdsByClassIID(lMapInterfaceNameToIID.at(aName), aObjIdsList);
6555 if (FAILED(hrc))
6556 hrc = setError(VBOX_E_OBJECT_NOT_FOUND, tr("No objects were found for the passed interface name '%s'."),
6557 aName.c_str());
6558 }
6559 else
6560 hrc = setError(E_INVALIDARG, tr("The objects of the passed interface '%s' are not tracked at moment."), aName.c_str());
6561 }
6562 catch (...)
6563 {
6564 hrc = setError(E_FAIL, tr("The unknown exception in the VirtualBox::getTrackedObjectIds()."));
6565 }
6566
6567 return hrc;
6568}
6569
6570/**
6571 * Retains a reference to the default cryptographic interface.
6572 *
6573 * @returns COM status code.
6574 * @param ppCryptoIf Where to store the pointer to the cryptographic interface on success.
6575 *
6576 * @note Locks this object for writing.
6577 */
6578HRESULT VirtualBox::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
6579{
6580 AssertReturn(ppCryptoIf != NULL, E_INVALIDARG);
6581
6582 AutoCaller autoCaller(this);
6583 AssertComRCReturnRC(autoCaller.hrc());
6584
6585 /*
6586 * No object lock due to some lock order fun with Machine objects.
6587 * There is a dedicated critical section to protect against concurrency
6588 * issues when loading the module.
6589 */
6590 RTCritSectEnter(&m->CritSectModCrypto);
6591
6592 /* Try to load the extension pack module if it isn't currently. */
6593 HRESULT hrc = S_OK;
6594 if (m->hLdrModCrypto == NIL_RTLDRMOD)
6595 {
6596#ifdef VBOX_WITH_EXTPACK
6597 /*
6598 * Check that a crypto extension pack name is set and resolve it into a
6599 * library path.
6600 */
6601 Utf8Str strExtPack;
6602 hrc = m->pSystemProperties->getDefaultCryptoExtPack(strExtPack);
6603 if (FAILED(hrc))
6604 {
6605 RTCritSectLeave(&m->CritSectModCrypto);
6606 return hrc;
6607 }
6608 if (strExtPack.isEmpty())
6609 {
6610 RTCritSectLeave(&m->CritSectModCrypto);
6611 return setError(VBOX_E_OBJECT_NOT_FOUND,
6612 tr("Ńo extension pack providing a cryptographic support module could be found"));
6613 }
6614
6615 Utf8Str strCryptoLibrary;
6616 int vrc = m->ptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
6617 if (RT_SUCCESS(vrc))
6618 {
6619 RTERRINFOSTATIC ErrInfo;
6620 vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &m->hLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
6621 if (RT_SUCCESS(vrc))
6622 {
6623 /* Resolve the entry point and query the pointer to the cryptographic interface. */
6624 PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
6625 vrc = RTLdrGetSymbol(m->hLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
6626 if (RT_SUCCESS(vrc))
6627 {
6628 vrc = pfnCryptoEntry(&m->pCryptoIf);
6629 if (RT_FAILURE(vrc))
6630 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6631 tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
6632 strCryptoLibrary.c_str(), strExtPack.c_str());
6633 }
6634 else
6635 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6636 tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
6637 strCryptoLibrary.c_str(), strExtPack.c_str());
6638 }
6639 else
6640 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6641 tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
6642 strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
6643 }
6644 else
6645 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
6646 tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
6647 strExtPack.c_str());
6648#else
6649 hrc = setError(VBOX_E_NOT_SUPPORTED,
6650 tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
6651#endif
6652 }
6653
6654 if (SUCCEEDED(hrc))
6655 {
6656 ASMAtomicIncU32(&m->cRefsCrypto);
6657 *ppCryptoIf = m->pCryptoIf;
6658 }
6659
6660 RTCritSectLeave(&m->CritSectModCrypto);
6661
6662 return hrc;
6663}
6664
6665
6666/**
6667 * Releases the reference of the given cryptographic interface.
6668 *
6669 * @returns COM status code.
6670 * @param pCryptoIf Pointer to the cryptographic interface to release.
6671 *
6672 * @note Locks this object for writing.
6673 */
6674HRESULT VirtualBox::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
6675{
6676 AutoCaller autoCaller(this);
6677 AssertComRCReturnRC(autoCaller.hrc());
6678
6679 AssertReturn(pCryptoIf == m->pCryptoIf, E_INVALIDARG);
6680
6681 ASMAtomicDecU32(&m->cRefsCrypto);
6682 return S_OK;
6683}
6684
6685
6686/**
6687 * Tries to unload any loaded cryptographic support module if it is not in use currently.
6688 *
6689 * @returns COM status code.
6690 *
6691 * @note Locks this object for writing.
6692 */
6693HRESULT VirtualBox::i_unloadCryptoIfModule(void)
6694{
6695 AutoCaller autoCaller(this);
6696 AssertComRCReturnRC(autoCaller.hrc());
6697
6698 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
6699
6700 if (m->cRefsCrypto)
6701 return setError(E_ACCESSDENIED,
6702 tr("The cryptographic support module is in use and can't be unloaded"));
6703
6704 RTCritSectEnter(&m->CritSectModCrypto);
6705 if (m->hLdrModCrypto != NIL_RTLDRMOD)
6706 {
6707 int vrc = RTLdrClose(m->hLdrModCrypto);
6708 AssertRC(vrc);
6709 m->hLdrModCrypto = NIL_RTLDRMOD;
6710 }
6711 RTCritSectLeave(&m->CritSectModCrypto);
6712
6713 return S_OK;
6714}
6715
6716
6717#ifdef RT_OS_WINDOWS
6718#include <psapi.h>
6719
6720/**
6721 * Report versions of installed drivers to release log.
6722 */
6723void VirtualBox::i_reportDriverVersions()
6724{
6725 /** @todo r=klaus this code is very confusing, as it uses TCHAR (and
6726 * randomly also _TCHAR, which sounds to me like asking for trouble),
6727 * the "sz" variable prefix but "%ls" for the format string - so the whole
6728 * thing is better compiled with UNICODE and _UNICODE defined. Would be
6729 * far easier to read if it would be coded explicitly for the unicode
6730 * case, as it won't work otherwise. */
6731 DWORD err;
6732 HRESULT hrc;
6733 LPVOID aDrivers[1024];
6734 LPVOID *pDrivers = aDrivers;
6735 UINT cNeeded = 0;
6736 TCHAR szSystemRoot[MAX_PATH];
6737 TCHAR *pszSystemRoot = szSystemRoot;
6738 LPVOID pVerInfo = NULL;
6739 DWORD cbVerInfo = 0;
6740
6741 do
6742 {
6743 cNeeded = GetWindowsDirectory(szSystemRoot, RT_ELEMENTS(szSystemRoot));
6744 if (cNeeded == 0)
6745 {
6746 err = GetLastError();
6747 hrc = HRESULT_FROM_WIN32(err);
6748 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hrc=%Rhrc (0x%x) err=%u\n",
6749 hrc, hrc, err));
6750 break;
6751 }
6752 else if (cNeeded > RT_ELEMENTS(szSystemRoot))
6753 {
6754 /* The buffer is too small, allocate big one. */
6755 pszSystemRoot = (TCHAR *)RTMemTmpAlloc(cNeeded * sizeof(_TCHAR));
6756 if (!pszSystemRoot)
6757 {
6758 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cNeeded));
6759 break;
6760 }
6761 if (GetWindowsDirectory(pszSystemRoot, cNeeded) == 0)
6762 {
6763 err = GetLastError();
6764 hrc = HRESULT_FROM_WIN32(err);
6765 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hrc=%Rhrc (0x%x) err=%u\n",
6766 hrc, hrc, err));
6767 break;
6768 }
6769 }
6770
6771 DWORD cbNeeded = 0;
6772 if (!EnumDeviceDrivers(aDrivers, sizeof(aDrivers), &cbNeeded) || cbNeeded > sizeof(aDrivers))
6773 {
6774 pDrivers = (LPVOID *)RTMemTmpAlloc(cbNeeded);
6775 if (!EnumDeviceDrivers(pDrivers, cbNeeded, &cbNeeded))
6776 {
6777 err = GetLastError();
6778 hrc = HRESULT_FROM_WIN32(err);
6779 AssertLogRelMsgFailed(("EnumDeviceDrivers failed, hrc=%Rhrc (0x%x) err=%u\n",
6780 hrc, hrc, err));
6781 break;
6782 }
6783 }
6784
6785 LogRel(("Installed Drivers:\n"));
6786
6787 TCHAR szDriver[1024];
6788 int cDrivers = cbNeeded / sizeof(pDrivers[0]);
6789 for (int i = 0; i < cDrivers; i++)
6790 {
6791 if (GetDeviceDriverBaseName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
6792 {
6793 if (_tcsnicmp(TEXT("vbox"), szDriver, 4))
6794 continue;
6795 }
6796 else
6797 continue;
6798 if (GetDeviceDriverFileName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
6799 {
6800 _TCHAR szTmpDrv[1024];
6801 _TCHAR *pszDrv = szDriver;
6802 if (!_tcsncmp(TEXT("\\SystemRoot"), szDriver, 11))
6803 {
6804 _tcscpy_s(szTmpDrv, pszSystemRoot);
6805 _tcsncat_s(szTmpDrv, szDriver + 11, sizeof(szTmpDrv) / sizeof(szTmpDrv[0]) - _tclen(pszSystemRoot));
6806 pszDrv = szTmpDrv;
6807 }
6808 else if (!_tcsncmp(TEXT("\\??\\"), szDriver, 4))
6809 pszDrv = szDriver + 4;
6810
6811 /* Allocate a buffer for version info. Reuse if large enough. */
6812 DWORD cbNewVerInfo = GetFileVersionInfoSize(pszDrv, NULL);
6813 if (cbNewVerInfo > cbVerInfo)
6814 {
6815 if (pVerInfo)
6816 RTMemTmpFree(pVerInfo);
6817 cbVerInfo = cbNewVerInfo;
6818 pVerInfo = RTMemTmpAlloc(cbVerInfo);
6819 if (!pVerInfo)
6820 {
6821 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cbVerInfo));
6822 break;
6823 }
6824 }
6825
6826 if (GetFileVersionInfo(pszDrv, NULL, cbVerInfo, pVerInfo))
6827 {
6828 UINT cbSize = 0;
6829 LPBYTE lpBuffer = NULL;
6830 if (VerQueryValue(pVerInfo, TEXT("\\"), (VOID FAR* FAR*)&lpBuffer, &cbSize))
6831 {
6832 if (cbSize)
6833 {
6834 VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
6835 if (pFileInfo->dwSignature == 0xfeef04bd)
6836 {
6837 LogRel((" %ls (Version: %d.%d.%d.%d)\n", pszDrv,
6838 (pFileInfo->dwFileVersionMS >> 16) & 0xffff,
6839 (pFileInfo->dwFileVersionMS >> 0) & 0xffff,
6840 (pFileInfo->dwFileVersionLS >> 16) & 0xffff,
6841 (pFileInfo->dwFileVersionLS >> 0) & 0xffff));
6842 }
6843 }
6844 }
6845 }
6846 }
6847 }
6848
6849 }
6850 while (0);
6851
6852 if (pVerInfo)
6853 RTMemTmpFree(pVerInfo);
6854
6855 if (pDrivers != aDrivers)
6856 RTMemTmpFree(pDrivers);
6857
6858 if (pszSystemRoot != szSystemRoot)
6859 RTMemTmpFree(pszSystemRoot);
6860}
6861#else /* !RT_OS_WINDOWS */
6862void VirtualBox::i_reportDriverVersions(void)
6863{
6864}
6865#endif /* !RT_OS_WINDOWS */
6866
6867#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
6868
6869# include <psapi.h> /* for GetProcessImageFileNameW */
6870
6871/**
6872 * Callout from the wrapper.
6873 */
6874void VirtualBox::i_callHook(const char *a_pszFunction)
6875{
6876 RT_NOREF(a_pszFunction);
6877
6878 /*
6879 * Let'see figure out who is calling.
6880 * Note! Requires Vista+, so skip this entirely on older systems.
6881 */
6882 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
6883 {
6884 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
6885 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
6886 if ( rcRpc == RPC_S_OK
6887 && CallAttribs.ClientPID != 0)
6888 {
6889 RTPROCESS const pidClient = (RTPROCESS)(uintptr_t)CallAttribs.ClientPID;
6890 if (pidClient != RTProcSelf())
6891 {
6892 /** @todo LogRel2 later: */
6893 LogRel(("i_callHook: %Rfn [ClientPID=%#zx/%zu IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6894 a_pszFunction, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
6895 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6896 &CallAttribs.InterfaceUuid));
6897
6898 /*
6899 * Do we know this client PID already?
6900 */
6901 RTCritSectRwEnterShared(&m->WatcherCritSect);
6902 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(pidClient);
6903 if (It != m->WatchedProcesses.end())
6904 RTCritSectRwLeaveShared(&m->WatcherCritSect); /* Known process, nothing to do. */
6905 else
6906 {
6907 /* This is a new client process, start watching it. */
6908 RTCritSectRwLeaveShared(&m->WatcherCritSect);
6909 i_watchClientProcess(pidClient, a_pszFunction);
6910 }
6911 }
6912 }
6913 else
6914 LogRel(("i_callHook: %Rfn - rcRpc=%#x ClientPID=%#zx/%zu !! [IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6915 a_pszFunction, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
6916 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6917 &CallAttribs.InterfaceUuid));
6918 }
6919}
6920
6921
6922/**
6923 * Watches @a a_pidClient for termination.
6924 *
6925 * @returns true if successfully enabled watching of it, false if not.
6926 * @param a_pidClient The PID to watch.
6927 * @param a_pszFunction The function we which we detected the client in.
6928 */
6929bool VirtualBox::i_watchClientProcess(RTPROCESS a_pidClient, const char *a_pszFunction)
6930{
6931 RT_NOREF_PV(a_pszFunction);
6932
6933 /*
6934 * Open the client process.
6935 */
6936 HANDLE hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE /*fInherit*/, a_pidClient);
6937 if (hClient == NULL)
6938 hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE , a_pidClient);
6939 if (hClient == NULL)
6940 hClient = OpenProcess(SYNCHRONIZE, FALSE , a_pidClient);
6941 AssertLogRelMsgReturn(hClient != NULL, ("pidClient=%d (%#x) err=%d\n", a_pidClient, a_pidClient, GetLastError()),
6942 m->fWatcherIsReliable = false);
6943
6944 /*
6945 * Create a new watcher structure and try add it to the map.
6946 */
6947 bool fRet = true;
6948 WatchedClientProcess *pWatched = new (std::nothrow) WatchedClientProcess(a_pidClient, hClient);
6949 if (pWatched)
6950 {
6951 RTCritSectRwEnterExcl(&m->WatcherCritSect);
6952
6953 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(a_pidClient);
6954 if (It == m->WatchedProcesses.end())
6955 {
6956 try
6957 {
6958 m->WatchedProcesses.insert(WatchedClientProcessMap::value_type(a_pidClient, pWatched));
6959 }
6960 catch (std::bad_alloc &)
6961 {
6962 fRet = false;
6963 }
6964 if (fRet)
6965 {
6966 /*
6967 * Schedule it on a watcher thread.
6968 */
6969 /** @todo later. */
6970 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6971 }
6972 else
6973 {
6974 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6975 delete pWatched;
6976 LogRel(("VirtualBox::i_watchClientProcess: out of memory inserting into client map!\n"));
6977 }
6978 }
6979 else
6980 {
6981 /*
6982 * Someone raced us here, we lost.
6983 */
6984 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6985 delete pWatched;
6986 }
6987 }
6988 else
6989 {
6990 LogRel(("VirtualBox::i_watchClientProcess: out of memory!\n"));
6991 CloseHandle(hClient);
6992 m->fWatcherIsReliable = fRet = false;
6993 }
6994 return fRet;
6995}
6996
6997
6998/** Logs the RPC caller info to the release log. */
6999/*static*/ void VirtualBox::i_logCaller(const char *a_pszFormat, ...)
7000{
7001 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
7002 {
7003 char szTmp[80];
7004 va_list va;
7005 va_start(va, a_pszFormat);
7006 RTStrPrintfV(szTmp, sizeof(szTmp), a_pszFormat, va);
7007 va_end(va);
7008
7009 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
7010 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
7011
7012 RTUTF16 wszProcName[256];
7013 wszProcName[0] = '\0';
7014 if (rcRpc == 0 && CallAttribs.ClientPID != 0)
7015 {
7016 HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)(uintptr_t)CallAttribs.ClientPID);
7017 if (hProcess)
7018 {
7019 RT_ZERO(wszProcName);
7020 GetProcessImageFileNameW(hProcess, wszProcName, RT_ELEMENTS(wszProcName) - 1);
7021 CloseHandle(hProcess);
7022 }
7023 }
7024 LogRel(("%s [rcRpc=%#x ClientPID=%#zx/%zu (%ls) IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
7025 szTmp, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, wszProcName, CallAttribs.IsClientLocal,
7026 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
7027 &CallAttribs.InterfaceUuid));
7028 }
7029}
7030
7031#endif /* RT_OS_WINDOWS && VBOXSVC_WITH_CLIENT_WATCHER */
7032
7033
7034/* vi: set tabstop=4 shiftwidth=4 expandtab: */
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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