libdvb 0.5.0

Interface for DVB-API v5 devices in Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
//! en50221 7.2: session layer
//!
//! The session layer multiplexes sessions between module applications
//! and host resources on top of the transport layer. The module opens
//! sessions to host resources; the host allocates session numbers,
//! dispatches incoming APDUs to the resources and reports the activity
//! as [`CaEvent`].

use std::{
    collections::VecDeque,
    os::{
        fd::{
            AsFd,
            BorrowedFd,
        },
        unix::io::{
            AsRawFd,
            RawFd,
        },
    },
    time::Instant,
};

use super::{
    apdu,
    apdu::ApduTag,
    capmt::Program,
    controller::{
        CaSlotFailure,
        CaSlotStatus,
        CamStatus,
    },
    resource::{
        ApplicationInfo,
        MmiMenu,
        ResourceContext,
        ResourceId,
        ResourceRegistry,
        mmi,
    },
    spdu,
    spdu::Spdu,
    transport::{
        CiTransport,
        TransportRecv,
    },
};
use crate::error::{
    Error,
    Result,
};

/// Highest number of concurrent sessions per slot
const MAX_SLOT_SESSIONS: usize = 16;

/// DVB-CI activity delivered by [`CiSession::next_event`] or
/// [`super::CiController::poll_event`]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CaEvent {
    /// The high-level controller changed the physical/transport state
    /// of a slot
    SlotStatusChanged {
        slot_id: u8,
        old: CaSlotStatus,
        new: CaSlotStatus,
    },
    /// The high-level controller advanced or cleared the confirmed CAM
    /// application state
    CamStatusChanged {
        slot_id: u8,
        old: CamStatus,
        new: CamStatus,
    },
    /// The high-level controller abandoned the current transport
    /// connection and scheduled recovery
    SlotFailed { slot_id: u8, reason: CaSlotFailure },
    /// TT_CTC_REPLY: the transport connection is established and the
    /// module is about to open sessions
    TransportReady { slot_id: u8 },
    /// A frame or an object attributable to a slot failed the
    /// validation; the data is dropped but the slot keeps going
    Malformed { slot_id: u8, context: String },
    /// The module opened a session to a host resource
    SessionOpened {
        slot_id: u8,
        session_id: u16,
        resource_id: ResourceId,
    },
    /// The module requested a session the host refused; `status` is the
    /// en50221 Table 7 value: 0xF0 - the resource does not exist,
    /// 0xF2 - only a lower version is available, 0xF3 - no free
    /// session numbers
    SessionRefused {
        slot_id: u8,
        resource_id: ResourceId,
        status: u8,
    },
    /// The session is gone: module close request, host close completion
    /// or slot drop
    SessionClosed {
        slot_id: u8,
        session_id: u16,
        resource_id: ResourceId,
    },
    /// application_info: the module identified itself
    ApplicationInfo { slot_id: u8, info: ApplicationInfo },
    /// ca_info: one Conditional Access application reported the CA
    /// systems it supports
    CaInfo {
        slot_id: u8,
        session_id: u16,
        /// CA_system_id values in the order supplied by the module
        caids: Vec<u16>,
    },
    /// close_mmi: the module asks to close the dialogue; `delay` is the
    /// close delay in seconds when the module asked for a deferred close
    MmiClose {
        slot_id: u8,
        session_id: u16,
        delay: Option<u8>,
    },
    /// text_last: a standalone text object to display
    MmiText {
        slot_id: u8,
        session_id: u16,
        text: Vec<u8>,
    },
    /// menu_last: a menu to display; the selection is answered with
    /// [`CiSession::mmi_menu_answer`]
    MmiMenu {
        slot_id: u8,
        session_id: u16,
        menu: MmiMenu,
    },
    /// list_last: a list to display; when the user finishes viewing it,
    /// acknowledge it with [`CiSession::mmi_list_close`]
    MmiList {
        slot_id: u8,
        session_id: u16,
        menu: MmiMenu,
    },
    /// enq: the module asks the user for a text answer (a PIN code
    /// usually), answered with [`CiSession::mmi_answer`]
    MmiEnq {
        slot_id: u8,
        session_id: u16,
        /// mask the user input
        blind: bool,
        /// expected answer length
        answer_len: u8,
        /// prompt in DVB charset coding (EN 300 468 annex A)
        text: Vec<u8>,
    },
    /// tune: the module asks the host to tune to the service
    Tune {
        slot_id: u8,
        network_id: u16,
        original_network_id: u16,
        transport_stream_id: u16,
        service_id: u16,
    },
    /// replace: the module asks to substitute a PID in the stream
    /// passed through it
    Replace {
        slot_id: u8,
        replace_ref: u8,
        replaced_pid: u16,
        replacement_pid: u16,
    },
    /// clear_replace: the module withdraws a replace request
    ClearReplace { slot_id: u8, replace_ref: u8 },
}

/// State of one open session
enum SessionState {
    Active,
    /// the host sent close_session_request and waits for the response
    Closing,
}

struct Session {
    slot_id: u8,
    resource_id: ResourceId,
    state: SessionState,
}

/// en50221 7.2 session layer on top of a [`CiTransport`]
///
/// The layer is driven from the outside: [`CiSession::recv`] consumes
/// one link frame, [`CiSession::tick`] runs the time-based work of the
/// resources (periodic date_time updates), [`CiSession::next_event`]
/// drains the queued activity.
///
/// ```no_run
/// use libdvb::ca::{CaDevice, CiSession, CiTransport};
///
/// fn main() -> libdvb::error::Result<()> {
///     let device = CaDevice::open(0, 0)?;
///     let slots_num = device.caps()?.slot_num as u8;
///     let mut session = CiSession::new(CiTransport::new(device, slots_num));
///
///     // on every read event of the device descriptor:
///     while session.recv()? {}
///     while let Some(event) = session.next_event() {
///         println!("{:?}", event);
///     }
///     // and periodically:
///     session.tick()?;
///
///     Ok(())
/// }
/// ```
pub struct CiSession {
    transport: CiTransport,
    resources: ResourceRegistry,
    /// session state indexed by session number - 1
    sessions: Vec<Option<Session>>,
    events: VecDeque<CaEvent>,
}

impl AsRawFd for CiSession {
    fn as_raw_fd(&self) -> RawFd {
        self.transport.as_raw_fd()
    }
}

impl AsFd for CiSession {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.transport.as_fd()
    }
}

impl CiSession {
    /// Creates the session layer over the given transport
    pub fn new(transport: CiTransport) -> Self {
        CiSession {
            transport,
            resources: ResourceRegistry::new(),
            sessions: Vec::new(),
            events: VecDeque::new(),
        }
    }

    /// Returns a reference to the underlying transport
    pub fn transport(&self) -> &CiTransport {
        &self.transport
    }

    /// Returns a mutable reference to the underlying transport
    pub fn transport_mut(&mut self) -> &mut CiTransport {
        &mut self.transport
    }

    /// Takes the next queued event
    pub fn next_event(&mut self) -> Option<CaEvent> {
        self.events.pop_front()
    }

    /// Pulls one frame from the transport and advances the session
    /// state. Returns `Ok(false)` when the link has no data. Call
    /// [`CiSession::next_event`] to drain the produced events.
    pub fn recv(&mut self) -> Result<bool> {
        Ok(self.recv_filtered(|_| true)?.is_some())
    }

    /// Controller-aware receive path. The controller rejects SPDUs from
    /// slots without an active transport connection while still consuming
    /// and acknowledging the link frame.
    pub(crate) fn recv_controller(&mut self, active_slots: &[bool]) -> Result<Option<u8>> {
        self.recv_filtered(|slot_id| {
            active_slots
                .get(usize::from(slot_id))
                .copied()
                .unwrap_or(false)
        })
    }

