summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-server/VirtualBoxImpl.cpp
blob: 73e07dbb6654642d759d4ba312105ed2b110b159 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
/* $Id: VirtualBoxImpl.cpp $ */
/** @file
 * Implementation of IVirtualBox in VBoxSVC.
 */

/*
 * Copyright (C) 2006-2023 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 "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"

#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
//
////////////////////////////////////////////////////////////////////////////////

// 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;


#if 0 /* obsoleted by AsyncEvent */
////////////////////////////////////////////////////////////////////////////////
//
// CallbackEvent class
//
////////////////////////////////////////////////////////////////////////////////

/**
 *  Abstract callback event class to asynchronously call VirtualBox callbacks
 *  on a dedicated event thread. Subclasses reimplement #prepareEventDesc()
 *  to initialize the event depending on the event to be dispatched.
 *
 *  @note The VirtualBox instance passed to the constructor is strongly
 *  referenced, so that the VirtualBox singleton won't be released until the
 *  event gets handled by the event thread.
 */
class VirtualBox::CallbackEvent : public Event
{
public:

    CallbackEvent(VirtualBox *aVirtualBox, VBoxEventType_T aWhat)
        : mVirtualBox(aVirtualBox), mWhat(aWhat)
    {
        Assert(aVirtualBox);
    }

    void *handler();

    virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc) = 0;

private:

    /**
     *  Note that this is a weak ref -- the CallbackEvent handler thread
     *  is bound to the lifetime of the VirtualBox instance, so it's safe.
     */
    VirtualBox         *mVirtualBox;
protected:
    VBoxEventType_T     mWhat;
};
#endif

////////////////////////////////////////////////////////////////////////////////
//
// 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)
        , allMachines(lockMachines)
        , lockGuestOSTypes(LOCKCLASS_LISTOFOTHEROBJECTS)
        , allGuestOSTypes(lockGuestOSTypes)
        , lockMedia(LOCKCLASS_LISTOFMEDIA)
        , allHardDisks(lockMedia)
        , allDVDImages(lockMedia)
        , allFloppyImages(lockMedia)
        , lockSharedFolders(LOCKCLASS_LISTOFOTHEROBJECTS)
        , allSharedFolders(lockSharedFolders)
        , lockDHCPServers(LOCKCLASS_LISTOFOTHEROBJECTS)
        , allDHCPServers(lockDHCPServers)
        , lockNATNetworks(LOCKCLASS_LISTOFOTHEROBJECTS)
        , allNATNetworks(lockNATNetworks)
#ifdef VBOX_WITH_VMNET
        , lockHostOnlyNetworks(LOCKCLASS_LISTOFOTHEROBJECTS)
        , allHostOnlyNetworks(lockHostOnlyNetworks)
#endif /* VBOX_WITH_VMNET */
#ifdef VBOX_WITH_CLOUD_NET
        , lockCloudNetworks(LOCKCLASS_LISTOFOTHEROBJECTS)
        , allCloudNetworks(lockCloudNetworks)
#endif /* VBOX_WITH_CLOUD_NET */
        , mtxProgressOperations(LOCKCLASS_PROGRESSLIST)
        , 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
        , hLdrModCrypto(NIL_RTLDRMOD)
        , cRefsCrypto(0)
        , pCryptoIf(NULL)
    {
#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;

#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

    /** @name Members related to the cryptographic support interface.
     * @{ */
    /** The loaded module handle if loaded. */
    RTLDRMOD                            hLdrModCrypto;
    /** Reference counter tracking how many users of the cryptographic support
     * are there currently. */
    volatile uint32_t                   cRefsCrypto;
    /** Pointer to the cryptographic support interface. */
    PCVBOXCRYPTOIF                      pCryptoIf;
    /** Critical section protecting the module handle. */
    RTCRITSECT                          CritSectModCrypto;
    /** @} */
};

// 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);

    LogFlowThisFunc(("Version: %s, Package: %s, API Version: %s\n", sVersion.c_str(), sPackageType.c_str(), sAPIVersion.c_str()));

    /* 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();

        /* Create the critical section protecting the cryptographic module handle. */
        {
            int vrc = RTCritSectInit(&m->CritSectModCrypto);
            if (RT_FAILURE(vrc))
                throw setErrorBoth(E_FAIL, vrc,
                                   tr("Could not create the cryptographic module critical section (%Rrc)"),
                                   vrc);

        }

        /* 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;
        }

        /* 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;

        hrc = Medium::initFromSettings(this,
                                       DeviceType_DVD,
                                       uuidRegistry,
                                       strMachineFolder,
                                       xmlDvd,
                                       treeLock,
                                       uIdsForNotify);
        if (FAILED(hrc)) return hrc;
    }

    for (it = mediaRegistry.llFloppyImages.begin();
         it != mediaRegistry.llFloppyImages.end();
         ++it)
    {
        const settings::Medium &xmlFloppy = *it;

        hrc = Medium::initFromSettings(this,
                                       DeviceType_Floppy,
                                       uuidRegistry,
                                       strMachineFolder,
                                       xmlFloppy,
                                       treeLock,
                                       uIdsForNotify);
        if (FAILED(hrc)) return hrc;
    }

    for (std::list<std::pair<Guid, DeviceType_T> >::const_iterator itItem = uIdsForNotify.begin();
         itItem != uIdsForNotify.end();
         ++itItem)
    {
        i_onMediumRegistered(itItem->first, itItem->second, TRUE);
    }

    LogFlow(("VirtualBox::initMedia LEAVING\n"));

    return S_OK;
}

void VirtualBox::uninit()
{
    /* Must be done outside the AutoUninitSpan, as it expects AutoCaller to
     * be successful. This needs additional checks to protect against double
     * uninit, as then the pointer is NULL. */
    if (RT_VALID_PTR(m))
    {
        Assert(!m->uRegistryNeedsSaving);
        if (m->uRegistryNeedsSaving)
            i_saveSettings();
    }

    /* Enclose the state transition Ready->InUninit->NotReady */
    AutoUninitSpan autoUninitSpan(this);
    if (autoUninitSpan.uninitDone())
        return;

    LogFlow(("===========================================================\n"));
    LogFlowThisFuncEnter();
    LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));

    /* tell all our child objects we've been uninitialized */

    LogFlowThisFunc(("Uninitializing machines (%d)...\n", m->allMachines.size()));
    if (m->pHost)
    {
        /* It is necessary to hold the VirtualBox and Host locks here because
           we may have to uninitialize SessionMachines. */
        AutoMultiWriteLock2 multilock(this, m->pHost COMMA_LOCKVAL_SRC_POS);
        m->allMachines.uninitAll();
    }
    else
        m->allMachines.uninitAll();
    m->allFloppyImages.uninitAll();
    m->allDVDImages.uninitAll();
    m->allHardDisks.uninitAll();
    m->allDHCPServers.uninitAll();

    m->mapProgressOperations.clear();

    m->allGuestOSTypes.uninitAll();

    /* Note that we release singleton children after we've all other children.
     * In some cases this is important because these other children may use
     * some resources of the singletons which would prevent them from
     * uninitializing (as for example, mSystemProperties which owns
     * MediumFormat objects which Medium objects refer to) */
    if (m->pCloudProviderManager)
    {
        m->pCloudProviderManager->uninit();
        unconst(m->pCloudProviderManager).setNull();
    }

    if (m->pSystemProperties)
    {
        m->pSystemProperties->uninit();
        unconst(m->pSystemProperties).setNull();
    }

    if (m->pHost)
    {
        m->pHost->uninit();
        unconst(m->pHost).setNull();
    }

#ifdef VBOX_WITH_RESOURCE_USAGE_API
    if (m->pPerformanceCollector)
    {
        m->pPerformanceCollector->uninit();
        unconst(m->pPerformanceCollector).setNull();
    }
#endif /* VBOX_WITH_RESOURCE_USAGE_API */

    /*
     * Unload the cryptographic module if loaded before the extension
     * pack manager is torn down.
     */
    Assert(!m->cRefsCrypto);
    if (m->hLdrModCrypto != NIL_RTLDRMOD)
    {
        m->pCryptoIf = NULL;

        int vrc = RTLdrClose(m->hLdrModCrypto);
        AssertRC(vrc);
        m->hLdrModCrypto = NIL_RTLDRMOD;
    }

    RTCritSectDelete(&m->CritSectModCrypto);

#ifdef VBOX_WITH_EXTPACK
    if (m->ptrExtPackManager)
    {
        m->ptrExtPackManager->uninit();
        unconst(m->ptrExtPackManager).setNull();
    }
#endif

    LogFlowThisFunc(("Terminating the async event handler...\n"));
    if (m->threadAsyncEvent != NIL_RTTHREAD)
    {
        /* signal to exit the event loop */
        if (RT_SUCCESS(m->pAsyncEventQ->interruptEventQueueProcessing()))
        {
            /*
             *  Wait for thread termination (only after we've successfully
             *  interrupted the event queue processing!)
             */
            int vrc = RTThreadWait(m->threadAsyncEvent, 60000, NULL);
            if (RT_FAILURE(vrc))
                Log1WarningFunc(("RTThreadWait(%RTthrd) -> %Rrc\n", m->threadAsyncEvent, vrc));
        }
        else
        {
            AssertMsgFailed(("interruptEventQueueProcessing() failed\n"));
            RTThreadWait(m->threadAsyncEvent, 0, NULL);
        }

        unconst(m->threadAsyncEvent) = NIL_RTTHREAD;
        unconst(m->pAsyncEventQ) = NULL;
    }

    LogFlowThisFunc(("Releasing event source...\n"));
    if (m->pEventSource)
    {
        // Must uninit the event source here, because it makes no sense that
        // it survives longer than the base object. If someone gets an event
        // with such an event source then that's life and it has to be dealt
        // with appropriately on the API client side.
        m->pEventSource->uninit();
        unconst(m->pEventSource).setNull();
    }

    LogFlowThisFunc(("Terminating the client watcher...\n"));
    if (m->pClientWatcher)
    {
        delete m->pClientWatcher;
        unconst(m->pClientWatcher) = NULL;
    }

    delete m->pAutostartDb;
#ifdef VBOX_WITH_MAIN_NLS
    if (m->pVBoxTranslator)
        m->pVBoxTranslator->release();
#endif
    // clean up our instance data
    delete m;
    m = NULL;

    /* Unload hard disk plugin backends. */
    VDShutdown();

    LogFlowThisFuncLeave();
    LogFlow(("===========================================================\n"));
}

// Wrapped IVirtualBox properties
/////////////////////////////////////////////////////////////////////////////
HRESULT VirtualBox::getVersion(com::Utf8Str &aVersion)
{
    aVersion = sVersion;
    return S_OK;
}

HRESULT VirtualBox::getVersionNormalized(com::Utf8Str &aVersionNormalized)
{
    aVersionNormalized = sVersionNormalized;
    return S_OK;
}

HRESULT VirtualBox::getRevision(ULONG *aRevision)
{
    *aRevision = sRevision;
    return S_OK;
}

HRESULT VirtualBox::getPackageType(com::Utf8Str &aPackageType)
{
    aPackageType = sPackageType;
    return S_OK;
}

HRESULT VirtualBox::getAPIVersion(com::Utf8Str &aAPIVersion)
{
    aAPIVersion = sAPIVersion;
    return S_OK;
}

HRESULT VirtualBox::getAPIRevision(LONG64 *aAPIRevision)
{
    AssertCompile(VBOX_VERSION_MAJOR < 128 && VBOX_VERSION_MAJOR > 0);
    AssertCompile((uint64_t)VBOX_VERSION_MINOR < 256);
    uint64_t uRevision = ((uint64_t)VBOX_VERSION_MAJOR << 56)
                       | ((uint64_t)VBOX_VERSION_MINOR << 48)
                       | ((uint64_t)VBOX_VERSION_BUILD << 40);

    /** @todo This needs to be the same in OSE and non-OSE, preferrably
     *        only changing when actual API changes happens. */
    uRevision |= 1;

    *aAPIRevision = (LONG64)uRevision;

    return S_OK;
}

HRESULT VirtualBox::getHomeFolder(com::Utf8Str &aHomeFolder)
{
    /* mHomeDir is const and doesn't need a lock */
    aHomeFolder = m->strHomeDir;
    return S_OK;
}

HRESULT VirtualBox::getSettingsFilePath(com::Utf8Str &aSettingsFilePath)
{
    /* mCfgFile.mName is const and doesn't need a lock */
    aSettingsFilePath = m->strSettingsFilePath;
    return S_OK;
}

