VirtualBox

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

Last change on this file since 86506 was 86501, checked in by vboxsync, 4 years ago

VBoxSVC: Fix Medium leak when encoutering duplicate instances while loading a media registry (from settings) via VirtualBox::initMedia(). The media registration is now moved to before any children are loaded, so that we use the right parent for them. This essentially changes the operation to a merge. An unaddressed issue is that on child load failure, we will leave the parent(s) still registered but non-functioning (uninit was done). (The old code would just leave any successfully loaded children registered with non-working parents only accessible via their parent attribute.) bugref:9841

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

© 2023 Oracle
ContactPrivacy policyTerms of Use