summaryrefslogtreecommitdiff
path: root/src/VBox/HostServices/SharedClipboard/VBoxSharedClipboardSvc.cpp
blob: 1d66df278dbf8f684e7d33c66bf0787afd5aaa28 (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
/* $Id$ */
/** @file
 * Shared Clipboard Service - Host service entry points.
 */

/*
 * Copyright (C) 2006-2019 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */


/** @page pg_hostclip       The Shared Clipboard Host Service
 *
 * The shared clipboard host service is the host half of the clibpoard proxying
 * between the host and the guest.  The guest parts live in VBoxClient, VBoxTray
 * and VBoxService depending on the OS, with code shared between host and guest
 * under src/VBox/GuestHost/SharedClipboard/.
 *
 * The service is split into a platform-independent core and platform-specific
 * backends.  The service defines two communication protocols - one to
 * communicate with the clipboard service running on the guest, and one to
 * communicate with the backend.  These will be described in a very skeletal
 * fashion here.
 *
 * r=bird: The "two communication protocols" does not seems to be factual, there
 * is only one protocol, the first one mentioned.  It cannot be backend
 * specific, because the guest/host protocol is platform and backend agnostic in
 * nature.  You may call it versions, but I take a great dislike to "protocol
 * versions" here, as you've just extended the existing protocol with a feature
 * that allows to transfer files and directories too.  See @bugref{9437#c39}.
 *
 *
 * @section sec_hostclip_guest_proto  The guest communication protocol
 *
 * The guest clipboard service communicates with the host service over HGCM
 * (the host is a HGCM service).  HGCM is connection based, so the guest side
 * has to connect before anything else can be done.  (Windows hosts currently
 * only support one simultaneous connection.)  Once it has connected, it can
 * send messages to the host services, some of which will receive immediate
 * replies from the host, others which will block till a reply becomes
 * available.  The latter is because HGCM does't allow the host to initiate
 * communication, it must be guest triggered.  The HGCM service is single
 * threaded, so it doesn't matter if the guest tries to send lots of requests in
 * parallel, the service will process them one at the time.
 *
 * There are currently four messages defined.  The first is
 * VBOX_SHCL_GUEST_FN_MSG_GET / VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT, which waits
 * for a message from the host.  If a host message is sent while the guest is
 * not waiting, it will be queued until the guest requests it.  The host code
 * only supports a single simultaneous GET call from one client guest.
 *
 * The second guest message is VBOX_SHCL_GUEST_FN_REPORT_FORMATS, which tells
 * the host that the guest has new clipboard data available.  The third is
 * VBOX_SHCL_GUEST_FN_DATA_READ, which asks the host to send its clipboard data
 * and waits until it arrives.  The host supports at most one simultaneous
 * VBOX_SHCL_GUEST_FN_DATA_READ call from a guest - if a second call is made
 * before the first has returned, the first will be aborted.
 *
 * The last guest message is VBOX_SHCL_GUEST_FN_DATA_WRITE, which is used to
 * send the contents of the guest clipboard to the host.  This call should be
 * used after the host has requested data from the guest.
 *
 *
 * @section sec_hostclip_backend_proto  The communication protocol with the
 *                                      platform-specific backend
 *
 * The initial protocol implementation (called protocol v0) was very simple,
 * and could only handle simple data (like copied text and so on). It also
 * was limited to two (2) fixed parameters at all times.
 *
 * Since VBox 6.1 a newer protocol (v1) has been established to also support
 * file transfers. This protocol uses a (per-client) message queue instead
 * (see VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT vs. VBOX_SHCL_GUEST_FN_GET_HOST_MSG).
 *
 * To distinguish the old (legacy) or new(er) protocol, the VBOX_SHCL_GUEST_FN_CONNECT
 * message has been introduced. If an older guest does not send this message,
 * an appropriate translation will be done to serve older Guest Additions (< 6.1).
 *
 * The protocol also support out-of-order messages by using so-called "context IDs",
 * which are generated by the host. A context ID consists of a so-called "source event ID"
 * and a so-called "event ID". Each HGCM client has an own, random, source event ID and
 * generates non-deterministic event IDs so that the guest side does not known what
 * comes next; the guest side has to reply with the same conext ID which was sent by
 * the host request.
 *
 * Also see the protocol changelog at VBoxShClSvc.h.
 *
 *
 * @section sec_uri_intro               Transferring files
 *
 * Since VBox x.x.x transferring files via Shared Clipboard is supported.
 * See the VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS define for supported / enabled
 * platforms. This is called "Shared Clipboard transfers".
 *
 * Copying files / directories from guest A to guest B requires the host
 * service to act as a proxy and cache, as we don't allow direct VM-to-VM
 * communication. Copying from / to the host also is taken into account.
 *
 * At the moment a transfer is a all-or-nothing operation, e.g. it either
 * completes or fails completely. There might be callbacks in the future
 * to e.g. skip failing entries.
 *
 * Known limitations:
 *
 * - Support for VRDE (VRDP) is not implemented yet (see #9498).
 * - Unicode support on Windows hosts / guests is not enabled (yet).
 * - Symbolic links / Windows junctions are not allowed.
 * - Windows alternate data streams (ADS) are not allowed.
 * - No support for ACLs yet.
 * - No (maybe never) support for NT4.
 *
 * @section sec_transfers_areas         Clipboard areas.
 *
 * For larger / longer transfers there might be file data
 * temporarily cached on the host, which has not been transferred to the
 * destination yet. Such a cache is called a "Shared Clipboard Area", which
 * in turn is identified by a unique ID across all VMs running on the same
 * host. To control the access (and needed cleanup) of such clipboard areas,
 * VBoxSVC (Main) is used for this task. A Shared Clipboard client can register,
 * unregister, attach to and detach from a clipboard area. If all references
 * to a clipboard area are released, a clipboard area gets detroyed automatically
 * by VBoxSVC.
 *
 * By default a clipboard area lives in the user's temporary directory in the
 * sub folder "VirtualBox Shared Clipboards/clipboard-<ID>". VBoxSVC does not
 * do any file locking in a clipboard area, but keeps the clipboard areas's
 * directory open to prevent deletion by third party processes.
 *
 * @todo We might use some VFS / container (IPRT?) for this instead of the
 *       host's file system directly?
 *       bird> Yes, but may take some work as we don't have the pick and choose
 *             kind of VFS containers implemented yet.
 *
 * @section sec_transfer_structure        Transfer handling structure
 *
 * All structures / classes are designed for running on both, on the guest
 * (via VBoxTray / VBoxClient) or on the host (host service) to avoid code
 * duplication where applicable.
 *
 * Per HGCM client there is a so-called "transfer context", which in turn can
 * have one or mulitple so-called "Shared Clipboard transfer" objects. At the
 * moment we only support on concurrent Shared Clipboard transfer per transfer
 * context. It's being used for reading from a source or writing to destination,
 * depening on its direction. An Shared Clipboard transfer can have optional
 * callbacks which might be needed by various implementations. Also, transfers
 * optionally can run in an asynchronous thread to prevent blocking the UI while
 * running.
 *
 * A Shared Clipboard transfer can maintain its own clipboard area; for the host
 * service such a clipboard area is coupled to a clipboard area registered or
 * attached with VBoxSVC. This is needed because multiple transfers from
 * multiple VMs (n:n) can rely on the same clipboard area, so there needs a
 * master keeping tracking of a clipboard area. To minimize IPC traffic only the
 * minimum de/attaching is done at the moment. A clipboard area gets cleaned up
 * (i.e. physically deleted) if no references are held to it  anymore, or if
 * VBoxSVC goes down.
 *
 * @section sec_transfer_providers        Transfer providers
 *
 * For certain implementations (for example on Windows guests / hosts, using
 * IDataObject and IStream objects) a more flexible approach reqarding reading /
 * writing is needed. For this so-called transfer providers abstract the way of how
 * data is being read / written in the current context (host / guest), while
 * the rest of the code stays the same.
 *
 * @section sec_transfer_protocol         Transfer protocol
 *
 * The host service issues commands which the guest has to respond with an own
 * message to. The protocol itself is designed so that it has primitives to list
 * directories and open/close/read/write file system objects.
 *
 * Note that this is different from the DnD approach, as Shared Clipboard transfers
 * need to be deeper integrated within the host / guest OS (i.e. for progress UI),
 * and this might require non-monolithic / random access APIs to achieve.
 *
 * As there can be multiple file system objects (fs objects) selected for transfer,
 * a transfer can be queried for its root entries, which then contains the top-level
 * elements. Based on these elements, (a) (recursive) listing(s) can be performed
 * to (partially) walk down into directories and query fs object information. The
 * provider provides appropriate interface for this, even if not all implementations
 * might need this mechanism.
 *
 * An Shared Clipboard transfer has three stages:
 *  - 1. Announcement: An Shared Clipboard transfer-compatible format (currently only one format available)
 *          has been announced, the destination side creates a transfer object, which then,
 *          depending on the actual implementation, can be used to tell the OS that
 *          there is transfer (file) data available.
 *          At this point this just acts as a (kind-of) promise to the OS that we
 *          can provide (file) data at some later point in time.
 *
 *  - 2. Initialization: As soon as the OS requests the (file) data, mostly triggered
 *          by the user starting a paste operation (CTRL + V), the transfer get initialized
 *          on the destination side, which in turn lets the source know that a transfer
 *          is going to happen.
 *
 *  - 3. Transfer: At this stage the actual transfer from source to the destination takes
 *          place. How the actual transfer is structurized (e.g. which files / directories
 *          are transferred in which order) depends on the destination implementation. This
 *          is necessary in order to fulfill requirements on the destination side with
 *          regards to ETA calculation or other dependencies.
 *          Both sides can abort or cancel the transfer at any time.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_SHARED_CLIPBOARD
#include <VBox/log.h>

#include <VBox/GuestHost/clipboard-helper.h>
#include <VBox/HostServices/Service.h>
#include <VBox/HostServices/VBoxClipboardSvc.h>
#include <VBox/HostServices/VBoxClipboardExt.h>

#include <VBox/AssertGuest.h>
#include <VBox/err.h>
#include <VBox/VMMDev.h>
#include <VBox/vmm/ssm.h>

#include <iprt/mem.h>
#include <iprt/string.h>
#include <iprt/assert.h>
#include <iprt/critsect.h>
#include <iprt/rand.h>

#include "VBoxSharedClipboardSvc-internal.h"
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
# include "VBoxSharedClipboardSvc-transfers.h"
#endif

using namespace HGCM;


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** @name The saved state versions for the shared clipboard service.
 *
 * @note We set bit 31 because prior to version 0x80000002 there would be a
 *       structure size rather than a version number.  Setting bit 31 dispells
 *       any possible ambiguity.
 *
 * @{ */
/** The current saved state version. */
#define VBOX_SHCL_SAVED_STATE_VER_CURRENT   VBOX_SHCL_SAVED_STATE_VER_6_1RC1
/** Adds the client's POD state and client state flags.
 * @since 6.1 RC1 */
#define VBOX_SHCL_SAVED_STATE_VER_6_1RC1    UINT32_C(0x80000004)
/** First attempt saving state during @bugref{9437} development.
 * @since 6.1 BETA 2   */
#define VBOX_SHCL_SAVED_STATE_VER_6_1B2     UINT32_C(0x80000003)
/** First structured version.
 * @since 3.1 / r53668 */
#define VBOX_SHCL_SAVED_STATE_VER_3_1       UINT32_C(0x80000002)
/** This was just a state memory dump, including pointers and everything.
 * @note This is not supported any more. Sorry.  */
#define VBOX_SHCL_SAVED_STATE_VER_NOT_SUPP  (ARCH_BITS == 64 ? UINT32_C(72) : UINT32_C(48))
/** @} */


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
PVBOXHGCMSVCHELPERS g_pHelpers;

static RTCRITSECT g_CritSect;
/** Global Shared Clipboard mode. */
static uint32_t g_uMode  = VBOX_SHCL_MODE_OFF;
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
/** Global Shared Clipboard (file) transfer mode. */
uint32_t g_fTransferMode = VBOX_SHCL_TRANSFER_MODE_DISABLED;
#endif

/** Is the clipboard running in headless mode? */
static bool g_fHeadless = false;

/** Holds the service extension state. */
SHCLEXTSTATE g_ExtState = { 0 };

/** Global map of all connected clients. */
ClipboardClientMap g_mapClients;

/** Global list of all clients which are queued up (deferred return) and ready
 *  to process new commands. The key is the (unique) client ID. */
ClipboardClientQueue g_listClientsDeferred;

/** Host feature mask (VBOX_SHCL_HF_0_XXX) for VBOX_SHCL_GUEST_FN_REPORT_FEATURES
 * and VBOX_SHCL_GUEST_FN_QUERY_FEATURES. */
static uint64_t const g_fHostFeatures0 = VBOX_SHCL_HF_0_CONTEXT_ID
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
                                       | VBOX_SHCL_HF_0_TRANSFERS
#endif
                                       ;


/**
 * Returns the current Shared Clipboard service mode.
 *
 * @returns Current Shared Clipboard service mode.
 */
uint32_t ShClSvcGetMode(void)
{
    return g_uMode;
}

/**
 * Getter for headless setting. Also needed by testcase.
 *
 * @returns Whether service currently running in headless mode or not.
 */
bool ShClSvcGetHeadless(void)
{
    return g_fHeadless;
}

static int shClSvcModeSet(uint32_t uMode)
{
    int rc = VERR_NOT_SUPPORTED;

    switch (uMode)
    {
        case VBOX_SHCL_MODE_OFF:
            RT_FALL_THROUGH();
        case VBOX_SHCL_MODE_HOST_TO_GUEST:
            RT_FALL_THROUGH();
        case VBOX_SHCL_MODE_GUEST_TO_HOST:
            RT_FALL_THROUGH();
        case VBOX_SHCL_MODE_BIDIRECTIONAL:
        {
            g_uMode = uMode;

            rc = VINF_SUCCESS;
            break;
        }

        default:
        {
            g_uMode = VBOX_SHCL_MODE_OFF;
            break;
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

bool ShClSvcLock(void)
{
    return RT_SUCCESS(RTCritSectEnter(&g_CritSect));
}

void ShClSvcUnlock(void)
{
    int rc2 = RTCritSectLeave(&g_CritSect);
    AssertRC(rc2);
}

/**
 * Resets a client's state message queue.
 *
 * @param   pClient             Pointer to the client data structure to reset message queue for.
 * @note    Caller enters pClient->CritSect.
 */
void shClSvcMsgQueueReset(PSHCLCLIENT pClient)
{
    Assert(RTCritSectIsOwner(&pClient->CritSect));
    LogFlowFuncEnter();

    while (!RTListIsEmpty(&pClient->MsgQueue))
    {
        PSHCLCLIENTMSG pMsg = RTListRemoveFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
        shClSvcMsgFree(pClient, pMsg);
    }
}

/**
 * Allocates a new clipboard message.
 *
 * @returns Allocated clipboard message, or NULL on failure.
 * @param   pClient     The client which is target of this message.
 * @param   idMsg       The message ID (VBOX_SHCL_HOST_MSG_XXX) to use
 * @param   cParms      The number of parameters the message takes.
 */
PSHCLCLIENTMSG shClSvcMsgAlloc(PSHCLCLIENT pClient, uint32_t idMsg, uint32_t cParms)
{
    RT_NOREF(pClient);
    PSHCLCLIENTMSG pMsg = (PSHCLCLIENTMSG)RTMemAllocZ(RT_UOFFSETOF_DYN(SHCLCLIENTMSG, aParms[cParms]));
    if (pMsg)
    {
        uint32_t cAllocated = ASMAtomicIncU32(&pClient->cAllocatedMessages);
        if (cAllocated <= 4096)
        {
            RTListInit(&pMsg->ListEntry);
            pMsg->cParms = cParms;
            pMsg->idMsg  = idMsg;
            return pMsg;
        }
        AssertMsgFailed(("Too many messages allocated for client %u! (%u)\n", pClient->State.uClientID, cAllocated));
        ASMAtomicDecU32(&pClient->cAllocatedMessages);
        RTMemFree(pMsg);
    }
    return NULL;
}

/**
 * Frees a formerly allocated clipboard message.
 *
 * @param   pClient     The client which was the target of this message.
 * @param   pMsg        Clipboard message to free.
 */
void shClSvcMsgFree(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg)
{
    RT_NOREF(pClient);
    /** @todo r=bird: Do accounting. */
    if (pMsg)
    {
        pMsg->idMsg = UINT32_C(0xdeadface);
        RTMemFree(pMsg);

        uint32_t cAllocated = ASMAtomicDecU32(&pClient->cAllocatedMessages);
        Assert(cAllocated < UINT32_MAX / 2);
        RT_NOREF(cAllocated);
    }
}

/**
 * Sets the VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT and VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT
 * return parameters.
 *
 * @param   pMsg        Message to set return parameters to.
 * @param   paDstParms  The peek parameter vector.
 * @param   cDstParms   The number of peek parameters (at least two).
 * @remarks ASSUMES the parameters has been cleared by clientMsgPeek.
 */
static void shClSvcMsgSetPeekReturn(PSHCLCLIENTMSG pMsg, PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
{
    Assert(cDstParms >= 2);
    if (paDstParms[0].type == VBOX_HGCM_SVC_PARM_32BIT)
        paDstParms[0].u.uint32 = pMsg->idMsg;
    else
        paDstParms[0].u.uint64 = pMsg->idMsg;
    paDstParms[1].u.uint32 = pMsg->cParms;

    uint32_t i = RT_MIN(cDstParms, pMsg->cParms + 2);
    while (i-- > 2)
        switch (pMsg->aParms[i - 2].type)
        {
            case VBOX_HGCM_SVC_PARM_32BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint32_t); break;
            case VBOX_HGCM_SVC_PARM_64BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint64_t); break;
            case VBOX_HGCM_SVC_PARM_PTR:   paDstParms[i].u.uint32 = pMsg->aParms[i - 2].u.pointer.size; break;
        }
}

/**
 * Sets the VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT return parameters.
 *
 * @returns VBox status code.
 * @param   pMsg        The message which parameters to return to the guest.
 * @param   paDstParms  The peek parameter vector.
 * @param   cDstParms   The number of peek parameters should be exactly two
 */
static int shClSvcMsgSetOldWaitReturn(PSHCLCLIENTMSG pMsg, PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
{
    /*
     * Assert sanity.
     */
    AssertPtr(pMsg);
    AssertPtrReturn(paDstParms, VERR_INVALID_POINTER);
    AssertReturn(cDstParms >= 2, VERR_INVALID_PARAMETER);

    Assert(pMsg->cParms == 2);
    Assert(pMsg->aParms[0].u.uint32 == pMsg->idMsg);
    switch (pMsg->idMsg)
    {
        case VBOX_SHCL_HOST_MSG_READ_DATA:
        case VBOX_SHCL_HOST_MSG_FORMATS_REPORT:
            break;
        default:
            AssertFailed();
    }

    /*
     * Set the parameters.
     */
    if (pMsg->cParms > 0)
        paDstParms[0] = pMsg->aParms[0];
    if (pMsg->cParms > 1)
        paDstParms[1] = pMsg->aParms[1];
    return VINF_SUCCESS;
}

/**
 * Adds a new message to a client'S message queue.
 *
 * @returns IPRT status code.
 * @param   pClient             Pointer to the client data structure to add new message to.
 * @param   pMsg                Pointer to message to add. The queue then owns the pointer.
 * @param   fAppend             Whether to append or prepend the message to the queue.
 *
 * @note    Caller must enter critical section.
 */
void shClSvcMsgAdd(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg, bool fAppend)
{
    Assert(RTCritSectIsOwned(&pClient->CritSect));
    AssertPtr(pMsg);

    LogFlowFunc(("idMsg=%s (%RU32) cParms=%RU32 fAppend=%RTbool\n",
                 ShClHostMsgToStr(pMsg->idMsg), pMsg->idMsg, pMsg->cParms, fAppend));

    if (fAppend)
        RTListAppend(&pClient->MsgQueue, &pMsg->ListEntry);
    else
        RTListPrepend(&pClient->MsgQueue, &pMsg->ListEntry);
}


/**
 * Appends a message to the client's queue and wake it up.
 *
 * @returns VBox status code, though the message is consumed regardless of what
 *          is returned.
 * @param   pClient             The client to queue the message on.
 * @param   pMsg                The message to queue.  Ownership is always
 *                              transfered to the queue.
 *
 * @note    Caller must enter critical section.
 */
int shClSvcMsgAddAndWakeupClient(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg)
{
    Assert(RTCritSectIsOwned(&pClient->CritSect));
    AssertPtr(pMsg);
    AssertPtr(pClient);
    LogFlowFunc(("idMsg=%s (%u) cParms=%u\n", ShClHostMsgToStr(pMsg->idMsg), pMsg->idMsg, pMsg->cParms));

    RTListAppend(&pClient->MsgQueue, &pMsg->ListEntry);
    return shClSvcClientWakeup(pClient);
}

/**
 * Initializes a Shared Clipboard client.
 *
 * @param   pClient             Client to initialize.
 * @param   uClientID           HGCM client ID to assign client to.
 */
int shClSvcClientInit(PSHCLCLIENT pClient, uint32_t uClientID)
{
    AssertPtrReturn(pClient, VERR_INVALID_POINTER);

    /* Assign the client ID. */
    pClient->State.uClientID = uClientID;
    RTListInit(&pClient->MsgQueue);
    pClient->cAllocatedMessages = 0;

    LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));

    int rc = RTCritSectInit(&pClient->CritSect);
    if (RT_SUCCESS(rc))
    {
        /* Create the client's own event source. */
        rc = ShClEventSourceCreate(&pClient->EventSrc, 0 /* ID, ignored */);
        if (RT_SUCCESS(rc))
        {
            LogFlowFunc(("[Client %RU32] Using event source %RU32\n", uClientID, pClient->EventSrc.uID));

            /* Reset the client state. */
            shclSvcClientStateReset(&pClient->State);

            /* (Re-)initialize the client state. */
            rc = shClSvcClientStateInit(&pClient->State, uClientID);

#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
            if (RT_SUCCESS(rc))
                rc = ShClTransferCtxInit(&pClient->TransferCtx);
#endif
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

/**
 * Destroys a Shared Clipboard client.
 *
 * @param   pClient             Client to destroy.
 */
void shClSvcClientDestroy(PSHCLCLIENT pClient)
{
    AssertPtrReturnVoid(pClient);

    LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));

    /* Make sure to send a quit message to the guest so that it can terminate gracefully. */
    RTCritSectEnter(&pClient->CritSect);
    if (pClient->Pending.uType)
    {
        if (pClient->Pending.cParms > 1)
            HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_QUIT);
        if (pClient->Pending.cParms > 2)
            HGCMSvcSetU32(&pClient->Pending.paParms[1], 0);
        g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, VINF_SUCCESS);
        pClient->Pending.uType   = 0;
        pClient->Pending.cParms  = 0;
        pClient->Pending.hHandle = NULL;
        pClient->Pending.paParms = NULL;
    }
    RTCritSectLeave(&pClient->CritSect);

    ShClEventSourceDestroy(&pClient->EventSrc);

    shClSvcClientStateDestroy(&pClient->State);

    int rc2 = RTCritSectDelete(&pClient->CritSect);
    AssertRC(rc2);

    ClipboardClientMap::iterator itClient = g_mapClients.find(pClient->State.uClientID);
    if (itClient != g_mapClients.end())
    {
        g_mapClients.erase(itClient);
    }
    else
        AssertFailed();

    LogFlowFuncLeave();
}

/**
 * Resets a Shared Clipboard client.
 *
 * @param   pClient             Client to reset.
 */
void shClSvcClientReset(PSHCLCLIENT pClient)
{
    if (!pClient)
        return;

    LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
    RTCritSectEnter(&pClient->CritSect);

    /* Reset message queue. */
    shClSvcMsgQueueReset(pClient);

    /* Reset event source. */
    ShClEventSourceReset(&pClient->EventSrc);

    /* Reset pending state. */
    RT_ZERO(pClient->Pending);

#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
    shClSvcClientTransfersReset(pClient);
#endif

    shclSvcClientStateReset(&pClient->State);

    RTCritSectLeave(&pClient->CritSect);
}

/**
 * Implements VBOX_SHCL_GUEST_FN_REPORT_FEATURES.
 *
 * @returns VBox status code.
 * @retval  VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
 * @retval  VERR_ACCESS_DENIED if not master
 * @retval  VERR_INVALID_PARAMETER if bit 63 in the 2nd parameter isn't set.
 * @retval  VERR_WRONG_PARAMETER_COUNT
 *
 * @param   pClient     The client state.
 * @param   hCall       The client's call handle.
 * @param   cParms      Number of parameters.
 * @param   paParms     Array of parameters.
 */
int shClSvcClientReportFeatures(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall,
                                uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    /*
     * Validate the request.
     */
    ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
    ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
    uint64_t const fFeatures0 = paParms[0].u.uint64;
    ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
    uint64_t const fFeatures1 = paParms[1].u.uint64;
    ASSERT_GUEST_RETURN(fFeatures1 & VBOX_SHCL_GF_1_MUST_BE_ONE, VERR_INVALID_PARAMETER);

    /*
     * Do the work.
     */
    paParms[0].u.uint64 = g_fHostFeatures0;
    paParms[1].u.uint64 = 0;

    int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
    if (RT_SUCCESS(rc))
    {
        pClient->State.fGuestFeatures0 = fFeatures0;
        pClient->State.fGuestFeatures1 = fFeatures1;
        Log(("[Client %RU32] features: %#RX64 %#RX64\n", pClient->State.uClientID, fFeatures0, fFeatures1));
    }
    else
        LogFunc(("pfnCallComplete -> %Rrc\n", rc));

    return VINF_HGCM_ASYNC_EXECUTE;
}

/**
 * Implements VBOX_SHCL_GUEST_FN_QUERY_FEATURES.
 *
 * @returns VBox status code.
 * @retval  VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
 * @retval  VERR_WRONG_PARAMETER_COUNT
 *
 * @param   hCall       The client's call handle.
 * @param   cParms      Number of parameters.
 * @param   paParms     Array of parameters.
 */
int shClSvcClientQueryFeatures(VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    /*
     * Validate the request.
     */
    ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
    ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
    ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
    ASSERT_GUEST(paParms[1].u.uint64 & RT_BIT_64(63));

    /*
     * Do the work.
     */
    paParms[0].u.uint64 = g_fHostFeatures0;
    paParms[1].u.uint64 = 0;
    int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
    if (RT_FAILURE(rc))
        LogFunc(("pfnCallComplete -> %Rrc\n", rc));

    return VINF_HGCM_ASYNC_EXECUTE;
}

/**
 * Implements VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT and VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT.
 *
 * @returns VBox status code.
 * @retval  VINF_SUCCESS if a message was pending and is being returned.
 * @retval  VERR_TRY_AGAIN if no message pending and not blocking.
 * @retval  VERR_RESOURCE_BUSY if another read already made a waiting call.
 * @retval  VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
 *
 * @param   pClient     The client state.
 * @param   hCall       The client's call handle.
 * @param   cParms      Number of parameters.
 * @param   paParms     Array of parameters.
 * @param   fWait       Set if we should wait for a message, clear if to return
 *                      immediately.
 *
 * @note    Caller takes and leave the client's critical section.
 */
static int shClSvcClientMsgPeek(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool fWait)
{
    /*
     * Validate the request.
     */
    ASSERT_GUEST_MSG_RETURN(cParms >= 2, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);

    uint64_t idRestoreCheck = 0;
    uint32_t i              = 0;
    if (paParms[i].type == VBOX_HGCM_SVC_PARM_64BIT)
    {
        idRestoreCheck = paParms[0].u.uint64;
        paParms[0].u.uint64 = 0;
        i++;
    }
    for (; i < cParms; i++)
    {
        ASSERT_GUEST_MSG_RETURN(paParms[i].type == VBOX_HGCM_SVC_PARM_32BIT, ("#%u type=%u\n", i, paParms[i].type),
                                VERR_WRONG_PARAMETER_TYPE);
        paParms[i].u.uint32 = 0;
    }

    /*
     * Check restore session ID.
     */
    if (idRestoreCheck != 0)
    {
        uint64_t idRestore = g_pHelpers->pfnGetVMMDevSessionId(g_pHelpers);
        if (idRestoreCheck != idRestore)
        {
            paParms[0].u.uint64 = idRestore;
            LogFlowFunc(("[Client %RU32] VBOX_SHCL_GUEST_FN_MSG_PEEK_XXX -> VERR_VM_RESTORED (%#RX64 -> %#RX64)\n",
                         pClient->State.uClientID, idRestoreCheck, idRestore));
            return VERR_VM_RESTORED;
        }
        Assert(!g_pHelpers->pfnIsCallRestored(hCall));
    }

    /*
     * Return information about the first message if one is pending in the list.
     */
    PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
    if (pFirstMsg)
    {
        shClSvcMsgSetPeekReturn(pFirstMsg, paParms, cParms);
        LogFlowFunc(("[Client %RU32] VBOX_SHCL_GUEST_FN_MSG_PEEK_XXX -> VINF_SUCCESS (idMsg=%s (%u), cParms=%u)\n",
                     pClient->State.uClientID, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
        return VINF_SUCCESS;
    }

    /*
     * If we cannot wait, fail the call.
     */
    if (!fWait)
    {
        LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_NOWAIT -> VERR_TRY_AGAIN\n", pClient->State.uClientID));
        return VERR_TRY_AGAIN;
    }

    /*
     * Wait for the host to queue a message for this client.
     */
    ASSERT_GUEST_MSG_RETURN(pClient->Pending.uType == 0, ("Already pending! (idClient=%RU32)\n",
                                                           pClient->State.uClientID), VERR_RESOURCE_BUSY);
    pClient->Pending.hHandle = hCall;
    pClient->Pending.cParms  = cParms;
    pClient->Pending.paParms = paParms;
    pClient->Pending.uType   = VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT;
    LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->State.uClientID));
    return VINF_HGCM_ASYNC_EXECUTE;
}

/**
 * Implements VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT.
 *
 * @returns VBox status code.
 * @retval  VINF_SUCCESS if a message was pending and is being returned.
 * @retval  VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
 *
 * @param   pClient     The client state.
 * @param   hCall       The client's call handle.
 * @param   cParms      Number of parameters.
 * @param   paParms     Array of parameters.
 *
 * @note    Caller takes and leave the client's critical section.
 */
static int shClSvcClientMsgOldGet(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    /*
     * Validate input.
     */
    ASSERT_GUEST_RETURN(cParms == VBOX_SHCL_CPARMS_GET_HOST_MSG_OLD, VERR_WRONG_PARAMETER_COUNT);
    ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* id32Msg */
    ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* f32Formats */

    paParms[0].u.uint32 = 0;
    paParms[1].u.uint32 = 0;

    /*
     * If there is a message pending we can return immediately.
     */
    int rc;
    PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
    if (pFirstMsg)
    {
        LogFlowFunc(("[Client %RU32] uMsg=%s (%RU32), cParms=%RU32\n", pClient->State.uClientID,
                     ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));

        rc = shClSvcMsgSetOldWaitReturn(pFirstMsg, paParms, cParms);
        AssertPtr(g_pHelpers);
        rc = g_pHelpers->pfnCallComplete(hCall, rc);
        if (rc != VERR_CANCELLED)
        {
            RTListNodeRemove(&pFirstMsg->ListEntry);
            shClSvcMsgFree(pClient, pFirstMsg);

            rc = VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
        }
    }
    /*
     * Otherwise we must wait.
     */
    else
    {
        ASSERT_GUEST_MSG_RETURN(pClient->Pending.uType == 0, ("Already pending! (idClient=%RU32)\n", pClient->State.uClientID),
                                VERR_RESOURCE_BUSY);

        pClient->Pending.hHandle = hCall;
        pClient->Pending.cParms  = cParms;
        pClient->Pending.paParms = paParms;
        pClient->Pending.uType   = VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT;

        rc = VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */

        LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->State.uClientID));
    }

    LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));
    return rc;
}

