VirtualBox

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

Last change on this file since 69731 was 69500, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

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

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