summaryrefslogtreecommitdiffstats
path: root/src/VBox/Additions/common/VBoxService/VBoxServiceControlSession.cpp
blob: 001d468d3c9a8d01bb52ba73aeeacdbf10697cab (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
/* $Id: VBoxServiceControlSession.cpp $ */
/** @file
 * VBoxServiceControlSession - Guest session handling. Also handles the spawned session processes.
 */

/*
 * Copyright (C) 2013-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
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/dir.h>
#include <iprt/env.h>
#include <iprt/file.h>
#include <iprt/getopt.h>
#include <iprt/handle.h>
#include <iprt/mem.h>
#include <iprt/message.h>
#include <iprt/path.h>
#include <iprt/pipe.h>
#include <iprt/poll.h>
#include <iprt/process.h>
#include <iprt/rand.h>
#include <iprt/system.h> /* For RTShutdown. */

#include "VBoxServiceInternal.h"
#include "VBoxServiceUtils.h"
#include "VBoxServiceControl.h"

using namespace guestControl;


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/** Generic option indices for session spawn arguments. */
enum
{
    VBOXSERVICESESSIONOPT_FIRST = 1000, /* For initialization. */
    VBOXSERVICESESSIONOPT_DOMAIN,
#ifdef DEBUG
    VBOXSERVICESESSIONOPT_DUMP_STDOUT,
    VBOXSERVICESESSIONOPT_DUMP_STDERR,
#endif
    VBOXSERVICESESSIONOPT_LOG_FILE,
    VBOXSERVICESESSIONOPT_USERNAME,
    VBOXSERVICESESSIONOPT_SESSION_ID,
    VBOXSERVICESESSIONOPT_SESSION_PROTO,
    VBOXSERVICESESSIONOPT_THREAD_ID
};


static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession);
static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess);


/**
 * Helper that grows the scratch buffer.
 * @returns Success indicator.
 */
static bool vgsvcGstCtrlSessionGrowScratchBuf(void **ppvScratchBuf, uint32_t *pcbScratchBuf, uint32_t cbMinBuf)
{
    uint32_t cbNew = *pcbScratchBuf * 2;
    if (   cbNew    <= VMMDEV_MAX_HGCM_DATA_SIZE
        && cbMinBuf <= VMMDEV_MAX_HGCM_DATA_SIZE)
    {
        while (cbMinBuf > cbNew)
            cbNew *= 2;
        void *pvNew = RTMemRealloc(*ppvScratchBuf, cbNew);
        if (pvNew)
        {
            *ppvScratchBuf = pvNew;
            *pcbScratchBuf = cbNew;
            return true;
        }
    }
    return false;
}



static int vgsvcGstCtrlSessionFileFree(PVBOXSERVICECTRLFILE pFile)
{
    AssertPtrReturn(pFile, VERR_INVALID_POINTER);

    int rc = RTFileClose(pFile->hFile);
    if (RT_SUCCESS(rc))
    {
        RTStrFree(pFile->pszName);

        /* Remove file entry in any case. */
        RTListNodeRemove(&pFile->Node);
        /* Destroy this object. */
        RTMemFree(pFile);
    }

    return rc;
}


/** @todo No locking done yet! */
static PVBOXSERVICECTRLFILE vgsvcGstCtrlSessionFileGetLocked(const PVBOXSERVICECTRLSESSION pSession, uint32_t uHandle)
{
    AssertPtrReturn(pSession, NULL);

    /** @todo Use a map later! */
    PVBOXSERVICECTRLFILE pFileCur;
    RTListForEach(&pSession->lstFiles, pFileCur, VBOXSERVICECTRLFILE, Node)
    {
        if (pFileCur->uHandle == uHandle)
            return pFileCur;
    }

    return NULL;
}


/**
 * Recursion worker for vgsvcGstCtrlSessionHandleDirRemove.
 * Only (recursively) removes directory structures which are not empty. Will fail if not empty.
 *
 * @returns IPRT status code.
 * @param   pszDir              The directory buffer, RTPATH_MAX in length.
 *                              Contains the abs path to the directory to
 *                              recurse into. Trailing slash.
 * @param   cchDir              The length of the directory we're recursing into,
 *                              including the trailing slash.
 * @param   pDirEntry           The dir entry buffer.  (Shared to save stack.)
 */
static int vgsvcGstCtrlSessionHandleDirRemoveSub(char *pszDir, size_t cchDir, PRTDIRENTRY pDirEntry)
{
    RTDIR hDir;
    int rc = RTDirOpen(&hDir, pszDir);
    if (RT_FAILURE(rc))
    {
        /* Ignore non-existing directories like RTDirRemoveRecursive does: */
        if (rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND)
            return VINF_SUCCESS;
        return rc;
    }

    for (;;)
    {
        rc = RTDirRead(hDir, pDirEntry, NULL);
        if (RT_FAILURE(rc))
        {
            if (rc == VERR_NO_MORE_FILES)
                rc = VINF_SUCCESS;
            break;
        }

        if (!RTDirEntryIsStdDotLink(pDirEntry))
        {
            /* Construct the full name of the entry. */
            if (cchDir + pDirEntry->cbName + 1 /* dir slash */ < RTPATH_MAX)
                memcpy(&pszDir[cchDir], pDirEntry->szName, pDirEntry->cbName + 1);
            else
            {
                rc = VERR_FILENAME_TOO_LONG;
                break;
            }

            /* Make sure we've got the entry type. */
            if (pDirEntry->enmType == RTDIRENTRYTYPE_UNKNOWN)
                RTDirQueryUnknownType(pszDir, false /*fFollowSymlinks*/, &pDirEntry->enmType);

            /* Recurse into subdirs and remove them: */
            if (pDirEntry->enmType == RTDIRENTRYTYPE_DIRECTORY)
            {
                size_t cchSubDir    = cchDir + pDirEntry->cbName;
                pszDir[cchSubDir++] = RTPATH_SLASH;
                pszDir[cchSubDir]   = '\0';
                rc = vgsvcGstCtrlSessionHandleDirRemoveSub(pszDir, cchSubDir, pDirEntry);
                if (RT_SUCCESS(rc))
                {
                    pszDir[cchSubDir] = '\0';
                    rc = RTDirRemove(pszDir);
                    if (RT_FAILURE(rc))
                        break;
                }
                else
                    break;
            }
            /* Not a subdirectory - fail: */
            else
            {
                rc = VERR_DIR_NOT_EMPTY;
                break;
            }
        }
    }

    RTDirClose(hDir);
    return rc;
}


