VirtualBox

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

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

Main: bugref:6913: Fixed compiler errors

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