HRESULT VirtualBox::getHost(ComPtr<IHost> &aHost)
{
    /* mHost is const, no need to lock */
    m->pHost.queryInterfaceTo(aHost.asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getSystemProperties(ComPtr<ISystemProperties> &aSystemProperties)
{
    /* mSystemProperties is const, no need to lock */
    m->pSystemProperties.queryInterfaceTo(aSystemProperties.asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getMachines(std::vector<ComPtr<IMachine> > &aMachines)
{
    AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aMachines.resize(m->allMachines.size());
    size_t i = 0;
    for (MachinesOList::const_iterator it= m->allMachines.begin();
         it!= m->allMachines.end(); ++it, ++i)
        (*it).queryInterfaceTo(aMachines[i].asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getMachineGroups(std::vector<com::Utf8Str> &aMachineGroups)
{
    std::list<com::Utf8Str> allGroups;

    /* get copy of all machine references, to avoid holding the list lock */
    MachinesOList::MyList allMachines;
    {
        AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
        allMachines = m->allMachines.getList();
    }
    for (MachinesOList::MyList::const_iterator it = allMachines.begin();
         it != allMachines.end();
         ++it)
    {
        const ComObjPtr<Machine> &pMachine = *it;
        AutoCaller autoMachineCaller(pMachine);
        if (FAILED(autoMachineCaller.hrc()))
            continue;
        AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);

        if (pMachine->i_isAccessible())
        {
            const StringsList &thisGroups = pMachine->i_getGroups();
            for (StringsList::const_iterator it2 = thisGroups.begin();
                 it2 != thisGroups.end(); ++it2)
                allGroups.push_back(*it2);
        }
    }

    /* throw out any duplicates */
    allGroups.sort();
    allGroups.unique();
    aMachineGroups.resize(allGroups.size());
    size_t i = 0;
    for (std::list<com::Utf8Str>::const_iterator it = allGroups.begin();
         it != allGroups.end(); ++it, ++i)
        aMachineGroups[i] = (*it);
    return S_OK;
}

HRESULT VirtualBox::getHardDisks(std::vector<ComPtr<IMedium> > &aHardDisks)
{
    AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aHardDisks.resize(m->allHardDisks.size());
    size_t i = 0;
    for (MediaOList::const_iterator it = m->allHardDisks.begin();
         it !=  m->allHardDisks.end(); ++it, ++i)
        (*it).queryInterfaceTo(aHardDisks[i].asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getDVDImages(std::vector<ComPtr<IMedium> > &aDVDImages)
{
    AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aDVDImages.resize(m->allDVDImages.size());
    size_t i = 0;
    for (MediaOList::const_iterator it = m->allDVDImages.begin();
         it!= m->allDVDImages.end(); ++it, ++i)
        (*it).queryInterfaceTo(aDVDImages[i].asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getFloppyImages(std::vector<ComPtr<IMedium> > &aFloppyImages)
{
    AutoReadLock al(m->allFloppyImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aFloppyImages.resize(m->allFloppyImages.size());
    size_t i = 0;
    for (MediaOList::const_iterator it = m->allFloppyImages.begin();
         it != m->allFloppyImages.end(); ++it, ++i)
        (*it).queryInterfaceTo(aFloppyImages[i].asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getProgressOperations(std::vector<ComPtr<IProgress> > &aProgressOperations)
{
    /* protect mProgressOperations */
    AutoReadLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
    ProgressMap pmap(m->mapProgressOperations);
    /* Can release lock now. The following code works on a copy of the map. */
    safeLock.release();
    aProgressOperations.resize(pmap.size());
    size_t i = 0;
    for (ProgressMap::iterator it = pmap.begin(); it != pmap.end(); ++it, ++i)
        it->second.queryInterfaceTo(aProgressOperations[i].asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getGuestOSTypes(std::vector<ComPtr<IGuestOSType> > &aGuestOSTypes)
{
    AutoReadLock al(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aGuestOSTypes.resize(m->allGuestOSTypes.size());
    size_t i = 0;
    for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
         it != m->allGuestOSTypes.end(); ++it, ++i)
         (*it).queryInterfaceTo(aGuestOSTypes[i].asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getSharedFolders(std::vector<ComPtr<ISharedFolder> > &aSharedFolders)
{
    NOREF(aSharedFolders);

    return setError(E_NOTIMPL, tr("Not yet implemented"));
}

HRESULT VirtualBox::getPerformanceCollector(ComPtr<IPerformanceCollector> &aPerformanceCollector)
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
    /* mPerformanceCollector is const, no need to lock */
    m->pPerformanceCollector.queryInterfaceTo(aPerformanceCollector.asOutParam());

    return S_OK;
#else /* !VBOX_WITH_RESOURCE_USAGE_API */
    NOREF(aPerformanceCollector);
    ReturnComNotImplemented();
#endif /* !VBOX_WITH_RESOURCE_USAGE_API */
}

HRESULT VirtualBox::getDHCPServers(std::vector<ComPtr<IDHCPServer> > &aDHCPServers)
{
    AutoReadLock al(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aDHCPServers.resize(m->allDHCPServers.size());
    size_t i = 0;
    for (DHCPServersOList::const_iterator it= m->allDHCPServers.begin();
         it!= m->allDHCPServers.end(); ++it, ++i)
         (*it).queryInterfaceTo(aDHCPServers[i].asOutParam());
    return S_OK;
}


HRESULT VirtualBox::getNATNetworks(std::vector<ComPtr<INATNetwork> > &aNATNetworks)
{
#ifdef VBOX_WITH_NAT_SERVICE
    AutoReadLock al(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aNATNetworks.resize(m->allNATNetworks.size());
    size_t i = 0;
    for (NATNetworksOList::const_iterator it= m->allNATNetworks.begin();
         it!= m->allNATNetworks.end(); ++it, ++i)
         (*it).queryInterfaceTo(aNATNetworks[i].asOutParam());
    return S_OK;
#else
    NOREF(aNATNetworks);
    return E_NOTIMPL;
#endif
}

HRESULT VirtualBox::getEventSource(ComPtr<IEventSource> &aEventSource)
{
    /* event source is const, no need to lock */
    m->pEventSource.queryInterfaceTo(aEventSource.asOutParam());
    return S_OK;
}

HRESULT VirtualBox::getExtensionPackManager(ComPtr<IExtPackManager> &aExtensionPackManager)
{
    HRESULT hrc = S_OK;
#ifdef VBOX_WITH_EXTPACK
    /* The extension pack manager is const, no need to lock. */
    hrc = m->ptrExtPackManager.queryInterfaceTo(aExtensionPackManager.asOutParam());
#else
    hrc = E_NOTIMPL;
    NOREF(aExtensionPackManager);
#endif
    return hrc;
}

/**
 * Host Only Network
 */
HRESULT VirtualBox::createHostOnlyNetwork(const com::Utf8Str &aNetworkName,
                                          ComPtr<IHostOnlyNetwork> &aNetwork)
{
#ifdef VBOX_WITH_VMNET
    ComObjPtr<HostOnlyNetwork> HostOnlyNetwork;
    HostOnlyNetwork.createObject();
    HRESULT hrc = HostOnlyNetwork->init(this, aNetworkName);
    if (FAILED(hrc)) return hrc;

    m->allHostOnlyNetworks.addChild(HostOnlyNetwork);

    {
        AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
        vboxLock.release();

        if (FAILED(hrc))
            m->allHostOnlyNetworks.removeChild(HostOnlyNetwork);
        else
            HostOnlyNetwork.queryInterfaceTo(aNetwork.asOutParam());
    }

    return hrc;
#else /* !VBOX_WITH_VMNET */
    NOREF(aNetworkName);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_VMNET */
}

HRESULT VirtualBox::findHostOnlyNetworkByName(const com::Utf8Str &aNetworkName,
                                           ComPtr<IHostOnlyNetwork> &aNetwork)
{
#ifdef VBOX_WITH_VMNET
    Bstr bstrNameToFind(aNetworkName);

    AutoReadLock alock(m->allHostOnlyNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (HostOnlyNetworksOList::const_iterator it = m->allHostOnlyNetworks.begin();
         it != m->allHostOnlyNetworks.end();
         ++it)
    {
        Bstr bstrHostOnlyNetworkName;
        HRESULT hrc = (*it)->COMGETTER(NetworkName)(bstrHostOnlyNetworkName.asOutParam());
        if (FAILED(hrc)) return hrc;

        if (bstrHostOnlyNetworkName == bstrNameToFind)
        {
            it->queryInterfaceTo(aNetwork.asOutParam());
            return S_OK;
        }
    }
    return VBOX_E_OBJECT_NOT_FOUND;
#else /* !VBOX_WITH_VMNET */
    NOREF(aNetworkName);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_VMNET */
}

HRESULT VirtualBox::findHostOnlyNetworkById(const com::Guid &aId,
                                           ComPtr<IHostOnlyNetwork> &aNetwork)
{
#ifdef VBOX_WITH_VMNET
    ComObjPtr<HostOnlyNetwork> network;
    AutoReadLock alock(m->allHostOnlyNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (HostOnlyNetworksOList::const_iterator it = m->allHostOnlyNetworks.begin();
         it != m->allHostOnlyNetworks.end();
         ++it)
    {
        Bstr bstrHostOnlyNetworkId;
        HRESULT hrc = (*it)->COMGETTER(Id)(bstrHostOnlyNetworkId.asOutParam());
        if (FAILED(hrc)) return hrc;

        if (Guid(bstrHostOnlyNetworkId) == aId)
        {
            it->queryInterfaceTo(aNetwork.asOutParam());;
            return S_OK;
        }
    }
    return VBOX_E_OBJECT_NOT_FOUND;
#else /* !VBOX_WITH_VMNET */
    NOREF(aId);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_VMNET */
}

HRESULT VirtualBox::removeHostOnlyNetwork(const ComPtr<IHostOnlyNetwork> &aNetwork)
{
#ifdef VBOX_WITH_VMNET
    Bstr name;
    HRESULT hrc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
    if (FAILED(hrc))
        return hrc;
    IHostOnlyNetwork *p = aNetwork;
    HostOnlyNetwork *network = static_cast<HostOnlyNetwork *>(p);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller HostOnlyNetworkCaller(network);
    AssertComRCReturnRC(HostOnlyNetworkCaller.hrc());

    m->allHostOnlyNetworks.removeChild(network);

    {
        AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
        vboxLock.release();

        if (FAILED(hrc))
            m->allHostOnlyNetworks.addChild(network);
    }
    return hrc;
#else /* !VBOX_WITH_VMNET */
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_VMNET */
}

HRESULT VirtualBox::getHostOnlyNetworks(std::vector<ComPtr<IHostOnlyNetwork> > &aHostOnlyNetworks)
{
#ifdef VBOX_WITH_VMNET
    AutoReadLock al(m->allHostOnlyNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aHostOnlyNetworks.resize(m->allHostOnlyNetworks.size());
    size_t i = 0;
    for (HostOnlyNetworksOList::const_iterator it = m->allHostOnlyNetworks.begin();
         it != m->allHostOnlyNetworks.end(); ++it)
         (*it).queryInterfaceTo(aHostOnlyNetworks[i++].asOutParam());
    return S_OK;
#else /* !VBOX_WITH_VMNET */
    NOREF(aHostOnlyNetworks);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_VMNET */
}


HRESULT VirtualBox::getInternalNetworks(std::vector<com::Utf8Str> &aInternalNetworks)
{
    std::list<com::Utf8Str> allInternalNetworks;

    /* get copy of all machine references, to avoid holding the list lock */
    MachinesOList::MyList allMachines;
    {
        AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
        allMachines = m->allMachines.getList();
    }
    for (MachinesOList::MyList::const_iterator it = allMachines.begin();
         it != allMachines.end(); ++it)
    {
        const ComObjPtr<Machine> &pMachine = *it;
        AutoCaller autoMachineCaller(pMachine);
        if (FAILED(autoMachineCaller.hrc()))
            continue;
        AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);

        if (pMachine->i_isAccessible())
        {
            uint32_t cNetworkAdapters = Global::getMaxNetworkAdapters(pMachine->i_getChipsetType());
            for (ULONG i = 0; i < cNetworkAdapters; i++)
            {
                ComPtr<INetworkAdapter> pNet;
                HRESULT hrc = pMachine->GetNetworkAdapter(i, pNet.asOutParam());
                if (FAILED(hrc) || pNet.isNull())
                    continue;
                Bstr strInternalNetwork;
                hrc = pNet->COMGETTER(InternalNetwork)(strInternalNetwork.asOutParam());
                if (FAILED(hrc) || strInternalNetwork.isEmpty())
                    continue;

                allInternalNetworks.push_back(Utf8Str(strInternalNetwork));
            }
        }
    }

    /* throw out any duplicates */
    allInternalNetworks.sort();
    allInternalNetworks.unique();
    size_t i = 0;
    aInternalNetworks.resize(allInternalNetworks.size());
    for (std::list<com::Utf8Str>::const_iterator it = allInternalNetworks.begin();
         it != allInternalNetworks.end();
         ++it, ++i)
        aInternalNetworks[i] = *it;
    return S_OK;
}

HRESULT VirtualBox::getGenericNetworkDrivers(std::vector<com::Utf8Str> &aGenericNetworkDrivers)
{
    std::list<com::Utf8Str> allGenericNetworkDrivers;

    /* get copy of all machine references, to avoid holding the list lock */
    MachinesOList::MyList allMachines;
    {
        AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
        allMachines = m->allMachines.getList();
    }
    for (MachinesOList::MyList::const_iterator it = allMachines.begin();
         it != allMachines.end();
         ++it)
    {
        const ComObjPtr<Machine> &pMachine = *it;
        AutoCaller autoMachineCaller(pMachine);
        if (FAILED(autoMachineCaller.hrc()))
            continue;
        AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);

        if (pMachine->i_isAccessible())
        {
            uint32_t cNetworkAdapters = Global::getMaxNetworkAdapters(pMachine->i_getChipsetType());
            for (ULONG i = 0; i < cNetworkAdapters; i++)
            {
                ComPtr<INetworkAdapter> pNet;
                HRESULT hrc = pMachine->GetNetworkAdapter(i, pNet.asOutParam());
                if (FAILED(hrc) || pNet.isNull())
                    continue;
                Bstr strGenericNetworkDriver;
                hrc = pNet->COMGETTER(GenericDriver)(strGenericNetworkDriver.asOutParam());
                if (FAILED(hrc) || strGenericNetworkDriver.isEmpty())
                    continue;

                allGenericNetworkDrivers.push_back(Utf8Str(strGenericNetworkDriver).c_str());
            }
        }
    }

    /* throw out any duplicates */
    allGenericNetworkDrivers.sort();
    allGenericNetworkDrivers.unique();
    aGenericNetworkDrivers.resize(allGenericNetworkDrivers.size());
    size_t i = 0;
    for (std::list<com::Utf8Str>::const_iterator it = allGenericNetworkDrivers.begin();
         it != allGenericNetworkDrivers.end(); ++it, ++i)
        aGenericNetworkDrivers[i] = *it;

    return S_OK;
}

/**
 * Cloud Network
 */
#ifdef VBOX_WITH_CLOUD_NET
HRESULT VirtualBox::i_findCloudNetworkByName(const com::Utf8Str &aNetworkName,
                                             ComObjPtr<CloudNetwork> *aNetwork)
{
    ComPtr<CloudNetwork> found;
    Bstr bstrNameToFind(aNetworkName);

    AutoReadLock alock(m->allCloudNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (CloudNetworksOList::const_iterator it = m->allCloudNetworks.begin();
         it != m->allCloudNetworks.end();
         ++it)
    {
        Bstr bstrCloudNetworkName;
        HRESULT hrc = (*it)->COMGETTER(NetworkName)(bstrCloudNetworkName.asOutParam());
        if (FAILED(hrc)) return hrc;

        if (bstrCloudNetworkName == bstrNameToFind)
        {
            *aNetwork = *it;
            return S_OK;
        }
    }
    return VBOX_E_OBJECT_NOT_FOUND;
}
#endif /* VBOX_WITH_CLOUD_NET */

HRESULT VirtualBox::createCloudNetwork(const com::Utf8Str &aNetworkName,
                                       ComPtr<ICloudNetwork> &aNetwork)
{
#ifdef VBOX_WITH_CLOUD_NET
    ComObjPtr<CloudNetwork> cloudNetwork;
    cloudNetwork.createObject();
    HRESULT hrc = cloudNetwork->init(this, aNetworkName);
    if (FAILED(hrc)) return hrc;

    m->allCloudNetworks.addChild(cloudNetwork);

    {
        AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
        vboxLock.release();

        if (FAILED(hrc))
            m->allCloudNetworks.removeChild(cloudNetwork);
        else
            cloudNetwork.queryInterfaceTo(aNetwork.asOutParam());
    }

    return hrc;
#else /* !VBOX_WITH_CLOUD_NET */
    NOREF(aNetworkName);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_CLOUD_NET */
}

HRESULT VirtualBox::findCloudNetworkByName(const com::Utf8Str &aNetworkName,
                                           ComPtr<ICloudNetwork> &aNetwork)
{
#ifdef VBOX_WITH_CLOUD_NET
    ComObjPtr<CloudNetwork> network;
    HRESULT hrc = i_findCloudNetworkByName(aNetworkName, &network);
    if (SUCCEEDED(hrc))
        network.queryInterfaceTo(aNetwork.asOutParam());
    return hrc;
#else /* !VBOX_WITH_CLOUD_NET */
    NOREF(aNetworkName);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_CLOUD_NET */
}

HRESULT VirtualBox::removeCloudNetwork(const ComPtr<ICloudNetwork> &aNetwork)
{
#ifdef VBOX_WITH_CLOUD_NET
    Bstr name;
    HRESULT hrc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
    if (FAILED(hrc))
        return hrc;
    ICloudNetwork *p = aNetwork;
    CloudNetwork *network = static_cast<CloudNetwork *>(p);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller cloudNetworkCaller(network);
    AssertComRCReturnRC(cloudNetworkCaller.hrc());

    m->allCloudNetworks.removeChild(network);

    {
        AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
        vboxLock.release();

        if (FAILED(hrc))
            m->allCloudNetworks.addChild(network);
    }
    return hrc;
#else /* !VBOX_WITH_CLOUD_NET */
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_CLOUD_NET */
}

HRESULT VirtualBox::getCloudNetworks(std::vector<ComPtr<ICloudNetwork> > &aCloudNetworks)
{
#ifdef VBOX_WITH_CLOUD_NET
    AutoReadLock al(m->allCloudNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    aCloudNetworks.resize(m->allCloudNetworks.size());
    size_t i = 0;
    for (CloudNetworksOList::const_iterator it = m->allCloudNetworks.begin();
         it != m->allCloudNetworks.end(); ++it)
         (*it).queryInterfaceTo(aCloudNetworks[i++].asOutParam());
    return S_OK;
#else /* !VBOX_WITH_CLOUD_NET */
    NOREF(aCloudNetworks);
    return E_NOTIMPL;
#endif /* !VBOX_WITH_CLOUD_NET */
}

#ifdef VBOX_WITH_CLOUD_NET
HRESULT VirtualBox::i_getEventSource(ComPtr<IEventSource>& aSource)
{
    m->pEventSource.queryInterfaceTo(aSource.asOutParam());
    return S_OK;
}
#endif /* VBOX_WITH_CLOUD_NET */

HRESULT VirtualBox::getCloudProviderManager(ComPtr<ICloudProviderManager> &aCloudProviderManager)
{
    HRESULT hrc = m->pCloudProviderManager.queryInterfaceTo(aCloudProviderManager.asOutParam());
    return hrc;
}

HRESULT VirtualBox::checkFirmwarePresent(FirmwareType_T aFirmwareType,
                                         const com::Utf8Str &aVersion,
                                         com::Utf8Str &aUrl,
                                         com::Utf8Str &aFile,
                                         BOOL *aResult)
{
    NOREF(aVersion);

    static const struct
    {
        FirmwareType_T  enmType;
        bool            fBuiltIn;
        const char     *pszFileName;
        const char     *pszUrl;
    }
    firmwareDesc[] =
    {
        {   FirmwareType_BIOS,    true,  NULL,             NULL },
#ifdef VBOX_WITH_EFI_IN_DD2
        {   FirmwareType_EFI32,   true,  "VBoxEFI32.fd",   NULL },
        {   FirmwareType_EFI64,   true,  "VBoxEFI64.fd",   NULL },
        {   FirmwareType_EFIDUAL, true,  "VBoxEFIDual.fd", NULL },
#else
        {   FirmwareType_EFI32,   false, "VBoxEFI32.fd",   "http://virtualbox.org/firmware/VBoxEFI32.fd" },
        {   FirmwareType_EFI64,   false, "VBoxEFI64.fd",   "http://virtualbox.org/firmware/VBoxEFI64.fd" },
        {   FirmwareType_EFIDUAL, false, "VBoxEFIDual.fd", "http://virtualbox.org/firmware/VBoxEFIDual.fd" },
#endif
    };

    for (size_t i = 0; i < sizeof(firmwareDesc) / sizeof(firmwareDesc[0]); i++)
    {
        if (aFirmwareType != firmwareDesc[i].enmType)
            continue;

        /* compiled-in firmware */
        if (firmwareDesc[i].fBuiltIn)
        {
            aFile = firmwareDesc[i].pszFileName;
            *aResult = TRUE;
            break;
        }

        Utf8Str    fullName;
        Utf8StrFmt shortName("Firmware%c%s", RTPATH_DELIMITER, firmwareDesc[i].pszFileName);
        int vrc = i_calculateFullPath(shortName, fullName);
        AssertRCReturn(vrc, VBOX_E_IPRT_ERROR);
        if (RTFileExists(fullName.c_str()))
        {
            *aResult = TRUE;
            aFile = fullName;
            break;
        }

        char szVBoxPath[RTPATH_MAX];
        vrc = RTPathExecDir(szVBoxPath, RTPATH_MAX);
        AssertRCReturn(vrc, VBOX_E_IPRT_ERROR);
        vrc = RTPathAppend(szVBoxPath, sizeof(szVBoxPath), firmwareDesc[i].pszFileName);
        AssertRCReturn(vrc, VBOX_E_IPRT_ERROR);
        if (RTFileExists(szVBoxPath))
        {
            *aResult = TRUE;
            aFile = szVBoxPath;
            break;
        }

        /** @todo account for version in the URL */
        aUrl = firmwareDesc[i].pszUrl;
        *aResult = FALSE;

        /* Assume single record per firmware type */
        break;
    }

    return S_OK;
}
// Wrapped IVirtualBox methods
/////////////////////////////////////////////////////////////////////////////

/* Helper for VirtualBox::ComposeMachineFilename */
static void sanitiseMachineFilename(Utf8Str &aName);

HRESULT VirtualBox::composeMachineFilename(const com::Utf8Str &aName,
                                           const com::Utf8Str &aGroup,
                                           const com::Utf8Str &aCreateFlags,
                                           const com::Utf8Str &aBaseFolder,
                                           com::Utf8Str       &aFile)
{
    if (RT_UNLIKELY(aName.isEmpty()))
        return setError(E_INVALIDARG, tr("Machine name is invalid, must not be empty"));

    Utf8Str strBase = aBaseFolder;
    Utf8Str strName = aName;

    LogFlowThisFunc(("aName=\"%s\",aBaseFolder=\"%s\"\n", strName.c_str(), strBase.c_str()));

    com::Guid id;
    bool fDirectoryIncludesUUID = false;
    if (!aCreateFlags.isEmpty())
    {
        size_t uPos = 0;
        com::Utf8Str strKey;
        com::Utf8Str strValue;
        while ((uPos = aCreateFlags.parseKeyValue(strKey, strValue, uPos)) != com::Utf8Str::npos)
        {
            if (strKey == "UUID")
                id = strValue.c_str();
            else if (strKey == "directoryIncludesUUID")
                fDirectoryIncludesUUID = (strValue == "1");
        }
    }

    if (id.isZero())
        fDirectoryIncludesUUID = false;
    else if (!id.isValid())
    {
        /* do something else */
        return setError(E_INVALIDARG,
                 tr("'%s' is not a valid Guid"),
                 id.toStringCurly().c_str());
    }

    Utf8Str strGroup(aGroup);
    if (strGroup.isEmpty())
        strGroup = "/";
    HRESULT hrc = i_validateMachineGroup(strGroup, true);
    if (FAILED(hrc))
        return hrc;

    /* Compose the settings file name using the following scheme:
     *
     *     <base_folder><group>/<machine_name>/<machine_name>.xml
     *
     * If a non-null and non-empty base folder is specified, the default
     * machine folder will be used as a base folder.
     * We sanitise the machine name to a safe white list of characters before
     * using it.
     */
    Utf8Str strDirName(strName);
    if (fDirectoryIncludesUUID)
        strDirName += Utf8StrFmt(" (%RTuuid)", id.raw());
    sanitiseMachineFilename(strName);
    sanitiseMachineFilename(strDirName);

    if (strBase.isEmpty())
        /* we use the non-full folder value below to keep the path relative */
        i_getDefaultMachineFolder(strBase);

    i_calculateFullPath(strBase, strBase);

    /* eliminate toplevel group to avoid // in the result */
    if (strGroup == "/")
        strGroup.setNull();
    aFile = com::Utf8StrFmt("%s%s%c%s%c%s.vbox",
                            strBase.c_str(),
                            strGroup.c_str(),
                            RTPATH_DELIMITER,
                            strDirName.c_str(),
                            RTPATH_DELIMITER,
                            strName.c_str());
    return S_OK;
}

/**
 * Remove characters from a machine file name which can be problematic on
 * particular systems.
 * @param  strName  The file name to sanitise.
 */
void sanitiseMachineFilename(Utf8Str &strName)
{
    if (strName.isEmpty())
        return;

    /* Set of characters which should be safe for use in filenames: some basic
     * ASCII, Unicode from Latin-1 alphabetic to the end of Hangul.  We try to
     * skip anything that could count as a control character in Windows or
     * *nix, or be otherwise difficult for shells to handle (I would have
     * preferred to remove the space and brackets too).  We also remove all
     * characters which need UTF-16 surrogate pairs for Windows's benefit.
     */
    static RTUNICP const s_uszValidRangePairs[] =
    {
        ' ', ' ',
        '(', ')',
        '-', '.',
        '0', '9',
        'A', 'Z',
        'a', 'z',
        '_', '_',
        0xa0, 0xd7af,
        '\0'
    };

    char *pszName = strName.mutableRaw();
    ssize_t cReplacements = RTStrPurgeComplementSet(pszName, s_uszValidRangePairs, '_');
    Assert(cReplacements >= 0);
    NOREF(cReplacements);

    /* No leading dot or dash. */
    if (pszName[0] == '.' || pszName[0] == '-')
        pszName[0] = '_';

    /* No trailing dot. */
    if (pszName[strName.length() - 1] == '.')
        pszName[strName.length() - 1] = '_';

    /* Mangle leading and trailing spaces. */
    for (size_t i = 0; pszName[i] == ' '; ++i)
        pszName[i] = '_';
    for (size_t i = strName.length() - 1; i && pszName[i] == ' '; --i)
        pszName[i] = '_';
}

#ifdef DEBUG
typedef DECLCALLBACKTYPE(void, FNTESTPRINTF,(const char *, ...));
/** Simple unit test/operation examples for sanitiseMachineFilename(). */
static unsigned testSanitiseMachineFilename(FNTESTPRINTF *pfnPrintf)
{
    unsigned cErrors = 0;

    /** Expected results of sanitising given file names. */
    static struct
    {
        /** The test file name to be sanitised (Utf-8). */
        const char *pcszIn;
        /** The expected sanitised output (Utf-8). */
        const char *pcszOutExpected;
    } aTest[] =
    {
        { "OS/2 2.1", "OS_2 2.1" },
        { "-!My VM!-", "__My VM_-" },
        { "\xF0\x90\x8C\xB0", "____" },
        { "  My VM  ", "__My VM__" },
        { ".My VM.", "_My VM_" },
        { "My VM", "My VM" }
    };
    for (unsigned i = 0; i < RT_ELEMENTS(aTest); ++i)
    {
        Utf8Str str(aTest[i].pcszIn);
        sanitiseMachineFilename(str);
        if (str.compare(aTest[i].pcszOutExpected))
        {
            ++cErrors;
            pfnPrintf("%s: line %d, expected %s, actual %s\n",
                      __PRETTY_FUNCTION__, i, aTest[i].pcszOutExpected,
                      str.c_str());
        }
    }
    return cErrors;
}

/** @todo Proper testcase. */
/** @todo Do we have a better method of doing init functions? */
namespace
{
    class TestSanitiseMachineFilename
    {
    public:
        TestSanitiseMachineFilename(void)
        {
            Assert(!testSanitiseMachineFilename(RTAssertMsg2));
        }
    };
    TestSanitiseMachineFilename s_TestSanitiseMachineFilename;
}
#endif

/** @note Locks mSystemProperties object for reading. */
HRESULT VirtualBox::createMachine(const com::Utf8Str &aSettingsFile,
                                  const com::Utf8Str &aName,
                                  const std::vector<com::Utf8Str> &aGroups,
                                  const com::Utf8Str &aOsTypeId,
                                  const com::Utf8Str &aFlags,
                                  const com::Utf8Str &aCipher,
                                  const com::Utf8Str &aPasswordId,
                                  const com::Utf8Str &aPassword,
                                  ComPtr<IMachine> &aMachine)
{
    LogFlowThisFuncEnter();
    LogFlowThisFunc(("aSettingsFile=\"%s\", aName=\"%s\", aOsTypeId =\"%s\", aCreateFlags=\"%s\"\n",
                     aSettingsFile.c_str(), aName.c_str(), aOsTypeId.c_str(), aFlags.c_str()));

    StringsList llGroups;
    HRESULT hrc = i_convertMachineGroups(aGroups, &llGroups);
    if (FAILED(hrc))
        return hrc;

    /** @todo r=bird: Would be goot to rewrite this parsing using offset into
     *        aFlags and drop all the C pointers, strchr, misguided RTStrStr and
     *        tedious copying of substrings. */
    Utf8Str strCreateFlags(aFlags); /** @todo r=bird: WTF is the point of this copy? */
    Guid id;
    bool fForceOverwrite = false;
    bool fDirectoryIncludesUUID = false;
    if (!strCreateFlags.isEmpty())
    {
        const char *pcszNext = strCreateFlags.c_str();
        while (*pcszNext != '\0')
        {
            Utf8Str strFlag;
            const char *pcszComma = strchr(pcszNext, ','); /*clueless version: RTStrStr(pcszNext, ","); */
            if (!pcszComma)
                strFlag = pcszNext;
            else
                strFlag.assign(pcszNext, (size_t)(pcszComma - pcszNext));

            const char *pcszEqual = strchr(strFlag.c_str(), '='); /* more cluelessness: RTStrStr(strFlag.c_str(), "="); */
            /* skip over everything which doesn't contain '=' */
            if (pcszEqual && pcszEqual != strFlag.c_str())
            {
                Utf8Str strKey(strFlag.c_str(), (size_t)(pcszEqual - strFlag.c_str()));
                Utf8Str strValue(strFlag.c_str() + (pcszEqual - strFlag.c_str() + 1));

                if (strKey == "UUID")
                    id = strValue.c_str();
                else if (strKey == "forceOverwrite")
                    fForceOverwrite = (strValue == "1");
                else if (strKey == "directoryIncludesUUID")
                    fDirectoryIncludesUUID = (strValue == "1");
            }

            if (!pcszComma)
                pcszNext += strFlag.length();  /* you can just 'break' out here... */
            else
                pcszNext += strFlag.length() + 1;
        }
    }

    /* Create UUID if none was specified. */
    if (id.isZero())
        id.create();
    else if (!id.isValid())
    {
        /* do something else */
        return setError(E_INVALIDARG, tr("'%s' is not a valid Guid"), id.toStringCurly().c_str());
    }

    /* NULL settings file means compose automatically */
    Utf8Str strSettingsFile(aSettingsFile);
    if (strSettingsFile.isEmpty())
    {
        Utf8Str strNewCreateFlags(Utf8StrFmt("UUID=%RTuuid", id.raw()));
        if (fDirectoryIncludesUUID)
            strNewCreateFlags += ",directoryIncludesUUID=1";

        com::Utf8Str blstr;
        hrc = composeMachineFilename(aName,
                                     llGroups.front(),
                                     strNewCreateFlags,
                                     blstr /* aBaseFolder */,
                                     strSettingsFile);
        if (FAILED(hrc)) return hrc;
    }

    /* create a new object */
    ComObjPtr<Machine> machine;
    hrc = machine.createObject();
    if (FAILED(hrc)) return hrc;

    ComObjPtr<GuestOSType> osType;
    if (!aOsTypeId.isEmpty())
        i_findGuestOSType(aOsTypeId, osType);

    /* initialize the machine object */
    hrc = machine->init(this,
                        strSettingsFile,
                        aName,
                        llGroups,
                        aOsTypeId,
                        osType,
                        id,
                        fForceOverwrite,
                        fDirectoryIncludesUUID,
                        aCipher,
                        aPasswordId,
                        aPassword);
    if (SUCCEEDED(hrc))
    {
        /* set the return value */
        machine.queryInterfaceTo(aMachine.asOutParam());
        AssertComRC(hrc);

#ifdef VBOX_WITH_EXTPACK
        /* call the extension pack hooks */
        m->ptrExtPackManager->i_callAllVmCreatedHooks(machine);
#endif
    }

    LogFlowThisFuncLeave();

    return hrc;
}

HRESULT VirtualBox::openMachine(const com::Utf8Str &aSettingsFile,
                                const com::Utf8Str &aPassword,
                                ComPtr<IMachine> &aMachine)
{
    /* create a new object */
    ComObjPtr<Machine> machine;
    HRESULT hrc = machine.createObject();
    if (SUCCEEDED(hrc))
    {
        /* initialize the machine object */
        hrc = machine->initFromSettings(this, aSettingsFile, NULL /* const Guid *aId */, aPassword);
        if (SUCCEEDED(hrc))
        {
            /* set the return value */
            machine.queryInterfaceTo(aMachine.asOutParam());
            ComAssertComRC(hrc);
        }
    }

    return hrc;
}

/** @note Locks objects! */
HRESULT VirtualBox::registerMachine(const ComPtr<IMachine> &aMachine)
{
    Bstr name;
    HRESULT hrc = aMachine->COMGETTER(Name)(name.asOutParam());
    if (FAILED(hrc)) return hrc;

    /* We can safely cast child to Machine * here because only Machine
     * implementations of IMachine can be among our children. */
    IMachine *aM = aMachine;
    Machine *pMachine = static_cast<Machine*>(aM);

    AutoCaller machCaller(pMachine);
    ComAssertComRCRetRC(machCaller.hrc());

    hrc = i_registerMachine(pMachine);
    /* fire an event */
    if (SUCCEEDED(hrc))
        i_onMachineRegistered(pMachine->i_getId(), TRUE);

    return hrc;
}

/** @note Locks this object for reading, then some machine objects for reading. */
HRESULT VirtualBox::findMachine(const com::Utf8Str &aSettingsFile,
                                ComPtr<IMachine> &aMachine)
{
    LogFlowThisFuncEnter();
    LogFlowThisFunc(("aSettingsFile=\"%s\", aMachine={%p}\n", aSettingsFile.c_str(), &aMachine));

    /* start with not found */
    HRESULT hrc = S_OK;
    ComObjPtr<Machine> pMachineFound;

    Guid id(aSettingsFile);
    Utf8Str strFile(aSettingsFile);
    if (id.isValid() && !id.isZero())
        hrc = i_findMachine(id,
                            true /* fPermitInaccessible */,
                            true /* setError */,
                            &pMachineFound);
        // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
    else
    {
        hrc = i_findMachineByName(strFile,
                                  true /* setError */,
                                  &pMachineFound);
        // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
    }

    /* this will set (*machine) to NULL if machineObj is null */
    pMachineFound.queryInterfaceTo(aMachine.asOutParam());

    LogFlowThisFunc(("aName=\"%s\", aMachine=%p, hrc=%08X\n", aSettingsFile.c_str(), &aMachine, hrc));
    LogFlowThisFuncLeave();

    return hrc;
}

HRESULT VirtualBox::getMachinesByGroups(const std::vector<com::Utf8Str> &aGroups,
                                        std::vector<ComPtr<IMachine> > &aMachines)
{
    StringsList llGroups;
    HRESULT hrc = i_convertMachineGroups(aGroups, &llGroups);
    if (FAILED(hrc))
        return hrc;

    /* we want to rely on sorted groups during compare, to save time */
    llGroups.sort();

    /* get copy of all machine references, to avoid holding the list lock */
    MachinesOList::MyList allMachines;
    AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    allMachines = m->allMachines.getList();

    std::vector<ComObjPtr<IMachine> > saMachines;
    saMachines.resize(0);
    for (MachinesOList::MyList::const_iterator it = allMachines.begin();
         it != allMachines.end();
         ++it)
    {
        const ComObjPtr<Machine> &pMachine = *it;
        AutoCaller autoMachineCaller(pMachine);
        if (FAILED(autoMachineCaller.hrc()))
            continue;
        AutoReadLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);

        if (pMachine->i_isAccessible())
        {
            const StringsList &thisGroups = pMachine->i_getGroups();
            for (StringsList::const_iterator it2 = thisGroups.begin();
                 it2 != thisGroups.end();
                 ++it2)
            {
                const Utf8Str &group = *it2;
                bool fAppended = false;
                for (StringsList::const_iterator it3 = llGroups.begin();
                     it3 != llGroups.end();
                     ++it3)
                {
                    int order = it3->compare(group);
                    if (order == 0)
                    {
                        saMachines.push_back(static_cast<IMachine *>(pMachine));
                        fAppended = true;
                        break;
                    }
                    else if (order > 0)
                        break;
                    else
                        continue;
                }
                /* avoid duplicates and save time */
                if (fAppended)
                    break;
            }
        }
    }
    aMachines.resize(saMachines.size());
    size_t i = 0;
    for(i = 0; i < saMachines.size(); ++i)
        saMachines[i].queryInterfaceTo(aMachines[i].asOutParam());

    return S_OK;
}

HRESULT VirtualBox::getMachineStates(const std::vector<ComPtr<IMachine> > &aMachines,
                                     std::vector<MachineState_T> &aStates)
{
    com::SafeIfaceArray<IMachine> saMachines(aMachines);
    aStates.resize(aMachines.size());
    for (size_t i = 0; i < saMachines.size(); i++)
    {
        ComPtr<IMachine> pMachine = saMachines[i];
        MachineState_T state = MachineState_Null;
        if (!pMachine.isNull())
        {
            HRESULT hrc = pMachine->COMGETTER(State)(&state);
            if (hrc == E_ACCESSDENIED)
                hrc = S_OK;
            AssertComRC(hrc);
        }
        aStates[i] = state;
    }
    return S_OK;
}

HRESULT VirtualBox::createUnattendedInstaller(ComPtr<IUnattended> &aUnattended)
{
#ifdef VBOX_WITH_UNATTENDED
    ComObjPtr<Unattended> ptrUnattended;
    HRESULT hrc = ptrUnattended.createObject();
    if (SUCCEEDED(hrc))
    {
        AutoReadLock wlock(this COMMA_LOCKVAL_SRC_POS);
        hrc = ptrUnattended->initUnattended(this);
        if (SUCCEEDED(hrc))
            hrc = ptrUnattended.queryInterfaceTo(aUnattended.asOutParam());
    }
    return hrc;
#else
    NOREF(aUnattended);
    return E_NOTIMPL;
#endif
}

HRESULT VirtualBox::createMedium(const com::Utf8Str &aFormat,
                                 const com::Utf8Str &aLocation,
                                 AccessMode_T aAccessMode,
                                 DeviceType_T aDeviceType,
                                 ComPtr<IMedium> &aMedium)
{
    NOREF(aAccessMode); /**< @todo r=klaus make use of access mode */

    HRESULT hrc = S_OK;

    ComObjPtr<Medium> medium;
    medium.createObject();
    com::Utf8Str format = aFormat;

    switch (aDeviceType)
    {
        case DeviceType_HardDisk:
        {

            /* we don't access non-const data members so no need to lock */
            if (format.isEmpty())
                i_getDefaultHardDiskFormat(format);

            hrc = medium->init(this,
                               format,
                               aLocation,
                               Guid::Empty /* media registry: none yet */,
                               aDeviceType);
        }
        break;

        case DeviceType_DVD:
        case DeviceType_Floppy:
        {

            if (format.isEmpty())
                return setError(E_INVALIDARG, tr("Format must be Valid Type%s"), format.c_str());

            // enforce read-only for DVDs even if caller specified ReadWrite
            if (aDeviceType == DeviceType_DVD)
                aAccessMode = AccessMode_ReadOnly;

             hrc = medium->init(this,
                                format,
                                aLocation,
                                Guid::Empty /* media registry: none yet */,
                                aDeviceType);

         }
         break;

         default:
             return setError(E_INVALIDARG, tr("Device type must be HardDisk, DVD or Floppy %d"), aDeviceType);
    }

    if (SUCCEEDED(hrc))
    {
        medium.queryInterfaceTo(aMedium.asOutParam());
        com::Guid uMediumId = medium->i_getId();
        if (uMediumId.isValid() && !uMediumId.isZero())
            i_onMediumRegistered(uMediumId, medium->i_getDeviceType(), TRUE);
    }

    return hrc;
}

HRESULT VirtualBox::openMedium(const com::Utf8Str &aLocation,
                               DeviceType_T aDeviceType,
                               AccessMode_T aAccessMode,
                               BOOL aForceNewUuid,
                               ComPtr<IMedium> &aMedium)
{
    HRESULT hrc = S_OK;
    Guid id(aLocation);
    ComObjPtr<Medium> pMedium;

    // have to get write lock as the whole find/update sequence must be done
    // in one critical section, otherwise there are races which can lead to
    // multiple Medium objects with the same content
    AutoWriteLock treeLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);

    // check if the device type is correct, and see if a medium for the
    // given path has already initialized; if so, return that
    switch (aDeviceType)
    {
        case DeviceType_HardDisk:
            if (id.isValid() && !id.isZero())
                hrc = i_findHardDiskById(id, false /* setError */, &pMedium);
            else
                hrc = i_findHardDiskByLocation(aLocation, false, /* aSetError */ &pMedium);
        break;

        case DeviceType_Floppy:
        case DeviceType_DVD:
            if (id.isValid() && !id.isZero())
                hrc = i_findDVDOrFloppyImage(aDeviceType, &id, Utf8Str::Empty, false /* setError */, &pMedium);
            else
                hrc = i_findDVDOrFloppyImage(aDeviceType, NULL, aLocation, false /* setError */, &pMedium);

            // enforce read-only for DVDs even if caller specified ReadWrite
            if (aDeviceType == DeviceType_DVD)
                aAccessMode = AccessMode_ReadOnly;
        break;

        default:
            return setError(E_INVALIDARG, tr("Device type must be HardDisk, DVD or Floppy %d"), aDeviceType);
    }

    bool fMediumRegistered = false;
    if (pMedium.isNull())
    {
        pMedium.createObject();
        treeLock.release();
        hrc = pMedium->init(this,
                            aLocation,
                            (aAccessMode == AccessMode_ReadWrite) ? Medium::OpenReadWrite : Medium::OpenReadOnly,
                            !!aForceNewUuid,
                            aDeviceType);
        treeLock.acquire();

        if (SUCCEEDED(hrc))
        {
            hrc = i_registerMedium(pMedium, &pMedium, treeLock);

            treeLock.release();

            /* Note that it's important to call uninit() on failure to register
             * because the differencing hard disk would have been already associated
             * with the parent and this association needs to be broken. */

            if (FAILED(hrc))
            {
                pMedium->uninit();
                hrc = VBOX_E_OBJECT_NOT_FOUND;
            }
            else
                fMediumRegistered = true;
        }
        else if (hrc != VBOX_E_INVALID_OBJECT_STATE)
            hrc = VBOX_E_OBJECT_NOT_FOUND;
    }

    if (SUCCEEDED(hrc))
    {
        pMedium.queryInterfaceTo(aMedium.asOutParam());
        if (fMediumRegistered)
            i_onMediumRegistered(pMedium->i_getId(), pMedium->i_getDeviceType() ,TRUE);
    }

    return hrc;
}


/** @note Locks this object for reading. */
HRESULT VirtualBox::getGuestOSType(const com::Utf8Str &aId,
                                   ComPtr<IGuestOSType> &aType)
{
    ComObjPtr<GuestOSType> pType;
    HRESULT hrc = i_findGuestOSType(aId, pType);
    pType.queryInterfaceTo(aType.asOutParam());
    return hrc;
}

HRESULT VirtualBox::createSharedFolder(const com::Utf8Str &aName,
                                       const com::Utf8Str &aHostPath,
                                       BOOL aWritable,
                                       BOOL aAutomount,
                                       const com::Utf8Str &aAutoMountPoint)
{
    NOREF(aName);
    NOREF(aHostPath);
    NOREF(aWritable);
    NOREF(aAutomount);
    NOREF(aAutoMountPoint);

    return setError(E_NOTIMPL, tr("Not yet implemented"));
}

HRESULT VirtualBox::removeSharedFolder(const com::Utf8Str &aName)
{
    NOREF(aName);
    return setError(E_NOTIMPL, tr("Not yet implemented"));
}

/**
 *  @note Locks this object for reading.
 */
HRESULT VirtualBox::getExtraDataKeys(std::vector<com::Utf8Str> &aKeys)
{
    using namespace settings;

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aKeys.resize(m->pMainConfigFile->mapExtraDataItems.size());
    size_t i = 0;
    for (StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.begin();
         it != m->pMainConfigFile->mapExtraDataItems.end(); ++it, ++i)
        aKeys[i] = it->first;

    return S_OK;
}

/**
 *  @note Locks this object for reading.
 */
HRESULT VirtualBox::getExtraData(const com::Utf8Str &aKey,
                                 com::Utf8Str &aValue)
{
    settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(aKey);
    if (it != m->pMainConfigFile->mapExtraDataItems.end())
        // found:
        aValue = it->second; // source is a Utf8Str

    /* return the result to caller (may be empty) */

    return S_OK;
}

/**
 *  @note Locks this object for writing.
 */
HRESULT VirtualBox::setExtraData(const com::Utf8Str &aKey,
                                 const com::Utf8Str &aValue)
{
    Utf8Str strKey(aKey);
    Utf8Str strValue(aValue);
    Utf8Str strOldValue;            // empty
    HRESULT hrc = S_OK;

    /* Because control characters in aKey have caused problems in the settings
     * they are rejected unless the key should be deleted. */
    if (!strValue.isEmpty())
    {
        for (size_t i = 0; i < strKey.length(); ++i)
        {
            char ch = strKey[i];
            if (RTLocCIsCntrl(ch))
                return E_INVALIDARG;
        }
    }

    // locking note: we only hold the read lock briefly to look up the old value,
    // then release it and call the onExtraCanChange callbacks. There is a small
    // chance of a race insofar as the callback might be called twice if two callers
    // change the same key at the same time, but that's a much better solution
    // than the deadlock we had here before. The actual changing of the extradata
    // is then performed under the write lock and race-free.

    // look up the old value first; if nothing has changed then we need not do anything
    {
        AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
        settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
        if (it != m->pMainConfigFile->mapExtraDataItems.end())
            strOldValue = it->second;
    }

    bool fChanged;
    if ((fChanged = (strOldValue != strValue)))
    {
        // ask for permission from all listeners outside the locks;
        // onExtraDataCanChange() only briefly requests the VirtualBox
        // lock to copy the list of callbacks to invoke
        Bstr error;

        if (!i_onExtraDataCanChange(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw(), error))
        {
            const char *sep = error.isEmpty() ? "" : ": ";
            Log1WarningFunc(("Someone vetoed! Change refused%s%ls\n", sep, error.raw()));
            return setError(E_ACCESSDENIED,
                            tr("Could not set extra data because someone refused the requested change of '%s' to '%s'%s%ls"),
                            strKey.c_str(),
                            strValue.c_str(),
                            sep,
                            error.raw());
        }

        // data is changing and change not vetoed: then write it out under the lock

        AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

        if (strValue.isEmpty())
            m->pMainConfigFile->mapExtraDataItems.erase(strKey);
        else
            m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
                // creates a new key if needed

        /* save settings on success */
        hrc = i_saveSettings();
        if (FAILED(hrc)) return hrc;
    }

    // fire notification outside the lock
    if (fChanged)
        i_onExtraDataChanged(Guid::Empty, Bstr(aKey).raw(), Bstr(aValue).raw());

    return hrc;
}

/**
 *
 */
HRESULT VirtualBox::setSettingsSecret(const com::Utf8Str &aPassword)
{
    i_storeSettingsKey(aPassword);
    i_decryptSettings();
    return S_OK;
}

int VirtualBox::i_decryptMediumSettings(Medium *pMedium)
{
    Bstr bstrCipher;
    HRESULT hrc = pMedium->GetProperty(Bstr("InitiatorSecretEncrypted").raw(),
                                       bstrCipher.asOutParam());
    if (SUCCEEDED(hrc))
    {
        Utf8Str strPlaintext;
        int vrc = i_decryptSetting(&strPlaintext, bstrCipher);
        if (RT_SUCCESS(vrc))
            pMedium->i_setPropertyDirect("InitiatorSecret", strPlaintext);
        else
            return vrc;
    }
    return VINF_SUCCESS;
}

/**
 * Decrypt all encrypted settings.
 *
 * So far we only have encrypted iSCSI initiator secrets so we just go through
 * all hard disk media and determine the plain 'InitiatorSecret' from
 * 'InitiatorSecretEncrypted. The latter is stored as Base64 because medium
 * properties need to be null-terminated strings.
 */
int VirtualBox::i_decryptSettings()
{
    bool fFailure = false;
    AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    for (MediaList::const_iterator mt = m->allHardDisks.begin();
         mt != m->allHardDisks.end();
         ++mt)
    {
        ComObjPtr<Medium> pMedium = *mt;
        AutoCaller medCaller(pMedium);
        if (FAILED(medCaller.hrc()))
            continue;
        AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
        int vrc = i_decryptMediumSettings(pMedium);
        if (RT_FAILURE(vrc))
            fFailure = true;
    }
    if (!fFailure)
    {
        for (MediaList::const_iterator mt = m->allHardDisks.begin();
             mt != m->allHardDisks.end();
             ++mt)
        {
            i_onMediumConfigChanged(*mt);
        }
    }
    return fFailure ? VERR_INVALID_PARAMETER : VINF_SUCCESS;
}

/**
 * Encode.
 *
 * @param aPlaintext      plaintext to be encrypted
 * @param aCiphertext     resulting ciphertext (base64-encoded)
 */
int VirtualBox::i_encryptSetting(const Utf8Str &aPlaintext, Utf8Str *aCiphertext)
{
    uint8_t abCiphertext[32];
    char    szCipherBase64[128];
    size_t  cchCipherBase64;
    int vrc = i_encryptSettingBytes((uint8_t*)aPlaintext.c_str(), abCiphertext, aPlaintext.length()+1, sizeof(abCiphertext));
    if (RT_SUCCESS(vrc))
    {
        vrc = RTBase64Encode(abCiphertext, sizeof(abCiphertext), szCipherBase64, sizeof(szCipherBase64), &cchCipherBase64);
        if (RT_SUCCESS(vrc))
            *aCiphertext = szCipherBase64;
    }
    return vrc;
}

/**
 * Decode.
 *
 * @param aPlaintext      resulting plaintext
 * @param aCiphertext     ciphertext (base64-encoded) to decrypt
 */
int VirtualBox::i_decryptSetting(Utf8Str *aPlaintext, const Utf8Str &aCiphertext)
{
    uint8_t abPlaintext[64];
    uint8_t abCiphertext[64];
    size_t  cbCiphertext;
    int vrc = RTBase64Decode(aCiphertext.c_str(),
                             abCiphertext, sizeof(abCiphertext),
                             &cbCiphertext, NULL);
    if (RT_SUCCESS(vrc))
    {
        vrc = i_decryptSettingBytes(abPlaintext, abCiphertext, cbCiphertext);
        if (RT_SUCCESS(vrc))
        {
            for (unsigned i = 0; i < cbCiphertext; i++)
            {
                /* sanity check: null-terminated string? */
                if (abPlaintext[i] == '\0')
                {
                    /* sanity check: valid UTF8 string? */
                    if (RTStrIsValidEncoding((const char*)abPlaintext))
                    {
                        *aPlaintext = Utf8Str((const char*)abPlaintext);
                        return VINF_SUCCESS;
                    }
                }
            }
            vrc = VERR_INVALID_MAGIC;
        }
    }
    return vrc;
}

/**
 * Encrypt secret bytes. Use the m->SettingsCipherKey as key.
 *
 * @param aPlaintext      clear text to be encrypted
 * @param aCiphertext     resulting encrypted text
 * @param aPlaintextSize  size of the plaintext
 * @param aCiphertextSize size of the ciphertext
 */
int VirtualBox::i_encryptSettingBytes(const uint8_t *aPlaintext, uint8_t *aCiphertext,
                                    size_t aPlaintextSize, size_t aCiphertextSize) const
{
    unsigned i, j;
    uint8_t aBytes[64];

    if (!m->fSettingsCipherKeySet)
        return VERR_INVALID_STATE;

    if (aCiphertextSize > sizeof(aBytes))
        return VERR_BUFFER_OVERFLOW;

    if (aCiphertextSize < 32)
        return VERR_INVALID_PARAMETER;

    AssertCompile(sizeof(m->SettingsCipherKey) >= 32);

    /* store the first 8 bytes of the cipherkey for verification */
    for (i = 0, j = 0; i < 8; i++, j++)
        aCiphertext[i] = m->SettingsCipherKey[j];

    for (unsigned k = 0; k < aPlaintextSize && i < aCiphertextSize; i++, k++)
    {
        aCiphertext[i] = (aPlaintext[k] ^ m->SettingsCipherKey[j]);
        if (++j >= sizeof(m->SettingsCipherKey))
            j = 0;
    }

    /* fill with random data to have a minimal length (salt) */
    if (i < aCiphertextSize)
    {
        RTRandBytes(aBytes, aCiphertextSize - i);
        for (int k = 0; i < aCiphertextSize; i++, k++)
        {
            aCiphertext[i] = aBytes[k] ^ m->SettingsCipherKey[j];
            if (++j >= sizeof(m->SettingsCipherKey))
                j = 0;
        }
    }

    return VINF_SUCCESS;
}

/**
 * Decrypt secret bytes. Use the m->SettingsCipherKey as key.
 *
 * @param aPlaintext      resulting plaintext
 * @param aCiphertext     ciphertext to be decrypted
 * @param aCiphertextSize size of the ciphertext == size of the plaintext
 */
int VirtualBox::i_decryptSettingBytes(uint8_t *aPlaintext,
                                      const uint8_t *aCiphertext, size_t aCiphertextSize) const
{
    unsigned i, j;

    if (!m->fSettingsCipherKeySet)
        return VERR_INVALID_STATE;

    if (aCiphertextSize < 32)
        return VERR_INVALID_PARAMETER;

    /* key verification */
    for (i = 0, j = 0; i < 8; i++, j++)
        if (aCiphertext[i] != m->SettingsCipherKey[j])
            return VERR_INVALID_MAGIC;

    /* poison */
    memset(aPlaintext, 0xff, aCiphertextSize);
    for (int k = 0; i < aCiphertextSize; i++, k++)
    {
        aPlaintext[k] = aCiphertext[i] ^ m->SettingsCipherKey[j];
        if (++j >= sizeof(m->SettingsCipherKey))
            j = 0;
    }

    return VINF_SUCCESS;
}

/**
 * Store a settings key.
 *
 * @param aKey          the key to store
 */
void VirtualBox::i_storeSettingsKey(const Utf8Str &aKey)
{
    RTSha512(aKey.c_str(), aKey.length(), m->SettingsCipherKey);
    m->fSettingsCipherKeySet = true;
}

// public methods only for internal purposes
/////////////////////////////////////////////////////////////////////////////

#ifdef DEBUG
void VirtualBox::i_dumpAllBackRefs()
{
    {
        AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
        for (MediaList::const_iterator mt = m->allHardDisks.begin();
             mt != m->allHardDisks.end();
             ++mt)
        {
            ComObjPtr<Medium> pMedium = *mt;
            pMedium->i_dumpBackRefs();
        }
    }
    {
        AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
        for (MediaList::const_iterator mt = m->allDVDImages.begin();
             mt != m->allDVDImages.end();
             ++mt)
        {
            ComObjPtr<Medium> pMedium = *mt;
            pMedium->i_dumpBackRefs();
        }
    }
}
#endif

/**
 *  Posts an event to the event queue that is processed asynchronously
 *  on a dedicated thread.
 *
 *  Posting events to the dedicated event queue is useful to perform secondary
 *  actions outside any object locks -- for example, to iterate over a list
 *  of callbacks and inform them about some change caused by some object's
 *  method call.
 *
 *  @param event    event to post; must have been allocated using |new|, will
 *                  be deleted automatically by the event thread after processing
 *
 *  @note Doesn't lock any object.
 */
HRESULT VirtualBox::i_postEvent(Event *event)
{
    AssertReturn(event, E_FAIL);

    HRESULT hrc;
    AutoCaller autoCaller(this);
    if (SUCCEEDED((hrc = autoCaller.hrc())))
    {
        if (getObjectState().getState() != ObjectState::Ready)
            Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
                             getObjectState().getState()));
            // return S_OK
        else if (    (m->pAsyncEventQ)
                  && (m->pAsyncEventQ->postEvent(event))
                )
            return S_OK;
        else
            hrc = E_FAIL;
    }

    // in any event of failure, we must clean up here, or we'll leak;
    // the caller has allocated the object using new()
    delete event;
    return hrc;
}

/**
 * Adds a progress to the global collection of pending operations.
 * Usually gets called upon progress object initialization.
 *
 * @param aProgress Operation to add to the collection.
 *
 * @note Doesn't lock objects.
 */
HRESULT VirtualBox::i_addProgress(IProgress *aProgress)
{
    CheckComArgNotNull(aProgress);

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

    Bstr id;
    HRESULT hrc = aProgress->COMGETTER(Id)(id.asOutParam());
    AssertComRCReturnRC(hrc);

    /* protect mProgressOperations */
    AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);

    m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
    return S_OK;
}

/**
 * Removes the progress from the global collection of pending operations.
 * Usually gets called upon progress completion.
 *
 * @param aId   UUID of the progress operation to remove
 *
 * @note Doesn't lock objects.
 */
HRESULT VirtualBox::i_removeProgress(IN_GUID aId)
{
    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

    ComPtr<IProgress> progress;

    /* protect mProgressOperations */
    AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);

    size_t cnt = m->mapProgressOperations.erase(aId);
    Assert(cnt == 1);
    NOREF(cnt);

    return S_OK;
}

#ifdef RT_OS_WINDOWS

class StartSVCHelperClientData : public ThreadTask
{
public:
    StartSVCHelperClientData()
    {
        LogFlowFuncEnter();
        m_strTaskName = "SVCHelper";
        threadVoidData = NULL;
        initialized = false;
    }

    virtual ~StartSVCHelperClientData()
    {
        LogFlowFuncEnter();
        if (threadVoidData!=NULL)
        {
            delete threadVoidData;
            threadVoidData=NULL;
        }
    };

    void handler()
    {
        VirtualBox::i_SVCHelperClientThreadTask(this);
    }

    const ComPtr<Progress>& GetProgressObject() const {return progress;}

    bool init(VirtualBox* aVbox,
              Progress* aProgress,
              bool aPrivileged,
              VirtualBox::PFN_SVC_HELPER_CLIENT_T aFunc,
              void *aUser)
    {
        LogFlowFuncEnter();
        that = aVbox;
        progress = aProgress;
        privileged = aPrivileged;
        func = aFunc;
        user = aUser;

        initThreadVoidData();

        initialized = true;

        return initialized;
    }

    bool isOk() const{ return initialized;}

    bool initialized;
    ComObjPtr<VirtualBox> that;
    ComObjPtr<Progress> progress;
    bool privileged;
    VirtualBox::PFN_SVC_HELPER_CLIENT_T func;
    void *user;
    ThreadVoidData *threadVoidData;

private:
    bool initThreadVoidData()
    {
        LogFlowFuncEnter();
        threadVoidData = static_cast<ThreadVoidData*>(user);
        return true;
    }
};

/**
 *  Helper method that starts a worker thread that:
 *  - creates a pipe communication channel using SVCHlpClient;
 *  - starts an SVC Helper process that will inherit this channel;
 *  - executes the supplied function by passing it the created SVCHlpClient
 *    and opened instance to communicate to the Helper process and the given
 *    Progress object.
 *
 *  The user function is supposed to communicate to the helper process
 *  using the \a aClient argument to do the requested job and optionally expose
 *  the progress through the \a aProgress object. The user function should never
 *  call notifyComplete() on it: this will be done automatically using the
 *  result code returned by the function.
 *
 *  Before the user function is started, the communication channel passed to
 *  the \a aClient argument is fully set up, the function should start using
 *  its write() and read() methods directly.
 *
 *  The \a aVrc parameter of the user function may be used to return an error
 *  code if it is related to communication errors (for example, returned by
 *  the SVCHlpClient members when they fail). In this case, the correct error
 *  message using this value will be reported to the caller. Note that the
 *  value of \a aVrc is inspected only if the user function itself returns
 *  success.
 *
 *  If a failure happens anywhere before the user function would be normally
 *  called, it will be called anyway in special "cleanup only" mode indicated
 *  by \a aClient, \a aProgress and \a aVrc arguments set to NULL. In this mode,
 *  all the function is supposed to do is to cleanup its aUser argument if
 *  necessary (it's assumed that the ownership of this argument is passed to
 *  the user function once #startSVCHelperClient() returns a success, thus
 *  making it responsible for the cleanup).
 *
 *  After the user function returns, the thread will send the SVCHlpMsg::Null
 *  message to indicate a process termination.
 *
 *  @param  aPrivileged |true| to start the SVC Helper process as a privileged
 *                      user that can perform administrative tasks
 *  @param  aFunc       user function to run
 *  @param  aUser       argument to the user function
 *  @param  aProgress   progress object that will track operation completion
 *
 *  @note aPrivileged is currently ignored (due to some unsolved problems in
 *        Vista) and the process will be started as a normal (unprivileged)
 *        process.
 *
 *  @note Doesn't lock anything.
 */
HRESULT VirtualBox::i_startSVCHelperClient(bool aPrivileged,
                                           PFN_SVC_HELPER_CLIENT_T aFunc,
                                           void *aUser, Progress *aProgress)
{
    LogFlowFuncEnter();
    AssertReturn(aFunc, E_POINTER);
    AssertReturn(aProgress, E_POINTER);

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

    /* create the i_SVCHelperClientThreadTask() argument */

    HRESULT hrc = S_OK;
    StartSVCHelperClientData *pTask = NULL;
    try
    {
        pTask = new StartSVCHelperClientData();

        pTask->init(this, aProgress, aPrivileged, aFunc, aUser);

        if (!pTask->isOk())
        {
            delete pTask;
            LogRel(("Could not init StartSVCHelperClientData object \n"));
            throw E_FAIL;
        }

        //this function delete pTask in case of exceptions, so there is no need in the call of delete operator
        hrc = pTask->createThreadWithType(RTTHREADTYPE_MAIN_WORKER);

    }
    catch(std::bad_alloc &)
    {
        hrc = setError(E_OUTOFMEMORY);
    }
    catch(...)
    {
        LogRel(("Could not create thread for StartSVCHelperClientData \n"));
        hrc = E_FAIL;
    }

    return hrc;
}

/**
 *  Worker thread for startSVCHelperClient().
 */
/* static */
void VirtualBox::i_SVCHelperClientThreadTask(StartSVCHelperClientData *pTask)
{
    LogFlowFuncEnter();
    HRESULT hrc = S_OK;
    bool userFuncCalled = false;

    do
    {
        AssertBreakStmt(pTask, hrc = E_POINTER);
        AssertReturnVoid(!pTask->progress.isNull());

        /* protect VirtualBox from uninitialization */
        AutoCaller autoCaller(pTask->that);
        if (!autoCaller.isOk())
        {
            /* it's too late */
            hrc = autoCaller.hrc();
            break;
        }

        int vrc = VINF_SUCCESS;

        Guid id;
        id.create();
        SVCHlpClient client;
        vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
                                       id.raw()).c_str());
        if (RT_FAILURE(vrc))
        {
            hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not create the communication channel (%Rrc)"), vrc);
            break;
        }

        /* get the path to the executable */
        char exePathBuf[RTPATH_MAX];
        char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
        if (!exePath)
        {
            hrc = pTask->that->setError(E_FAIL, tr("Cannot get executable name"));
            break;
        }

        Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());

        LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));

        RTPROCESS pid = NIL_RTPROCESS;

        if (pTask->privileged)
        {
            /* Attempt to start a privileged process using the Run As dialog */

            Bstr file = exePath;
            Bstr parameters = argsStr;

            SHELLEXECUTEINFO shExecInfo;

            shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);

            shExecInfo.fMask = NULL;
            shExecInfo.hwnd = NULL;
            shExecInfo.lpVerb = L"runas";
            shExecInfo.lpFile = file.raw();
            shExecInfo.lpParameters = parameters.raw();
            shExecInfo.lpDirectory = NULL;
            shExecInfo.nShow = SW_NORMAL;
            shExecInfo.hInstApp = NULL;

            if (!ShellExecuteEx(&shExecInfo))
            {
                int vrc2 = RTErrConvertFromWin32(GetLastError());
                /* hide excessive details in case of a frequent error
                 * (pressing the Cancel button to close the Run As dialog) */
                if (vrc2 == VERR_CANCELLED)
                    hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Operation canceled by the user"));
                else
                    hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a privileged process '%s' (%Rrc)"), exePath, vrc2);
                break;
            }
        }
        else
        {
            const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
            vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
            if (RT_FAILURE(vrc))
            {
                hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
                break;
            }
        }

        /* wait for the client to connect */
        vrc = client.connect();
        if (RT_SUCCESS(vrc))
        {
            /* start the user supplied function */
            hrc = pTask->func(&client, pTask->progress, pTask->user, &vrc);
            userFuncCalled = true;
        }

        /* send the termination signal to the process anyway */
        {
            int vrc2 = client.write(SVCHlpMsg::Null);
            if (RT_SUCCESS(vrc))
                vrc = vrc2;
        }

        if (SUCCEEDED(hrc) && RT_FAILURE(vrc))
        {
            hrc = pTask->that->setErrorBoth(E_FAIL, vrc, tr("Could not operate the communication channel (%Rrc)"), vrc);
            break;
        }
    }
    while (0);

    if (FAILED(hrc) && !userFuncCalled)
    {
        /* call the user function in the "cleanup only" mode
         * to let it free resources passed to in aUser */
        pTask->func(NULL, NULL, pTask->user, NULL);
    }

    pTask->progress->i_notifyComplete(hrc);

    LogFlowFuncLeave();
}

#endif /* RT_OS_WINDOWS */

/**
 *  Sends a signal to the client watcher to rescan the set of machines
 *  that have open sessions.
 *
 *  @note Doesn't lock anything.
 */
void VirtualBox::i_updateClientWatcher()
{
    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.hrc());

    AssertPtrReturnVoid(m->pClientWatcher);
    m->pClientWatcher->update();
}

/**
 *  Adds the given child process ID to the list of processes to be reaped.
 *  This call should be followed by #i_updateClientWatcher() to take the effect.
 *
 *  @note Doesn't lock anything.
 */
void VirtualBox::i_addProcessToReap(RTPROCESS pid)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.hrc());

    AssertPtrReturnVoid(m->pClientWatcher);
    m->pClientWatcher->addProcess(pid);
}

/**
 * VD plugin load
 */
int VirtualBox::i_loadVDPlugin(const char *pszPluginLibrary)
{
    return m->pSystemProperties->i_loadVDPlugin(pszPluginLibrary);
}

/**
 * VD plugin unload
 */
int VirtualBox::i_unloadVDPlugin(const char *pszPluginLibrary)
{
    return m->pSystemProperties->i_unloadVDPlugin(pszPluginLibrary);
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onMediumRegistered(const Guid &aMediumId, const DeviceType_T aDevType, const BOOL aRegistered)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMediumRegisteredEvent(ptrEvent.asOutParam(), m->pEventSource,
                                                aMediumId.toString(), aDevType, aRegistered);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

void VirtualBox::i_onMediumConfigChanged(IMedium *aMedium)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMediumConfigChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aMedium);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

void VirtualBox::i_onMediumChanged(IMediumAttachment *aMediumAttachment)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMediumChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aMediumAttachment);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onStorageControllerChanged(const Guid &aMachineId, const com::Utf8Str &aControllerName)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateStorageControllerChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
                                                        aMachineId.toString(), aControllerName);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

void VirtualBox::i_onStorageDeviceChanged(IMediumAttachment *aStorageDevice, const BOOL fRemoved, const BOOL fSilent)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateStorageDeviceChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aStorageDevice, fRemoved, fSilent);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onMachineStateChanged(const Guid &aId, MachineState_T aState)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMachineStateChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aState);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onMachineDataChanged(const Guid &aId, BOOL aTemporary)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMachineDataChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aTemporary);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onMachineGroupsChanged(const Guid &aId)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMachineGroupsChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), FALSE /*aDummy*/);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Locks this object for reading.
 */