static int vgsvcGstCtrlSessionHandleDirRemove(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the message.
     */
    char        szDir[RTPATH_MAX];
    uint32_t    fFlags; /* DIRREMOVE_FLAG_XXX */
    int rc = VbglR3GuestCtrlDirGetRemove(pHostCtx, szDir, sizeof(szDir), &fFlags);
    if (RT_SUCCESS(rc))
    {
        /*
         * Do some validating before executing the job.
         */
        if (!(fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK))
        {
            if (fFlags & DIRREMOVEREC_FLAG_RECURSIVE)
            {
                if (fFlags & (DIRREMOVEREC_FLAG_CONTENT_AND_DIR | DIRREMOVEREC_FLAG_CONTENT_ONLY))
                {
                    uint32_t fFlagsRemRec = fFlags & DIRREMOVEREC_FLAG_CONTENT_AND_DIR
                                          ? RTDIRRMREC_F_CONTENT_AND_DIR : RTDIRRMREC_F_CONTENT_ONLY;
                    rc = RTDirRemoveRecursive(szDir, fFlagsRemRec);
                }
                else /* Only remove empty directory structures. Will fail if non-empty. */
                {
                    RTDIRENTRY DirEntry;
                    RTPathEnsureTrailingSeparator(szDir, sizeof(szDir));
                    rc = vgsvcGstCtrlSessionHandleDirRemoveSub(szDir, strlen(szDir), &DirEntry);
                }
                VGSvcVerbose(4, "[Dir %s]: rmdir /s (%#x) -> rc=%Rrc\n", szDir, fFlags, rc);
            }
            else
            {
                /* Only delete directory if not empty. */
                rc = RTDirRemove(szDir);
                VGSvcVerbose(4, "[Dir %s]: rmdir (%#x), rc=%Rrc\n", szDir, fFlags, rc);
            }
        }
        else
        {
            VGSvcError("[Dir %s]: Unsupported flags: %#x (all %#x)\n", szDir, (fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK), fFlags);
            rc = VERR_NOT_SUPPORTED;
        }

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("[Dir %s]: Failed to report removing status, rc=%Rrc\n", szDir, rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for rmdir operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }

    VGSvcVerbose(6, "Removing directory '%s' returned rc=%Rrc\n", szDir, rc);
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileOpen(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the message.
     */
    char     szFile[RTPATH_MAX];
    char     szAccess[64];
    char     szDisposition[64];
    char     szSharing[64];
    uint32_t uCreationMode = 0;
    uint64_t offOpen       = 0;
    uint32_t uHandle       = 0;
    int rc = VbglR3GuestCtrlFileGetOpen(pHostCtx,
                                        /* File to open. */
                                        szFile, sizeof(szFile),
                                        /* Open mode. */
                                        szAccess, sizeof(szAccess),
                                        /* Disposition. */
                                        szDisposition, sizeof(szDisposition),
                                        /* Sharing. */
                                        szSharing, sizeof(szSharing),
                                        /* Creation mode. */
                                        &uCreationMode,
                                        /* Offset. */
                                        &offOpen);
    VGSvcVerbose(4, "[File %s]: szAccess=%s, szDisposition=%s, szSharing=%s, offOpen=%RU64, rc=%Rrc\n",
                 szFile, szAccess, szDisposition, szSharing, offOpen, rc);
    if (RT_SUCCESS(rc))
    {
        PVBOXSERVICECTRLFILE pFile = (PVBOXSERVICECTRLFILE)RTMemAllocZ(sizeof(VBOXSERVICECTRLFILE));
        if (pFile)
        {
            pFile->hFile = NIL_RTFILE; /* Not zero or NULL! */
            if (szFile[0])
            {
                pFile->pszName = RTStrDup(szFile);
                if (!pFile->pszName)
                    rc = VERR_NO_MEMORY;
/** @todo
 * Implement szSharing!
 */
                uint64_t fFlags;
                if (RT_SUCCESS(rc))
                {
                    rc = RTFileModeToFlagsEx(szAccess, szDisposition, NULL /* pszSharing, not used yet */, &fFlags);
                    VGSvcVerbose(4, "[File %s] Opening with fFlags=%#RX64 -> rc=%Rrc\n", pFile->pszName, fFlags, rc);
                }

                if (RT_SUCCESS(rc))
                {
                    fFlags |= (uCreationMode << RTFILE_O_CREATE_MODE_SHIFT) & RTFILE_O_CREATE_MODE_MASK;
                    /* If we're opening a file in read-only mode, strip truncation mode.
                     * rtFileRecalcAndValidateFlags() will validate it anyway, but avoid asserting in debug builds. */
                    if (fFlags & RTFILE_O_READ)
                        fFlags &= ~RTFILE_O_TRUNCATE;
                    rc = RTFileOpen(&pFile->hFile, pFile->pszName, fFlags);
                    if (RT_SUCCESS(rc))
                    {
                        RTFSOBJINFO objInfo;
                        rc = RTFileQueryInfo(pFile->hFile, &objInfo, RTFSOBJATTRADD_NOTHING);
                        if (RT_SUCCESS(rc))
                        {
                            /* Make sure that we only open stuff we really support.
                             * Only POSIX / UNIX we could open stuff like directories and sockets as well. */
                            if (   RT_LIKELY(RTFS_IS_FILE(objInfo.Attr.fMode))
                                ||           RTFS_IS_SYMLINK(objInfo.Attr.fMode))
                            {
                                /* Seeking is optional. However, the whole operation
                                 * will fail if we don't succeed seeking to the wanted position. */
                                if (offOpen)
                                    rc = RTFileSeek(pFile->hFile, (int64_t)offOpen, RTFILE_SEEK_BEGIN, NULL /* Current offset */);
                                if (RT_SUCCESS(rc))
                                {
                                    /*
                                     * Succeeded!
                                     */
                                    uHandle = VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pHostCtx->uContextID);
                                    pFile->uHandle = uHandle;
                                    pFile->fOpen   = fFlags;
                                    RTListAppend(&pSession->lstFiles, &pFile->Node);
                                    VGSvcVerbose(2, "[File %s] Opened (ID=%RU32)\n", pFile->pszName, pFile->uHandle);
                                }
                                else
                                    VGSvcError("[File %s] Seeking to offset %RU64 failed: rc=%Rrc\n", pFile->pszName, offOpen, rc);
                            }
                            else
                            {
                                VGSvcError("[File %s] Unsupported mode %#x\n", pFile->pszName, objInfo.Attr.fMode);
                                rc = VERR_NOT_SUPPORTED;
                            }
                        }
                        else
                            VGSvcError("[File %s] Getting mode failed with rc=%Rrc\n", pFile->pszName, rc);
                    }
                    else
                        VGSvcError("[File %s] Opening failed with rc=%Rrc\n", pFile->pszName, rc);
                }
            }
            else
            {
                VGSvcError("[File %s] empty filename!\n", szFile);
                rc = VERR_INVALID_NAME;
            }

            /* clean up if we failed. */
            if (RT_FAILURE(rc))
            {
                RTStrFree(pFile->pszName);
                if (pFile->hFile != NIL_RTFILE)
                    RTFileClose(pFile->hFile);
                RTMemFree(pFile);
            }
        }
        else
            rc = VERR_NO_MEMORY;

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlFileCbOpen(pHostCtx, rc, uHandle);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("[File %s]: Failed to report file open status, rc=%Rrc\n", szFile, rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for open file operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }

    VGSvcVerbose(4, "[File %s] Opening (open mode='%s', disposition='%s', creation mode=0x%x) returned rc=%Rrc\n",
                 szFile, szAccess, szDisposition, uCreationMode, rc);
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileClose(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the message.
     */
    uint32_t uHandle = 0;
    int rc = VbglR3GuestCtrlFileGetClose(pHostCtx, &uHandle /* File handle to close */);
    if (RT_SUCCESS(rc))
    {
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            VGSvcVerbose(2, "[File %s] Closing (handle=%RU32)\n", pFile ? pFile->pszName : "<Not found>", uHandle);
            rc = vgsvcGstCtrlSessionFileFree(pFile);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlFileCbClose(pHostCtx, rc);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file close status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for close file operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileRead(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
                                             void **ppvScratchBuf, uint32_t *pcbScratchBuf)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uHandle = 0;
    uint32_t cbToRead;
    int rc = VbglR3GuestCtrlFileGetRead(pHostCtx, &uHandle, &cbToRead);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the file and do the reading.
         *
         * If the request is larger than our scratch buffer, try grow it - just
         * ignore failure as the host better respect our buffer limits.
         */
        uint32_t offNew = 0;
        size_t   cbRead = 0;
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            if (*pcbScratchBuf < cbToRead)
                 vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToRead);

            rc = RTFileRead(pFile->hFile, *ppvScratchBuf, RT_MIN(cbToRead, *pcbScratchBuf), &cbRead);
            offNew = (int64_t)RTFileTell(pFile->hFile);
            VGSvcVerbose(5, "[File %s] Read %zu/%RU32 bytes, rc=%Rrc, offNew=%RI64\n", pFile->pszName, cbRead, cbToRead, rc, offNew);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result and data back to the host.
         */
        int rc2;
        if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
            rc2 = VbglR3GuestCtrlFileCbReadOffset(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead, offNew);
        else
            rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file read status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file read operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileReadAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
                                               void **ppvScratchBuf, uint32_t *pcbScratchBuf)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uHandle = 0;
    uint32_t cbToRead;
    uint64_t offReadAt;
    int rc = VbglR3GuestCtrlFileGetReadAt(pHostCtx, &uHandle, &cbToRead, &offReadAt);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the file and do the reading.
         *
         * If the request is larger than our scratch buffer, try grow it - just
         * ignore failure as the host better respect our buffer limits.
         */
        int64_t offNew = 0;
        size_t  cbRead = 0;
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            if (*pcbScratchBuf < cbToRead)
                 vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToRead);

            rc = RTFileReadAt(pFile->hFile, (RTFOFF)offReadAt, *ppvScratchBuf, RT_MIN(cbToRead, *pcbScratchBuf), &cbRead);
            if (RT_SUCCESS(rc))
            {
                offNew = offReadAt + cbRead;
                RTFileSeek(pFile->hFile, offNew, RTFILE_SEEK_BEGIN, NULL); /* RTFileReadAt does not always change position. */
            }
            else
                offNew = (int64_t)RTFileTell(pFile->hFile);
            VGSvcVerbose(5, "[File %s] Read %zu bytes @ %RU64, rc=%Rrc, offNew=%RI64\n", pFile->pszName, cbRead, offReadAt, rc, offNew);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result and data back to the host.
         */
        int rc2;
        if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
            rc2 = VbglR3GuestCtrlFileCbReadOffset(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead, offNew);
        else
            rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file read at status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file read at operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileWrite(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
                                              void **ppvScratchBuf, uint32_t *pcbScratchBuf)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request and data to write.
     */
    uint32_t uHandle = 0;
    uint32_t cbToWrite;
    int rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite);
    if (   rc == VERR_BUFFER_OVERFLOW
        && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToWrite))
        rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the file and do the writing.
         */
        int64_t offNew    = 0;
        size_t  cbWritten = 0;
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            rc = RTFileWrite(pFile->hFile, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), &cbWritten);
            offNew = (int64_t)RTFileTell(pFile->hFile);
            VGSvcVerbose(5, "[File %s] Writing %p LB %RU32 =>  %Rrc, cbWritten=%zu, offNew=%RI64\n",
                         pFile->pszName, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), rc, cbWritten, offNew);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result back to host.
         */
        int rc2;
        if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
            rc2 = VbglR3GuestCtrlFileCbWriteOffset(pHostCtx, rc, (uint32_t)cbWritten, offNew);
        else
            rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file write operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileWriteAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
                                                void **ppvScratchBuf, uint32_t *pcbScratchBuf)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request and data to write.
     */
    uint32_t uHandle = 0;
    uint32_t cbToWrite;
    uint64_t offWriteAt;
    int rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite, &offWriteAt);
    if (   rc == VERR_BUFFER_OVERFLOW
        && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToWrite))
        rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite, &offWriteAt);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the file and do the writing.
         */
        int64_t offNew    = 0;
        size_t  cbWritten = 0;
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            rc = RTFileWriteAt(pFile->hFile, (RTFOFF)offWriteAt, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), &cbWritten);
            if (RT_SUCCESS(rc))
            {
                offNew = offWriteAt + cbWritten;

                /* RTFileWriteAt does not always change position: */
                if (!(pFile->fOpen & RTFILE_O_APPEND))
                    RTFileSeek(pFile->hFile, offNew, RTFILE_SEEK_BEGIN, NULL);
                else
                    RTFileSeek(pFile->hFile, 0, RTFILE_SEEK_END, (uint64_t *)&offNew);
            }
            else
                offNew = (int64_t)RTFileTell(pFile->hFile);
            VGSvcVerbose(5, "[File %s] Writing %p LB %RU32 @ %RU64 =>  %Rrc, cbWritten=%zu, offNew=%RI64\n",
                         pFile->pszName, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), offWriteAt, rc, cbWritten, offNew);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result back to host.
         */
        int rc2;
        if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
            rc2 = VbglR3GuestCtrlFileCbWriteOffset(pHostCtx, rc, (uint32_t)cbWritten, offNew);
        else
            rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file write at operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileSeek(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uHandle = 0;
    uint32_t uSeekMethod;
    uint64_t offSeek; /* Will be converted to int64_t. */
    int rc = VbglR3GuestCtrlFileGetSeek(pHostCtx, &uHandle, &uSeekMethod, &offSeek);
    if (RT_SUCCESS(rc))
    {
        uint64_t offActual = 0;

        /*
         * Validate and convert the seek method to IPRT speak.
         */
        static const uint8_t s_abMethods[GUEST_FILE_SEEKTYPE_END + 1] =
        {
            UINT8_MAX, RTFILE_SEEK_BEGIN, UINT8_MAX, UINT8_MAX, RTFILE_SEEK_CURRENT,
            UINT8_MAX, UINT8_MAX, UINT8_MAX, RTFILE_SEEK_END
        };
        if (   uSeekMethod < RT_ELEMENTS(s_abMethods)
            && s_abMethods[uSeekMethod] != UINT8_MAX)
        {
            /*
             * Locate the file and do the seek.
             */
            PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
            if (pFile)
            {
                rc = RTFileSeek(pFile->hFile, (int64_t)offSeek, s_abMethods[uSeekMethod], &offActual);
                VGSvcVerbose(5, "[File %s]: Seeking to offSeek=%RI64, uSeekMethodIPRT=%u, rc=%Rrc\n",
                             pFile->pszName, offSeek, s_abMethods[uSeekMethod], rc);
            }
            else
            {
                VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
                rc = VERR_NOT_FOUND;
            }
        }
        else
        {
            VGSvcError("Invalid seek method: %#x\n", uSeekMethod);
            rc = VERR_NOT_SUPPORTED;
        }

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlFileCbSeek(pHostCtx, rc, offActual);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file seek status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file seek operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileTell(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uHandle = 0;
    int rc = VbglR3GuestCtrlFileGetTell(pHostCtx, &uHandle);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the file and ask for the current position.
         */
        uint64_t offCurrent = 0;
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            offCurrent = RTFileTell(pFile->hFile);
            VGSvcVerbose(5, "[File %s]: Telling offCurrent=%RU64\n", pFile->pszName, offCurrent);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlFileCbTell(pHostCtx, rc, offCurrent);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file tell operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandleFileSetSize(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uHandle = 0;
    uint64_t cbNew = 0;
    int rc = VbglR3GuestCtrlFileGetSetSize(pHostCtx, &uHandle, &cbNew);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the file and ask for the current position.
         */
        PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
        if (pFile)
        {
            rc = RTFileSetSize(pFile->hFile, cbNew);
            VGSvcVerbose(5, "[File %s]: Changing size to %RU64 (%#RX64), rc=%Rrc\n", pFile->pszName, cbNew, cbNew, rc);
        }
        else
        {
            VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
            cbNew = UINT64_MAX;
            rc = VERR_NOT_FOUND;
        }

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlFileCbSetSize(pHostCtx, rc, cbNew);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for file tell operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


static int vgsvcGstCtrlSessionHandlePathRename(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    char     szSource[RTPATH_MAX];
    char     szDest[RTPATH_MAX];
    uint32_t fFlags = 0; /* PATHRENAME_FLAG_XXX */
    int rc = VbglR3GuestCtrlPathGetRename(pHostCtx, szSource, sizeof(szSource), szDest, sizeof(szDest), &fFlags);
    if (RT_SUCCESS(rc))
    {
        /*
         * Validate the flags (kudos for using the same as IPRT), then do the renaming.
         */
        AssertCompile(PATHRENAME_FLAG_NO_REPLACE  == RTPATHRENAME_FLAGS_NO_REPLACE);
        AssertCompile(PATHRENAME_FLAG_REPLACE     == RTPATHRENAME_FLAGS_REPLACE);
        AssertCompile(PATHRENAME_FLAG_NO_SYMLINKS == RTPATHRENAME_FLAGS_NO_SYMLINKS);
        AssertCompile(PATHRENAME_FLAG_VALID_MASK  == (RTPATHRENAME_FLAGS_NO_REPLACE | RTPATHRENAME_FLAGS_REPLACE | RTPATHRENAME_FLAGS_NO_SYMLINKS));
        if (!(fFlags & ~PATHRENAME_FLAG_VALID_MASK))
        {
            VGSvcVerbose(4, "Renaming '%s' to '%s', fFlags=%#x, rc=%Rrc\n", szSource, szDest, fFlags, rc);
            rc = RTPathRename(szSource, szDest, fFlags);
        }
        else
        {
            VGSvcError("Invalid rename flags: %#x\n", fFlags);
            rc = VERR_NOT_SUPPORTED;
        }

        /*
         * Report result back to host.
         */
        int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report renaming status, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for rename operation: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    VGSvcVerbose(5, "Renaming '%s' to '%s' returned rc=%Rrc\n", szSource, szDest, rc);
    return rc;
}


/**
 * Handles getting the user's documents directory.
 *
 * @returns VBox status code.
 * @param   pSession        Guest session.
 * @param   pHostCtx        Host context.
 */
static int vgsvcGstCtrlSessionHandlePathUserDocuments(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    int rc = VbglR3GuestCtrlPathGetUserDocuments(pHostCtx);
    if (RT_SUCCESS(rc))
    {
        /*
         * Get the path and pass it back to the host..
         */
        char szPath[RTPATH_MAX];
        rc = RTPathUserDocuments(szPath, sizeof(szPath));
#ifdef DEBUG
        VGSvcVerbose(2, "User documents is '%s', rc=%Rrc\n", szPath, rc);
#endif

        int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
                                            RT_SUCCESS(rc) ? (uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report user documents, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for user documents path request: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


/**
 * Handles shutting down / rebooting the guest OS.
 *
 * @returns VBox status code.
 * @param   pSession        Guest session.
 * @param   pHostCtx        Host context.
 */
static int vgsvcGstCtrlSessionHandleShutdown(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t fAction;
    int rc = VbglR3GuestCtrlGetShutdown(pHostCtx, &fAction);
    if (RT_SUCCESS(rc))
    {
        VGSvcVerbose(1, "Host requested to %s system ...\n", (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "reboot" : "shutdown");

        /* Reply first to the host, in order to avoid host hangs when issuing the guest shutdown. */
        rc = VbglR3GuestCtrlMsgReply(pHostCtx, VINF_SUCCESS);
        if (RT_FAILURE(rc))
        {
            VGSvcError("Failed to reply to shutdown / reboot request, rc=%Rrc\n", rc);
        }
        else
        {
            int fSystemShutdown = RTSYSTEM_SHUTDOWN_PLANNED;

            /* Translate SHUTDOWN_FLAG_ into RTSYSTEM_SHUTDOWN_ flags. */
            if (fAction & GUEST_SHUTDOWN_FLAG_REBOOT)
                fSystemShutdown |= RTSYSTEM_SHUTDOWN_REBOOT;
            else /* SHUTDOWN_FLAG_POWER_OFF */
                fSystemShutdown |= RTSYSTEM_SHUTDOWN_POWER_OFF;

            if (fAction & GUEST_SHUTDOWN_FLAG_FORCE)
                fSystemShutdown |= RTSYSTEM_SHUTDOWN_FORCE;

            rc = RTSystemShutdown(0 /*cMsDelay*/, fSystemShutdown, "VBoxService");
            if (RT_FAILURE(rc))
                VGSvcError("%s system failed with %Rrc\n",
                           (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "Rebooting" : "Shutting down", rc);
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for shutdown / reboot request: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }

    return rc;
}


/**
 * Handles getting the user's home directory.
 *
 * @returns VBox status code.
 * @param   pSession        Guest session.
 * @param   pHostCtx        Host context.
 */
static int vgsvcGstCtrlSessionHandlePathUserHome(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    int rc = VbglR3GuestCtrlPathGetUserHome(pHostCtx);
    if (RT_SUCCESS(rc))
    {
        /*
         * Get the path and pass it back to the host..
         */
        char szPath[RTPATH_MAX];
        rc = RTPathUserHome(szPath, sizeof(szPath));

#ifdef DEBUG
        VGSvcVerbose(2, "User home is '%s', rc=%Rrc\n", szPath, rc);
#endif
        /* Report back in any case. */
        int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
                                            RT_SUCCESS(rc) ?(uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Failed to report user home, rc=%Rrc\n", rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for user home directory path request: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}

/**
 * Handles starting a guest processes.
 *
 * @returns VBox status code.
 * @param   pSession        Guest session.
 * @param   pHostCtx        Host context.
 */
static int vgsvcGstCtrlSessionHandleProcExec(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /* Initialize maximum environment block size -- needed as input
     * parameter to retrieve the stuff from the host. On output this then
     * will contain the actual block size. */
    PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo;
    int rc = VbglR3GuestCtrlProcGetStart(pHostCtx, &pStartupInfo);
    if (RT_SUCCESS(rc))
    {
        VGSvcVerbose(3, "Request to start process szCmd=%s, fFlags=0x%x, szArgs=%s, szEnv=%s, uTimeout=%RU32\n",
                     pStartupInfo->pszCmd, pStartupInfo->fFlags,
                     pStartupInfo->cArgs    ? pStartupInfo->pszArgs : "<None>",
                     pStartupInfo->cEnvVars ? pStartupInfo->pszEnv  : "<None>",
                     pStartupInfo->uTimeLimitMS);

        bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
        rc = VGSvcGstCtrlSessionProcessStartAllowed(pSession, &fStartAllowed);
        if (RT_SUCCESS(rc))
        {
            vgsvcGstCtrlSessionCleanupProcesses(pSession);

            if (fStartAllowed)
                rc = VGSvcGstCtrlProcessStart(pSession, pStartupInfo, pHostCtx->uContextID);
            else
                rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
        }

        /* We're responsible for signaling errors to the host (it will wait for ever otherwise). */
        if (RT_FAILURE(rc))
        {
            VGSvcError("Starting process failed with rc=%Rrc, protocol=%RU32, parameters=%RU32\n",
                       rc, pHostCtx->uProtocol, pHostCtx->uNumParms);
            int rc2 = VbglR3GuestCtrlProcCbStatus(pHostCtx, 0 /*nil-PID*/, PROC_STS_ERROR, rc, NULL /*pvData*/, 0 /*cbData*/);
            if (RT_FAILURE(rc2))
                VGSvcError("Error sending start process status to host, rc=%Rrc\n", rc2);
        }

        VbglR3GuestCtrlProcStartupInfoFree(pStartupInfo);
        pStartupInfo = NULL;
    }
    else
    {
        VGSvcError("Failed to retrieve parameters for process start: %Rrc (cParms=%u)\n", rc, pHostCtx->uNumParms);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }

    return rc;
}


/**
 * Sends stdin input to a specific guest process.
 *
 * @returns VBox status code.
 * @param   pSession            The session which is in charge.
 * @param   pHostCtx            The host context to use.
 * @param   ppvScratchBuf       The scratch buffer, we may grow it.
 * @param   pcbScratchBuf       The scratch buffer size for retrieving the input
 *                              data.
 */
static int vgsvcGstCtrlSessionHandleProcInput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
                                              void **ppvScratchBuf, uint32_t *pcbScratchBuf)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the data from the host.
     */
    uint32_t uPID;
    uint32_t fFlags;
    uint32_t cbInput;
    int rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
    if (   rc == VERR_BUFFER_OVERFLOW
        && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbInput))
        rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
    if (RT_SUCCESS(rc))
    {
        if (fFlags & GUEST_PROC_IN_FLAG_EOF)
            VGSvcVerbose(4, "Got last process input block for PID=%RU32 (%RU32 bytes) ...\n", uPID, cbInput);

        /*
         * Locate the process and feed it.
         */
        PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
        if (pProcess)
        {
            rc = VGSvcGstCtrlProcessHandleInput(pProcess, pHostCtx, RT_BOOL(fFlags & GUEST_PROC_IN_FLAG_EOF),
                                                *ppvScratchBuf, RT_MIN(cbInput, *pcbScratchBuf));
            if (RT_FAILURE(rc))
                VGSvcError("Error handling input message for PID=%RU32, rc=%Rrc\n", uPID, rc);
            VGSvcGstCtrlProcessRelease(pProcess);
        }
        else
        {
            VGSvcError("Could not find PID %u for feeding %u bytes to it.\n", uPID, cbInput);
            rc = VERR_PROCESS_NOT_FOUND;
            VbglR3GuestCtrlProcCbStatusInput(pHostCtx, uPID, INPUT_STS_ERROR, rc, 0);
        }
    }
    else
    {
        VGSvcError("Failed to retrieve parameters for process input: %Rrc (scratch %u bytes)\n", rc, *pcbScratchBuf);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }

    VGSvcVerbose(6, "Feeding input to PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
    return rc;
}


/**
 * Gets stdout/stderr output of a specific guest process.
 *
 * @returns VBox status code.
 * @param   pSession            The session which is in charge.
 * @param   pHostCtx            The host context to use.
 */
static int vgsvcGstCtrlSessionHandleProcOutput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uPID;
    uint32_t uHandleID;
    uint32_t fFlags;
    int rc = VbglR3GuestCtrlProcGetOutput(pHostCtx, &uPID, &uHandleID, &fFlags);
#ifdef DEBUG_andy
    VGSvcVerbose(4, "Getting output for PID=%RU32, CID=%RU32, uHandleID=%RU32, fFlags=%RU32\n",
                 uPID, pHostCtx->uContextID, uHandleID, fFlags);
#endif
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the process and hand it the output request.
         */
        PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
        if (pProcess)
        {
            rc = VGSvcGstCtrlProcessHandleOutput(pProcess, pHostCtx, uHandleID, _64K /* cbToRead */, fFlags);
            if (RT_FAILURE(rc))
                VGSvcError("Error getting output for PID=%RU32, rc=%Rrc\n", uPID, rc);
            VGSvcGstCtrlProcessRelease(pProcess);
        }
        else
        {
            VGSvcError("Could not find PID %u for draining handle %u (%#x).\n", uPID, uHandleID, uHandleID);
            rc = VERR_PROCESS_NOT_FOUND;
/** @todo r=bird:
 *
 *  No way to report status status code for output requests?
 *
 */
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for process output request: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }

#ifdef DEBUG_andy
    VGSvcVerbose(4, "Getting output for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
#endif
    return rc;
}


/**
 * Tells a guest process to terminate.
 *
 * @returns VBox status code.
 * @param   pSession            The session which is in charge.
 * @param   pHostCtx            The host context to use.
 */
static int vgsvcGstCtrlSessionHandleProcTerminate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uPID;
    int rc = VbglR3GuestCtrlProcGetTerminate(pHostCtx, &uPID);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the process and terminate it.
         */
        PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
        if (pProcess)
        {
            rc = VGSvcGstCtrlProcessHandleTerm(pProcess);
            if (RT_FAILURE(rc))
                VGSvcError("Error terminating PID=%RU32, rc=%Rrc\n", uPID, rc);

            VGSvcGstCtrlProcessRelease(pProcess);
        }
        else
        {
            VGSvcError("Could not find PID %u for termination.\n", uPID);
            rc = VERR_PROCESS_NOT_FOUND;
        }
    }
    else
    {
        VGSvcError("Error fetching parameters for process termination request: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
#ifdef DEBUG_andy
    VGSvcVerbose(4, "Terminating PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
#endif
    return rc;
}


static int vgsvcGstCtrlSessionHandleProcWaitFor(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);

    /*
     * Retrieve the request.
     */
    uint32_t uPID;
    uint32_t uWaitFlags;
    uint32_t uTimeoutMS;
    int rc = VbglR3GuestCtrlProcGetWaitFor(pHostCtx, &uPID, &uWaitFlags, &uTimeoutMS);
    if (RT_SUCCESS(rc))
    {
        /*
         * Locate the process and the realize that this call makes no sense
         * since we'll notify the host when a process terminates anyway and
         * hopefully don't need any additional encouragement.
         */
        PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
        if (pProcess)
        {
            rc = VERR_NOT_IMPLEMENTED; /** @todo */
            VGSvcGstCtrlProcessRelease(pProcess);
        }
        else
            rc = VERR_NOT_FOUND;
    }
    else
    {
        VGSvcError("Error fetching parameters for process wait request: %Rrc\n", rc);
        VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
    }
    return rc;
}


int VGSvcGstCtrlSessionHandler(PVBOXSERVICECTRLSESSION pSession, uint32_t uMsg, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
                               void **ppvScratchBuf, uint32_t *pcbScratchBuf, volatile bool *pfShutdown)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(*ppvScratchBuf, VERR_INVALID_POINTER);
    AssertPtrReturn(pfShutdown, VERR_INVALID_POINTER);


    /*
     * Only anonymous sessions (that is, sessions which run with local
     * service privileges) or spawned session processes can do certain
     * operations.
     */
    bool const fImpersonated = RT_BOOL(pSession->fFlags & (  VBOXSERVICECTRLSESSION_FLAG_SPAWN
                                                           | VBOXSERVICECTRLSESSION_FLAG_ANONYMOUS));
    int rc = VERR_NOT_SUPPORTED; /* Play safe by default. */

    switch (uMsg)
    {
        case HOST_MSG_SESSION_CLOSE:
            /* Shutdown (this spawn). */
            rc = VGSvcGstCtrlSessionClose(pSession);
            *pfShutdown = true; /* Shutdown in any case. */
            break;

        case HOST_MSG_DIR_REMOVE:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleDirRemove(pSession, pHostCtx);
            break;

        case HOST_MSG_EXEC_CMD:
            rc = vgsvcGstCtrlSessionHandleProcExec(pSession, pHostCtx);
            break;

        case HOST_MSG_EXEC_SET_INPUT:
            rc = vgsvcGstCtrlSessionHandleProcInput(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
            break;

        case HOST_MSG_EXEC_GET_OUTPUT:
            rc = vgsvcGstCtrlSessionHandleProcOutput(pSession, pHostCtx);
            break;

        case HOST_MSG_EXEC_TERMINATE:
            rc = vgsvcGstCtrlSessionHandleProcTerminate(pSession, pHostCtx);
            break;

        case HOST_MSG_EXEC_WAIT_FOR:
            rc = vgsvcGstCtrlSessionHandleProcWaitFor(pSession, pHostCtx);
            break;

        case HOST_MSG_FILE_OPEN:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileOpen(pSession, pHostCtx);
            break;

        case HOST_MSG_FILE_CLOSE:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileClose(pSession, pHostCtx);
            break;

        case HOST_MSG_FILE_READ:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileRead(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
            break;

        case HOST_MSG_FILE_READ_AT:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileReadAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
            break;

        case HOST_MSG_FILE_WRITE:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileWrite(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
            break;

        case HOST_MSG_FILE_WRITE_AT:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileWriteAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
            break;

        case HOST_MSG_FILE_SEEK:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileSeek(pSession, pHostCtx);
            break;

        case HOST_MSG_FILE_TELL:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileTell(pSession, pHostCtx);
            break;

        case HOST_MSG_FILE_SET_SIZE:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandleFileSetSize(pSession, pHostCtx);
            break;

        case HOST_MSG_PATH_RENAME:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandlePathRename(pSession, pHostCtx);
            break;

        case HOST_MSG_PATH_USER_DOCUMENTS:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandlePathUserDocuments(pSession, pHostCtx);
            break;

        case HOST_MSG_PATH_USER_HOME:
            if (fImpersonated)
                rc = vgsvcGstCtrlSessionHandlePathUserHome(pSession, pHostCtx);
            break;

        case HOST_MSG_SHUTDOWN:
            rc = vgsvcGstCtrlSessionHandleShutdown(pSession, pHostCtx);
            break;

        default: /* Not supported, see next code block. */
            break;
    }
    if (RT_SUCCESS(rc))
    { /* likely */ }
    else if (rc != VERR_NOT_SUPPORTED) /* Note: Reply to host must must be sent by above handler. */
        VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);
    else
    {
        /* We must skip and notify host here as best we can... */
        VGSvcVerbose(1, "Unsupported message (uMsg=%RU32, cParms=%RU32) from host, skipping\n", uMsg, pHostCtx->uNumParms);
        if (VbglR3GuestCtrlSupportsOptimizations(pHostCtx->uClientID))
            VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, VERR_NOT_SUPPORTED, uMsg);
        else
            VbglR3GuestCtrlMsgSkipOld(pHostCtx->uClientID);
        rc = VINF_SUCCESS;
    }

    if (RT_FAILURE(rc))
        VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);

    return rc;
}


/**
 * Thread main routine for a spawned guest session process.
 *
 * This thread runs in the main executable to control the spawned session process.
 *
 * @returns VBox status code.
 * @param   hThreadSelf     Thread handle.
 * @param   pvUser          Pointer to a VBOXSERVICECTRLSESSIONTHREAD structure.
 *
 */
static DECLCALLBACK(int) vgsvcGstCtrlSessionThread(RTTHREAD hThreadSelf, void *pvUser)
{
    PVBOXSERVICECTRLSESSIONTHREAD pThread = (PVBOXSERVICECTRLSESSIONTHREAD)pvUser;
    AssertPtrReturn(pThread, VERR_INVALID_POINTER);

    uint32_t const idSession = pThread->pStartupInfo->uSessionID;
    uint32_t const idClient  = g_idControlSvcClient;
    VGSvcVerbose(3, "Session ID=%RU32 thread running\n", idSession);

    /* Let caller know that we're done initializing, regardless of the result. */
    int rc2 = RTThreadUserSignal(hThreadSelf);
    AssertRC(rc2);

    /*
     * Wait for the child process to stop or the shutdown flag to be signalled.
     */
    RTPROCSTATUS    ProcessStatus       = { 0, RTPROCEXITREASON_NORMAL };
    bool            fProcessAlive       = true;
    bool            fSessionCancelled   = VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient);
    uint32_t        cMsShutdownTimeout  = 30 * 1000; /** @todo Make this configurable. Later. */
    uint64_t        msShutdownStart     = 0;
    uint64_t const  msStart             = RTTimeMilliTS();
    size_t          offSecretKey        = 0;
    int             rcWait;
    for (;;)
    {
        /* Secret key feeding. */
        if (offSecretKey < sizeof(pThread->abKey))
        {
            size_t cbWritten = 0;
            rc2 = RTPipeWrite(pThread->hKeyPipe, &pThread->abKey[offSecretKey], sizeof(pThread->abKey) - offSecretKey, &cbWritten);
            if (RT_SUCCESS(rc2))
                offSecretKey += cbWritten;
        }

        /* Poll child process status. */
        rcWait = RTProcWaitNoResume(pThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
        if (   rcWait == VINF_SUCCESS
            || rcWait == VERR_PROCESS_NOT_FOUND)
        {
            fProcessAlive = false;
            break;
        }
        AssertMsgBreak(rcWait == VERR_PROCESS_RUNNING || rcWait == VERR_INTERRUPTED,
                       ("Got unexpected rc=%Rrc while waiting for session process termination\n", rcWait));

        /* Shutting down? */
        if (ASMAtomicReadBool(&pThread->fShutdown))
        {
            if (!msShutdownStart)
            {
                VGSvcVerbose(3, "Notifying guest session process (PID=%RU32, session ID=%RU32) ...\n",
                             pThread->hProcess, idSession);

                VBGLR3GUESTCTRLCMDCTX hostCtx =
                {
                    /* .idClient  = */  idClient,
                    /* .idContext = */  VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
                    /* .uProtocol = */  pThread->pStartupInfo->uProtocol,
                    /* .cParams   = */  2
                };
                rc2 = VbglR3GuestCtrlSessionClose(&hostCtx, 0 /* fFlags */);
                if (RT_FAILURE(rc2))
                {
                    VGSvcError("Unable to notify guest session process (PID=%RU32, session ID=%RU32), rc=%Rrc\n",
                               pThread->hProcess, idSession, rc2);

                    if (rc2 == VERR_NOT_SUPPORTED)
                    {
                        /* Terminate guest session process in case it's not supported by a too old host. */
                        rc2 = RTProcTerminate(pThread->hProcess);
                        VGSvcVerbose(3, "Terminating guest session process (PID=%RU32) ended with rc=%Rrc\n",
                                     pThread->hProcess, rc2);
                    }
                    break;
                }

                VGSvcVerbose(3, "Guest session ID=%RU32 thread was asked to terminate, waiting for session process to exit (%RU32 ms timeout) ...\n",
                             idSession, cMsShutdownTimeout);
                msShutdownStart = RTTimeMilliTS();
                continue; /* Don't waste time on waiting. */
            }
            if (RTTimeMilliTS() - msShutdownStart > cMsShutdownTimeout)
            {
                 VGSvcVerbose(3, "Guest session ID=%RU32 process did not shut down within time\n", idSession);
                 break;
            }
        }

        /* Cancel the prepared session stuff after 30 seconds. */
        if (  !fSessionCancelled
            && RTTimeMilliTS() - msStart >= 30000)
        {
            VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
            fSessionCancelled = true;
        }

/** @todo r=bird: This 100ms sleep is _extremely_ sucky! */
        RTThreadSleep(100); /* Wait a bit. */
    }

    if (!fSessionCancelled)
        VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);

    if (!fProcessAlive)
    {
        VGSvcVerbose(2, "Guest session process (ID=%RU32) terminated with rc=%Rrc, reason=%d, status=%d\n",
                     idSession, rcWait, ProcessStatus.enmReason, ProcessStatus.iStatus);
        if (ProcessStatus.iStatus == RTEXITCODE_INIT)
        {
            VGSvcError("Guest session process (ID=%RU32) failed to initialize. Here some hints:\n", idSession);
            VGSvcError("- Is logging enabled and the output directory is read-only by the guest session user?\n");
            /** @todo Add more here. */
        }
    }

    uint32_t uSessionStatus = GUEST_SESSION_NOTIFYTYPE_UNDEFINED;
    int32_t  iSessionResult = VINF_SUCCESS;

    if (fProcessAlive)
    {
        for (int i = 0; i < 3; i++)
        {
            if (i)
                RTThreadSleep(3000);

            VGSvcVerbose(2, "Guest session ID=%RU32 process still alive, killing attempt %d/3\n", idSession, i + 1);

            rc2 = RTProcTerminate(pThread->hProcess);
            if (RT_SUCCESS(rc2))
                break;
        }

        VGSvcVerbose(2, "Guest session ID=%RU32 process termination resulted in rc=%Rrc\n", idSession, rc2);
        uSessionStatus = RT_SUCCESS(rc2) ? GUEST_SESSION_NOTIFYTYPE_TOK : GUEST_SESSION_NOTIFYTYPE_TOA;
    }
    else if (RT_SUCCESS(rcWait))
    {
        switch (ProcessStatus.enmReason)
        {
            case RTPROCEXITREASON_NORMAL:
                uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
                iSessionResult = ProcessStatus.iStatus; /* Report back the session's exit code. */
                break;

            case RTPROCEXITREASON_ABEND:
                uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
                /* iSessionResult is undefined (0). */
                break;

            case RTPROCEXITREASON_SIGNAL:
                uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TES;
                iSessionResult = ProcessStatus.iStatus; /* Report back the signal number. */
                break;

            default:
                AssertMsgFailed(("Unhandled process termination reason (%d)\n", ProcessStatus.enmReason));
                uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
                break;
        }
    }
    else
    {
        /* If we didn't find the guest process anymore, just assume it terminated normally. */
        uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
    }

    /* Make sure to set stopped state before we let the host know. */
    ASMAtomicWriteBool(&pThread->fStopped, true);

    /* Report final status, regardless if we failed to wait above, so that the host knows what's going on. */
    VGSvcVerbose(3, "Reporting final status %RU32 of session ID=%RU32\n", uSessionStatus, idSession);
    Assert(uSessionStatus != GUEST_SESSION_NOTIFYTYPE_UNDEFINED);

    VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
                                  0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
    rc2 = VbglR3GuestCtrlSessionNotify(&ctx, uSessionStatus, iSessionResult);
    if (RT_FAILURE(rc2))
        VGSvcError("Reporting final status of session ID=%RU32 failed with rc=%Rrc\n", idSession, rc2);

    VGSvcVerbose(3, "Thread for session ID=%RU32 ended with sessionStatus=%#x (%RU32), sessionRc=%#x (%Rrc)\n",
                 idSession, uSessionStatus, uSessionStatus, iSessionResult, iSessionResult);

    return VINF_SUCCESS;
}

/**
 * Reads the secret key the parent VBoxService instance passed us and pass it
 * along as a authentication token to the host service.
 *
 * For older hosts, this sets up the message filtering.
 *
 * @returns VBox status code.
 * @param   idClient        The HGCM client ID.
 * @param   idSession       The session ID.
 */
static int vgsvcGstCtrlSessionReadKeyAndAccept(uint32_t idClient, uint32_t idSession)
{
    /*
     * Read it.
     */
    RTHANDLE Handle;
    int rc = RTHandleGetStandard(RTHANDLESTD_INPUT, true /*fLeaveOpen*/, &Handle);
    if (RT_SUCCESS(rc))
    {
        if (Handle.enmType == RTHANDLETYPE_PIPE)
        {
            uint8_t abSecretKey[RT_SIZEOFMEMB(VBOXSERVICECTRLSESSIONTHREAD, abKey)];
            rc = RTPipeReadBlocking(Handle.u.hPipe, abSecretKey, sizeof(abSecretKey), NULL);
            if (RT_SUCCESS(rc))
            {
                VGSvcVerbose(3, "Got secret key from standard input.\n");

                /*
                 * Do the accepting, if appropriate.
                 */
                if (g_fControlSupportsOptimizations)
                {
                    rc = VbglR3GuestCtrlSessionAccept(idClient, idSession, abSecretKey, sizeof(abSecretKey));
                    if (RT_SUCCESS(rc))
                        VGSvcVerbose(3, "Session %u accepted (client ID %u)\n", idClient, idSession);
                    else
                        VGSvcError("Failed to accept session %u (client ID %u): %Rrc\n", idClient, idSession, rc);
                }
                else
                {
                    /* For legacy hosts, we do the filtering thingy. */
                    rc = VbglR3GuestCtrlMsgFilterSet(idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
                                                     VBOX_GUESTCTRL_FILTER_BY_SESSION(idSession), 0);
                    if (RT_SUCCESS(rc))
                        VGSvcVerbose(3, "Session %u filtering successfully enabled\n", idSession);
                    else
                        VGSvcError("Failed to set session filter: %Rrc\n", rc);
                }
            }
            else
                VGSvcError("Error reading secret key from standard input: %Rrc\n", rc);
        }
        else
        {
            VGSvcError("Standard input is not a pipe!\n");
            rc = VERR_INVALID_HANDLE;
        }
        RTHandleClose(&Handle);
    }
    else
        VGSvcError("RTHandleGetStandard failed on standard input: %Rrc\n", rc);
    return rc;
}

/**
 * Invalidates a guest session by updating all it's internal parameters like host features and stuff.
 *
 * @param   pSession            Session to invalidate.
 * @param   idClient            Client ID to use.
 */
static void vgsvcGstCtrlSessionInvalidate(PVBOXSERVICECTRLSESSION pSession, uint32_t idClient)
{
    RT_NOREF(pSession);

    VGSvcVerbose(1, "Invalidating session %RU32 (client ID=%RU32)\n", idClient, pSession->StartupInfo.uSessionID);

    int rc2 = VbglR3GuestCtrlQueryFeatures(idClient, &g_fControlHostFeatures0);
    if (RT_SUCCESS(rc2)) /* Querying host features is not fatal -- do not use rc here. */
    {
        VGSvcVerbose(1, "g_fControlHostFeatures0=%#x\n", g_fControlHostFeatures0);
    }
    else
        VGSvcVerbose(1, "Querying host features failed with %Rrc\n", rc2);
}

/**
 * Main message handler for the guest control session process.
 *
 * @returns exit code.
 * @param   pSession    Pointer to g_Session.
 * @thread  main.
 */
static RTEXITCODE vgsvcGstCtrlSessionSpawnWorker(PVBOXSERVICECTRLSESSION pSession)
{
    AssertPtrReturn(pSession, RTEXITCODE_FAILURE);
    VGSvcVerbose(0, "Hi, this is guest session ID=%RU32\n", pSession->StartupInfo.uSessionID);

    /*
     * Connect to the host service.
     */
    uint32_t idClient;
    int rc = VbglR3GuestCtrlConnect(&idClient);
    if (RT_FAILURE(rc))
        return VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
    g_fControlSupportsOptimizations = VbglR3GuestCtrlSupportsOptimizations(idClient);
    g_idControlSvcClient            = idClient;

    VGSvcVerbose(1, "Using client ID=%RU32\n", idClient);

    vgsvcGstCtrlSessionInvalidate(pSession, idClient);

    rc = vgsvcGstCtrlSessionReadKeyAndAccept(idClient, pSession->StartupInfo.uSessionID);
    if (RT_SUCCESS(rc))
    {
        /*
         * Report started status.
         * If session status cannot be posted to the host for some reason, bail out.
         */
        VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID),
                                      0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
        rc = VbglR3GuestCtrlSessionNotify(&ctx, GUEST_SESSION_NOTIFYTYPE_STARTED, VINF_SUCCESS);
        if (RT_SUCCESS(rc))
        {
            /*
             * Allocate a scratch buffer for messages which also send payload data with them.
             * This buffer may grow if the host sends us larger chunks of data.
             */
            uint32_t cbScratchBuf = _64K;
            void    *pvScratchBuf = RTMemAlloc(cbScratchBuf);
            if (pvScratchBuf)
            {
                int cFailedMsgPeeks = 0;

                /*
                 * Message processing loop.
                 */
                VBGLR3GUESTCTRLCMDCTX CtxHost = { idClient, 0 /* Context ID */, pSession->StartupInfo.uProtocol, 0 };
                for (;;)
                {
                    VGSvcVerbose(3, "Waiting for host msg ...\n");
                    uint32_t uMsg = 0;
                    rc = VbglR3GuestCtrlMsgPeekWait(idClient, &uMsg, &CtxHost.uNumParms, NULL);
                    if (RT_SUCCESS(rc))
                    {
                        VGSvcVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved (%Rrc)\n", uMsg, CtxHost.uNumParms, rc);

                        /*
                         * Pass it on to the session handler.
                         * Note! Only when handling HOST_SESSION_CLOSE is the rc used.
                         */
                        bool fShutdown = false;
                        rc = VGSvcGstCtrlSessionHandler(pSession, uMsg, &CtxHost, &pvScratchBuf, &cbScratchBuf, &fShutdown);
                        if (fShutdown)
                            break;

                        cFailedMsgPeeks = 0;

                        /* Let others run (guests are often single CPU) ... */
                        RTThreadYield();
                    }
                    /*
                     * Handle restore notification from host.  All the context IDs (sessions,
                     * files, proceses, etc) are invalidated by a VM restore and must be closed.
                     */
                    else if (rc == VERR_VM_RESTORED)
                    {
                        VGSvcVerbose(1, "The VM session ID changed (i.e. restored), closing stale session %RU32\n",
                                     pSession->StartupInfo.uSessionID);

                        /* We currently don't serialize guest sessions, guest processes and other guest control objects
                         * within saved states. So just close this session and report success to the parent process.
                         *
                         * Note: Not notifying the host here is intentional, as it wouldn't have any information
                         *       about what to do with it.
                         */
                        rc = VINF_SUCCESS; /* Report success as exit code. */
                        break;
                    }
                    else
                    {
                        VGSvcVerbose(1, "Getting host message failed with %Rrc\n", rc);

                        if (cFailedMsgPeeks++ == 3)
                            break;

                        RTThreadSleep(3 * RT_MS_1SEC);

                        /** @todo Shouldn't we have a plan for handling connection loss and such? */
                    }
                }

                /*
                 * Shutdown.
                 */
                RTMemFree(pvScratchBuf);
            }
            else
                rc = VERR_NO_MEMORY;

            VGSvcVerbose(0, "Session %RU32 ended\n", pSession->StartupInfo.uSessionID);
        }
        else
            VGSvcError("Reporting session ID=%RU32 started status failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
    }
    else
        VGSvcError("Setting message filterAdd=0x%x failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);

    VGSvcVerbose(3, "Disconnecting client ID=%RU32 ...\n", idClient);
    VbglR3GuestCtrlDisconnect(idClient);
    g_idControlSvcClient = 0;

    VGSvcVerbose(3, "Session worker returned with rc=%Rrc\n", rc);
    return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}


/**
 * Finds a (formerly) started guest process given by its PID and increases its
 * reference count.
 *
 * Must be decreased by the caller with VGSvcGstCtrlProcessRelease().
 *
 * @returns Guest process if found, otherwise NULL.
 * @param   pSession    Pointer to guest session where to search process in.
 * @param   uPID        PID to search for.
 *
 * @note    This does *not lock the process!
 */
PVBOXSERVICECTRLPROCESS VGSvcGstCtrlSessionRetainProcess(PVBOXSERVICECTRLSESSION pSession, uint32_t uPID)
{
    AssertPtrReturn(pSession, NULL);

    PVBOXSERVICECTRLPROCESS pProcess = NULL;
    int rc = RTCritSectEnter(&pSession->CritSect);
    if (RT_SUCCESS(rc))
    {
        PVBOXSERVICECTRLPROCESS pCurProcess;
        RTListForEach(&pSession->lstProcesses, pCurProcess, VBOXSERVICECTRLPROCESS, Node)
        {
            if (pCurProcess->uPID == uPID)
            {
                rc = RTCritSectEnter(&pCurProcess->CritSect);
                if (RT_SUCCESS(rc))
                {
                    pCurProcess->cRefs++;
                    rc = RTCritSectLeave(&pCurProcess->CritSect);
                    AssertRC(rc);
                }

                if (RT_SUCCESS(rc))
                    pProcess = pCurProcess;
                break;
            }
        }

        rc = RTCritSectLeave(&pSession->CritSect);
        AssertRC(rc);
    }

    return pProcess;
}


int VGSvcGstCtrlSessionClose(PVBOXSERVICECTRLSESSION pSession)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);

    VGSvcVerbose(0, "Session %RU32 is about to close ...\n", pSession->StartupInfo.uSessionID);

    int rc = RTCritSectEnter(&pSession->CritSect);
    if (RT_SUCCESS(rc))
    {
        /*
         * Close all guest processes.
         */
        VGSvcVerbose(0, "Stopping all guest processes ...\n");

        /* Signal all guest processes in the active list that we want to shutdown. */
        PVBOXSERVICECTRLPROCESS pProcess;
        RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
            VGSvcGstCtrlProcessStop(pProcess);

        VGSvcVerbose(1, "%RU32 guest processes were signalled to stop\n", pSession->cProcesses);

        /* Wait for all active threads to shutdown and destroy the active thread list. */
        PVBOXSERVICECTRLPROCESS pProcessNext;
        RTListForEachSafe(&pSession->lstProcesses, pProcess, pProcessNext, VBOXSERVICECTRLPROCESS, Node)
        {
            int rc3 = RTCritSectLeave(&pSession->CritSect);
            AssertRC(rc3);

            int rc2 = VGSvcGstCtrlProcessWait(pProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);

            rc3 = RTCritSectEnter(&pSession->CritSect);
            AssertRC(rc3);

            if (RT_SUCCESS(rc2))
            {
                rc2 = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
                if (RT_SUCCESS(rc2))
                {
                    VGSvcGstCtrlProcessFree(pProcess);
                    pProcess = NULL;
                }
            }
        }

        AssertMsg(pSession->cProcesses == 0,
                  ("Session process list still contains %RU32 when it should not\n", pSession->cProcesses));
        AssertMsg(RTListIsEmpty(&pSession->lstProcesses),
                  ("Session process list is not empty when it should\n"));

        /*
         * Close all left guest files.
         */
        VGSvcVerbose(0, "Closing all guest files ...\n");

        PVBOXSERVICECTRLFILE pFile, pFileNext;
        RTListForEachSafe(&pSession->lstFiles, pFile, pFileNext, VBOXSERVICECTRLFILE, Node)
        {
            int rc2 = vgsvcGstCtrlSessionFileFree(pFile);
            if (RT_FAILURE(rc2))
            {
                VGSvcError("Unable to close file '%s'; rc=%Rrc\n", pFile->pszName, rc2);
                if (RT_SUCCESS(rc))
                    rc = rc2;
                /* Keep going. */
            }

            pFile = NULL; /* To make it obvious. */
        }

        AssertMsg(pSession->cFiles == 0,
                  ("Session file list still contains %RU32 when it should not\n", pSession->cFiles));
        AssertMsg(RTListIsEmpty(&pSession->lstFiles),
                  ("Session file list is not empty when it should\n"));

        int rc2 = RTCritSectLeave(&pSession->CritSect);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }

    return rc;
}


int VGSvcGstCtrlSessionDestroy(PVBOXSERVICECTRLSESSION pSession)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);

    int rc = VGSvcGstCtrlSessionClose(pSession);

    /* Destroy critical section. */
    RTCritSectDelete(&pSession->CritSect);

    return rc;
}


int VGSvcGstCtrlSessionInit(PVBOXSERVICECTRLSESSION pSession, uint32_t fFlags)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);

    RTListInit(&pSession->lstProcesses);
    RTListInit(&pSession->lstFiles);

    pSession->cProcesses = 0;
    pSession->cFiles     = 0;

    pSession->fFlags = fFlags;

    /* Init critical section for protecting the thread lists. */
    int rc = RTCritSectInit(&pSession->CritSect);
    AssertRC(rc);

    return rc;
}


/**
 * Adds a guest process to a session's process list.
 *
 * @return  VBox status code.
 * @param   pSession                Guest session to add process to.
 * @param   pProcess                Guest process to add.
 */
int VGSvcGstCtrlSessionProcessAdd(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pProcess, VERR_INVALID_POINTER);

    int rc = RTCritSectEnter(&pSession->CritSect);
    if (RT_SUCCESS(rc))
    {
        VGSvcVerbose(3, "Adding process (PID %RU32) to session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);

        /* Add process to session list. */
        RTListAppend(&pSession->lstProcesses, &pProcess->Node);

        pSession->cProcesses++;
        VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
                     pSession->StartupInfo.uSessionID, pSession->cProcesses);

        int rc2 = RTCritSectLeave(&pSession->CritSect);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }

    return VINF_SUCCESS;
}

/**
 * Removes a guest process from a session's process list.
 * Internal version, does not do locking.
 *
 * @return  VBox status code.
 * @param   pSession                Guest session to remove process from.
 * @param   pProcess                Guest process to remove.
 */
static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
{
    VGSvcVerbose(3, "Removing process (PID %RU32) from session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
    AssertReturn(pProcess->cRefs == 0, VERR_WRONG_ORDER);

    RTListNodeRemove(&pProcess->Node);

    AssertReturn(pSession->cProcesses, VERR_WRONG_ORDER);
    pSession->cProcesses--;
    VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
                 pSession->StartupInfo.uSessionID, pSession->cProcesses);

    return VINF_SUCCESS;
}

/**
 * Removes a guest process from a session's process list.
 *
 * @return  VBox status code.
 * @param   pSession                Guest session to remove process from.
 * @param   pProcess                Guest process to remove.
 */
int VGSvcGstCtrlSessionProcessRemove(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pProcess, VERR_INVALID_POINTER);

    int rc = RTCritSectEnter(&pSession->CritSect);
    if (RT_SUCCESS(rc))
    {
        rc = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);

        int rc2 = RTCritSectLeave(&pSession->CritSect);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }

    return rc;
}


/**
 * Determines whether starting a new guest process according to the
 * maximum number of concurrent guest processes defined is allowed or not.
 *
 * @return  VBox status code.
 * @param   pSession            The guest session.
 * @param   pfAllowed           \c True if starting (another) guest process
 *                              is allowed, \c false if not.
 */
int VGSvcGstCtrlSessionProcessStartAllowed(const PVBOXSERVICECTRLSESSION pSession, bool *pfAllowed)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);
    AssertPtrReturn(pfAllowed, VERR_INVALID_POINTER);

    int rc = RTCritSectEnter(&pSession->CritSect);
    if (RT_SUCCESS(rc))
    {
        /*
         * Check if we're respecting our memory policy by checking
         * how many guest processes are started and served already.
         */
        bool fLimitReached = false;
        if (pSession->uProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
        {
            VGSvcVerbose(3, "Maximum kept guest processes set to %RU32, acurrent=%RU32\n",
                         pSession->uProcsMaxKept, pSession->cProcesses);

            int32_t iProcsLeft = (pSession->uProcsMaxKept - pSession->cProcesses - 1);
            if (iProcsLeft < 0)
            {
                VGSvcVerbose(3, "Maximum running guest processes reached (%RU32)\n", pSession->uProcsMaxKept);
                fLimitReached = true;
            }
        }

        *pfAllowed = !fLimitReached;

        int rc2 = RTCritSectLeave(&pSession->CritSect);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }

    return rc;
}


/**
 * Cleans up stopped and no longer used processes.
 *
 * This will free and remove processes from the session's process list.
 *
 * @returns VBox status code.
 * @param   pSession            Session to clean up processes for.
 */
static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession)
{
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);

    VGSvcVerbose(3, "Cleaning up stopped processes for session %RU32 ...\n", pSession->StartupInfo.uSessionID);

    int rc2 = RTCritSectEnter(&pSession->CritSect);
    AssertRC(rc2);

    int rc = VINF_SUCCESS;

    PVBOXSERVICECTRLPROCESS pCurProcess, pNextProcess;
    RTListForEachSafe(&pSession->lstProcesses, pCurProcess, pNextProcess, VBOXSERVICECTRLPROCESS, Node)
    {
        if (ASMAtomicReadBool(&pCurProcess->fStopped))
        {
            rc2 = RTCritSectLeave(&pSession->CritSect);
            AssertRC(rc2);

            rc = VGSvcGstCtrlProcessWait(pCurProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
            if (RT_SUCCESS(rc))
            {
                VGSvcGstCtrlSessionProcessRemove(pSession, pCurProcess);
                VGSvcGstCtrlProcessFree(pCurProcess);
            }

            rc2 = RTCritSectEnter(&pSession->CritSect);
            AssertRC(rc2);

            /* If failed, try next time we're being called. */
        }
    }

    rc2 = RTCritSectLeave(&pSession->CritSect);
    AssertRC(rc2);

    if (RT_FAILURE(rc))
        VGSvcError("Cleaning up stopped processes for session %RU32 failed with %Rrc\n", pSession->StartupInfo.uSessionID, rc);

    return rc;
}


