VirtualBox

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

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

Main: gcc warnings

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