/**
 * Implements VBOX_SHCL_GUEST_FN_MSG_GET.
 *
 * @returns VBox status code.
 * @retval  VINF_SUCCESS if message retrieved and removed from the pending queue.
 * @retval  VERR_TRY_AGAIN if no message pending.
 * @retval  VERR_BUFFER_OVERFLOW if a parmeter buffer is too small.  The buffer
 *          size was updated to reflect the required size, though this isn't yet
 *          forwarded to the guest.  (The guest is better of using peek with
 *          parameter count + 2 parameters to get the sizes.)
 * @retval  VERR_MISMATCH if the incoming message ID does not match the pending.
 * @retval  VINF_HGCM_ASYNC_EXECUTE if message was completed already.
 *
 * @param   pClient      The client state.
 * @param   hCall        The client's call handle.
 * @param   cParms       Number of parameters.
 * @param   paParms      Array of parameters.
 *
 * @note    Called from within pClient->CritSect.
 */
static int shClSvcClientMsgGet(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    /*
     * Validate the request.
     */
    uint32_t const idMsgExpected = cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT ? paParms[0].u.uint32
                                 : cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT ? paParms[0].u.uint64
                                 : UINT32_MAX;

    /*
     * Return information about the first message if one is pending in the list.
     */
    PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
    if (pFirstMsg)
    {
        LogFlowFunc(("First message is: %s (%u), cParms=%RU32\n", ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));

        ASSERT_GUEST_MSG_RETURN(pFirstMsg->idMsg == idMsgExpected || idMsgExpected == UINT32_MAX,
                                ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
                                 pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->cParms,
                                 idMsgExpected, ShClHostMsgToStr(idMsgExpected), cParms),
                                VERR_MISMATCH);
        ASSERT_GUEST_MSG_RETURN(pFirstMsg->cParms == cParms,
                                ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
                                 pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->cParms,
                                 idMsgExpected, ShClHostMsgToStr(idMsgExpected), cParms),
                                VERR_WRONG_PARAMETER_COUNT);

        /* Check the parameter types. */
        for (uint32_t i = 0; i < cParms; i++)
            ASSERT_GUEST_MSG_RETURN(pFirstMsg->aParms[i].type == paParms[i].type,
                                    ("param #%u: type %u, caller expected %u (idMsg=%u %s)\n", i, pFirstMsg->aParms[i].type,
                                     paParms[i].type, pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg)),
                                    VERR_WRONG_PARAMETER_TYPE);
        /*
         * Copy out the parameters.
         *
         * No assertions on buffer overflows, and keep going till the end so we can
         * communicate all the required buffer sizes.
         */
        int rc = VINF_SUCCESS;
        for (uint32_t i = 0; i < cParms; i++)
            switch (pFirstMsg->aParms[i].type)
            {
                case VBOX_HGCM_SVC_PARM_32BIT:
                    paParms[i].u.uint32 = pFirstMsg->aParms[i].u.uint32;
                    break;

                case VBOX_HGCM_SVC_PARM_64BIT:
                    paParms[i].u.uint64 = pFirstMsg->aParms[i].u.uint64;
                    break;

                case VBOX_HGCM_SVC_PARM_PTR:
                {
                    uint32_t const cbSrc = pFirstMsg->aParms[i].u.pointer.size;
                    uint32_t const cbDst = paParms[i].u.pointer.size;
                    paParms[i].u.pointer.size = cbSrc; /** @todo Check if this is safe in other layers...
                                                        * Update: Safe, yes, but VMMDevHGCM doesn't pass it along. */
                    if (cbSrc <= cbDst)
                        memcpy(paParms[i].u.pointer.addr, pFirstMsg->aParms[i].u.pointer.addr, cbSrc);
                    else
                    {
                        AssertMsgFailed(("#%u: cbSrc=%RU32 is bigger than cbDst=%RU32\n", i, cbSrc, cbDst));
                        rc = VERR_BUFFER_OVERFLOW;
                    }
                    break;
                }

                default:
                    AssertMsgFailed(("#%u: %u\n", i, pFirstMsg->aParms[i].type));
                    rc = VERR_INTERNAL_ERROR;
                    break;
            }
        if (RT_SUCCESS(rc))
        {
            /*
             * Complete the message and remove the pending message unless the
             * guest raced us and cancelled this call in the meantime.
             */
            AssertPtr(g_pHelpers);
            rc = g_pHelpers->pfnCallComplete(hCall, rc);

            LogFlowFunc(("[Client %RU32] pfnCallComplete -> %Rrc\n", pClient->State.uClientID, rc));

            if (rc != VERR_CANCELLED)
            {
                RTListNodeRemove(&pFirstMsg->ListEntry);
                shClSvcMsgFree(pClient, pFirstMsg);
            }

            return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
        }

        LogFlowFunc(("[Client %RU32] Returning %Rrc\n", pClient->State.uClientID, rc));
        return rc;
    }

    paParms[0].u.uint32 = 0;
    paParms[1].u.uint32 = 0;
    LogFlowFunc(("[Client %RU32] -> VERR_TRY_AGAIN\n", pClient->State.uClientID));
    return VERR_TRY_AGAIN;
}

