kermit-proto 0.3.0

Sans-IO Kermit client and server for HP calculators: the client for the Kermit servers of the 48 and 49, the server for the 38G, 39G and 40G
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Packet framing: character transforms, block checks, packet encoding and the
//! byte-stream deframer.

/// Start-of-header byte that begins every packet.
pub const SOH: u8 = 0x01;
/// Carriage return, the default end-of-line byte.
pub const CR: u8 = 0x0D;
/// Largest LEN value a (short) packet can carry: `tochar(94)` is `~`.
pub const MAX_LEN: usize = 94;

/// Turn a small number (0..=94) into a printable character.
pub const fn tochar(x: u8) -> u8 {
    x.wrapping_add(32)
}

/// Inverse of [`tochar`].
pub const fn unchar(x: u8) -> u8 {
    x.wrapping_sub(32)
}

/// Toggle bit 6, mapping control characters to printable ones and back.
pub const fn ctl(x: u8) -> u8 {
    x ^ 64
}

/// Block check type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum BlockCheck {
    /// Single-character arithmetic checksum.
    Type1,
    /// Two-character 12-bit checksum.
    Type2,
    /// Three-character CRC-16/KERMIT.
    #[default]
    Type3,
}

impl BlockCheck {
    /// Number of check characters on the wire (1, 2 or 3).
    #[allow(clippy::len_without_is_empty)]
    pub fn len(self) -> usize {
        match self {
            BlockCheck::Type1 => 1,
            BlockCheck::Type2 => 2,
            BlockCheck::Type3 => 3,
        }
    }

    /// Parse the CHKT Send-Init field (`b'1'`, `b'2'`, `b'3'`).
    pub fn from_char(c: u8) -> Option<Self> {
        match c {
            b'1' => Some(BlockCheck::Type1),
            b'2' => Some(BlockCheck::Type2),
            b'3' => Some(BlockCheck::Type3),
            _ => None,
        }
    }

    /// The CHKT Send-Init field for this check type.
    pub fn to_char(self) -> u8 {
        match self {
            BlockCheck::Type1 => b'1',
            BlockCheck::Type2 => b'2',
            BlockCheck::Type3 => b'3',
        }
    }

    /// Compute the check characters over `body` (LEN through the end of DATA).
    pub fn compute(self, body: &[u8]) -> Vec<u8> {
        match self {
            BlockCheck::Type1 => {
                let s: u32 = body.iter().map(|&b| u32::from(b)).sum();
                vec![tochar(((s + ((s & 192) >> 6)) & 63) as u8)]
            }
            BlockCheck::Type2 => {
                let s: u32 = body.iter().map(|&b| u32::from(b)).sum::<u32>() & 0xFFF;
                vec![tochar(((s >> 6) & 63) as u8), tochar((s & 63) as u8)]
            }
            BlockCheck::Type3 => {
                let crc = crc16(body);
                vec![
                    tochar(((crc >> 12) & 15) as u8),
                    tochar(((crc >> 6) & 63) as u8),
                    tochar((crc & 63) as u8),
                ]
            }
        }
    }
}

/// CRC-16/KERMIT (init 0) as used by the type 3 block check.
pub fn crc16(body: &[u8]) -> u16 {
    let mut crc: u16 = 0;
    for &b in body {
        let b = u16::from(b);
        crc = (crc >> 4) ^ (((crc ^ b) & 15) * 0x1081);
        crc = (crc >> 4) ^ (((crc ^ (b >> 4)) & 15) * 0x1081);
    }
    crc
}

/// One packet; `data` is the already prefix-encoded data field.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Packet {
    /// Sequence number, 0..=63.
    pub seq: u8,
    /// Packet type, e.g. `b'D'`.
    pub kind: u8,
    /// Encoded data field.
    pub data: Vec<u8>,
}

impl Packet {
    /// Build a packet; `seq` is stored modulo 64.
    pub fn new(seq: u8, kind: u8, data: Vec<u8>) -> Self {
        Packet {
            seq: seq % 64,
            kind,
            data,
        }
    }

