summaryrefslogtreecommitdiffstats
path: root/src/VBox/ValidationKit/utils/usb/UsbTestService.cpp
blob: dc77f2d484fbc9c1e80dafb229c5d95883f25314 (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
/* $Id: UsbTestService.cpp $ */
/** @file
 * UsbTestService - Remote USB test configuration and execution server.
 */

/*
 * Copyright (C) 2010-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.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP RTLOGGROUP_DEFAULT
#include <iprt/alloca.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/critsect.h>
#include <iprt/crc.h>
#include <iprt/ctype.h>
#include <iprt/dir.h>
#include <iprt/env.h>
#include <iprt/err.h>
#include <iprt/getopt.h>
#include <iprt/handle.h>
#include <iprt/initterm.h>
#include <iprt/json.h>
#include <iprt/list.h>
#include <iprt/log.h>
#include <iprt/mem.h>
#include <iprt/message.h>
#include <iprt/param.h>
#include <iprt/path.h>
#include <iprt/pipe.h>
#include <iprt/poll.h>
#include <iprt/process.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/thread.h>

#include "UsbTestServiceInternal.h"
#include "UsbTestServiceGadget.h"
#include "UsbTestServicePlatform.h"



/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/

#define UTS_USBIP_PORT_FIRST 3240
#define UTS_USBIP_PORT_LAST  3340

/**
 * UTS client state.
 */
typedef enum UTSCLIENTSTATE
{
    /** Invalid client state. */
    UTSCLIENTSTATE_INVALID = 0,
    /** Client is initialising, only the HOWDY and BYE packets are allowed. */
    UTSCLIENTSTATE_INITIALISING,
    /** Client is in fully cuntional state and ready to process all requests. */
    UTSCLIENTSTATE_READY,
    /** Client is destroying. */
    UTSCLIENTSTATE_DESTROYING,
    /** 32bit hack. */
    UTSCLIENTSTATE_32BIT_HACK = 0x7fffffff
} UTSCLIENTSTATE;

/**
 * UTS client instance.
 */
typedef struct UTSCLIENT
{
    /** List node for new clients. */
    RTLISTNODE             NdLst;
    /** The current client state. */
    UTSCLIENTSTATE         enmState;
    /** Transport backend specific data. */
    PUTSTRANSPORTCLIENT    pTransportClient;
    /** Client hostname. */
    char                  *pszHostname;
    /** Gadget host handle. */
    UTSGADGETHOST          hGadgetHost;
    /** Handle fo the current configured gadget. */
    UTSGADGET              hGadget;
} UTSCLIENT;
/** Pointer to a UTS client instance. */
typedef UTSCLIENT *PUTSCLIENT;


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/**
 * Transport layers.
 */
static const PCUTSTRANSPORT g_apTransports[] =
{
    &g_TcpTransport,
    //&g_SerialTransport,
    //&g_FileSysTransport,
    //&g_GuestPropTransport,
    //&g_TestDevTransport,
};

/** The select transport layer. */
static PCUTSTRANSPORT       g_pTransport;
/** The config path. */
static char                 g_szCfgPath[RTPATH_MAX];
/** The scratch path. */
static char                 g_szScratchPath[RTPATH_MAX];
/** The default scratch path. */
static char                 g_szDefScratchPath[RTPATH_MAX];
/** The CD/DVD-ROM path. */
static char                 g_szCdRomPath[RTPATH_MAX];
/** The default CD/DVD-ROM path. */
static char                 g_szDefCdRomPath[RTPATH_MAX];
/** The operating system short name. */
static char                 g_szOsShortName[16];
/** The CPU architecture short name. */
static char                 g_szArchShortName[16];
/** The combined "OS.arch" name. */
static char                 g_szOsDotArchShortName[32];
/** The combined "OS/arch" name. */
static char                 g_szOsSlashArchShortName[32];
/** The executable suffix. */
static char                 g_szExeSuff[8];
/** The shell script suffix. */
static char                 g_szScriptSuff[8];
/** Whether to display the output of the child process or not.  */
static bool                 g_fDisplayOutput = true;
/** Whether to terminate or not.
 * @todo implement signals and stuff.  */
static bool volatile        g_fTerminate = false;
/** Configuration AST. */
static RTJSONVAL            g_hCfgJson = NIL_RTJSONVAL;
/** Pipe for communicating with the serving thread about new clients. - read end */
static RTPIPE               g_hPipeR;
/** Pipe for communicating with the serving thread about new clients. - write end */
static RTPIPE               g_hPipeW;
/** Thread serving connected clients. */
static RTTHREAD             g_hThreadServing;
/** Critical section protecting the list of new clients. */
static RTCRITSECT           g_CritSectClients;
/** List of new clients waiting to be picked up by the client worker thread. */
static RTLISTANCHOR         g_LstClientsNew;
/** First USB/IP port we can use. */
static uint16_t             g_uUsbIpPortFirst = UTS_USBIP_PORT_FIRST;
/** Last USB/IP port we can use. */
static uint16_t             g_uUsbIpPortLast  = UTS_USBIP_PORT_LAST;
/** Next free port. */
static uint16_t             g_uUsbIpPortNext  = UTS_USBIP_PORT_FIRST;



/**
 * Returns the string represenation of the given state.
 */
static const char *utsClientStateStringify(UTSCLIENTSTATE enmState)
{
    switch (enmState)
    {
        case UTSCLIENTSTATE_INVALID:
            return "INVALID";
        case UTSCLIENTSTATE_INITIALISING:
            return "INITIALISING";
        case UTSCLIENTSTATE_READY:
            return "READY";
        case UTSCLIENTSTATE_DESTROYING:
            return "DESTROYING";
        case UTSCLIENTSTATE_32BIT_HACK:
        default:
            break;
    }

    AssertMsgFailed(("Unknown state %#x\n", enmState));
    return "UNKNOWN";
}

/**
 * Calculates the checksum value, zero any padding space and send the packet.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPkt                The packet to send.  Must point to a correctly
 *                              aligned buffer.
 */
static int utsSendPkt(PUTSCLIENT pClient, PUTSPKTHDR pPkt)
{
    Assert(pPkt->cb >= sizeof(*pPkt));
    pPkt->uCrc32 = RTCrc32(pPkt->achOpcode, pPkt->cb - RT_UOFFSETOF(UTSPKTHDR, achOpcode));
    if (pPkt->cb != RT_ALIGN_32(pPkt->cb, UTSPKT_ALIGNMENT))
        memset((uint8_t *)pPkt + pPkt->cb, '\0', RT_ALIGN_32(pPkt->cb, UTSPKT_ALIGNMENT) - pPkt->cb);

    Log(("utsSendPkt: cb=%#x opcode=%.8s\n", pPkt->cb, pPkt->achOpcode));
    Log2(("%.*Rhxd\n", RT_MIN(pPkt->cb, 256), pPkt));
    int rc = g_pTransport->pfnSendPkt(pClient->pTransportClient, pPkt);
    while (RT_UNLIKELY(rc == VERR_INTERRUPTED) && !g_fTerminate)
        rc = g_pTransport->pfnSendPkt(pClient->pTransportClient, pPkt);
    if (RT_FAILURE(rc))
        Log(("utsSendPkt: rc=%Rrc\n", rc));

    return rc;
}

/**
 * Sends a babble reply and disconnects the client (if applicable).
 *
 * @param   pClient             The UTS client structure.
 * @param   pszOpcode           The BABBLE opcode.
 */
static void utsReplyBabble(PUTSCLIENT pClient, const char *pszOpcode)
{
    UTSPKTHDR Reply;
    Reply.cb     = sizeof(Reply);
    Reply.uCrc32 = 0;
    memcpy(Reply.achOpcode, pszOpcode, sizeof(Reply.achOpcode));

    g_pTransport->pfnBabble(pClient->pTransportClient, &Reply, 20*1000);
}

/**
 * Receive and validate a packet.
 *
 * Will send bable responses to malformed packets that results in a error status
 * code.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   ppPktHdr            Where to return the packet on success.  Free
 *                              with RTMemFree.
 * @param   fAutoRetryOnFailure Whether to retry on error.
 */
static int utsRecvPkt(PUTSCLIENT pClient, PPUTSPKTHDR ppPktHdr, bool fAutoRetryOnFailure)
{
    for (;;)
    {
        PUTSPKTHDR pPktHdr;
        int rc = g_pTransport->pfnRecvPkt(pClient->pTransportClient, &pPktHdr);
        if (RT_SUCCESS(rc))
        {
            /* validate the packet. */
            if (   pPktHdr->cb >= sizeof(UTSPKTHDR)
                && pPktHdr->cb < UTSPKT_MAX_SIZE)
            {
                Log2(("utsRecvPkt: pPktHdr=%p cb=%#x crc32=%#x opcode=%.8s\n"
                      "%.*Rhxd\n",
                      pPktHdr, pPktHdr->cb, pPktHdr->uCrc32, pPktHdr->achOpcode, RT_MIN(pPktHdr->cb, 256), pPktHdr));
                uint32_t uCrc32Calc = pPktHdr->uCrc32 != 0
                                    ? RTCrc32(&pPktHdr->achOpcode[0], pPktHdr->cb - RT_UOFFSETOF(UTSPKTHDR, achOpcode))
                                    : 0;
                if (pPktHdr->uCrc32 == uCrc32Calc)
                {
                    AssertCompileMemberSize(UTSPKTHDR, achOpcode, 8);
                    if (   RT_C_IS_UPPER(pPktHdr->achOpcode[0])
                        && RT_C_IS_UPPER(pPktHdr->achOpcode[1])
                        && (RT_C_IS_UPPER(pPktHdr->achOpcode[2]) || pPktHdr->achOpcode[2] == ' ')
                        && (RT_C_IS_PRINT(pPktHdr->achOpcode[3]) || pPktHdr->achOpcode[3] == ' ')
                        && (RT_C_IS_PRINT(pPktHdr->achOpcode[4]) || pPktHdr->achOpcode[4] == ' ')
                        && (RT_C_IS_PRINT(pPktHdr->achOpcode[5]) || pPktHdr->achOpcode[5] == ' ')
                        && (RT_C_IS_PRINT(pPktHdr->achOpcode[6]) || pPktHdr->achOpcode[6] == ' ')
                        && (RT_C_IS_PRINT(pPktHdr->achOpcode[7]) || pPktHdr->achOpcode[7] == ' ')
                       )
                    {
                        Log(("utsRecvPkt: cb=%#x opcode=%.8s\n", pPktHdr->cb, pPktHdr->achOpcode));
                        *ppPktHdr = pPktHdr;
                        return rc;
                    }

                    rc = VERR_IO_BAD_COMMAND;
                }
                else
                {
                    Log(("utsRecvPkt: cb=%#x opcode=%.8s crc32=%#x actual=%#x\n",
                         pPktHdr->cb, pPktHdr->achOpcode, pPktHdr->uCrc32, uCrc32Calc));
                    rc = VERR_IO_CRC;
                }
            }
            else
                rc = VERR_IO_BAD_LENGTH;

            /* Send babble reply and disconnect the client if the transport is
               connection oriented. */
            if (rc == VERR_IO_BAD_LENGTH)
                utsReplyBabble(pClient, "BABBLE L");
            else if (rc == VERR_IO_CRC)
                utsReplyBabble(pClient, "BABBLE C");
            else if (rc == VERR_IO_BAD_COMMAND)
                utsReplyBabble(pClient, "BABBLE O");
            else
                utsReplyBabble(pClient, "BABBLE  ");
            RTMemFree(pPktHdr);
        }

        /* Try again or return failure? */
        if (   g_fTerminate
            || rc != VERR_INTERRUPTED
            || !fAutoRetryOnFailure
            )
        {
            Log(("utsRecvPkt: rc=%Rrc\n", rc));
            return rc;
        }
    }
}

/**
 * Make a simple reply, only status opcode.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pReply              The reply packet.
 * @param   pszOpcode           The status opcode.  Exactly 8 chars long, padd
 *                              with space.
 * @param   cbExtra             Bytes in addition to the header.
 */
static int utsReplyInternal(PUTSCLIENT pClient, PUTSPKTSTS pReply, const char *pszOpcode, size_t cbExtra)
{
    /* copy the opcode, don't be too strict in case of a padding screw up. */
    size_t cchOpcode = strlen(pszOpcode);
    if (RT_LIKELY(cchOpcode == sizeof(pReply->Hdr.achOpcode)))
        memcpy(pReply->Hdr.achOpcode, pszOpcode, sizeof(pReply->Hdr.achOpcode));
    else
    {
        Assert(cchOpcode == sizeof(pReply->Hdr.achOpcode));
        while (cchOpcode > 0 && pszOpcode[cchOpcode - 1] == ' ')
            cchOpcode--;
        AssertMsgReturn(cchOpcode < sizeof(pReply->Hdr.achOpcode), ("%d/'%.8s'\n", cchOpcode, pszOpcode), VERR_INTERNAL_ERROR_4);
        memcpy(pReply->Hdr.achOpcode, pszOpcode, cchOpcode);
        memset(&pReply->Hdr.achOpcode[cchOpcode], ' ', sizeof(pReply->Hdr.achOpcode) - cchOpcode);
    }

    pReply->Hdr.cb     = (uint32_t)sizeof(UTSPKTSTS) + (uint32_t)cbExtra;
    pReply->Hdr.uCrc32 = 0;

    return utsSendPkt(pClient, &pReply->Hdr);
}

/**
 * Make a simple reply, only status opcode.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The original packet (for future use).
 * @param   pszOpcode           The status opcode.  Exactly 8 chars long, padd
 *                              with space.
 */
static int utsReplySimple(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode)
{
    UTSPKTSTS Pkt;

    RT_ZERO(Pkt);
    Pkt.rcReq = VINF_SUCCESS;
    Pkt.cchStsMsg = 0;
    NOREF(pPktHdr);
    return utsReplyInternal(pClient, &Pkt, pszOpcode, 0);
}

/**
 * Acknowledges a packet with success.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The original packet (for future use).
 */
static int utsReplyAck(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    return utsReplySimple(pClient, pPktHdr, "ACK     ");
}

/**
 * Replies with a failure.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The original packet (for future use).
 * @param   rcReq               Status code.
 * @param   pszOpcode           The status opcode.  Exactly 8 chars long, padd
 *                              with space.
 * @param   rcReq               The status code of the request.
 * @param   pszDetailFmt        Longer description of the problem (format string).
 * @param   va                  Format arguments.
 */
static int utsReplyFailureV(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode, int rcReq, const char *pszDetailFmt, va_list va)
{
    NOREF(pPktHdr);
    union
    {
        UTSPKTSTS   Hdr;
        char        ach[256];
    } uPkt;

    RT_ZERO(uPkt);
    size_t cchDetail = RTStrPrintfV(&uPkt.ach[sizeof(UTSPKTSTS)],
                                    sizeof(uPkt) - sizeof(UTSPKTSTS),
                                    pszDetailFmt, va);
    uPkt.Hdr.rcReq = rcReq;
    uPkt.Hdr.cchStsMsg = cchDetail;
    return utsReplyInternal(pClient, &uPkt.Hdr, pszOpcode, cchDetail + 1);
}

/**
 * Replies with a failure.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The original packet (for future use).
 * @param   pszOpcode           The status opcode.  Exactly 8 chars long, padd
 *                              with space.
 * @param   rcReq               Status code.
 * @param   pszDetailFmt        Longer description of the problem (format string).
 * @param   ...                 Format arguments.
 */
static int utsReplyFailure(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode, int rcReq, const char *pszDetailFmt, ...)
{
    va_list va;
    va_start(va, pszDetailFmt);
    int rc = utsReplyFailureV(pClient, pPktHdr, pszOpcode, rcReq, pszDetailFmt, va);
    va_end(va);
    return rc;
}

/**
 * Replies according to the return code.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet to reply to.
 * @param   rcOperation         The status code to report.
 * @param   pszOperationFmt     The operation that failed.  Typically giving the
 *                              function call with important arguments.
 * @param   ...                 Arguments to the format string.
 */
static int utsReplyRC(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, int rcOperation, const char *pszOperationFmt, ...)
{
    if (RT_SUCCESS(rcOperation))
        return utsReplyAck(pClient, pPktHdr);

    char    szOperation[128];
    va_list va;
    va_start(va, pszOperationFmt);
    RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
    va_end(va);

    return utsReplyFailure(pClient, pPktHdr, "FAILED  ", rcOperation, "%s failed with rc=%Rrc (opcode '%.8s')",
                           szOperation, rcOperation, pPktHdr->achOpcode);
}

#if 0 /* unused */
/**
 * Signal a bad packet minum size.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet to reply to.
 * @param   cbMin               The minimum size.
 */
static int utsReplyBadMinSize(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, size_t cbMin)
{
    return utsReplyFailure(pClient, pPktHdr, "BAD SIZE", VERR_INVALID_PARAMETER, "Expected at least %zu bytes, got %u (opcode '%.8s')",
                           cbMin, pPktHdr->cb, pPktHdr->achOpcode);
}
#endif

/**
 * Signal a bad packet exact size.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet to reply to.
 * @param   cb                  The wanted size.
 */
static int utsReplyBadSize(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, size_t cb)
{
    return utsReplyFailure(pClient, pPktHdr, "BAD SIZE", VERR_INVALID_PARAMETER, "Expected at %zu bytes, got %u  (opcode '%.8s')",
                           cb, pPktHdr->cb, pPktHdr->achOpcode);
}

#if 0 /* unused */
/**
 * Deals with a command that isn't implemented yet.
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet which opcode isn't implemented.
 */
static int utsReplyNotImplemented(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    return utsReplyFailure(pClient, pPktHdr, "NOT IMPL", VERR_NOT_IMPLEMENTED, "Opcode '%.8s' is not implemented", pPktHdr->achOpcode);
}
#endif

/**
 * Deals with a unknown command.
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet to reply to.
 */
static int utsReplyUnknown(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    return utsReplyFailure(pClient, pPktHdr, "UNKNOWN ", VERR_NOT_FOUND, "Opcode '%.8s' is not known", pPktHdr->achOpcode);
}

/**
 * Deals with a command which contains an unterminated string.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet containing the unterminated string.
 */
static int utsReplyBadStrTermination(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    return utsReplyFailure(pClient, pPktHdr, "BAD TERM", VERR_INVALID_PARAMETER, "Opcode '%.8s' contains an unterminated string", pPktHdr->achOpcode);
}

/**
 * Deals with a command sent in an invalid client state.
 *
 * @returns IPRT status code of the send.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The packet containing the unterminated string.
 */
static int utsReplyInvalidState(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    return utsReplyFailure(pClient, pPktHdr, "INVSTATE", VERR_INVALID_STATE, "Opcode '%.8s' is not supported at client state '%s",
                           pPktHdr->achOpcode, utsClientStateStringify(pClient->enmState));
}

/**
 * Parses an unsigned integer from the given value string.
 *
 * @returns IPRT status code.
 * @retval  VERR_OUT_OF_RANGE if the parsed value exceeds the given maximum.
 * @param   pszVal              The value string.
 * @param   uMax                The maximum value.
 * @param   pu64                Where to store the parsed number on success.
 */
static int utsDoGadgetCreateCfgParseUInt(const char *pszVal, uint64_t uMax, uint64_t *pu64)
{
    int rc = RTStrToUInt64Ex(pszVal, NULL, 0, pu64);
    if (RT_SUCCESS(rc))
    {
        if (*pu64 > uMax)
            rc = VERR_OUT_OF_RANGE;
    }

    return rc;
}

/**
 * Parses a signed integer from the given value string.
 *
 * @returns IPRT status code.
 * @retval  VERR_OUT_OF_RANGE if the parsed value exceeds the given range.
 * @param   pszVal              The value string.
 * @param   iMin                The minimum value.
 * @param   iMax                The maximum value.
 * @param   pi64                Where to store the parsed number on success.
 */
static int utsDoGadgetCreateCfgParseInt(const char *pszVal, int64_t iMin, int64_t iMax, int64_t *pi64)
{
    int rc = RTStrToInt64Ex(pszVal, NULL, 0, pi64);
    if (RT_SUCCESS(rc))
    {
        if (   *pi64 < iMin
            || *pi64 > iMax)
            rc = VERR_OUT_OF_RANGE;
    }

    return rc;
}

/**
 * Parses the given config item and fills in the value according to the given type.
 *
 * @returns IPRT status code.
 * @param   pCfgItem            The config item to parse.
 * @param   u32Type             The config type.
 * @param   pszVal              The value encoded as a string.
 */
static int utsDoGadgetCreateCfgParseItem(PUTSGADGETCFGITEM pCfgItem, uint32_t u32Type,
                                         const char *pszVal)
{
    int rc = VINF_SUCCESS;

    switch (u32Type)
    {
        case UTSPKT_GDGT_CFG_ITEM_TYPE_BOOLEAN:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_BOOLEAN;
            if (   RTStrICmp(pszVal, "enabled")
                || RTStrICmp(pszVal, "1")
                || RTStrICmp(pszVal, "true"))
                pCfgItem->Val.u.f = true;
            else if (   RTStrICmp(pszVal, "disabled")
                     || RTStrICmp(pszVal, "0")
                     || RTStrICmp(pszVal, "false"))
                pCfgItem->Val.u.f = false;
            else
                rc = VERR_INVALID_PARAMETER;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_STRING:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_STRING;
            pCfgItem->Val.u.psz = RTStrDup(pszVal);
            if (!pCfgItem->Val.u.psz)
                rc = VERR_NO_STR_MEMORY;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT8:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT8;

            uint64_t u64;
            rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT8_MAX, &u64);
            if (RT_SUCCESS(rc))
                pCfgItem->Val.u.u8 = (uint8_t)u64;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT16:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT16;

            uint64_t u64;
            rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT16_MAX, &u64);
            if (RT_SUCCESS(rc))
                pCfgItem->Val.u.u16 = (uint16_t)u64;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT32:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT32;

            uint64_t u64;
            rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT32_MAX, &u64);
            if (RT_SUCCESS(rc))
                pCfgItem->Val.u.u32 = (uint32_t)u64;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT64:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT64;
            rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT64_MAX, &pCfgItem->Val.u.u64);
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_INT8:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT8;

            int64_t i64;
            rc = utsDoGadgetCreateCfgParseInt(pszVal, INT8_MIN, INT8_MAX, &i64);
            if (RT_SUCCESS(rc))
                pCfgItem->Val.u.i8 = (int8_t)i64;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_INT16:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT16;

            int64_t i64;
            rc = utsDoGadgetCreateCfgParseInt(pszVal, INT16_MIN, INT16_MAX, &i64);
            if (RT_SUCCESS(rc))
                pCfgItem->Val.u.i16 = (int16_t)i64;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_INT32:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT32;

            int64_t i64;
            rc = utsDoGadgetCreateCfgParseInt(pszVal, INT32_MIN, INT32_MAX, &i64);
            if (RT_SUCCESS(rc))
                pCfgItem->Val.u.i32 = (int32_t)i64;
            break;
        }
        case UTSPKT_GDGT_CFG_ITEM_TYPE_INT64:
        {
            pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT64;
            rc = utsDoGadgetCreateCfgParseInt(pszVal, INT64_MIN, INT64_MAX, &pCfgItem->Val.u.i64);
            break;
        }
        default:
            rc = VERR_INVALID_PARAMETER;
    }

    return rc;
}

/**
 * Creates the configuration from the given GADGET CREATE packet.
 *
 * @returns IPRT status code.
 * @param   pCfgItem            The first config item header in the request packet.
 * @param   cCfgItems           Number of config items in the packet to parse.
 * @param   cbPkt               Number of bytes left in the packet for the config data.
 * @param   paCfg               The array of configuration items to fill.
 */
static int utsDoGadgetCreateFillCfg(PUTSPKTREQGDGTCTORCFGITEM pCfgItem, unsigned cCfgItems,
                                    size_t cbPkt, PUTSGADGETCFGITEM paCfg)
{
    int rc = VINF_SUCCESS;
    unsigned idxCfg = 0;

    while (   RT_SUCCESS(rc)
           && cCfgItems
           && cbPkt)
    {
        if (cbPkt >= sizeof(UTSPKTREQGDGTCTORCFGITEM))
        {
            cbPkt -= sizeof(UTSPKTREQGDGTCTORCFGITEM);
            if (pCfgItem->u32KeySize + pCfgItem->u32ValSize >= cbPkt)
            {
                const char *pszKey = (const char *)(pCfgItem + 1);
                const char *pszVal = pszKey + pCfgItem->u32KeySize;

                /* Validate termination. */
                if (   *(pszKey + pCfgItem->u32KeySize - 1) != '\0'
                    || *(pszVal + pCfgItem->u32ValSize - 1) != '\0')
                    rc = VERR_INVALID_PARAMETER;
                else
                {
                    paCfg[idxCfg].pszKey = RTStrDup(pszKey);

                    rc = utsDoGadgetCreateCfgParseItem(&paCfg[idxCfg], pCfgItem->u32Type, pszVal);
                    if (RT_SUCCESS(rc))
                    {
                        cbPkt -= pCfgItem->u32KeySize + pCfgItem->u32ValSize;
                        cCfgItems--;
                        idxCfg++;
                        pCfgItem = (PUTSPKTREQGDGTCTORCFGITEM)(pszVal + pCfgItem->u32ValSize);
                    }
                }
            }
            else
                rc = VERR_INVALID_PARAMETER;
        }
        else
            rc = VERR_INVALID_PARAMETER;
    }

    return rc;
}

/**
 * Verifies and acknowledges a "BYE" request.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The howdy packet.
 */
static int utsDoBye(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    int rc;
    if (pPktHdr->cb == sizeof(UTSPKTHDR))
        rc = utsReplyAck(pClient, pPktHdr);
    else
        rc = utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTHDR));
    return rc;
}

/**
 * Verifies and acknowledges a "HOWDY" request.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The howdy packet.
 */
static int utsDoHowdy(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    int rc = VINF_SUCCESS;

    if (pPktHdr->cb != sizeof(UTSPKTREQHOWDY))
        return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQHOWDY));

    if (pClient->enmState != UTSCLIENTSTATE_INITIALISING)
        return utsReplyInvalidState(pClient, pPktHdr);

    PUTSPKTREQHOWDY pReq = (PUTSPKTREQHOWDY)pPktHdr;

    if (pReq->uVersion != UTS_PROTOCOL_VS)
        return utsReplyRC(pClient, pPktHdr, VERR_VERSION_MISMATCH, "The given version %#x is not supported", pReq->uVersion);

    /* Verify hostname string. */
    if (pReq->cchHostname >= sizeof(pReq->achHostname))
        return utsReplyBadSize(pClient, pPktHdr, sizeof(pReq->achHostname) - 1);

    if (pReq->achHostname[pReq->cchHostname] != '\0')
        return utsReplyBadStrTermination(pClient, pPktHdr);

    /* Extract string. */
    pClient->pszHostname = RTStrDup(&pReq->achHostname[0]);
    if (!pClient->pszHostname)
        return utsReplyRC(pClient, pPktHdr, VERR_NO_MEMORY, "Failed to allocate memory for the hostname string");

    if (pReq->fUsbConn & UTSPKT_HOWDY_CONN_F_PHYSICAL)
        return utsReplyRC(pClient, pPktHdr, VERR_NOT_SUPPORTED, "Physical connections are not yet supported");

    if (pReq->fUsbConn & UTSPKT_HOWDY_CONN_F_USBIP)
    {
        /* Set up the USB/IP server, find an unused port we can start the server on. */
        UTSGADGETCFGITEM aCfg[2];

        uint16_t uPort = g_uUsbIpPortNext;

        if (g_uUsbIpPortNext == g_uUsbIpPortLast)
            g_uUsbIpPortNext = g_uUsbIpPortFirst;
        else
            g_uUsbIpPortNext++;

        aCfg[0].pszKey      = "UsbIp/Port";
        aCfg[0].Val.enmType = UTSGADGETCFGTYPE_UINT16;
        aCfg[0].Val.u.u16   = uPort;
        aCfg[1].pszKey      = NULL;

        rc = utsGadgetHostCreate(UTSGADGETHOSTTYPE_USBIP, &aCfg[0], &pClient->hGadgetHost);
        if (RT_SUCCESS(rc))
        {
            /* Send the reply with the configured USB/IP port. */
            UTSPKTREPHOWDY Rep;

            RT_ZERO(Rep);

            Rep.uVersion         = UTS_PROTOCOL_VS;
            Rep.fUsbConn         = UTSPKT_HOWDY_CONN_F_USBIP;
            Rep.uUsbIpPort       = uPort;
            Rep.cUsbIpDevices    = 1;
            Rep.cPhysicalDevices = 0;

            rc = utsReplyInternal(pClient, &Rep.Sts, "ACK     ", sizeof(Rep) - sizeof(UTSPKTSTS));
            if (RT_SUCCESS(rc))
            {
                g_pTransport->pfnNotifyHowdy(pClient->pTransportClient);
                pClient->enmState = UTSCLIENTSTATE_READY;
                RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
            }
        }
        else
            return utsReplyRC(pClient, pPktHdr, rc, "Creating the USB/IP gadget host failed");
    }
    else
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_PARAMETER, "No access method requested");

    return rc;
}

/**
 * Verifies and processes a "GADGET CREATE" request.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The gadget create packet.
 */
static int utsDoGadgetCreate(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    int rc = VINF_SUCCESS;

    if (pPktHdr->cb < sizeof(UTSPKTREQGDGTCTOR))
        return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTCTOR));

    if (   pClient->enmState != UTSCLIENTSTATE_READY
        || pClient->hGadgetHost == NIL_UTSGADGETHOST)
        return utsReplyInvalidState(pClient, pPktHdr);

    PUTSPKTREQGDGTCTOR pReq = (PUTSPKTREQGDGTCTOR)pPktHdr;

    if (pReq->u32GdgtType != UTSPKT_GDGT_CREATE_TYPE_TEST)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_PARAMETER, "The given gadget type is not supported");

    if (pReq->u32GdgtAccess != UTSPKT_GDGT_CREATE_ACCESS_USBIP)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_PARAMETER, "The given gadget access method is not supported");

    PUTSGADGETCFGITEM paCfg = NULL;
    if (pReq->u32CfgItems > 0)
    {
        paCfg = (PUTSGADGETCFGITEM)RTMemAllocZ((pReq->u32CfgItems + 1) * sizeof(UTSGADGETCFGITEM));
        if (RT_UNLIKELY(!paCfg))
            return utsReplyRC(pClient, pPktHdr, VERR_NO_MEMORY, "Failed to allocate memory for configration items");

        rc = utsDoGadgetCreateFillCfg((PUTSPKTREQGDGTCTORCFGITEM)(pReq + 1), pReq->u32CfgItems,
                                      pPktHdr->cb - sizeof(UTSPKTREQGDGTCTOR), paCfg);
        if (RT_FAILURE(rc))
        {
            RTMemFree(paCfg);
            return utsReplyRC(pClient, pPktHdr, rc, "Failed to parse configuration");
        }
    }

    rc = utsGadgetCreate(pClient->hGadgetHost, UTSGADGETCLASS_TEST, paCfg, &pClient->hGadget);
    if (RT_SUCCESS(rc))
    {
        UTSPKTREPGDGTCTOR Rep;
        RT_ZERO(Rep);

        Rep.idGadget = 0;
        Rep.u32BusId = utsGadgetGetBusId(pClient->hGadget);
        Rep.u32DevId = utsGadgetGetDevId(pClient->hGadget);
        rc = utsReplyInternal(pClient, &Rep.Sts, "ACK     ", sizeof(Rep) - sizeof(UTSPKTSTS));
    }
    else
        rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to create gadget with %Rrc\n", rc);

    return rc;
}