/**
 * Implements VBOX_SHCL_GUEST_FN_MSG_GET.
 *
 * @returns VBox status code.
 * @retval  VINF_SUCCESS if message retrieved and removed from the pending queue.
 * @retval  VERR_TRY_AGAIN if no message pending.
 * @retval  VERR_MISMATCH if the incoming message ID does not match the pending.
 * @retval  VINF_HGCM_ASYNC_EXECUTE if message was completed already.
 *
 * @param   pClient      The client state.
 * @param   cParms       Number of parameters.
 *
 * @note    Called from within pClient->CritSect.
 */
static int shClSvcClientMsgCancel(PSHCLCLIENT pClient, uint32_t cParms)
{
    /*
     * Validate the request.
     */
    ASSERT_GUEST_MSG_RETURN(cParms == 0, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);

    /*
     * Execute.
     */
    if (pClient->Pending.uType != 0)
    {
        LogFlowFunc(("[Client %RU32] Cancelling waiting thread, isPending=%d, pendingNumParms=%RU32, m_idSession=%x\n",
                     pClient->State.uClientID, pClient->Pending.uType, pClient->Pending.cParms, pClient->State.uSessionID));

        /*
         * The PEEK call is simple: At least two parameters, all set to zero before sleeping.
         */
        int rcComplete;
        if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT)
        {
            Assert(pClient->Pending.cParms >= 2);
            if (pClient->Pending.paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT)
                HGCMSvcSetU64(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
            else
                HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
            rcComplete = VINF_TRY_AGAIN;
        }
        /*
         * The MSG_OLD call is complicated, though we're
         * generally here to wake up someone who is peeking and have two parameters.
         * If there aren't two parameters, fail the call.
         */
        else
        {
            Assert(pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT);
            if (pClient->Pending.cParms > 0)
                HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
            if (pClient->Pending.cParms > 1)
                HGCMSvcSetU32(&pClient->Pending.paParms[1], 0);
            rcComplete = pClient->Pending.cParms == 2 ? VINF_SUCCESS : VERR_TRY_AGAIN;
        }

        g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, rcComplete);

        pClient->Pending.hHandle    = NULL;
        pClient->Pending.paParms    = NULL;
        pClient->Pending.cParms     = 0;
        pClient->Pending.uType      = 0;
        return VINF_SUCCESS;
    }
    return VWRN_NOT_FOUND;
}


