ironrdp_rdpdr/pdu/
esc.rs

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
//! PDUs for [\[MS-RDPESC\]: Remote Desktop Protocol: Smart Card Virtual Channel Extension]
//!
//! [\[MS-RDPESC\]: Remote Desktop Protocol: Smart Card Virtual Channel Extension]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/0428ca28-b4dc-46a3-97c3-01887fa44a90

pub mod ndr;
pub mod rpce;

use core::mem::size_of;

use bitflags::bitflags;
use ironrdp_core::{
    cast_length, ensure_size, invalid_field_err, other_err, DecodeError, DecodeResult, EncodeResult, ReadCursor,
    WriteCursor,
};
use ironrdp_pdu::utils::{
    encoded_multistring_len, read_multistring_from_cursor, write_multistring_to_cursor, CharacterSet,
};

use super::efs::IoCtlCode;
use crate::pdu::esc::ndr::{Decode as _, Encode as _};

/// [2.2.2] TS Server-Generated Structures
///
/// [2.2.2]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/f4ca3b61-b49c-463c-8932-2cf82fb7ec7a
#[derive(Debug, PartialEq, Clone)]
pub enum ScardCall {
    AccessStartedEventCall(ScardAccessStartedEventCall),
    EstablishContextCall(EstablishContextCall),
    ListReadersCall(ListReadersCall),
    GetStatusChangeCall(GetStatusChangeCall),
    ConnectCall(ConnectCall),
    HCardAndDispositionCall(HCardAndDispositionCall),
    TransmitCall(TransmitCall),
    StatusCall(StatusCall),
    ContextCall(ContextCall),
    GetDeviceTypeIdCall(GetDeviceTypeIdCall),
    ReadCacheCall(ReadCacheCall),
    WriteCacheCall(WriteCacheCall),
    GetReaderIconCall(GetReaderIconCall),
    Unsupported,
}

impl ScardCall {
    pub fn decode(io_ctl_code: ScardIoCtlCode, src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        match io_ctl_code {
            ScardIoCtlCode::AccessStartedEvent => Ok(ScardCall::AccessStartedEventCall(
                ScardAccessStartedEventCall::decode(src)?,
            )),
            ScardIoCtlCode::EstablishContext => Ok(ScardCall::EstablishContextCall(EstablishContextCall::decode(src)?)),
            ScardIoCtlCode::ListReadersW => Ok(ScardCall::ListReadersCall(ListReadersCall::decode(
                src,
                Some(CharacterSet::Unicode),
            )?)),
            ScardIoCtlCode::ListReadersA => Ok(ScardCall::ListReadersCall(ListReadersCall::decode(
                src,
                Some(CharacterSet::Ansi),
            )?)),
            ScardIoCtlCode::GetStatusChangeW => Ok(ScardCall::GetStatusChangeCall(GetStatusChangeCall::decode(
                src,
                Some(CharacterSet::Unicode),
            )?)),
            ScardIoCtlCode::GetStatusChangeA => Ok(ScardCall::GetStatusChangeCall(GetStatusChangeCall::decode(
                src,
                Some(CharacterSet::Ansi),
            )?)),
            ScardIoCtlCode::ConnectW => Ok(ScardCall::ConnectCall(ConnectCall::decode(
                src,
                Some(CharacterSet::Unicode),
            )?)),
            ScardIoCtlCode::ConnectA => Ok(ScardCall::ConnectCall(ConnectCall::decode(
                src,
                Some(CharacterSet::Ansi),
            )?)),
            ScardIoCtlCode::BeginTransaction => Ok(ScardCall::HCardAndDispositionCall(
                HCardAndDispositionCall::decode(src)?,
            )),
            ScardIoCtlCode::Transmit => Ok(ScardCall::TransmitCall(TransmitCall::decode(src)?)),
            ScardIoCtlCode::StatusW | ScardIoCtlCode::StatusA => Ok(ScardCall::StatusCall(StatusCall::decode(src)?)),
            ScardIoCtlCode::ReleaseContext => Ok(ScardCall::ContextCall(ContextCall::decode(src)?)),
            ScardIoCtlCode::EndTransaction => Ok(ScardCall::HCardAndDispositionCall(HCardAndDispositionCall::decode(
                src,
            )?)),
            ScardIoCtlCode::Disconnect => Ok(ScardCall::HCardAndDispositionCall(HCardAndDispositionCall::decode(
                src,
            )?)),
            ScardIoCtlCode::Cancel => Ok(ScardCall::ContextCall(ContextCall::decode(src)?)),
            ScardIoCtlCode::IsValidContext => Ok(ScardCall::ContextCall(ContextCall::decode(src)?)),
            ScardIoCtlCode::GetDeviceTypeId => Ok(ScardCall::GetDeviceTypeIdCall(GetDeviceTypeIdCall::decode(src)?)),
            ScardIoCtlCode::ReadCacheW => Ok(ScardCall::ReadCacheCall(ReadCacheCall::decode(
                src,
                Some(CharacterSet::Unicode),
            )?)),
            ScardIoCtlCode::ReadCacheA => Ok(ScardCall::ReadCacheCall(ReadCacheCall::decode(
                src,
                Some(CharacterSet::Ansi),
            )?)),
            ScardIoCtlCode::WriteCacheW => Ok(ScardCall::WriteCacheCall(WriteCacheCall::decode(
                src,
                Some(CharacterSet::Unicode),
            )?)),
            ScardIoCtlCode::WriteCacheA => Ok(ScardCall::WriteCacheCall(WriteCacheCall::decode(
                src,
                Some(CharacterSet::Ansi),
            )?)),
            ScardIoCtlCode::GetReaderIcon => Ok(ScardCall::GetReaderIconCall(GetReaderIconCall::decode(src)?)),
            _ => {
                warn!(?io_ctl_code, "Unsupported ScardIoCtlCode");
                // TODO: maybe this should be an error
                Ok(Self::Unsupported)
            }
        }
    }
}

/// [2.2.1.1] REDIR_SCARDCONTEXT
///
/// [2.2.1.1]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/060abee1-e520-4149-9ef7-ce79eb500a59
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct ScardContext {
    /// Shortcut: we always create 4-byte context values.
    /// The spec allows this field to have variable length.
    pub value: u32,
}

impl ScardContext {
    /// See [`ScardContext::value`]
    const VALUE_LENGTH: u32 = 4;

    pub fn new(value: u32) -> Self {
        Self { value }
    }
}

impl ndr::Encode for ScardContext {
    fn encode_ptr(&self, index: &mut u32, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ndr::encode_ptr(Some(Self::VALUE_LENGTH), index, dst)
    }

    fn encode_value(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size_value());
        dst.write_u32(Self::VALUE_LENGTH);
        dst.write_u32(self.value);
        Ok(())
    }

    fn size_ptr(&self) -> usize {
        ndr::ptr_size(true)
    }

    fn size_value(&self) -> usize {
        4 /* cbContext */ + 4 /* pbContext */
    }
}

impl ndr::Decode for ScardContext {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self>
    where
        Self: Sized,
    {
        ensure_size!(in: src, size: size_of::<u32>());
        let length = src.read_u32();
        if length != Self::VALUE_LENGTH {
            error!(?length, "Unsupported value length in ScardContext");
            return Err(invalid_field_err!(
                "decode_ptr",
                "unsupported value length in ScardContext"
            ));
        }

        let _ptr = ndr::decode_ptr(src, index)?;
        Ok(Self { value: 0 })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        expect_no_charset(charset)?;
        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let length = src.read_u32();
        if length != Self::VALUE_LENGTH {
            error!(?length, "Unsupported value length in ScardContext");
            return Err(invalid_field_err!(
                "decode_value",
                "unsupported value length in ScardContext"
            ));
        }
        self.value = src.read_u32();
        Ok(())
    }
}

