dvb-ci 0.10.0

DVB Common Interface (EN 50221) — APDU/resource objects, session/transport PDUs, and a CA_PMT builder from a dvb-si PMT.
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
//! Auxiliary File System resource (CICAM file retrieval) — ETSI TS 103 205
//! V1.4.1 §9, Tables 72-75 (PDF pp. 96-99). See `docs/ts_103_205/file-retrieval.md`.
//!
//! Resource ID `0x00910041` (Class 145, Type 1, Version 1). A generic read-only
//! mechanism for a CICAM to offer files to the Host (including CICAM broadcast
//! applications to launch). Tags live in the CI Plus `0x9F94xx` namespace.
//!
//! - `FileSystemOffer` (`9F 94 00`, Table 72) — CICAM → Host.
//! - `FileSystemAck` (`9F 94 01`, Table 73) — Host → CICAM.
//! - `FileRequest` (`9F 94 02`, §9.4) — Host → CICAM.
//! - `FileAcknowledge` (`9F 94 03`, §9.5) — CICAM → Host.
//!
//! ## Deferred bodies (`FileRequest` / `FileAcknowledge`)
//!
//! TS 103 205 §9.4/§9.5 establish only the **tags and direction** of
//! `FileRequest` (`0x9F9402`) and `FileAcknowledge` (`0x9F9403`); their syntax is
//! by reference to CI Plus V1.3 \[3\] §14.5.1 / §14.5.2 (proprietary, not
//! reproduced). We therefore model both as opaque header-only APDUs carrying their
//! body verbatim as borrowed `&[u8]` ([`FileRequest`] / [`FileAcknowledge`]) — the
//! field layout is **not invented**. A caller that knows the V1.3 body shape can
//! decode `body` itself.

use crate::error::{Error, Result};
use crate::objects;
use broadcast_common::{Parse, Serialize};

/// Resource-scoped `apdu_tag`s for the Auxiliary File System resource (Table 75).
pub mod tag {
    use crate::tag::ApduTag;
    /// `FilesystemOffer_tag` = `9F 94 00`.
    pub const FILE_SYSTEM_OFFER: ApduTag = ApduTag::from_bytes(0x9F, 0x94, 0x00);
    /// `FilesystemAck_tag` = `9F 94 01`.
    pub const FILE_SYSTEM_ACK: ApduTag = ApduTag::from_bytes(0x9F, 0x94, 0x01);
    /// `FileRequest_tag` = `9F 94 02` (body deferred to CI Plus V1.3 §14.5.1).
    pub const FILE_REQUEST: ApduTag = ApduTag::from_bytes(0x9F, 0x94, 0x02);
    /// `FileAcknowledge_tag` = `9F 94 03` (body deferred to CI Plus V1.3 §14.5.2).
    pub const FILE_ACKNOWLEDGE: ApduTag = ApduTag::from_bytes(0x9F, 0x94, 0x03);
}

// --- AckCode (Table 74) ---

/// `AckCode` values (Table 74), the Host's response to a [`FileSystemOffer`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum AckCode {
    /// `0x01` — OK, the application environment is supported by the Host.
    Ok,
    /// `0x02` — Unknown DomainIdentifier, not supported by the Host.
    UnknownDomainIdentifier,
    /// Reserved (`0x00`, `0x03`–`0xFF`).
    Reserved(u8),
}
impl AckCode {
    /// Decode an `AckCode` byte.
    #[must_use]
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x01 => Self::Ok,
            0x02 => Self::UnknownDomainIdentifier,
            other => Self::Reserved(other),
        }
    }
    /// Wire byte.
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::Ok => 0x01,
            Self::UnknownDomainIdentifier => 0x02,
            Self::Reserved(v) => v,
        }
    }
    /// Spec token, or `"reserved"`.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::UnknownDomainIdentifier => "unknown_domain_identifier",
            Self::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(AckCode, Reserved);

// ---------------------------------------------------------------------------
// FileSystemOffer (Table 72)
// ---------------------------------------------------------------------------