/**
 * Wakes up a pending client (i.e. waiting for new messages).
 *
 * @returns VBox status code.
 * @retval  VINF_NO_CHANGE if the client is not in pending mode.
 *
 * @param   pClient             Client to wake up.
 * @note    Caller must enter pClient->CritSect.
 */
int shClSvcClientWakeup(PSHCLCLIENT pClient)
{
    Assert(RTCritSectIsOwner(&pClient->CritSect));
    int rc = VINF_NO_CHANGE;

    if (pClient->Pending.uType != 0)
    {
        LogFunc(("[Client %RU32] Waking up ...\n", pClient->State.uClientID));

        PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
        AssertReturn(pFirstMsg, VERR_INTERNAL_ERROR);

        LogFunc(("[Client %RU32] Current host message is %s (%RU32), cParms=%RU32\n",
                 pClient->State.uClientID, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));

        if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT)
            shClSvcMsgSetPeekReturn(pFirstMsg, pClient->Pending.paParms, pClient->Pending.cParms);
        else if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT) /* Legacy, Guest Additions < 6.1. */
            shClSvcMsgSetOldWaitReturn(pFirstMsg, pClient->Pending.paParms, pClient->Pending.cParms);
        else
            AssertMsgFailedReturn(("pClient->Pending.uType=%u\n", pClient->Pending.uType), VERR_INTERNAL_ERROR_3);

        rc = g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, VINF_SUCCESS);

        if (   rc != VERR_CANCELLED
            && pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT)
        {
            RTListNodeRemove(&pFirstMsg->ListEntry);
            shClSvcMsgFree(pClient, pFirstMsg);
        }

        pClient->Pending.hHandle = NULL;
        pClient->Pending.paParms = NULL;
        pClient->Pending.cParms  = 0;
        pClient->Pending.uType   = 0;
    }
    else
        LogFunc(("[Client %RU32] Not in pending state, skipping wakeup\n", pClient->State.uClientID));

    return rc;
}

/**
 * Requests to read clipboard data from the guest.
 *
 * @returns VBox status code.
 * @param   pClient             Client to request to read data form.
 * @param   fFormat             The format being requested (VBOX_SHCL_FMT_XXX).
 * @param   pidEvent            Event ID for waiting for new data. Optional.
 */
int ShClSvcDataReadRequest(PSHCLCLIENT pClient, SHCLFORMAT fFormat, PSHCLEVENTID pidEvent)
{
    LogFlowFuncEnter();
    if (pidEvent)
        *pidEvent = 0;
    AssertPtrReturn(pClient,  VERR_INVALID_POINTER);

    /*
     * Allocate a message.
     */
    int rc;
    PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient,
                                          pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID
                                          ? VBOX_SHCL_HOST_MSG_READ_DATA_CID : VBOX_SHCL_HOST_MSG_READ_DATA,
                                          2);
    if (pMsg)
    {
        /*
         * Enter the critical section and generate an event.
         */
        RTCritSectEnter(&pClient->CritSect);

        const SHCLEVENTID idEvent = ShClEventIdGenerateAndRegister(&pClient->EventSrc);
        if (idEvent != 0)
        {
            LogFlowFunc(("fFormat=%#x idEvent=%#x\n", fFormat, idEvent));

            /*
             * Format the message
             */
            if (pMsg->idMsg == VBOX_SHCL_HOST_MSG_READ_DATA_CID)
                HGCMSvcSetU64(&pMsg->aParms[0], VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID, idEvent));
            else
                HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_READ_DATA);
            HGCMSvcSetU32(&pMsg->aParms[1], fFormat);

            /*
             * Queue it and wake up the client if it's waiting on a message.
             */
            shClSvcMsgAddAndWakeupClient(pClient, pMsg);
            if (pidEvent)
                *pidEvent = idEvent;
            rc = VINF_SUCCESS;
        }
        else
            rc = VERR_TRY_AGAIN;

        RTCritSectLeave(&pClient->CritSect);
    }
    else
        rc = VERR_NO_MEMORY;

    LogFlowFuncLeaveRC(rc);
    return rc;
}

