VirtualBox

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

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

Main: Machine+VirtualBox: slightly prettier fix to bugref:9075, including comment adjustments

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