dvb-ci-runtime 0.23.0

Pure-Rust EN 50221 DVB Common Interface driver runtime — device I/O, TPDU/SPDU poll loop, resource state machines, and CAM/card hot-plug notifications over the dvb-ci codecs.
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
//! Human-readable decoding of CI link frames, for diagnosing live-CAM
//! exchanges (e.g. issue #337).
//!
//! [`decode_frame`] turns one raw link frame into a one-line annotation —
//! TPDU tag → SPDU tag → APDU tag — so a [`RecordingCaDevice`] capture reads
//! like the byte traces in bug reports without hand-decoding. [`decode_log`]
//! formats a whole captured exchange.
//!
//! [`RecordingCaDevice`]: crate::device::RecordingCaDevice

use crate::device::LinkEvent;
use crate::resource::APDU_TAG_LEN;
use dvb_ci::resource::ResourceId;
use dvb_ci::spdu::tags as spdu_tags;
use dvb_ci::tag::ApduTag;
use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};

/// Offset of `t_c_id` within a TPDU frame with a one-byte `length_field`.
const TPDU_TCID_OFFSET: usize = 2;

/// Offset of the data-available byte appended to a `T_SB` TPDU.
const TPDU_SB_DATA_AVAILABLE_OFFSET: usize = 3;

/// Offset of the `length_field` within a TPDU frame.
const TPDU_LENGTH_FIELD_OFFSET: usize = 1;

/// Bytes of `t_c_id` in a data TPDU.
const TPDU_TCID_LEN: usize = 1;

/// Maximum frame bytes shown in the unknown-tag preview.
const FRAME_PREVIEW_LEN: usize = 8;

/// Offset of the `session_number` field within a `session_number` SPDU.
const SPDU_SESSION_NUMBER_OFFSET: usize = 2;
/// Offset of `resource_id` within an `open_session_request` / `create_session`
/// SPDU.
const SPDU_RESOURCE_ID_OFFSET: usize = 2;
/// Offset of `nb` within a `create_session` SPDU.
const SPDU_CREATE_SESSION_NB_OFFSET: usize = 6;
/// Offset of `status` within a session-response SPDU.
const SPDU_STATUS_OFFSET: usize = 2;
/// Offset of `resource_id` within a session-response SPDU.
const SPDU_RESPONSE_RESOURCE_ID_OFFSET: usize = 3;
/// Offset of `nb` within a session-response SPDU.
const SPDU_RESPONSE_NB_OFFSET: usize = 7;

/// Bytes in a big-endian `u16` field.
const U16_LEN: usize = core::mem::size_of::<u16>();
/// Bytes in a big-endian `u32` field.
const U32_LEN: usize = core::mem::size_of::<u32>();

/// Name of a TPDU tag (Table A.16), or `"T_?"` for an unknown one.
fn tpdu_name(tag: u8) -> &'static str {
    match tag {
        tpdu_tags::SB => "T_SB",
        tpdu_tags::RCV => "T_RCV",
        tpdu_tags::CREATE_T_C => "Create_T_C",
        tpdu_tags::C_T_C_REPLY => "C_T_C_Reply",
        tpdu_tags::DELETE_T_C => "Delete_T_C",
        tpdu_tags::D_T_C_REPLY => "D_T_C_Reply",
        tpdu_tags::REQUEST_T_C => "Request_T_C",
        tpdu_tags::NEW_T_C => "New_T_C",
        tpdu_tags::T_C_ERROR => "T_C_Error",
        tpdu_tags::DATA_LAST => "T_Data_Last",
        tpdu_tags::DATA_MORE => "T_Data_More",
        _ => "T_?",
    }
}

/// Name of a session SPDU tag (§7), or `"spdu(?)"` for an unknown one.
fn spdu_name(tag: u8) -> &'static str {
    match tag {
        spdu_tags::SESSION_NUMBER => "session_number",
        spdu_tags::OPEN_SESSION_REQUEST => "open_session_request",
        spdu_tags::OPEN_SESSION_RESPONSE => "open_session_response",
        spdu_tags::CREATE_SESSION => "create_session",
        spdu_tags::CREATE_SESSION_RESPONSE => "create_session_response",
        spdu_tags::CLOSE_SESSION_REQUEST => "close_session_request",
        spdu_tags::CLOSE_SESSION_RESPONSE => "close_session_response",
        _ => "spdu(?)",
    }
}

