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