/// [2.2.1.7] ReaderStateW
///
/// [2.2.1.7]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/0ba03cd2-bed0-495b-adbe-3d2cde61980c
#[derive(Debug, PartialEq, Clone)]
pub struct ReaderState {
    pub reader: String,
    pub common: ReaderStateCommonCall,
}

impl ndr::Decode for ReaderState {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self> {
        let _reader_ptr = ndr::decode_ptr(src, index)?;
        let common = ReaderStateCommonCall::decode(src)?;
        Ok(Self {
            reader: String::new(),
            common,
        })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        let charset = expect_charset(charset)?;
        self.reader = ndr::read_string_from_cursor(src, charset)?;
        Ok(())
    }
}

/// From [3.1.4] Message Processing Events and Sequencing Rules
///
/// [3.1.4]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/60d5977d-0017-4c90-ab0c-f34bf44a74a5
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(u32)]
pub enum ScardIoCtlCode {
    /// SCARD_IOCTL_ESTABLISHCONTEXT
    EstablishContext = 0x0009_0014,
    /// SCARD_IOCTL_RELEASECONTEXT
    ReleaseContext = 0x0009_0018,
    /// SCARD_IOCTL_ISVALIDCONTEXT
    IsValidContext = 0x0009_001C,
    /// SCARD_IOCTL_LISTREADERGROUPSA
    ListReaderGroupsA = 0x0009_0020,
    /// SCARD_IOCTL_LISTREADERGROUPSW
    ListReaderGroupsW = 0x0009_0024,
    /// SCARD_IOCTL_LISTREADERSA
    ListReadersA = 0x0009_0028,
    /// SCARD_IOCTL_LISTREADERSW
    ListReadersW = 0x0009_002C,
    /// SCARD_IOCTL_INTRODUCEREADERGROUPA
    IntroduceReaderGroupA = 0x0009_0050,
    /// SCARD_IOCTL_INTRODUCEREADERGROUPW
    IntroduceReaderGroupW = 0x0009_0054,
    /// SCARD_IOCTL_FORGETREADERGROUPA
    ForgetReaderGroupA = 0x0009_0058,
    /// SCARD_IOCTL_FORGETREADERGROUPW
    ForgetReaderGroupW = 0x0009_005C,
    /// SCARD_IOCTL_INTRODUCEREADERA
    IntroduceReaderA = 0x0009_0060,
    /// SCARD_IOCTL_INTRODUCEREADERW
    IntroduceReaderW = 0x0009_0064,
    /// SCARD_IOCTL_FORGETREADERA
    ForgetReaderA = 0x0009_0068,
    /// SCARD_IOCTL_FORGETREADERW
    ForgetReaderW = 0x0009_006C,
    /// SCARD_IOCTL_ADDREADERTOGROUPA
    AddReaderToGroupA = 0x0009_0070,
    /// SCARD_IOCTL_ADDREADERTOGROUPW
    AddReaderToGroupW = 0x0009_0074,
    /// SCARD_IOCTL_REMOVEREADERFROMGROUPA
    RemoveReaderFromGroupA = 0x0009_0078,
    /// SCARD_IOCTL_REMOVEREADERFROMGROUPW
    RemoveReaderFromGroupW = 0x0009_007C,
    /// SCARD_IOCTL_LOCATECARDSA
    LocateCardsA = 0x0009_0098,
    /// SCARD_IOCTL_LOCATECARDSW
    LocateCardsW = 0x0009_009C,
    /// SCARD_IOCTL_GETSTATUSCHANGEA
    GetStatusChangeA = 0x0009_00A0,
    /// SCARD_IOCTL_GETSTATUSCHANGEW
    GetStatusChangeW = 0x0009_00A4,
    /// SCARD_IOCTL_CANCEL
    Cancel = 0x0009_00A8,
    /// SCARD_IOCTL_CONNECTA
    ConnectA = 0x0009_00AC,
    /// SCARD_IOCTL_CONNECTW
    ConnectW = 0x0009_00B0,
    /// SCARD_IOCTL_RECONNECT
    Reconnect = 0x0009_00B4,
    /// SCARD_IOCTL_DISCONNECT
    Disconnect = 0x0009_00B8,
    /// SCARD_IOCTL_BEGINTRANSACTION
    BeginTransaction = 0x0009_00BC,
    /// SCARD_IOCTL_ENDTRANSACTION
    EndTransaction = 0x0009_00C0,
    /// SCARD_IOCTL_STATE
    State = 0x0009_00C4,
    /// SCARD_IOCTL_STATUSA
    StatusA = 0x0009_00C8,
    /// SCARD_IOCTL_STATUSW
    StatusW = 0x0009_00CC,
    /// SCARD_IOCTL_TRANSMIT
    Transmit = 0x0009_00D0,
    /// SCARD_IOCTL_CONTROL
    Control = 0x0009_00D4,
    /// SCARD_IOCTL_GETATTRIB
    GetAttrib = 0x0009_00D8,
    /// SCARD_IOCTL_SETATTRIB
    SetAttrib = 0x0009_00DC,
    /// SCARD_IOCTL_ACCESSSTARTEDEVENT
    AccessStartedEvent = 0x0009_00E0,
    /// SCARD_IOCTL_RELEASETARTEDEVENT
    ReleaseTartedEvent = 0x0009_00E4,
    /// SCARD_IOCTL_LOCATECARDSBYATRA
    LocateCardsByAtrA = 0x0009_00E8,
    /// SCARD_IOCTL_LOCATECARDSBYATRW
    LocateCardsByAtrW = 0x0009_00EC,
    /// SCARD_IOCTL_READCACHEA
    ReadCacheA = 0x0009_00F0,
    /// SCARD_IOCTL_READCACHEW
    ReadCacheW = 0x0009_00F4,
    /// SCARD_IOCTL_WRITECACHEA
    WriteCacheA = 0x0009_00F8,
    /// SCARD_IOCTL_WRITECACHEW
    WriteCacheW = 0x0009_00FC,
    /// SCARD_IOCTL_GETTRANSMITCOUNT
    GetTransmitCount = 0x0009_0100,
    /// SCARD_IOCTL_GETREADERICON
    GetReaderIcon = 0x0009_0104,
    /// SCARD_IOCTL_GETDEVICETYPEID
    GetDeviceTypeId = 0x0009_0108,
}

