dvb-ci 0.8.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
//! Resource Manager v2 objects — ETSI TS 101 699 V1.1.1 §4.2.1, Tables 3-7
//! (PDF pp. 13-17). See `docs/ci_plus/resource-manager-v2.md`.
//!
//! Resource ID `0x00010042`. Adds Module ID establishment to the EN 50221 v1
//! Resource Manager. The three v1 objects (Profile Enquiry, Profile Reply,
//! Profile Changed) are layout-identical to EN 50221 but are re-defined here so
//! the v2 resource owns its own object set:
//!
//! - `profile_enq` (`9F 80 10`, Table 3) — header-only enquiry.
//! - `profile_reply` (`9F 80 11`, Table 4) — list of `resource_identifier()`s.
//! - `profile_changed` (`9F 80 12`, Table 5) — header-only notification.
//! - `module_id_send` (`9F 80 13`, Table 6) — module returns its Module ID.
//! - `module_id_command` (`9F 80 14`, Table 7) — host ack / sets the Module ID.

use crate::error::{Error, Result};
use crate::objects;
use crate::resource::ResourceId;
use crate::tag::ApduTag;
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

/// Resource-scoped `apdu_tag`s for the Resource Manager v2 (Table 87 / Tables 3-7).
pub mod tag {
    use crate::tag::ApduTag;
    /// `Tprofile_enq` = `9F 80 10`.
    pub const PROFILE_ENQ: ApduTag = ApduTag::from_bytes(0x9F, 0x80, 0x10);
    /// `Tprofile_reply` = `9F 80 11`.
    pub const PROFILE_REPLY: ApduTag = ApduTag::from_bytes(0x9F, 0x80, 0x11);
    /// `Tprofile_changed` = `9F 80 12`.
    pub const PROFILE_CHANGED: ApduTag = ApduTag::from_bytes(0x9F, 0x80, 0x12);
    /// `Tmodule_id_send` = `9F 80 13`.
    pub const MODULE_ID_SEND: ApduTag = ApduTag::from_bytes(0x9F, 0x80, 0x13);
    /// `Tmodule_id_command` = `9F 80 14`.
    pub const MODULE_ID_COMMAND: ApduTag = ApduTag::from_bytes(0x9F, 0x80, 0x14);
}

/// `profile_enq()` — Profile Enquiry, empty body (Table 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ProfileEnq;

/// `profile_changed()` — Profile Changed, empty body (Table 5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ProfileChanged;

/// `profile_reply()` — the list of resources the sender provides (Table 4).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ProfileReply {
    /// Advertised `resource_identifier()`s, in wire order (`length_field = N*4`).
    pub resources: Vec<ResourceId>,
}

/// `module_id_send()` — module returns its current Module ID (Table 6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ModuleIdSend {
    /// The 6-bit Module ID (`0` if the host has not allocated one). Only the low
    /// 6 bits are significant; the top 2 bits are reserved.
    pub module_id: u8,
}

/// `command` values for `module_id_command()` (Table 7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ModuleIdCommandKind {
    /// `0x01` — host accepts the Module ID; module continues to Profile.
    Acknowledgement,
    /// `0x02` — `module_id` carries a new ID to set.
    SetModuleId,
    /// Any other value (reserved).
    Reserved(u8),
}

impl ModuleIdCommandKind {
    /// Decode a `command` byte.
    #[must_use]
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x01 => Self::Acknowledgement,
            0x02 => Self::SetModuleId,
            other => Self::Reserved(other),
        }
    }
    /// Wire byte.
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::Acknowledgement => 0x01,
            Self::SetModuleId => 0x02,
            Self::Reserved(v) => v,
        }
    }
    /// Spec token, or `"reserved"`.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Acknowledgement => "Acknowledgement",
            Self::SetModuleId => "Set_ModuleID",
            Self::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(ModuleIdCommandKind, Reserved);

/// `module_id_command()` — host acknowledges or sets the Module ID (Table 7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ModuleIdCommand {
    /// `command`.
    pub command: ModuleIdCommandKind,
    /// The 6-bit Module ID (significant only for `Set_ModuleID`).
    pub module_id: u8,
}

// --- profile_enq / profile_changed (empty body) ---

impl<'a> Parse<'a> for ProfileEnq {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        objects::parse_empty_apdu(bytes, tag::PROFILE_ENQ, "profile_enq")?;
        Ok(Self)
    }
}
impl Serialize for ProfileEnq {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::empty_apdu_len()
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        objects::serialize_empty_apdu(tag::PROFILE_ENQ, buf)
    }
}

impl<'a> Parse<'a> for ProfileChanged {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        objects::parse_empty_apdu(bytes, tag::PROFILE_CHANGED, "profile_changed")?;
        Ok(Self)
    }
}
impl Serialize for ProfileChanged {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::empty_apdu_len()
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        objects::serialize_empty_apdu(tag::PROFILE_CHANGED, buf)
    }
}

