VirtualBox

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

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

use openMedium instead of findMedium

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette