VirtualBox

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

Last change on this file since 92176 was 92176, checked in by vboxsync, 4 years ago

Main/VirtualBox: Few comment fixes (there is no VirtualBox::saveSettings for many years) and small whitespace adjustment

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