VirtualBox

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

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

OCI: (bugref:9469) cloud network integration multiple targets and configuration support (enabled in Config.kmk).

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

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