Skip to main content

dvb_si/descriptors/
ca.rs

1//! Conditional Access (CA) Descriptor — ISO/IEC 13818-1 §2.6.16 (tag 0x09).
2//!
3//! Identifies a conditional access system and the PID carrying ECM/EMM data
4//! for that system. Optional private data may follow the standard fields.
5
6use super::descriptor_body;
7use crate::error::{Error, Result};
8use dvb_common::{Parse, Serialize};
9
10/// Descriptor tag for CA_descriptor.
11pub const TAG: u8 = 0x09;
12const HEADER_LEN: usize = 2;
13const MIN_BODY_LEN: usize = 4; // ca_system_id (2) + ca_pid (2)
14
15/// Conditional Access Descriptor.
16///
17/// Carried in the program-level or ES-level descriptor loops of a PMT, or in
18/// the CAT. Identifies the CA system and the PID where Entitlement Control
19/// Messages (ECMs) or Entitlement Management Messages (EMMs) can be found.
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize))]
22#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
23pub struct CaDescriptor<'a> {
24    /// Conditional Access System ID.
25    ///
26    /// Well-known CAIDs:
27    ///   0x0100  Seca/Mediaguard
28    ///   0x0500  Viaccess
29    ///   0x0600  Irdeto
30    ///   0x0B00  Conax
31    ///   0x0D00  Cryptoworks
32    ///   0x0E00  PowerVu
33    ///   0x0F00  Tandberg/Clear
34    ///   0x1700  Nagravision 2
35    ///   0x1800  Nagravision 3
36    ///   0x2600  BISS
37    pub ca_system_id: u16,
38
39    /// PID carrying ECM/EMM data for this CA system.
40    /// Bits `[12:0]` of the 2-byte field; upper 3 bits are reserved.
41    pub ca_pid: u16,
42
43    /// Optional private data following the standard CA descriptor fields.
44    pub private_data: &'a [u8],
45}
46
47impl<'a> Parse<'a> for CaDescriptor<'a> {
48    type Error = crate::error::Error;
49
50    fn parse(bytes: &'a [u8]) -> Result<Self> {
51        let body = descriptor_body(
52            bytes,
53            TAG,
54            "CaDescriptor",
55            "unexpected tag for CA_descriptor",
56        )?;
57        if body.len() < MIN_BODY_LEN {
58            return Err(Error::InvalidDescriptor {
59                tag: TAG,
60                reason: "CA_descriptor length too short for mandatory fields",
61            });
62        }
63        let ca_system_id = u16::from_be_bytes([body[0], body[1]]);
64        // ca_pid: upper 3 bits are reserved (should be 0b111), lower 13 bits are the PID
65        let ca_pid = ((u16::from(body[2]) & 0x1F) << 8) | u16::from(body[3]);
66        let private_data = if body.len() > MIN_BODY_LEN {
67            &body[MIN_BODY_LEN..]
68        } else {
69            &[]
70        };
71        Ok(Self {
72            ca_system_id,
73            ca_pid,
74            private_data,
75        })
76    }
77}
78
79impl Serialize for CaDescriptor<'_> {
80    type Error = crate::error::Error;
81
82    fn serialized_len(&self) -> usize {
83        HEADER_LEN + MIN_BODY_LEN + self.private_data.len()
84    }
85
86    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
87        let len = self.serialized_len();
88        if buf.len() < len {
89            return Err(Error::OutputBufferTooSmall {
90                need: len,
91                have: buf.len(),
92            });
93        }
94        buf[0] = TAG;
95        buf[1] = (len - HEADER_LEN) as u8;
96        buf[2] = (self.ca_system_id >> 8) as u8;
97        buf[3] = (self.ca_system_id & 0xFF) as u8;
98        // ca_pid with reserved upper 3 bits set to 1
99        buf[4] = 0xE0 | ((self.ca_pid >> 8) as u8);
100        buf[5] = (self.ca_pid & 0xFF) as u8;
101        if !self.private_data.is_empty() {
102            buf[HEADER_LEN + MIN_BODY_LEN..len].copy_from_slice(self.private_data);
103        }
104        Ok(len)
105    }
106}
107impl<'a> crate::traits::DescriptorDef<'a> for CaDescriptor<'a> {
108    const TAG: u8 = TAG;
109    const NAME: &'static str = "CA";
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn parse_viaccess_ecm_pid() {
118        // tag=0x09, len=4, CAID=0x0500 (Viaccess), PID=0x0101
119        let bytes = [TAG, 4, 0x05, 0x00, 0xE1, 0x01];
120        let d = CaDescriptor::parse(&bytes).unwrap();
121        assert_eq!(d.ca_system_id, 0x0500);
122        assert_eq!(d.ca_pid, 0x0101);
123        assert!(d.private_data.is_empty());
124    }
125
126    #[test]
127    fn parse_with_private_data() {
128        // tag=0x09, len=6, CAID=0x0500, PID=0x0101, private=[0xAA, 0xBB]
129        let bytes = [TAG, 6, 0x05, 0x00, 0xE1, 0x01, 0xAA, 0xBB];
130        let d = CaDescriptor::parse(&bytes).unwrap();
131        assert_eq!(d.ca_system_id, 0x0500);
132        assert_eq!(d.ca_pid, 0x0101);
133        assert_eq!(d.private_data, &[0xAA, 0xBB]);
134    }
135
136    #[test]
137    fn parse_rejects_wrong_tag() {
138        let err = CaDescriptor::parse(&[0x0A, 4, 0x05, 0x00, 0xE1, 0x01]).unwrap_err();
139        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x0A, .. }));
140    }
141
142    #[test]
143    fn parse_rejects_short_header() {
144        let err = CaDescriptor::parse(&[TAG]).unwrap_err();
145        assert!(matches!(err, Error::BufferTooShort { .. }));
146    }
147
148    #[test]
149    fn parse_rejects_length_too_short() {
150        let bytes = [TAG, 3, 0x05, 0x00, 0xE1];
151        let err = CaDescriptor::parse(&bytes).unwrap_err();
152        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
153    }
154
155    #[test]
156    fn parse_rejects_length_overflow() {
157        let bytes = [TAG, 10, 0x05, 0x00, 0xE1, 0x01];
158        let err = CaDescriptor::parse(&bytes).unwrap_err();
159        assert!(matches!(err, Error::BufferTooShort { .. }));
160    }
161
162    #[test]
163    fn serialize_round_trip() {
164        let d = CaDescriptor {
165            ca_system_id: 0x1800,
166            ca_pid: 0x0200,
167            private_data: &[0xDE, 0xAD],
168        };
169        let mut buf = vec![0u8; d.serialized_len()];
170        d.serialize_into(&mut buf).unwrap();
171        let reparsed = CaDescriptor::parse(&buf).unwrap();
172        assert_eq!(d, reparsed);
173    }
174
175    #[test]
176    fn serialize_round_trip_no_private_data() {
177        let d = CaDescriptor {
178            ca_system_id: 0x0500,
179            ca_pid: 0x0101,
180            private_data: &[],
181        };
182        let mut buf = vec![0u8; d.serialized_len()];
183        d.serialize_into(&mut buf).unwrap();
184        let reparsed = CaDescriptor::parse(&buf).unwrap();
185        assert_eq!(d, reparsed);
186    }
187
188    #[test]
189    fn serialize_rejects_small_buffer() {
190        let d = CaDescriptor {
191            ca_system_id: 0x0500,
192            ca_pid: 0x0101,
193            private_data: &[],
194        };
195        let mut tiny = vec![0u8; 3];
196        let err = d.serialize_into(&mut tiny).unwrap_err();
197        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
198    }
199
200    #[test]
201    fn descriptor_length_matches_payload() {
202        let d = CaDescriptor {
203            ca_system_id: 0x0500,
204            ca_pid: 0x0101,
205            private_data: &[0xAA],
206        };
207        assert_eq!(d.serialized_len() - 2, 5);
208    }
209}