VirtualBox

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

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

Main/VirtualBox+Machine: implement the directory handling/renaming logic for gro
up changes, plus strict validation of the VM groups to avoid trouble when using
it as a directory component

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