    /// Longest data field that fits in a packet whose LEN may be at most
    /// `maxl` (capped at [`MAX_LEN`]) with block check `check`.
    pub fn max_data(maxl: usize, check: BlockCheck) -> usize {
        maxl.min(MAX_LEN).saturating_sub(2 + check.len())
    }

    /// NPAD x PADC, SOH, LEN, SEQ, TYPE, DATA, CHECK, EOL.
    ///
    /// Fails if the data field does not fit in a (short) packet:
    /// `data.len()` must be at most `Packet::max_data(MAX_LEN, check)`.
    pub fn encode(&self, check: BlockCheck, framing: &Framing) -> Result<Vec<u8>, EncodeError> {
        let max = Packet::max_data(MAX_LEN, check);
        if self.data.len() > max {
            return Err(EncodeError {
                len: self.data.len(),
                max,
            });
        }
        Ok(self.wire(check, framing))
    }

    /// [`Packet::encode`] for data the caller has already fitted (the
    /// client sizes every data field with [`Packet::max_data`]). Should the
    /// invariant break, LEN saturates at `~` rather than wrapping into a
    /// different, valid-looking length.
    pub(crate) fn wire(&self, check: BlockCheck, framing: &Framing) -> Vec<u8> {
        let len = 2 + self.data.len() + check.len();
        debug_assert!(
            len <= MAX_LEN,
            "packet data too long: LEN {len} exceeds {MAX_LEN}"
        );
        let len_char = u8::try_from(len.min(MAX_LEN)).map_or(tochar(94), tochar);
        let mut out = Vec::with_capacity(usize::from(framing.npad) + len + 3);
        out.extend(std::iter::repeat_n(framing.padc, usize::from(framing.npad)));
        out.push(SOH);
        let body_start = out.len();
        out.push(len_char);
        out.push(tochar(self.seq % 64));
        out.push(self.kind);
        out.extend_from_slice(&self.data);
        let chk = check.compute(&out[body_start..]);
        out.extend_from_slice(&chk);
        out.push(framing.eol);
        out
    }
}

/// [`Packet::encode`] was given a data field that does not fit in a packet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncodeError {
    /// Length of the data field.
    pub len: usize,
    /// Longest data field that fits with the block check used.
    pub max: usize,
}

impl std::fmt::Display for EncodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "packet data too long: {} bytes, at most {} fit",
            self.len, self.max
        )
    }
}

impl std::error::Error for EncodeError {}

/// What the peer asked us to put around each packet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Framing {
    /// Number of pad bytes before each packet.
    pub npad: u8,
    /// The pad byte.
    pub padc: u8,
    /// End-of-line byte after each packet.
    pub eol: u8,
}

impl Default for Framing {
    fn default() -> Self {
        Framing {
            npad: 0,
            padc: 0,
            eol: CR,
        }
    }
}

/// Reasons a frame is rejected by [`parse_frame`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FrameError {
    /// LEN out of range or inconsistent with the frame size.
    BadLength,
    /// The block check does not match.
    BadCheck,
}

/// Accumulates raw input bytes and splits out complete frames.
#[derive(Debug, Default)]
pub struct Deframer {
    buf: Vec<u8>,
}

impl Deframer {
    /// Empty deframer.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append received bytes.
    pub fn push(&mut self, bytes: &[u8]) {
        self.buf.extend_from_slice(bytes);
    }

