VirtualBox

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

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

Main/DHCPServer+NatNetwork+VirtualBox+Console: Remove old DHCP methods, attributes and interfaces, plus eliminate useless parameters from NATNetwork and DHCPServer Start methods. Additionally a few fixes to the DTD (and correcting some XML goofs in VirtualBox.xidl). More reserved attributes for the not yet implemented ICloudNetwork.

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

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