VirtualBox

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

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

Main/Update check: Big overhaul of the API and functionality.

  • Now uses VBOX_WITH_UPDATE_AGENT to entirely disable the feature (enabled by default).
  • Main: Uses new (more abstract) API as proposed in the latest UML docs.
  • Main: Added support for several events.
  • Main: Added support for update severities, order and dependencies (all optional).
  • Settings/XML: Now has own "Updates" branch to also cover other updatable components (later); not part of the system properties anymore.
  • Prepared for GuestAdditions and ExtPack updates.
  • FE/Qt: Adapted to new API.
  • FE/VBoxManage: Adapted to new API; uses more uniform (common) synopsis "modify" and "list" for modifying and listing (showing) update settings.
  • Docs: Fixed various typos, extended documentation.

Work in progress. bugref:7983

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

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