int ShClSvcDataReadSignal(PSHCLCLIENT pClient, PSHCLCLIENTCMDCTX pCmdCtx,
                          PSHCLDATABLOCK pData)
{
    AssertPtrReturn(pClient, VERR_INVALID_POINTER);
    AssertPtrReturn(pCmdCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(pData,   VERR_INVALID_POINTER);

    LogFlowFuncEnter();

    SHCLEVENTID uEvent;
    if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)) /* Legacy, Guest Additions < 6.1. */
    {
        /* Older Guest Additions (<= VBox 6.0) did not have any context ID handling, so we ASSUME that the last event registered
         * is the one we want to handle (as this all was a synchronous protocol anyway). */
        uEvent = ShClEventGetLast(&pClient->EventSrc);
    }
    else
        uEvent = VBOX_SHCL_CONTEXTID_GET_EVENT(pCmdCtx->uContextID);

    int rc = VINF_SUCCESS;

    PSHCLEVENTPAYLOAD pPayload = NULL;
    if (pData->cbData)
        rc = ShClPayloadAlloc(uEvent, pData->pvData, pData->cbData, &pPayload);

    if (RT_SUCCESS(rc))
    {
        RTCritSectEnter(&pClient->CritSect);
        rc = ShClEventSignal(&pClient->EventSrc, uEvent, pPayload);
        RTCritSectLeave(&pClient->CritSect);
        if (RT_FAILURE(rc))
            ShClPayloadFree(pPayload);
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

/**
 * Reports available VBox clipboard formats to the guest.
 *
 * @returns VBox status code.
 * @param   pClient             Client to request to read data form.
 * @param   fFormats            The formats to report (VBOX_SHCL_FMT_XXX), zero
 *                              is okay (empty the clipboard).
 */
int ShClSvcHostReportFormats(PSHCLCLIENT pClient, SHCLFORMATS fFormats)
{
    LogFlowFuncEnter();
    AssertPtrReturn(pClient,  VERR_INVALID_POINTER);

#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
    /*
     * If transfer mode is set to disabled, don't report the URI list format to the guest.
     */
    if (!(g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_ENABLED))
    {
        LogFlowFunc(("fFormats=%#x -> %#x\n", fFormats, fFormats & ~VBOX_SHCL_FMT_URI_LIST));
        fFormats &= ~VBOX_SHCL_FMT_URI_LIST;
    }
#endif
    LogRel2(("Shared Clipboard: Reporting formats %#x to guest\n", fFormats));

    /*
     * Allocate a message, populate parameters and post it to the client.
     */
    int rc;
    PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, VBOX_SHCL_HOST_MSG_FORMATS_REPORT, 2);
    if (pMsg)
    {
        HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_FORMATS_REPORT);
        HGCMSvcSetU32(&pMsg->aParms[1], fFormats);

        RTCritSectEnter(&pClient->CritSect);
        shClSvcMsgAddAndWakeupClient(pClient, pMsg);
        RTCritSectLeave(&pClient->CritSect);

        /*
         * ...
         */
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
# error fixme
        /* If we announce an URI list, create a transfer locally and also tell the guest to create
         * a transfer on the guest side. */
        if (fFormats & VBOX_SHCL_FMT_URI_LIST)
        {
            rc = shClSvcTransferStart(pClient, SHCLTRANSFERDIR_TO_REMOTE, SHCLSOURCE_LOCAL,
                                      NULL /* pTransfer */);
            if (RT_FAILURE(rc))
                LogRel(("Shared Clipboard: Initializing host write transfer failed with %Rrc\n", rc));
        }
        else
#endif
        {
            pClient->State.fFlags |= SHCLCLIENTSTATE_FLAGS_READ_ACTIVE;
            rc = VINF_SUCCESS;
        }
        /** @todo r=bird: shouldn't we also call shClSvcSetSource(pClient, SHCLSOURCE_LOCAL) here??
         * Looks like the caller of this function does it, but only on windows.  Very helpful. */
    }
    else
        rc = VERR_NO_MEMORY;

    LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * Handles the VBOX_SHCL_GUEST_FN_REPORT_FORMATS message from the guest.
 */
static int shClSvcClientReportFormats(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    /*
     * Check if the service mode allows this operation and whether the guest is
     * supposed to be reading from the host.
     */
    uint32_t uMode = ShClSvcGetMode();
    if (   uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
        || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
    { /* likely */ }
    else
        return VERR_ACCESS_DENIED;

    /*
     * Digest parameters.
     */
    ASSERT_GUEST_RETURN(   cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS
                        || (   cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B
                            && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
                        VERR_WRONG_PARAMETER_COUNT);

    uintptr_t iParm = 0;
    if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
        /* no defined value, so just ignore it */
        iParm++;
    }
    ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
    uint32_t const fFormats = paParms[iParm].u.uint32;
    iParm++;
    if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
        ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
        iParm++;
    }
    Assert(iParm == cParms);

    /*
     * Report the formats.
     *
     * We ignore empty reports if the guest isn't the clipboard owner, this
     * prevents a freshly booted guest with an empty clibpoard from clearing
     * the host clipboard on startup.  Likewise, when a guest shutdown it will
     * typically issue an empty report in case it's the owner, we don't want
     * that to clear host content either.
     */
    int rc;
    if (!fFormats && pClient->State.enmSource != SHCLSOURCE_REMOTE)
        rc = VINF_SUCCESS;
    else
    {
        rc = shClSvcSetSource(pClient, SHCLSOURCE_REMOTE);
        if (RT_SUCCESS(rc))
        {
            if (g_ExtState.pfnExtension)
            {
                SHCLEXTPARMS parms;
                RT_ZERO(parms);
                parms.uFormat = fFormats;

                g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE, &parms, sizeof(parms));
            }
            else
            {
                SHCLCLIENTCMDCTX CmdCtx;
                RT_ZERO(CmdCtx);

                SHCLFORMATDATA FormatData;
                FormatData.fFlags  = 0;
                FormatData.Formats = fFormats;
                rc = ShClSvcImplFormatAnnounce(pClient, &CmdCtx, &FormatData);
            }

            /** @todo r=bird: I'm not sure if the guest should be automatically allowed
             *        to write the host clipboard now.  It would make more sense to disallow
             *        host clipboard reads until the host reports formats.
             *
             *        The writes should only really be allowed upon request from the host,
             *        shouldn't they? (Though, I'm not sure, maybe there are situations
             *        where the guest side will just want to push the content over
             *        immediately while it's still available, I don't quite recall now...
             */
            if (RT_SUCCESS(rc))
                pClient->State.fFlags |= SHCLCLIENTSTATE_FLAGS_WRITE_ACTIVE;
        }
    }

    return rc;
}

/**
 * Handles the VBOX_SHCL_GUEST_FN_DATA_READ message from the guest.
 */
