VirtualBox

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

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

Fix attaching a hard disk by UUID through VBoxManage (4.2 regression, see public #11209)

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