VirtualBox

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

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

Main/src-server/VirtualBoxImpl.cpp: Missing error check and disable unused code, bugref:3409

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