// --- profile_reply (resource-id list) ---

impl<'a> Parse<'a> for ProfileReply {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = objects::parse_apdu_header(bytes, tag::PROFILE_REPLY, "profile_reply")?;
        if body.len() % ResourceId::LEN != 0 {
            return Err(Error::InvalidObject {
                what: "profile_reply",
                reason: "body length is not a multiple of 4",
            });
        }
        let mut resources = Vec::with_capacity(body.len() / ResourceId::LEN);
        for chunk in body.chunks_exact(ResourceId::LEN) {
            resources.push(ResourceId::parse(chunk)?);
        }
        Ok(Self { resources })
    }
}
impl Serialize for ProfileReply {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(self.resources.len() * ResourceId::LEN)
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let body_len = self.resources.len() * ResourceId::LEN;
        let mut pos = objects::write_apdu_header(tag::PROFILE_REPLY, body_len, buf)?;
        for r in &self.resources {
            pos += r.serialize_into(&mut buf[pos..])?;
        }
        Ok(pos)
    }
}

// --- module_id_send ---

// reserved(2) + module_id(6).
const MODULE_ID_SEND_BODY: usize = 1;

impl<'a> Parse<'a> for ModuleIdSend {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = objects::parse_apdu_header(bytes, tag::MODULE_ID_SEND, "module_id_send")?;
        if body.len() < MODULE_ID_SEND_BODY {
            return Err(Error::BufferTooShort {
                need: MODULE_ID_SEND_BODY,
                have: body.len(),
                what: "module_id_send",
            });
        }
        Ok(Self {
            module_id: body[0] & 0x3F,
        })
    }
}
impl Serialize for ModuleIdSend {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(MODULE_ID_SEND_BODY)
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let pos = objects::write_apdu_header(tag::MODULE_ID_SEND, MODULE_ID_SEND_BODY, buf)?;
        // reserved(2)='00', module_id(6).
        buf[pos] = self.module_id & 0x3F;
        Ok(pos + MODULE_ID_SEND_BODY)
    }
}

// --- module_id_command ---

// command(8) + reserved(2) + module_id(6).
const MODULE_ID_COMMAND_BODY: usize = 2;

impl<'a> Parse<'a> for ModuleIdCommand {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = objects::parse_apdu_header(bytes, tag::MODULE_ID_COMMAND, "module_id_command")?;
        if body.len() < MODULE_ID_COMMAND_BODY {
            return Err(Error::BufferTooShort {
                need: MODULE_ID_COMMAND_BODY,
                have: body.len(),
                what: "module_id_command",
            });
        }
        Ok(Self {
            command: ModuleIdCommandKind::from_u8(body[0]),
            module_id: body[1] & 0x3F,
        })
    }
}
impl Serialize for ModuleIdCommand {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        objects::apdu_len(MODULE_ID_COMMAND_BODY)
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let pos = objects::write_apdu_header(tag::MODULE_ID_COMMAND, MODULE_ID_COMMAND_BODY, buf)?;
        buf[pos] = self.command.to_u8();
        buf[pos + 1] = self.module_id & 0x3F;
        Ok(pos + MODULE_ID_COMMAND_BODY)
    }
}

/// Resource-scoped dispatch over the Resource Manager v2 objects (Tables 3-7).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ResourceManagerV2Apdu {
    /// `profile_enq` (`9F 80 10`).
    ProfileEnq(ProfileEnq),
    /// `profile_reply` (`9F 80 11`).
    ProfileReply(ProfileReply),
    /// `profile_changed` (`9F 80 12`).
    ProfileChanged(ProfileChanged),
    /// `module_id_send` (`9F 80 13`).
    ModuleIdSend(ModuleIdSend),
    /// `module_id_command` (`9F 80 14`).
    ModuleIdCommand(ModuleIdCommand),
}

impl ResourceManagerV2Apdu {
    /// Parse a Resource Manager v2 APDU, dispatching on the leading `apdu_tag`.
    pub fn parse(body: &[u8]) -> Result<Self> {
        if body.len() < 3 {
            return Err(Error::BufferTooShort {
                need: 3,
                have: body.len(),
                what: "resource_manager_v2 apdu_tag",
            });
        }
        let t = ApduTag::from_bytes(body[0], body[1], body[2]);
        match t {
            tag::PROFILE_ENQ => Ok(Self::ProfileEnq(ProfileEnq::parse(body)?)),
            tag::PROFILE_REPLY => Ok(Self::ProfileReply(ProfileReply::parse(body)?)),
            tag::PROFILE_CHANGED => Ok(Self::ProfileChanged(ProfileChanged::parse(body)?)),
            tag::MODULE_ID_SEND => Ok(Self::ModuleIdSend(ModuleIdSend::parse(body)?)),
            tag::MODULE_ID_COMMAND => Ok(Self::ModuleIdCommand(ModuleIdCommand::parse(body)?)),
            _ => Err(Error::UnexpectedApduTag {
                got: t.as_u24(),
                expected: tag::PROFILE_ENQ.as_u24(),
                what: "resource_manager_v2",
            }),
        }
    }
}

