VirtualBox

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

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

Autostart: Make the path to the autostart database configurable

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

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