VirtualBox

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

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

iprt/cdefs.h: Refactored the typedef use of DECLCALLBACK as well as DECLCALLBACKMEMBER to wrap the whole expression, similar to the DECLR?CALLBACKMEMBER macros. This allows adding a throw() at the end when compiling with the VC++ compiler to indicate that the callbacks won't throw anything, so we can stop supressing the C5039 warning about passing functions that can potential throw C++ exceptions to extern C code that can't necessarily cope with such (unwind,++). Introduced a few _EX variations that allows specifying different/no calling convention too, as that's handy when dynamically resolving host APIs. Fixed numerous places missing DECLCALLBACK and such. Left two angry @todos regarding use of CreateThread. bugref:9794

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 209.2 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 85121 2020-07-08 19:33:26Z vboxsync $ */
2/** @file
3 * Implementation of IVirtualBox in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_MAIN_VIRTUALBOX
19#include <iprt/asm.h>
20#include <iprt/base64.h>
21#include <iprt/buildconfig.h>
22#include <iprt/cpp/utils.h>
23#include <iprt/dir.h>
24#include <iprt/env.h>
25#include <iprt/file.h>
26#include <iprt/path.h>
27#include <iprt/process.h>
28#include <iprt/rand.h>
29#include <iprt/sha.h>
30#include <iprt/string.h>
31#include <iprt/stream.h>
32#include <iprt/system.h>
33#include <iprt/thread.h>
34#include <iprt/uuid.h>
35#include <iprt/cpp/xml.h>
36#include <iprt/ctype.h>
37
38#include <VBox/com/com.h>
39#include <VBox/com/array.h>
40#include "VBox/com/EventQueue.h"
41#include "VBox/com/MultiResult.h"
42
43#include <VBox/err.h>
44#include <VBox/param.h>
45#include <VBox/settings.h>
46#include <VBox/version.h>
47
48#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
49# include <VBox/GuestHost/SharedClipboard-transfers.h>
50#endif
51
52#include <package-generated.h>
53
54#include <algorithm>
55#include <set>
56#include <vector>
57#include <memory> // for auto_ptr
58
59#include "VirtualBoxImpl.h"
60
61#include "Global.h"
62#include "MachineImpl.h"
63#include "MediumImpl.h"
64#include "SharedFolderImpl.h"
65#include "ProgressImpl.h"
66#include "HostImpl.h"
67#include "USBControllerImpl.h"
68#include "SystemPropertiesImpl.h"
69#include "GuestOSTypeImpl.h"
70#include "NetworkServiceRunner.h"
71#include "DHCPServerImpl.h"
72#include "NATNetworkImpl.h"
73#ifdef VBOX_WITH_CLOUD_NET
74#include "CloudNetworkImpl.h"
75#endif /* VBOX_WITH_CLOUD_NET */
76#ifdef VBOX_WITH_RESOURCE_USAGE_API
77# include "PerformanceImpl.h"
78#endif /* VBOX_WITH_RESOURCE_USAGE_API */
79#include "EventImpl.h"
80#ifdef VBOX_WITH_EXTPACK
81# include "ExtPackManagerImpl.h"
82#endif
83#ifdef VBOX_WITH_UNATTENDED
84# include "UnattendedImpl.h"
85#endif
86#include "AutostartDb.h"
87#include "ClientWatcher.h"
88#include "AutoCaller.h"
89#include "LoggingNew.h"
90#include "CloudProviderManagerImpl.h"
91#include "ThreadTask.h"
92
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 = VBOX_E_OBJECT_NOT_FOUND;
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 HRESULT hrc = (*it)->COMGETTER(NetworkName)(bstrCloudNetworkName.asOutParam());
1521 if (FAILED(hrc)) return hrc;
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
1620#ifdef VBOX_WITH_CLOUD_NET
1621HRESULT VirtualBox::i_getEventSource(ComPtr<IEventSource>& aSource)
1622{
1623 m->pEventSource.queryInterfaceTo(aSource.asOutParam());
1624 return S_OK;
1625}
1626#endif /* VBOX_WITH_CLOUD_NET */
1627
1628HRESULT VirtualBox::getCloudProviderManager(ComPtr<ICloudProviderManager> &aCloudProviderManager)
1629{
1630 HRESULT hrc = m->pCloudProviderManager.queryInterfaceTo(aCloudProviderManager.asOutParam());
1631 return hrc;
1632}
1633
1634HRESULT VirtualBox::checkFirmwarePresent(FirmwareType_T aFirmwareType,
1635 const com::Utf8Str &aVersion,
1636 com::Utf8Str &aUrl,
1637 com::Utf8Str &aFile,
1638 BOOL *aResult)
1639{
1640 NOREF(aVersion);
1641
1642 static const struct
1643 {
1644 FirmwareType_T enmType;
1645 bool fBuiltIn;
1646 const char *pszFileName;
1647 const char *pszUrl;
1648 }
1649 firmwareDesc[] =
1650 {
1651 { FirmwareType_BIOS, true, NULL, NULL },
1652#ifdef VBOX_WITH_EFI_IN_DD2
1653 { FirmwareType_EFI32, true, "VBoxEFI32.fd", NULL },
1654 { FirmwareType_EFI64, true, "VBoxEFI64.fd", NULL },
1655 { FirmwareType_EFIDUAL, true, "VBoxEFIDual.fd", NULL },
1656#else
1657 { FirmwareType_EFI32, false, "VBoxEFI32.fd", "http://virtualbox.org/firmware/VBoxEFI32.fd" },
1658 { FirmwareType_EFI64, false, "VBoxEFI64.fd", "http://virtualbox.org/firmware/VBoxEFI64.fd" },
1659 { FirmwareType_EFIDUAL, false, "VBoxEFIDual.fd", "http://virtualbox.org/firmware/VBoxEFIDual.fd" },
1660#endif
1661 };
1662
1663 for (size_t i = 0; i < sizeof(firmwareDesc) / sizeof(firmwareDesc[0]); i++)
1664 {
1665 if (aFirmwareType != firmwareDesc[i].enmType)
1666 continue;
1667
1668 /* compiled-in firmware */
1669 if (firmwareDesc[i].fBuiltIn)
1670 {
1671 aFile = firmwareDesc[i].pszFileName;
1672 *aResult = TRUE;
1673 break;
1674 }
1675
1676 Utf8Str fullName;
1677 Utf8StrFmt shortName("Firmware%c%s", RTPATH_DELIMITER, firmwareDesc[i].pszFileName);
1678 int rc = i_calculateFullPath(shortName, fullName);
1679 AssertRCReturn(rc, VBOX_E_IPRT_ERROR);
1680 if (RTFileExists(fullName.c_str()))
1681 {
1682 *aResult = TRUE;
1683 aFile = fullName;
1684 break;
1685 }
1686
1687 char szVBoxPath[RTPATH_MAX];
1688 rc = RTPathExecDir(szVBoxPath, RTPATH_MAX);
1689 AssertRCReturn(rc, VBOX_E_IPRT_ERROR);
1690 rc = RTPathAppend(szVBoxPath, sizeof(szVBoxPath), firmwareDesc[i].pszFileName);
1691 if (RTFileExists(szVBoxPath))
1692 {
1693 *aResult = TRUE;
1694 aFile = szVBoxPath;
1695 break;
1696 }
1697
1698 /** @todo account for version in the URL */
1699 aUrl = firmwareDesc[i].pszUrl;
1700 *aResult = FALSE;
1701
1702 /* Assume single record per firmware type */
1703 break;
1704 }
1705
1706 return S_OK;
1707}
1708// Wrapped IVirtualBox methods
1709/////////////////////////////////////////////////////////////////////////////
1710
1711/* Helper for VirtualBox::ComposeMachineFilename */
1712static void sanitiseMachineFilename(Utf8Str &aName);
1713
1714HRESULT VirtualBox::composeMachineFilename(const com::Utf8Str &aName,
1715 const com::Utf8Str &aGroup,
1716 const com::Utf8Str &aCreateFlags,
1717 const com::Utf8Str &aBaseFolder,
1718 com::Utf8Str &aFile)
1719{
1720 if (RT_UNLIKELY(aName.isEmpty()))
1721 return setError(E_INVALIDARG, tr("Machine name is invalid, must not be empty"));
1722
1723 Utf8Str strBase = aBaseFolder;
1724 Utf8Str strName = aName;
1725
1726 LogFlowThisFunc(("aName=\"%s\",aBaseFolder=\"%s\"\n", strName.c_str(), strBase.c_str()));
1727
1728 com::Guid id;
1729 bool fDirectoryIncludesUUID = false;
1730 if (!aCreateFlags.isEmpty())
1731 {
1732 size_t uPos = 0;
1733 com::Utf8Str strKey;
1734 com::Utf8Str strValue;
1735 while ((uPos = aCreateFlags.parseKeyValue(strKey, strValue, uPos)) != com::Utf8Str::npos)
1736 {
1737 if (strKey == "UUID")
1738 id = strValue.c_str();
1739 else if (strKey == "directoryIncludesUUID")
1740 fDirectoryIncludesUUID = (strValue == "1");
1741 }
1742 }
1743
1744 if (id.isZero())
1745 fDirectoryIncludesUUID = false;
1746 else if (!id.isValid())
1747 {
1748 /* do something else */
1749 return setError(E_INVALIDARG,
1750 tr("'%s' is not a valid Guid"),
1751 id.toStringCurly().c_str());
1752 }
1753
1754 Utf8Str strGroup(aGroup);
1755 if (strGroup.isEmpty())
1756 strGroup = "/";
1757 HRESULT rc = i_validateMachineGroup(strGroup, true);
1758 if (FAILED(rc))
1759 return rc;
1760
1761 /* Compose the settings file name using the following scheme:
1762 *
1763 * <base_folder><group>/<machine_name>/<machine_name>.xml
1764 *
1765 * If a non-null and non-empty base folder is specified, the default
1766 * machine folder will be used as a base folder.
1767 * We sanitise the machine name to a safe white list of characters before
1768 * using it.
1769 */
1770 Utf8Str strDirName(strName);
1771 if (fDirectoryIncludesUUID)
1772 strDirName += Utf8StrFmt(" (%RTuuid)", id.raw());
1773 sanitiseMachineFilename(strName);
1774 sanitiseMachineFilename(strDirName);
1775
1776 if (strBase.isEmpty())
1777 /* we use the non-full folder value below to keep the path relative */
1778 i_getDefaultMachineFolder(strBase);
1779
1780 i_calculateFullPath(strBase, strBase);
1781
1782 /* eliminate toplevel group to avoid // in the result */
1783 if (strGroup == "/")
1784 strGroup.setNull();
1785 aFile = com::Utf8StrFmt("%s%s%c%s%c%s.vbox",
1786 strBase.c_str(),
1787 strGroup.c_str(),
1788 RTPATH_DELIMITER,
1789 strDirName.c_str(),
1790 RTPATH_DELIMITER,
1791 strName.c_str());
1792 return S_OK;
1793}
1794
1795/**
1796 * Remove characters from a machine file name which can be problematic on
1797 * particular systems.
1798 * @param strName The file name to sanitise.
1799 */
1800void sanitiseMachineFilename(Utf8Str &strName)
1801{
1802 if (strName.isEmpty())
1803 return;
1804
1805 /* Set of characters which should be safe for use in filenames: some basic
1806 * ASCII, Unicode from Latin-1 alphabetic to the end of Hangul. We try to
1807 * skip anything that could count as a control character in Windows or
1808 * *nix, or be otherwise difficult for shells to handle (I would have
1809 * preferred to remove the space and brackets too). We also remove all
1810 * characters which need UTF-16 surrogate pairs for Windows's benefit.
1811 */
1812 static RTUNICP const s_uszValidRangePairs[] =
1813 {
1814 ' ', ' ',
1815 '(', ')',
1816 '-', '.',
1817 '0', '9',
1818 'A', 'Z',
1819 'a', 'z',
1820 '_', '_',
1821 0xa0, 0xd7af,
1822 '\0'
1823 };
1824
1825 char *pszName = strName.mutableRaw();
1826 ssize_t cReplacements = RTStrPurgeComplementSet(pszName, s_uszValidRangePairs, '_');
1827 Assert(cReplacements >= 0);
1828 NOREF(cReplacements);
1829
1830 /* No leading dot or dash. */
1831 if (pszName[0] == '.' || pszName[0] == '-')
1832 pszName[0] = '_';
1833
1834 /* No trailing dot. */
1835 if (pszName[strName.length() - 1] == '.')
1836 pszName[strName.length() - 1] = '_';
1837
1838 /* Mangle leading and trailing spaces. */
1839 for (size_t i = 0; pszName[i] == ' '; ++i)
1840 pszName[i] = '_';
1841 for (size_t i = strName.length() - 1; i && pszName[i] == ' '; --i)
1842 pszName[i] = '_';
1843}
1844
1845#ifdef DEBUG
1846typedef DECLCALLBACKTYPE(void, FNTESTPRINTF,(const char *, ...));
1847/** Simple unit test/operation examples for sanitiseMachineFilename(). */
1848static unsigned testSanitiseMachineFilename(FNTESTPRINTF *pfnPrintf)
1849{
1850 unsigned cErrors = 0;
1851
1852 /** Expected results of sanitising given file names. */
1853 static struct
1854 {
1855 /** The test file name to be sanitised (Utf-8). */
1856 const char *pcszIn;
1857 /** The expected sanitised output (Utf-8). */
1858 const char *pcszOutExpected;
1859 } aTest[] =
1860 {
1861 { "OS/2 2.1", "OS_2 2.1" },
1862 { "-!My VM!-", "__My VM_-" },
1863 { "\xF0\x90\x8C\xB0", "____" },
1864 { " My VM ", "__My VM__" },
1865 { ".My VM.", "_My VM_" },
1866 { "My VM", "My VM" }
1867 };
1868 for (unsigned i = 0; i < RT_ELEMENTS(aTest); ++i)
1869 {
1870 Utf8Str str(aTest[i].pcszIn);
1871 sanitiseMachineFilename(str);
1872 if (str.compare(aTest[i].pcszOutExpected))
1873 {
1874 ++cErrors;
1875 pfnPrintf("%s: line %d, expected %s, actual %s\n",
1876 __PRETTY_FUNCTION__, i, aTest[i].pcszOutExpected,
1877 str.c_str());
1878 }
1879 }
1880 return cErrors;
1881}
1882
1883/** @todo Proper testcase. */
1884/** @todo Do we have a better method of doing init functions? */
1885namespace
1886{
1887 class TestSanitiseMachineFilename
1888 {
1889 public:
1890 TestSanitiseMachineFilename(void)
1891 {
1892 Assert(!testSanitiseMachineFilename(RTAssertMsg2));
1893 }
1894 };
1895 TestSanitiseMachineFilename s_TestSanitiseMachineFilename;
1896}
1897#endif
1898
1899/** @note Locks mSystemProperties object for reading. */
1900HRESULT VirtualBox::createMachine(const com::Utf8Str &aSettingsFile,
1901 const com::Utf8Str &aName,
1902 const std::vector<com::Utf8Str> &aGroups,
1903 const com::Utf8Str &aOsTypeId,
1904 const com::Utf8Str &aFlags,
1905 ComPtr<IMachine> &aMachine)
1906{
1907 LogFlowThisFuncEnter();
1908 LogFlowThisFunc(("aSettingsFile=\"%s\", aName=\"%s\", aOsTypeId =\"%s\", aCreateFlags=\"%s\"\n",
1909 aSettingsFile.c_str(), aName.c_str(), aOsTypeId.c_str(), aFlags.c_str()));
1910
1911 StringsList llGroups;
1912 HRESULT rc = i_convertMachineGroups(aGroups, &llGroups);
1913 if (FAILED(rc))
1914 return rc;
1915
1916 Utf8Str strCreateFlags(aFlags);
1917 Guid id;
1918 bool fForceOverwrite = false;
1919 bool fDirectoryIncludesUUID = false;
1920 if (!strCreateFlags.isEmpty())
1921 {
1922 const char *pcszNext = strCreateFlags.c_str();
1923 while (*pcszNext != '\0')
1924 {
1925 Utf8Str strFlag;
1926 const char *pcszComma = RTStrStr(pcszNext, ",");
1927 if (!pcszComma)
1928 strFlag = pcszNext;
1929 else
1930 strFlag = Utf8Str(pcszNext, pcszComma - pcszNext);
1931
1932 const char *pcszEqual = RTStrStr(strFlag.c_str(), "=");
1933 /* skip over everything which doesn't contain '=' */
1934 if (pcszEqual && pcszEqual != strFlag.c_str())
1935 {
1936 Utf8Str strKey(strFlag.c_str(), pcszEqual - strFlag.c_str());
1937 Utf8Str strValue(strFlag.c_str() + (pcszEqual - strFlag.c_str() + 1));
1938
1939 if (strKey == "UUID")
1940 id = strValue.c_str();
1941 else if (strKey == "forceOverwrite")
1942 fForceOverwrite = (strValue == "1");
1943 else if (strKey == "directoryIncludesUUID")
1944 fDirectoryIncludesUUID = (strValue == "1");
1945 }
1946
1947 if (!pcszComma)
1948 pcszNext += strFlag.length();
1949 else
1950 pcszNext += strFlag.length() + 1;
1951 }
1952 }
1953 /* Create UUID if none was specified. */
1954 if (id.isZero())
1955 id.create();
1956 else if (!id.isValid())
1957 {
1958 /* do something else */
1959 return setError(E_INVALIDARG,
1960 tr("'%s' is not a valid Guid"),
1961 id.toStringCurly().c_str());
1962 }
1963
1964 /* NULL settings file means compose automatically */
1965 Utf8Str strSettingsFile(aSettingsFile);
1966 if (strSettingsFile.isEmpty())
1967 {
1968 Utf8Str strNewCreateFlags(Utf8StrFmt("UUID=%RTuuid", id.raw()));
1969 if (fDirectoryIncludesUUID)
1970 strNewCreateFlags += ",directoryIncludesUUID=1";
1971
1972 com::Utf8Str blstr;
1973 rc = composeMachineFilename(aName,
1974 llGroups.front(),
1975 strNewCreateFlags,
1976 blstr /* aBaseFolder */,
1977 strSettingsFile);
1978 if (FAILED(rc)) return rc;
1979 }
1980
1981 /* create a new object */
1982 ComObjPtr<Machine> machine;
1983 rc = machine.createObject();
1984 if (FAILED(rc)) return rc;
1985
1986 ComObjPtr<GuestOSType> osType;
1987 if (!aOsTypeId.isEmpty())
1988 i_findGuestOSType(aOsTypeId, osType);
1989
1990 /* initialize the machine object */
1991 rc = machine->init(this,
1992 strSettingsFile,
1993 aName,
1994 llGroups,
1995 aOsTypeId,
1996 osType,
1997 id,
1998 fForceOverwrite,
1999 fDirectoryIncludesUUID);
2000 if (SUCCEEDED(rc))
2001 {
2002 /* set the return value */
2003 machine.queryInterfaceTo(aMachine.asOutParam());
2004 AssertComRC(rc);
2005
2006#ifdef VBOX_WITH_EXTPACK
2007 /* call the extension pack hooks */
2008 m->ptrExtPackManager->i_callAllVmCreatedHooks(machine);
2009#endif
2010 }
2011
2012 LogFlowThisFuncLeave();
2013
2014 return rc;
2015}
2016
2017HRESULT VirtualBox::openMachine(const com::Utf8Str &aSettingsFile,
2018 ComPtr<IMachine> &aMachine)
2019{
2020 HRESULT rc = E_FAIL;
2021
2022 /* create a new object */
2023 ComObjPtr<Machine> machine;
2024 rc = machine.createObject();
2025 if (SUCCEEDED(rc))
2026 {
2027 /* initialize the machine object */
2028 rc = machine->initFromSettings(this,
2029 aSettingsFile,
2030 NULL); /* const Guid *aId */
2031 if (SUCCEEDED(rc))
2032 {
2033 /* set the return value */
2034 machine.queryInterfaceTo(aMachine.asOutParam());
2035 ComAssertComRC(rc);
2036 }
2037 }
2038
2039 return rc;
2040}
2041
2042/** @note Locks objects! */
2043HRESULT VirtualBox::registerMachine(const ComPtr<IMachine> &aMachine)
2044{
2045 HRESULT rc;
2046
2047 Bstr name;
2048 rc = aMachine->COMGETTER(Name)(name.asOutParam());
2049 if (FAILED(rc)) return rc;
2050
2051 /* We can safely cast child to Machine * here because only Machine
2052 * implementations of IMachine can be among our children. */
2053 IMachine *aM = aMachine;
2054 Machine *pMachine = static_cast<Machine*>(aM);
2055
2056 AutoCaller machCaller(pMachine);
2057 ComAssertComRCRetRC(machCaller.rc());
2058
2059 rc = i_registerMachine(pMachine);
2060 /* fire an event */
2061 if (SUCCEEDED(rc))
2062 i_onMachineRegistered(pMachine->i_getId(), TRUE);
2063
2064 return rc;
2065}
2066
2067/** @note Locks this object for reading, then some machine objects for reading. */
2068HRESULT VirtualBox::findMachine(const com::Utf8Str &aSettingsFile,
2069 ComPtr<IMachine> &aMachine)
2070{
2071 LogFlowThisFuncEnter();
2072 LogFlowThisFunc(("aSettingsFile=\"%s\", aMachine={%p}\n", aSettingsFile.c_str(), &aMachine));
2073
2074 /* start with not found */
2075 HRESULT rc = S_OK;
2076 ComObjPtr<Machine> pMachineFound;
2077
2078 Guid id(aSettingsFile);
2079 Utf8Str strFile(aSettingsFile);
2080 if (id.isValid() && !id.isZero())
2081
2082 rc = i_findMachine(id,
2083 true /* fPermitInaccessible */,
2084 true /* setError */,
2085 &pMachineFound);
2086 // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
2087 else
2088 {
2089 rc = i_findMachineByName(strFile,
2090 true /* setError */,
2091 &pMachineFound);
2092 // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
2093 }
2094
2095 /* this will set (*machine) to NULL if machineObj is null */
2096 pMachineFound.queryInterfaceTo(aMachine.asOutParam());
2097
2098 LogFlowThisFunc(("aName=\"%s\", aMachine=%p, rc=%08X\n", aSettingsFile.c_str(), &aMachine, rc));
2099 LogFlowThisFuncLeave();
2100
2101 return rc;
2102}
2103
2104HRESULT VirtualBox::getMachinesByGroups(const std::vector<com::Utf8Str> &aGroups,
2105 std::vector<ComPtr<IMachine> > &aMachines)
2106{
2107 StringsList llGroups;
2108 HRESULT rc = i_convertMachineGroups(aGroups, &llGroups);
2109 if (FAILED(rc))
2110 return rc;
2111
2112 /* we want to rely on sorted groups during compare, to save time */
2113 llGroups.sort();
2114
2115 /* get copy of all machine references, to avoid holding the list lock */
2116 MachinesOList::MyList allMachines;
2117 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2118 allMachines = m->allMachines.getList();
2119
2120 std::vector<ComObjPtr<IMachine> > saMachines;
2121 saMachines.resize(0);
2122 for (MachinesOList::MyList::const_iterator it = allMachines.begin();
2123 it != allMachines.end();
2124 ++it)
2125 {
2126 const ComObjPtr<Machine> &pMachine = *it;
2127 AutoCaller autoMachineCaller(pMachine);
2128 if (FAILED(autoMachineCaller.rc()))
2129 continue;
2130 AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
2131
2132 if (pMachine->i_isAccessible())
2133 {
2134 const StringsList &thisGroups = pMachine->i_getGroups();
2135 for (StringsList::const_iterator it2 = thisGroups.begin();
2136 it2 != thisGroups.end();
2137 ++it2)
2138 {
2139 const Utf8Str &group = *it2;
2140 bool fAppended = false;
2141 for (StringsList::const_iterator it3 = llGroups.begin();
2142 it3 != llGroups.end();
2143 ++it3)
2144 {
2145 int order = it3->compare(group);
2146 if (order == 0)
2147 {
2148 saMachines.push_back(static_cast<IMachine *>(pMachine));
2149 fAppended = true;
2150 break;
2151 }
2152 else if (order > 0)
2153 break;
2154 else
2155 continue;
2156 }
2157 /* avoid duplicates and save time */
2158 if (fAppended)
2159 break;
2160 }
2161 }
2162 }
2163 aMachines.resize(saMachines.size());
2164 size_t i = 0;
2165 for(i = 0; i < saMachines.size(); ++i)
2166 saMachines[i].queryInterfaceTo(aMachines[i].asOutParam());
2167
2168 return S_OK;
2169}
2170
2171HRESULT VirtualBox::getMachineStates(const std::vector<ComPtr<IMachine> > &aMachines,
2172 std::vector<MachineState_T> &aStates)
2173{
2174 com::SafeIfaceArray<IMachine> saMachines(aMachines);
2175 aStates.resize(aMachines.size());
2176 for (size_t i = 0; i < saMachines.size(); i++)
2177 {
2178 ComPtr<IMachine> pMachine = saMachines[i];
2179 MachineState_T state = MachineState_Null;
2180 if (!pMachine.isNull())
2181 {
2182 HRESULT rc = pMachine->COMGETTER(State)(&state);
2183 if (rc == E_ACCESSDENIED)
2184 rc = S_OK;
2185 AssertComRC(rc);
2186 }
2187 aStates[i] = state;
2188 }
2189 return S_OK;
2190}
2191
2192HRESULT VirtualBox::createUnattendedInstaller(ComPtr<IUnattended> &aUnattended)
2193{
2194#ifdef VBOX_WITH_UNATTENDED
2195 ComObjPtr<Unattended> ptrUnattended;
2196 HRESULT hrc = ptrUnattended.createObject();
2197 if (SUCCEEDED(hrc))
2198 {
2199 AutoReadLock wlock(this COMMA_LOCKVAL_SRC_POS);
2200 hrc = ptrUnattended->initUnattended(this);
2201 if (SUCCEEDED(hrc))
2202 hrc = ptrUnattended.queryInterfaceTo(aUnattended.asOutParam());
2203 }
2204 return hrc;
2205#else
2206 NOREF(aUnattended);
2207 return E_NOTIMPL;
2208#endif
2209}
2210
2211HRESULT VirtualBox::createMedium(const com::Utf8Str &aFormat,
2212 const com::Utf8Str &aLocation,
2213 AccessMode_T aAccessMode,
2214 DeviceType_T aDeviceType,
2215 ComPtr<IMedium> &aMedium)
2216{
2217 NOREF(aAccessMode); /**< @todo r=klaus make use of access mode */
2218
2219 HRESULT rc = S_OK;
2220
2221 ComObjPtr<Medium> medium;
2222 medium.createObject();
2223 com::Utf8Str format = aFormat;
2224
2225 switch (aDeviceType)
2226 {
2227 case DeviceType_HardDisk:
2228 {
2229
2230 /* we don't access non-const data members so no need to lock */
2231 if (format.isEmpty())
2232 i_getDefaultHardDiskFormat(format);
2233
2234 rc = medium->init(this,
2235 format,
2236 aLocation,
2237 Guid::Empty /* media registry: none yet */,
2238 aDeviceType);
2239 }
2240 break;
2241
2242 case DeviceType_DVD:
2243 case DeviceType_Floppy:
2244 {
2245
2246 if (format.isEmpty())
2247 return setError(E_INVALIDARG, "Format must be Valid Type%s", format.c_str());
2248
2249 // enforce read-only for DVDs even if caller specified ReadWrite
2250 if (aDeviceType == DeviceType_DVD)
2251 aAccessMode = AccessMode_ReadOnly;
2252
2253 rc = medium->init(this,
2254 format,
2255 aLocation,
2256 Guid::Empty /* media registry: none yet */,
2257 aDeviceType);
2258
2259 }
2260 break;
2261
2262 default:
2263 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy %d", aDeviceType);
2264 }
2265
2266 if (SUCCEEDED(rc))
2267 {
2268 medium.queryInterfaceTo(aMedium.asOutParam());
2269 com::Guid uMediumId = medium->i_getId();
2270 if (uMediumId.isValid() && !uMediumId.isZero())
2271 i_onMediumRegistered(uMediumId, medium->i_getDeviceType(), TRUE);
2272 }
2273
2274 return rc;
2275}
2276
2277HRESULT VirtualBox::openMedium(const com::Utf8Str &aLocation,
2278 DeviceType_T aDeviceType,
2279 AccessMode_T aAccessMode,
2280 BOOL aForceNewUuid,
2281 ComPtr<IMedium> &aMedium)
2282{
2283 HRESULT rc = S_OK;
2284 Guid id(aLocation);
2285 ComObjPtr<Medium> pMedium;
2286
2287 // have to get write lock as the whole find/update sequence must be done
2288 // in one critical section, otherwise there are races which can lead to
2289 // multiple Medium objects with the same content
2290 AutoWriteLock treeLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2291
2292 // check if the device type is correct, and see if a medium for the
2293 // given path has already initialized; if so, return that
2294 switch (aDeviceType)
2295 {
2296 case DeviceType_HardDisk:
2297 if (id.isValid() && !id.isZero())
2298 rc = i_findHardDiskById(id, false /* setError */, &pMedium);
2299 else
2300 rc = i_findHardDiskByLocation(aLocation,
2301 false, /* aSetError */
2302 &pMedium);
2303 break;
2304
2305 case DeviceType_Floppy:
2306 case DeviceType_DVD:
2307 if (id.isValid() && !id.isZero())
2308 rc = i_findDVDOrFloppyImage(aDeviceType, &id, Utf8Str::Empty,
2309 false /* setError */, &pMedium);
2310 else
2311 rc = i_findDVDOrFloppyImage(aDeviceType, NULL, aLocation,
2312 false /* setError */, &pMedium);
2313
2314 // enforce read-only for DVDs even if caller specified ReadWrite
2315 if (aDeviceType == DeviceType_DVD)
2316 aAccessMode = AccessMode_ReadOnly;
2317 break;
2318
2319 default:
2320 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy %d", aDeviceType);
2321 }
2322
2323 bool fMediumRegistered = false;
2324 if (pMedium.isNull())
2325 {
2326 pMedium.createObject();
2327 treeLock.release();
2328 rc = pMedium->init(this,
2329 aLocation,
2330 (aAccessMode == AccessMode_ReadWrite) ? Medium::OpenReadWrite : Medium::OpenReadOnly,
2331 !!aForceNewUuid,
2332 aDeviceType);
2333 treeLock.acquire();
2334
2335 if (SUCCEEDED(rc))
2336 {
2337 rc = i_registerMedium(pMedium, &pMedium, treeLock);
2338
2339 treeLock.release();
2340
2341 /* Note that it's important to call uninit() on failure to register
2342 * because the differencing hard disk would have been already associated
2343 * with the parent and this association needs to be broken. */
2344
2345 if (FAILED(rc))
2346 {
2347 pMedium->uninit();
2348 rc = VBOX_E_OBJECT_NOT_FOUND;
2349 }
2350 else
2351 {
2352 fMediumRegistered = true;
2353 }
2354 }
2355 else
2356 {
2357 if (rc != VBOX_E_INVALID_OBJECT_STATE)
2358 rc = VBOX_E_OBJECT_NOT_FOUND;
2359 }
2360 }
2361
2362 if (SUCCEEDED(rc))
2363 {
2364 pMedium.queryInterfaceTo(aMedium.asOutParam());
2365 if (fMediumRegistered)
2366 i_onMediumRegistered(pMedium->i_getId(), pMedium->i_getDeviceType() ,TRUE);
2367 }
2368
2369 return rc;
2370}
2371
2372
2373/** @note Locks this object for reading. */
2374HRESULT VirtualBox::getGuestOSType(const com::Utf8Str &aId,
2375 ComPtr<IGuestOSType> &aType)
2376{
2377 ComObjPtr<GuestOSType> pType;
2378 HRESULT rc = i_findGuestOSType(aId, pType);
2379 pType.queryInterfaceTo(aType.asOutParam());
2380 return rc;
2381}
2382
2383HRESULT VirtualBox::createSharedFolder(const com::Utf8Str &aName,
2384 const com::Utf8Str &aHostPath,
2385 BOOL aWritable,
2386 BOOL aAutomount,
2387 const com::Utf8Str &aAutoMountPoint)
2388{
2389 NOREF(aName);
2390 NOREF(aHostPath);
2391 NOREF(aWritable);
2392 NOREF(aAutomount);
2393 NOREF(aAutoMountPoint);
2394
2395 return setError(E_NOTIMPL, "Not yet implemented");
2396}
2397
2398HRESULT VirtualBox::removeSharedFolder(const com::Utf8Str &aName)
2399{
2400 NOREF(aName);
2401 return setError(E_NOTIMPL, "Not yet implemented");
2402}
2403
2404/**
2405 * @note Locks this object for reading.
2406 */
2407HRESULT VirtualBox::getExtraDataKeys(std::vector<com::Utf8Str> &aKeys)
2408{
2409 using namespace settings;
2410
2411 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2412
2413 aKeys.resize(m->pMainConfigFile->mapExtraDataItems.size());
2414 size_t i = 0;
2415 for (StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.begin();
2416 it != m->pMainConfigFile->mapExtraDataItems.end(); ++it, ++i)
2417 aKeys[i] = it->first;
2418
2419 return S_OK;
2420}
2421
2422/**
2423 * @note Locks this object for reading.
2424 */
2425HRESULT VirtualBox::getExtraData(const com::Utf8Str &aKey,
2426 com::Utf8Str &aValue)
2427{
2428 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(aKey);
2429 if (it != m->pMainConfigFile->mapExtraDataItems.end())
2430 // found:
2431 aValue = it->second; // source is a Utf8Str
2432
2433 /* return the result to caller (may be empty) */
2434
2435 return S_OK;
2436}
2437
2438/**
2439 * @note Locks this object for writing.
2440 */
2441HRESULT VirtualBox::setExtraData(const com::Utf8Str &aKey,
2442 const com::Utf8Str &aValue)
2443{
2444 Utf8Str strKey(aKey);
2445 Utf8Str strValue(aValue);
2446 Utf8Str strOldValue; // empty
2447 HRESULT rc = S_OK;
2448
2449 /* Because control characters in aKey have caused problems in the settings
2450 * they are rejected unless the key should be deleted. */
2451 if (!strValue.isEmpty())
2452 {
2453 for (size_t i = 0; i < strKey.length(); ++i)
2454 {
2455 char ch = strKey[i];
2456 if (RTLocCIsCntrl(ch))
2457 return E_INVALIDARG;
2458 }
2459 }
2460
2461 // locking note: we only hold the read lock briefly to look up the old value,
2462 // then release it and call the onExtraCanChange callbacks. There is a small
2463 // chance of a race insofar as the callback might be called twice if two callers
2464 // change the same key at the same time, but that's a much better solution
2465 // than the deadlock we had here before. The actual changing of the extradata
2466 // is then performed under the write lock and race-free.
2467
2468 // look up the old value first; if nothing has changed then we need not do anything
2469 {
2470 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
2471 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
2472 if (it != m->pMainConfigFile->mapExtraDataItems.end())
2473 strOldValue = it->second;
2474 }
2475
2476 bool fChanged;
2477 if ((fChanged = (strOldValue != strValue)))
2478 {
2479 // ask for permission from all listeners outside the locks;
2480 // onExtraDataCanChange() only briefly requests the VirtualBox
2481 // lock to copy the list of callbacks to invoke
2482 Bstr error;
2483
2484 if (!i_onExtraDataCanChange(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw(), error))
2485 {
2486 const char *sep = error.isEmpty() ? "" : ": ";
2487 Log1WarningFunc(("Someone vetoed! Change refused%s%ls\n", sep, error.raw()));
2488 return setError(E_ACCESSDENIED,
2489 tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
2490 strKey.c_str(),
2491 strValue.c_str(),
2492 sep,
2493 error.raw());
2494 }
2495
2496 // data is changing and change not vetoed: then write it out under the lock
2497
2498 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2499
2500 if (strValue.isEmpty())
2501 m->pMainConfigFile->mapExtraDataItems.erase(strKey);
2502 else
2503 m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
2504 // creates a new key if needed
2505
2506 /* save settings on success */
2507 rc = i_saveSettings();
2508 if (FAILED(rc)) return rc;
2509 }
2510
2511 // fire notification outside the lock
2512 if (fChanged)
2513 i_onExtraDataChange(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw());
2514
2515 return rc;
2516}
2517
2518/**
2519 *
2520 */
2521HRESULT VirtualBox::setSettingsSecret(const com::Utf8Str &aPassword)
2522{
2523 i_storeSettingsKey(aPassword);
2524 i_decryptSettings();
2525 return S_OK;
2526}
2527
2528int VirtualBox::i_decryptMediumSettings(Medium *pMedium)
2529{
2530 Bstr bstrCipher;
2531 HRESULT hrc = pMedium->GetProperty(Bstr("InitiatorSecretEncrypted").raw(),
2532 bstrCipher.asOutParam());
2533 if (SUCCEEDED(hrc))
2534 {
2535 Utf8Str strPlaintext;
2536 int rc = i_decryptSetting(&strPlaintext, bstrCipher);
2537 if (RT_SUCCESS(rc))
2538 pMedium->i_setPropertyDirect("InitiatorSecret", strPlaintext);
2539 else
2540 return rc;
2541 }
2542 return VINF_SUCCESS;
2543}
2544
2545/**
2546 * Decrypt all encrypted settings.
2547 *
2548 * So far we only have encrypted iSCSI initiator secrets so we just go through
2549 * all hard disk mediums and determine the plain 'InitiatorSecret' from
2550 * 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
2551 * properties need to be null-terminated strings.
2552 */
2553int VirtualBox::i_decryptSettings()
2554{
2555 bool fFailure = false;
2556 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2557 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2558 mt != m->allHardDisks.end();
2559 ++mt)
2560 {
2561 ComObjPtr<Medium> pMedium = *mt;
2562 AutoCaller medCaller(pMedium);
2563 if (FAILED(medCaller.rc()))
2564 continue;
2565 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2566 int vrc = i_decryptMediumSettings(pMedium);
2567 if (RT_FAILURE(vrc))
2568 fFailure = true;
2569 }
2570 if (!fFailure)
2571 {
2572 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2573 mt != m->allHardDisks.end();
2574 ++mt)
2575 {
2576 i_onMediumConfigChanged(*mt);
2577 }
2578 }
2579 return fFailure ? VERR_INVALID_PARAMETER : VINF_SUCCESS;
2580}
2581
2582/**
2583 * Encode.
2584 *
2585 * @param aPlaintext plaintext to be encrypted
2586 * @param aCiphertext resulting ciphertext (base64-encoded)
2587 */
2588int VirtualBox::i_encryptSetting(const Utf8Str &aPlaintext, Utf8Str *aCiphertext)
2589{
2590 uint8_t abCiphertext[32];
2591 char szCipherBase64[128];
2592 size_t cchCipherBase64;
2593 int rc = i_encryptSettingBytes((uint8_t*)aPlaintext.c_str(), abCiphertext,
2594 aPlaintext.length()+1, sizeof(abCiphertext));
2595 if (RT_SUCCESS(rc))
2596 {
2597 rc = RTBase64Encode(abCiphertext, sizeof(abCiphertext),
2598 szCipherBase64, sizeof(szCipherBase64),
2599 &cchCipherBase64);
2600 if (RT_SUCCESS(rc))
2601 *aCiphertext = szCipherBase64;
2602 }
2603 return rc;
2604}
2605
2606/**
2607 * Decode.
2608 *
2609 * @param aPlaintext resulting plaintext
2610 * @param aCiphertext ciphertext (base64-encoded) to decrypt
2611 */
2612int VirtualBox::i_decryptSetting(Utf8Str *aPlaintext, const Utf8Str &aCiphertext)
2613{
2614 uint8_t abPlaintext[64];
2615 uint8_t abCiphertext[64];
2616 size_t cbCiphertext;
2617 int rc = RTBase64Decode(aCiphertext.c_str(),
2618 abCiphertext, sizeof(abCiphertext),
2619 &cbCiphertext, NULL);
2620 if (RT_SUCCESS(rc))
2621 {
2622 rc = i_decryptSettingBytes(abPlaintext, abCiphertext, cbCiphertext);
2623 if (RT_SUCCESS(rc))
2624 {
2625 for (unsigned i = 0; i < cbCiphertext; i++)
2626 {
2627 /* sanity check: null-terminated string? */
2628 if (abPlaintext[i] == '\0')
2629 {
2630 /* sanity check: valid UTF8 string? */
2631 if (RTStrIsValidEncoding((const char*)abPlaintext))
2632 {
2633 *aPlaintext = Utf8Str((const char*)abPlaintext);
2634 return VINF_SUCCESS;
2635 }
2636 }
2637 }
2638 rc = VERR_INVALID_MAGIC;
2639 }
2640 }
2641 return rc;
2642}
2643
2644/**
2645 * Encrypt secret bytes. Use the m->SettingsCipherKey as key.
2646 *
2647 * @param aPlaintext clear text to be encrypted
2648 * @param aCiphertext resulting encrypted text
2649 * @param aPlaintextSize size of the plaintext
2650 * @param aCiphertextSize size of the ciphertext
2651 */
2652int VirtualBox::i_encryptSettingBytes(const uint8_t *aPlaintext, uint8_t *aCiphertext,
2653 size_t aPlaintextSize, size_t aCiphertextSize) const
2654{
2655 unsigned i, j;
2656 uint8_t aBytes[64];
2657
2658 if (!m->fSettingsCipherKeySet)
2659 return VERR_INVALID_STATE;
2660
2661 if (aCiphertextSize > sizeof(aBytes))
2662 return VERR_BUFFER_OVERFLOW;
2663
2664 if (aCiphertextSize < 32)
2665 return VERR_INVALID_PARAMETER;
2666
2667 AssertCompile(sizeof(m->SettingsCipherKey) >= 32);
2668
2669 /* store the first 8 bytes of the cipherkey for verification */
2670 for (i = 0, j = 0; i < 8; i++, j++)
2671 aCiphertext[i] = m->SettingsCipherKey[j];
2672
2673 for (unsigned k = 0; k < aPlaintextSize && i < aCiphertextSize; i++, k++)
2674 {
2675 aCiphertext[i] = (aPlaintext[k] ^ m->SettingsCipherKey[j]);
2676 if (++j >= sizeof(m->SettingsCipherKey))
2677 j = 0;
2678 }
2679
2680 /* fill with random data to have a minimal length (salt) */
2681 if (i < aCiphertextSize)
2682 {
2683 RTRandBytes(aBytes, aCiphertextSize - i);
2684 for (int k = 0; i < aCiphertextSize; i++, k++)
2685 {
2686 aCiphertext[i] = aBytes[k] ^ m->SettingsCipherKey[j];
2687 if (++j >= sizeof(m->SettingsCipherKey))
2688 j = 0;
2689 }
2690 }
2691
2692 return VINF_SUCCESS;
2693}
2694
2695/**
2696 * Decrypt secret bytes. Use the m->SettingsCipherKey as key.
2697 *
2698 * @param aPlaintext resulting plaintext
2699 * @param aCiphertext ciphertext to be decrypted
2700 * @param aCiphertextSize size of the ciphertext == size of the plaintext
2701 */
2702int VirtualBox::i_decryptSettingBytes(uint8_t *aPlaintext,
2703 const uint8_t *aCiphertext, size_t aCiphertextSize) const
2704{
2705 unsigned i, j;
2706
2707 if (!m->fSettingsCipherKeySet)
2708 return VERR_INVALID_STATE;
2709
2710 if (aCiphertextSize < 32)
2711 return VERR_INVALID_PARAMETER;
2712
2713 /* key verification */
2714 for (i = 0, j = 0; i < 8; i++, j++)
2715 if (aCiphertext[i] != m->SettingsCipherKey[j])
2716 return VERR_INVALID_MAGIC;
2717
2718 /* poison */
2719 memset(aPlaintext, 0xff, aCiphertextSize);
2720 for (int k = 0; i < aCiphertextSize; i++, k++)
2721 {
2722 aPlaintext[k] = aCiphertext[i] ^ m->SettingsCipherKey[j];
2723 if (++j >= sizeof(m->SettingsCipherKey))
2724 j = 0;
2725 }
2726
2727 return VINF_SUCCESS;
2728}
2729
2730/**
2731 * Store a settings key.
2732 *
2733 * @param aKey the key to store
2734 */
2735void VirtualBox::i_storeSettingsKey(const Utf8Str &aKey)
2736{
2737 RTSha512(aKey.c_str(), aKey.length(), m->SettingsCipherKey);
2738 m->fSettingsCipherKeySet = true;
2739}
2740
2741// public methods only for internal purposes
2742/////////////////////////////////////////////////////////////////////////////
2743
2744#ifdef DEBUG
2745void VirtualBox::i_dumpAllBackRefs()
2746{
2747 {
2748 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2749 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2750 mt != m->allHardDisks.end();
2751 ++mt)
2752 {
2753 ComObjPtr<Medium> pMedium = *mt;
2754 pMedium->i_dumpBackRefs();
2755 }
2756 }
2757 {
2758 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2759 for (MediaList::const_iterator mt = m->allDVDImages.begin();
2760 mt != m->allDVDImages.end();
2761 ++mt)
2762 {
2763 ComObjPtr<Medium> pMedium = *mt;
2764 pMedium->i_dumpBackRefs();
2765 }
2766 }
2767}
2768#endif
2769
2770/**
2771 * Posts an event to the event queue that is processed asynchronously
2772 * on a dedicated thread.
2773 *
2774 * Posting events to the dedicated event queue is useful to perform secondary
2775 * actions outside any object locks -- for example, to iterate over a list
2776 * of callbacks and inform them about some change caused by some object's
2777 * method call.
2778 *
2779 * @param event event to post; must have been allocated using |new|, will
2780 * be deleted automatically by the event thread after processing
2781 *
2782 * @note Doesn't lock any object.
2783 */
2784HRESULT VirtualBox::i_postEvent(Event *event)
2785{
2786 AssertReturn(event, E_FAIL);
2787
2788 HRESULT rc;
2789 AutoCaller autoCaller(this);
2790 if (SUCCEEDED((rc = autoCaller.rc())))
2791 {
2792 if (getObjectState().getState() != ObjectState::Ready)
2793 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
2794 getObjectState().getState()));
2795 // return S_OK
2796 else if ( (m->pAsyncEventQ)
2797 && (m->pAsyncEventQ->postEvent(event))
2798 )
2799 return S_OK;
2800 else
2801 rc = E_FAIL;
2802 }
2803
2804 // in any event of failure, we must clean up here, or we'll leak;
2805 // the caller has allocated the object using new()
2806 delete event;
2807 return rc;
2808}
2809
2810/**
2811 * Adds a progress to the global collection of pending operations.
2812 * Usually gets called upon progress object initialization.
2813 *
2814 * @param aProgress Operation to add to the collection.
2815 *
2816 * @note Doesn't lock objects.
2817 */
2818HRESULT VirtualBox::i_addProgress(IProgress *aProgress)
2819{
2820 CheckComArgNotNull(aProgress);
2821
2822 AutoCaller autoCaller(this);
2823 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2824
2825 Bstr id;
2826 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
2827 AssertComRCReturnRC(rc);
2828
2829 /* protect mProgressOperations */
2830 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2831
2832 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
2833 return S_OK;
2834}
2835
2836/**
2837 * Removes the progress from the global collection of pending operations.
2838 * Usually gets called upon progress completion.
2839 *
2840 * @param aId UUID of the progress operation to remove
2841 *
2842 * @note Doesn't lock objects.
2843 */
2844HRESULT VirtualBox::i_removeProgress(IN_GUID aId)
2845{
2846 AutoCaller autoCaller(this);
2847 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2848
2849 ComPtr<IProgress> progress;
2850
2851 /* protect mProgressOperations */
2852 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2853
2854 size_t cnt = m->mapProgressOperations.erase(aId);
2855 Assert(cnt == 1);
2856 NOREF(cnt);
2857
2858 return S_OK;
2859}
2860
2861#ifdef RT_OS_WINDOWS
2862
2863class StartSVCHelperClientData : public ThreadTask
2864{
2865public:
2866 StartSVCHelperClientData()
2867 {
2868 LogFlowFuncEnter();
2869 m_strTaskName = "SVCHelper";
2870 threadVoidData = NULL;
2871 initialized = false;
2872 }
2873
2874 virtual ~StartSVCHelperClientData()
2875 {
2876 LogFlowFuncEnter();
2877 if (threadVoidData!=NULL)
2878 {
2879 delete threadVoidData;
2880 threadVoidData=NULL;
2881 }
2882 };
2883
2884 void handler()
2885 {
2886 VirtualBox::i_SVCHelperClientThreadTask(this);
2887 }
2888
2889 const ComPtr<Progress>& GetProgressObject() const {return progress;}
2890
2891 bool init(VirtualBox* aVbox,
2892 Progress* aProgress,
2893 bool aPrivileged,
2894 VirtualBox::SVCHelperClientFunc aFunc,
2895 void *aUser)
2896 {
2897 LogFlowFuncEnter();
2898 that = aVbox;
2899 progress = aProgress;
2900 privileged = aPrivileged;
2901 func = aFunc;
2902 user = aUser;
2903
2904 initThreadVoidData();
2905
2906 initialized = true;
2907
2908 return initialized;
2909 }
2910
2911 bool isOk() const{ return initialized;}
2912
2913 bool initialized;
2914 ComObjPtr<VirtualBox> that;
2915 ComObjPtr<Progress> progress;
2916 bool privileged;
2917 VirtualBox::SVCHelperClientFunc func;
2918 void *user;
2919 ThreadVoidData *threadVoidData;
2920
2921private:
2922 bool initThreadVoidData()
2923 {
2924 LogFlowFuncEnter();
2925 threadVoidData = static_cast<ThreadVoidData*>(user);
2926 return true;
2927 }
2928};
2929
2930/**
2931 * Helper method that starts a worker thread that:
2932 * - creates a pipe communication channel using SVCHlpClient;
2933 * - starts an SVC Helper process that will inherit this channel;
2934 * - executes the supplied function by passing it the created SVCHlpClient
2935 * and opened instance to communicate to the Helper process and the given
2936 * Progress object.
2937 *
2938 * The user function is supposed to communicate to the helper process
2939 * using the \a aClient argument to do the requested job and optionally expose
2940 * the progress through the \a aProgress object. The user function should never
2941 * call notifyComplete() on it: this will be done automatically using the
2942 * result code returned by the function.
2943 *
2944 * Before the user function is started, the communication channel passed to
2945 * the \a aClient argument is fully set up, the function should start using
2946 * its write() and read() methods directly.
2947 *
2948 * The \a aVrc parameter of the user function may be used to return an error
2949 * code if it is related to communication errors (for example, returned by
2950 * the SVCHlpClient members when they fail). In this case, the correct error
2951 * message using this value will be reported to the caller. Note that the
2952 * value of \a aVrc is inspected only if the user function itself returns
2953 * success.
2954 *
2955 * If a failure happens anywhere before the user function would be normally
2956 * called, it will be called anyway in special "cleanup only" mode indicated
2957 * by \a aClient, \a aProgress and \a aVrc arguments set to NULL. In this mode,
2958 * all the function is supposed to do is to cleanup its aUser argument if
2959 * necessary (it's assumed that the ownership of this argument is passed to
2960 * the user function once #startSVCHelperClient() returns a success, thus
2961 * making it responsible for the cleanup).
2962 *
2963 * After the user function returns, the thread will send the SVCHlpMsg::Null
2964 * message to indicate a process termination.
2965 *
2966 * @param aPrivileged |true| to start the SVC Helper process as a privileged
2967 * user that can perform administrative tasks
2968 * @param aFunc user function to run
2969 * @param aUser argument to the user function
2970 * @param aProgress progress object that will track operation completion
2971 *
2972 * @note aPrivileged is currently ignored (due to some unsolved problems in
2973 * Vista) and the process will be started as a normal (unprivileged)
2974 * process.
2975 *
2976 * @note Doesn't lock anything.
2977 */
2978HRESULT VirtualBox::i_startSVCHelperClient(bool aPrivileged,
2979 SVCHelperClientFunc aFunc,
2980 void *aUser, Progress *aProgress)
2981{
2982 LogFlowFuncEnter();
2983 AssertReturn(aFunc, E_POINTER);
2984 AssertReturn(aProgress, E_POINTER);
2985
2986 AutoCaller autoCaller(this);
2987 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2988
2989 /* create the i_SVCHelperClientThreadTask() argument */
2990
2991 HRESULT hr = S_OK;
2992 StartSVCHelperClientData *pTask = NULL;
2993 try
2994 {
2995 pTask = new StartSVCHelperClientData();
2996
2997 pTask->init(this, aProgress, aPrivileged, aFunc, aUser);
2998
2999 if (!pTask->isOk())
3000 {
3001 delete pTask;
3002 LogRel(("Could not init StartSVCHelperClientData object \n"));
3003 throw E_FAIL;
3004 }
3005
3006 //this function delete pTask in case of exceptions, so there is no need in the call of delete operator
3007 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_WORKER);
3008
3009 }
3010 catch(std::bad_alloc &)
3011 {
3012 hr = setError(E_OUTOFMEMORY);
3013 }
3014 catch(...)
3015 {
3016 LogRel(("Could not create thread for StartSVCHelperClientData \n"));
3017 hr = E_FAIL;
3018 }
3019
3020 return hr;
3021}
3022
3023/**
3024 * Worker thread for startSVCHelperClient().
3025 */
3026/* static */
3027void VirtualBox::i_SVCHelperClientThreadTask(StartSVCHelperClientData *pTask)
3028{
3029 LogFlowFuncEnter();
3030 HRESULT rc = S_OK;
3031 bool userFuncCalled = false;
3032
3033 do
3034 {
3035 AssertBreakStmt(pTask, rc = E_POINTER);
3036 AssertReturnVoid(!pTask->progress.isNull());
3037
3038 /* protect VirtualBox from uninitialization */
3039 AutoCaller autoCaller(pTask->that);
3040 if (!autoCaller.isOk())
3041 {
3042 /* it's too late */
3043 rc = autoCaller.rc();
3044 break;
3045 }
3046
3047 int vrc = VINF_SUCCESS;
3048
3049 Guid id;
3050 id.create();
3051 SVCHlpClient client;
3052 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
3053 id.raw()).c_str());
3054 if (RT_FAILURE(vrc))
3055 {
3056 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not create the communication channel (%Rrc)"), vrc);
3057 break;
3058 }
3059
3060 /* get the path to the executable */
3061 char exePathBuf[RTPATH_MAX];
3062 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
3063 if (!exePath)
3064 {
3065 rc = pTask->that->setError(E_FAIL, tr("Cannot get executable name"));
3066 break;
3067 }
3068
3069 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
3070
3071 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
3072
3073 RTPROCESS pid = NIL_RTPROCESS;
3074
3075 if (pTask->privileged)
3076 {
3077 /* Attempt to start a privileged process using the Run As dialog */
3078
3079 Bstr file = exePath;
3080 Bstr parameters = argsStr;
3081
3082 SHELLEXECUTEINFO shExecInfo;
3083
3084 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
3085
3086 shExecInfo.fMask = NULL;
3087 shExecInfo.hwnd = NULL;
3088 shExecInfo.lpVerb = L"runas";
3089 shExecInfo.lpFile = file.raw();
3090 shExecInfo.lpParameters = parameters.raw();
3091 shExecInfo.lpDirectory = NULL;
3092 shExecInfo.nShow = SW_NORMAL;
3093 shExecInfo.hInstApp = NULL;
3094
3095 if (!ShellExecuteEx(&shExecInfo))
3096 {
3097 int vrc2 = RTErrConvertFromWin32(GetLastError());
3098 /* hide excessive details in case of a frequent error
3099 * (pressing the Cancel button to close the Run As dialog) */
3100 if (vrc2 == VERR_CANCELLED)
3101 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Operation canceled by the user"));
3102 else
3103 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a privileged process '%s' (%Rrc)"), exePath, vrc2);
3104 break;
3105 }
3106 }
3107 else
3108 {
3109 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
3110 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
3111 if (RT_FAILURE(vrc))
3112 {
3113 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
3114 break;
3115 }
3116 }
3117
3118 /* wait for the client to connect */
3119 vrc = client.connect();
3120 if (RT_SUCCESS(vrc))
3121 {
3122 /* start the user supplied function */
3123 rc = pTask->func(&client, pTask->progress, pTask->user, &vrc);
3124 userFuncCalled = true;
3125 }
3126
3127 /* send the termination signal to the process anyway */
3128 {
3129 int vrc2 = client.write(SVCHlpMsg::Null);
3130 if (RT_SUCCESS(vrc))
3131 vrc = vrc2;
3132 }
3133
3134 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
3135 {
3136 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not operate the communication channel (%Rrc)"), vrc);
3137 break;
3138 }
3139 }
3140 while (0);
3141
3142 if (FAILED(rc) && !userFuncCalled)
3143 {
3144 /* call the user function in the "cleanup only" mode
3145 * to let it free resources passed to in aUser */
3146 pTask->func(NULL, NULL, pTask->user, NULL);
3147 }
3148
3149 pTask->progress->i_notifyComplete(rc);
3150
3151 LogFlowFuncLeave();
3152}
3153
3154#endif /* RT_OS_WINDOWS */
3155
3156/**
3157 * Sends a signal to the client watcher to rescan the set of machines
3158 * that have open sessions.
3159 *
3160 * @note Doesn't lock anything.
3161 */
3162void VirtualBox::i_updateClientWatcher()
3163{
3164 AutoCaller autoCaller(this);
3165 AssertComRCReturnVoid(autoCaller.rc());
3166
3167 AssertPtrReturnVoid(m->pClientWatcher);
3168 m->pClientWatcher->update();
3169}
3170
3171/**
3172 * Adds the given child process ID to the list of processes to be reaped.
3173 * This call should be followed by #i_updateClientWatcher() to take the effect.
3174 *
3175 * @note Doesn't lock anything.
3176 */
3177void VirtualBox::i_addProcessToReap(RTPROCESS pid)
3178{
3179 AutoCaller autoCaller(this);
3180 AssertComRCReturnVoid(autoCaller.rc());
3181
3182 AssertPtrReturnVoid(m->pClientWatcher);
3183 m->pClientWatcher->addProcess(pid);
3184}
3185
3186/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
3187struct MachineEvent : public VirtualBox::CallbackEvent
3188{
3189 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
3190 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
3191 , mBool(aBool)
3192 { }
3193
3194 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
3195 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
3196 , mState(aState)
3197 {}
3198
3199 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3200 {
3201 switch (mWhat)
3202 {
3203 case VBoxEventType_OnMachineDataChanged:
3204 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
3205 break;
3206
3207 case VBoxEventType_OnMachineStateChanged:
3208 aEvDesc.init(aSource, mWhat, id.raw(), mState);
3209 break;
3210
3211 case VBoxEventType_OnMachineRegistered:
3212 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
3213 break;
3214
3215 default:
3216 AssertFailedReturn(S_OK);
3217 }
3218 return S_OK;
3219 }
3220
3221 Bstr id;
3222 MachineState_T mState;
3223 BOOL mBool;
3224};
3225
3226
3227/**
3228 * VD plugin load
3229 */
3230int VirtualBox::i_loadVDPlugin(const char *pszPluginLibrary)
3231{
3232 return m->pSystemProperties->i_loadVDPlugin(pszPluginLibrary);
3233}
3234
3235/**
3236 * VD plugin unload
3237 */
3238int VirtualBox::i_unloadVDPlugin(const char *pszPluginLibrary)
3239{
3240 return m->pSystemProperties->i_unloadVDPlugin(pszPluginLibrary);
3241}
3242
3243
3244/** Event for onMediumRegistered() */
3245struct MediumRegisteredEventStruct : public VirtualBox::CallbackEvent
3246{
3247 MediumRegisteredEventStruct(VirtualBox *aVB, const Guid &aMediumId,
3248 const DeviceType_T aDevType, const BOOL aRegistered)
3249 : CallbackEvent(aVB, VBoxEventType_OnMediumRegistered)
3250 , mMediumId(aMediumId.toUtf16()), mDevType(aDevType), mRegistered(aRegistered)
3251 {}
3252
3253 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
3254 {
3255 return aEvDesc.init(aSource, VBoxEventType_OnMediumRegistered, mMediumId.raw(), mDevType, mRegistered);
3256 }
3257
3258 Bstr mMediumId;
3259 DeviceType_T mDevType;
3260 BOOL mRegistered;
3261};
3262
3263/**
3264 * @note Doesn't lock any object.
3265 */
3266void VirtualBox::i_onMediumRegistered(const Guid &aMediumId, const DeviceType_T aDevType, const BOOL aRegistered)
3267{
3268 i_postEvent(new MediumRegisteredEventStruct(this, aMediumId, aDevType, aRegistered));
3269}
3270
3271/** Event for onMediumConfigChanged() */
3272struct MediumConfigChangedEventStruct : public VirtualBox::CallbackEvent
3273{
3274 MediumConfigChangedEventStruct(VirtualBox *aVB, IMedium *aMedium)
3275 : CallbackEvent(aVB, VBoxEventType_OnMediumConfigChanged)
3276 , mMedium(aMedium)
3277 {}
3278
3279 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
3280 {
3281 return aEvDesc.init(aSource, VBoxEventType_OnMediumConfigChanged, mMedium);
3282 }
3283
3284 IMedium* mMedium;
3285};
3286
3287void VirtualBox::i_onMediumConfigChanged(IMedium *aMedium)
3288{
3289 i_postEvent(new MediumConfigChangedEventStruct(this, aMedium));
3290}
3291
3292/** Event for onMediumChanged() */
3293struct MediumChangedEventStruct : public VirtualBox::CallbackEvent
3294{
3295 MediumChangedEventStruct(VirtualBox *aVB, IMediumAttachment *aMediumAttachment)
3296 : CallbackEvent(aVB, VBoxEventType_OnMediumChanged)
3297 , mMediumAttachment(aMediumAttachment)
3298 {}
3299
3300 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
3301 {
3302 return aEvDesc.init(aSource, VBoxEventType_OnMediumChanged, mMediumAttachment);
3303 }
3304
3305 IMediumAttachment* mMediumAttachment;
3306};
3307
3308void VirtualBox::i_onMediumChanged(IMediumAttachment *aMediumAttachment)
3309{
3310 i_postEvent(new MediumChangedEventStruct(this, aMediumAttachment));
3311}
3312
3313/** Event for onStorageControllerChanged() */
3314struct StorageControllerChangedEventStruct : public VirtualBox::CallbackEvent
3315{
3316 StorageControllerChangedEventStruct(VirtualBox *aVB, const Guid &aMachineId,
3317 const com::Utf8Str &aControllerName)
3318 : CallbackEvent(aVB, VBoxEventType_OnStorageControllerChanged)
3319 , mMachineId(aMachineId.toUtf16()), mControllerName(aControllerName)
3320 {}
3321
3322 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
3323 {
3324 return aEvDesc.init(aSource, VBoxEventType_OnStorageControllerChanged, mMachineId.raw(), mControllerName.raw());
3325 }
3326
3327 Bstr mMachineId;
3328 Bstr mControllerName;
3329};
3330
3331/**
3332 * @note Doesn't lock any object.
3333 */
3334void VirtualBox::i_onStorageControllerChanged(const Guid &aMachineId, const com::Utf8Str &aControllerName)
3335{
3336 i_postEvent(new StorageControllerChangedEventStruct(this, aMachineId, aControllerName));
3337}
3338
3339/** Event for onStorageDeviceChanged() */
3340struct StorageDeviceChangedEventStruct : public VirtualBox::CallbackEvent
3341{
3342 StorageDeviceChangedEventStruct(VirtualBox *aVB, IMediumAttachment *aStorageDevice, BOOL fRemoved, BOOL fSilent)
3343 : CallbackEvent(aVB, VBoxEventType_OnStorageDeviceChanged)
3344 , mStorageDevice(aStorageDevice)
3345 , mRemoved(fRemoved)
3346 , mSilent(fSilent)
3347 {}
3348
3349 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
3350 {
3351 return aEvDesc.init(aSource, VBoxEventType_OnStorageDeviceChanged, mStorageDevice, mRemoved, mSilent);
3352 }
3353
3354 IMediumAttachment* mStorageDevice;
3355 BOOL mRemoved;
3356 BOOL mSilent;
3357};
3358
3359void VirtualBox::i_onStorageDeviceChanged(IMediumAttachment *aStorageDevice, const BOOL fRemoved, const BOOL fSilent)
3360{
3361 i_postEvent(new StorageDeviceChangedEventStruct(this, aStorageDevice, fRemoved, fSilent));
3362}
3363
3364/**
3365 * @note Doesn't lock any object.
3366 */
3367void VirtualBox::i_onMachineStateChange(const Guid &aId, MachineState_T aState)
3368{
3369 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
3370}
3371
3372/**
3373 * @note Doesn't lock any object.
3374 */
3375void VirtualBox::i_onMachineDataChange(const Guid &aId, BOOL aTemporary)
3376{
3377 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
3378}
3379
3380/**
3381 * @note Locks this object for reading.
3382 */
3383BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
3384 Bstr &aError)
3385{
3386 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
3387 aId.toString().c_str(), aKey, aValue));
3388
3389 AutoCaller autoCaller(this);
3390 AssertComRCReturn(autoCaller.rc(), FALSE);
3391
3392 BOOL allowChange = TRUE;
3393 Bstr id = aId.toUtf16();
3394
3395 VBoxEventDesc evDesc;
3396 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
3397 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
3398 //Assert(fDelivered);
3399 if (fDelivered)
3400 {
3401 ComPtr<IEvent> aEvent;
3402 evDesc.getEvent(aEvent.asOutParam());
3403 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
3404 Assert(aCanChangeEvent);
3405 BOOL fVetoed = FALSE;
3406 aCanChangeEvent->IsVetoed(&fVetoed);
3407 allowChange = !fVetoed;
3408
3409 if (!allowChange)
3410 {
3411 SafeArray<BSTR> aVetos;
3412 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
3413 if (aVetos.size() > 0)
3414 aError = aVetos[0];
3415 }
3416 }
3417 else
3418 allowChange = TRUE;
3419
3420 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
3421 return allowChange;
3422}
3423
3424/** Event for onExtraDataChange() */
3425struct ExtraDataEvent : public VirtualBox::CallbackEvent
3426{
3427 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
3428 IN_BSTR aKey, IN_BSTR aVal)
3429 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
3430 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
3431 {}
3432
3433 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3434 {
3435 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
3436 }
3437
3438 Bstr machineId, key, val;
3439};
3440
3441/**
3442 * @note Doesn't lock any object.
3443 */
3444void VirtualBox::i_onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
3445{
3446 i_postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
3447}
3448
3449/**
3450 * @note Doesn't lock any object.
3451 */
3452void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
3453{
3454 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
3455}
3456
3457/** Event for onSessionStateChange() */
3458struct SessionEvent : public VirtualBox::CallbackEvent
3459{
3460 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
3461 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
3462 , machineId(aMachineId.toUtf16()), sessionState(aState)
3463 {}
3464
3465 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3466 {
3467 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
3468 }
3469 Bstr machineId;
3470 SessionState_T sessionState;
3471};
3472
3473/**
3474 * @note Doesn't lock any object.
3475 */
3476void VirtualBox::i_onSessionStateChange(const Guid &aId, SessionState_T aState)
3477{
3478 i_postEvent(new SessionEvent(this, aId, aState));
3479}
3480
3481/** Event for i_onSnapshotTaken(), i_onSnapshotDeleted(), i_onSnapshotRestored() and i_onSnapshotChange() */
3482struct SnapshotEvent : public VirtualBox::CallbackEvent
3483{
3484 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
3485 VBoxEventType_T aWhat)
3486 : CallbackEvent(aVB, aWhat)
3487 , machineId(aMachineId), snapshotId(aSnapshotId)
3488 {}
3489
3490 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3491 {
3492 return aEvDesc.init(aSource, mWhat, machineId.toUtf16().raw(),
3493 snapshotId.toUtf16().raw());
3494 }
3495
3496 Guid machineId;
3497 Guid snapshotId;
3498};
3499
3500/**
3501 * @note Doesn't lock any object.
3502 */
3503void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
3504{
3505 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3506 VBoxEventType_OnSnapshotTaken));
3507}
3508
3509/**
3510 * @note Doesn't lock any object.
3511 */
3512void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
3513{
3514 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3515 VBoxEventType_OnSnapshotDeleted));
3516}
3517
3518/**
3519 * @note Doesn't lock any object.
3520 */
3521void VirtualBox::i_onSnapshotRestored(const Guid &aMachineId, const Guid &aSnapshotId)
3522{
3523 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3524 VBoxEventType_OnSnapshotRestored));
3525}
3526
3527/**
3528 * @note Doesn't lock any object.
3529 */
3530void VirtualBox::i_onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
3531{
3532 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3533 VBoxEventType_OnSnapshotChanged));
3534}
3535
3536/** Event for onGuestPropertyChange() */
3537struct GuestPropertyEvent : public VirtualBox::CallbackEvent
3538{
3539 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
3540 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
3541 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
3542 machineId(aMachineId),
3543 name(aName),
3544 value(aValue),
3545 flags(aFlags)
3546 {}
3547
3548 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3549 {
3550 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
3551 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
3552 }
3553
3554 Guid machineId;
3555 Bstr name, value, flags;
3556};
3557
3558#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
3559/**
3560 * Generates a new clipboard area on the host by opening (and locking) a new, temporary directory.
3561 *
3562 * @returns VBox status code.
3563 * @param uAreaID Clipboard area ID to use for creation.
3564 * @param fFlags Additional creation flags; currently unused and ignored.
3565 * @param ppAreaData Where to return the created clipboard area on success.
3566 */
3567int VirtualBox::i_clipboardAreaCreate(ULONG uAreaID, uint32_t fFlags, SharedClipboardAreaData **ppAreaData)
3568{
3569 RT_NOREF(fFlags);
3570
3571 int vrc;
3572
3573 SharedClipboardAreaData *pAreaData = new SharedClipboardAreaData();
3574 if (pAreaData)
3575 {
3576 vrc = pAreaData->Area.OpenTemp(uAreaID, SHCLAREA_OPEN_FLAGS_MUST_NOT_EXIST);
3577 if (RT_SUCCESS(vrc))
3578 {
3579 pAreaData->uID = uAreaID;
3580
3581 *ppAreaData = pAreaData;
3582 }
3583 }
3584 else
3585 vrc = VERR_NO_MEMORY;
3586
3587 LogFlowFunc(("uID=%RU32, rc=%Rrc\n", uAreaID, vrc));
3588 return vrc;
3589}
3590
3591/**
3592 * Destroys a formerly created clipboard area.
3593 *
3594 * @returns VBox status code.
3595 * @param pAreaData Area data to destroy. The pointer will be invalid on successful return.
3596 */
3597int VirtualBox::i_clipboardAreaDestroy(SharedClipboardAreaData *pAreaData)
3598{
3599 if (!pAreaData)
3600 return VINF_SUCCESS;
3601
3602 /** @todo Do we need a worker for this to not block here for too long?
3603 * This could take a while to clean up huge areas ... */
3604 int vrc = pAreaData->Area.Close();
3605 if (RT_SUCCESS(vrc))
3606 {
3607 delete pAreaData;
3608 pAreaData = NULL;
3609 }
3610
3611 LogFlowFunc(("uID=%RU32, rc=%Rrc\n", pAreaData->uID, vrc));
3612 return vrc;
3613}
3614
3615/**
3616 * Registers and creates a new clipboard area on the host (for all VMs), returned the clipboard area ID for it.
3617 *
3618 * @returns HRESULT
3619 * @param aParms Creation parameters. Currently unused.
3620 * @param aID Where to return the clipboard area ID on success.
3621 */
3622HRESULT VirtualBox::i_onClipboardAreaRegister(const std::vector<com::Utf8Str> &aParms, ULONG *aID)
3623{
3624 RT_NOREF(aParms);
3625
3626 HRESULT rc = S_OK;
3627
3628 int vrc = RTCritSectEnter(&m->SharedClipboard.CritSect);
3629 if (RT_SUCCESS(vrc))
3630 {
3631 try
3632 {
3633 if (m->SharedClipboard.mapClipboardAreas.size() < m->SharedClipboard.uMaxClipboardAreas)
3634 {
3635 for (unsigned uTries = 0; uTries < 32; uTries++) /* Don't try too hard. */
3636 {
3637 const ULONG uAreaID = m->SharedClipboard.GenerateAreaID();
3638
3639 /* Area ID already taken? */
3640 if (m->SharedClipboard.mapClipboardAreas.find(uAreaID) != m->SharedClipboard.mapClipboardAreas.end())
3641 continue;
3642
3643 SharedClipboardAreaData *pAreaData;
3644 vrc = i_clipboardAreaCreate(uAreaID, 0 /* fFlags */, &pAreaData);
3645 if (RT_SUCCESS(vrc))
3646 {
3647 m->SharedClipboard.mapClipboardAreas[uAreaID] = pAreaData;
3648 m->SharedClipboard.uMostRecentClipboardAreaID = uAreaID;
3649
3650 /** @todo Implement collision detection / wrap-around. */
3651
3652 if (aID)
3653 *aID = uAreaID;
3654
3655 LogThisFunc(("Registered new clipboard area %RU32: '%s'\n",
3656 uAreaID, pAreaData->Area.GetDirAbs()));
3657 break;
3658 }
3659 }
3660
3661 if (RT_FAILURE(vrc))
3662 rc = setError(E_FAIL, /** @todo Find a better rc. */
3663 tr("Failed to create new clipboard area (%Rrc)"), vrc);
3664 }
3665 else
3666 {
3667 rc = setError(E_FAIL, /** @todo Find a better rc. */
3668 tr("Maximum number of concurrent clipboard areas reached (%RU32)"),
3669 m->SharedClipboard.uMaxClipboardAreas);
3670 }
3671 }
3672 catch (std::bad_alloc &ba)
3673 {
3674 vrc = VERR_NO_MEMORY;
3675 RT_NOREF(ba);
3676 }
3677
3678 RTCritSectLeave(&m->SharedClipboard.CritSect);
3679 }
3680 LogFlowThisFunc(("rc=%Rhrc\n", rc));
3681 return rc;
3682}
3683
3684/**
3685 * Unregisters (destroys) a formerly created clipboard area.
3686 *
3687 * @returns HRESULT
3688 * @param aID ID of clipboard area to destroy.
3689 */
3690HRESULT VirtualBox::i_onClipboardAreaUnregister(ULONG aID)
3691{
3692 HRESULT rc = S_OK;
3693
3694 int vrc = RTCritSectEnter(&m->SharedClipboard.CritSect);
3695 if (RT_SUCCESS(vrc))
3696 {
3697 SharedClipboardAreaMap::iterator itArea = m->SharedClipboard.mapClipboardAreas.find(aID);
3698 if (itArea != m->SharedClipboard.mapClipboardAreas.end())
3699 {
3700 if (itArea->second->Area.GetRefCount() == 0)
3701 {
3702 vrc = i_clipboardAreaDestroy(itArea->second);
3703 if (RT_SUCCESS(vrc))
3704 {
3705 m->SharedClipboard.mapClipboardAreas.erase(itArea);
3706 }
3707 }
3708 else
3709 rc = setError(E_ACCESSDENIED, /** @todo Find a better rc. */
3710 tr("Area with ID %RU32 still in used, cannot unregister"), aID);
3711 }
3712 else
3713 rc = setError(VBOX_E_OBJECT_NOT_FOUND, /** @todo Find a better rc. */
3714 tr("Could not find a registered clipboard area with ID %RU32"), aID);
3715
3716 int vrc2 = RTCritSectLeave(&m->SharedClipboard.CritSect);
3717 AssertRC(vrc2);
3718 }
3719 LogFlowThisFunc(("aID=%RU32, rc=%Rhrc\n", aID, rc));
3720 return rc;
3721}
3722
3723/**
3724 * Attaches to an existing clipboard area.
3725 *
3726 * @returns HRESULT
3727 * @param aID ID of clipboard area to attach.
3728 */
3729HRESULT VirtualBox::i_onClipboardAreaAttach(ULONG aID)
3730{
3731 HRESULT rc = S_OK;
3732
3733 int vrc = RTCritSectEnter(&m->SharedClipboard.CritSect);
3734 if (RT_SUCCESS(vrc))
3735 {
3736 SharedClipboardAreaMap::iterator itArea = m->SharedClipboard.mapClipboardAreas.find(aID);
3737 if (itArea != m->SharedClipboard.mapClipboardAreas.end())
3738 {
3739 const uint32_t cRefs = itArea->second->Area.AddRef();
3740 RT_NOREF(cRefs);
3741 LogFlowThisFunc(("aID=%RU32 -> cRefs=%RU32\n", aID, cRefs));
3742 vrc = VINF_SUCCESS;
3743 }
3744 else
3745 rc = setError(VBOX_E_OBJECT_NOT_FOUND, /** @todo Find a better rc. */
3746 tr("Could not find a registered clipboard area with ID %RU32"), aID);
3747
3748 int vrc2 = RTCritSectLeave(&m->SharedClipboard.CritSect);
3749 AssertRC(vrc2);
3750 }
3751 LogFlowThisFunc(("aID=%RU32, rc=%Rhrc\n", aID, rc));
3752 return rc;
3753}
3754
3755/**
3756 * Detaches from an existing clipboard area.
3757 *
3758 * @returns HRESULT
3759 * @param aID ID of clipboard area to detach from.
3760 */
3761HRESULT VirtualBox::i_onClipboardAreaDetach(ULONG aID)
3762{
3763 HRESULT rc = S_OK;
3764
3765 int vrc = RTCritSectEnter(&m->SharedClipboard.CritSect);
3766 if (RT_SUCCESS(vrc))
3767 {
3768 SharedClipboardAreaMap::iterator itArea = m->SharedClipboard.mapClipboardAreas.find(aID);
3769 if (itArea != m->SharedClipboard.mapClipboardAreas.end())
3770 {
3771 const uint32_t cRefs = itArea->second->Area.Release();
3772 RT_NOREF(cRefs);
3773 LogFlowThisFunc(("aID=%RU32 -> cRefs=%RU32\n", aID, cRefs));
3774 vrc = VINF_SUCCESS;
3775 }
3776 else
3777 rc = setError(VBOX_E_OBJECT_NOT_FOUND, /** @todo Find a better rc. */
3778 tr("Could not find a registered clipboard area with ID %RU32"), aID);
3779
3780 int rc2 = RTCritSectLeave(&m->SharedClipboard.CritSect);
3781 AssertRC(rc2);
3782 }
3783 LogFlowThisFunc(("aID=%RU32, rc=%Rhrc\n", aID, rc));
3784 return rc;
3785}
3786
3787/**
3788 * Returns the ID of the most recent (last created) clipboard area,
3789 * or NIL_SHCLAREAID if no clipboard area has been created yet.
3790 *
3791 * @returns Most recent clipboard area ID.
3792 */
3793ULONG VirtualBox::i_onClipboardAreaGetMostRecent(void)
3794{
3795 ULONG aID = 0;
3796 int vrc2 = RTCritSectEnter(&m->SharedClipboard.CritSect);
3797 if (RT_SUCCESS(vrc2))
3798 {
3799 aID = m->SharedClipboard.uMostRecentClipboardAreaID;
3800
3801 vrc2 = RTCritSectLeave(&m->SharedClipboard.CritSect);
3802 AssertRC(vrc2);
3803 }
3804 LogFlowThisFunc(("aID=%RU32\n", aID));
3805 return aID;
3806}
3807
3808/**
3809 * Returns the current reference count of a clipboard area.
3810 *
3811 * @returns Reference count of given clipboard area ID.
3812 */
3813ULONG VirtualBox::i_onClipboardAreaGetRefCount(ULONG aID)
3814{
3815 ULONG cRefCount = 0;
3816 int rc2 = RTCritSectEnter(&m->SharedClipboard.CritSect);
3817 if (RT_SUCCESS(rc2))
3818 {
3819 SharedClipboardAreaMap::iterator itArea = m->SharedClipboard.mapClipboardAreas.find(aID);
3820 if (itArea != m->SharedClipboard.mapClipboardAreas.end())
3821 {
3822 cRefCount = itArea->second->Area.GetRefCount();
3823 }
3824
3825 rc2 = RTCritSectLeave(&m->SharedClipboard.CritSect);
3826 AssertRC(rc2);
3827 }
3828 LogFlowThisFunc(("aID=%RU32, cRefCount=%RU32\n", aID, cRefCount));
3829 return cRefCount;
3830}
3831#endif /* VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS */
3832
3833/**
3834 * @note Doesn't lock any object.
3835 */
3836void VirtualBox::i_onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
3837 IN_BSTR aValue, IN_BSTR aFlags)
3838{
3839 i_postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
3840}
3841
3842/**
3843 * @note Doesn't lock any object.
3844 */
3845void VirtualBox::i_onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
3846 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
3847 IN_BSTR aGuestIp, uint16_t aGuestPort)
3848{
3849 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
3850 aHostPort, aGuestIp, aGuestPort);
3851}
3852
3853void VirtualBox::i_onNATNetworkChange(IN_BSTR aName)
3854{
3855 fireNATNetworkChangedEvent(m->pEventSource, aName);
3856}
3857
3858void VirtualBox::i_onNATNetworkStartStop(IN_BSTR aName, BOOL fStart)
3859{
3860 fireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
3861}
3862
3863void VirtualBox::i_onNATNetworkSetting(IN_BSTR aNetworkName, BOOL aEnabled,
3864 IN_BSTR aNetwork, IN_BSTR aGateway,
3865 BOOL aAdvertiseDefaultIpv6RouteEnabled,
3866 BOOL fNeedDhcpServer)
3867{
3868 fireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled,
3869 aNetwork, aGateway,
3870 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
3871}
3872
3873void VirtualBox::i_onNATNetworkPortForward(IN_BSTR aNetworkName, BOOL create, BOOL fIpv6,
3874 IN_BSTR aRuleName, NATProtocol_T proto,
3875 IN_BSTR aHostIp, LONG aHostPort,
3876 IN_BSTR aGuestIp, LONG aGuestPort)
3877{
3878 fireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create,
3879 fIpv6, aRuleName, proto,
3880 aHostIp, aHostPort,
3881 aGuestIp, aGuestPort);
3882}
3883
3884
3885void VirtualBox::i_onHostNameResolutionConfigurationChange()
3886{
3887 if (m->pEventSource)
3888 fireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
3889}
3890
3891
3892int VirtualBox::i_natNetworkRefInc(const Utf8Str &aNetworkName)
3893{
3894 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3895
3896 if (!sNatNetworkNameToRefCount[aNetworkName])
3897 {
3898 ComPtr<INATNetwork> nat;
3899 HRESULT rc = findNATNetworkByName(aNetworkName, nat);
3900 if (FAILED(rc)) return -1;
3901
3902 rc = nat->Start();
3903 if (SUCCEEDED(rc))
3904 LogRel(("Started NAT network '%s'\n", aNetworkName.c_str()));
3905 else
3906 LogRel(("Error %Rhrc starting NAT network '%s'\n", rc, aNetworkName.c_str()));
3907 AssertComRCReturn(rc, -1);
3908 }
3909
3910 sNatNetworkNameToRefCount[aNetworkName]++;
3911
3912 return sNatNetworkNameToRefCount[aNetworkName];
3913}
3914
3915
3916int VirtualBox::i_natNetworkRefDec(const Utf8Str &aNetworkName)
3917{
3918 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3919
3920 if (!sNatNetworkNameToRefCount[aNetworkName])
3921 return 0;
3922
3923 sNatNetworkNameToRefCount[aNetworkName]--;
3924
3925 if (!sNatNetworkNameToRefCount[aNetworkName])
3926 {
3927 ComPtr<INATNetwork> nat;
3928 HRESULT rc = findNATNetworkByName(aNetworkName, nat);
3929 if (FAILED(rc)) return -1;
3930
3931 rc = nat->Stop();
3932 if (SUCCEEDED(rc))
3933 LogRel(("Stopped NAT network '%s'\n", aNetworkName.c_str()));
3934 else
3935 LogRel(("Error %Rhrc stopping NAT network '%s'\n", rc, aNetworkName.c_str()));
3936 AssertComRCReturn(rc, -1);
3937 }
3938
3939 return sNatNetworkNameToRefCount[aNetworkName];
3940}
3941
3942
3943/**
3944 * @note Locks the list of other objects for reading.
3945 */
3946ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
3947{
3948 ComObjPtr<GuestOSType> type;
3949
3950 /* unknown type must always be the first */
3951 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
3952
3953 return m->allGuestOSTypes.front();
3954}
3955
3956/**
3957 * Returns the list of opened machines (machines having VM sessions opened,
3958 * ignoring other sessions) and optionally the list of direct session controls.
3959 *
3960 * @param aMachines Where to put opened machines (will be empty if none).
3961 * @param aControls Where to put direct session controls (optional).
3962 *
3963 * @note The returned lists contain smart pointers. So, clear it as soon as
3964 * it becomes no more necessary to release instances.
3965 *
3966 * @note It can be possible that a session machine from the list has been
3967 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
3968 * when accessing unprotected data directly.
3969 *
3970 * @note Locks objects for reading.
3971 */
3972void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
3973 InternalControlList *aControls /*= NULL*/)
3974{
3975 AutoCaller autoCaller(this);
3976 AssertComRCReturnVoid(autoCaller.rc());
3977
3978 aMachines.clear();
3979 if (aControls)
3980 aControls->clear();
3981
3982 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3983
3984 for (MachinesOList::iterator it = m->allMachines.begin();
3985 it != m->allMachines.end();
3986 ++it)
3987 {
3988 ComObjPtr<SessionMachine> sm;
3989 ComPtr<IInternalSessionControl> ctl;
3990 if ((*it)->i_isSessionOpenVM(sm, &ctl))
3991 {
3992 aMachines.push_back(sm);
3993 if (aControls)
3994 aControls->push_back(ctl);
3995 }
3996 }
3997}
3998
3999/**
4000 * Gets a reference to the machine list. This is the real thing, not a copy,
4001 * so bad things will happen if the caller doesn't hold the necessary lock.
4002 *
4003 * @returns reference to machine list
4004 *
4005 * @note Caller must hold the VirtualBox object lock at least for reading.
4006 */
4007VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
4008{
4009 return m->allMachines;
4010}
4011
4012/**
4013 * Searches for a machine object with the given ID in the collection
4014 * of registered machines.
4015 *
4016 * @param aId Machine UUID to look for.
4017 * @param fPermitInaccessible If true, inaccessible machines will be found;
4018 * if false, this will fail if the given machine is inaccessible.
4019 * @param aSetError If true, set errorinfo if the machine is not found.
4020 * @param aMachine Returned machine, if found.
4021 * @return
4022 */
4023HRESULT VirtualBox::i_findMachine(const Guid &aId,
4024 bool fPermitInaccessible,
4025 bool aSetError,
4026 ComObjPtr<Machine> *aMachine /* = NULL */)
4027{
4028 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
4029
4030 AutoCaller autoCaller(this);
4031 AssertComRCReturnRC(autoCaller.rc());
4032
4033 {
4034 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4035
4036 for (MachinesOList::iterator it = m->allMachines.begin();
4037 it != m->allMachines.end();
4038 ++it)
4039 {
4040 ComObjPtr<Machine> pMachine = *it;
4041
4042 if (!fPermitInaccessible)
4043 {
4044 // skip inaccessible machines
4045 AutoCaller machCaller(pMachine);
4046 if (FAILED(machCaller.rc()))
4047 continue;
4048 }
4049
4050 if (pMachine->i_getId() == aId)
4051 {
4052 rc = S_OK;
4053 if (aMachine)
4054 *aMachine = pMachine;
4055 break;
4056 }
4057 }
4058 }
4059
4060 if (aSetError && FAILED(rc))
4061 rc = setError(rc,
4062 tr("Could not find a registered machine with UUID {%RTuuid}"),
4063 aId.raw());
4064
4065 return rc;
4066}
4067
4068/**
4069 * Searches for a machine object with the given name or location in the
4070 * collection of registered machines.
4071 *
4072 * @param aName Machine name or location to look for.
4073 * @param aSetError If true, set errorinfo if the machine is not found.
4074 * @param aMachine Returned machine, if found.
4075 * @return
4076 */
4077HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
4078 bool aSetError,
4079 ComObjPtr<Machine> *aMachine /* = NULL */)
4080{
4081 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
4082
4083 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4084 for (MachinesOList::iterator it = m->allMachines.begin();
4085 it != m->allMachines.end();
4086 ++it)
4087 {
4088 ComObjPtr<Machine> &pMachine = *it;
4089 AutoCaller machCaller(pMachine);
4090 if (!machCaller.isOk())
4091 continue; // we can't ask inaccessible machines for their names
4092
4093 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
4094 if (pMachine->i_getName() == aName)
4095 {
4096 rc = S_OK;
4097 if (aMachine)
4098 *aMachine = pMachine;
4099 break;
4100 }
4101 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
4102 {
4103 rc = S_OK;
4104 if (aMachine)
4105 *aMachine = pMachine;
4106 break;
4107 }
4108 }
4109
4110 if (aSetError && FAILED(rc))
4111 rc = setError(rc,
4112 tr("Could not find a registered machine named '%s'"), aName.c_str());
4113
4114 return rc;
4115}
4116
4117static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
4118{
4119 /* empty strings are invalid */
4120 if (aGroup.isEmpty())
4121 return E_INVALIDARG;
4122 /* the toplevel group is valid */
4123 if (aGroup == "/")
4124 return S_OK;
4125 /* any other strings of length 1 are invalid */
4126 if (aGroup.length() == 1)
4127 return E_INVALIDARG;
4128 /* must start with a slash */
4129 if (aGroup.c_str()[0] != '/')
4130 return E_INVALIDARG;
4131 /* must not end with a slash */
4132 if (aGroup.c_str()[aGroup.length() - 1] == '/')
4133 return E_INVALIDARG;
4134 /* check the group components */
4135 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
4136 while (pStr)
4137 {
4138 char *pSlash = RTStrStr(pStr, "/");
4139 if (pSlash)
4140 {
4141 /* no empty components (or // sequences in other words) */
4142 if (pSlash == pStr)
4143 return E_INVALIDARG;
4144 /* check if the machine name rules are violated, because that means
4145 * the group components are too close to the limits. */
4146 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
4147 Utf8Str tmp2(tmp);
4148 sanitiseMachineFilename(tmp);
4149 if (tmp != tmp2)
4150 return E_INVALIDARG;
4151 if (fPrimary)
4152 {
4153 HRESULT rc = pVirtualBox->i_findMachineByName(tmp,
4154 false /* aSetError */);
4155 if (SUCCEEDED(rc))
4156 return VBOX_E_VM_ERROR;
4157 }
4158 pStr = pSlash + 1;
4159 }
4160 else
4161 {
4162 /* check if the machine name rules are violated, because that means
4163 * the group components is too close to the limits. */
4164 Utf8Str tmp(pStr);
4165 Utf8Str tmp2(tmp);
4166 sanitiseMachineFilename(tmp);
4167 if (tmp != tmp2)
4168 return E_INVALIDARG;
4169 pStr = NULL;
4170 }
4171 }
4172 return S_OK;
4173}
4174
4175/**
4176 * Validates a machine group.
4177 *
4178 * @param aGroup Machine group.
4179 * @param fPrimary Set if this is the primary group.
4180 *
4181 * @return S_OK or E_INVALIDARG
4182 */
4183HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
4184{
4185 HRESULT rc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
4186 if (FAILED(rc))
4187 {
4188 if (rc == VBOX_E_VM_ERROR)
4189 rc = setError(E_INVALIDARG,
4190 tr("Machine group '%s' conflicts with a virtual machine name"),
4191 aGroup.c_str());
4192 else
4193 rc = setError(rc,
4194 tr("Invalid machine group '%s'"),
4195 aGroup.c_str());
4196 }
4197 return rc;
4198}
4199
4200/**
4201 * Takes a list of machine groups, and sanitizes/validates it.
4202 *
4203 * @param aMachineGroups Array with the machine groups.
4204 * @param pllMachineGroups Pointer to list of strings for the result.
4205 *
4206 * @return S_OK or E_INVALIDARG
4207 */
4208HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
4209{
4210 pllMachineGroups->clear();
4211 if (aMachineGroups.size())
4212 {
4213 for (size_t i = 0; i < aMachineGroups.size(); i++)
4214 {
4215 Utf8Str group(aMachineGroups[i]);
4216 if (group.length() == 0)
4217 group = "/";
4218
4219 HRESULT rc = i_validateMachineGroup(group, i == 0);
4220 if (FAILED(rc))
4221 return rc;
4222
4223 /* no duplicates please */
4224 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
4225 == pllMachineGroups->end())
4226 pllMachineGroups->push_back(group);
4227 }
4228 if (pllMachineGroups->size() == 0)
4229 pllMachineGroups->push_back("/");
4230 }
4231 else
4232 pllMachineGroups->push_back("/");
4233
4234 return S_OK;
4235}
4236
4237/**
4238 * Searches for a Medium object with the given ID in the list of registered
4239 * hard disks.
4240 *
4241 * @param aId ID of the hard disk. Must not be empty.
4242 * @param aSetError If @c true , the appropriate error info is set in case
4243 * when the hard disk is not found.
4244 * @param aHardDisk Where to store the found hard disk object (can be NULL).
4245 *
4246 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4247 *
4248 * @note Locks the media tree for reading.
4249 */
4250HRESULT VirtualBox::i_findHardDiskById(const Guid &aId,
4251 bool aSetError,
4252 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
4253{
4254 AssertReturn(!aId.isZero(), E_INVALIDARG);
4255
4256 // we use the hard disks map, but it is protected by the
4257 // hard disk _list_ lock handle
4258 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4259
4260 HardDiskMap::const_iterator it = m->mapHardDisks.find(aId);
4261 if (it != m->mapHardDisks.end())
4262 {
4263 if (aHardDisk)
4264 *aHardDisk = (*it).second;
4265 return S_OK;
4266 }
4267
4268 if (aSetError)
4269 return setError(VBOX_E_OBJECT_NOT_FOUND,
4270 tr("Could not find an open hard disk with UUID {%RTuuid}"),
4271 aId.raw());
4272
4273 return VBOX_E_OBJECT_NOT_FOUND;
4274}
4275
4276/**
4277 * Searches for a Medium object with the given ID or location in the list of
4278 * registered hard disks. If both ID and location are specified, the first
4279 * object that matches either of them (not necessarily both) is returned.
4280 *
4281 * @param strLocation Full location specification. Must not be empty.
4282 * @param aSetError If @c true , the appropriate error info is set in case
4283 * when the hard disk is not found.
4284 * @param aHardDisk Where to store the found hard disk object (can be NULL).
4285 *
4286 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4287 *
4288 * @note Locks the media tree for reading.
4289 */
4290HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
4291 bool aSetError,
4292 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
4293{
4294 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
4295
4296 // we use the hard disks map, but it is protected by the
4297 // hard disk _list_ lock handle
4298 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4299
4300 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
4301 it != m->mapHardDisks.end();
4302 ++it)
4303 {
4304 const ComObjPtr<Medium> &pHD = (*it).second;
4305
4306 AutoCaller autoCaller(pHD);
4307 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4308 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
4309
4310 Utf8Str strLocationFull = pHD->i_getLocationFull();
4311
4312 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
4313 {
4314 if (aHardDisk)
4315 *aHardDisk = pHD;
4316 return S_OK;
4317 }
4318 }
4319
4320 if (aSetError)
4321 return setError(VBOX_E_OBJECT_NOT_FOUND,
4322 tr("Could not find an open hard disk with location '%s'"),
4323 strLocation.c_str());
4324
4325 return VBOX_E_OBJECT_NOT_FOUND;
4326}
4327
4328/**
4329 * Searches for a Medium object with the given ID or location in the list of
4330 * registered DVD or floppy images, depending on the @a mediumType argument.
4331 * If both ID and file path are specified, the first object that matches either
4332 * of them (not necessarily both) is returned.
4333 *
4334 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
4335 * @param aId ID of the image file (unused when NULL).
4336 * @param aLocation Full path to the image file (unused when NULL).
4337 * @param aSetError If @c true, the appropriate error info is set in case when
4338 * the image is not found.
4339 * @param aImage Where to store the found image object (can be NULL).
4340 *
4341 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
4342 *
4343 * @note Locks the media tree for reading.
4344 */
4345HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
4346 const Guid *aId,
4347 const Utf8Str &aLocation,
4348 bool aSetError,
4349 ComObjPtr<Medium> *aImage /* = NULL */)
4350{
4351 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
4352
4353 Utf8Str location;
4354 if (!aLocation.isEmpty())
4355 {
4356 int vrc = i_calculateFullPath(aLocation, location);
4357 if (RT_FAILURE(vrc))
4358 return setError(VBOX_E_FILE_ERROR,
4359 tr("Invalid image file location '%s' (%Rrc)"),
4360 aLocation.c_str(),
4361 vrc);
4362 }
4363
4364 MediaOList *pMediaList;
4365
4366 switch (mediumType)
4367 {
4368 case DeviceType_DVD:
4369 pMediaList = &m->allDVDImages;
4370 break;
4371
4372 case DeviceType_Floppy:
4373 pMediaList = &m->allFloppyImages;
4374 break;
4375
4376 default:
4377 return E_INVALIDARG;
4378 }
4379
4380 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
4381
4382 bool found = false;
4383
4384 for (MediaList::const_iterator it = pMediaList->begin();
4385 it != pMediaList->end();
4386 ++it)
4387 {
4388 // no AutoCaller, registered image life time is bound to this
4389 Medium *pMedium = *it;
4390 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
4391 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
4392
4393 found = ( aId
4394 && pMedium->i_getId() == *aId)
4395 || ( !aLocation.isEmpty()
4396 && RTPathCompare(location.c_str(),
4397 strLocationFull.c_str()) == 0);
4398 if (found)
4399 {
4400 if (pMedium->i_getDeviceType() != mediumType)
4401 {
4402 if (mediumType == DeviceType_DVD)
4403 return setError(E_INVALIDARG,
4404 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
4405 else
4406 return setError(E_INVALIDARG,
4407 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
4408 }
4409
4410 if (aImage)
4411 *aImage = pMedium;
4412 break;
4413 }
4414 }
4415
4416 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
4417
4418 if (aSetError && !found)
4419 {
4420 if (aId)
4421 setError(rc,
4422 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
4423 aId->raw(),
4424 m->strSettingsFilePath.c_str());
4425 else
4426 setError(rc,
4427 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
4428 aLocation.c_str(),
4429 m->strSettingsFilePath.c_str());
4430 }
4431
4432 return rc;
4433}
4434
4435/**
4436 * Searches for an IMedium object that represents the given UUID.
4437 *
4438 * If the UUID is empty (indicating an empty drive), this sets pMedium
4439 * to NULL and returns S_OK.
4440 *
4441 * If the UUID refers to a host drive of the given device type, this
4442 * sets pMedium to the object from the list in IHost and returns S_OK.
4443 *
4444 * If the UUID is an image file, this sets pMedium to the object that
4445 * findDVDOrFloppyImage() returned.
4446 *
4447 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
4448 *
4449 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
4450 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
4451 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
4452 * @param aSetError
4453 * @param pMedium out: IMedium object found.
4454 * @return
4455 */
4456HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
4457 const Guid &uuid,
4458 bool fRefresh,
4459 bool aSetError,
4460 ComObjPtr<Medium> &pMedium)
4461{
4462 if (uuid.isZero())
4463 {
4464 // that's easy
4465 pMedium.setNull();
4466 return S_OK;
4467 }
4468 else if (!uuid.isValid())
4469 {
4470 /* handling of case invalid GUID */
4471 return setError(VBOX_E_OBJECT_NOT_FOUND,
4472 tr("Guid '%s' is invalid"),
4473 uuid.toString().c_str());
4474 }
4475
4476 // first search for host drive with that UUID
4477 HRESULT rc = m->pHost->i_findHostDriveById(mediumType,
4478 uuid,
4479 fRefresh,
4480 pMedium);
4481 if (rc == VBOX_E_OBJECT_NOT_FOUND)
4482 // then search for an image with that UUID
4483 rc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
4484
4485 return rc;
4486}
4487
4488/* Look for a GuestOSType object */
4489HRESULT VirtualBox::i_findGuestOSType(const Utf8Str &strOSType,
4490 ComObjPtr<GuestOSType> &guestOSType)
4491{
4492 guestOSType.setNull();
4493
4494 AssertMsg(m->allGuestOSTypes.size() != 0,
4495 ("Guest OS types array must be filled"));
4496
4497 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4498 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
4499 it != m->allGuestOSTypes.end();
4500 ++it)
4501 {
4502 const Utf8Str &typeId = (*it)->i_id();
4503 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
4504 if (strOSType.compare(typeId, Utf8Str::CaseInsensitive) == 0)
4505 {
4506 guestOSType = *it;
4507 return S_OK;
4508 }
4509 }
4510
4511 return setError(VBOX_E_OBJECT_NOT_FOUND,
4512 tr("'%s' is not a valid Guest OS type"),
4513 strOSType.c_str());
4514}
4515
4516/**
4517 * Returns the constant pseudo-machine UUID that is used to identify the
4518 * global media registry.
4519 *
4520 * Starting with VirtualBox 4.0 each medium remembers in its instance data
4521 * in which media registry it is saved (if any): this can either be a machine
4522 * UUID, if it's in a per-machine media registry, or this global ID.
4523 *
4524 * This UUID is only used to identify the VirtualBox object while VirtualBox
4525 * is running. It is a compile-time constant and not saved anywhere.
4526 *
4527 * @return
4528 */
4529const Guid& VirtualBox::i_getGlobalRegistryId() const
4530{
4531 return m->uuidMediaRegistry;
4532}
4533
4534const ComObjPtr<Host>& VirtualBox::i_host() const
4535{
4536 return m->pHost;
4537}
4538
4539SystemProperties* VirtualBox::i_getSystemProperties() const
4540{
4541 return m->pSystemProperties;
4542}
4543
4544CloudProviderManager *VirtualBox::i_getCloudProviderManager() const
4545{
4546 return m->pCloudProviderManager;
4547}
4548
4549#ifdef VBOX_WITH_EXTPACK
4550/**
4551 * Getter that SystemProperties and others can use to talk to the extension
4552 * pack manager.
4553 */
4554ExtPackManager* VirtualBox::i_getExtPackManager() const
4555{
4556 return m->ptrExtPackManager;
4557}
4558#endif
4559
4560/**
4561 * Getter that machines can talk to the autostart database.
4562 */
4563AutostartDb* VirtualBox::i_getAutostartDb() const
4564{
4565 return m->pAutostartDb;
4566}
4567
4568#ifdef VBOX_WITH_RESOURCE_USAGE_API
4569const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
4570{
4571 return m->pPerformanceCollector;
4572}
4573#endif /* VBOX_WITH_RESOURCE_USAGE_API */
4574
4575/**
4576 * Returns the default machine folder from the system properties
4577 * with proper locking.
4578 * @return
4579 */
4580void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
4581{
4582 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
4583 str = m->pSystemProperties->m->strDefaultMachineFolder;
4584}
4585
4586/**
4587 * Returns the default hard disk format from the system properties
4588 * with proper locking.
4589 * @return
4590 */
4591void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
4592{
4593 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
4594 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
4595}
4596
4597const Utf8Str& VirtualBox::i_homeDir() const
4598{
4599 return m->strHomeDir;
4600}
4601
4602/**
4603 * Calculates the absolute path of the given path taking the VirtualBox home
4604 * directory as the current directory.
4605 *
4606 * @param strPath Path to calculate the absolute path for.
4607 * @param aResult Where to put the result (used only on success, can be the
4608 * same Utf8Str instance as passed in @a aPath).
4609 * @return IPRT result.
4610 *
4611 * @note Doesn't lock any object.
4612 */
4613int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
4614{
4615 AutoCaller autoCaller(this);
4616 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
4617
4618 /* no need to lock since strHomeDir is const */
4619
4620 char szFolder[RTPATH_MAX];
4621 size_t cbFolder = sizeof(szFolder);
4622 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
4623 strPath.c_str(),
4624 RTPATH_STR_F_STYLE_HOST,
4625 szFolder,
4626 &cbFolder);
4627 if (RT_SUCCESS(vrc))
4628 aResult = szFolder;
4629
4630 return vrc;
4631}
4632
4633/**
4634 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
4635 * if it is a subdirectory thereof, or simply copying it otherwise.
4636 *
4637 * @param strSource Path to evalue and copy.
4638 * @param strTarget Buffer to receive target path.
4639 */
4640void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
4641 Utf8Str &strTarget)
4642{
4643 AutoCaller autoCaller(this);
4644 AssertComRCReturnVoid(autoCaller.rc());
4645
4646 // no need to lock since mHomeDir is const
4647
4648 // use strTarget as a temporary buffer to hold the machine settings dir
4649 strTarget = m->strHomeDir;
4650 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
4651 // is relative: then append what's left
4652 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
4653 else
4654 // is not relative: then overwrite
4655 strTarget = strSource;
4656}
4657
4658// private methods
4659/////////////////////////////////////////////////////////////////////////////
4660
4661/**
4662 * Checks if there is a hard disk, DVD or floppy image with the given ID or
4663 * location already registered.
4664 *
4665 * On return, sets @a aConflict to the string describing the conflicting medium,
4666 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
4667 * either case. A failure is unexpected.
4668 *
4669 * @param aId UUID to check.
4670 * @param aLocation Location to check.
4671 * @param aConflict Where to return parameters of the conflicting medium.
4672 * @param ppMedium Medium reference in case this is simply a duplicate.
4673 *
4674 * @note Locks the media tree and media objects for reading.
4675 */
4676HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
4677 const Utf8Str &aLocation,
4678 Utf8Str &aConflict,
4679 ComObjPtr<Medium> *ppMedium)
4680{
4681 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
4682 AssertReturn(ppMedium, E_INVALIDARG);
4683
4684 aConflict.setNull();
4685 ppMedium->setNull();
4686
4687 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4688
4689 HRESULT rc = S_OK;
4690
4691 ComObjPtr<Medium> pMediumFound;
4692 const char *pcszType = NULL;
4693
4694 if (aId.isValid() && !aId.isZero())
4695 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4696 if (FAILED(rc) && !aLocation.isEmpty())
4697 rc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
4698 if (SUCCEEDED(rc))
4699 pcszType = tr("hard disk");
4700
4701 if (!pcszType)
4702 {
4703 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
4704 if (SUCCEEDED(rc))
4705 pcszType = tr("CD/DVD image");
4706 }
4707
4708 if (!pcszType)
4709 {
4710 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
4711 if (SUCCEEDED(rc))
4712 pcszType = tr("floppy image");
4713 }
4714
4715 if (pcszType && pMediumFound)
4716 {
4717 /* Note: no AutoCaller since bound to this */
4718 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
4719
4720 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
4721 Guid idFound = pMediumFound->i_getId();
4722
4723 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
4724 && (idFound == aId)
4725 )
4726 *ppMedium = pMediumFound;
4727
4728 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
4729 pcszType,
4730 strLocFound.c_str(),
4731 idFound.raw());
4732 }
4733
4734 return S_OK;
4735}
4736
4737/**
4738 * Checks whether the given UUID is already in use by one medium for the
4739 * given device type.
4740 *
4741 * @returns true if the UUID is already in use
4742 * fale otherwise
4743 * @param aId The UUID to check.
4744 * @param deviceType The device type the UUID is going to be checked for
4745 * conflicts.
4746 */
4747bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
4748{
4749 /* A zero UUID is invalid here, always claim that it is already used. */
4750 AssertReturn(!aId.isZero(), true);
4751
4752 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4753
4754 HRESULT rc = S_OK;
4755 bool fInUse = false;
4756
4757 ComObjPtr<Medium> pMediumFound;
4758
4759 switch (deviceType)
4760 {
4761 case DeviceType_HardDisk:
4762 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4763 break;
4764 case DeviceType_DVD:
4765 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4766 break;
4767 case DeviceType_Floppy:
4768 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4769 break;
4770 default:
4771 AssertMsgFailed(("Invalid device type %d\n", deviceType));
4772 }
4773
4774 if (SUCCEEDED(rc) && pMediumFound)
4775 fInUse = true;
4776
4777 return fInUse;
4778}
4779
4780/**
4781 * Called from Machine::prepareSaveSettings() when it has detected
4782 * that a machine has been renamed. Such renames will require
4783 * updating the global media registry during the
4784 * VirtualBox::saveSettings() that follows later.
4785*
4786 * When a machine is renamed, there may well be media (in particular,
4787 * diff images for snapshots) in the global registry that will need
4788 * to have their paths updated. Before 3.2, Machine::saveSettings
4789 * used to call VirtualBox::saveSettings implicitly, which was both
4790 * unintuitive and caused locking order problems. Now, we remember
4791 * such pending name changes with this method so that
4792 * VirtualBox::saveSettings() can process them properly.
4793 */
4794void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
4795 const Utf8Str &strNewConfigDir)
4796{
4797 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4798
4799 Data::PendingMachineRename pmr;
4800 pmr.strConfigDirOld = strOldConfigDir;
4801 pmr.strConfigDirNew = strNewConfigDir;
4802 m->llPendingMachineRenames.push_back(pmr);
4803}
4804
4805static DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4806
4807class SaveMediaRegistriesDesc : public ThreadTask
4808{
4809
4810public:
4811 SaveMediaRegistriesDesc()
4812 {
4813 m_strTaskName = "SaveMediaReg";
4814 }
4815 virtual ~SaveMediaRegistriesDesc(void) { }
4816
4817private:
4818 void handler()
4819 {
4820 try
4821 {
4822 fntSaveMediaRegistries(this);
4823 }
4824 catch(...)
4825 {
4826 LogRel(("Exception in the function fntSaveMediaRegistries()\n"));
4827 }
4828 }
4829
4830 MediaList llMedia;
4831 ComObjPtr<VirtualBox> pVirtualBox;
4832
4833 friend DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4834 friend void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4835 const Guid &uuidRegistry,
4836 const Utf8Str &strMachineFolder);
4837};
4838
4839DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser)
4840{
4841 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
4842 if (!pDesc)
4843 {
4844 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
4845 return VERR_INVALID_PARAMETER;
4846 }
4847
4848 for (MediaList::const_iterator it = pDesc->llMedia.begin();
4849 it != pDesc->llMedia.end();
4850 ++it)
4851 {
4852 Medium *pMedium = *it;
4853 pMedium->i_markRegistriesModified();
4854 }
4855
4856 pDesc->pVirtualBox->i_saveModifiedRegistries();
4857
4858 pDesc->llMedia.clear();
4859 pDesc->pVirtualBox.setNull();
4860
4861 return VINF_SUCCESS;
4862}
4863
4864/**
4865 * Goes through all known media (hard disks, floppies and DVDs) and saves
4866 * those into the given settings::MediaRegistry structures whose registry
4867 * ID match the given UUID.
4868 *
4869 * Before actually writing to the structures, all media paths (not just the
4870 * ones for the given registry) are updated if machines have been renamed
4871 * since the last call.
4872 *
4873 * This gets called from two contexts:
4874 *
4875 * -- VirtualBox::saveSettings() with the UUID of the global registry
4876 * (VirtualBox::Data.uuidRegistry); this will save those media
4877 * which had been loaded from the global registry or have been
4878 * attached to a "legacy" machine which can't save its own registry;
4879 *
4880 * -- Machine::saveSettings() with the UUID of a machine, if a medium
4881 * has been attached to a machine created with VirtualBox 4.0 or later.
4882 *
4883 * Media which have only been temporarily opened without having been
4884 * attached to a machine have a NULL registry UUID and therefore don't
4885 * get saved.
4886 *
4887 * This locks the media tree. Throws HRESULT on errors!
4888 *
4889 * @param mediaRegistry Settings structure to fill.
4890 * @param uuidRegistry The UUID of the media registry; either a machine UUID
4891 * (if machine registry) or the UUID of the global registry.
4892 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
4893 */
4894void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4895 const Guid &uuidRegistry,
4896 const Utf8Str &strMachineFolder)
4897{
4898 // lock all media for the following; use a write lock because we're
4899 // modifying the PendingMachineRenamesList, which is protected by this
4900 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4901
4902 // if a machine was renamed, then we'll need to refresh media paths
4903 if (m->llPendingMachineRenames.size())
4904 {
4905 // make a single list from the three media lists so we don't need three loops
4906 MediaList llAllMedia;
4907 // with hard disks, we must use the map, not the list, because the list only has base images
4908 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
4909 llAllMedia.push_back(it->second);
4910 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
4911 llAllMedia.push_back(*it);
4912 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
4913 llAllMedia.push_back(*it);
4914
4915 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
4916 for (MediaList::iterator it = llAllMedia.begin();
4917 it != llAllMedia.end();
4918 ++it)
4919 {
4920 Medium *pMedium = *it;
4921 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
4922 it2 != m->llPendingMachineRenames.end();
4923 ++it2)
4924 {
4925 const Data::PendingMachineRename &pmr = *it2;
4926 HRESULT rc = pMedium->i_updatePath(pmr.strConfigDirOld,
4927 pmr.strConfigDirNew);
4928 if (SUCCEEDED(rc))
4929 {
4930 // Remember which medium objects has been changed,
4931 // to trigger saving their registries later.
4932 pDesc->llMedia.push_back(pMedium);
4933 } else if (rc == VBOX_E_FILE_ERROR)
4934 /* nothing */;
4935 else
4936 AssertComRC(rc);
4937 }
4938 }
4939 // done, don't do it again until we have more machine renames
4940 m->llPendingMachineRenames.clear();
4941
4942 if (pDesc->llMedia.size())
4943 {
4944 // Handle the media registry saving in a separate thread, to
4945 // avoid giant locking problems and passing up the list many
4946 // levels up to whoever triggered saveSettings, as there are
4947 // lots of places which would need to handle saving more settings.
4948 pDesc->pVirtualBox = this;
4949
4950 //the function createThread() takes ownership of pDesc
4951 //so there is no need to use delete operator for pDesc
4952 //after calling this function
4953 HRESULT hr = pDesc->createThread();
4954 pDesc = NULL;
4955
4956 if (FAILED(hr))
4957 {
4958 // failure means that settings aren't saved, but there isn't
4959 // much we can do besides avoiding memory leaks
4960 LogRelFunc(("Failed to create thread for saving media registries (%Rhr)\n", hr));
4961 }
4962 }
4963 else
4964 delete pDesc;
4965 }
4966
4967 struct {
4968 MediaOList &llSource;
4969 settings::MediaList &llTarget;
4970 } s[] =
4971 {
4972 // hard disks
4973 { m->allHardDisks, mediaRegistry.llHardDisks },
4974 // CD/DVD images
4975 { m->allDVDImages, mediaRegistry.llDvdImages },
4976 // floppy images
4977 { m->allFloppyImages, mediaRegistry.llFloppyImages }
4978 };
4979
4980 HRESULT rc;
4981
4982 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
4983 {
4984 MediaOList &llSource = s[i].llSource;
4985 settings::MediaList &llTarget = s[i].llTarget;
4986 llTarget.clear();
4987 for (MediaList::const_iterator it = llSource.begin();
4988 it != llSource.end();
4989 ++it)
4990 {
4991 Medium *pMedium = *it;
4992 AutoCaller autoCaller(pMedium);
4993 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
4994 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4995
4996 if (pMedium->i_isInRegistry(uuidRegistry))
4997 {
4998 llTarget.push_back(settings::Medium::Empty);
4999 rc = pMedium->i_saveSettings(llTarget.back(), strMachineFolder); // this recurses into child hard disks
5000 if (FAILED(rc))
5001 {
5002 llTarget.pop_back();
5003 throw rc;
5004 }
5005 }
5006 }
5007 }
5008}
5009
5010/**
5011 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
5012 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
5013 * places internally when settings need saving.
5014 *
5015 * @note Caller must have locked the VirtualBox object for writing and must not hold any
5016 * other locks since this locks all kinds of member objects and trees temporarily,
5017 * which could cause conflicts.
5018 */
5019HRESULT VirtualBox::i_saveSettings()
5020{
5021 AutoCaller autoCaller(this);
5022 AssertComRCReturnRC(autoCaller.rc());
5023
5024 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5025 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
5026
5027 i_unmarkRegistryModified(i_getGlobalRegistryId());
5028
5029 HRESULT rc = S_OK;
5030
5031 try
5032 {
5033 // machines
5034 m->pMainConfigFile->llMachines.clear();
5035 {
5036 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5037 for (MachinesOList::iterator it = m->allMachines.begin();
5038 it != m->allMachines.end();
5039 ++it)
5040 {
5041 Machine *pMachine = *it;
5042 // save actual machine registry entry
5043 settings::MachineRegistryEntry mre;
5044 rc = pMachine->i_saveRegistryEntry(mre);
5045 m->pMainConfigFile->llMachines.push_back(mre);
5046 }
5047 }
5048
5049 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
5050 m->uuidMediaRegistry, // global media registry ID
5051 Utf8Str::Empty); // strMachineFolder
5052
5053 m->pMainConfigFile->llDhcpServers.clear();
5054 {
5055 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5056 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5057 it != m->allDHCPServers.end();
5058 ++it)
5059 {
5060 settings::DHCPServer d;
5061 rc = (*it)->i_saveSettings(d);
5062 if (FAILED(rc)) throw rc;
5063 m->pMainConfigFile->llDhcpServers.push_back(d);
5064 }
5065 }
5066
5067#ifdef VBOX_WITH_NAT_SERVICE
5068 /* Saving NAT Network configuration */
5069 m->pMainConfigFile->llNATNetworks.clear();
5070 {
5071 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5072 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
5073 it != m->allNATNetworks.end();
5074 ++it)
5075 {
5076 settings::NATNetwork n;
5077 rc = (*it)->i_saveSettings(n);
5078 if (FAILED(rc)) throw rc;
5079 m->pMainConfigFile->llNATNetworks.push_back(n);
5080 }
5081 }
5082#endif
5083
5084#ifdef VBOX_WITH_CLOUD_NET
5085 m->pMainConfigFile->llCloudNetworks.clear();
5086 {
5087 AutoReadLock cloudNetworkLock(m->allCloudNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5088 for (CloudNetworksOList::const_iterator it = m->allCloudNetworks.begin();
5089 it != m->allCloudNetworks.end();
5090 ++it)
5091 {
5092 settings::CloudNetwork n;
5093 rc = (*it)->i_saveSettings(n);
5094 if (FAILED(rc)) throw rc;
5095 m->pMainConfigFile->llCloudNetworks.push_back(n);
5096 }
5097 }
5098#endif /* VBOX_WITH_CLOUD_NET */
5099 // leave extra data alone, it's still in the config file
5100
5101 // host data (USB filters)
5102 rc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
5103 if (FAILED(rc)) throw rc;
5104
5105 rc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
5106 if (FAILED(rc)) throw rc;
5107
5108 // and write out the XML, still under the lock
5109 m->pMainConfigFile->write(m->strSettingsFilePath);
5110 }
5111 catch (HRESULT err)
5112 {
5113 /* we assume that error info is set by the thrower */
5114 rc = err;
5115 }
5116 catch (...)
5117 {
5118 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
5119 }
5120
5121 return rc;
5122}
5123
5124/**
5125 * Helper to register the machine.
5126 *
5127 * When called during VirtualBox startup, adds the given machine to the
5128 * collection of registered machines. Otherwise tries to mark the machine
5129 * as registered, and, if succeeded, adds it to the collection and
5130 * saves global settings.
5131 *
5132 * @note The caller must have added itself as a caller of the @a aMachine
5133 * object if calls this method not on VirtualBox startup.
5134 *
5135 * @param aMachine machine to register
5136 *
5137 * @note Locks objects!
5138 */
5139HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
5140{
5141 ComAssertRet(aMachine, E_INVALIDARG);
5142
5143 AutoCaller autoCaller(this);
5144 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5145
5146 HRESULT rc = S_OK;
5147
5148 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5149
5150 {
5151 ComObjPtr<Machine> pMachine;
5152 rc = i_findMachine(aMachine->i_getId(),
5153 true /* fPermitInaccessible */,
5154 false /* aDoSetError */,
5155 &pMachine);
5156 if (SUCCEEDED(rc))
5157 {
5158 /* sanity */
5159 AutoLimitedCaller machCaller(pMachine);
5160 AssertComRC(machCaller.rc());
5161
5162 return setError(E_INVALIDARG,
5163 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
5164 aMachine->i_getId().raw(),
5165 pMachine->i_getSettingsFileFull().c_str());
5166 }
5167
5168 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
5169 rc = S_OK;
5170 }
5171
5172 if (getObjectState().getState() != ObjectState::InInit)
5173 {
5174 rc = aMachine->i_prepareRegister();
5175 if (FAILED(rc)) return rc;
5176 }
5177
5178 /* add to the collection of registered machines */
5179 m->allMachines.addChild(aMachine);
5180
5181 if (getObjectState().getState() != ObjectState::InInit)
5182 rc = i_saveSettings();
5183
5184 return rc;
5185}
5186
5187/**
5188 * Remembers the given medium object by storing it in either the global
5189 * medium registry or a machine one.
5190 *
5191 * @note Caller must hold the media tree lock for writing; in addition, this
5192 * locks @a pMedium for reading
5193 *
5194 * @param pMedium Medium object to remember.
5195 * @param ppMedium Actually stored medium object. Can be different if due
5196 * to an unavoidable race there was a duplicate Medium object
5197 * created.
5198 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
5199 * lock, necessary to release it in the right spot.
5200 * @return
5201 */
5202HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
5203 ComObjPtr<Medium> *ppMedium,
5204 AutoWriteLock &mediaTreeLock)
5205{
5206 AssertReturn(pMedium != NULL, E_INVALIDARG);
5207 AssertReturn(ppMedium != NULL, E_INVALIDARG);
5208
5209 // caller must hold the media tree write lock
5210 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5211
5212 AutoCaller autoCaller(this);
5213 AssertComRCReturnRC(autoCaller.rc());
5214
5215 AutoCaller mediumCaller(pMedium);
5216 AssertComRCReturnRC(mediumCaller.rc());
5217
5218 bool fAddToGlobalRegistry = false;
5219 const char *pszDevType = NULL;
5220 Guid regId;
5221 ObjectsList<Medium> *pall = NULL;
5222 DeviceType_T devType;
5223 {
5224 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5225 devType = pMedium->i_getDeviceType();
5226
5227 if (!pMedium->i_getFirstRegistryMachineId(regId))
5228 fAddToGlobalRegistry = true;
5229 }
5230 switch (devType)
5231 {
5232 case DeviceType_HardDisk:
5233 pall = &m->allHardDisks;
5234 pszDevType = tr("hard disk");
5235 break;
5236 case DeviceType_DVD:
5237 pszDevType = tr("DVD image");
5238 pall = &m->allDVDImages;
5239 break;
5240 case DeviceType_Floppy:
5241 pszDevType = tr("floppy image");
5242 pall = &m->allFloppyImages;
5243 break;
5244 default:
5245 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
5246 }
5247
5248 Guid id;
5249 Utf8Str strLocationFull;
5250 ComObjPtr<Medium> pParent;
5251 {
5252 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5253 id = pMedium->i_getId();
5254 strLocationFull = pMedium->i_getLocationFull();
5255 pParent = pMedium->i_getParent();
5256 }
5257
5258 HRESULT rc;
5259
5260 Utf8Str strConflict;
5261 ComObjPtr<Medium> pDupMedium;
5262 rc = i_checkMediaForConflicts(id,
5263 strLocationFull,
5264 strConflict,
5265 &pDupMedium);
5266 if (FAILED(rc)) return rc;
5267
5268 if (pDupMedium.isNull())
5269 {
5270 if (strConflict.length())
5271 return setError(E_INVALIDARG,
5272 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
5273 pszDevType,
5274 strLocationFull.c_str(),
5275 id.raw(),
5276 strConflict.c_str(),
5277 m->strSettingsFilePath.c_str());
5278
5279 // add to the collection if it is a base medium
5280 if (pParent.isNull())
5281 pall->getList().push_back(pMedium);
5282
5283 // store all hard disks (even differencing images) in the map
5284 if (devType == DeviceType_HardDisk)
5285 m->mapHardDisks[id] = pMedium;
5286
5287 mediumCaller.release();
5288 mediaTreeLock.release();
5289 *ppMedium = pMedium;
5290 }
5291 else
5292 {
5293 // pMedium may be the last reference to the Medium object, and the
5294 // caller may have specified the same ComObjPtr as the output parameter.
5295 // In this case the assignment will uninit the object, and we must not
5296 // have a caller pending.
5297 mediumCaller.release();
5298 // release media tree lock, must not be held at uninit time.
5299 mediaTreeLock.release();
5300 // must not hold the media tree write lock any more
5301 Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5302 *ppMedium = pDupMedium;
5303 }
5304
5305 if (fAddToGlobalRegistry)
5306 {
5307 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5308 if (pMedium->i_addRegistry(m->uuidMediaRegistry))
5309 i_markRegistryModified(m->uuidMediaRegistry);
5310 }
5311
5312 // Restore the initial lock state, so that no unexpected lock changes are
5313 // done by this method, which would need adjustments everywhere.
5314 mediaTreeLock.acquire();
5315
5316 return rc;
5317}
5318
5319/**
5320 * Removes the given medium from the respective registry.
5321 *
5322 * @param pMedium Hard disk object to remove.
5323 *
5324 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
5325 */
5326HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
5327{
5328 AssertReturn(pMedium != NULL, E_INVALIDARG);
5329
5330 AutoCaller autoCaller(this);
5331 AssertComRCReturnRC(autoCaller.rc());
5332
5333 AutoCaller mediumCaller(pMedium);
5334 AssertComRCReturnRC(mediumCaller.rc());
5335
5336 // caller must hold the media tree write lock
5337 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5338
5339 Guid id;
5340 ComObjPtr<Medium> pParent;
5341 DeviceType_T devType;
5342 {
5343 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
5344 id = pMedium->i_getId();
5345 pParent = pMedium->i_getParent();
5346 devType = pMedium->i_getDeviceType();
5347 }
5348
5349 ObjectsList<Medium> *pall = NULL;
5350 switch (devType)
5351 {
5352 case DeviceType_HardDisk:
5353 pall = &m->allHardDisks;
5354 break;
5355 case DeviceType_DVD:
5356 pall = &m->allDVDImages;
5357 break;
5358 case DeviceType_Floppy:
5359 pall = &m->allFloppyImages;
5360 break;
5361 default:
5362 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
5363 }
5364
5365 // remove from the collection if it is a base medium
5366 if (pParent.isNull())
5367 pall->getList().remove(pMedium);
5368
5369 // remove all hard disks (even differencing images) from map
5370 if (devType == DeviceType_HardDisk)
5371 {
5372 size_t cnt = m->mapHardDisks.erase(id);
5373 Assert(cnt == 1);
5374 NOREF(cnt);
5375 }
5376
5377 return S_OK;
5378}
5379
5380/**
5381 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
5382 * with children appearing before their parents.
5383 * @param llMedia
5384 * @param pMedium
5385 */
5386void VirtualBox::i_pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
5387{
5388 // recurse first, then add ourselves; this way children end up on the
5389 // list before their parents
5390
5391 const MediaList &llChildren = pMedium->i_getChildren();
5392 for (MediaList::const_iterator it = llChildren.begin();
5393 it != llChildren.end();
5394 ++it)
5395 {
5396 Medium *pChild = *it;
5397 i_pushMediumToListWithChildren(llMedia, pChild);
5398 }
5399
5400 Log(("Pushing medium %RTuuid\n", pMedium->i_getId().raw()));
5401 llMedia.push_back(pMedium);
5402}
5403
5404/**
5405 * Unregisters all Medium objects which belong to the given machine registry.
5406 * Gets called from Machine::uninit() just before the machine object dies
5407 * and must only be called with a machine UUID as the registry ID.
5408 *
5409 * Locks the media tree.
5410 *
5411 * @param uuidMachine Medium registry ID (always a machine UUID)
5412 * @return
5413 */
5414HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
5415{
5416 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
5417
5418 LogFlowFuncEnter();
5419
5420 AutoCaller autoCaller(this);
5421 AssertComRCReturnRC(autoCaller.rc());
5422
5423 MediaList llMedia2Close;
5424
5425 {
5426 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5427
5428 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
5429 it != m->allHardDisks.getList().end();
5430 ++it)
5431 {
5432 ComObjPtr<Medium> pMedium = *it;
5433 AutoCaller medCaller(pMedium);
5434 if (FAILED(medCaller.rc())) return medCaller.rc();
5435 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
5436
5437 if (pMedium->i_isInRegistry(uuidMachine))
5438 // recursively with children first
5439 i_pushMediumToListWithChildren(llMedia2Close, pMedium);
5440 }
5441 }
5442
5443 for (MediaList::iterator it = llMedia2Close.begin();
5444 it != llMedia2Close.end();
5445 ++it)
5446 {
5447 ComObjPtr<Medium> pMedium = *it;
5448 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
5449 AutoCaller mac(pMedium);
5450 pMedium->i_close(mac);
5451 }
5452
5453 LogFlowFuncLeave();
5454
5455 return S_OK;
5456}
5457
5458/**
5459 * Removes the given machine object from the internal list of registered machines.
5460 * Called from Machine::Unregister().
5461 * @param pMachine
5462 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
5463 * @return
5464 */
5465HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
5466 const Guid &id)
5467{
5468 // remove from the collection of registered machines
5469 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5470 m->allMachines.removeChild(pMachine);
5471 // save the global registry
5472 HRESULT rc = i_saveSettings();
5473 alock.release();
5474
5475 /*
5476 * Now go over all known media and checks if they were registered in the
5477 * media registry of the given machine. Each such medium is then moved to
5478 * a different media registry to make sure it doesn't get lost since its
5479 * media registry is about to go away.
5480 *
5481 * This fixes the following use case: Image A.vdi of machine A is also used
5482 * by machine B, but registered in the media registry of machine A. If machine
5483 * A is deleted, A.vdi must be moved to the registry of B, or else B will
5484 * become inaccessible.
5485 */
5486 {
5487 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5488 // iterate over the list of *base* images
5489 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
5490 it != m->allHardDisks.getList().end();
5491 ++it)
5492 {
5493 ComObjPtr<Medium> &pMedium = *it;
5494 AutoCaller medCaller(pMedium);
5495 if (FAILED(medCaller.rc())) return medCaller.rc();
5496 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
5497
5498 if (pMedium->i_removeRegistryRecursive(id))
5499 {
5500 // machine ID was found in base medium's registry list:
5501 // move this base image and all its children to another registry then
5502 // 1) first, find a better registry to add things to
5503 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref();
5504 if (puuidBetter)
5505 {
5506 // 2) better registry found: then use that
5507 pMedium->i_addRegistryRecursive(*puuidBetter);
5508 // 3) and make sure the registry is saved below
5509 mlock.release();
5510 tlock.release();
5511 i_markRegistryModified(*puuidBetter);
5512 tlock.acquire();
5513 mlock.acquire();
5514 }
5515 }
5516 }
5517 }
5518
5519 i_saveModifiedRegistries();
5520
5521 /* fire an event */
5522 i_onMachineRegistered(id, FALSE);
5523
5524 return rc;
5525}
5526
5527/**
5528 * Marks the registry for @a uuid as modified, so that it's saved in a later
5529 * call to saveModifiedRegistries().
5530 *
5531 * @param uuid
5532 */
5533void VirtualBox::i_markRegistryModified(const Guid &uuid)
5534{
5535 if (uuid == i_getGlobalRegistryId())
5536 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
5537 else
5538 {
5539 ComObjPtr<Machine> pMachine;
5540 HRESULT rc = i_findMachine(uuid,
5541 false /* fPermitInaccessible */,
5542 false /* aSetError */,
5543 &pMachine);
5544 if (SUCCEEDED(rc))
5545 {
5546 AutoCaller machineCaller(pMachine);
5547 if (SUCCEEDED(machineCaller.rc()) && pMachine->i_isAccessible())
5548 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
5549 }
5550 }
5551}
5552
5553/**
5554 * Marks the registry for @a uuid as unmodified, so that it's not saved in
5555 * a later call to saveModifiedRegistries().
5556 *
5557 * @param uuid
5558 */
5559void VirtualBox::i_unmarkRegistryModified(const Guid &uuid)
5560{
5561 uint64_t uOld;
5562 if (uuid == i_getGlobalRegistryId())
5563 {
5564 for (;;)
5565 {
5566 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5567 if (!uOld)
5568 break;
5569 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5570 break;
5571 ASMNopPause();
5572 }
5573 }
5574 else
5575 {
5576 ComObjPtr<Machine> pMachine;
5577 HRESULT rc = i_findMachine(uuid,
5578 false /* fPermitInaccessible */,
5579 false /* aSetError */,
5580 &pMachine);
5581 if (SUCCEEDED(rc))
5582 {
5583 AutoCaller machineCaller(pMachine);
5584 if (SUCCEEDED(machineCaller.rc()))
5585 {
5586 for (;;)
5587 {
5588 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5589 if (!uOld)
5590 break;
5591 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5592 break;
5593 ASMNopPause();
5594 }
5595 }
5596 }
5597 }
5598}
5599
5600/**
5601 * Saves all settings files according to the modified flags in the Machine
5602 * objects and in the VirtualBox object.
5603 *
5604 * This locks machines and the VirtualBox object as necessary, so better not
5605 * hold any locks before calling this.
5606 *
5607 * @return
5608 */
5609void VirtualBox::i_saveModifiedRegistries()
5610{
5611 HRESULT rc = S_OK;
5612 bool fNeedsGlobalSettings = false;
5613 uint64_t uOld;
5614
5615 {
5616 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5617 for (MachinesOList::iterator it = m->allMachines.begin();
5618 it != m->allMachines.end();
5619 ++it)
5620 {
5621 const ComObjPtr<Machine> &pMachine = *it;
5622
5623 for (;;)
5624 {
5625 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5626 if (!uOld)
5627 break;
5628 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5629 break;
5630 ASMNopPause();
5631 }
5632 if (uOld)
5633 {
5634 AutoCaller autoCaller(pMachine);
5635 if (FAILED(autoCaller.rc()))
5636 continue;
5637 /* object is already dead, no point in saving settings */
5638 if (getObjectState().getState() != ObjectState::Ready)
5639 continue;
5640 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
5641 rc = pMachine->i_saveSettings(&fNeedsGlobalSettings,
5642 Machine::SaveS_Force); // caller said save, so stop arguing
5643 }
5644 }
5645 }
5646
5647 for (;;)
5648 {
5649 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5650 if (!uOld)
5651 break;
5652 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5653 break;
5654 ASMNopPause();
5655 }
5656 if (uOld || fNeedsGlobalSettings)
5657 {
5658 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5659 rc = i_saveSettings();
5660 }
5661 NOREF(rc); /* XXX */
5662}
5663
5664
5665/* static */
5666const com::Utf8Str &VirtualBox::i_getVersionNormalized()
5667{
5668 return sVersionNormalized;
5669}
5670
5671/**
5672 * Checks if the path to the specified file exists, according to the path
5673 * information present in the file name. Optionally the path is created.
5674 *
5675 * Note that the given file name must contain the full path otherwise the
5676 * extracted relative path will be created based on the current working
5677 * directory which is normally unknown.
5678 *
5679 * @param strFileName Full file name which path is checked/created.
5680 * @param fCreate Flag if the path should be created if it doesn't exist.
5681 *
5682 * @return Extended error information on failure to check/create the path.
5683 */
5684/* static */
5685HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
5686{
5687 Utf8Str strDir(strFileName);
5688 strDir.stripFilename();
5689 if (!RTDirExists(strDir.c_str()))
5690 {
5691 if (fCreate)
5692 {
5693 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
5694 if (RT_FAILURE(vrc))
5695 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, vrc,
5696 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
5697 strDir.c_str(),
5698 vrc));
5699 }
5700 else
5701 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, VERR_FILE_NOT_FOUND,
5702 Utf8StrFmt(tr("Directory '%s' does not exist"), strDir.c_str()));
5703 }
5704
5705 return S_OK;
5706}
5707
5708const Utf8Str& VirtualBox::i_settingsFilePath()
5709{
5710 return m->strSettingsFilePath;
5711}
5712
5713/**
5714 * Returns the lock handle which protects the machines list. As opposed
5715 * to version 3.1 and earlier, these lists are no longer protected by the
5716 * VirtualBox lock, but by this more specialized lock. Mind the locking
5717 * order: always request this lock after the VirtualBox object lock but
5718 * before the locks of any machine object. See AutoLock.h.
5719 */
5720RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
5721{
5722 return m->lockMachines;
5723}
5724
5725/**
5726 * Returns the lock handle which protects the media trees (hard disks,
5727 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
5728 * are no longer protected by the VirtualBox lock, but by this more
5729 * specialized lock. Mind the locking order: always request this lock
5730 * after the VirtualBox object lock but before the locks of the media
5731 * objects contained in these lists. See AutoLock.h.
5732 */
5733RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
5734{
5735 return m->lockMedia;
5736}
5737
5738/**
5739 * Thread function that handles custom events posted using #i_postEvent().
5740 */
5741// static
5742DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
5743{
5744 LogFlowFuncEnter();
5745
5746 AssertReturn(pvUser, VERR_INVALID_POINTER);
5747
5748 HRESULT hr = com::Initialize();
5749 if (FAILED(hr))
5750 return VERR_COM_UNEXPECTED;
5751
5752 int rc = VINF_SUCCESS;
5753
5754 try
5755 {
5756 /* Create an event queue for the current thread. */
5757 EventQueue *pEventQueue = new EventQueue();
5758 AssertPtr(pEventQueue);
5759
5760 /* Return the queue to the one who created this thread. */
5761 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
5762
5763 /* signal that we're ready. */
5764 RTThreadUserSignal(thread);
5765
5766 /*
5767 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
5768 * we must not stop processing events and delete the pEventQueue object. This must
5769 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
5770 * See @bugref{5724}.
5771 */
5772 for (;;)
5773 {
5774 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
5775 if (rc == VERR_INTERRUPTED)
5776 {
5777 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
5778 rc = VINF_SUCCESS; /* Set success when exiting. */
5779 break;
5780 }
5781 }
5782
5783 delete pEventQueue;
5784 }
5785 catch (std::bad_alloc &ba)
5786 {
5787 rc = VERR_NO_MEMORY;
5788 NOREF(ba);
5789 }
5790
5791 com::Shutdown();
5792
5793 LogFlowFuncLeaveRC(rc);
5794 return rc;
5795}
5796
5797
5798////////////////////////////////////////////////////////////////////////////////
5799
5800/**
5801 * Prepare the event using the overwritten #prepareEventDesc method and fire.
5802 *
5803 * @note Locks the managed VirtualBox object for reading but leaves the lock
5804 * before iterating over callbacks and calling their methods.
5805 */
5806void *VirtualBox::CallbackEvent::handler()
5807{
5808 if (!mVirtualBox)
5809 return NULL;
5810
5811 AutoCaller autoCaller(mVirtualBox);
5812 if (!autoCaller.isOk())
5813 {
5814 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
5815 mVirtualBox->getObjectState().getState()));
5816 /* We don't need mVirtualBox any more, so release it */
5817 mVirtualBox = NULL;
5818 return NULL;
5819 }
5820
5821 {
5822 VBoxEventDesc evDesc;
5823 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
5824
5825 evDesc.fire(/* don't wait for delivery */0);
5826 }
5827
5828 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
5829 return NULL;
5830}
5831
5832//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
5833//{
5834// return E_NOTIMPL;
5835//}
5836
5837HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
5838 ComPtr<IDHCPServer> &aServer)
5839{
5840 ComObjPtr<DHCPServer> dhcpServer;
5841 dhcpServer.createObject();
5842 HRESULT rc = dhcpServer->init(this, aName);
5843 if (FAILED(rc)) return rc;
5844
5845 rc = i_registerDHCPServer(dhcpServer, true);
5846 if (FAILED(rc)) return rc;
5847
5848 dhcpServer.queryInterfaceTo(aServer.asOutParam());
5849
5850 return rc;
5851}
5852
5853HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
5854 ComPtr<IDHCPServer> &aServer)
5855{
5856 HRESULT rc = S_OK;
5857 ComPtr<DHCPServer> found;
5858
5859 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5860
5861 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5862 it != m->allDHCPServers.end();
5863 ++it)
5864 {
5865 Bstr bstrNetworkName;
5866 rc = (*it)->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
5867 if (FAILED(rc)) return rc;
5868
5869 if (Utf8Str(bstrNetworkName) == aName)
5870 {
5871 found = *it;
5872 break;
5873 }
5874 }
5875
5876 if (!found)
5877 return E_INVALIDARG;
5878
5879 rc = found.queryInterfaceTo(aServer.asOutParam());
5880
5881 return rc;
5882}
5883
5884HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
5885{
5886 IDHCPServer *aP = aServer;
5887
5888 HRESULT rc = i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
5889
5890 return rc;
5891}
5892
5893/**
5894 * Remembers the given DHCP server in the settings.
5895 *
5896 * @param aDHCPServer DHCP server object to remember.
5897 * @param aSaveSettings @c true to save settings to disk (default).
5898 *
5899 * When @a aSaveSettings is @c true, this operation may fail because of the
5900 * failed #i_saveSettings() method it calls. In this case, the dhcp server object
5901 * will not be remembered. It is therefore the responsibility of the caller to
5902 * call this method as the last step of some action that requires registration
5903 * in order to make sure that only fully functional dhcp server objects get
5904 * registered.
5905 *
5906 * @note Locks this object for writing and @a aDHCPServer for reading.
5907 */
5908HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
5909 bool aSaveSettings /*= true*/)
5910{
5911 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5912
5913 AutoCaller autoCaller(this);
5914 AssertComRCReturnRC(autoCaller.rc());
5915
5916 // Acquire a lock on the VirtualBox object early to avoid lock order issues
5917 // when we call i_saveSettings() later on.
5918 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5919 // need it below, in findDHCPServerByNetworkName (reading) and in
5920 // m->allDHCPServers.addChild, so need to get it here to avoid lock
5921 // order trouble with dhcpServerCaller
5922 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5923
5924 AutoCaller dhcpServerCaller(aDHCPServer);
5925 AssertComRCReturnRC(dhcpServerCaller.rc());
5926
5927 Bstr bstrNetworkName;
5928 HRESULT rc = S_OK;
5929 rc = aDHCPServer->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
5930 if (FAILED(rc)) return rc;
5931
5932 ComPtr<IDHCPServer> existing;
5933 rc = findDHCPServerByNetworkName(Utf8Str(bstrNetworkName), existing);
5934 if (SUCCEEDED(rc))
5935 return E_INVALIDARG;
5936 rc = S_OK;
5937
5938 m->allDHCPServers.addChild(aDHCPServer);
5939 // we need to release the list lock before we attempt to acquire locks
5940 // on other objects in i_saveSettings (see @bugref{7500})
5941 alock.release();
5942
5943 if (aSaveSettings)
5944 {
5945 // we acquired the lock on 'this' earlier to avoid lock order issues
5946 rc = i_saveSettings();
5947
5948 if (FAILED(rc))
5949 {
5950 alock.acquire();
5951 m->allDHCPServers.removeChild(aDHCPServer);
5952 }
5953 }
5954
5955 return rc;
5956}
5957
5958/**
5959 * Removes the given DHCP server from the settings.
5960 *
5961 * @param aDHCPServer DHCP server object to remove.
5962 *
5963 * This operation may fail because of the failed #i_saveSettings() method it
5964 * calls. In this case, the DHCP server will NOT be removed from the settings
5965 * when this method returns.
5966 *
5967 * @note Locks this object for writing.
5968 */
5969HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
5970{
5971 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5972
5973 AutoCaller autoCaller(this);
5974 AssertComRCReturnRC(autoCaller.rc());
5975
5976 AutoCaller dhcpServerCaller(aDHCPServer);
5977 AssertComRCReturnRC(dhcpServerCaller.rc());
5978
5979 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5980 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5981 m->allDHCPServers.removeChild(aDHCPServer);
5982 // we need to release the list lock before we attempt to acquire locks
5983 // on other objects in i_saveSettings (see @bugref{7500})
5984 alock.release();
5985
5986 HRESULT rc = i_saveSettings();
5987
5988 // undo the changes if we failed to save them
5989 if (FAILED(rc))
5990 {
5991 alock.acquire();
5992 m->allDHCPServers.addChild(aDHCPServer);
5993 }
5994
5995 return rc;
5996}
5997
5998
5999/**
6000 * NAT Network
6001 */
6002HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
6003 ComPtr<INATNetwork> &aNetwork)
6004{
6005#ifdef VBOX_WITH_NAT_SERVICE
6006 ComObjPtr<NATNetwork> natNetwork;
6007 natNetwork.createObject();
6008 HRESULT rc = natNetwork->init(this, aNetworkName);
6009 if (FAILED(rc)) return rc;
6010
6011 rc = i_registerNATNetwork(natNetwork, true);
6012 if (FAILED(rc)) return rc;
6013
6014 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
6015
6016 fireNATNetworkCreationDeletionEvent(m->pEventSource, Bstr(aNetworkName).raw(), TRUE);
6017
6018 return rc;
6019#else
6020 NOREF(aNetworkName);
6021 NOREF(aNetwork);
6022 return E_NOTIMPL;
6023#endif
6024}
6025
6026HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
6027 ComPtr<INATNetwork> &aNetwork)
6028{
6029#ifdef VBOX_WITH_NAT_SERVICE
6030
6031 HRESULT rc = S_OK;
6032 ComPtr<NATNetwork> found;
6033
6034 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
6035
6036 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
6037 it != m->allNATNetworks.end();
6038 ++it)
6039 {
6040 Bstr bstrNATNetworkName;
6041 rc = (*it)->COMGETTER(NetworkName)(bstrNATNetworkName.asOutParam());
6042 if (FAILED(rc)) return rc;
6043
6044 if (Utf8Str(bstrNATNetworkName) == aNetworkName)
6045 {
6046 found = *it;
6047 break;
6048 }
6049 }
6050
6051 if (!found)
6052 return E_INVALIDARG;
6053 found.queryInterfaceTo(aNetwork.asOutParam());
6054 return rc;
6055#else
6056 NOREF(aNetworkName);
6057 NOREF(aNetwork);
6058 return E_NOTIMPL;
6059#endif
6060}
6061
6062HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
6063{
6064#ifdef VBOX_WITH_NAT_SERVICE
6065 Bstr name;
6066 HRESULT rc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
6067 if (FAILED(rc))
6068 return rc;
6069 INATNetwork *p = aNetwork;
6070 NATNetwork *network = static_cast<NATNetwork *>(p);
6071 rc = i_unregisterNATNetwork(network, true);
6072 fireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
6073 return rc;
6074#else
6075 NOREF(aNetwork);
6076 return E_NOTIMPL;
6077#endif
6078
6079}
6080/**
6081 * Remembers the given NAT network in the settings.
6082 *
6083 * @param aNATNetwork NAT Network object to remember.
6084 * @param aSaveSettings @c true to save settings to disk (default).
6085 *
6086 *
6087 * @note Locks this object for writing and @a aNATNetwork for reading.
6088 */
6089HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
6090 bool aSaveSettings /*= true*/)
6091{
6092#ifdef VBOX_WITH_NAT_SERVICE
6093 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
6094
6095 AutoCaller autoCaller(this);
6096 AssertComRCReturnRC(autoCaller.rc());
6097
6098 AutoCaller natNetworkCaller(aNATNetwork);
6099 AssertComRCReturnRC(natNetworkCaller.rc());
6100
6101 Bstr name;
6102 HRESULT rc;
6103 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
6104 AssertComRCReturnRC(rc);
6105
6106 /* returned value isn't 0 and aSaveSettings is true
6107 * means that we create duplicate, otherwise we just load settings.
6108 */
6109 if ( sNatNetworkNameToRefCount[name]
6110 && aSaveSettings)
6111 AssertComRCReturnRC(E_INVALIDARG);
6112
6113 rc = S_OK;
6114
6115 sNatNetworkNameToRefCount[name] = 0;
6116
6117 m->allNATNetworks.addChild(aNATNetwork);
6118
6119 if (aSaveSettings)
6120 {
6121 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6122 rc = i_saveSettings();
6123 vboxLock.release();
6124
6125 if (FAILED(rc))
6126 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
6127 }
6128
6129 return rc;
6130#else
6131 NOREF(aNATNetwork);
6132 NOREF(aSaveSettings);
6133 /* No panic please (silently ignore) */
6134 return S_OK;
6135#endif
6136}
6137
6138/**
6139 * Removes the given NAT network from the settings.
6140 *
6141 * @param aNATNetwork NAT network object to remove.
6142 * @param aSaveSettings @c true to save settings to disk (default).
6143 *
6144 * When @a aSaveSettings is @c true, this operation may fail because of the
6145 * failed #i_saveSettings() method it calls. In this case, the DHCP server
6146 * will NOT be removed from the settingsi when this method returns.
6147 *
6148 * @note Locks this object for writing.
6149 */
6150HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
6151 bool aSaveSettings /*= true*/)
6152{
6153#ifdef VBOX_WITH_NAT_SERVICE
6154 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
6155
6156 AutoCaller autoCaller(this);
6157 AssertComRCReturnRC(autoCaller.rc());
6158
6159 AutoCaller natNetworkCaller(aNATNetwork);
6160 AssertComRCReturnRC(natNetworkCaller.rc());
6161
6162 Bstr name;
6163 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
6164 /* Hm, there're still running clients. */
6165 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
6166 AssertComRCReturnRC(E_INVALIDARG);
6167
6168 m->allNATNetworks.removeChild(aNATNetwork);
6169
6170 if (aSaveSettings)
6171 {
6172 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
6173 rc = i_saveSettings();
6174 vboxLock.release();
6175
6176 if (FAILED(rc))
6177 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
6178 }
6179
6180 return rc;
6181#else
6182 NOREF(aNATNetwork);
6183 NOREF(aSaveSettings);
6184 return E_NOTIMPL;
6185#endif
6186}
6187
6188
6189#ifdef RT_OS_WINDOWS
6190#include <psapi.h>
6191
6192/**
6193 * Report versions of installed drivers to release log.
6194 */
6195void VirtualBox::i_reportDriverVersions()
6196{
6197 /** @todo r=klaus this code is very confusing, as it uses TCHAR (and
6198 * randomly also _TCHAR, which sounds to me like asking for trouble),
6199 * the "sz" variable prefix but "%ls" for the format string - so the whole
6200 * thing is better compiled with UNICODE and _UNICODE defined. Would be
6201 * far easier to read if it would be coded explicitly for the unicode
6202 * case, as it won't work otherwise. */
6203 DWORD err;
6204 HRESULT hrc;
6205 LPVOID aDrivers[1024];
6206 LPVOID *pDrivers = aDrivers;
6207 UINT cNeeded = 0;
6208 TCHAR szSystemRoot[MAX_PATH];
6209 TCHAR *pszSystemRoot = szSystemRoot;
6210 LPVOID pVerInfo = NULL;
6211 DWORD cbVerInfo = 0;
6212
6213 do
6214 {
6215 cNeeded = GetWindowsDirectory(szSystemRoot, RT_ELEMENTS(szSystemRoot));
6216 if (cNeeded == 0)
6217 {
6218 err = GetLastError();
6219 hrc = HRESULT_FROM_WIN32(err);
6220 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
6221 hrc, hrc, err));
6222 break;
6223 }
6224 else if (cNeeded > RT_ELEMENTS(szSystemRoot))
6225 {
6226 /* The buffer is too small, allocate big one. */
6227 pszSystemRoot = (TCHAR *)RTMemTmpAlloc(cNeeded * sizeof(_TCHAR));
6228 if (!pszSystemRoot)
6229 {
6230 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cNeeded));
6231 break;
6232 }
6233 if (GetWindowsDirectory(pszSystemRoot, cNeeded) == 0)
6234 {
6235 err = GetLastError();
6236 hrc = HRESULT_FROM_WIN32(err);
6237 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
6238 hrc, hrc, err));
6239 break;
6240 }
6241 }
6242
6243 DWORD cbNeeded = 0;
6244 if (!EnumDeviceDrivers(aDrivers, sizeof(aDrivers), &cbNeeded) || cbNeeded > sizeof(aDrivers))
6245 {
6246 pDrivers = (LPVOID *)RTMemTmpAlloc(cbNeeded);
6247 if (!EnumDeviceDrivers(pDrivers, cbNeeded, &cbNeeded))
6248 {
6249 err = GetLastError();
6250 hrc = HRESULT_FROM_WIN32(err);
6251 AssertLogRelMsgFailed(("EnumDeviceDrivers failed, hr=%Rhrc (0x%x) err=%u\n",
6252 hrc, hrc, err));
6253 break;
6254 }
6255 }
6256
6257 LogRel(("Installed Drivers:\n"));
6258
6259 TCHAR szDriver[1024];
6260 int cDrivers = cbNeeded / sizeof(pDrivers[0]);
6261 for (int i = 0; i < cDrivers; i++)
6262 {
6263 if (GetDeviceDriverBaseName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
6264 {
6265 if (_tcsnicmp(TEXT("vbox"), szDriver, 4))
6266 continue;
6267 }
6268 else
6269 continue;
6270 if (GetDeviceDriverFileName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
6271 {
6272 _TCHAR szTmpDrv[1024];
6273 _TCHAR *pszDrv = szDriver;
6274 if (!_tcsncmp(TEXT("\\SystemRoot"), szDriver, 11))
6275 {
6276 _tcscpy_s(szTmpDrv, pszSystemRoot);
6277 _tcsncat_s(szTmpDrv, szDriver + 11, sizeof(szTmpDrv) / sizeof(szTmpDrv[0]) - _tclen(pszSystemRoot));
6278 pszDrv = szTmpDrv;
6279 }
6280 else if (!_tcsncmp(TEXT("\\??\\"), szDriver, 4))
6281 pszDrv = szDriver + 4;
6282
6283 /* Allocate a buffer for version info. Reuse if large enough. */
6284 DWORD cbNewVerInfo = GetFileVersionInfoSize(pszDrv, NULL);
6285 if (cbNewVerInfo > cbVerInfo)
6286 {
6287 if (pVerInfo)
6288 RTMemTmpFree(pVerInfo);
6289 cbVerInfo = cbNewVerInfo;
6290 pVerInfo = RTMemTmpAlloc(cbVerInfo);
6291 if (!pVerInfo)
6292 {
6293 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cbVerInfo));
6294 break;
6295 }
6296 }
6297
6298 if (GetFileVersionInfo(pszDrv, NULL, cbVerInfo, pVerInfo))
6299 {
6300 UINT cbSize = 0;
6301 LPBYTE lpBuffer = NULL;
6302 if (VerQueryValue(pVerInfo, TEXT("\\"), (VOID FAR* FAR*)&lpBuffer, &cbSize))
6303 {
6304 if (cbSize)
6305 {
6306 VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
6307 if (pFileInfo->dwSignature == 0xfeef04bd)
6308 {
6309 LogRel((" %ls (Version: %d.%d.%d.%d)\n", pszDrv,
6310 (pFileInfo->dwFileVersionMS >> 16) & 0xffff,
6311 (pFileInfo->dwFileVersionMS >> 0) & 0xffff,
6312 (pFileInfo->dwFileVersionLS >> 16) & 0xffff,
6313 (pFileInfo->dwFileVersionLS >> 0) & 0xffff));
6314 }
6315 }
6316 }
6317 }
6318 }
6319 }
6320
6321 }
6322 while (0);
6323
6324 if (pVerInfo)
6325 RTMemTmpFree(pVerInfo);
6326
6327 if (pDrivers != aDrivers)
6328 RTMemTmpFree(pDrivers);
6329
6330 if (pszSystemRoot != szSystemRoot)
6331 RTMemTmpFree(pszSystemRoot);
6332}
6333#else /* !RT_OS_WINDOWS */
6334void VirtualBox::i_reportDriverVersions(void)
6335{
6336}
6337#endif /* !RT_OS_WINDOWS */
6338
6339#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
6340
6341# include <psapi.h> /* for GetProcessImageFileNameW */
6342
6343/**
6344 * Callout from the wrapper.
6345 */
6346void VirtualBox::i_callHook(const char *a_pszFunction)
6347{
6348 RT_NOREF(a_pszFunction);
6349
6350 /*
6351 * Let'see figure out who is calling.
6352 * Note! Requires Vista+, so skip this entirely on older systems.
6353 */
6354 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
6355 {
6356 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
6357 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
6358 if ( rcRpc == RPC_S_OK
6359 && CallAttribs.ClientPID != 0)
6360 {
6361 RTPROCESS const pidClient = (RTPROCESS)(uintptr_t)CallAttribs.ClientPID;
6362 if (pidClient != RTProcSelf())
6363 {
6364 /** @todo LogRel2 later: */
6365 LogRel(("i_callHook: %Rfn [ClientPID=%#zx/%zu IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6366 a_pszFunction, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
6367 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6368 &CallAttribs.InterfaceUuid));
6369
6370 /*
6371 * Do we know this client PID already?
6372 */
6373 RTCritSectRwEnterShared(&m->WatcherCritSect);
6374 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(pidClient);
6375 if (It != m->WatchedProcesses.end())
6376 RTCritSectRwLeaveShared(&m->WatcherCritSect); /* Known process, nothing to do. */
6377 else
6378 {
6379 /* This is a new client process, start watching it. */
6380 RTCritSectRwLeaveShared(&m->WatcherCritSect);
6381 i_watchClientProcess(pidClient, a_pszFunction);
6382 }
6383 }
6384 }
6385 else
6386 LogRel(("i_callHook: %Rfn - rcRpc=%#x ClientPID=%#zx/%zu !! [IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6387 a_pszFunction, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
6388 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6389 &CallAttribs.InterfaceUuid));
6390 }
6391}
6392
6393
6394/**
6395 * Wathces @a a_pidClient for termination.
6396 *
6397 * @returns true if successfully enabled watching of it, false if not.
6398 * @param a_pidClient The PID to watch.
6399 * @param a_pszFunction The function we which we detected the client in.
6400 */
6401bool VirtualBox::i_watchClientProcess(RTPROCESS a_pidClient, const char *a_pszFunction)
6402{
6403 RT_NOREF_PV(a_pszFunction);
6404
6405 /*
6406 * Open the client process.
6407 */
6408 HANDLE hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE /*fInherit*/, a_pidClient);
6409 if (hClient == NULL)
6410 hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE , a_pidClient);
6411 if (hClient == NULL)
6412 hClient = OpenProcess(SYNCHRONIZE, FALSE , a_pidClient);
6413 AssertLogRelMsgReturn(hClient != NULL, ("pidClient=%d (%#x) err=%d\n", a_pidClient, a_pidClient, GetLastError()),
6414 m->fWatcherIsReliable = false);
6415
6416 /*
6417 * Create a new watcher structure and try add it to the map.
6418 */
6419 bool fRet = true;
6420 WatchedClientProcess *pWatched = new (std::nothrow) WatchedClientProcess(a_pidClient, hClient);
6421 if (pWatched)
6422 {
6423 RTCritSectRwEnterExcl(&m->WatcherCritSect);
6424
6425 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(a_pidClient);
6426 if (It == m->WatchedProcesses.end())
6427 {
6428 try
6429 {
6430 m->WatchedProcesses.insert(WatchedClientProcessMap::value_type(a_pidClient, pWatched));
6431 }
6432 catch (std::bad_alloc &)
6433 {
6434 fRet = false;
6435 }
6436 if (fRet)
6437 {
6438 /*
6439 * Schedule it on a watcher thread.
6440 */
6441 /** @todo later. */
6442 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6443 }
6444 else
6445 {
6446 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6447 delete pWatched;
6448 LogRel(("VirtualBox::i_watchClientProcess: out of memory inserting into client map!\n"));
6449 }
6450 }
6451 else
6452 {
6453 /*
6454 * Someone raced us here, we lost.
6455 */
6456 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
6457 delete pWatched;
6458 }
6459 }
6460 else
6461 {
6462 LogRel(("VirtualBox::i_watchClientProcess: out of memory!\n"));
6463 CloseHandle(hClient);
6464 m->fWatcherIsReliable = fRet = false;
6465 }
6466 return fRet;
6467}
6468
6469
6470/** Logs the RPC caller info to the release log. */
6471/*static*/ void VirtualBox::i_logCaller(const char *a_pszFormat, ...)
6472{
6473 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
6474 {
6475 char szTmp[80];
6476 va_list va;
6477 va_start(va, a_pszFormat);
6478 RTStrPrintfV(szTmp, sizeof(szTmp), a_pszFormat, va);
6479 va_end(va);
6480
6481 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
6482 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
6483
6484 RTUTF16 wszProcName[256];
6485 wszProcName[0] = '\0';
6486 if (rcRpc == 0 && CallAttribs.ClientPID != 0)
6487 {
6488 HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)(uintptr_t)CallAttribs.ClientPID);
6489 if (hProcess)
6490 {
6491 RT_ZERO(wszProcName);
6492 GetProcessImageFileNameW(hProcess, wszProcName, RT_ELEMENTS(wszProcName) - 1);
6493 CloseHandle(hProcess);
6494 }
6495 }
6496 LogRel(("%s [rcRpc=%#x ClientPID=%#zx/%zu (%ls) IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
6497 szTmp, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, wszProcName, CallAttribs.IsClientLocal,
6498 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
6499 &CallAttribs.InterfaceUuid));
6500 }
6501}
6502
6503#endif /* RT_OS_WINDOWS && VBOXSVC_WITH_CLIENT_WATCHER */
6504
6505
6506/* 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