impl Serialize for ResourceManagerV2Apdu {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        match self {
            Self::ProfileEnq(o) => o.serialized_len(),
            Self::ProfileReply(o) => o.serialized_len(),
            Self::ProfileChanged(o) => o.serialized_len(),
            Self::ModuleIdSend(o) => o.serialized_len(),
            Self::ModuleIdCommand(o) => o.serialized_len(),
        }
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        match self {
            Self::ProfileEnq(o) => o.serialize_into(buf),
            Self::ProfileReply(o) => o.serialize_into(buf),
            Self::ProfileChanged(o) => o.serialize_into(buf),
            Self::ModuleIdSend(o) => o.serialize_into(buf),
            Self::ModuleIdCommand(o) => o.serialize_into(buf),
        }
    }
}

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

    #[test]
    fn profile_enq_round_trips() {
        let bytes = ProfileEnq.to_bytes();
        assert_eq!(bytes, [0x9F, 0x80, 0x10, 0x00]);
        assert_eq!(ProfileEnq::parse(&bytes).unwrap(), ProfileEnq);
    }

    #[test]
    fn profile_changed_round_trips() {
        let bytes = ProfileChanged.to_bytes();
        assert_eq!(bytes, [0x9F, 0x80, 0x12, 0x00]);
        assert_eq!(ProfileChanged::parse(&bytes).unwrap(), ProfileChanged);
    }

    #[test]
    fn profile_reply_multi_round_trips_and_bites() {
        let p = ProfileReply {
            resources: alloc::vec![ResourceId(0x0001_0042), ResourceId(0x0002_0042)],
        };
        let bytes = p.to_bytes();
        // tag(3) + len(1) + 2*4 = 12; len = 0x08.
        assert_eq!(
            bytes,
            [
                0x9F, 0x80, 0x11, 0x08, 0x00, 0x01, 0x00, 0x42, 0x00, 0x02, 0x00, 0x42
            ]
        );
        assert_eq!(ProfileReply::parse(&bytes).unwrap(), p);
        let mut other = p.clone();
        other.resources[1] = ResourceId(0x0022_0041);
        assert_ne!(bytes, other.to_bytes());
    }

    #[test]
    fn module_id_send_round_trips_and_bites() {
        let m = ModuleIdSend { module_id: 0x03 };
        let bytes = m.to_bytes();
        assert_eq!(bytes, [0x9F, 0x80, 0x13, 0x01, 0x03]);
        assert_eq!(ModuleIdSend::parse(&bytes).unwrap(), m);
        // top 2 bits ignored on read.
        let parsed = ModuleIdSend::parse(&[0x9F, 0x80, 0x13, 0x01, 0xC3]).unwrap();
        assert_eq!(parsed.module_id, 0x03);
        let other = ModuleIdSend { module_id: 0x04 };
        assert_ne!(bytes, other.to_bytes());
    }

    #[test]
    fn module_id_command_round_trips_and_bites() {
        let m = ModuleIdCommand {
            command: ModuleIdCommandKind::SetModuleId,
            module_id: 0x05,
        };
        let bytes = m.to_bytes();
        assert_eq!(bytes, [0x9F, 0x80, 0x14, 0x02, 0x02, 0x05]);
        assert_eq!(ModuleIdCommand::parse(&bytes).unwrap(), m);
        assert_eq!(m.command.name(), "Set_ModuleID");
        let mut other = m;
        other.command = ModuleIdCommandKind::Acknowledgement;
        assert_ne!(bytes, other.to_bytes());
    }

    #[test]
    fn dispatch_routes_each_tag() {
        let enq = ProfileEnq.to_bytes();
        assert!(matches!(
            ResourceManagerV2Apdu::parse(&enq).unwrap(),
            ResourceManagerV2Apdu::ProfileEnq(_)
        ));
        let mic = ModuleIdCommand {
            command: ModuleIdCommandKind::Acknowledgement,
            module_id: 1,
        }
        .to_bytes();
        let parsed = ResourceManagerV2Apdu::parse(&mic).unwrap();
        assert!(matches!(parsed, ResourceManagerV2Apdu::ModuleIdCommand(_)));
        // dispatch enum round-trips.
        assert_eq!(parsed.to_bytes(), mic);
    }
}