VirtualBox

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

Last change on this file since 43541 was 43479, checked in by vboxsync, 12 years ago

Main/VirtualBox: properly lock objects when saving the media registry, and handle inaccessible objects.

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