VirtualBox

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

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

Shared Clipboard/URI: Update.

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