/// Decode the APDU at the start of `apdu` (3-byte tag) into `name (9F80xx)`.
fn apdu_label(apdu: &[u8]) -> String {
    match apdu.first_chunk::<APDU_TAG_LEN>() {
        Some(&[a, b, c]) => {
            let tag = ApduTag::from_bytes(a, b, c);
            format!("{} ({:02X}{:02X}{:02X})", tag.name(), a, b, c)
        }
        None => "apdu(short)".to_string(),
    }
}

/// Decode the SPDU payload of a data TPDU into a label, recursing into the APDU
/// when the SPDU is a `session_number` wrapper.
fn spdu_label(spdu: &[u8]) -> String {
    match spdu.first().copied() {
        Some(spdu_tags::SESSION_NUMBER) if spdu.len() >= SPDU_SESSION_NUMBER_OFFSET + U16_LEN => {
            let nb = u16::from_be_bytes([
                spdu[SPDU_SESSION_NUMBER_OFFSET],
                spdu[SPDU_SESSION_NUMBER_OFFSET + 1],
            ]);
            let rest = &spdu[SPDU_SESSION_NUMBER_OFFSET + U16_LEN..];
            if rest.is_empty() {
                format!("session {nb}")
            } else {
                format!("session {nb} · {}", apdu_label(rest))
            }
        }
        // Session-management SPDUs: surface the resource_id (+ status/nb) so a
        // live trace shows *which* resource each create/open targets.
        Some(spdu_tags::OPEN_SESSION_REQUEST)
            if spdu.len() >= SPDU_RESOURCE_ID_OFFSET + U32_LEN =>
        {
            let r = ResourceId(u32::from_be_bytes([
                spdu[SPDU_RESOURCE_ID_OFFSET],
                spdu[SPDU_RESOURCE_ID_OFFSET + 1],
                spdu[SPDU_RESOURCE_ID_OFFSET + U16_LEN],
                spdu[SPDU_RESOURCE_ID_OFFSET + U16_LEN + 1],
            ]));
            format!("open_session_request {}", r.name())
        }
        Some(spdu_tags::CREATE_SESSION)
            if spdu.len() >= SPDU_CREATE_SESSION_NB_OFFSET + U16_LEN =>
        {
            let r = ResourceId(u32::from_be_bytes([
                spdu[SPDU_RESOURCE_ID_OFFSET],
                spdu[SPDU_RESOURCE_ID_OFFSET + 1],
                spdu[SPDU_RESOURCE_ID_OFFSET + U16_LEN],
                spdu[SPDU_RESOURCE_ID_OFFSET + U16_LEN + 1],
            ]));
            let nb = u16::from_be_bytes([
                spdu[SPDU_CREATE_SESSION_NB_OFFSET],
                spdu[SPDU_CREATE_SESSION_NB_OFFSET + 1],
            ]);
            format!("create_session {} (nb {nb})", r.name())
        }
        Some(t @ (spdu_tags::CREATE_SESSION_RESPONSE | spdu_tags::OPEN_SESSION_RESPONSE))
            if spdu.len() >= SPDU_RESPONSE_NB_OFFSET + U16_LEN =>
        {
            let status = spdu[SPDU_STATUS_OFFSET];
            let r = ResourceId(u32::from_be_bytes([
                spdu[SPDU_RESPONSE_RESOURCE_ID_OFFSET],
                spdu[SPDU_RESPONSE_RESOURCE_ID_OFFSET + 1],
                spdu[SPDU_RESPONSE_RESOURCE_ID_OFFSET + U16_LEN],
                spdu[SPDU_RESPONSE_RESOURCE_ID_OFFSET + U16_LEN + 1],
            ]));
            let nb = u16::from_be_bytes([
                spdu[SPDU_RESPONSE_NB_OFFSET],
                spdu[SPDU_RESPONSE_NB_OFFSET + 1],
            ]);
            format!("{} {} status={status:#04x} nb={nb}", spdu_name(t), r.name())
        }
        Some(t) => spdu_name(t).to_string(),
        None => "empty".to_string(),
    }
}