/**
 * Creates the process for a guest session.
 *
 * @return  VBox status code.
 * @param   pSessionStartupInfo     Session startup info.
 * @param   pSessionThread          The session thread under construction.
 * @param   uCtrlSessionThread      The session thread debug ordinal.
 */
static int vgsvcVGSvcGstCtrlSessionThreadCreateProcess(const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
                                                       PVBOXSERVICECTRLSESSIONTHREAD pSessionThread, uint32_t uCtrlSessionThread)
{
    RT_NOREF(uCtrlSessionThread);

    /*
     * Is this an anonymous session?  Anonymous sessions run with the same
     * privileges as the main VBoxService executable.
     */
    bool const fAnonymous =    pSessionThread->pStartupInfo->pszUser
                            && pSessionThread->pStartupInfo->pszUser[0] == '\0';
    if (fAnonymous)
    {
        Assert(!strlen(pSessionThread->pStartupInfo->pszPassword));
        Assert(!strlen(pSessionThread->pStartupInfo->pszDomain));

        VGSvcVerbose(3, "New anonymous guest session ID=%RU32 created, fFlags=%x, using protocol %RU32\n",
                     pSessionStartupInfo->uSessionID,
                     pSessionStartupInfo->fFlags,
                     pSessionStartupInfo->uProtocol);
    }
    else
    {
        VGSvcVerbose(3, "Spawning new guest session ID=%RU32, szUser=%s, szPassword=%s, szDomain=%s, fFlags=%x, using protocol %RU32\n",
                     pSessionStartupInfo->uSessionID,
                     pSessionStartupInfo->pszUser,
#ifdef DEBUG
                     pSessionStartupInfo->pszPassword,
#else
                     "XXX", /* Never show passwords in release mode. */
#endif
                     pSessionStartupInfo->pszDomain,
                     pSessionStartupInfo->fFlags,
                     pSessionStartupInfo->uProtocol);
    }

    /*
     * Spawn a child process for doing the actual session handling.
     * Start by assembling the argument list.
     */
    char szExeName[RTPATH_MAX];
    char *pszExeName = RTProcGetExecutablePath(szExeName, sizeof(szExeName));
    AssertPtrReturn(pszExeName, VERR_FILENAME_TOO_LONG);

    char szParmSessionID[32];
    RTStrPrintf(szParmSessionID, sizeof(szParmSessionID), "--session-id=%RU32", pSessionThread->pStartupInfo->uSessionID);

    char szParmSessionProto[32];
    RTStrPrintf(szParmSessionProto, sizeof(szParmSessionProto), "--session-proto=%RU32",
                pSessionThread->pStartupInfo->uProtocol);
#ifdef DEBUG
    char szParmThreadId[32];
    RTStrPrintf(szParmThreadId, sizeof(szParmThreadId), "--thread-id=%RU32", uCtrlSessionThread);
#endif
    unsigned    idxArg = 0; /* Next index in argument vector. */
    char const *apszArgs[24];

    apszArgs[idxArg++] = pszExeName;
#ifdef VBOXSERVICE_ARG1_UTF8_ARGV
    apszArgs[idxArg++] = VBOXSERVICE_ARG1_UTF8_ARGV; Assert(idxArg == 2);
#endif
    apszArgs[idxArg++] = "guestsession";
    apszArgs[idxArg++] = szParmSessionID;
    apszArgs[idxArg++] = szParmSessionProto;
#ifdef DEBUG
    apszArgs[idxArg++] = szParmThreadId;
#endif
    if (!fAnonymous) /* Do we need to pass a user name? */
    {
        apszArgs[idxArg++] = "--user";
        apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszUser;

        if (strlen(pSessionThread->pStartupInfo->pszDomain))
        {
            apszArgs[idxArg++] = "--domain";
            apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszDomain;
        }
    }

    /* Add same verbose flags as parent process. */
    char szParmVerbose[32];
    if (g_cVerbosity > 0)
    {
        unsigned cVs = RT_MIN(g_cVerbosity, RT_ELEMENTS(szParmVerbose) - 2);
        szParmVerbose[0] = '-';
        memset(&szParmVerbose[1], 'v', cVs);
        szParmVerbose[1 + cVs] = '\0';
        apszArgs[idxArg++] = szParmVerbose;
    }

    /* Add log file handling. Each session will have an own
     * log file, naming based on the parent log file. */
    char szParmLogFile[sizeof(g_szLogFile) + 128];
    if (g_szLogFile[0])
    {
        const char *pszSuffix = RTPathSuffix(g_szLogFile);
        if (!pszSuffix)
            pszSuffix = strchr(g_szLogFile, '\0');
        size_t cchBase = pszSuffix - g_szLogFile;

        RTTIMESPEC Now;
        RTTimeNow(&Now);
        char szTime[64];
        RTTimeSpecToString(&Now, szTime, sizeof(szTime));

        /* Replace out characters not allowed on Windows platforms, put in by RTTimeSpecToString(). */
        static const RTUNICP s_uszValidRangePairs[] =
        {
            ' ', ' ',
            '(', ')',
            '-', '.',
            '0', '9',
            'A', 'Z',
            'a', 'z',
            '_', '_',
            0xa0, 0xd7af,
            '\0'
        };
        ssize_t cReplaced = RTStrPurgeComplementSet(szTime, s_uszValidRangePairs, '_' /* chReplacement */);
        AssertReturn(cReplaced, VERR_INVALID_UTF8_ENCODING);

#ifndef DEBUG
        RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%s-%s%s",
                    cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, pSessionStartupInfo->pszUser, szTime, pszSuffix);
#else
        RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%RU32-%s-%s%s",
                    cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, uCtrlSessionThread,
                    pSessionStartupInfo->pszUser, szTime, pszSuffix);
