VirtualBox

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

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

Main: propagate error during medium settings decryption

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 163.0 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 42210 2012-07-18 14:11:35Z 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 int vrc = decryptSettings();
2044 return RT_SUCCESS(vrc) ? S_OK : E_FAIL;
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 Bstr bstrName;
2055 pMedium->COMGETTER(Name)(bstrName.asOutParam());
2056 Utf8Str strPlaintext;
2057 int rc = decryptSetting(&strPlaintext, bstrCipher);
2058 if (RT_SUCCESS(rc))
2059 pMedium->setPropertyDirect("InitiatorSecret", strPlaintext);
2060 else
2061 return rc;
2062 }
2063 return VINF_SUCCESS;
2064}
2065
2066/**
2067 * Decrypt all encrypted settings.
2068 *
2069 * So far we only have encrypted iSCSI initiator secrets so we just go through
2070 * all hard disk mediums and determine the plain 'InitiatorSecret' from
2071 * 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
2072 * properties need to be null-terminated strings.
2073 */
2074int VirtualBox::decryptSettings()
2075{
2076 bool fFailure = false;
2077 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2078 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2079 mt != m->allHardDisks.end();
2080 ++mt)
2081 {
2082 ComObjPtr<Medium> pMedium = *mt;
2083 AutoCaller medCaller(pMedium);
2084 if (FAILED(medCaller.rc()))
2085 continue;
2086 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2087 int vrc = decryptMediumSettings(pMedium);
2088 if (RT_FAILURE(vrc))
2089 fFailure = true;
2090 }
2091 return fFailure ? VERR_INVALID_PARAMETER : VINF_SUCCESS;
2092}
2093
2094/**
2095 * Encode.
2096 *
2097 * @param aPlaintext plaintext to be encrypted
2098 * @param aCiphertext resulting ciphertext (base64-encoded)
2099 */
2100int VirtualBox::encryptSetting(const Utf8Str &aPlaintext, Utf8Str *aCiphertext)
2101{
2102 uint8_t abCiphertext[32];
2103 char szCipherBase64[128];
2104 size_t cchCipherBase64;
2105 int rc = encryptSettingBytes((uint8_t*)aPlaintext.c_str(), abCiphertext,
2106 aPlaintext.length()+1, sizeof(abCiphertext));
2107 if (RT_SUCCESS(rc))
2108 {
2109 rc = RTBase64Encode(abCiphertext, sizeof(abCiphertext),
2110 szCipherBase64, sizeof(szCipherBase64),
2111 &cchCipherBase64);
2112 if (RT_SUCCESS(rc))
2113 *aCiphertext = szCipherBase64;
2114 }
2115 return rc;
2116}
2117
2118/**
2119 * Decode.
2120 *
2121 * @param aPlaintext resulting plaintext
2122 * @param aCiphertext ciphertext (base64-encoded) to decrypt
2123 */
2124int VirtualBox::decryptSetting(Utf8Str *aPlaintext, const Utf8Str &aCiphertext)
2125{
2126 uint8_t abPlaintext[64];
2127 uint8_t abCiphertext[64];
2128 size_t cbCiphertext;
2129 int rc = RTBase64Decode(aCiphertext.c_str(),
2130 abCiphertext, sizeof(abCiphertext),
2131 &cbCiphertext, NULL);
2132 if (RT_SUCCESS(rc))
2133 {
2134 rc = decryptSettingBytes(abPlaintext, abCiphertext, cbCiphertext);
2135 if (RT_SUCCESS(rc))
2136 {
2137 /* check if this is really a Null-terminated string. */
2138 for (unsigned i = 0; i < cbCiphertext; i++)
2139 {
2140 if (abPlaintext[i] == '\0')
2141 {
2142 *aPlaintext = Utf8Str((const char*)abPlaintext);
2143 return VINF_SUCCESS;
2144 }
2145 }
2146 rc = VERR_INVALID_PARAMETER;
2147 }
2148 }
2149 return rc;
2150}
2151
2152/**
2153 * Encrypt secret bytes. Use the m->SettingsCipherKey as key.
2154 *
2155 * @param aPlaintext clear text to be encrypted
2156 * @param aCiphertext resulting encrypted text
2157 * @param aPlaintextSize size of the plaintext
2158 * @param aCiphertextSize size of the ciphertext
2159 */
2160int VirtualBox::encryptSettingBytes(const uint8_t *aPlaintext, uint8_t *aCiphertext,
2161 size_t aPlaintextSize, size_t aCiphertextSize) const
2162{
2163 unsigned i, j;
2164 uint8_t aBytes[64];
2165
2166 if (!m->fSettingsCipherKeySet)
2167 return VERR_INVALID_STATE;
2168
2169 if (aCiphertextSize > sizeof(aBytes))
2170 return VERR_BUFFER_OVERFLOW;
2171
2172 for (i = 0, j = 0; i < aPlaintextSize && i < aCiphertextSize; i++)
2173 {
2174 aCiphertext[i] = (aPlaintext[i] ^ m->SettingsCipherKey[j]);
2175 if (++j >= sizeof(m->SettingsCipherKey))
2176 j = 0;
2177 }
2178
2179 /* fill with random data to have a minimal length (salt) */
2180 if (i < aCiphertextSize)
2181 {
2182 RTRandBytes(aBytes, aCiphertextSize - i);
2183 for (; i < aCiphertextSize; i++)
2184 {
2185 aCiphertext[i] = aBytes[i] ^ m->SettingsCipherKey[j];
2186 if (++j >= sizeof(m->SettingsCipherKey))
2187 j = 0;
2188 }
2189 }
2190
2191 return VINF_SUCCESS;
2192}
2193
2194/**
2195 * Decrypt secret bytes. Use the m->SettingsCipherKey as key.
2196 *
2197 * @param aPlaintext resulting plaintext
2198 * @param aCiphertext ciphertext to be decrypted
2199 * @param aCiphertextSize size of the ciphertext == size of the plaintext
2200 */
2201int VirtualBox::decryptSettingBytes(uint8_t *aPlaintext,
2202 const uint8_t *aCiphertext, size_t aCiphertextSize) const
2203{
2204 if (!m->fSettingsCipherKeySet)
2205 return VERR_INVALID_STATE;
2206
2207 for (unsigned i = 0, j = 0; i < aCiphertextSize; i++)
2208 {
2209 aPlaintext[i] = aCiphertext[i] ^ m->SettingsCipherKey[j];
2210 if (++j >= sizeof(m->SettingsCipherKey))
2211 j = 0;
2212 }
2213
2214 return VINF_SUCCESS;
2215}
2216
2217/**
2218 * Store a settings key.
2219 *
2220 * @param aKey the key to store
2221 */
2222void VirtualBox::storeSettingsKey(const Utf8Str &aKey)
2223{
2224 RTSha512(aKey.c_str(), aKey.length(), m->SettingsCipherKey);
2225 m->fSettingsCipherKeySet = true;
2226}
2227
2228// public methods only for internal purposes
2229/////////////////////////////////////////////////////////////////////////////
2230
2231#ifdef DEBUG
2232void VirtualBox::dumpAllBackRefs()
2233{
2234 {
2235 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2236 for (MediaList::const_iterator mt = m->allHardDisks.begin();
2237 mt != m->allHardDisks.end();
2238 ++mt)
2239 {
2240 ComObjPtr<Medium> pMedium = *mt;
2241 pMedium->dumpBackRefs();
2242 }
2243 }
2244 {
2245 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2246 for (MediaList::const_iterator mt = m->allDVDImages.begin();
2247 mt != m->allDVDImages.end();
2248 ++mt)
2249 {
2250 ComObjPtr<Medium> pMedium = *mt;
2251 pMedium->dumpBackRefs();
2252 }
2253 }
2254}
2255#endif
2256
2257/**
2258 * Posts an event to the event queue that is processed asynchronously
2259 * on a dedicated thread.
2260 *
2261 * Posting events to the dedicated event queue is useful to perform secondary
2262 * actions outside any object locks -- for example, to iterate over a list
2263 * of callbacks and inform them about some change caused by some object's
2264 * method call.
2265 *
2266 * @param event event to post; must have been allocated using |new|, will
2267 * be deleted automatically by the event thread after processing
2268 *
2269 * @note Doesn't lock any object.
2270 */
2271HRESULT VirtualBox::postEvent(Event *event)
2272{
2273 AssertReturn(event, E_FAIL);
2274
2275 HRESULT rc;
2276 AutoCaller autoCaller(this);
2277 if (SUCCEEDED((rc = autoCaller.rc())))
2278 {
2279 if (autoCaller.state() != Ready)
2280 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
2281 autoCaller.state()));
2282 // return S_OK
2283 else if ( (m->pAsyncEventQ)
2284 && (m->pAsyncEventQ->postEvent(event))
2285 )
2286 return S_OK;
2287 else
2288 rc = E_FAIL;
2289 }
2290
2291 // in any event of failure, we must clean up here, or we'll leak;
2292 // the caller has allocated the object using new()
2293 delete event;
2294 return rc;
2295}
2296
2297/**
2298 * Adds a progress to the global collection of pending operations.
2299 * Usually gets called upon progress object initialization.
2300 *
2301 * @param aProgress Operation to add to the collection.
2302 *
2303 * @note Doesn't lock objects.
2304 */
2305HRESULT VirtualBox::addProgress(IProgress *aProgress)
2306{
2307 CheckComArgNotNull(aProgress);
2308
2309 AutoCaller autoCaller(this);
2310 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2311
2312 Bstr id;
2313 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
2314 AssertComRCReturnRC(rc);
2315
2316 /* protect mProgressOperations */
2317 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2318
2319 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
2320 return S_OK;
2321}
2322
2323/**
2324 * Removes the progress from the global collection of pending operations.
2325 * Usually gets called upon progress completion.
2326 *
2327 * @param aId UUID of the progress operation to remove
2328 *
2329 * @note Doesn't lock objects.
2330 */
2331HRESULT VirtualBox::removeProgress(IN_GUID aId)
2332{
2333 AutoCaller autoCaller(this);
2334 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2335
2336 ComPtr<IProgress> progress;
2337
2338 /* protect mProgressOperations */
2339 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
2340
2341 size_t cnt = m->mapProgressOperations.erase(aId);
2342 Assert(cnt == 1);
2343 NOREF(cnt);
2344
2345 return S_OK;
2346}
2347
2348#ifdef RT_OS_WINDOWS
2349
2350struct StartSVCHelperClientData
2351{
2352 ComObjPtr<VirtualBox> that;
2353 ComObjPtr<Progress> progress;
2354 bool privileged;
2355 VirtualBox::SVCHelperClientFunc func;
2356 void *user;
2357};
2358
2359/**
2360 * Helper method that starts a worker thread that:
2361 * - creates a pipe communication channel using SVCHlpClient;
2362 * - starts an SVC Helper process that will inherit this channel;
2363 * - executes the supplied function by passing it the created SVCHlpClient
2364 * and opened instance to communicate to the Helper process and the given
2365 * Progress object.
2366 *
2367 * The user function is supposed to communicate to the helper process
2368 * using the \a aClient argument to do the requested job and optionally expose
2369 * the progress through the \a aProgress object. The user function should never
2370 * call notifyComplete() on it: this will be done automatically using the
2371 * result code returned by the function.
2372 *
2373 * Before the user function is started, the communication channel passed to
2374 * the \a aClient argument is fully set up, the function should start using
2375 * its write() and read() methods directly.
2376 *
2377 * The \a aVrc parameter of the user function may be used to return an error
2378 * code if it is related to communication errors (for example, returned by
2379 * the SVCHlpClient members when they fail). In this case, the correct error
2380 * message using this value will be reported to the caller. Note that the
2381 * value of \a aVrc is inspected only if the user function itself returns
2382 * success.
2383 *
2384 * If a failure happens anywhere before the user function would be normally
2385 * called, it will be called anyway in special "cleanup only" mode indicated
2386 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
2387 * all the function is supposed to do is to cleanup its aUser argument if
2388 * necessary (it's assumed that the ownership of this argument is passed to
2389 * the user function once #startSVCHelperClient() returns a success, thus
2390 * making it responsible for the cleanup).
2391 *
2392 * After the user function returns, the thread will send the SVCHlpMsg::Null
2393 * message to indicate a process termination.
2394 *
2395 * @param aPrivileged |true| to start the SVC Helper process as a privileged
2396 * user that can perform administrative tasks
2397 * @param aFunc user function to run
2398 * @param aUser argument to the user function
2399 * @param aProgress progress object that will track operation completion
2400 *
2401 * @note aPrivileged is currently ignored (due to some unsolved problems in
2402 * Vista) and the process will be started as a normal (unprivileged)
2403 * process.
2404 *
2405 * @note Doesn't lock anything.
2406 */
2407HRESULT VirtualBox::startSVCHelperClient(bool aPrivileged,
2408 SVCHelperClientFunc aFunc,
2409 void *aUser, Progress *aProgress)
2410{
2411 AssertReturn(aFunc, E_POINTER);
2412 AssertReturn(aProgress, E_POINTER);
2413
2414 AutoCaller autoCaller(this);
2415 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2416
2417 /* create the SVCHelperClientThread() argument */
2418 std::auto_ptr <StartSVCHelperClientData>
2419 d(new StartSVCHelperClientData());
2420 AssertReturn(d.get(), E_OUTOFMEMORY);
2421
2422 d->that = this;
2423 d->progress = aProgress;
2424 d->privileged = aPrivileged;
2425 d->func = aFunc;
2426 d->user = aUser;
2427
2428 RTTHREAD tid = NIL_RTTHREAD;
2429 int vrc = RTThreadCreate(&tid, SVCHelperClientThread,
2430 static_cast <void *>(d.get()),
2431 0, RTTHREADTYPE_MAIN_WORKER,
2432 RTTHREADFLAGS_WAITABLE, "SVCHelper");
2433 if (RT_FAILURE(vrc))
2434 return setError(E_FAIL, "Could not create SVCHelper thread (%Rrc)", vrc);
2435
2436 /* d is now owned by SVCHelperClientThread(), so release it */
2437 d.release();
2438
2439 return S_OK;
2440}
2441
2442/**
2443 * Worker thread for startSVCHelperClient().
2444 */
2445/* static */
2446DECLCALLBACK(int)
2447VirtualBox::SVCHelperClientThread(RTTHREAD aThread, void *aUser)
2448{
2449 LogFlowFuncEnter();
2450
2451 std::auto_ptr<StartSVCHelperClientData>
2452 d(static_cast<StartSVCHelperClientData*>(aUser));
2453
2454 HRESULT rc = S_OK;
2455 bool userFuncCalled = false;
2456
2457 do
2458 {
2459 AssertBreakStmt(d.get(), rc = E_POINTER);
2460 AssertReturn(!d->progress.isNull(), E_POINTER);
2461
2462 /* protect VirtualBox from uninitialization */
2463 AutoCaller autoCaller(d->that);
2464 if (!autoCaller.isOk())
2465 {
2466 /* it's too late */
2467 rc = autoCaller.rc();
2468 break;
2469 }
2470
2471 int vrc = VINF_SUCCESS;
2472
2473 Guid id;
2474 id.create();
2475 SVCHlpClient client;
2476 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2477 id.raw()).c_str());
2478 if (RT_FAILURE(vrc))
2479 {
2480 rc = d->that->setError(E_FAIL,
2481 tr("Could not create the communication channel (%Rrc)"), vrc);
2482 break;
2483 }
2484
2485 /* get the path to the executable */
2486 char exePathBuf[RTPATH_MAX];
2487 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2488 if (!exePath)
2489 {
2490 rc = d->that->setError(E_FAIL, tr("Cannot get executable name"));
2491 break;
2492 }
2493
2494 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2495
2496 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2497
2498 RTPROCESS pid = NIL_RTPROCESS;
2499
2500 if (d->privileged)
2501 {
2502 /* Attempt to start a privileged process using the Run As dialog */
2503
2504 Bstr file = exePath;
2505 Bstr parameters = argsStr;
2506
2507 SHELLEXECUTEINFO shExecInfo;
2508
2509 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2510
2511 shExecInfo.fMask = NULL;
2512 shExecInfo.hwnd = NULL;
2513 shExecInfo.lpVerb = L"runas";
2514 shExecInfo.lpFile = file.raw();
2515 shExecInfo.lpParameters = parameters.raw();
2516 shExecInfo.lpDirectory = NULL;
2517 shExecInfo.nShow = SW_NORMAL;
2518 shExecInfo.hInstApp = NULL;
2519
2520 if (!ShellExecuteEx(&shExecInfo))
2521 {
2522 int vrc2 = RTErrConvertFromWin32(GetLastError());
2523 /* hide excessive details in case of a frequent error
2524 * (pressing the Cancel button to close the Run As dialog) */
2525 if (vrc2 == VERR_CANCELLED)
2526 rc = d->that->setError(E_FAIL,
2527 tr("Operation canceled by the user"));
2528 else
2529 rc = d->that->setError(E_FAIL,
2530 tr("Could not launch a privileged process '%s' (%Rrc)"),
2531 exePath, vrc2);
2532 break;
2533 }
2534 }
2535 else
2536 {
2537 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2538 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2539 if (RT_FAILURE(vrc))
2540 {
2541 rc = d->that->setError(E_FAIL,
2542 tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2543 break;
2544 }
2545 }
2546
2547 /* wait for the client to connect */
2548 vrc = client.connect();
2549 if (RT_SUCCESS(vrc))
2550 {
2551 /* start the user supplied function */
2552 rc = d->func(&client, d->progress, d->user, &vrc);
2553 userFuncCalled = true;
2554 }
2555
2556 /* send the termination signal to the process anyway */
2557 {
2558 int vrc2 = client.write(SVCHlpMsg::Null);
2559 if (RT_SUCCESS(vrc))
2560 vrc = vrc2;
2561 }
2562
2563 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2564 {
2565 rc = d->that->setError(E_FAIL,
2566 tr("Could not operate the communication channel (%Rrc)"), vrc);
2567 break;
2568 }
2569 }
2570 while (0);
2571
2572 if (FAILED(rc) && !userFuncCalled)
2573 {
2574 /* call the user function in the "cleanup only" mode
2575 * to let it free resources passed to in aUser */
2576 d->func(NULL, NULL, d->user, NULL);
2577 }
2578
2579 d->progress->notifyComplete(rc);
2580
2581 LogFlowFuncLeave();
2582 return 0;
2583}
2584
2585#endif /* RT_OS_WINDOWS */
2586
2587/**
2588 * Sends a signal to the client watcher thread to rescan the set of machines
2589 * that have open sessions.
2590 *
2591 * @note Doesn't lock anything.
2592 */
2593void VirtualBox::updateClientWatcher()
2594{
2595 AutoCaller autoCaller(this);
2596 AssertComRCReturnVoid(autoCaller.rc());
2597
2598 AssertReturnVoid(m->threadClientWatcher != NIL_RTTHREAD);
2599
2600 /* sent an update request */
2601#if defined(RT_OS_WINDOWS)
2602 ::SetEvent(m->updateReq);
2603#elif defined(RT_OS_OS2)
2604 RTSemEventSignal(m->updateReq);
2605#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
2606 RTSemEventSignal(m->updateReq);
2607#else
2608# error "Port me!"
2609#endif
2610}
2611
2612/**
2613 * Adds the given child process ID to the list of processes to be reaped.
2614 * This call should be followed by #updateClientWatcher() to take the effect.
2615 */
2616void VirtualBox::addProcessToReap(RTPROCESS pid)
2617{
2618 AutoCaller autoCaller(this);
2619 AssertComRCReturnVoid(autoCaller.rc());
2620
2621 /// @todo (dmik) Win32?
2622#ifndef RT_OS_WINDOWS
2623 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2624 m->llProcesses.push_back(pid);
2625#endif
2626}
2627
2628/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2629struct MachineEvent : public VirtualBox::CallbackEvent
2630{
2631 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, BOOL aBool)
2632 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2633 , mBool(aBool)
2634 { }
2635
2636 MachineEvent(VirtualBox *aVB, VBoxEventType_T aWhat, const Guid &aId, MachineState_T aState)
2637 : CallbackEvent(aVB, aWhat), id(aId.toUtf16())
2638 , mState(aState)
2639 {}
2640
2641 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2642 {
2643 switch (mWhat)
2644 {
2645 case VBoxEventType_OnMachineDataChanged:
2646 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2647 break;
2648
2649 case VBoxEventType_OnMachineStateChanged:
2650 aEvDesc.init(aSource, mWhat, id.raw(), mState);
2651 break;
2652
2653 case VBoxEventType_OnMachineRegistered:
2654 aEvDesc.init(aSource, mWhat, id.raw(), mBool);
2655 break;
2656
2657 default:
2658 AssertFailedReturn(S_OK);
2659 }
2660 return S_OK;
2661 }
2662
2663 Bstr id;
2664 MachineState_T mState;
2665 BOOL mBool;
2666};
2667
2668/**
2669 * @note Doesn't lock any object.
2670 */
2671void VirtualBox::onMachineStateChange(const Guid &aId, MachineState_T aState)
2672{
2673 postEvent(new MachineEvent(this, VBoxEventType_OnMachineStateChanged, aId, aState));
2674}
2675
2676/**
2677 * @note Doesn't lock any object.
2678 */
2679void VirtualBox::onMachineDataChange(const Guid &aId, BOOL aTemporary)
2680{
2681 postEvent(new MachineEvent(this, VBoxEventType_OnMachineDataChanged, aId, aTemporary));
2682}
2683
2684/**
2685 * @note Locks this object for reading.
2686 */
2687BOOL VirtualBox::onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
2688 Bstr &aError)
2689{
2690 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
2691 aId.toString().c_str(), aKey, aValue));
2692
2693 AutoCaller autoCaller(this);
2694 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2695
2696 BOOL allowChange = TRUE;
2697 Bstr id = aId.toUtf16();
2698
2699 VBoxEventDesc evDesc;
2700 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
2701 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
2702 //Assert(fDelivered);
2703 if (fDelivered)
2704 {
2705 ComPtr<IEvent> aEvent;
2706 evDesc.getEvent(aEvent.asOutParam());
2707 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
2708 Assert(aCanChangeEvent);
2709 BOOL fVetoed = FALSE;
2710 aCanChangeEvent->IsVetoed(&fVetoed);
2711 allowChange = !fVetoed;
2712
2713 if (!allowChange)
2714 {
2715 SafeArray<BSTR> aVetos;
2716 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
2717 if (aVetos.size() > 0)
2718 aError = aVetos[0];
2719 }
2720 }
2721 else
2722 allowChange = TRUE;
2723
2724 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
2725 return allowChange;
2726}
2727
2728/** Event for onExtraDataChange() */
2729struct ExtraDataEvent : public VirtualBox::CallbackEvent
2730{
2731 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
2732 IN_BSTR aKey, IN_BSTR aVal)
2733 : CallbackEvent(aVB, VBoxEventType_OnExtraDataChanged)
2734 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
2735 {}
2736
2737 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2738 {
2739 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
2740 }
2741
2742 Bstr machineId, key, val;
2743};
2744
2745/**
2746 * @note Doesn't lock any object.
2747 */
2748void VirtualBox::onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
2749{
2750 postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
2751}
2752
2753/**
2754 * @note Doesn't lock any object.
2755 */
2756void VirtualBox::onMachineRegistered(const Guid &aId, BOOL aRegistered)
2757{
2758 postEvent(new MachineEvent(this, VBoxEventType_OnMachineRegistered, aId, aRegistered));
2759}
2760
2761/** Event for onSessionStateChange() */
2762struct SessionEvent : public VirtualBox::CallbackEvent
2763{
2764 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2765 : CallbackEvent(aVB, VBoxEventType_OnSessionStateChanged)
2766 , machineId(aMachineId.toUtf16()), sessionState(aState)
2767 {}
2768
2769 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2770 {
2771 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
2772 }
2773 Bstr machineId;
2774 SessionState_T sessionState;
2775};
2776
2777/**
2778 * @note Doesn't lock any object.
2779 */
2780void VirtualBox::onSessionStateChange(const Guid &aId, SessionState_T aState)
2781{
2782 postEvent(new SessionEvent(this, aId, aState));
2783}
2784
2785/** Event for onSnapshotTaken(), onSnapshotDeleted() and onSnapshotChange() */
2786struct SnapshotEvent : public VirtualBox::CallbackEvent
2787{
2788 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2789 VBoxEventType_T aWhat)
2790 : CallbackEvent(aVB, aWhat)
2791 , machineId(aMachineId), snapshotId(aSnapshotId)
2792 {}
2793
2794 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2795 {
2796 return aEvDesc.init(aSource, VBoxEventType_OnSnapshotTaken,
2797 machineId.toUtf16().raw(), snapshotId.toUtf16().raw());
2798 }
2799
2800 Guid machineId;
2801 Guid snapshotId;
2802};
2803
2804/**
2805 * @note Doesn't lock any object.
2806 */
2807void VirtualBox::onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
2808{
2809 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2810 VBoxEventType_OnSnapshotTaken));
2811}
2812
2813/**
2814 * @note Doesn't lock any object.
2815 */
2816void VirtualBox::onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
2817{
2818 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2819 VBoxEventType_OnSnapshotDeleted));
2820}
2821
2822/**
2823 * @note Doesn't lock any object.
2824 */
2825void VirtualBox::onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
2826{
2827 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2828 VBoxEventType_OnSnapshotChanged));
2829}
2830
2831/** Event for onGuestPropertyChange() */
2832struct GuestPropertyEvent : public VirtualBox::CallbackEvent
2833{
2834 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
2835 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
2836 : CallbackEvent(aVBox, VBoxEventType_OnGuestPropertyChanged),
2837 machineId(aMachineId),
2838 name(aName),
2839 value(aValue),
2840 flags(aFlags)
2841 {}
2842
2843 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2844 {
2845 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
2846 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
2847 }
2848
2849 Guid machineId;
2850 Bstr name, value, flags;
2851};
2852
2853/**
2854 * @note Doesn't lock any object.
2855 */
2856void VirtualBox::onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
2857 IN_BSTR aValue, IN_BSTR aFlags)
2858{
2859 postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
2860}
2861
2862/** Event for onMachineUninit(), this is not a CallbackEvent */
2863class MachineUninitEvent : public Event
2864{
2865public:
2866
2867 MachineUninitEvent(VirtualBox *aVirtualBox, Machine *aMachine)
2868 : mVirtualBox(aVirtualBox), mMachine(aMachine)
2869 {
2870 Assert(aVirtualBox);
2871 Assert(aMachine);
2872 }
2873
2874 void *handler()
2875 {
2876#ifdef VBOX_WITH_RESOURCE_USAGE_API
2877 /* Handle unregistering metrics here, as it is not vital to get
2878 * it done immediately. It reduces the number of locks needed and
2879 * the lock contention in SessionMachine::uninit. */
2880 {
2881 AutoWriteLock mLock(mMachine COMMA_LOCKVAL_SRC_POS);
2882 mMachine->unregisterMetrics(mVirtualBox->performanceCollector(), mMachine);
2883 }
2884#endif /* VBOX_WITH_RESOURCE_USAGE_API */
2885
2886 return NULL;
2887 }
2888
2889private:
2890
2891 /**
2892 * Note that this is a weak ref -- the CallbackEvent handler thread
2893 * is bound to the lifetime of the VirtualBox instance, so it's safe.
2894 */
2895 VirtualBox *mVirtualBox;
2896
2897 /** Reference to the machine object. */
2898 ComObjPtr<Machine> mMachine;
2899};
2900
2901/**
2902 * Trigger internal event. This isn't meant to be signalled to clients.
2903 * @note Doesn't lock any object.
2904 */
2905void VirtualBox::onMachineUninit(Machine *aMachine)
2906{
2907 postEvent(new MachineUninitEvent(this, aMachine));
2908}
2909
2910/**
2911 * @note Doesn't lock any object.
2912 */
2913void VirtualBox::onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
2914 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
2915 IN_BSTR aGuestIp, uint16_t aGuestPort)
2916{
2917 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
2918 aHostPort, aGuestIp, aGuestPort);
2919}
2920
2921/**
2922 * @note Locks this object for reading.
2923 */
2924ComObjPtr<GuestOSType> VirtualBox::getUnknownOSType()
2925{
2926 ComObjPtr<GuestOSType> type;
2927 AutoCaller autoCaller(this);
2928 AssertComRCReturn(autoCaller.rc(), type);
2929
2930 /* unknown type must always be the first */
2931 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
2932
2933 return m->allGuestOSTypes.front();
2934}
2935
2936/**
2937 * Returns the list of opened machines (machines having direct sessions opened
2938 * by client processes) and optionally the list of direct session controls.
2939 *
2940 * @param aMachines Where to put opened machines (will be empty if none).
2941 * @param aControls Where to put direct session controls (optional).
2942 *
2943 * @note The returned lists contain smart pointers. So, clear it as soon as
2944 * it becomes no more necessary to release instances.
2945 *
2946 * @note It can be possible that a session machine from the list has been
2947 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
2948 * when accessing unprotected data directly.
2949 *
2950 * @note Locks objects for reading.
2951 */
2952void VirtualBox::getOpenedMachines(SessionMachinesList &aMachines,
2953 InternalControlList *aControls /*= NULL*/)
2954{
2955 AutoCaller autoCaller(this);
2956 AssertComRCReturnVoid(autoCaller.rc());
2957
2958 aMachines.clear();
2959 if (aControls)
2960 aControls->clear();
2961
2962 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2963
2964 for (MachinesOList::iterator it = m->allMachines.begin();
2965 it != m->allMachines.end();
2966 ++it)
2967 {
2968 ComObjPtr<SessionMachine> sm;
2969 ComPtr<IInternalSessionControl> ctl;
2970 if ((*it)->isSessionOpen(sm, &ctl))
2971 {
2972 aMachines.push_back(sm);
2973 if (aControls)
2974 aControls->push_back(ctl);
2975 }
2976 }
2977}
2978
2979/**
2980 * Searches for a machine object with the given ID in the collection
2981 * of registered machines.
2982 *
2983 * @param aId Machine UUID to look for.
2984 * @param aPermitInaccessible If true, inaccessible machines will be found;
2985 * if false, this will fail if the given machine is inaccessible.
2986 * @param aSetError If true, set errorinfo if the machine is not found.
2987 * @param aMachine Returned machine, if found.
2988 * @return
2989 */
2990HRESULT VirtualBox::findMachine(const Guid &aId,
2991 bool fPermitInaccessible,
2992 bool aSetError,
2993 ComObjPtr<Machine> *aMachine /* = NULL */)
2994{
2995 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
2996
2997 AutoCaller autoCaller(this);
2998 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2999
3000 {
3001 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3002
3003 for (MachinesOList::iterator it = m->allMachines.begin();
3004 it != m->allMachines.end();
3005 ++it)
3006 {
3007 ComObjPtr<Machine> pMachine2 = *it;
3008
3009 if (!fPermitInaccessible)
3010 {
3011 // skip inaccessible machines
3012 AutoCaller machCaller(pMachine2);
3013 if (FAILED(machCaller.rc()))
3014 continue;
3015 }
3016
3017 if (pMachine2->getId() == aId)
3018 {
3019 rc = S_OK;
3020 if (aMachine)
3021 *aMachine = pMachine2;
3022 break;
3023 }
3024 }
3025 }
3026
3027 if (aSetError && FAILED(rc))
3028 rc = setError(rc,
3029 tr("Could not find a registered machine with UUID {%RTuuid}"),
3030 aId.raw());
3031
3032 return rc;
3033}
3034
3035static HRESULT validateMachineGroupHelper(const Utf8Str &aGroup)
3036{
3037 /* empty strings are invalid */
3038 if (aGroup.isEmpty())
3039 return E_INVALIDARG;
3040 /* the toplevel group is valid */
3041 if (aGroup == "/")
3042 return S_OK;
3043 /* any other strings of length 1 are invalid */
3044 if (aGroup.length() == 1)
3045 return E_INVALIDARG;
3046 /* must start with a slash */
3047 if (aGroup.c_str()[0] != '/')
3048 return E_INVALIDARG;
3049 /* must not end with a slash */
3050 if (aGroup.c_str()[aGroup.length() - 1] == '/')
3051 return E_INVALIDARG;
3052 /* check the group components */
3053 const char *pStr = aGroup.c_str() + 1; /* first char is /, skip it */
3054 while (pStr)
3055 {
3056 char *pSlash = RTStrStr(pStr, "/");
3057 if (pSlash)
3058 {
3059 /* no empty components (or // sequences in other words) */
3060 if (pSlash == pStr)
3061 return E_INVALIDARG;
3062 /* check if the machine name rules are violated, because that means
3063 * the group components is too close to the limits. */
3064 Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
3065 Utf8Str tmp2(tmp);
3066 sanitiseMachineFilename(tmp);
3067 if (tmp != tmp2)
3068 return E_INVALIDARG;
3069 pStr = pSlash + 1;
3070 }
3071 else
3072 {
3073 /* check if the machine name rules are violated, because that means
3074 * the group components is too close to the limits. */
3075 Utf8Str tmp(pStr);
3076 Utf8Str tmp2(tmp);
3077 sanitiseMachineFilename(tmp);
3078 if (tmp != tmp2)
3079 return E_INVALIDARG;
3080 pStr = NULL;
3081 }
3082 }
3083 return S_OK;
3084}
3085
3086/**
3087 * Validates a machine group.
3088 *
3089 * @param aMachineGroup Machine group.
3090 *
3091 * @return S_OK or E_INVALIDARG
3092 */
3093HRESULT VirtualBox::validateMachineGroup(const Utf8Str &aGroup)
3094{
3095 HRESULT rc = validateMachineGroupHelper(aGroup);
3096 if (FAILED(rc))
3097 rc = setError(rc,
3098 tr("Invalid machine group '%s'"),
3099 aGroup.c_str());
3100 return rc;
3101}
3102
3103/**
3104 * Takes a list of machine groups, and sanitizes/validates it.
3105 *
3106 * @param aMachineGroups Safearray with the machine groups.
3107 * @param pllMachineGroups Pointer to list of strings for the result.
3108 *
3109 * @return S_OK or E_INVALIDARG
3110 */
3111HRESULT VirtualBox::convertMachineGroups(ComSafeArrayIn(IN_BSTR, aMachineGroups), StringsList *pllMachineGroups)
3112{
3113 pllMachineGroups->clear();
3114 if (aMachineGroups)
3115 {
3116 com::SafeArray<IN_BSTR> machineGroups(ComSafeArrayInArg(aMachineGroups));
3117 for (size_t i = 0; i < machineGroups.size(); i++)
3118 {
3119 Utf8Str group(machineGroups[i]);
3120 if (group.length() == 0)
3121 group = "/";
3122
3123 HRESULT rc = validateMachineGroup(group);
3124 if (FAILED(rc))
3125 return rc;
3126
3127 /* no duplicates please */
3128 if ( find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
3129 == pllMachineGroups->end())
3130 pllMachineGroups->push_back(group);
3131 }
3132 if (pllMachineGroups->size() == 0)
3133 pllMachineGroups->push_back("/");
3134 }
3135 else
3136 pllMachineGroups->push_back("/");
3137
3138 return S_OK;
3139}
3140
3141/**
3142 * Searches for a Medium object with the given ID in the list of registered
3143 * hard disks.
3144 *
3145 * @param aId ID of the hard disk. Must not be empty.
3146 * @param aSetError If @c true , the appropriate error info is set in case
3147 * when the hard disk is not found.
3148 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3149 *
3150 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3151 *
3152 * @note Locks the media tree for reading.
3153 */
3154HRESULT VirtualBox::findHardDiskById(const Guid &id,
3155 bool aSetError,
3156 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3157{
3158 AssertReturn(!id.isEmpty(), E_INVALIDARG);
3159
3160 // we use the hard disks map, but it is protected by the
3161 // hard disk _list_ lock handle
3162 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3163
3164 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
3165 if (it != m->mapHardDisks.end())
3166 {
3167 if (aHardDisk)
3168 *aHardDisk = (*it).second;
3169 return S_OK;
3170 }
3171
3172 if (aSetError)
3173 return setError(VBOX_E_OBJECT_NOT_FOUND,
3174 tr("Could not find an open hard disk with UUID {%RTuuid}"),
3175 id.raw());
3176
3177 return VBOX_E_OBJECT_NOT_FOUND;
3178}
3179
3180/**
3181 * Searches for a Medium object with the given ID or location in the list of
3182 * registered hard disks. If both ID and location are specified, the first
3183 * object that matches either of them (not necessarily both) is returned.
3184 *
3185 * @param aLocation Full location specification. Must not be empty.
3186 * @param aSetError If @c true , the appropriate error info is set in case
3187 * when the hard disk is not found.
3188 * @param aHardDisk Where to store the found hard disk object (can be NULL).
3189 *
3190 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3191 *
3192 * @note Locks the media tree for reading.
3193 */
3194HRESULT VirtualBox::findHardDiskByLocation(const Utf8Str &strLocation,
3195 bool aSetError,
3196 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
3197{
3198 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
3199
3200 // we use the hard disks map, but it is protected by the
3201 // hard disk _list_ lock handle
3202 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3203
3204 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
3205 it != m->mapHardDisks.end();
3206 ++it)
3207 {
3208 const ComObjPtr<Medium> &pHD = (*it).second;
3209
3210 AutoCaller autoCaller(pHD);
3211 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3212 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
3213
3214 Utf8Str strLocationFull = pHD->getLocationFull();
3215
3216 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
3217 {
3218 if (aHardDisk)
3219 *aHardDisk = pHD;
3220 return S_OK;
3221 }
3222 }
3223
3224 if (aSetError)
3225 return setError(VBOX_E_OBJECT_NOT_FOUND,
3226 tr("Could not find an open hard disk with location '%s'"),
3227 strLocation.c_str());
3228
3229 return VBOX_E_OBJECT_NOT_FOUND;
3230}
3231
3232/**
3233 * Searches for a Medium object with the given ID or location in the list of
3234 * registered DVD or floppy images, depending on the @a mediumType argument.
3235 * If both ID and file path are specified, the first object that matches either
3236 * of them (not necessarily both) is returned.
3237 *
3238 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
3239 * @param aId ID of the image file (unused when NULL).
3240 * @param aLocation Full path to the image file (unused when NULL).
3241 * @param aSetError If @c true, the appropriate error info is set in case when
3242 * the image is not found.
3243 * @param aImage Where to store the found image object (can be NULL).
3244 *
3245 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
3246 *
3247 * @note Locks the media tree for reading.
3248 */
3249HRESULT VirtualBox::findDVDOrFloppyImage(DeviceType_T mediumType,
3250 const Guid *aId,
3251 const Utf8Str &aLocation,
3252 bool aSetError,
3253 ComObjPtr<Medium> *aImage /* = NULL */)
3254{
3255 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
3256
3257 Utf8Str location;
3258 if (!aLocation.isEmpty())
3259 {
3260 int vrc = calculateFullPath(aLocation, location);
3261 if (RT_FAILURE(vrc))
3262 return setError(VBOX_E_FILE_ERROR,
3263 tr("Invalid image file location '%s' (%Rrc)"),
3264 aLocation.c_str(),
3265 vrc);
3266 }
3267
3268 MediaOList *pMediaList;
3269
3270 switch (mediumType)
3271 {
3272 case DeviceType_DVD:
3273 pMediaList = &m->allDVDImages;
3274 break;
3275
3276 case DeviceType_Floppy:
3277 pMediaList = &m->allFloppyImages;
3278 break;
3279
3280 default:
3281 return E_INVALIDARG;
3282 }
3283
3284 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
3285
3286 bool found = false;
3287
3288 for (MediaList::const_iterator it = pMediaList->begin();
3289 it != pMediaList->end();
3290 ++it)
3291 {
3292 // no AutoCaller, registered image life time is bound to this
3293 Medium *pMedium = *it;
3294 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
3295 const Utf8Str &strLocationFull = pMedium->getLocationFull();
3296
3297 found = ( aId
3298 && pMedium->getId() == *aId)
3299 || ( !aLocation.isEmpty()
3300 && RTPathCompare(location.c_str(),
3301 strLocationFull.c_str()) == 0);
3302 if (found)
3303 {
3304 if (pMedium->getDeviceType() != mediumType)
3305 {
3306 if (mediumType == DeviceType_DVD)
3307 return setError(E_INVALIDARG,
3308 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
3309 else
3310 return setError(E_INVALIDARG,
3311 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
3312 }
3313
3314 if (aImage)
3315 *aImage = pMedium;
3316 break;
3317 }
3318 }
3319
3320 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
3321
3322 if (aSetError && !found)
3323 {
3324 if (aId)
3325 setError(rc,
3326 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
3327 aId->raw(),
3328 m->strSettingsFilePath.c_str());
3329 else
3330 setError(rc,
3331 tr("Could not find an image file with location '%s' in the media registry ('%s')"),
3332 aLocation.c_str(),
3333 m->strSettingsFilePath.c_str());
3334 }
3335
3336 return rc;
3337}
3338
3339/**
3340 * Searches for an IMedium object that represents the given UUID.
3341 *
3342 * If the UUID is empty (indicating an empty drive), this sets pMedium
3343 * to NULL and returns S_OK.
3344 *
3345 * If the UUID refers to a host drive of the given device type, this
3346 * sets pMedium to the object from the list in IHost and returns S_OK.
3347 *
3348 * If the UUID is an image file, this sets pMedium to the object that
3349 * findDVDOrFloppyImage() returned.
3350 *
3351 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
3352 *
3353 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
3354 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
3355 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
3356 * @param pMedium out: IMedium object found.
3357 * @return
3358 */
3359HRESULT VirtualBox::findRemoveableMedium(DeviceType_T mediumType,
3360 const Guid &uuid,
3361 bool fRefresh,
3362 bool aSetError,
3363 ComObjPtr<Medium> &pMedium)
3364{
3365 if (uuid.isEmpty())
3366 {
3367 // that's easy
3368 pMedium.setNull();
3369 return S_OK;
3370 }
3371
3372 // first search for host drive with that UUID
3373 HRESULT rc = m->pHost->findHostDriveById(mediumType,
3374 uuid,
3375 fRefresh,
3376 pMedium);
3377 if (rc == VBOX_E_OBJECT_NOT_FOUND)
3378 // then search for an image with that UUID
3379 rc = findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);
3380
3381 return rc;
3382}
3383
3384HRESULT VirtualBox::findGuestOSType(const Bstr &bstrOSType,
3385 GuestOSType*& pGuestOSType)
3386{
3387 /* Look for a GuestOSType object */
3388 AssertMsg(m->allGuestOSTypes.size() != 0,
3389 ("Guest OS types array must be filled"));
3390
3391 if (bstrOSType.isEmpty())
3392 {
3393 pGuestOSType = NULL;
3394 return S_OK;
3395 }
3396
3397 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3398 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
3399 it != m->allGuestOSTypes.end();
3400 ++it)
3401 {
3402 if ((*it)->id() == bstrOSType)
3403 {
3404 pGuestOSType = *it;
3405 return S_OK;
3406 }
3407 }
3408
3409 return setError(VBOX_E_OBJECT_NOT_FOUND,
3410 tr("Guest OS type '%ls' is invalid"),
3411 bstrOSType.raw());
3412}
3413
3414/**
3415 * Returns the constant pseudo-machine UUID that is used to identify the
3416 * global media registry.
3417 *
3418 * Starting with VirtualBox 4.0 each medium remembers in its instance data
3419 * in which media registry it is saved (if any): this can either be a machine
3420 * UUID, if it's in a per-machine media registry, or this global ID.
3421 *
3422 * This UUID is only used to identify the VirtualBox object while VirtualBox
3423 * is running. It is a compile-time constant and not saved anywhere.
3424 *
3425 * @return
3426 */
3427const Guid& VirtualBox::getGlobalRegistryId() const
3428{
3429 return m->uuidMediaRegistry;
3430}
3431
3432const ComObjPtr<Host>& VirtualBox::host() const
3433{
3434 return m->pHost;
3435}
3436
3437SystemProperties* VirtualBox::getSystemProperties() const
3438{
3439 return m->pSystemProperties;
3440}
3441
3442#ifdef VBOX_WITH_EXTPACK
3443/**
3444 * Getter that SystemProperties and others can use to talk to the extension
3445 * pack manager.
3446 */
3447ExtPackManager* VirtualBox::getExtPackManager() const
3448{
3449 return m->ptrExtPackManager;
3450}
3451#endif
3452
3453/**
3454 * Getter that machines can talk to the autostart database.
3455 */
3456AutostartDb* VirtualBox::getAutostartDb() const
3457{
3458 return m->pAutostartDb;
3459}
3460
3461#ifdef VBOX_WITH_RESOURCE_USAGE_API
3462const ComObjPtr<PerformanceCollector>& VirtualBox::performanceCollector() const
3463{
3464 return m->pPerformanceCollector;
3465}
3466#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3467
3468/**
3469 * Returns the default machine folder from the system properties
3470 * with proper locking.
3471 * @return
3472 */
3473void VirtualBox::getDefaultMachineFolder(Utf8Str &str) const
3474{
3475 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3476 str = m->pSystemProperties->m->strDefaultMachineFolder;
3477}
3478
3479/**
3480 * Returns the default hard disk format from the system properties
3481 * with proper locking.
3482 * @return
3483 */
3484void VirtualBox::getDefaultHardDiskFormat(Utf8Str &str) const
3485{
3486 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
3487 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
3488}
3489
3490const Utf8Str& VirtualBox::homeDir() const
3491{
3492 return m->strHomeDir;
3493}
3494
3495/**
3496 * Calculates the absolute path of the given path taking the VirtualBox home
3497 * directory as the current directory.
3498 *
3499 * @param aPath Path to calculate the absolute path for.
3500 * @param aResult Where to put the result (used only on success, can be the
3501 * same Utf8Str instance as passed in @a aPath).
3502 * @return IPRT result.
3503 *
3504 * @note Doesn't lock any object.
3505 */
3506int VirtualBox::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3507{
3508 AutoCaller autoCaller(this);
3509 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
3510
3511 /* no need to lock since mHomeDir is const */
3512
3513 char folder[RTPATH_MAX];
3514 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
3515 strPath.c_str(),
3516 folder,
3517 sizeof(folder));
3518 if (RT_SUCCESS(vrc))
3519 aResult = folder;
3520
3521 return vrc;
3522}
3523
3524/**
3525 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
3526 * if it is a subdirectory thereof, or simply copying it otherwise.
3527 *
3528 * @param strSource Path to evalue and copy.
3529 * @param strTarget Buffer to receive target path.
3530 */
3531void VirtualBox::copyPathRelativeToConfig(const Utf8Str &strSource,
3532 Utf8Str &strTarget)
3533{
3534 AutoCaller autoCaller(this);
3535 AssertComRCReturnVoid(autoCaller.rc());
3536
3537 // no need to lock since mHomeDir is const
3538
3539 // use strTarget as a temporary buffer to hold the machine settings dir
3540 strTarget = m->strHomeDir;
3541 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3542 // is relative: then append what's left
3543 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3544 else
3545 // is not relative: then overwrite
3546 strTarget = strSource;
3547}
3548
3549// private methods
3550/////////////////////////////////////////////////////////////////////////////
3551
3552/**
3553 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3554 * location already registered.
3555 *
3556 * On return, sets @a aConflict to the string describing the conflicting medium,
3557 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3558 * either case. A failure is unexpected.
3559 *
3560 * @param aId UUID to check.
3561 * @param aLocation Location to check.
3562 * @param aConflict Where to return parameters of the conflicting medium.
3563 * @param ppMedium Medium reference in case this is simply a duplicate.
3564 *
3565 * @note Locks the media tree and media objects for reading.
3566 */
3567HRESULT VirtualBox::checkMediaForConflicts(const Guid &aId,
3568 const Utf8Str &aLocation,
3569 Utf8Str &aConflict,
3570 ComObjPtr<Medium> *ppMedium)
3571{
3572 AssertReturn(!aId.isEmpty() && !aLocation.isEmpty(), E_FAIL);
3573 AssertReturn(ppMedium, E_INVALIDARG);
3574
3575 aConflict.setNull();
3576 ppMedium->setNull();
3577
3578 AutoReadLock alock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3579
3580 HRESULT rc = S_OK;
3581
3582 ComObjPtr<Medium> pMediumFound;
3583 const char *pcszType = NULL;
3584
3585 if (!aId.isEmpty())
3586 rc = findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3587 if (FAILED(rc) && !aLocation.isEmpty())
3588 rc = findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3589 if (SUCCEEDED(rc))
3590 pcszType = tr("hard disk");
3591
3592 if (!pcszType)
3593 {
3594 rc = findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3595 if (SUCCEEDED(rc))
3596 pcszType = tr("CD/DVD image");
3597 }
3598
3599 if (!pcszType)
3600 {
3601 rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3602 if (SUCCEEDED(rc))
3603 pcszType = tr("floppy image");
3604 }
3605
3606 if (pcszType && pMediumFound)
3607 {
3608 /* Note: no AutoCaller since bound to this */
3609 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3610
3611 Utf8Str strLocFound = pMediumFound->getLocationFull();
3612 Guid idFound = pMediumFound->getId();
3613
3614 if ( (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
3615 && (idFound == aId)
3616 )
3617 *ppMedium = pMediumFound;
3618
3619 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3620 pcszType,
3621 strLocFound.c_str(),
3622 idFound.raw());
3623 }
3624
3625 return S_OK;
3626}
3627
3628/**
3629 * Called from Machine::prepareSaveSettings() when it has detected
3630 * that a machine has been renamed. Such renames will require
3631 * updating the global media registry during the
3632 * VirtualBox::saveSettings() that follows later.
3633*
3634 * When a machine is renamed, there may well be media (in particular,
3635 * diff images for snapshots) in the global registry that will need
3636 * to have their paths updated. Before 3.2, Machine::saveSettings
3637 * used to call VirtualBox::saveSettings implicitly, which was both
3638 * unintuitive and caused locking order problems. Now, we remember
3639 * such pending name changes with this method so that
3640 * VirtualBox::saveSettings() can process them properly.
3641 */
3642void VirtualBox::rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3643 const Utf8Str &strNewConfigDir)
3644{
3645 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3646
3647 Data::PendingMachineRename pmr;
3648 pmr.strConfigDirOld = strOldConfigDir;
3649 pmr.strConfigDirNew = strNewConfigDir;
3650 m->llPendingMachineRenames.push_back(pmr);
3651}
3652
3653struct SaveMediaRegistriesDesc
3654{
3655 MediaList llMedia;
3656 ComObjPtr<VirtualBox> pVirtualBox;
3657};
3658
3659static int fntSaveMediaRegistries(RTTHREAD ThreadSelf, void *pvUser)
3660{
3661 NOREF(ThreadSelf);
3662 SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
3663 if (!pDesc)
3664 {
3665 LogRelFunc(("Thread for saving media registries lacks parameters\n"));
3666 return VERR_INVALID_PARAMETER;
3667 }
3668
3669 for (MediaList::const_iterator it = pDesc->llMedia.begin();
3670 it != pDesc->llMedia.end();
3671 ++it)
3672 {
3673 Medium *pMedium = *it;
3674 pMedium->markRegistriesModified();
3675 }
3676
3677 pDesc->pVirtualBox->saveModifiedRegistries();
3678
3679 pDesc->llMedia.clear();
3680 pDesc->pVirtualBox.setNull();
3681 delete pDesc;
3682
3683 return VINF_SUCCESS;
3684}
3685
3686/**
3687 * Goes through all known media (hard disks, floppies and DVDs) and saves
3688 * those into the given settings::MediaRegistry structures whose registry
3689 * ID match the given UUID.
3690 *
3691 * Before actually writing to the structures, all media paths (not just the
3692 * ones for the given registry) are updated if machines have been renamed
3693 * since the last call.
3694 *
3695 * This gets called from two contexts:
3696 *
3697 * -- VirtualBox::saveSettings() with the UUID of the global registry
3698 * (VirtualBox::Data.uuidRegistry); this will save those media
3699 * which had been loaded from the global registry or have been
3700 * attached to a "legacy" machine which can't save its own registry;
3701 *
3702 * -- Machine::saveSettings() with the UUID of a machine, if a medium
3703 * has been attached to a machine created with VirtualBox 4.0 or later.
3704 *
3705 * Media which have only been temporarily opened without having been
3706 * attached to a machine have a NULL registry UUID and therefore don't
3707 * get saved.
3708 *
3709 * This locks the media tree. Throws HRESULT on errors!
3710 *
3711 * @param mediaRegistry Settings structure to fill.
3712 * @param uuidRegistry The UUID of the media registry; either a machine UUID (if machine registry) or the UUID of the global registry.
3713 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
3714 */
3715void VirtualBox::saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
3716 const Guid &uuidRegistry,
3717 const Utf8Str &strMachineFolder)
3718{
3719 // lock all media for the following; use a write lock because we're
3720 // modifying the PendingMachineRenamesList, which is protected by this
3721 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3722
3723 // if a machine was renamed, then we'll need to refresh media paths
3724 if (m->llPendingMachineRenames.size())
3725 {
3726 // make a single list from the three media lists so we don't need three loops
3727 MediaList llAllMedia;
3728 // with hard disks, we must use the map, not the list, because the list only has base images
3729 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
3730 llAllMedia.push_back(it->second);
3731 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
3732 llAllMedia.push_back(*it);
3733 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
3734 llAllMedia.push_back(*it);
3735
3736 SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
3737 for (MediaList::iterator it = llAllMedia.begin();
3738 it != llAllMedia.end();
3739 ++it)
3740 {
3741 Medium *pMedium = *it;
3742 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
3743 it2 != m->llPendingMachineRenames.end();
3744 ++it2)
3745 {
3746 const Data::PendingMachineRename &pmr = *it2;
3747 HRESULT rc = pMedium->updatePath(pmr.strConfigDirOld,
3748 pmr.strConfigDirNew);
3749 if (SUCCEEDED(rc))
3750 {
3751 // Remember which medium objects has been changed,
3752 // to trigger saving their registries later.
3753 pDesc->llMedia.push_back(pMedium);
3754 } else if (rc == VBOX_E_FILE_ERROR)
3755 /* nothing */;
3756 else
3757 AssertComRC(rc);
3758 }
3759 }
3760 // done, don't do it again until we have more machine renames
3761 m->llPendingMachineRenames.clear();
3762
3763 if (pDesc->llMedia.size())
3764 {
3765 // Handle the media registry saving in a separate thread, to
3766 // avoid giant locking problems and passing up the list many
3767 // levels up to whoever triggered saveSettings, as there are
3768 // lots of places which would need to handle saving more settings.
3769 pDesc->pVirtualBox = this;
3770 int vrc = RTThreadCreate(NULL,
3771 fntSaveMediaRegistries,
3772 (void *)pDesc,
3773 0, // cbStack (default)
3774 RTTHREADTYPE_MAIN_WORKER,
3775 0, // flags
3776 "SaveMediaReg");
3777 ComAssertRC(vrc);
3778 // failure means that settings aren't saved, but there isn't
3779 // much we can do besides avoiding memory leaks
3780 if (RT_FAILURE(vrc))
3781 {
3782 LogRelFunc(("Failed to create thread for saving media registries (%Rrc)\n", vrc));
3783 delete pDesc;
3784 }
3785 }
3786 else
3787 delete pDesc;
3788 }
3789
3790 struct {
3791 MediaOList &llSource;
3792 settings::MediaList &llTarget;
3793 } s[] =
3794 {
3795 // hard disks
3796 { m->allHardDisks, mediaRegistry.llHardDisks },
3797 // CD/DVD images
3798 { m->allDVDImages, mediaRegistry.llDvdImages },
3799 // floppy images
3800 { m->allFloppyImages, mediaRegistry.llFloppyImages }
3801 };
3802
3803 HRESULT rc;
3804
3805 for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
3806 {
3807 MediaOList &llSource = s[i].llSource;
3808 settings::MediaList &llTarget = s[i].llTarget;
3809 llTarget.clear();
3810 for (MediaList::const_iterator it = llSource.begin();
3811 it != llSource.end();
3812 ++it)
3813 {
3814 Medium *pMedium = *it;
3815 AutoCaller autoCaller(pMedium);
3816 if (FAILED(autoCaller.rc())) throw autoCaller.rc();
3817 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
3818
3819 if (pMedium->isInRegistry(uuidRegistry))
3820 {
3821 settings::Medium med;
3822 rc = pMedium->saveSettings(med, strMachineFolder); // this recurses into child hard disks
3823 if (FAILED(rc)) throw rc;
3824 llTarget.push_back(med);
3825 }
3826 }
3827 }
3828}
3829
3830/**
3831 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
3832 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
3833 * places internally when settings need saving.
3834 *
3835 * @note Caller must have locked the VirtualBox object for writing and must not hold any
3836 * other locks since this locks all kinds of member objects and trees temporarily,
3837 * which could cause conflicts.
3838 */
3839HRESULT VirtualBox::saveSettings()
3840{
3841 AutoCaller autoCaller(this);
3842 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3843
3844 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
3845 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
3846
3847 HRESULT rc = S_OK;
3848
3849 try
3850 {
3851 // machines
3852 m->pMainConfigFile->llMachines.clear();
3853 {
3854 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3855 for (MachinesOList::iterator it = m->allMachines.begin();
3856 it != m->allMachines.end();
3857 ++it)
3858 {
3859 Machine *pMachine = *it;
3860 // save actual machine registry entry
3861 settings::MachineRegistryEntry mre;
3862 rc = pMachine->saveRegistryEntry(mre);
3863 m->pMainConfigFile->llMachines.push_back(mre);
3864 }
3865 }
3866
3867 saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
3868 m->uuidMediaRegistry, // global media registry ID
3869 Utf8Str::Empty); // strMachineFolder
3870
3871 m->pMainConfigFile->llDhcpServers.clear();
3872 {
3873 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3874 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
3875 it != m->allDHCPServers.end();
3876 ++it)
3877 {
3878 settings::DHCPServer d;
3879 rc = (*it)->saveSettings(d);
3880 if (FAILED(rc)) throw rc;
3881 m->pMainConfigFile->llDhcpServers.push_back(d);
3882 }
3883 }
3884
3885 // leave extra data alone, it's still in the config file
3886
3887 // host data (USB filters)
3888 rc = m->pHost->saveSettings(m->pMainConfigFile->host);
3889 if (FAILED(rc)) throw rc;
3890
3891 rc = m->pSystemProperties->saveSettings(m->pMainConfigFile->systemProperties);
3892 if (FAILED(rc)) throw rc;
3893
3894 // and write out the XML, still under the lock
3895 m->pMainConfigFile->write(m->strSettingsFilePath);
3896 }
3897 catch (HRESULT err)
3898 {
3899 /* we assume that error info is set by the thrower */
3900 rc = err;
3901 }
3902 catch (...)
3903 {
3904 rc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
3905 }
3906
3907 return rc;
3908}
3909
3910/**
3911 * Helper to register the machine.
3912 *
3913 * When called during VirtualBox startup, adds the given machine to the
3914 * collection of registered machines. Otherwise tries to mark the machine
3915 * as registered, and, if succeeded, adds it to the collection and
3916 * saves global settings.
3917 *
3918 * @note The caller must have added itself as a caller of the @a aMachine
3919 * object if calls this method not on VirtualBox startup.
3920 *
3921 * @param aMachine machine to register
3922 *
3923 * @note Locks objects!
3924 */
3925HRESULT VirtualBox::registerMachine(Machine *aMachine)
3926{
3927 ComAssertRet(aMachine, E_INVALIDARG);
3928
3929 AutoCaller autoCaller(this);
3930 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3931
3932 HRESULT rc = S_OK;
3933
3934 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3935
3936 {
3937 ComObjPtr<Machine> pMachine;
3938 rc = findMachine(aMachine->getId(),
3939 true /* fPermitInaccessible */,
3940 false /* aDoSetError */,
3941 &pMachine);
3942 if (SUCCEEDED(rc))
3943 {
3944 /* sanity */
3945 AutoLimitedCaller machCaller(pMachine);
3946 AssertComRC(machCaller.rc());
3947
3948 return setError(E_INVALIDARG,
3949 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
3950 aMachine->getId().raw(),
3951 pMachine->getSettingsFileFull().c_str());
3952 }
3953
3954 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
3955 rc = S_OK;
3956 }
3957
3958 if (autoCaller.state() != InInit)
3959 {
3960 rc = aMachine->prepareRegister();
3961 if (FAILED(rc)) return rc;
3962 }
3963
3964 /* add to the collection of registered machines */
3965 m->allMachines.addChild(aMachine);
3966
3967 if (autoCaller.state() != InInit)
3968 rc = saveSettings();
3969
3970 return rc;
3971}
3972
3973/**
3974 * Remembers the given medium object by storing it in either the global
3975 * medium registry or a machine one.
3976 *
3977 * @note Caller must hold the media tree lock for writing; in addition, this
3978 * locks @a pMedium for reading
3979 *
3980 * @param pMedium Medium object to remember.
3981 * @param ppMedium Actually stored medium object. Can be different if due
3982 * to an unavoidable race there was a duplicate Medium object
3983 * created.
3984 * @param argType Either DeviceType_HardDisk, DeviceType_DVD or DeviceType_Floppy.
3985 * @return
3986 */
3987HRESULT VirtualBox::registerMedium(const ComObjPtr<Medium> &pMedium,
3988 ComObjPtr<Medium> *ppMedium,
3989 DeviceType_T argType)
3990{
3991 AssertReturn(pMedium != NULL, E_INVALIDARG);
3992 AssertReturn(ppMedium != NULL, E_INVALIDARG);
3993
3994 AutoCaller autoCaller(this);
3995 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3996
3997 AutoCaller mediumCaller(pMedium);
3998 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
3999
4000 const char *pszDevType = NULL;
4001 ObjectsList<Medium> *pall = NULL;
4002 switch (argType)
4003 {
4004 case DeviceType_HardDisk:
4005 pall = &m->allHardDisks;
4006 pszDevType = tr("hard disk");
4007 break;
4008 case DeviceType_DVD:
4009 pszDevType = tr("DVD image");
4010 pall = &m->allDVDImages;
4011 break;
4012 case DeviceType_Floppy:
4013 pszDevType = tr("floppy image");
4014 pall = &m->allFloppyImages;
4015 break;
4016 default:
4017 AssertMsgFailedReturn(("invalid device type %d", argType), E_INVALIDARG);
4018 }
4019
4020 // caller must hold the media tree write lock
4021 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4022
4023 Guid id;
4024 Utf8Str strLocationFull;
4025 ComObjPtr<Medium> pParent;
4026 {
4027 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4028 id = pMedium->getId();
4029 strLocationFull = pMedium->getLocationFull();
4030 pParent = pMedium->getParent();
4031 }
4032
4033 HRESULT rc;
4034
4035 Utf8Str strConflict;
4036 ComObjPtr<Medium> pDupMedium;
4037 rc = checkMediaForConflicts(id,
4038 strLocationFull,
4039 strConflict,
4040 &pDupMedium);
4041 if (FAILED(rc)) return rc;
4042
4043 if (pDupMedium.isNull())
4044 {
4045 if (strConflict.length())
4046 return setError(E_INVALIDARG,
4047 tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
4048 pszDevType,
4049 strLocationFull.c_str(),
4050 id.raw(),
4051 strConflict.c_str(),
4052 m->strSettingsFilePath.c_str());
4053
4054 // add to the collection if it is a base medium
4055 if (pParent.isNull())
4056 pall->getList().push_back(pMedium);
4057
4058 // store all hard disks (even differencing images) in the map
4059 if (argType == DeviceType_HardDisk)
4060 m->mapHardDisks[id] = pMedium;
4061
4062 *ppMedium = pMedium;
4063 }
4064 else
4065 {
4066 // pMedium may be the last reference to the Medium object, and the
4067 // caller may have specified the same ComObjPtr as the output parameter.
4068 // In this case the assignment will uninit the object, and we must not
4069 // have a caller pending.
4070 mediumCaller.release();
4071 *ppMedium = pDupMedium;
4072 }
4073
4074 return rc;
4075}
4076
4077/**
4078 * Removes the given medium from the respective registry.
4079 *
4080 * @param pMedium Hard disk object to remove.
4081 *
4082 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
4083 */
4084HRESULT VirtualBox::unregisterMedium(Medium *pMedium)
4085{
4086 AssertReturn(pMedium != NULL, E_INVALIDARG);
4087
4088 AutoCaller autoCaller(this);
4089 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4090
4091 AutoCaller mediumCaller(pMedium);
4092 AssertComRCReturn(mediumCaller.rc(), mediumCaller.rc());
4093
4094 // caller must hold the media tree write lock
4095 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4096
4097 Guid id;
4098 ComObjPtr<Medium> pParent;
4099 DeviceType_T devType;
4100 {
4101 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4102 id = pMedium->getId();
4103 pParent = pMedium->getParent();
4104 devType = pMedium->getDeviceType();
4105 }
4106
4107 ObjectsList<Medium> *pall = NULL;
4108 switch (devType)
4109 {
4110 case DeviceType_HardDisk:
4111 pall = &m->allHardDisks;
4112 break;
4113 case DeviceType_DVD:
4114 pall = &m->allDVDImages;
4115 break;
4116 case DeviceType_Floppy:
4117 pall = &m->allFloppyImages;
4118 break;
4119 default:
4120 AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
4121 }
4122
4123 // remove from the collection if it is a base medium
4124 if (pParent.isNull())
4125 pall->getList().remove(pMedium);
4126
4127 // remove all hard disks (even differencing images) from map
4128 if (devType == DeviceType_HardDisk)
4129 {
4130 size_t cnt = m->mapHardDisks.erase(id);
4131 Assert(cnt == 1);
4132 NOREF(cnt);
4133 }
4134
4135 return S_OK;
4136}
4137
4138/**
4139 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
4140 * with children appearing before their parents.
4141 * @param llMedia
4142 * @param pMedium
4143 */
4144void VirtualBox::pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
4145{
4146 // recurse first, then add ourselves; this way children end up on the
4147 // list before their parents
4148
4149 const MediaList &llChildren = pMedium->getChildren();
4150 for (MediaList::const_iterator it = llChildren.begin();
4151 it != llChildren.end();
4152 ++it)
4153 {
4154 Medium *pChild = *it;
4155 pushMediumToListWithChildren(llMedia, pChild);
4156 }
4157
4158 Log(("Pushing medium %RTuuid\n", pMedium->getId().raw()));
4159 llMedia.push_back(pMedium);
4160}
4161
4162/**
4163 * Unregisters all Medium objects which belong to the given machine registry.
4164 * Gets called from Machine::uninit() just before the machine object dies
4165 * and must only be called with a machine UUID as the registry ID.
4166 *
4167 * Locks the media tree.
4168 *
4169 * @param uuidMachine Medium registry ID (always a machine UUID)
4170 * @return
4171 */
4172HRESULT VirtualBox::unregisterMachineMedia(const Guid &uuidMachine)
4173{
4174 Assert(!uuidMachine.isEmpty());
4175
4176 LogFlowFuncEnter();
4177
4178 AutoCaller autoCaller(this);
4179 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4180
4181 MediaList llMedia2Close;
4182
4183 {
4184 AutoWriteLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4185
4186 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4187 it != m->allHardDisks.getList().end();
4188 ++it)
4189 {
4190 ComObjPtr<Medium> pMedium = *it;
4191 AutoCaller medCaller(pMedium);
4192 if (FAILED(medCaller.rc())) return medCaller.rc();
4193 AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
4194
4195 if (pMedium->isInRegistry(uuidMachine))
4196 // recursively with children first
4197 pushMediumToListWithChildren(llMedia2Close, pMedium);
4198 }
4199 }
4200
4201 for (MediaList::iterator it = llMedia2Close.begin();
4202 it != llMedia2Close.end();
4203 ++it)
4204 {
4205 ComObjPtr<Medium> pMedium = *it;
4206 Log(("Closing medium %RTuuid\n", pMedium->getId().raw()));
4207 AutoCaller mac(pMedium);
4208 pMedium->close(mac);
4209 }
4210
4211 LogFlowFuncLeave();
4212
4213 return S_OK;
4214}
4215
4216/**
4217 * Removes the given machine object from the internal list of registered machines.
4218 * Called from Machine::Unregister().
4219 * @param pMachine
4220 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
4221 * @return
4222 */
4223HRESULT VirtualBox::unregisterMachine(Machine *pMachine,
4224 const Guid &id)
4225{
4226 // remove from the collection of registered machines
4227 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4228 m->allMachines.removeChild(pMachine);
4229 // save the global registry
4230 HRESULT rc = saveSettings();
4231 alock.release();
4232
4233 /*
4234 * Now go over all known media and checks if they were registered in the
4235 * media registry of the given machine. Each such medium is then moved to
4236 * a different media registry to make sure it doesn't get lost since its
4237 * media registry is about to go away.
4238 *
4239 * This fixes the following use case: Image A.vdi of machine A is also used
4240 * by machine B, but registered in the media registry of machine A. If machine
4241 * A is deleted, A.vdi must be moved to the registry of B, or else B will
4242 * become inaccessible.
4243 */
4244 {
4245 AutoReadLock tlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4246 // iterate over the list of *base* images
4247 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
4248 it != m->allHardDisks.getList().end();
4249 ++it)
4250 {
4251 ComObjPtr<Medium> &pMedium = *it;
4252 AutoCaller medCaller(pMedium);
4253 if (FAILED(medCaller.rc())) return medCaller.rc();
4254 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
4255
4256 if (pMedium->removeRegistry(id, true /* fRecurse */))
4257 {
4258 // machine ID was found in base medium's registry list:
4259 // move this base image and all its children to another registry then
4260 // 1) first, find a better registry to add things to
4261 const Guid *puuidBetter = pMedium->getAnyMachineBackref();
4262 if (puuidBetter)
4263 {
4264 // 2) better registry found: then use that
4265 pMedium->addRegistry(*puuidBetter, true /* fRecurse */);
4266 // 3) and make sure the registry is saved below
4267 mlock.release();
4268 tlock.release();
4269 markRegistryModified(*puuidBetter);
4270 tlock.acquire();
4271 mlock.release();
4272 }
4273 }
4274 }
4275 }
4276
4277 saveModifiedRegistries();
4278
4279 /* fire an event */
4280 onMachineRegistered(id, FALSE);
4281
4282 return rc;
4283}
4284
4285/**
4286 * Marks the registry for @a uuid as modified, so that it's saved in a later
4287 * call to saveModifiedRegistries().
4288 *
4289 * @param uuid
4290 */
4291void VirtualBox::markRegistryModified(const Guid &uuid)
4292{
4293 if (uuid == getGlobalRegistryId())
4294 ASMAtomicIncU64(&m->uRegistryNeedsSaving);
4295 else
4296 {
4297 ComObjPtr<Machine> pMachine;
4298 HRESULT rc = findMachine(uuid,
4299 false /* fPermitInaccessible */,
4300 false /* aSetError */,
4301 &pMachine);
4302 if (SUCCEEDED(rc))
4303 {
4304 AutoCaller machineCaller(pMachine);
4305 if (SUCCEEDED(machineCaller.rc()))
4306 ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
4307 }
4308 }
4309}
4310
4311/**
4312 * Saves all settings files according to the modified flags in the Machine
4313 * objects and in the VirtualBox object.
4314 *
4315 * This locks machines and the VirtualBox object as necessary, so better not
4316 * hold any locks before calling this.
4317 *
4318 * @return
4319 */
4320void VirtualBox::saveModifiedRegistries()
4321{
4322 HRESULT rc = S_OK;
4323 bool fNeedsGlobalSettings = false;
4324 uint64_t uOld;
4325
4326 for (MachinesOList::iterator it = m->allMachines.begin();
4327 it != m->allMachines.end();
4328 ++it)
4329 {
4330 const ComObjPtr<Machine> &pMachine = *it;
4331
4332 for (;;)
4333 {
4334 uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
4335 if (!uOld)
4336 break;
4337 if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
4338 break;
4339 ASMNopPause();
4340 }
4341 if (uOld)
4342 {
4343 AutoCaller autoCaller(pMachine);
4344 if (FAILED(autoCaller.rc())) continue;
4345 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
4346 rc = pMachine->saveSettings(&fNeedsGlobalSettings,
4347 Machine::SaveS_Force); // caller said save, so stop arguing
4348 }
4349 }
4350
4351 for (;;)
4352 {
4353 uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
4354 if (!uOld)
4355 break;
4356 if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
4357 break;
4358 ASMNopPause();
4359 }
4360 if (uOld || fNeedsGlobalSettings)
4361 {
4362 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4363 rc = saveSettings();
4364 }
4365 NOREF(rc); /* XXX */
4366}
4367
4368/**
4369 * Checks if the path to the specified file exists, according to the path
4370 * information present in the file name. Optionally the path is created.
4371 *
4372 * Note that the given file name must contain the full path otherwise the
4373 * extracted relative path will be created based on the current working
4374 * directory which is normally unknown.
4375 *
4376 * @param aFileName Full file name which path is checked/created.
4377 * @param aCreate Flag if the path should be created if it doesn't exist.
4378 *
4379 * @return Extended error information on failure to check/create the path.
4380 */
4381/* static */
4382HRESULT VirtualBox::ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
4383{
4384 Utf8Str strDir(strFileName);
4385 strDir.stripFilename();
4386 if (!RTDirExists(strDir.c_str()))
4387 {
4388 if (fCreate)
4389 {
4390 int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
4391 if (RT_FAILURE(vrc))
4392 return setErrorStatic(VBOX_E_IPRT_ERROR,
4393 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
4394 strDir.c_str(),
4395 vrc));
4396 }
4397 else
4398 return setErrorStatic(VBOX_E_IPRT_ERROR,
4399 Utf8StrFmt(tr("Directory '%s' does not exist"),
4400 strDir.c_str()));
4401 }
4402
4403 return S_OK;
4404}
4405
4406const Utf8Str& VirtualBox::settingsFilePath()
4407{
4408 return m->strSettingsFilePath;
4409}
4410
4411/**
4412 * Returns the lock handle which protects the media trees (hard disks,
4413 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
4414 * are no longer protected by the VirtualBox lock, but by this more
4415 * specialized lock. Mind the locking order: always request this lock
4416 * after the VirtualBox object lock but before the locks of the media
4417 * objects contained in these lists. See AutoLock.h.
4418 */
4419RWLockHandle& VirtualBox::getMediaTreeLockHandle()
4420{
4421 return m->lockMedia;
4422}
4423
4424/**
4425 * Thread function that watches the termination of all client processes
4426 * that have opened sessions using IMachine::LockMachine()
4427 */
4428// static
4429DECLCALLBACK(int) VirtualBox::ClientWatcher(RTTHREAD /* thread */, void *pvUser)
4430{
4431 LogFlowFuncEnter();
4432
4433 VirtualBox *that = (VirtualBox*)pvUser;
4434 Assert(that);
4435
4436 typedef std::vector< ComObjPtr<Machine> > MachineVector;
4437 typedef std::vector< ComObjPtr<SessionMachine> > SessionMachineVector;
4438
4439 SessionMachineVector machines;
4440 MachineVector spawnedMachines;
4441
4442 size_t cnt = 0;
4443 size_t cntSpawned = 0;
4444
4445 VirtualBoxBase::initializeComForThread();
4446
4447#if defined(RT_OS_WINDOWS)
4448
4449 /// @todo (dmik) processes reaping!
4450
4451 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
4452 handles[0] = that->m->updateReq;
4453
4454 do
4455 {
4456 AutoCaller autoCaller(that);
4457 /* VirtualBox has been early uninitialized, terminate */
4458 if (!autoCaller.isOk())
4459 break;
4460
4461 do
4462 {
4463 /* release the caller to let uninit() ever proceed */
4464 autoCaller.release();
4465
4466 DWORD rc = ::WaitForMultipleObjects((DWORD)(1 + cnt + cntSpawned),
4467 handles,
4468 FALSE,
4469 INFINITE);
4470
4471 /* Restore the caller before using VirtualBox. If it fails, this
4472 * means VirtualBox is being uninitialized and we must terminate. */
4473 autoCaller.add();
4474 if (!autoCaller.isOk())
4475 break;
4476
4477 bool update = false;
4478
4479 if (rc == WAIT_OBJECT_0)
4480 {
4481 /* update event is signaled */
4482 update = true;
4483 }
4484 else if (rc > WAIT_OBJECT_0 && rc <= (WAIT_OBJECT_0 + cnt))
4485 {
4486 /* machine mutex is released */
4487 (machines[rc - WAIT_OBJECT_0 - 1])->checkForDeath();
4488 update = true;
4489 }
4490 else if (rc > WAIT_ABANDONED_0 && rc <= (WAIT_ABANDONED_0 + cnt))
4491 {
4492 /* machine mutex is abandoned due to client process termination */
4493 (machines[rc - WAIT_ABANDONED_0 - 1])->checkForDeath();
4494 update = true;
4495 }
4496 else if (rc > WAIT_OBJECT_0 + cnt && rc <= (WAIT_OBJECT_0 + cntSpawned))
4497 {
4498 /* spawned VM process has terminated (normally or abnormally) */
4499 (spawnedMachines[rc - WAIT_OBJECT_0 - cnt - 1])->
4500 checkForSpawnFailure();
4501 update = true;
4502 }
4503
4504 if (update)
4505 {
4506 /* close old process handles */
4507 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++i)
4508 CloseHandle(handles[i]);
4509
4510 // lock the machines list for reading
4511 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4512
4513 /* obtain a new set of opened machines */
4514 cnt = 0;
4515 machines.clear();
4516
4517 for (MachinesOList::iterator it = that->m->allMachines.begin();
4518 it != that->m->allMachines.end();
4519 ++it)
4520 {
4521 /// @todo handle situations with more than 64 objects
4522 AssertMsgBreak((1 + cnt) <= MAXIMUM_WAIT_OBJECTS,
4523 ("MAXIMUM_WAIT_OBJECTS reached"));
4524
4525 ComObjPtr<SessionMachine> sm;
4526 HANDLE ipcSem;
4527 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4528 {
4529 machines.push_back(sm);
4530 handles[1 + cnt] = ipcSem;
4531 ++cnt;
4532 }
4533 }
4534
4535 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4536
4537 /* obtain a new set of spawned machines */
4538 cntSpawned = 0;
4539 spawnedMachines.clear();
4540
4541 for (MachinesOList::iterator it = that->m->allMachines.begin();
4542 it != that->m->allMachines.end();
4543 ++it)
4544 {
4545 /// @todo handle situations with more than 64 objects
4546 AssertMsgBreak((1 + cnt + cntSpawned) <= MAXIMUM_WAIT_OBJECTS,
4547 ("MAXIMUM_WAIT_OBJECTS reached"));
4548
4549 RTPROCESS pid;
4550 if ((*it)->isSessionSpawning(&pid))
4551 {
4552 HANDLE ph = OpenProcess(SYNCHRONIZE, FALSE, pid);
4553 AssertMsg(ph != NULL, ("OpenProcess (pid=%d) failed with %d\n",
4554 pid, GetLastError()));
4555 if (rc == 0)
4556 {
4557 spawnedMachines.push_back(*it);
4558 handles[1 + cnt + cntSpawned] = ph;
4559 ++cntSpawned;
4560 }
4561 }
4562 }
4563
4564 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4565
4566 // machines lock unwinds here
4567 }
4568 }
4569 while (true);
4570 }
4571 while (0);
4572
4573 /* close old process handles */
4574 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++ i)
4575 CloseHandle(handles[i]);
4576
4577 /* release sets of machines if any */
4578 machines.clear();
4579 spawnedMachines.clear();
4580
4581 ::CoUninitialize();
4582
4583#elif defined(RT_OS_OS2)
4584
4585 /// @todo (dmik) processes reaping!
4586
4587 /* according to PMREF, 64 is the maximum for the muxwait list */
4588 SEMRECORD handles[64];
4589
4590 HMUX muxSem = NULLHANDLE;
4591
4592 do
4593 {
4594 AutoCaller autoCaller(that);
4595 /* VirtualBox has been early uninitialized, terminate */
4596 if (!autoCaller.isOk())
4597 break;
4598
4599 do
4600 {
4601 /* release the caller to let uninit() ever proceed */
4602 autoCaller.release();
4603
4604 int vrc = RTSemEventWait(that->m->updateReq, 500);
4605
4606 /* Restore the caller before using VirtualBox. If it fails, this
4607 * means VirtualBox is being uninitialized and we must terminate. */
4608 autoCaller.add();
4609 if (!autoCaller.isOk())
4610 break;
4611
4612 bool update = false;
4613 bool updateSpawned = false;
4614
4615 if (RT_SUCCESS(vrc))
4616 {
4617 /* update event is signaled */
4618 update = true;
4619 updateSpawned = true;
4620 }
4621 else
4622 {
4623 AssertMsg(vrc == VERR_TIMEOUT || vrc == VERR_INTERRUPTED,
4624 ("RTSemEventWait returned %Rrc\n", vrc));
4625
4626 /* are there any mutexes? */
4627 if (cnt > 0)
4628 {
4629 /* figure out what's going on with machines */
4630
4631 unsigned long semId = 0;
4632 APIRET arc = ::DosWaitMuxWaitSem(muxSem,
4633 SEM_IMMEDIATE_RETURN, &semId);
4634
4635 if (arc == NO_ERROR)
4636 {
4637 /* machine mutex is normally released */
4638 Assert(semId >= 0 && semId < cnt);
4639 if (semId >= 0 && semId < cnt)
4640 {
4641#if 0//def DEBUG
4642 {
4643 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4644 LogFlowFunc(("released mutex: machine='%ls'\n",
4645 machines[semId]->name().raw()));
4646 }
4647#endif
4648 machines[semId]->checkForDeath();
4649 }
4650 update = true;
4651 }
4652 else if (arc == ERROR_SEM_OWNER_DIED)
4653 {
4654 /* machine mutex is abandoned due to client process
4655 * termination; find which mutex is in the Owner Died
4656 * state */
4657 for (size_t i = 0; i < cnt; ++ i)
4658 {
4659 PID pid; TID tid;
4660 unsigned long reqCnt;
4661 arc = DosQueryMutexSem((HMTX)handles[i].hsemCur, &pid, &tid, &reqCnt);
4662 if (arc == ERROR_SEM_OWNER_DIED)
4663 {
4664 /* close the dead mutex as asked by PMREF */
4665 ::DosCloseMutexSem((HMTX)handles[i].hsemCur);
4666
4667 Assert(i >= 0 && i < cnt);
4668 if (i >= 0 && i < cnt)
4669 {
4670#if 0//def DEBUG
4671 {
4672 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4673 LogFlowFunc(("mutex owner dead: machine='%ls'\n",
4674 machines[i]->name().raw()));
4675 }
4676#endif
4677 machines[i]->checkForDeath();
4678 }
4679 }
4680 }
4681 update = true;
4682 }
4683 else
4684 AssertMsg(arc == ERROR_INTERRUPT || arc == ERROR_TIMEOUT,
4685 ("DosWaitMuxWaitSem returned %d\n", arc));
4686 }
4687
4688 /* are there any spawning sessions? */
4689 if (cntSpawned > 0)
4690 {
4691 for (size_t i = 0; i < cntSpawned; ++ i)
4692 updateSpawned |= (spawnedMachines[i])->
4693 checkForSpawnFailure();
4694 }
4695 }
4696
4697 if (update || updateSpawned)
4698 {
4699 AutoReadLock thatLock(that COMMA_LOCKVAL_SRC_POS);
4700
4701 if (update)
4702 {
4703 /* close the old muxsem */
4704 if (muxSem != NULLHANDLE)
4705 ::DosCloseMuxWaitSem(muxSem);
4706
4707 /* obtain a new set of opened machines */
4708 cnt = 0;
4709 machines.clear();
4710
4711 for (MachinesOList::iterator it = that->m->allMachines.begin();
4712 it != that->m->allMachines.end(); ++ it)
4713 {
4714 /// @todo handle situations with more than 64 objects
4715 AssertMsg(cnt <= 64 /* according to PMREF */,
4716 ("maximum of 64 mutex semaphores reached (%d)",
4717 cnt));
4718
4719 ComObjPtr<SessionMachine> sm;
4720 HMTX ipcSem;
4721 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4722 {
4723 machines.push_back(sm);
4724 handles[cnt].hsemCur = (HSEM)ipcSem;
4725 handles[cnt].ulUser = cnt;
4726 ++ cnt;
4727 }
4728 }
4729
4730 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4731
4732 if (cnt > 0)
4733 {
4734 /* create a new muxsem */
4735 APIRET arc = ::DosCreateMuxWaitSem(NULL, &muxSem, cnt,
4736 handles,
4737 DCMW_WAIT_ANY);
4738 AssertMsg(arc == NO_ERROR,
4739 ("DosCreateMuxWaitSem returned %d\n", arc));
4740 NOREF(arc);
4741 }
4742 }
4743
4744 if (updateSpawned)
4745 {
4746 /* obtain a new set of spawned machines */
4747 spawnedMachines.clear();
4748
4749 for (MachinesOList::iterator it = that->m->allMachines.begin();
4750 it != that->m->allMachines.end(); ++ it)
4751 {
4752 if ((*it)->isSessionSpawning())
4753 spawnedMachines.push_back(*it);
4754 }
4755
4756 cntSpawned = spawnedMachines.size();
4757 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4758 }
4759 }
4760 }
4761 while (true);
4762 }
4763 while (0);
4764
4765 /* close the muxsem */
4766 if (muxSem != NULLHANDLE)
4767 ::DosCloseMuxWaitSem(muxSem);
4768
4769 /* release sets of machines if any */
4770 machines.clear();
4771 spawnedMachines.clear();
4772
4773#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
4774
4775 bool update = false;
4776 bool updateSpawned = false;
4777
4778 do
4779 {
4780 AutoCaller autoCaller(that);
4781 if (!autoCaller.isOk())
4782 break;
4783
4784 do
4785 {
4786 /* release the caller to let uninit() ever proceed */
4787 autoCaller.release();
4788
4789 int rc = RTSemEventWait(that->m->updateReq, 500);
4790
4791 /*
4792 * Restore the caller before using VirtualBox. If it fails, this
4793 * means VirtualBox is being uninitialized and we must terminate.
4794 */
4795 autoCaller.add();
4796 if (!autoCaller.isOk())
4797 break;
4798
4799 if (RT_SUCCESS(rc) || update || updateSpawned)
4800 {
4801 /* RT_SUCCESS(rc) means an update event is signaled */
4802
4803 // lock the machines list for reading
4804 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4805
4806 if (RT_SUCCESS(rc) || update)
4807 {
4808 /* obtain a new set of opened machines */
4809 machines.clear();
4810
4811 for (MachinesOList::iterator it = that->m->allMachines.begin();
4812 it != that->m->allMachines.end();
4813 ++it)
4814 {
4815 ComObjPtr<SessionMachine> sm;
4816 if ((*it)->isSessionOpenOrClosing(sm))
4817 machines.push_back(sm);
4818 }
4819
4820 cnt = machines.size();
4821 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4822 }
4823
4824 if (RT_SUCCESS(rc) || updateSpawned)
4825 {
4826 /* obtain a new set of spawned machines */
4827 spawnedMachines.clear();
4828
4829 for (MachinesOList::iterator it = that->m->allMachines.begin();
4830 it != that->m->allMachines.end();
4831 ++it)
4832 {
4833 if ((*it)->isSessionSpawning())
4834 spawnedMachines.push_back(*it);
4835 }
4836
4837 cntSpawned = spawnedMachines.size();
4838 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4839 }
4840
4841 // machines lock unwinds here
4842 }
4843
4844 update = false;
4845 for (size_t i = 0; i < cnt; ++ i)
4846 update |= (machines[i])->checkForDeath();
4847
4848 updateSpawned = false;
4849 for (size_t i = 0; i < cntSpawned; ++ i)
4850 updateSpawned |= (spawnedMachines[i])->checkForSpawnFailure();
4851
4852 /* reap child processes */
4853 {
4854 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
4855 if (that->m->llProcesses.size())
4856 {
4857 LogFlowFunc(("UPDATE: child process count = %d\n",
4858 that->m->llProcesses.size()));
4859 VirtualBox::Data::ProcessList::iterator it = that->m->llProcesses.begin();
4860 while (it != that->m->llProcesses.end())
4861 {
4862 RTPROCESS pid = *it;
4863 RTPROCSTATUS status;
4864 int vrc = ::RTProcWait(pid, RTPROCWAIT_FLAGS_NOBLOCK, &status);
4865 if (vrc == VINF_SUCCESS)
4866 {
4867 LogFlowFunc(("pid %d (%x) was reaped, status=%d, reason=%d\n",
4868 pid, pid, status.iStatus,
4869 status.enmReason));
4870 it = that->m->llProcesses.erase(it);
4871 }
4872 else
4873 {
4874 LogFlowFunc(("pid %d (%x) was NOT reaped, vrc=%Rrc\n",
4875 pid, pid, vrc));
4876 if (vrc != VERR_PROCESS_RUNNING)
4877 {
4878 /* remove the process if it is not already running */
4879 it = that->m->llProcesses.erase(it);
4880 }
4881 else
4882 ++ it;
4883 }
4884 }
4885 }
4886 }
4887 }
4888 while (true);
4889 }
4890 while (0);
4891
4892 /* release sets of machines if any */
4893 machines.clear();
4894 spawnedMachines.clear();
4895
4896#else
4897# error "Port me!"
4898#endif
4899
4900 VirtualBoxBase::uninitializeComForThread();
4901 LogFlowFuncLeave();
4902 return 0;
4903}
4904
4905/**
4906 * Thread function that handles custom events posted using #postEvent().
4907 */
4908// static
4909DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4910{
4911 LogFlowFuncEnter();
4912
4913 AssertReturn(pvUser, VERR_INVALID_POINTER);
4914
4915 com::Initialize();
4916
4917 // create an event queue for the current thread
4918 EventQueue *eventQ = new EventQueue();
4919 AssertReturn(eventQ, VERR_NO_MEMORY);
4920
4921 // return the queue to the one who created this thread
4922 *(static_cast <EventQueue **>(pvUser)) = eventQ;
4923 // signal that we're ready
4924 RTThreadUserSignal(thread);
4925
4926 /*
4927 * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
4928 * we must not stop processing events and delete the "eventQ" object. This must
4929 * be done ONLY when we stop this loop via interruptEventQueueProcessing().
4930 * See @bugref{5724}.
4931 */
4932 while (eventQ->processEventQueue(RT_INDEFINITE_WAIT) != VERR_INTERRUPTED)
4933 /* nothing */ ;
4934
4935 delete eventQ;
4936
4937 com::Shutdown();
4938
4939
4940 LogFlowFuncLeave();
4941
4942 return 0;
4943}
4944
4945
4946////////////////////////////////////////////////////////////////////////////////
4947
4948/**
4949 * Takes the current list of registered callbacks of the managed VirtualBox
4950 * instance, and calls #handleCallback() for every callback item from the
4951 * list, passing the item as an argument.
4952 *
4953 * @note Locks the managed VirtualBox object for reading but leaves the lock
4954 * before iterating over callbacks and calling their methods.
4955 */
4956void *VirtualBox::CallbackEvent::handler()
4957{
4958 if (!mVirtualBox)
4959 return NULL;
4960
4961 AutoCaller autoCaller(mVirtualBox);
4962 if (!autoCaller.isOk())
4963 {
4964 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4965 autoCaller.state()));
4966 /* We don't need mVirtualBox any more, so release it */
4967 mVirtualBox = NULL;
4968 return NULL;
4969 }
4970
4971 {
4972 VBoxEventDesc evDesc;
4973 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4974
4975 evDesc.fire(/* don't wait for delivery */0);
4976 }
4977
4978 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4979 return NULL;
4980}
4981
4982//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4983//{
4984// return E_NOTIMPL;
4985//}
4986
4987STDMETHODIMP VirtualBox::CreateDHCPServer(IN_BSTR aName, IDHCPServer ** aServer)
4988{
4989 CheckComArgStrNotEmptyOrNull(aName);
4990 CheckComArgNotNull(aServer);
4991
4992 AutoCaller autoCaller(this);
4993 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4994
4995 ComObjPtr<DHCPServer> dhcpServer;
4996 dhcpServer.createObject();
4997 HRESULT rc = dhcpServer->init(this, aName);
4998 if (FAILED(rc)) return rc;
4999
5000 rc = registerDHCPServer(dhcpServer, true);
5001 if (FAILED(rc)) return rc;
5002
5003 dhcpServer.queryInterfaceTo(aServer);
5004
5005 return rc;
5006}
5007
5008STDMETHODIMP VirtualBox::FindDHCPServerByNetworkName(IN_BSTR aName, IDHCPServer ** aServer)
5009{
5010 CheckComArgStrNotEmptyOrNull(aName);
5011 CheckComArgNotNull(aServer);
5012
5013 AutoCaller autoCaller(this);
5014 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5015
5016 HRESULT rc;
5017 Bstr bstr;
5018 ComPtr<DHCPServer> found;
5019
5020 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
5021
5022 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
5023 it != m->allDHCPServers.end();
5024 ++it)
5025 {
5026 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
5027 if (FAILED(rc)) return rc;
5028
5029 if (bstr == aName)
5030 {
5031 found = *it;
5032 break;
5033 }
5034 }
5035
5036 if (!found)
5037 return E_INVALIDARG;
5038
5039 return found.queryInterfaceTo(aServer);
5040}
5041
5042STDMETHODIMP VirtualBox::RemoveDHCPServer(IDHCPServer * aServer)
5043{
5044 CheckComArgNotNull(aServer);
5045
5046 AutoCaller autoCaller(this);
5047 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5048
5049 HRESULT rc = unregisterDHCPServer(static_cast<DHCPServer *>(aServer), true);
5050
5051 return rc;
5052}
5053
5054/**
5055 * Remembers the given DHCP server in the settings.
5056 *
5057 * @param aDHCPServer DHCP server object to remember.
5058 * @param aSaveSettings @c true to save settings to disk (default).
5059 *
5060 * When @a aSaveSettings is @c true, this operation may fail because of the
5061 * failed #saveSettings() method it calls. In this case, the dhcp server object
5062 * will not be remembered. It is therefore the responsibility of the caller to
5063 * call this method as the last step of some action that requires registration
5064 * in order to make sure that only fully functional dhcp server objects get
5065 * registered.
5066 *
5067 * @note Locks this object for writing and @a aDHCPServer for reading.
5068 */
5069HRESULT VirtualBox::registerDHCPServer(DHCPServer *aDHCPServer,
5070 bool aSaveSettings /*= true*/)
5071{
5072 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5073
5074 AutoCaller autoCaller(this);
5075 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5076
5077 AutoCaller dhcpServerCaller(aDHCPServer);
5078 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
5079
5080 Bstr name;
5081 HRESULT rc;
5082 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
5083 if (FAILED(rc)) return rc;
5084
5085 ComPtr<IDHCPServer> existing;
5086 rc = FindDHCPServerByNetworkName(name.raw(), existing.asOutParam());
5087 if (SUCCEEDED(rc))
5088 return E_INVALIDARG;
5089
5090 rc = S_OK;
5091
5092 m->allDHCPServers.addChild(aDHCPServer);
5093
5094 if (aSaveSettings)
5095 {
5096 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5097 rc = saveSettings();
5098 vboxLock.release();
5099
5100 if (FAILED(rc))
5101 unregisterDHCPServer(aDHCPServer, false /* aSaveSettings */);
5102 }
5103
5104 return rc;
5105}
5106
5107/**
5108 * Removes the given DHCP server from the settings.
5109 *
5110 * @param aDHCPServer DHCP server object to remove.
5111 * @param aSaveSettings @c true to save settings to disk (default).
5112 *
5113 * When @a aSaveSettings is @c true, this operation may fail because of the
5114 * failed #saveSettings() method it calls. In this case, the DHCP server
5115 * will NOT be removed from the settingsi when this method returns.
5116 *
5117 * @note Locks this object for writing.
5118 */
5119HRESULT VirtualBox::unregisterDHCPServer(DHCPServer *aDHCPServer,
5120 bool aSaveSettings /*= true*/)
5121{
5122 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
5123
5124 AutoCaller autoCaller(this);
5125 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5126
5127 AutoCaller dhcpServerCaller(aDHCPServer);
5128 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
5129
5130 m->allDHCPServers.removeChild(aDHCPServer);
5131
5132 HRESULT rc = S_OK;
5133
5134 if (aSaveSettings)
5135 {
5136 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
5137 rc = saveSettings();
5138 vboxLock.release();
5139
5140 if (FAILED(rc))
5141 registerDHCPServer(aDHCPServer, false /* aSaveSettings */);
5142 }
5143
5144 return rc;
5145}
5146
5147/* 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