/// Decode one raw link frame into a one-line annotation.
///
/// Handles the leading TPDU, the SPDU it carries (for `T_Data_*`), and the APDU
/// inside a `session_number` SPDU. Appended `T_SB` data-available bits are noted.
#[must_use]
pub fn decode_frame(frame: &[u8]) -> String {
    let Some(&tag) = frame.first() else {
        return "empty frame".to_string();
    };
    match tag {
        tpdu_tags::SB => match frame.get(TPDU_SB_DATA_AVAILABLE_OFFSET) {
            Some(&sb) => format!(
                "T_SB tcid={} DA={}",
                frame.get(TPDU_TCID_OFFSET).copied().unwrap_or(0),
                u8::from(SbValue(sb).data_available())
            ),
            None => "T_SB (short)".to_string(),
        },
        tpdu_tags::CREATE_T_C
        | tpdu_tags::C_T_C_REPLY
        | tpdu_tags::DELETE_T_C
        | tpdu_tags::D_T_C_REPLY
        | tpdu_tags::REQUEST_T_C
        | tpdu_tags::NEW_T_C
        | tpdu_tags::RCV
        | tpdu_tags::T_C_ERROR => {
            format!(
                "{} tcid={}",
                tpdu_name(tag),
                frame.get(TPDU_TCID_OFFSET).copied().unwrap_or(0)
            )
        }
        tpdu_tags::DATA_LAST | tpdu_tags::DATA_MORE => {
            // tag · length_field · t_c_id · data(=SPDU) · [appended T_SB].
            // length_field uses the Table-1 codec (long-form for >127 bytes), so
            // decode it rather than assuming a single byte.
            let Ok((len, hdr)) = dvb_ci::length::decode(&frame[TPDU_LENGTH_FIELD_OFFSET..]) else {
                return format!("{} (bad length_field)", tpdu_name(tag));
            };
            let start = TPDU_LENGTH_FIELD_OFFSET + hdr; // t_c_id offset
            let tcid = frame.get(start).copied().unwrap_or(0);
            // `length` counts t_c_id + data; the SPDU is the data after t_c_id.
            let data_end = (start + len).min(frame.len());
            let spdu = frame.get(start + TPDU_TCID_LEN..data_end).unwrap_or(&[]);
            if spdu.is_empty() {
                format!("{} tcid={} (poll)", tpdu_name(tag), tcid)
            } else {
                format!("{} tcid={} · {}", tpdu_name(tag), tcid, spdu_label(spdu))
            }
        }
        _ => format!(
            "{} {:02X?}",
            tpdu_name(tag),
            &frame[..frame.len().min(FRAME_PREVIEW_LEN)]
        ),
    }
}

