VirtualBox

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

Last change on this file since 59967 was 59571, checked in by vboxsync, 9 years ago

Main(bugref:7809): Moved driver version reporting from VBox.log to VBoxSVC.log

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