VirtualBox

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

Last change on this file since 73188 was 73155, checked in by vboxsync, 7 years ago

bugref:9152. The function createCloudUserProfileManager was added.

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

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