/**
 * Verifies and processes a "GADGET DESTROY" request.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The gadget destroy packet.
 */
static int utsDoGadgetDestroy(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    if (pPktHdr->cb != sizeof(UTSPKTREQGDGTDTOR))
        return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTDTOR));

    if (   pClient->enmState != UTSCLIENTSTATE_READY
        || pClient->hGadgetHost == NIL_UTSGADGETHOST)
        return utsReplyInvalidState(pClient, pPktHdr);

    PUTSPKTREQGDGTDTOR pReq = (PUTSPKTREQGDGTDTOR)pPktHdr;

    if (pReq->idGadget != 0)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
    if (pClient->hGadget == NIL_UTSGADGET)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");

    utsGadgetRelease(pClient->hGadget);
    pClient->hGadget = NIL_UTSGADGET;

    return utsReplyAck(pClient, pPktHdr);
}

/**
 * Verifies and processes a "GADGET CONNECT" request.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The gadget connect packet.
 */
static int utsDoGadgetConnect(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    if (pPktHdr->cb != sizeof(UTSPKTREQGDGTCNCT))
        return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTCNCT));

    if (   pClient->enmState != UTSCLIENTSTATE_READY
        || pClient->hGadgetHost == NIL_UTSGADGETHOST)
        return utsReplyInvalidState(pClient, pPktHdr);

    PUTSPKTREQGDGTCNCT pReq = (PUTSPKTREQGDGTCNCT)pPktHdr;

    if (pReq->idGadget != 0)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
    if (pClient->hGadget == NIL_UTSGADGET)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");

    int rc = utsGadgetConnect(pClient->hGadget);
    if (RT_SUCCESS(rc))
        rc = utsReplyAck(pClient, pPktHdr);
    else
        rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to connect the gadget");

    return rc;
}