#endif
        apszArgs[idxArg++] = "--logfile";
        apszArgs[idxArg++] = szParmLogFile;
    }

#ifdef DEBUG
    if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT)
        apszArgs[idxArg++] = "--dump-stdout";
    if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR)
        apszArgs[idxArg++] = "--dump-stderr";
#endif
    apszArgs[idxArg] = NULL;
    Assert(idxArg < RT_ELEMENTS(apszArgs));

    if (g_cVerbosity > 3)
    {
        VGSvcVerbose(4, "Spawning parameters:\n");
        for (idxArg = 0; apszArgs[idxArg]; idxArg++)
            VGSvcVerbose(4, "    %s\n", apszArgs[idxArg]);
    }

    /*
     * Flags.
     */
    uint32_t const fProcCreate = RTPROC_FLAGS_PROFILE
#ifdef RT_OS_WINDOWS
                               | RTPROC_FLAGS_SERVICE
                               | RTPROC_FLAGS_HIDDEN
#endif
                               | VBOXSERVICE_PROC_F_UTF8_ARGV;

    /*
     * Configure standard handles.
     */
    RTHANDLE hStdIn;
    int rc = RTPipeCreate(&hStdIn.u.hPipe, &pSessionThread->hKeyPipe, RTPIPE_C_INHERIT_READ);
    if (RT_SUCCESS(rc))
    {
        hStdIn.enmType = RTHANDLETYPE_PIPE;

        RTHANDLE hStdOutAndErr;
        rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
        if (RT_SUCCESS(rc))
        {
            hStdOutAndErr.enmType = RTHANDLETYPE_FILE;

            /*
             * Windows: If a domain name is given, construct an UPN (User Principle Name)
             *          with the domain name built-in, e.g. "joedoe@example.com".
             */
            const char *pszUser    = pSessionThread->pStartupInfo->pszUser;
#ifdef RT_OS_WINDOWS
            char       *pszUserUPN = NULL;
            if (pSessionThread->pStartupInfo->pszDomain[0])
            {
                int cchbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s",
                                               pSessionThread->pStartupInfo->pszUser,
                                               pSessionThread->pStartupInfo->pszDomain);
                if (cchbUserUPN > 0)
                {
                    pszUser = pszUserUPN;
                    VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
                }
                else
                    rc = VERR_NO_STR_MEMORY;
            }
            if (RT_SUCCESS(rc))
#endif
            {
                /*
                 * Finally, create the process.
                 */
                rc = RTProcCreateEx(pszExeName, apszArgs, RTENV_DEFAULT, fProcCreate,
                                    &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
                                    !fAnonymous ? pszUser : NULL,
                                    !fAnonymous ? pSessionThread->pStartupInfo->pszPassword : NULL,
                                    NULL /*pvExtraData*/,
                                    &pSessionThread->hProcess);
            }
#ifdef RT_OS_WINDOWS
            RTStrFree(pszUserUPN);
#endif
            RTFileClose(hStdOutAndErr.u.hFile);
        }

        RTPipeClose(hStdIn.u.hPipe);
    }
    return rc;
}