    fn recv_filtered(&mut self, accept_spdu: impl FnOnce(u8) -> bool) -> Result<Option<u8>> {
        let recv = match self.transport.recv_apdu()? {
            Some(recv) => recv,
            None => return Ok(None),
        };
        let slot_id = recv.slot_id();

        match recv {
            TransportRecv::TcReply { slot_id } => {
                self.events.push_back(CaEvent::TransportReady { slot_id });
            }
            TransportRecv::Spdu { slot_id, spdu } if accept_spdu(slot_id) => {
                self.dispatch_spdu(slot_id, &spdu)?
            }
            TransportRecv::Spdu { slot_id, .. } => {
                self.events.push_back(CaEvent::Malformed {
                    slot_id,
                    context: format!(
                        "ca slot {}: session data before the transport connection is active",
                        slot_id
                    ),
                });
            }
            TransportRecv::Status { .. } => {}
            TransportRecv::Malformed { slot_id, context } => {
                self.events
                    .push_back(CaEvent::Malformed { slot_id, context });
            }
        }

        // the read event allows the next queued frame out
        self.transport.flush(slot_id)?;

        Ok(Some(slot_id))
    }

    /// Runs the time-based work of the resources: periodic date_time
    /// updates. Call once a second or so.
    pub fn tick(&mut self) -> Result<()> {
        self.tick_at(Instant::now())
    }

    /// Runs resource timers against an explicit monotonic instant. This is
    /// used by [`super::CiController::tick`] and is useful to event loops
    /// which already own their notion of time.
    pub fn tick_at(&mut self, now: Instant) -> Result<()> {
        self.resources.tick(&mut self.transport, now)
    }

    /// Closes all sessions of the slot and clears its transport state;
    /// for the slot manager to call when the module is gone or the
    /// transport connection is reset
    pub fn drop_slot(&mut self, slot_id: u8) {
        self.transport.clear_slot(slot_id);

        for index in 0 .. self.sessions.len() {
            let matches = self.sessions[index]
                .as_ref()
                .is_some_and(|session| session.slot_id == slot_id);
            if matches {
                self.free_session((index + 1) as u16);
            }
        }
    }

    /// Last application info received from the module in the slot
    pub fn app_info(&self, slot_id: u8) -> Option<&ApplicationInfo> {
        self.resources.application_info.info(slot_id)
    }

    /// Sorted, deduplicated union of CAIDs reported by all live
    /// Conditional Access Support sessions in the slot
    pub fn caids(&self, slot_id: u8) -> Vec<u16> {
        let mut caids = Vec::new();
        for (index, session) in self.sessions.iter().enumerate() {
            let Some(session) = session else {
                continue;
            };
            if session.slot_id != slot_id
                || session.resource_id.base() != ResourceId::CONDITIONAL_ACCESS_SUPPORT.base()
                || !matches!(session.state, SessionState::Active)
            {
                continue;
            }

            if let Some(session_caids) = self
                .resources
                .conditional_access
                .session_caids(slot_id, (index + 1) as u16)
            {
                caids.extend_from_slice(session_caids);
            }
        }
        caids.sort_unstable();
        caids.dedup();
        caids
    }

    /// CAIDs reported by one live Conditional Access Support session
    ///
    /// `None` means the session is unknown, belongs to another slot, or
    /// has not replied with CA_INFO yet. A confirmed empty CA_INFO is
    /// returned as `Some(&[])`.
    pub fn session_caids(&self, slot_id: u8, session_id: u16) -> Option<&[u16]> {
        let session = self.session(session_id)?;
        if session.slot_id != slot_id
            || session.resource_id.base() != ResourceId::CONDITIONAL_ACCESS_SUPPORT.base()
            || !matches!(session.state, SessionState::Active)
        {
            return None;
        }

        self.resources
            .conditional_access
            .session_caids(slot_id, session_id)
    }

    pub(super) fn set_program(&mut self, program: Program) -> Result<Vec<u8>> {
        self.resources
            .conditional_access
            .set_program(&mut self.transport, program)
    }

    pub(super) fn remove_program(&mut self, program_number: u16) -> Result<Vec<u8>> {
        self.resources
            .conditional_access
            .remove_program(&mut self.transport, program_number)
    }

    pub(crate) fn has_ca_info(&self, slot_id: u8) -> bool {
        self.sessions.iter().enumerate().any(|(index, session)| {
            session.as_ref().is_some_and(|session| {
                session.slot_id == slot_id
                    && session.resource_id.base() == ResourceId::CONDITIONAL_ACCESS_SUPPORT.base()
                    && matches!(session.state, SessionState::Active)
                    && self
                        .resources
                        .conditional_access
                        .session_caids(slot_id, (index + 1) as u16)
                        .is_some()
            })
        })
    }

    /// Asks the module to show its menu (enter_menu on the application
    /// information session)
    pub fn enter_menu(&mut self, slot_id: u8) -> Result<()> {
        let confirmed_session = self
            .resources
            .application_info
            .info_session(slot_id)
            .map(|(session_id, _)| session_id)
            .filter(|&session_id| {
                matches!(
                    self.session(session_id),
                    Some(session)
                        if session.slot_id == slot_id
                            && session.resource_id.base()
                                == ResourceId::APPLICATION_INFORMATION.base()
                            && matches!(session.state, SessionState::Active)
                )
            });
        let session_id = match confirmed_session {
            Some(session_id) => session_id,
            None => self.find_session(slot_id, ResourceId::APPLICATION_INFORMATION)?,
        };
        self.transport
            .send_apdu(slot_id, session_id, ApduTag::ENTER_MENU, &[])
    }

    /// Answers a [`CaEvent::MmiMenu`] selection on the exact MMI session
    /// with the 1-based item number; 0 cancels the menu
    pub fn mmi_menu_answer(&mut self, slot_id: u8, session_id: u16, choice: u8) -> Result<()> {
        self.require_session(slot_id, session_id, ResourceId::MMI)?;
        self.transport
            .send_apdu(slot_id, session_id, ApduTag::MENU_ANSW, &[choice])
    }

    /// Finishes viewing a [`CaEvent::MmiList`] by sending menu_answ with
    /// choice_ref 0 on the exact MMI session
    pub fn mmi_list_close(&mut self, slot_id: u8, session_id: u16) -> Result<()> {
        self.mmi_menu_answer(slot_id, session_id, 0)
    }

    /// Answers a [`CaEvent::MmiEnq`] enquiry on the exact MMI session;
    /// `None` cancels the enquiry
    pub fn mmi_answer(
        &mut self,
        slot_id: u8,
        session_id: u16,
        answer: Option<&[u8]>,
    ) -> Result<()> {
        self.require_session(slot_id, session_id, ResourceId::MMI)?;
        self.transport
            .send_apdu(slot_id, session_id, ApduTag::ANSW, &mmi::build_answ(answer))
    }

    /// Asks the module to close the dialogue on the exact MMI session;
    /// the module closes the session in response
    pub fn mmi_close(&mut self, slot_id: u8, session_id: u16) -> Result<()> {
        self.require_session(slot_id, session_id, ResourceId::MMI)?;
        self.transport
            .send_apdu(slot_id, session_id, ApduTag::CLOSE_MMI, &mmi::build_close())
    }

    /// Asks the module to release the host control resource
    pub fn ask_release(&mut self, slot_id: u8) -> Result<()> {
        let session_id = self.find_session(slot_id, ResourceId::HOST_CONTROL)?;
        self.transport
            .send_apdu(slot_id, session_id, ApduTag::ASK_RELEASE, &[])
    }

    fn session(&self, session_id: u16) -> Option<&Session> {
        let index = usize::from(session_id.checked_sub(1)?);
        self.sessions.get(index)?.as_ref()
    }

    /// Requires one exact active session of the slot connected to the resource.
    fn require_session(&self, slot_id: u8, session_id: u16, resource_id: ResourceId) -> Result<()> {
        if matches!(
            self.session(session_id),
            Some(session)
                if session.slot_id == slot_id
                    && session.resource_id.base() == resource_id.base()
                    && matches!(session.state, SessionState::Active)
        ) {
            return Ok(());
        }

        Err(Error::InvalidProperty(format!(
            "ca slot {}: no active {:?} session {}",
            slot_id, resource_id, session_id
        )))
    }