BOOL VirtualBox::i_onExtraDataCanChange(const Guid &aId, const Utf8Str &aKey, const Utf8Str &aValue, Bstr &aError)
{
    LogFlowThisFunc(("machine={%RTuuid} aKey={%s} aValue={%s}\n", aId.raw(), aKey.c_str(), aValue.c_str()));

    AutoCaller autoCaller(this);
    AssertComRCReturn(autoCaller.hrc(), FALSE);

    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateExtraDataCanChangeEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aKey, aValue);
    AssertComRCReturn(hrc, TRUE);

    VBoxEventDesc EvtDesc(ptrEvent, m->pEventSource);
    BOOL fDelivered = EvtDesc.fire(3000); /* Wait up to 3 secs for delivery */
    //Assert(fDelivered);
    BOOL fAllowChange = TRUE;
    if (fDelivered)
    {
        ComPtr<IExtraDataCanChangeEvent> ptrCanChangeEvent = ptrEvent;
        Assert(ptrCanChangeEvent);

        BOOL fVetoed = FALSE;
        ptrCanChangeEvent->IsVetoed(&fVetoed);
        fAllowChange = !fVetoed;

        if (!fAllowChange)
        {
            SafeArray<BSTR> aVetos;
            ptrCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
            if (aVetos.size() > 0)
                aError = aVetos[0];
        }
    }

    LogFlowThisFunc(("fAllowChange=%RTbool\n", fAllowChange));
    return fAllowChange;
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onExtraDataChanged(const Guid &aId, const Utf8Str &aKey, const Utf8Str &aValue)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateExtraDataChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aKey, aValue);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onMachineRegistered(const Guid &aId, BOOL aRegistered)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateMachineRegisteredEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aRegistered);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onSessionStateChanged(const Guid &aId, SessionState_T aState)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateSessionStateChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aId.toString(), aState);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateSnapshotTakenEvent(ptrEvent.asOutParam(), m->pEventSource,
                                             aMachineId.toString(), aSnapshotId.toString());
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateSnapshotDeletedEvent(ptrEvent.asOutParam(), m->pEventSource,
                                               aMachineId.toString(), aSnapshotId.toString());
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onSnapshotRestored(const Guid &aMachineId, const Guid &aSnapshotId)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateSnapshotRestoredEvent(ptrEvent.asOutParam(), m->pEventSource,
                                                aMachineId.toString(), aSnapshotId.toString());
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onSnapshotChanged(const Guid &aMachineId, const Guid &aSnapshotId)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateSnapshotChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
                                               aMachineId.toString(), aSnapshotId.toString());
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onGuestPropertyChanged(const Guid &aMachineId, const Utf8Str &aName, const Utf8Str &aValue,
                                          const Utf8Str &aFlags, const BOOL fWasDeleted)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateGuestPropertyChangedEvent(ptrEvent.asOutParam(), m->pEventSource,
                                                    aMachineId.toString(), aName, aValue, aFlags, fWasDeleted);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onNatRedirectChanged(const Guid &aMachineId, ULONG ulSlot, bool fRemove, const Utf8Str &aName,
                                        NATProtocol_T aProto, const Utf8Str &aHostIp, uint16_t aHostPort,
                                        const Utf8Str &aGuestIp, uint16_t aGuestPort)
{
    ::FireNATRedirectEvent(m->pEventSource, aMachineId.toString(), ulSlot, fRemove, aName, aProto, aHostIp,
                           aHostPort, aGuestIp, aGuestPort);
}