/**
 * Creates a guest session.
 *
 * This will spawn a new VBoxService.exe instance under behalf of the given user
 * which then will act as a session host. On successful open, the session will
 * be added to the given session thread list.
 *
 * @return  VBox status code.
 * @param   pList                   Which list to use to store the session thread in.
 * @param   pSessionStartupInfo     Session startup info.
 * @param   ppSessionThread         Returns newly created session thread on success.
 *                                  Optional.
 */
int VGSvcGstCtrlSessionThreadCreate(PRTLISTANCHOR pList, const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
                                    PVBOXSERVICECTRLSESSIONTHREAD *ppSessionThread)
{
    AssertPtrReturn(pList, VERR_INVALID_POINTER);
    AssertPtrReturn(pSessionStartupInfo, VERR_INVALID_POINTER);
    /* ppSessionThread is optional. */

#ifdef VBOX_STRICT
    /* Check for existing session in debug mode. Should never happen because of
     * Main consistency. */
    PVBOXSERVICECTRLSESSIONTHREAD pSessionCur;
    RTListForEach(pList, pSessionCur, VBOXSERVICECTRLSESSIONTHREAD, Node)
    {
        AssertMsgReturn(   pSessionCur->fStopped == true
                        || pSessionCur->pStartupInfo->uSessionID != pSessionStartupInfo->uSessionID,
                        ("Guest session thread ID=%RU32 already exists (fStopped=%RTbool)\n",
                         pSessionCur->pStartupInfo->uSessionID, pSessionCur->fStopped), VERR_ALREADY_EXISTS);
    }
#endif

    /* Static counter to help tracking session thread <-> process relations. */
    static uint32_t s_uCtrlSessionThread = 0;

    /*
     * Allocate and initialize the session thread structure.
     */
    int rc;
    PVBOXSERVICECTRLSESSIONTHREAD pSessionThread = (PVBOXSERVICECTRLSESSIONTHREAD)RTMemAllocZ(sizeof(*pSessionThread));
    if (pSessionThread)
    {
        //pSessionThread->fShutdown = false;
        //pSessionThread->fStarted  = false;
        //pSessionThread->fStopped  = false;
        pSessionThread->hKeyPipe  = NIL_RTPIPE;
        pSessionThread->Thread    = NIL_RTTHREAD;
        pSessionThread->hProcess  = NIL_RTPROCESS;

        /* Duplicate startup info. */
        pSessionThread->pStartupInfo = VbglR3GuestCtrlSessionStartupInfoDup(pSessionStartupInfo);
        AssertPtrReturn(pSessionThread->pStartupInfo, VERR_NO_MEMORY);

        /* Generate the secret key. */
        RTRandBytes(pSessionThread->abKey, sizeof(pSessionThread->abKey));

        rc = RTCritSectInit(&pSessionThread->CritSect);
        AssertRC(rc);
        if (RT_SUCCESS(rc))
        {
            /*
             * Give the session key to the host so it can validate the client.
             */
            if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
            {
                for (uint32_t i = 0; i < 10; i++)
                {
                    rc = VbglR3GuestCtrlSessionPrepare(g_idControlSvcClient, pSessionStartupInfo->uSessionID,
                                                       pSessionThread->abKey, sizeof(pSessionThread->abKey));
                    if (rc != VERR_OUT_OF_RESOURCES)
                        break;
                    RTThreadSleep(100);
                }
            }
            if (RT_SUCCESS(rc))
            {
                s_uCtrlSessionThread++;

                /*
                 * Start the session child process.
                 */
                rc = vgsvcVGSvcGstCtrlSessionThreadCreateProcess(pSessionStartupInfo, pSessionThread, s_uCtrlSessionThread);
                if (RT_SUCCESS(rc))
                {
                    /*
                     * Start the session thread.
                     */
                    rc = RTThreadCreateF(&pSessionThread->Thread, vgsvcGstCtrlSessionThread, pSessionThread /*pvUser*/, 0 /*cbStack*/,
                                         RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctls%RU32", s_uCtrlSessionThread);
                    if (RT_SUCCESS(rc))
                    {
                        /* Wait for the thread to initialize. */
                        rc = RTThreadUserWait(pSessionThread->Thread, RT_MS_1MIN);
                        if (   RT_SUCCESS(rc)
                            && !ASMAtomicReadBool(&pSessionThread->fShutdown))
                        {
                            VGSvcVerbose(2, "Thread for session ID=%RU32 started\n", pSessionThread->pStartupInfo->uSessionID);

                            ASMAtomicXchgBool(&pSessionThread->fStarted, true);

                            /* Add session to list. */
                            RTListAppend(pList, &pSessionThread->Node);
                            if (ppSessionThread) /* Return session if wanted. */
                                *ppSessionThread = pSessionThread;
                            return VINF_SUCCESS;
                        }

                        /*
                         * Bail out.
                         */
                        VGSvcError("Thread for session ID=%RU32 failed to start, rc=%Rrc\n",
                                   pSessionThread->pStartupInfo->uSessionID, rc);
                        if (RT_SUCCESS_NP(rc))
                            rc = VERR_CANT_CREATE; /** @todo Find a better rc. */
                    }
                    else
                        VGSvcError("Creating session thread failed, rc=%Rrc\n", rc);

                    RTProcTerminate(pSessionThread->hProcess);
                    uint32_t cMsWait = 1;
                    while (   RTProcWait(pSessionThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, NULL) == VERR_PROCESS_RUNNING
                           && cMsWait <= 9) /* 1023 ms */
                    {
                        RTThreadSleep(cMsWait);
                        cMsWait <<= 1;
                    }
                }

                if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
                    VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, pSessionStartupInfo->uSessionID);
            }
            else
                VGSvcVerbose(3, "VbglR3GuestCtrlSessionPrepare failed: %Rrc\n", rc);
            RTPipeClose(pSessionThread->hKeyPipe);
            pSessionThread->hKeyPipe = NIL_RTPIPE;
            RTCritSectDelete(&pSessionThread->CritSect);
        }
        RTMemFree(pSessionThread);
    }
    else
        rc = VERR_NO_MEMORY;

    VGSvcVerbose(3, "Spawning session thread returned returned rc=%Rrc\n", rc);
    return rc;
}