/// Format a whole captured exchange as a multi-line annotated trace.
#[must_use]
pub fn decode_log(log: &[LinkEvent]) -> String {
    let mut out = String::new();
    for ev in log {
        let line = match ev {
            LinkEvent::Tx(f) => format!("W {}", decode_frame(f)),
            LinkEvent::Rx(f) => format!("R {}", decode_frame(f)),
            LinkEvent::Reset => "  reset()".to_string(),
            LinkEvent::SlotInfo(si) => format!(
                "  slot_info() -> present={} ready={}",
                si.module_present, si.module_ready
            ),
        };
        out.push_str(&line);
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn names_every_connection_management_tpdu() {
        // Table A.16: Delete/Request/New T_C used to fall through to "T_?".
        assert_eq!(decode_frame(&[0x84, 0x01, 0x01]), "Delete_T_C tcid=1");
        assert_eq!(decode_frame(&[0x85, 0x01, 0x01]), "D_T_C_Reply tcid=1");
        assert_eq!(decode_frame(&[0x86, 0x01, 0x01]), "Request_T_C tcid=1");
    }

    #[test]
    fn decodes_the_337_handshake_frames() {
        // Bytes lifted from issue #337's trace.
        assert_eq!(decode_frame(&[0x82, 0x01, 0x01]), "Create_T_C tcid=1");
        assert_eq!(decode_frame(&[0x81, 0x01, 0x01]), "T_RCV tcid=1");
        assert_eq!(decode_frame(&[0x80, 0x02, 0x01, 0x00]), "T_SB tcid=1 DA=0");

        // open_session_request (module): a0 07 01 | 91 04 00 01 00 41 | SB
        let osr = [
            0xA0, 0x07, 0x01, 0x91, 0x04, 0x00, 0x01, 0x00, 0x41, 0x80, 0x02, 0x01, 0x00,
        ];
        assert_eq!(
            decode_frame(&osr),
            "T_Data_Last tcid=1 · open_session_request resource_manager"
        );

        // profile_enq (host): a0 09 01 | 90 02 00 01 | 9f 80 10 00
        let enq = [
            0xA0, 0x09, 0x01, 0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x10, 0x00,
        ];
        assert_eq!(
            decode_frame(&enq),
            "T_Data_Last tcid=1 · session 1 · profile_enq (9F8010)"
        );
    }

    #[test]
    fn decodes_long_form_length_profile_reply() {
        // The module's profile_reply, captured raw on hardware (#337): the
        // length_field is long-form `82 00 09`. A short-form decoder mis-reads
        // tcid as 0x00 and garbles the SPDU.
        let f = [
            0xA0, 0x82, 0x00, 0x09, 0x01, 0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x11, 0x00, 0x80,
            0x02, 0x01, 0x00,
        ];
        assert_eq!(
            decode_frame(&f),
            "T_Data_Last tcid=1 · session 1 · profile (9F8011)"
        );
    }

    #[test]
    fn decodes_log_directions() {
        let log = [
            LinkEvent::Reset,
            LinkEvent::Tx(vec![0x82, 0x01, 0x01]),
            LinkEvent::Rx(vec![0x80, 0x02, 0x01, 0x00]),
        ];
        let s = decode_log(&log);
        assert!(s.contains("  reset()"));
        assert!(s.contains("W Create_T_C tcid=1"));
        assert!(s.contains("R T_SB tcid=1 DA=0"));
    }

    /// Every TPDU tag (Table A.16) has its own label; an unknown one is `T_?`.
    #[test]
    fn every_tpdu_tag_has_its_name() {
        for (tag, name) in [
            (tpdu_tags::SB, "T_SB"),
            (tpdu_tags::RCV, "T_RCV"),
            (tpdu_tags::CREATE_T_C, "Create_T_C"),
            (tpdu_tags::C_T_C_REPLY, "C_T_C_Reply"),
            (tpdu_tags::DELETE_T_C, "Delete_T_C"),
            (tpdu_tags::D_T_C_REPLY, "D_T_C_Reply"),
            (tpdu_tags::REQUEST_T_C, "Request_T_C"),
            (tpdu_tags::NEW_T_C, "New_T_C"),
            (tpdu_tags::T_C_ERROR, "T_C_Error"),
            (tpdu_tags::DATA_LAST, "T_Data_Last"),
            (tpdu_tags::DATA_MORE, "T_Data_More"),
            (0x00, "T_?"),
        ] {
            assert_eq!(tpdu_name(tag), name);
        }
        // …and each one reaches the decoded line, not just the helper.
        for (tag, name) in [
            (tpdu_tags::C_T_C_REPLY, "C_T_C_Reply"),
            (tpdu_tags::NEW_T_C, "New_T_C"),
            (tpdu_tags::T_C_ERROR, "T_C_Error"),
            (tpdu_tags::DATA_MORE, "T_Data_More"),
        ] {
            assert!(
                decode_frame(&[tag, 0x01, 0x01]).starts_with(name),
                "{tag:#04x} must decode as {name}"
            );
        }
    }

    /// Every session SPDU tag (§7) has its own label; an unknown one is
    /// `spdu(?)`.
    #[test]
    fn every_spdu_tag_has_its_name() {
        for (tag, name) in [
            (spdu_tags::SESSION_NUMBER, "session_number"),
            (spdu_tags::OPEN_SESSION_REQUEST, "open_session_request"),
            (spdu_tags::OPEN_SESSION_RESPONSE, "open_session_response"),
            (spdu_tags::CREATE_SESSION, "create_session"),
            (
                spdu_tags::CREATE_SESSION_RESPONSE,
                "create_session_response",
            ),
            (spdu_tags::CLOSE_SESSION_REQUEST, "close_session_request"),
            (spdu_tags::CLOSE_SESSION_RESPONSE, "close_session_response"),
            (0x00, "spdu(?)"),
        ] {
            assert_eq!(spdu_name(tag), name);
        }
    }

    /// Wrap `spdu` in a module→host `T_Data_Last` frame on tcid 1.
    fn data_frame(spdu: &[u8]) -> Vec<u8> {
        let mut f = vec![tpdu_tags::DATA_LAST, (1 + spdu.len()) as u8, 0x01];
        f.extend_from_slice(spdu);
        f
    }

    /// The session-management labels each decode a fixed-size header, so the
    /// guard length is the shortest SPDU that carries one: one byte less must
    /// fall back to the plain label instead of indexing past the end.
    #[test]
    fn spdu_labels_guard_the_exact_header_lengths() {
        assert_eq!(
            decode_frame(&data_frame(&[spdu_tags::SESSION_NUMBER, 0x01, 0x00])),
            "T_Data_Last tcid=1 · session_number"
        );
        assert_eq!(
            decode_frame(&data_frame(&[spdu_tags::SESSION_NUMBER, 0x02, 0x00, 0x01])),
            "T_Data_Last tcid=1 · session 1"
        );

        assert_eq!(
            decode_frame(&data_frame(&[
                spdu_tags::OPEN_SESSION_REQUEST,
                0x03,
                0x00,
                0x01,
                0x00
            ])),
            "T_Data_Last tcid=1 · open_session_request"
        );
        assert_eq!(
            decode_frame(&data_frame(&[
                spdu_tags::OPEN_SESSION_REQUEST,
                0x04,
                0x00,
                0x01,
                0x00,
                0x41
            ])),
            "T_Data_Last tcid=1 · open_session_request resource_manager"
        );

        assert_eq!(
            decode_frame(&data_frame(&[
                spdu_tags::CREATE_SESSION,
                0x05,
                0x00,
                0x01,
                0x00,
                0x41,
                0x00
            ])),
            "T_Data_Last tcid=1 · create_session"
        );
        assert_eq!(
            decode_frame(&data_frame(&[
                spdu_tags::CREATE_SESSION,
                0x06,
                0x00,
                0x01,
                0x00,
                0x41,
                0x00,
                0x00
            ])),
            "T_Data_Last tcid=1 · create_session resource_manager (nb 0)"
        );

        assert_eq!(
            decode_frame(&data_frame(&[
                spdu_tags::OPEN_SESSION_RESPONSE,
                0x06,
                0x00,
                0x00,
                0x01,
                0x00,
                0x41,
                0x00
            ])),
            "T_Data_Last tcid=1 · open_session_response"
        );
        assert_eq!(
            decode_frame(&data_frame(&[
                spdu_tags::OPEN_SESSION_RESPONSE,
                0x07,
                0x00,
                0x00,
                0x01,
                0x00,
                0x41,
                0x00,
                0x00
            ])),
            "T_Data_Last tcid=1 · open_session_response resource_manager status=0x00 nb=0"
        );
    }

    /// The SPDU slice ends at `t_c_id offset + length_field`; the appended
    /// status byte after it is not part of the SPDU.
    #[test]
    fn a_data_tpdu_ignores_the_appended_status_byte() {
        // length_field 5 = the 1-byte t_c_id plus a 4-byte session_number SPDU
        // with no APDU inside it, then the module's appended T_SB.
        let frame = [
            0xA0,
            0x05,
            0x01,
            spdu_tags::SESSION_NUMBER,
            0x02,
            0x00,
            0x01,
            0x80,
            0x02,
            0x01,
            0x00,
        ];
        assert_eq!(decode_frame(&frame), "T_Data_Last tcid=1 · session 1");
    }
}