/** @todo Unused!!  */
void VirtualBox::i_onNATNetworkChanged(const Utf8Str &aName)
{
    ::FireNATNetworkChangedEvent(m->pEventSource, aName);
}

void VirtualBox::i_onNATNetworkStartStop(const Utf8Str &aName, BOOL fStart)
{
    ::FireNATNetworkStartStopEvent(m->pEventSource, aName, fStart);
}

void VirtualBox::i_onNATNetworkSetting(const Utf8Str &aNetworkName, BOOL aEnabled,
                                       const Utf8Str &aNetwork, const Utf8Str &aGateway,
                                       BOOL aAdvertiseDefaultIpv6RouteEnabled,
                                       BOOL fNeedDhcpServer)
{
    ::FireNATNetworkSettingEvent(m->pEventSource, aNetworkName, aEnabled, aNetwork, aGateway,
                                 aAdvertiseDefaultIpv6RouteEnabled, fNeedDhcpServer);
}

void VirtualBox::i_onNATNetworkPortForward(const Utf8Str &aNetworkName, BOOL create, BOOL fIpv6,
                                           const Utf8Str &aRuleName, NATProtocol_T proto,
                                           const Utf8Str &aHostIp, LONG aHostPort,
                                           const Utf8Str &aGuestIp, LONG aGuestPort)
{
    ::FireNATNetworkPortForwardEvent(m->pEventSource, aNetworkName, create, fIpv6, aRuleName, proto,
                                     aHostIp, aHostPort, aGuestIp, aGuestPort);
}


void VirtualBox::i_onHostNameResolutionConfigurationChange()
{
    if (m->pEventSource)
        ::FireHostNameResolutionConfigurationChangeEvent(m->pEventSource);
}


int VirtualBox::i_natNetworkRefInc(const Utf8Str &aNetworkName)
{
    AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);

    if (!sNatNetworkNameToRefCount[aNetworkName])
    {
        ComPtr<INATNetwork> nat;
        HRESULT hrc = findNATNetworkByName(aNetworkName, nat);
        if (FAILED(hrc)) return -1;

        hrc = nat->Start();
        if (SUCCEEDED(hrc))
            LogRel(("Started NAT network '%s'\n", aNetworkName.c_str()));
        else
            LogRel(("Error %Rhrc starting NAT network '%s'\n", hrc, aNetworkName.c_str()));
        AssertComRCReturn(hrc, -1);
    }

    sNatNetworkNameToRefCount[aNetworkName]++;

    return sNatNetworkNameToRefCount[aNetworkName];
}


