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 crate::error::{Error, Result};
7use crate::traits::Descriptor;
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, serde::Deserialize))]
22pub struct CaDescriptor<'a> {
23    /// Conditional Access System ID.
24    ///
25    /// Well-known CAIDs:
26    ///   0x0100  Seca/Mediaguard
27    ///   0x0500  Viaccess
28    ///   0x0600  Irdeto
29    ///   0x0B00  Conax
30    ///   0x0D00  Cryptoworks
31    ///   0x0E00  PowerVu
32    ///   0x0F00  Tandberg/Clear
33    ///   0x1700  Nagravision 2
34    ///   0x1800  Nagravision 3
35    ///   0x2600  BISS
36    pub ca_system_id: u16,
37
38    /// PID carrying ECM/EMM data for this CA system.
39    /// Bits [12:0] of the 2-byte field; upper 3 bits are reserved.
40    pub ca_pid: u16,
41
42    /// Optional private data following the standard CA descriptor fields.
43    #[cfg_attr(feature = "serde", serde(borrow))]
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        if bytes.len() < HEADER_LEN {
52            return Err(Error::BufferTooShort {
53                need: HEADER_LEN,
54                have: bytes.len(),
55                what: "CaDescriptor header",
56            });
57        }
58        if bytes[0] != TAG {
59            return Err(Error::InvalidDescriptor {
60                tag: bytes[0],
61                reason: "unexpected tag for CA_descriptor",
62            });
63        }
64        let length = bytes[1] as usize;
65        if length < MIN_BODY_LEN {
66            return Err(Error::InvalidDescriptor {
67                tag: TAG,
68                reason: "CA_descriptor length too short for mandatory fields",
69            });
70        }
71        let total = HEADER_LEN + length;
72        if bytes.len() < total {
73            return Err(Error::BufferTooShort {
74                need: total,
75                have: bytes.len(),
76                what: "CaDescriptor body",
77            });
78        }
79        let body = &bytes[HEADER_LEN..total];
80        let ca_system_id = u16::from_be_bytes([body[0], body[1]]);
81        // ca_pid: upper 3 bits are reserved (should be 0b111), lower 13 bits are the PID
82        let ca_pid = ((u16::from(body[2]) & 0x1F) << 8) | u16::from(body[3]);
83        let private_data = if body.len() > MIN_BODY_LEN {
84            &body[MIN_BODY_LEN..]
85        } else {
86            &[]
87        };
88        Ok(Self {
89            ca_system_id,
90            ca_pid,
91            private_data,
92        })
93    }
94}
95
96impl Serialize for CaDescriptor<'_> {
97    type Error = crate::error::Error;
98
99    fn serialized_len(&self) -> usize {
100        HEADER_LEN + MIN_BODY_LEN + self.private_data.len()
101    }
102
103    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
104        let len = self.serialized_len();
105        if buf.len() < len {
106            return Err(Error::OutputBufferTooSmall {
107                need: len,
108                have: buf.len(),
109            });
110        }
111        buf[0] = TAG;
112        buf[1] = (len - HEADER_LEN) as u8;
113        buf[2] = (self.ca_system_id >> 8) as u8;
114        buf[3] = (self.ca_system_id & 0xFF) as u8;
115        // ca_pid with reserved upper 3 bits set to 1
116        buf[4] = 0xE0 | ((self.ca_pid >> 8) as u8);
117        buf[5] = (self.ca_pid & 0xFF) as u8;
118        if !self.private_data.is_empty() {
119            buf[HEADER_LEN + MIN_BODY_LEN..len].copy_from_slice(self.private_data);
120        }
121        Ok(len)
122    }
123}
124
125impl<'a> Descriptor<'a> for CaDescriptor<'a> {
126    const TAG: u8 = TAG;
127
128    fn descriptor_length(&self) -> u8 {
129        (self.serialized_len() - HEADER_LEN) as u8
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn parse_viaccess_ecm_pid() {
139        // tag=0x09, len=4, CAID=0x0500 (Viaccess), PID=0x0101
140        let bytes = [TAG, 4, 0x05, 0x00, 0xE1, 0x01];
141        let d = CaDescriptor::parse(&bytes).unwrap();
142        assert_eq!(d.ca_system_id, 0x0500);
143        assert_eq!(d.ca_pid, 0x0101);
144        assert!(d.private_data.is_empty());
145    }
146
147    #[test]
148    fn parse_with_private_data() {
149        // tag=0x09, len=6, CAID=0x0500, PID=0x0101, private=[0xAA, 0xBB]
150        let bytes = [TAG, 6, 0x05, 0x00, 0xE1, 0x01, 0xAA, 0xBB];
151        let d = CaDescriptor::parse(&bytes).unwrap();
152        assert_eq!(d.ca_system_id, 0x0500);
153        assert_eq!(d.ca_pid, 0x0101);
154        assert_eq!(d.private_data, &[0xAA, 0xBB]);
155    }
156
157    #[test]
158    fn parse_rejects_wrong_tag() {
159        let err = CaDescriptor::parse(&[0x0A, 4, 0x05, 0x00, 0xE1, 0x01]).unwrap_err();
160        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x0A, .. }));
161    }
162
163    #[test]
164    fn parse_rejects_short_header() {
165        let err = CaDescriptor::parse(&[TAG]).unwrap_err();
166        assert!(matches!(err, Error::BufferTooShort { .. }));
167    }
168
169    #[test]
170    fn parse_rejects_length_too_short() {
171        let bytes = [TAG, 3, 0x05, 0x00, 0xE1];
172        let err = CaDescriptor::parse(&bytes).unwrap_err();
173        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
174    }
175
176    #[test]
177    fn parse_rejects_length_overflow() {
178        let bytes = [TAG, 10, 0x05, 0x00, 0xE1, 0x01];
179        let err = CaDescriptor::parse(&bytes).unwrap_err();
180        assert!(matches!(err, Error::BufferTooShort { .. }));
181    }
182
183    #[test]
184    fn serialize_round_trip() {
185        let d = CaDescriptor {
186            ca_system_id: 0x1800,
187            ca_pid: 0x0200,
188            private_data: &[0xDE, 0xAD],
189        };
190        let mut buf = vec![0u8; d.serialized_len()];
191        d.serialize_into(&mut buf).unwrap();
192        let reparsed = CaDescriptor::parse(&buf).unwrap();
193        assert_eq!(d, reparsed);
194    }
195
196    #[test]
197    fn serialize_round_trip_no_private_data() {
198        let d = CaDescriptor {
199            ca_system_id: 0x0500,
200            ca_pid: 0x0101,
201            private_data: &[],
202        };
203        let mut buf = vec![0u8; d.serialized_len()];
204        d.serialize_into(&mut buf).unwrap();
205        let reparsed = CaDescriptor::parse(&buf).unwrap();
206        assert_eq!(d, reparsed);
207    }
208
209    #[test]
210    fn serialize_rejects_small_buffer() {
211        let d = CaDescriptor {
212            ca_system_id: 0x0500,
213            ca_pid: 0x0101,
214            private_data: &[],
215        };
216        let mut tiny = vec![0u8; 3];
217        let err = d.serialize_into(&mut tiny).unwrap_err();
218        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
219    }
220
221    #[test]
222    fn descriptor_length_matches_payload() {
223        let d = CaDescriptor {
224            ca_system_id: 0x0500,
225            ca_pid: 0x0101,
226            private_data: &[0xAA],
227        };
228        assert_eq!(d.descriptor_length(), 5);
229    }
230}