VirtualBox

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

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

doc/manual,Main,Frontends: API changes in preparation for full VM encryption, guarded by VBOX_WITH_FULL_VM_ENCRYPTION (disabled by default) and returning a not supported error for now, bugref:9955

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