VirtualBox

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

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

Main: Try harder using the Utf8Str versions of the event stuff where possible. bugref:9790

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