/**
 * Verifies and processes a "GADGET DISCONNECT" request.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure.
 * @param   pPktHdr             The gadget disconnect packet.
 */
static int utsDoGadgetDisconnect(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
{
    if (pPktHdr->cb != sizeof(UTSPKTREQGDGTDCNT))
        return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTDCNT));

    if (   pClient->enmState != UTSCLIENTSTATE_READY
        || pClient->hGadgetHost == NIL_UTSGADGETHOST)
        return utsReplyInvalidState(pClient, pPktHdr);

    PUTSPKTREQGDGTDCNT pReq = (PUTSPKTREQGDGTDCNT)pPktHdr;

    if (pReq->idGadget != 0)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
    if (pClient->hGadget == NIL_UTSGADGET)
        return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");

    int rc = utsGadgetDisconnect(pClient->hGadget);
    if (RT_SUCCESS(rc))
        rc = utsReplyAck(pClient, pPktHdr);
    else
        rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to disconnect the gadget");

    return rc;
}

/**
 * Main request processing routine for each client.
 *
 * @returns IPRT status code.
 * @param   pClient             The UTS client structure sending the request.
 */
static int utsClientReqProcess(PUTSCLIENT pClient)
{
    /*
     * Read client command packet and process it.
     */
    PUTSPKTHDR pPktHdr = NULL;
    int rc = utsRecvPkt(pClient, &pPktHdr, true /*fAutoRetryOnFailure*/);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Do a string switch on the opcode bit.
     */
    /* Connection: */
    if (     utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_HOWDY))
        rc = utsDoHowdy(pClient, pPktHdr);
    else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_BYE))
        rc = utsDoBye(pClient, pPktHdr);
    /* Gadget API. */
    else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_CREATE))
        rc = utsDoGadgetCreate(pClient, pPktHdr);
    else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_DESTROY))
        rc = utsDoGadgetDestroy(pClient, pPktHdr);
    else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_CONNECT))
        rc = utsDoGadgetConnect(pClient, pPktHdr);
    else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_DISCONNECT))
        rc = utsDoGadgetDisconnect(pClient, pPktHdr);
    /* Misc: */
    else
        rc = utsReplyUnknown(pClient, pPktHdr);

    RTMemFree(pPktHdr);

    return rc;
}

/**
 * Destroys a client instance.
 *
 * @returns nothing.
 * @param   pClient             The UTS client structure.
 */
static void utsClientDestroy(PUTSCLIENT pClient)
{
    if (pClient->pszHostname)
        RTStrFree(pClient->pszHostname);
    if (pClient->hGadget != NIL_UTSGADGET)
        utsGadgetRelease(pClient->hGadget);
    if (pClient->hGadgetHost != NIL_UTSGADGETHOST)
        utsGadgetHostRelease(pClient->hGadgetHost);
    RTMemFree(pClient);
}

/**
 * The main thread worker serving the clients.
 */
static DECLCALLBACK(int) utsClientWorker(RTTHREAD hThread, void *pvUser)
{
    RT_NOREF2(hThread, pvUser);
    unsigned    cClientsMax = 0;
    unsigned    cClientsCur = 0;
    PUTSCLIENT *papClients  = NULL;
    RTPOLLSET   hPollSet;

    int rc = RTPollSetCreate(&hPollSet);
    if (RT_FAILURE(rc))
        return rc;

    /* Add the pipe to the poll set. */
    rc = RTPollSetAddPipe(hPollSet, g_hPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 0);
    if (RT_SUCCESS(rc))
    {
        while (!g_fTerminate)
        {
            uint32_t fEvts;
            uint32_t uId;
            rc = RTPoll(hPollSet, RT_INDEFINITE_WAIT, &fEvts, &uId);
            if (RT_SUCCESS(rc))
            {
                if (uId == 0)
                {
                    if (fEvts & RTPOLL_EVT_ERROR)
                        break;

                    /* We got woken up because of a new client. */
                    Assert(fEvts & RTPOLL_EVT_READ);

                    uint8_t bRead;
                    size_t cbRead = 0;
                    rc = RTPipeRead(g_hPipeR, &bRead, 1, &cbRead);
                    AssertRC(rc);

                    RTCritSectEnter(&g_CritSectClients);
                    /* Walk the list and add all new clients. */
                    PUTSCLIENT pIt, pItNext;
                    RTListForEachSafe(&g_LstClientsNew, pIt, pItNext, UTSCLIENT, NdLst)
                    {
                        RTListNodeRemove(&pIt->NdLst);
                        Assert(cClientsCur <= cClientsMax);
                        if (cClientsCur == cClientsMax)
                        {
                            /* Realloc to accommodate for the new clients. */
                            PUTSCLIENT *papClientsNew = (PUTSCLIENT *)RTMemRealloc(papClients, (cClientsMax + 10) * sizeof(PUTSCLIENT));
                            if (RT_LIKELY(papClientsNew))
                            {
                                cClientsMax += 10;
                                papClients = papClientsNew;
                            }
                        }

                        if (cClientsCur < cClientsMax)
                        {
                            /* Find a free slot in the client array. */
                            unsigned idxSlt = 0;
                            while (   idxSlt < cClientsMax
                                   && papClients[idxSlt] != NULL)
                                idxSlt++;

                            rc = g_pTransport->pfnPollSetAdd(hPollSet, pIt->pTransportClient, idxSlt + 1);
                            if (RT_SUCCESS(rc))
                            {
                                cClientsCur++;
                                papClients[idxSlt] = pIt;
                            }
                            else
                            {
                                g_pTransport->pfnNotifyBye(pIt->pTransportClient);
                                utsClientDestroy(pIt);
                            }
                        }
                        else
                        {
                            g_pTransport->pfnNotifyBye(pIt->pTransportClient);
                            utsClientDestroy(pIt);
                        }
                    }
                    RTCritSectLeave(&g_CritSectClients);
                }
                else
                {
                    /* Client sends a request, pick the right client and process it. */
                    PUTSCLIENT pClient = papClients[uId - 1];
                    AssertPtr(pClient);
                    if (fEvts & RTPOLL_EVT_READ)
                        rc = utsClientReqProcess(pClient);

                    if (   (fEvts & RTPOLL_EVT_ERROR)
                        || RT_FAILURE(rc))
                    {
                        /* Close connection and remove client from array. */
                        rc = g_pTransport->pfnPollSetRemove(hPollSet, pClient->pTransportClient, uId);
                        AssertRC(rc);

                        g_pTransport->pfnNotifyBye(pClient->pTransportClient);
                        papClients[uId - 1] = NULL;
                        cClientsCur--;
                        utsClientDestroy(pClient);
                    }
                }
            }
        }
    }

    RTPollSetDestroy(hPollSet);

    return rc;
}

