VirtualBox

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

Last change on this file since 57415 was 57134, checked in by vboxsync, 9 years ago

Main/Machine: fix session state checking helpers (properly distinguishing "only VM sessions" from "all sessions"), to hopefully fix the Windows session crash detection

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

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