impl TryFrom<u32> for ScardIoCtlCode {
    type Error = DecodeError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            0x0009_0014 => Ok(ScardIoCtlCode::EstablishContext),
            0x0009_0018 => Ok(ScardIoCtlCode::ReleaseContext),
            0x0009_001C => Ok(ScardIoCtlCode::IsValidContext),
            0x0009_0020 => Ok(ScardIoCtlCode::ListReaderGroupsA),
            0x0009_0024 => Ok(ScardIoCtlCode::ListReaderGroupsW),
            0x0009_0028 => Ok(ScardIoCtlCode::ListReadersA),
            0x0009_002C => Ok(ScardIoCtlCode::ListReadersW),
            0x0009_0050 => Ok(ScardIoCtlCode::IntroduceReaderGroupA),
            0x0009_0054 => Ok(ScardIoCtlCode::IntroduceReaderGroupW),
            0x0009_0058 => Ok(ScardIoCtlCode::ForgetReaderGroupA),
            0x0009_005C => Ok(ScardIoCtlCode::ForgetReaderGroupW),
            0x0009_0060 => Ok(ScardIoCtlCode::IntroduceReaderA),
            0x0009_0064 => Ok(ScardIoCtlCode::IntroduceReaderW),
            0x0009_0068 => Ok(ScardIoCtlCode::ForgetReaderA),
            0x0009_006C => Ok(ScardIoCtlCode::ForgetReaderW),
            0x0009_0070 => Ok(ScardIoCtlCode::AddReaderToGroupA),
            0x0009_0074 => Ok(ScardIoCtlCode::AddReaderToGroupW),
            0x0009_0078 => Ok(ScardIoCtlCode::RemoveReaderFromGroupA),
            0x0009_007C => Ok(ScardIoCtlCode::RemoveReaderFromGroupW),
            0x0009_0098 => Ok(ScardIoCtlCode::LocateCardsA),
            0x0009_009C => Ok(ScardIoCtlCode::LocateCardsW),
            0x0009_00A0 => Ok(ScardIoCtlCode::GetStatusChangeA),
            0x0009_00A4 => Ok(ScardIoCtlCode::GetStatusChangeW),
            0x0009_00A8 => Ok(ScardIoCtlCode::Cancel),
            0x0009_00AC => Ok(ScardIoCtlCode::ConnectA),
            0x0009_00B0 => Ok(ScardIoCtlCode::ConnectW),
            0x0009_00B4 => Ok(ScardIoCtlCode::Reconnect),
            0x0009_00B8 => Ok(ScardIoCtlCode::Disconnect),
            0x0009_00BC => Ok(ScardIoCtlCode::BeginTransaction),
            0x0009_00C0 => Ok(ScardIoCtlCode::EndTransaction),
            0x0009_00C4 => Ok(ScardIoCtlCode::State),
            0x0009_00C8 => Ok(ScardIoCtlCode::StatusA),
            0x0009_00CC => Ok(ScardIoCtlCode::StatusW),
            0x0009_00D0 => Ok(ScardIoCtlCode::Transmit),
            0x0009_00D4 => Ok(ScardIoCtlCode::Control),
            0x0009_00D8 => Ok(ScardIoCtlCode::GetAttrib),
            0x0009_00DC => Ok(ScardIoCtlCode::SetAttrib),
            0x0009_00E0 => Ok(ScardIoCtlCode::AccessStartedEvent),
            0x0009_00E4 => Ok(ScardIoCtlCode::ReleaseTartedEvent),
            0x0009_00E8 => Ok(ScardIoCtlCode::LocateCardsByAtrA),
            0x0009_00EC => Ok(ScardIoCtlCode::LocateCardsByAtrW),
            0x0009_00F0 => Ok(ScardIoCtlCode::ReadCacheA),
            0x0009_00F4 => Ok(ScardIoCtlCode::ReadCacheW),
            0x0009_00F8 => Ok(ScardIoCtlCode::WriteCacheA),
            0x0009_00FC => Ok(ScardIoCtlCode::WriteCacheW),
            0x0009_0100 => Ok(ScardIoCtlCode::GetTransmitCount),
            0x0009_0104 => Ok(ScardIoCtlCode::GetReaderIcon),
            0x0009_0108 => Ok(ScardIoCtlCode::GetDeviceTypeId),
            _ => {
                error!("Unsupported ScardIoCtlCode: 0x{:08x}", value);
                Err(invalid_field_err!("try_from", "ScardIoCtlCode", "unsupported value"))
            }
        }
    }
}

/// Allow [`ScardIoCtlCode`] to be used as an [`IoCtlCode`].
impl IoCtlCode for ScardIoCtlCode {}

/// [2.2.2.30] ScardAccessStartedEvent_Call
///
/// [2.2.2.30]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/c5ab8dd0-4914-4355-960c-0a527971ea69
#[derive(Debug, PartialEq, Clone)]
pub struct ScardAccessStartedEventCall;

impl ScardAccessStartedEventCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        ironrdp_pdu::read_padding!(src, 4); // Unused (4 bytes)
        Ok(Self)
    }
}

/// [2.2.3.3] Long_Return
///
/// [2.2.3.3]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/e77a1365-2379-4037-99c4-d30d14ba10fc
#[derive(Debug, PartialEq, Clone)]
pub struct LongReturn {
    return_code: ReturnCode,
}

impl LongReturn {
    const NAME: &'static str = "Long_Return";

    pub fn new(return_code: ReturnCode) -> rpce::Pdu<Self> {
        rpce::Pdu(Self { return_code })
    }
}

impl rpce::HeaderlessEncode for LongReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size()
    }
}

/// [2.2.8] Return Code
///
/// [2.2.8]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/9861f8da-76fe-41e6-847e-40c9aa35df8d
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u32)]
pub enum ReturnCode {
    /// SCARD_S_SUCCESS
    Success = 0x0000_0000,
    /// SCARD_F_INTERNAL_ERROR
    InternalError = 0x8010_0001,
    /// SCARD_E_CANCELLED
    Cancelled = 0x8010_0002,
    /// SCARD_E_INVALID_HANDLE
    InvalidHandle = 0x8010_0003,
    /// SCARD_E_INVALID_PARAMETER
    InvalidParameter = 0x8010_0004,
    /// SCARD_E_INVALID_TARGET
    InvalidTarget = 0x8010_0005,
    /// SCARD_E_NO_MEMORY
    NoMemory = 0x8010_0006,
    /// SCARD_F_WAITED_TOO_LONG
    WaitedTooLong = 0x8010_0007,
    /// SCARD_E_INSUFFICIENT_BUFFER
    InsufficientBuffer = 0x8010_0008,
    /// SCARD_E_UNKNOWN_READER
    UnknownReader = 0x8010_0009,
    /// SCARD_E_TIMEOUT
    Timeout = 0x8010_000A,
    /// SCARD_E_SHARING_VIOLATION
    SharingViolation = 0x8010_000B,
    /// SCARD_E_NO_SMARTCARD
    NoSmartcard = 0x8010_000C,
    /// SCARD_E_UNKNOWN_CARD
    UnknownCard = 0x8010_000D,
    /// SCARD_E_CANT_DISPOSE
    CantDispose = 0x8010_000E,
    /// SCARD_E_PROTO_MISMATCH
    ProtoMismatch = 0x8010_000F,
    /// SCARD_E_NOT_READY
    NotReady = 0x8010_0010,
    /// SCARD_E_INVALID_VALUE
    InvalidValue = 0x8010_0011,
    /// SCARD_E_SYSTEM_CANCELLED
    SystemCancelled = 0x8010_0012,
    /// SCARD_F_COMM_ERROR
    CommError = 0x8010_0013,
    /// SCARD_F_UNKNOWN_ERROR
    UnknownError = 0x8010_0014,
    /// SCARD_E_INVALID_ATR
    InvalidAtr = 0x8010_0015,
    /// SCARD_E_NOT_TRANSACTED
    NotTransacted = 0x8010_0016,
    /// SCARD_E_READER_UNAVAILABLE
    ReaderUnavailable = 0x8010_0017,
    /// SCARD_P_SHUTDOWN
    Shutdown = 0x8010_0018,
    /// SCARD_E_PCI_TOO_SMALL
    PciTooSmall = 0x8010_0019,
    /// SCARD_E_ICC_INSTALLATION
    IccInstallation = 0x8010_0020,
    /// SCARD_E_ICC_CREATEORDER
    IccCreateorder = 0x8010_0021,
    /// SCARD_E_UNSUPPORTED_FEATURE
    UnsupportedFeature = 0x8010_0022,
    /// SCARD_E_DIR_NOT_FOUND
    DirNotFound = 0x8010_0023,
    /// SCARD_E_FILE_NOT_FOUND
    FileNotFound = 0x8010_0024,
    /// SCARD_E_NO_DIR
    NoDir = 0x8010_0025,
    /// SCARD_E_READER_UNSUPPORTED
    ReaderUnsupported = 0x8010_001A,
    /// SCARD_E_DUPLICATE_READER
    DuplicateReader = 0x8010_001B,
    /// SCARD_E_CARD_UNSUPPORTED
    CardUnsupported = 0x8010_001C,
    /// SCARD_E_NO_SERVICE
    NoService = 0x8010_001D,
    /// SCARD_E_SERVICE_STOPPED
    ServiceStopped = 0x8010_001E,
    /// SCARD_E_UNEXPECTED
    Unexpected = 0x8010_001F,
    /// SCARD_E_NO_FILE
    NoFile = 0x8010_0026,
    /// SCARD_E_NO_ACCESS
    NoAccess = 0x8010_0027,
    /// SCARD_E_WRITE_TOO_MANY
    WriteTooMany = 0x8010_0028,
    /// SCARD_E_BAD_SEEK
    BadSeek = 0x8010_0029,
    /// SCARD_E_INVALID_CHV
    InvalidChv = 0x8010_002A,
    /// SCARD_E_UNKNOWN_RES_MSG
    UnknownResMsg = 0x8010_002B,
    /// SCARD_E_NO_SUCH_CERTIFICATE
    NoSuchCertificate = 0x8010_002C,
    /// SCARD_E_CERTIFICATE_UNAVAILABLE
    CertificateUnavailable = 0x8010_002D,
    /// SCARD_E_NO_READERS_AVAILABLE
    NoReadersAvailable = 0x8010_002E,
    /// SCARD_E_COMM_DATA_LOST
    CommDataLost = 0x8010_002F,
    /// SCARD_E_NO_KEY_CONTAINER
    NoKeyContainer = 0x8010_0030,
    /// SCARD_E_SERVER_TOO_BUSY
    ServerTooBusy = 0x8010_0031,
    /// SCARD_E_PIN_CACHE_EXPIRED
    PinCacheExpired = 0x8010_0032,
    /// SCARD_E_NO_PIN_CACHE
    NoPinCache = 0x8010_0033,
    /// SCARD_E_READ_ONLY_CARD
    ReadOnlyCard = 0x8010_0034,
    /// SCARD_W_UNSUPPORTED_CARD
    UnsupportedCard = 0x8010_0065,
    /// SCARD_W_UNRESPONSIVE_CARD
    UnresponsiveCard = 0x8010_0066,
    /// SCARD_W_UNPOWERED_CARD
    UnpoweredCard = 0x8010_0067,
    /// SCARD_W_RESET_CARD
    ResetCard = 0x8010_0068,
    /// SCARD_W_REMOVED_CARD
    RemovedCard = 0x8010_0069,
    /// SCARD_W_SECURITY_VIOLATION
    SecurityViolation = 0x8010_006A,
    /// SCARD_W_WRONG_CHV
    WrongChv = 0x8010_006B,
    /// SCARD_W_CHV_BLOCKED
    ChvBlocked = 0x8010_006C,
    /// SCARD_W_EOF
    Eof = 0x8010_006D,
    /// SCARD_W_CANCELLED_BY_USER
    CancelledByUser = 0x8010_006E,
    /// SCARD_W_CARD_NOT_AUTHENTICATED
    CardNotAuthenticated = 0x8010_006F,
    /// SCARD_W_CACHE_ITEM_NOT_FOUND
    CacheItemNotFound = 0x8010_0070,
    /// SCARD_W_CACHE_ITEM_STALE
    CacheItemStale = 0x8010_0071,
    /// SCARD_W_CACHE_ITEM_TOO_BIG
    CacheItemTooBig = 0x8010_0072,
}