/**
 * The main loop.
 *
 * @returns exit code.
 */
static RTEXITCODE utsMainLoop(void)
{
    RTEXITCODE enmExitCode = RTEXITCODE_SUCCESS;
    while (!g_fTerminate)
    {
        /*
         * Wait for new connection and spin off a new thread
         * for every new client.
         */
        PUTSTRANSPORTCLIENT pTransportClient;
        int rc = g_pTransport->pfnWaitForConnect(&pTransportClient);
        if (RT_FAILURE(rc))
            continue;

        /*
         * New connection, create new client structure and spin of
         * the request handling thread.
         */
        PUTSCLIENT pClient = (PUTSCLIENT)RTMemAllocZ(sizeof(UTSCLIENT));
        if (RT_LIKELY(pClient))
        {
            pClient->enmState         = UTSCLIENTSTATE_INITIALISING;
            pClient->pTransportClient = pTransportClient;
            pClient->pszHostname      = NULL;
            pClient->hGadgetHost      = NIL_UTSGADGETHOST;
            pClient->hGadget          = NIL_UTSGADGET;

            /* Add client to the new list and inform the worker thread. */
            RTCritSectEnter(&g_CritSectClients);
            RTListAppend(&g_LstClientsNew, &pClient->NdLst);
            RTCritSectLeave(&g_CritSectClients);

            size_t cbWritten = 0;
            rc = RTPipeWrite(g_hPipeW, "", 1, &cbWritten);
            if (RT_FAILURE(rc))
                RTMsgError("Failed to inform worker thread of a new client");
        }
        else
        {
            RTMsgError("Creating new client structure failed with out of memory error\n");
            g_pTransport->pfnNotifyBye(pTransportClient);
        }


    }

    return enmExitCode;
}

/**
 * Initializes the global UTS state.
 *
 * @returns IPRT status code.
 */
static int utsInit(void)
{
    int rc = VINF_SUCCESS;
    PRTERRINFO pErrInfo = NULL;

    RTListInit(&g_LstClientsNew);

    rc = RTJsonParseFromFile(&g_hCfgJson, g_szCfgPath, pErrInfo);
    if (RT_SUCCESS(rc))
    {
        rc = utsPlatformInit();
        if (RT_SUCCESS(rc))
        {
            rc = RTCritSectInit(&g_CritSectClients);
            if (RT_SUCCESS(rc))
            {
                rc = RTPipeCreate(&g_hPipeR, &g_hPipeW, 0);
                if (RT_SUCCESS(rc))
                {
                    /* Spin off the thread serving connections. */
                    rc = RTThreadCreate(&g_hThreadServing, utsClientWorker, NULL, 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE,
                                        "USBTSTSRV");
                    if (RT_SUCCESS(rc))
                        return VINF_SUCCESS;
                    else
                        RTMsgError("Creating the client worker thread failed with %Rrc\n", rc);

                    RTPipeClose(g_hPipeR);
                    RTPipeClose(g_hPipeW);
                }
                else
                    RTMsgError("Creating communications pipe failed with %Rrc\n", rc);

                RTCritSectDelete(&g_CritSectClients);
            }
            else
                RTMsgError("Creating global critical section failed with %Rrc\n", rc);

            RTJsonValueRelease(g_hCfgJson);
        }
        else
            RTMsgError("Initializing the platform failed with %Rrc\n", rc);
    }
    else
    {
        if (RTErrInfoIsSet(pErrInfo))
        {
            RTMsgError("Failed to parse config with detailed error: %s (%Rrc)\n",
                       pErrInfo->pszMsg, pErrInfo->rc);
            RTErrInfoFree(pErrInfo);
        }
        else
            RTMsgError("Failed to parse config with unknown error (%Rrc)\n", rc);
    }

    return rc;
}

/**
 * Determines the default configuration.
 */
static void utsSetDefaults(void)
{
    /*
     * OS and ARCH.
     */
    AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
    strcpy(g_szOsShortName, KBUILD_TARGET);

    AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
    strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);

    AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
    strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
    g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
    strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);

    AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
    strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
    g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
    strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);

#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
    strcpy(g_szExeSuff,    ".exe");
    strcpy(g_szScriptSuff, ".cmd");
#else
    strcpy(g_szExeSuff,    "");
    strcpy(g_szScriptSuff, ".sh");
#endif

    /*
     * The CD/DVD-ROM location.
     */
    /** @todo do a better job here :-) */
#ifdef RT_OS_WINDOWS
    strcpy(g_szDefCdRomPath, "D:/");
#elif defined(RT_OS_OS2)
    strcpy(g_szDefCdRomPath, "D:/");
#else
    if (RTDirExists("/media"))
        strcpy(g_szDefCdRomPath, "/media/cdrom");
    else
        strcpy(g_szDefCdRomPath, "/mnt/cdrom");
#endif
    strcpy(g_szCdRomPath, g_szDefCdRomPath);

    /*
     * Temporary directory.
     */
    int rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
    if (RT_SUCCESS(rc))
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
        rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXX.tmp");
#else
        rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXXXXXXX.tmp");
#endif
    if (RT_FAILURE(rc))
    {
        RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
        strcpy(g_szDefScratchPath, "/tmp/uts-XXXX.tmp");
    }
    strcpy(g_szScratchPath, g_szDefScratchPath);

    /*
     * Config file location.
     */
    /** @todo Improve */
#if !defined(RT_OS_WINDOWS)
    strcpy(g_szCfgPath, "/etc/uts.conf");
#else
    strcpy(g_szCfgPath, "");
#endif

    /*
     * The default transporter is the first one.
     */
    g_pTransport = g_apTransports[0];
}

/**
 * Prints the usage.
 *
 * @param   pStrm               Where to print it.
 * @param   pszArgv0            The program name (argv[0]).
 */