    /// Next complete frame: from SOH through the last CHECK byte (EOL and anything
    /// between frames is dropped). Rules: discard bytes before the first SOH; if
    /// unchar(LEN) is < 3 or > 94, drop that SOH and rescan; if another SOH appears
    /// before the frame is complete, restart at the new SOH (all control chars are
    /// prefixed, so a bare SOH always starts a packet). Returns None if incomplete.
    ///
    /// Linear in the buffered input: the scan moves a cursor and the buffer is
    /// shifted once per call, so a long run of SOH bytes costs no more than
    /// any other noise.
    pub fn next_frame(&mut self) -> Option<Vec<u8>> {
        let mut from = 0;
        loop {
            let Some(s) = self
                .buf
                .get(from..)
                .and_then(|rest| rest.iter().position(|&b| b == SOH))
                .map(|i| from + i)
            else {
                self.buf.clear();
                return None;
            };
            let Some(&len_byte) = self.buf.get(s + 1) else {
                self.buf.drain(..s);
                return None;
            };
            let len = usize::from(unchar(len_byte));
            if !(3..=94).contains(&len) {
                from = s + 1;
                continue;
            }
            let total = 2 + len;
            let end = (s + total).min(self.buf.len());
            if let Some(j) = self.buf[s + 1..end].iter().position(|&b| b == SOH) {
                from = s + 1 + j;
                continue;
            }
            if self.buf.len() < s + total {
                self.buf.drain(..s);
                return None;
            }
            let frame = self.buf[s..s + total].to_vec();
            self.buf.drain(..s + total);
            return Some(frame);
        }
    }

    /// Drop all buffered input.
    pub fn clear(&mut self) {
        self.buf.clear();
    }
}

