VirtualBox

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

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

optional encrypted store of the iSCSI initiator secret

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