impl ReturnCode {
    pub fn size(&self) -> usize {
        size_of::<u32>()
    }
}

impl From<ReturnCode> for u32 {
    fn from(val: ReturnCode) -> Self {
        val as u32
    }
}

/// [2.2.2.1] EstablishContext_Call
///
/// [2.2.2.1]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/b990635a-7637-464a-8923-361ed3e3d67a
#[derive(Debug, PartialEq, Clone)]
pub struct EstablishContextCall {
    pub scope: Scope,
}

impl EstablishContextCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }

    fn size() -> usize {
        size_of::<u32>()
    }
}

impl rpce::HeaderlessDecode for EstablishContextCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        ensure_size!(in: src, size: Self::size());
        let scope = Scope::try_from(src.read_u32())?;
        Ok(Self { scope })
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u32)]
pub enum Scope {
    User = 0x0000_0000,
    Terminal = 0x0000_0001,
    System = 0x0000_0002,
}

impl Scope {
    pub fn size(&self) -> usize {
        size_of::<u32>()
    }
}

impl TryFrom<u32> for Scope {
    type Error = DecodeError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            0x0000_0000 => Ok(Scope::User),
            0x0000_0001 => Ok(Scope::Terminal),
            0x0000_0002 => Ok(Scope::System),
            _ => {
                error!("Unsupported Scope: 0x{:08x}", value);
                Err(invalid_field_err!("try_from", "Scope", "unsupported value"))
            }
        }
    }
}

/// [2.2.3.2] EstablishContext_Return
///
/// [2.2.3.2]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/9135d95f-3740-411b-bdca-34ac7571fddc
#[derive(Debug, PartialEq, Clone)]
pub struct EstablishContextReturn {
    return_code: ReturnCode,
    context: ScardContext,
}

impl EstablishContextReturn {
    const NAME: &'static str = "EstablishContext_Return";

    pub fn new(return_code: ReturnCode, context: ScardContext) -> rpce::Pdu<Self> {
        rpce::Pdu(Self { return_code, context })
    }
}

impl rpce::HeaderlessEncode for EstablishContextReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let mut index = 0;
        self.context.encode_ptr(&mut index, dst)?;
        self.context.encode_value(dst)?;
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() + self.context.size()
    }
}

/// [2.2.2.4] ListReaders_Call
///
/// [2.2.2.4]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/be2f46a5-77fb-40bf-839c-aed45f0a26d7
#[derive(Debug, PartialEq, Clone)]
pub struct ListReadersCall {
    pub context: ScardContext,
    pub groups_ptr_length: u32,
    pub groups_length: u32,
    pub groups_ptr: u32,
    pub groups: Vec<String>,
    pub readers_is_null: bool, // u32
    pub readers_size: u32,
}

impl ListReadersCall {
    pub fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, charset)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for ListReadersCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        let charset = expect_charset(charset)?;
        let mut index = 0;
        let mut context = ScardContext::decode_ptr(src, &mut index)?;

        ensure_size!(in: src, size: size_of::<u32>());
        let groups_ptr_length = src.read_u32();

        let groups_ptr = ndr::decode_ptr(src, &mut index)?;

        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let readers_is_null = (src.read_u32()) == 0x0000_0001;
        let readers_size = src.read_u32();

        context.decode_value(src, None)?;

        if groups_ptr == 0 {
            return Ok(Self {
                context,
                groups_ptr_length,
                groups_ptr,
                groups_length: 0,
                groups: Vec::new(),
                readers_is_null,
                readers_size,
            });
        }

        ensure_size!(in: src, size: size_of::<u32>());
        let groups_length = src.read_u32();
        if groups_length != groups_ptr_length {
            return Err(invalid_field_err!(
                "decode",
                "mismatched reader groups length in NDR pointer and value"
            ));
        }

        let groups = read_multistring_from_cursor(src, charset)?;

        Ok(Self {
            context,
            groups_ptr_length,
            groups_ptr,
            groups_length,
            groups,
            readers_is_null,
            readers_size,
        })
    }
}

/// [2.2.3.4] ListReaderGroups_Return and ListReaders_Return
///
/// [2.2.3.4]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/6630bb5b-fc0e-4141-8b53-263225c7628d
#[derive(Debug, PartialEq, Clone)]
pub struct ListReadersReturn {
    pub return_code: ReturnCode,
    pub readers: Vec<String>,
}

impl ListReadersReturn {
    const NAME: &'static str = "ListReaders_Return";

    pub fn new(return_code: ReturnCode, readers: Vec<String>) -> rpce::Pdu<Self> {
        rpce::Pdu(Self { return_code, readers })
    }
}

impl rpce::HeaderlessEncode for ListReadersReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let readers_length: u32 = cast_length!(
            "ListReadersReturn",
            "readers",
            encoded_multistring_len(&self.readers, CharacterSet::Unicode)
        )?;
        let mut index = 0;
        ndr::encode_ptr(Some(readers_length), &mut index, dst)?;
        dst.write_u32(readers_length);
        write_multistring_to_cursor(dst, &self.readers, CharacterSet::Unicode)?;
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() // dst.write_u32(self.return_code.into());
        + ndr::ptr_size(true) // ndr::encode_ptr(...);
        + 4 // dst.write_u32(readers_length);
        + encoded_multistring_len(&self.readers, CharacterSet::Unicode) // write_multistring_to_cursor(...);
    }
}