static int shClSvcClientReadData(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    LogFlowFuncEnter();

    /*
     * Check if the service mode allows this operation and whether the guest is
     * supposed to be reading from the host.
     */
    uint32_t uMode = ShClSvcGetMode();
    if (   uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
        || uMode == VBOX_SHCL_MODE_HOST_TO_GUEST)
    { /* likely */ }
    else
        return VERR_ACCESS_DENIED;

    /// @todo r=bird: The management of the SHCLCLIENTSTATE_FLAGS_READ_ACTIVE
    /// makes it impossible for the guest to retrieve more than one format from
    /// the clipboard.  I.e. it can either get the TEXT or the HTML rendering,
    /// but not both.  So, I've disable the check. */
    //ASSERT_GUEST_RETURN(pClient->State.fFlags & SHCLCLIENTSTATE_FLAGS_READ_ACTIVE, VERR_WRONG_ORDER);

    /*
     * Digest parameters.
     *
     * We are dragging some legacy here from the 6.1 dev cycle, a 5 parameter
     * variant which prepends a 64-bit context ID (RAZ as meaning not defined),
     * a 32-bit flag (MBZ, no defined meaning) and switches the last two parameters.
     */
    ASSERT_GUEST_RETURN(   cParms == VBOX_SHCL_CPARMS_DATA_READ
                        || (    cParms == VBOX_SHCL_CPARMS_DATA_READ_61B
                            &&  (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
                        VERR_WRONG_PARAMETER_COUNT);

    uintptr_t iParm = 0;
    SHCLCLIENTCMDCTX cmdCtx;
    RT_ZERO(cmdCtx);
    if (cParms == VBOX_SHCL_CPARMS_DATA_READ_61B)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
        /* This has no defined meaning and was never used, however the guest passed stuff, so ignore it and leave idContext=0. */
        iParm++;
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
        ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
        iParm++;
    }

    SHCLDATABLOCK dataBlock;
    ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
    dataBlock.uFormat = paParms[iParm].u.uint32;
    iParm++;
    if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
        dataBlock.pvData = paParms[iParm].u.pointer.addr;
        dataBlock.cbData = paParms[iParm].u.pointer.size;
        iParm++;
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
        iParm++;
    }
    else
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
        iParm++;
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
        dataBlock.pvData = paParms[iParm].u.pointer.addr;
        dataBlock.cbData = paParms[iParm].u.pointer.size;
        iParm++;
    }
    Assert(iParm == cParms);

    /*
     * For some reason we need to do this (makes absolutely no sense to bird).
     */
    /** @todo r=bird: I really don't get why you need the State.POD.uFormat
     *        member.  I'm sure there is a reason.  Incomplete code? */
    if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
    {
        if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
            pClient->State.POD.uFormat = dataBlock.uFormat;
        /// @todo r=bird: This actively breaks copying different types of data into the
        /// guest (first copy a text snippet, then you cannot copy any bitmaps), so I've
        /// disabled it.
        //ASSERT_GUEST_MSG_RETURN(pClient->State.POD.uFormat == dataBlock.uFormat,
        //                        ("Requested %#x, POD.uFormat=%#x\n", dataBlock.uFormat, pClient->State.POD.uFormat),
        //                        VERR_BAD_EXE_FORMAT /*VERR_INTERNAL_ERROR*/);
    }

    /*
     * Do the reading.
     */
    int rc;
    uint32_t cbActual = 0;

    /* If there is a service extension active, try reading data from it first. */
    if (g_ExtState.pfnExtension)
    {
        SHCLEXTPARMS parms;
        RT_ZERO(parms);

        parms.uFormat  = dataBlock.uFormat;
        parms.u.pvData = dataBlock.pvData;
        parms.cbData   = dataBlock.cbData;

        g_ExtState.fReadingData = true;

        /* Read clipboard data from the extension. */
        rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_READ, &parms, sizeof(parms));
        LogRelFlowFunc(("DATA/Ext: fDelayedAnnouncement=%RTbool fDelayedFormats=%#x cbData=%RU32->%RU32 rc=%Rrc\n",
                        g_ExtState.fDelayedAnnouncement, g_ExtState.fDelayedFormats, dataBlock.cbData, parms.cbData, rc));

        /* Did the extension send the clipboard formats yet?
         * Otherwise, do this now. */
        if (g_ExtState.fDelayedAnnouncement)
        {
            int rc2 = ShClSvcHostReportFormats(pClient, g_ExtState.fDelayedFormats);
            AssertRC(rc2);

            g_ExtState.fDelayedAnnouncement = false;
            g_ExtState.fDelayedFormats = 0;
        }

        g_ExtState.fReadingData = false;

        if (RT_SUCCESS(rc))
            cbActual = parms.cbData;
    }
    else
    {
        rc = ShClSvcImplReadData(pClient, &cmdCtx, &dataBlock, &cbActual);
        LogRelFlowFunc(("DATA/Host: cbData=%RU32->%RU32 rc=%Rrc\n", dataBlock.cbData, cbActual, rc));
    }

    if (RT_SUCCESS(rc))
    {
        /* Return the actual size required to fullfil the request. */
        if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
            HGCMSvcSetU32(&paParms[2], cbActual);
        else
            HGCMSvcSetU32(&paParms[3], cbActual);

        /* If the data to return exceeds the buffer the guest supplies, tell it (and let it try again). */
        if (cbActual >= dataBlock.cbData)
            rc = VINF_BUFFER_OVERFLOW;

        if (rc == VINF_SUCCESS)
        {
            /* Only remove "read active" flag after successful read again. */
            /** @todo r=bird: This doesn't make any effing sense.  What if the guest
             *        wants to read another format???  */
            pClient->State.fFlags &= ~SHCLCLIENTSTATE_FLAGS_READ_ACTIVE;
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

int shClSvcClientWriteData(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    LogFlowFuncEnter();

    /*
     * Check if the service mode allows this operation and whether the guest is
     * supposed to be reading from the host.
     */
    uint32_t uMode = ShClSvcGetMode();
    if (   uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
        || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
    { /* likely */ }
    else
        return VERR_ACCESS_DENIED;

    /** @todo r=bird: This whole active flag stuff is broken, so disabling for now. */
    //if (pClient->State.fFlags & SHCLCLIENTSTATE_FLAGS_WRITE_ACTIVE)
    //{ /* likely */ }
    //else
    //    return VERR_WRONG_ORDER;

    /*
     * Digest parameters.
     *
     * There are 3 different format here, formatunately no parameters have been
     * switch around so it's plain sailing compared to the DATA_READ message.
     */
    ASSERT_GUEST_RETURN(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID
                        ? cParms == VBOX_SHCL_CPARMS_DATA_WRITE || cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B
                        : cParms == VBOX_SHCL_CPARMS_DATA_WRITE_OLD,
                        VERR_WRONG_PARAMETER_COUNT);

    uintptr_t iParm = 0;
    SHCLCLIENTCMDCTX cmdCtx;
    RT_ZERO(cmdCtx);
    if (cParms > VBOX_SHCL_CPARMS_DATA_WRITE_OLD)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
        cmdCtx.uContextID = paParms[iParm].u.uint64;
        uint64_t const idCtxExpected = VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID,
                                                                VBOX_SHCL_CONTEXTID_GET_EVENT(cmdCtx.uContextID));
        ASSERT_GUEST_MSG_RETURN(cmdCtx.uContextID == idCtxExpected,
                                ("Wrong context ID: %#RX64, expected %#RX64\n", cmdCtx.uContextID, idCtxExpected),
                                VERR_INVALID_CONTEXT);
        iParm++;
    }
    else
    {
        /** @todo supply CID from client state? Setting it in ShClSvcDataReadRequest? */
    }
    if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
        ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
        iParm++;
    }
    SHCLDATABLOCK dataBlock;
    ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* Format bit. */
    dataBlock.uFormat = paParms[iParm].u.uint32;
    iParm++;
    if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
    {
        ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* "cbData" - duplicates buffer size. */
        iParm++;
    }
    ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
    dataBlock.pvData = paParms[iParm].u.pointer.addr;
    dataBlock.cbData = paParms[iParm].u.pointer.size;
    iParm++;
    Assert(iParm == cParms);

    /*
     * For some reason we need to do this (makes absolutely no sense to bird).
     */
    /** @todo r=bird: I really don't get why you need the State.POD.uFormat
     *        member.  I'm sure there is a reason.  Incomplete code? */
    if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
    {
        if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
            pClient->State.POD.uFormat = dataBlock.uFormat;
        /** @todo r=bird: this must be buggy to, I've disabled it without testing
         *        though. */
        //ASSERT_GUEST_MSG_RETURN(pClient->State.POD.uFormat == dataBlock.uFormat,
        //                        ("Requested %#x, POD.uFormat=%#x\n", dataBlock.uFormat, pClient->State.POD.uFormat),
        //                        VERR_BAD_EXE_FORMAT /*VERR_INTERNAL_ERROR*/);
    }

    /*
     * Write the data to the active host side clipboard.
     */
    int rc;
    if (g_ExtState.pfnExtension)
    {
        SHCLEXTPARMS parms;
        RT_ZERO(parms);
        parms.uFormat   = dataBlock.uFormat;
        parms.u.pvData  = dataBlock.pvData;
        parms.cbData    = dataBlock.cbData;

        g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_WRITE, &parms, sizeof(parms));
        rc = VINF_SUCCESS;
    }
    else
        rc = ShClSvcImplWriteData(pClient, &cmdCtx, &dataBlock);
    if (RT_SUCCESS(rc))
    {
        /* Remove "write active" flag after successful read again. */
        /** @todo r=bird: This doesn't make any effing sense.  What if the host
         *         wants to have the guest write it another format???  */
        pClient->State.fFlags &= ~SHCLCLIENTSTATE_FLAGS_WRITE_ACTIVE;
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

/**
 * Gets an error from HGCM service parameters.
 *
 * @returns VBox status code.
 * @param   cParms              Number of HGCM parameters supplied in \a paParms.
 * @param   paParms             Array of HGCM parameters.
 * @param   pRc                 Where to store the received error code.
 */
static int shClSvcClientError(uint32_t cParms, VBOXHGCMSVCPARM paParms[], int *pRc)
{
    AssertPtrReturn(paParms, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pRc,     VERR_INVALID_PARAMETER);

    int rc;

    if (cParms == VBOX_SHCL_CPARMS_ERROR)
    {
        rc = HGCMSvcGetU32(&paParms[1], (uint32_t *)pRc); /** @todo int vs. uint32_t !!! */
    }
    else
        rc = VERR_INVALID_PARAMETER;

    LogFlowFuncLeaveRC(rc);
    return rc;
}

int shClSvcSetSource(PSHCLCLIENT pClient, SHCLSOURCE enmSource)
{
    if (!pClient) /* If no client connected (anymore), bail out. */
        return VINF_SUCCESS;

    int rc = VINF_SUCCESS;

    if (ShClSvcLock())
    {
        pClient->State.enmSource = enmSource;

        LogFlowFunc(("Source of client %RU32 is now %RU32\n", pClient->State.uClientID, pClient->State.enmSource));

        ShClSvcUnlock();
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

static int svcInit(void)
{
    int rc = RTCritSectInit(&g_CritSect);

    if (RT_SUCCESS(rc))
    {
        shClSvcModeSet(VBOX_SHCL_MODE_OFF);

        rc = ShClSvcImplInit();

        /* Clean up on failure, because 'svnUnload' will not be called
         * if the 'svcInit' returns an error.
         */
        if (RT_FAILURE(rc))
        {
            RTCritSectDelete(&g_CritSect);
        }
    }

    return rc;
}

static DECLCALLBACK(int) svcUnload(void *)
{
    LogFlowFuncEnter();

    ShClSvcImplDestroy();

    RTCritSectDelete(&g_CritSect);

    return VINF_SUCCESS;
}

static DECLCALLBACK(int) svcDisconnect(void *, uint32_t u32ClientID, void *pvClient)
{
    RT_NOREF(u32ClientID);

    LogFunc(("u32ClientID=%RU32\n", u32ClientID));

    PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
    AssertPtr(pClient);

#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
    shClSvcClientTransfersReset(pClient);
#endif

    ShClSvcImplDisconnect(pClient);

    shClSvcClientDestroy(pClient);

    return VINF_SUCCESS;
}

static DECLCALLBACK(int) svcConnect(void *, uint32_t u32ClientID, void *pvClient, uint32_t fRequestor, bool fRestoring)
{
    RT_NOREF(fRequestor, fRestoring);

    PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
    AssertPtr(pvClient);

    int rc = shClSvcClientInit(pClient, u32ClientID);
    if (RT_SUCCESS(rc))
    {
        rc = ShClSvcImplConnect(pClient, ShClSvcGetHeadless());
        if (RT_SUCCESS(rc))
        {
            /* Sync the host clipboard content with the client. */
            rc = ShClSvcImplSync(pClient);
            if (rc == VINF_NO_CHANGE)
            {
                /*
                 * The sync could return VINF_NO_CHANGE if nothing has changed on the host, but older
                 * Guest Additions rely on the fact that only VINF_SUCCESS indicates a successful connect
                 * to the host service (instead of using RT_SUCCESS()).
                 *
                 * So implicitly set VINF_SUCCESS here to not break older Guest Additions.
                 */
                rc = VINF_SUCCESS;
            }

            if (RT_SUCCESS(rc))
            {
                /* Assign weak pointer to client map .*/
                g_mapClients[u32ClientID] = pClient; /** @todo Handle OOM / collisions? */

                /* For now we ASSUME that the first client ever connected is in charge for
                 * communicating withe the service extension.
                 *
                 ** @todo This needs to be fixed ASAP w/o breaking older guest / host combos. */
                if (g_ExtState.uClientID == 0)
                    g_ExtState.uClientID = u32ClientID;
            }
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

static DECLCALLBACK(void) svcCall(void *,
                                  VBOXHGCMCALLHANDLE callHandle,
                                  uint32_t u32ClientID,
                                  void *pvClient,
                                  uint32_t u32Function,
                                  uint32_t cParms,
                                  VBOXHGCMSVCPARM paParms[],
                                  uint64_t tsArrival)
{
    RT_NOREF(u32ClientID, pvClient, tsArrival);
    PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
    AssertPtr(pClient);

#ifdef LOG_ENABLED
    LogFunc(("u32ClientID=%RU32, fn=%RU32 (%s), cParms=%RU32, paParms=%p\n",
             u32ClientID, u32Function, ShClGuestMsgToStr(u32Function), cParms, paParms));
    for (uint32_t i = 0; i < cParms; i++)
    {
        /** @todo parameters other than 32 bit */
        LogFunc(("    paParms[%d]: type %RU32 - value %RU32\n", i, paParms[i].type, paParms[i].u.uint32));
    }
    LogFunc(("Client state: fFlags=0x%x, fGuestFeatures0=0x%x, fGuestFeatures1=0x%x\n",
             pClient->State.fFlags, pClient->State.fGuestFeatures0, pClient->State.fGuestFeatures1));
#endif

    int rc;
    switch (u32Function)
    {
        case VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT:
            RTCritSectEnter(&pClient->CritSect);
            rc = shClSvcClientMsgOldGet(pClient, callHandle, cParms, paParms);
            RTCritSectLeave(&pClient->CritSect);
            break;

        case VBOX_SHCL_GUEST_FN_CONNECT:
            LogRel(("6.1.0 beta or rc additions detected. Please upgrade!\n"));
            rc = VERR_NOT_IMPLEMENTED;
            break;

        case VBOX_SHCL_GUEST_FN_REPORT_FEATURES:
            rc = shClSvcClientReportFeatures(pClient, callHandle, cParms, paParms);
            break;

        case VBOX_SHCL_GUEST_FN_QUERY_FEATURES:
            rc = shClSvcClientQueryFeatures(callHandle, cParms, paParms);
            break;

        case VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT:
            RTCritSectEnter(&pClient->CritSect);
            rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, false /*fWait*/);
            RTCritSectLeave(&pClient->CritSect);
            break;

        case VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT:
            RTCritSectEnter(&pClient->CritSect);
            rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, true /*fWait*/);
            RTCritSectLeave(&pClient->CritSect);
            break;

        case VBOX_SHCL_GUEST_FN_MSG_GET:
            RTCritSectEnter(&pClient->CritSect);
            rc = shClSvcClientMsgGet(pClient, callHandle, cParms, paParms);
            RTCritSectLeave(&pClient->CritSect);
            break;

        case VBOX_SHCL_GUEST_FN_MSG_CANCEL:
            RTCritSectEnter(&pClient->CritSect);
            rc = shClSvcClientMsgCancel(pClient, cParms);
            RTCritSectLeave(&pClient->CritSect);
            break;

        case VBOX_SHCL_GUEST_FN_REPORT_FORMATS:
            rc = shClSvcClientReportFormats(pClient, cParms, paParms);
            break;

        case VBOX_SHCL_GUEST_FN_DATA_READ:
            rc = shClSvcClientReadData(pClient, cParms, paParms);
            break;

        case VBOX_SHCL_GUEST_FN_DATA_WRITE:
            rc = shClSvcClientWriteData(pClient, cParms, paParms);
            break;

        case VBOX_SHCL_GUEST_FN_ERROR:
        {
            int rcGuest;
            rc = shClSvcClientError(cParms,paParms, &rcGuest);
            if (RT_SUCCESS(rc))
            {
                LogRel(("Shared Clipboard: Error from guest side: %Rrc\n", rcGuest));

                /* Reset client state and start over. */
                shclSvcClientStateReset(&pClient->State);
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
                shClSvcClientTransfersReset(pClient);
#endif
            }
            break;
        }

        default:
        {
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
            if (   u32Function <= VBOX_SHCL_GUEST_FN_LAST
                && (pClient->State.fGuestFeatures0 &  VBOX_SHCL_GF_0_CONTEXT_ID) )
            {
                if (g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_ENABLED)
                    rc = shClSvcTransferHandler(pClient, callHandle, u32Function, cParms, paParms, tsArrival);
                else
                {
                    LogRel2(("Shared Clipboard: File transfers are disabled for this VM\n"));
                    rc = VERR_ACCESS_DENIED;
                }
            }
            else
#endif
            {
                LogRel2(("Shared Clipboard: Unknown guest function: %u (%#x)\n", u32Function, u32Function));
                rc = VERR_NOT_IMPLEMENTED;
            }
            break;
        }
    }

    LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));

    if (rc != VINF_HGCM_ASYNC_EXECUTE)
        g_pHelpers->pfnCallComplete(callHandle, rc);
}

/**
 * Initializes a Shared Clipboard service's client state.
 *
 * @returns VBox status code.
 * @param   pClientState        Client state to initialize.
 * @param   uClientID           Client ID (HGCM) to use for this client state.
 */
int shClSvcClientStateInit(PSHCLCLIENTSTATE pClientState, uint32_t uClientID)
{
    LogFlowFuncEnter();

    shclSvcClientStateReset(pClientState);

    /* Register the client. */
    pClientState->uClientID    = uClientID;

    return VINF_SUCCESS;
}

/**
 * Destroys a Shared Clipboard service's client state.
 *
 * @returns VBox status code.
 * @param   pClientState        Client state to destroy.
 */
int shClSvcClientStateDestroy(PSHCLCLIENTSTATE pClientState)
{
    RT_NOREF(pClientState);

    LogFlowFuncEnter();

    return VINF_SUCCESS;
}

/**
 * Resets a Shared Clipboard service's client state.
 *
 * @param   pClientState    Client state to reset.
 */
void shclSvcClientStateReset(PSHCLCLIENTSTATE pClientState)
{
    LogFlowFuncEnter();

    pClientState->fGuestFeatures0 = VBOX_SHCL_GF_NONE;
    pClientState->fGuestFeatures1 = VBOX_SHCL_GF_NONE;

    pClientState->cbChunkSize        = _64K; /** Make this configurable. */
    pClientState->enmSource          = SHCLSOURCE_INVALID;
    pClientState->fFlags             = SHCLCLIENTSTATE_FLAGS_NONE;

    pClientState->POD.enmDir             = SHCLTRANSFERDIR_UNKNOWN;
    pClientState->POD.uFormat            = VBOX_SHCL_FMT_NONE;
    pClientState->POD.cbToReadWriteTotal = 0;
    pClientState->POD.cbReadWritten      = 0;

#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
    pClientState->Transfers.enmTransferDir = SHCLTRANSFERDIR_UNKNOWN;
#endif


}

/*
 * We differentiate between a function handler for the guest and one for the host.
 */
static DECLCALLBACK(int) svcHostCall(void *,
                                     uint32_t u32Function,
                                     uint32_t cParms,
                                     VBOXHGCMSVCPARM paParms[])
{
    int rc = VINF_SUCCESS;

    LogFlowFunc(("u32Function=%RU32 (%s), cParms=%RU32, paParms=%p\n",
                 u32Function, ShClHostFunctionToStr(u32Function), cParms, paParms));

    switch (u32Function)
    {
        case VBOX_SHCL_HOST_FN_SET_MODE:
        {
            if (cParms != 1)
            {
                rc = VERR_INVALID_PARAMETER;
            }
            else
            {
                uint32_t u32Mode = VBOX_SHCL_MODE_OFF;

                rc = HGCMSvcGetU32(&paParms[0], &u32Mode);
                if (RT_SUCCESS(rc))
                    rc = shClSvcModeSet(u32Mode);
            }

            break;
        }

#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
        case VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE:
        {
            if (cParms != 1)
            {
                rc = VERR_INVALID_PARAMETER;
            }
            else
            {
                uint32_t fTransferMode;
                rc = HGCMSvcGetU32(&paParms[0], &fTransferMode);
                if (RT_SUCCESS(rc))
                    rc = shClSvcTransferModeSet(fTransferMode);
            }
            break;
        }
#endif
        case VBOX_SHCL_HOST_FN_SET_HEADLESS:
        {
            if (cParms != 1)
            {
                rc = VERR_INVALID_PARAMETER;
            }
            else
            {
                uint32_t uHeadless;
                rc = HGCMSvcGetU32(&paParms[0], &uHeadless);
                if (RT_SUCCESS(rc))
                {
                    g_fHeadless = RT_BOOL(uHeadless);
                    LogRel(("Shared Clipboard: Service running in %s mode\n", g_fHeadless ? "headless" : "normal"));
                }
            }
            break;
        }

        default:
        {
#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
            rc = shClSvcTransferHostHandler(u32Function, cParms, paParms);
#else
            rc = VERR_NOT_IMPLEMENTED;
#endif
            break;
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}

#ifndef UNIT_TEST
/**
 * SSM descriptor table for the SHCLCLIENTSTATE structure.
 *
 * @note Saving the session ID not necessary, as they're not persistent across
 *       state save/restore.
 */
static SSMFIELD const s_aShClSSMClientState[] =
{
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, fFlags),
    SSMFIELD_ENTRY_TERM()
};

/**
 * VBox 6.1 Beta 1 version of s_aShClSSMClientState (no flags).
 */
static SSMFIELD const s_aShClSSMClientState61B1[] =
{
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
    SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
    SSMFIELD_ENTRY_TERM()
};

/**
 * SSM descriptor table for the SHCLCLIENTPODSTATE structure.
 */
static SSMFIELD const s_aShClSSMClientPODState[] =
{
    SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, enmDir),
    SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, uFormat),
    SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbToReadWriteTotal),
    SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbReadWritten),
    SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, tsLastReadWrittenMs),
    SSMFIELD_ENTRY_TERM()
};

