VirtualBox

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

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

Main/IVirtualBox::APIVersion: On second though, always include the build number in the build revision, that'll make it more useful.

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