/// [2.2.2.12] GetStatusChangeW_Call
///
/// [2.2.2.12]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/af357ce8-63ee-4577-b6bf-c6f5ca68d754
#[derive(Debug, PartialEq, Clone)]
pub struct GetStatusChangeCall {
    pub context: ScardContext,
    pub timeout: u32,
    pub states_ptr_length: u32,
    pub states_ptr: u32,
    pub states_length: u32,
    pub states: Vec<ReaderState>,
}

impl GetStatusChangeCall {
    pub fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, charset)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for GetStatusChangeCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        let mut index = 0;
        let mut context = ScardContext::decode_ptr(src, &mut index)?;

        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let timeout = src.read_u32();
        let states_ptr_length = src.read_u32();

        let states_ptr = ndr::decode_ptr(src, &mut index)?;

        context.decode_value(src, None)?;

        ensure_size!(in: src, size: size_of::<u32>());
        let states_length = src.read_u32();

        let mut states = Vec::new();
        for _ in 0..states_length {
            let state = ReaderState::decode_ptr(src, &mut index)?;
            states.push(state);
        }
        for state in states.iter_mut() {
            state.decode_value(src, charset)?;
        }

        Ok(Self {
            context,
            timeout,
            states_ptr_length,
            states_ptr,
            states_length,
            states,
        })
    }
}

/// [2.2.1.5] ReaderState_Common_Call
///
/// [2.2.1.5]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/a71e63ba-e58f-487c-a5d2-5a3e48856594
#[derive(Debug, PartialEq, Clone)]
pub struct ReaderStateCommonCall {
    pub current_state: CardStateFlags,
    pub event_state: CardStateFlags,
    pub atr_length: u32,
    pub atr: [u8; 36],
}

impl ReaderStateCommonCall {
    const FIXED_PART_SIZE: usize = size_of::<u32>() * 3 /* dwCurrentState, dwEventState, cbAtr */ + 36 /* rgbAtr */;

    fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        ensure_size!(in: src, size: Self::FIXED_PART_SIZE);
        let current_state = CardStateFlags::from_bits_retain(src.read_u32());
        let event_state = CardStateFlags::from_bits_retain(src.read_u32());
        let atr_length = src.read_u32();
        let atr = src.read_array::<36>();

        Ok(Self {
            current_state,
            event_state,
            atr_length,
            atr,
        })
    }

    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        dst.write_u32(self.current_state.bits());
        dst.write_u32(self.event_state.bits());
        dst.write_u32(self.atr_length);
        dst.write_slice(&self.atr);
        Ok(())
    }

    fn size() -> usize {
        Self::FIXED_PART_SIZE
    }
}

bitflags! {
    #[derive(Debug, PartialEq, Clone, Copy)]
    pub struct CardStateFlags: u32 {
        const SCARD_STATE_UNAWARE = 0x0000_0000;
        const SCARD_STATE_IGNORE = 0x0000_0001;
        const SCARD_STATE_CHANGED = 0x0000_0002;
        const SCARD_STATE_UNKNOWN = 0x0000_0004;
        const SCARD_STATE_UNAVAILABLE = 0x0000_0008;
        const SCARD_STATE_EMPTY = 0x0000_0010;
        const SCARD_STATE_PRESENT = 0x0000_0020;
        const SCARD_STATE_ATRMATCH = 0x0000_0040;
        const SCARD_STATE_EXCLUSIVE = 0x0000_0080;
        const SCARD_STATE_INUSE = 0x0000_0100;
        const SCARD_STATE_MUTE = 0x0000_0200;
        const SCARD_STATE_UNPOWERED = 0x0000_0400;
    }
}

/// [2.2.3.5] LocateCards_Return and GetStatusChange_Return
///
/// [2.2.3.5]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/7b73e0c2-e0fc-46b1-9b03-50684ad2beba
#[derive(Debug, PartialEq, Clone)]
pub struct GetStatusChangeReturn {
    pub return_code: ReturnCode,
    pub reader_states: Vec<ReaderStateCommonCall>,
}

impl GetStatusChangeReturn {
    const NAME: &'static str = "GetStatusChange_Return";

    pub fn new(return_code: ReturnCode, reader_states: Vec<ReaderStateCommonCall>) -> rpce::Pdu<Self> {
        rpce::Pdu(Self {
            return_code,
            reader_states,
        })
    }
}

impl rpce::HeaderlessEncode for GetStatusChangeReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let reader_states_len = cast_length!("GetStatusChangeReturn", "reader_states", self.reader_states.len())?;
        let mut index = 0;
        ndr::encode_ptr(Some(reader_states_len), &mut index, dst)?;
        dst.write_u32(reader_states_len);
        for reader_state in &self.reader_states {
            reader_state.encode(dst)?;
        }
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() // dst.write_u32(self.return_code.into());
        + ndr::ptr_size(true) // ndr::encode_ptr(Some(reader_states_len), &mut index, dst)?;
        + 4 // dst.write_u32(reader_states_len);
        + self.reader_states.iter().map(|_s| ReaderStateCommonCall::size()).sum::<usize>()
    }
}

/// [2.2.2.14] ConnectW_Call
///
/// [2.2.2.14]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/fd06f6a0-a9ea-478c-9b5e-470fd9cde5a6
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectCall {
    pub reader: String,
    pub common: ConnectCommon,
}

impl ConnectCall {
    pub fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, charset)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for ConnectCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        let charset = expect_charset(charset)?;
        let mut index = 0;
        let _reader_ptr = ndr::decode_ptr(src, &mut index)?;
        let mut common = ConnectCommon::decode_ptr(src, &mut index)?;
        let reader = ndr::read_string_from_cursor(src, charset)?;
        common.decode_value(src, None)?;
        Ok(Self { reader, common })
    }
}

/// [2.2.1.3] Connect_Common
///
/// [2.2.1.3]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/32752f32-4410-4682-b9fc-9096674b52de
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectCommon {
    pub context: ScardContext,
    pub share_mode: u32,
    pub preferred_protocols: CardProtocol,
}

impl ndr::Decode for ConnectCommon {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self>
    where
        Self: Sized,
    {
        let context = ScardContext::decode_ptr(src, index)?;
        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let share_mode = src.read_u32();
        let preferred_protocols = CardProtocol::from_bits_retain(src.read_u32());
        Ok(Self {
            context,
            share_mode,
            preferred_protocols,
        })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        expect_no_charset(charset)?;
        self.context.decode_value(src, None)
    }
}

bitflags! {
    /// [2.2.5] Protocol Identifier
    ///
    /// [2.2.5]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/41673567-2710-4e86-be87-7b6f46fe10af
    #[derive(Debug, PartialEq, Clone)]
    pub struct CardProtocol: u32 {
        const SCARD_PROTOCOL_UNDEFINED = 0x0000_0000;
        const SCARD_PROTOCOL_T0 = 0x0000_0001;
        const SCARD_PROTOCOL_T1 = 0x0000_0002;
        const SCARD_PROTOCOL_TX = 0x0000_0003;
        const SCARD_PROTOCOL_RAW = 0x0001_0000;
        const SCARD_PROTOCOL_DEFAULT = 0x8000_0000;
        const SCARD_PROTOCOL_OPTIMAL = 0x0000_0000;
    }
}

/// [2.2.1.2] REDIR_SCARDHANDLE
///
/// [2.2.1.2]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/b6276356-7c5f-4d3e-be92-a6c85e58d008
#[derive(Debug, PartialEq, Clone)]
pub struct ScardHandle {
    pub context: ScardContext,
    /// Shortcut: we always create 4-byte handle values.
    /// The spec allows this field to have variable length.
    pub value: u32,
}

