VirtualBox

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

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

Same for DVD and floppy images

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