/// Verify the check and split a frame from [`Deframer::next_frame`].
/// `check` is used except for kind b'N': a NAK has no data, so its check length is
/// unchar(LEN) - 2 (Kermit manual p. 30) when that is 1..=3.
pub fn parse_frame(frame: &[u8], check: BlockCheck) -> Result<Packet, FrameError> {
    if frame.len() < 5 || frame[0] != SOH {
        return Err(FrameError::BadLength);
    }
    let len = usize::from(unchar(frame[1]));
    if !(3..=94).contains(&len) || frame.len() != 2 + len {
        return Err(FrameError::BadLength);
    }
    let kind = frame[3];
    let check = if kind == b'N' {
        match len - 2 {
            1 => BlockCheck::Type1,
            2 => BlockCheck::Type2,
            3 => BlockCheck::Type3,
            _ => check,
        }
    } else {
        check
    };
    let cl = check.len();
    if len < 2 + cl {
        return Err(FrameError::BadLength);
    }
    let split = frame.len() - cl;
    if check.compute(&frame[1..split]) != frame[split..] {
        return Err(FrameError::BadCheck);
    }
    Ok(Packet::new(
        unchar(frame[2]),
        kind,
        frame[4..split].to_vec(),
    ))
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    /// (wire bytes incl. CR, seq, kind, data)
    const VECTORS: &[(&[u8], u8, u8, &[u8])] = &[
        (b"\x01, I~* @-#Y3~Z\r", 0, b'I', b"~* @-#Y3~"),
        (b"\x01+ Y~& @-# 3,\r", 0, b'Y', b"~& @-# 3"),
        (b"\x01( C6 7 *C\r", 0, b'C', b"6 7 *"),
        (b"\x01+ S~* @-#Y3$\r", 0, b'S', b"~* @-#Y3"),
        (b"\x01# N3\r", 0, b'N', b""),
        (b"\x01#!X>\r", 1, b'X', b""),
        (b"\x01#!Y?\r", 1, b'Y', b""),
        (
            b"\x01?\"D1:                    42#M#J6\r",
            2,
            b'D',
            b"1:                    42#M#J",
        ),
    ];

    #[test]
    fn char_transforms() {
        assert_eq!(tochar(0), b' ');
        assert_eq!(tochar(94), b'~');
        assert_eq!(unchar(b'~'), 94);
        assert_eq!(unchar(tochar(17)), 17);
        assert_eq!(ctl(0), b'@');
        assert_eq!(ctl(b'M'), CR);
        assert_eq!(ctl(0x7F), b'?');
    }

    #[test]
    fn crc_vector() {
        assert_eq!(crc16(b"123456789"), 0x2189);
        assert_eq!(crc16(b""), 0);
    }

    #[test]
    fn check_types() {
        assert_eq!(BlockCheck::Type1.compute(b"# N"), b"3");
        let s: u32 = b"abc".iter().map(|&b| u32::from(b)).sum();
        assert_eq!(
            BlockCheck::Type2.compute(b"abc"),
            vec![tochar(((s >> 6) & 63) as u8), tochar((s & 63) as u8)]
        );
        let c = crc16(b"123456789");
        assert_eq!(
            BlockCheck::Type3.compute(b"123456789"),
            vec![
                tochar((c >> 12) as u8 & 15),
                tochar((c >> 6) as u8 & 63),
                tochar(c as u8 & 63)
            ]
        );
        for t in [BlockCheck::Type1, BlockCheck::Type2, BlockCheck::Type3] {
            assert_eq!(BlockCheck::from_char(t.to_char()), Some(t));
            assert_eq!(t.compute(b"xyz").len(), t.len());
        }
        assert_eq!(BlockCheck::from_char(b'4'), None);
        assert_eq!(BlockCheck::default(), BlockCheck::Type3);
    }

    #[test]
    fn wire_vectors_round_trip() {
        for &(wire, seq, kind, data) in VECTORS {
            let frame = &wire[..wire.len() - 1];
            let p = parse_frame(frame, BlockCheck::Type1).unwrap();
            assert_eq!(p, Packet::new(seq, kind, data.to_vec()), "{wire:?}");
            assert_eq!(
                p.encode(BlockCheck::Type1, &Framing::default()),
                Ok(wire.to_vec())
            );
        }
    }

    #[test]
    fn type2_type3_round_trip() {
        let p = Packet::new(70, b'D', b"hello #M#J world".to_vec());
        assert_eq!(p.seq, 6);
        for t in [BlockCheck::Type1, BlockCheck::Type2, BlockCheck::Type3] {
            let wire = p.encode(t, &Framing::default()).unwrap();
            let frame = &wire[..wire.len() - 1];
            assert_eq!(parse_frame(frame, t).unwrap(), p);
        }
    }

    #[test]
    fn max_data_and_longest_packet() {
        assert_eq!(Packet::max_data(80, BlockCheck::Type1), 77);
        assert_eq!(Packet::max_data(94, BlockCheck::Type3), 89);
        assert_eq!(Packet::max_data(200, BlockCheck::Type3), 89);
        assert_eq!(Packet::max_data(3, BlockCheck::Type3), 0);
        let p = Packet::new(0, b'D', vec![b'x'; 89]);
        let wire = p.encode(BlockCheck::Type3, &Framing::default()).unwrap();
        assert_eq!(wire[1], b'~');
        let frame = &wire[..wire.len() - 1];
        assert_eq!(parse_frame(frame, BlockCheck::Type3).unwrap(), p);
    }

    #[test]
    fn oversized_packet_is_an_error() {
        let p = Packet::new(0, b'D', vec![b'x'; 90]);
        let err = p.encode(BlockCheck::Type3, &Framing::default());
        assert_eq!(err, Err(EncodeError { len: 90, max: 89 }));
        let p = Packet::new(0, b'D', vec![b'x'; 91]);
        assert!(p.encode(BlockCheck::Type1, &Framing::default()).is_ok());
        let p = Packet::new(0, b'D', vec![b'x'; 92]);
        assert!(p.encode(BlockCheck::Type1, &Framing::default()).is_err());
    }

    #[test]
    fn padding_and_eol() {
        let f = Framing {
            npad: 2,
            padc: 0,
            eol: b'\n',
        };
        let wire = Packet::new(1, b'Y', vec![])
            .encode(BlockCheck::Type1, &f)
            .unwrap();
        assert_eq!(wire, b"\0\0\x01#!Y?\n");
    }

    #[test]
    fn bad_check_detected() {
        let wire = Packet::new(3, b'D', b"abcdef".to_vec())
            .encode(BlockCheck::Type3, &Framing::default())
            .unwrap();
        let mut frame = wire[..wire.len() - 1].to_vec();
        frame[6] ^= 1;
        assert_eq!(
            parse_frame(&frame, BlockCheck::Type3),
            Err(FrameError::BadCheck)
        );
    }

    #[test]
    fn bad_length() {
        assert_eq!(
            parse_frame(b"\x01$ Y?", BlockCheck::Type1),
            Err(FrameError::BadLength)
        );
        assert_eq!(
            parse_frame(b"\x01\" Y?", BlockCheck::Type1),
            Err(FrameError::BadLength)
        );
        // LEN 3 with a type 3 check leaves no room.
        assert_eq!(
            parse_frame(b"\x01# Y?", BlockCheck::Type3),
            Err(FrameError::BadLength)
        );
    }

    #[test]
    fn nak_check_length_heuristic() {
        let nak = Packet::new(5, b'N', vec![]);
        for t in [BlockCheck::Type1, BlockCheck::Type2, BlockCheck::Type3] {
            let wire = nak.encode(t, &Framing::default()).unwrap();
            let frame = &wire[..wire.len() - 1];
            assert_eq!(parse_frame(frame, BlockCheck::Type1).unwrap(), nak);
            assert_eq!(parse_frame(frame, BlockCheck::Type3).unwrap(), nak);
        }
    }

    fn drain(d: &mut Deframer) -> Vec<Vec<u8>> {
        let mut v = Vec::new();
        while let Some(f) = d.next_frame() {
            v.push(f);
        }
        v
    }

    #[test]
    fn deframer_byte_by_byte() {
        let mut d = Deframer::new();
        let mut frames = Vec::new();
        let input: Vec<u8> = VECTORS.iter().flat_map(|v| v.0.iter().copied()).collect();
        for b in input {
            d.push(&[b]);
            frames.extend(drain(&mut d));
        }
        assert_eq!(frames.len(), VECTORS.len());
        for (f, v) in frames.iter().zip(VECTORS) {
            assert_eq!(f.as_slice(), &v.0[..v.0.len() - 1]);
        }
    }

    #[test]
    fn deframer_garbage_and_two_packets() {
        let mut d = Deframer::new();
        d.push(b"noise\r\n\x01# N3\r\x01#!Y?\r");
        assert_eq!(
            drain(&mut d),
            vec![b"\x01# N3".to_vec(), b"\x01#!Y?".to_vec()]
        );
        d.push(b"only garbage");
        assert_eq!(d.next_frame(), None);
    }

    #[test]
    fn deframer_invalid_len_skipped() {
        let mut d = Deframer::new();
        d.push(b"\x01\x7f\x01\"x\x01#!Y?\r");
        assert_eq!(drain(&mut d), vec![b"\x01#!Y?".to_vec()]);
    }

    #[test]
    fn deframer_resync_on_truncated() {
        let mut d = Deframer::new();
        d.push(b"\x01?\"D1:   ");
        assert_eq!(d.next_frame(), None);
        d.push(b"\x01#!Y?\r");
        assert_eq!(drain(&mut d), vec![b"\x01#!Y?".to_vec()]);
    }

    #[test]
    fn deframer_soh_run_is_linear() {
        // 1 MiB of SOH: every LEN byte is SOH (invalid). Quadratic resync
        // would take minutes; one linear pass is milliseconds.
        let mut d = Deframer::new();
        d.push(&vec![SOH; 1 << 20]);
        let t = std::time::Instant::now();
        assert_eq!(d.next_frame(), None);
        assert!(t.elapsed() < std::time::Duration::from_secs(2));
        // The trailing SOH may still start a packet.
        d.push(b"#!Y?\r");
        assert_eq!(drain(&mut d), vec![b"\x01#!Y?".to_vec()]);
        // A run of valid-looking SOH LEN pairs, each cut short by the next SOH.
        let mut d = Deframer::new();
        d.push(&b"\x01~".repeat(1 << 19));
        let t = std::time::Instant::now();
        assert_eq!(d.next_frame(), None);
        assert!(t.elapsed() < std::time::Duration::from_secs(2));
    }

    #[test]
    fn deframer_clear() {
        let mut d = Deframer::new();
        d.push(b"\x01#!Y");
        d.clear();
        d.push(b"?\r");
        assert_eq!(d.next_frame(), None);
    }
}