VirtualBox

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

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

6813 src-all/ExtPackManagerImpl.cpp

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

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