VirtualBox

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

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

Main: fixed wrong access

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