VirtualBox

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

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

Main: Guest Properties: ​bugref:10185 post-review fixes.

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

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