int VirtualBox::i_natNetworkRefDec(const Utf8Str &aNetworkName)
{
    AutoWriteLock safeLock(*spMtxNatNetworkNameToRefCountLock COMMA_LOCKVAL_SRC_POS);

    if (!sNatNetworkNameToRefCount[aNetworkName])
        return 0;

    sNatNetworkNameToRefCount[aNetworkName]--;

    if (!sNatNetworkNameToRefCount[aNetworkName])
    {
        ComPtr<INATNetwork> nat;
        HRESULT hrc = findNATNetworkByName(aNetworkName, nat);
        if (FAILED(hrc)) return -1;

        hrc = nat->Stop();
        if (SUCCEEDED(hrc))
            LogRel(("Stopped NAT network '%s'\n", aNetworkName.c_str()));
        else
            LogRel(("Error %Rhrc stopping NAT network '%s'\n", hrc, aNetworkName.c_str()));
        AssertComRCReturn(hrc, -1);
    }

    return sNatNetworkNameToRefCount[aNetworkName];
}


/*
 * Export this to NATNetwork so that its setters can refuse to change
 * essential network settings when an VBoxNatNet instance is running.
 */
RWLockHandle *VirtualBox::i_getNatNetLock() const
{
    return spMtxNatNetworkNameToRefCountLock;
}


/*
 * Export this to NATNetwork so that its setters can refuse to change
 * essential network settings when an VBoxNatNet instance is running.
 * The caller is expected to hold a read lock on i_getNatNetLock().
 */
bool VirtualBox::i_isNatNetStarted(const Utf8Str &aNetworkName) const
{
    return sNatNetworkNameToRefCount[aNetworkName] > 0;
}


void VirtualBox::i_onCloudProviderListChanged(BOOL aRegistered)
{
    ::FireCloudProviderListChangedEvent(m->pEventSource, aRegistered);
}


void VirtualBox::i_onCloudProviderRegistered(const Utf8Str &aProviderId, BOOL aRegistered)
{
    ::FireCloudProviderRegisteredEvent(m->pEventSource, aProviderId, aRegistered);
}


void VirtualBox::i_onCloudProviderUninstall(const Utf8Str &aProviderId)
{
    HRESULT hrc;

    ComPtr<IEvent> pEvent;
    hrc = CreateCloudProviderUninstallEvent(pEvent.asOutParam(),
                                            m->pEventSource, aProviderId);
    if (FAILED(hrc))
        return;

    BOOL fDelivered = FALSE;
    hrc = m->pEventSource->FireEvent(pEvent, /* :timeout */ 10000, &fDelivered);
    if (FAILED(hrc))
        return;
}

void VirtualBox::i_onLanguageChanged(const Utf8Str &aLanguageId)
{
    ComPtr<IEvent> ptrEvent;
    HRESULT hrc = ::CreateLanguageChangedEvent(ptrEvent.asOutParam(), m->pEventSource, aLanguageId);
    AssertComRCReturnVoid(hrc);
    i_postEvent(new AsyncEvent(this, ptrEvent));
}

void VirtualBox::i_onProgressCreated(const Guid &aId, BOOL aCreated)
{
    ::FireProgressCreatedEvent(m->pEventSource, aId.toString(), aCreated);
}

#ifdef VBOX_WITH_UPDATE_AGENT
/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onUpdateAgentAvailable(IUpdateAgent *aAgent,
                                          const Utf8Str &aVer, UpdateChannel_T aChannel, UpdateSeverity_T aSev,
                                          const Utf8Str &aDownloadURL, const Utf8Str &aWebURL, const Utf8Str &aReleaseNotes)
{
    ::FireUpdateAgentAvailableEvent(m->pEventSource, aAgent, aVer, aChannel, aSev,
                                    aDownloadURL, aWebURL, aReleaseNotes);
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onUpdateAgentError(IUpdateAgent *aAgent, const Utf8Str &aErrMsg, LONG aRc)
{
    ::FireUpdateAgentErrorEvent(m->pEventSource, aAgent, aErrMsg, aRc);
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onUpdateAgentStateChanged(IUpdateAgent *aAgent, UpdateState_T aState)
{
    ::FireUpdateAgentStateChangedEvent(m->pEventSource, aAgent, aState);
}

/**
 *  @note Doesn't lock any object.
 */
void VirtualBox::i_onUpdateAgentSettingsChanged(IUpdateAgent *aAgent, const Utf8Str &aAttributeHint)
{
    ::FireUpdateAgentSettingsChangedEvent(m->pEventSource, aAgent, aAttributeHint);
}
#endif /* VBOX_WITH_UPDATE_AGENT */

/**
 *  @note Locks the list of other objects for reading.
 */
ComObjPtr<GuestOSType> VirtualBox::i_getUnknownOSType()
{
    ComObjPtr<GuestOSType> type;

    /* unknown type must always be the first */
    ComAssertRet(m->allGuestOSTypes.size() > 0, type);

    return m->allGuestOSTypes.front();
}

/**
 * Returns the list of opened machines (machines having VM sessions opened,
 * ignoring other sessions) and optionally the list of direct session controls.
 *
 * @param aMachines     Where to put opened machines (will be empty if none).
 * @param aControls     Where to put direct session controls (optional).
 *
 * @note The returned lists contain smart pointers. So, clear it as soon as
 * it becomes no more necessary to release instances.
 *
 * @note It can be possible that a session machine from the list has been
 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
 * when accessing unprotected data directly.
 *
 * @note Locks objects for reading.
 */
void VirtualBox::i_getOpenedMachines(SessionMachinesList &aMachines,
                                     InternalControlList *aControls /*= NULL*/)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.hrc());

    aMachines.clear();
    if (aControls)
        aControls->clear();

    AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (MachinesOList::iterator it = m->allMachines.begin();
         it != m->allMachines.end();
         ++it)
    {
        ComObjPtr<SessionMachine> sm;
        ComPtr<IInternalSessionControl> ctl;
        if ((*it)->i_isSessionOpenVM(sm, &ctl))
        {
            aMachines.push_back(sm);
            if (aControls)
                aControls->push_back(ctl);
        }
    }
}

/**
 * Gets a reference to the machine list. This is the real thing, not a copy,
 * so bad things will happen if the caller doesn't hold the necessary lock.
 *
 * @returns reference to machine list
 *
 * @note Caller must hold the VirtualBox object lock at least for reading.
 */
VirtualBox::MachinesOList &VirtualBox::i_getMachinesList(void)
{
    return m->allMachines;
}

/**
 *  Searches for a machine object with the given ID in the collection
 *  of registered machines.
 *
 * @param aId Machine UUID to look for.
 * @param fPermitInaccessible If true, inaccessible machines will be found;
 *                  if false, this will fail if the given machine is inaccessible.
 * @param aSetError If true, set errorinfo if the machine is not found.
 * @param aMachine Returned machine, if found.
 * @return
 */
HRESULT VirtualBox::i_findMachine(const Guid &aId,
                                  bool fPermitInaccessible,
                                  bool aSetError,
                                  ComObjPtr<Machine> *aMachine /* = NULL */)
{
    HRESULT hrc = VBOX_E_OBJECT_NOT_FOUND;

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    {
        AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);

        for (MachinesOList::iterator it = m->allMachines.begin();
             it != m->allMachines.end();
             ++it)
        {
            ComObjPtr<Machine> pMachine = *it;

            if (!fPermitInaccessible)
            {
                // skip inaccessible machines
                AutoCaller machCaller(pMachine);
                if (FAILED(machCaller.hrc()))
                    continue;
            }

            if (pMachine->i_getId() == aId)
            {
                hrc = S_OK;
                if (aMachine)
                    *aMachine = pMachine;
                break;
            }
        }
    }

    if (aSetError && FAILED(hrc))
        hrc = setError(hrc, tr("Could not find a registered machine with UUID {%RTuuid}"), aId.raw());

    return hrc;
}

/**
 * Searches for a machine object with the given name or location in the
 * collection of registered machines.
 *
 * @param aName Machine name or location to look for.
 * @param aSetError If true, set errorinfo if the machine is not found.
 * @param aMachine Returned machine, if found.
 * @return
 */
HRESULT VirtualBox::i_findMachineByName(const Utf8Str &aName,
                                        bool  aSetError,
                                        ComObjPtr<Machine> *aMachine /* = NULL */)
{
    HRESULT hrc = VBOX_E_OBJECT_NOT_FOUND;

    AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    for (MachinesOList::iterator it = m->allMachines.begin();
         it != m->allMachines.end();
         ++it)
    {
        ComObjPtr<Machine> &pMachine = *it;
        AutoCaller machCaller(pMachine);
        if (!machCaller.isOk())
            continue;       // we can't ask inaccessible machines for their names

        AutoReadLock machLock(pMachine COMMA_LOCKVAL_SRC_POS);
        if (pMachine->i_getName() == aName)
        {
            hrc = S_OK;
            if (aMachine)
                *aMachine = pMachine;
            break;
        }
        if (!RTPathCompare(pMachine->i_getSettingsFileFull().c_str(), aName.c_str()))
        {
            hrc = S_OK;
            if (aMachine)
                *aMachine = pMachine;
            break;
        }
    }

    if (aSetError && FAILED(hrc))
        hrc = setError(hrc, tr("Could not find a registered machine named '%s'"), aName.c_str());

    return hrc;
}

static HRESULT i_validateMachineGroupHelper(const Utf8Str &aGroup, bool fPrimary, VirtualBox *pVirtualBox)
{
    /* empty strings are invalid */
    if (aGroup.isEmpty())
        return E_INVALIDARG;
    /* the toplevel group is valid */
    if (aGroup == "/")
        return S_OK;
    /* any other strings of length 1 are invalid */
    if (aGroup.length() == 1)
        return E_INVALIDARG;
    /* must start with a slash */
    if (aGroup.c_str()[0] != '/')
        return E_INVALIDARG;
    /* must not end with a slash */
    if (aGroup.c_str()[aGroup.length() - 1] == '/')
        return E_INVALIDARG;
    /* check the group components */
    const char *pStr = aGroup.c_str() + 1;  /* first char is /, skip it */
    while (pStr)
    {
        char *pSlash = RTStrStr(pStr, "/");
        if (pSlash)
        {
            /* no empty components (or // sequences in other words) */
            if (pSlash == pStr)
                return E_INVALIDARG;
            /* check if the machine name rules are violated, because that means
             * the group components are too close to the limits. */
            Utf8Str tmp((const char *)pStr, (size_t)(pSlash - pStr));
            Utf8Str tmp2(tmp);
            sanitiseMachineFilename(tmp);
            if (tmp != tmp2)
                return E_INVALIDARG;
            if (fPrimary)
            {
                HRESULT hrc = pVirtualBox->i_findMachineByName(tmp, false /* aSetError */);
                if (SUCCEEDED(hrc))
                    return VBOX_E_VM_ERROR;
            }
            pStr = pSlash + 1;
        }
        else
        {
            /* check if the machine name rules are violated, because that means
             * the group components is too close to the limits. */
            Utf8Str tmp(pStr);
            Utf8Str tmp2(tmp);
            sanitiseMachineFilename(tmp);
            if (tmp != tmp2)
                return E_INVALIDARG;
            pStr = NULL;
        }
    }
    return S_OK;
}

/**
 * Validates a machine group.
 *
 * @param aGroup    Machine group.
 * @param fPrimary  Set if this is the primary group.
 *
 * @return S_OK or E_INVALIDARG
 */
HRESULT VirtualBox::i_validateMachineGroup(const Utf8Str &aGroup, bool fPrimary)
{
    HRESULT hrc = i_validateMachineGroupHelper(aGroup, fPrimary, this);
    if (FAILED(hrc))
    {
        if (hrc == VBOX_E_VM_ERROR)
            hrc = setError(E_INVALIDARG, tr("Machine group '%s' conflicts with a virtual machine name"), aGroup.c_str());
        else
            hrc = setError(hrc, tr("Invalid machine group '%s'"), aGroup.c_str());
    }
    return hrc;
}

/**
 * Takes a list of machine groups, and sanitizes/validates it.
 *
 * @param aMachineGroups    Array with the machine groups.
 * @param pllMachineGroups  Pointer to list of strings for the result.
 *
 * @return S_OK or E_INVALIDARG
 */
HRESULT VirtualBox::i_convertMachineGroups(const std::vector<com::Utf8Str> aMachineGroups, StringsList *pllMachineGroups)
{
    pllMachineGroups->clear();
    if (aMachineGroups.size())
    {
        for (size_t i = 0; i < aMachineGroups.size(); i++)
        {
            Utf8Str group(aMachineGroups[i]);
            if (group.length() == 0)
                group = "/";

            HRESULT hrc = i_validateMachineGroup(group, i == 0);
            if (FAILED(hrc))
                return hrc;

            /* no duplicates please */
            if (   find(pllMachineGroups->begin(), pllMachineGroups->end(), group)
                == pllMachineGroups->end())
                pllMachineGroups->push_back(group);
        }
        if (pllMachineGroups->size() == 0)
            pllMachineGroups->push_back("/");
    }
    else
        pllMachineGroups->push_back("/");

    return S_OK;
}

/**
 * Searches for a Medium object with the given ID in the list of registered
 * hard disks.
 *
 * @param aId           ID of the hard disk. Must not be empty.
 * @param aSetError     If @c true , the appropriate error info is set in case
 *                      when the hard disk is not found.
 * @param aHardDisk     Where to store the found hard disk object (can be NULL).
 *
 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
 *
 * @note Locks the media tree for reading.
 */
HRESULT VirtualBox::i_findHardDiskById(const Guid &aId,
                                       bool aSetError,
                                       ComObjPtr<Medium> *aHardDisk /*= NULL*/)
{
    AssertReturn(!aId.isZero(), E_INVALIDARG);

    // we use the hard disks map, but it is protected by the
    // hard disk _list_ lock handle
    AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    HardDiskMap::const_iterator it = m->mapHardDisks.find(aId);
    if (it != m->mapHardDisks.end())
    {
        if (aHardDisk)
            *aHardDisk = (*it).second;
        return S_OK;
    }

    if (aSetError)
        return setError(VBOX_E_OBJECT_NOT_FOUND,
                        tr("Could not find an open hard disk with UUID {%RTuuid}"),
                        aId.raw());

    return VBOX_E_OBJECT_NOT_FOUND;
}

/**
 * Searches for a Medium object with the given ID or location in the list of
 * registered hard disks. If both ID and location are specified, the first
 * object that matches either of them (not necessarily both) is returned.
 *
 * @param strLocation   Full location specification. Must not be empty.
 * @param aSetError     If @c true , the appropriate error info is set in case
 *                      when the hard disk is not found.
 * @param aHardDisk     Where to store the found hard disk object (can be NULL).
 *
 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
 *
 * @note Locks the media tree for reading.
 */
HRESULT VirtualBox::i_findHardDiskByLocation(const Utf8Str &strLocation,
                                             bool aSetError,
                                             ComObjPtr<Medium> *aHardDisk /*= NULL*/)
{
    AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);

    // we use the hard disks map, but it is protected by the
    // hard disk _list_ lock handle
    AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
         it != m->mapHardDisks.end();
         ++it)
    {
        const ComObjPtr<Medium> &pHD = (*it).second;

        AutoCaller autoCaller(pHD);
        if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
        AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);

        Utf8Str strLocationFull = pHD->i_getLocationFull();

        if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
        {
            if (aHardDisk)
                *aHardDisk = pHD;
            return S_OK;
        }
    }

    if (aSetError)
        return setError(VBOX_E_OBJECT_NOT_FOUND,
                        tr("Could not find an open hard disk with location '%s'"),
                        strLocation.c_str());

    return VBOX_E_OBJECT_NOT_FOUND;
}

/**
 * Searches for a Medium object with the given ID or location in the list of
 * registered DVD or floppy images, depending on the @a mediumType argument.
 * If both ID and file path are specified, the first object that matches either
 * of them (not necessarily both) is returned.
 *
 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
 * @param aId       ID of the image file (unused when NULL).
 * @param aLocation Full path to the image file (unused when NULL).
 * @param aSetError If @c true, the appropriate error info is set in case when
 *                  the image is not found.
 * @param aImage    Where to store the found image object (can be NULL).
 *
 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
 *
 * @note Locks the media tree for reading.
 */
HRESULT VirtualBox::i_findDVDOrFloppyImage(DeviceType_T mediumType,
                                           const Guid *aId,
                                           const Utf8Str &aLocation,
                                           bool aSetError,
                                           ComObjPtr<Medium> *aImage /* = NULL */)
{
    AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);

    Utf8Str location;
    if (!aLocation.isEmpty())
    {
        int vrc = i_calculateFullPath(aLocation, location);
        if (RT_FAILURE(vrc))
            return setError(VBOX_E_FILE_ERROR,
                            tr("Invalid image file location '%s' (%Rrc)"),
                            aLocation.c_str(),
                            vrc);
    }

    MediaOList *pMediaList;

    switch (mediumType)
    {
        case DeviceType_DVD:
            pMediaList = &m->allDVDImages;
        break;

        case DeviceType_Floppy:
            pMediaList = &m->allFloppyImages;
        break;

        default:
            return E_INVALIDARG;
    }

    AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);

    bool found = false;

    for (MediaList::const_iterator it = pMediaList->begin();
         it != pMediaList->end();
         ++it)
    {
        // no AutoCaller, registered image life time is bound to this
        Medium *pMedium = *it;
        AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
        const Utf8Str &strLocationFull = pMedium->i_getLocationFull();

        found =     (    aId
                      && pMedium->i_getId() == *aId)
                 || (    !aLocation.isEmpty()
                      && RTPathCompare(location.c_str(),
                                       strLocationFull.c_str()) == 0);
        if (found)
        {
            if (pMedium->i_getDeviceType() != mediumType)
            {
                if (mediumType == DeviceType_DVD)
                    return setError(E_INVALIDARG,
                                    tr("Cannot mount DVD medium '%s' as floppy"), strLocationFull.c_str());
                else
                    return setError(E_INVALIDARG,
                                    tr("Cannot mount floppy medium '%s' as DVD"), strLocationFull.c_str());
            }

            if (aImage)
                *aImage = pMedium;
            break;
        }
    }

    HRESULT hrc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;

    if (aSetError && !found)
    {
        if (aId)
            setError(hrc,
                     tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
                     aId->raw(),
                     m->strSettingsFilePath.c_str());
        else
            setError(hrc,
                     tr("Could not find an image file with location '%s' in the media registry ('%s')"),
                     aLocation.c_str(),
                     m->strSettingsFilePath.c_str());
    }

    return hrc;
}

/**
 * Searches for an IMedium object that represents the given UUID.
 *
 * If the UUID is empty (indicating an empty drive), this sets pMedium
 * to NULL and returns S_OK.
 *
 * If the UUID refers to a host drive of the given device type, this
 * sets pMedium to the object from the list in IHost and returns S_OK.
 *
 * If the UUID is an image file, this sets pMedium to the object that
 * findDVDOrFloppyImage() returned.
 *
 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
 *
 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
 * @param aSetError
 * @param pMedium out: IMedium object found.
 * @return
 */
HRESULT VirtualBox::i_findRemoveableMedium(DeviceType_T mediumType,
                                           const Guid &uuid,
                                           bool fRefresh,
                                           bool aSetError,
                                           ComObjPtr<Medium> &pMedium)
{
    if (uuid.isZero())
    {
        // that's easy
        pMedium.setNull();
        return S_OK;
    }
    else if (!uuid.isValid())
    {
        /* handling of case invalid GUID */
        return setError(VBOX_E_OBJECT_NOT_FOUND,
                            tr("Guid '%s' is invalid"),
                            uuid.toString().c_str());
    }

    // first search for host drive with that UUID
    HRESULT hrc = m->pHost->i_findHostDriveById(mediumType, uuid, fRefresh, pMedium);
    if (hrc == VBOX_E_OBJECT_NOT_FOUND)
                // then search for an image with that UUID
        hrc = i_findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, aSetError, &pMedium);

    return hrc;
}

/* Look for a GuestOSType object */
HRESULT VirtualBox::i_findGuestOSType(const Utf8Str &strOSType,
                                      ComObjPtr<GuestOSType> &guestOSType)
{
    guestOSType.setNull();

    AssertMsg(m->allGuestOSTypes.size() != 0,
              ("Guest OS types array must be filled"));

    AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
         it != m->allGuestOSTypes.end();
         ++it)
    {
        const Utf8Str &typeId = (*it)->i_id();
        AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
        if (strOSType.compare(typeId, Utf8Str::CaseInsensitive) == 0)
        {
            guestOSType = *it;
            return S_OK;
        }
    }

    return setError(VBOX_E_OBJECT_NOT_FOUND,
                    tr("'%s' is not a valid Guest OS type"),
                    strOSType.c_str());
}

/**
 * Returns the constant pseudo-machine UUID that is used to identify the
 * global media registry.
 *
 * Starting with VirtualBox 4.0 each medium remembers in its instance data
 * in which media registry it is saved (if any): this can either be a machine
 * UUID, if it's in a per-machine media registry, or this global ID.
 *
 * This UUID is only used to identify the VirtualBox object while VirtualBox
 * is running. It is a compile-time constant and not saved anywhere.
 *
 * @return
 */
const Guid& VirtualBox::i_getGlobalRegistryId() const
{
    return m->uuidMediaRegistry;
}

const ComObjPtr<Host>& VirtualBox::i_host() const
{
    return m->pHost;
}

SystemProperties* VirtualBox::i_getSystemProperties() const
{
    return m->pSystemProperties;
}

CloudProviderManager *VirtualBox::i_getCloudProviderManager() const
{
    return m->pCloudProviderManager;
}

#ifdef VBOX_WITH_EXTPACK
/**
 * Getter that SystemProperties and others can use to talk to the extension
 * pack manager.
 */
ExtPackManager* VirtualBox::i_getExtPackManager() const
{
    return m->ptrExtPackManager;
}
#endif

/**
 * Getter that machines can talk to the autostart database.
 */
AutostartDb* VirtualBox::i_getAutostartDb() const
{
    return m->pAutostartDb;
}

#ifdef VBOX_WITH_RESOURCE_USAGE_API
const ComObjPtr<PerformanceCollector>& VirtualBox::i_performanceCollector() const
{
    return m->pPerformanceCollector;
}
#endif /* VBOX_WITH_RESOURCE_USAGE_API */

/**
 * Returns the default machine folder from the system properties
 * with proper locking.
 */
