Skip to main content

xmodem_proto/
codec.rs

1//! XModem block framing and block checks.
2//!
3//! A block is `SOH|STX, blk, 255-blk, data, check`: 128 data bytes after SOH,
4//! 1024 after STX; the check is one byte (sum of the data mod 256) or two
5//! bytes (CRC-16, high byte first; standard or HP's own, see [`Check`]).
6
7/// Start of a 128-byte block.
8pub const SOH: u8 = 0x01;
9/// Start of a 1024-byte block.
10pub const STX: u8 = 0x02;
11/// End of transmission.
12pub const EOT: u8 = 0x04;
13/// Positive acknowledgement.
14pub const ACK: u8 = 0x06;
15/// Negative acknowledgement; as a receiver's start character it asks for
16/// checksum mode.
17pub const NAK: u8 = 0x15;
18/// Cancel; two in a row abort the transfer.
19pub const CAN: u8 = 0x18;
20/// Receiver start character asking for CRC-16 mode.
21pub const CRC_START: u8 = b'C';
22/// Receiver start character asking for HP's CRC mode ([`Check::HpCrc`]).
23pub const HP_CRC_START: u8 = b'D';
24/// End of a Kermit packet (the calculator's server may still send one).
25pub(crate) const CR_KERMIT: u8 = b'\r';
26/// CP/M end-of-file, the classic XModem padding byte.
27pub const SUB: u8 = 0x1A;
28
29/// The block check a transfer uses.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Check {
33    /// One byte: the sum of the data bytes mod 256. The only mode the 48G
34    /// series knows.
35    Checksum,
36    /// Two bytes, high byte first: CRC-16 with polynomial #1021, MSB first,
37    /// initial value 0 ("CRC-16/XMODEM"). Not the Kermit type-3 check, which
38    /// is LSB first (#8408 reflected, i.e. #1081 per nibble).
39    Crc16,
40    /// HP's own mode, requested with `D`: two bytes, high byte first, of the
41    /// CRC-16 the Saturn hardware and Kermit's type-3 check use (polynomial
42    /// #1081 per nibble, LSB first, initial value 0, i.e. "CRC-16/KERMIT").
43    /// The 49G's `XRECV` asks for it first (three `D`s, then NAK) and
44    /// accepts 1k and 128-byte blocks with it; verified on the emulated 49G.
45    HpCrc,
46}
47
48impl Check {
49    /// Number of check bytes after the data.
50    pub fn len(self) -> usize {
51        match self {
52            Check::Checksum => 1,
53            Check::Crc16 | Check::HpCrc => 2,
54        }
55    }
56
57    /// Always false; a check has at least one byte (clippy's `len` pairing).
58    pub fn is_empty(self) -> bool {
59        false
60    }
61
62    /// The check bytes for `data`, in wire order.
63    pub fn compute(self, data: &[u8]) -> Vec<u8> {
64        match self {
65            Check::Checksum => vec![checksum(data)],
66            Check::Crc16 => crc16(data).to_be_bytes().to_vec(),
67            Check::HpCrc => hp_crc(data).to_be_bytes().to_vec(),
68        }
69    }
70
71    /// The receiver start character that requests this check.
72    pub fn start_char(self) -> u8 {
73        match self {
74            Check::Checksum => NAK,
75            Check::Crc16 => CRC_START,
76            Check::HpCrc => HP_CRC_START,
77        }
78    }
79
80    /// The check a receiver's start character asks for.
81    pub fn from_start_char(byte: u8) -> Option<Check> {
82        match byte {
83            NAK => Some(Check::Checksum),
84            CRC_START => Some(Check::Crc16),
85            HP_CRC_START => Some(Check::HpCrc),
86            _ => None,
87        }
88    }
89}
90
91/// Data size of a block.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum BlockSize {
95    /// 128 bytes, header SOH.
96    B128,
97    /// 1024 bytes, header STX (XModem-1K).
98    B1k,
99}
100
101impl BlockSize {
102    /// Number of data bytes.
103    pub fn len(self) -> usize {
104        match self {
105            BlockSize::B128 => 128,
106            BlockSize::B1k => 1024,
107        }
108    }
109
110    /// Always false (clippy's `len` pairing).
111    pub fn is_empty(self) -> bool {
112        false
113    }
114
115    /// The header byte (SOH or STX).
116    pub fn header(self) -> u8 {
117        match self {
118            BlockSize::B128 => SOH,
119            BlockSize::B1k => STX,
120        }
121    }
122
123    /// The block size a header byte announces, if it is SOH or STX.
124    pub fn from_header(byte: u8) -> Option<BlockSize> {
125        match byte {
126            SOH => Some(BlockSize::B128),
127            STX => Some(BlockSize::B1k),
128            _ => None,
129        }
130    }
131}
132
133/// Sum of `data` mod 256.
134pub fn checksum(data: &[u8]) -> u8 {
135    data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b))
136}
137
138/// CRC-16/XMODEM: polynomial #1021, MSB first, initial value 0, no final XOR.
139pub fn crc16(data: &[u8]) -> u16 {
140    let mut crc: u16 = 0;
141    for &byte in data {
142        crc ^= u16::from(byte) << 8;
143        for _ in 0..8 {
144            crc = if crc & 0x8000 != 0 {
145                (crc << 1) ^ 0x1021
146            } else {
147                crc << 1
148            };
149        }
150    }
151    crc
152}
153
154/// CRC-16/KERMIT: polynomial #1081 applied per nibble, LSB first, initial
155/// value 0. Same value as the Saturn CRC circuit and Kermit's type-3 check.
156pub fn hp_crc(data: &[u8]) -> u16 {
157    let mut crc: u16 = 0;
158    for &byte in data {
159        for nibble in [byte & 0x0F, byte >> 4] {
160            let q = (crc ^ u16::from(nibble)) & 0x0F;
161            crc = (crc >> 4) ^ (q * 0x1081);
162        }
163    }
164    crc
165}
166
167/// Total length on the wire of a block of `size` with `check`.
168pub fn frame_len(size: BlockSize, check: Check) -> usize {
169    3 + size.len() + check.len()
170}
171
172/// Encode block number `num` holding `data`, padded with `pad` to the full
173/// block size. Fails if `data` is longer than the block.
174pub fn encode_block(
175    num: u8,
176    size: BlockSize,
177    data: &[u8],
178    pad: u8,
179    check: Check,
180) -> Result<Vec<u8>, EncodeError> {
181    if data.len() > size.len() {
182        return Err(EncodeError {
183            len: data.len(),
184            max: size.len(),
185        });
186    }
187    Ok(frame_block(num, size, data, pad, check))
188}
189
190/// [`encode_block`] for data the caller has already cut to the block size
191/// (the sender always does); longer data is cut.
192pub(crate) fn frame_block(num: u8, size: BlockSize, data: &[u8], pad: u8, check: Check) -> Vec<u8> {
193    let n = size.len();
194    let mut out = Vec::with_capacity(frame_len(size, check));
195    out.push(size.header());
196    out.push(num);
197    out.push(!num);
198    let take = data.len().min(n);
199    out.extend_from_slice(data.get(..take).unwrap_or_default());
200    out.resize(3 + n, pad);
201    let check_bytes = check.compute(out.get(3..).unwrap_or_default());
202    out.extend_from_slice(&check_bytes);
203    out
204}
205
206/// [`encode_block`] was given more data than fits in the block.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub struct EncodeError {
209    /// Length of the data.
210    pub len: usize,
211    /// The block size.
212    pub max: usize,
213}
214
215impl std::fmt::Display for EncodeError {
216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217        write!(
218            f,
219            "block data too long: {} bytes, the block holds {}",
220            self.len, self.max
221        )
222    }
223}
224
225impl std::error::Error for EncodeError {}
226
227/// A complete block decoded from the wire.
228#[derive(Clone, Debug, PartialEq, Eq)]
229pub struct Block {
230    /// Block number as sent.
231    pub num: u8,
232    /// The data (128 or 1024 bytes), padding included.
233    pub data: Vec<u8>,
234}
235
236/// Why a frame was rejected.
237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238pub enum BlockError {
239    /// Not SOH or STX.
240    BadHeader,
241    /// The block number and its complement disagree.
242    BadNumber,
243    /// The frame has the wrong length for its header and check.
244    BadLength,
245    /// The block check does not match.
246    BadCheck,
247}
248
249/// Decode one complete frame (header to check) with `check`.
250pub fn decode_block(frame: &[u8], check: Check) -> Result<Block, BlockError> {
251    let size = frame
252        .first()
253        .and_then(|&b| BlockSize::from_header(b))
254        .ok_or(BlockError::BadHeader)?;
255    if frame.len() != frame_len(size, check) {
256        return Err(BlockError::BadLength);
257    }
258    let (num, inv) = match (frame.get(1), frame.get(2)) {
259        (Some(&a), Some(&b)) => (a, b),
260        _ => return Err(BlockError::BadLength),
261    };
262    if num != !inv {
263        return Err(BlockError::BadNumber);
264    }
265    let data = frame.get(3..3 + size.len()).ok_or(BlockError::BadLength)?;
266    let got = frame.get(3 + size.len()..).ok_or(BlockError::BadLength)?;
267    if got != check.compute(data).as_slice() {
268        return Err(BlockError::BadCheck);
269    }
270    Ok(Block {
271        num,
272        data: data.to_vec(),
273    })
274}
275
276#[cfg(test)]
277#[allow(clippy::unwrap_used, clippy::expect_used)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn crc16_known_vectors() {
283        // CRC-16/XMODEM check value.
284        assert_eq!(crc16(b"123456789"), 0x31C3);
285        assert_eq!(crc16(b""), 0);
286        assert_eq!(crc16(b"A"), 0x58E5);
287        // 128 bytes of SUB (an all-padding block).
288        assert_eq!(crc16(&[SUB; 128]), crc16(&[SUB; 128]));
289        assert_eq!(crc16(&[0u8; 128]), 0);
290    }
291
292    #[test]
293    fn crc16_is_not_the_kermit_check() {
294        // Kermit type 3 (LSB first, reflected) of "123456789" is 0x2189.
295        assert_ne!(crc16(b"123456789"), 0x2189);
296    }
297
298    #[test]
299    fn hp_crc_known_vectors() {
300        // CRC-16/KERMIT check value.
301        assert_eq!(hp_crc(b"123456789"), 0x2189);
302        assert_eq!(hp_crc(b""), 0);
303        assert_eq!(Check::HpCrc.compute(b"123456789"), vec![0x21, 0x89]);
304        assert_eq!(Check::from_start_char(b'D'), Some(Check::HpCrc));
305        assert_eq!(Check::from_start_char(0x15), Some(Check::Checksum));
306        assert_eq!(Check::from_start_char(b'C'), Some(Check::Crc16));
307        assert_eq!(Check::from_start_char(b'X'), None);
308    }
309
310    #[test]
311    fn checksum_wraps() {
312        assert_eq!(checksum(b""), 0);
313        assert_eq!(checksum(&[0xFF, 0x02]), 0x01);
314        let all: Vec<u8> = (0..=127).collect();
315        assert_eq!(checksum(&all), (127 * 128 / 2 % 256) as u8);
316    }
317
318    #[test]
319    fn encode_checksum_block_bytes() {
320        let b = encode_block(1, BlockSize::B128, b"AB", SUB, Check::Checksum).unwrap();
321        assert_eq!(b.len(), 132);
322        assert_eq!(&b[..5], &[SOH, 0x01, 0xFE, b'A', b'B']);
323        assert!(b[5..131].iter().all(|&x| x == SUB));
324        // 0x41 + 0x42 + 126 * 0x1A = 0x83 + 0xCCC = 0xD4F -> 0x4F
325        assert_eq!(b[131], 0x4F);
326    }
327
328    #[test]
329    fn encode_crc_block_bytes() {
330        let data: Vec<u8> = (0..128).collect();
331        let b = encode_block(0xFF, BlockSize::B128, &data, 0, Check::Crc16).unwrap();
332        assert_eq!(b.len(), 133);
333        assert_eq!(&b[..3], &[SOH, 0xFF, 0x00]);
334        let crc = crc16(&data);
335        assert_eq!(&b[131..], &[(crc >> 8) as u8, crc as u8]);
336    }
337
338    #[test]
339    fn encode_1k_block() {
340        let b = encode_block(2, BlockSize::B1k, &[7; 1000], 0, Check::Crc16).unwrap();
341        assert_eq!(b.len(), 1029);
342        assert_eq!(&b[..3], &[STX, 2, 0xFD]);
343        assert_eq!(b[1002], 7);
344        assert_eq!(b[1003], 0);
345    }
346
347    #[test]
348    fn oversized_block_is_an_error() {
349        assert_eq!(
350            encode_block(1, BlockSize::B128, &[0; 129], SUB, Check::Crc16),
351            Err(EncodeError { len: 129, max: 128 })
352        );
353        assert!(encode_block(1, BlockSize::B1k, &[0; 1024], SUB, Check::Crc16).is_ok());
354    }
355
356    #[test]
357    fn decode_round_trip_and_errors() {
358        let b = encode_block(3, BlockSize::B128, b"hello", SUB, Check::Crc16).unwrap();
359        let got = decode_block(&b, Check::Crc16).unwrap();
360        assert_eq!(got.num, 3);
361        assert!(got.data.starts_with(b"hello"));
362        assert_eq!(
363            decode_block(&b, Check::Checksum),
364            Err(BlockError::BadLength)
365        );
366        let mut bad = b.clone();
367        bad[10] ^= 1;
368        assert_eq!(decode_block(&bad, Check::Crc16), Err(BlockError::BadCheck));
369        let mut bad = b.clone();
370        bad[2] = 0;
371        assert_eq!(decode_block(&bad, Check::Crc16), Err(BlockError::BadNumber));
372        assert_eq!(
373            decode_block(&[EOT], Check::Crc16),
374            Err(BlockError::BadHeader)
375        );
376    }
377}