Skip to main content

dlms_cosem_kit/transport/
wrapper.rs

1//! The wrapper — DLMS over TCP and UDP.
2//!
3//! Eight bytes in front of the APDU: a version, the sending and receiving service
4//! access points, and a length. Over UDP one datagram is one wrapper PDU; over TCP the
5//! layer must reassemble, because an APDU may arrive in as many segments as the network
6//! feels like.
7
8use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
9
10/// The only wrapper version defined.
11pub const VERSION: u16 = 0x0001;
12
13/// The port IANA assigned to DLMS.
14pub const DEFAULT_PORT: u16 = 4059;
15
16/// The eight-byte wrapper header.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct Header {
19    /// Always [`VERSION`].
20    pub version: u16,
21    /// The sender's service access point — the client SAP in a request.
22    pub source: u16,
23    /// The receiver's service access point — the logical device in a request.
24    pub destination: u16,
25    /// How many bytes of APDU follow.
26    pub length: u16,
27}
28
29impl Header {
30    /// A header for an APDU of `length` bytes.
31    #[must_use]
32    pub const fn new(source: u16, destination: u16, length: u16) -> Self {
33        Self { version: VERSION, source, destination, length }
34    }
35
36    /// The header size, which is fixed.
37    pub const LEN: usize = 8;
38}
39
40impl Encode for Header {
41    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
42        w.write_u16(self.version)?;
43        w.write_u16(self.source)?;
44        w.write_u16(self.destination)?;
45        w.write_u16(self.length)
46    }
47
48    fn encoded_len(&self) -> usize {
49        Self::LEN
50    }
51}
52
53impl<'a> Decode<'a> for Header {
54    fn decode(r: &mut Reader<'a>) -> Result<Self> {
55        let version = r.u16()?;
56        if version != VERSION {
57            return Err(r.err_back(ErrorKind::InvalidValue, 2));
58        }
59        Ok(Self { version, source: r.u16()?, destination: r.u16()?, length: r.u16()? })
60    }
61}
62
63/// A wrapper PDU: a header and the APDU it carries.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct Wpdu<'a> {
66    /// The header.
67    pub header: Header,
68    /// The APDU.
69    pub apdu: &'a [u8],
70}
71
72impl<'a> Wpdu<'a> {
73    /// A PDU carrying `apdu` between two service access points.
74    ///
75    /// # Errors
76    /// When the APDU is longer than the sixteen-bit length field can describe.
77    pub fn new(source: u16, destination: u16, apdu: &'a [u8]) -> Result<Self> {
78        let length = u16::try_from(apdu.len()).map_err(|_| Error::new(ErrorKind::InvalidLength, 0))?;
79        Ok(Self { header: Header::new(source, destination, length), apdu })
80    }
81}
82
83impl Encode for Wpdu<'_> {
84    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
85        self.header.encode(w)?;
86        w.write_bytes(self.apdu)
87    }
88
89    fn encoded_len(&self) -> usize {
90        Header::LEN + self.apdu.len()
91    }
92}
93
94impl<'a> Decode<'a> for Wpdu<'a> {
95    fn decode(r: &mut Reader<'a>) -> Result<Self> {
96        let header = Header::decode(r)?;
97        let apdu = r.take(usize::from(header.length))?;
98        Ok(Self { header, apdu })
99    }
100}
101
102/// Reassembles wrapper PDUs from a TCP stream.
103///
104/// Holds no buffer of its own: the caller keeps the bytes and is told how many were
105/// consumed, which is what lets the same code serve a `Vec` on a head-end and a fixed
106/// array in firmware. Everything a header announces is checked on its eight bytes,
107/// before the caller waits for or buffers the body.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct StreamReassembler {
110    max_apdu: u16,
111    peer: Option<(u16, u16)>,
112}
113
114impl StreamReassembler {
115    /// A reassembler that refuses any PDU claiming more than `max_apdu` bytes.
116    ///
117    /// The length field is attacker-controlled: a peer that announces 65 535 bytes must
118    /// not make the caller hold that much before anything is authenticated. 0 admits
119    /// only empty APDUs.
120    #[must_use]
121    pub const fn new(max_apdu: u16) -> Self {
122        Self { max_apdu, peer: None }
123    }
124
125    /// Also refuse a PDU whose service access points are not `source` → `destination`.
126    ///
127    /// A client expects the meter's replies: `source` is the logical device's port and
128    /// `destination` its own.
129    ///
130    /// ```
131    /// # use dlms_cosem_kit::transport::wrapper::StreamReassembler;
132    /// let r = StreamReassembler::new(1024).with_peer(0x0001, 0x0010);
133    /// // A reply from logical device 2: refused on the header alone.
134    /// assert!(r.next_pdu(&[0x00, 0x01, 0x00, 0x02, 0x00, 0x10, 0x00, 0x05]).is_err());
135    /// ```
136    #[must_use]
137    pub const fn with_peer(self, source: u16, destination: u16) -> Self {
138        Self { peer: Some((source, destination)), ..self }
139    }
140
141    /// The header at the front of `buf`, once its eight bytes are there and pass every
142    /// check. The body need not have arrived.
143    ///
144    /// ```
145    /// # use dlms_cosem_kit::transport::wrapper::StreamReassembler;
146    /// let r = StreamReassembler::new(256);
147    /// let header = r.header(&[0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x00, 0x20]).unwrap().unwrap();
148    /// assert_eq!(header.length, 32); // read exactly 32 more bytes
149    /// assert!(r.header(&[0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x01, 0x01]).is_err()); // 257
150    /// ```
151    ///
152    /// # Errors
153    /// As [`StreamReassembler::next_pdu`].
154    pub fn header(&self, buf: &[u8]) -> Result<Option<Header>> {
155        if buf.len() < Header::LEN {
156            return Ok(None);
157        }
158        let header = Header::decode(&mut Reader::new(buf))?;
159        if let Some((source, destination)) = self.peer {
160            if header.source != source {
161                return Err(Error::new(ErrorKind::InvalidValue, 2));
162            }
163            if header.destination != destination {
164                return Err(Error::new(ErrorKind::InvalidValue, 4));
165            }
166        }
167        if header.length > self.max_apdu {
168            return Err(Error::new(ErrorKind::InvalidLength, 6));
169        }
170        Ok(Some(header))
171    }
172
173    /// The next complete PDU in `buf`, and how many bytes it used.
174    ///
175    /// # Errors
176    /// [`ErrorKind::InvalidValue`] for a bad version (offset 0) or, with
177    /// [`with_peer`](Self::with_peer), the wrong source (offset 2) or destination (offset
178    /// 4); [`ErrorKind::InvalidLength`] when the announced length exceeds the maximum.
179    pub fn next_pdu<'b>(&self, buf: &'b [u8]) -> Result<Option<(Wpdu<'b>, usize)>> {
180        let Some(header) = self.header(buf)? else {
181            return Ok(None);
182        };
183        let total = Header::LEN + usize::from(header.length);
184        match buf.get(Header::LEN..total) {
185            Some(apdu) => Ok(Some((Wpdu { header, apdu }, total))),
186            None => Ok(None),
187        }
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::codec::SliceWriter;
195
196    #[test]
197    fn the_header_is_eight_bytes_big_endian() {
198        let w = Wpdu::new(0x0010, 0x0001, &[0xC0, 0x01, 0x81]).unwrap();
199        let mut buf = [0u8; 32];
200        let mut sw = SliceWriter::new(&mut buf);
201        w.encode(&mut sw).unwrap();
202        assert_eq!(sw.as_slice(), [0x00, 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x03, 0xC0, 0x01, 0x81]);
203        assert_eq!(Wpdu::from_bytes(sw.as_slice()).unwrap(), w);
204    }
205
206    #[test]
207    fn a_wrong_version_is_refused() {
208        assert_eq!(
209            Header::from_bytes(&[0x00, 0x02, 0, 0x10, 0, 1, 0, 0]).unwrap_err().kind,
210            ErrorKind::InvalidValue
211        );
212    }
213
214    #[test]
215    fn the_reassembler_waits_for_every_byte() {
216        let w = Wpdu::new(0x0010, 0x0001, &[0xAA; 20]).unwrap();
217        let mut buf = [0u8; 64];
218        let mut sw = SliceWriter::new(&mut buf);
219        w.encode(&mut sw).unwrap();
220        let n = sw.written();
221        let r = StreamReassembler::new(1024);
222        for split in 0..n {
223            assert!(r.next_pdu(&buf[..split]).unwrap().is_none(), "cut at {split}");
224        }
225        let (pdu, used) = r.next_pdu(&buf[..n]).unwrap().unwrap();
226        assert_eq!(used, n);
227        assert_eq!(pdu.apdu.len(), 20);
228    }
229
230    #[test]
231    fn an_oversized_announcement_is_refused_before_it_is_buffered() {
232        let r = StreamReassembler::new(256);
233        let header = [0x00, 0x01, 0x00, 0x10, 0x00, 0x01, 0xFF, 0xFF];
234        assert_eq!(r.next_pdu(&header).unwrap_err().kind, ErrorKind::InvalidLength);
235    }
236
237    /// 003-checked-clock-and-links/SR-001
238    #[test]
239    fn a_reply_from_the_wrong_peer_is_refused_on_its_header() {
240        let r = StreamReassembler::new(1024).with_peer(0x0001, 0x0010);
241        let good = [0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x00, 0x03];
242        assert_eq!(r.header(&good).unwrap(), Some(Header::new(0x0001, 0x0010, 3)));
243        assert_eq!(r.next_pdu(&good).unwrap(), None, "the body is still missing");
244        let wrong_source = [0x00, 0x01, 0x00, 0x02, 0x00, 0x10, 0x00, 0x03];
245        let e = r.next_pdu(&wrong_source).unwrap_err();
246        assert_eq!((e.kind, e.offset), (ErrorKind::InvalidValue, 2));
247        let wrong_destination = [0x00, 0x01, 0x00, 0x01, 0x00, 0x11, 0x00, 0x03];
248        let e = r.next_pdu(&wrong_destination).unwrap_err();
249        assert_eq!((e.kind, e.offset), (ErrorKind::InvalidValue, 4));
250        // Without a peer any addresses pass.
251        assert!(StreamReassembler::new(1024).header(&wrong_source).unwrap().is_some());
252    }
253
254    /// 003-checked-clock-and-links/SR-002
255    #[test]
256    fn a_zero_maximum_admits_only_empty_apdus() {
257        let r = StreamReassembler::new(0);
258        assert!(r.next_pdu(&[0x00, 0x01, 0, 0x10, 0, 1, 0, 0]).unwrap().is_some());
259        assert_eq!(
260            r.next_pdu(&[0x00, 0x01, 0, 0x10, 0, 1, 0, 1]).unwrap_err().kind,
261            ErrorKind::InvalidLength
262        );
263    }
264
265    #[test]
266    fn two_pdus_back_to_back_are_returned_one_at_a_time() {
267        let mut stream = alloc::vec::Vec::new();
268        for i in 0..2u8 {
269            let body = [i, i, i];
270            let w = Wpdu::new(0x0010, 0x0001, &body).unwrap();
271            w.encode(&mut stream).unwrap();
272        }
273        let r = StreamReassembler::new(1024);
274        let (first, used) = r.next_pdu(&stream).unwrap().unwrap();
275        assert_eq!(first.apdu, &[0, 0, 0]);
276        let (second, _) = r.next_pdu(&stream[used..]).unwrap().unwrap();
277        assert_eq!(second.apdu, &[1, 1, 1]);
278    }
279}