VirtualBox

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

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

Main/NATNetwork API (xTracker/5894).

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

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