/// `FileSystemOffer()` (Table 72): CICAM → Host. Specifies the file system
/// provided by the CICAM.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FileSystemOffer<'a> {
    /// How the `length_field` was coded on the wire: a non-minimal long form
    /// (e.g. `82 00 09`) is preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`](crate::length::LengthForm::Minimal) for a hand-built value.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: crate::length::LengthForm,

    /// `DomainIdentifier` body (`DomainIdentifierLength` bytes) — opaque
    /// middleware-defined identifier (URL / UUID / DVB-registered id).
    #[cfg_attr(feature = "serde", serde(borrow, with = "crate::objects::bytes_serde"))]
    pub domain_identifier: &'a [u8],
}

// DomainIdentifierLength(1) + DomainIdentifier bytes.
const OFFER_PREFIX: usize = 1;

impl<'a> Parse<'a> for FileSystemOffer<'a> {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) =
            objects::parse_apdu_header(bytes, tag::FILE_SYSTEM_OFFER, "FileSystemOffer")?;
        if body.len() < OFFER_PREFIX {
            return Err(Error::BufferTooShort {
                need: OFFER_PREFIX,
                have: body.len(),
                what: "FileSystemOffer",
            });
        }
        let len = body[0] as usize;
        let end = OFFER_PREFIX + len;
        if body.len() < end {
            return Err(Error::LengthMismatch {
                what: "FileSystemOffer DomainIdentifier",
                declared: len,
                actual: body.len().saturating_sub(OFFER_PREFIX),
            });
        }
        objects::reject_trailing_body(body, end, "FileSystemOffer")?;
        Ok(Self {
            length_form,
            domain_identifier: &body[OFFER_PREFIX..end],
        })
    }
}
impl Serialize for FileSystemOffer<'_> {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(
            OFFER_PREFIX + self.domain_identifier.len(),
            self.length_form,
        )
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        objects::fit_bits(
            self.domain_identifier.len() as u64,
            8,
            "FileSystemOffer DomainIdentifierLength",
        )?;
        let body_len = OFFER_PREFIX + self.domain_identifier.len();
        let pos =
            objects::write_apdu_header(tag::FILE_SYSTEM_OFFER, body_len, self.length_form, buf)?;
        buf[pos] = self.domain_identifier.len() as u8;
        buf[pos + OFFER_PREFIX..pos + body_len].copy_from_slice(self.domain_identifier);
        Ok(pos + body_len)
    }
}

// ---------------------------------------------------------------------------
// FileSystemAck (Table 73)
// ---------------------------------------------------------------------------

/// `FileSystemAck()` (Table 73): Host → CICAM.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FileSystemAck {
    /// How the `length_field` was coded on the wire: a non-minimal long form
    /// (e.g. `82 00 09`) is preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`](crate::length::LengthForm::Minimal) for a hand-built value.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: crate::length::LengthForm,

    /// `AckCode` (8) — Table 74.
    pub ack_code: AckCode,
}

const ACK_BODY: usize = 1;

impl<'a> Parse<'a> for FileSystemAck {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) =
            objects::parse_apdu_header(bytes, tag::FILE_SYSTEM_ACK, "FileSystemAck")?;
        if body.len() < ACK_BODY {
            return Err(Error::BufferTooShort {
                need: ACK_BODY,
                have: body.len(),
                what: "FileSystemAck",
            });
        }
        crate::objects::reject_trailing_body(body, ACK_BODY, "FileSystemAck")?;
        Ok(Self {
            length_form,
            ack_code: AckCode::from_u8(body[0]),
        })
    }
}
impl Serialize for FileSystemAck {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(ACK_BODY, self.length_form)
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let pos =
            objects::write_apdu_header(tag::FILE_SYSTEM_ACK, ACK_BODY, self.length_form, buf)?;
        buf[pos] = self.ack_code.to_u8();
        Ok(pos + ACK_BODY)
    }
}

// ---------------------------------------------------------------------------
// FileRequest (§9.4) / FileAcknowledge (§9.5) — bodies deferred to CI Plus V1.3
// ---------------------------------------------------------------------------

/// `FileRequest()` (§9.4, tag `0x9F9402`): Host → CICAM. **Body deferred** to
/// CI Plus V1.3 \[3\] §14.5.1 (proprietary, not reproduced in TS 103 205) — the
/// body is carried verbatim as opaque borrowed bytes; the field layout is not
/// invented.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FileRequest<'a> {
    /// How the `length_field` was coded on the wire: a non-minimal long form
    /// (e.g. `82 00 09`) is preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`](crate::length::LengthForm::Minimal) for a hand-built value.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: crate::length::LengthForm,

    /// Opaque CI Plus V1.3 §14.5.1 body (whole `length_field()` body, verbatim).
    #[cfg_attr(feature = "serde", serde(borrow, with = "crate::objects::bytes_serde"))]
    pub body: &'a [u8],
}

