use crate::crc::{CrcCheck, Kermit, X25};
use crate::{Error, Result};
pub const ESCAPE: [u8; 4] = [0x1B; 4];
pub const START: [u8; 4] = [0x01; 4];
pub const END: u8 = 0x1A;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
Hunting(u8),
Payload,
Command,
}
#[derive(Clone)]
pub struct Decoder<B> {
buf: B,
len: usize,
state: State,
word: [u8; 4],
word_len: usize,
crc: X25,
kermit: Kermit,
check: CrcCheck,
}
impl<B: AsRef<[u8]>> core::fmt::Debug for Decoder<B> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Decoder")
.field("state", &self.state)
.field("len", &self.len)
.field("capacity", &self.buf.as_ref().len())
.field("check", &self.check)
.finish_non_exhaustive()
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> Decoder<B> {
pub fn new(buf: B) -> Self {
Self {
buf,
len: 0,
state: State::Hunting(0),
word: [0; 4],
word_len: 0,
crc: X25::new(),
kermit: Kermit::new(),
check: CrcCheck::Strict,
}
}
#[must_use]
pub fn with_crc_check(mut self, check: CrcCheck) -> Self {
self.check = check;
self
}
pub fn reset(&mut self) {
self.state = State::Hunting(0);
self.word_len = 0;
self.len = 0;
}
pub fn into_inner(self) -> B {
self.buf
}
pub fn push_slice(&mut self, data: &[u8], mut on_frame: impl FnMut(Result<&[u8]>)) {
for &b in data {
match self.push(b) {
Ok(Some(frame)) => on_frame(Ok(frame)),
Ok(None) => {}
Err(e) => on_frame(Err(e)),
}
}
}
pub fn push(&mut self, byte: u8) -> Result<Option<&[u8]>> {
match self.state {
State::Hunting(matched) => {
self.hunt(matched, byte);
Ok(None)
}
State::Payload | State::Command => {
if let Some(slot) = self.word.get_mut(self.word_len) {
*slot = byte;
}
self.word_len += 1;
if self.word_len < 4 {
return Ok(None);
}
self.word_len = 0;
let word = self.word;
if self.state == State::Payload { self.payload_word(word) } else { self.command_word(word) }
}
}
}
fn hunt(&mut self, matched: u8, byte: u8) {
let expected = if matched < 4 { 0x1B } else { 0x01 };
let next = if byte == expected {
matched + 1
} else if byte == 0x1B {
if matched == 4 { 4 } else { 1 }
} else {
0
};
if next == 8 {
self.begin_frame();
} else {
self.state = State::Hunting(next);
}
}
fn begin_frame(&mut self) {
self.len = 0;
self.word_len = 0;
self.crc = X25::new();
self.kermit = Kermit::new();
self.update_crc(&ESCAPE);
self.update_crc(&START);
self.state = State::Payload;
}
fn update_crc(&mut self, bytes: &[u8]) {
self.crc.update(bytes);
self.kermit.update(bytes);
}
fn abort(&mut self, e: Error) -> Result<Option<&[u8]>> {
self.state = State::Hunting(0);
Err(e)
}
fn append(&mut self, word: [u8; 4]) -> Result<()> {
let end = self.len.checked_add(4).ok_or(Error::BufferFull)?;
self.buf.as_mut().get_mut(self.len..end).ok_or(Error::BufferFull)?.copy_from_slice(&word);
self.len = end;
Ok(())
}
fn payload_word(&mut self, word: [u8; 4]) -> Result<Option<&[u8]>> {
self.update_crc(&word);
if word == ESCAPE {
self.state = State::Command;
return Ok(None);
}
match self.append(word) {
Ok(()) => Ok(None),
Err(e) => self.abort(e),
}
}
fn command_word(&mut self, word: [u8; 4]) -> Result<Option<&[u8]>> {
self.state = State::Payload;
if word == ESCAPE {
self.update_crc(&word);
return match self.append(ESCAPE) {
Ok(()) => Ok(None),
Err(e) => self.abort(e),
};
}
if word == START {
self.begin_frame();
return Err(Error::UnexpectedStart);
}
let [cmd, padding, hi, lo] = word;
if cmd != END {
return self.abort(Error::InvalidEscape(word));
}
self.update_crc(&[cmd, padding]);
let computed = self.crc.finish();
let found = u16::from_be_bytes([hi, lo]);
self.state = State::Hunting(0);
if !self.check.accepts(computed, self.kermit.finish(), found) {
return Err(Error::FrameCrc { computed, found });
}
let padding = usize::from(padding);
let Some(payload_len) = self.len.checked_sub(padding).filter(|_| padding <= 3) else {
return Err(Error::InvalidPadding);
};
let payload = self.buf.as_ref().get(..self.len).ok_or(Error::BufferFull)?;
let (data, pad) = payload.split_at(payload_len);
if pad.iter().any(|&b| b != 0) {
return Err(Error::InvalidPadding);
}
Ok(Some(data))
}
}
pub fn encode_frame(payload: &[u8], out: &mut [u8]) -> Result<usize> {
let mut w = crate::tl::Writer::new(out);
w.raw(&ESCAPE)?;
w.raw(&START)?;
let padding = [0u8, 3, 2, 1].get(payload.len() % 4).copied().unwrap_or(0);
for chunk in payload.chunks(4) {
let mut word = [0u8; 4];
word.get_mut(..chunk.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(chunk);
if word == ESCAPE {
w.raw(&ESCAPE)?;
}
w.raw(&word)?;
}
w.raw(&ESCAPE)?;
w.raw(&[END, padding])?;
let crc = crate::crc::x25(w.written());
w.raw(&crc.to_le_bytes())?;
Ok(w.position())
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
fn decode_all(wire: &[u8]) -> ([u8; 128], usize, usize) {
let mut buf = [0u8; 128];
let mut out = [0u8; 128];
let mut out_len = 0;
let mut frames = 0;
let mut d = Decoder::new(&mut buf);
d.push_slice(wire, |f| {
let f = f.unwrap();
out[..f.len()].copy_from_slice(f);
out_len = f.len();
frames += 1;
});
(out, out_len, frames)
}
#[test]
fn round_trip_with_padding() {
for len in 0..=9 {
let payload: [u8; 9] = core::array::from_fn(|i| u8::try_from(i).unwrap() + 0x40);
let mut wire = [0u8; 64];
let n = encode_frame(&payload[..len], &mut wire).unwrap();
assert_eq!(n % 4, 0);
let (out, out_len, frames) = decode_all(&wire[..n]);
assert_eq!(frames, 1);
assert_eq!(&out[..out_len], &payload[..len]);
}
}
#[test]
fn escaped_payload_word_survives() {
let payload = [0x76, 0x05, 0x00, 0x00, 0x1B, 0x1B, 0x1B, 0x1B, 0x62, 0x00];
let mut wire = [0u8; 64];
let n = encode_frame(&payload, &mut wire).unwrap();
assert_eq!(&wire[12..20], &[0x1B; 8]);
let (out, out_len, _) = decode_all(&wire[..n]);
assert_eq!(&out[..out_len], &payload);
}
#[test]
fn garbage_before_the_start_is_skipped() {
let mut wire = [0u8; 64];
wire[..5].copy_from_slice(&[0x00, 0x1B, 0x1B, 0x42, 0x1B]);
let n = encode_frame(&[1, 2, 3, 4], &mut wire[5..]).unwrap();
let (out, out_len, frames) = decode_all(&wire[..5 + n]);
assert_eq!(frames, 1);
assert_eq!(&out[..out_len], &[1, 2, 3, 4]);
}
#[test]
fn a_flipped_bit_fails_the_crc() {
let mut wire = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
wire[9] ^= 0x01;
let mut buf = [0u8; 64];
let mut d = Decoder::new(&mut buf);
let mut errors = 0;
d.push_slice(&wire[..n], |f| {
assert!(matches!(f, Err(Error::FrameCrc { .. })));
errors += 1;
});
assert_eq!(errors, 1);
}
fn frames(wire: &[u8]) -> usize {
let mut d = Decoder::new([0u8; 64]);
let mut n = 0;
d.push_slice(wire, |f| n += usize::from(f.is_ok()));
n
}
#[test]
fn hunter_rejects_a_start_broken_by_a_stray_escape_byte() {
let mut frame = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
let mut wire = std::vec![0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x1B, 0x01, 0x01, 0x01, 0x01];
wire.extend_from_slice(&frame[8..n]);
assert_eq!(frames(&wire), 0);
}
#[test]
fn hunter_resynchronises_on_extra_escape_bytes() {
let mut frame = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
for prefix in [&[0x1B][..], &[0x1B, 0x1B, 0x1B], &[0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x1B]] {
let mut wire = prefix.to_vec();
wire.extend_from_slice(&frame[..n]);
assert_eq!(frames(&wire), 1, "prefix {prefix:02x?}");
}
}
#[test]
fn transport_v2_start_is_not_a_frame_start() {
let mut frame = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
let mut wire = std::vec![0x1B, 0x1B, 0x1B, 0x1B, 0x02, 0x00, 0x00, 0x01];
wire.extend_from_slice(&frame[8..n]);
assert_eq!(frames(&wire), 0);
wire.extend_from_slice(&frame[..n]);
assert_eq!(frames(&wire), 1);
}
#[test]
fn byte_by_byte_and_chunked_feeding_agree() {
let mut frame = [0u8; 64];
let n = encode_frame(&[9; 13], &mut frame).unwrap();
for chunk in 1..=n {
let mut d = Decoder::new([0u8; 64]);
let mut got = 0;
for part in frame[..n].chunks(chunk) {
d.push_slice(part, |f| got += usize::from(f.is_ok()));
}
assert_eq!(got, 1, "chunk size {chunk}");
}
}
#[test]
fn lenient_accepts_a_kermit_frame_crc_strict_does_not() {
let mut wire = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
let k = crate::crc::kermit(&wire[..n - 2]);
wire[n - 2..n].copy_from_slice(&k.to_be_bytes());
let mut strict = Decoder::new([0u8; 64]);
let mut errors = 0;
strict.push_slice(&wire[..n], |f| errors += usize::from(matches!(f, Err(Error::FrameCrc { .. }))));
assert_eq!(errors, 1);
let mut lenient = Decoder::new([0u8; 64]).with_crc_check(CrcCheck::Lenient);
let mut ok = 0;
lenient.push_slice(&wire[..n], |f| ok += usize::from(f.is_ok()));
assert_eq!(ok, 1);
}
#[test]
fn switching_to_lenient_mid_frame_still_accepts_kermit() {
let mut wire = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
let k = crate::crc::kermit(&wire[..n - 2]);
wire[n - 2..n].copy_from_slice(&k.to_be_bytes());
let mut d = Decoder::new([0u8; 64]);
d.push_slice(&wire[..6], |_| {});
let mut d = d.with_crc_check(CrcCheck::Lenient);
let mut ok = 0;
d.push_slice(&wire[6..n], |f| ok += usize::from(f.is_ok()));
assert_eq!(ok, 1);
}
#[test]
fn debug_shows_state_not_buffer() {
let d = Decoder::new([0x42u8; 8]);
assert_eq!(
std::format!("{d:?}"),
"Decoder { state: Hunting(0), len: 0, capacity: 8, check: Strict, .. }"
);
}
#[test]
fn reset_drops_a_frame_in_progress() {
let mut wire = [0u8; 64];
let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
let mut d = Decoder::new([0u8; 64]);
d.push_slice(&wire[..10], |_| {});
d.reset();
let mut ok = 0;
d.push_slice(&wire[..n], |f| ok += usize::from(f.is_ok()));
assert_eq!(ok, 1);
}
#[test]
fn a_frame_larger_than_the_buffer_is_reported() {
let mut wire = [0u8; 64];
let n = encode_frame(&[7; 20], &mut wire).unwrap();
let mut buf = [0u8; 8];
let mut d = Decoder::new(&mut buf);
let mut full = false;
d.push_slice(&wire[..n], |f| full |= f == Err(Error::BufferFull));
assert!(full);
}
}