VirtualBox

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

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

Main: fix COM/XPCOM incompatibility issues and add safearray setter support to the C binding XSLT, too

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