void VirtualBox::i_getDefaultMachineFolder(Utf8Str &str) const
{
    AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
    str = m->pSystemProperties->m->strDefaultMachineFolder;
}

/**
 * Returns the default hard disk format from the system properties
 * with proper locking.
 */
void VirtualBox::i_getDefaultHardDiskFormat(Utf8Str &str) const
{
    AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
    str = m->pSystemProperties->m->strDefaultHardDiskFormat;
}

const Utf8Str& VirtualBox::i_homeDir() const
{
    return m->strHomeDir;
}

/**
 * Calculates the absolute path of the given path taking the VirtualBox home
 * directory as the current directory.
 *
 * @param  strPath  Path to calculate the absolute path for.
 * @param  aResult  Where to put the result (used only on success, can be the
 *                  same Utf8Str instance as passed in @a aPath).
 * @return IPRT result.
 *
 * @note Doesn't lock any object.
 */
int VirtualBox::i_calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
{
    AutoCaller autoCaller(this);
    AssertComRCReturn(autoCaller.hrc(), VERR_GENERAL_FAILURE);

    /* no need to lock since strHomeDir is const */

    char szFolder[RTPATH_MAX];
    size_t cbFolder = sizeof(szFolder);
    int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
                          strPath.c_str(),
                          RTPATH_STR_F_STYLE_HOST,
                          szFolder,
                          &cbFolder);
    if (RT_SUCCESS(vrc))
        aResult = szFolder;

    return vrc;
}

/**
 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
 * if it is a subdirectory thereof, or simply copying it otherwise.
 *
 * @param strSource Path to evalue and copy.
 * @param strTarget Buffer to receive target path.
 */
void VirtualBox::i_copyPathRelativeToConfig(const Utf8Str &strSource,
                                            Utf8Str &strTarget)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnVoid(autoCaller.hrc());

    // no need to lock since mHomeDir is const

    // use strTarget as a temporary buffer to hold the machine settings dir
    strTarget = m->strHomeDir;
    if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
        // is relative: then append what's left
        strTarget.append(strSource.c_str() + strTarget.length());     // include '/'
    else
        // is not relative: then overwrite
        strTarget = strSource;
}

// private methods
/////////////////////////////////////////////////////////////////////////////

/**
 * Checks if there is a hard disk, DVD or floppy image with the given ID or
 * location already registered.
 *
 * On return, sets @a aConflict to the string describing the conflicting medium,
 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
 * either case. A failure is unexpected.
 *
 * @param aId           UUID to check.
 * @param aLocation     Location to check.
 * @param aConflict     Where to return parameters of the conflicting medium.
 * @param ppMedium      Medium reference in case this is simply a duplicate.
 *
 * @note Locks the media tree and media objects for reading.
 */
HRESULT VirtualBox::i_checkMediaForConflicts(const Guid &aId,
                                             const Utf8Str &aLocation,
                                             Utf8Str &aConflict,
                                             ComObjPtr<Medium> *ppMedium)
{
    AssertReturn(!aId.isZero() && !aLocation.isEmpty(), E_FAIL);
    AssertReturn(ppMedium, E_INVALIDARG);

    aConflict.setNull();
    ppMedium->setNull();

    AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);

    HRESULT hrc = S_OK;

    ComObjPtr<Medium> pMediumFound;
    const char *pcszType = NULL;

    if (aId.isValid() && !aId.isZero())
        hrc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
    if (FAILED(hrc) && !aLocation.isEmpty())
        hrc = i_findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
    if (SUCCEEDED(hrc))
        pcszType = tr("hard disk");

    if (!pcszType)
    {
        hrc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
        if (SUCCEEDED(hrc))
            pcszType = tr("CD/DVD image");
    }

    if (!pcszType)
    {
        hrc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
        if (SUCCEEDED(hrc))
            pcszType = tr("floppy image");
    }

    if (pcszType && pMediumFound)
    {
        /* Note: no AutoCaller since bound to this */
        AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);

        Utf8Str strLocFound = pMediumFound->i_getLocationFull();
        Guid idFound = pMediumFound->i_getId();

        if (    (RTPathCompare(strLocFound.c_str(), aLocation.c_str()) == 0)
             && (idFound == aId)
           )
            *ppMedium = pMediumFound;

        aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
                               pcszType,
                               strLocFound.c_str(),
                               idFound.raw());
    }

    return S_OK;
}

/**
 * Checks whether the given UUID is already in use by one medium for the
 * given device type.
 *
 * @returns true if the UUID is already in use
 *          fale otherwise
 * @param   aId           The UUID to check.
 * @param   deviceType    The device type the UUID is going to be checked for
 *                        conflicts.
 */
bool VirtualBox::i_isMediaUuidInUse(const Guid &aId, DeviceType_T deviceType)
{
    /* A zero UUID is invalid here, always claim that it is already used. */
    AssertReturn(!aId.isZero(), true);

    AutoReadLock alock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);

    bool fInUse = false;

    ComObjPtr<Medium> pMediumFound;

    HRESULT hrc;
    switch (deviceType)
    {
        case DeviceType_HardDisk:
            hrc = i_findHardDiskById(aId, false /* aSetError */, &pMediumFound);
            break;
        case DeviceType_DVD:
            hrc = i_findDVDOrFloppyImage(DeviceType_DVD, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
            break;
        case DeviceType_Floppy:
            hrc = i_findDVDOrFloppyImage(DeviceType_Floppy, &aId, Utf8Str::Empty, false /* aSetError */, &pMediumFound);
            break;
        default:
            AssertMsgFailed(("Invalid device type %d\n", deviceType));
            hrc = S_OK;
            break;
    }

    if (SUCCEEDED(hrc) && pMediumFound)
        fInUse = true;

    return fInUse;
}

/**
 * Called from Machine::prepareSaveSettings() when it has detected
 * that a machine has been renamed. Such renames will require
 * updating the global media registry during the
 * VirtualBox::i_saveSettings() that follows later.
*
 * When a machine is renamed, there may well be media (in particular,
 * diff images for snapshots) in the global registry that will need
 * to have their paths updated. Before 3.2, Machine::saveSettings
 * used to call VirtualBox::i_saveSettings implicitly, which was both
 * unintuitive and caused locking order problems. Now, we remember
 * such pending name changes with this method so that
 * VirtualBox::i_saveSettings() can process them properly.
 */
void VirtualBox::i_rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
                                                     const Utf8Str &strNewConfigDir)
{
    AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);

    Data::PendingMachineRename pmr;
    pmr.strConfigDirOld = strOldConfigDir;
    pmr.strConfigDirNew = strNewConfigDir;
    m->llPendingMachineRenames.push_back(pmr);
}

static DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);

class SaveMediaRegistriesDesc : public ThreadTask
{

public:
    SaveMediaRegistriesDesc()
    {
        m_strTaskName = "SaveMediaReg";
    }
    virtual ~SaveMediaRegistriesDesc(void) { }

private:
    void handler()
    {
        try
        {
            fntSaveMediaRegistries(this);
        }
        catch(...)
        {
            LogRel(("Exception in the function fntSaveMediaRegistries()\n"));
        }
    }

    MediaList llMedia;
    ComObjPtr<VirtualBox> pVirtualBox;

    friend DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser);
    friend void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
                                                const Guid &uuidRegistry,
                                                const Utf8Str &strMachineFolder);
};

DECLCALLBACK(int) fntSaveMediaRegistries(void *pvUser)
{
    SaveMediaRegistriesDesc *pDesc = (SaveMediaRegistriesDesc *)pvUser;
    if (!pDesc)
    {
        LogRelFunc(("Thread for saving media registries lacks parameters\n"));
        return VERR_INVALID_PARAMETER;
    }

    for (MediaList::const_iterator it = pDesc->llMedia.begin();
         it != pDesc->llMedia.end();
         ++it)
    {
        Medium *pMedium = *it;
        pMedium->i_markRegistriesModified();
    }

    pDesc->pVirtualBox->i_saveModifiedRegistries();

    pDesc->llMedia.clear();
    pDesc->pVirtualBox.setNull();

    return VINF_SUCCESS;
}

/**
 * Goes through all known media (hard disks, floppies and DVDs) and saves
 * those into the given settings::MediaRegistry structures whose registry
 * ID match the given UUID.
 *
 * Before actually writing to the structures, all media paths (not just the
 * ones for the given registry) are updated if machines have been renamed
 * since the last call.
 *
 * This gets called from two contexts:
 *
 *  -- VirtualBox::i_saveSettings() with the UUID of the global registry
 *     (VirtualBox::Data.uuidRegistry); this will save those media
 *     which had been loaded from the global registry or have been
 *     attached to a "legacy" machine which can't save its own registry;
 *
 *  -- Machine::saveSettings() with the UUID of a machine, if a medium
 *     has been attached to a machine created with VirtualBox 4.0 or later.
 *
 * Media which have only been temporarily opened without having been
 * attached to a machine have a NULL registry UUID and therefore don't
 * get saved.
 *
 * This locks the media tree. Throws HRESULT on errors!
 *
 * @param mediaRegistry Settings structure to fill.
 * @param uuidRegistry The UUID of the media registry; either a machine UUID
 *        (if machine registry) or the UUID of the global registry.
 * @param strMachineFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
 */
void VirtualBox::i_saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
                                     const Guid &uuidRegistry,
                                     const Utf8Str &strMachineFolder)
{
    // lock all media for the following; use a write lock because we're
    // modifying the PendingMachineRenamesList, which is protected by this
    AutoWriteLock mediaLock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);

    // if a machine was renamed, then we'll need to refresh media paths
    if (m->llPendingMachineRenames.size())
    {
        // make a single list from the three media lists so we don't need three loops
        MediaList llAllMedia;
        // with hard disks, we must use the map, not the list, because the list only has base images
        for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
            llAllMedia.push_back(it->second);
        for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
            llAllMedia.push_back(*it);
        for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
            llAllMedia.push_back(*it);

        SaveMediaRegistriesDesc *pDesc = new SaveMediaRegistriesDesc();
        for (MediaList::iterator it = llAllMedia.begin();
             it != llAllMedia.end();
             ++it)
        {
            Medium *pMedium = *it;
            for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
                 it2 != m->llPendingMachineRenames.end();
                 ++it2)
            {
                const Data::PendingMachineRename &pmr = *it2;
                HRESULT hrc = pMedium->i_updatePath(pmr.strConfigDirOld, pmr.strConfigDirNew);
                if (SUCCEEDED(hrc))
                {
                    // Remember which medium objects has been changed,
                    // to trigger saving their registries later.
                    pDesc->llMedia.push_back(pMedium);
                } else if (hrc == VBOX_E_FILE_ERROR)
                    /* nothing */;
                else
                    AssertComRC(hrc);
            }
        }
        // done, don't do it again until we have more machine renames
        m->llPendingMachineRenames.clear();

        if (pDesc->llMedia.size())
        {
            // Handle the media registry saving in a separate thread, to
            // avoid giant locking problems and passing up the list many
            // levels up to whoever triggered saveSettings, as there are
            // lots of places which would need to handle saving more settings.
            pDesc->pVirtualBox = this;

            //the function createThread() takes ownership of pDesc
            //so there is no need to use delete operator for pDesc
            //after calling this function
            HRESULT hrc = pDesc->createThread();
            pDesc = NULL;

            if (FAILED(hrc))
            {
                // failure means that settings aren't saved, but there isn't
                // much we can do besides avoiding memory leaks
                LogRelFunc(("Failed to create thread for saving media registries (%Rhr)\n", hrc));
            }
        }
        else
            delete pDesc;
    }

    struct {
        MediaOList &llSource;
        settings::MediaList &llTarget;
    } s[] =
    {
        // hard disks
        { m->allHardDisks, mediaRegistry.llHardDisks },
        // CD/DVD images
        { m->allDVDImages, mediaRegistry.llDvdImages },
        // floppy images
        { m->allFloppyImages, mediaRegistry.llFloppyImages }
    };

    for (size_t i = 0; i < RT_ELEMENTS(s); ++i)
    {
        MediaOList &llSource = s[i].llSource;
        settings::MediaList &llTarget = s[i].llTarget;
        llTarget.clear();
        for (MediaList::const_iterator it = llSource.begin();
             it != llSource.end();
             ++it)
        {
            Medium *pMedium = *it;
            AutoCaller autoCaller(pMedium);
            if (FAILED(autoCaller.hrc())) throw autoCaller.hrc();
            AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);

            if (pMedium->i_isInRegistry(uuidRegistry))
            {
                llTarget.push_back(settings::Medium::Empty);
                HRESULT hrc = pMedium->i_saveSettings(llTarget.back(), strMachineFolder); // this recurses into child hard disks
                if (FAILED(hrc))
                {
                    llTarget.pop_back();
                    throw hrc;
                }
            }
        }
    }
}

/**
 *  Helper function which actually writes out VirtualBox.xml, the main configuration file.
 *  Gets called from the public VirtualBox::SaveSettings() as well as from various other
 *  places internally when settings need saving.
 *
 *  @note Caller must have locked the VirtualBox object for writing and must not hold any
 *    other locks since this locks all kinds of member objects and trees temporarily,
 *    which could cause conflicts.
 */
HRESULT VirtualBox::i_saveSettings()
{
    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
    AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);

    i_unmarkRegistryModified(i_getGlobalRegistryId());

    HRESULT hrc = S_OK;

    try
    {
        // machines
        m->pMainConfigFile->llMachines.clear();
        {
            AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
            for (MachinesOList::iterator it = m->allMachines.begin();
                 it != m->allMachines.end();
                 ++it)
            {
                Machine *pMachine = *it;
                // save actual machine registry entry
                settings::MachineRegistryEntry mre;
                hrc = pMachine->i_saveRegistryEntry(mre);
                m->pMainConfigFile->llMachines.push_back(mre);
            }
        }

        i_saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
                            m->uuidMediaRegistry,         // global media registry ID
                            Utf8Str::Empty);              // strMachineFolder

        m->pMainConfigFile->llDhcpServers.clear();
        {
            AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
            for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
                 it != m->allDHCPServers.end();
                 ++it)
            {
                settings::DHCPServer d;
                hrc = (*it)->i_saveSettings(d);
                if (FAILED(hrc)) throw hrc;
                m->pMainConfigFile->llDhcpServers.push_back(d);
            }
        }

#ifdef VBOX_WITH_NAT_SERVICE
        /* Saving NAT Network configuration */
        m->pMainConfigFile->llNATNetworks.clear();
        {
            AutoReadLock natNetworkLock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
            for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
                 it != m->allNATNetworks.end();
                 ++it)
            {
                settings::NATNetwork n;
                hrc = (*it)->i_saveSettings(n);
                if (FAILED(hrc)) throw hrc;
                m->pMainConfigFile->llNATNetworks.push_back(n);
            }
        }
#endif

#ifdef VBOX_WITH_VMNET
        m->pMainConfigFile->llHostOnlyNetworks.clear();
        {
            AutoReadLock hostOnlyNetworkLock(m->allHostOnlyNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
            for (HostOnlyNetworksOList::const_iterator it = m->allHostOnlyNetworks.begin();
                 it != m->allHostOnlyNetworks.end();
                 ++it)
            {
                settings::HostOnlyNetwork n;
                hrc = (*it)->i_saveSettings(n);
                if (FAILED(hrc)) throw hrc;
                m->pMainConfigFile->llHostOnlyNetworks.push_back(n);
            }
        }
#endif /* VBOX_WITH_VMNET */

#ifdef VBOX_WITH_CLOUD_NET
        m->pMainConfigFile->llCloudNetworks.clear();
        {
            AutoReadLock cloudNetworkLock(m->allCloudNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
            for (CloudNetworksOList::const_iterator it = m->allCloudNetworks.begin();
                 it != m->allCloudNetworks.end();
                 ++it)
            {
                settings::CloudNetwork n;
                hrc = (*it)->i_saveSettings(n);
                if (FAILED(hrc)) throw hrc;
                m->pMainConfigFile->llCloudNetworks.push_back(n);
            }
        }
#endif /* VBOX_WITH_CLOUD_NET */
        // leave extra data alone, it's still in the config file

        // host data (USB filters)
        hrc = m->pHost->i_saveSettings(m->pMainConfigFile->host);
        if (FAILED(hrc)) throw hrc;

        hrc = m->pSystemProperties->i_saveSettings(m->pMainConfigFile->systemProperties);
        if (FAILED(hrc)) throw hrc;

        // and write out the XML, still under the lock
        m->pMainConfigFile->write(m->strSettingsFilePath);
    }
    catch (HRESULT hrcXcpt)
    {
        /* we assume that error info is set by the thrower */
        hrc = hrcXcpt;
    }
    catch (...)
    {
        hrc = VirtualBoxBase::handleUnexpectedExceptions(this, RT_SRC_POS);
    }

    return hrc;
}

/**
 *  Helper to register the machine.
 *
 *  When called during VirtualBox startup, adds the given machine to the
 *  collection of registered machines. Otherwise tries to mark the machine
 *  as registered, and, if succeeded, adds it to the collection and
 *  saves global settings.
 *
 *  @note The caller must have added itself as a caller of the @a aMachine
 *  object if calls this method not on VirtualBox startup.
 *
 *  @param aMachine     machine to register
 *
 *  @note Locks objects!
 */
HRESULT VirtualBox::i_registerMachine(Machine *aMachine)
{
    ComAssertRet(aMachine, E_INVALIDARG);

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

    HRESULT hrc = S_OK;

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    {
        ComObjPtr<Machine> pMachine;
        hrc = i_findMachine(aMachine->i_getId(),
                            true /* fPermitInaccessible */,
                            false /* aDoSetError */,
                            &pMachine);
        if (SUCCEEDED(hrc))
        {
            /* sanity */
            AutoLimitedCaller machCaller(pMachine);
            AssertComRC(machCaller.hrc());

            return setError(E_INVALIDARG,
                            tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
                            aMachine->i_getId().raw(),
                            pMachine->i_getSettingsFileFull().c_str());
        }

        ComAssertRet(hrc == VBOX_E_OBJECT_NOT_FOUND, hrc);
        hrc = S_OK;
    }

    if (getObjectState().getState() != ObjectState::InInit)
    {
        hrc = aMachine->i_prepareRegister();
        if (FAILED(hrc)) return hrc;
    }

    /* add to the collection of registered machines */
    m->allMachines.addChild(aMachine);

    if (getObjectState().getState() != ObjectState::InInit)
        hrc = i_saveSettings();

    return hrc;
}

/**
 * Remembers the given medium object by storing it in either the global
 * medium registry or a machine one.
 *
 * @note Caller must hold the media tree lock for writing; in addition, this
 * locks @a pMedium for reading
 *
 * @param pMedium   Medium object to remember.
 * @param ppMedium  Actually stored medium object. Can be different if due
 *                  to an unavoidable race there was a duplicate Medium object
 *                  created.
 * @param mediaTreeLock Reference to the AutoWriteLock holding the media tree
 *                  lock, necessary to release it in the right spot.
 * @param fCalledFromMediumInit Flag whether this is called from Medium::init().
 * @return
 */
