VirtualBox

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

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

Main: bugref:6913: Fixed NULL id in the IMediumRegisteredEvent and fixed generation other medium and storage device events

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

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