Skip to main content

spodes_rs/transport/
wrapper.rs

1//! The DLMS/COSEM wrapper sub-layer (IEC 62056-47).
2//!
3//! The wrapper carries an xDLMS APDU over a connection-oriented (TCP) or
4//! connectionless (UDP) transport by prefixing it with an 8-octet header:
5//!
6//! ```text
7//! +---------+-------------+------------------+--------+
8//! | version | source wPort| destination wPort| length |
9//! |  2 oct  |    2 oct    |      2 oct       | 2 oct  |
10//! +---------+-------------+------------------+--------+
11//! ```
12//!
13//! All fields are big-endian; `length` is the size of the APDU that follows.
14//! The wrapper is defined only over TCP/UDP, so [`Wrapper`] is bounded on
15//! [`crate::transport::NetworkTransport`].
16
17use std::io;
18
19#[cfg(feature = "tracing")]
20use tracing::trace;
21
22use super::{DataLinkLayer, NetworkTransport, PhysicalTransport};
23
24/// The only defined wrapper protocol version.
25pub const WRAPPER_VERSION: u16 = 0x0001;
26
27/// The 8-octet wrapper header.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct WrapperHeader {
30    /// Protocol version (always [`WRAPPER_VERSION`]).
31    pub version: u16,
32    /// Source wPort (the sender's SAP).
33    pub source: u16,
34    /// Destination wPort (the receiver's SAP).
35    pub destination: u16,
36    /// Length of the APDU that follows the header.
37    pub length: u16,
38}
39
40/// Errors that can occur while decoding a wrapper PDU.
41#[derive(Debug, PartialEq, Eq)]
42pub enum WrapperError {
43    /// Fewer than 8 octets were available for the header.
44    TooShort,
45    /// The version field did not equal [`WRAPPER_VERSION`].
46    UnsupportedVersion(u16),
47    /// The buffer did not contain `length` octets after the header.
48    LengthMismatch {
49        /// The length declared in the header.
50        declared: usize,
51        /// The number of APDU octets actually present.
52        actual: usize,
53    },
54}
55
56impl std::fmt::Display for WrapperError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            WrapperError::TooShort => write!(f, "wrapper header is shorter than 8 octets"),
60            WrapperError::UnsupportedVersion(v) => write!(f, "unsupported wrapper version {v:#06x}"),
61            WrapperError::LengthMismatch { declared, actual } => {
62                write!(f, "wrapper length mismatch: declared {declared}, actual {actual}")
63            }
64        }
65    }
66}
67
68impl std::error::Error for WrapperError {}
69
70impl From<WrapperError> for io::Error {
71    fn from(e: WrapperError) -> Self {
72        io::Error::new(io::ErrorKind::InvalidData, e)
73    }
74}
75
76impl WrapperHeader {
77    /// Appends the header to `buf` (big-endian).
78    pub fn encode(&self, buf: &mut Vec<u8>) {
79        buf.extend_from_slice(&self.version.to_be_bytes());
80        buf.extend_from_slice(&self.source.to_be_bytes());
81        buf.extend_from_slice(&self.destination.to_be_bytes());
82        buf.extend_from_slice(&self.length.to_be_bytes());
83    }
84
85    /// Parses a header from the first 8 octets of `bytes`.
86    pub fn decode(bytes: &[u8]) -> Result<WrapperHeader, WrapperError> {
87        if bytes.len() < 8 {
88            return Err(WrapperError::TooShort);
89        }
90        let version = u16::from_be_bytes([bytes[0], bytes[1]]);
91        if version != WRAPPER_VERSION {
92            return Err(WrapperError::UnsupportedVersion(version));
93        }
94        Ok(WrapperHeader {
95            version,
96            source: u16::from_be_bytes([bytes[2], bytes[3]]),
97            destination: u16::from_be_bytes([bytes[4], bytes[5]]),
98            length: u16::from_be_bytes([bytes[6], bytes[7]]),
99        })
100    }
101}
102
103/// Builds a complete wrapper PDU (header + APDU).
104///
105/// # Panics
106/// Panics (debug builds only) if `apdu` exceeds 65535 octets: the wrapper
107/// header's length field (IEC 62056-47) is 16 bits wide, and callers are
108/// expected to keep APDUs under the negotiated max-PDU size (a few KB at
109/// most in this crate) via GET/SET-WITH-DATABLOCK segmentation.
110pub fn encode(source: u16, destination: u16, apdu: &[u8]) -> Vec<u8> {
111    debug_assert!(apdu.len() <= usize::from(u16::MAX), "APDU exceeds the 16-bit wrapper length field");
112    #[allow(clippy::cast_possible_truncation)]
113    let length = apdu.len() as u16;
114    let header = WrapperHeader { version: WRAPPER_VERSION, source, destination, length };
115    let mut buf = Vec::with_capacity(8 + apdu.len());
116    header.encode(&mut buf);
117    buf.extend_from_slice(apdu);
118    buf
119}
120
121/// Parses a complete wrapper PDU, returning the header and the APDU.
122pub fn decode(bytes: &[u8]) -> Result<(WrapperHeader, Vec<u8>), WrapperError> {
123    let header = WrapperHeader::decode(bytes)?;
124    let apdu = &bytes[8..];
125    if apdu.len() != header.length as usize {
126        return Err(WrapperError::LengthMismatch { declared: header.length as usize, actual: apdu.len() });
127    }
128    Ok((header, apdu.to_vec()))
129}
130
131/// The wrapper data-link sub-layer over a network (TCP/UDP) transport.
132#[derive(Debug)]
133pub struct Wrapper<T: NetworkTransport> {
134    transport: T,
135    source: u16,
136    destination: u16,
137}
138
139impl<T: NetworkTransport> Wrapper<T> {
140    /// Creates a wrapper layer that sends from `source` wPort to `destination`
141    /// wPort over `transport`.
142    pub fn new(transport: T, source: u16, destination: u16) -> Self {
143        Wrapper { transport, source, destination }
144    }
145
146    /// Returns a mutable reference to the underlying transport.
147    pub fn transport_mut(&mut self) -> &mut T {
148        &mut self.transport
149    }
150
151    /// Consumes the layer and returns the underlying transport.
152    pub fn into_inner(self) -> T {
153        self.transport
154    }
155}
156
157impl<T: NetworkTransport> DataLinkLayer for Wrapper<T> {
158    fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
159        #[cfg(feature = "tracing")]
160        trace!(source = self.source, dest = self.destination, apdu_len = apdu.len(), "wrapper send");
161        let pdu = encode(self.source, self.destination, apdu);
162        self.transport.send(&pdu)
163    }
164
165    fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
166        let mut header_bytes = [0u8; 8];
167        read_exact(&mut self.transport, &mut header_bytes)?;
168        let header = WrapperHeader::decode(&header_bytes)?;
169        #[cfg(feature = "tracing")]
170        trace!(source = header.source, dest = header.destination, apdu_len = header.length, "wrapper receive");
171        let mut apdu = vec![0u8; header.length as usize];
172        read_exact(&mut self.transport, &mut apdu)?;
173        Ok(apdu)
174    }
175}
176
177/// Reads exactly `buf.len()` bytes from `transport`, looping over short reads.
178fn read_exact<T: PhysicalTransport>(transport: &mut T, buf: &mut [u8]) -> io::Result<()> {
179    let mut filled = 0;
180    while filled < buf.len() {
181        let n = transport.receive(&mut buf[filled..])?;
182        if n == 0 {
183            return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "transport closed"));
184        }
185        filled += n;
186    }
187    Ok(())
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use crate::transport::MemoryTransport;
194
195    #[test]
196    fn encode_decode_round_trip() {
197        let apdu = vec![0xC0, 0x01, 0x00, 0x08];
198        let pdu = encode(0x0001, 0x0010, &apdu);
199        // Header: version 0001, source 0001, dest 0010, length 0004.
200        assert_eq!(&pdu[..8], &[0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x00, 0x04]);
201        let (header, decoded) = decode(&pdu).unwrap();
202        assert_eq!(header.source, 0x0001);
203        assert_eq!(header.destination, 0x0010);
204        assert_eq!(decoded, apdu);
205    }
206
207    #[test]
208    fn decode_rejects_bad_version_and_length() {
209        assert_eq!(WrapperHeader::decode(&[0u8; 4]), Err(WrapperError::TooShort));
210        let bad_version = [0x00, 0x02, 0, 1, 0, 1, 0, 0];
211        assert_eq!(WrapperHeader::decode(&bad_version), Err(WrapperError::UnsupportedVersion(2)));
212        let short_body = encode(1, 1, &[1, 2, 3]);
213        assert!(matches!(decode(&short_body[..8]), Err(WrapperError::LengthMismatch { .. })));
214    }
215
216    #[test]
217    fn layer_round_trips_over_transport() {
218        let mut layer = Wrapper::new(MemoryTransport::new(), 0x0001, 0x0010);
219        let apdu = vec![0x61, 0x1F, 0x30, 0x00];
220        layer.send_apdu(&apdu).unwrap();
221        let received = layer.receive_apdu().unwrap();
222        assert_eq!(received, apdu);
223    }
224}