impl ScardHandle {
    /// See [`ScardHandle::value`]
    const VALUE_LENGTH: u32 = 4;

    pub fn new(context: ScardContext, value: u32) -> Self {
        Self { context, value }
    }
}

impl ndr::Decode for ScardHandle {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self>
    where
        Self: Sized,
    {
        let context = ScardContext::decode_ptr(src, index)?;
        ensure_size!(ctx: "ScardHandle::decode_ptr", in: src, size: size_of::<u32>());
        let length = src.read_u32();
        if length != Self::VALUE_LENGTH {
            error!(?length, "Unsupported value length in ScardHandle");
            return Err(invalid_field_err!(
                "decode_ptr",
                "unsupported value length in ScardHandle"
            ));
        }
        let _ptr = ndr::decode_ptr(src, index)?;
        Ok(Self { context, value: 0 })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        expect_no_charset(charset)?;
        self.context.decode_value(src, None)?;
        ensure_size!(in: src, size: size_of::<u32>());
        let length = src.read_u32();
        if length != Self::VALUE_LENGTH {
            error!(?length, "Unsupported value length in ScardHandle");
            return Err(invalid_field_err!(
                "decode_value",
                "unsupported value length in ScardHandle"
            ));
        }
        ensure_size!(in: src, size: size_of::<u32>());
        self.value = src.read_u32();
        Ok(())
    }
}

impl ndr::Encode for ScardHandle {
    fn encode_ptr(&self, index: &mut u32, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        self.context.encode_ptr(index, dst)?;
        ndr::encode_ptr(Some(Self::VALUE_LENGTH), index, dst)?;
        Ok(())
    }

    fn encode_value(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size_value());
        self.context.encode_value(dst)?;
        dst.write_u32(Self::VALUE_LENGTH);
        dst.write_u32(self.value);
        Ok(())
    }

    fn size_ptr(&self) -> usize {
        self.context.size_ptr() + ndr::ptr_size(true)
    }

    fn size_value(&self) -> usize {
        self.context.size_value() + 4 /* cbHandle */ + 4 /* pbHandle */
    }
}

/// [2.2.3.8] Connect_Return
///
/// [2.2.3.8]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/ad9fbc8e-0963-44ac-8d71-38021685790c
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectReturn {
    pub return_code: ReturnCode,
    pub handle: ScardHandle,
    pub active_protocol: CardProtocol,
}

impl ConnectReturn {
    const NAME: &'static str = "Connect_Return";

    pub fn new(return_code: ReturnCode, handle: ScardHandle, active_protocol: CardProtocol) -> rpce::Pdu<Self> {
        rpce::Pdu(Self {
            return_code,
            handle,
            active_protocol,
        })
    }
}

impl rpce::HeaderlessEncode for ConnectReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let mut index = 0;
        self.handle.encode_ptr(&mut index, dst)?;
        dst.write_u32(self.active_protocol.bits());
        self.handle.encode_value(dst)?;
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() + self.handle.size() + 4 /* dwActiveProtocol */
    }
}

/// [2.2.2.16] HCardAndDisposition_Call
///
/// [2.2.2.16]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/f15ae865-9e99-4c5b-bb43-15a6b4885bd0
#[derive(Debug, PartialEq, Clone)]
pub struct HCardAndDispositionCall {
    pub handle: ScardHandle,
    pub disposition: u32,
}

impl HCardAndDispositionCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for HCardAndDispositionCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        let mut index = 0;
        let mut handle = ScardHandle::decode_ptr(src, &mut index)?;
        ensure_size!(in: src, size: size_of::<u32>());
        let disposition = src.read_u32();
        handle.decode_value(src, None)?;
        Ok(Self { handle, disposition })
    }
}

/// [2.2.2.19] Transmit_Call
///
/// [2.2.2.19]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/e3861cfa-e61b-4d64-b19d-f6b31e076beb
#[derive(Debug, PartialEq, Clone)]
pub struct TransmitCall {
    pub handle: ScardHandle,
    pub send_pci: SCardIORequest,
    pub send_length: u32,
    pub send_buffer: Vec<u8>,
    pub recv_pci: Option<SCardIORequest>,
    pub recv_buffer_is_null: bool,
    pub recv_length: u32,
}

impl TransmitCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for TransmitCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        let mut index = 0;
        let mut handle = ScardHandle::decode_ptr(src, &mut index)?;
        let mut send_pci = SCardIORequest::decode_ptr(src, &mut index)?;
        ensure_size!(in: src, size: size_of::<u32>());
        let _send_length = src.read_u32();
        let _send_buffer_ptr = ndr::decode_ptr(src, &mut index)?;
        let recv_pci_ptr = ndr::decode_ptr(src, &mut index)?;
        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let recv_buffer_is_null = src.read_u32() == 1;
        let recv_length = src.read_u32();

        handle.decode_value(src, None)?;
        send_pci.decode_value(src, None)?;

        ensure_size!(in: src, size: size_of::<u32>());
        let send_length = src.read_u32();
        let send_length_usize: usize = cast_length!("TransmitCall", "send_length", send_length)?;
        ensure_size!(in: src, size: send_length_usize);
        let send_buffer = src.read_slice(send_length_usize).to_vec();

        let recv_pci = if recv_pci_ptr != 0 {
            let mut recv_pci = SCardIORequest::decode_ptr(src, &mut index)?;
            recv_pci.decode_value(src, None)?;
            Some(recv_pci)
        } else {
            None
        };

        Ok(Self {
            handle,
            send_pci,
            send_length,
            send_buffer,
            recv_pci,
            recv_buffer_is_null,
            recv_length,
        })
    }
}

/// [2.2.1.8] SCardIO_Request
///
/// [2.2.1.8]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/f6e15da8-5bc0-4ef6-b28a-ce88e8415621
#[derive(Debug, PartialEq, Clone)]
pub struct SCardIORequest {
    pub protocol: CardProtocol,
    pub extra_bytes_length: u32,
    pub extra_bytes: Vec<u8>,
}

impl ndr::Decode for SCardIORequest {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self>
    where
        Self: Sized,
    {
        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let protocol = CardProtocol::from_bits_retain(src.read_u32());
        let extra_bytes_length = src.read_u32();
        let _extra_bytes_ptr = ndr::decode_ptr(src, index)?;
        let extra_bytes = Vec::new();
        Ok(Self {
            protocol,
            extra_bytes_length,
            extra_bytes,
        })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        expect_no_charset(charset)?;
        let extra_bytes_length: usize = cast_length!("TransmitCall", "extra_bytes_length", self.extra_bytes_length)?;
        ensure_size!(in: src, size: extra_bytes_length);
        self.extra_bytes = src.read_slice(extra_bytes_length).to_vec();
        Ok(())
    }
}

impl ndr::Encode for SCardIORequest {
    fn encode_ptr(&self, index: &mut u32, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size_ptr());
        dst.write_u32(self.protocol.bits());
        ndr::encode_ptr(Some(self.extra_bytes_length), index, dst)
    }

    fn encode_value(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size_value());
        dst.write_slice(&self.extra_bytes);
        Ok(())
    }

    fn size_ptr(&self) -> usize {
        4 /* dwProtocol */ + ndr::ptr_size(true)
    }

    fn size_value(&self) -> usize {
        self.extra_bytes_length as usize
    }
}

/// [2.2.3.11] Transmit_Return
///
/// [2.2.3.11]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/252cffd0-58b8-434d-9e1b-0d547544fb0f
#[derive(Debug, PartialEq, Clone)]
pub struct TransmitReturn {
    pub return_code: ReturnCode,
    pub recv_pci: Option<SCardIORequest>,
    pub recv_buffer: Vec<u8>,
}

impl TransmitReturn {
    const NAME: &'static str = "Transmit_Return";