/**
 * SSM descriptor table for the SHCLCLIENTURISTATE structure.
 */
static SSMFIELD const s_aShClSSMClientTransferState[] =
{
    SSMFIELD_ENTRY(SHCLCLIENTTRANSFERSTATE, enmTransferDir),
    SSMFIELD_ENTRY_TERM()
};

/**
 * SSM descriptor table for the header of the SHCLCLIENTMSG structure.
 * The actual message parameters will be serialized separately.
 */
static SSMFIELD const s_aShClSSMClientMsgHdr[] =
{
    SSMFIELD_ENTRY(SHCLCLIENTMSG, idMsg),
    SSMFIELD_ENTRY(SHCLCLIENTMSG, cParms),
    SSMFIELD_ENTRY_TERM()
};

/**
 * SSM descriptor table for what used to be the VBOXSHCLMSGCTX structure but is
 * now part of SHCLCLIENTMSG.
 */
static SSMFIELD const s_aShClSSMClientMsgCtx[] =
{
    SSMFIELD_ENTRY(SHCLCLIENTMSG, idContext),
    SSMFIELD_ENTRY_TERM()
};
#endif /* !UNIT_TEST */

static DECLCALLBACK(int) svcSaveState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM)
{
    LogFlowFuncEnter();

#ifndef UNIT_TEST
    /*
     * When the state will be restored, pending requests will be reissued
     * by VMMDev. The service therefore must save state as if there were no
     * pending request.
     * Pending requests, if any, will be completed in svcDisconnect.
     */
    RT_NOREF(u32ClientID);
    LogFunc(("u32ClientID=%RU32\n", u32ClientID));

    PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
    AssertPtr(pClient);

    /* Write Shared Clipboard saved state version. */
    SSMR3PutU32(pSSM, VBOX_SHCL_SAVED_STATE_VER_CURRENT);

    int rc = SSMR3PutStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /*fFlags*/, &s_aShClSSMClientState[0], NULL);
    AssertRCReturn(rc, rc);

    rc = SSMR3PutStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /*fFlags*/, &s_aShClSSMClientPODState[0], NULL);
    AssertRCReturn(rc, rc);

    rc = SSMR3PutStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /*fFlags*/, &s_aShClSSMClientTransferState[0], NULL);
    AssertRCReturn(rc, rc);

    /* Serialize the client's internal message queue. */
    uint32_t cMsgs = 0;
    PSHCLCLIENTMSG pMsg;
    RTListForEach(&pClient->MsgQueue, pMsg, SHCLCLIENTMSG, ListEntry)
    {
        cMsgs += 1;
    }

    rc = SSMR3PutU64(pSSM, cMsgs);
    AssertRCReturn(rc, rc);

    RTListForEach(&pClient->MsgQueue, pMsg, SHCLCLIENTMSG, ListEntry)
    {
        SSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgHdr[0], NULL);
        SSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgCtx[0], NULL);

        for (uint32_t iParm = 0; iParm < pMsg->cParms; iParm++)
            HGCMSvcSSMR3Put(&pMsg->aParms[iParm], pSSM);
    }