HRESULT VirtualBox::i_registerMedium(const ComObjPtr<Medium> &pMedium,
                                     ComObjPtr<Medium> *ppMedium,
                                     AutoWriteLock &mediaTreeLock,
                                     bool fCalledFromMediumInit)
{
    AssertReturn(pMedium != NULL, E_INVALIDARG);
    AssertReturn(ppMedium != NULL, E_INVALIDARG);

    // caller must hold the media tree write lock
    Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller mediumCaller(pMedium);
    AssertComRCReturnRC(mediumCaller.hrc());

    bool fAddToGlobalRegistry = false;
    const char *pszDevType = NULL;
    Guid regId;
    ObjectsList<Medium> *pall = NULL;
    DeviceType_T devType;
    {
        AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
        devType = pMedium->i_getDeviceType();

        if (!pMedium->i_getFirstRegistryMachineId(regId))
            fAddToGlobalRegistry = true;
    }
    switch (devType)
    {
        case DeviceType_HardDisk:
            pall = &m->allHardDisks;
            pszDevType = tr("hard disk");
            break;
        case DeviceType_DVD:
            pszDevType = tr("DVD image");
            pall = &m->allDVDImages;
            break;
        case DeviceType_Floppy:
            pszDevType = tr("floppy image");
            pall = &m->allFloppyImages;
            break;
        default:
            AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
    }

    Guid id;
    Utf8Str strLocationFull;
    ComObjPtr<Medium> pParent;
    {
        AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
        id = pMedium->i_getId();
        strLocationFull = pMedium->i_getLocationFull();
        pParent = pMedium->i_getParent();

        /*
         * If a separate thread has called Medium::close() for this medium at the same
         * time as this i_registerMedium() call then there is a window of opportunity in
         * Medium::i_close() where the media tree lock is dropped before calling
         * Medium::uninit() (which reacquires the lock) that we can end up here attempting
         * to register a medium which is in the process of being closed.  In addition, if
         * this is a differencing medium and Medium::close() is in progress for one its
         * parent media then we are similarly operating on a media registry in flux.  In
         * either case registering a medium just before calling Medium::uninit() will
         * lead to an inconsistent media registry so bail out here since Medium::close()
         * got to this medium (or one of its parents) first.
         */
        if (devType == DeviceType_HardDisk)
        {
            ComObjPtr<Medium> pTmpMedium = pMedium;
            while (pTmpMedium.isNotNull())
            {
                AutoCaller mediumAC(pTmpMedium);
                if (FAILED(mediumAC.hrc())) return mediumAC.hrc();
                AutoReadLock mlock(pTmpMedium COMMA_LOCKVAL_SRC_POS);

                if (pTmpMedium->i_isClosing())
                    return setError(E_INVALIDARG,
                                    tr("Cannot register %s '%s' {%RTuuid} because it is in the process of being closed"),
                                    pszDevType,
                                    pTmpMedium->i_getLocationFull().c_str(),
                                    pTmpMedium->i_getId().raw());

                pTmpMedium = pTmpMedium->i_getParent();
            }
        }
    }

    HRESULT hrc;

    Utf8Str strConflict;
    ComObjPtr<Medium> pDupMedium;
    hrc = i_checkMediaForConflicts(id, strLocationFull, strConflict, &pDupMedium);
    if (FAILED(hrc)) return hrc;

    if (pDupMedium.isNull())
    {
        if (strConflict.length())
            return setError(E_INVALIDARG,
                            tr("Cannot register the %s '%s' {%RTuuid} because a %s already exists"),
                            pszDevType,
                            strLocationFull.c_str(),
                            id.raw(),
                            strConflict.c_str(),
                            m->strSettingsFilePath.c_str());

        // add to the collection if it is a base medium
        if (pParent.isNull())
            pall->getList().push_back(pMedium);

        // store all hard disks (even differencing images) in the map
        if (devType == DeviceType_HardDisk)
            m->mapHardDisks[id] = pMedium;
    }

    /*
     * If we have been called from Medium::initFromSettings() then the Medium object's
     * AutoCaller status will be 'InInit' which means that when making the assigment to
     * ppMedium below the Medium object will not call Medium::uninit().  By excluding
     * this code path from releasing and reacquiring the media tree lock we avoid a
     * potential deadlock with other threads which may be operating on the
     * disks/DVDs/floppies in the VM's media registry at the same time such as
     * Machine::unregister().
     */
    if (!fCalledFromMediumInit)
    {
        // pMedium may be the last reference to the Medium object, and the
        // caller may have specified the same ComObjPtr as the output parameter.
        // In this case the assignment will uninit the object, and we must not
        // have a caller pending.
        mediumCaller.release();
        // release media tree lock, must not be held at uninit time.
        mediaTreeLock.release();
        // must not hold the media tree write lock any more
        Assert(!i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
    }

    *ppMedium = pDupMedium.isNull() ? pMedium : pDupMedium;

    if (fAddToGlobalRegistry)
    {
        AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
        if (  fCalledFromMediumInit
            ? (*ppMedium)->i_addRegistryNoCallerCheck(m->uuidMediaRegistry)
            : (*ppMedium)->i_addRegistry(m->uuidMediaRegistry))
            i_markRegistryModified(m->uuidMediaRegistry);
    }

    // Restore the initial lock state, so that no unexpected lock changes are
    // done by this method, which would need adjustments everywhere.
    if (!fCalledFromMediumInit)
        mediaTreeLock.acquire();

    return hrc;
}

/**
 * Removes the given medium from the respective registry.
 *
 * @param pMedium    Hard disk object to remove.
 *
 * @note Caller must hold the media tree lock for writing; in addition, this locks @a pMedium for reading
 */
HRESULT VirtualBox::i_unregisterMedium(Medium *pMedium)
{
    AssertReturn(pMedium != NULL, E_INVALIDARG);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller mediumCaller(pMedium);
    AssertComRCReturnRC(mediumCaller.hrc());

    // caller must hold the media tree write lock
    Assert(i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());

    Guid id;
    ComObjPtr<Medium> pParent;
    DeviceType_T devType;
    {
        AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
        id = pMedium->i_getId();
        pParent = pMedium->i_getParent();
        devType = pMedium->i_getDeviceType();
    }

    ObjectsList<Medium> *pall = NULL;
    switch (devType)
    {
        case DeviceType_HardDisk:
            pall = &m->allHardDisks;
            break;
        case DeviceType_DVD:
            pall = &m->allDVDImages;
            break;
        case DeviceType_Floppy:
            pall = &m->allFloppyImages;
            break;
        default:
            AssertMsgFailedReturn(("invalid device type %d", devType), E_INVALIDARG);
    }

    // remove from the collection if it is a base medium
    if (pParent.isNull())
        pall->getList().remove(pMedium);

    // remove all hard disks (even differencing images) from map
    if (devType == DeviceType_HardDisk)
    {
        size_t cnt = m->mapHardDisks.erase(id);
        Assert(cnt == 1);
        NOREF(cnt);
    }

    return S_OK;
}

/**
 * Unregisters all Medium objects which belong to the given machine registry.
 * Gets called from Machine::uninit() just before the machine object dies
 * and must only be called with a machine UUID as the registry ID.
 *
 * Locks the media tree.
 *
 * @param uuidMachine Medium registry ID (always a machine UUID)
 * @return
 */
HRESULT VirtualBox::i_unregisterMachineMedia(const Guid &uuidMachine)
{
    Assert(!uuidMachine.isZero() && uuidMachine.isValid());

    LogFlowFuncEnter();

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    MediaList llMedia2Close;

    {
        AutoWriteLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);

        for (MediaOList::iterator it = m->allHardDisks.getList().begin();
             it != m->allHardDisks.getList().end();
             ++it)
        {
            ComObjPtr<Medium> pMedium = *it;
            AutoCaller medCaller(pMedium);
            if (FAILED(medCaller.hrc())) return medCaller.hrc();
            AutoReadLock medlock(pMedium COMMA_LOCKVAL_SRC_POS);
            Log(("Looking at medium %RTuuid\n", pMedium->i_getId().raw()));

            /* If the medium is still in the registry then either some code is
             * seriously buggy (unregistering a VM removes it automatically),
             * or the reference to a Machine object is destroyed without ever
             * being registered. The second condition checks if a medium is
             * in no registry, which indicates (set by unregistering) that a
             * medium is not used by any other VM and thus can be closed. */
            Guid dummy;
            if (   pMedium->i_isInRegistry(uuidMachine)
                || !pMedium->i_getFirstRegistryMachineId(dummy))
            {
                /* Collect all medium objects into llMedia2Close,
                 * in right order for closing. */
                MediaList llMediaTodo;
                llMediaTodo.push_back(pMedium);

                while (llMediaTodo.size() > 0)
                {
                    ComObjPtr<Medium> pCurrent = llMediaTodo.front();
                    llMediaTodo.pop_front();

                    /* Add to front, order must be children then parent. */
                    Log(("Pushing medium %RTuuid (front)\n", pCurrent->i_getId().raw()));
                    llMedia2Close.push_front(pCurrent);

                    /* process all children */
                    MediaList::const_iterator itBegin = pCurrent->i_getChildren().begin();
                    MediaList::const_iterator itEnd = pCurrent->i_getChildren().end();
                    for (MediaList::const_iterator it2 = itBegin; it2 != itEnd; ++it2)
                        llMediaTodo.push_back(*it2);
                }
            }
        }
    }

    for (MediaList::iterator it = llMedia2Close.begin();
         it != llMedia2Close.end();
         ++it)
    {
        ComObjPtr<Medium> pMedium = *it;
        Log(("Closing medium %RTuuid\n", pMedium->i_getId().raw()));
        AutoCaller mac(pMedium);
        HRESULT hrc = pMedium->i_close(mac);
        if (FAILED(hrc))
            return hrc;
    }

    LogFlowFuncLeave();

    return S_OK;
}

/**
 * Removes the given machine object from the internal list of registered machines.
 * Called from Machine::Unregister().
 * @param pMachine
 * @param aCleanupMode  How to handle medium attachments. For
 *      CleanupMode_UnregisterOnly the associated medium objects will be
 *      closed when the Machine object is uninitialized, otherwise they will
 *      go to the global registry if no better registry is found.
 * @param id  UUID of the machine. Must be passed by caller because machine may be dead by this time.
 * @return
 */
HRESULT VirtualBox::i_unregisterMachine(Machine *pMachine,
                                        CleanupMode_T aCleanupMode,
                                        const Guid &id)
{
    // remove from the collection of registered machines
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
    m->allMachines.removeChild(pMachine);
    // save the global registry
    HRESULT hrc = i_saveSettings();
    alock.release();

    /*
     * Now go over all known media and checks if they were registered in the
     * media registry of the given machine. Each such medium is then moved to
     * a different media registry to make sure it doesn't get lost since its
     * media registry is about to go away.
     *
     * This fixes the following use case: Image A.vdi of machine A is also used
     * by machine B, but registered in the media registry of machine A. If machine
     * A is deleted, A.vdi must be moved to the registry of B, or else B will
     * become inaccessible.
     */
    {
        AutoReadLock tlock(i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
        // iterate over the list of *base* images
        for (MediaOList::iterator it = m->allHardDisks.getList().begin();
             it != m->allHardDisks.getList().end();
             ++it)
        {
            ComObjPtr<Medium> &pMedium = *it;
            AutoCaller medCaller(pMedium);
            if (FAILED(medCaller.hrc())) return medCaller.hrc();
            AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);

            if (pMedium->i_removeRegistryAll(id))
            {
                // machine ID was found in base medium's registry list:
                // move this base image and all its children to another registry then
                // 1) first, find a better registry to add things to
                const Guid *puuidBetter = pMedium->i_getAnyMachineBackref(id);
                if (puuidBetter)
                {
                    // 2) better registry found: then use that
                    pMedium->i_addRegistryAll(*puuidBetter);
                    // 3) and make sure the registry is saved below
                    mlock.release();
                    tlock.release();
                    i_markRegistryModified(*puuidBetter);
                    tlock.acquire();
                    mlock.acquire();
                }
                else if (aCleanupMode != CleanupMode_UnregisterOnly)
                {
                    pMedium->i_addRegistryAll(i_getGlobalRegistryId());
                    mlock.release();
                    tlock.release();
                    i_markRegistryModified(i_getGlobalRegistryId());
                    tlock.acquire();
                    mlock.acquire();
                }
            }
        }
    }

    i_saveModifiedRegistries();

    /* fire an event */
    i_onMachineRegistered(id, FALSE);

    return hrc;
}

/**
 * Marks the registry for @a uuid as modified, so that it's saved in a later
 * call to saveModifiedRegistries().
 *
 * @param uuid
 */
void VirtualBox::i_markRegistryModified(const Guid &uuid)
{
    if (uuid == i_getGlobalRegistryId())
        ASMAtomicIncU64(&m->uRegistryNeedsSaving);
    else
    {
        ComObjPtr<Machine> pMachine;
        HRESULT hrc = i_findMachine(uuid, false /* fPermitInaccessible */, false /* aSetError */, &pMachine);
        if (SUCCEEDED(hrc))
        {
            AutoCaller machineCaller(pMachine);
            if (SUCCEEDED(machineCaller.hrc()) && pMachine->i_isAccessible())
                ASMAtomicIncU64(&pMachine->uRegistryNeedsSaving);
        }
    }
}

/**
 * Marks the registry for @a uuid as unmodified, so that it's not saved in
 * a later call to saveModifiedRegistries().
 *
 * @param uuid
 */
void VirtualBox::i_unmarkRegistryModified(const Guid &uuid)
{
    uint64_t uOld;
    if (uuid == i_getGlobalRegistryId())
    {
        for (;;)
        {
            uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
            if (!uOld)
                break;
            if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
                break;
            ASMNopPause();
        }
    }
    else
    {
        ComObjPtr<Machine> pMachine;
        HRESULT hrc = i_findMachine(uuid, false /* fPermitInaccessible */, false /* aSetError */, &pMachine);
        if (SUCCEEDED(hrc))
        {
            AutoCaller machineCaller(pMachine);
            if (SUCCEEDED(machineCaller.hrc()))
            {
                for (;;)
                {
                    uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
                    if (!uOld)
                        break;
                    if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
                        break;
                    ASMNopPause();
                }
            }
        }
    }
}

/**
 * Saves all settings files according to the modified flags in the Machine
 * objects and in the VirtualBox object.
 *
 * This locks machines and the VirtualBox object as necessary, so better not
 * hold any locks before calling this.
 */
void VirtualBox::i_saveModifiedRegistries()
{
    HRESULT hrc = S_OK;
    bool fNeedsGlobalSettings = false;
    uint64_t uOld;

    {
        AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
        for (MachinesOList::iterator it = m->allMachines.begin();
             it != m->allMachines.end();
             ++it)
        {
            const ComObjPtr<Machine> &pMachine = *it;

            for (;;)
            {
                uOld = ASMAtomicReadU64(&pMachine->uRegistryNeedsSaving);
                if (!uOld)
                    break;
                if (ASMAtomicCmpXchgU64(&pMachine->uRegistryNeedsSaving, 0, uOld))
                    break;
                ASMNopPause();
            }
            if (uOld)
            {
                AutoCaller autoCaller(pMachine);
                if (FAILED(autoCaller.hrc()))
                    continue;
                /* object is already dead, no point in saving settings */
                if (getObjectState().getState() != ObjectState::Ready)
                    continue;
                AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
                hrc = pMachine->i_saveSettings(&fNeedsGlobalSettings, mlock,
                                               Machine::SaveS_Force);           // caller said save, so stop arguing
            }
        }
    }

    for (;;)
    {
        uOld = ASMAtomicReadU64(&m->uRegistryNeedsSaving);
        if (!uOld)
            break;
        if (ASMAtomicCmpXchgU64(&m->uRegistryNeedsSaving, 0, uOld))
            break;
        ASMNopPause();
    }
    if (uOld || fNeedsGlobalSettings)
    {
        AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
    }
    NOREF(hrc); /* XXX */
}


/* static */
const com::Utf8Str &VirtualBox::i_getVersionNormalized()
{
    return sVersionNormalized;
}

/**
 * Checks if the path to the specified file exists, according to the path
 * information present in the file name. Optionally the path is created.
 *
 * Note that the given file name must contain the full path otherwise the
 * extracted relative path will be created based on the current working
 * directory which is normally unknown.
 *
 * @param strFileName   Full file name which path is checked/created.
 * @param fCreate       Flag if the path should be created if it doesn't exist.
 *
 * @return Extended error information on failure to check/create the path.
 */
/* static */
HRESULT VirtualBox::i_ensureFilePathExists(const Utf8Str &strFileName, bool fCreate)
{
    Utf8Str strDir(strFileName);
    strDir.stripFilename();
    if (!RTDirExists(strDir.c_str()))
    {
        if (fCreate)
        {
            int vrc = RTDirCreateFullPath(strDir.c_str(), 0700);
            if (RT_FAILURE(vrc))
                return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, vrc,
                                            tr("Could not create the directory '%s' (%Rrc)"),
                                            strDir.c_str(),
                                            vrc);
        }
        else
            return i_setErrorStaticBoth(VBOX_E_IPRT_ERROR, VERR_FILE_NOT_FOUND,
                                        tr("Directory '%s' does not exist"), strDir.c_str());
    }

    return S_OK;
}

const Utf8Str& VirtualBox::i_settingsFilePath()
{
    return m->strSettingsFilePath;
}

/**
 * Returns the lock handle which protects the machines list. As opposed
 * to version 3.1 and earlier, these lists are no longer protected by the
 * VirtualBox lock, but by this more specialized lock. Mind the locking
 * order: always request this lock after the VirtualBox object lock but
 * before the locks of any machine object. See AutoLock.h.
 */
RWLockHandle& VirtualBox::i_getMachinesListLockHandle()
{
    return m->lockMachines;
}

/**
 * Returns the lock handle which protects the media trees (hard disks,
 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
 * are no longer protected by the VirtualBox lock, but by this more
 * specialized lock. Mind the locking order: always request this lock
 * after the VirtualBox object lock but before the locks of the media
 * objects contained in these lists. See AutoLock.h.
 */
RWLockHandle& VirtualBox::i_getMediaTreeLockHandle()
{
    return m->lockMedia;
}

/**
 *  Thread function that handles custom events posted using #i_postEvent().
 */
// static
DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
{
    LogFlowFuncEnter();

    AssertReturn(pvUser, VERR_INVALID_POINTER);

    HRESULT hrc = com::Initialize();
    if (FAILED(hrc))
        return VERR_COM_UNEXPECTED;

    int vrc = VINF_SUCCESS;

    try
    {
        /* Create an event queue for the current thread. */
        EventQueue *pEventQueue = new EventQueue();
        AssertPtr(pEventQueue);

        /* Return the queue to the one who created this thread. */
        *(static_cast <EventQueue **>(pvUser)) = pEventQueue;

        /* signal that we're ready. */
        RTThreadUserSignal(thread);

        /*
         * In case of spurious wakeups causing VERR_TIMEOUTs and/or other return codes
         * we must not stop processing events and delete the pEventQueue object. This must
         * be done ONLY when we stop this loop via interruptEventQueueProcessing().
         * See @bugref{5724}.
         */
        for (;;)
        {
            vrc = pEventQueue->processEventQueue(RT_INDEFINITE_WAIT);
            if (vrc == VERR_INTERRUPTED)
            {
                LogFlow(("Event queue processing ended with vrc=%Rrc\n", vrc));
                vrc = VINF_SUCCESS; /* Set success when exiting. */
                break;
            }
        }

        delete pEventQueue;
    }
    catch (std::bad_alloc &ba)
    {
        vrc = VERR_NO_MEMORY;
        NOREF(ba);
    }

    com::Shutdown();

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}


////////////////////////////////////////////////////////////////////////////////

#if 0 /* obsoleted by AsyncEvent */
/**
 * Prepare the event using the overwritten #prepareEventDesc method and fire.
 *
 *  @note Locks the managed VirtualBox object for reading but leaves the lock
 *        before iterating over callbacks and calling their methods.
 */
void *VirtualBox::CallbackEvent::handler()
{
    if (!mVirtualBox)
        return NULL;

    AutoCaller autoCaller(mVirtualBox);
    if (!autoCaller.isOk())
    {
        Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
                         mVirtualBox->getObjectState().getState()));
        /* We don't need mVirtualBox any more, so release it */
        mVirtualBox = NULL;
        return NULL;
    }

    {
        VBoxEventDesc evDesc;
        prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);

        evDesc.fire(/* don't wait for delivery */0);
    }

    mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
    return NULL;
}
#endif

/**
 * Called on the event handler thread.
 *
 * @note Locks the managed VirtualBox object for reading but leaves the lock
 *       before iterating over callbacks and calling their methods.
 */
void *VirtualBox::AsyncEvent::handler()
{
    if (mVirtualBox)
    {
        AutoCaller autoCaller(mVirtualBox);
        if (autoCaller.isOk())
        {
            VBoxEventDesc EvtDesc(mEvent, mVirtualBox->m->pEventSource);
            EvtDesc.fire(/* don't wait for delivery */0);
        }
        else
            Log1WarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
                             mVirtualBox->getObjectState().getState()));
        mVirtualBox = NULL; /* Old code did this, not really necessary, but whatever. */
    }
    mEvent.setNull();
    return NULL;
}

//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
//{
//    return E_NOTIMPL;
//}

HRESULT VirtualBox::createDHCPServer(const com::Utf8Str &aName,
                                     ComPtr<IDHCPServer> &aServer)
{
    ComObjPtr<DHCPServer> dhcpServer;
    dhcpServer.createObject();
    HRESULT hrc = dhcpServer->init(this, aName);
    if (FAILED(hrc)) return hrc;

    hrc = i_registerDHCPServer(dhcpServer, true);
    if (FAILED(hrc)) return hrc;

    dhcpServer.queryInterfaceTo(aServer.asOutParam());

    return hrc;
}

HRESULT VirtualBox::findDHCPServerByNetworkName(const com::Utf8Str &aName,
                                                ComPtr<IDHCPServer> &aServer)
{
    ComPtr<DHCPServer> found;

    AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
         it != m->allDHCPServers.end();
         ++it)
    {
        Bstr bstrNetworkName;
        HRESULT hrc = (*it)->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
        if (FAILED(hrc)) return hrc;

        if (Utf8Str(bstrNetworkName) == aName)
        {
            found = *it;
            break;
        }
    }

    if (!found)
        return E_INVALIDARG;
    return found.queryInterfaceTo(aServer.asOutParam());
}

HRESULT VirtualBox::removeDHCPServer(const ComPtr<IDHCPServer> &aServer)
{
    IDHCPServer *aP = aServer;
    return i_unregisterDHCPServer(static_cast<DHCPServer *>(aP));
}

/**
 * Remembers the given DHCP server in the settings.
 *
 * @param aDHCPServer   DHCP server object to remember.
 * @param aSaveSettings @c true to save settings to disk (default).
 *
 * When @a aSaveSettings is @c true, this operation may fail because of the
 * failed #i_saveSettings() method it calls. In this case, the dhcp server object
 * will not be remembered. It is therefore the responsibility of the caller to
 * call this method as the last step of some action that requires registration
 * in order to make sure that only fully functional dhcp server objects get
 * registered.
 *
 * @note Locks this object for writing and @a aDHCPServer for reading.
 */
HRESULT VirtualBox::i_registerDHCPServer(DHCPServer *aDHCPServer,
                                         bool aSaveSettings /*= true*/)
{
    AssertReturn(aDHCPServer != NULL, E_INVALIDARG);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    // Acquire a lock on the VirtualBox object early to avoid lock order issues
    // when we call i_saveSettings() later on.
    AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
    // need it below, in findDHCPServerByNetworkName (reading) and in
    // m->allDHCPServers.addChild, so need to get it here to avoid lock
    // order trouble with dhcpServerCaller
    AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    AutoCaller dhcpServerCaller(aDHCPServer);
    AssertComRCReturnRC(dhcpServerCaller.hrc());

    Bstr bstrNetworkName;
    HRESULT hrc = aDHCPServer->COMGETTER(NetworkName)(bstrNetworkName.asOutParam());
    if (FAILED(hrc)) return hrc;

    ComPtr<IDHCPServer> existing;
    hrc = findDHCPServerByNetworkName(Utf8Str(bstrNetworkName), existing);
    if (SUCCEEDED(hrc))
        return E_INVALIDARG;
    hrc = S_OK;

    m->allDHCPServers.addChild(aDHCPServer);
    // we need to release the list lock before we attempt to acquire locks
    // on other objects in i_saveSettings (see @bugref{7500})
    alock.release();

    if (aSaveSettings)
    {
        // we acquired the lock on 'this' earlier to avoid lock order issues
        hrc = i_saveSettings();

        if (FAILED(hrc))
        {
            alock.acquire();
            m->allDHCPServers.removeChild(aDHCPServer);
        }
    }

    return hrc;
}

/**
 * Removes the given DHCP server from the settings.
 *
 * @param aDHCPServer   DHCP server object to remove.
 *
 * This operation may fail because of the failed #i_saveSettings() method it
 * calls. In this case, the DHCP server will NOT be removed from the settings
 * when this method returns.
 *
 * @note Locks this object for writing.
 */