    pub fn new(return_code: ReturnCode, recv_pci: Option<SCardIORequest>, recv_buffer: Vec<u8>) -> rpce::Pdu<Self> {
        rpce::Pdu(Self {
            return_code,
            recv_pci,
            recv_buffer,
        })
    }
}

impl rpce::HeaderlessEncode for TransmitReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());

        let mut index = 0;
        if let Some(recv_pci) = &self.recv_pci {
            recv_pci.encode_ptr(&mut index, dst)?;
            recv_pci.encode_value(dst)?;
        } else {
            dst.write_u32(0); // null value
        }

        let recv_buffer_len: u32 = cast_length!("TransmitReturn", "recv_buffer_len", self.recv_buffer.len())?;
        ndr::encode_ptr(Some(recv_buffer_len), &mut index, dst)?;
        dst.write_u32(recv_buffer_len);
        dst.write_slice(&self.recv_buffer);

        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() // dst.write_u32(self.return_code.into());
        + if let Some(recv_pci) = &self.recv_pci {
            recv_pci.size()
        } else {
            4 // null value
        }
        + ndr::ptr_size(true) // ndr::encode_ptr(Some(recv_buffer_len), &mut index, dst)?;
        + 4 // dst.write_u32(recv_buffer_len);
        + self.recv_buffer.len() // dst.write_slice(&self.recv_buffer);
    }
}

/// [2.2.2.18] Status_Call
///
/// [2.2.2.18]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/f1139aed-e578-47f3-a800-f36b56c80500
#[derive(Debug, PartialEq, Clone)]
pub struct StatusCall {
    pub handle: ScardHandle,
    pub reader_names_is_null: bool,
    pub reader_length: u32,
    pub atr_length: u32,
}

impl StatusCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for StatusCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        let mut index = 0;
        let mut handle = ScardHandle::decode_ptr(src, &mut index)?;
        ensure_size!(in: src, size: size_of::<u32>() * 3);
        let reader_names_is_null = src.read_u32() == 1;
        let reader_length = src.read_u32();
        let atr_length = src.read_u32();
        handle.decode_value(src, None)?;
        Ok(Self {
            handle,
            reader_names_is_null,
            reader_length,
            atr_length,
        })
    }
}

/// [2.2.3.10] Status_Return
///
/// [2.2.3.10]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/987c1358-ad6b-4c8e-88e1-06210c28a66f
#[derive(Debug, PartialEq, Clone)]
pub struct StatusReturn {
    pub return_code: ReturnCode,
    pub reader_names: Vec<String>,
    pub state: CardState,
    pub protocol: CardProtocol,
    pub atr: [u8; 32],
    pub atr_length: u32,

    pub encoding: CharacterSet,
}

impl StatusReturn {
    const NAME: &'static str = "Status_Return";

    pub fn new(
        return_code: ReturnCode,
        reader_names: Vec<String>,
        state: CardState,
        protocol: CardProtocol,
        atr: [u8; 32],
        atr_length: u32,
        encoding: CharacterSet,
    ) -> rpce::Pdu<Self> {
        rpce::Pdu(Self {
            return_code,
            reader_names,
            state,
            protocol,
            atr,
            atr_length,
            encoding,
        })
    }
}

impl rpce::HeaderlessEncode for StatusReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let mut index = 0;
        let reader_names_length: u32 = cast_length!(
            "StatusReturn",
            "reader_names_length",
            encoded_multistring_len(&self.reader_names, self.encoding)
        )?;
        ndr::encode_ptr(Some(reader_names_length), &mut index, dst)?;
        dst.write_u32(self.state.into());
        dst.write_u32(self.protocol.bits());
        dst.write_slice(&self.atr);
        dst.write_u32(self.atr_length);
        dst.write_u32(reader_names_length);
        write_multistring_to_cursor(dst, &self.reader_names, self.encoding)?;
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        size_of::<u32>() * 5 // dst.write_u32(self.return_code.into()); dst.write_u32(self.state.into()); dst.write_u32(self.protocol.bits()); dst.write_slice(&self.atr); dst.write_u32(self.atr_length);
        + ndr::ptr_size(true) // ndr::encode_ptr(Some(reader_names_length), &mut index, dst)?;
        + self.atr.len() // dst.write_slice(&self.atr);
        + encoded_multistring_len(&self.reader_names, self.encoding) // write_multistring_to_cursor(dst, &self.reader_names, self.encoding)?;
    }
}

/// [2.2.4] Card/Reader State
///
/// [2.2.4]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/264bc504-1195-43ff-a057-3d86a02c5d9c
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum CardState {
    /// SCARD_UNKNOWN
    Unknown = 0x0000_0000,
    /// SCARD_ABSENT
    Absent = 0x0000_0001,
    /// SCARD_PRESENT
    Present = 0x0000_0002,
    /// SCARD_SWALLOWED
    Swallowed = 0x0000_0003,
    /// SCARD_POWERED
    Powered = 0x0000_0004,
    /// SCARD_NEGOTIABLE
    Negotiable = 0x0000_0005,
    /// SCARD_SPECIFICMODE
    SpecificMode = 0x0000_0006,
}

impl From<CardState> for u32 {
    fn from(val: CardState) -> Self {
        val as u32
    }
}

/// [2.2.2.2] Context_Call
///
/// [2.2.2.2]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/b11d26d9-c3d5-4e96-8d9f-aba35cded852
#[derive(Debug, PartialEq, Clone)]
pub struct ContextCall {
    pub context: ScardContext,
}

impl ContextCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for ContextCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        let mut index = 0;
        let mut context = ScardContext::decode_ptr(src, &mut index)?;
        context.decode_value(src, None)?;
        Ok(Self { context })
    }
}

/// [2.2.2.32] GetDeviceTypeId_Call
///
/// [2.2.2.32]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/b5e18874-c42d-42ea-b1b1-3fd86a8a95f1
#[derive(Debug, PartialEq, Clone)]
pub struct GetDeviceTypeIdCall {
    pub context: ScardContext,
    pub reader_ptr: u32,
    pub reader_name: String,
}

impl GetDeviceTypeIdCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for GetDeviceTypeIdCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        let mut index = 0;
        let mut context = ScardContext::decode_ptr(src, &mut index)?;
        let reader_ptr = ndr::decode_ptr(src, &mut index)?;
        context.decode_value(src, None)?;
        let reader_name = ndr::read_string_from_cursor(src, CharacterSet::Unicode)?;
        Ok(Self {
            context,
            reader_ptr,
            reader_name,
        })
    }
}

/// [2.2.3.15] GetDeviceTypeId_Return
///
/// [2.2.3.15]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/fed90d29-c41f-490a-86e9-7e88e42656b2
#[derive(Debug, PartialEq, Clone)]
pub struct GetDeviceTypeIdReturn {
    pub return_code: ReturnCode,
    pub device_type_id: u32,
}

impl GetDeviceTypeIdReturn {
    const NAME: &'static str = "GetDeviceTypeId_Return";

    pub fn new(return_code: ReturnCode, device_type_id: u32) -> rpce::Pdu<Self> {
        rpce::Pdu(Self {
            return_code,
            device_type_id,
        })
    }
}

impl rpce::HeaderlessEncode for GetDeviceTypeIdReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        dst.write_u32(self.device_type_id);
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() // dst.write_u32(self.return_code.into());
        + size_of::<u32>() // dst.write_u32(self.device_type_id);
    }
}

/// [2.2.2.26] ReadCacheW_Call
///
/// [2.2.2.26]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/f45705cf-9299-4802-b408-685f02025e6a
#[derive(Debug, PartialEq, Clone)]
pub struct ReadCacheCall {
    pub lookup_name: String,
    pub common: ReadCacheCommon,
}

