VirtualBox

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

Last change on this file since 79305 was 79217, checked in by vboxsync, 6 years ago

Main: bugref:6913: Changed the order of the IMediumRegisterEvents being generated during open existing VM

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

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