VirtualBox

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

Last change on this file since 55839 was 55839, checked in by vboxsync, 10 years ago

VBoxSVC: log the home directory

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

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