impl ReadCacheCall {
    pub fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, charset)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for ReadCacheCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        let charset = expect_charset(charset)?;
        let mut index = 0;
        let _lookup_name_ptr = ndr::decode_ptr(src, &mut index)?;
        let mut common = ReadCacheCommon::decode_ptr(src, &mut index)?;
        let lookup_name = ndr::read_string_from_cursor(src, charset)?;
        common.decode_value(src, None)?;
        Ok(Self { lookup_name, common })
    }
}

/// [2.2.1.9] ReadCache_Common
///
/// [2.2.1.9]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/3f9e07fa-66e2-498b-920c-39531709116b
#[derive(Debug, PartialEq, Clone)]
pub struct ReadCacheCommon {
    pub context: ScardContext,
    pub card_uuid: Vec<u8>,
    pub freshness_counter: u32,
    pub data_is_null: bool,
    pub data_len: u32,
}

impl ndr::Decode for ReadCacheCommon {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self>
    where
        Self: Sized,
    {
        let context = ScardContext::decode_ptr(src, index)?;
        let _card_uuid_ptr = ndr::decode_ptr(src, index)?;
        ensure_size!(in: src, size: size_of::<u32>() * 2 + size_of::<i32>());
        let freshness_counter = src.read_u32();
        let data_is_null = src.read_i32() == 1;
        let data_len = src.read_u32();

        Ok(Self {
            context,
            card_uuid: Vec::new(),
            freshness_counter,
            data_is_null,
            data_len,
        })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        expect_no_charset(charset)?;
        self.context.decode_value(src, None)?;
        ensure_size!(in: src, size: 16);
        self.card_uuid = src.read_slice(16).to_vec();
        Ok(())
    }
}

/// [2.2.3.1] ReadCache_Return
///
/// [2.2.3.1]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/da342355-e37f-485e-a490-3222a97fa356
#[derive(Debug, PartialEq, Clone)]
pub struct ReadCacheReturn {
    pub return_code: ReturnCode,
    pub data: Vec<u8>,
}

impl ReadCacheReturn {
    const NAME: &'static str = "ReadCache_Return";

    pub fn new(return_code: ReturnCode, data: Vec<u8>) -> rpce::Pdu<Self> {
        rpce::Pdu(Self { return_code, data })
    }
}

impl rpce::HeaderlessEncode for ReadCacheReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let mut index = 0;
        let data_len: u32 = cast_length!("ReadCacheReturn", "data_len", self.data.len())?;
        ndr::encode_ptr(Some(data_len), &mut index, dst)?;
        dst.write_u32(data_len);
        dst.write_slice(&self.data);
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.return_code.size() // dst.write_u32(self.return_code.into());
        + ndr::ptr_size(true) // ndr::encode_ptr(Some(data_len), &mut index, dst)?;
        + size_of::<u32>() // dst.write_u32(data_len);
        + self.data.len() // dst.write_slice(&self.data);
    }
}

/// [2.2.2.28] WriteCacheW_Call
///
/// [2.2.2.28]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/3969bdcd-ecf3-42db-8bc6-2d6f970f9c67
#[derive(Debug, PartialEq, Clone)]
pub struct WriteCacheCall {
    pub lookup_name: String,
    pub common: WriteCacheCommon,
}

impl WriteCacheCall {
    pub fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, charset)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for WriteCacheCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        let charset = expect_charset(charset)?;
        let mut index = 0;
        let _lookup_name_ptr = ndr::decode_ptr(src, &mut index)?;
        let mut common = WriteCacheCommon::decode_ptr(src, &mut index)?;
        let lookup_name = ndr::read_string_from_cursor(src, charset)?;
        common.decode_value(src, None)?;
        Ok(Self { lookup_name, common })
    }
}

/// [2.2.1.10] WriteCache_Common
///
/// [2.2.1.10]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/5604251b-9173-457c-9476-57863df9010e
#[derive(Debug, PartialEq, Clone)]
pub struct WriteCacheCommon {
    pub context: ScardContext,
    pub card_uuid: Vec<u8>,
    pub freshness_counter: u32,
    pub data: Vec<u8>,
}

impl ndr::Decode for WriteCacheCommon {
    fn decode_ptr(src: &mut ReadCursor<'_>, index: &mut u32) -> DecodeResult<Self>
    where
        Self: Sized,
    {
        let context = ScardContext::decode_ptr(src, index)?;
        let _card_uuid_ptr = ndr::decode_ptr(src, index)?;
        ensure_size!(in: src, size: size_of::<u32>() * 2);
        let freshness_counter = src.read_u32();
        let _data_len = src.read_u32();
        let _data_ptr = ndr::decode_ptr(src, index)?;

        Ok(Self {
            context,
            card_uuid: Vec::new(),
            freshness_counter,
            data: Vec::new(),
        })
    }

    fn decode_value(&mut self, src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<()> {
        expect_no_charset(charset)?;
        self.context.decode_value(src, None)?;
        ensure_size!(in: src, size: 16);
        self.card_uuid = src.read_slice(16).to_vec();
        ensure_size!(in: src, size: size_of::<u32>());
        let data_len: usize = cast_length!("WriteCacheCommon", "data_len", src.read_u32())?;
        ensure_size!(in: src, size: data_len);
        self.data = src.read_slice(data_len).to_vec();
        Ok(())
    }
}

/// [2.2.2.31] GetReaderIcon_Call
///
/// [2.2.2.31]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/e6a68d90-697f-4b98-8ad6-f74853d27ccb
#[derive(Debug, PartialEq, Clone)]
pub struct GetReaderIconCall {
    pub context: ScardContext,
    pub reader_name: String,
}

impl GetReaderIconCall {
    pub fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        Ok(rpce::Pdu::<Self>::decode(src, None)?.into_inner())
    }
}

impl rpce::HeaderlessDecode for GetReaderIconCall {
    fn decode(src: &mut ReadCursor<'_>, charset: Option<CharacterSet>) -> DecodeResult<Self> {
        expect_no_charset(charset)?;
        let mut index = 0;
        let mut context = ScardContext::decode_ptr(src, &mut index)?;

        let _reader_ptr = ndr::decode_ptr(src, &mut index)?;

        context.decode_value(src, None)?;
        let reader_name = ndr::read_string_from_cursor(src, CharacterSet::Unicode)?;
        Ok(Self { context, reader_name })
    }
}

/// [2.2.3.14] GetReaderIcon_Return
///
/// [2.2.3.14]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpesc/f011f3d9-e2a4-4c43-a336-4c89ecaa8360
#[derive(Debug, PartialEq, Clone)]
pub struct GetReaderIconReturn {
    pub return_code: ReturnCode,
    pub data: Vec<u8>,
}

impl GetReaderIconReturn {
    const NAME: &'static str = "GetReaderIcon_Return";

    pub fn new(return_code: ReturnCode, data: Vec<u8>) -> rpce::Pdu<Self> {
        rpce::Pdu(Self { return_code, data })
    }
}

impl rpce::HeaderlessEncode for GetReaderIconReturn {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());
        dst.write_u32(self.return_code.into());
        let data_len: u32 = cast_length!("GetReaderIconReturn", "data_len", self.data.len())?;
        let mut index = 0;
        ndr::encode_ptr(Some(data_len), &mut index, dst)?;
        dst.write_u32(data_len);
        dst.write_slice(&self.data);
        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        size_of::<u32>() // dst.write_u32(self.return_code.into());
        + ndr::ptr_size(true) // ndr::encode_ptr(Some(data_len), &mut index, dst)?;
        + size_of::<u32>() // dst.write_u32(data_len);
        + self.data.len() // dst.write_slice(&self.data);
    }
}

fn expect_charset(charset: Option<CharacterSet>) -> DecodeResult<CharacterSet> {
    if charset.is_none() {
        return Err(other_err!("internal error: missing character set"));
    }
    Ok(charset.unwrap())
}

fn expect_no_charset(charset: Option<CharacterSet>) -> DecodeResult<()> {
    if charset.is_some() {
        return Err(other_err!(
            "internal error: character set given where none was expected"
        ));
    }
    Ok(())
}