/**
 * Waits for a formerly opened guest session process to close.
 *
 * @return  VBox status code.
 * @param   pThread                 Guest session thread to wait for.
 * @param   uTimeoutMS              Waiting timeout (in ms).
 * @param   fFlags                  Closing flags.
 */
int VGSvcGstCtrlSessionThreadWait(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t uTimeoutMS, uint32_t fFlags)
{
    RT_NOREF(fFlags);
    AssertPtrReturn(pThread, VERR_INVALID_POINTER);
    /** @todo Validate closing flags. */

    AssertMsgReturn(pThread->Thread != NIL_RTTHREAD,
                    ("Guest session thread of session %p does not exist when it should\n", pThread),
                    VERR_NOT_FOUND);

    int rc = VINF_SUCCESS;

    /*
     * The spawned session process should have received the same closing request,
     * so just wait for the process to close.
     */
    if (ASMAtomicReadBool(&pThread->fStarted))
    {
        /* Ask the thread to shutdown. */
        ASMAtomicXchgBool(&pThread->fShutdown, true);

        VGSvcVerbose(3, "Waiting for session thread ID=%RU32 to close (%RU32ms) ...\n",
                     pThread->pStartupInfo->uSessionID, uTimeoutMS);

        int rcThread;
        rc = RTThreadWait(pThread->Thread, uTimeoutMS, &rcThread);
        if (RT_SUCCESS(rc))
        {
            AssertMsg(pThread->fStopped, ("Thread of session ID=%RU32 not in stopped state when it should\n",
                      pThread->pStartupInfo->uSessionID));

            VGSvcVerbose(3, "Session thread ID=%RU32 ended with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rcThread);
        }
        else
            VGSvcError("Waiting for session thread ID=%RU32 to close failed with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rc);
    }
    else
        VGSvcVerbose(3, "Thread for session ID=%RU32 not in started state, skipping wait\n", pThread->pStartupInfo->uSessionID);

    LogFlowFuncLeaveRC(rc);
    return rc;
}

/**
 * Waits for the specified session thread to end and remove
 * it from the session thread list.
 *
 * @return  VBox status code.
 * @param   pThread                 Session thread to destroy.
 * @param   fFlags                  Closing flags.
 */
int VGSvcGstCtrlSessionThreadDestroy(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t fFlags)
{
    AssertPtrReturn(pThread, VERR_INVALID_POINTER);
    AssertPtrReturn(pThread->pStartupInfo, VERR_WRONG_ORDER);

    const uint32_t uSessionID = pThread->pStartupInfo->uSessionID;

    VGSvcVerbose(3, "Destroying session ID=%RU32 ...\n", uSessionID);

    int rc = VGSvcGstCtrlSessionThreadWait(pThread, 5 * 60 * 1000 /* 5 minutes timeout */, fFlags);
    if (RT_SUCCESS(rc))
    {
        VbglR3GuestCtrlSessionStartupInfoFree(pThread->pStartupInfo);
        pThread->pStartupInfo = NULL;

        RTPipeClose(pThread->hKeyPipe);
        pThread->hKeyPipe = NIL_RTPIPE;

        RTCritSectDelete(&pThread->CritSect);

        /* Remove session from list and destroy object. */
        RTListNodeRemove(&pThread->Node);

        RTMemFree(pThread);
        pThread = NULL;
    }

    VGSvcVerbose(3, "Destroyed session ID=%RU32 with %Rrc\n", uSessionID, rc);
    return rc;
}

/**
 * Close all open guest session threads.
 *
 * @note    Caller is responsible for locking!
 *
 * @return  VBox status code.
 * @param   pList                   Which list to close the session threads for.
 * @param   fFlags                  Closing flags.
 */
int VGSvcGstCtrlSessionThreadDestroyAll(PRTLISTANCHOR pList, uint32_t fFlags)
{
    AssertPtrReturn(pList, VERR_INVALID_POINTER);

    int rc = VINF_SUCCESS;

    /*int rc = VbglR3GuestCtrlClose
        if (RT_FAILURE(rc))
            VGSvcError("Cancelling pending waits failed; rc=%Rrc\n", rc);*/

    PVBOXSERVICECTRLSESSIONTHREAD pSessIt;
    PVBOXSERVICECTRLSESSIONTHREAD pSessItNext;
    RTListForEachSafe(pList, pSessIt, pSessItNext, VBOXSERVICECTRLSESSIONTHREAD, Node)
    {
        int rc2 = VGSvcGstCtrlSessionThreadDestroy(pSessIt, fFlags);
        if (RT_FAILURE(rc2))
        {
            VGSvcError("Closing session thread '%s' failed with rc=%Rrc\n", RTThreadGetName(pSessIt->Thread), rc2);
            if (RT_SUCCESS(rc))
                rc = rc2;
            /* Keep going. */
        }
    }

    VGSvcVerbose(4, "Destroying guest session threads ended with %Rrc\n", rc);
    return rc;
}


/**
 * Main function for the session process.
 *
 * @returns exit code.
 * @param   argc        Argument count.
 * @param   argv        Argument vector (UTF-8).
 */
RTEXITCODE VGSvcGstCtrlSessionSpawnInit(int argc, char **argv)
{
    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--domain",          VBOXSERVICESESSIONOPT_DOMAIN,          RTGETOPT_REQ_STRING },
#ifdef DEBUG
        { "--dump-stdout",     VBOXSERVICESESSIONOPT_DUMP_STDOUT,     RTGETOPT_REQ_NOTHING },
        { "--dump-stderr",     VBOXSERVICESESSIONOPT_DUMP_STDERR,     RTGETOPT_REQ_NOTHING },
#endif
        { "--logfile",         VBOXSERVICESESSIONOPT_LOG_FILE,        RTGETOPT_REQ_STRING },
        { "--user",            VBOXSERVICESESSIONOPT_USERNAME,        RTGETOPT_REQ_STRING },
        { "--session-id",      VBOXSERVICESESSIONOPT_SESSION_ID,      RTGETOPT_REQ_UINT32 },
        { "--session-proto",   VBOXSERVICESESSIONOPT_SESSION_PROTO,   RTGETOPT_REQ_UINT32 },
#ifdef DEBUG
        { "--thread-id",       VBOXSERVICESESSIONOPT_THREAD_ID,       RTGETOPT_REQ_UINT32 },
#endif /* DEBUG */
        { "--verbose",         'v',                                   RTGETOPT_REQ_NOTHING }
    };

    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, argc, argv,
                 s_aOptions, RT_ELEMENTS(s_aOptions),
                 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    uint32_t fSession = VBOXSERVICECTRLSESSION_FLAG_SPAWN;

    /* Protocol and session ID must be specified explicitly. */
    g_Session.StartupInfo.uProtocol  = UINT32_MAX;
    g_Session.StartupInfo.uSessionID = UINT32_MAX;

    int ch;
    RTGETOPTUNION ValueUnion;
    while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case VBOXSERVICESESSIONOPT_DOMAIN:
                /* Information not needed right now, skip. */
                break;
#ifdef DEBUG
            case VBOXSERVICESESSIONOPT_DUMP_STDOUT:
                fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
                break;

            case VBOXSERVICESESSIONOPT_DUMP_STDERR:
                fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
                break;
#endif
            case VBOXSERVICESESSIONOPT_SESSION_ID:
                g_Session.StartupInfo.uSessionID = ValueUnion.u32;
                break;

            case VBOXSERVICESESSIONOPT_SESSION_PROTO:
                g_Session.StartupInfo.uProtocol = ValueUnion.u32;
                break;
#ifdef DEBUG
            case VBOXSERVICESESSIONOPT_THREAD_ID:
                /* Not handled. Mainly for processs listing. */
                break;
#endif
            case VBOXSERVICESESSIONOPT_LOG_FILE:
            {
                int rc = RTStrCopy(g_szLogFile, sizeof(g_szLogFile), ValueUnion.psz);
                if (RT_FAILURE(rc))
                    return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error copying log file name: %Rrc", rc);
                break;
            }

            case VBOXSERVICESESSIONOPT_USERNAME:
                /* Information not needed right now, skip. */
                break;

            /** @todo Implement help? */

            case 'v':
                g_cVerbosity++;
                break;

            case VINF_GETOPT_NOT_OPTION:
            {
                if (!RTStrICmp(ValueUnion.psz, VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
                    break;
                /* else fall through and bail out. */
                RT_FALL_THROUGH();
            }
            default:
                return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'", ValueUnion.psz);
        }
    }

    /* Check that we've got all the required options. */
    if (g_Session.StartupInfo.uProtocol == UINT32_MAX)
        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No protocol version specified");

    if (g_Session.StartupInfo.uSessionID == UINT32_MAX)
        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No session ID specified");

    /* Init the session object. */
    int rc = VGSvcGstCtrlSessionInit(&g_Session, fSession);
    if (RT_FAILURE(rc))
        return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to initialize session object, rc=%Rrc\n", rc);

    rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
    if (RT_FAILURE(rc))
        return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to create log file '%s', rc=%Rrc\n",
                              g_szLogFile[0] ? g_szLogFile : "<None>", rc);

    RTEXITCODE rcExit = vgsvcGstCtrlSessionSpawnWorker(&g_Session);

    VGSvcLogDestroy();
    return rcExit;
}