VirtualBox

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

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

Shared Clipboard/URI: Update.

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