Skip to main content

kermit_proto/
client.rs

1//! The Kermit client (user Kermit) state machine: we are the host, the
2//! calculator is the server.
3
4use crate::time::{Duration, Instant};
5use std::collections::VecDeque;
6use std::fmt;
7
8use crate::codec::{BlockCheck, CR, Deframer, FrameError, Framing, Packet, parse_frame, unchar};
9use crate::params::{InitParams, Negotiated, negotiate};
10use crate::prefix::{self, Quoting};
11
12/// Tunables of a [`Client`].
13///
14/// Non-exhaustive: start from [`Config::default`] and set the fields you
15/// need.
16#[derive(Clone, Debug)]
17#[non_exhaustive]
18pub struct Config {
19    /// Block check we offer in our Send-Init (default type 3).
20    pub block_check: BlockCheck,
21    /// `true` (default): we offer QBIN `Y` (no 8th-bit prefixing unless the peer
22    /// asks); `false`: we ask for 8th-bit prefixing with `&`.
23    pub eight_bit_clean: bool,
24    /// `true` (default): we offer REPT `~`; `false`: no repeat compression.
25    pub repeat: bool,
26    /// Our receive timeout per packet (default 20 s).
27    pub timeout: Duration,
28    /// Retransmissions per packet before giving up (default 5).
29    pub retries: u32,
30    /// Retransmissions of the packet that starts a server transaction (the
31    /// `C`, `R`, `G` or `I`) while no reply to it has arrived; `None`
32    /// (default) means [`Config::retries`]. Once the server answers (its
33    /// `S`), [`Config::retries`] applies to the rest of the transaction.
34    /// `Some(0)` sends a host command exactly once: a server cannot tell a
35    /// resent `C` from a new one and runs it again, while a damaged reply
36    /// packet is still re-requested.
37    pub first_packet_retries: Option<u32>,
38    /// Immediate-NAK window for the first packet (default `None`: off).
39    /// When [`Config::first_packet_retries`] forbids another resend of the
40    /// packet that starts a transaction, a NAK of it (seq 0) that arrives
41    /// within this window after [`Client::poll_output`] handed the packet
42    /// out allows exactly one more resend: the server rejected the packet
43    /// (damaged on the line, sent while it was busy). The resend goes out
44    /// after [`Config::first_packet_nak_grace`] unless the server's `S` (or
45    /// another answer) arrives first. A later NAK, a second NAK and a
46    /// timeout never allow it. Set it to the time the packet takes on the
47    /// wire plus slack: an idle server's periodic NAK is byte-identical to a
48    /// rejection, and one that crosses the packet inside the window (the
49    /// server did take it) makes the command run twice if its answer takes
50    /// longer than the grace.
51    pub first_packet_nak_window: Option<Duration>,
52    /// Wait after a NAK inside [`Config::first_packet_nak_window`] before
53    /// the one resend it allows; `None` (default) means
54    /// [`Config::nak_grace`]. Capped by the receive timeout. Further NAKs
55    /// while the granted resend waits do not shorten it.
56    pub first_packet_nak_grace: Option<Duration>,
57    /// Lower bound of [`Config::first_packet_nak_window`]: the time one byte
58    /// takes on the link (10 bits / baud, ~1.04 ms at 9600 baud). A NAK that
59    /// arrives sooner after the packet was handed out than the packet's
60    /// length times this cannot be the server's answer to it (the packet
61    /// had not finished arriving): it is stale (input that was waiting, or
62    /// the idle server's NAK sent while ours was on the wire). `None`
63    /// (default): no lower bound.
64    pub first_packet_nak_byte_time: Option<Duration>,
65    /// Delay before each packet we send in reply to input (default 0).
66    pub packet_pause: Duration,
67    /// How long a NAK received while waiting for the reply to the first packet
68    /// is tolerated before we resend (default 1 s); such a NAK is usually a
69    /// stale one from the idle server.
70    pub nak_grace: Duration,
71    /// After we ACK the final `B` packet of a receive, keep answering a
72    /// retransmitted `B` with the same ACK for this long (default 1 s), in
73    /// case our ACK was damaged or lost. `Done` is emitted when the ACK is
74    /// queued; the linger emits nothing. [`Client::is_idle`] is false while
75    /// it lasts; [`Client::start`] ends it early. `Duration::ZERO` turns it
76    /// off. A peer that only retransmits after its own timeout (the TIME
77    /// we send, [`Config::timeout`]) is caught only by a linger that long.
78    pub linger: Duration,
79    /// Receive: most decoded data bytes accepted in one transaction (all
80    /// files and server text together); more fails the transaction with
81    /// [`Error::TooLarge`] and an E packet. Default 4 MiB, well above the
82    /// largest HP object; `None` means no limit.
83    pub max_size: Option<usize>,
84}
85
86impl Default for Config {
87    fn default() -> Self {
88        Config {
89            block_check: BlockCheck::Type3,
90            eight_bit_clean: true,
91            repeat: true,
92            timeout: Duration::from_secs(20),
93            retries: 5,
94            first_packet_retries: None,
95            first_packet_nak_window: None,
96            first_packet_nak_grace: None,
97            first_packet_nak_byte_time: None,
98            packet_pause: Duration::ZERO,
99            nak_grace: Duration::from_secs(1),
100            linger: Duration::from_secs(1),
101            max_size: Some(DEFAULT_MAX_SIZE),
102        }
103    }
104}
105
106/// Default [`Config::max_size`]: 4 MiB.
107const DEFAULT_MAX_SIZE: usize = 4 << 20;
108
109/// A file to send: the name the server should store it under, and its bytes.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub struct OutgoingFile {
112    /// Name sent in the F packet.
113    pub name: Vec<u8>,
114    /// File contents.
115    pub data: Vec<u8>,
116}
117
118/// One client transaction.
119#[derive(Clone, Debug, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum Command {
122    /// I exchange (parameters only).
123    Info,
124    /// Send files: S F D.. Z [F D.. Z].. B.
125    Send(Vec<OutgoingFile>),
126    /// R name; receive the file(s) the server sends back.
127    Get(Vec<u8>),
128    /// C text (host command); the reply arrives as [`Event::ServerText`].
129    Host(Vec<u8>),
130    /// G D (directory); the reply arrives as [`Event::ServerText`].
131    Directory,
132    /// G F: end server mode.
133    Finish,
134    /// G L: end server mode and log out.
135    Logout,
136}
137
138/// Something that happened during a transaction.
139#[derive(Clone, Debug, PartialEq, Eq)]
140#[non_exhaustive]
141pub enum Event {
142    /// A file starts. Receive: the name from the F packet. Send: the name from
143    /// the ACK to F if non-empty, else the name we sent.
144    FileStart {
145        /// File name.
146        name: Vec<u8>,
147    },
148    /// Decoded data of one received D packet (file transfer only, not X text).
149    Data(Vec<u8>),
150    /// Send progress after each acknowledged D packet.
151    Progress {
152        /// Input bytes of the current file acknowledged so far.
153        sent: u64,
154        /// Size of the current file.
155        total: u64,
156    },
157    /// Z received or acknowledged.
158    FileEnd {
159        /// The file was discarded (Z data `D`, or we interrupted on an X/Z ACK).
160        discarded: bool,
161    },
162    /// Reply text to Host/Directory.
163    ServerText(Vec<u8>),
164    /// Terminal failure; the client is idle.
165    Error(Error),
166    /// Terminal success. The client is idle, or lingers after the final ACK
167    /// of a receive ([`Config::linger`]).
168    Done,
169}
170
171/// Why a transaction failed.
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[non_exhaustive]
174pub enum Error {
175    /// Decoded data of an E packet from the peer.
176    Remote(Vec<u8>),
177    /// Retries exhausted.
178    Timeout,
179    /// Unexpected packet or undecodable data.
180    Protocol(String),
181    /// [`Client::cancel`] was called.
182    Cancelled,
183    /// The received data exceeded [`Config::max_size`]; we sent an E packet.
184    TooLarge {
185        /// The limit that was exceeded.
186        limit: usize,
187    },
188}
189
190impl fmt::Display for Error {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            Error::Remote(text) => write!(f, "remote error: {}", String::from_utf8_lossy(text)),
194            Error::Timeout => f.write_str("timed out: too many retries"),
195            Error::Protocol(msg) => write!(f, "protocol error: {msg}"),
196            Error::Cancelled => f.write_str("cancelled"),
197            Error::TooLarge { limit } => {
198                write!(f, "received data exceeds the limit of {limit} bytes")
199            }
200        }
201    }
202}
203
204impl std::error::Error for Error {}
205
206/// Default MAXL assumed for the peer before any Send-Init exchange.
207const DEFAULT_MAXL: usize = 80;
208
209/// Why [`Client::start`] refused a command.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum StartError {
213    /// A transaction is already running.
214    Busy,
215    /// The encoded command data (R name, C text) does not fit in one packet
216    /// under the default MAXL of 80 with block check type 1.
217    TooLong {
218        /// Encoded data length.
219        len: usize,
220        /// Largest encoded data length that fits.
221        max: usize,
222    },
223}
224
225impl fmt::Display for StartError {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        match self {
228            StartError::Busy => f.write_str("a transaction is already running"),
229            StartError::TooLong { len, max } => write!(
230                f,
231                "command too long: {len} encoded bytes, at most {max} fit in one packet"
232            ),
233        }
234    }
235}
236
237impl std::error::Error for StartError {}
238
239/// What the reply to the command packet means.
240#[derive(Clone, Copy, Debug, PartialEq, Eq)]
241enum Kind {
242    Info,
243    Get,
244    Text,
245    Generic,
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249enum Step {
250    Init,
251    File,
252    Data { chunk: usize },
253    Eof { discarded: bool, skip_rest: bool },
254    Break,
255}
256
257#[derive(Debug)]
258struct Sending {
259    files: Vec<OutgoingFile>,
260    idx: usize,
261    pos: usize,
262    step: Step,
263}
264
265#[derive(Debug)]
266enum Phase {
267    Idle,
268    /// Waiting for the reply to the command packet (seq 0).
269    Await(Kind),
270    /// Receiving a transfer; `text` is Some while in X (text) mode, `file`
271    /// is true between an F and its Z.
272    Receive {
273        text: Option<Vec<u8>>,
274        file: bool,
275    },
276    Send(Sending),
277    /// The final ACK of a receive is out; re-ACK a retransmitted B (seq
278    /// `self.seq`) until `self.deadline`.
279    Linger,
280}
281
282/// Sans-IO Kermit client. See the crate documentation for the driver loop.
283#[derive(Debug)]
284pub struct Client {
285    config: Config,
286    ours: InitParams,
287    deframer: Deframer,
288    phase: Phase,
289    neg: Option<Negotiated>,
290    peer: Option<InitParams>,
291    /// Receive: the expected seq. Send: the seq of the packet awaiting its ACK.
292    seq: u8,
293    last_sent: Vec<u8>,
294    queue: VecDeque<(Instant, Vec<u8>)>,
295    events: VecDeque<Event>,
296    deadline: Option<Instant>,
297    retries: u32,
298    /// Receive: decoded data bytes accepted in this transaction.
299    received: usize,
300    /// Await: when the first packet last went out ([`Client::poll_output`])
301    /// and its length in bytes.
302    first_sent: Option<(Instant, usize)>,
303    /// Await: an immediate NAK granted the one extra resend
304    /// ([`Config::first_packet_nak_window`]).
305    nak_resend: bool,
306    /// See [`Client::accepted`].
307    accepted: u64,
308}
309
310impl Client {
311    /// New idle client.
312    pub fn new(config: Config) -> Self {
313        let ours = InitParams {
314            maxl: 94,
315            time: config.timeout.as_secs().clamp(1, 94) as u8,
316            npad: 0,
317            padc: 0,
318            eol: CR,
319            qctl: b'#',
320            qbin: if config.eight_bit_clean { b'Y' } else { b'&' },
321            chkt: config.block_check.to_char(),
322            rept: if config.repeat { b'~' } else { b' ' },
323        };
324        Client {
325            config,
326            ours,
327            deframer: Deframer::new(),
328            phase: Phase::Idle,
329            neg: None,
330            peer: None,
331            seq: 0,
332            last_sent: Vec::new(),
333            queue: VecDeque::new(),
334            events: VecDeque::new(),
335            deadline: None,
336            retries: 0,
337            received: 0,
338            first_sent: None,
339            nak_resend: false,
340            accepted: 0,
341        }
342    }
343
344    /// Begin a transaction. First packet is available from
345    /// `poll_output(now)` immediately.
346    ///
347    /// Starts from a clean slate: buffered input, output and events of the
348    /// previous transaction that were not polled yet are dropped, and
349    /// [`Client::peer_params`] is cleared. A linger after the previous
350    /// transaction ([`Config::linger`]) ends.
351    ///
352    /// Fails with [`StartError::Busy`] while a transaction is running and with
353    /// [`StartError::TooLong`] if the encoded command data does not fit in one
354    /// packet; the client is unchanged in both cases.
355    pub fn start(&mut self, now: Instant, command: Command) -> Result<(), StartError> {
356        if !matches!(self.phase, Phase::Idle | Phase::Linger) {
357            return Err(StartError::Busy);
358        }
359        let q = Quoting::default();
360        let (kind, data, phase) = match command {
361            Command::Info => (b'I', self.ours.encode(), Phase::Await(Kind::Info)),
362            Command::Send(files) => (
363                b'S',
364                self.ours.encode(),
365                Phase::Send(Sending {
366                    files,
367                    idx: 0,
368                    pos: 0,
369                    step: Step::Init,
370                }),
371            ),
372            Command::Get(name) => (b'R', prefix::encode_all(&name, &q), Phase::Await(Kind::Get)),
373            Command::Host(text) => (
374                b'C',
375                prefix::encode_all(&text, &q),
376                Phase::Await(Kind::Text),
377            ),
378            Command::Directory => (b'G', b"D".to_vec(), Phase::Await(Kind::Text)),
379            Command::Finish => (b'G', b"F".to_vec(), Phase::Await(Kind::Generic)),
380            Command::Logout => (b'G', b"L".to_vec(), Phase::Await(Kind::Generic)),
381        };
382        // Commands go out before negotiation: default MAXL, block check 1.
383        let max = Packet::max_data(DEFAULT_MAXL, BlockCheck::Type1);
384        if data.len() > max {
385            return Err(StartError::TooLong {
386                len: data.len(),
387                max,
388            });
389        }
390        self.deframer.clear();
391        self.queue.clear();
392        self.events.clear();
393        self.neg = None;
394        self.peer = None;
395        self.seq = 0;
396        self.retries = 0;
397        self.received = 0;
398        self.first_sent = None;
399        self.nak_resend = false;
400        self.deadline = None;
401        self.phase = phase;
402        let bytes = Packet::new(0, kind, data).wire(BlockCheck::Type1, &Framing::default());
403        self.last_sent = bytes.clone();
404        self.queue.push_back((now, bytes));
405        Ok(())
406    }
407
408    /// Feed bytes read from the link.
409    pub fn handle_input(&mut self, now: Instant, bytes: &[u8]) {
410        if self.is_idle() {
411            self.deframer.clear();
412            return;
413        }
414        self.deframer.push(bytes);
415        while !self.is_idle() {
416            let Some(frame) = self.deframer.next_frame() else {
417                break;
418            };
419            let check = match self.neg {
420                Some(n) if frame.get(3) != Some(&b'S') => n.check,
421                _ => BlockCheck::Type1,
422            };
423            let parsed = parse_frame(&frame, check);
424            // SEQ as received, also for frames that fail the check.
425            let raw_seq = frame.get(2).map(|&c| unchar(c));
426            match self.phase {
427                Phase::Idle => {}
428                Phase::Await(kind) => self.on_await(now, kind, parsed),
429                Phase::Receive { .. } => self.on_receive(now, parsed),
430                Phase::Send(_) => self.on_send(now, parsed, raw_seq),
431                Phase::Linger => self.on_linger(now, parsed),
432            }
433        }
434        if self.is_idle() {
435            self.deframer.clear();
436        }
437    }
438
439    /// Call when the time from [`Client::next_timeout`] has passed.
440    pub fn handle_timeout(&mut self, now: Instant) {
441        if self.is_idle() {
442            return;
443        }
444        if let Some(d) = self.deadline
445            && now >= d
446        {
447            self.deadline = None;
448            match self.phase {
449                Phase::Linger => self.end_linger(),
450                // Receiving: NAK the packet we expect (Kermit), not the last ACK.
451                Phase::Receive { .. } => {
452                    let nak = self.nak();
453                    self.retry_with(now, now, nak);
454                }
455                _ => self.retry(now, now),
456            }
457        }
458    }
459
460    /// Next bytes to write, written atomically (one packet incl. padding and
461    /// EOL). None if nothing is due yet at `now` (packet_pause). Keep calling
462    /// after Done/Error until None: the final ACK or an E packet may still be
463    /// queued.
464    pub fn poll_output(&mut self, now: Instant) -> Option<Vec<u8>> {
465        match self.queue.front() {
466            Some((due, _)) if *due <= now => {}
467            _ => return None,
468        }
469        let (_, bytes) = self.queue.pop_front()?;
470        // The linger's deadline is fixed when it starts.
471        if !matches!(self.phase, Phase::Idle | Phase::Linger) {
472            // Overflow (absurdly large timeout) means no deadline.
473            self.deadline = now.checked_add(self.config.timeout);
474        }
475        if matches!(self.phase, Phase::Await(_)) {
476            self.first_sent = Some((now, bytes.len()));
477        }
478        Some(bytes)
479    }
480
481    /// Next event, in order.
482    pub fn poll_event(&mut self) -> Option<Event> {
483        self.events.pop_front()
484    }
485
486    /// Earliest of: when a queued packet becomes due, the retransmit deadline.
487    pub fn next_timeout(&self) -> Option<Instant> {
488        let due = self.queue.iter().map(|(t, _)| *t).min();
489        match (due, self.deadline) {
490            (Some(a), Some(b)) => Some(a.min(b)),
491            (a, b) => a.or(b),
492        }
493    }
494
495    /// No transaction running and no linger after one (output may still be
496    /// queued).
497    pub fn is_idle(&self) -> bool {
498        matches!(self.phase, Phase::Idle)
499    }
500
501    /// Abort: queue an E packet "Cancelled", emit Error(Cancelled), go idle.
502    /// No-op when idle. During the linger after `Done` it only ends the
503    /// linger: no E packet, no event.
504    pub fn cancel(&mut self, now: Instant) {
505        match self.phase {
506            Phase::Idle => {}
507            Phase::Linger => self.end_linger(),
508            _ => self.fail(now, Error::Cancelled, Some(b"Cancelled")),
509        }
510    }
511
512    /// How many packets of the peer this client has taken as new since it
513    /// was made: the server's `S` answering the first packet, each packet
514    /// of a receive with the next sequence number, each ACK (or NAK of the
515    /// next packet) of the packet we sent. A repeated packet, a NAK, a
516    /// damaged packet, an E packet and noise do not count, nor do the
517    /// answers that end a transaction (`Done` and `Error` say so). A caller
518    /// that sees it unchanged for longer than the client's own retries can
519    /// take knows the peer keeps the transaction alive without moving it on.
520    pub fn accepted(&self) -> u64 {
521        self.accepted
522    }
523
524    /// Parameters the peer sent in its S, or ACK to our S/I, in the current
525    /// (or last finished) transaction; cleared by [`Client::start`].
526    pub fn peer_params(&self) -> Option<InitParams> {
527        self.peer
528    }
529
530    // ---- helpers ----
531
532    fn check(&self) -> BlockCheck {
533        self.neg.map_or(BlockCheck::Type1, |n| n.check)
534    }
535
536    fn framing(&self) -> Framing {
537        self.neg.map_or_else(Framing::default, |n| n.framing)
538    }
539
540    fn send_quoting(&self) -> Quoting {
541        self.neg.map_or_else(Quoting::default, |n| n.send)
542    }
543
544    fn recv_quoting(&self) -> Quoting {
545        self.neg.map_or_else(Quoting::default, |n| n.recv)
546    }
547
548    /// When a packet sent in reply to input at `now` becomes due. A pause that
549    /// overflows `Instant` is ignored rather than delaying forever.
550    fn paused(&self, now: Instant) -> Instant {
551        now.checked_add(self.config.packet_pause).unwrap_or(now)
552    }
553
554    /// NAK for the expected seq with the negotiated check and framing.
555    fn nak(&self) -> Vec<u8> {
556        Packet::new(self.seq, b'N', Vec::new()).wire(self.check(), &self.framing())
557    }
558
559    /// Queue a new packet in reply to input; it becomes the retransmit copy.
560    fn reply(&mut self, now: Instant, bytes: Vec<u8>) {
561        self.last_sent = bytes.clone();
562        self.deadline = None;
563        let due = self.paused(now);
564        self.queue.push_back((due, bytes));
565    }
566
567    fn reply_packet(&mut self, now: Instant, seq: u8, kind: u8, data: Vec<u8>) {
568        let bytes = Packet::new(seq, kind, data).wire(self.check(), &self.framing());
569        self.reply(now, bytes);
570    }
571
572    /// Count a retry and re-queue `last_sent` due at `due`, or give up.
573    fn retry(&mut self, now: Instant, due: Instant) {
574        let bytes = self.last_sent.clone();
575        self.retry_with(now, due, bytes);
576    }
577
578    /// Count a retry and queue `bytes` (not stored as `last_sent`) due at
579    /// `due`, or give up.
580    fn retry_with(&mut self, now: Instant, due: Instant, bytes: Vec<u8>) {
581        self.retries += 1;
582        let limit = match (&self.phase, self.config.first_packet_retries) {
583            (Phase::Await(_), Some(first)) => first.saturating_add(u32::from(self.nak_resend)),
584            _ => self.config.retries,
585        };
586        if self.retries > limit {
587            self.fail(now, Error::Timeout, Some(b"Too many retries"));
588        } else {
589            self.deadline = None;
590            self.queue.push_back((due, bytes));
591        }
592    }
593
594    fn stale_nak(&mut self, now: Instant) {
595        self.nak_wait(now, self.config.nak_grace);
596    }
597
598    /// Resend (or give up) at `now + grace` at the latest.
599    fn nak_wait(&mut self, now: Instant, grace: Duration) {
600        // A grace period that overflows `Instant` leaves the deadline as is.
601        if let Some(grace) = now.checked_add(grace) {
602            self.deadline = Some(self.deadline.map_or(grace, |d| d.min(grace)));
603        }
604    }
605
606    /// A NAK of seq `seq` while awaiting the answer to the first packet.
607    /// Inside [`Config::first_packet_nak_window`] (and not before the
608    /// packet's wire time, [`Config::first_packet_nak_byte_time`]), with the
609    /// first-packet budget spent and no extra resend granted yet, it grants
610    /// one; while that resend waits, a NAK changes nothing; otherwise it is
611    /// a stale NAK.
612    fn await_nak(&mut self, now: Instant, seq: u8) {
613        let Some(first) = self.config.first_packet_retries else {
614            return self.stale_nak(now);
615        };
616        if self.nak_resend && self.retries <= first {
617            // The granted resend is pending: keep its deadline.
618            return;
619        }
620        if let (Some(window), Some((sent, len))) =
621            (self.config.first_packet_nak_window, self.first_sent)
622            && seq == 0
623            && !self.nak_resend
624            && self.retries >= first
625        {
626            let since = now.saturating_duration_since(sent);
627            // The packet's wire time; an overflow means it never ends.
628            let wire = match self.config.first_packet_nak_byte_time {
629                None => Some(Duration::ZERO),
630                Some(byte) => u32::try_from(len).ok().and_then(|n| byte.checked_mul(n)),
631            };
632            if wire.is_some_and(|wire| since >= wire) && since <= window {
633                self.nak_resend = true;
634                let grace = self
635                    .config
636                    .first_packet_nak_grace
637                    .unwrap_or(self.config.nak_grace);
638                return self.nak_wait(now, grace);
639            }
640        }
641        self.stale_nak(now);
642    }
643
644    fn finish(&mut self, event: Event) {
645        self.events.push_back(event);
646        self.phase = Phase::Idle;
647        self.deadline = None;
648    }
649
650    /// Done after the final ACK to B (queued at `now`): linger for
651    /// [`Config::linger`] after it goes out, or go idle at once.
652    fn finish_lingering(&mut self, now: Instant) {
653        self.finish(Event::Done);
654        // A linger that overflows `Instant` would never end: skip it.
655        if let Some(end) = self.paused(now).checked_add(self.config.linger)
656            && !self.config.linger.is_zero()
657        {
658            self.phase = Phase::Linger;
659            self.deadline = Some(end);
660        }
661    }
662
663    fn end_linger(&mut self) {
664        self.phase = Phase::Idle;
665        self.deadline = None;
666        self.deframer.clear();
667    }
668
669    /// Drop queued copies of `bytes` that have not gone out yet: the reply
670    /// that made them obsolete has arrived.
671    fn drop_queued(&mut self, bytes: &[u8]) {
672        self.queue.retain(|(_, b)| b.as_slice() != bytes);
673    }
674
675    /// Queue an E packet (if `text`), emit Error, go idle. Output still queued
676    /// (a held-back ACK, D or F) is dropped first so nothing follows the E.
677    fn fail(&mut self, now: Instant, err: Error, text: Option<&[u8]>) {
678        self.queue.clear();
679        if let Some(text) = text {
680            let data = prefix::encode_all(text, &self.send_quoting());
681            let bytes = Packet::new(self.seq, b'E', data).wire(self.check(), &self.framing());
682            self.queue.push_back((now, bytes));
683        }
684        self.finish(Event::Error(err));
685    }
686
687    fn protocol(&mut self, now: Instant, msg: String, text: &[u8]) {
688        self.fail(now, Error::Protocol(msg), Some(text));
689    }
690
691    fn remote(&mut self, data: &[u8], q: &Quoting) {
692        let text = prefix::decode(data, q).unwrap_or_else(|_| data.to_vec());
693        self.finish(Event::Error(Error::Remote(text)));
694    }
695
696    /// Decode received data, failing the transaction on a prefix error.
697    fn decode(&mut self, now: Instant, data: &[u8], q: &Quoting) -> Option<Vec<u8>> {
698        match prefix::decode(data, q) {
699            Ok(v) => Some(v),
700            Err(e) => {
701                self.protocol(now, e.to_string(), b"Bad prefix");
702                None
703            }
704        }
705    }
706
707    // ---- receiving ----
708
709    fn on_await(&mut self, now: Instant, kind: Kind, parsed: Result<Packet, FrameError>) {
710        let Ok(p) = parsed else { return };
711        match p.kind {
712            b'N' => self.await_nak(now, p.seq),
713            b'E' => {
714                if kind == Kind::Info {
715                    self.finish(Event::Done);
716                } else {
717                    self.remote(&p.data, &Quoting::default());
718                }
719            }
720            b'S' if p.seq == 0 => {
721                let theirs = InitParams::decode(&p.data);
722                let n = negotiate(&self.ours, &theirs);
723                self.peer = Some(theirs);
724                // The ACK to S uses type 1 but already the peer's framing.
725                let bytes =
726                    Packet::new(0, b'Y', self.ours.encode()).wire(BlockCheck::Type1, &n.framing);
727                self.reply(now, bytes);
728                self.neg = Some(n);
729                self.seq = 1;
730                self.retries = 0;
731                self.accepted += 1;
732                self.phase = Phase::Receive {
733                    text: None,
734                    file: false,
735                };
736            }
737            b'Y' if p.seq == 0 => match kind {
738                Kind::Info => {
739                    self.peer = Some(InitParams::decode(&p.data));
740                    self.finish(Event::Done);
741                }
742                Kind::Text => {
743                    if !p.data.is_empty() {
744                        let Some(text) = self.decode(now, &p.data, &Quoting::default()) else {
745                            return;
746                        };
747                        self.events.push_back(Event::ServerText(text));
748                    }
749                    self.finish(Event::Done);
750                }
751                Kind::Generic => self.finish(Event::Done),
752                Kind::Get => {
753                    self.protocol(now, "unexpected ACK to R".to_string(), b"Unexpected packet")
754                }
755            },
756            _ => {}
757        }
758    }
759
760    fn on_receive(&mut self, now: Instant, parsed: Result<Packet, FrameError>) {
761        let n = self.seq;
762        let p = match parsed {
763            Ok(p) => p,
764            Err(FrameError::BadCheck) => {
765                // Not stored as last_sent: a duplicate still gets the last ACK.
766                let nak = self.nak();
767                let due = self.paused(now);
768                self.retry_with(now, due, nak);
769                return;
770            }
771            Err(FrameError::BadLength) => return,
772        };
773        if p.kind == b'E' {
774            let q = self.recv_quoting();
775            self.remote(&p.data, &q);
776            return;
777        }
778        if p.seq != n {
779            if p.seq == (n + 63) % 64 && p.kind != b'N' {
780                // The previous packet again: the last ACK again, counted as
781                // a retry (only a new packet resets the count), so a peer
782                // replaying one packet cannot hold the transaction open.
783                let due = self.paused(now);
784                self.retry(now, due);
785            }
786            return;
787        }
788        if p.kind != b'N' {
789            // Packet n arrived: a NAK for it still queued is obsolete.
790            let nak = self.nak();
791            self.drop_queued(&nak);
792        }
793        let q = self.recv_quoting();
794        match p.kind {
795            b'F' | b'D' | b'Z' => {
796                let Some(data) = self.decode(now, &p.data, &q) else {
797                    return;
798                };
799                if p.kind == b'D' && !self.accept(now, data.len()) {
800                    return;
801                }
802                let Phase::Receive { text, file } = &mut self.phase else {
803                    return;
804                };
805                match (p.kind, text.as_mut()) {
806                    (b'F', _) => {
807                        *text = None;
808                        *file = true;
809                        self.events.push_back(Event::FileStart { name: data });
810                    }
811                    (b'D', Some(buf)) => buf.extend_from_slice(&data),
812                    (b'D', None) => self.events.push_back(Event::Data(data)),
813                    (_, Some(_)) => {
814                        let buf = text.take().unwrap_or_default();
815                        self.events.push_back(Event::ServerText(buf));
816                    }
817                    (_, None) => {
818                        *file = false;
819                        self.events.push_back(Event::FileEnd {
820                            discarded: data == b"D",
821                        });
822                    }
823                }
824            }
825            b'X' => {
826                if let Phase::Receive { text, .. } = &mut self.phase {
827                    *text = Some(Vec::new());
828                }
829            }
830            b'A' => {}
831            b'B' => {
832                let open = match &self.phase {
833                    Phase::Receive { text, file } => *file || text.is_some(),
834                    _ => false,
835                };
836                if open {
837                    // Acknowledging it would pass off a truncated file (or
838                    // reply text) as a success.
839                    self.protocol(
840                        now,
841                        "B before the Z of the current file".to_string(),
842                        b"Unexpected B",
843                    );
844                    return;
845                }
846                self.reply_packet(now, n, b'Y', Vec::new());
847                self.finish_lingering(now);
848                return;
849            }
850            b'N' => return,
851            other => {
852                self.protocol(
853                    now,
854                    format!("unexpected packet {:?}", char::from(other)),
855                    b"Unexpected packet",
856                );
857                return;
858            }
859        }
860        self.reply_packet(now, n, b'Y', Vec::new());
861        self.seq = (n + 1) % 64;
862        self.retries = 0;
863        self.accepted += 1;
864    }
865
866    /// Count `len` received data bytes against [`Config::max_size`]; false
867    /// (and the transaction failed) if they do not fit.
868    fn accept(&mut self, now: Instant, len: usize) -> bool {
869        self.received = self.received.saturating_add(len);
870        match self.config.max_size {
871            Some(limit) if self.received > limit => {
872                self.fail(now, Error::TooLarge { limit }, Some(b"Too large"));
873                false
874            }
875            _ => true,
876        }
877    }
878
879    /// After the final ACK: answer a retransmitted B with the same ACK (one
880    /// pending copy at most); anything else is ignored.
881    fn on_linger(&mut self, now: Instant, parsed: Result<Packet, FrameError>) {
882        if let Ok(p) = parsed
883            && p.kind == b'B'
884            && p.seq == self.seq
885            && !self.queue.iter().any(|(_, b)| *b == self.last_sent)
886        {
887            let due = self.paused(now);
888            self.queue.push_back((due, self.last_sent.clone()));
889        }
890    }
891
892    // ---- sending ----
893
894    fn on_send(&mut self, now: Instant, parsed: Result<Packet, FrameError>, raw_seq: Option<u8>) {
895        let n = self.seq;
896        let init = matches!(&self.phase, Phase::Send(s) if s.step == Step::Init);
897        let p = match parsed {
898            Ok(p) => p,
899            Err(FrameError::BadCheck) => {
900                // A damaged reply for the outstanding packet acts as a NAK.
901                // Anything else (e.g. a late duplicate ACK(0) to S, which uses
902                // check type 1) is ignored.
903                if raw_seq == Some(n) {
904                    let due = self.paused(now);
905                    self.retry(now, due);
906                }
907                return;
908            }
909            Err(FrameError::BadLength) => return,
910        };
911        match p.kind {
912            b'E' => {
913                let q = self.recv_quoting();
914                self.remote(&p.data, &q);
915            }
916            b'Y' if p.seq == n => {
917                self.drop_obsolete_retry();
918                self.on_ack(now, &p.data);
919            }
920            b'N' if p.seq == (n + 1) % 64 => {
921                self.drop_obsolete_retry();
922                self.on_ack(now, &[]);
923            }
924            b'N' if p.seq == n => {
925                if init {
926                    self.stale_nak(now);
927                } else {
928                    let due = self.paused(now);
929                    self.retry(now, due);
930                }
931            }
932            _ => {}
933        }
934    }
935
936    /// Packet n is acknowledged: a retransmission of it still queued (from a
937    /// NAK or damaged reply in the same input, or held back by
938    /// `packet_pause`) would only delay the next packet.
939    fn drop_obsolete_retry(&mut self) {
940        let sent = std::mem::take(&mut self.last_sent);
941        self.drop_queued(&sent);
942        self.last_sent = sent;
943    }
944
945    fn send_next(&mut self, now: Instant, kind: u8, data: Vec<u8>) {
946        self.seq = (self.seq + 1) % 64;
947        self.reply_packet(now, self.seq, kind, data);
948    }
949
950    fn max_data(&self) -> usize {
951        let maxl = self.neg.map_or(DEFAULT_MAXL, |n| usize::from(n.peer_maxl));
952        Packet::max_data(maxl, self.check())
953    }
954
955    fn sending(&mut self) -> Option<&mut Sending> {
956        match &mut self.phase {
957            Phase::Send(s) => Some(s),
958            _ => None,
959        }
960    }
961
962    fn on_ack(&mut self, now: Instant, data: &[u8]) {
963        self.retries = 0;
964        self.accepted += 1;
965        let Some(step) = self.sending().map(|s| s.step) else {
966            return;
967        };
968        match step {
969            Step::Init => {
970                let theirs = InitParams::decode(data);
971                self.peer = Some(theirs);
972                self.neg = Some(negotiate(&self.ours, &theirs));
973                self.next_file(now);
974            }
975            Step::File => {
976                let name = if data.is_empty() {
977                    self.sending()
978                        .and_then(|s| s.files.get(s.idx))
979                        .map(|f| f.name.clone())
980                        .unwrap_or_default()
981                } else {
982                    let q = self.recv_quoting();
983                    let Some(name) = self.decode(now, data, &q) else {
984                        return;
985                    };
986                    name
987                };
988                self.events.push_back(Event::FileStart { name });
989                self.next_data(now);
990            }
991            Step::Data { chunk } => {
992                let Some(s) = self.sending() else { return };
993                s.pos += chunk;
994                let sent = s.pos as u64;
995                let total = s.files.get(s.idx).map_or(0, |f| f.data.len()) as u64;
996                self.events.push_back(Event::Progress { sent, total });
997                if data == b"X" || data == b"Z" {
998                    if let Some(s) = self.sending() {
999                        s.step = Step::Eof {
1000                            discarded: true,
1001                            skip_rest: data == b"Z",
1002                        };
1003                    }
1004                    let d = prefix::encode_all(b"D", &self.send_quoting());
1005                    self.send_next(now, b'Z', d);
1006                } else {
1007                    self.next_data(now);
1008                }
1009            }
1010            Step::Eof {
1011                discarded,
1012                skip_rest,
1013            } => {
1014                self.events.push_back(Event::FileEnd { discarded });
1015                if let Some(s) = self.sending() {
1016                    s.idx = if skip_rest { s.files.len() } else { s.idx + 1 };
1017                }
1018                self.next_file(now);
1019            }
1020            Step::Break => self.finish(Event::Done),
1021        }
1022    }
1023
1024    /// Send F for the current file, or B when all files are done. Fails the
1025    /// transaction if the encoded name does not fit in one packet.
1026    fn next_file(&mut self, now: Instant) {
1027        let max = self.max_data();
1028        let q = self.send_quoting();
1029        let Some(s) = self.sending() else { return };
1030        let encoded = s.files.get(s.idx).map(|f| {
1031            let (enc, used) = prefix::encode(&f.name, &q, max);
1032            (enc, used == f.name.len())
1033        });
1034        match encoded {
1035            Some((_, false)) => {
1036                self.protocol(
1037                    now,
1038                    format!("file name does not fit in a packet of {max} data bytes"),
1039                    b"File name too long",
1040                );
1041            }
1042            Some((name, true)) => {
1043                s.pos = 0;
1044                s.step = Step::File;
1045                self.send_next(now, b'F', name);
1046            }
1047            None => {
1048                s.step = Step::Break;
1049                self.send_next(now, b'B', Vec::new());
1050            }
1051        }
1052    }
1053
1054    /// Send the next D chunk of the current file, or Z at its end.
1055    fn next_data(&mut self, now: Instant) {
1056        let max = self.max_data();
1057        let q = self.send_quoting();
1058        let Some(s) = self.sending() else { return };
1059        let rest = s
1060            .files
1061            .get(s.idx)
1062            .and_then(|f| f.data.get(s.pos..))
1063            .unwrap_or_default();
1064        if rest.is_empty() {
1065            s.step = Step::Eof {
1066                discarded: false,
1067                skip_rest: false,
1068            };
1069            self.send_next(now, b'Z', Vec::new());
1070        } else {
1071            let (enc, used) = prefix::encode(rest, &q, max);
1072            s.step = Step::Data { chunk: used };
1073            self.send_next(now, b'D', enc);
1074        }
1075    }
1076}
1077
1078/// Test helpers shared by trace tests.
1079#[cfg(test)]
1080#[allow(clippy::unwrap_used, clippy::expect_used)]
1081pub(crate) mod test_support {
1082    use super::*;
1083    use crate::trace::{self, Direction};
1084
1085    /// Replay `trace` at a fixed `now`: Out lines must match `poll_output`, In
1086    /// lines are fed to `handle_input`. Returns the client and all events.
1087    pub(crate) fn replay_client(cmd: Command, config: Config, text: &str) -> (Client, Vec<Event>) {
1088        let now = Instant::now();
1089        let mut c = Client::new(config);
1090        c.start(now, cmd).unwrap();
1091        let mut events = Vec::new();
1092        for (i, (dir, bytes)) in trace::parse(text).unwrap().into_iter().enumerate() {
1093            match dir {
1094                Direction::Out => {
1095                    let got = c.poll_output(now);
1096                    assert_eq!(
1097                        got.as_deref().map(trace::escape),
1098                        Some(trace::escape(&bytes)),
1099                        "trace entry {i}: expected output > {}",
1100                        trace::escape(&bytes)
1101                    );
1102                }
1103                Direction::In => c.handle_input(now, &bytes),
1104            }
1105            while let Some(e) = c.poll_event() {
1106                events.push(e);
1107            }
1108        }
1109        let extra = c.poll_output(now);
1110        assert_eq!(
1111            extra.as_deref().map(trace::escape),
1112            None,
1113            "unexpected trailing output"
1114        );
1115        (c, events)
1116    }
1117
1118    /// [`replay_client`] returning only the events.
1119    pub(crate) fn replay(cmd: Command, config: Config, text: &str) -> Vec<Event> {
1120        replay_client(cmd, config, text).1
1121    }
1122}
1123
1124#[cfg(test)]
1125#[allow(clippy::unwrap_used, clippy::expect_used)]
1126mod tests {
1127    use super::test_support::{replay, replay_client};
1128    use super::*;
1129    use crate::trace;
1130
1131    const T1: BlockCheck = BlockCheck::Type1;
1132    const T3: BlockCheck = BlockCheck::Type3;
1133    /// Our params with the default config.
1134    const OURS: &[u8] = b"~4 @-#Y3~";
1135
1136    fn wire(seq: u8, kind: u8, data: &[u8], check: BlockCheck) -> Vec<u8> {
1137        Packet::new(seq, kind, data.to_vec())
1138            .encode(check, &Framing::default())
1139            .unwrap()
1140    }
1141
1142    fn out(seq: u8, kind: u8, data: &[u8], check: BlockCheck) -> String {
1143        format!("> {}\n", trace::escape(&wire(seq, kind, data, check)))
1144    }
1145
1146    fn inp(seq: u8, kind: u8, data: &[u8], check: BlockCheck) -> String {
1147        format!("< {}\n", trace::escape(&wire(seq, kind, data, check)))
1148    }
1149
1150    fn hp_text() -> Vec<u8> {
1151        let mut v = b"1:".to_vec();
1152        v.extend_from_slice(&[b' '; 20]);
1153        v.extend_from_slice(b"42\r\n");
1154        v
1155    }
1156
1157    fn cfg() -> Config {
1158        Config::default()
1159    }
1160
1161    /// The HP's server-side Send-Init reply prefix: S, our ACK.
1162    fn s_exchange(theirs: &[u8]) -> String {
1163        inp(0, b'S', theirs, T1) + &out(0, b'Y', OURS, T1)
1164    }
1165
1166    #[test]
1167    fn our_params_encode() {
1168        assert_eq!(Client::new(cfg()).ours.encode(), OURS);
1169    }
1170
1171    #[test]
1172    fn host_long_reply_real_bytes() {
1173        let mut t = String::from("> \\x01( C6 7 *C\\r\n< \\x01+ S~* @-#Y3$\\r\n");
1174        t += &out(0, b'Y', OURS, T1);
1175        t += &inp(1, b'X', b"", T3);
1176        t += &out(1, b'Y', b"", T3);
1177        t += &inp(2, b'D', b"1:                    42#M#J", T3);
1178        t += &out(2, b'Y', b"", T3);
1179        t += &inp(3, b'Z', b"", T3);
1180        t += &out(3, b'Y', b"", T3);
1181        t += &inp(4, b'B', b"", T3);
1182        t += &out(4, b'Y', b"", T3);
1183        let ev = replay(Command::Host(b"6 7 *".to_vec()), cfg(), &t);
1184        assert_eq!(ev, vec![Event::ServerText(hp_text()), Event::Done]);
1185    }
1186
1187    #[test]
1188    fn host_short_reply() {
1189        let t = out(0, b'C', b"VARS", T1) + &inp(0, b'Y', b"{ A B }#M#J", T1);
1190        let ev = replay(Command::Host(b"VARS".to_vec()), cfg(), &t);
1191        assert_eq!(
1192            ev,
1193            vec![Event::ServerText(b"{ A B }\r\n".to_vec()), Event::Done]
1194        );
1195    }
1196
1197    #[test]
1198    fn directory_and_finish() {
1199        let t = out(0, b'G', b"D", T1) + &inp(0, b'Y', b"X 12", T1);
1200        let ev = replay(Command::Directory, cfg(), &t);
1201        assert_eq!(ev, vec![Event::ServerText(b"X 12".to_vec()), Event::Done]);
1202
1203        let t = out(0, b'G', b"F", T1) + &inp(0, b'Y', b"", T1);
1204        assert_eq!(replay(Command::Finish, cfg(), &t), vec![Event::Done]);
1205        let t = out(0, b'G', b"L", T1) + &inp(0, b'Y', b"", T1);
1206        assert_eq!(replay(Command::Logout, cfg(), &t), vec![Event::Done]);
1207    }
1208
1209    #[test]
1210    fn info_exchange() {
1211        let mut i = b"\x01, I~4 @-#Y3~".to_vec();
1212        let chk = T1.compute(&i[1..]);
1213        i.extend_from_slice(&chk);
1214        i.push(CR);
1215        assert_eq!(wire(0, b'I', OURS, T1), i);
1216        let t = format!("> {}\n< \\x01+ Y~& @-# 3,\\r\n", trace::escape(&i));
1217        let (c, ev) = replay_client(Command::Info, cfg(), &t);
1218        assert_eq!(ev, vec![Event::Done]);
1219        assert!(c.is_idle());
1220        assert_eq!(c.peer_params(), Some(InitParams::decode(b"~& @-# 3")));
1221        assert_eq!(c.peer_params().map(|p| p.time), Some(6));
1222
1223        let t = format!("> {}\n", trace::escape(&i)) + &inp(0, b'E', b"no I", T1);
1224        assert_eq!(replay(Command::Info, cfg(), &t), vec![Event::Done]);
1225    }
1226
1227    fn get_trace(theirs: &[u8], d1: &[u8], d2: &[u8]) -> String {
1228        let mut t = out(0, b'R', b"FILE", T1);
1229        t += &s_exchange(theirs);
1230        t += &inp(1, b'F', b"FILE", T3);
1231        t += &out(1, b'Y', b"", T3);
1232        t += &inp(2, b'D', d1, T3);
1233        t += &out(2, b'Y', b"", T3);
1234        t += &inp(3, b'D', d2, T3);
1235        t += &out(3, b'Y', b"", T3);
1236        t += &inp(4, b'Z', b"", T3);
1237        t += &out(4, b'Y', b"", T3);
1238        t += &inp(5, b'B', b"", T3);
1239        t += &out(5, b'Y', b"", T3);
1240        t
1241    }
1242
1243    fn get_events(d1: &[u8], d2: &[u8]) -> Vec<Event> {
1244        vec![
1245            Event::FileStart {
1246                name: b"FILE".to_vec(),
1247            },
1248            Event::Data(d1.to_vec()),
1249            Event::Data(d2.to_vec()),
1250            Event::FileEnd { discarded: false },
1251            Event::Done,
1252        ]
1253    }
1254
1255    #[test]
1256    fn get_eight_bit_clean() {
1257        // Peer QBIN 'Y', we offer 'Y': no 8th-bit prefixing; repeat agreed.
1258        let d1: &[u8] = &[b'H', b'P', 0xC1, b'#', b'#', 0xA3, b'#', b'~'];
1259        let d2: &[u8] = &[b'#', 0xC1, b'#', b'M', b'~', b'%', b'x'];
1260        let t = get_trace(b"~* @-#Y3~", d1, d2);
1261        let ev = replay(Command::Get(b"FILE".to_vec()), cfg(), &t);
1262        assert_eq!(
1263            ev,
1264            get_events(
1265                &[b'H', b'P', 0xC1, b'#', 0xA3, b'~'],
1266                &[0x81, b'\r', b'x', b'x', b'x', b'x', b'x']
1267            )
1268        );
1269    }
1270
1271    #[test]
1272    fn get_eight_bit_prefixed() {
1273        let config = Config {
1274            eight_bit_clean: false,
1275            ..cfg()
1276        };
1277        let mut t = out(0, b'R', b"FILE", T1);
1278        t += &inp(0, b'S', b"~* @-#Y3~", T1);
1279        t += &out(0, b'Y', b"~4 @-#&3~", T1);
1280        t += &get_trace(b"", b"&A&#A#&", b"&#?")
1281            .lines()
1282            .skip(3)
1283            .map(|l| format!("{l}\n"))
1284            .collect::<String>();
1285        let ev = replay(Command::Get(b"FILE".to_vec()), config, &t);
1286        assert_eq!(ev, get_events(&[0xC1, 0x81, b'&'], &[0xFF]));
1287    }
1288
1289    #[test]
1290    fn get_ack_is_protocol_error() {
1291        let t = out(0, b'R', b"X", T1)
1292            + &inp(0, b'Y', b"", T1)
1293            + &out(0, b'E', b"Unexpected packet", T1);
1294        let ev = replay(Command::Get(b"X".to_vec()), cfg(), &t);
1295        assert!(matches!(ev.as_slice(), [Event::Error(Error::Protocol(_))]));
1296    }
1297
1298    const PEER_SMALL: &[u8] = b"4* @-#Y3"; // maxl 20, no repeat
1299
1300    fn file(name: &[u8], data: &[u8]) -> OutgoingFile {
1301        OutgoingFile {
1302            name: name.to_vec(),
1303            data: data.to_vec(),
1304        }
1305    }
1306
1307    fn send_start() -> String {
1308        out(0, b'S', OURS, T1) + &inp(0, b'Y', PEER_SMALL, T1)
1309    }
1310
1311    const DATA40: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN";
1312
1313    #[test]
1314    fn send_one_file_with_stored_name() {
1315        // Peer MAXL 20, type 3: 15 data chars per D packet.
1316        let mut t = send_start();
1317        t += &out(1, b'F', b"local", T3);
1318        t += &inp(1, b'Y', b"STORED", T3);
1319        t += &out(2, b'D', &DATA40[..15], T3);
1320        t += &inp(2, b'Y', b"", T3);
1321        t += &out(3, b'D', &DATA40[15..30], T3);
1322        t += &inp(3, b'Y', b"", T3);
1323        t += &out(4, b'D', &DATA40[30..], T3);
1324        t += &inp(4, b'Y', b"", T3);
1325        t += &out(5, b'Z', b"", T3);
1326        t += &inp(5, b'Y', b"", T3);
1327        t += &out(6, b'B', b"", T3);
1328        t += &inp(6, b'Y', b"", T3);
1329        let (c, ev) = replay_client(Command::Send(vec![file(b"local", DATA40)]), cfg(), &t);
1330        assert_eq!(
1331            ev,
1332            vec![
1333                Event::FileStart {
1334                    name: b"STORED".to_vec()
1335                },
1336                Event::Progress {
1337                    sent: 15,
1338                    total: 40
1339                },
1340                Event::Progress {
1341                    sent: 30,
1342                    total: 40
1343                },
1344                Event::Progress {
1345                    sent: 40,
1346                    total: 40
1347                },
1348                Event::FileEnd { discarded: false },
1349                Event::Done,
1350            ]
1351        );
1352        assert_eq!(c.peer_params(), Some(InitParams::decode(PEER_SMALL)));
1353    }
1354
1355    #[test]
1356    fn send_naks_and_duplicates() {
1357        let mut t = send_start();
1358        t += &out(1, b'F', b"A", T3);
1359        // NAK for n+1 counts as the ACK for n (no stored name).
1360        t += &inp(2, b'N', b"", T3);
1361        t += &out(2, b'D', &DATA40[..15], T3);
1362        // NAK for n: immediate resend.
1363        t += &inp(2, b'N', b"", T3);
1364        t += &out(2, b'D', &DATA40[..15], T3);
1365        t += &inp(2, b'Y', b"", T3);
1366        t += &out(3, b'D', &DATA40[15..20], T3);
1367        // Duplicate ACK ignored.
1368        t += &inp(2, b'Y', b"", T3);
1369        t += &inp(3, b'Y', b"", T3);
1370        t += &out(4, b'Z', b"", T3);
1371        t += &inp(4, b'Y', b"", T3);
1372        t += &out(5, b'B', b"", T3);
1373        t += &inp(5, b'Y', b"", T3);
1374        let ev = replay(Command::Send(vec![file(b"A", &DATA40[..20])]), cfg(), &t);
1375        assert_eq!(
1376            ev,
1377            vec![
1378                Event::FileStart {
1379                    name: b"A".to_vec()
1380                },
1381                Event::Progress {
1382                    sent: 15,
1383                    total: 20
1384                },
1385                Event::Progress {
1386                    sent: 20,
1387                    total: 20
1388                },
1389                Event::FileEnd { discarded: false },
1390                Event::Done,
1391            ]
1392        );
1393    }
1394
1395    #[test]
1396    fn send_bad_check_resends() {
1397        let mut t = send_start();
1398        t += &out(1, b'F', b"A", T3);
1399        let mut bad = wire(1, b'Y', b"", T3);
1400        bad[4] ^= 1;
1401        t += &format!("< {}\n", trace::escape(&bad));
1402        t += &out(1, b'F', b"A", T3);
1403        let ev = replay(Command::Send(vec![file(b"A", b"")]), cfg(), &t);
1404        assert!(ev.is_empty());
1405    }
1406
1407    #[test]
1408    fn send_two_files_and_empty() {
1409        let mut t = send_start();
1410        t += &out(1, b'F', b"E", T3);
1411        t += &inp(1, b'Y', b"", T3);
1412        t += &out(2, b'Z', b"", T3);
1413        t += &inp(2, b'Y', b"", T3);
1414        t += &out(3, b'F', b"T", T3);
1415        t += &inp(3, b'Y', b"", T3);
1416        t += &out(4, b'D', b"hi#M#J", T3);
1417        t += &inp(4, b'Y', b"", T3);
1418        t += &out(5, b'Z', b"", T3);
1419        t += &inp(5, b'Y', b"", T3);
1420        t += &out(6, b'B', b"", T3);
1421        t += &inp(6, b'Y', b"", T3);
1422        let ev = replay(
1423            Command::Send(vec![file(b"E", b""), file(b"T", b"hi\r\n")]),
1424            cfg(),
1425            &t,
1426        );
1427        assert_eq!(
1428            ev,
1429            vec![
1430                Event::FileStart {
1431                    name: b"E".to_vec()
1432                },
1433                Event::FileEnd { discarded: false },
1434                Event::FileStart {
1435                    name: b"T".to_vec()
1436                },
1437                Event::Progress { sent: 4, total: 4 },
1438                Event::FileEnd { discarded: false },
1439                Event::Done,
1440            ]
1441        );
1442    }
1443
1444    #[test]
1445    fn send_interrupted_by_x() {
1446        let mut t = send_start();
1447        t += &out(1, b'F', b"A", T3);
1448        t += &inp(1, b'Y', b"", T3);
1449        t += &out(2, b'D', &DATA40[..15], T3);
1450        t += &inp(2, b'Y', b"X", T3);
1451        t += &out(3, b'Z', b"D", T3);
1452        t += &inp(3, b'Y', b"", T3);
1453        t += &out(4, b'F', b"B", T3);
1454        t += &inp(4, b'Y', b"", T3);
1455        t += &out(5, b'Z', b"", T3);
1456        t += &inp(5, b'Y', b"", T3);
1457        t += &out(6, b'B', b"", T3);
1458        t += &inp(6, b'Y', b"", T3);
1459        let ev = replay(
1460            Command::Send(vec![file(b"A", DATA40), file(b"B", b"")]),
1461            cfg(),
1462            &t,
1463        );
1464        assert_eq!(
1465            ev,
1466            vec![
1467                Event::FileStart {
1468                    name: b"A".to_vec()
1469                },
1470                Event::Progress {
1471                    sent: 15,
1472                    total: 40
1473                },
1474                Event::FileEnd { discarded: true },
1475                Event::FileStart {
1476                    name: b"B".to_vec()
1477                },
1478                Event::FileEnd { discarded: false },
1479                Event::Done,
1480            ]
1481        );
1482    }
1483
1484    #[test]
1485    fn send_interrupted_by_z_skips_rest() {
1486        let mut t = send_start();
1487        t += &out(1, b'F', b"A", T3);
1488        t += &inp(1, b'Y', b"", T3);
1489        t += &out(2, b'D', &DATA40[..15], T3);
1490        t += &inp(2, b'Y', b"Z", T3);
1491        t += &out(3, b'Z', b"D", T3);
1492        t += &inp(3, b'Y', b"", T3);
1493        t += &out(4, b'B', b"", T3);
1494        t += &inp(4, b'Y', b"", T3);
1495        let ev = replay(
1496            Command::Send(vec![file(b"A", DATA40), file(b"B", b"")]),
1497            cfg(),
1498            &t,
1499        );
1500        assert_eq!(ev[2], Event::FileEnd { discarded: true });
1501        assert_eq!(ev.len(), 4);
1502        assert_eq!(ev[3], Event::Done);
1503    }
1504
1505    #[test]
1506    fn stale_nak_before_reply() {
1507        let mut t = String::from("> \\x01( C6 7 *C\\r\n< \\x01# N3\\r\n< \\x01+ S~* @-#Y3$\\r\n");
1508        t += &out(0, b'Y', OURS, T1);
1509        t += &inp(1, b'B', b"", T3);
1510        t += &out(1, b'Y', b"", T3);
1511        let ev = replay(Command::Host(b"6 7 *".to_vec()), cfg(), &t);
1512        assert_eq!(ev, vec![Event::Done]);
1513    }
1514
1515    #[test]
1516    fn stale_nak_then_silence() {
1517        let config = cfg();
1518        let grace = config.nak_grace;
1519        let now = Instant::now();
1520        let mut c = Client::new(config);
1521        c.start(now, Command::Host(b"6 7 *".to_vec())).unwrap();
1522        let cmd = c.poll_output(now).unwrap();
1523        assert_eq!(cmd, b"\x01( C6 7 *C\r");
1524        c.handle_input(now, b"\x01# N3\r");
1525        assert_eq!(c.poll_output(now), None);
1526        assert_eq!(c.next_timeout(), Some(now + grace));
1527        c.handle_timeout(now + grace - Duration::from_millis(1));
1528        assert_eq!(c.poll_output(now + grace - Duration::from_millis(1)), None);
1529        c.handle_timeout(now + grace);
1530        assert_eq!(c.poll_output(now + grace), Some(cmd));
1531        assert_eq!(c.poll_event(), None);
1532    }
1533
1534    #[test]
1535    fn stale_nak_while_waiting_for_s_ack() {
1536        let mut t = out(0, b'S', OURS, T1);
1537        t += "< \\x01# N3\\r\n";
1538        t += &inp(0, b'Y', PEER_SMALL, T1);
1539        t += &out(1, b'B', b"", T3);
1540        t += &inp(1, b'Y', b"", T3);
1541        assert_eq!(replay(Command::Send(vec![]), cfg(), &t), vec![Event::Done]);
1542    }
1543
1544    #[test]
1545    fn input_while_idle_dropped() {
1546        let now = Instant::now();
1547        let mut c = Client::new(cfg());
1548        c.handle_input(now, b"\x01# N3\r\x01+ S~* @-#Y3$\r");
1549        c.handle_timeout(now + Duration::from_secs(100));
1550        assert_eq!(c.poll_event(), None);
1551        assert_eq!(c.poll_output(now), None);
1552        assert_eq!(c.next_timeout(), None);
1553        assert!(c.is_idle());
1554        // A partial packet before start does not leak into the transaction.
1555        c.handle_input(now, b"\x01+ S~*");
1556        c.start(now, Command::Finish).unwrap();
1557        c.handle_input(now, b" @-#Y3$\r");
1558        assert_eq!(c.poll_event(), None);
1559    }
1560
1561    #[test]
1562    fn receive_duplicate_bad_check_and_error() {
1563        let mut t = out(0, b'R', b"F", T1);
1564        t += &s_exchange(b"~* @-#Y3");
1565        t += &inp(1, b'F', b"F", T3);
1566        t += &out(1, b'Y', b"", T3);
1567        t += &inp(2, b'D', b"abc", T3);
1568        t += &out(2, b'Y', b"", T3);
1569        // Duplicate: our ACK was lost, re-ACK.
1570        t += &inp(2, b'D', b"abc", T3);
1571        t += &out(2, b'Y', b"", T3);
1572        // Bad check: NAK the expected seq.
1573        let mut bad = wire(3, b'D', b"def", T3);
1574        bad[5] ^= 1;
1575        t += &format!("< {}\n", trace::escape(&bad));
1576        t += &out(3, b'N', b"", T3);
1577        t += &inp(3, b'E', b"Disk full", T3);
1578        let ev = replay(Command::Get(b"F".to_vec()), cfg(), &t);
1579        assert_eq!(
1580            ev,
1581            vec![
1582                Event::FileStart {
1583                    name: b"F".to_vec()
1584                },
1585                Event::Data(b"abc".to_vec()),
1586                Event::Error(Error::Remote(b"Disk full".to_vec())),
1587            ]
1588        );
1589    }
1590
1591    #[test]
1592    fn receive_unexpected_and_bad_prefix() {
1593        let mut t = out(0, b'R', b"F", T1);
1594        t += &s_exchange(b"~* @-#Y3");
1595        t += &inp(1, b'Q', b"", T3);
1596        t += &out(1, b'E', b"Unexpected packet", T3);
1597        let ev = replay(Command::Get(b"F".to_vec()), cfg(), &t);
1598        assert!(matches!(ev.as_slice(), [Event::Error(Error::Protocol(_))]));
1599
1600        let mut t = out(0, b'R', b"F", T1);
1601        t += &s_exchange(b"~* @-#Y3");
1602        t += &inp(1, b'F', b"ab#", T3);
1603        t += &out(1, b'E', b"Bad prefix", T3);
1604        let ev = replay(Command::Get(b"F".to_vec()), cfg(), &t);
1605        assert!(matches!(ev.as_slice(), [Event::Error(Error::Protocol(_))]));
1606    }
1607
1608    #[test]
1609    fn remote_error_reply() {
1610        let t = out(0, b'C', b"X", T1) + &inp(0, b'E', b"Bad command", T1);
1611        let ev = replay(Command::Host(b"X".to_vec()), cfg(), &t);
1612        assert_eq!(
1613            ev,
1614            vec![Event::Error(Error::Remote(b"Bad command".to_vec()))]
1615        );
1616    }
1617
1618    #[test]
1619    fn timeouts_and_retries() {
1620        let config = Config {
1621            retries: 2,
1622            ..cfg()
1623        };
1624        let timeout = config.timeout;
1625        let now = Instant::now();
1626        let mut c = Client::new(config);
1627        c.start(now, Command::Finish).unwrap();
1628        assert_eq!(c.next_timeout(), Some(now));
1629        let pkt = c.poll_output(now).unwrap();
1630        assert_eq!(c.next_timeout(), Some(now + timeout));
1631        let mut t = now;
1632        // Too early: nothing happens.
1633        c.handle_timeout(now + timeout - Duration::from_millis(1));
1634        assert_eq!(c.poll_output(now + timeout), None);
1635        for _ in 0..2 {
1636            t += timeout;
1637            c.handle_timeout(t);
1638            assert_eq!(c.poll_output(t), Some(pkt.clone()));
1639            assert_eq!(c.next_timeout(), Some(t + timeout));
1640        }
1641        t += timeout;
1642        c.handle_timeout(t);
1643        assert_eq!(
1644            c.poll_output(t),
1645            Some(wire(0, b'E', b"Too many retries", T1))
1646        );
1647        assert_eq!(c.poll_output(t), None);
1648        assert_eq!(c.poll_event(), Some(Event::Error(Error::Timeout)));
1649        assert!(c.is_idle());
1650        assert_eq!(c.next_timeout(), None);
1651    }
1652
1653    #[test]
1654    fn packet_pause_delays_replies() {
1655        let pause = Duration::from_millis(100);
1656        let config = Config {
1657            packet_pause: pause,
1658            ..cfg()
1659        };
1660        let now = Instant::now();
1661        let mut c = Client::new(config);
1662        c.start(now, Command::Host(b"6 7 *".to_vec())).unwrap();
1663        assert_eq!(c.poll_output(now).unwrap(), b"\x01( C6 7 *C\r");
1664        c.handle_input(now, b"\x01+ S~* @-#Y3$\r");
1665        assert_eq!(c.poll_output(now), None);
1666        assert_eq!(c.next_timeout(), Some(now + pause));
1667        assert_eq!(c.poll_output(now + pause), Some(wire(0, b'Y', OURS, T1)));
1668    }
1669
1670    #[test]
1671    fn start_rejects_command_too_long() {
1672        let now = Instant::now();
1673        let mut c = Client::new(cfg());
1674        // Default MAXL 80, check type 1: 77 data bytes fit.
1675        assert_eq!(
1676            c.start(now, Command::Host(vec![b'x'; 78])),
1677            Err(StartError::TooLong { len: 78, max: 77 })
1678        );
1679        // Control characters double in size when encoded.
1680        assert_eq!(
1681            c.start(now, Command::Get(vec![b'\r'; 39])),
1682            Err(StartError::TooLong { len: 78, max: 77 })
1683        );
1684        assert!(c.is_idle());
1685        assert_eq!(c.poll_output(now), None);
1686        c.start(now, Command::Host(vec![b'x'; 77])).unwrap();
1687        let pkt = c.poll_output(now).unwrap();
1688        assert_eq!(pkt, wire(0, b'C', &[b'x'; 77], T1));
1689        assert_eq!(pkt[1], b'~' - 14); // LEN 80
1690    }
1691
1692    /// Get: R out, S in, ACK out, F(1) in, ACK(1) out.
1693    fn get_started(config: Config) -> (Client, Instant) {
1694        let now = Instant::now();
1695        let mut c = Client::new(config);
1696        c.start(now, Command::Get(b"F".to_vec())).unwrap();
1697        assert_eq!(c.poll_output(now), Some(wire(0, b'R', b"F", T1)));
1698        c.handle_input(now, &wire(0, b'S', b"~* @-#Y3", T1));
1699        assert_eq!(c.poll_output(now), Some(wire(0, b'Y', OURS, T1)));
1700        (c, now)
1701    }
1702
1703    /// `first_packet_retries = Some(0)` (satx's host commands, audit PR #18
1704    /// #1): the `C` is never resent, neither after a timeout nor after a
1705    /// NAK; once the server's `S` is in, a damaged reply packet is still
1706    /// NAKed and re-requested with the normal retries.
1707    #[test]
1708    fn first_packet_retries_only_cover_the_command() {
1709        let config = Config {
1710            first_packet_retries: Some(0),
1711            nak_grace: Duration::from_secs(20),
1712            ..cfg()
1713        };
1714        let timeout = config.timeout;
1715        let now = Instant::now();
1716        let mut c = Client::new(config.clone());
1717        c.start(now, Command::Host(b"X".to_vec())).unwrap();
1718        assert_eq!(c.poll_output(now), Some(wire(0, b'C', b"X", T1)));
1719        c.handle_input(now, &wire(0, b'N', b"", T1));
1720        c.handle_timeout(now + timeout);
1721        assert_eq!(
1722            c.poll_output(now + timeout),
1723            Some(wire(0, b'E', b"Too many retries", T1))
1724        );
1725        assert_eq!(c.poll_output(now + timeout), None);
1726        assert_eq!(c.poll_event(), Some(Event::Error(Error::Timeout)));
1727
1728        // The same command answered: S, X, then a damaged D is NAKed twice
1729        // and the good copy accepted.
1730        let mut c = Client::new(config);
1731        c.start(now, Command::Host(b"X".to_vec())).unwrap();
1732        c.poll_output(now).unwrap();
1733        c.handle_input(now, &wire(0, b'S', b"~* @-#Y3", T1));
1734        assert_eq!(c.poll_output(now), Some(wire(0, b'Y', OURS, T1)));
1735        c.handle_input(now, &wire(1, b'X', b"", T3));
1736        assert_eq!(c.poll_output(now), Some(wire(1, b'Y', b"", T3)));
1737        let mut bad = wire(2, b'D', b"42", T3);
1738        bad[5] ^= 1;
1739        for _ in 0..2 {
1740            c.handle_input(now, &bad);
1741            assert_eq!(c.poll_output(now), Some(wire(2, b'N', b"", T3)));
1742        }
1743        // A lost packet: the timeout NAKs it too.
1744        c.handle_timeout(now + timeout);
1745        assert_eq!(c.poll_output(now + timeout), Some(wire(2, b'N', b"", T3)));
1746        c.handle_input(now + timeout, &wire(2, b'D', b"42", T3));
1747        assert_eq!(c.poll_output(now + timeout), Some(wire(2, b'Y', b"", T3)));
1748        assert!(
1749            !all_events(&mut c)
1750                .iter()
1751                .any(|e| matches!(e, Event::Error(_)))
1752        );
1753    }
1754
1755    const NAK_WINDOW: Duration = Duration::from_millis(250);
1756    const NAK_GRACE: Duration = Duration::from_secs(3);
1757    /// One byte at 9600 baud (10 bits).
1758    const BYTE_TIME: Duration = Duration::from_micros(1042);
1759
1760    /// satx's host-command config with the immediate-NAK window.
1761    fn nak_window_cfg() -> Config {
1762        Config {
1763            first_packet_retries: Some(0),
1764            first_packet_nak_window: Some(NAK_WINDOW),
1765            first_packet_nak_grace: Some(NAK_GRACE),
1766            first_packet_nak_byte_time: Some(BYTE_TIME),
1767            nak_grace: Duration::from_secs(20),
1768            ..cfg()
1769        }
1770    }
1771
1772    /// The Saturnus trace (48SX, link clock in seconds): our `C` at 0.000,
1773    /// the server's NAK seq 0 at 0.011, no `S` ever. Returns the client
1774    /// with the NAK fed, the start time and the `C` packet.
1775    fn nak_11ms_after_c(config: Config) -> (Client, Instant, Vec<u8>) {
1776        let now = Instant::now();
1777        let mut c = Client::new(config);
1778        c.start(now, Command::Host(b"2_m".to_vec())).unwrap();
1779        let cmd = c.poll_output(now).unwrap();
1780        assert_eq!(cmd, b"\x01& C2_m)\r");
1781        c.handle_input(now + Duration::from_millis(11), b"\x01# N3\r");
1782        assert_eq!(c.poll_output(now + Duration::from_millis(11)), None);
1783        (c, now, cmd)
1784    }
1785
1786    /// Iteration 13: the Saturnus trace. A NAK 11 ms after the `C` is a
1787    /// rejection: with `first_packet_retries = Some(0)` the `C` is resent
1788    /// once, after the immediate-NAK grace (not the 20 s `nak_grace`), and
1789    /// the server's answer to the resend completes the command.
1790    #[test]
1791    fn immediate_nak_allows_one_resend() {
1792        let (mut c, now, cmd) = nak_11ms_after_c(nak_window_cfg());
1793        let at = now + Duration::from_millis(11) + NAK_GRACE;
1794        assert_eq!(c.next_timeout(), Some(at));
1795        c.handle_timeout(at - Duration::from_millis(1));
1796        assert_eq!(c.poll_output(at), None);
1797        c.handle_timeout(at);
1798        assert_eq!(c.poll_output(at), Some(cmd));
1799        assert_eq!(c.poll_event(), None);
1800        c.handle_input(at, &wire(0, b'Y', b"{ A }", T1));
1801        assert_eq!(
1802            all_events(&mut c),
1803            vec![Event::ServerText(b"{ A }".to_vec()), Event::Done]
1804        );
1805    }
1806
1807    /// Iteration 13: an immediate NAK followed by the server's `S` within
1808    /// the grace (the NAK was a stale one that crossed our `C`, and the
1809    /// server did take it): no resend, the reply is received as usual.
1810    #[test]
1811    fn immediate_nak_then_s_is_not_resent() {
1812        let (mut c, now, _) = nak_11ms_after_c(nak_window_cfg());
1813        let t = now + Duration::from_secs(1);
1814        c.handle_input(t, &wire(0, b'S', b"~* @-#Y3", T1));
1815        assert_eq!(c.poll_output(t), Some(wire(0, b'Y', OURS, T1)));
1816        c.handle_input(t, &wire(1, b'B', b"", T3));
1817        assert_eq!(c.poll_output(t), Some(wire(1, b'Y', b"", T3)));
1818        assert_eq!(c.poll_output(t + NAK_GRACE), None);
1819        assert_eq!(all_events(&mut c), vec![Event::Done]);
1820    }
1821
1822    /// Iteration 13: a NAK after the window (here 251 ms after the `C`) is
1823    /// the idle server's periodic NAK, which may have crossed a `C` it took:
1824    /// `Some(0)` as before, no resend, neither after it nor after the
1825    /// timeout, and the wait is the full `nak_grace`.
1826    #[test]
1827    fn nak_after_the_window_is_not_resent() {
1828        let config = nak_window_cfg();
1829        let timeout = config.timeout;
1830        let now = Instant::now();
1831        let mut c = Client::new(config);
1832        c.start(now, Command::Host(b"2_m".to_vec())).unwrap();
1833        c.poll_output(now).unwrap();
1834        let late = now + NAK_WINDOW + Duration::from_millis(1);
1835        c.handle_input(late, b"\x01# N3\r");
1836        assert_eq!(c.next_timeout(), Some(now + timeout));
1837        c.handle_timeout(now + timeout);
1838        assert_eq!(
1839            c.poll_output(now + timeout),
1840            Some(wire(0, b'E', b"Too many retries", T1))
1841        );
1842        assert_eq!(c.poll_output(now + timeout), None);
1843        assert_eq!(all_events(&mut c), vec![Event::Error(Error::Timeout)]);
1844    }
1845
1846    /// Iteration 13: only one resend per command. Two immediate NAKs before
1847    /// the resend grant one, and an immediate NAK of the resend grants no
1848    /// second: the client waits the full `nak_grace` (timeout) and gives up.
1849    #[test]
1850    fn two_immediate_naks_allow_only_one_resend() {
1851        let config = nak_window_cfg();
1852        let timeout = config.timeout;
1853        let (mut c, now, cmd) = nak_11ms_after_c(config);
1854        c.handle_input(now + Duration::from_millis(20), b"\x01# N3\r");
1855        let at = now + Duration::from_millis(11) + NAK_GRACE;
1856        assert_eq!(c.next_timeout(), Some(at));
1857        c.handle_timeout(at);
1858        assert_eq!(c.poll_output(at), Some(cmd));
1859        c.handle_input(at + Duration::from_millis(11), b"\x01# N3\r");
1860        assert_eq!(c.next_timeout(), Some(at + timeout));
1861        c.handle_timeout(at + timeout);
1862        assert_eq!(
1863            c.poll_output(at + timeout),
1864            Some(wire(0, b'E', b"Too many retries", T1))
1865        );
1866        assert_eq!(all_events(&mut c), vec![Event::Error(Error::Timeout)]);
1867    }
1868
1869    /// PR #26 review, #1: a NAK sooner than our packet's wire time (9
1870    /// bytes at 9600 baud, 9.4 ms) cannot answer it: input that was
1871    /// waiting in the buffer, or the idle server's NAK sent while our `C`
1872    /// was on the wire. It is stale: no resend, the full `nak_grace`.
1873    #[test]
1874    fn nak_before_the_wire_time_is_stale() {
1875        let config = nak_window_cfg();
1876        let timeout = config.timeout;
1877        let now = Instant::now();
1878        let mut c = Client::new(config);
1879        c.start(now, Command::Host(b"2_m".to_vec())).unwrap();
1880        let cmd = c.poll_output(now).unwrap();
1881        assert_eq!(cmd.len(), 9);
1882        for ms in [0, 9] {
1883            c.handle_input(now + Duration::from_millis(ms), b"\x01# N3\r");
1884        }
1885        assert_eq!(c.next_timeout(), Some(now + timeout));
1886        c.handle_timeout(now + timeout);
1887        assert_eq!(
1888            c.poll_output(now + timeout),
1889            Some(wire(0, b'E', b"Too many retries", T1))
1890        );
1891        assert_eq!(all_events(&mut c), vec![Event::Error(Error::Timeout)]);
1892    }
1893
1894    /// PR #26 review, #3: once an immediate NAK granted the resend, a
1895    /// further NAK (here a stale one with a `nak_grace` shorter than the
1896    /// immediate-NAK grace) does not bring the resend forward.
1897    #[test]
1898    fn nak_after_the_grant_keeps_the_grace() {
1899        let config = Config {
1900            nak_grace: Duration::from_secs(1),
1901            ..nak_window_cfg()
1902        };
1903        let (mut c, now, cmd) = nak_11ms_after_c(config);
1904        let at = now + Duration::from_millis(11) + NAK_GRACE;
1905        c.handle_input(now + Duration::from_millis(500), b"\x01# N3\r");
1906        assert_eq!(c.next_timeout(), Some(at));
1907        c.handle_timeout(now + Duration::from_millis(1500));
1908        assert_eq!(c.poll_output(now + Duration::from_millis(1500)), None);
1909        c.handle_timeout(at);
1910        assert_eq!(c.poll_output(at), Some(cmd));
1911    }
1912
1913    /// Iteration 13: without a NAK, a timeout keeps `Some(0)`: the window
1914    /// never turns silence into a resend.
1915    #[test]
1916    fn nak_window_does_not_resend_after_a_timeout() {
1917        let config = nak_window_cfg();
1918        let timeout = config.timeout;
1919        let now = Instant::now();
1920        let mut c = Client::new(config);
1921        c.start(now, Command::Host(b"2_m".to_vec())).unwrap();
1922        c.poll_output(now).unwrap();
1923        c.handle_timeout(now + timeout);
1924        assert_eq!(
1925            c.poll_output(now + timeout),
1926            Some(wire(0, b'E', b"Too many retries", T1))
1927        );
1928        assert_eq!(all_events(&mut c), vec![Event::Error(Error::Timeout)]);
1929    }
1930
1931    #[test]
1932    fn receive_timeout_naks_expected_packet() {
1933        let config = Config {
1934            retries: 2,
1935            ..cfg()
1936        };
1937        let timeout = config.timeout;
1938        let (mut c, mut t) = get_started(config);
1939        // Timeout right after the S ACK: NAK(1), which the sender reads as ACK(0).
1940        t += timeout;
1941        c.handle_timeout(t);
1942        assert_eq!(c.poll_output(t), Some(wire(1, b'N', b"", T3)));
1943        c.handle_input(t, &wire(1, b'F', b"F", T3));
1944        assert_eq!(c.poll_output(t), Some(wire(1, b'Y', b"", T3)));
1945        // A timeout while waiting for packet 2: NAK(2), counted as a retry.
1946        t += timeout;
1947        c.handle_timeout(t);
1948        assert_eq!(c.poll_output(t), Some(wire(2, b'N', b"", T3)));
1949        // A duplicate still gets the last ACK, not the NAK; it counts as a
1950        // retry too (the second of two).
1951        c.handle_input(t, &wire(1, b'F', b"F", T3));
1952        assert_eq!(c.poll_output(t), Some(wire(1, b'Y', b"", T3)));
1953        t += timeout;
1954        c.handle_timeout(t);
1955        assert_eq!(
1956            c.poll_output(t),
1957            Some(wire(2, b'E', b"Too many retries", T3))
1958        );
1959        assert_eq!(
1960            c.poll_event(),
1961            Some(Event::FileStart {
1962                name: b"F".to_vec()
1963            })
1964        );
1965        assert_eq!(c.poll_event(), Some(Event::Error(Error::Timeout)));
1966    }
1967
1968    /// A peer that replays the previous packet forever gets its ACK
1969    /// `retries` times, then the transaction ends with the retry error; a
1970    /// new packet in between resets the count.
1971    #[test]
1972    fn a_replaying_peer_runs_out_of_retries() {
1973        let config = Config {
1974            retries: 3,
1975            ..cfg()
1976        };
1977        let (mut c, t) = get_started(config);
1978        c.handle_input(t, &wire(1, b'F', b"F", T3));
1979        assert_eq!(c.poll_output(t), Some(wire(1, b'Y', b"", T3)));
1980        for _ in 0..3 {
1981            c.handle_input(t, &wire(1, b'F', b"F", T3));
1982            assert_eq!(c.poll_output(t), Some(wire(1, b'Y', b"", T3)));
1983        }
1984        // Packet 2 resets the count: three more replays of it are ACKed.
1985        c.handle_input(t, &wire(2, b'D', b"x", T3));
1986        assert_eq!(c.poll_output(t), Some(wire(2, b'Y', b"", T3)));
1987        for _ in 0..3 {
1988            c.handle_input(t, &wire(2, b'D', b"x", T3));
1989            assert_eq!(c.poll_output(t), Some(wire(2, b'Y', b"", T3)));
1990        }
1991        c.handle_input(t, &wire(2, b'D', b"x", T3));
1992        assert_eq!(
1993            c.poll_output(t),
1994            Some(wire(3, b'E', b"Too many retries", T3))
1995        );
1996        assert_eq!(c.poll_output(t), None);
1997        let events = all_events(&mut c);
1998        assert_eq!(events.last(), Some(&Event::Error(Error::Timeout)));
1999    }
2000
2001    /// `accepted` counts new packets only: a replay, a NAK, a damaged
2002    /// packet and noise leave it alone.
2003    #[test]
2004    fn accepted_counts_new_packets_only() {
2005        let (mut c, t) = get_started(cfg());
2006        let start = c.accepted();
2007        assert_eq!(start, 1, "the S answering the R");
2008        c.handle_input(t, &wire(1, b'F', b"F", T3));
2009        assert_eq!(c.accepted(), 2);
2010        c.handle_input(t, &wire(1, b'F', b"F", T3));
2011        c.handle_input(t, &wire(2, b'N', b"", T3));
2012        c.handle_input(t, b"zq~ noise");
2013        let mut damaged = wire(2, b'D', b"x", T3);
2014        let last = damaged.len() - 2;
2015        damaged[last] ^= 1;
2016        c.handle_input(t, &damaged);
2017        assert_eq!(c.accepted(), 2);
2018        c.handle_input(t, &wire(2, b'D', b"x", T3));
2019        assert_eq!(c.accepted(), 3);
2020    }
2021
2022    #[test]
2023    fn send_ignores_bad_check_for_other_seq() {
2024        let mut t = send_start();
2025        t += &out(1, b'F', b"A", T3);
2026        // Late duplicate ACK(0) to S: type 1, fails the type 3 check, ignored.
2027        t += &inp(0, b'Y', PEER_SMALL, T1);
2028        // Damaged frame with an unrelated seq: ignored.
2029        let mut bad = wire(5, b'Y', b"", T3);
2030        bad[4] ^= 1;
2031        t += &format!("< {}\n", trace::escape(&bad));
2032        t += &inp(1, b'Y', b"", T3);
2033        t += &out(2, b'Z', b"", T3);
2034        let (c, ev) = replay_client(Command::Send(vec![file(b"A", b"")]), cfg(), &t);
2035        assert_eq!(
2036            ev,
2037            vec![Event::FileStart {
2038                name: b"A".to_vec()
2039            }]
2040        );
2041        assert_eq!(c.retries, 0);
2042    }
2043
2044    #[test]
2045    fn send_file_name_too_long_fails() {
2046        // Peer MAXL 20, type 3: 15 data bytes; the name needs 16.
2047        let mut t = send_start();
2048        t += &out(0, b'E', b"File name too long", T3);
2049        let ev = replay(
2050            Command::Send(vec![file(b"ABCDEFGHIJKLMNOP", b"x")]),
2051            cfg(),
2052            &t,
2053        );
2054        assert!(matches!(ev.as_slice(), [Event::Error(Error::Protocol(_))]));
2055        // 15 bytes fit.
2056        let mut t = send_start();
2057        t += &out(1, b'F', b"ABCDEFGHIJKLMNO", T3);
2058        let ev = replay(
2059            Command::Send(vec![file(b"ABCDEFGHIJKLMNO", b"")]),
2060            cfg(),
2061            &t,
2062        );
2063        assert!(ev.is_empty());
2064    }
2065
2066    #[test]
2067    fn cancel_drops_queued_output() {
2068        let pause = Duration::from_millis(100);
2069        let config = Config {
2070            packet_pause: pause,
2071            ..cfg()
2072        };
2073        let now = Instant::now();
2074        let mut c = Client::new(config);
2075        c.start(now, Command::Host(b"6 7 *".to_vec())).unwrap();
2076        assert!(c.poll_output(now).is_some());
2077        // The ACK to S is held back by the pause when we cancel.
2078        c.handle_input(now, b"\x01+ S~* @-#Y3$\r");
2079        c.cancel(now);
2080        assert_eq!(c.poll_output(now), Some(wire(1, b'E', b"Cancelled", T3)));
2081        assert_eq!(c.poll_output(now + pause), None);
2082        assert_eq!(c.next_timeout(), None);
2083        assert_eq!(c.poll_event(), Some(Event::Error(Error::Cancelled)));
2084    }
2085
2086    #[test]
2087    fn huge_durations_do_not_overflow() {
2088        let config = Config {
2089            timeout: Duration::MAX,
2090            packet_pause: Duration::MAX,
2091            nak_grace: Duration::MAX,
2092            ..cfg()
2093        };
2094        let now = Instant::now();
2095        let mut c = Client::new(config);
2096        c.start(now, Command::Host(b"6 7 *".to_vec())).unwrap();
2097        assert!(c.poll_output(now).is_some());
2098        // Deadline overflows: none.
2099        assert_eq!(c.next_timeout(), None);
2100        // Grace overflows: no deadline either.
2101        c.handle_input(now, b"\x01# N3\r");
2102        assert_eq!(c.next_timeout(), None);
2103        // Pause overflows: the reply is not delayed.
2104        c.handle_input(now, b"\x01+ S~* @-#Y3$\r");
2105        let ack = wire(0, b'Y', &c.ours.encode(), T1);
2106        assert_eq!(c.poll_output(now), Some(ack));
2107        c.handle_timeout(now);
2108        assert_eq!(c.poll_output(now), None);
2109        assert_eq!(c.poll_event(), None);
2110    }
2111
2112    /// [`get_started`], then F(1) "F" with its ACK.
2113    fn get_file_open(config: Config) -> (Client, Instant) {
2114        let (mut c, now) = get_started(config);
2115        c.handle_input(now, &wire(1, b'F', b"F", T3));
2116        assert_eq!(c.poll_output(now), Some(wire(1, b'Y', b"", T3)));
2117        (c, now)
2118    }
2119
2120    fn all_events(c: &mut Client) -> Vec<Event> {
2121        std::iter::from_fn(|| c.poll_event()).collect()
2122    }
2123
2124    #[test]
2125    fn lost_final_ack_is_answered_while_lingering() {
2126        let config = cfg();
2127        let linger = config.linger;
2128        let (mut c, now) = get_file_open(config);
2129        c.handle_input(now, &wire(2, b'Z', b"", T3));
2130        assert_eq!(c.poll_output(now), Some(wire(2, b'Y', b"", T3)));
2131        c.handle_input(now, &wire(3, b'B', b"", T3));
2132        let ack = wire(3, b'Y', b"", T3);
2133        assert_eq!(c.poll_output(now), Some(ack.clone()));
2134        assert_eq!(
2135            all_events(&mut c),
2136            vec![
2137                Event::FileStart {
2138                    name: b"F".to_vec()
2139                },
2140                Event::FileEnd { discarded: false },
2141                Event::Done
2142            ]
2143        );
2144        assert!(!c.is_idle());
2145        assert_eq!(c.next_timeout(), Some(now + linger));
2146        // Our ACK was lost: the server sends B again and gets the same ACK,
2147        // without a second Done. Other packets are ignored.
2148        let t = now + linger / 2;
2149        c.handle_input(t, &wire(3, b'B', b"", T3));
2150        assert_eq!(c.poll_output(t), Some(ack.clone()));
2151        c.handle_input(t, &wire(2, b'Z', b"", T3));
2152        c.handle_input(t, b"\x01# N3\r");
2153        assert_eq!(c.poll_output(t), None);
2154        assert_eq!(c.poll_event(), None);
2155        // The re-ACK does not extend the linger.
2156        assert_eq!(c.next_timeout(), Some(now + linger));
2157        c.handle_timeout(now + linger);
2158        assert!(c.is_idle());
2159        assert_eq!(c.next_timeout(), None);
2160        c.handle_input(now + linger, &wire(3, b'B', b"", T3));
2161        assert_eq!(c.poll_output(now + linger), None);
2162        assert_eq!(c.poll_event(), None);
2163    }
2164
2165    #[test]
2166    fn repeated_bs_while_lingering_queue_one_ack() {
2167        let (mut c, now) = get_started(cfg());
2168        c.handle_input(now, &wire(1, b'B', b"", T3));
2169        let ack = wire(1, b'Y', b"", T3);
2170        assert_eq!(c.poll_output(now), Some(ack.clone()));
2171        let burst: Vec<u8> = (0..10).flat_map(|_| wire(1, b'B', b"", T3)).collect();
2172        c.handle_input(now, &burst);
2173        assert_eq!(c.poll_output(now), Some(ack.clone()));
2174        assert_eq!(c.poll_output(now), None);
2175        // Once it is out, the next repeat gets another.
2176        c.handle_input(now, &wire(1, b'B', b"", T3));
2177        assert_eq!(c.poll_output(now), Some(ack));
2178        assert_eq!(c.poll_output(now), None);
2179    }
2180
2181    #[test]
2182    fn start_and_cancel_end_the_linger() {
2183        let (mut c, now) = get_started(cfg());
2184        c.handle_input(now, &wire(1, b'B', b"", T3));
2185        assert_eq!(c.poll_output(now), Some(wire(1, b'Y', b"", T3)));
2186        assert_eq!(all_events(&mut c), vec![Event::Done]);
2187        c.cancel(now);
2188        assert!(c.is_idle());
2189        assert_eq!(c.poll_output(now), None);
2190        assert_eq!(c.poll_event(), None);
2191
2192        let (mut c, now) = get_started(cfg());
2193        c.handle_input(now, &wire(1, b'B', b"", T3));
2194        assert!(!c.is_idle());
2195        c.start(now, Command::Finish).unwrap();
2196        assert_eq!(c.poll_output(now), Some(wire(0, b'G', b"F", T1)));
2197        assert_eq!(c.poll_output(now), None);
2198        assert_eq!(c.poll_event(), None);
2199    }
2200
2201    #[test]
2202    fn zero_linger_goes_idle_at_once() {
2203        let config = Config {
2204            linger: Duration::ZERO,
2205            ..cfg()
2206        };
2207        let (mut c, now) = get_started(config);
2208        c.handle_input(now, &wire(1, b'B', b"", T3));
2209        assert!(c.is_idle());
2210        assert_eq!(c.poll_output(now), Some(wire(1, b'Y', b"", T3)));
2211        assert_eq!(c.next_timeout(), None);
2212    }
2213
2214    #[test]
2215    fn b_before_z_is_a_protocol_error() {
2216        let (mut c, now) = get_file_open(cfg());
2217        c.handle_input(now, &wire(2, b'D', b"abc", T3));
2218        assert_eq!(c.poll_output(now), Some(wire(2, b'Y', b"", T3)));
2219        c.handle_input(now, &wire(3, b'B', b"", T3));
2220        assert_eq!(c.poll_output(now), Some(wire(3, b'E', b"Unexpected B", T3)));
2221        let ev = all_events(&mut c);
2222        assert!(matches!(
2223            ev.as_slice(),
2224            [_, Event::Data(_), Event::Error(Error::Protocol(_))]
2225        ));
2226        assert!(c.is_idle());
2227    }
2228
2229    #[test]
2230    fn b_with_text_buffered_is_a_protocol_error() {
2231        let (mut c, now) = get_started(cfg());
2232        c.handle_input(now, &wire(1, b'X', b"", T3));
2233        assert_eq!(c.poll_output(now), Some(wire(1, b'Y', b"", T3)));
2234        c.handle_input(now, &wire(2, b'D', b"partial", T3));
2235        assert_eq!(c.poll_output(now), Some(wire(2, b'Y', b"", T3)));
2236        c.handle_input(now, &wire(3, b'B', b"", T3));
2237        assert_eq!(c.poll_output(now), Some(wire(3, b'E', b"Unexpected B", T3)));
2238        assert!(matches!(
2239            all_events(&mut c).as_slice(),
2240            [Event::Error(Error::Protocol(_))]
2241        ));
2242    }
2243
2244    #[test]
2245    fn ack_drops_a_queued_retransmission() {
2246        let pause = Duration::from_millis(100);
2247        let config = Config {
2248            packet_pause: pause,
2249            ..cfg()
2250        };
2251        let now = Instant::now();
2252        let mut c = Client::new(config);
2253        c.start(now, Command::Send(vec![file(b"A", b"x")])).unwrap();
2254        assert_eq!(c.poll_output(now), Some(wire(0, b'S', OURS, T1)));
2255        c.handle_input(now, &wire(0, b'Y', PEER_SMALL, T1));
2256        let t = now + pause;
2257        assert_eq!(c.poll_output(t), Some(wire(1, b'F', b"A", T3)));
2258        // A NAK and the ACK for F in one read: the resend the NAK queued
2259        // (held back by the pause) is dropped, D goes out next.
2260        let mut input = wire(1, b'N', b"", T3);
2261        input.extend(wire(1, b'Y', b"", T3));
2262        c.handle_input(t, &input);
2263        let t = t + pause;
2264        assert_eq!(c.poll_output(t), Some(wire(2, b'D', b"x", T3)));
2265        assert_eq!(c.poll_output(t), None);
2266        // Same with a NAK for n + 1 as the ACK.
2267        let mut input = wire(2, b'N', b"", T3);
2268        input.extend(wire(3, b'N', b"", T3));
2269        c.handle_input(t, &input);
2270        let t = t + pause;
2271        assert_eq!(c.poll_output(t), Some(wire(3, b'Z', b"", T3)));
2272        assert_eq!(c.poll_output(t), None);
2273    }
2274
2275    #[test]
2276    fn packet_drops_a_queued_nak() {
2277        let pause = Duration::from_millis(100);
2278        let config = Config {
2279            packet_pause: pause,
2280            ..cfg()
2281        };
2282        let now = Instant::now();
2283        let mut c = Client::new(config);
2284        c.start(now, Command::Get(b"F".to_vec())).unwrap();
2285        assert!(c.poll_output(now).is_some());
2286        c.handle_input(now, &wire(0, b'S', b"~* @-#Y3", T1));
2287        assert_eq!(c.poll_output(now + pause), Some(wire(0, b'Y', OURS, T1)));
2288        // A damaged F, then the good retransmission in the same read.
2289        let mut bad = wire(1, b'F', b"F", T3);
2290        bad[5] ^= 1;
2291        bad.extend(wire(1, b'F', b"F", T3));
2292        c.handle_input(now + pause, &bad);
2293        let t = now + pause * 2;
2294        assert_eq!(c.poll_output(t), Some(wire(1, b'Y', b"", T3)));
2295        assert_eq!(c.poll_output(t), None);
2296    }
2297
2298    #[test]
2299    fn bad_check_naks_count_as_retries() {
2300        let config = Config {
2301            retries: 2,
2302            ..cfg()
2303        };
2304        let (mut c, now) = get_file_open(config);
2305        let mut bad = wire(2, b'D', b"abc", T3);
2306        bad[5] ^= 1;
2307        for _ in 0..2 {
2308            c.handle_input(now, &bad);
2309            assert_eq!(c.poll_output(now), Some(wire(2, b'N', b"", T3)));
2310        }
2311        c.handle_input(now, &bad);
2312        assert_eq!(
2313            c.poll_output(now),
2314            Some(wire(2, b'E', b"Too many retries", T3))
2315        );
2316        assert_eq!(
2317            all_events(&mut c).last(),
2318            Some(&Event::Error(Error::Timeout))
2319        );
2320        // A good packet in between resets the count.
2321        let config = Config {
2322            retries: 1,
2323            ..cfg()
2324        };
2325        let (mut c, now) = get_file_open(config);
2326        c.handle_input(now, &bad);
2327        assert_eq!(c.poll_output(now), Some(wire(2, b'N', b"", T3)));
2328        c.handle_input(now, &wire(2, b'D', b"abc", T3));
2329        assert_eq!(c.poll_output(now), Some(wire(2, b'Y', b"", T3)));
2330        let mut bad = wire(3, b'D', b"def", T3);
2331        bad[5] ^= 1;
2332        c.handle_input(now, &bad);
2333        assert_eq!(c.poll_output(now), Some(wire(3, b'N', b"", T3)));
2334    }
2335
2336    #[test]
2337    fn receive_size_cap() {
2338        let config = Config {
2339            max_size: Some(5),
2340            ..cfg()
2341        };
2342        let (mut c, now) = get_file_open(config);
2343        c.handle_input(now, &wire(2, b'D', b"abc", T3));
2344        assert_eq!(c.poll_output(now), Some(wire(2, b'Y', b"", T3)));
2345        c.handle_input(now, &wire(3, b'D', b"de", T3));
2346        assert_eq!(c.poll_output(now), Some(wire(3, b'Y', b"", T3)));
2347        c.handle_input(now, &wire(4, b'D', b"f", T3));
2348        assert_eq!(c.poll_output(now), Some(wire(4, b'E', b"Too large", T3)));
2349        assert_eq!(
2350            all_events(&mut c).last(),
2351            Some(&Event::Error(Error::TooLarge { limit: 5 }))
2352        );
2353        assert!(c.is_idle());
2354        // Server text counts too.
2355        let config = Config {
2356            max_size: Some(2),
2357            ..cfg()
2358        };
2359        let (mut c, now) = get_started(config);
2360        c.handle_input(now, &wire(1, b'X', b"", T3));
2361        assert_eq!(c.poll_output(now), Some(wire(1, b'Y', b"", T3)));
2362        c.handle_input(now, &wire(2, b'D', b"abc", T3));
2363        assert_eq!(c.poll_output(now), Some(wire(2, b'E', b"Too large", T3)));
2364        assert_eq!(Config::default().max_size, Some(4 << 20));
2365    }
2366
2367    #[test]
2368    fn start_clears_the_previous_transaction() {
2369        let pause = Duration::from_millis(100);
2370        let config = Config {
2371            packet_pause: pause,
2372            ..cfg()
2373        };
2374        let now = Instant::now();
2375        let mut c = Client::new(config);
2376        c.start(now, Command::Info).unwrap();
2377        assert!(c.poll_output(now).is_some());
2378        c.handle_input(now, b"\x01+ Y~& @-# 3,\r");
2379        assert!(c.peer_params().is_some());
2380        assert!(c.is_idle());
2381        // Done not polled; a failed transaction leaves an E packet queued.
2382        c.start(now, Command::Host(b"X".to_vec())).unwrap();
2383        assert_eq!(c.peer_params(), None);
2384        assert_eq!(c.poll_event(), None);
2385        assert!(c.poll_output(now).is_some());
2386        c.handle_input(now, b"\x01+ S~* @-#Y3$\r");
2387        c.cancel(now);
2388        c.start(now, Command::Finish).unwrap();
2389        assert_eq!(c.poll_output(now + pause), Some(wire(0, b'G', b"F", T1)));
2390        assert_eq!(c.poll_output(now + pause), None);
2391        assert_eq!(c.poll_event(), None);
2392    }
2393
2394    #[test]
2395    fn busy_and_cancel() {
2396        let now = Instant::now();
2397        let mut c = Client::new(cfg());
2398        c.start(now, Command::Directory).unwrap();
2399        assert_eq!(c.start(now, Command::Finish), Err(StartError::Busy));
2400        assert!(c.poll_output(now).is_some());
2401        c.cancel(now);
2402        assert_eq!(c.poll_output(now), Some(wire(0, b'E', b"Cancelled", T1)));
2403        assert_eq!(c.poll_event(), Some(Event::Error(Error::Cancelled)));
2404        assert!(c.is_idle());
2405        c.cancel(now);
2406        assert_eq!(c.poll_output(now), None);
2407        assert_eq!(c.poll_event(), None);
2408        assert!(c.start(now, Command::Finish).is_ok());
2409    }
2410}