Skip to main content

sml_kit/
transport.rs

1//! SML transport protocol version 1: framing, escaping, padding and the frame CRC.
2//!
3//! ```text
4//! 1b 1b 1b 1b  01 01 01 01      start sequence
5//! …payload…                     SML messages, padded with 0x00 to a multiple of 4
6//! 1b 1b 1b 1b  1a pp cc cc      end sequence: pp padding bytes, cc cc CRC
7//! ```
8//!
9//! After the start sequence the stream is read in 4-byte words. A word of four `0x1b`
10//! is an escape: the next word is a command. `1b 1b 1b 1b` again means the payload
11//! itself contains those four bytes; `1a …` ends the frame; `01 01 01 01` starts a new
12//! one. Escapes are aligned to 4 bytes, which is why the payload is padded. Every CRC-valid
13//! frame in the public real-meter corpus agrees, and libsml reads the same way.
14//!
15//! The CRC covers every transmitted byte from the start sequence up to and including
16//! the padding count.
17
18use crate::crc::{CrcCheck, Kermit, X25};
19use crate::{Error, Result};
20
21/// The escape word.
22pub const ESCAPE: [u8; 4] = [0x1B; 4];
23/// The start command of transport version 1.
24pub const START: [u8; 4] = [0x01; 4];
25/// The first byte of the end command.
26pub const END: u8 = 0x1A;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29enum State {
30    /// Looking for the 8-byte start sequence; the number of bytes matched so far.
31    Hunting(u8),
32    /// Inside a frame, collecting a payload word.
33    Payload,
34    /// Inside a frame, collecting the word after an escape.
35    Command,
36}
37
38/// A sans-I/O transport decoder that assembles frames in a buffer of type `B`.
39///
40/// Feed it bytes as they arrive, from an optical head, a serial line or a capture file,
41/// and it hands out each complete, verified payload. It never allocates and never
42/// panics. Garbage before a start sequence is skipped.
43///
44/// The buffer can be owned (`[u8; N]`, or a `Vec<u8>` with `std`) or borrowed
45/// (`&mut [u8]`). Its length is the largest frame accepted.
46///
47/// ```
48/// use sml_kit::{Decoder, encode_frame};
49///
50/// let mut wire = [0u8; 64];
51/// let n = encode_frame(&[0x01, 0x02, 0x03], &mut wire).unwrap();
52///
53/// let mut decoder = Decoder::new([0u8; 64]);
54/// let mut frames = 0;
55/// decoder.push_slice(&wire[..n], |frame| {
56///     assert_eq!(frame.unwrap(), &[0x01, 0x02, 0x03]);
57///     frames += 1;
58/// });
59/// assert_eq!(frames, 1);
60/// ```
61#[derive(Clone)]
62pub struct Decoder<B> {
63    buf: B,
64    len: usize,
65    state: State,
66    word: [u8; 4],
67    word_len: usize,
68    crc: X25,
69    kermit: Kermit,
70    check: CrcCheck,
71}
72
73/// Shows the state, never the buffer: a frame may hold credentials.
74impl<B: AsRef<[u8]>> core::fmt::Debug for Decoder<B> {
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        f.debug_struct("Decoder")
77            .field("state", &self.state)
78            .field("len", &self.len)
79            .field("capacity", &self.buf.as_ref().len())
80            .field("check", &self.check)
81            .finish_non_exhaustive()
82    }
83}
84
85impl<B: AsRef<[u8]> + AsMut<[u8]>> Decoder<B> {
86    /// A decoder that assembles frames in `buf`. A frame larger than `buf` is reported
87    /// as [`Error::BufferFull`] and skipped.
88    pub fn new(buf: B) -> Self {
89        Self {
90            buf,
91            len: 0,
92            state: State::Hunting(0),
93            word: [0; 4],
94            word_len: 0,
95            crc: X25::new(),
96            kermit: Kermit::new(),
97            check: CrcCheck::Strict,
98        }
99    }
100
101    /// Set how the frame CRC is checked. [`CrcCheck::Strict`] by default.
102    #[must_use]
103    pub fn with_crc_check(mut self, check: CrcCheck) -> Self {
104        self.check = check;
105        self
106    }
107
108    /// Forget any frame in progress and look for the next start sequence, e.g. after a
109    /// serial-port timeout.
110    pub fn reset(&mut self) {
111        self.state = State::Hunting(0);
112        self.word_len = 0;
113        self.len = 0;
114    }
115
116    /// The buffer frames are assembled in.
117    pub fn into_inner(self) -> B {
118        self.buf
119    }
120
121    /// Feed every byte of `data`, calling `on_frame` for each complete frame or error.
122    pub fn push_slice(&mut self, data: &[u8], mut on_frame: impl FnMut(Result<&[u8]>)) {
123        for &b in data {
124            match self.push(b) {
125                Ok(Some(frame)) => on_frame(Ok(frame)),
126                Ok(None) => {}
127                Err(e) => on_frame(Err(e)),
128            }
129        }
130    }
131
132    /// Feed one byte. Returns the payload when this byte completes a frame.
133    pub fn push(&mut self, byte: u8) -> Result<Option<&[u8]>> {
134        match self.state {
135            State::Hunting(matched) => {
136                self.hunt(matched, byte);
137                Ok(None)
138            }
139            State::Payload | State::Command => {
140                if let Some(slot) = self.word.get_mut(self.word_len) {
141                    *slot = byte;
142                }
143                self.word_len += 1;
144                if self.word_len < 4 {
145                    return Ok(None);
146                }
147                self.word_len = 0;
148                let word = self.word;
149                if self.state == State::Payload { self.payload_word(word) } else { self.command_word(word) }
150            }
151        }
152    }
153
154    fn hunt(&mut self, matched: u8, byte: u8) {
155        let expected = if matched < 4 { 0x1B } else { 0x01 };
156        let next = if byte == expected {
157            matched + 1
158        } else if byte == 0x1B {
159            // A fifth 0x1b right after four keeps the last four as the escape. After a
160            // partial `01` run, a 0x1b can only begin a new escape: one byte matched.
161            if matched == 4 { 4 } else { 1 }
162        } else {
163            0
164        };
165        if next == 8 {
166            self.begin_frame();
167        } else {
168            self.state = State::Hunting(next);
169        }
170    }
171
172    fn begin_frame(&mut self) {
173        self.len = 0;
174        self.word_len = 0;
175        self.crc = X25::new();
176        self.kermit = Kermit::new();
177        self.update_crc(&ESCAPE);
178        self.update_crc(&START);
179        self.state = State::Payload;
180    }
181
182    fn update_crc(&mut self, bytes: &[u8]) {
183        self.crc.update(bytes);
184        // Always kept, so changing the CRC mode mid-frame cannot leave it incomplete.
185        self.kermit.update(bytes);
186    }
187
188    fn abort(&mut self, e: Error) -> Result<Option<&[u8]>> {
189        self.state = State::Hunting(0);
190        Err(e)
191    }
192
193    fn append(&mut self, word: [u8; 4]) -> Result<()> {
194        let end = self.len.checked_add(4).ok_or(Error::BufferFull)?;
195        self.buf.as_mut().get_mut(self.len..end).ok_or(Error::BufferFull)?.copy_from_slice(&word);
196        self.len = end;
197        Ok(())
198    }
199
200    fn payload_word(&mut self, word: [u8; 4]) -> Result<Option<&[u8]>> {
201        self.update_crc(&word);
202        if word == ESCAPE {
203            self.state = State::Command;
204            return Ok(None);
205        }
206        match self.append(word) {
207            Ok(()) => Ok(None),
208            Err(e) => self.abort(e),
209        }
210    }
211
212    fn command_word(&mut self, word: [u8; 4]) -> Result<Option<&[u8]>> {
213        self.state = State::Payload;
214        if word == ESCAPE {
215            self.update_crc(&word);
216            return match self.append(ESCAPE) {
217                Ok(()) => Ok(None),
218                Err(e) => self.abort(e),
219            };
220        }
221        if word == START {
222            self.begin_frame();
223            return Err(Error::UnexpectedStart);
224        }
225        let [cmd, padding, hi, lo] = word;
226        if cmd != END {
227            return self.abort(Error::InvalidEscape(word));
228        }
229        self.update_crc(&[cmd, padding]);
230        let computed = self.crc.finish();
231        let found = u16::from_be_bytes([hi, lo]);
232        self.state = State::Hunting(0);
233        if !self.check.accepts(computed, self.kermit.finish(), found) {
234            return Err(Error::FrameCrc { computed, found });
235        }
236        let padding = usize::from(padding);
237        let Some(payload_len) = self.len.checked_sub(padding).filter(|_| padding <= 3) else {
238            return Err(Error::InvalidPadding);
239        };
240        let payload = self.buf.as_ref().get(..self.len).ok_or(Error::BufferFull)?;
241        let (data, pad) = payload.split_at(payload_len);
242        if pad.iter().any(|&b| b != 0) {
243            return Err(Error::InvalidPadding);
244        }
245        Ok(Some(data))
246    }
247}
248
249/// Frame `payload` for transport version 1 into `out`: start sequence, escaped payload,
250/// zero padding to a multiple of 4, end sequence and CRC (low byte first). Returns the
251/// number of bytes written.
252pub fn encode_frame(payload: &[u8], out: &mut [u8]) -> Result<usize> {
253    let mut w = crate::tl::Writer::new(out);
254    w.raw(&ESCAPE)?;
255    w.raw(&START)?;
256    // Zero bytes that bring the payload to a multiple of 4: 0 to 3.
257    let padding = [0u8, 3, 2, 1].get(payload.len() % 4).copied().unwrap_or(0);
258    for chunk in payload.chunks(4) {
259        let mut word = [0u8; 4];
260        word.get_mut(..chunk.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(chunk);
261        if word == ESCAPE {
262            w.raw(&ESCAPE)?;
263        }
264        w.raw(&word)?;
265    }
266    w.raw(&ESCAPE)?;
267    w.raw(&[END, padding])?;
268    let crc = crate::crc::x25(w.written());
269    w.raw(&crc.to_le_bytes())?;
270    Ok(w.position())
271}
272
273#[cfg(test)]
274mod tests {
275    extern crate std;
276    use super::*;
277
278    fn decode_all(wire: &[u8]) -> ([u8; 128], usize, usize) {
279        let mut buf = [0u8; 128];
280        let mut out = [0u8; 128];
281        let mut out_len = 0;
282        let mut frames = 0;
283        let mut d = Decoder::new(&mut buf);
284        d.push_slice(wire, |f| {
285            let f = f.unwrap();
286            out[..f.len()].copy_from_slice(f);
287            out_len = f.len();
288            frames += 1;
289        });
290        (out, out_len, frames)
291    }
292
293    #[test]
294    fn round_trip_with_padding() {
295        for len in 0..=9 {
296            let payload: [u8; 9] = core::array::from_fn(|i| u8::try_from(i).unwrap() + 0x40);
297            let mut wire = [0u8; 64];
298            let n = encode_frame(&payload[..len], &mut wire).unwrap();
299            assert_eq!(n % 4, 0);
300            let (out, out_len, frames) = decode_all(&wire[..n]);
301            assert_eq!(frames, 1);
302            assert_eq!(&out[..out_len], &payload[..len]);
303        }
304    }
305
306    #[test]
307    fn escaped_payload_word_survives() {
308        let payload = [0x76, 0x05, 0x00, 0x00, 0x1B, 0x1B, 0x1B, 0x1B, 0x62, 0x00];
309        let mut wire = [0u8; 64];
310        let n = encode_frame(&payload, &mut wire).unwrap();
311        // The aligned 1b1b1b1b word is doubled on the wire.
312        assert_eq!(&wire[12..20], &[0x1B; 8]);
313        let (out, out_len, _) = decode_all(&wire[..n]);
314        assert_eq!(&out[..out_len], &payload);
315    }
316
317    #[test]
318    fn garbage_before_the_start_is_skipped() {
319        let mut wire = [0u8; 64];
320        wire[..5].copy_from_slice(&[0x00, 0x1B, 0x1B, 0x42, 0x1B]);
321        let n = encode_frame(&[1, 2, 3, 4], &mut wire[5..]).unwrap();
322        let (out, out_len, frames) = decode_all(&wire[..5 + n]);
323        assert_eq!(frames, 1);
324        assert_eq!(&out[..out_len], &[1, 2, 3, 4]);
325    }
326
327    #[test]
328    fn a_flipped_bit_fails_the_crc() {
329        let mut wire = [0u8; 64];
330        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
331        wire[9] ^= 0x01;
332        let mut buf = [0u8; 64];
333        let mut d = Decoder::new(&mut buf);
334        let mut errors = 0;
335        d.push_slice(&wire[..n], |f| {
336            assert!(matches!(f, Err(Error::FrameCrc { .. })));
337            errors += 1;
338        });
339        assert_eq!(errors, 1);
340    }
341
342    fn frames(wire: &[u8]) -> usize {
343        let mut d = Decoder::new([0u8; 64]);
344        let mut n = 0;
345        d.push_slice(wire, |f| n += usize::from(f.is_ok()));
346        n
347    }
348
349    // 001-real-meter-readiness/SR-002
350    #[test]
351    fn hunter_rejects_a_start_broken_by_a_stray_escape_byte() {
352        let mut frame = [0u8; 64];
353        let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
354        // `1b1b1b1b 01 1b 01 01 01 01` is not a start sequence, so the body that follows
355        // must not become a frame.
356        let mut wire = std::vec![0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x1B, 0x01, 0x01, 0x01, 0x01];
357        wire.extend_from_slice(&frame[8..n]);
358        assert_eq!(frames(&wire), 0);
359    }
360
361    // 001-real-meter-readiness/SR-002
362    #[test]
363    fn hunter_resynchronises_on_extra_escape_bytes() {
364        let mut frame = [0u8; 64];
365        let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
366        for prefix in [&[0x1B][..], &[0x1B, 0x1B, 0x1B], &[0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x1B]] {
367            let mut wire = prefix.to_vec();
368            wire.extend_from_slice(&frame[..n]);
369            assert_eq!(frames(&wire), 1, "prefix {prefix:02x?}");
370        }
371    }
372
373    // 002-complete-protocol/SR-005: transport version 2 is refused.
374    #[test]
375    fn transport_v2_start_is_not_a_frame_start() {
376        let mut frame = [0u8; 64];
377        let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
378        // 1b1b1b1b 02 TT UU 01: a version-2 start, block 0, file 0.
379        let mut wire = std::vec![0x1B, 0x1B, 0x1B, 0x1B, 0x02, 0x00, 0x00, 0x01];
380        wire.extend_from_slice(&frame[8..n]);
381        assert_eq!(frames(&wire), 0);
382        // A version-1 frame right after it is still found.
383        wire.extend_from_slice(&frame[..n]);
384        assert_eq!(frames(&wire), 1);
385    }
386
387    #[test]
388    fn byte_by_byte_and_chunked_feeding_agree() {
389        let mut frame = [0u8; 64];
390        let n = encode_frame(&[9; 13], &mut frame).unwrap();
391        for chunk in 1..=n {
392            let mut d = Decoder::new([0u8; 64]);
393            let mut got = 0;
394            for part in frame[..n].chunks(chunk) {
395                d.push_slice(part, |f| got += usize::from(f.is_ok()));
396            }
397            assert_eq!(got, 1, "chunk size {chunk}");
398        }
399    }
400
401    #[test]
402    fn lenient_accepts_a_kermit_frame_crc_strict_does_not() {
403        let mut wire = [0u8; 64];
404        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
405        let k = crate::crc::kermit(&wire[..n - 2]);
406        wire[n - 2..n].copy_from_slice(&k.to_be_bytes());
407        let mut strict = Decoder::new([0u8; 64]);
408        let mut errors = 0;
409        strict.push_slice(&wire[..n], |f| errors += usize::from(matches!(f, Err(Error::FrameCrc { .. }))));
410        assert_eq!(errors, 1);
411        let mut lenient = Decoder::new([0u8; 64]).with_crc_check(CrcCheck::Lenient);
412        let mut ok = 0;
413        lenient.push_slice(&wire[..n], |f| ok += usize::from(f.is_ok()));
414        assert_eq!(ok, 1);
415    }
416
417    #[test]
418    fn switching_to_lenient_mid_frame_still_accepts_kermit() {
419        let mut wire = [0u8; 64];
420        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
421        let k = crate::crc::kermit(&wire[..n - 2]);
422        wire[n - 2..n].copy_from_slice(&k.to_be_bytes());
423        let mut d = Decoder::new([0u8; 64]);
424        d.push_slice(&wire[..6], |_| {});
425        let mut d = d.with_crc_check(CrcCheck::Lenient);
426        let mut ok = 0;
427        d.push_slice(&wire[6..n], |f| ok += usize::from(f.is_ok()));
428        assert_eq!(ok, 1);
429    }
430
431    #[test]
432    fn debug_shows_state_not_buffer() {
433        let d = Decoder::new([0x42u8; 8]);
434        assert_eq!(
435            std::format!("{d:?}"),
436            "Decoder { state: Hunting(0), len: 0, capacity: 8, check: Strict, .. }"
437        );
438    }
439
440    #[test]
441    fn reset_drops_a_frame_in_progress() {
442        let mut wire = [0u8; 64];
443        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
444        let mut d = Decoder::new([0u8; 64]);
445        d.push_slice(&wire[..10], |_| {});
446        d.reset();
447        let mut ok = 0;
448        d.push_slice(&wire[..n], |f| ok += usize::from(f.is_ok()));
449        assert_eq!(ok, 1);
450    }
451
452    #[test]
453    fn a_frame_larger_than_the_buffer_is_reported() {
454        let mut wire = [0u8; 64];
455        let n = encode_frame(&[7; 20], &mut wire).unwrap();
456        let mut buf = [0u8; 8];
457        let mut d = Decoder::new(&mut buf);
458        let mut full = false;
459        d.push_slice(&wire[..n], |f| full |= f == Err(Error::BufferFull));
460        assert!(full);
461    }
462}