Skip to main content

xmodem_proto/
transfer.rs

1//! The XModem state machine, both roles. wiki: protocols/xmodem,
2//! protocols/xmodem-hp.
3
4use crate::time::{Duration, Instant};
5use std::collections::VecDeque;
6use std::fmt;
7
8use crate::codec::{
9    ACK, BlockSize, CAN, CR_KERMIT, Check, EOT, NAK, SOH, STX, SUB, decode_block, frame_block,
10    frame_len,
11};
12
13/// Tunables of a [`Transfer`].
14///
15/// Non-exhaustive: start from [`Config::default`] and set the fields you
16/// need.
17#[derive(Clone, Debug)]
18#[non_exhaustive]
19pub struct Config {
20    /// Receiver: the check asked for first. [`Check::HpCrc`] (default) sends
21    /// `D`, [`Check::Crc16`] sends `C`; both fall back to NAK (checksum)
22    /// after [`Config::crc_attempts`] unanswered start characters.
23    /// [`Check::Checksum`] sends NAK from the start. The sender ignores this
24    /// and uses whatever the receiver asks for (NAK, `C` or `D`). Before
25    /// the first ACK the sender follows a later `C` or `D`, and a NAK after
26    /// `D` (the 49G's fallback); a NAK in CRC-16 mode only resends block 1
27    /// in CRC-16, since a standard receiver NAKs a damaged block that way.
28    ///
29    /// `D` is the default because no HP calculator answers `C`: the 49G's
30    /// XSEND answers `D` with HP-CRC blocks (1k blocks when the object is big
31    /// enough) and ignores `C`; the 48GX's XSEND ignores both and answers the
32    /// NAK. Verified on the emulated 49G and 48GX (traces `49g-xsend*`,
33    /// `48gx-xsend*`).
34    pub check: Check,
35    /// Receiver: `C`s (or `D`s) sent before falling back to checksum
36    /// (default 3).
37    pub crc_attempts: u32,
38    /// Receiver: wait after each `C` or `D` before the next start character
39    /// (default 3 s).
40    pub crc_interval: Duration,
41    /// Sender: block size for full blocks (default 128). 1k blocks go out
42    /// only when the receiver asked for a CRC (`C` or `D`), unless
43    /// [`Config::checksum_1k`] is set: a receiver that opens with NAK gets
44    /// 128-byte blocks.
45    pub block_size: BlockSize,
46    /// Sender: also send 1k blocks when the receiver asked for checksum mode
47    /// (default false). The 48GX, which knows only checksum mode, NAKs every
48    /// 1k block and cancels after nine (trace `48gx-xrecv-1k`); XModem-1K
49    /// is classically used with CRC only.
50    pub checksum_1k: bool,
51    /// Sender with 1k blocks: send the tail of the file in 128-byte blocks once
52    /// no more than 896 bytes (7 x 128) remain, so no block carries 128 or
53    /// more bytes of padding (default true). The 49G does not convert a
54    /// received object with more than about 255 bytes of padding (as HP's
55    /// Conn4x source notes).
56    pub short_tail: bool,
57    /// Sender: padding byte for the last block (default 0x1A, SUB).
58    pub pad: u8,
59    /// Sender: how long to wait for the receiver's first start character
60    /// (default 60 s). Receiver: the overall wait for the first block is
61    /// bounded by the start-character retries instead, or by
62    /// [`Config::recv_start_timeout`].
63    pub start_timeout: Duration,
64    /// Wait for an ACK/NAK (sender) or for the next block (receiver)
65    /// (default 10 s).
66    pub timeout: Duration,
67    /// Receiver: longest gap between two bytes of one block (default 1 s).
68    pub byte_timeout: Duration,
69    /// Receiver: after a bad block, input must be silent this long before we
70    /// NAK, so the sender hears the NAK (default 1 s).
71    pub purge: Duration,
72    /// Retries per block (or per EOT, or NAKs while starting) before giving
73    /// up (default 10).
74    pub retries: u32,
75    /// Receiver: keep sending start characters until this much time has
76    /// passed since [`Transfer::start`], instead of stopping after
77    /// `crc_attempts + retries` of them (default `None`: count only). For
78    /// a transfer a human starts on the calculator keyboard. The switch
79    /// from `C`/`D` to NAK still happens after [`Config::crc_attempts`].
80    pub recv_start_timeout: Option<Duration>,
81    /// Receiver: after we ACK the EOT, keep answering a retransmitted EOT
82    /// with ACK for this long (default 1 s), in case our ACK was damaged or
83    /// lost. `FileEnd` and `Done` are emitted when the ACK is queued; the
84    /// linger emits nothing. [`Transfer::is_idle`] is false while it lasts;
85    /// [`Transfer::start`] ends it early. `Duration::ZERO` turns it off. A
86    /// sender that only retransmits after its reply timeout is caught only
87    /// by a linger that long.
88    pub linger: Duration,
89    /// Receiver: most data bytes (padding included) accepted; a block that
90    /// would go beyond fails the transfer with [`Error::TooLarge`] and CANs.
91    /// Default 4 MiB, well above the largest HP object; `None` means no
92    /// limit. XModem has no length field and block numbers wrap, so without
93    /// a limit a peer can grow the buffer without bound.
94    pub max_size: Option<usize>,
95}
96
97/// Default [`Config::max_size`]: 4 MiB.
98const DEFAULT_MAX_SIZE: usize = 4 << 20;
99
100impl Default for Config {
101    fn default() -> Self {
102        Config {
103            check: Check::HpCrc,
104            crc_attempts: 3,
105            crc_interval: Duration::from_secs(3),
106            block_size: BlockSize::B128,
107            checksum_1k: false,
108            short_tail: true,
109            pad: SUB,
110            start_timeout: Duration::from_secs(60),
111            timeout: Duration::from_secs(10),
112            byte_timeout: Duration::from_secs(1),
113            purge: Duration::from_secs(1),
114            retries: 10,
115            recv_start_timeout: None,
116            linger: Duration::from_secs(1),
117            max_size: Some(DEFAULT_MAX_SIZE),
118        }
119    }
120}
121
122/// One transfer.
123#[derive(Clone, Debug, PartialEq, Eq)]
124#[non_exhaustive]
125pub enum Command {
126    /// We are the sender (the calculator runs `XRECV`); the whole file.
127    Send(Vec<u8>),
128    /// We are the receiver (the calculator runs `XSEND`).
129    Receive,
130}
131
132/// Something that happened during a transfer.
133#[derive(Clone, Debug, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum Event {
136    /// The check the transfer runs with is settled: sender, on the receiver's
137    /// start character, and again if a later start character before the
138    /// first ACK changes it (`C` or `D` at any time before the first ACK; NAK
139    /// only after `D`, the 49G's fallback to checksum: after `C` a NAK asks
140    /// for a damaged block 1 again in CRC-16); receiver, on the first block.
141    Started {
142        /// The block check in use.
143        check: Check,
144    },
145    /// After each acknowledged block (send) or accepted new block (receive).
146    Progress {
147        /// Bytes of the file acknowledged (send, at most the file size) or
148        /// received (receive, padding included).
149        bytes: u64,
150        /// File size when sending; `None` when receiving.
151        total: Option<u64>,
152    },
153    /// Receive: EOT acknowledged; the file as received.
154    FileEnd {
155        /// Every data byte received, padding of the last block included:
156        /// stripping it is the caller's job. XModem carries no file length.
157        /// For an HP object (the calculators send binary objects: an 8-byte
158        /// `HPHP48-x`/`HPHP49-x` header, then the object), the real end is
159        /// found by walking the object: read its prolog and the size its
160        /// type implies (a length field for strings, code and the like, the
161        /// nested objects for composites), and cut there.
162        data: Vec<u8>,
163        /// Size of the last block (128 or 1024; 0 for an empty transfer):
164        /// the most padding the file can carry.
165        last_block: usize,
166        /// Trailing bytes of the last block equal to its final byte, when that
167        /// byte is 0x1A or 0x00: the likely padding. A hint only; real data
168        /// may end in such bytes, and the 49G's XSEND pads with whatever
169        /// follows the object in memory (hint 0), while the 48GX pads with
170        /// zeros. Only the object-length walk finds the real end.
171        padding: usize,
172    },
173    /// Terminal failure; the machine is idle.
174    Error(Error),
175    /// Terminal success. The machine is idle, or, as receiver, lingers
176    /// after the final ACK ([`Config::linger`]).
177    Done,
178}
179
180/// Why a transfer failed.
181#[derive(Clone, Debug, PartialEq, Eq)]
182#[non_exhaustive]
183pub enum Error {
184    /// Retries exhausted, or no start character within `start_timeout`.
185    Timeout,
186    /// The peer sent two CANs in a row.
187    RemoteCancelled,
188    /// A block out of sequence (lost sync); we sent CANs.
189    Protocol(String),
190    /// [`Transfer::cancel`] was called; we sent CANs.
191    Cancelled,
192    /// The received data exceeded [`Config::max_size`]; we sent CANs.
193    TooLarge {
194        /// The limit that was exceeded.
195        limit: usize,
196    },
197}
198
199impl fmt::Display for Error {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        match self {
202            Error::Timeout => f.write_str("timed out: too many retries"),
203            Error::RemoteCancelled => f.write_str("cancelled by the peer"),
204            Error::Protocol(msg) => write!(f, "protocol error: {msg}"),
205            Error::Cancelled => f.write_str("cancelled"),
206            Error::TooLarge { limit } => {
207                write!(f, "received data exceeds the limit of {limit} bytes")
208            }
209        }
210    }
211}
212
213impl std::error::Error for Error {}
214
215/// Why [`Transfer::start`] refused a command.
216#[derive(Clone, Copy, Debug, PartialEq, Eq)]
217#[non_exhaustive]
218pub enum StartError {
219    /// A transfer is already running.
220    Busy,
221}
222
223impl fmt::Display for StartError {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        f.write_str("a transfer is already running")
226    }
227}
228
229impl std::error::Error for StartError {}
230
231/// What we wait for after a queued write is handed out.
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
233enum Wait {
234    /// Nothing (terminal output).
235    None,
236    /// The normal reply timeout.
237    Reply,
238    /// The next start character after a `C`.
239    CrcInterval,
240}
241
242#[derive(Debug)]
243enum Phase {
244    Idle,
245    /// Sender: waiting for NAK, `C` or `D`. `skip`: bytes left to skip of a
246    /// Kermit packet (SOH .. CR) the calculator may still send.
247    SendStart {
248        skip: u8,
249    },
250    /// Sender: block at `pos` of `len` data bytes is out, awaiting ACK.
251    SendBlock {
252        len: usize,
253    },
254    /// Sender: EOT is out, awaiting ACK.
255    SendEot,
256    /// Receiver: start characters going out, no block yet.
257    RecvStart,
258    /// Receiver: blocks flowing.
259    RecvBlocks,
260    /// Receiver: EOT acknowledged; re-ACK a retransmitted EOT until
261    /// `deadline`.
262    RecvLinger,
263}
264
265/// Sans-IO XModem transfer, sender or receiver. See the crate documentation
266/// for the driver loop.
267#[derive(Debug)]
268pub struct Transfer {
269    config: Config,
270    phase: Phase,
271    check: Check,
272    /// Send: the file. Receive: the data received so far.
273    data: Vec<u8>,
274    /// Send: offset of the current block.
275    pos: usize,
276    /// Send: current block number. Receive: the next expected block number.
277    blk: u8,
278    /// Send: some block has been ACKed (later `C`s are ignored).
279    acked_any: bool,
280    last_sent: Vec<u8>,
281    queue: VecDeque<(Vec<u8>, Wait)>,
282    events: VecDeque<Event>,
283    deadline: Option<Instant>,
284    retries: u32,
285    /// Consecutive CANs seen where a control byte was expected.
286    cans: u8,
287    /// Receive: start characters sent so far.
288    starts: u32,
289    /// Receive: partial frame.
290    buf: Vec<u8>,
291    /// Receive: when the last byte of `buf` arrived.
292    last_byte: Option<Instant>,
293    /// Receive: discarding input until the line is quiet, then NAK.
294    purging: bool,
295    /// Receive: size of the last accepted block.
296    last_block: usize,
297    /// Receive: when [`Transfer::start`] ran (for
298    /// [`Config::recv_start_timeout`]).
299    started_at: Option<Instant>,
300    /// Receive, starting: the start-character deadline, held while a block
301    /// arrives (the byte timeout governs it) and restored if it is dropped.
302    held_deadline: Option<Instant>,
303}
304
305const CANCEL: [u8; 3] = [CAN, CAN, CAN];
306
307/// Longest Kermit packet after its SOH: LEN, at most 94 more bytes, CR.
308const KERMIT_MAX_PACKET: u8 = 96;
309
310impl Transfer {
311    /// New idle machine.
312    pub fn new(config: Config) -> Self {
313        Transfer {
314            check: config.check,
315            config,
316            phase: Phase::Idle,
317            data: Vec::new(),
318            pos: 0,
319            blk: 1,
320            acked_any: false,
321            last_sent: Vec::new(),
322            queue: VecDeque::new(),
323            events: VecDeque::new(),
324            deadline: None,
325            retries: 0,
326            cans: 0,
327            starts: 0,
328            buf: Vec::new(),
329            last_byte: None,
330            purging: false,
331            last_block: 0,
332            started_at: None,
333            held_deadline: None,
334        }
335    }
336
337    /// Begin a transfer. A sender waits for the receiver's start character
338    /// (nothing to write yet); a receiver's first start character is available
339    /// from `poll_output(now)` at once.
340    ///
341    /// Output and events of the previous transfer that were not polled yet
342    /// are dropped; a linger after it ([`Config::linger`]) ends.
343    pub fn start(&mut self, now: Instant, command: Command) -> Result<(), StartError> {
344        if !matches!(self.phase, Phase::Idle | Phase::RecvLinger) {
345            return Err(StartError::Busy);
346        }
347        self.queue.clear();
348        self.events.clear();
349        self.held_deadline = None;
350        self.pos = 0;
351        self.blk = 1;
352        self.acked_any = false;
353        self.retries = 0;
354        self.cans = 0;
355        self.starts = 0;
356        self.buf.clear();
357        self.last_byte = None;
358        self.purging = false;
359        self.last_block = 0;
360        self.last_sent.clear();
361        self.started_at = Some(now);
362        match command {
363            Command::Send(data) => {
364                self.data = data;
365                self.phase = Phase::SendStart { skip: 0 };
366                self.deadline = now.checked_add(self.config.start_timeout);
367            }
368            Command::Receive => {
369                self.data = Vec::new();
370                self.check = self.config.check;
371                self.phase = Phase::RecvStart;
372                self.deadline = None;
373                self.send_start_char(now);
374            }
375        }
376        Ok(())
377    }
378
379    /// Feed bytes read from the link, in any chunking.
380    pub fn handle_input(&mut self, now: Instant, bytes: &[u8]) {
381        for &b in bytes {
382            if self.is_idle() {
383                return;
384            }
385            match self.phase {
386                Phase::Idle => {}
387                Phase::SendStart { .. } | Phase::SendBlock { .. } | Phase::SendEot => {
388                    self.on_send_byte(now, b)
389                }
390                Phase::RecvStart | Phase::RecvBlocks => self.on_recv_byte(now, b),
391                // A retransmitted EOT: our ACK was lost or damaged. One
392                // pending ACK answers any number of them.
393                Phase::RecvLinger if b == EOT => {
394                    if !self.queue.iter().any(|(q, _)| q.as_slice() == [ACK]) {
395                        self.push(vec![ACK], Wait::None);
396                    }
397                }
398                Phase::RecvLinger => {}
399            }
400        }
401    }
402
403    /// Call when the time from [`Transfer::next_timeout`] has passed (or
404    /// whenever a read times out; it does nothing early).
405    pub fn handle_timeout(&mut self, now: Instant) {
406        match self.next_timeout() {
407            Some(due) if now >= due => {}
408            _ => return,
409        }
410        self.deadline = None;
411        match self.phase {
412            Phase::Idle => {}
413            Phase::SendStart { .. } => self.finish(Event::Error(Error::Timeout)),
414            Phase::SendBlock { .. } | Phase::SendEot => self.resend(),
415            Phase::RecvStart => {
416                if !self.buf.is_empty() {
417                    // A block stalled: drop it and resume the start-character
418                    // interval that was running when it began.
419                    self.drop_partial();
420                    if self.deadline.is_some_and(|d| now < d) {
421                        return;
422                    }
423                }
424                self.purging = false;
425                self.send_start_char(now);
426            }
427            Phase::RecvBlocks => {
428                if self.purging || !self.buf.is_empty() {
429                    // The line went quiet after a bad or partial block.
430                    self.buf.clear();
431                    self.purging = false;
432                }
433                self.nak();
434            }
435            Phase::RecvLinger => self.phase = Phase::Idle,
436        }
437    }
438
439    /// Next bytes to write, written atomically: a whole block, a single
440    /// control byte, or the CAN sequence. Keep calling after `Done`/`Error`
441    /// until `None`: a final ACK or the CANs may still be queued.
442    pub fn poll_output(&mut self, now: Instant) -> Option<Vec<u8>> {
443        let (bytes, wait) = self.queue.pop_front()?;
444        // The linger's deadline is fixed when it starts.
445        if !matches!(self.phase, Phase::Idle | Phase::RecvLinger) {
446            let span = match wait {
447                Wait::None => None,
448                Wait::Reply => Some(self.config.timeout),
449                Wait::CrcInterval => Some(self.config.crc_interval),
450            };
451            // Overflow (absurd timeout) means no deadline.
452            self.deadline = span.and_then(|s| now.checked_add(s));
453        }
454        Some(bytes)
455    }
456
457    /// Next event, in order.
458    pub fn poll_event(&mut self) -> Option<Event> {
459        self.events.pop_front()
460    }
461
462    /// The earliest instant at which [`Transfer::handle_timeout`] has work.
463    pub fn next_timeout(&self) -> Option<Instant> {
464        if self.is_idle() {
465            return None;
466        }
467        let byte = match (self.purging, self.last_byte) {
468            (true, Some(t)) => t.checked_add(self.config.purge),
469            (false, Some(t)) if !self.buf.is_empty() => t.checked_add(self.config.byte_timeout),
470            _ => None,
471        };
472        match (byte, self.deadline) {
473            (Some(a), Some(b)) => Some(a.min(b)),
474            (a, b) => a.or(b),
475        }
476    }
477
478    /// No transfer running and no linger after one (output may still be
479    /// queued).
480    pub fn is_idle(&self) -> bool {
481        matches!(self.phase, Phase::Idle)
482    }
483
484    /// The check in use (receive: requested so far; settled after
485    /// [`Event::Started`]).
486    pub fn check(&self) -> Check {
487        self.check
488    }
489
490    /// Abort: queue the CAN sequence, emit `Error(Cancelled)`, go idle.
491    /// No-op when idle. During the linger after `Done` it only ends the
492    /// linger: no CANs, no event.
493    pub fn cancel(&mut self, _now: Instant) {
494        match self.phase {
495            Phase::Idle => {}
496            Phase::RecvLinger => {
497                self.phase = Phase::Idle;
498                self.deadline = None;
499            }
500            _ => self.fail(Error::Cancelled, true),
501        }
502    }
503
504    // ---- helpers ----
505
506    fn push(&mut self, bytes: Vec<u8>, wait: Wait) {
507        self.queue.push_back((bytes, wait));
508    }
509
510    /// Queue `bytes` as the retransmit copy.
511    fn send(&mut self, bytes: Vec<u8>) {
512        self.last_sent = bytes.clone();
513        self.deadline = None;
514        self.push(bytes, Wait::Reply);
515    }
516
517    fn finish(&mut self, event: Event) {
518        self.events.push_back(event);
519        self.phase = Phase::Idle;
520        self.deadline = None;
521        self.buf.clear();
522        self.last_byte = None;
523        self.purging = false;
524    }
525
526    /// Emit Error, optionally queue CANs (dropping anything still queued),
527    /// go idle.
528    fn fail(&mut self, err: Error, cancel: bool) {
529        self.queue.clear();
530        if cancel {
531            self.push(CANCEL.to_vec(), Wait::None);
532        }
533        self.finish(Event::Error(err));
534    }
535
536    /// Count a retry; true if the caller may retry, otherwise the transfer
537    /// failed with a timeout.
538    fn retry(&mut self) -> bool {
539        self.retries += 1;
540        if self.retries > self.config.retries {
541            self.fail(Error::Timeout, true);
542            false
543        } else {
544            true
545        }
546    }
547
548    /// A CAN where a control byte was expected; true once two came in a row.
549    fn on_can(&mut self, b: u8) -> bool {
550        if b == CAN {
551            self.cans += 1;
552            if self.cans >= 2 {
553                self.fail(Error::RemoteCancelled, false);
554                return true;
555            }
556        } else {
557            self.cans = 0;
558        }
559        false
560    }
561
562    // ---- sender ----
563
564    /// Data length of the block at `pos`.
565    fn block_len(&self) -> (BlockSize, usize) {
566        let left = self.data.len().saturating_sub(self.pos);
567        let size = match self.config.block_size {
568            BlockSize::B1k if self.check == Check::Checksum && !self.config.checksum_1k => {
569                BlockSize::B128
570            }
571            BlockSize::B1k if self.config.short_tail && left <= 7 * 128 => BlockSize::B128,
572            s => s,
573        };
574        (size, left.min(size.len()))
575    }
576
577    fn send_block(&mut self) {
578        if self.pos >= self.data.len() {
579            self.phase = Phase::SendEot;
580            self.send(vec![EOT]);
581            return;
582        }
583        let (size, len) = self.block_len();
584        let chunk = self.data.get(self.pos..self.pos + len).unwrap_or_default();
585        let bytes = frame_block(self.blk, size, chunk, self.config.pad, self.check);
586        self.phase = Phase::SendBlock { len };
587        self.send(bytes);
588    }
589
590    fn resend(&mut self) {
591        if self.retry() {
592            let bytes = self.last_sent.clone();
593            self.deadline = None;
594            self.push(bytes, Wait::Reply);
595        }
596    }
597
598    fn on_send_byte(&mut self, _now: Instant, b: u8) {
599        if self.on_can(b) {
600            return;
601        }
602        match self.phase {
603            Phase::SendStart { skip } => {
604                // A Kermit packet (SOH .. CR) from the calculator, e.g. the
605                // idle server's NAK or a reply whose D packets hold a `D`, may
606                // still be in the pipe; its bytes are not start characters.
607                // A packet is at most 96 bytes, so a lost CR cannot hide
608                // start characters for long.
609                if skip > 0 {
610                    let skip = if b == CR_KERMIT { 0 } else { skip - 1 };
611                    self.phase = Phase::SendStart { skip };
612                    return;
613                }
614                if b == SOH {
615                    self.phase = Phase::SendStart {
616                        skip: KERMIT_MAX_PACKET,
617                    };
618                    return;
619                }
620                let Some(check) = Check::from_start_char(b) else {
621                    return;
622                };
623                self.check = check;
624                self.events.push_back(Event::Started { check });
625                self.send_block();
626            }
627            // A reply cannot answer a write that is still queued.
628            _ if !self.queue.is_empty() => {}
629            // Before the first ACK the receiver may still be starting: `C`
630            // or `D` asks for block 1 again in the check it names. A NAK
631            // switches to checksum only from HP's CRC (the 49G's XRECV falls
632            // back from `D` to NAK); in CRC-16 or checksum mode it is a plain
633            // NAK for a damaged block 1, which a standard CRC-16 receiver
634            // sends while staying in CRC mode.
635            Phase::SendBlock { .. } if !self.acked_any && Check::from_start_char(b).is_some() => {
636                let Some(asked) = Check::from_start_char(b) else {
637                    return;
638                };
639                let check = match (asked, self.check) {
640                    (Check::Checksum, Check::Crc16) => Check::Crc16,
641                    (asked, _) => asked,
642                };
643                if self.retry() {
644                    if check != self.check {
645                        self.check = check;
646                        self.events.push_back(Event::Started { check });
647                    }
648                    // Re-encoded: the check (and with it the block size)
649                    // may have changed.
650                    self.send_block();
651                }
652            }
653            Phase::SendBlock { len } => match b {
654                ACK => {
655                    self.retries = 0;
656                    self.acked_any = true;
657                    self.pos += len;
658                    self.blk = self.blk.wrapping_add(1);
659                    self.events.push_back(Event::Progress {
660                        bytes: self.pos as u64,
661                        total: Some(self.data.len() as u64),
662                    });
663                    self.send_block();
664                }
665                NAK => self.resend(),
666                _ => {}
667            },
668            Phase::SendEot => match b {
669                ACK => self.finish(Event::Done),
670                NAK => self.resend(),
671                _ => {}
672            },
673            _ => {}
674        }
675    }
676
677    // ---- receiver ----
678
679    fn send_start_char(&mut self, now: Instant) {
680        let crc = self.config.check != Check::Checksum && self.starts < self.config.crc_attempts;
681        let limit = match self.config.check {
682            Check::Checksum => self.config.retries,
683            Check::Crc16 | Check::HpCrc => {
684                self.config.crc_attempts.saturating_add(self.config.retries)
685            }
686        };
687        let exhausted = match (self.config.recv_start_timeout, self.started_at) {
688            // Overflow (absurd timeout) means no limit.
689            (Some(window), Some(at)) => at.checked_add(window).is_some_and(|end| now >= end),
690            _ => self.starts >= limit,
691        };
692        if exhausted {
693            self.fail(Error::Timeout, true);
694            return;
695        }
696        self.starts += 1;
697        let (check, wait) = if crc {
698            (self.config.check, Wait::CrcInterval)
699        } else {
700            (Check::Checksum, Wait::Reply)
701        };
702        self.check = check;
703        self.last_sent = vec![check.start_char()];
704        self.push(vec![check.start_char()], wait);
705    }
706
707    fn nak(&mut self) {
708        if self.retry() {
709            self.send(vec![NAK]);
710        }
711    }
712
713    /// Starting: drop the partial frame and restore the start-character
714    /// deadline held while it arrived.
715    fn drop_partial(&mut self) {
716        self.buf.clear();
717        self.last_byte = None;
718        if let Some(d) = self.held_deadline.take() {
719            self.deadline = Some(d);
720        }
721    }
722
723    /// Bad frame while blocks flow: discard input until the line is quiet,
724    /// then NAK (from `handle_timeout`). A line that never goes quiet (a
725    /// babbling peer) gets the NAK after [`Config::timeout`] all the same,
726    /// so the retries run out instead of the purge lasting for ever.
727    fn purge(&mut self, now: Instant) {
728        self.buf.clear();
729        self.purging = true;
730        self.last_byte = Some(now);
731        self.deadline = now.checked_add(self.config.timeout);
732    }
733
734    fn on_recv_byte(&mut self, now: Instant, b: u8) {
735        if self.purging {
736            self.last_byte = Some(now);
737            return;
738        }
739        if self.buf.is_empty() {
740            if self.on_can(b) {
741                return;
742            }
743            match b {
744                SOH | STX => {
745                    self.buf.push(b);
746                    self.last_byte = Some(now);
747                    if matches!(self.phase, Phase::RecvStart) {
748                        // A block may be arriving: the byte timeout governs
749                        // it, not the start-character interval, which would
750                        // otherwise discard it (or switch the check) halfway.
751                        self.held_deadline = self.deadline.take();
752                    }
753                }
754                EOT if matches!(self.phase, Phase::RecvBlocks) => self.on_eot(now),
755                // Line noise or a Kermit packet before the transfer.
756                _ => {}
757            }
758            return;
759        }
760        self.buf.push(b);
761        self.last_byte = Some(now);
762        if self.buf.len() == 3 && self.buf.get(1).map(|n| !n) != self.buf.get(2).copied() {
763            // Not a block header: noise, or a Kermit packet (SOH LEN SEQ ..).
764            if matches!(self.phase, Phase::RecvStart) {
765                self.drop_partial();
766            } else {
767                self.purge(now);
768            }
769            return;
770        }
771        let size = match self.buf.first().and_then(|&h| BlockSize::from_header(h)) {
772            Some(s) => s,
773            None => return,
774        };
775        if self.buf.len() < frame_len(size, self.check) {
776            return;
777        }
778        let frame = std::mem::take(&mut self.buf);
779        self.last_byte = None;
780        self.on_frame(now, size, &frame);
781    }
782
783    fn on_frame(&mut self, now: Instant, size: BlockSize, frame: &[u8]) {
784        let block = match decode_block(frame, self.check) {
785            Ok(b) => b,
786            Err(_) => {
787                if matches!(self.phase, Phase::RecvStart) {
788                    // The check we asked for does not fit; keep asking.
789                    self.drop_partial();
790                    return;
791                }
792                self.purge(now);
793                return;
794            }
795        };
796        if matches!(self.phase, Phase::RecvStart) {
797            self.phase = Phase::RecvBlocks;
798            self.held_deadline = None;
799            self.events.push_back(Event::Started { check: self.check });
800        }
801        if block.num == self.blk {
802            if let Some(limit) = self.config.max_size
803                && self.data.len().saturating_add(block.data.len()) > limit
804            {
805                self.fail(Error::TooLarge { limit }, true);
806                return;
807            }
808            self.retries = 0;
809            self.blk = self.blk.wrapping_add(1);
810            self.data.extend_from_slice(&block.data);
811            self.last_block = size.len();
812            self.events.push_back(Event::Progress {
813                bytes: self.data.len() as u64,
814                total: None,
815            });
816            self.send(vec![ACK]);
817        } else if block.num == self.blk.wrapping_sub(1) {
818            // Our ACK was lost: acknowledge the repeat and drop it.
819            self.send(vec![ACK]);
820        } else {
821            self.fail(
822                Error::Protocol(format!(
823                    "block {} out of sequence, expected {}",
824                    block.num, self.blk
825                )),
826                true,
827            );
828        }
829    }
830
831    fn on_eot(&mut self, now: Instant) {
832        self.push(vec![ACK], Wait::None);
833        let data = std::mem::take(&mut self.data);
834        let last_block = self.last_block;
835        let padding = match data.last() {
836            Some(&p) if p == SUB || p == 0 => data
837                .iter()
838                .rev()
839                .take(last_block)
840                .take_while(|&&b| b == p)
841                .count(),
842            _ => 0,
843        };
844        self.events.push_back(Event::FileEnd {
845            data,
846            last_block,
847            padding,
848        });
849        self.finish(Event::Done);
850        // A linger that overflows `Instant` would never end: skip it.
851        if let Some(end) = now.checked_add(self.config.linger)
852            && !self.config.linger.is_zero()
853        {
854            self.phase = Phase::RecvLinger;
855            self.deadline = Some(end);
856        }
857    }
858}
859
860#[cfg(test)]
861#[allow(clippy::unwrap_used, clippy::expect_used)]
862mod tests {
863    use super::*;
864    use crate::codec::{STX, crc16, encode_block};
865
866    fn t0() -> Instant {
867        Instant::now()
868    }
869
870    fn drain(t: &mut Transfer, now: Instant) -> Vec<Vec<u8>> {
871        std::iter::from_fn(|| t.poll_output(now)).collect()
872    }
873
874    fn events(t: &mut Transfer) -> Vec<Event> {
875        std::iter::from_fn(|| t.poll_event()).collect()
876    }
877
878    fn block(num: u8, data: &[u8], check: Check) -> Vec<u8> {
879        encode_block(num, BlockSize::B128, data, SUB, check).unwrap()
880    }
881
882    fn sender(data: &[u8], config: Config) -> (Transfer, Instant) {
883        let now = t0();
884        let mut t = Transfer::new(config);
885        t.start(now, Command::Send(data.to_vec())).unwrap();
886        (t, now)
887    }
888
889    /// Receiver asking with `C` (CRC-16), the standard XModem start.
890    fn crc() -> Config {
891        Config {
892            check: Check::Crc16,
893            ..Config::default()
894        }
895    }
896
897    #[test]
898    fn default_receiver_asks_with_d() {
899        let (mut t, now) = receiver(Config::default());
900        assert_eq!(drain(&mut t, now), vec![b"D".to_vec()]);
901    }
902
903    fn receiver(config: Config) -> (Transfer, Instant) {
904        let now = t0();
905        let mut t = Transfer::new(config);
906        t.start(now, Command::Receive).unwrap();
907        (t, now)
908    }
909
910    // ---- sender ----
911
912    #[test]
913    fn send_checksum_on_nak() {
914        let (mut t, now) = sender(b"hello", Config::default());
915        assert_eq!(t.poll_output(now), None, "sender waits for the receiver");
916        t.handle_input(now, &[NAK]);
917        assert_eq!(
918            drain(&mut t, now),
919            vec![block(1, b"hello", Check::Checksum)]
920        );
921        t.handle_input(now, &[ACK]);
922        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
923        t.handle_input(now, &[ACK]);
924        assert_eq!(
925            events(&mut t),
926            vec![
927                Event::Started {
928                    check: Check::Checksum
929                },
930                Event::Progress {
931                    bytes: 5,
932                    total: Some(5)
933                },
934                Event::Done
935            ]
936        );
937        assert!(t.is_idle());
938    }
939
940    #[test]
941    fn send_crc_on_c() {
942        let (mut t, now) = sender(&[0x55; 200], Config::default());
943        t.handle_input(now, b"C");
944        let out = drain(&mut t, now);
945        assert_eq!(out, vec![block(1, &[0x55; 128], Check::Crc16)]);
946        assert_eq!(out[0].len(), 133);
947        t.handle_input(now, &[ACK]);
948        assert_eq!(
949            drain(&mut t, now),
950            vec![block(2, &[0x55; 72], Check::Crc16)]
951        );
952        // `C` after the first ACK is ignored.
953        t.handle_input(now, b"C");
954        assert_eq!(drain(&mut t, now), Vec::<Vec<u8>>::new());
955        // Two ACKs in one read: the second cannot answer the unwritten EOT.
956        t.handle_input(now, &[ACK, ACK]);
957        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
958        t.handle_input(now, &[ACK]);
959        assert_eq!(events(&mut t).last(), Some(&Event::Done));
960    }
961
962    #[test]
963    fn send_hp_crc_on_d() {
964        let cfg = Config {
965            block_size: BlockSize::B1k,
966            ..Config::default()
967        };
968        let data = vec![0xA5; 1500];
969        let (mut t, now) = sender(&data, cfg);
970        t.handle_input(now, b"D");
971        let out = drain(&mut t, now);
972        assert_eq!(
973            out,
974            vec![encode_block(1, BlockSize::B1k, &data[..1024], SUB, Check::HpCrc).unwrap()]
975        );
976        let crc = crate::codec::hp_crc(&data[..1024]);
977        assert_eq!(&out[0][1027..], &crc.to_be_bytes());
978        // An extra `D` before the first ACK resends.
979        t.handle_input(now, b"D");
980        assert_eq!(drain(&mut t, now), out);
981        assert_eq!(
982            events(&mut t)[0],
983            Event::Started {
984                check: Check::HpCrc
985            }
986        );
987    }
988
989    #[test]
990    fn receive_hp_crc_then_fallback() {
991        let cfg = Config {
992            check: Check::HpCrc,
993            crc_attempts: 2,
994            ..Config::default()
995        };
996        let (mut t, now) = receiver(cfg);
997        let mut starts = drain(&mut t, now);
998        let at = t.next_timeout().unwrap();
999        t.handle_timeout(at);
1000        starts.extend(drain(&mut t, at));
1001        let at = t.next_timeout().unwrap();
1002        t.handle_timeout(at);
1003        starts.extend(drain(&mut t, at));
1004        assert_eq!(starts, vec![b"D".to_vec(), b"D".to_vec(), vec![NAK]]);
1005    }
1006
1007    #[test]
1008    fn receive_hp_crc_block() {
1009        let cfg = Config {
1010            check: Check::HpCrc,
1011            ..Config::default()
1012        };
1013        let (mut t, now) = receiver(cfg);
1014        drain(&mut t, now);
1015        t.handle_input(
1016            now,
1017            &encode_block(1, BlockSize::B1k, b"hp", 0, Check::HpCrc).unwrap(),
1018        );
1019        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1020    }
1021
1022    #[test]
1023    fn send_ignores_noise_and_kermit_packets_before_start() {
1024        let (mut t, now) = sender(b"x", Config::default());
1025        // A stale Kermit NAK and a reply packet holding a `C`.
1026        t.handle_input(now, b"\x01# N3\r\x01& DCC\r junk");
1027        assert_eq!(t.poll_output(now), None);
1028        t.handle_input(now, b"C");
1029        assert_eq!(drain(&mut t, now), vec![block(1, b"x", Check::Crc16)]);
1030    }
1031
1032    #[test]
1033    fn send_kermit_skip_is_bounded() {
1034        // A Kermit packet whose CR was lost: start characters count again
1035        // after at most 96 bytes.
1036        let (mut t, now) = sender(b"x", Config::default());
1037        t.handle_input(now, &[0x01]);
1038        t.handle_input(now, &[b'C'; 96]);
1039        assert_eq!(t.poll_output(now), None);
1040        t.handle_input(now, b"C");
1041        assert_eq!(drain(&mut t, now), vec![block(1, b"x", Check::Crc16)]);
1042    }
1043
1044    #[test]
1045    fn send_extra_c_before_first_ack_resends() {
1046        let (mut t, now) = sender(b"x", Config::default());
1047        t.handle_input(now, b"C");
1048        let first = drain(&mut t, now);
1049        t.handle_input(now, b"C");
1050        assert_eq!(drain(&mut t, now), first);
1051    }
1052
1053    #[test]
1054    fn send_reply_before_write_is_ignored() {
1055        // Two start characters in one read: the second cannot answer block 1.
1056        let (mut t, now) = sender(b"x", Config::default());
1057        t.handle_input(now, b"CC");
1058        assert_eq!(drain(&mut t, now).len(), 1);
1059    }
1060
1061    #[test]
1062    fn send_nak_resends_then_gives_up_with_cans() {
1063        let cfg = Config {
1064            retries: 2,
1065            ..Config::default()
1066        };
1067        let (mut t, now) = sender(b"abc", cfg);
1068        t.handle_input(now, &[NAK]);
1069        let b = drain(&mut t, now);
1070        t.handle_input(now, &[NAK]);
1071        assert_eq!(drain(&mut t, now), b);
1072        t.handle_input(now, &[NAK]);
1073        assert_eq!(drain(&mut t, now), b);
1074        t.handle_input(now, &[NAK]);
1075        assert_eq!(drain(&mut t, now), vec![CANCEL.to_vec()]);
1076        assert_eq!(events(&mut t).last(), Some(&Event::Error(Error::Timeout)));
1077    }
1078
1079    #[test]
1080    fn send_timeout_resends() {
1081        let (mut t, now) = sender(b"abc", Config::default());
1082        t.handle_input(now, &[NAK]);
1083        let b = drain(&mut t, now);
1084        let due = t.next_timeout().unwrap();
1085        assert_eq!(due, now + Duration::from_secs(10));
1086        t.handle_timeout(due - Duration::from_millis(1));
1087        assert_eq!(t.poll_output(due), None, "nothing early");
1088        t.handle_timeout(due);
1089        assert_eq!(drain(&mut t, due), b);
1090    }
1091
1092    #[test]
1093    fn send_start_timeout() {
1094        let (mut t, now) = sender(b"abc", Config::default());
1095        let due = t.next_timeout().unwrap();
1096        assert_eq!(due, now + Duration::from_secs(60));
1097        t.handle_timeout(due);
1098        assert_eq!(events(&mut t), vec![Event::Error(Error::Timeout)]);
1099        assert_eq!(t.poll_output(due), None);
1100    }
1101
1102    #[test]
1103    fn send_remote_can() {
1104        let (mut t, now) = sender(b"abc", Config::default());
1105        t.handle_input(now, &[NAK]);
1106        drain(&mut t, now);
1107        // One CAN is noise; two in a row abort.
1108        t.handle_input(now, &[CAN, ACK]);
1109        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
1110        t.handle_input(now, &[CAN, CAN]);
1111        assert_eq!(
1112            events(&mut t).last(),
1113            Some(&Event::Error(Error::RemoteCancelled))
1114        );
1115        assert_eq!(t.poll_output(now), None);
1116    }
1117
1118    #[test]
1119    fn send_eot_nak_resends_eot() {
1120        let (mut t, now) = sender(b"a", Config::default());
1121        t.handle_input(now, &[NAK]);
1122        drain(&mut t, now);
1123        t.handle_input(now, &[ACK]);
1124        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
1125        t.handle_input(now, &[NAK]);
1126        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
1127        t.handle_input(now, &[ACK]);
1128        assert_eq!(events(&mut t).last(), Some(&Event::Done));
1129    }
1130
1131    #[test]
1132    fn send_empty_file_is_just_eot() {
1133        let (mut t, now) = sender(b"", Config::default());
1134        t.handle_input(now, &[NAK]);
1135        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
1136        t.handle_input(now, &[ACK]);
1137        assert_eq!(events(&mut t).last(), Some(&Event::Done));
1138    }
1139
1140    #[test]
1141    fn send_1k_with_short_tail() {
1142        fn headers(len: usize) -> Vec<u8> {
1143            let cfg = Config {
1144                block_size: BlockSize::B1k,
1145                pad: 0,
1146                ..Config::default()
1147            };
1148            let data: Vec<u8> = (0..len).map(|i| i as u8).collect();
1149            let (mut t, now) = sender(&data, cfg);
1150            t.handle_input(now, b"C");
1151            let mut out = Vec::new();
1152            loop {
1153                let block = drain(&mut t, now);
1154                if block == vec![vec![EOT]] {
1155                    return out;
1156                }
1157                out.push(block[0][0]);
1158                t.handle_input(now, &[ACK]);
1159            }
1160        }
1161        // 896 bytes (7 x 128) left: 128-byte blocks; 897 left: one 1k block.
1162        assert_eq!(headers(1024 + 896), [vec![STX], vec![SOH; 7]].concat());
1163        assert_eq!(headers(1024 + 897), vec![STX, STX]);
1164        assert_eq!(headers(100), vec![SOH]);
1165    }
1166
1167    #[test]
1168    fn send_1k_without_short_tail() {
1169        let cfg = Config {
1170            block_size: BlockSize::B1k,
1171            short_tail: false,
1172            ..Config::default()
1173        };
1174        let (mut t, now) = sender(&[1; 300], cfg);
1175        t.handle_input(now, b"D");
1176        let out = drain(&mut t, now);
1177        assert_eq!(out[0].len(), 3 + 1024 + 2);
1178        assert_eq!(out[0][0], STX);
1179        assert_eq!(out[0][303], SUB);
1180    }
1181
1182    #[test]
1183    fn send_1k_needs_a_crc_receiver() {
1184        // A receiver that opens with NAK (the 48GX) gets 128-byte blocks even
1185        // with 1k configured; `checksum_1k` forces 1k anyway.
1186        let cfg = Config {
1187            block_size: BlockSize::B1k,
1188            short_tail: false,
1189            ..Config::default()
1190        };
1191        let (mut t, now) = sender(&[1; 300], cfg.clone());
1192        t.handle_input(now, &[NAK]);
1193        let out = drain(&mut t, now);
1194        assert_eq!(out, vec![block(1, &[1; 128], Check::Checksum)]);
1195
1196        let forced = Config {
1197            checksum_1k: true,
1198            ..cfg
1199        };
1200        let (mut t, now) = sender(&[1; 300], forced);
1201        t.handle_input(now, &[NAK]);
1202        let out = drain(&mut t, now);
1203        assert_eq!(out[0].len(), 3 + 1024 + 1);
1204        assert_eq!(out[0][0], STX);
1205    }
1206
1207    #[test]
1208    fn send_block_number_wraps_to_zero() {
1209        let (mut t, now) = sender(&[0; 128 * 257], Config::default());
1210        t.handle_input(now, &[NAK]);
1211        let mut nums = Vec::new();
1212        for _ in 0..257 {
1213            nums.push(drain(&mut t, now)[0][1]);
1214            t.handle_input(now, &[ACK]);
1215        }
1216        assert_eq!(&nums[254..], &[255, 0, 1]);
1217    }
1218
1219    #[test]
1220    fn cancel_sends_cans() {
1221        let (mut t, now) = sender(b"a", Config::default());
1222        t.cancel(now);
1223        assert_eq!(drain(&mut t, now), vec![CANCEL.to_vec()]);
1224        assert_eq!(events(&mut t), vec![Event::Error(Error::Cancelled)]);
1225        assert!(t.start(now, Command::Receive).is_ok());
1226        assert_eq!(t.start(now, Command::Receive), Err(StartError::Busy));
1227    }
1228
1229    // ---- receiver ----
1230
1231    #[test]
1232    fn receive_crc() {
1233        let (mut t, now) = receiver(crc());
1234        assert_eq!(drain(&mut t, now), vec![b"C".to_vec()]);
1235        t.handle_input(now, &block(1, b"hi", Check::Crc16));
1236        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1237        t.handle_input(now, &[EOT]);
1238        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1239        let ev = events(&mut t);
1240        assert_eq!(
1241            ev[0],
1242            Event::Started {
1243                check: Check::Crc16
1244            }
1245        );
1246        let Event::FileEnd {
1247            data,
1248            last_block,
1249            padding,
1250        } = &ev[2]
1251        else {
1252            panic!("{ev:?}")
1253        };
1254        assert_eq!(data.len(), 128);
1255        assert!(data.starts_with(b"hi"));
1256        assert_eq!((*last_block, *padding), (128, 126));
1257        assert_eq!(ev[3], Event::Done);
1258    }
1259
1260    #[test]
1261    fn receive_falls_back_to_checksum() {
1262        let (mut t, now) = receiver(crc());
1263        let mut at = now;
1264        let mut starts = Vec::new();
1265        for _ in 0..4 {
1266            starts.extend(drain(&mut t, at));
1267            at = t.next_timeout().unwrap();
1268            t.handle_timeout(at);
1269        }
1270        assert_eq!(
1271            starts,
1272            vec![b"C".to_vec(), b"C".to_vec(), b"C".to_vec(), vec![NAK]]
1273        );
1274        // Three C at 3 s, then the NAK waits the full 10 s.
1275        assert_eq!(at, now + Duration::from_secs(19));
1276        drain(&mut t, at);
1277        t.handle_input(at, &block(1, b"48", Check::Checksum));
1278        assert_eq!(drain(&mut t, at), vec![vec![ACK]]);
1279        assert_eq!(
1280            events(&mut t)[0],
1281            Event::Started {
1282                check: Check::Checksum
1283            }
1284        );
1285    }
1286
1287    #[test]
1288    fn receive_checksum_from_start() {
1289        let cfg = Config {
1290            check: Check::Checksum,
1291            ..Config::default()
1292        };
1293        let (mut t, now) = receiver(cfg);
1294        assert_eq!(drain(&mut t, now), vec![vec![NAK]]);
1295    }
1296
1297    #[test]
1298    fn receive_start_gives_up() {
1299        let cfg = Config {
1300            retries: 1,
1301            crc_attempts: 1,
1302            ..crc()
1303        };
1304        let (mut t, mut at) = receiver(cfg);
1305        let mut out = Vec::new();
1306        for _ in 0..2 {
1307            out.extend(drain(&mut t, at));
1308            at = t.next_timeout().unwrap();
1309            t.handle_timeout(at);
1310        }
1311        out.extend(drain(&mut t, at));
1312        assert_eq!(out, vec![b"C".to_vec(), vec![NAK], CANCEL.to_vec()]);
1313        assert_eq!(events(&mut t), vec![Event::Error(Error::Timeout)]);
1314    }
1315
1316    #[test]
1317    fn receive_start_window_outlasts_the_count() {
1318        // With `recv_start_timeout` the receiver keeps asking until the window
1319        // closes, however many start characters that takes.
1320        let cfg = Config {
1321            retries: 1,
1322            crc_attempts: 2,
1323            crc_interval: Duration::from_secs(1),
1324            timeout: Duration::from_secs(1),
1325            recv_start_timeout: Some(Duration::from_secs(5)),
1326            ..Config::default()
1327        };
1328        let (mut t, start) = receiver(cfg);
1329        let mut at = start;
1330        let mut out = Vec::new();
1331        while !t.is_idle() {
1332            out.extend(drain(&mut t, at));
1333            at = t.next_timeout().unwrap();
1334            t.handle_timeout(at);
1335        }
1336        out.extend(drain(&mut t, at));
1337        assert_eq!(at.duration_since(start), Duration::from_secs(5));
1338        let mut want = vec![b"D".to_vec(), b"D".to_vec()];
1339        want.extend(vec![vec![NAK]; 3]);
1340        want.push(CANCEL.to_vec());
1341        assert_eq!(out, want);
1342        assert_eq!(events(&mut t), vec![Event::Error(Error::Timeout)]);
1343    }
1344
1345    #[test]
1346    fn receive_skips_kermit_packet_before_first_block() {
1347        let (mut t, now) = receiver(crc());
1348        drain(&mut t, now);
1349        t.handle_input(now, b"\x01# N3\r");
1350        t.handle_input(now, &block(1, b"ok", Check::Crc16));
1351        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1352    }
1353
1354    #[test]
1355    fn receive_duplicate_block_acked_and_dropped() {
1356        let (mut t, now) = receiver(crc());
1357        drain(&mut t, now);
1358        t.handle_input(now, &block(1, b"one", Check::Crc16));
1359        t.handle_input(now, &block(1, b"one", Check::Crc16));
1360        t.handle_input(now, &block(2, b"two", Check::Crc16));
1361        assert_eq!(drain(&mut t, now), vec![vec![ACK]; 3]);
1362        t.handle_input(now, &[EOT]);
1363        let ev = events(&mut t);
1364        let data = ev
1365            .iter()
1366            .find_map(|e| match e {
1367                Event::FileEnd { data, .. } => Some(data.clone()),
1368                _ => None,
1369            })
1370            .unwrap();
1371        assert_eq!(data.len(), 256);
1372        assert!(data[128..].starts_with(b"two"));
1373    }
1374
1375    #[test]
1376    fn receive_out_of_sequence_cancels() {
1377        let (mut t, now) = receiver(crc());
1378        drain(&mut t, now);
1379        t.handle_input(now, &block(1, b"one", Check::Crc16));
1380        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1381        t.handle_input(now, &block(3, b"three", Check::Crc16));
1382        assert_eq!(drain(&mut t, now), vec![CANCEL.to_vec()]);
1383        assert!(matches!(
1384            events(&mut t).last(),
1385            Some(Event::Error(Error::Protocol(_)))
1386        ));
1387    }
1388
1389    #[test]
1390    fn receive_bad_check_purges_then_naks() {
1391        let (mut t, now) = receiver(crc());
1392        drain(&mut t, now);
1393        t.handle_input(now, &block(1, b"one", Check::Crc16));
1394        drain(&mut t, now);
1395        let mut bad = block(2, b"two", Check::Crc16);
1396        bad[20] ^= 0xFF;
1397        t.handle_input(now, &bad);
1398        assert_eq!(t.poll_output(now), None, "no NAK while the line is busy");
1399        // More garbage extends the quiet period.
1400        let later = now + Duration::from_millis(500);
1401        t.handle_input(later, b"xyz");
1402        assert_eq!(t.next_timeout(), Some(later + Duration::from_secs(1)));
1403        t.handle_timeout(later + Duration::from_secs(1));
1404        assert_eq!(drain(&mut t, later), vec![vec![NAK]]);
1405        let at = later + Duration::from_secs(1);
1406        t.handle_input(at, &block(2, b"two", Check::Crc16));
1407        assert_eq!(drain(&mut t, at), vec![vec![ACK]]);
1408    }
1409
1410    /// A peer that never stops sending garbage after a bad block cannot
1411    /// keep the purge going: each purge NAKs after the reply timeout, and
1412    /// the retries run out.
1413    #[test]
1414    fn a_babbling_line_runs_out_of_retries() {
1415        let cfg = Config {
1416            retries: 2,
1417            ..crc()
1418        };
1419        let (mut t, now) = receiver(cfg);
1420        drain(&mut t, now);
1421        t.handle_input(now, &block(1, b"one", Check::Crc16));
1422        drain(&mut t, now);
1423        let mut at = now;
1424        let mut naks = 0;
1425        let end = now + Duration::from_secs(120);
1426        while at < end {
1427            // SOH bytes: never a block header, so a purge each time.
1428            t.handle_input(at, &[SOH]);
1429            if t.next_timeout().is_some_and(|d| at >= d) {
1430                t.handle_timeout(at);
1431            }
1432            naks += drain(&mut t, at)
1433                .iter()
1434                .filter(|o| *o == &vec![NAK])
1435                .count();
1436            if t.is_idle() {
1437                break;
1438            }
1439            at += Duration::from_millis(100);
1440        }
1441        assert!(t.is_idle(), "the purge ended the transfer");
1442        assert_eq!(naks, 2);
1443        assert!(at <= now + Duration::from_secs(31), "{:?}", at - now);
1444        assert!(matches!(
1445            events(&mut t).last(),
1446            Some(Event::Error(Error::Timeout))
1447        ));
1448    }
1449
1450    #[test]
1451    fn receive_split_block_and_byte_timeout() {
1452        let (mut t, now) = receiver(crc());
1453        drain(&mut t, now);
1454        let b = block(1, b"split", Check::Crc16);
1455        t.handle_input(now, &b[..50]);
1456        t.handle_input(now, &b[50..]);
1457        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1458        // A partial block that stalls is NAKed after the byte timeout.
1459        let b2 = block(2, b"stall", Check::Crc16);
1460        t.handle_input(now, &b2[..10]);
1461        assert_eq!(t.next_timeout(), Some(now + Duration::from_secs(1)));
1462        t.handle_timeout(now + Duration::from_secs(1));
1463        assert_eq!(drain(&mut t, now), vec![vec![NAK]]);
1464    }
1465
1466    #[test]
1467    fn receive_block_timeout_naks_and_gives_up() {
1468        let cfg = Config {
1469            retries: 1,
1470            ..crc()
1471        };
1472        let (mut t, now) = receiver(cfg);
1473        drain(&mut t, now);
1474        t.handle_input(now, &block(1, b"a", Check::Crc16));
1475        drain(&mut t, now);
1476        let at = now + Duration::from_secs(10);
1477        assert_eq!(t.next_timeout(), Some(at));
1478        t.handle_timeout(at);
1479        assert_eq!(drain(&mut t, at), vec![vec![NAK]]);
1480        t.handle_timeout(at + Duration::from_secs(10));
1481        assert_eq!(drain(&mut t, at), vec![CANCEL.to_vec()]);
1482        assert_eq!(events(&mut t).last(), Some(&Event::Error(Error::Timeout)));
1483    }
1484
1485    #[test]
1486    fn receive_remote_can() {
1487        let (mut t, now) = receiver(crc());
1488        drain(&mut t, now);
1489        t.handle_input(now, &block(1, b"a", Check::Crc16));
1490        drain(&mut t, now);
1491        t.handle_input(now, &[CAN, CAN]);
1492        assert_eq!(
1493            events(&mut t).last(),
1494            Some(&Event::Error(Error::RemoteCancelled))
1495        );
1496        assert_eq!(t.poll_output(now), None);
1497    }
1498
1499    #[test]
1500    fn receive_1k_and_mixed_blocks() {
1501        let (mut t, now) = receiver(crc());
1502        drain(&mut t, now);
1503        t.handle_input(
1504            now,
1505            &encode_block(1, BlockSize::B1k, &[9; 1024], 0, Check::Crc16).unwrap(),
1506        );
1507        t.handle_input(now, &block(2, &[0; 3], Check::Crc16));
1508        assert_eq!(drain(&mut t, now), vec![vec![ACK]; 2]);
1509        t.handle_input(now, &[EOT]);
1510        let ev = events(&mut t);
1511        let Some(Event::FileEnd {
1512            data,
1513            last_block,
1514            padding,
1515        }) = ev.iter().find(|e| matches!(e, Event::FileEnd { .. }))
1516        else {
1517            panic!("{ev:?}")
1518        };
1519        assert_eq!(data.len(), 1152);
1520        // SUB padding of the 128-byte tail block.
1521        assert_eq!((*last_block, *padding), (128, 125));
1522    }
1523
1524    #[test]
1525    fn receive_empty_transfer_eot_first_is_ignored_before_start() {
1526        // EOT before any block is noise while still starting.
1527        let (mut t, now) = receiver(crc());
1528        drain(&mut t, now);
1529        t.handle_input(now, &[EOT]);
1530        assert_eq!(t.poll_output(now), None);
1531        assert!(!t.is_idle());
1532    }
1533
1534    /// A CRC receiver that has accepted block 1 ("one").
1535    fn receiving(config: Config) -> (Transfer, Instant) {
1536        let (mut t, now) = receiver(config);
1537        drain(&mut t, now);
1538        t.handle_input(now, &block(1, b"one", Check::Crc16));
1539        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1540        (t, now)
1541    }
1542
1543    #[test]
1544    fn lost_final_ack_is_answered_while_lingering() {
1545        let cfg = crc();
1546        let linger = cfg.linger;
1547        let (mut t, now) = receiving(cfg);
1548        t.handle_input(now, &[EOT]);
1549        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1550        let ev = events(&mut t);
1551        assert!(matches!(
1552            ev.as_slice(),
1553            [.., Event::FileEnd { .. }, Event::Done]
1554        ));
1555        assert!(!t.is_idle());
1556        assert_eq!(t.next_timeout(), Some(now + linger));
1557        // The sender did not get our ACK and repeats EOT: ACK again, no
1558        // second FileEnd or Done. Other bytes are ignored.
1559        let at = now + linger / 2;
1560        t.handle_input(at, &[EOT]);
1561        assert_eq!(drain(&mut t, at), vec![vec![ACK]]);
1562        t.handle_input(at, &block(2, b"x", Check::Crc16));
1563        assert_eq!(drain(&mut t, at), Vec::<Vec<u8>>::new());
1564        assert_eq!(events(&mut t), vec![]);
1565        // The linger is bounded: the re-ACK does not extend it.
1566        assert_eq!(t.next_timeout(), Some(now + linger));
1567        t.handle_timeout(now + linger);
1568        assert!(t.is_idle());
1569        assert_eq!(t.next_timeout(), None);
1570        t.handle_input(now + linger, &[EOT]);
1571        assert_eq!(t.poll_output(now + linger), None);
1572        assert_eq!(events(&mut t), vec![]);
1573    }
1574
1575    #[test]
1576    fn start_and_cancel_end_the_linger() {
1577        let (mut t, now) = receiving(crc());
1578        t.handle_input(now, &[EOT]);
1579        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1580        events(&mut t);
1581        t.cancel(now);
1582        assert!(t.is_idle());
1583        assert_eq!(t.poll_output(now), None, "no CANs after Done");
1584        assert_eq!(events(&mut t), vec![]);
1585
1586        let (mut t, now) = receiving(crc());
1587        t.handle_input(now, &[EOT]);
1588        t.start(now, Command::Receive).unwrap();
1589        assert_eq!(drain(&mut t, now), vec![b"C".to_vec()]);
1590        assert_eq!(events(&mut t), vec![], "the old events are dropped");
1591    }
1592
1593    #[test]
1594    fn zero_linger_goes_idle_at_once() {
1595        let cfg = Config {
1596            linger: Duration::ZERO,
1597            ..crc()
1598        };
1599        let (mut t, now) = receiving(cfg);
1600        t.handle_input(now, &[EOT]);
1601        assert!(t.is_idle());
1602        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1603        assert_eq!(t.next_timeout(), None);
1604    }
1605
1606    #[test]
1607    fn block_straddling_the_start_interval_is_kept() {
1608        // The last `D` before the switch to checksum goes out at 0; a 1k
1609        // HP-CRC block starts at 2.5 s and ends at 3.9 s, past the 3 s
1610        // interval. The byte timeout governs the block, so the check stays.
1611        let cfg = Config {
1612            crc_attempts: 1,
1613            ..Config::default()
1614        };
1615        let interval = cfg.crc_interval;
1616        let (mut t, now) = receiver(cfg);
1617        assert_eq!(drain(&mut t, now), vec![b"D".to_vec()]);
1618        assert_eq!(t.next_timeout(), Some(now + interval));
1619        let b = encode_block(1, BlockSize::B1k, b"hp", 0, Check::HpCrc).unwrap();
1620        let ms = |n| now + Duration::from_millis(n);
1621        t.handle_input(ms(2500), &b[..400]);
1622        assert_eq!(t.next_timeout(), Some(ms(3500)));
1623        t.handle_timeout(ms(3000));
1624        assert_eq!(t.poll_output(ms(3000)), None);
1625        t.handle_input(ms(3200), &b[400..800]);
1626        t.handle_timeout(ms(3500));
1627        assert_eq!(t.poll_output(ms(3500)), None);
1628        t.handle_input(ms(3900), &b[800..]);
1629        assert_eq!(drain(&mut t, ms(3900)), vec![vec![ACK]]);
1630        assert_eq!(
1631            events(&mut t)[0],
1632            Event::Started {
1633                check: Check::HpCrc
1634            }
1635        );
1636    }
1637
1638    #[test]
1639    fn stalled_first_block_resumes_the_start_interval() {
1640        let cfg = crc();
1641        let (mut t, now) = receiver(cfg);
1642        assert_eq!(drain(&mut t, now), vec![b"C".to_vec()]);
1643        let ms = |n| now + Duration::from_millis(n);
1644        // A fragment at 0.5 s, then silence: dropped after the byte timeout
1645        // (1.5 s); the interval running since 0 still ends at 3 s.
1646        t.handle_input(ms(500), &block(1, b"x", Check::Crc16)[..20]);
1647        assert_eq!(t.next_timeout(), Some(ms(1500)));
1648        t.handle_timeout(ms(1500));
1649        assert_eq!(t.poll_output(ms(1500)), None);
1650        assert_eq!(t.next_timeout(), Some(ms(3000)));
1651        t.handle_timeout(ms(3000));
1652        assert_eq!(drain(&mut t, ms(3000)), vec![b"C".to_vec()]);
1653        // A fragment that stalls past the interval: the next start character
1654        // goes out when it is dropped.
1655        t.handle_input(ms(5500), &block(1, b"x", Check::Crc16)[..20]);
1656        t.handle_timeout(ms(6500));
1657        assert_eq!(drain(&mut t, ms(6500)), vec![b"C".to_vec()]);
1658        // A Kermit packet (not a block header) restores the interval too.
1659        t.handle_input(ms(7000), b"\x01# N3\r");
1660        assert_eq!(t.next_timeout(), Some(ms(9500)));
1661    }
1662
1663    #[test]
1664    fn send_start_character_reselects_the_check() {
1665        // The receiver's first `D` gets a 1k HP-CRC block; before any ACK it
1666        // falls back to NAK (checksum): block 1 again, as a 128-byte checksum
1667        // block. A later `C` switches to CRC-16 with 1k blocks again.
1668        let cfg = Config {
1669            block_size: BlockSize::B1k,
1670            short_tail: false,
1671            ..Config::default()
1672        };
1673        let data = vec![7u8; 2000];
1674        let (mut t, now) = sender(&data, cfg);
1675        t.handle_input(now, b"D");
1676        let out = drain(&mut t, now);
1677        assert_eq!(out[0].len(), 3 + 1024 + 2);
1678        t.handle_input(now, &[NAK]);
1679        assert_eq!(
1680            drain(&mut t, now),
1681            vec![block(1, &data[..128], Check::Checksum)]
1682        );
1683        t.handle_input(now, b"C");
1684        assert_eq!(
1685            drain(&mut t, now),
1686            vec![encode_block(1, BlockSize::B1k, &data[..1024], SUB, Check::Crc16).unwrap()]
1687        );
1688        // The same character again only resends.
1689        t.handle_input(now, b"C");
1690        assert_eq!(drain(&mut t, now)[0].len(), 3 + 1024 + 2);
1691        assert_eq!(
1692            events(&mut t),
1693            vec![
1694                Event::Started {
1695                    check: Check::HpCrc
1696                },
1697                Event::Started {
1698                    check: Check::Checksum
1699                },
1700                Event::Started {
1701                    check: Check::Crc16
1702                },
1703            ]
1704        );
1705        // After the first ACK, NAK means resend and `C`/`D` are ignored.
1706        t.handle_input(now, &[ACK]);
1707        let second = drain(&mut t, now);
1708        t.handle_input(now, b"D");
1709        assert_eq!(drain(&mut t, now), Vec::<Vec<u8>>::new());
1710        t.handle_input(now, &[NAK]);
1711        assert_eq!(drain(&mut t, now), second);
1712    }
1713
1714    #[test]
1715    fn send_nak_in_crc16_mode_resends_block_1_in_crc16() {
1716        // A standard CRC-16 receiver NAKs a damaged block 1 and stays in CRC
1717        // mode: the same CRC block again, no switch to checksum.
1718        let (mut t, now) = sender(b"x", Config::default());
1719        t.handle_input(now, b"C");
1720        let first = drain(&mut t, now);
1721        assert_eq!(first, vec![block(1, b"x", Check::Crc16)]);
1722        t.handle_input(now, &[NAK]);
1723        assert_eq!(drain(&mut t, now), first);
1724        t.handle_input(now, &[ACK]);
1725        assert_eq!(drain(&mut t, now), vec![vec![EOT]]);
1726        assert_eq!(
1727            events(&mut t)[..1],
1728            [Event::Started {
1729                check: Check::Crc16
1730            }]
1731        );
1732        assert_eq!(t.check(), Check::Crc16);
1733        // A checksum receiver's NAK simply resends too.
1734        let (mut t, now) = sender(b"x", Config::default());
1735        t.handle_input(now, &[NAK]);
1736        let first = drain(&mut t, now);
1737        t.handle_input(now, &[NAK]);
1738        assert_eq!(drain(&mut t, now), first);
1739    }
1740
1741    #[test]
1742    fn repeated_eots_while_lingering_queue_one_ack() {
1743        let (mut t, now) = receiving(crc());
1744        t.handle_input(now, &[EOT]);
1745        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1746        t.handle_input(now, &[EOT; 10]);
1747        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1748        t.handle_input(now, &[EOT, EOT]);
1749        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1750    }
1751
1752    #[test]
1753    fn send_start_characters_count_as_retries() {
1754        let cfg = Config {
1755            retries: 1,
1756            ..Config::default()
1757        };
1758        let (mut t, now) = sender(b"x", cfg);
1759        t.handle_input(now, b"D");
1760        drain(&mut t, now);
1761        t.handle_input(now, &[NAK]);
1762        assert_eq!(drain(&mut t, now), vec![block(1, b"x", Check::Checksum)]);
1763        t.handle_input(now, &[NAK]);
1764        assert_eq!(drain(&mut t, now), vec![CANCEL.to_vec()]);
1765        assert_eq!(events(&mut t).last(), Some(&Event::Error(Error::Timeout)));
1766    }
1767
1768    #[test]
1769    fn receive_size_cap() {
1770        let cfg = Config {
1771            max_size: Some(256),
1772            ..crc()
1773        };
1774        let (mut t, now) = receiving(cfg);
1775        t.handle_input(now, &block(2, b"two", Check::Crc16));
1776        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1777        // A duplicate is not counted.
1778        t.handle_input(now, &block(2, b"two", Check::Crc16));
1779        assert_eq!(drain(&mut t, now), vec![vec![ACK]]);
1780        t.handle_input(now, &block(3, b"three", Check::Crc16));
1781        assert_eq!(drain(&mut t, now), vec![CANCEL.to_vec()]);
1782        assert_eq!(
1783            events(&mut t).last(),
1784            Some(&Event::Error(Error::TooLarge { limit: 256 }))
1785        );
1786        assert!(t.is_idle());
1787        assert_eq!(Config::default().max_size, Some(4 << 20));
1788    }
1789
1790    #[test]
1791    fn crc_bytes_are_high_first_on_the_wire() {
1792        let data = [0x31u8; 128];
1793        let b = block(1, &data, Check::Crc16);
1794        let crc = crc16(&data);
1795        assert_eq!(b[131], (crc >> 8) as u8);
1796        assert_eq!(b[132], (crc & 0xFF) as u8);
1797    }
1798}