Skip to main content

dvb_si/tables/
cat.rs

1//! Conditional Access Table — ISO/IEC 13818-1 §2.4.4.6.
2//!
3//! Carried on PID 0x0001 with table_id 0x01. Contains a flat
4//! list of CA descriptors (tag 0x09) identifying every CA system
5//! in use plus the EMM PID on which Entitlement Management
6//! Messages for that system are carried.
7//!
8//! A single-section table per CAS standard.
9
10use crate::descriptors::ca::CaDescriptor;
11use crate::descriptors::DescriptorLoop;
12use crate::error::{Error, Result};
13use alloc::vec::Vec;
14use dvb_common::{Parse, Serialize};
15
16/// CAT table_id (ISO/IEC 13818-1 Table 2-30).
17pub const TABLE_ID: u8 = 0x01;
18/// CAT well-known PID.
19pub const PID: u16 = 0x0001;
20
21const MIN_HEADER_LEN: usize = 3;
22const EXTENSION_HEADER_LEN: usize = 5;
23const CRC_LEN: usize = 4;
24const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
25
26/// One CA descriptor entry from the CAT, in owned form so it
27/// outlives the source section bytes.
28#[derive(Debug, Clone, PartialEq, Eq, Default)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize))]
30pub struct CatCaEntry {
31    /// CA System ID — the CAID. e.g. 0x0500 Viaccess, 0x0650
32    /// Irdeto ORF-ICE, 0x0100 Seca/Mediaguard.
33    pub ca_system_id: u16,
34    /// EMM PID for this CA system.
35    pub ca_pid: u16,
36    /// Optional private data after the standard CA fields.
37    pub private_data: Vec<u8>,
38}
39
40/// Conditional Access Table.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize))]
43#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
44pub struct CatSection<'a> {
45    /// 5-bit version_number from the section header.
46    pub version_number: u8,
47    /// current_next_indicator bit.
48    pub current_next_indicator: bool,
49    /// section_number in the sub-table sequence (typically 0 — single-section).
50    pub section_number: u8,
51    /// last_section_number (typically 0).
52    pub last_section_number: u8,
53    /// Descriptor loop (byte 8 → CRC), preserved verbatim. ISO/IEC 13818-1
54    /// §2.4.4.6 permits descriptors other than CA in this loop; keeping the loop
55    /// raw makes parse → serialize identity hold for all of them. Serializes as
56    /// the typed descriptor sequence; `.raw()` yields the wire bytes. Use
57    /// [`CatSection::ca_descriptors`] for the typed CA (tag 0x09) view.
58    pub descriptors: DescriptorLoop<'a>,
59}
60
61impl<'a> CatSection<'a> {
62    /// Typed view of the CA descriptors (tag 0x09) in the descriptor loop.
63    /// Non-CA descriptors are skipped; a truncated trailing descriptor returns
64    /// an error.
65    pub fn ca_descriptors(&self) -> Result<Vec<CatCaEntry>> {
66        let mut out = Vec::new();
67        let mut pos = 0;
68        while pos + 2 <= self.descriptors.len() {
69            let tag = self.descriptors[pos];
70            let length = self.descriptors[pos + 1] as usize;
71            let end = pos + 2 + length;
72            if end > self.descriptors.len() {
73                return Err(Error::BufferTooShort {
74                    need: end - pos,
75                    have: self.descriptors.len() - pos,
76                    what: "CatSection ca_descriptors truncated descriptor",
77                });
78            }
79            if tag == crate::descriptors::ca::TAG {
80                if let Ok(ca) = CaDescriptor::parse(&self.descriptors[pos..end]) {
81                    out.push(CatCaEntry {
82                        ca_system_id: ca.ca_system_id,
83                        ca_pid: ca.ca_pid,
84                        private_data: ca.private_data.to_vec(),
85                    });
86                }
87            }
88            pos = end;
89        }
90        Ok(out)
91    }
92}
93
94impl<'a> Parse<'a> for CatSection<'a> {
95    type Error = Error;
96
97    fn parse(bytes: &'a [u8]) -> Result<Self> {
98        if bytes.len() < MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN {
99            return Err(Error::BufferTooShort {
100                need: MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN,
101                have: bytes.len(),
102                what: "CatSection",
103            });
104        }
105
106        if bytes[0] != TABLE_ID {
107            return Err(Error::UnexpectedTableId {
108                table_id: bytes[0],
109                what: "CatSection",
110                expected: &[TABLE_ID],
111            });
112        }
113
114        let section_length = (((bytes[1] & 0x0F) as u16) << 8) | bytes[2] as u16;
115        let total = super::check_section_length(
116            bytes.len(),
117            MIN_HEADER_LEN,
118            section_length as usize,
119            MIN_SECTION_LEN,
120        )?;
121
122        // Skip the 2-byte reserved + extension (bytes 3-4), read version+cni at 5,
123        // section/last_section at 6,7. CAT's "table_id_extension" (bytes 3-4) is
124        // reserved per spec — we don't expose it.
125        let version_number = (bytes[5] >> 1) & 0x1F;
126        let current_next_indicator = (bytes[5] & 0x01) != 0;
127        let section_number = bytes[6];
128        let last_section_number = bytes[7];
129
130        // Descriptor loop runs from byte 8 up to (but not including) the 4-byte
131        // CRC. Kept raw — see the field doc; typed CA view via ca_descriptors().
132        let descriptors_end = total - CRC_LEN;
133
134        Ok(CatSection {
135            version_number,
136            current_next_indicator,
137            section_number,
138            last_section_number,
139            descriptors: DescriptorLoop::new(&bytes[8..descriptors_end]),
140        })
141    }
142}
143
144impl Serialize for CatSection<'_> {
145    type Error = Error;
146
147    fn serialized_len(&self) -> usize {
148        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.descriptors.len() + CRC_LEN
149    }
150
151    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
152        let len = self.serialized_len();
153        if buf.len() < len {
154            return Err(Error::OutputBufferTooSmall {
155                need: len,
156                have: buf.len(),
157            });
158        }
159        let section_length = (len - MIN_HEADER_LEN) as u16;
160        buf[0] = TABLE_ID;
161        buf[1] = super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F);
162        buf[2] = (section_length & 0xFF) as u8;
163        // table_id_extension is reserved for the CAT — conventionally 0xFFFF.
164        buf[3] = 0xFF;
165        buf[4] = 0xFF;
166        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
167        buf[6] = self.section_number;
168        buf[7] = self.last_section_number;
169        let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
170        buf[desc_start..desc_start + self.descriptors.len()]
171            .copy_from_slice(self.descriptors.raw());
172        let crc_pos = len - CRC_LEN;
173        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
174        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
175        Ok(len)
176    }
177}
178impl<'a> crate::traits::TableDef<'a> for CatSection<'a> {
179    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
180    const NAME: &'static str = "CONDITIONAL_ACCESS";
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    /// Build a CAT section with the given CA descriptors and placeholder CRC.
188    fn build_cat(version: u8, descriptors: &[u8]) -> Vec<u8> {
189        let section_length: u16 =
190            (EXTENSION_HEADER_LEN as u16) + descriptors.len() as u16 + (CRC_LEN as u16);
191        let mut v = Vec::new();
192        v.push(TABLE_ID);
193        v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
194        v.push((section_length & 0xFF) as u8);
195        // table_id_extension (reserved for CAT) — typically 0xFFFF in the wild.
196        v.extend_from_slice(&[0xFF, 0xFF]);
197        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01); // version + cni=1
198        v.push(0x00); // section_number
199        v.push(0x00); // last_section_number
200        v.extend_from_slice(descriptors);
201        v.extend_from_slice(&[0, 0, 0, 0]); // placeholder CRC
202        v
203    }
204
205    fn ca_descriptor(ca_system_id: u16, ca_pid: u16) -> [u8; 6] {
206        [
207            0x09,
208            0x04,
209            (ca_system_id >> 8) as u8,
210            (ca_system_id & 0xFF) as u8,
211            0xE0 | ((ca_pid >> 8) as u8 & 0x1F),
212            (ca_pid & 0xFF) as u8,
213        ]
214    }
215
216    #[test]
217    fn parse_empty_cat_zero_descriptors() {
218        let bytes = build_cat(5, &[]);
219        let cat = CatSection::parse(&bytes).expect("parse");
220        assert_eq!(cat.version_number, 5);
221        assert!(cat.current_next_indicator);
222        assert!(cat.descriptors.is_empty());
223        assert_eq!(cat.ca_descriptors().unwrap().len(), 0);
224    }
225
226    #[test]
227    fn parse_single_ca_descriptor_extracts_caid_and_pid() {
228        let mut desc = Vec::new();
229        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
230        let bytes = build_cat(0, &desc);
231        let cat = CatSection::parse(&bytes).unwrap();
232        let cas = cat.ca_descriptors().unwrap();
233        assert_eq!(cas.len(), 1);
234        assert_eq!(cas[0].ca_system_id, 0x0500);
235        assert_eq!(cas[0].ca_pid, 0x0050);
236        assert!(cas[0].private_data.is_empty());
237    }
238
239    #[test]
240    fn parse_multiple_ca_descriptors_preserves_order() {
241        let mut desc = Vec::new();
242        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
243        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
244        desc.extend_from_slice(&ca_descriptor(0x0100, 0x0080));
245        let bytes = build_cat(2, &desc);
246        let cat = CatSection::parse(&bytes).unwrap();
247        let cas = cat.ca_descriptors().unwrap();
248        assert_eq!(cas.len(), 3);
249        assert_eq!(cas[0].ca_system_id, 0x0500);
250        assert_eq!(cas[1].ca_system_id, 0x0650);
251        assert_eq!(cas[2].ca_system_id, 0x0100);
252        assert_eq!(cas[1].ca_pid, 0x0062);
253    }
254
255    #[test]
256    fn parse_rejects_wrong_table_id() {
257        let mut bytes = build_cat(0, &[]);
258        bytes[0] = 0x02; // PMT table_id
259        let err = CatSection::parse(&bytes).unwrap_err();
260        assert!(matches!(
261            err,
262            Error::UnexpectedTableId { table_id: 0x02, .. }
263        ));
264    }
265
266    #[test]
267    fn parse_rejects_short_buffer() {
268        let err = CatSection::parse(&[0x01, 0x00]).unwrap_err();
269        assert!(matches!(err, Error::BufferTooShort { .. }));
270    }
271
272    /// §2.4.4.6 permits non-CA descriptors in the CAT loop: the typed view
273    /// skips them, but parse → serialize MUST preserve them byte-for-byte.
274    #[test]
275    fn non_ca_descriptors_skipped_by_view_but_round_trip() {
276        let mut desc = Vec::new();
277        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
278        desc.extend_from_slice(&[0x12, 0x02, 0xAA, 0xBB]); // unknown tag 0x12, len 2
279        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
280        let bytes = build_cat(0, &desc);
281        let cat = CatSection::parse(&bytes).unwrap();
282        let cas = cat.ca_descriptors().unwrap();
283        assert_eq!(cas.len(), 2);
284        assert_eq!(cas[0].ca_system_id, 0x0500);
285        assert_eq!(cas[1].ca_system_id, 0x0650);
286        // The unknown descriptor survives the round trip verbatim.
287        assert_eq!(cat.descriptors.raw(), desc);
288        let mut buf = vec![0u8; cat.serialized_len()];
289        cat.serialize_into(&mut buf).unwrap();
290        let re = CatSection::parse(&buf).unwrap();
291        assert_eq!(re.descriptors.raw(), desc);
292    }
293
294    #[test]
295    fn serialize_round_trip() {
296        let mut desc = Vec::new();
297        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
298        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
299        let bytes = build_cat(3, &desc);
300        let cat = CatSection::parse(&bytes).unwrap();
301        let mut buf = vec![0u8; cat.serialized_len()];
302        cat.serialize_into(&mut buf).unwrap();
303        assert_eq!(CatSection::parse(&buf).unwrap(), cat);
304    }
305
306    #[test]
307    fn table_trait_constants() {
308        assert_eq!(TABLE_ID, 0x01);
309        assert_eq!(PID, 0x0001);
310    }
311
312    /// CAT borrows its descriptor loop (3.0): the loop serializes as the
313    /// typed descriptor sequence and the struct is serialize-only. Verify the
314    /// CA descriptor decodes inside the JSON.
315    #[cfg(feature = "serde")]
316    #[test]
317    fn serde_json_serializes_typed_loop() {
318        let bytes = build_cat(1, &ca_descriptor(0x0500, 0x0050));
319        let cat = CatSection::parse(&bytes).unwrap();
320        let v = serde_json::to_value(&cat).unwrap();
321        let loop_ = v["descriptors"]
322            .as_array()
323            .expect("typed descriptor sequence");
324        assert_eq!(loop_.len(), 1);
325        assert_eq!(loop_[0]["ca"]["ca_system_id"], 0x0500);
326        assert_eq!(loop_[0]["ca"]["ca_pid"], 0x0050);
327    }
328
329    #[test]
330    fn parse_rejects_zero_section_length() {
331        let mut buf = vec![0u8; 64];
332        buf[0] = TABLE_ID;
333        buf[1] = 0xF0;
334        buf[2] = 0x00;
335        for b in &mut buf[3..] {
336            *b = 0xFF;
337        }
338        assert!(matches!(
339            CatSection::parse(&buf).unwrap_err(),
340            Error::SectionLengthOverflow { .. }
341        ));
342    }
343
344    #[test]
345    fn ca_descriptors_rejects_truncated_descriptor() {
346        let mut desc = Vec::new();
347        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
348        desc.push(0x09);
349        desc.push(0x10);
350        let bytes = build_cat(0, &desc);
351        let cat = CatSection::parse(&bytes).unwrap();
352        assert!(matches!(
353            cat.ca_descriptors().unwrap_err(),
354            Error::BufferTooShort {
355                what: "CatSection ca_descriptors truncated descriptor",
356                ..
357            }
358        ));
359    }
360}