VirtualBox

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

Last change on this file since 92154 was 91743, checked in by vboxsync, 3 years ago

Main/Machine: Release lock while waiting in Machine::i_ensureNoStateDependencies. Needs passing the lock from the caller (and a bit of multiple lock untangling). Regression introduced in r76471. bugref:10121

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

© 2023 Oracle
ContactPrivacy policyTerms of Use