    /// First active session of the slot connected to the resource
    fn find_session(&self, slot_id: u8, resource_id: ResourceId) -> Result<u16> {
        for (index, entry) in self.sessions.iter().enumerate() {
            if let Some(session) = entry
                && session.slot_id == slot_id
                && session.resource_id.base() == resource_id.base()
                && matches!(session.state, SessionState::Active)
            {
                return Ok((index + 1) as u16);
            }
        }

        Err(Error::InvalidProperty(format!(
            "ca slot {}: no open {:?} session",
            slot_id, resource_id
        )))
    }

    fn alloc_session(&mut self, slot_id: u8, resource_id: ResourceId) -> Option<u16> {
        // the pool is per slot: one module cannot starve the others
        let in_use = self
            .sessions
            .iter()
            .flatten()
            .filter(|session| session.slot_id == slot_id)
            .count();
        if in_use >= MAX_SLOT_SESSIONS {
            return None;
        }

        let index = match self.sessions.iter().position(Option::is_none) {
            Some(index) => index,
            None => {
                self.sessions.push(None);
                self.sessions.len() - 1
            }
        };

        self.sessions[index] = Some(Session {
            slot_id,
            resource_id,
            state: SessionState::Active,
        });

        Some((index + 1) as u16)
    }

    /// Frees the session and runs the resource close callback
    fn free_session(&mut self, session_id: u16) {
        let Some(index) = session_id.checked_sub(1) else {
            return;
        };
        let Some(session) = self
            .sessions
            .get_mut(usize::from(index))
            .and_then(Option::take)
        else {
            return;
        };

        if let Some(resource) = self.resources.lookup(session.resource_id) {
            resource.on_close(session.slot_id, session_id);
        }

        self.events.push_back(CaEvent::SessionClosed {
            slot_id: session.slot_id,
            session_id,
            resource_id: session.resource_id,
        });
    }

    fn dispatch_spdu(&mut self, slot_id: u8, data: &[u8]) -> Result<()> {
        let spdu = match spdu::parse(data) {
            Ok(spdu) => spdu,
            Err(Error::InvalidData(context)) => {
                self.events
                    .push_back(CaEvent::Malformed { slot_id, context });
                return Ok(());
            }
            Err(e) => return Err(e),
        };

        match spdu {
            Spdu::SessionNumber { session_id, apdu } => {
                self.dispatch_apdu(slot_id, session_id, apdu)
            }
            Spdu::OpenSessionRequest { resource_id } => self.open_session(slot_id, resource_id),
            Spdu::CloseSessionRequest { session_id } => self.close_session(slot_id, session_id),
            Spdu::CloseSessionResponse { status, session_id } => {
                self.close_session_complete(slot_id, session_id, status);
                Ok(())
            }
            Spdu::CreateSessionResponse { .. } => {
                // the host never sends create_session
                self.events.push_back(CaEvent::Malformed {
                    slot_id,
                    context: format!("ca slot {}: unexpected create_session_response", slot_id),
                });
                Ok(())
            }
        }
    }

    /// Handles open_session_request: allocates a session, replies and
    /// runs the resource open callback
    fn open_session(&mut self, slot_id: u8, resource_id: ResourceId) -> Result<()> {
        let available_resource_id = self
            .resources
            .lookup(resource_id)
            .map(|resource| resource.resource_id());
        let response_resource_id = available_resource_id.unwrap_or(resource_id);
        let mut session_id = 0;
        let status = match available_resource_id {
            None => spdu::SS_NOT_ALLOCATED,
            Some(available) if resource_id.version() > available.version() => {
                spdu::SS_LOWER_VERSION
            }
            Some(available) => match self.alloc_session(slot_id, available) {
                Some(allocated) => {
                    session_id = allocated;
                    spdu::SS_OK
                }
                None => spdu::SS_BUSY,
            },
        };

        let response = spdu::build_open_session_response(status, response_resource_id, session_id);
        self.transport.send_spdu(slot_id, &response)?;

        if status != spdu::SS_OK {
            self.events.push_back(CaEvent::SessionRefused {
                slot_id,
                resource_id,
                status,
            });
            return Ok(());
        }

        self.events.push_back(CaEvent::SessionOpened {
            slot_id,
            session_id,
            resource_id: response_resource_id,
        });

        let resource = self
            .resources
            .lookup(response_resource_id)
            .expect("the resource is present: the session was allocated");
        let mut ctx = ResourceContext {
            transport: &mut self.transport,
            events: &mut self.events,
            slot_id,
            session_id,
            close_session: false,
        };

        let result = resource.on_open(&mut ctx);
        Self::resource_result(&mut self.events, slot_id, result)
    }

    /// Dispatches the APDUs of a session_number SPDU to the resource
    /// bound to the session
    fn dispatch_apdu(&mut self, slot_id: u8, session_id: u16, data: &[u8]) -> Result<()> {
        let resource_id = match self.session(session_id) {
            Some(session) if session.slot_id == slot_id => session.resource_id,
            _ => {
                self.events.push_back(CaEvent::Malformed {
                    slot_id,
                    context: format!(
                        "ca slot {}: apdu on unknown session {}",
                        slot_id, session_id
                    ),
                });
                return Ok(());
            }
        };

        let resource = self
            .resources
            .lookup(resource_id)
            .expect("the resource is present: the session was allocated");

        let mut close_session = false;
        for item in apdu::iter(data) {
            match item {
                Ok(item) => {
                    let mut ctx = ResourceContext {
                        transport: &mut self.transport,
                        events: &mut self.events,
                        slot_id,
                        session_id,
                        close_session: false,
                    };

                    let result = resource.on_apdu(&mut ctx, item.tag, item.body);
                    close_session |= ctx.close_session;
                    Self::resource_result(&mut self.events, slot_id, result)?;
                }
                Err(Error::InvalidData(context)) => {
                    self.events
                        .push_back(CaEvent::Malformed { slot_id, context });
                    break;
                }
                Err(e) => return Err(e),
            }
        }

        if close_session {
            self.request_close(slot_id, session_id)?;
        }

        Ok(())
    }

    /// Turns a resource-level data error into a Malformed event; the
    /// slot keeps going
    fn resource_result(
        events: &mut VecDeque<CaEvent>,
        slot_id: u8,
        result: Result<()>,
    ) -> Result<()> {
        match result {
            Err(Error::InvalidData(context)) => {
                events.push_back(CaEvent::Malformed { slot_id, context });
                Ok(())
            }
            result => result,
        }
    }

    /// Starts a host-initiated session close; a second request for a
    /// session already closing is not sent
    fn request_close(&mut self, slot_id: u8, session_id: u16) -> Result<()> {
        let Some(index) = session_id.checked_sub(1).map(usize::from) else {
            return Ok(());
        };
        match self.sessions.get_mut(index) {
            Some(Some(session))
                if session.slot_id == slot_id && matches!(session.state, SessionState::Active) =>
            {
                session.state = SessionState::Closing;
            }
            _ => return Ok(()),
        }

        let request = spdu::build_close_session_request(session_id);
        self.transport.send_spdu(slot_id, &request)
    }

    /// Handles close_session_request from the module
    fn close_session(&mut self, slot_id: u8, session_id: u16) -> Result<()> {
        let known = matches!(
            self.session(session_id),
            Some(session) if session.slot_id == slot_id
        );
        let status = if known {
            spdu::SS_OK
        } else {
            spdu::SS_NOT_ALLOCATED
        };

        let response = spdu::build_close_session_response(status, session_id);
        self.transport.send_spdu(slot_id, &response)?;

        if known {
            self.free_session(session_id);
        } else {
            self.events.push_back(CaEvent::Malformed {
                slot_id,
                context: format!(
                    "ca slot {}: close request for unknown session {}",
                    slot_id, session_id
                ),
            });
        }

        Ok(())
    }

