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/// Best-effort, non-exhaustive mapping from CA system ID to a human-readable
16/// name.  Verified ranges from the DVB Services registry.
17#[must_use]
18pub fn ca_system_name(ca_system_id: u16) -> Option<&'static str> {
19    match ca_system_id {
20        0x0100..=0x01FF => Some("Seca / Mediaguard"),
21        0x0500..=0x05FF => Some("Viaccess"),
22        0x0600..=0x06FF => Some("Irdeto"),
23        0x0700..=0x07FF => Some("DigiCipher 2"),
24        0x0900..=0x09FF => Some("NDS / Videoguard"),
25        0x0B00..=0x0BFF => Some("Conax"),
26        0x0D00..=0x0DFF => Some("Cryptoworks"),
27        0x0E00..=0x0EFF => Some("PowerVu"),
28        0x1700..=0x17FF => Some("Verimatrix (BetaCrypt)"),
29        0x1800..=0x18FF => Some("Nagravision"),
30        0x2600..=0x26FF => Some("BISS"),
31        0x4AD4..=0x4AD5 => Some("Widevine"),
32        0x4AE0..=0x4AE1 => Some("DRE-Crypt"),
33        0x5601..=0x5604 => Some("Verimatrix VCAS"),
34        _ => None,
35    }
36}
37
38/// Conditional Access Descriptor.
39///
40/// Carried in the program-level or ES-level descriptor loops of a PMT, or in
41/// the CAT. Identifies the CA system and the PID where Entitlement Control
42/// Messages (ECMs) or Entitlement Management Messages (EMMs) can be found.
43#[derive(Debug, Clone, PartialEq, Eq)]
44#[cfg_attr(feature = "serde", derive(serde::Serialize))]
45#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
46pub struct CaDescriptor<'a> {
47    /// Conditional Access System ID.
48    ///
49    /// Well-known CAID ranges (DVB Services registry):
50    ///   0x0100–0x01FF  Seca / Mediaguard
51    ///   0x0500–0x05FF  Viaccess
52    ///   0x0600–0x06FF  Irdeto
53    ///   0x0700–0x07FF  DigiCipher 2
54    ///   0x0900–0x09FF  NDS / Videoguard
55    ///   0x0B00–0x0BFF  Conax
56    ///   0x0D00–0x0DFF  Cryptoworks
57    ///   0x0E00–0x0EFF  PowerVu
58    ///   0x1700–0x17FF  Verimatrix (BetaCrypt)
59    ///   0x1800–0x18FF  Nagravision
60    ///   0x2600–0x26FF  BISS
61    ///   0x4AD4–0x4AD5  Widevine
62    ///   0x4AE0–0x4AE1  DRE-Crypt
63    ///   0x5601–0x5604  Verimatrix VCAS
64    pub ca_system_id: u16,
65
66    /// PID carrying ECM/EMM data for this CA system.
67    /// Bits `[12:0]` of the 2-byte field; upper 3 bits are reserved.
68    pub ca_pid: u16,
69
70    /// Optional private data following the standard CA descriptor fields.
71    pub private_data: &'a [u8],
72}
73
74impl<'a> Parse<'a> for CaDescriptor<'a> {
75    type Error = crate::error::Error;
76
77    fn parse(bytes: &'a [u8]) -> Result<Self> {
78        let body = descriptor_body(
79            bytes,
80            TAG,
81            "CaDescriptor",
82            "unexpected tag for CA_descriptor",
83        )?;
84        if body.len() < MIN_BODY_LEN {
85            return Err(Error::InvalidDescriptor {
86                tag: TAG,
87                reason: "CA_descriptor length too short for mandatory fields",
88            });
89        }
90        let ca_system_id = u16::from_be_bytes([body[0], body[1]]);
91        // ca_pid: upper 3 bits are reserved (should be 0b111), lower 13 bits are the PID
92        let ca_pid = ((u16::from(body[2]) & 0x1F) << 8) | u16::from(body[3]);
93        let private_data = if body.len() > MIN_BODY_LEN {
94            &body[MIN_BODY_LEN..]
95        } else {
96            &[]
97        };
98        Ok(Self {
99            ca_system_id,
100            ca_pid,
101            private_data,
102        })
103    }
104}
105
106impl Serialize for CaDescriptor<'_> {
107    type Error = crate::error::Error;
108
109    fn serialized_len(&self) -> usize {
110        HEADER_LEN + MIN_BODY_LEN + self.private_data.len()
111    }
112
113    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
114        let len = self.serialized_len();
115        if buf.len() < len {
116            return Err(Error::OutputBufferTooSmall {
117                need: len,
118                have: buf.len(),
119            });
120        }
121        buf[0] = TAG;
122        buf[1] = (len - HEADER_LEN) as u8;
123        buf[2] = (self.ca_system_id >> 8) as u8;
124        buf[3] = (self.ca_system_id & 0xFF) as u8;
125        // ca_pid with reserved upper 3 bits set to 1
126        buf[4] = 0xE0 | ((self.ca_pid >> 8) as u8);
127        buf[5] = (self.ca_pid & 0xFF) as u8;
128        if !self.private_data.is_empty() {
129            buf[HEADER_LEN + MIN_BODY_LEN..len].copy_from_slice(self.private_data);
130        }
131        Ok(len)
132    }
133}
134impl<'a> crate::traits::DescriptorDef<'a> for CaDescriptor<'a> {
135    const TAG: u8 = TAG;
136    const NAME: &'static str = "CA";
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn parse_viaccess_ecm_pid() {
145        // tag=0x09, len=4, CAID=0x0500 (Viaccess), PID=0x0101
146        let bytes = [TAG, 4, 0x05, 0x00, 0xE1, 0x01];
147        let d = CaDescriptor::parse(&bytes).unwrap();
148        assert_eq!(d.ca_system_id, 0x0500);
149        assert_eq!(d.ca_pid, 0x0101);
150        assert!(d.private_data.is_empty());
151    }
152
153    #[test]
154    fn parse_with_private_data() {
155        // tag=0x09, len=6, CAID=0x0500, PID=0x0101, private=[0xAA, 0xBB]
156        let bytes = [TAG, 6, 0x05, 0x00, 0xE1, 0x01, 0xAA, 0xBB];
157        let d = CaDescriptor::parse(&bytes).unwrap();
158        assert_eq!(d.ca_system_id, 0x0500);
159        assert_eq!(d.ca_pid, 0x0101);
160        assert_eq!(d.private_data, &[0xAA, 0xBB]);
161    }
162
163    #[test]
164    fn parse_rejects_wrong_tag() {
165        let err = CaDescriptor::parse(&[0x0A, 4, 0x05, 0x00, 0xE1, 0x01]).unwrap_err();
166        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x0A, .. }));
167    }
168
169    #[test]
170    fn parse_rejects_short_header() {
171        let err = CaDescriptor::parse(&[TAG]).unwrap_err();
172        assert!(matches!(err, Error::BufferTooShort { .. }));
173    }
174
175    #[test]
176    fn parse_rejects_length_too_short() {
177        let bytes = [TAG, 3, 0x05, 0x00, 0xE1];
178        let err = CaDescriptor::parse(&bytes).unwrap_err();
179        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
180    }
181
182    #[test]
183    fn parse_rejects_length_overflow() {
184        let bytes = [TAG, 10, 0x05, 0x00, 0xE1, 0x01];
185        let err = CaDescriptor::parse(&bytes).unwrap_err();
186        assert!(matches!(err, Error::BufferTooShort { .. }));
187    }
188
189    #[test]
190    fn serialize_round_trip() {
191        let d = CaDescriptor {
192            ca_system_id: 0x1800,
193            ca_pid: 0x0200,
194            private_data: &[0xDE, 0xAD],
195        };
196        let mut buf = vec![0u8; d.serialized_len()];
197        d.serialize_into(&mut buf).unwrap();
198        let reparsed = CaDescriptor::parse(&buf).unwrap();
199        assert_eq!(d, reparsed);
200    }
201
202    #[test]
203    fn serialize_round_trip_no_private_data() {
204        let d = CaDescriptor {
205            ca_system_id: 0x0500,
206            ca_pid: 0x0101,
207            private_data: &[],
208        };
209        let mut buf = vec![0u8; d.serialized_len()];
210        d.serialize_into(&mut buf).unwrap();
211        let reparsed = CaDescriptor::parse(&buf).unwrap();
212        assert_eq!(d, reparsed);
213    }
214
215    #[test]
216    fn serialize_rejects_small_buffer() {
217        let d = CaDescriptor {
218            ca_system_id: 0x0500,
219            ca_pid: 0x0101,
220            private_data: &[],
221        };
222        let mut tiny = vec![0u8; 3];
223        let err = d.serialize_into(&mut tiny).unwrap_err();
224        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
225    }
226
227    #[test]
228    fn descriptor_length_matches_payload() {
229        let d = CaDescriptor {
230            ca_system_id: 0x0500,
231            ca_pid: 0x0101,
232            private_data: &[0xAA],
233        };
234        assert_eq!(d.serialized_len() - 2, 5);
235    }
236
237    #[test]
238    fn ca_system_name_verified_ranges() {
239        assert_eq!(ca_system_name(0x0100), Some("Seca / Mediaguard"));
240        assert_eq!(ca_system_name(0x01FF), Some("Seca / Mediaguard"));
241        assert_eq!(ca_system_name(0x0500), Some("Viaccess"));
242        assert_eq!(ca_system_name(0x05FF), Some("Viaccess"));
243        assert_eq!(ca_system_name(0x0600), Some("Irdeto"));
244        assert_eq!(ca_system_name(0x0700), Some("DigiCipher 2"));
245        assert_eq!(ca_system_name(0x0900), Some("NDS / Videoguard"));
246        assert_eq!(ca_system_name(0x0B00), Some("Conax"));
247        assert_eq!(ca_system_name(0x0D00), Some("Cryptoworks"));
248        assert_eq!(ca_system_name(0x0E00), Some("PowerVu"));
249        assert_eq!(ca_system_name(0x1700), Some("Verimatrix (BetaCrypt)"));
250        assert_eq!(ca_system_name(0x1800), Some("Nagravision"));
251        assert_eq!(ca_system_name(0x2600), Some("BISS"));
252        assert_eq!(ca_system_name(0x4AD4), Some("Widevine"));
253        assert_eq!(ca_system_name(0x4AE0), Some("DRE-Crypt"));
254        assert_eq!(ca_system_name(0x5601), Some("Verimatrix VCAS"));
255    }
256
257    #[test]
258    fn ca_system_name_removed_entries_return_none() {
259        assert_eq!(ca_system_name(0x0000), None);
260        assert_eq!(ca_system_name(0x5605), None);
261        assert_eq!(ca_system_name(0x4AE2), None);
262        assert_eq!(ca_system_name(0x0F00), None);
263    }
264
265    #[test]
266    fn ca_system_name_unknown() {
267        assert_eq!(ca_system_name(0xdead), None);
268    }
269}