VirtualBox

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

Last change on this file since 42712 was 42569, checked in by vboxsync, 13 years ago

Main/VirtualBox+Machine: new API method for getting VMs which are in the given groups, plus a bit of performance tuning/simplification

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