-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathVirtualBoxImpl.cpp
More file actions
7072 lines (6172 loc) · 232 KB
/
VirtualBoxImpl.cpp
File metadata and controls
7072 lines (6172 loc) · 232 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $Id: VirtualBoxImpl.cpp 112403 2026-01-11 19:29:08Z knut.osmundsen@oracle.com $ */
/** @file
* Implementation of IVirtualBox in VBoxSVC.
*/
/*
* Copyright (C) 2006-2026 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* SPDX-License-Identifier: GPL-3.0-only
*/
#define LOG_GROUP LOG_GROUP_MAIN_VIRTUALBOX
#include <iprt/asm.h>
#include <iprt/base64.h>
#include <iprt/buildconfig.h>
#include <iprt/cpp/utils.h>
#include <iprt/dir.h>
#include <iprt/env.h>
#include <iprt/file.h>
#include <iprt/path.h>
#include <iprt/process.h>
#include <iprt/rand.h>
#include <iprt/sha.h>
#include <iprt/string.h>
#include <iprt/stream.h>
#include <iprt/system.h>
#include <iprt/thread.h>
#include <iprt/uuid.h>
#include <iprt/cpp/xml.h>
#include <iprt/ctype.h>
#include <VBox/com/com.h>
#include <VBox/com/array.h>
#include "VBox/com/EventQueue.h"
#include "VBox/com/MultiResult.h"
#include <VBox/err.h>
#include <VBox/param.h>
#include <VBox/settings.h>
#include <VBox/sup.h>
#include <VBox/version.h>
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
# include <VBox/GuestHost/SharedClipboard-transfers.h>
#endif
#include <package-generated.h>
#include <algorithm>
#include <set>
#include <vector>
#include <memory> // for auto_ptr
#include "VirtualBoxImpl.h"
#include "Global.h"
#include "MachineImpl.h"
#include "MediumImpl.h"
#include "SharedFolderImpl.h"
#include "ProgressImpl.h"
#include "HostImpl.h"
#include "USBControllerImpl.h"
#include "SystemPropertiesImpl.h"
#include "CertificateImpl.h"
#include "GuestOSTypeImpl.h"
#include "NetworkServiceRunner.h"
#include "DHCPServerImpl.h"
#include "NATNetworkImpl.h"
#ifdef VBOX_WITH_VMNET
#include "HostOnlyNetworkImpl.h"
#endif /* VBOX_WITH_VMNET */
#ifdef VBOX_WITH_CLOUD_NET
#include "CloudNetworkImpl.h"
#endif /* VBOX_WITH_CLOUD_NET */
#ifdef VBOX_WITH_RESOURCE_USAGE_API
# include "PerformanceImpl.h"
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
#ifdef VBOX_WITH_UPDATE_AGENT
# include "UpdateAgentImpl.h"
#endif
#include "EventImpl.h"
#ifdef VBOX_WITH_EXTPACK
# include "ExtPackManagerImpl.h"
#endif
#ifdef VBOX_WITH_UNATTENDED
# include "UnattendedImpl.h"
#endif
#include "AutostartDb.h"
#include "ClientWatcher.h"
#include "AutoCaller.h"
#include "LoggingNew.h"
#include "CloudProviderManagerImpl.h"
#include "ThreadTask.h"
#include "VBoxEvents.h"
#ifdef VBOX_WITH_MAIN_OBJECT_TRACKER
# include "ObjectsTracker.h"
#endif
#include <QMTranslator.h>
#ifdef RT_OS_WINDOWS
# include "win/svchlp.h"
# include "tchar.h"
#endif
////////////////////////////////////////////////////////////////////////////////
//
// Definitions
//
////////////////////////////////////////////////////////////////////////////////
#define VBOX_GLOBAL_SETTINGS_FILE "VirtualBox.xml"
////////////////////////////////////////////////////////////////////////////////
//
// Global variables
//
////////////////////////////////////////////////////////////////////////////////
#ifdef VBOX_WITH_MAIN_OBJECT_TRACKER
extern TrackedObjectsCollector gTrackedObjectsCollector;
#endif
// static
com::Utf8Str VirtualBox::sVersion;
// static
com::Utf8Str VirtualBox::sVersionNormalized;
// static
ULONG VirtualBox::sRevision;
// static
com::Utf8Str VirtualBox::sPackageType;
// static
com::Utf8Str VirtualBox::sAPIVersion;
// static
std::map<com::Utf8Str, int> VirtualBox::sNatNetworkNameToRefCount;
// static leaked (todo: find better place to free it.)
RWLockHandle *VirtualBox::spMtxNatNetworkNameToRefCountLock;
////////////////////////////////////////////////////////////////////////////////
//
// AsyncEvent class
//
////////////////////////////////////////////////////////////////////////////////
/**
* For firing off an event on asynchronously on an event thread.
*/
class VirtualBox::AsyncEvent : public Event
{
public:
AsyncEvent(VirtualBox *a_pVirtualBox, ComPtr<IEvent> const &a_rEvent)
: mVirtualBox(a_pVirtualBox), mEvent(a_rEvent)
{
Assert(a_pVirtualBox);
}
void *handler() RT_OVERRIDE;
private:
/**
* @note This is a weak ref -- the CallbackEvent handler thread is bound to the
* lifetime of the VirtualBox instance, so it's safe.
*/
VirtualBox *mVirtualBox;
/** The event. */
ComPtr<IEvent> mEvent;
};
////////////////////////////////////////////////////////////////////////////////
//
// VirtualBox private member data definition
//
////////////////////////////////////////////////////////////////////////////////
#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
/**
* Client process watcher data.
*/
class WatchedClientProcess
{
public:
WatchedClientProcess(RTPROCESS a_pid, HANDLE a_hProcess) RT_NOEXCEPT
: m_pid(a_pid)
, m_cRefs(1)
, m_hProcess(a_hProcess)
{
}
~WatchedClientProcess()
{
if (m_hProcess != NULL)
{
::CloseHandle(m_hProcess);
m_hProcess = NULL;
}
m_pid = NIL_RTPROCESS;
}
/** The client PID. */
RTPROCESS m_pid;
/** Number of references to this structure. */
uint32_t volatile m_cRefs;
/** Handle of the client process.
* Ideally, we've got full query privileges, but we'll settle for waiting. */
HANDLE m_hProcess;
};
typedef std::map<RTPROCESS, WatchedClientProcess *> WatchedClientProcessMap;
#endif
typedef ObjectsList<Medium> MediaOList;
typedef ObjectsList<GuestOSType> GuestOSTypesOList;
typedef ObjectsList<SharedFolder> SharedFoldersOList;
typedef ObjectsList<DHCPServer> DHCPServersOList;
typedef ObjectsList<NATNetwork> NATNetworksOList;
#ifdef VBOX_WITH_VMNET
typedef ObjectsList<HostOnlyNetwork> HostOnlyNetworksOList;
#endif /* VBOX_WITH_VMNET */
#ifdef VBOX_WITH_CLOUD_NET
typedef ObjectsList<CloudNetwork> CloudNetworksOList;
#endif /* VBOX_WITH_CLOUD_NET */
typedef std::map<Guid, ComPtr<IProgress> > ProgressMap;
typedef std::map<Guid, ComObjPtr<Medium> > HardDiskMap;
/**
* Main VirtualBox data structure.
* @note |const| members are persistent during lifetime so can be accessed
* without locking.
*/
struct VirtualBox::Data
{
Data()
: pMainConfigFile(NULL)
, uuidMediaRegistry("48024e5c-fdd9-470f-93af-ec29f7ea518c")
, uRegistryNeedsSaving(0)
, lockMachines(LOCKCLASS_LISTOFMACHINES, "Machines")
, allMachines(lockMachines)
, lockGuestOSTypes(LOCKCLASS_LISTOFOTHEROBJECTS, "GuestOSTypes")
, allGuestOSTypes(lockGuestOSTypes)
, lockMedia(LOCKCLASS_LISTOFMEDIA, "Media")
, allHardDisks(lockMedia)
, allDVDImages(lockMedia)
, allFloppyImages(lockMedia)
, lockSharedFolders(LOCKCLASS_LISTOFOTHEROBJECTS, "SharedFolders")
, allSharedFolders(lockSharedFolders)
, lockDHCPServers(LOCKCLASS_LISTOFOTHEROBJECTS, "DHCPServers")
, allDHCPServers(lockDHCPServers)
, lockNATNetworks(LOCKCLASS_LISTOFOTHEROBJECTS, "NATNetworks")
, allNATNetworks(lockNATNetworks)
#ifdef VBOX_WITH_VMNET
, lockHostOnlyNetworks(LOCKCLASS_LISTOFOTHEROBJECTS, "HostOnlyNetworks")
, allHostOnlyNetworks(lockHostOnlyNetworks)
#endif /* VBOX_WITH_VMNET */
#ifdef VBOX_WITH_CLOUD_NET
, lockCloudNetworks(LOCKCLASS_LISTOFOTHEROBJECTS, "CloudNetworks")
, allCloudNetworks(lockCloudNetworks)
#endif /* VBOX_WITH_CLOUD_NET */
, mtxProgressOperations(LOCKCLASS_PROGRESSLIST, "ProgressOperations")
, pClientWatcher(NULL)
, threadAsyncEvent(NIL_RTTHREAD)
, pAsyncEventQ(NULL)
, pAutostartDb(NULL)
, fSettingsCipherKeySet(false)
#ifdef VBOX_WITH_MAIN_NLS
, pVBoxTranslator(NULL)
, pTrComponent(NULL)
#endif
#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
, fWatcherIsReliable(RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
#endif
#ifdef VBOX_WITH_MAIN_OBJECT_TRACKER
, objectTrackerTask(NULL)
#endif
{
#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
RTCritSectRwInit(&WatcherCritSect);
#endif
}
~Data()
{
if (pMainConfigFile)
{
delete pMainConfigFile;
pMainConfigFile = NULL;
}
};
// const data members not requiring locking
const Utf8Str strHomeDir;
// VirtualBox main settings file
const Utf8Str strSettingsFilePath;
settings::MainConfigFile *pMainConfigFile;
// constant pseudo-machine ID for global media registry
const Guid uuidMediaRegistry;
// counter if global media registry needs saving, updated using atomic
// operations, without requiring any locks
uint64_t uRegistryNeedsSaving;
// const objects not requiring locking
const ComObjPtr<Host> pHost;
const ComObjPtr<SystemProperties> pSystemProperties;
#ifdef VBOX_WITH_RESOURCE_USAGE_API
const ComObjPtr<PerformanceCollector> pPerformanceCollector;
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
// Each of the following lists use a particular lock handle that protects the
// list as a whole. As opposed to version 3.1 and earlier, these lists no
// longer need the main VirtualBox object lock, but only the respective list
// lock. In each case, the locking order is defined that the list must be
// requested before object locks of members of the lists (see the order definitions
// in AutoLock.h; e.g. LOCKCLASS_LISTOFMACHINES before LOCKCLASS_MACHINEOBJECT).
RWLockHandle lockMachines;
MachinesOList allMachines;
RWLockHandle lockGuestOSTypes;
GuestOSTypesOList allGuestOSTypes;
// All the media lists are protected by the following locking handle:
RWLockHandle lockMedia;
MediaOList allHardDisks, // base images only!
allDVDImages,
allFloppyImages;
// the hard disks map is an additional map sorted by UUID for quick lookup
// and contains ALL hard disks (base and differencing); it is protected by
// the same lock as the other media lists above
HardDiskMap mapHardDisks;
// list of pending machine renames (also protected by media tree lock;
// see VirtualBox::rememberMachineNameChangeForMedia())
struct PendingMachineRename
{
Utf8Str strConfigDirOld;
Utf8Str strConfigDirNew;
};
typedef std::list<PendingMachineRename> PendingMachineRenamesList;
PendingMachineRenamesList llPendingMachineRenames;
RWLockHandle lockSharedFolders;
SharedFoldersOList allSharedFolders;
RWLockHandle lockDHCPServers;
DHCPServersOList allDHCPServers;
RWLockHandle lockNATNetworks;
NATNetworksOList allNATNetworks;
#ifdef VBOX_WITH_VMNET
RWLockHandle lockHostOnlyNetworks;
HostOnlyNetworksOList allHostOnlyNetworks;
#endif /* VBOX_WITH_VMNET */
#ifdef VBOX_WITH_CLOUD_NET
RWLockHandle lockCloudNetworks;
CloudNetworksOList allCloudNetworks;
#endif /* VBOX_WITH_CLOUD_NET */
RWLockHandle mtxProgressOperations;
ProgressMap mapProgressOperations;
ClientWatcher * const pClientWatcher;
// the following are data for the async event thread
const RTTHREAD threadAsyncEvent;
EventQueue * const pAsyncEventQ;
const ComObjPtr<EventSource> pEventSource;
ComObjPtr<Certificate> ptrCertificateInfo;
#ifdef VBOX_WITH_EXTPACK
/** The extension pack manager object lives here. */
const ComObjPtr<ExtPackManager> ptrExtPackManager;
#endif
/** The reference to the cloud provider manager singleton. */
const ComObjPtr<CloudProviderManager> pCloudProviderManager;
/** The global autostart database for the user. */
AutostartDb * const pAutostartDb;
/** Settings secret */
bool fSettingsCipherKeySet;
uint8_t SettingsCipherKey[RTSHA512_HASH_SIZE];
#ifdef VBOX_WITH_MAIN_NLS
VirtualBoxTranslator *pVBoxTranslator;
PTRCOMPONENT pTrComponent;
#endif
#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)
/** Critical section protecting WatchedProcesses. */
RTCRITSECTRW WatcherCritSect;
/** Map of processes being watched, key is the PID. */
WatchedClientProcessMap WatchedProcesses;
/** Set if the watcher is reliable, otherwise cleared.
* The watcher goes unreliable when we run out of memory, fail open a client
* process, or if the watcher thread gets messed up. */
bool fWatcherIsReliable;
#endif
#ifdef VBOX_WITH_MAIN_OBJECT_TRACKER
/** The tracked object collector (better if it'll be a singleton) */
ObjectTracker *objectTrackerTask;
#endif
};
/**
* VirtualBox firmware descriptor.
*/
typedef struct VBOXFWDESC
{
FirmwareType_T enmType;
bool fBuiltIn;
const char *pszFileName;
const char *pszUrl;
} VBoxFwDesc;
typedef const VBOXFWDESC *PVBOXFWDESC;
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
DEFINE_EMPTY_CTOR_DTOR(VirtualBox)
HRESULT VirtualBox::FinalConstruct()
{
LogRelFlowThisFuncEnter();
LogRel(("VirtualBox: object creation starts\n"));
BaseFinalConstruct();
HRESULT hrc = init();
LogRelFlowThisFuncLeave();
LogRel(("VirtualBox: object created\n"));
return hrc;
}
void VirtualBox::FinalRelease()
{
LogRelFlowThisFuncEnter();
LogRel(("VirtualBox: object deletion starts\n"));
uninit();
BaseFinalRelease();
LogRel(("VirtualBox: object deleted\n"));
LogRelFlowThisFuncLeave();
}
// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////
/**
* Initializes the VirtualBox object.
*
* @return COM result code
*/
HRESULT VirtualBox::init()
{
LogRelFlowThisFuncEnter();
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
AssertReturn(autoInitSpan.isOk(), E_FAIL);
/* Locking this object for writing during init sounds a bit paradoxical,
* but in the current locking mess this avoids that some code gets a
* read lock and later calls code which wants the same write lock. */
AutoWriteLock lock(this COMMA_LOCKVAL_SRC_POS);
// allocate our instance data
m = new Data;
LogFlow(("===========================================================\n"));
LogFlowThisFuncEnter();
if (sVersion.isEmpty())
sVersion = RTBldCfgVersion();
if (sVersionNormalized.isEmpty())
{
Utf8Str tmp(RTBldCfgVersion());
if (tmp.endsWith(VBOX_BUILD_PUBLISHER))
tmp = tmp.substr(0, tmp.length() - strlen(VBOX_BUILD_PUBLISHER));
sVersionNormalized = tmp;
}
sRevision = RTBldCfgRevision();
if (sPackageType.isEmpty())
sPackageType = VBOX_PACKAGE_STRING;
if (sAPIVersion.isEmpty())
sAPIVersion = VBOX_API_VERSION_STRING;
if (!spMtxNatNetworkNameToRefCountLock)
spMtxNatNetworkNameToRefCountLock = new RWLockHandle(LOCKCLASS_VIRTUALBOXOBJECT, "spMtxNatNetworkNameToRefCountLock");
LogFlowThisFunc(("Version: %s, Package: %s, API Version: %s\n", sVersion.c_str(), sPackageType.c_str(), sAPIVersion.c_str()));
#ifdef VBOX_WITH_MAIN_OBJECT_TRACKER
/* Try to start Object tracker thread as earlier as possible (same code in VirtualBoxClientImpl.cpp). */
{
int vrc = VERR_GENERAL_FAILURE;
if (gTrackedObjectsCollector.init())
{
LogRel(("Starting the Object tracker thread\n"));
try
{
m->objectTrackerTask = new ObjectTracker();
if (m->objectTrackerTask->init()) // some init procedure - bird: some comment!
vrc = m->objectTrackerTask->createThread();
}
catch (...)
{
LogRel(("Exception during starting the Object tracker thread\n"));
if (m->objectTrackerTask)
{
delete m->objectTrackerTask;
m->objectTrackerTask = NULL;
}
vrc = VERR_INVALID_STATE;
}
}
if (RT_SUCCESS(vrc))
LogRel(("Successfully started the Object tracker thread\n"));
else
LogRel(("Failed to start the Object tracker thread (%Rrc)\n", vrc));
}
#endif
/* Important: DO NOT USE any kind of "early return" (except the single
* one above, checking the init span success) in this method. It is vital
* for correct error handling that it has only one point of return, which
* does all the magic on COM to signal object creation success and
* reporting the error later for every API method. COM translates any
* unsuccessful object creation to REGDB_E_CLASSNOTREG errors or similar
* unhelpful ones which cause us a lot of grief with troubleshooting. */
HRESULT hrc = S_OK;
bool fCreate = false;
try
{
/* Create the event source early as we may fire async event during settings loading (media). */
hrc = unconst(m->pEventSource).createObject();
if (FAILED(hrc)) throw hrc;
hrc = m->pEventSource->init();
if (FAILED(hrc)) throw hrc;
/* Get the VirtualBox home directory. */
{
char szHomeDir[RTPATH_MAX];
int vrc = com::GetVBoxUserHomeDirectory(szHomeDir, sizeof(szHomeDir));
if (RT_FAILURE(vrc))
throw setErrorBoth(E_FAIL, vrc,
tr("Could not create the VirtualBox home directory '%s' (%Rrc)"),
szHomeDir, vrc);
unconst(m->strHomeDir) = szHomeDir;
}
LogRel(("Home directory: '%s'\n", m->strHomeDir.c_str()));
i_reportDriverVersions();
/* compose the VirtualBox.xml file name */
unconst(m->strSettingsFilePath) = Utf8StrFmt("%s%c%s",
m->strHomeDir.c_str(),
RTPATH_DELIMITER,
VBOX_GLOBAL_SETTINGS_FILE);
// load and parse VirtualBox.xml; this will throw on XML or logic errors
try
{
m->pMainConfigFile = new settings::MainConfigFile(&m->strSettingsFilePath);
}
catch (xml::EIPRTFailure &e)
{
// this is thrown by the XML backend if the RTOpen() call fails;
// only if the main settings file does not exist, create it,
// if there's something more serious, then do fail!
if (e.getStatus() == VERR_FILE_NOT_FOUND)
fCreate = true;
else
throw;
}
if (fCreate)
m->pMainConfigFile = new settings::MainConfigFile(NULL);
#ifdef VBOX_WITH_RESOURCE_USAGE_API
/* create the performance collector object BEFORE host */
unconst(m->pPerformanceCollector).createObject();
hrc = m->pPerformanceCollector->init();
ComAssertComRCThrowRC(hrc);
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/* create the host object early, machines will need it */
unconst(m->pHost).createObject();
hrc = m->pHost->init(this);
ComAssertComRCThrowRC(hrc);
hrc = m->pHost->i_loadSettings(m->pMainConfigFile->host);
if (FAILED(hrc)) throw hrc;
/*
* Create autostart database object early, because the system properties
* might need it.
*/
unconst(m->pAutostartDb) = new AutostartDb;
/* create the system properties object, someone may need it too */
hrc = unconst(m->pSystemProperties).createObject();
if (SUCCEEDED(hrc))
hrc = m->pSystemProperties->init(this);
ComAssertComRCThrowRC(hrc);
hrc = m->pSystemProperties->i_loadSettings(m->pMainConfigFile->systemProperties);
if (FAILED(hrc)) throw hrc;
#ifdef VBOX_WITH_MAIN_NLS
m->pVBoxTranslator = VirtualBoxTranslator::instance();
/* Do not throw an exception on language errors.
* Just do not use translation. */
if (m->pVBoxTranslator)
{
char szNlsPath[RTPATH_MAX];
int vrc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
if (RT_SUCCESS(vrc))
vrc = RTPathAppend(szNlsPath, sizeof(szNlsPath), "nls" RTPATH_SLASH_STR "VirtualBoxAPI");
if (RT_SUCCESS(vrc))
{
vrc = m->pVBoxTranslator->registerTranslation(szNlsPath, true, &m->pTrComponent);
if (RT_SUCCESS(vrc))
{
com::Utf8Str strLocale;
HRESULT hrc2 = m->pSystemProperties->getLanguageId(strLocale);
if (SUCCEEDED(hrc2))
{
vrc = m->pVBoxTranslator->i_loadLanguage(strLocale.c_str());
if (RT_FAILURE(vrc))
{
hrc2 = Global::vboxStatusCodeToCOM(vrc);
LogRel(("Load language failed (%Rhrc).\n", hrc2));
}
}
else
{
LogRel(("Getting language settings failed (%Rhrc).\n", hrc2));
m->pVBoxTranslator->release();
m->pVBoxTranslator = NULL;
m->pTrComponent = NULL;
}
}
else
{
HRESULT hrc2 = Global::vboxStatusCodeToCOM(vrc);
LogRel(("Register translation failed (%Rhrc).\n", hrc2));
m->pVBoxTranslator->release();
m->pVBoxTranslator = NULL;
m->pTrComponent = NULL;
}
}
else
{
HRESULT hrc2 = Global::vboxStatusCodeToCOM(vrc);
LogRel(("Path constructing failed (%Rhrc).\n", hrc2));
m->pVBoxTranslator->release();
m->pVBoxTranslator = NULL;
m->pTrComponent = NULL;
}
}
else
LogRel(("Translator creation failed.\n"));
#endif
#ifdef VBOX_WITH_EXTPACK
/*
* Initialize extension pack manager before system properties because
* it is required for the VD plugins.
*/
hrc = unconst(m->ptrExtPackManager).createObject();
if (SUCCEEDED(hrc))
hrc = m->ptrExtPackManager->initExtPackManager(this, VBOXEXTPACKCTX_PER_USER_DAEMON);
if (FAILED(hrc))
throw hrc;
#endif
/* guest OS type objects, needed by machines */
for (size_t i = 0; i < Global::cOSTypes; ++i)
{
ComObjPtr<GuestOSType> guestOSTypeObj;
hrc = guestOSTypeObj.createObject();
if (SUCCEEDED(hrc))
{
hrc = guestOSTypeObj->init(Global::sOSTypes[i]);
if (SUCCEEDED(hrc))
m->allGuestOSTypes.addChild(guestOSTypeObj);
}
ComAssertComRCThrowRC(hrc);
}
/* all registered media, needed by machines */
if (FAILED(hrc = initMedia(m->uuidMediaRegistry,
m->pMainConfigFile->mediaRegistry,
Utf8Str::Empty))) // const Utf8Str &machineFolder
throw hrc;
/* machines */
if (FAILED(hrc = initMachines()))
throw hrc;
#ifdef DEBUG
LogFlowThisFunc(("Dumping media backreferences\n"));
i_dumpAllBackRefs();
#endif
/* net services - dhcp services */
for (settings::DHCPServersList::const_iterator it = m->pMainConfigFile->llDhcpServers.begin();
it != m->pMainConfigFile->llDhcpServers.end();
++it)
{
const settings::DHCPServer &data = *it;
ComObjPtr<DHCPServer> pDhcpServer;
if (SUCCEEDED(hrc = pDhcpServer.createObject()))
hrc = pDhcpServer->init(this, data);
if (FAILED(hrc)) throw hrc;
hrc = i_registerDHCPServer(pDhcpServer, false /* aSaveRegistry */);
if (FAILED(hrc)) throw hrc;
}
for (settings::SharedFoldersList::const_iterator it = m->pMainConfigFile->llGlobalSharedFolders.begin();
it != m->pMainConfigFile->llGlobalSharedFolders.end();
++it)
{
const settings::SharedFolder &sf = *it;
ComObjPtr<SharedFolder> pSharedFolder;
hrc = pSharedFolder.createObject();
AssertComRCThrowRC(hrc);
hrc = pSharedFolder->init(this, sf);
if (FAILED(hrc)) throw hrc;
AutoWriteLock alock(m->allSharedFolders.getLockHandle() COMMA_LOCKVAL_SRC_POS);
m->allSharedFolders.addChild(pSharedFolder);
alock.release();
}
/* net services - nat networks */
for (settings::NATNetworksList::const_iterator it = m->pMainConfigFile->llNATNetworks.begin();
it != m->pMainConfigFile->llNATNetworks.end();
++it)
{
const settings::NATNetwork &net = *it;
ComObjPtr<NATNetwork> pNATNetwork;
hrc = pNATNetwork.createObject();
AssertComRCThrowRC(hrc);
hrc = pNATNetwork->init(this, "");
AssertComRCThrowRC(hrc);
hrc = pNATNetwork->i_loadSettings(net);
AssertComRCThrowRC(hrc);
hrc = i_registerNATNetwork(pNATNetwork, false /* aSaveRegistry */);
AssertComRCThrowRC(hrc);
}
#ifdef VBOX_WITH_VMNET
/* host-only networks */
for (settings::HostOnlyNetworksList::const_iterator it = m->pMainConfigFile->llHostOnlyNetworks.begin();
it != m->pMainConfigFile->llHostOnlyNetworks.end();
++it)
{
ComObjPtr<HostOnlyNetwork> pHostOnlyNetwork;
hrc = pHostOnlyNetwork.createObject();
AssertComRCThrowRC(hrc);
hrc = pHostOnlyNetwork->init(this, "TODO???");
AssertComRCThrowRC(hrc);
hrc = pHostOnlyNetwork->i_loadSettings(*it);
AssertComRCThrowRC(hrc);
m->allHostOnlyNetworks.addChild(pHostOnlyNetwork);
AssertComRCThrowRC(hrc);
}
#endif /* VBOX_WITH_VMNET */
#ifdef VBOX_WITH_CLOUD_NET
/* net services - cloud networks */
for (settings::CloudNetworksList::const_iterator it = m->pMainConfigFile->llCloudNetworks.begin();
it != m->pMainConfigFile->llCloudNetworks.end();
++it)
{
ComObjPtr<CloudNetwork> pCloudNetwork;
hrc = pCloudNetwork.createObject();
AssertComRCThrowRC(hrc);
hrc = pCloudNetwork->init(this, "");
AssertComRCThrowRC(hrc);
hrc = pCloudNetwork->i_loadSettings(*it);
AssertComRCThrowRC(hrc);
m->allCloudNetworks.addChild(pCloudNetwork);
AssertComRCThrowRC(hrc);
}
#endif /* VBOX_WITH_CLOUD_NET */
/* cloud provider manager */
hrc = unconst(m->pCloudProviderManager).createObject();
if (SUCCEEDED(hrc))
hrc = m->pCloudProviderManager->init(this);
ComAssertComRCThrowRC(hrc);
if (FAILED(hrc)) throw hrc;
}
catch (HRESULT err)
{
/* we assume that error info is set by the thrower */
hrc = err;
}
catch (...)
{
hrc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
}
if (SUCCEEDED(hrc))
{
/* set up client monitoring */
try
{
unconst(m->pClientWatcher) = new ClientWatcher(this);
if (!m->pClientWatcher->isReady())
{
delete m->pClientWatcher;
unconst(m->pClientWatcher) = NULL;
hrc = E_FAIL;
}
}
catch (std::bad_alloc &)
{
hrc = E_OUTOFMEMORY;
}
}
if (SUCCEEDED(hrc))
{
try
{
/* start the async event handler thread */
int vrc = RTThreadCreate(&unconst(m->threadAsyncEvent),
AsyncEventHandler,
&unconst(m->pAsyncEventQ),
0,
RTTHREADTYPE_MAIN_WORKER,
RTTHREADFLAGS_WAITABLE,
"EventHandler");
ComAssertRCThrow(vrc, E_FAIL);
/* wait until the thread sets m->pAsyncEventQ */
RTThreadUserWait(m->threadAsyncEvent, RT_INDEFINITE_WAIT);
ComAssertThrow(m->pAsyncEventQ, E_FAIL);
}
catch (HRESULT hrcXcpt)
{
hrc = hrcXcpt;
}
}
#ifdef VBOX_WITH_EXTPACK
/* Let the extension packs have a go at things. */
if (SUCCEEDED(hrc))
{
lock.release();
m->ptrExtPackManager->i_callAllVirtualBoxReadyHooks();
}
#endif
/* Confirm a successful initialization when it's the case. Must be last,
* as on failure it will uninitialize the object. */
if (SUCCEEDED(hrc))
autoInitSpan.setSucceeded();
else
autoInitSpan.setFailed(hrc);
LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
LogFlowThisFuncLeave();
LogFlow(("===========================================================\n"));
/* Unconditionally return success, because the error return is delayed to
* the attribute/method calls through the InitFailed object state. */
return S_OK;
}
HRESULT VirtualBox::initMachines()
{
for (settings::MachinesRegistry::const_iterator it = m->pMainConfigFile->llMachines.begin();
it != m->pMainConfigFile->llMachines.end();
++it)
{
HRESULT hrc = S_OK;
const settings::MachineRegistryEntry &xmlMachine = *it;
Guid uuid = xmlMachine.uuid;
/* Check if machine record has valid parameters. */
if (xmlMachine.strSettingsFile.isEmpty() || uuid.isZero())
{
LogRel(("Skipped invalid machine record.\n"));
continue;
}
ComObjPtr<Machine> pMachine;
com::Utf8Str strPassword;
if (SUCCEEDED(hrc = pMachine.createObject()))
{
hrc = pMachine->initFromSettings(this, xmlMachine.strSettingsFile, &uuid, strPassword);
if (SUCCEEDED(hrc))
hrc = i_registerMachine(pMachine);
if (FAILED(hrc))
return hrc;
}
}
return S_OK;
}
/**
* Loads a media registry from XML and adds the media contained therein to
* the global lists of known media.
*
* This now (4.0) gets called from two locations:
*
* -- VirtualBox::init(), to load the global media registry from VirtualBox.xml;
*
* -- Machine::loadMachineDataFromSettings(), to load the per-machine registry
* from machine XML, for machines created with VirtualBox 4.0 or later.
*
* In both cases, the media found are added to the global lists so the
* global arrays of media (including the GUI's virtual media manager)
* continue to work as before.
*
* @param uuidRegistry The UUID of the media registry. This is either the
* transient UUID created at VirtualBox startup for the global registry or
* a machine ID.
* @param mediaRegistry The XML settings structure to load, either from VirtualBox.xml
* or a machine XML.
* @param strMachineFolder The folder of the machine.
* @return
*/
HRESULT VirtualBox::initMedia(const Guid &uuidRegistry,
const settings::MediaRegistry &mediaRegistry,
const Utf8Str &strMachineFolder)
{
LogFlow(("VirtualBox::initMedia ENTERING, uuidRegistry=%s, strMachineFolder=%s\n",
uuidRegistry.toString().c_str(),
strMachineFolder.c_str()));
AutoWriteLock treeLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
// the order of notification is critical for GUI, so use std::list<std::pair> instead of map
std::list<std::pair<Guid, DeviceType_T> > uIdsForNotify;
HRESULT hrc = S_OK;
settings::MediaList::const_iterator it;
for (it = mediaRegistry.llHardDisks.begin();
it != mediaRegistry.llHardDisks.end();
++it)
{
const settings::Medium &xmlHD = *it;
hrc = Medium::initFromSettings(this,
DeviceType_HardDisk,
uuidRegistry,
strMachineFolder,
xmlHD,
treeLock,
uIdsForNotify);
if (FAILED(hrc)) return hrc;
}
for (it = mediaRegistry.llDvdImages.begin();
it != mediaRegistry.llDvdImages.end();
++it)
{
const settings::Medium &xmlDvd = *it;