HRESULT VirtualBox::i_unregisterDHCPServer(DHCPServer *aDHCPServer)
{
    AssertReturn(aDHCPServer != NULL, E_INVALIDARG);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller dhcpServerCaller(aDHCPServer);
    AssertComRCReturnRC(dhcpServerCaller.hrc());

    AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
    AutoWriteLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
    m->allDHCPServers.removeChild(aDHCPServer);
    // we need to release the list lock before we attempt to acquire locks
    // on other objects in i_saveSettings (see @bugref{7500})
    alock.release();

    HRESULT hrc = i_saveSettings();

    // undo the changes if we failed to save them
    if (FAILED(hrc))
    {
        alock.acquire();
        m->allDHCPServers.addChild(aDHCPServer);
    }

    return hrc;
}


/**
 * NAT Network
 */
HRESULT VirtualBox::createNATNetwork(const com::Utf8Str &aNetworkName,
                                     ComPtr<INATNetwork> &aNetwork)
{
#ifdef VBOX_WITH_NAT_SERVICE
    ComObjPtr<NATNetwork> natNetwork;
    natNetwork.createObject();
    HRESULT hrc = natNetwork->init(this, aNetworkName);
    if (FAILED(hrc)) return hrc;

    hrc = i_registerNATNetwork(natNetwork, true);
    if (FAILED(hrc)) return hrc;

    natNetwork.queryInterfaceTo(aNetwork.asOutParam());

    ::FireNATNetworkCreationDeletionEvent(m->pEventSource, aNetworkName, TRUE);

    return hrc;
#else
    NOREF(aNetworkName);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif
}

HRESULT VirtualBox::findNATNetworkByName(const com::Utf8Str &aNetworkName,
                                         ComPtr<INATNetwork> &aNetwork)
{
#ifdef VBOX_WITH_NAT_SERVICE

    HRESULT hrc = S_OK;
    ComPtr<NATNetwork> found;

    AutoReadLock alock(m->allNATNetworks.getLockHandle() COMMA_LOCKVAL_SRC_POS);

    for (NATNetworksOList::const_iterator it = m->allNATNetworks.begin();
         it != m->allNATNetworks.end();
         ++it)
    {
        Bstr bstrNATNetworkName;
        hrc = (*it)->COMGETTER(NetworkName)(bstrNATNetworkName.asOutParam());
        if (FAILED(hrc)) return hrc;

        if (Utf8Str(bstrNATNetworkName) == aNetworkName)
        {
            found = *it;
            break;
        }
    }

    if (!found)
        return E_INVALIDARG;
    found.queryInterfaceTo(aNetwork.asOutParam());
    return hrc;
#else
    NOREF(aNetworkName);
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif
}

HRESULT VirtualBox::removeNATNetwork(const ComPtr<INATNetwork> &aNetwork)
{
#ifdef VBOX_WITH_NAT_SERVICE
    Bstr name;
    HRESULT hrc = aNetwork->COMGETTER(NetworkName)(name.asOutParam());
    if (FAILED(hrc))
        return hrc;
    INATNetwork *p = aNetwork;
    NATNetwork *network = static_cast<NATNetwork *>(p);
    hrc = i_unregisterNATNetwork(network, true);
    ::FireNATNetworkCreationDeletionEvent(m->pEventSource, name.raw(), FALSE);
    return hrc;
#else
    NOREF(aNetwork);
    return E_NOTIMPL;
#endif

}
/**
 * Remembers the given NAT network in the settings.
 *
 * @param aNATNetwork    NAT Network object to remember.
 * @param aSaveSettings @c true to save settings to disk (default).
 *
 *
 * @note Locks this object for writing and @a aNATNetwork for reading.
 */
HRESULT VirtualBox::i_registerNATNetwork(NATNetwork *aNATNetwork,
                                         bool aSaveSettings /*= true*/)
{
#ifdef VBOX_WITH_NAT_SERVICE
    AssertReturn(aNATNetwork != NULL, E_INVALIDARG);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller natNetworkCaller(aNATNetwork);
    AssertComRCReturnRC(natNetworkCaller.hrc());

    Bstr name;
    HRESULT hrc;
    hrc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
    AssertComRCReturnRC(hrc);

    /* returned value isn't 0 and aSaveSettings is true
     * means that we create duplicate, otherwise we just load settings.
     */
    if (   sNatNetworkNameToRefCount[name]
        && aSaveSettings)
        AssertComRCReturnRC(E_INVALIDARG);

    hrc = S_OK;

    sNatNetworkNameToRefCount[name] = 0;

    m->allNATNetworks.addChild(aNATNetwork);

    if (aSaveSettings)
    {
        AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
        vboxLock.release();

        if (FAILED(hrc))
            i_unregisterNATNetwork(aNATNetwork, false /* aSaveSettings */);
    }

    return hrc;
#else
    NOREF(aNATNetwork);
    NOREF(aSaveSettings);
    /* No panic please (silently ignore) */
    return S_OK;
#endif
}

/**
 * Removes the given NAT network from the settings.
 *
 * @param aNATNetwork   NAT network object to remove.
 * @param aSaveSettings @c true to save settings to disk (default).
 *
 * When @a aSaveSettings is @c true, this operation may fail because of the
 * failed #i_saveSettings() method it calls. In this case, the DHCP server
 * will NOT be removed from the settingsi when this method returns.
 *
 * @note Locks this object for writing.
 */
HRESULT VirtualBox::i_unregisterNATNetwork(NATNetwork *aNATNetwork,
                                           bool aSaveSettings /*= true*/)
{
#ifdef VBOX_WITH_NAT_SERVICE
    AssertReturn(aNATNetwork != NULL, E_INVALIDARG);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoCaller natNetworkCaller(aNATNetwork);
    AssertComRCReturnRC(natNetworkCaller.hrc());

    Bstr name;
    HRESULT hrc = aNATNetwork->COMGETTER(NetworkName)(name.asOutParam());
    /* Hm, there're still running clients. */
    if (FAILED(hrc) || sNatNetworkNameToRefCount[name])
        AssertComRCReturnRC(E_INVALIDARG);

    m->allNATNetworks.removeChild(aNATNetwork);

    if (aSaveSettings)
    {
        AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
        hrc = i_saveSettings();
        vboxLock.release();

        if (FAILED(hrc))
            i_registerNATNetwork(aNATNetwork, false /* aSaveSettings */);
    }

    return hrc;
#else
    NOREF(aNATNetwork);
    NOREF(aSaveSettings);
    return E_NOTIMPL;
#endif
}


HRESULT VirtualBox::findProgressById(const com::Guid &aId,
                                     ComPtr<IProgress> &aProgressObject)
{
    if (!aId.isValid())
        return setError(E_INVALIDARG,
                        tr("The provided progress object GUID is invalid"));

    /* protect mProgressOperations */
    AutoReadLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);

    ProgressMap::const_iterator it = m->mapProgressOperations.find(aId);
    if (it != m->mapProgressOperations.end())
    {
        aProgressObject = it->second;
        return S_OK;
    }
    return setError(E_INVALIDARG,
                    tr("The progress object with the given GUID could not be found"));
}


/**
 * Retains a reference to the default cryptographic interface.
 *
 * @returns COM status code.
 * @param   ppCryptoIf          Where to store the pointer to the cryptographic interface on success.
 *
 * @note Locks this object for writing.
 */
HRESULT VirtualBox::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
{
    AssertReturn(ppCryptoIf != NULL, E_INVALIDARG);

    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    /*
     * No object lock due to some lock order fun with Machine objects.
     * There is a dedicated critical section to protect against concurrency
     * issues when loading the module.
     */
    RTCritSectEnter(&m->CritSectModCrypto);

    /* Try to load the extension pack module if it isn't currently. */
    HRESULT hrc = S_OK;
    if (m->hLdrModCrypto == NIL_RTLDRMOD)
    {
#ifdef VBOX_WITH_EXTPACK
        /*
         * Check that a crypto extension pack name is set and resolve it into a
         * library path.
         */
        Utf8Str strExtPack;
        hrc = m->pSystemProperties->getDefaultCryptoExtPack(strExtPack);
        if (FAILED(hrc))
        {
            RTCritSectLeave(&m->CritSectModCrypto);
            return hrc;
        }
        if (strExtPack.isEmpty())
        {
            RTCritSectLeave(&m->CritSectModCrypto);
            return setError(VBOX_E_OBJECT_NOT_FOUND,
                            tr("Ńo extension pack providing a cryptographic support module could be found"));
        }

        Utf8Str strCryptoLibrary;
        int vrc = m->ptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
        if (RT_SUCCESS(vrc))
        {
            RTERRINFOSTATIC ErrInfo;
            vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &m->hLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
            if (RT_SUCCESS(vrc))
            {
                /* Resolve the entry point and query the pointer to the cryptographic interface. */
                PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
                vrc = RTLdrGetSymbol(m->hLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
                if (RT_SUCCESS(vrc))
                {
                    vrc = pfnCryptoEntry(&m->pCryptoIf);
                    if (RT_FAILURE(vrc))
                        hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                           tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
                                           strCryptoLibrary.c_str(), strExtPack.c_str());
                }
                else
                    hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                       tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
                                       strCryptoLibrary.c_str(), strExtPack.c_str());
            }
            else
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                   tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
                                   strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
        }
        else
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                               tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
                               strExtPack.c_str());
#else
        hrc = setError(VBOX_E_NOT_SUPPORTED,
                       tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
#endif
    }

    if (SUCCEEDED(hrc))
    {
        ASMAtomicIncU32(&m->cRefsCrypto);
        *ppCryptoIf = m->pCryptoIf;
    }

    RTCritSectLeave(&m->CritSectModCrypto);

    return hrc;
}


/**
 * Releases the reference of the given cryptographic interface.
 *
 * @returns COM status code.
 * @param   pCryptoIf           Pointer to the cryptographic interface to release.
 *
 * @note Locks this object for writing.
 */
HRESULT VirtualBox::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AssertReturn(pCryptoIf == m->pCryptoIf, E_INVALIDARG);

    ASMAtomicDecU32(&m->cRefsCrypto);
    return S_OK;
}


/**
 * Tries to unload any loaded cryptographic support module if it is not in use currently.
 *
 * @returns COM status code.
 *
 * @note Locks this object for writing.
 */
HRESULT VirtualBox::i_unloadCryptoIfModule(void)
{
    AutoCaller autoCaller(this);
    AssertComRCReturnRC(autoCaller.hrc());

    AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);

    if (m->cRefsCrypto)
        return setError(E_ACCESSDENIED,
                        tr("The cryptographic support module is in use and can't be unloaded"));

    RTCritSectEnter(&m->CritSectModCrypto);
    if (m->hLdrModCrypto != NIL_RTLDRMOD)
    {
        int vrc = RTLdrClose(m->hLdrModCrypto);
        AssertRC(vrc);
        m->hLdrModCrypto = NIL_RTLDRMOD;
    }
    RTCritSectLeave(&m->CritSectModCrypto);

    return S_OK;
}


#ifdef RT_OS_WINDOWS
#include <psapi.h>

/**
 * Report versions of installed drivers to release log.
 */
void VirtualBox::i_reportDriverVersions()
{
    /** @todo r=klaus this code is very confusing, as it uses TCHAR (and
     * randomly also _TCHAR, which sounds to me like asking for trouble),
     * the "sz" variable prefix but "%ls" for the format string - so the whole
     * thing is better compiled with UNICODE and _UNICODE defined. Would be
     * far easier to read if it would be coded explicitly for the unicode
     * case, as it won't work otherwise. */
    DWORD   err;
    HRESULT hrc;
    LPVOID  aDrivers[1024];
    LPVOID *pDrivers      = aDrivers;
    UINT    cNeeded       = 0;
    TCHAR   szSystemRoot[MAX_PATH];
    TCHAR  *pszSystemRoot = szSystemRoot;
    LPVOID  pVerInfo      = NULL;
    DWORD   cbVerInfo     = 0;

    do
    {
        cNeeded = GetWindowsDirectory(szSystemRoot, RT_ELEMENTS(szSystemRoot));
        if (cNeeded == 0)
        {
            err = GetLastError();
            hrc = HRESULT_FROM_WIN32(err);
            AssertLogRelMsgFailed(("GetWindowsDirectory failed, hrc=%Rhrc (0x%x) err=%u\n",
                                                   hrc, hrc, err));
            break;
        }
        else if (cNeeded > RT_ELEMENTS(szSystemRoot))
        {
            /* The buffer is too small, allocate big one. */
            pszSystemRoot = (TCHAR *)RTMemTmpAlloc(cNeeded * sizeof(_TCHAR));
            if (!pszSystemRoot)
            {
                AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cNeeded));
                break;
            }
            if (GetWindowsDirectory(pszSystemRoot, cNeeded) == 0)
            {
                err = GetLastError();
                hrc = HRESULT_FROM_WIN32(err);
                AssertLogRelMsgFailed(("GetWindowsDirectory failed, hrc=%Rhrc (0x%x) err=%u\n",
                                                   hrc, hrc, err));
                break;
            }
        }

        DWORD  cbNeeded = 0;
        if (!EnumDeviceDrivers(aDrivers, sizeof(aDrivers), &cbNeeded) || cbNeeded > sizeof(aDrivers))
        {
            pDrivers = (LPVOID *)RTMemTmpAlloc(cbNeeded);
            if (!EnumDeviceDrivers(pDrivers, cbNeeded, &cbNeeded))
            {
                err = GetLastError();
                hrc = HRESULT_FROM_WIN32(err);
                AssertLogRelMsgFailed(("EnumDeviceDrivers failed, hrc=%Rhrc (0x%x) err=%u\n",
                                                   hrc, hrc, err));
                break;
            }
        }

        LogRel(("Installed Drivers:\n"));

        TCHAR szDriver[1024];
        int cDrivers = cbNeeded / sizeof(pDrivers[0]);
        for (int i = 0; i < cDrivers; i++)
        {
            if (GetDeviceDriverBaseName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
            {
                if (_tcsnicmp(TEXT("vbox"), szDriver, 4))
                    continue;
            }
            else
                continue;
            if (GetDeviceDriverFileName(pDrivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
            {
                _TCHAR szTmpDrv[1024];
                _TCHAR *pszDrv = szDriver;
                if (!_tcsncmp(TEXT("\\SystemRoot"), szDriver, 11))
                {
                    _tcscpy_s(szTmpDrv, pszSystemRoot);
                    _tcsncat_s(szTmpDrv, szDriver + 11, sizeof(szTmpDrv) / sizeof(szTmpDrv[0]) - _tclen(pszSystemRoot));
                    pszDrv = szTmpDrv;
                }
                else if (!_tcsncmp(TEXT("\\??\\"), szDriver, 4))
                    pszDrv = szDriver + 4;

                /* Allocate a buffer for version info. Reuse if large enough. */
                DWORD cbNewVerInfo = GetFileVersionInfoSize(pszDrv, NULL);
                if (cbNewVerInfo > cbVerInfo)
                {
                    if (pVerInfo)
                        RTMemTmpFree(pVerInfo);
                    cbVerInfo = cbNewVerInfo;
                    pVerInfo = RTMemTmpAlloc(cbVerInfo);
                    if (!pVerInfo)
                    {
                        AssertLogRelMsgFailed(("RTMemTmpAlloc failed to allocate %d bytes\n", cbVerInfo));
                        break;
                    }
                }

                if (GetFileVersionInfo(pszDrv, NULL, cbVerInfo, pVerInfo))
                {
                    UINT   cbSize = 0;
                    LPBYTE lpBuffer = NULL;
                    if (VerQueryValue(pVerInfo, TEXT("\\"), (VOID FAR* FAR*)&lpBuffer, &cbSize))
                    {
                        if (cbSize)
                        {
                            VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
                            if (pFileInfo->dwSignature == 0xfeef04bd)
                            {
                                LogRel(("  %ls (Version: %d.%d.%d.%d)\n", pszDrv,
                                        (pFileInfo->dwFileVersionMS >> 16) & 0xffff,
                                        (pFileInfo->dwFileVersionMS >> 0) & 0xffff,
                                        (pFileInfo->dwFileVersionLS >> 16) & 0xffff,
                                        (pFileInfo->dwFileVersionLS >> 0) & 0xffff));
                            }
                        }
                    }
                }
            }
        }

    }
    while (0);

    if (pVerInfo)
        RTMemTmpFree(pVerInfo);

    if (pDrivers != aDrivers)
        RTMemTmpFree(pDrivers);

    if (pszSystemRoot != szSystemRoot)
        RTMemTmpFree(pszSystemRoot);
}
#else /* !RT_OS_WINDOWS */
void VirtualBox::i_reportDriverVersions(void)
{
}
#endif /* !RT_OS_WINDOWS */

#if defined(RT_OS_WINDOWS) && defined(VBOXSVC_WITH_CLIENT_WATCHER)

# include <psapi.h> /* for GetProcessImageFileNameW */

/**
 * Callout from the wrapper.
 */
void VirtualBox::i_callHook(const char *a_pszFunction)
{
    RT_NOREF(a_pszFunction);

    /*
     * Let'see figure out who is calling.
     * Note! Requires Vista+, so skip this entirely on older systems.
     */
    if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
    {
        RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
        RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
        if (   rcRpc == RPC_S_OK
            && CallAttribs.ClientPID != 0)
        {
            RTPROCESS const pidClient = (RTPROCESS)(uintptr_t)CallAttribs.ClientPID;
            if (pidClient != RTProcSelf())
            {
                /** @todo LogRel2 later: */
                LogRel(("i_callHook: %Rfn [ClientPID=%#zx/%zu IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
                        a_pszFunction, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
                        CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
                        &CallAttribs.InterfaceUuid));

                /*
                 * Do we know this client PID already?
                 */
                RTCritSectRwEnterShared(&m->WatcherCritSect);
                WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(pidClient);
                if (It != m->WatchedProcesses.end())
                    RTCritSectRwLeaveShared(&m->WatcherCritSect); /* Known process, nothing to do. */
                else
                {
                    /* This is a new client process, start watching it. */
                    RTCritSectRwLeaveShared(&m->WatcherCritSect);
                    i_watchClientProcess(pidClient, a_pszFunction);
                }
            }
        }
        else
            LogRel(("i_callHook: %Rfn - rcRpc=%#x ClientPID=%#zx/%zu !! [IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
                    a_pszFunction, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, CallAttribs.IsClientLocal,
                    CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
                    &CallAttribs.InterfaceUuid));
    }
}


/**
 * Watches @a a_pidClient for termination.
 *
 * @returns true if successfully enabled watching of it, false if not.
 * @param   a_pidClient     The PID to watch.
 * @param   a_pszFunction   The function we which we detected the client in.
 */
bool VirtualBox::i_watchClientProcess(RTPROCESS a_pidClient, const char *a_pszFunction)
{
    RT_NOREF_PV(a_pszFunction);

    /*
     * Open the client process.
     */
    HANDLE hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE /*fInherit*/, a_pidClient);
    if (hClient == NULL)
        hClient = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE , a_pidClient);
    if (hClient == NULL)
        hClient = OpenProcess(SYNCHRONIZE, FALSE , a_pidClient);
    AssertLogRelMsgReturn(hClient != NULL, ("pidClient=%d (%#x) err=%d\n", a_pidClient, a_pidClient, GetLastError()),
                          m->fWatcherIsReliable = false);

    /*
     * Create a new watcher structure and try add it to the map.
     */
    bool fRet = true;
    WatchedClientProcess *pWatched = new (std::nothrow) WatchedClientProcess(a_pidClient, hClient);
    if (pWatched)
    {
        RTCritSectRwEnterExcl(&m->WatcherCritSect);

        WatchedClientProcessMap::iterator It = m->WatchedProcesses.find(a_pidClient);
        if (It == m->WatchedProcesses.end())
        {
            try
            {
                m->WatchedProcesses.insert(WatchedClientProcessMap::value_type(a_pidClient, pWatched));
            }
            catch (std::bad_alloc &)
            {
                fRet = false;
            }
            if (fRet)
            {
                /*
                 * Schedule it on a watcher thread.
                 */
                /** @todo later. */
                RTCritSectRwLeaveExcl(&m->WatcherCritSect);
            }
            else
            {
                RTCritSectRwLeaveExcl(&m->WatcherCritSect);
                delete pWatched;
                LogRel(("VirtualBox::i_watchClientProcess: out of memory inserting into client map!\n"));
            }
        }
        else
        {
            /*
             * Someone raced us here, we lost.
             */
            RTCritSectRwLeaveExcl(&m->WatcherCritSect);
            delete pWatched;
        }
    }
    else
    {
        LogRel(("VirtualBox::i_watchClientProcess: out of memory!\n"));
        CloseHandle(hClient);
        m->fWatcherIsReliable = fRet = false;
    }
    return fRet;
}


/** Logs the RPC caller info to the release log. */
/*static*/ void VirtualBox::i_logCaller(const char *a_pszFormat, ...)
{
    if (RTSystemGetNtVersion() >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
    {
        char szTmp[80];
        va_list va;
        va_start(va, a_pszFormat);
        RTStrPrintfV(szTmp, sizeof(szTmp), a_pszFormat, va);
        va_end(va);

        RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
        RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);

        RTUTF16 wszProcName[256];
        wszProcName[0] = '\0';
        if (rcRpc == 0 && CallAttribs.ClientPID != 0)
        {
            HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)(uintptr_t)CallAttribs.ClientPID);
            if (hProcess)
            {
                RT_ZERO(wszProcName);
                GetProcessImageFileNameW(hProcess, wszProcName, RT_ELEMENTS(wszProcName) - 1);
                CloseHandle(hProcess);
            }
        }
        LogRel(("%s [rcRpc=%#x ClientPID=%#zx/%zu (%ls) IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid]\n",
                szTmp, rcRpc, CallAttribs.ClientPID, CallAttribs.ClientPID, wszProcName, CallAttribs.IsClientLocal,
                CallAttribs.ProtocolSequence, CallAttribs.CallStatus, CallAttribs.CallType, CallAttribs.OpNum,
                &CallAttribs.InterfaceUuid));
    }
}

#endif /* RT_OS_WINDOWS && VBOXSVC_WITH_CLIENT_WATCHER */


/* vi: set tabstop=4 shiftwidth=4 expandtab: */