VirtualBox

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

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

VBoxSVC/VirtualBoxImpl.cpp: update @todo from r140816. bugref:9841

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