    /// Handles close_session_response completing a host-initiated close
    fn close_session_complete(&mut self, slot_id: u8, session_id: u16, status: u8) {
        let closing = matches!(
            self.session(session_id),
            Some(session) if session.slot_id == slot_id
                && matches!(session.state, SessionState::Closing)
        );

        if !closing {
            self.events.push_back(CaEvent::Malformed {
                slot_id,
                context: format!(
                    "ca slot {}: unexpected close response for session {}",
                    slot_id, session_id
                ),
            });
            return;
        }

        match status {
            // SS_NOT_ALLOCATED also means that the peer has no session to
            // communicate on, so the local half must be released.
            spdu::SS_OK | spdu::SS_NOT_ALLOCATED => self.free_session(session_id),
            status => {
                if let Some(Some(session)) = self.sessions.get_mut(usize::from(session_id - 1)) {
                    session.state = SessionState::Active;
                }
                self.events.push_back(CaEvent::Malformed {
                    slot_id,
                    context: format!(
                        "ca slot {}: invalid close response status 0x{:02X} for session {}",
                        slot_id, status, session_id
                    ),
                });
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs::File,
        io::{
            ErrorKind,
            Read,
            Write,
        },
        os::{
            fd::OwnedFd,
            unix::net::UnixDatagram,
        },
        time::Duration,
    };

    use super::{
        super::{
            CaDevice,
            asn1,
            tpdu::TpduTag,
        },
        *,
    };

    /// The module side of a socketpair link: SOCK_DGRAM is available on
    /// Linux and macOS and keeps message boundaries like the kernel CA
    /// device does
    struct TestCam {
        file: File,
    }

    fn pair_slots(slots_num: u8) -> (CiSession, TestCam) {
        let (host, cam) = UnixDatagram::pair().unwrap();
        host.set_nonblocking(true).unwrap();
        cam.set_nonblocking(true).unwrap();

        let host = File::from(OwnedFd::from(host));
        let cam = File::from(OwnedFd::from(cam));

        let session = CiSession::new(CiTransport::new(CaDevice::from_file(host), slots_num));

        (session, TestCam { file: cam })
    }

    fn pair() -> (CiSession, TestCam) {
        pair_slots(1)
    }

    impl TestCam {
        /// Wraps the payload into an R_TPDU with a clean status trailer
        /// and writes it to the link
        fn send_slot(&mut self, slot_id: u8, tag: TpduTag, payload: &[u8]) {
            let t_c_id = slot_id + 1;
            let mut frame = vec![slot_id, t_c_id];

            match tag {
                TpduTag::SB => {}
                TpduTag::CTC_REPLY => frame.extend_from_slice(&[tag.raw(), 0x01, t_c_id]),
                TpduTag::DATA_LAST | TpduTag::DATA_MORE => {
                    frame.push(tag.raw());
                    asn1::encode(payload.len() as u16 + 1, &mut frame);
                    frame.push(t_c_id);
                    frame.extend_from_slice(payload);
                }
                tag => panic!("unsupported test tag {:?}", tag),
            }

            frame.extend_from_slice(&[TpduTag::SB.raw(), 0x02, t_c_id, 0x00]);
            self.file.write_all(&frame).unwrap();
        }

        fn send(&mut self, tag: TpduTag, payload: &[u8]) {
            self.send_slot(0, tag, payload);
        }

        /// Sends an SPDU wrapped into a data R_TPDU on slot 0
        fn send_spdu(&mut self, spdu: &[u8]) {
            self.send(TpduTag::DATA_LAST, spdu);
        }

        /// Sends an APDU on the session wrapped into a data R_TPDU on
        /// slot 0
        fn send_apdu(&mut self, session_id: u16, tag: ApduTag, body: &[u8]) {
            self.send_apdu_slot(0, session_id, tag, body);
        }

        fn send_apdu_slot(&mut self, slot_id: u8, session_id: u16, tag: ApduTag, body: &[u8]) {
            let mut payload = spdu::build_session_number(session_id);
            apdu::build(&mut payload, tag, body);
            self.send_slot(slot_id, TpduTag::DATA_LAST, &payload);
        }

        /// Reads one C_TPDU frame from the link
        fn recv(&mut self) -> Option<Vec<u8>> {
            let mut buf = [0; 2048];
            match self.file.read(&mut buf) {
                Ok(len) => Some(buf[.. len].to_vec()),
                Err(e) if e.kind() == ErrorKind::WouldBlock => None,
                Err(e) => panic!("cam link read: {}", e),
            }
        }

        /// Extracts the SPDU payload from a host data C_TPDU
        fn unwrap_data_slot(frame: &[u8], slot_id: u8) -> Vec<u8> {
            let t_c_id = slot_id + 1;
            assert_eq!(&frame[.. 2], &[slot_id, t_c_id], "slot and t_c_id");
            assert_eq!(frame[2], TpduTag::DATA_LAST.raw(), "data frame tag");
            let (length, consumed) = asn1::decode(&frame[3 ..]).unwrap();
            assert_eq!(frame[3 + consumed], t_c_id, "t_c_id byte");
            let start = 3 + consumed + 1;
            assert_eq!(frame.len(), start + usize::from(length) - 1);

            frame[start ..].to_vec()
        }
    }

    /// Runs the host receive loop against the module side. Every frame
    /// the module reads is acknowledged with a status R_TPDU so the
    /// host flushes the next queued frame; returns the SPDU payloads
    /// the host sent. All frames must arrive on the given slot.
    fn pump_slot(session: &mut CiSession, cam: &mut TestCam, slot_id: u8) -> Vec<Vec<u8>> {
        let mut spdus = Vec::new();

        loop {
            while session.recv().unwrap() {}
            match cam.recv() {
                Some(frame) => {
                    spdus.push(TestCam::unwrap_data_slot(&frame, slot_id));
                    // en50221 7.1: the host must not send the next frame
                    // before the module responds to the previous one
                    assert!(
                        cam.recv().is_none(),
                        "two outstanding frames on slot {}",
                        slot_id
                    );
                    cam.send_slot(slot_id, TpduTag::SB, &[]);
                }
                None => break,
            }
        }

        spdus
    }

    fn pump(session: &mut CiSession, cam: &mut TestCam) -> Vec<Vec<u8>> {
        pump_slot(session, cam, 0)
    }

    fn events(session: &mut CiSession) -> Vec<CaEvent> {
        let mut events = Vec::new();
        while let Some(event) = session.next_event() {
            events.push(event);
        }
        events
    }

    fn open_session_request(resource_id: ResourceId) -> Vec<u8> {
        let raw = resource_id.raw();
        vec![
            0x91,
            0x04,
            (raw >> 24) as u8,
            (raw >> 16) as u8,
            (raw >> 8) as u8,
            raw as u8,
        ]
    }

    /// Opens a session to the resource consuming the handshake frames;
    /// returns the allocated session id
    fn open_session(session: &mut CiSession, cam: &mut TestCam, resource_id: ResourceId) -> u16 {
        open_session_slot(session, cam, 0, resource_id)
    }

    fn open_session_slot(
        session: &mut CiSession,
        cam: &mut TestCam,
        slot_id: u8,
        resource_id: ResourceId,
    ) -> u16 {
        if slot_id == 0 {
            cam.send_spdu(&open_session_request(resource_id));
        } else {
            cam.send_slot(
                slot_id,
                TpduTag::DATA_LAST,
                &open_session_request(resource_id),
            );
        }
        pump_slot(session, cam, slot_id);

        match events(session).first() {
            Some(&CaEvent::SessionOpened {
                slot_id: event_slot,
                session_id,
                ..
            }) if event_slot == slot_id => session_id,
            event => panic!("expected SessionOpened, got {:?}", event),
        }
    }

    #[test]
    fn test_transport_ready() {
        let (mut session, mut cam) = pair();

        cam.send(TpduTag::CTC_REPLY, &[]);
        assert!(session.recv().unwrap());
        assert_eq!(
            session.next_event(),
            Some(CaEvent::TransportReady { slot_id: 0 })
        );
    }

    #[test]
    fn test_rm_handshake() {
        let (mut session, mut cam) = pair();

        // the module opens a session to the resource manager
        cam.send_spdu(&open_session_request(ResourceId::RESOURCE_MANAGER));
        let spdus = pump(&mut session, &mut cam);

        // open_session_response (ok, session 1), then profile_enq
        assert_eq!(spdus.len(), 2);
        assert_eq!(
            spdus[0],
            vec![0x92, 0x07, 0x00, 0x00, 0x01, 0x00, 0x41, 0x00, 0x01]
        );
        assert_eq!(
            spdus[1],
            vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x10, 0x00]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionOpened {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::RESOURCE_MANAGER,
            }]
        );

        // empty module profile: the host replies profile_change
        cam.send_apdu(1, ApduTag::PROFILE, &[]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x12, 0x00]]
        );

        // profile_enq: the host replies profile with its resource list
        cam.send_apdu(1, ApduTag::PROFILE_ENQ, &[]);
        let spdus = pump(&mut session, &mut cam);
        let mut expected = vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x11, 24];
        expected.extend_from_slice(&[
            0x00, 0x01, 0x00, 0x41, // Resource Manager
            0x00, 0x02, 0x00, 0x41, // Application Information
            0x00, 0x03, 0x00, 0x41, // Conditional Access Support
            0x00, 0x20, 0x00, 0x41, // Host Control
            0x00, 0x24, 0x00, 0x41, // Date-Time
            0x00, 0x40, 0x00, 0x41, // MMI
        ]);
        assert_eq!(spdus, vec![expected]);
        assert!(events(&mut session).is_empty());
    }

    #[test]
    fn test_open_session_refused() {
        let (mut session, mut cam) = pair();

        // an unknown resource class
        let unknown = ResourceId::new(0x00FF_0041);
        cam.send_spdu(&open_session_request(unknown));
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x92, 0x07, 0xF0, 0x00, 0xFF, 0x00, 0x41, 0x00, 0x00]]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionRefused {
                slot_id: 0,
                resource_id: unknown,
                status: 0xF0,
            }]
        );

        // a higher resource version than the host provides
        cam.send_spdu(&open_session_request(ResourceId::new(0x0003_0042)));
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x92, 0x07, 0xF2, 0x00, 0x03, 0x00, 0x41, 0x00, 0x00]]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionRefused {
                slot_id: 0,
                resource_id: ResourceId::new(0x0003_0042),
                status: 0xF2,
            }]
        );
    }

    #[test]
    fn test_open_lower_resource_version_uses_host_version() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&open_session_request(ResourceId::new(0x0003_0040)));
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![
                vec![0x92, 0x07, 0x00, 0x00, 0x03, 0x00, 0x41, 0x00, 0x01],
                vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x30, 0x00],
            ]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionOpened {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::CONDITIONAL_ACCESS_SUPPORT,
            }]
        );
    }

    #[test]
    fn test_session_exhaustion() {
        let (mut session, mut cam) = pair();

        for expected in 1 ..= 16 {
            assert_eq!(
                open_session(&mut session, &mut cam, ResourceId::HOST_CONTROL),
                expected
            );
        }

        // the 17th session on the slot is refused as busy
        cam.send_spdu(&open_session_request(ResourceId::HOST_CONTROL));
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x92, 0x07, 0xF3, 0x00, 0x20, 0x00, 0x41, 0x00, 0x00]]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionRefused {
                slot_id: 0,
                resource_id: ResourceId::HOST_CONTROL,
                status: 0xF3,
            }]
        );

        // closing one session makes room again
        cam.send_spdu(&[0x95, 0x02, 0x00, 0x05]);
        pump(&mut session, &mut cam);
        events(&mut session);
        assert_eq!(
            open_session(&mut session, &mut cam, ResourceId::HOST_CONTROL),
            5
        );
    }

    #[test]
    fn test_application_info() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&open_session_request(ResourceId::APPLICATION_INFORMATION));
        let spdus = pump(&mut session, &mut cam);
        // open_session_response, then application_info_enq
        assert_eq!(spdus.len(), 2);
        assert_eq!(
            spdus[1],
            vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x20, 0x00]
        );
        events(&mut session);

        let info_body = [
            0x01, 0x12, 0x34, 0x56, 0x78, 0x08, b'T', b'e', b's', b't', b' ', b'C', b'A', b'M',
        ];
        cam.send_apdu(1, ApduTag::APPLICATION_INFO, &info_body);
        pump(&mut session, &mut cam);

        let info = ApplicationInfo {
            application_type: 0x01,
            application_manufacturer: 0x1234,
            manufacturer_code: 0x5678,
            menu_string: b"Test CAM".to_vec(),
        };
        assert_eq!(
            events(&mut session),
            vec![CaEvent::ApplicationInfo {
                slot_id: 0,
                info: info.clone(),
            }]
        );
        assert_eq!(session.app_info(0), Some(&info));
        assert_eq!(session.app_info(1), None);

        // enter_menu goes out on the application information session
        session.enter_menu(0).unwrap();
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x22, 0x00]]
        );
    }

    #[test]
    fn test_application_info_survives_another_session_close() {
        let (mut session, mut cam) = pair();
        let first = open_session(&mut session, &mut cam, ResourceId::APPLICATION_INFORMATION);
        let second = open_session(&mut session, &mut cam, ResourceId::APPLICATION_INFORMATION);

        // The first session is still pending; the confirmed second session
        // supplies both app_info() and the target for enter_menu().
        cam.send_apdu(
            second,
            ApduTag::APPLICATION_INFO,
            &[0x01, 0, 2, 0, 2, 3, b'T', b'w', b'o'],
        );
        pump(&mut session, &mut cam);
        events(&mut session);
        assert_eq!(session.app_info(0).unwrap().menu_string, b"Two");
        session.enter_menu(0).unwrap();
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![0x90, 0x02, 0x00, 0x02, 0x9F, 0x80, 0x22, 0x00]]
        );

        // A later reply becomes the selected application.
        cam.send_apdu(
            first,
            ApduTag::APPLICATION_INFO,
            &[0x01, 0, 1, 0, 1, 3, b'O', b'n', b'e'],
        );
        pump(&mut session, &mut cam);
        events(&mut session);
        assert_eq!(session.app_info(0).unwrap().menu_string, b"One");
        session.enter_menu(0).unwrap();
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x22, 0x00]]
        );

        cam.send_spdu(&[0x95, 0x02, 0x00, first as u8]);
        pump(&mut session, &mut cam);
        events(&mut session);
        assert_eq!(session.app_info(0).unwrap().menu_string, b"Two");
    }

    #[test]
    fn test_conditional_access_info() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&open_session_request(
            ResourceId::CONDITIONAL_ACCESS_SUPPORT,
        ));
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![
                vec![0x92, 0x07, 0x00, 0x00, 0x03, 0x00, 0x41, 0x00, 0x01],
                vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x30, 0x00],
            ]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionOpened {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::CONDITIONAL_ACCESS_SUPPORT,
            }]
        );
        assert_eq!(session.session_caids(0, 1), None);
        assert!(session.caids(0).is_empty());

        // Session-level data preserves the module order and duplicates;
        // the slot aggregate is deterministic and deduplicated.
        cam.send_apdu(
            1,
            ApduTag::CA_INFO,
            &[0x05, 0x00, 0x01, 0x00, 0x05, 0x00, 0x0B, 0x00],
        );
        assert!(pump(&mut session, &mut cam).is_empty());
        assert_eq!(
            events(&mut session),
            vec![CaEvent::CaInfo {
                slot_id: 0,
                session_id: 1,
                caids: vec![0x0500, 0x0100, 0x0500, 0x0B00],
            }]
        );
        assert_eq!(
            session.session_caids(0, 1),
            Some([0x0500, 0x0100, 0x0500, 0x0B00].as_slice())
        );
        assert_eq!(session.caids(0), [0x0100, 0x0500, 0x0B00]);

        // A malformed replacement is reported but leaves the last valid
        // list intact.
        cam.send_apdu(1, ApduTag::CA_INFO, &[0x01, 0x00, 0xFF]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));
        assert_eq!(
            session.session_caids(0, 1),
            Some([0x0500, 0x0100, 0x0500, 0x0B00].as_slice())
        );

        // Empty CA_INFO is a valid confirmed replacement, not the same as
        // a missing reply.
        cam.send_apdu(1, ApduTag::CA_INFO, &[]);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::CaInfo {
                slot_id: 0,
                session_id: 1,
                caids: Vec::new(),
            }]
        );
        assert_eq!(session.session_caids(0, 1), Some([].as_slice()));

        cam.send_spdu(&[0x95, 0x02, 0x00, 0x01]);
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![0x96, 0x03, 0x00, 0x00, 0x01]]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionClosed {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::CONDITIONAL_ACCESS_SUPPORT,
            }]
        );
        assert_eq!(session.session_caids(0, 1), None);
        assert!(session.caids(0).is_empty());
    }

    #[test]
    fn test_conditional_access_sessions_are_independent() {
        let (mut session, mut cam) = pair();
        let first = open_session(
            &mut session,
            &mut cam,
            ResourceId::CONDITIONAL_ACCESS_SUPPORT,
        );
        let second = open_session(
            &mut session,
            &mut cam,
            ResourceId::CONDITIONAL_ACCESS_SUPPORT,
        );
        assert_eq!((first, second), (1, 2));

        cam.send_apdu(first, ApduTag::CA_INFO, &[0x05, 0x00, 0x01, 0x00]);
        cam.send_apdu(second, ApduTag::CA_INFO, &[0x06, 0x04, 0x05, 0x00]);
        pump(&mut session, &mut cam);
        events(&mut session);
        assert_eq!(
            session.session_caids(0, first),
            Some([0x0500, 0x0100].as_slice())
        );
        assert_eq!(
            session.session_caids(0, second),
            Some([0x0604, 0x0500].as_slice())
        );
        assert_eq!(session.caids(0), [0x0100, 0x0500, 0x0604]);

        cam.send_spdu(&[0x95, 0x02, 0x00, first as u8]);
        pump(&mut session, &mut cam);
        events(&mut session);
        assert_eq!(session.session_caids(0, first), None);
        assert_eq!(session.caids(0), [0x0500, 0x0604]);

        // Reusing the freed number starts without the old CA_INFO.
        let reused = open_session(
            &mut session,
            &mut cam,
            ResourceId::CONDITIONAL_ACCESS_SUPPORT,
        );
        assert_eq!(reused, first);
        assert_eq!(session.session_caids(0, reused), None);
        assert_eq!(session.caids(0), [0x0500, 0x0604]);
    }

    #[test]
    fn test_conditional_access_caids_do_not_cross_slots() {
        let (mut session, mut cam) = pair_slots(2);
        let first = open_session_slot(
            &mut session,
            &mut cam,
            0,
            ResourceId::CONDITIONAL_ACCESS_SUPPORT,
        );
        let second = open_session_slot(
            &mut session,
            &mut cam,
            1,
            ResourceId::CONDITIONAL_ACCESS_SUPPORT,
        );

        cam.send_apdu_slot(0, first, ApduTag::CA_INFO, &[0x01, 0x00]);
        pump_slot(&mut session, &mut cam, 0);
        cam.send_apdu_slot(1, second, ApduTag::CA_INFO, &[0x06, 0x04]);
        pump_slot(&mut session, &mut cam, 1);
        events(&mut session);

        assert_eq!(session.caids(0), [0x0100]);
        assert_eq!(session.caids(1), [0x0604]);
        assert_eq!(session.session_caids(0, second), None);
        assert_eq!(session.session_caids(1, first), None);

        session.drop_slot(0);
        events(&mut session);
        assert!(session.caids(0).is_empty());
        assert_eq!(session.caids(1), [0x0604]);
    }

    #[test]
    fn test_mmi_dialogue() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);
        assert_eq!(session_id, 1);

        // display_control set_mmi_mode high level -> display_reply ack
        cam.send_apdu(session_id, ApduTag::DISPLAY_CONTROL, &[0x01, 0x01]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![
                0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x02, 0x02, 0x01, 0x01
            ]]
        );

        // menu with two items
        let mut menu_body = vec![0x02];
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"Menu");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"Info");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"Exit");
        cam.send_apdu(session_id, ApduTag::MENU_LAST, &menu_body);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiMenu {
                slot_id: 0,
                session_id,
                menu: MmiMenu {
                    title: b"Menu".to_vec(),
                    sub_title: Vec::new(),
                    bottom: Vec::new(),
                    items: vec![b"Info".to_vec(), b"Exit".to_vec()],
                },
            }]
        );

        // the user picks the second item
        session.mmi_menu_answer(0, session_id, 2).unwrap();
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x0B, 0x01, 0x02]]
        );

        // a blind enquiry (PIN code)
        let mut enq_body = vec![0x01, 0x04];
        enq_body.extend_from_slice(b"PIN:");
        cam.send_apdu(session_id, ApduTag::ENQ, &enq_body);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiEnq {
                slot_id: 0,
                session_id,
                blind: true,
                answer_len: 4,
                text: b"PIN:".to_vec(),
            }]
        );

        session
            .mmi_answer(0, session_id, Some(b"1234"))
            .unwrap();
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![
                0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x08, 0x05, 0x01, b'1', b'2', b'3', b'4',
            ]]
        );

        // the module closes the dialogue: the host requests the session
        // close and completes it on the module response
        cam.send_apdu(session_id, ApduTag::CLOSE_MMI, &[0x00]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus, vec![vec![0x95, 0x02, 0x00, 0x01]]);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiClose {
                slot_id: 0,
                session_id,
                delay: None,
            }]
        );

        cam.send_spdu(&[0x96, 0x03, 0x00, 0x00, 0x01]);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionClosed {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::MMI,
            }]
        );

        // the session is gone
        assert!(session.mmi_menu_answer(0, session_id, 1).is_err());
    }

    #[test]
    fn test_mmi_commands_target_exact_session() {
        let (mut session, mut cam) = pair();
        let first = open_session(&mut session, &mut cam, ResourceId::MMI);
        let second = open_session(&mut session, &mut cam, ResourceId::MMI);

        session.mmi_menu_answer(0, second, 2).unwrap();
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![0x90, 0x02, 0x00, 0x02, 0x9F, 0x88, 0x0B, 0x01, 0x02]]
        );

        session.mmi_answer(0, first, Some(b"1")).unwrap();
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![
                0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x08, 0x02, 0x01, b'1',
            ]]
        );

        assert!(session.mmi_close(1, second).is_err());
        assert!(pump(&mut session, &mut cam).is_empty());
    }

    #[test]
    fn test_fragmented_spdu() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::APPLICATION_INFORMATION);

        // an application_info too large for one link frame arrives as
        // TT_DATA_MORE + TT_DATA_LAST and is reassembled by the transport
        let mut body = vec![0x01, 0x12, 0x34, 0x56, 0x78, 200];
        body.extend_from_slice(&[b'x'; 200]);
        let mut payload = spdu::build_session_number(session_id);
        apdu::build(&mut payload, ApduTag::APPLICATION_INFO, &body);

        let (head, tail) = payload.split_at(100);
        cam.send(TpduTag::DATA_MORE, head);
        cam.send(TpduTag::DATA_LAST, tail);
        pump(&mut session, &mut cam);

        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::ApplicationInfo { slot_id: 0, .. }]
        ));
        assert_eq!(session.app_info(0).unwrap().menu_string, vec![b'x'; 200]);
    }

    #[test]
    fn test_mmi_chained_objects() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);

        // a menu split into menu_more + menu_last fragments
        let mut menu_body = vec![0x02];
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"Menu");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"Info");
        apdu::build(&mut menu_body, ApduTag::TEXT_LAST, b"Exit");
        let (head, tail) = menu_body.split_at(7);

        cam.send_apdu(session_id, ApduTag::MENU_MORE, head);
        cam.send_apdu(session_id, ApduTag::MENU_LAST, tail);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiMenu {
                slot_id: 0,
                session_id,
                menu: MmiMenu {
                    title: b"Menu".to_vec(),
                    sub_title: Vec::new(),
                    bottom: Vec::new(),
                    items: vec![b"Info".to_vec(), b"Exit".to_vec()],
                },
            }]
        );

        // a standalone text split into text_more + text_last
        cam.send_apdu(session_id, ApduTag::TEXT_MORE, b"Hello, ");
        cam.send_apdu(session_id, ApduTag::TEXT_LAST, b"world");
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiText {
                slot_id: 0,
                session_id,
                text: b"Hello, world".to_vec(),
            }]
        );

        // a list split into list_more + list_last
        let (head, tail) = menu_body.split_at(10);
        cam.send_apdu(session_id, ApduTag::LIST_MORE, head);
        cam.send_apdu(session_id, ApduTag::LIST_LAST, tail);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiList {
                slot_id: 0,
                session_id,
                menu: MmiMenu {
                    title: b"Menu".to_vec(),
                    sub_title: Vec::new(),
                    bottom: Vec::new(),
                    items: vec![b"Info".to_vec(), b"Exit".to_vec()],
                },
            }]
        );

        session.mmi_list_close(0, session_id).unwrap();
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x0B, 0x01, 0x00]]
        );
    }

    #[test]
    fn test_mmi_display_control_errors() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);

        // an unknown display_control command
        cam.send_apdu(session_id, ApduTag::DISPLAY_CONTROL, &[0x02]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x02, 0x01, 0xF0]]
        );

        // set_mmi_mode with an unsupported mode
        cam.send_apdu(session_id, ApduTag::DISPLAY_CONTROL, &[0x01, 0x02]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x02, 0x01, 0xF1]]
        );
    }

    #[test]
    fn test_mmi_close_delay() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);

        // a deferred close carries the delay byte
        cam.send_apdu(session_id, ApduTag::CLOSE_MMI, &[0x01, 0x05]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus, vec![vec![0x95, 0x02, 0x00, 0x01]]);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiClose {
                slot_id: 0,
                session_id,
                delay: Some(5),
            }]
        );
    }

    #[test]
    fn test_closing_session_races() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);

        // close_mmi puts the session into the closing state
        cam.send_apdu(session_id, ApduTag::CLOSE_MMI, &[0x00]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus, vec![vec![0x95, 0x02, 0x00, 0x01]]);
        events(&mut session);

        // data in flight is still delivered while closing
        cam.send_apdu(session_id, ApduTag::TEXT_LAST, b"bye");
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::MmiText {
                slot_id: 0,
                session_id,
                text: b"bye".to_vec(),
            }]
        );

        // a duplicate close_mmi does not send a second close request
        cam.send_apdu(session_id, ApduTag::CLOSE_MMI, &[0x00]);
        let spdus = pump(&mut session, &mut cam);
        assert!(spdus.is_empty());
        events(&mut session);

        // the module close request crosses the host one: the host
        // replies and frees the session
        cam.send_spdu(&[0x95, 0x02, 0x00, 0x01]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus, vec![vec![0x96, 0x03, 0x00, 0x00, 0x01]]);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionClosed {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::MMI,
            }]
        );

        // the stale response to the host close request is reported
        cam.send_spdu(&[0x96, 0x03, 0x00, 0x00, 0x01]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));
    }

    #[test]
    fn test_close_session_response_status() {
        // F0 says that the peer no longer has the session. The local half is
        // released just like it is after a successful close.
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);
        session.request_close(0, session_id).unwrap();
        pump(&mut session, &mut cam);

        cam.send_spdu(&[0x96, 0x03, spdu::SS_NOT_ALLOCATED, 0x00, 0x01]);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionClosed {
                slot_id: 0,
                session_id,
                resource_id: ResourceId::MMI,
            }]
        );
        assert!(session.mmi_menu_answer(0, session_id, 1).is_err());

        // Reserved status values do not prove that the peer closed the
        // session. Report the bad response and restore the active state so
        // the application is not left with an unusable closing session.
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::MMI);
        session.request_close(0, session_id).unwrap();
        pump(&mut session, &mut cam);

        cam.send_spdu(&[0x96, 0x03, 0x01, 0x00, 0x01]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));

        session.mmi_menu_answer(0, session_id, 1).unwrap();
        assert_eq!(
            pump(&mut session, &mut cam),
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x88, 0x0B, 0x01, 0x01]]
        );
    }

    #[test]
    fn test_malformed_spdu() {
        let (mut session, mut cam) = pair();

        // a wrong spdu length field
        cam.send_spdu(&[0x91, 0x05, 0x00, 0x01, 0x00, 0x41]);
        let spdus = pump(&mut session, &mut cam);
        assert!(spdus.is_empty());
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));

        // create_session is never sent to a host
        cam.send_spdu(&[0x93, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));

        // the slot keeps working
        assert_eq!(
            open_session(&mut session, &mut cam, ResourceId::RESOURCE_MANAGER),
            1
        );
    }

    #[test]
    fn test_rm_profile_change_from_module() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::RESOURCE_MANAGER);

        // the module profile changed: the host re-enquires
        cam.send_apdu(session_id, ApduTag::PROFILE_CHANGE, &[]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x10, 0x00]]
        );
        assert!(events(&mut session).is_empty());
    }

    #[test]
    fn test_date_time_periodic() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&open_session_request(ResourceId::DATE_TIME));
        pump(&mut session, &mut cam);
        events(&mut session);

        cam.send_apdu(1, ApduTag::DATE_TIME_ENQ, &[30]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus.len(), 1);

        // The first explicit tick anchors the interval to the caller's
        // monotonic clock; no sleep or backdating is needed.
        let now = Instant::now();
        session.tick_at(now).unwrap();
        assert!(pump(&mut session, &mut cam).is_empty());

        session.tick_at(now + Duration::from_secs(29)).unwrap();
        assert!(pump(&mut session, &mut cam).is_empty());

        // the interval elapsed: tick_at resends the time
        session.tick_at(now + Duration::from_secs(30)).unwrap();
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus.len(), 1);
        assert_eq!(
            &spdus[0][.. 8],
            &[0x90, 0x02, 0x00, 0x01, 0x9F, 0x84, 0x41, 0x05]
        );

        // and the send resets the interval timer
        session.tick().unwrap();
        assert!(pump(&mut session, &mut cam).is_empty());
    }

    #[test]
    fn test_date_time_enq_empty_body() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&open_session_request(ResourceId::DATE_TIME));
        pump(&mut session, &mut cam);
        events(&mut session);

        cam.send_apdu(1, ApduTag::DATE_TIME_ENQ, &[]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus.len(), 1);
        assert_eq!(
            &spdus[0][.. 8],
            &[0x90, 0x02, 0x00, 0x01, 0x9F, 0x84, 0x41, 0x05]
        );
        assert!(events(&mut session).is_empty());
    }

    #[test]
    fn test_two_slots() {
        let (mut session, mut cam) = pair_slots(2);

        // slot 0: host control, slot 1: mmi
        let first = open_session(&mut session, &mut cam, ResourceId::HOST_CONTROL);
        assert_eq!(first, 1);

        cam.send_slot(
            1,
            TpduTag::DATA_LAST,
            &open_session_request(ResourceId::MMI),
        );
        let spdus = pump_slot(&mut session, &mut cam, 1);
        assert_eq!(
            spdus,
            vec![vec![0x92, 0x07, 0x00, 0x00, 0x40, 0x00, 0x41, 0x00, 0x02]]
        );
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionOpened {
                slot_id: 1,
                session_id: 2,
                resource_id: ResourceId::MMI,
            }]
        );

        // session 1 belongs to slot 0: an apdu for it on slot 1 is refused
        let mut payload = spdu::build_session_number(1);
        apdu::build(&mut payload, ApduTag::CLEAR_REPLACE, &[0x01]);
        cam.send_slot(1, TpduTag::DATA_LAST, &payload);
        pump_slot(&mut session, &mut cam, 1);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 1, .. }]
        ));

        // dropping slot 0 leaves the slot 1 session alive
        session.drop_slot(0);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionClosed {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::HOST_CONTROL,
            }]
        );

        session.mmi_close(1, 2).unwrap();
        let spdus = pump_slot(&mut session, &mut cam, 1);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x02, 0x9F, 0x88, 0x00, 0x01, 0x00]]
        );
    }

    #[test]
    fn test_date_time() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&open_session_request(ResourceId::DATE_TIME));
        let spdus = pump(&mut session, &mut cam);
        // open_session_response, then an unsolicited date_time object
        assert_eq!(spdus.len(), 2);
        assert_eq!(
            &spdus[1][.. 8],
            &[0x90, 0x02, 0x00, 0x01, 0x9F, 0x84, 0x41, 0x05]
        );
        assert_eq!(spdus[1].len(), 13);
        // MJD 61041 is 2026-01-01: the test runs later than that
        let mjd = (u16::from(spdus[1][8]) << 8) | u16::from(spdus[1][9]);
        assert!(mjd >= 61041, "mjd {}", mjd);

        // date_time_enq: the host replies right away
        cam.send_apdu(1, ApduTag::DATE_TIME_ENQ, &[30]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus.len(), 1);
        assert_eq!(
            &spdus[0][.. 8],
            &[0x90, 0x02, 0x00, 0x01, 0x9F, 0x84, 0x41, 0x05]
        );

        // the 30 seconds interval has not elapsed: tick sends nothing
        session.tick().unwrap();
        assert!(pump(&mut session, &mut cam).is_empty());
    }

    #[test]
    fn test_host_control() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::HOST_CONTROL);

        cam.send_apdu(
            session_id,
            ApduTag::TUNE,
            &[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88],
        );
        cam.send_apdu(
            session_id,
            ApduTag::REPLACE,
            &[0x07, 0xFF, 0xFE, 0xE1, 0x23],
        );
        cam.send_apdu(session_id, ApduTag::CLEAR_REPLACE, &[0x07]);
        pump(&mut session, &mut cam);

        assert_eq!(
            events(&mut session),
            vec![
                CaEvent::Tune {
                    slot_id: 0,
                    network_id: 0x1122,
                    original_network_id: 0x3344,
                    transport_stream_id: 0x5566,
                    service_id: 0x7788,
                },
                CaEvent::Replace {
                    slot_id: 0,
                    replace_ref: 0x07,
                    replaced_pid: 0x1FFE,
                    replacement_pid: 0x0123,
                },
                CaEvent::ClearReplace {
                    slot_id: 0,
                    replace_ref: 0x07,
                },
            ]
        );

        session.ask_release(0).unwrap();
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(
            spdus,
            vec![vec![0x90, 0x02, 0x00, 0x01, 0x9F, 0x84, 0x03, 0x00]]
        );
    }

    #[test]
    fn test_session_number_reuse() {
        let (mut session, mut cam) = pair();

        assert_eq!(
            open_session(&mut session, &mut cam, ResourceId::RESOURCE_MANAGER),
            1
        );
        assert_eq!(
            open_session(&mut session, &mut cam, ResourceId::APPLICATION_INFORMATION),
            2
        );

        // the module closes the first session
        cam.send_spdu(&[0x95, 0x02, 0x00, 0x01]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus, vec![vec![0x96, 0x03, 0x00, 0x00, 0x01]]);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::SessionClosed {
                slot_id: 0,
                session_id: 1,
                resource_id: ResourceId::RESOURCE_MANAGER,
            }]
        );

        // the freed session number is allocated again
        assert_eq!(open_session(&mut session, &mut cam, ResourceId::MMI), 1);
    }

    #[test]
    fn test_close_unknown_session() {
        let (mut session, mut cam) = pair();

        cam.send_spdu(&[0x95, 0x02, 0x00, 0x63]);
        let spdus = pump(&mut session, &mut cam);
        assert_eq!(spdus, vec![vec![0x96, 0x03, 0xF0, 0x00, 0x63]]);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));
    }

    #[test]
    fn test_malformed_apdu_keeps_slot_going() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::HOST_CONTROL);

        // an apdu on a session that was never opened
        cam.send_apdu(0x63, ApduTag::TUNE, &[0; 8]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));

        // an apdu the resource does not accept
        cam.send_apdu(session_id, ApduTag::PROFILE_ENQ, &[]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));

        // a truncated apdu body
        cam.send_apdu(session_id, ApduTag::TUNE, &[0x11, 0x22]);
        pump(&mut session, &mut cam);
        assert!(matches!(
            events(&mut session).as_slice(),
            [CaEvent::Malformed { slot_id: 0, .. }]
        ));

        // the session keeps working after all of that
        cam.send_apdu(session_id, ApduTag::CLEAR_REPLACE, &[0x01]);
        pump(&mut session, &mut cam);
        assert_eq!(
            events(&mut session),
            vec![CaEvent::ClearReplace {
                slot_id: 0,
                replace_ref: 0x01,
            }]
        );
    }

    #[test]
    fn test_empty_session_number_tail() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::RESOURCE_MANAGER);

        cam.send_spdu(&spdu::build_session_number(session_id));
        pump(&mut session, &mut cam);
        assert!(events(&mut session).is_empty());
    }

    #[test]
    fn test_packed_apdus() {
        let (mut session, mut cam) = pair();
        let session_id = open_session(&mut session, &mut cam, ResourceId::HOST_CONTROL);

        // two apdus packed into one spdu
        let mut payload = spdu::build_session_number(session_id);
        apdu::build(
            &mut payload,
            ApduTag::REPLACE,
            &[0x01, 0x00, 0x64, 0x00, 0xC8],
        );
        apdu::build(&mut payload, ApduTag::CLEAR_REPLACE, &[0x01]);
        cam.send_spdu(&payload);
        pump(&mut session, &mut cam);

        assert_eq!(
            events(&mut session),
            vec![
                CaEvent::Replace {
                    slot_id: 0,
                    replace_ref: 0x01,
                    replaced_pid: 0x0064,
                    replacement_pid: 0x00C8,
                },
                CaEvent::ClearReplace {
                    slot_id: 0,
                    replace_ref: 0x01,
                },
            ]
        );
    }

    #[test]
    fn test_drop_slot() {
        let (mut session, mut cam) = pair();

        open_session(&mut session, &mut cam, ResourceId::APPLICATION_INFORMATION);
        let mmi_session_id = open_session(&mut session, &mut cam, ResourceId::MMI);
        cam.send_apdu(
            1,
            ApduTag::APPLICATION_INFO,
            &[0x01, 0x12, 0x34, 0x56, 0x78, 0x00],
        );
        pump(&mut session, &mut cam);
        events(&mut session);
        assert!(session.app_info(0).is_some());

        session.drop_slot(0);
        assert_eq!(
            events(&mut session),
            vec![
                CaEvent::SessionClosed {
                    slot_id: 0,
                    session_id: 1,
                    resource_id: ResourceId::APPLICATION_INFORMATION,
                },
                CaEvent::SessionClosed {
                    slot_id: 0,
                    session_id: 2,
                    resource_id: ResourceId::MMI,
                },
            ]
        );
        // the stored application info went away with the slot
        assert!(session.app_info(0).is_none());
        assert!(session.mmi_menu_answer(0, mmi_session_id, 1).is_err());

        // the slot is usable again
        assert_eq!(
            open_session(&mut session, &mut cam, ResourceId::RESOURCE_MANAGER),
            1
        );
    }
}