impl<'a> Parse<'a> for FileRequest<'a> {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) =
            objects::parse_apdu_header(bytes, tag::FILE_REQUEST, "FileRequest")?;
        Ok(Self { length_form, body })
    }
}
impl Serialize for FileRequest<'_> {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(self.body.len(), self.length_form)
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let pos =
            objects::write_apdu_header(tag::FILE_REQUEST, self.body.len(), self.length_form, buf)?;
        buf[pos..pos + self.body.len()].copy_from_slice(self.body);
        Ok(pos + self.body.len())
    }
}

/// `FileAcknowledge()` (§9.5, tag `0x9F9403`): CICAM → Host. **Body deferred** to
/// CI Plus V1.3 \[3\] §14.5.2 (proprietary, not reproduced in TS 103 205) — the
/// body is carried verbatim as opaque borrowed bytes; the field layout is not
/// invented.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FileAcknowledge<'a> {
    /// How the `length_field` was coded on the wire: a non-minimal long form
    /// (e.g. `82 00 09`) is preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`](crate::length::LengthForm::Minimal) for a hand-built value.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: crate::length::LengthForm,

    /// Opaque CI Plus V1.3 §14.5.2 body (whole `length_field()` body, verbatim).
    #[cfg_attr(feature = "serde", serde(borrow, with = "crate::objects::bytes_serde"))]
    pub body: &'a [u8],
}

impl<'a> Parse<'a> for FileAcknowledge<'a> {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) =
            objects::parse_apdu_header(bytes, tag::FILE_ACKNOWLEDGE, "FileAcknowledge")?;
        Ok(Self { length_form, body })
    }
}
impl Serialize for FileAcknowledge<'_> {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(self.body.len(), self.length_form)
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let pos = objects::write_apdu_header(
            tag::FILE_ACKNOWLEDGE,
            self.body.len(),
            self.length_form,
            buf,
        )?;
        buf[pos..pos + self.body.len()].copy_from_slice(self.body);
        Ok(pos + self.body.len())
    }
}

// ---------------------------------------------------------------------------
// Resource-scoped dispatch
// ---------------------------------------------------------------------------

