dlms_cosem_kit/transport/
wrapper.rs1use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
9
10pub const VERSION: u16 = 0x0001;
12
13pub const DEFAULT_PORT: u16 = 4059;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct Header {
19 pub version: u16,
21 pub source: u16,
23 pub destination: u16,
25 pub length: u16,
27}
28
29impl Header {
30 #[must_use]
32 pub const fn new(source: u16, destination: u16, length: u16) -> Self {
33 Self { version: VERSION, source, destination, length }
34 }
35
36 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct Wpdu<'a> {
66 pub header: Header,
68 pub apdu: &'a [u8],
70}
71
72impl<'a> Wpdu<'a> {
73 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct StreamReassembler {
110 max_apdu: u16,
111 peer: Option<(u16, u16)>,
112}
113
114impl StreamReassembler {
115 #[must_use]
121 pub const fn new(max_apdu: u16) -> Self {
122 Self { max_apdu, peer: None }
123 }
124
125 #[must_use]
137 pub const fn with_peer(self, source: u16, destination: u16) -> Self {
138 Self { peer: Some((source, destination)), ..self }
139 }
140
141 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 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 #[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 assert!(StreamReassembler::new(1024).header(&wrong_source).unwrap().is_some());
252 }
253
254 #[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}