#else  /* UNIT_TEST */
    RT_NOREF3(u32ClientID, pvClient, pSSM);
#endif /* UNIT_TEST */
    return VINF_SUCCESS;
}

#ifndef UNIT_TEST
static int svcLoadStateV0(uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, uint32_t uVersion)
{
    RT_NOREF(u32ClientID, pvClient, pSSM, uVersion);

    uint32_t uMarker;
    int rc = SSMR3GetU32(pSSM, &uMarker);   /* Begin marker. */
    AssertRC(rc);
    Assert(uMarker == UINT32_C(0x19200102)  /* SSMR3STRUCT_BEGIN */);

    rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Client ID */
    AssertRCReturn(rc, rc);

    bool fValue;
    rc = SSMR3GetBool(pSSM, &fValue);       /* fHostMsgQuit */
    AssertRCReturn(rc, rc);

    rc = SSMR3GetBool(pSSM, &fValue);       /* fHostMsgReadData */
    AssertRCReturn(rc, rc);

    rc = SSMR3GetBool(pSSM, &fValue);       /* fHostMsgFormats */
    AssertRCReturn(rc, rc);

    uint32_t fFormats;
    rc = SSMR3GetU32(pSSM, &fFormats);      /* u32RequestedFormat */
    AssertRCReturn(rc, rc);

    rc = SSMR3GetU32(pSSM, &uMarker);       /* End marker. */
    AssertRCReturn(rc, rc);
    Assert(uMarker == UINT32_C(0x19920406) /* SSMR3STRUCT_END */);

    return VINF_SUCCESS;
}
#endif /* UNIT_TEST */

static DECLCALLBACK(int) svcLoadState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, uint32_t uVersion)
{
    LogFlowFuncEnter();

#ifndef UNIT_TEST

    RT_NOREF(u32ClientID, uVersion);

    PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
    AssertPtr(pClient);

    /* Restore the client data. */
    uint32_t lenOrVer;
    int rc = SSMR3GetU32(pSSM, &lenOrVer);
    AssertRCReturn(rc, rc);

    LogFunc(("u32ClientID=%RU32, lenOrVer=%#RX64\n", u32ClientID, lenOrVer));

    if (lenOrVer == VBOX_SHCL_SAVED_STATE_VER_3_1)
        return svcLoadStateV0(u32ClientID, pvClient, pSSM, uVersion);

    if (   lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1B2
        && lenOrVer <= VBOX_SHCL_SAVED_STATE_VER_CURRENT)
    {
        if (lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1RC1)
        {
            SSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */, &s_aShClSSMClientState[0], NULL);
            SSMR3GetStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /* fFlags */,
                             &s_aShClSSMClientPODState[0], NULL);
        }
        else
            SSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */, &s_aShClSSMClientState61B1[0], NULL);
        rc = SSMR3GetStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /* fFlags */,
                              &s_aShClSSMClientTransferState[0], NULL);
        AssertRCReturn(rc, rc);

        /* Load the client's internal message queue. */
        uint64_t cMsgs;
        rc = SSMR3GetU64(pSSM, &cMsgs);
        AssertRCReturn(rc, rc);
        AssertLogRelMsgReturn(cMsgs < _16K, ("Too many messages: %u (%x)\n", cMsgs, cMsgs), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);

        for (uint64_t i = 0; i < cMsgs; i++)
        {
            union
            {
                SHCLCLIENTMSG Msg;
                uint8_t abPadding[RT_UOFFSETOF(SHCLCLIENTMSG, aParms) + sizeof(VBOXHGCMSVCPARM) * 2];
            } u;

            SSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/, &s_aShClSSMClientMsgHdr[0], NULL);
            rc = SSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/, &s_aShClSSMClientMsgCtx[0], NULL);
            AssertRCReturn(rc, rc);

            AssertLogRelMsgReturn(u.Msg.cParms <= VMMDEV_MAX_HGCM_PARMS,
                                  ("Too many HGCM message parameters: %u (%#x)\n", u.Msg.cParms, u.Msg.cParms),
                                  VERR_SSM_DATA_UNIT_FORMAT_CHANGED);

            PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, u.Msg.idMsg, u.Msg.cParms);
            AssertReturn(pMsg, VERR_NO_MEMORY);
            pMsg->idContext = u.Msg.idContext;

            for (uint32_t p = 0; p < pMsg->cParms; p++)
            {
                rc = HGCMSvcSSMR3Get(&pMsg->aParms[p], pSSM);
                AssertRCReturnStmt(rc, shClSvcMsgFree(pClient, pMsg), rc);
            }

            shClSvcMsgAdd(pClient, pMsg, true /* fAppend */);
        }
    }
    else
    {
        LogRel(("Shared Clipboard: Unsupported saved state version (%#x)\n", lenOrVer));
        return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
    }

    /* Actual host data are to be reported to guest (SYNC). */
    ShClSvcImplSync(pClient);

#else  /* UNIT_TEST */
    RT_NOREF(u32ClientID, pvClient, pSSM, uVersion);
#endif /* UNIT_TEST */
    return VINF_SUCCESS;
}

static DECLCALLBACK(int) extCallback(uint32_t u32Function, uint32_t u32Format, void *pvData, uint32_t cbData)
{
    RT_NOREF(pvData, cbData);

    LogFlowFunc(("u32Function=%RU32\n", u32Function));

    int rc = VINF_SUCCESS;

    /* Figure out if the client in charge for the service extension still is connected. */
    ClipboardClientMap::const_iterator itClient = g_mapClients.find(g_ExtState.uClientID);
    if (itClient != g_mapClients.end())
    {
        PSHCLCLIENT pClient = itClient->second;
        AssertPtr(pClient);

        switch (u32Function)
        {
            /* The service extension announces formats to the guest. */
            case VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE:
            {
                LogFlowFunc(("VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE: g_ExtState.fReadingData=%RTbool\n", g_ExtState.fReadingData));
                if (!g_ExtState.fReadingData)
                    rc = ShClSvcHostReportFormats(pClient, u32Format);
                else
                {
                    g_ExtState.fDelayedAnnouncement = true;
                    g_ExtState.fDelayedFormats = u32Format;
                    rc = VINF_SUCCESS;
                }
                break;
            }

            /* The service extension wants read data from the guest. */
            case VBOX_CLIPBOARD_EXT_FN_DATA_READ:
                rc = ShClSvcDataReadRequest(pClient, u32Format, NULL /* puEvent */);
                break;

            default:
                /* Just skip other messages. */
                break;
        }
    }
    else
        rc = VERR_NOT_FOUND;

    LogFlowFuncLeaveRC(rc);
    return rc;
}

static DECLCALLBACK(int) svcRegisterExtension(void *, PFNHGCMSVCEXT pfnExtension, void *pvExtension)
{
    LogFlowFunc(("pfnExtension=%p\n", pfnExtension));

    SHCLEXTPARMS parms;
    RT_ZERO(parms);

    if (pfnExtension)
    {
        /* Install extension. */
        g_ExtState.pfnExtension = pfnExtension;
        g_ExtState.pvExtension  = pvExtension;

        parms.u.pfnCallback = extCallback;

        g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
    }
    else
    {
        if (g_ExtState.pfnExtension)
            g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));

        /* Uninstall extension. */
        g_ExtState.pfnExtension = NULL;
        g_ExtState.pvExtension = NULL;
    }

    return VINF_SUCCESS;
}

extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable)
{
    int rc = VINF_SUCCESS;

    LogFlowFunc(("pTable=%p\n", pTable));

    if (!VALID_PTR(pTable))
    {
        rc = VERR_INVALID_PARAMETER;
    }
    else
    {
        LogFunc(("pTable->cbSize = %d, ptable->u32Version = 0x%08X\n", pTable->cbSize, pTable->u32Version));

        if (   pTable->cbSize     != sizeof (VBOXHGCMSVCFNTABLE)
            || pTable->u32Version != VBOX_HGCM_SVC_VERSION)
        {
            rc = VERR_VERSION_MISMATCH;
        }
        else
        {
            g_pHelpers = pTable->pHelpers;

            pTable->cbClient = sizeof(SHCLCLIENT);

            pTable->pfnUnload            = svcUnload;
            pTable->pfnConnect           = svcConnect;
            pTable->pfnDisconnect        = svcDisconnect;
            pTable->pfnCall              = svcCall;
            pTable->pfnHostCall          = svcHostCall;
            pTable->pfnSaveState         = svcSaveState;
            pTable->pfnLoadState         = svcLoadState;
            pTable->pfnRegisterExtension = svcRegisterExtension;
            pTable->pfnNotify            = NULL;
            pTable->pvService            = NULL;

            /* Service specific initialization. */
            rc = svcInit();
        }
    }

    LogFlowFunc(("Returning %Rrc\n", rc));
    return rc;
}