VirtualBox

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

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

IPRT,*: Cleaning up RTPathAbsExEx, renaming it to RTPathAbsEx and removing dead code. bugref:9172

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 188.4 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 78098 2019-04-10 15:51:59Z 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.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_MAIN_VIRTUALBOX
19#include <iprt/asm.h>
20#include <iprt/base64.h>
21#include <iprt/buildconfig.h>
22#include <iprt/cpp/utils.h>
23#include <iprt/dir.h>
24#include <iprt/env.h>
25#include <iprt/file.h>
26#include <iprt/path.h>
27#include <iprt/process.h>
28#include <iprt/rand.h>
29#include <iprt/sha.h>
30#include <iprt/string.h>
31#include <iprt/stream.h>
32#include <iprt/system.h>
33#include <iprt/thread.h>
34#include <iprt/uuid.h>
35#include <iprt/cpp/xml.h>
36#include <iprt/ctype.h>
37
38#include <VBox/com/com.h>
39#include <VBox/com/array.h>
40#include "VBox/com/EventQueue.h"
41#include "VBox/com/MultiResult.h"
42
43#include <VBox/err.h>
44#include <VBox/param.h>
45#include <VBox/settings.h>
46#include <VBox/version.h>
47
48#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 Log1WarningFunc(("Someone vetoed! Change refused%s%ls\n", sep, error.raw()));
2183 return setError(E_ACCESSDENIED,
2184 tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
2185 strKey.c_str(),
2186 strValue.c_str(),
2187 sep,
2188 error.raw());
2189 }
2190
2191 // data is changing and change not vetoed: then write it out under the lock
2192
2193 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2194
2195 if (strValue.isEmpty())
2196 m->pMainConfigFile->mapExtraDataItems.erase(strKey);
2197 else
2198 m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
2199 // creates a new key if needed
2200
2201 /* save settings on success */
2202 rc = i_saveSettings();
2203 if (FAILED(rc)) return rc;
2204 }
2205
2206 // fire notification outside the lock
2207 if (fChanged)
2208 i_onExtraDataChange(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw());
2209
2210 return rc;
2211}
2212
2213/**
2214 *
2215 */
2216HRESULT VirtualBox::setSettingsSecret(const com::Utf8Str &aPassword)
2217{
2218 i_storeSettingsKey(aPassword);
2219 i_decryptSettings();
2220 return S_OK;
2221}
2222
2223int VirtualBox::i_decryptMediumSettings(Medium *pMedium)
2224{
2225 Bstr bstrCipher;
2226 HRESULT hrc = pMedium->GetProperty(Bstr("InitiatorSecretEncrypted").raw(),
2227 bstrCipher.asOutParam());
2228 if (SUCCEEDED(hrc))
2229 {
2230 Utf8Str strPlaintext;
2231 int rc = i_decryptSetting(&strPlaintext, bstrCipher);
2232 if (RT_SUCCESS(rc))
2233 pMedium->i_setPropertyDirect("InitiatorSecret", strPlaintext);
2234 else
2235 return rc;
2236 }
2237 return VINF_SUCCESS;
2238}
2239
2240/**
2241 * Decrypt all encrypted settings.
2242 *
2243 * So far we only have encrypted iSCSI initiator secrets so we just go through
2244 * all hard disk mediums and determine the plain 'InitiatorSecret' from
2245 * 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
2246 * properties need to be null-terminated strings.
2247 */
2248int VirtualBox::i_decryptSettings()
2249{
2250 bool fFailure = false;
2251 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2252 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2253 mt != m->allHardDisks.end();
2254 ++mt)
2255 {
2256 ComObjPtr<Medium> pMedium = *mt;
2257 AutoCaller medCaller(pMedium);
2258 if (FAILED(medCaller.rc()))
2259 continue;
2260 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2261 int vrc = i_decryptMediumSettings(pMedium);
2262 if (RT_FAILURE(vrc))
2263 fFailure = true;
2264 }
2265 if (!fFailure)
2266 {
2267 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2268 mt != m->allHardDisks.end();
2269 ++mt)
2270 {
2271 i_onMediumConfigChanged(*mt);
2272 }
2273 }
2274 return fFailure ? VERR_INVALID_PARAMETER : VINF_SUCCESS;
2275}
2276
2277/**
2278 * Encode.
2279 *
2280 * @param aPlaintext plaintext to be encrypted
2281 * @param aCiphertext resulting ciphertext (base64-encoded)
2282 */
2283int VirtualBox::i_encryptSetting(const Utf8Str &aPlaintext, Utf8Str *aCiphertext)
2284{
2285 uint8_t abCiphertext[32];
2286 char szCipherBase64[128];
2287 size_t cchCipherBase64;
2288 int rc = i_encryptSettingBytes((uint8_t*)aPlaintext.c_str(), abCiphertext,
2289 aPlaintext.length()+1, sizeof(abCiphertext));
2290 if (RT_SUCCESS(rc))
2291 {
2292 rc = RTBase64Encode(abCiphertext, sizeof(abCiphertext),
2293 szCipherBase64, sizeof(szCipherBase64),
2294 &cchCipherBase64);
2295 if (RT_SUCCESS(rc))
2296 *aCiphertext = szCipherBase64;
2297 }
2298 return rc;
2299}
2300
2301/**
2302 * Decode.
2303 *
2304 * @param aPlaintext resulting plaintext
2305 * @param aCiphertext ciphertext (base64-encoded) to decrypt
2306 */
2307int VirtualBox::i_decryptSetting(Utf8Str *aPlaintext, const Utf8Str &aCiphertext)
2308{
2309 uint8_t abPlaintext[64];
2310 uint8_t abCiphertext[64];
2311 size_t cbCiphertext;
2312 int rc = RTBase64Decode(aCiphertext.c_str(),
2313 abCiphertext, sizeof(abCiphertext),
2314 &cbCiphertext, NULL);
2315 if (RT_SUCCESS(rc))
2316 {
2317 rc = i_decryptSettingBytes(abPlaintext, abCiphertext, cbCiphertext);
2318 if (RT_SUCCESS(rc))
2319 {
2320 for (unsigned i = 0; i < cbCiphertext; i++)
2321 {
2322 /* sanity check: null-terminated string? */
2323 if (abPlaintext[i] == '\0')
2324 {
2325 /* sanity check: valid UTF8 string? */
2326 if (RTStrIsValidEncoding((const char*)abPlaintext))
2327 {
2328 *aPlaintext = Utf8Str((const char*)abPlaintext);
2329 return VINF_SUCCESS;
2330 }
2331 }
2332 }
2333 rc = VERR_INVALID_MAGIC;
2334 }
2335 }
2336 return rc;
2337}
2338
2339/**
2340 * Encrypt secret bytes. Use the m->SettingsCipherKey as key.
2341 *
2342 * @param aPlaintext clear text to be encrypted
2343 * @param aCiphertext resulting encrypted text
2344 * @param aPlaintextSize size of the plaintext
2345 * @param aCiphertextSize size of the ciphertext
2346 */
2347int VirtualBox::i_encryptSettingBytes(const uint8_t *aPlaintext, uint8_t *aCiphertext,
2348 size_t aPlaintextSize, size_t aCiphertextSize) const
2349{
2350 unsigned i, j;
2351 uint8_t aBytes[64];
2352
2353 if (!m->fSettingsCipherKeySet)
2354 return VERR_INVALID_STATE;
2355
2356 if (aCiphertextSize > sizeof(aBytes))
2357 return VERR_BUFFER_OVERFLOW;
2358
2359 if (aCiphertextSize < 32)
2360 return VERR_INVALID_PARAMETER;
2361
2362 AssertCompile(sizeof(m->SettingsCipherKey) >= 32);
2363
2364 /* store the first 8 bytes of the cipherkey for verification */
2365 for (i = 0, j = 0; i < 8; i++, j++)
2366 aCiphertext[i] = m->SettingsCipherKey[j];
2367
2368 for (unsigned k = 0; k < aPlaintextSize && i < aCiphertextSize; i++, k++)
2369 {
2370 aCiphertext[i] = (aPlaintext[k] ^ m->SettingsCipherKey[j]);
2371 if (++j >= sizeof(m->SettingsCipherKey))
2372 j = 0;
2373 }
2374
2375 /* fill with random data to have a minimal length (salt) */
2376 if (i < aCiphertextSize)
2377 {
2378 RTRandBytes(aBytes, aCiphertextSize - i);
2379 for (int k = 0; i < aCiphertextSize; i++, k++)
2380 {
2381 aCiphertext[i] = aBytes[k] ^ m->SettingsCipherKey[j];
2382 if (++j >= sizeof(m->SettingsCipherKey))
2383 j = 0;
2384 }
2385 }
2386
2387 return VINF_SUCCESS;
2388}
2389
2390/**
2391 * Decrypt secret bytes. Use the m->SettingsCipherKey as key.
2392 *
2393 * @param aPlaintext resulting plaintext
2394 * @param aCiphertext ciphertext to be decrypted
2395 * @param aCiphertextSize size of the ciphertext == size of the plaintext
2396 */
2397int VirtualBox::i_decryptSettingBytes(uint8_t *aPlaintext,
2398 const uint8_t *aCiphertext, size_t aCiphertextSize) const
2399{
2400 unsigned i, j;
2401
2402 if (!m->fSettingsCipherKeySet)
2403 return VERR_INVALID_STATE;
2404
2405 if (aCiphertextSize < 32)
2406 return VERR_INVALID_PARAMETER;
2407
2408 /* key verification */
2409 for (i = 0, j = 0; i < 8; i++, j++)
2410 if (aCiphertext[i] != m->SettingsCipherKey[j])
2411 return VERR_INVALID_MAGIC;
2412
2413 /* poison */
2414 memset(aPlaintext, 0xff, aCiphertextSize);
2415 for (int k = 0; i < aCiphertextSize; i++, k++)
2416 {
2417 aPlaintext[k] = aCiphertext[i] ^ m->SettingsCipherKey[j];
2418 if (++j >= sizeof(m->SettingsCipherKey))
2419 j = 0;
2420 }
2421
2422 return VINF_SUCCESS;
2423}
2424
2425/**
2426 * Store a settings key.
2427 *
2428 * @param aKey the key to store
2429 */
2430void VirtualBox::i_storeSettingsKey(const Utf8Str &aKey)
2431{
2432 RTSha512(aKey.c_str(), aKey.length(), m->SettingsCipherKey);
2433 m->fSettingsCipherKeySet = true;
2434}
2435
2436// public methods only for internal purposes
2437/////////////////////////////////////////////////////////////////////////////
2438
2439#ifdef DEBUG
2440void VirtualBox::i_dumpAllBackRefs()
2441{
2442 {
2443 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2444 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2445 mt != m->allHardDisks.end();
2446 ++mt)
2447 {
2448 ComObjPtr<Medium> pMedium = *mt;
2449 pMedium->i_dumpBackRefs();
2450 }
2451 }
2452 {
2453 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2454 for (MediaList::const_iterator mt = m->allDVDImages.begin();
2455 mt != m->allDVDImages.end();
2456 ++mt)
2457 {
2458 ComObjPtr<Medium> pMedium = *mt;
2459 pMedium->i_dumpBackRefs();
2460 }
2461 }
2462}
2463#endif
2464
2465/**
2466 * Posts an event to the event queue that is processed asynchronously
2467 * on a dedicated thread.
2468 *
2469 * Posting events to the dedicated event queue is useful to perform secondary
2470 * actions outside any object locks -- for example, to iterate over a list
2471 * of callbacks and inform them about some change caused by some object's
2472 * method call.
2473 *
2474 * @param event event to post; must have been allocated using |new|, will
2475 * be deleted automatically by the event thread after processing
2476 *
2477 * @note Doesn't lock any object.
2478 */
2479HRESULT VirtualBox::i_postEvent(Event *event)
2480{
2481 AssertReturn(event, E_FAIL);
2482
2483 HRESULT rc;
2484 AutoCaller autoCaller(this);
2485 if (SUCCEEDED((rc = autoCaller.rc())))
2486 {
2487 if (getObjectState().getState() != ObjectState::Ready)
2488 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
2489 getObjectState().getState()));
2490 // return S_OK
2491 else if ( (m->pAsyncEventQ)
2492 && (m->pAsyncEventQ->postEvent(event))
2493 )
2494 return S_OK;
2495 else
2496 rc = E_FAIL;
2497 }
2498
2499 // in any event of failure, we must clean up here, or we'll leak;
2500 // the caller has allocated the object using new()
2501 delete event;
2502 return rc;
2503}
2504
2505/**
2506 * Adds a progress to the global collection of pending operations.
2507 * Usually gets called upon progress object initialization.
2508 *
2509 * @param aProgress Operation to add to the collection.
2510 *
2511 * @note Doesn't lock objects.
2512 */
2513HRESULT VirtualBox::i_addProgress(IProgress *aProgress)
2514{
2515 CheckComArgNotNull(aProgress);
2516
2517 AutoCaller autoCaller(this);
2518 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2519
2520 Bstr id;
2521 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
2522 AssertComRCReturnRC(rc);
2523
2524 /* protect mProgressOperations */
2525 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2526
2527 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
2528 return S_OK;
2529}
2530
2531/**
2532 * Removes the progress from the global collection of pending operations.
2533 * Usually gets called upon progress completion.
2534 *
2535 * @param aId UUID of the progress operation to remove
2536 *
2537 * @note Doesn't lock objects.
2538 */
2539HRESULT VirtualBox::i_removeProgress(IN_GUID aId)
2540{
2541 AutoCaller autoCaller(this);
2542 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2543
2544 ComPtr<IProgress> progress;
2545
2546 /* protect mProgressOperations */
2547 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2548
2549 size_t cnt = m->mapProgressOperations.erase(aId);
2550 Assert(cnt == 1);
2551 NOREF(cnt);
2552
2553 return S_OK;
2554}
2555
2556#ifdef RT_OS_WINDOWS
2557
2558class StartSVCHelperClientData : public ThreadTask
2559{
2560public:
2561 StartSVCHelperClientData()
2562 {
2563 LogFlowFuncEnter();
2564 m_strTaskName = "SVCHelper";
2565 threadVoidData = NULL;
2566 initialized = false;
2567 }
2568
2569 virtual ~StartSVCHelperClientData()
2570 {
2571 LogFlowFuncEnter();
2572 if (threadVoidData!=NULL)
2573 {
2574 delete threadVoidData;
2575 threadVoidData=NULL;
2576 }
2577 };
2578
2579 void handler()
2580 {
2581 VirtualBox::i_SVCHelperClientThreadTask(this);
2582 }
2583
2584 const ComPtr<Progress>& GetProgressObject() const {return progress;}
2585
2586 bool init(VirtualBox* aVbox,
2587 Progress* aProgress,
2588 bool aPrivileged,
2589 VirtualBox::SVCHelperClientFunc aFunc,
2590 void *aUser)
2591 {
2592 LogFlowFuncEnter();
2593 that = aVbox;
2594 progress = aProgress;
2595 privileged = aPrivileged;
2596 func = aFunc;
2597 user = aUser;
2598
2599 initThreadVoidData();
2600
2601 initialized = true;
2602
2603 return initialized;
2604 }
2605
2606 bool isOk() const{ return initialized;}
2607
2608 bool initialized;
2609 ComObjPtr<VirtualBox> that;
2610 ComObjPtr<Progress> progress;
2611 bool privileged;
2612 VirtualBox::SVCHelperClientFunc func;
2613 void *user;
2614 ThreadVoidData *threadVoidData;
2615
2616private:
2617 bool initThreadVoidData()
2618 {
2619 LogFlowFuncEnter();
2620 threadVoidData = static_cast<ThreadVoidData*>(user);
2621 return true;
2622 }
2623};
2624
2625/**
2626 * Helper method that starts a worker thread that:
2627 * - creates a pipe communication channel using SVCHlpClient;
2628 * - starts an SVC Helper process that will inherit this channel;
2629 * - executes the supplied function by passing it the created SVCHlpClient
2630 * and opened instance to communicate to the Helper process and the given
2631 * Progress object.
2632 *
2633 * The user function is supposed to communicate to the helper process
2634 * using the \a aClient argument to do the requested job and optionally expose
2635 * the progress through the \a aProgress object. The user function should never
2636 * call notifyComplete() on it: this will be done automatically using the
2637 * result code returned by the function.
2638 *
2639 * Before the user function is started, the communication channel passed to
2640 * the \a aClient argument is fully set up, the function should start using
2641 * its write() and read() methods directly.
2642 *
2643 * The \a aVrc parameter of the user function may be used to return an error
2644 * code if it is related to communication errors (for example, returned by
2645 * the SVCHlpClient members when they fail). In this case, the correct error
2646 * message using this value will be reported to the caller. Note that the
2647 * value of \a aVrc is inspected only if the user function itself returns
2648 * success.
2649 *
2650 * If a failure happens anywhere before the user function would be normally
2651 * called, it will be called anyway in special "cleanup only" mode indicated
2652 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
2653 * all the function is supposed to do is to cleanup its aUser argument if
2654 * necessary (it's assumed that the ownership of this argument is passed to
2655 * the user function once #startSVCHelperClient() returns a success, thus
2656 * making it responsible for the cleanup).
2657 *
2658 * After the user function returns, the thread will send the SVCHlpMsg::Null
2659 * message to indicate a process termination.
2660 *
2661 * @param aPrivileged |true| to start the SVC Helper process as a privileged
2662 * user that can perform administrative tasks
2663 * @param aFunc user function to run
2664 * @param aUser argument to the user function
2665 * @param aProgress progress object that will track operation completion
2666 *
2667 * @note aPrivileged is currently ignored (due to some unsolved problems in
2668 * Vista) and the process will be started as a normal (unprivileged)
2669 * process.
2670 *
2671 * @note Doesn't lock anything.
2672 */
2673HRESULT VirtualBox::i_startSVCHelperClient(bool aPrivileged,
2674 SVCHelperClientFunc aFunc,
2675 void *aUser, Progress *aProgress)
2676{
2677 LogFlowFuncEnter();
2678 AssertReturn(aFunc, E_POINTER);
2679 AssertReturn(aProgress, E_POINTER);
2680
2681 AutoCaller autoCaller(this);
2682 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2683
2684 /* create the i_SVCHelperClientThreadTask() argument */
2685
2686 HRESULT hr = S_OK;
2687 StartSVCHelperClientData *pTask = NULL;
2688 try
2689 {
2690 pTask = new StartSVCHelperClientData();
2691
2692 pTask->init(this, aProgress, aPrivileged, aFunc, aUser);
2693
2694 if (!pTask->isOk())
2695 {
2696 delete pTask;
2697 LogRel(("Could not init StartSVCHelperClientData object \n"));
2698 throw E_FAIL;
2699 }
2700
2701 //this function delete pTask in case of exceptions, so there is no need in the call of delete operator
2702 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_WORKER);
2703
2704 }
2705 catch(std::bad_alloc &)
2706 {
2707 hr = setError(E_OUTOFMEMORY);
2708 }
2709 catch(...)
2710 {
2711 LogRel(("Could not create thread for StartSVCHelperClientData \n"));
2712 hr = E_FAIL;
2713 }
2714
2715 return hr;
2716}
2717
2718/**
2719 * Worker thread for startSVCHelperClient().
2720 */
2721/* static */
2722void VirtualBox::i_SVCHelperClientThreadTask(StartSVCHelperClientData *pTask)
2723{
2724 LogFlowFuncEnter();
2725 HRESULT rc = S_OK;
2726 bool userFuncCalled = false;
2727
2728 do
2729 {
2730 AssertBreakStmt(pTask, rc = E_POINTER);
2731 AssertReturnVoid(!pTask->progress.isNull());
2732
2733 /* protect VirtualBox from uninitialization */
2734 AutoCaller autoCaller(pTask->that);
2735 if (!autoCaller.isOk())
2736 {
2737 /* it's too late */
2738 rc = autoCaller.rc();
2739 break;
2740 }
2741
2742 int vrc = VINF_SUCCESS;
2743
2744 Guid id;
2745 id.create();
2746 SVCHlpClient client;
2747 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2748 id.raw()).c_str());
2749 if (RT_FAILURE(vrc))
2750 {
2751 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not create the communication channel (%Rrc)"), vrc);
2752 break;
2753 }
2754
2755 /* get the path to the executable */
2756 char exePathBuf[RTPATH_MAX];
2757 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2758 if (!exePath)
2759 {
2760 rc = pTask->that->setError(E_FAIL, tr("Cannot get executable name"));
2761 break;
2762 }
2763
2764 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2765
2766 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2767
2768 RTPROCESS pid = NIL_RTPROCESS;
2769
2770 if (pTask->privileged)
2771 {
2772 /* Attempt to start a privileged process using the Run As dialog */
2773
2774 Bstr file = exePath;
2775 Bstr parameters = argsStr;
2776
2777 SHELLEXECUTEINFO shExecInfo;
2778
2779 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2780
2781 shExecInfo.fMask = NULL;
2782 shExecInfo.hwnd = NULL;
2783 shExecInfo.lpVerb = L"runas";
2784 shExecInfo.lpFile = file.raw();
2785 shExecInfo.lpParameters = parameters.raw();
2786 shExecInfo.lpDirectory = NULL;
2787 shExecInfo.nShow = SW_NORMAL;
2788 shExecInfo.hInstApp = NULL;
2789
2790 if (!ShellExecuteEx(&shExecInfo))
2791 {
2792 int vrc2 = RTErrConvertFromWin32(GetLastError());
2793 /* hide excessive details in case of a frequent error
2794 * (pressing the Cancel button to close the Run As dialog) */
2795 if (vrc2 == VERR_CANCELLED)
2796 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Operation canceled by the user"));
2797 else
2798 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a privileged process '%s' (%Rrc)"), exePath, vrc2);
2799 break;
2800 }
2801 }
2802 else
2803 {
2804 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2805 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2806 if (RT_FAILURE(vrc))
2807 {
2808 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2809 break;
2810 }
2811 }
2812
2813 /* wait for the client to connect */
2814 vrc = client.connect();
2815 if (RT_SUCCESS(vrc))
2816 {
2817 /* start the user supplied function */
2818 rc = pTask->func(&client, pTask->progress, pTask->user, &vrc);
2819 userFuncCalled = true;
2820 }
2821
2822 /* send the termination signal to the process anyway */
2823 {
2824 int vrc2 = client.write(SVCHlpMsg::Null);
2825 if (RT_SUCCESS(vrc))
2826 vrc = vrc2;
2827 }
2828
2829 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2830 {
2831 rc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not operate the communication channel (%Rrc)"), vrc);
2832 break;
2833 }
2834 }
2835 while (0);
2836
2837 if (FAILED(rc) && !userFuncCalled)
2838 {
2839 /* call the user function in the "cleanup only" mode
2840 * to let it free resources passed to in aUser */
2841 pTask->func(NULL, NULL, pTask->user, NULL);
2842 }
2843
2844 pTask->progress->i_notifyComplete(rc);
2845
2846 LogFlowFuncLeave();
2847}
2848
2849#endif /* RT_OS_WINDOWS */
2850
2851/**
2852 * Sends a signal to the client watcher to rescan the set of machines
2853 * that have open sessions.
2854 *
2855 * @note Doesn't lock anything.
2856 */
2857void VirtualBox::i_updateClientWatcher()
2858{
2859 AutoCaller autoCaller(this);
2860 AssertComRCReturnVoid(autoCaller.rc());
2861
2862 AssertPtrReturnVoid(m->pClientWatcher);
2863 m->pClientWatcher->update();
2864}
2865
2866/**
2867 * Adds the given child process ID to the list of processes to be reaped.
2868 * This call should be followed by #i_updateClientWatcher() to take the effect.
2869 *
2870 * @note Doesn't lock anything.
2871 */
2872void VirtualBox::i_addProcessToReap(RTPROCESS pid)
2873{
2874 AutoCaller autoCaller(this);
2875 AssertComRCReturnVoid(autoCaller.rc());
2876
2877 AssertPtrReturnVoid(m->pClientWatcher);
2878 m->pClientWatcher->addProcess(pid);
2879}
2880
2881/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2882struct MachineEvent : public VirtualBox::CallbackEvent
2883{
2884 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
2885 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2886 , mBool(aBool)
2887 { }
2888
2889 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
2890 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2891 , mState(aState)
2892 {}
2893
2894 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2895 {
2896 switch (mWhat)
2897 {
2898 case VBoxEventType_OnMachineDataChanged:
2899 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2900 break;
2901
2902 case VBoxEventType_OnMachineStateChanged:
2903 aEvDesc.init(aSource, mWhat, id.raw(), mState);
2904 break;
2905
2906 case VBoxEventType_OnMachineRegistered:
2907 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2908 break;
2909
2910 default:
2911 AssertFailedReturn(S_OK);
2912 }
2913 return S_OK;
2914 }
2915
2916 Bstr id;
2917 MachineState_T mState;
2918 BOOL mBool;
2919};
2920
2921
2922/**
2923 * VD plugin load
2924 */
2925int VirtualBox::i_loadVDPlugin(const char *pszPluginLibrary)
2926{
2927 return m->pSystemProperties->i_loadVDPlugin(pszPluginLibrary);
2928}
2929
2930/**
2931 * VD plugin unload
2932 */
2933int VirtualBox::i_unloadVDPlugin(const char *pszPluginLibrary)
2934{
2935 return m->pSystemProperties->i_unloadVDPlugin(pszPluginLibrary);
2936}
2937
2938
2939/** Event for onMediumRegistered() */
2940struct MediumRegisteredEventStruct : public VirtualBox::CallbackEvent
2941{
2942 MediumRegisteredEventStruct(VirtualBox *aVB, const Guid &aMediumId,
2943 const DeviceType_T aDevType, const BOOL aRegistered)
2944 : CallbackEvent(aVB, VBoxEventType_OnMediumRegistered)
2945 , mMediumId(aMediumId.toUtf16()), mDevType(aDevType), mRegistered(aRegistered)
2946 {}
2947
2948 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
2949 {
2950 return aEvDesc.init(aSource, VBoxEventType_OnMediumRegistered, mMediumId.raw(), mDevType, mRegistered);
2951 }
2952
2953 Bstr mMediumId;
2954 DeviceType_T mDevType;
2955 BOOL mRegistered;
2956};
2957
2958/**
2959 * @note Doesn't lock any object.
2960 */
2961void VirtualBox::i_onMediumRegistered(const Guid &aMediumId, const DeviceType_T aDevType, const BOOL aRegistered)
2962{
2963 i_postEvent(new MediumRegisteredEventStruct(this, aMediumId, aDevType, aRegistered));
2964}
2965
2966/** Event for onMediumConfigChanged() */
2967struct MediumConfigChangedEventStruct : public VirtualBox::CallbackEvent
2968{
2969 MediumConfigChangedEventStruct(VirtualBox *aVB, IMedium *aMedium)
2970 : CallbackEvent(aVB, VBoxEventType_OnMediumConfigChanged)
2971 , mMedium(aMedium)
2972 {}
2973
2974 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
2975 {
2976 return aEvDesc.init(aSource, VBoxEventType_OnMediumConfigChanged, mMedium);
2977 }
2978
2979 IMedium* mMedium;
2980};
2981
2982void VirtualBox::i_onMediumConfigChanged(IMedium *aMedium)
2983{
2984 i_postEvent(new MediumConfigChangedEventStruct(this, aMedium));
2985}
2986
2987/** Event for onMediumChanged() */
2988struct MediumChangedEventStruct : public VirtualBox::CallbackEvent
2989{
2990 MediumChangedEventStruct(VirtualBox *aVB, IMediumAttachment *aMediumAttachment)
2991 : CallbackEvent(aVB, VBoxEventType_OnMediumChanged)
2992 , mMediumAttachment(aMediumAttachment)
2993 {}
2994
2995 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
2996 {
2997 return aEvDesc.init(aSource, VBoxEventType_OnMediumChanged, mMediumAttachment);
2998 }
2999
3000 IMediumAttachment* mMediumAttachment;
3001};
3002
3003void VirtualBox::i_onMediumChanged(IMediumAttachment *aMediumAttachment)
3004{
3005 i_postEvent(new MediumChangedEventStruct(this, aMediumAttachment));
3006}
3007
3008/** Event for onStorageDeviceChanged() */
3009struct StorageDeviceChangedEventStruct : public VirtualBox::CallbackEvent
3010{
3011 StorageDeviceChangedEventStruct(VirtualBox *aVB, IMediumAttachment *aStorageDevice, BOOL fRemoved, BOOL fSilent)
3012 : CallbackEvent(aVB, VBoxEventType_OnStorageDeviceChanged)
3013 , mStorageDevice(aStorageDevice)
3014 , mRemoved(fRemoved)
3015 , mSilent(fSilent)
3016 {}
3017
3018 virtual HRESULT prepareEventDesc(IEventSource *aSource, VBoxEventDesc &aEvDesc)
3019 {
3020 return aEvDesc.init(aSource, VBoxEventType_OnStorageDeviceChanged, mStorageDevice, mRemoved, mSilent);
3021 }
3022
3023 IMediumAttachment* mStorageDevice;
3024 BOOL mRemoved;
3025 BOOL mSilent;
3026};
3027
3028void VirtualBox::i_onStorageDeviceChanged(IMediumAttachment *aStorageDevice, const BOOL fRemoved, const BOOL fSilent)
3029{
3030 i_postEvent(new StorageDeviceChangedEventStruct(this, aStorageDevice, fRemoved, fSilent));
3031}
3032
3033/**
3034 * @note Doesn't lock any object.
3035 */
3036void VirtualBox::i_onMachineStateChange(const Guid &aId, MachineState_T aState)
3037{
3038 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
3039}
3040
3041/**
3042 * @note Doesn't lock any object.
3043 */
3044void VirtualBox::i_onMachineDataChange(const Guid &aId, BOOL aTemporary)
3045{
3046 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
3047}
3048
3049/**
3050 * @note Locks this object for reading.
3051 */
3052BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
3053 Bstr &aError)
3054{
3055 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
3056 aId.toString().c_str(), aKey, aValue));
3057
3058 AutoCaller autoCaller(this);
3059 AssertComRCReturn(autoCaller.rc(), FALSE);
3060
3061 BOOL allowChange = TRUE;
3062 Bstr id = aId.toUtf16();
3063
3064 VBoxEventDesc evDesc;
3065 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
3066 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
3067 //Assert(fDelivered);
3068 if (fDelivered)
3069 {
3070 ComPtr<IEvent> aEvent;
3071 evDesc.getEvent(aEvent.asOutParam());
3072 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
3073 Assert(aCanChangeEvent);
3074 BOOL fVetoed = FALSE;
3075 aCanChangeEvent->IsVetoed(&fVetoed);
3076 allowChange = !fVetoed;
3077
3078 if (!allowChange)
3079 {
3080 SafeArray<BSTR> aVetos;
3081 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
3082 if (aVetos.size() > 0)
3083 aError = aVetos[0];
3084 }
3085 }
3086 else
3087 allowChange = TRUE;
3088
3089 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
3090 return allowChange;
3091}
3092
3093/** Event for onExtraDataChange() */
3094struct ExtraDataEvent : public VirtualBox::CallbackEvent
3095{
3096 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
3097 IN_BSTR aKey, IN_BSTR aVal)
3098 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
3099 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
3100 {}
3101
3102 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3103 {
3104 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
3105 }
3106
3107 Bstr machineId, key, val;
3108};
3109
3110/**
3111 * @note Doesn't lock any object.
3112 */
3113void VirtualBox::i_onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
3114{
3115 i_postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
3116}
3117
3118/**
3119 * @note Doesn't lock any object.
3120 */
3121void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
3122{
3123 i_postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
3124}
3125
3126/** Event for onSessionStateChange() */
3127struct SessionEvent : public VirtualBox::CallbackEvent
3128{
3129 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
3130 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
3131 , machineId(aMachineId.toUtf16()), sessionState(aState)
3132 {}
3133
3134 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3135 {
3136 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
3137 }
3138 Bstr machineId;
3139 SessionState_T sessionState;
3140};
3141
3142/**
3143 * @note Doesn't lock any object.
3144 */
3145void VirtualBox::i_onSessionStateChange(const Guid &aId, SessionState_T aState)
3146{
3147 i_postEvent(new SessionEvent(this, aId, aState));
3148}
3149
3150/** Event for i_onSnapshotTaken(), i_onSnapshotDeleted(), i_onSnapshotRestored() and i_onSnapshotChange() */
3151struct SnapshotEvent : public VirtualBox::CallbackEvent
3152{
3153 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
3154 VBoxEventType_T aWhat)
3155 : CallbackEvent(aVB, aWhat)
3156 , machineId(aMachineId), snapshotId(aSnapshotId)
3157 {}
3158
3159 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3160 {
3161 return aEvDesc.init(aSource, mWhat, machineId.toUtf16().raw(),
3162 snapshotId.toUtf16().raw());
3163 }
3164
3165 Guid machineId;
3166 Guid snapshotId;
3167};
3168
3169/**
3170 * @note Doesn't lock any object.
3171 */
3172void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
3173{
3174 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3175 VBoxEventType_OnSnapshotTaken));
3176}
3177
3178/**
3179 * @note Doesn't lock any object.
3180 */
3181void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
3182{
3183 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3184 VBoxEventType_OnSnapshotDeleted));
3185}
3186
3187/**
3188 * @note Doesn't lock any object.
3189 */
3190void VirtualBox::i_onSnapshotRestored(const Guid &aMachineId, const Guid &aSnapshotId)
3191{
3192 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3193 VBoxEventType_OnSnapshotRestored));
3194}
3195
3196/**
3197 * @note Doesn't lock any object.
3198 */
3199void VirtualBox::i_onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
3200{
3201 i_postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
3202 VBoxEventType_OnSnapshotChanged));
3203}
3204
3205/** Event for onGuestPropertyChange() */
3206struct GuestPropertyEvent : public VirtualBox::CallbackEvent
3207{
3208 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
3209 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
3210 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
3211 machineId(aMachineId),
3212 name(aName),
3213 value(aValue),
3214 flags(aFlags)
3215 {}
3216
3217 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
3218 {
3219 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
3220 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
3221 }
3222
3223 Guid machineId;
3224 Bstr name, value, flags;
3225};
3226
3227/**
3228 * @note Doesn't lock any object.
3229 */
3230void VirtualBox::i_onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
3231 IN_BSTR aValue, IN_BSTR aFlags)
3232{
3233 i_postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
3234}
3235
3236/**
3237 * @note Doesn't lock any object.
3238 */
3239void VirtualBox::i_onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
3240 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
3241 IN_BSTR aGuestIp, uint16_t aGuestPort)
3242{
3243 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
3244 aHostPort, aGuestIp, aGuestPort);
3245}
3246
3247void VirtualBox::i_onNATNetworkChange(IN_BSTR aName)
3248{
3249 fireNATNetworkChangedEvent(m->pEventSource, aName);
3250}
3251
3252void VirtualBox::i_onNATNetworkStartStop(IN_BSTR aName, BOOL fStart)
3253{
3254 fireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
3255}
3256
3257void VirtualBox::i_onNATNetworkSetting(IN_BSTR aNetworkName, BOOL aEnabled,
3258 IN_BSTR aNetwork, IN_BSTR aGateway,
3259 BOOL aAdvertiseDefaultIpv6RouteEnabled,
3260 BOOL fNeedDhcpServer)
3261{
3262 fireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled,
3263 aNetwork, aGateway,
3264 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
3265}
3266
3267void VirtualBox::i_onNATNetworkPortForward(IN_BSTR aNetworkName, BOOL create, BOOL fIpv6,
3268 IN_BSTR aRuleName, NATProtocol_T proto,
3269 IN_BSTR aHostIp, LONG aHostPort,
3270 IN_BSTR aGuestIp, LONG aGuestPort)
3271{
3272 fireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create,
3273 fIpv6, aRuleName, proto,
3274 aHostIp, aHostPort,
3275 aGuestIp, aGuestPort);
3276}
3277
3278
3279void VirtualBox::i_onHostNameResolutionConfigurationChange()
3280{
3281 if (m->pEventSource)
3282 fireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
3283}
3284
3285
3286int VirtualBox::i_natNetworkRefInc(const Utf8Str &aNetworkName)
3287{
3288 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3289
3290 if (!sNatNetworkNameToRefCount[aNetworkName])
3291 {
3292 ComPtr<INATNetwork> nat;
3293 HRESULT rc = findNATNetworkByName(aNetworkName, nat);
3294 if (FAILED(rc)) return -1;
3295
3296 rc = nat->Start(Bstr("whatever").raw());
3297 if (SUCCEEDED(rc))
3298 LogRel(("Started NAT network '%s'\n", aNetworkName.c_str()));
3299 else
3300 LogRel(("Error %Rhrc starting NAT network '%s'\n", rc, aNetworkName.c_str()));
3301 AssertComRCReturn(rc, -1);
3302 }
3303
3304 sNatNetworkNameToRefCount[aNetworkName]++;
3305
3306 return sNatNetworkNameToRefCount[aNetworkName];
3307}
3308
3309
3310int VirtualBox::i_natNetworkRefDec(const Utf8Str &aNetworkName)
3311{
3312 AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);
3313
3314 if (!sNatNetworkNameToRefCount[aNetworkName])
3315 return 0;
3316
3317 sNatNetworkNameToRefCount[aNetworkName]--;
3318
3319 if (!sNatNetworkNameToRefCount[aNetworkName])
3320 {
3321 ComPtr<INATNetwork> nat;
3322 HRESULT rc = findNATNetworkByName(aNetworkName, nat);
3323 if (FAILED(rc)) return -1;
3324
3325 rc = nat->Stop();
3326 if (SUCCEEDED(rc))
3327 LogRel(("Stopped NAT network '%s'\n", aNetworkName.c_str()));
3328 else
3329 LogRel(("Error %Rhrc stopping NAT network '%s'\n", rc, aNetworkName.c_str()));
3330 AssertComRCReturn(rc, -1);
3331 }
3332
3333 return sNatNetworkNameToRefCount[aNetworkName];
3334}
3335
3336
3337/**
3338 * @note Locks the list of other objects for reading.
3339 */
3340ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
3341{
3342 ComObjPtr<GuestOSType> type;
3343
3344 /* unknown type must always be the first */
3345 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
3346
3347 return m->allGuestOSTypes.front();
3348}
3349
3350/**
3351 * Returns the list of opened machines (machines having VM sessions opened,
3352 * ignoring other sessions) and optionally the list of direct session controls.
3353 *
3354 * @param aMachines Where to put opened machines (will be empty if none).
3355 * @param aControls Where to put direct session controls (optional).
3356 *
3357 * @note The returned lists contain smart pointers. So, clear it as soon as
3358 * it becomes no more necessary to release instances.
3359 *
3360 * @note It can be possible that a session machine from the list has been
3361 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
3362 * when accessing unprotected data directly.
3363 *
3364 * @note Locks objects for reading.
3365 */
3366void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
3367 InternalControlList *aControls /*= NULL*/)
3368{
3369 AutoCaller autoCaller(this);
3370 AssertComRCReturnVoid(autoCaller.rc());
3371
3372 aMachines.clear();
3373 if (aControls)
3374 aControls->clear();
3375
3376 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3377
3378 for (MachinesOList::iterator it = m->allMachines.begin();
3379 it != m->allMachines.end();
3380 ++it)
3381 {
3382 ComObjPtr<SessionMachine> sm;
3383 ComPtr<IInternalSessionControl> ctl;
3384 if ((*it)->i_isSessionOpenVM(sm, &ctl))
3385 {
3386 aMachines.push_back(sm);
3387 if (aControls)
3388 aControls->push_back(ctl);
3389 }
3390 }
3391}
3392
3393/**
3394 * Gets a reference to the machine list. This is the real thing, not a copy,
3395 * so bad things will happen if the caller doesn't hold the necessary lock.
3396 *
3397 * @returns reference to machine list
3398 *
3399 * @note Caller must hold the VirtualBox object lock at least for reading.
3400 */
3401VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
3402{
3403 return m->allMachines;
3404}
3405
3406/**
3407 * Searches for a machine object with the given ID in the collection
3408 * of registered machines.
3409 *
3410 * @param aId Machine UUID to look for.
3411 * @param fPermitInaccessible If true, inaccessible machines will be found;
3412 * if false, this will fail if the given machine is inaccessible.
3413 * @param aSetError If true, set errorinfo if the machine is not found.
3414 * @param aMachine Returned machine, if found.
3415 * @return
3416 */
3417HRESULT VirtualBox::i_findMachine(const Guid &aId,
3418 bool fPermitInaccessible,
3419 bool aSetError,
3420 ComObjPtr<Machine> *aMachine /* = NULL */)
3421{
3422 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3423
3424 AutoCaller autoCaller(this);
3425 AssertComRCReturnRC(autoCaller.rc());
3426
3427 {
3428 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3429
3430 for (MachinesOList::iterator it = m->allMachines.begin();
3431 it != m->allMachines.end();
3432 ++it)
3433 {
3434 ComObjPtr<Machine> pMachine = *it;
3435
3436 if (!fPermitInaccessible)
3437 {
3438 // skip inaccessible machines
3439 AutoCaller machCaller(pMachine);
3440 if (FAILED(machCaller.rc()))
3441 continue;
3442 }
3443
3444 if (pMachine->i_getId() == aId)
3445 {
3446 rc = S_OK;
3447 if (aMachine)
3448 *aMachine = pMachine;
3449 break;
3450 }
3451 }
3452 }
3453
3454 if (aSetError && FAILED(rc))
3455 rc = setError(rc,
3456 tr("Could not find a registered machine with UUID {%RTuuid}"),
3457 aId.raw());
3458
3459 return rc;
3460}
3461
3462/**
3463 * Searches for a machine object with the given name or location in the
3464 * collection of registered machines.
3465 *
3466 * @param aName Machine name or location to look for.
3467 * @param aSetError If true, set errorinfo if the machine is not found.
3468 * @param aMachine Returned machine, if found.
3469 * @return
3470 */
3471HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
3472 bool aSetError,
3473 ComObjPtr<Machine> *aMachine /* = NULL */)
3474{
3475 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
3476
3477 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3478 for (MachinesOList::iterator it = m->allMachines.begin();
3479 it != m->allMachines.end();
3480 ++it)
3481 {
3482 ComObjPtr<Machine> &pMachine = *it;
3483 AutoCaller machCaller(pMachine);
3484 if (machCaller.rc())
3485 continue; // we can't ask inaccessible machines for their names
3486
3487 AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
3488 if (pMachine->i_getName() == aName)
3489 {
3490 rc = S_OK;
3491 if (aMachine)
3492 *aMachine = pMachine;
3493 break;
3494 }
3495 if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
3496 {
3497 rc = S_OK;
3498 if (aMachine)
3499 *aMachine = pMachine;
3500 break;
3501 }
3502 }
3503
3504 if (aSetError && FAILED(rc))
3505 rc = setError(rc,
3506 tr("Could not find a registered machine named '%s'"), aName.c_str());
3507
3508 return rc;
3509}
3510
3511static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
3512{
3513 /* empty strings are invalid */
3514 if (aGroup.isEmpty())
3515 return E_INVALIDARG;
3516 /* the toplevel group is valid */
3517 if (aGroup == "/")
3518 return S_OK;
3519 /* any other strings of length 1 are invalid */
3520 if (aGroup.length() == 1)
3521 return E_INVALIDARG;
3522 /* must start with a slash */
3523 if (aGroup.c_str()[0] != '/')
3524 return E_INVALIDARG;
3525 /* must not end with a slash */
3526 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3527 return E_INVALIDARG;
3528 /* check the group components */
3529 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3530 while (pStr)
3531 {
3532 char *pSlash = RTStrStr(pStr, "/");
3533 if (pSlash)
3534 {
3535 /* no empty components (or // sequences in other words) */
3536 if (pSlash == pStr)
3537 return E_INVALIDARG;
3538 /* check if the machine name rules are violated, because that means
3539 * the group components are too close to the limits. */
3540 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3541 Utf8Str tmp2(tmp);
3542 sanitiseMachineFilename(tmp);
3543 if (tmp != tmp2)
3544 return E_INVALIDARG;
3545 if (fPrimary)
3546 {
3547 HRESULT rc = pVirtualBox->i_findMachineByName(tmp,
3548 false /* aSetError */);
3549 if (SUCCEEDED(rc))
3550 return VBOX_E_VM_ERROR;
3551 }
3552 pStr = pSlash + 1;
3553 }
3554 else
3555 {
3556 /* check if the machine name rules are violated, because that means
3557 * the group components is too close to the limits. */
3558 Utf8Str tmp(pStr);
3559 Utf8Str tmp2(tmp);
3560 sanitiseMachineFilename(tmp);
3561 if (tmp != tmp2)
3562 return E_INVALIDARG;
3563 pStr = NULL;
3564 }
3565 }
3566 return S_OK;
3567}
3568
3569/**
3570 * Validates a machine group.
3571 *
3572 * @param aGroup Machine group.
3573 * @param fPrimary Set if this is the primary group.
3574 *
3575 * @return S_OK or E_INVALIDARG
3576 */
3577HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
3578{
3579 HRESULT rc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
3580 if (FAILED(rc))
3581 {
3582 if (rc == VBOX_E_VM_ERROR)
3583 rc = setError(E_INVALIDARG,
3584 tr("Machine group '%s' conflicts with a virtual machine name"),
3585 aGroup.c_str());
3586 else
3587 rc = setError(rc,
3588 tr("Invalid machine group '%s'"),
3589 aGroup.c_str());
3590 }
3591 return rc;
3592}
3593
3594/**
3595 * Takes a list of machine groups, and sanitizes/validates it.
3596 *
3597 * @param aMachineGroups Array with the machine groups.
3598 * @param pllMachineGroups Pointer to list of strings for the result.
3599 *
3600 * @return S_OK or E_INVALIDARG
3601 */
3602HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
3603{
3604 pllMachineGroups->clear();
3605 if (aMachineGroups.size())
3606 {
3607 for (size_t i = 0; i < aMachineGroups.size(); i++)
3608 {
3609 Utf8Str group(aMachineGroups[i]);
3610 if (group.length() == 0)
3611 group = "/";
3612
3613 HRESULT rc = i_validateMachineGroup(group, i == 0);
3614 if (FAILED(rc))
3615 return rc;
3616
3617 /* no duplicates please */
3618 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3619 == pllMachineGroups->end())
3620 pllMachineGroups->push_back(group);
3621 }
3622 if (pllMachineGroups->size() == 0)
3623 pllMachineGroups->push_back("/");
3624 }
3625 else
3626 pllMachineGroups->push_back("/");
3627
3628 return S_OK;
3629}
3630
3631/**
3632 * Searches for a Medium object with the given ID in the list of registered
3633 * hard disks.
3634 *
3635 * @param aId ID of the hard disk. Must not be empty.
3636 * @param aSetError If @c true , the appropriate error info is set in case
3637 * when the hard disk is not found.
3638 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3639 *
3640 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3641 *
3642 * @note Locks the media tree for reading.
3643 */
3644HRESULT VirtualBox::i_findHardDiskById(const Guid &aId,
3645 bool aSetError,
3646 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3647{
3648 AssertReturn(!aId.isZero(), E_INVALIDARG);
3649
3650 // we use the hard disks map, but it is protected by the
3651 // hard disk _list_ lock handle
3652 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3653
3654 HardDiskMap::const_iterator it = m->mapHardDisks.find(aId);
3655 if (it != m->mapHardDisks.end())
3656 {
3657 if (aHardDisk)
3658 *aHardDisk = (*it).second;
3659 return S_OK;
3660 }
3661
3662 if (aSetError)
3663 return setError(VBOX_E_OBJECT_NOT_FOUND,
3664 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3665 aId.raw());
3666
3667 return VBOX_E_OBJECT_NOT_FOUND;
3668}
3669
3670/**
3671 * Searches for a Medium object with the given ID or location in the list of
3672 * registered hard disks. If both ID and location are specified, the first
3673 * object that matches either of them (not necessarily both) is returned.
3674 *
3675 * @param strLocation Full location specification. Must not be empty.
3676 * @param aSetError If @c true , the appropriate error info is set in case
3677 * when the hard disk is not found.
3678 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3679 *
3680 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3681 *
3682 * @note Locks the media tree for reading.
3683 */
3684HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
3685 bool aSetError,
3686 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3687{
3688 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3689
3690 // we use the hard disks map, but it is protected by the
3691 // hard disk _list_ lock handle
3692 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3693
3694 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3695 it != m->mapHardDisks.end();
3696 ++it)
3697 {
3698 const ComObjPtr<Medium> &pHD = (*it).second;
3699
3700 AutoCaller autoCaller(pHD);
3701 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3702 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3703
3704 Utf8Str strLocationFull = pHD->i_getLocationFull();
3705
3706 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3707 {
3708 if (aHardDisk)
3709 *aHardDisk = pHD;
3710 return S_OK;
3711 }
3712 }
3713
3714 if (aSetError)
3715 return setError(VBOX_E_OBJECT_NOT_FOUND,
3716 tr("Could not find an open hard disk with location '%s'"),
3717 strLocation.c_str());
3718
3719 return VBOX_E_OBJECT_NOT_FOUND;
3720}
3721
3722/**
3723 * Searches for a Medium object with the given ID or location in the list of
3724 * registered DVD or floppy images, depending on the @a mediumType argument.
3725 * If both ID and file path are specified, the first object that matches either
3726 * of them (not necessarily both) is returned.
3727 *
3728 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3729 * @param aId ID of the image file (unused when NULL).
3730 * @param aLocation Full path to the image file (unused when NULL).
3731 * @param aSetError If @c true, the appropriate error info is set in case when
3732 * the image is not found.
3733 * @param aImage Where to store the found image object (can be NULL).
3734 *
3735 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3736 *
3737 * @note Locks the media tree for reading.
3738 */
3739HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
3740 const Guid *aId,
3741 const Utf8Str &aLocation,
3742 bool aSetError,
3743 ComObjPtr<Medium> *aImage /* = NULL */)
3744{
3745 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3746
3747 Utf8Str location;
3748 if (!aLocation.isEmpty())
3749 {
3750 int vrc = i_calculateFullPath(aLocation, location);
3751 if (RT_FAILURE(vrc))
3752 return setError(VBOX_E_FILE_ERROR,
3753 tr("Invalid image file location '%s' (%Rrc)"),
3754 aLocation.c_str(),
3755 vrc);
3756 }
3757
3758 MediaOList *pMediaList;
3759
3760 switch (mediumType)
3761 {
3762 case DeviceType_DVD:
3763 pMediaList = &m->allDVDImages;
3764 break;
3765
3766 case DeviceType_Floppy:
3767 pMediaList = &m->allFloppyImages;
3768 break;
3769
3770 default:
3771 return E_INVALIDARG;
3772 }
3773
3774 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3775
3776 bool found = false;
3777
3778 for (MediaList::const_iterator it = pMediaList->begin();
3779 it != pMediaList->end();
3780 ++it)
3781 {
3782 // no AutoCaller, registered image life time is bound to this
3783 Medium *pMedium = *it;
3784 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3785 const Utf8Str &strLocationFull = pMedium->i_getLocationFull();
3786
3787 found = ( aId
3788 && pMedium->i_getId() == *aId)
3789 || ( !aLocation.isEmpty()
3790 && RTPathCompare(location.c_str(),
3791 strLocationFull.c_str()) == 0);
3792 if (found)
3793 {
3794 if (pMedium->i_getDeviceType() != mediumType)
3795 {
3796 if (mediumType == DeviceType_DVD)
3797 return setError(E_INVALIDARG,
3798 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3799 else
3800 return setError(E_INVALIDARG,
3801 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3802 }
3803
3804 if (aImage)
3805 *aImage = pMedium;
3806 break;
3807 }
3808 }
3809
3810 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3811
3812 if (aSetError && !found)
3813 {
3814 if (aId)
3815 setError(rc,
3816 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3817 aId->raw(),
3818 m->strSettingsFilePath.c_str());
3819 else
3820 setError(rc,
3821 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3822 aLocation.c_str(),
3823 m->strSettingsFilePath.c_str());
3824 }
3825
3826 return rc;
3827}
3828
3829/**
3830 * Searches for an IMedium object that represents the given UUID.
3831 *
3832 * If the UUID is empty (indicating an empty drive), this sets pMedium
3833 * to NULL and returns S_OK.
3834 *
3835 * If the UUID refers to a host drive of the given device type, this
3836 * sets pMedium to the object from the list in IHost and returns S_OK.
3837 *
3838 * If the UUID is an image file, this sets pMedium to the object that
3839 * findDVDOrFloppyImage() returned.
3840 *
3841 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3842 *
3843 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3844 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3845 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3846 * @param aSetError
3847 * @param pMedium out: IMedium object found.
3848 * @return
3849 */
3850HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
3851 const Guid &uuid,
3852 bool fRefresh,
3853 bool aSetError,
3854 ComObjPtr<Medium> &pMedium)
3855{
3856 if (uuid.isZero())
3857 {
3858 // that's easy
3859 pMedium.setNull();
3860 return S_OK;
3861 }
3862 else if (!uuid.isValid())
3863 {
3864 /* handling of case invalid GUID */
3865 return setError(VBOX_E_OBJECT_NOT_FOUND,
3866 tr("Guid '%s' is invalid"),
3867 uuid.toString().c_str());
3868 }
3869
3870 // first search for host drive with that UUID
3871 HRESULT rc = m->pHost->i_findHostDriveById(mediumType,
3872 uuid,
3873 fRefresh,
3874 pMedium);
3875 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3876 // then search for an image with that UUID
3877 rc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3878
3879 return rc;
3880}
3881
3882/* Look for a GuestOSType object */
3883HRESULT VirtualBox::i_findGuestOSType(const Utf8Str &strOSType,
3884 ComObjPtr<GuestOSType> &guestOSType)
3885{
3886 guestOSType.setNull();
3887
3888 AssertMsg(m->allGuestOSTypes.size() != 0,
3889 ("Guest OS types array must be filled"));
3890
3891 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3892 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3893 it != m->allGuestOSTypes.end();
3894 ++it)
3895 {
3896 const Utf8Str &typeId = (*it)->i_id();
3897 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
3898 if (strOSType.compare(typeId, Utf8Str::CaseInsensitive) == 0)
3899 {
3900 guestOSType = *it;
3901 return S_OK;
3902 }
3903 }
3904
3905 return setError(VBOX_E_OBJECT_NOT_FOUND,
3906 tr("'%s' is not a valid Guest OS type"),
3907 strOSType.c_str());
3908}
3909
3910/**
3911 * Returns the constant pseudo-machine UUID that is used to identify the
3912 * global media registry.
3913 *
3914 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3915 * in which media registry it is saved (if any): this can either be a machine
3916 * UUID, if it's in a per-machine media registry, or this global ID.
3917 *
3918 * This UUID is only used to identify the VirtualBox object while VirtualBox
3919 * is running. It is a compile-time constant and not saved anywhere.
3920 *
3921 * @return
3922 */
3923const Guid& VirtualBox::i_getGlobalRegistryId() const
3924{
3925 return m->uuidMediaRegistry;
3926}
3927
3928const ComObjPtr<Host>& VirtualBox::i_host() const
3929{
3930 return m->pHost;
3931}
3932
3933SystemProperties* VirtualBox::i_getSystemProperties() const
3934{
3935 return m->pSystemProperties;
3936}
3937
3938CloudProviderManager *VirtualBox::i_getCloudProviderManager() const
3939{
3940 return m->pCloudProviderManager;
3941}
3942
3943#ifdef VBOX_WITH_EXTPACK
3944/**
3945 * Getter that SystemProperties and others can use to talk to the extension
3946 * pack manager.
3947 */
3948ExtPackManager* VirtualBox::i_getExtPackManager() const
3949{
3950 return m->ptrExtPackManager;
3951}
3952#endif
3953
3954/**
3955 * Getter that machines can talk to the autostart database.
3956 */
3957AutostartDb* VirtualBox::i_getAutostartDb() const
3958{
3959 return m->pAutostartDb;
3960}
3961
3962#ifdef VBOX_WITH_RESOURCE_USAGE_API
3963const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
3964{
3965 return m->pPerformanceCollector;
3966}
3967#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3968
3969/**
3970 * Returns the default machine folder from the system properties
3971 * with proper locking.
3972 * @return
3973 */
3974void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
3975{
3976 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3977 str = m->pSystemProperties->m->strDefaultMachineFolder;
3978}
3979
3980/**
3981 * Returns the default hard disk format from the system properties
3982 * with proper locking.
3983 * @return
3984 */
3985void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
3986{
3987 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3988 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3989}
3990
3991const Utf8Str& VirtualBox::i_homeDir() const
3992{
3993 return m->strHomeDir;
3994}
3995
3996/**
3997 * Calculates the absolute path of the given path taking the VirtualBox home
3998 * directory as the current directory.
3999 *
4000 * @param strPath Path to calculate the absolute path for.
4001 * @param aResult Where to put the result (used only on success, can be the
4002 * same Utf8Str instance as passed in @a aPath).
4003 * @return IPRT result.
4004 *
4005 * @note Doesn't lock any object.
4006 */
4007int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
4008{
4009 AutoCaller autoCaller(this);
4010 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
4011
4012 /* no need to lock since strHomeDir is const */
4013
4014 char szFolder[RTPATH_MAX];
4015 size_t cbFolder = sizeof(szFolder);
4016 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
4017 strPath.c_str(),
4018 RTPATH_STR_F_STYLE_HOST,
4019 szFolder,
4020 &cbFolder);
4021 if (RT_SUCCESS(vrc))
4022 aResult = szFolder;
4023
4024 return vrc;
4025}
4026
4027/**
4028 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
4029 * if it is a subdirectory thereof, or simply copying it otherwise.
4030 *
4031 * @param strSource Path to evalue and copy.
4032 * @param strTarget Buffer to receive target path.
4033 */
4034void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
4035 Utf8Str &strTarget)
4036{
4037 AutoCaller autoCaller(this);
4038 AssertComRCReturnVoid(autoCaller.rc());
4039
4040 // no need to lock since mHomeDir is const
4041
4042 // use strTarget as a temporary buffer to hold the machine settings dir
4043 strTarget = m->strHomeDir;
4044 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
4045 // is relative: then append what's left
4046 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
4047 else
4048 // is not relative: then overwrite
4049 strTarget = strSource;
4050}
4051
4052// private methods
4053/////////////////////////////////////////////////////////////////////////////
4054
4055/**
4056 * Checks if there is a hard disk, DVD or floppy image with the given ID or
4057 * location already registered.
4058 *
4059 * On return, sets @a aConflict to the string describing the conflicting medium,
4060 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
4061 * either case. A failure is unexpected.
4062 *
4063 * @param aId UUID to check.
4064 * @param aLocation Location to check.
4065 * @param aConflict Where to return parameters of the conflicting medium.
4066 * @param ppMedium Medium reference in case this is simply a duplicate.
4067 *
4068 * @note Locks the media tree and media objects for reading.
4069 */
4070HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
4071 const Utf8Str &aLocation,
4072 Utf8Str &aConflict,
4073 ComObjPtr<Medium> *ppMedium)
4074{
4075 AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
4076 AssertReturn(ppMedium, E_INVALIDARG);
4077
4078 aConflict.setNull();
4079 ppMedium->setNull();
4080
4081 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4082
4083 HRESULT rc = S_OK;
4084
4085 ComObjPtr<Medium> pMediumFound;
4086 const char *pcszType = NULL;
4087
4088 if (aId.isValid() && !aId.isZero())
4089 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4090 if (FAILED(rc) && !aLocation.isEmpty())
4091 rc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
4092 if (SUCCEEDED(rc))
4093 pcszType = tr("hard disk");
4094
4095 if (!pcszType)
4096 {
4097 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
4098 if (SUCCEEDED(rc))
4099 pcszType = tr("CD/DVD image");
4100 }
4101
4102 if (!pcszType)
4103 {
4104 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
4105 if (SUCCEEDED(rc))
4106 pcszType = tr("floppy image");
4107 }
4108
4109 if (pcszType && pMediumFound)
4110 {
4111 /* Note: no AutoCaller since bound to this */
4112 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
4113
4114 Utf8Str strLocFound = pMediumFound->i_getLocationFull();
4115 Guid idFound = pMediumFound->i_getId();
4116
4117 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
4118 && (idFound == aId)
4119 )
4120 *ppMedium = pMediumFound;
4121
4122 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
4123 pcszType,
4124 strLocFound.c_str(),
4125 idFound.raw());
4126 }
4127
4128 return S_OK;
4129}
4130
4131/**
4132 * Checks whether the given UUID is already in use by one medium for the
4133 * given device type.
4134 *
4135 * @returns true if the UUID is already in use
4136 * fale otherwise
4137 * @param aId The UUID to check.
4138 * @param deviceType The device type the UUID is going to be checked for
4139 * conflicts.
4140 */
4141bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
4142{
4143 /* A zero UUID is invalid here, always claim that it is already used. */
4144 AssertReturn(!aId.isZero(), true);
4145
4146 AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4147
4148 HRESULT rc = S_OK;
4149 bool fInUse = false;
4150
4151 ComObjPtr<Medium> pMediumFound;
4152
4153 switch (deviceType)
4154 {
4155 case DeviceType_HardDisk:
4156 rc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
4157 break;
4158 case DeviceType_DVD:
4159 rc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4160 break;
4161 case DeviceType_Floppy:
4162 rc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
4163 break;
4164 default:
4165 AssertMsgFailed(("Invalid device type %d\n", deviceType));
4166 }
4167
4168 if (SUCCEEDED(rc) && pMediumFound)
4169 fInUse = true;
4170
4171 return fInUse;
4172}
4173
4174/**
4175 * Called from Machine::prepareSaveSettings() when it has detected
4176 * that a machine has been renamed. Such renames will require
4177 * updating the global media registry during the
4178 * VirtualBox::saveSettings() that follows later.
4179*
4180 * When a machine is renamed, there may well be media (in particular,
4181 * diff images for snapshots) in the global registry that will need
4182 * to have their paths updated. Before 3.2, Machine::saveSettings
4183 * used to call VirtualBox::saveSettings implicitly, which was both
4184 * unintuitive and caused locking order problems. Now, we remember
4185 * such pending name changes with this method so that
4186 * VirtualBox::saveSettings() can process them properly.
4187 */
4188void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
4189 const Utf8Str &strNewConfigDir)
4190{
4191 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4192
4193 Data::PendingMachineRename pmr;
4194 pmr.strConfigDirOld = strOldConfigDir;
4195 pmr.strConfigDirNew = strNewConfigDir;
4196 m->llPendingMachineRenames.push_back(pmr);
4197}
4198
4199static DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4200
4201class SaveMediaRegistriesDesc : public ThreadTask
4202{
4203
4204public:
4205 SaveMediaRegistriesDesc()
4206 {
4207 m_strTaskName = "SaveMediaReg";
4208 }
4209 virtual ~SaveMediaRegistriesDesc(void) { }
4210
4211private:
4212 void handler()
4213 {
4214 try
4215 {
4216 fntSaveMediaRegistries(this);
4217 }
4218 catch(...)
4219 {
4220 LogRel(("Exception in the function fntSaveMediaRegistries()\n"));
4221 }
4222 }
4223
4224 MediaList llMedia;
4225 ComObjPtr<VirtualBox> pVirtualBox;
4226
4227 friend DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
4228 friend void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4229 const Guid &uuidRegistry,
4230 const Utf8Str &strMachineFolder);
4231};
4232
4233DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser)
4234{
4235 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
4236 if (!pDesc)
4237 {
4238 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
4239 return VERR_INVALID_PARAMETER;
4240 }
4241
4242 for (MediaList::const_iterator it = pDesc->llMedia.begin();
4243 it != pDesc->llMedia.end();
4244 ++it)
4245 {
4246 Medium *pMedium = *it;
4247 pMedium->i_markRegistriesModified();
4248 }
4249
4250 pDesc->pVirtualBox->i_saveModifiedRegistries();
4251
4252 pDesc->llMedia.clear();
4253 pDesc->pVirtualBox.setNull();
4254
4255 return VINF_SUCCESS;
4256}
4257
4258/**
4259 * Goes through all known media (hard disks, floppies and DVDs) and saves
4260 * those into the given settings::MediaRegistry structures whose registry
4261 * ID match the given UUID.
4262 *
4263 * Before actually writing to the structures, all media paths (not just the
4264 * ones for the given registry) are updated if machines have been renamed
4265 * since the last call.
4266 *
4267 * This gets called from two contexts:
4268 *
4269 * -- VirtualBox::saveSettings() with the UUID of the global registry
4270 * (VirtualBox::Data.uuidRegistry); this will save those media
4271 * which had been loaded from the global registry or have been
4272 * attached to a "legacy" machine which can't save its own registry;
4273 *
4274 * -- Machine::saveSettings() with the UUID of a machine, if a medium
4275 * has been attached to a machine created with VirtualBox 4.0 or later.
4276 *
4277 * Media which have only been temporarily opened without having been
4278 * attached to a machine have a NULL registry UUID and therefore don't
4279 * get saved.
4280 *
4281 * This locks the media tree. Throws HRESULT on errors!
4282 *
4283 * @param mediaRegistry Settings structure to fill.
4284 * @param uuidRegistry The UUID of the media registry; either a machine UUID
4285 * (if machine registry) or the UUID of the global registry.
4286 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
4287 */
4288void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
4289 const Guid &uuidRegistry,
4290 const Utf8Str &strMachineFolder)
4291{
4292 // lock all media for the following; use a write lock because we're
4293 // modifying the PendingMachineRenamesList, which is protected by this
4294 AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4295
4296 // if a machine was renamed, then we'll need to refresh media paths
4297 if (m->llPendingMachineRenames.size())
4298 {
4299 // make a single list from the three media lists so we don't need three loops
4300 MediaList llAllMedia;
4301 // with hard disks, we must use the map, not the list, because the list only has base images
4302 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
4303 llAllMedia.push_back(it->second);
4304 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
4305 llAllMedia.push_back(*it);
4306 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
4307 llAllMedia.push_back(*it);
4308
4309 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
4310 for (MediaList::iterator it = llAllMedia.begin();
4311 it != llAllMedia.end();
4312 ++it)
4313 {
4314 Medium *pMedium = *it;
4315 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
4316 it2 != m->llPendingMachineRenames.end();
4317 ++it2)
4318 {
4319 const Data::PendingMachineRename &pmr = *it2;
4320 HRESULT rc = pMedium->i_updatePath(pmr.strConfigDirOld,
4321 pmr.strConfigDirNew);
4322 if (SUCCEEDED(rc))
4323 {
4324 // Remember which medium objects has been changed,
4325 // to trigger saving their registries later.
4326 pDesc->llMedia.push_back(pMedium);
4327 } else if (rc == VBOX_E_FILE_ERROR)
4328 /* nothing */;
4329 else
4330 AssertComRC(rc);
4331 }
4332 }
4333 // done, don't do it again until we have more machine renames
4334 m->llPendingMachineRenames.clear();
4335
4336 if (pDesc->llMedia.size())
4337 {
4338 // Handle the media registry saving in a separate thread, to
4339 // avoid giant locking problems and passing up the list many
4340 // levels up to whoever triggered saveSettings, as there are
4341 // lots of places which would need to handle saving more settings.
4342 pDesc->pVirtualBox = this;
4343 HRESULT hr = S_OK;
4344 try
4345 {
4346 //the function createThread() takes ownership of pDesc
4347 //so there is no need to use delete operator for pDesc
4348 //after calling this function
4349 hr = pDesc->createThread();
4350 }
4351 catch(...)
4352 {
4353 hr = E_FAIL;
4354 }
4355
4356 if (FAILED(hr))
4357 {
4358 // failure means that settings aren't saved, but there isn't
4359 // much we can do besides avoiding memory leaks
4360 LogRelFunc(("Failed to create thread for saving media registries (%Rhr)\n", hr));
4361 }
4362 }
4363 else
4364 delete pDesc;
4365 }
4366
4367 struct {
4368 MediaOList &llSource;
4369 settings::MediaList &llTarget;
4370 } s[] =
4371 {
4372 // hard disks
4373 { m->allHardDisks, mediaRegistry.llHardDisks },
4374 // CD/DVD images
4375 { m->allDVDImages, mediaRegistry.llDvdImages },
4376 // floppy images
4377 { m->allFloppyImages, mediaRegistry.llFloppyImages }
4378 };
4379
4380 HRESULT rc;
4381
4382 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
4383 {
4384 MediaOList &llSource = s[i].llSource;
4385 settings::MediaList &llTarget = s[i].llTarget;
4386 llTarget.clear();
4387 for (MediaList::const_iterator it = llSource.begin();
4388 it != llSource.end();
4389 ++it)
4390 {
4391 Medium *pMedium = *it;
4392 AutoCaller autoCaller(pMedium);
4393 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
4394 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4395
4396 if (pMedium->i_isInRegistry(uuidRegistry))
4397 {
4398 llTarget.push_back(settings::Medium::Empty);
4399 rc = pMedium->i_saveSettings(llTarget.back(), strMachineFolder); // this recurses into child hard disks
4400 if (FAILED(rc))
4401 {
4402 llTarget.pop_back();
4403 throw rc;
4404 }
4405 }
4406 }
4407 }
4408}
4409
4410/**
4411 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
4412 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
4413 * places internally when settings need saving.
4414 *
4415 * @note Caller must have locked the VirtualBox object for writing and must not hold any
4416 * other locks since this locks all kinds of member objects and trees temporarily,
4417 * which could cause conflicts.
4418 */
4419HRESULT VirtualBox::i_saveSettings()
4420{
4421 AutoCaller autoCaller(this);
4422 AssertComRCReturnRC(autoCaller.rc());
4423
4424 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
4425 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
4426
4427 i_unmarkRegistryModified(i_getGlobalRegistryId());
4428
4429 HRESULT rc = S_OK;
4430
4431 try
4432 {
4433 // machines
4434 m->pMainConfigFile->llMachines.clear();
4435 {
4436 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4437 for (MachinesOList::iterator it = m->allMachines.begin();
4438 it != m->allMachines.end();
4439 ++it)
4440 {
4441 Machine *pMachine = *it;
4442 // save actual machine registry entry
4443 settings::MachineRegistryEntry mre;
4444 rc = pMachine->i_saveRegistryEntry(mre);
4445 m->pMainConfigFile->llMachines.push_back(mre);
4446 }
4447 }
4448
4449 i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
4450 m->uuidMediaRegistry, // global media registry ID
4451 Utf8Str::Empty); // strMachineFolder
4452
4453 m->pMainConfigFile->llDhcpServers.clear();
4454 {
4455 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4456 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4457 it != m->allDHCPServers.end();
4458 ++it)
4459 {
4460 settings::DHCPServer d;
4461 rc = (*it)->i_saveSettings(d);
4462 if (FAILED(rc)) throw rc;
4463 m->pMainConfigFile->llDhcpServers.push_back(d);
4464 }
4465 }
4466
4467#ifdef VBOX_WITH_NAT_SERVICE
4468 /* Saving NAT Network configuration */
4469 m->pMainConfigFile->llNATNetworks.clear();
4470 {
4471 AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4472 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
4473 it != m->allNATNetworks.end();
4474 ++it)
4475 {
4476 settings::NATNetwork n;
4477 rc = (*it)->i_saveSettings(n);
4478 if (FAILED(rc)) throw rc;
4479 m->pMainConfigFile->llNATNetworks.push_back(n);
4480 }
4481 }
4482#endif
4483
4484 // leave extra data alone, it's still in the config file
4485
4486 // host data (USB filters)
4487 rc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
4488 if (FAILED(rc)) throw rc;
4489
4490 rc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
4491 if (FAILED(rc)) throw rc;
4492
4493 // and write out the XML, still under the lock
4494 m->pMainConfigFile->write(m->strSettingsFilePath);
4495 }
4496 catch (HRESULT err)
4497 {
4498 /* we assume that error info is set by the thrower */
4499 rc = err;
4500 }
4501 catch (...)
4502 {
4503 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
4504 }
4505
4506 return rc;
4507}
4508
4509/**
4510 * Helper to register the machine.
4511 *
4512 * When called during VirtualBox startup, adds the given machine to the
4513 * collection of registered machines. Otherwise tries to mark the machine
4514 * as registered, and, if succeeded, adds it to the collection and
4515 * saves global settings.
4516 *
4517 * @note The caller must have added itself as a caller of the @a aMachine
4518 * object if calls this method not on VirtualBox startup.
4519 *
4520 * @param aMachine machine to register
4521 *
4522 * @note Locks objects!
4523 */
4524HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
4525{
4526 ComAssertRet(aMachine, E_INVALIDARG);
4527
4528 AutoCaller autoCaller(this);
4529 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4530
4531 HRESULT rc = S_OK;
4532
4533 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4534
4535 {
4536 ComObjPtr<Machine> pMachine;
4537 rc = i_findMachine(aMachine->i_getId(),
4538 true /* fPermitInaccessible */,
4539 false /* aDoSetError */,
4540 &pMachine);
4541 if (SUCCEEDED(rc))
4542 {
4543 /* sanity */
4544 AutoLimitedCaller machCaller(pMachine);
4545 AssertComRC(machCaller.rc());
4546
4547 return setError(E_INVALIDARG,
4548 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
4549 aMachine->i_getId().raw(),
4550 pMachine->i_getSettingsFileFull().c_str());
4551 }
4552
4553 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
4554 rc = S_OK;
4555 }
4556
4557 if (getObjectState().getState() != ObjectState::InInit)
4558 {
4559 rc = aMachine->i_prepareRegister();
4560 if (FAILED(rc)) return rc;
4561 }
4562
4563 /* add to the collection of registered machines */
4564 m->allMachines.addChild(aMachine);
4565
4566 if (getObjectState().getState() != ObjectState::InInit)
4567 rc = i_saveSettings();
4568
4569 return rc;
4570}
4571
4572/**
4573 * Remembers the given medium object by storing it in either the global
4574 * medium registry or a machine one.
4575 *
4576 * @note Caller must hold the media tree lock for writing; in addition, this
4577 * locks @a pMedium for reading
4578 *
4579 * @param pMedium Medium object to remember.
4580 * @param ppMedium Actually stored medium object. Can be different if due
4581 * to an unavoidable race there was a duplicate Medium object
4582 * created.
4583 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
4584 * lock, necessary to release it in the right spot.
4585 * @return
4586 */
4587HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
4588 ComObjPtr<Medium> *ppMedium,
4589 AutoWriteLock &mediaTreeLock)
4590{
4591 AssertReturn(pMedium != NULL, E_INVALIDARG);
4592 AssertReturn(ppMedium != NULL, E_INVALIDARG);
4593
4594 // caller must hold the media tree write lock
4595 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4596
4597 AutoCaller autoCaller(this);
4598 AssertComRCReturnRC(autoCaller.rc());
4599
4600 AutoCaller mediumCaller(pMedium);
4601 AssertComRCReturnRC(mediumCaller.rc());
4602
4603 bool fAddToGlobalRegistry = false;
4604 const char *pszDevType = NULL;
4605 Guid regId;
4606 ObjectsList<Medium> *pall = NULL;
4607 DeviceType_T devType;
4608 {
4609 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4610 devType = pMedium->i_getDeviceType();
4611
4612 if (!pMedium->i_getFirstRegistryMachineId(regId))
4613 fAddToGlobalRegistry = true;
4614 }
4615 switch (devType)
4616 {
4617 case DeviceType_HardDisk:
4618 pall = &m->allHardDisks;
4619 pszDevType = tr("hard disk");
4620 break;
4621 case DeviceType_DVD:
4622 pszDevType = tr("DVD image");
4623 pall = &m->allDVDImages;
4624 break;
4625 case DeviceType_Floppy:
4626 pszDevType = tr("floppy image");
4627 pall = &m->allFloppyImages;
4628 break;
4629 default:
4630 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4631 }
4632
4633 Guid id;
4634 Utf8Str strLocationFull;
4635 ComObjPtr<Medium> pParent;
4636 {
4637 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4638 id = pMedium->i_getId();
4639 strLocationFull = pMedium->i_getLocationFull();
4640 pParent = pMedium->i_getParent();
4641 }
4642
4643 HRESULT rc;
4644
4645 Utf8Str strConflict;
4646 ComObjPtr<Medium> pDupMedium;
4647 rc = i_checkMediaForConflicts(id,
4648 strLocationFull,
4649 strConflict,
4650 &pDupMedium);
4651 if (FAILED(rc)) return rc;
4652
4653 if (pDupMedium.isNull())
4654 {
4655 if (strConflict.length())
4656 return setError(E_INVALIDARG,
4657 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4658 pszDevType,
4659 strLocationFull.c_str(),
4660 id.raw(),
4661 strConflict.c_str(),
4662 m->strSettingsFilePath.c_str());
4663
4664 // add to the collection if it is a base medium
4665 if (pParent.isNull())
4666 pall->getList().push_back(pMedium);
4667
4668 // store all hard disks (even differencing images) in the map
4669 if (devType == DeviceType_HardDisk)
4670 m->mapHardDisks[id] = pMedium;
4671
4672 mediumCaller.release();
4673 mediaTreeLock.release();
4674 *ppMedium = pMedium;
4675 }
4676 else
4677 {
4678 // pMedium may be the last reference to the Medium object, and the
4679 // caller may have specified the same ComObjPtr as the output parameter.
4680 // In this case the assignment will uninit the object, and we must not
4681 // have a caller pending.
4682 mediumCaller.release();
4683 // release media tree lock, must not be held at uninit time.
4684 mediaTreeLock.release();
4685 // must not hold the media tree write lock any more
4686 Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4687 *ppMedium = pDupMedium;
4688 }
4689
4690 if (fAddToGlobalRegistry)
4691 {
4692 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4693 if (pMedium->i_addRegistry(m->uuidMediaRegistry))
4694 i_markRegistryModified(m->uuidMediaRegistry);
4695 }
4696
4697 // Restore the initial lock state, so that no unexpected lock changes are
4698 // done by this method, which would need adjustments everywhere.
4699 mediaTreeLock.acquire();
4700
4701 return rc;
4702}
4703
4704/**
4705 * Removes the given medium from the respective registry.
4706 *
4707 * @param pMedium Hard disk object to remove.
4708 *
4709 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4710 */
4711HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
4712{
4713 AssertReturn(pMedium != NULL, E_INVALIDARG);
4714
4715 AutoCaller autoCaller(this);
4716 AssertComRCReturnRC(autoCaller.rc());
4717
4718 AutoCaller mediumCaller(pMedium);
4719 AssertComRCReturnRC(mediumCaller.rc());
4720
4721 // caller must hold the media tree write lock
4722 Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4723
4724 Guid id;
4725 ComObjPtr<Medium> pParent;
4726 DeviceType_T devType;
4727 {
4728 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4729 id = pMedium->i_getId();
4730 pParent = pMedium->i_getParent();
4731 devType = pMedium->i_getDeviceType();
4732 }
4733
4734 ObjectsList<Medium> *pall = NULL;
4735 switch (devType)
4736 {
4737 case DeviceType_HardDisk:
4738 pall = &m->allHardDisks;
4739 break;
4740 case DeviceType_DVD:
4741 pall = &m->allDVDImages;
4742 break;
4743 case DeviceType_Floppy:
4744 pall = &m->allFloppyImages;
4745 break;
4746 default:
4747 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4748 }
4749
4750 // remove from the collection if it is a base medium
4751 if (pParent.isNull())
4752 pall->getList().remove(pMedium);
4753
4754 // remove all hard disks (even differencing images) from map
4755 if (devType == DeviceType_HardDisk)
4756 {
4757 size_t cnt = m->mapHardDisks.erase(id);
4758 Assert(cnt == 1);
4759 NOREF(cnt);
4760 }
4761
4762 return S_OK;
4763}
4764
4765/**
4766 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4767 * with children appearing before their parents.
4768 * @param llMedia
4769 * @param pMedium
4770 */
4771void VirtualBox::i_pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4772{
4773 // recurse first, then add ourselves; this way children end up on the
4774 // list before their parents
4775
4776 const MediaList &llChildren = pMedium->i_getChildren();
4777 for (MediaList::const_iterator it = llChildren.begin();
4778 it != llChildren.end();
4779 ++it)
4780 {
4781 Medium *pChild = *it;
4782 i_pushMediumToListWithChildren(llMedia, pChild);
4783 }
4784
4785 Log(("Pushing medium %RTuuid\n", pMedium->i_getId().raw()));
4786 llMedia.push_back(pMedium);
4787}
4788
4789/**
4790 * Unregisters all Medium objects which belong to the given machine registry.
4791 * Gets called from Machine::uninit() just before the machine object dies
4792 * and must only be called with a machine UUID as the registry ID.
4793 *
4794 * Locks the media tree.
4795 *
4796 * @param uuidMachine Medium registry ID (always a machine UUID)
4797 * @return
4798 */
4799HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
4800{
4801 Assert(!uuidMachine.isZero() && uuidMachine.isValid());
4802
4803 LogFlowFuncEnter();
4804
4805 AutoCaller autoCaller(this);
4806 AssertComRCReturnRC(autoCaller.rc());
4807
4808 MediaList llMedia2Close;
4809
4810 {
4811 AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4812
4813 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4814 it != m->allHardDisks.getList().end();
4815 ++it)
4816 {
4817 ComObjPtr<Medium> pMedium = *it;
4818 AutoCaller medCaller(pMedium);
4819 if (FAILED(medCaller.rc())) return medCaller.rc();
4820 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4821
4822 if (pMedium->i_isInRegistry(uuidMachine))
4823 // recursively with children first
4824 i_pushMediumToListWithChildren(llMedia2Close, pMedium);
4825 }
4826 }
4827
4828 for (MediaList::iterator it = llMedia2Close.begin();
4829 it != llMedia2Close.end();
4830 ++it)
4831 {
4832 ComObjPtr<Medium> pMedium = *it;
4833 Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
4834 AutoCaller mac(pMedium);
4835 pMedium->i_close(mac);
4836 }
4837
4838 LogFlowFuncLeave();
4839
4840 return S_OK;
4841}
4842
4843/**
4844 * Removes the given machine object from the internal list of registered machines.
4845 * Called from Machine::Unregister().
4846 * @param pMachine
4847 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4848 * @return
4849 */
4850HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
4851 const Guid &id)
4852{
4853 // remove from the collection of registered machines
4854 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4855 m->allMachines.removeChild(pMachine);
4856 // save the global registry
4857 HRESULT rc = i_saveSettings();
4858 alock.release();
4859
4860 /*
4861 * Now go over all known media and checks if they were registered in the
4862 * media registry of the given machine. Each such medium is then moved to
4863 * a different media registry to make sure it doesn't get lost since its
4864 * media registry is about to go away.
4865 *
4866 * This fixes the following use case: Image A.vdi of machine A is also used
4867 * by machine B, but registered in the media registry of machine A. If machine
4868 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4869 * become inaccessible.
4870 */
4871 {
4872 AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4873 // iterate over the list of *base* images
4874 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4875 it != m->allHardDisks.getList().end();
4876 ++it)
4877 {
4878 ComObjPtr<Medium> &pMedium = *it;
4879 AutoCaller medCaller(pMedium);
4880 if (FAILED(medCaller.rc())) return medCaller.rc();
4881 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4882
4883 if (pMedium->i_removeRegistryRecursive(id))
4884 {
4885 // machine ID was found in base medium's registry list:
4886 // move this base image and all its children to another registry then
4887 // 1) first, find a better registry to add things to
4888 const Guid *puuidBetter = pMedium->i_getAnyMachineBackref();
4889 if (puuidBetter)
4890 {
4891 // 2) better registry found: then use that
4892 pMedium->i_addRegistryRecursive(*puuidBetter);
4893 // 3) and make sure the registry is saved below
4894 mlock.release();
4895 tlock.release();
4896 i_markRegistryModified(*puuidBetter);
4897 tlock.acquire();
4898 mlock.acquire();
4899 }
4900 }
4901 }
4902 }
4903
4904 i_saveModifiedRegistries();
4905
4906 /* fire an event */
4907 i_onMachineRegistered(id, FALSE);
4908
4909 return rc;
4910}
4911
4912/**
4913 * Marks the registry for @a uuid as modified, so that it's saved in a later
4914 * call to saveModifiedRegistries().
4915 *
4916 * @param uuid
4917 */
4918void VirtualBox::i_markRegistryModified(const Guid &uuid)
4919{
4920 if (uuid == i_getGlobalRegistryId())
4921 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4922 else
4923 {
4924 ComObjPtr<Machine> pMachine;
4925 HRESULT rc = i_findMachine(uuid,
4926 false /* fPermitInaccessible */,
4927 false /* aSetError */,
4928 &pMachine);
4929 if (SUCCEEDED(rc))
4930 {
4931 AutoCaller machineCaller(pMachine);
4932 if (SUCCEEDED(machineCaller.rc()))
4933 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4934 }
4935 }
4936}
4937
4938/**
4939 * Marks the registry for @a uuid as unmodified, so that it's not saved in
4940 * a later call to saveModifiedRegistries().
4941 *
4942 * @param uuid
4943 */
4944void VirtualBox::i_unmarkRegistryModified(const Guid &uuid)
4945{
4946 uint64_t uOld;
4947 if (uuid == i_getGlobalRegistryId())
4948 {
4949 for (;;)
4950 {
4951 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4952 if (!uOld)
4953 break;
4954 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4955 break;
4956 ASMNopPause();
4957 }
4958 }
4959 else
4960 {
4961 ComObjPtr<Machine> pMachine;
4962 HRESULT rc = i_findMachine(uuid,
4963 false /* fPermitInaccessible */,
4964 false /* aSetError */,
4965 &pMachine);
4966 if (SUCCEEDED(rc))
4967 {
4968 AutoCaller machineCaller(pMachine);
4969 if (SUCCEEDED(machineCaller.rc()))
4970 {
4971 for (;;)
4972 {
4973 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4974 if (!uOld)
4975 break;
4976 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4977 break;
4978 ASMNopPause();
4979 }
4980 }
4981 }
4982 }
4983}
4984
4985/**
4986 * Saves all settings files according to the modified flags in the Machine
4987 * objects and in the VirtualBox object.
4988 *
4989 * This locks machines and the VirtualBox object as necessary, so better not
4990 * hold any locks before calling this.
4991 *
4992 * @return
4993 */
4994void VirtualBox::i_saveModifiedRegistries()
4995{
4996 HRESULT rc = S_OK;
4997 bool fNeedsGlobalSettings = false;
4998 uint64_t uOld;
4999
5000 {
5001 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5002 for (MachinesOList::iterator it = m->allMachines.begin();
5003 it != m->allMachines.end();
5004 ++it)
5005 {
5006 const ComObjPtr<Machine> &pMachine = *it;
5007
5008 for (;;)
5009 {
5010 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
5011 if (!uOld)
5012 break;
5013 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
5014 break;
5015 ASMNopPause();
5016 }
5017 if (uOld)
5018 {
5019 AutoCaller autoCaller(pMachine);
5020 if (FAILED(autoCaller.rc()))
5021 continue;
5022 /* object is already dead, no point in saving settings */
5023 if (getObjectState().getState() != ObjectState::Ready)
5024 continue;
5025 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
5026 rc = pMachine->i_saveSettings(&fNeedsGlobalSettings,
5027 Machine::SaveS_Force); // caller said save, so stop arguing
5028 }
5029 }
5030 }
5031
5032 for (;;)
5033 {
5034 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
5035 if (!uOld)
5036 break;
5037 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
5038 break;
5039 ASMNopPause();
5040 }
5041 if (uOld || fNeedsGlobalSettings)
5042 {
5043 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5044 rc = i_saveSettings();
5045 }
5046 NOREF(rc); /* XXX */
5047}
5048
5049
5050/* static */
5051const com::Utf8Str &VirtualBox::i_getVersionNormalized()
5052{
5053 return sVersionNormalized;
5054}
5055
5056/**
5057 * Checks if the path to the specified file exists, according to the path
5058 * information present in the file name. Optionally the path is created.
5059 *
5060 * Note that the given file name must contain the full path otherwise the
5061 * extracted relative path will be created based on the current working
5062 * directory which is normally unknown.
5063 *
5064 * @param strFileName Full file name which path is checked/created.
5065 * @param fCreate Flag if the path should be created if it doesn't exist.
5066 *
5067 * @return Extended error information on failure to check/create the path.
5068 */
5069/* static */
5070HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
5071{
5072 Utf8Str strDir(strFileName);
5073 strDir.stripFilename();
5074 if (!RTDirExists(strDir.c_str()))
5075 {
5076 if (fCreate)
5077 {
5078 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
5079 if (RT_FAILURE(vrc))
5080 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, vrc,
5081 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
5082 strDir.c_str(),
5083 vrc));
5084 }
5085 else
5086 return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, VERR_FILE_NOT_FOUND,
5087 Utf8StrFmt(tr("Directory '%s' does not exist"), strDir.c_str()));
5088 }
5089
5090 return S_OK;
5091}
5092
5093const Utf8Str& VirtualBox::i_settingsFilePath()
5094{
5095 return m->strSettingsFilePath;
5096}
5097
5098/**
5099 * Returns the lock handle which protects the machines list. As opposed
5100 * to version 3.1 and earlier, these lists are no longer protected by the
5101 * VirtualBox lock, but by this more specialized lock. Mind the locking
5102 * order: always request this lock after the VirtualBox object lock but
5103 * before the locks of any machine object. See AutoLock.h.
5104 */
5105RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
5106{
5107 return m->lockMachines;
5108}
5109
5110/**
5111 * Returns the lock handle which protects the media trees (hard disks,
5112 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
5113 * are no longer protected by the VirtualBox lock, but by this more
5114 * specialized lock. Mind the locking order: always request this lock
5115 * after the VirtualBox object lock but before the locks of the media
5116 * objects contained in these lists. See AutoLock.h.
5117 */
5118RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
5119{
5120 return m->lockMedia;
5121}
5122
5123/**
5124 * Thread function that handles custom events posted using #i_postEvent().
5125 */
5126// static
5127DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
5128{
5129 LogFlowFuncEnter();
5130
5131 AssertReturn(pvUser, VERR_INVALID_POINTER);
5132
5133 HRESULT hr = com::Initialize();
5134 if (FAILED(hr))
5135 return VERR_COM_UNEXPECTED;
5136
5137 int rc = VINF_SUCCESS;
5138
5139 try
5140 {
5141 /* Create an event queue for the current thread. */
5142 EventQueue *pEventQueue = new EventQueue();
5143 AssertPtr(pEventQueue);
5144
5145 /* Return the queue to the one who created this thread. */
5146 *(static_cast <EventQueue **>(pvUser)) = pEventQueue;
5147
5148 /* signal that we're ready. */
5149 RTThreadUserSignal(thread);
5150
5151 /*
5152 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
5153 * we must not stop processing events and delete the pEventQueue object. This must
5154 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
5155 * See @bugref{5724}.
5156 */
5157 for (;;)
5158 {
5159 rc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
5160 if (rc == VERR_INTERRUPTED)
5161 {
5162 LogFlow(("Event queue processing ended with rc=%Rrc\n", rc));
5163 rc = VINF_SUCCESS; /* Set success when exiting. */
5164 break;
5165 }
5166 }
5167
5168 delete pEventQueue;
5169 }
5170 catch (std::bad_alloc &ba)
5171 {
5172 rc = VERR_NO_MEMORY;
5173 NOREF(ba);
5174 }
5175
5176 com::Shutdown();
5177
5178 LogFlowFuncLeaveRC(rc);
5179 return rc;
5180}
5181
5182
5183////////////////////////////////////////////////////////////////////////////////
5184
5185/**
5186 * Prepare the event using the overwritten #prepareEventDesc method and fire.
5187 *
5188 * @note Locks the managed VirtualBox object for reading but leaves the lock
5189 * before iterating over callbacks and calling their methods.
5190 */
5191void *VirtualBox::CallbackEvent::handler()
5192{
5193 if (!mVirtualBox)
5194 return NULL;
5195
5196 AutoCaller autoCaller(mVirtualBox);
5197 if (!autoCaller.isOk())
5198 {
5199 Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
5200 mVirtualBox->getObjectState().getState()));
5201 /* We don't need mVirtualBox any more, so release it */
5202 mVirtualBox = NULL;
5203 return NULL;
5204 }
5205
5206 {
5207 VBoxEventDesc evDesc;
5208 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
5209
5210 evDesc.fire(/* don't wait for delivery */0);
5211 }
5212
5213 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
5214 return NULL;
5215}
5216
5217//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
5218//{
5219// return E_NOTIMPL;
5220//}
5221
5222HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
5223 ComPtr<IDHCPServer> &aServer)
5224{
5225 ComObjPtr<DHCPServer> dhcpServer;
5226 dhcpServer.createObject();
5227 HRESULT rc = dhcpServer->init(this, aName);
5228 if (FAILED(rc)) return rc;
5229
5230 rc = i_registerDHCPServer(dhcpServer, true);
5231 if (FAILED(rc)) return rc;
5232
5233 dhcpServer.queryInterfaceTo(aServer.asOutParam());
5234
5235 return rc;
5236}
5237
5238HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
5239 ComPtr<IDHCPServer> &aServer)
5240{
5241 HRESULT rc = S_OK;
5242 ComPtr<DHCPServer> found;
5243
5244 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5245
5246 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5247 it != m->allDHCPServers.end();
5248 ++it)
5249 {
5250 Bstr bstrNetworkName;
5251 rc = (*it)->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
5252 if (FAILED(rc)) return rc;
5253
5254 if (Utf8Str(bstrNetworkName) == aName)
5255 {
5256 found = *it;
5257 break;
5258 }
5259 }
5260
5261 if (!found)
5262 return E_INVALIDARG;
5263
5264 rc = found.queryInterfaceTo(aServer.asOutParam());
5265
5266 return rc;
5267}
5268
5269HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
5270{
5271 IDHCPServer *aP = aServer;
5272
5273 HRESULT rc = i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
5274
5275 return rc;
5276}
5277
5278/**
5279 * Remembers the given DHCP server in the settings.
5280 *
5281 * @param aDHCPServer DHCP server object to remember.
5282 * @param aSaveSettings @c true to save settings to disk (default).
5283 *
5284 * When @a aSaveSettings is @c true, this operation may fail because of the
5285 * failed #i_saveSettings() method it calls. In this case, the dhcp server object
5286 * will not be remembered. It is therefore the responsibility of the caller to
5287 * call this method as the last step of some action that requires registration
5288 * in order to make sure that only fully functional dhcp server objects get
5289 * registered.
5290 *
5291 * @note Locks this object for writing and @a aDHCPServer for reading.
5292 */
5293HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
5294 bool aSaveSettings /*= true*/)
5295{
5296 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5297
5298 AutoCaller autoCaller(this);
5299 AssertComRCReturnRC(autoCaller.rc());
5300
5301 // Acquire a lock on the VirtualBox object early to avoid lock order issues
5302 // when we call i_saveSettings() later on.
5303 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5304 // need it below, in findDHCPServerByNetworkName (reading) and in
5305 // m->allDHCPServers.addChild, so need to get it here to avoid lock
5306 // order trouble with dhcpServerCaller
5307 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5308
5309 AutoCaller dhcpServerCaller(aDHCPServer);
5310 AssertComRCReturnRC(dhcpServerCaller.rc());
5311
5312 Bstr bstrNetworkName;
5313 HRESULT rc = S_OK;
5314 rc = aDHCPServer->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
5315 if (FAILED(rc)) return rc;
5316
5317 ComPtr<IDHCPServer> existing;
5318 rc = findDHCPServerByNetworkName(Utf8Str(bstrNetworkName), existing);
5319 if (SUCCEEDED(rc))
5320 return E_INVALIDARG;
5321 rc = S_OK;
5322
5323 m->allDHCPServers.addChild(aDHCPServer);
5324 // we need to release the list lock before we attempt to acquire locks
5325 // on other objects in i_saveSettings (see @bugref{7500})
5326 alock.release();
5327
5328 if (aSaveSettings)
5329 {
5330 // we acquired the lock on 'this' earlier to avoid lock order issues
5331 rc = i_saveSettings();
5332
5333 if (FAILED(rc))
5334 {
5335 alock.acquire();
5336 m->allDHCPServers.removeChild(aDHCPServer);
5337 }
5338 }
5339
5340 return rc;
5341}
5342
5343/**
5344 * Removes the given DHCP server from the settings.
5345 *
5346 * @param aDHCPServer DHCP server object to remove.
5347 *
5348 * This operation may fail because of the failed #i_saveSettings() method it
5349 * calls. In this case, the DHCP server will NOT be removed from the settings
5350 * when this method returns.
5351 *
5352 * @note Locks this object for writing.
5353 */
5354HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
5355{
5356 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5357
5358 AutoCaller autoCaller(this);
5359 AssertComRCReturnRC(autoCaller.rc());
5360
5361 AutoCaller dhcpServerCaller(aDHCPServer);
5362 AssertComRCReturnRC(dhcpServerCaller.rc());
5363
5364 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5365 AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5366 m->allDHCPServers.removeChild(aDHCPServer);
5367 // we need to release the list lock before we attempt to acquire locks
5368 // on other objects in i_saveSettings (see @bugref{7500})
5369 alock.release();
5370
5371 HRESULT rc = i_saveSettings();
5372
5373 // undo the changes if we failed to save them
5374 if (FAILED(rc))
5375 {
5376 alock.acquire();
5377 m->allDHCPServers.addChild(aDHCPServer);
5378 }
5379
5380 return rc;
5381}
5382
5383
5384/**
5385 * NAT Network
5386 */
5387HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
5388 ComPtr<INATNetwork> &aNetwork)
5389{
5390#ifdef VBOX_WITH_NAT_SERVICE
5391 ComObjPtr<NATNetwork> natNetwork;
5392 natNetwork.createObject();
5393 HRESULT rc = natNetwork->init(this, aNetworkName);
5394 if (FAILED(rc)) return rc;
5395
5396 rc = i_registerNATNetwork(natNetwork, true);
5397 if (FAILED(rc)) return rc;
5398
5399 natNetwork.queryInterfaceTo(aNetwork.asOutParam());
5400
5401 fireNATNetworkCreationDeletionEvent(m->pEventSource, Bstr(aNetworkName).raw(), TRUE);
5402
5403 return rc;
5404#else
5405 NOREF(aNetworkName);
5406 NOREF(aNetwork);
5407 return E_NOTIMPL;
5408#endif
5409}
5410
5411HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
5412 ComPtr<INATNetwork> &aNetwork)
5413{
5414#ifdef VBOX_WITH_NAT_SERVICE
5415
5416 HRESULT rc = S_OK;
5417 ComPtr<NATNetwork> found;
5418
5419 AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5420
5421 for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
5422 it != m->allNATNetworks.end();
5423 ++it)
5424 {
5425 Bstr bstrNATNetworkName;
5426 rc = (*it)->COMGETTER(NetworkName)(bstrNATNetworkName.asOutParam());
5427 if (FAILED(rc)) return rc;
5428
5429 if (Utf8Str(bstrNATNetworkName) == aNetworkName)
5430 {
5431 found = *it;
5432 break;
5433 }
5434 }
5435
5436 if (!found)
5437 return E_INVALIDARG;
5438 found.queryInterfaceTo(aNetwork.asOutParam());
5439 return rc;
5440#else
5441 NOREF(aNetworkName);
5442 NOREF(aNetwork);
5443 return E_NOTIMPL;
5444#endif
5445}
5446
5447HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
5448{
5449#ifdef VBOX_WITH_NAT_SERVICE
5450 Bstr name;
5451 HRESULT rc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
5452 if (FAILED(rc))
5453 return rc;
5454 INATNetwork *p = aNetwork;
5455 NATNetwork *network = static_cast<NATNetwork *>(p);
5456 rc = i_unregisterNATNetwork(network, true);
5457 fireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
5458 return rc;
5459#else
5460 NOREF(aNetwork);
5461 return E_NOTIMPL;
5462#endif
5463
5464}
5465/**
5466 * Remembers the given NAT network in the settings.
5467 *
5468 * @param aNATNetwork NAT Network object to remember.
5469 * @param aSaveSettings @c true to save settings to disk (default).
5470 *
5471 *
5472 * @note Locks this object for writing and @a aNATNetwork for reading.
5473 */
5474HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
5475 bool aSaveSettings /*= true*/)
5476{
5477#ifdef VBOX_WITH_NAT_SERVICE
5478 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5479
5480 AutoCaller autoCaller(this);
5481 AssertComRCReturnRC(autoCaller.rc());
5482
5483 AutoCaller natNetworkCaller(aNATNetwork);
5484 AssertComRCReturnRC(natNetworkCaller.rc());
5485
5486 Bstr name;
5487 HRESULT rc;
5488 rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5489 AssertComRCReturnRC(rc);
5490
5491 /* returned value isn't 0 and aSaveSettings is true
5492 * means that we create duplicate, otherwise we just load settings.
5493 */
5494 if ( sNatNetworkNameToRefCount[name]
5495 && aSaveSettings)
5496 AssertComRCReturnRC(E_INVALIDARG);
5497
5498 rc = S_OK;
5499
5500 sNatNetworkNameToRefCount[name] = 0;
5501
5502 m->allNATNetworks.addChild(aNATNetwork);
5503
5504 if (aSaveSettings)
5505 {
5506 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5507 rc = i_saveSettings();
5508 vboxLock.release();
5509
5510 if (FAILED(rc))
5511 i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
5512 }
5513
5514 return rc;
5515#else
5516 NOREF(aNATNetwork);
5517 NOREF(aSaveSettings);
5518 /* No panic please (silently ignore) */
5519 return S_OK;
5520#endif
5521}
5522
5523/**
5524 * Removes the given NAT network from the settings.
5525 *
5526 * @param aNATNetwork NAT network object to remove.
5527 * @param aSaveSettings @c true to save settings to disk (default).
5528 *
5529 * When @a aSaveSettings is @c true, this operation may fail because of the
5530 * failed #i_saveSettings() method it calls. In this case, the DHCP server
5531 * will NOT be removed from the settingsi when this method returns.
5532 *
5533 * @note Locks this object for writing.
5534 */
5535HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
5536 bool aSaveSettings /*= true*/)
5537{
5538#ifdef VBOX_WITH_NAT_SERVICE
5539 AssertReturn(aNATNetwork != NULL, E_INVALIDARG);
5540
5541 AutoCaller autoCaller(this);
5542 AssertComRCReturnRC(autoCaller.rc());
5543
5544 AutoCaller natNetworkCaller(aNATNetwork);
5545 AssertComRCReturnRC(natNetworkCaller.rc());
5546
5547 Bstr name;
5548 HRESULT rc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
5549 /* Hm, there're still running clients. */
5550 if (FAILED(rc) || sNatNetworkNameToRefCount[name])
5551 AssertComRCReturnRC(E_INVALIDARG);
5552
5553 m->allNATNetworks.removeChild(aNATNetwork);
5554
5555 if (aSaveSettings)
5556 {
5557 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5558 rc = i_saveSettings();
5559 vboxLock.release();
5560
5561 if (FAILED(rc))
5562 i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
5563 }
5564
5565 return rc;
5566#else
5567 NOREF(aNATNetwork);
5568 NOREF(aSaveSettings);
5569 return E_NOTIMPL;
5570#endif
5571}
5572
5573
5574#ifdef RT_OS_WINDOWS
5575#include <psapi.h>
5576
5577/**
5578 * Report versions of installed drivers to release log.
5579 */
5580void VirtualBox::i_reportDriverVersions()
5581{
5582 /** @todo r=klaus this code is very confusing, as it uses TCHAR (and
5583 * randomly also _TCHAR, which sounds to me like asking for trouble),
5584 * the "sz" variable prefix but "%ls" for the format string - so the whole
5585 * thing is better compiled with UNICODE and _UNICODE defined. Would be
5586 * far easier to read if it would be coded explicitly for the unicode
5587 * case, as it won't work otherwise. */
5588 DWORD err;
5589 HRESULT hrc;
5590 LPVOID aDrivers[1024];
5591 LPVOID *pDrivers = aDrivers;
5592 UINT cNeeded = 0;
5593 TCHAR szSystemRoot[MAX_PATH];
5594 TCHAR *pszSystemRoot = szSystemRoot;
5595 LPVOID pVerInfo = NULL;
5596 DWORD cbVerInfo = 0;
5597
5598 do
5599 {
5600 cNeeded = GetWindowsDirectory(szSystemRoot, RT_ELEMENTS(szSystemRoot));
5601 if (cNeeded == 0)
5602 {
5603 err = GetLastError();
5604 hrc = HRESULT_FROM_WIN32(err);
5605 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
5606 hrc, hrc, err));
5607 break;
5608 }
5609 else if (cNeeded > RT_ELEMENTS(szSystemRoot))
5610 {
5611 /* The buffer is too small, allocate big one. */
5612 pszSystemRoot = (TCHAR *)RTMemTmpAlloc(cNeeded * sizeof(_TCHAR));
5613 if (!pszSystemRoot)
5614 {
5615 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cNeeded));
5616 break;
5617 }
5618 if (GetWindowsDirectory(pszSystemRoot, cNeeded) == 0)
5619 {
5620 err = GetLastError();
5621 hrc = HRESULT_FROM_WIN32(err);
5622 AssertLogRelMsgFailed(("GetWindowsDirectory failed, hr=%Rhrc (0x%x) err=%u\n",
5623 hrc, hrc, err));
5624 break;
5625 }
5626 }
5627
5628 DWORD cbNeeded = 0;
5629 if (!EnumDeviceDrivers(aDrivers, sizeof(aDrivers), &cbNeeded) || cbNeeded > sizeof(aDrivers))
5630 {
5631 pDrivers = (LPVOID *)RTMemTmpAlloc(cbNeeded);
5632 if (!EnumDeviceDrivers(pDrivers, cbNeeded, &cbNeeded))
5633 {
5634 err = GetLastError();
5635 hrc = HRESULT_FROM_WIN32(err);
5636 AssertLogRelMsgFailed(("EnumDeviceDrivers failed, hr=%Rhrc (0x%x) err=%u\n",
5637 hrc, hrc, err));
5638 break;
5639 }
5640 }
5641
5642 LogRel(("Installed Drivers:\n"));
5643
5644 TCHAR szDriver[1024];
5645 int cDrivers = cbNeeded / sizeof(pDrivers[0]);
5646 for (int i = 0; i < cDrivers; i++)
5647 {
5648 if (GetDeviceDriverBaseName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
5649 {
5650 if (_tcsnicmp(TEXT("vbox"), szDriver, 4))
5651 continue;
5652 }
5653 else
5654 continue;
5655 if (GetDeviceDriverFileName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
5656 {
5657 _TCHAR szTmpDrv[1024];
5658 _TCHAR *pszDrv = szDriver;
5659 if (!_tcsncmp(TEXT("\\SystemRoot"), szDriver, 11))
5660 {
5661 _tcscpy_s(szTmpDrv, pszSystemRoot);
5662 _tcsncat_s(szTmpDrv, szDriver + 11, sizeof(szTmpDrv) / sizeof(szTmpDrv[0]) - _tclen(pszSystemRoot));
5663 pszDrv = szTmpDrv;
5664 }
5665 else if (!_tcsncmp(TEXT("\\??\\"), szDriver, 4))
5666 pszDrv = szDriver + 4;
5667
5668 /* Allocate a buffer for version info. Reuse if large enough. */
5669 DWORD cbNewVerInfo = GetFileVersionInfoSize(pszDrv, NULL);
5670 if (cbNewVerInfo > cbVerInfo)
5671 {
5672 if (pVerInfo)
5673 RTMemTmpFree(pVerInfo);
5674 cbVerInfo = cbNewVerInfo;
5675 pVerInfo = RTMemTmpAlloc(cbVerInfo);
5676 if (!pVerInfo)
5677 {
5678 AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cbVerInfo));
5679 break;
5680 }
5681 }
5682
5683 if (GetFileVersionInfo(pszDrv, NULL, cbVerInfo, pVerInfo))
5684 {
5685 UINT cbSize = 0;
5686 LPBYTE lpBuffer = NULL;
5687 if (VerQueryValue(pVerInfo, TEXT("\\"), (VOID FAR* FAR*)&lpBuffer, &cbSize))
5688 {
5689 if (cbSize)
5690 {
5691 VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
5692 if (pFileInfo->dwSignature == 0xfeef04bd)
5693 {
5694 LogRel((" %ls (Version: %d.%d.%d.%d)\n", pszDrv,
5695 (pFileInfo->dwFileVersionMS >> 16) & 0xffff,
5696 (pFileInfo->dwFileVersionMS >> 0) & 0xffff,
5697 (pFileInfo->dwFileVersionLS >> 16) & 0xffff,
5698 (pFileInfo->dwFileVersionLS >> 0) & 0xffff));
5699 }
5700 }
5701 }
5702 }
5703 }
5704 }
5705
5706 }
5707 while (0);
5708
5709 if (pVerInfo)
5710 RTMemTmpFree(pVerInfo);
5711
5712 if (pDrivers != aDrivers)
5713 RTMemTmpFree(pDrivers);
5714
5715 if (pszSystemRoot != szSystemRoot)
5716 RTMemTmpFree(pszSystemRoot);
5717}
5718#else /* !RT_OS_WINDOWS */
5719void VirtualBox::i_reportDriverVersions(void)
5720{
5721}
5722#endif /* !RT_OS_WINDOWS */
5723
5724#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
5725
5726# include <psapi.h> /* for GetProcessImageFileNameW */
5727
5728/**
5729 * Callout from the wrapper.
5730 */
5731void VirtualBox::i_callHook(const char *a_pszFunction)
5732{
5733 RT_NOREF(a_pszFunction);
5734
5735 /*
5736 * Let'see figure out who is calling.
5737 * Note! Requires Vista+, so skip this entirely on older systems.
5738 */
5739 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
5740 {
5741 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
5742 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
5743 if ( rcRpc == RPC_S_OK
5744 && CallAttribs.ClientPID != 0)
5745 {
5746 RTPROCESS const pidClient = (RTPROCESS)(uintptr_t)CallAttribs.ClientPID;
5747 if (pidClient != RTProcSelf())
5748 {
5749 /** @todo LogRel2 later: */
5750 LogRel(("i_callHook: %Rfn [ClientPID=%#zx/%zu IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
5751 a_pszFunction, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
5752 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
5753 &CallAttribs.InterfaceUuid));
5754
5755 /*
5756 * Do we know this client PID already?
5757 */
5758 RTCritSectRwEnterShared(&m->WatcherCritSect);
5759 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(pidClient);
5760 if (It != m->WatchedProcesses.end())
5761 RTCritSectRwLeaveShared(&m->WatcherCritSect); /* Known process, nothing to do. */
5762 else
5763 {
5764 /* This is a new client process, start watching it. */
5765 RTCritSectRwLeaveShared(&m->WatcherCritSect);
5766 i_watchClientProcess(pidClient, a_pszFunction);
5767 }
5768 }
5769 }
5770 else
5771 LogRel(("i_callHook: %Rfn - rcRpc=%#x ClientPID=%#zx/%zu !! [IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
5772 a_pszFunction, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
5773 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
5774 &CallAttribs.InterfaceUuid));
5775 }
5776}
5777
5778
5779/**
5780 * Wathces @a a_pidClient for termination.
5781 *
5782 * @returns true if successfully enabled watching of it, false if not.
5783 * @param a_pidClient The PID to watch.
5784 * @param a_pszFunction The function we which we detected the client in.
5785 */
5786bool VirtualBox::i_watchClientProcess(RTPROCESS a_pidClient, const char *a_pszFunction)
5787{
5788 RT_NOREF_PV(a_pszFunction);
5789
5790 /*
5791 * Open the client process.
5792 */
5793 HANDLE hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE /*fInherit*/, a_pidClient);
5794 if (hClient == NULL)
5795 hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE , a_pidClient);
5796 if (hClient == NULL)
5797 hClient = OpenProcess(SYNCHRONIZE, FALSE , a_pidClient);
5798 AssertLogRelMsgReturn(hClient != NULL, ("pidClient=%d (%#x) err=%d\n", a_pidClient, a_pidClient, GetLastError()),
5799 m->fWatcherIsReliable = false);
5800
5801 /*
5802 * Create a new watcher structure and try add it to the map.
5803 */
5804 bool fRet = true;
5805 WatchedClientProcess *pWatched = new (std::nothrow) WatchedClientProcess(a_pidClient, hClient);
5806 if (pWatched)
5807 {
5808 RTCritSectRwEnterExcl(&m->WatcherCritSect);
5809
5810 WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(a_pidClient);
5811 if (It == m->WatchedProcesses.end())
5812 {
5813 try
5814 {
5815 m->WatchedProcesses.insert(WatchedClientProcessMap::value_type(a_pidClient, pWatched));
5816 }
5817 catch (std::bad_alloc &)
5818 {
5819 fRet = false;
5820 }
5821 if (fRet)
5822 {
5823 /*
5824 * Schedule it on a watcher thread.
5825 */
5826 /** @todo later. */
5827 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
5828 }
5829 else
5830 {
5831 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
5832 delete pWatched;
5833 LogRel(("VirtualBox::i_watchClientProcess: out of memory inserting into client map!\n"));
5834 }
5835 }
5836 else
5837 {
5838 /*
5839 * Someone raced us here, we lost.
5840 */
5841 RTCritSectRwLeaveExcl(&m->WatcherCritSect);
5842 delete pWatched;
5843 }
5844 }
5845 else
5846 {
5847 LogRel(("VirtualBox::i_watchClientProcess: out of memory!\n"));
5848 CloseHandle(hClient);
5849 m->fWatcherIsReliable = fRet = false;
5850 }
5851 return fRet;
5852}
5853
5854
5855/** Logs the RPC caller info to the release log. */
5856/*static*/ void VirtualBox::i_logCaller(const char *a_pszFormat, ...)
5857{
5858 if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
5859 {
5860 char szTmp[80];
5861 va_list va;
5862 va_start(va, a_pszFormat);
5863 RTStrPrintfV(szTmp, sizeof(szTmp), a_pszFormat, va);
5864 va_end(va);
5865
5866 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
5867 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
5868
5869 RTUTF16 wszProcName[256];
5870 wszProcName[0] = '\0';
5871 if (rcRpc == 0 && CallAttribs.ClientPID != 0)
5872 {
5873 HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)(uintptr_t)CallAttribs.ClientPID);
5874 if (hProcess)
5875 {
5876 RT_ZERO(wszProcName);
5877 GetProcessImageFileNameW(hProcess, wszProcName, RT_ELEMENTS(wszProcName) - 1);
5878 CloseHandle(hProcess);
5879 }
5880 }
5881 LogRel(("%s [rcRpc=%#x ClientPID=%#zx/%zu (%ls) IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
5882 szTmp, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, wszProcName, CallAttribs.IsClientLocal,
5883 CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
5884 &CallAttribs.InterfaceUuid));
5885 }
5886}
5887
5888#endif /* RT_OS_WINDOWS && VBOXSVC_WITH_CLIENT_WATCHER */
5889
5890
5891/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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