VirtualBox

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

Last change on this file since 76815 was 76592, checked in by vboxsync, 6 years ago

Main: Don't use Logging.h.

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