static void utsUsage(PRTSTREAM pStrm, const char *pszArgv0)
{
    RTStrmPrintf(pStrm,
                 "Usage: %Rbn [options]\n"
                 "\n"
                 "Options:\n"
                 "  --config <path>\n"
                 "      Where to load the config from\n"
                 "  --cdrom <path>\n"
                 "      Where the CD/DVD-ROM will be mounted.\n"
                 "      Default: %s\n"
                 "  --scratch <path>\n"
                 "      Where to put scratch files.\n"
                 "      Default: %s \n"
                 ,
                 pszArgv0,
                 g_szDefCdRomPath,
                 g_szDefScratchPath);
    RTStrmPrintf(pStrm,
                 "  --transport <name>\n"
                 "      Use the specified transport layer, one of the following:\n");
    for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
        RTStrmPrintf(pStrm, "          %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
    RTStrmPrintf(pStrm, "      Default: %s\n", g_pTransport->szName);
    RTStrmPrintf(pStrm,
                 "  --display-output, --no-display-output\n"
                 "      Display the output and the result of all child processes.\n");
    RTStrmPrintf(pStrm,
                 "  --foreground\n"
                 "      Don't daemonize, run in the foreground.\n");
    RTStrmPrintf(pStrm,
                 "  --help, -h, -?\n"
                 "      Display this message and exit.\n"
                 "  --version, -V\n"
                 "      Display the version and exit.\n");

    for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
        if (g_apTransports[i]->cOpts)
        {
            RTStrmPrintf(pStrm,
                         "\n"
                         "Options for %s:\n", g_apTransports[i]->szName);
            g_apTransports[i]->pfnUsage(g_pStdOut);
        }
}

/**
 * Parses the arguments.
 *
 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
 * @param   argc                The number of arguments.
 * @param   argv                The argument vector.
 * @param   pfExit              For indicating exit when the exit code is zero.
 */
static RTEXITCODE utsParseArgv(int argc, char **argv, bool *pfExit)
{
    *pfExit = false;

    /*
     * Storage for locally handled options.
     */
    bool fDaemonize  = true;
    bool fDaemonized = false;

    /*
     * Combine the base and transport layer option arrays.
     */
    static const RTGETOPTDEF s_aBaseOptions[] =
    {
        { "--config",           'C', RTGETOPT_REQ_STRING  },
        { "--transport",        't', RTGETOPT_REQ_STRING  },
        { "--cdrom",            'c', RTGETOPT_REQ_STRING  },
        { "--scratch",          's', RTGETOPT_REQ_STRING  },
        { "--display-output",   'd', RTGETOPT_REQ_NOTHING  },
        { "--no-display-output",'D', RTGETOPT_REQ_NOTHING  },
        { "--foreground",       'f', RTGETOPT_REQ_NOTHING  },
        { "--daemonized",       'Z', RTGETOPT_REQ_NOTHING  },
    };

    size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
    for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
        cOptions += g_apTransports[i]->cOpts;

    PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
    if (!paOptions)
        return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");

    memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
    cOptions = RT_ELEMENTS(s_aBaseOptions);
    for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
    {
        memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
        cOptions += g_apTransports[i]->cOpts;
    }

    /*
     * Parse the arguments.
     */
    RTGETOPTSTATE GetState;
    int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
    AssertRC(rc);

    int ch;
    RTGETOPTUNION Val;
    while ((ch = RTGetOpt(&GetState, &Val)))
    {
        switch (ch)
        {
            case 'C':
                rc = RTStrCopy(g_szCfgPath, sizeof(g_szCfgPath), Val.psz);
                if (RT_FAILURE(rc))
                    return RTMsgErrorExit(RTEXITCODE_FAILURE, "Config file path is path too long (%Rrc)\n", rc);
                break;

            case 'c':
                rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
                if (RT_FAILURE(rc))
                    return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
                break;

            case 'd':
                g_fDisplayOutput = true;
                break;

            case 'D':
                g_fDisplayOutput = false;
                break;

            case 'f':
                fDaemonize = false;
                break;

            case 'h':
                utsUsage(g_pStdOut, argv[0]);
                *pfExit = true;
                return RTEXITCODE_SUCCESS;

            case 's':
                rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
                if (RT_FAILURE(rc))
                    return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
                break;

            case 't':
            {
                PCUTSTRANSPORT pTransport = NULL;
                for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
                    if (!strcmp(g_apTransports[i]->szName, Val.psz))
                    {
                        pTransport = g_apTransports[i];
                        break;
                    }
                if (!pTransport)
                    return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
                g_pTransport = pTransport;
                break;
            }

            case 'V':
                RTPrintf("$Revision: 127855 $\n");
                *pfExit = true;
                return RTEXITCODE_SUCCESS;

            case 'Z':
                fDaemonized = true;
                fDaemonize = false;
                break;

            default:
            {
                rc = VERR_TRY_AGAIN;
                for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
                    if (g_apTransports[i]->cOpts)
                    {
                        rc = g_apTransports[i]->pfnOption(ch, &Val);
                        if (RT_SUCCESS(rc))
                            break;
                        if (rc != VERR_TRY_AGAIN)
                        {
                            *pfExit = true;
                            return RTEXITCODE_SYNTAX;
                        }
                    }
                if (rc == VERR_TRY_AGAIN)
                {
                    *pfExit = true;
                    return RTGetOptPrintError(ch, &Val);
                }
                break;
            }
        }
    }

    /*
     * Daemonize ourselves if asked to.
     */
    if (fDaemonize && !*pfExit)
    {
        rc = RTProcDaemonize(argv, "--daemonized");
        if (RT_FAILURE(rc))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
        *pfExit = true;
    }

    return RTEXITCODE_SUCCESS;
}


int main(int argc, char **argv)
{
    /*
     * Initialize the runtime.
     */
    int rc = RTR3InitExe(argc, &argv, 0);
    if (RT_FAILURE(rc))
        return RTMsgInitFailure(rc);

    /*
     * Determine defaults and parse the arguments.
     */
    utsSetDefaults();
    bool fExit;
    RTEXITCODE rcExit = utsParseArgv(argc, argv, &fExit);
    if (rcExit != RTEXITCODE_SUCCESS || fExit)
        return rcExit;

    /*
     * Initialize global state.
     */
    rc = utsInit();
    if (RT_FAILURE(rc))
        return RTEXITCODE_FAILURE;

    /*
     * Initialize the transport layer.
     */
    rc = g_pTransport->pfnInit();
    if (RT_FAILURE(rc))
        return RTEXITCODE_FAILURE;

    /*
     * Ok, start working
     */
    rcExit = utsMainLoop();

    /*
     * Cleanup.
     */
    g_pTransport->pfnTerm();

    utsPlatformTerm();

    return rcExit;
}