VirtualBox

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

Last change on this file since 47561 was 47561, checked in by vboxsync, 11 years ago

Main/VirtualBox+Machine+Session: separate out the client death detection functionality into separate objects

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