VirtualBox

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

Last change on this file since 81427 was 81427, checked in by vboxsync, 5 years ago

Build fixes for r134139

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

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