crate::dispatch::declare_resource_apdus! {
    /// Resource-scoped dispatch over the Auxiliary File System resource objects.
    #[derive(Debug, Clone, PartialEq, Eq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    #[non_exhaustive]
    pub enum FileRetrievalApdu<'a> ("file_retrieval") {
        /// `FileSystemOffer` (`9F 94 00`).
        FileSystemOffer(#[cfg_attr(feature = "serde", serde(borrow))] FileSystemOffer<'a>) = tag::FILE_SYSTEM_OFFER,
        /// `FileSystemAck` (`9F 94 01`).
        FileSystemAck(FileSystemAck) = tag::FILE_SYSTEM_ACK,
        /// `FileRequest` (`9F 94 02`) — opaque deferred body.
        FileRequest(#[cfg_attr(feature = "serde", serde(borrow))] FileRequest<'a>) = tag::FILE_REQUEST,
        /// `FileAcknowledge` (`9F 94 03`) — opaque deferred body.
        FileAcknowledge(#[cfg_attr(feature = "serde", serde(borrow))] FileAcknowledge<'a>) = tag::FILE_ACKNOWLEDGE,
    }
}

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

    #[test]
    fn offer_round_trips_and_bites() {
        // DomainIdentifier "ab".
        let o = FileSystemOffer {
            length_form: crate::length::LengthForm::Minimal,
            domain_identifier: &[0x61, 0x62],
        };
        let bytes = o.try_to_bytes().unwrap();
        // tag(9F 94 00) len(03) DomainIdentifierLength(02) 61 62.
        assert_eq!(bytes, [0x9F, 0x94, 0x00, 0x03, 0x02, 0x61, 0x62]);
        assert_eq!(FileSystemOffer::parse(&bytes).unwrap(), o);
        let other = FileSystemOffer {
            length_form: crate::length::LengthForm::Minimal,
            domain_identifier: &[0x61, 0x63],
        };
        assert_ne!(bytes, other.try_to_bytes().unwrap());
    }

    #[test]
    fn offer_empty_domain() {
        let o = FileSystemOffer {
            length_form: crate::length::LengthForm::Minimal,
            domain_identifier: &[],
        };
        let bytes = o.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x9F, 0x94, 0x00, 0x01, 0x00]);
        assert_eq!(FileSystemOffer::parse(&bytes).unwrap(), o);
    }

    #[test]
    fn ack_round_trips() {
        let a = FileSystemAck {
            length_form: crate::length::LengthForm::Minimal,
            ack_code: AckCode::UnknownDomainIdentifier,
        };
        let bytes = a.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x9F, 0x94, 0x01, 0x01, 0x02]);
        assert_eq!(FileSystemAck::parse(&bytes).unwrap(), a);
        let ok = FileSystemAck {
            length_form: crate::length::LengthForm::Minimal,
            ack_code: AckCode::Ok,
        };
        assert_eq!(ok.try_to_bytes().unwrap()[4], 0x01);
    }

    #[test]
    fn file_request_opaque_body_round_trips() {
        let r = FileRequest {
            length_form: crate::length::LengthForm::Minimal,
            body: &[0x01, 0x02, 0x03],
        };
        let bytes = r.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x9F, 0x94, 0x02, 0x03, 0x01, 0x02, 0x03]);
        assert_eq!(FileRequest::parse(&bytes).unwrap(), r);
    }

    #[test]
    fn file_acknowledge_opaque_body_round_trips() {
        let a = FileAcknowledge {
            length_form: crate::length::LengthForm::Minimal,
            body: &[0xAA, 0xBB],
        };
        let bytes = a.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x9F, 0x94, 0x03, 0x02, 0xAA, 0xBB]);
        assert_eq!(FileAcknowledge::parse(&bytes).unwrap(), a);
    }

    #[test]
    fn dispatch_routes_each_tag() {
        let cases: alloc::vec::Vec<alloc::vec::Vec<u8>> = alloc::vec![
            FileSystemOffer {
                length_form: crate::length::LengthForm::Minimal,
                domain_identifier: &[0x61]
            }
            .try_to_bytes()
            .unwrap(),
            FileSystemAck {
                length_form: crate::length::LengthForm::Minimal,
                ack_code: AckCode::Ok
            }
            .try_to_bytes()
            .unwrap(),
            FileRequest {
                length_form: crate::length::LengthForm::Minimal,
                body: &[0x00]
            }
            .try_to_bytes()
            .unwrap(),
            FileAcknowledge {
                length_form: crate::length::LengthForm::Minimal,
                body: &[0x00]
            }
            .try_to_bytes()
            .unwrap(),
        ];
        for c in &cases {
            assert_eq!(
                &FileRetrievalApdu::parse(c).unwrap().try_to_bytes().unwrap(),
                c
            );
        }
        assert!(matches!(
            FileRetrievalApdu::parse(&[0x9F, 0x94, 0x7E, 0x00]),
            Err(Error::UnexpectedApduTag { .. })
        ));
    }

    #[test]
    fn oversized_domain_identifier_is_rejected_not_wrapped() {
        // 256 bytes silently wrapped DomainIdentifierLength (u8) to 0 before
        // the fix.
        let big = alloc::vec![0x61u8; 256];
        let offer = FileSystemOffer {
            length_form: crate::length::LengthForm::Minimal,
            domain_identifier: &big,
        };
        let mut buf = alloc::vec![0u8; 300];
        assert!(matches!(
            offer.serialize_into(&mut buf),
            Err(Error::InvalidObject { .. })
        ));
    }

    #[test]
    fn max_domain_identifier_still_serializes_and_round_trips() {
        let data = alloc::vec![0x61u8; 255];
        let offer = FileSystemOffer {
            length_form: crate::length::LengthForm::Minimal,
            domain_identifier: &data,
        };
        let bytes = offer.try_to_bytes().unwrap();
        assert_eq!(FileSystemOffer::parse(&bytes).unwrap(), offer);
    }
}