Skip to main content

satx_core/
xmodem.rs

1//! Drives an [`xmodem_proto::Transfer`] over a byte link: XModem transfers
2//! with the calculator's `XRECV` and `XSEND`.
3//!
4//! The calculator side cannot be started from the host: inside the Kermit
5//! server both commands fail with "Port Not Available" (49G and 48GX,
6//! verified on the emulators; traces `49g-server-xrecv`, `48gx-server-xsend`
7//! in `xmodem-proto`). The flow is therefore:
8//!
9//! 1. [`Calculator::prepare_for_xmodem`](crate::Calculator::prepare_for_xmodem)
10//!    checks the name, sets RPN mode on a 49G, puts the program
11//!    `« 'NAME' XRECV »` (or `XSEND`) on the stack, ends the server (Kermit
12//!    FINISH) and returns an [`XmodemPlan`] with the keys that run it
13//!    (EVAL; right-shift SYMB on the 49G).
14//! 2. [`Calculator::into_transport`](crate::Calculator::into_transport) hands
15//!    over the open link; [`XmodemSession::new`] wraps it.
16//! 3. [`XmodemSession::send`] or [`XmodemSession::receive`] waits up to
17//!    [`XmodemOptions::start_timeout`] for the user to run the program,
18//!    then runs the transfer.
19//! 4. The calculator is out of server mode, its stack as before (EVAL
20//!    took the program, the command its name; a user who does not go on
21//!    drops the program with the backspace key): the user starts `SERVER`
22//!    again ([`server_again`]), and [`XmodemSession::into_transport`]
23//!    gives the link back for a new [`Session`](crate::Session).
24//!
25//! The loop has the same discipline as [`Session`](crate::Session): each
26//! block or control byte goes out in one write, reads wait at most until the
27//! machine's next deadline, `handle_timeout` runs after every read, and a
28//! watchdog cancels a transfer that stops making progress (a line full of
29//! noise never lets the machine's own timeouts fire). It is written once, as
30//! async code on the crate's link: [`XmodemSession`] runs it over a
31//! [`Transport`] with the system clock, a
32//! [`Machine`](crate::machine::Machine) from outside
33//! ([`Op::XmodemSend`](crate::machine::Op::XmodemSend),
34//! [`Op::XmodemReceive`](crate::machine::Op::XmodemReceive)).
35//!
36//! wiki: protocols/xmodem, protocols/xmodem-hp.
37
38use xmodem_proto::{BlockSize, Check, Command, Config, Event, Transfer};
39
40use crate::calc::Model;
41#[cfg(not(target_arch = "wasm32"))]
42use crate::link;
43use crate::link::{Link, Progress};
44use crate::object::{HEADER_LEN, inspect, strip_padding};
45use crate::time::Duration;
46#[cfg(not(target_arch = "wasm32"))]
47use crate::time::Instant;
48#[cfg(not(target_arch = "wasm32"))]
49use crate::transport::Transport;
50use crate::watchdog::Watchdog;
51use crate::{Error, Result};
52
53/// Read wait while the machine has no deadline.
54const IDLE_WAIT: Duration = Duration::from_millis(100);
55/// Shortest read wait.
56const MIN_WAIT: Duration = Duration::from_millis(10);
57/// Longest accepted [`XmodemOptions::start_timeout`].
58pub const MAX_START_TIMEOUT: Duration = Duration::from_secs(600);
59/// Shortest accepted [`XmodemOptions::start_timeout`].
60pub const MIN_START_TIMEOUT: Duration = Duration::from_secs(1);
61
62/// Tunables for an [`XmodemSession`].
63#[derive(Clone, Debug)]
64pub struct XmodemOptions {
65    /// The XModem machine's configuration: block size (sender), check asked
66    /// for first (receiver), timeouts, retries, pad byte. Its
67    /// `recv_start_timeout` is replaced by [`XmodemOptions::start_timeout`].
68    pub xmodem: Config,
69    /// How long to wait for the user to start `XRECV`/`XSEND` on the
70    /// calculator (default 60 s), clamped to
71    /// [`MIN_START_TIMEOUT`]..=[`MAX_START_TIMEOUT`]. Sender: wait for the
72    /// first start character. Receiver: keep sending start characters this
73    /// long.
74    pub start_timeout: Duration,
75    /// How long to discard input before the transfer (default 0: the machine
76    /// skips Kermit packets and noise before the first start character or
77    /// block, and draining could swallow a start character the calculator
78    /// already sent).
79    pub drain: Duration,
80}
81
82impl Default for XmodemOptions {
83    /// Model-independent defaults: ask for HP's CRC (`D`) three times, then
84    /// checksum; send 1k blocks when the receiver asks for a CRC, 128-byte
85    /// blocks when it asks for checksum.
86    fn default() -> Self {
87        let mut xmodem = Config::default();
88        xmodem.block_size = BlockSize::B1k;
89        // The receiver's linger after the EOT ACK delays the end of every
90        // receive by its length. There is no turnaround to hide it in (the
91        // user restarts SERVER by hand), so keep it as short as the Kermit
92        // session's (`Options::default`): it still answers an EOT repeated
93        // at once after a damaged ACK.
94        xmodem.linger = Duration::from_millis(200);
95        XmodemOptions {
96            xmodem,
97            start_timeout: Duration::from_secs(60),
98            drain: Duration::ZERO,
99        }
100    }
101}
102
103impl XmodemOptions {
104    /// Defaults for `model`. Errors for the 48S/SX, which has no XModem.
105    ///
106    /// - 49G: ask with `D` (HP's CRC) for the whole start window, so a user
107    ///   who takes longer than a few seconds to type `XSEND` still gets CRC
108    ///   mode; 1k blocks with the 128-byte short tail (verified on the
109    ///   emulated 49G).
110    /// - 48G/GX: checksum only, 128-byte blocks; it ignores `C` and `D` and
111    ///   rejects 1k blocks (verified on the emulated 48GX). A 3 s reply
112    ///   timeout, which also paces the receiver's start NAKs.
113    /// - 39G/40G: checksum, 128-byte blocks padded with NUL (aplets by
114    ///   "HP39/40 (Wire)", verified on the emulated 39G).
115    /// - 38G: an error, it has no XModem.
116    /// - Unknown: [`XmodemOptions::default`].
117    pub fn for_model(model: Model) -> Result<Self> {
118        let base = XmodemOptions::default();
119        match model {
120            Model::Hp48Sx => Err(Error::Unsupported(
121                "the HP 48S/SX has no XModem; use Kermit".into(),
122            )),
123            Model::Hp38G => Err(Error::Unsupported(
124                "the HP 38G has no XModem; it sends and receives aplets as a Kermit client".into(),
125            )),
126            Model::Hp49G => {
127                let mut xmodem = base.xmodem.clone();
128                xmodem.check = Check::HpCrc;
129                // Bounded by the start window, not by the count.
130                xmodem.crc_attempts = u32::MAX;
131                xmodem.block_size = BlockSize::B1k;
132                Ok(XmodemOptions { xmodem, ..base })
133            }
134            // The 39G/40G's "HP39/40 (Wire)": its receiver opens with NAK
135            // and takes 128-byte checksum blocks padded with NUL, as its own
136            // sender pads them (wiki: protocols/aplet-transfer).
137            Model::Hp39G => {
138                let mut xmodem = base.xmodem.clone();
139                xmodem.check = Check::Checksum;
140                xmodem.block_size = BlockSize::B128;
141                xmodem.pad = 0;
142                Ok(XmodemOptions { xmodem, ..base })
143            }
144            Model::Hp48Gx => {
145                let mut xmodem = base.xmodem.clone();
146                xmodem.check = Check::Checksum;
147                xmodem.block_size = BlockSize::B128;
148                // Also the pace of the start NAKs: with 10 s the user waits
149                // up to 10 s after typing XSEND. Conn4x uses 2 s for data
150                // (wiki: protocols/xmodem-hp).
151                xmodem.timeout = Duration::from_secs(3);
152                Ok(XmodemOptions { xmodem, ..base })
153            }
154            Model::Unknown => Ok(base),
155        }
156    }
157
158    /// The machine configuration actually used: the start window applied to
159    /// both roles.
160    fn config(&self) -> Config {
161        let start = self
162            .start_timeout
163            .clamp(MIN_START_TIMEOUT, MAX_START_TIMEOUT);
164        let mut config = self.xmodem.clone();
165        config.start_timeout = start;
166        config.recv_start_timeout = Some(start);
167        config
168    }
169}
170
171/// Outcome of [`XmodemSession::send`].
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct XmodemReport {
174    /// The block check the receiver asked for.
175    pub check: Check,
176    /// Bytes of the file sent and acknowledged.
177    pub bytes: u64,
178}
179
180/// Outcome of [`XmodemSession::receive`].
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct XmodemReceived {
183    /// The file: padding of the last block cut when the object walk
184    /// succeeded, otherwise every byte received.
185    pub data: Vec<u8>,
186    /// The block check the transfer ran with.
187    pub check: Check,
188    /// Bytes received, padding included.
189    pub received: usize,
190    /// Size of the last block (128 or 1024; 0 for an empty transfer), the
191    /// padding allowance passed to [`strip_padding`] is this minus one, the
192    /// most padding a sender can add.
193    pub last_block: usize,
194    /// Padding bytes cut. `None` when the object-length walk failed (not an
195    /// HP binary object, unknown prolog, or more excess than one block):
196    /// `data` is then exactly what was received, padding and all.
197    pub stripped: Option<usize>,
198}
199
200/// An XModem link to a calculator that runs (or is about to run) `XRECV` or
201/// `XSEND`. See the module documentation for the flow.
202#[cfg(not(target_arch = "wasm32"))]
203pub struct XmodemSession {
204    transport: Box<dyn Transport>,
205    options: XmodemOptions,
206    link: Link,
207}
208
209// The transport is a trait object without `Debug`.
210#[cfg(not(target_arch = "wasm32"))]
211impl std::fmt::Debug for XmodemSession {
212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213        f.debug_struct("XmodemSession")
214            .field("options", &self.options)
215            .finish_non_exhaustive()
216    }
217}
218
219/// What [`XmodemSession::run`] collected.
220struct Outcome {
221    check: Option<Check>,
222    bytes: u64,
223    file: Option<(Vec<u8>, usize)>,
224}
225
226#[cfg(not(target_arch = "wasm32"))]
227impl XmodemSession {
228    /// Wrap an open `transport` (e.g. from
229    /// [`Calculator::into_transport`](crate::Calculator::into_transport)).
230    pub fn new(transport: Box<dyn Transport>, options: XmodemOptions) -> Self {
231        XmodemSession {
232            transport,
233            options,
234            link: Link::new(Instant::now()),
235        }
236    }
237
238    /// The options in use.
239    pub fn options(&self) -> &XmodemOptions {
240        &self.options
241    }
242
243    /// Give the link back, e.g. for a new [`Session`](crate::Session) once
244    /// the user has typed `SERVER` again.
245    pub fn into_transport(self) -> Box<dyn Transport> {
246        self.transport
247    }
248
249    /// Send `data` to a calculator running `XRECV`.
250    pub fn send(&mut self, data: &[u8]) -> Result<XmodemReport> {
251        self.send_with(data, &mut |_| {})
252    }
253
254    /// [`XmodemSession::send`], passing every event to `progress`.
255    pub fn send_with(
256        &mut self,
257        data: &[u8],
258        progress: &mut dyn FnMut(&Event),
259    ) -> Result<XmodemReport> {
260        link::drive(
261            self.transport.as_mut(),
262            &self.link,
263            send(&self.link, &self.options, data),
264            &mut |p| {
265                if let Progress::Xmodem(event) = p {
266                    progress(event);
267                }
268            },
269        )
270    }
271
272    /// Receive a file from a calculator running `XSEND` and cut the padding
273    /// of its last block with the object-length walk (see
274    /// [`XmodemReceived::stripped`]).
275    pub fn receive(&mut self) -> Result<XmodemReceived> {
276        self.receive_with(&mut |_| {})
277    }
278
279    /// [`XmodemSession::receive`], passing every event to `progress`.
280    pub fn receive_with(&mut self, progress: &mut dyn FnMut(&Event)) -> Result<XmodemReceived> {
281        link::drive(
282            self.transport.as_mut(),
283            &self.link,
284            receive(&self.link, &self.options),
285            &mut |p| {
286                if let Progress::Xmodem(event) = p {
287                    progress(event);
288                }
289            },
290        )
291    }
292}
293
294/// Send `data` to a calculator running `XRECV`.
295pub(crate) async fn send(
296    link: &Link,
297    options: &XmodemOptions,
298    data: &[u8],
299) -> Result<XmodemReport> {
300    let outcome = run(link, options, Command::Send(data.to_vec())).await?;
301    Ok(XmodemReport {
302        check: outcome.check.unwrap_or(options.xmodem.check),
303        bytes: outcome.bytes,
304    })
305}
306
307/// Receive a file from a calculator running `XSEND` and cut the padding.
308pub(crate) async fn receive(link: &Link, options: &XmodemOptions) -> Result<XmodemReceived> {
309    let outcome = run(link, options, Command::Receive).await?;
310    let (raw, last_block) = outcome
311        .file
312        .ok_or_else(|| Error::Reply("XModem transfer ended without a file".into()))?;
313    // The object's length per the walk; the cut succeeded iff the result
314    // has exactly that length.
315    let object_len = inspect(&raw)
316        .ok()
317        .and_then(|i| i.size_nibbles)
318        .map(|n| HEADER_LEN + n.div_ceil(2));
319    // Padding never fills a whole block (a sender does not send a block
320    // of pure padding), so a cut may remove at most last_block - 1
321    // bytes; a walk that comes out a full block short leaves the data
322    // untouched instead of losing real bytes.
323    let data = strip_padding(&raw, last_block.saturating_sub(1)).to_vec();
324    let stripped = match object_len {
325        Some(len) if data.len() == len => Some(raw.len() - len),
326        _ => None,
327    };
328    Ok(XmodemReceived {
329        check: outcome.check.unwrap_or(options.xmodem.check),
330        received: raw.len(),
331        last_block,
332        stripped,
333        data,
334    })
335}
336
337async fn run(link: &Link, options: &XmodemOptions, command: Command) -> Result<Outcome> {
338    link.drain(options.drain).await?;
339    let config = options.config();
340    // Watchdog: the start window (plus one reply timeout for the last
341    // start character), then the time the machine needs to give up on
342    // one block. Reset on every sign of progress.
343    let start_limit = config.start_timeout.saturating_add(config.timeout);
344    let stall_limit = config
345        .timeout
346        .saturating_mul(config.retries.saturating_add(2))
347        .saturating_add(config.purge)
348        .saturating_add(config.byte_timeout);
349    let mut xfer = Transfer::new(config);
350    let begin = link.now();
351    xfer.start(begin, command)
352        .map_err(|e| Error::Reply(format!("XModem: {e}")))?;
353    let mut watchdog = Watchdog::new(begin, start_limit, stall_limit);
354    let mut stalled = false;
355
356    let mut out = Outcome {
357        check: None,
358        bytes: 0,
359        file: None,
360    };
361    let mut result: Option<Result<()>> = None;
362    'run: loop {
363        let now = link.now();
364        while let Some(bytes) = xfer.poll_output(now) {
365            match link.write(bytes) {
366                Ok(()) => {}
367                // A re-ACK during the linger: the file is complete, a
368                // failing link does not undo it.
369                Err(_) if matches!(result, Some(Ok(()))) => break 'run,
370                Err(e) => return Err(e.into()),
371            }
372        }
373        // Written before the events count: a failed write of the final ACK
374        // fails the transfer, a re-ACK's only ends the linger.
375        match link.flush().await {
376            Ok(()) => {}
377            Err(_) if matches!(result, Some(Ok(()))) => break 'run,
378            Err(e) => return Err(e.into()),
379        }
380        while let Some(event) = xfer.poll_event() {
381            link.emit(Progress::Xmodem(event.clone()));
382            match event {
383                Event::Started { check } => {
384                    out.check = Some(check);
385                    watchdog.progress(now);
386                }
387                Event::Progress { bytes, .. } => {
388                    out.bytes = bytes;
389                    watchdog.progress(now);
390                }
391                Event::FileEnd {
392                    data, last_block, ..
393                } => out.file = Some((data, last_block)),
394                Event::Done => result = Some(Ok(())),
395                Event::Error(xmodem_proto::Error::Cancelled) if stalled => {
396                    result = Some(Err(Error::Xmodem(xmodem_proto::Error::Timeout)));
397                }
398                Event::Error(e) => result = Some(Err(Error::Xmodem(e))),
399                _ => {}
400            }
401        }
402        if result.is_some() && xfer.next_timeout().is_none() {
403            // Done or failed, and the final ACK or CANs are written.
404            if xfer.poll_output(now).is_none() {
405                break;
406            }
407            continue;
408        }
409        if result.is_none() && watchdog.expired(now) {
410            stalled = true;
411            xfer.cancel(now);
412            continue;
413        }
414        let until = match (xfer.next_timeout(), watchdog.deadline()) {
415            (Some(a), Some(b)) => Some(a.min(b)),
416            (a, b) => a.or(b),
417        };
418        let deadline = until.unwrap_or(now + IDLE_WAIT).max(now + MIN_WAIT);
419        let input = match link.read(Some(deadline)).await {
420            Ok(input) => input,
421            // Lingering after Done: the file is complete, a failing
422            // link only ends the linger.
423            Err(_) if matches!(result, Some(Ok(()))) => break,
424            Err(e) => return Err(e.into()),
425        };
426        let now = link.now();
427        if !input.is_empty() {
428            xfer.handle_input(now, &input);
429        }
430        // Also after input: the machine checks deadlines only here.
431        xfer.handle_timeout(now);
432    }
433    match result {
434        Some(Err(e)) => Err(e),
435        _ => Ok(out),
436    }
437}
438
439/// Which way an XModem transfer goes.
440#[derive(Clone, Copy, Debug, PartialEq, Eq)]
441pub enum XmodemDirection {
442    /// Computer to calculator: the calculator runs `XRECV`.
443    ToCalculator,
444    /// Calculator to computer: the calculator runs `XSEND`.
445    FromCalculator,
446}
447
448impl XmodemDirection {
449    /// The calculator command for this direction.
450    pub fn calculator_command(self) -> &'static str {
451        match self {
452            XmodemDirection::ToCalculator => "XRECV",
453            XmodemDirection::FromCalculator => "XSEND",
454        }
455    }
456}
457
458/// The program a fast transfer leaves on the calculator's stack for the
459/// user to run: `\<< 'NAME' XSEND \>>` (or `XRECV`), in the calculator's
460/// ASCII spelling, as a host command sends it. A host command holding only
461/// a program puts the program on the stack without running it, and FINISH
462/// leaves the stack alone (real 49G, ROM 1.18, 2026-11-08; emulated 48GX
463/// and 49G). `name` must be a valid name
464/// ([`validate_name`](crate::calc::validate_name)): a plain name needs no
465/// escaping inside the quotes.
466pub fn stacked_program(direction: XmodemDirection, name: &str) -> String {
467    format!("\\<< '{name}' {} \\>>", direction.calculator_command())
468}
469
470/// [`stacked_program`] as the calculator shows it: `« 'NAME' XSEND »`.
471pub fn program_text(direction: XmodemDirection, name: &str) -> String {
472    format!("\u{ab} '{name}' {} \u{bb}", direction.calculator_command())
473}
474
475/// The keys that run the program on level 1 (EVAL), as the keyboard
476/// labels them: `EVAL` on the 48G/GX, right-shift then `SYMB` on the 49G,
477/// which has no EVAL key of its own (EVAL is right-shift SYMB there).
478pub fn eval_keys(model: Model) -> &'static [&'static str] {
479    match model {
480        Model::Hp49G => &["right-shift", "SYMB"],
481        _ => &["EVAL"],
482    }
483}
484
485/// [`eval_keys`] as words: `EVAL`, or `right-shift, then SYMB (EVAL)`.
486pub fn eval_keys_text(model: Model) -> String {
487    match eval_keys(model) {
488        [one] => (*one).to_string(),
489        keys => format!("{} (EVAL)", keys.join(", then ")),
490    }
491}
492
493/// How the user starts the Kermit server again after a fast transfer, as
494/// the verb part of a sentence (`type SERVER and press ENTER`). The 49G's shortcut
495/// (right-shift →) starts the XModem server instead when the keys are
496/// pressed with a pause between them (wiki: protocols/xserv), so only
497/// `SERVER` is named there; the 48G/GX's right-shift → starts the Kermit
498/// server however slowly it is pressed (emulated 48GX, ROM R, 2026-11-08).
499pub fn server_again(model: Model) -> &'static str {
500    match model {
501        Model::Hp48Gx => "press right-shift, then \u{2192} (or type SERVER and press ENTER)",
502        _ => "type SERVER and press ENTER",
503    }
504}
505
506/// What [`Calculator::prepare_for_xmodem`](crate::Calculator::prepare_for_xmodem)
507/// did and what the user must do next.
508#[derive(Clone, Debug, PartialEq, Eq)]
509pub struct XmodemPlan {
510    /// The detected model.
511    pub model: Model,
512    /// Which way the transfer goes.
513    pub direction: XmodemDirection,
514    /// The variable name.
515    pub name: String,
516    /// The program left on level 1 of the stack, as the calculator shows
517    /// it ([`program_text`]: `« 'NAME' XSEND »`).
518    pub program: String,
519    /// The keys that run it, as the keyboard labels them ([`eval_keys`]).
520    pub keys: Vec<String>,
521    /// The calculator was in algebraic mode (49G flag -95 set) and was
522    /// switched to RPN so that EVAL runs the program; `-95 SF` switches
523    /// back.
524    pub switched_to_rpn: bool,
525    /// The variable already exists (relevant for `XRECV`, see
526    /// [`XmodemPlan::notes`]).
527    pub exists: bool,
528    /// Further instructions for the user, one sentence each: the `.1`
529    /// suffix for an existing name, the RPN switch, dropping the program
530    /// instead, `SERVER` afterwards.
531    pub notes: Vec<String>,
532}
533
534impl XmodemPlan {
535    /// The keys as words ([`eval_keys_text`]).
536    pub fn keys_text(&self) -> String {
537        eval_keys_text(self.model)
538    }
539
540    /// The full instruction text: the keys first, then the notes.
541    pub fn instructions(&self) -> String {
542        let mut text = format!(
543            "{} is on the calculator's stack. On the calculator, press {} to run it.",
544            self.program,
545            self.keys_text()
546        );
547        for note in &self.notes {
548            text.push(' ');
549            text.push_str(note);
550        }
551        text
552    }
553}
554
555#[cfg(test)]
556#[allow(clippy::unwrap_used, clippy::expect_used)]
557mod tests {
558    use super::*;
559    use crate::object;
560    use crate::transport::MemoryTransport;
561    use std::collections::VecDeque;
562    use std::io;
563    use std::sync::{Arc, Mutex};
564    use xmodem_proto::codec::{ACK, CAN, EOT, NAK, SOH, STX, decode_block, encode_block};
565
566    const G49_XSEND_HPCRC: &str = include_str!("../../xmodem-proto/traces/49g-xsend-hpcrc.trace");
567    const G49_XSEND: &str = include_str!("../../xmodem-proto/traces/49g-xsend.trace");
568    const GX_XSEND: &str = include_str!("../../xmodem-proto/traces/48gx-xsend.trace");
569    const G49_XRECV: &str = include_str!("../../xmodem-proto/traces/49g-xrecv.trace");
570    const GX_XRECV: &str = include_str!("../../xmodem-proto/traces/48gx-xrecv.trace");
571
572    const H49: &[u8; 8] = b"HPHP49-C";
573    const H48: &[u8; 8] = b"HPHP48-R";
574
575    /// A String object file: `header`, prolog #02A2C, 5-nibble length,
576    /// characters (as the traces were recorded).
577    fn hp_string(header: &[u8; 8], chars: &[u8]) -> Vec<u8> {
578        let len = 5 + 2 * chars.len();
579        let mut nibbles = vec![0xC, 0x2, 0xA, 0x2, 0x0];
580        nibbles.extend((0..5).map(|i| ((len >> (4 * i)) & 0xF) as u8));
581        let mut out = header.to_vec();
582        out.extend(object::pack(&nibbles));
583        out.extend_from_slice(chars);
584        out
585    }
586
587    /// 269 bytes: every byte value once.
588    fn all_bytes(header: &[u8; 8]) -> Vec<u8> {
589        hp_string(header, &(0..=255).collect::<Vec<u8>>())
590    }
591
592    /// Fast timeouts for in-memory peers.
593    fn fast(mut options: XmodemOptions) -> XmodemOptions {
594        options.xmodem.crc_interval = Duration::from_millis(30);
595        options.xmodem.timeout = Duration::from_millis(60);
596        options.xmodem.byte_timeout = Duration::from_millis(30);
597        options.xmodem.purge = Duration::from_millis(20);
598        options.start_timeout = MIN_START_TIMEOUT;
599        options.drain = Duration::ZERO;
600        options
601    }
602
603    /// The part of a trace the XModem machine handles.
604    fn xmodem_part(trace: &str) -> &str {
605        let at = trace.find("# xmodem start").unwrap();
606        &trace[at..]
607    }
608
609    // ---- recorded payloads ----
610
611    #[test]
612    fn receive_49g_payload_strips_garbage_padding() {
613        // The 49G's XSEND pads the last block with whatever follows the
614        // object in memory; only the object walk finds the end.
615        let transport = MemoryTransport::from_trace(xmodem_part(G49_XSEND_HPCRC)).unwrap();
616        let options = fast(XmodemOptions::for_model(Model::Hp49G).unwrap());
617        let mut s = XmodemSession::new(Box::new(transport), options);
618        let got = s.receive().unwrap();
619        assert_eq!(got.data, all_bytes(H49));
620        assert_eq!(got.check, Check::HpCrc);
621        assert_eq!((got.received, got.last_block), (384, 128));
622        assert_eq!(got.stripped, Some(384 - 269));
623    }
624
625    #[test]
626    fn allowance_is_one_less_than_a_block() {
627        // A walk that ends exactly one block early must not cut a whole
628        // block of real data; one byte less is the most padding possible.
629        let object = all_bytes(H49);
630        let mut raw = object.clone();
631        raw.extend(std::iter::repeat_n(0u8, 128));
632        assert_eq!(strip_padding(&raw, 127).len(), raw.len());
633        raw.pop();
634        assert_eq!(strip_padding(&raw, 127), &object[..]);
635    }
636
637    #[test]
638    fn receive_49g_checksum_payload() {
639        // Recorded asking with `C` three times; the 49G answered the NAK.
640        let transport = MemoryTransport::from_trace(xmodem_part(G49_XSEND)).unwrap();
641        let mut options = fast(XmodemOptions::default());
642        options.xmodem.check = Check::Crc16;
643        let mut s = XmodemSession::new(Box::new(transport), options);
644        let got = s.receive().unwrap();
645        assert_eq!(got.check, Check::Checksum);
646        assert_eq!(got.data, all_bytes(H49));
647    }
648
649    #[test]
650    fn receive_48gx_payload_strips_zero_padding() {
651        let transport = MemoryTransport::from_trace(xmodem_part(GX_XSEND)).unwrap();
652        let mut options = fast(XmodemOptions::for_model(Model::Hp48Gx).unwrap());
653        // As recorded: three `C`s, then NAK.
654        options.xmodem.check = Check::Crc16;
655        options.xmodem.crc_attempts = 3;
656        let mut s = XmodemSession::new(Box::new(transport), options);
657        let got = s.receive().unwrap();
658        assert_eq!(got.check, Check::Checksum);
659        assert_eq!(got.data, all_bytes(H48));
660        assert_eq!(got.stripped, Some(115));
661    }
662
663    #[test]
664    fn send_replays_recorded_xrecv() {
665        for (trace, header, model) in [
666            (G49_XRECV, H49, Model::Hp49G),
667            (GX_XRECV, H48, Model::Hp48Gx),
668        ] {
669            let transport = MemoryTransport::from_trace(xmodem_part(trace)).unwrap();
670            let mut options = fast(XmodemOptions::for_model(model).unwrap());
671            // Recorded with the crate defaults: SUB padding.
672            options.xmodem.pad = xmodem_proto::codec::SUB;
673            let mut s = XmodemSession::new(Box::new(transport), options);
674            let report = s.send(&all_bytes(header)).unwrap();
675            assert_eq!(report.bytes, 269);
676        }
677    }
678
679    #[test]
680    fn walk_failure_keeps_every_byte() {
681        // Not an HP object: nothing is cut, and the report says so.
682        let peer = FakeCalc::sender(b"plain text, no header".to_vec(), Behaviour::hp49());
683        let mut s = XmodemSession::new(
684            Box::new(peer.clone()),
685            fast(XmodemOptions::for_model(Model::Hp49G).unwrap()),
686        );
687        let got = s.receive().unwrap();
688        assert_eq!(got.stripped, None);
689        assert_eq!(got.data.len(), 128);
690        assert!(got.data.starts_with(b"plain text"));
691    }
692
693    #[test]
694    fn exact_object_reports_zero_stripped() {
695        let peer = FakeCalc::sender(
696            hp_string(H49, &[b'x'; 128 - HEADER_LEN - 5]),
697            Behaviour::hp49(),
698        );
699        let mut s = XmodemSession::new(
700            Box::new(peer),
701            fast(XmodemOptions::for_model(Model::Hp49G).unwrap()),
702        );
703        let got = s.receive().unwrap();
704        assert_eq!(got.received, 128);
705        assert_eq!(got.stripped, Some(0));
706    }
707
708    // ---- scripted calculators ----
709
710    /// How a fake calculator behaves.
711    #[derive(Clone, Debug)]
712    struct Behaviour {
713        /// The start character it sends as receiver (`D` or NAK).
714        start: u8,
715        /// The start characters it answers as sender.
716        answers: Vec<u8>,
717        /// Accepts STX blocks (49G) or NAKs them and cancels after nine (48GX).
718        accepts_1k: bool,
719        /// Padding byte as sender; `None` = memory garbage.
720        pad: Option<u8>,
721        /// Swallow the first transmission of this block number.
722        drop_block: Option<u8>,
723        /// Corrupt the first transmission of this block number.
724        corrupt_block: Option<u8>,
725    }
726
727    impl Behaviour {
728        fn hp49() -> Self {
729            Behaviour {
730                start: b'D',
731                answers: vec![b'D', NAK],
732                accepts_1k: true,
733                pad: None,
734                drop_block: None,
735                corrupt_block: None,
736            }
737        }
738
739        fn hp48gx() -> Self {
740            Behaviour {
741                start: NAK,
742                answers: vec![NAK],
743                accepts_1k: false,
744                pad: Some(0),
745                drop_block: None,
746                corrupt_block: None,
747            }
748        }
749    }
750
751    #[derive(Default, Debug)]
752    struct State {
753        /// Bytes waiting to be read by the host.
754        readable: VecDeque<u8>,
755        /// Receiver: data so far; sender: unused.
756        received: Vec<u8>,
757        /// Receiver: next expected block; sender: current block.
758        blk: u8,
759        /// STX blocks NAKed so far (48GX).
760        rejected: u32,
761        /// Receiver: EOT seen. Sender: final ACK seen.
762        done: bool,
763        /// Sender: started.
764        started: bool,
765        /// Sender: offset of the current block.
766        pos: usize,
767        /// Sender: EOT sent.
768        eot: bool,
769        /// Blocks swallowed or corrupted already.
770        mangled: Vec<u8>,
771        /// Every byte the host wrote.
772        written: Vec<Vec<u8>>,
773        /// Receiver: check in use.
774        check: Option<Check>,
775        cans: Vec<u8>,
776    }
777
778    /// A calculator running XRECV (`file == None`) or XSEND.
779    #[derive(Clone)]
780    struct FakeCalc {
781        file: Option<Vec<u8>>,
782        behaviour: Behaviour,
783        state: Arc<Mutex<State>>,
784    }
785
786    impl FakeCalc {
787        fn receiver(behaviour: Behaviour) -> Self {
788            let state = State {
789                readable: VecDeque::from([behaviour.start]),
790                blk: 1,
791                check: Check::from_start_char(behaviour.start),
792                ..State::default()
793            };
794            FakeCalc {
795                file: None,
796                behaviour,
797                state: Arc::new(Mutex::new(state)),
798            }
799        }
800
801        fn sender(file: Vec<u8>, behaviour: Behaviour) -> Self {
802            let state = State {
803                blk: 1,
804                ..State::default()
805            };
806            FakeCalc {
807                file: Some(file),
808                behaviour,
809                state: Arc::new(Mutex::new(state)),
810            }
811        }
812
813        fn state(&self) -> std::sync::MutexGuard<'_, State> {
814            self.state.lock().unwrap()
815        }
816
817        /// Sender: the current block (or EOT) as the calculator sends it.
818        fn current(&self, st: &mut State) -> Vec<u8> {
819            let file = self.file.as_deref().unwrap_or_default();
820            if st.pos >= file.len() {
821                st.eot = true;
822                return vec![EOT];
823            }
824            let check = st.check.unwrap_or(Check::Checksum);
825            let end = (st.pos + 128).min(file.len());
826            let mut data = file[st.pos..end].to_vec();
827            let fill = |i: usize| match self.behaviour.pad {
828                Some(p) => p,
829                None => (i * 37 + 11) as u8,
830            };
831            while data.len() < 128 {
832                data.push(fill(data.len()));
833            }
834            let mut block = encode_block(st.blk, BlockSize::B128, &data, 0, check).unwrap();
835            if self.behaviour.corrupt_block == Some(st.blk) && !st.mangled.contains(&st.blk) {
836                st.mangled.push(st.blk);
837                block[10] ^= 0xFF;
838            }
839            if self.behaviour.drop_block == Some(st.blk) && !st.mangled.contains(&st.blk) {
840                st.mangled.push(st.blk);
841                return Vec::new();
842            }
843            block
844        }
845
846        fn on_write(&self, bytes: &[u8]) {
847            let mut st = self.state();
848            st.written.push(bytes.to_vec());
849            if self.file.is_some() {
850                self.on_write_as_sender(&mut st, bytes);
851            } else {
852                self.on_write_as_receiver(&mut st, bytes);
853            }
854        }
855
856        fn on_write_as_sender(&self, st: &mut State, bytes: &[u8]) {
857            if bytes.contains(&CAN) {
858                st.cans.extend(bytes.iter().filter(|&&b| b == CAN));
859                st.done = true;
860                return;
861            }
862            for &b in bytes {
863                if !st.started {
864                    if self.behaviour.answers.contains(&b) {
865                        st.started = true;
866                        st.check = Check::from_start_char(b);
867                        let block = self.current(st);
868                        st.readable.extend(block);
869                    }
870                    continue;
871                }
872                match b {
873                    ACK if st.eot => st.done = true,
874                    ACK => {
875                        st.pos += 128;
876                        st.blk = st.blk.wrapping_add(1);
877                        let block = self.current(st);
878                        st.readable.extend(block);
879                    }
880                    NAK => {
881                        let block = self.current(st);
882                        st.readable.extend(block);
883                    }
884                    _ => {}
885                }
886            }
887        }
888
889        fn on_write_as_receiver(&self, st: &mut State, bytes: &[u8]) {
890            let check = st.check.unwrap_or(Check::Checksum);
891            match bytes.first() {
892                Some(&EOT) => {
893                    st.done = true;
894                    st.readable.push_back(ACK);
895                }
896                Some(&CAN) => {
897                    st.cans.extend_from_slice(bytes);
898                    st.done = true;
899                }
900                Some(&STX) if !self.behaviour.accepts_1k => {
901                    st.rejected += 1;
902                    if st.rejected >= 9 {
903                        st.readable.extend([CAN, CAN, CAN]);
904                    } else {
905                        st.readable.push_back(NAK);
906                    }
907                }
908                Some(&(SOH | STX)) => {
909                    let num = bytes.get(1).copied().unwrap_or_default();
910                    if self.behaviour.drop_block == Some(num) && !st.mangled.contains(&num) {
911                        // Lost on the line: no reply; the host times out.
912                        st.mangled.push(num);
913                        return;
914                    }
915                    match decode_block(bytes, check) {
916                        Ok(block) if block.num == st.blk => {
917                            st.received.extend_from_slice(&block.data);
918                            st.blk = st.blk.wrapping_add(1);
919                            st.readable.push_back(ACK);
920                        }
921                        Ok(_) => st.readable.push_back(ACK),
922                        Err(_) => st.readable.push_back(NAK),
923                    }
924                }
925                _ => {}
926            }
927        }
928    }
929
930    impl Transport for FakeCalc {
931        fn write_packet(&mut self, packet: &[u8]) -> io::Result<()> {
932            self.on_write(packet);
933            Ok(())
934        }
935
936        fn read(&mut self, buf: &mut [u8], timeout: Duration) -> io::Result<usize> {
937            let mut st = self.state();
938            if st.readable.is_empty() {
939                drop(st);
940                std::thread::sleep(timeout.min(Duration::from_millis(20)));
941                return Ok(0);
942            }
943            let n = st.readable.len().min(buf.len());
944            for (slot, byte) in buf.iter_mut().zip(st.readable.drain(..n)) {
945                *slot = byte;
946            }
947            Ok(n)
948        }
949    }
950
951    /// [`FakeCalc`] whose link fails for reads once the transfer is done
952    /// (sender: our final ACK written).
953    struct LostAfterDone(FakeCalc);
954
955    impl Transport for LostAfterDone {
956        fn write_packet(&mut self, packet: &[u8]) -> io::Result<()> {
957            self.0.write_packet(packet)
958        }
959
960        fn read(&mut self, buf: &mut [u8], timeout: Duration) -> io::Result<usize> {
961            if self.0.state().done {
962                return Err(io::Error::other("link lost"));
963            }
964            self.0.read(buf, timeout)
965        }
966    }
967
968    #[test]
969    fn link_lost_while_lingering_keeps_the_file() {
970        let file = all_bytes(H49);
971        let peer = FakeCalc::sender(file.clone(), Behaviour::hp49());
972        let mut options = fast(XmodemOptions::for_model(Model::Hp49G).unwrap());
973        options.xmodem.linger = Duration::from_secs(5);
974        let mut s = XmodemSession::new(Box::new(LostAfterDone(peer.clone())), options);
975        let start = Instant::now();
976        let got = s.receive().unwrap();
977        assert_eq!(got.data, file);
978        assert!(peer.state().done);
979        assert!(
980            start.elapsed() < Duration::from_secs(5),
981            "linger ended early"
982        );
983    }
984
985    fn big_file(header: &[u8; 8]) -> Vec<u8> {
986        hp_string(header, &(0..1811).map(|i| i as u8).collect::<Vec<u8>>())
987    }
988
989    #[test]
990    fn send_to_49g_uses_hp_crc_and_1k() {
991        let peer = FakeCalc::receiver(Behaviour::hp49());
992        let options = fast(XmodemOptions::for_model(Model::Hp49G).unwrap());
993        let mut s = XmodemSession::new(Box::new(peer.clone()), options);
994        let file = big_file(H49);
995        let mut events = Vec::new();
996        let report = s.send_with(&file, &mut |e| events.push(e.clone())).unwrap();
997        assert_eq!(report.check, Check::HpCrc);
998        assert_eq!(report.bytes, file.len() as u64);
999        let st = peer.state();
1000        assert!(st.done);
1001        assert_eq!(&st.received[..file.len()], file.as_slice());
1002        // One 1k block, then the short tail.
1003        assert_eq!(st.written[0][0], STX);
1004        assert!(st.written[1..].iter().all(|w| w[0] != STX));
1005        assert!(events.contains(&Event::Done));
1006    }
1007
1008    #[test]
1009    fn send_to_48gx_uses_checksum_and_128_byte_blocks() {
1010        // 1k configured, but the 48GX opens with NAK: 128-byte blocks.
1011        let peer = FakeCalc::receiver(Behaviour::hp48gx());
1012        let mut options = fast(XmodemOptions::default());
1013        options.xmodem.block_size = BlockSize::B1k;
1014        let mut s = XmodemSession::new(Box::new(peer.clone()), options);
1015        let file = big_file(H48);
1016        let report = s.send(&file).unwrap();
1017        assert_eq!(report.check, Check::Checksum);
1018        let st = peer.state();
1019        assert_eq!(st.rejected, 0);
1020        assert_eq!(&st.received[..file.len()], file.as_slice());
1021        assert!(st.written.iter().all(|w| w[0] != STX));
1022    }
1023
1024    #[test]
1025    fn send_1k_forced_on_48gx_is_cancelled() {
1026        let peer = FakeCalc::receiver(Behaviour::hp48gx());
1027        let mut options = fast(XmodemOptions::default());
1028        options.xmodem.checksum_1k = true;
1029        let mut s = XmodemSession::new(Box::new(peer.clone()), options);
1030        let err = s.send(&big_file(H48)).unwrap_err();
1031        assert!(
1032            matches!(err, Error::Xmodem(xmodem_proto::Error::RemoteCancelled)),
1033            "{err:?}"
1034        );
1035        assert_eq!(peer.state().rejected, 9);
1036    }
1037
1038    #[test]
1039    fn send_recovers_a_dropped_block() {
1040        let peer = FakeCalc::receiver(Behaviour {
1041            drop_block: Some(2),
1042            ..Behaviour::hp48gx()
1043        });
1044        let mut s = XmodemSession::new(
1045            Box::new(peer.clone()),
1046            fast(XmodemOptions::for_model(Model::Hp48Gx).unwrap()),
1047        );
1048        let file = all_bytes(H48);
1049        s.send(&file).unwrap();
1050        let st = peer.state();
1051        assert_eq!(&st.received[..file.len()], file.as_slice());
1052        // Block 2 went out twice (the first copy was lost).
1053        let twos = st
1054            .written
1055            .iter()
1056            .filter(|w| w.first() == Some(&SOH) && w.get(1) == Some(&2))
1057            .count();
1058        assert_eq!(twos, 2);
1059    }
1060
1061    #[test]
1062    fn receive_from_49g_recovers_dropped_and_corrupt_blocks() {
1063        let file = big_file(H49);
1064        let peer = FakeCalc::sender(
1065            file.clone(),
1066            Behaviour {
1067                drop_block: Some(3),
1068                corrupt_block: Some(5),
1069                ..Behaviour::hp49()
1070            },
1071        );
1072        let mut s = XmodemSession::new(
1073            Box::new(peer.clone()),
1074            fast(XmodemOptions::for_model(Model::Hp49G).unwrap()),
1075        );
1076        let got = s.receive().unwrap();
1077        assert_eq!(got.check, Check::HpCrc);
1078        assert_eq!(got.data, file);
1079        let st = peer.state();
1080        assert!(st.done);
1081        assert_eq!(st.mangled, vec![3, 5]);
1082        // Our NAKs asked for both again.
1083        assert!(st.written.iter().filter(|w| **w == [NAK]).count() >= 2);
1084    }
1085
1086    #[test]
1087    fn receive_from_48gx_ignores_d_and_uses_checksum() {
1088        // Unknown model: `D` three times, then NAK, which the 48GX answers.
1089        let file = all_bytes(H48);
1090        let peer = FakeCalc::sender(file.clone(), Behaviour::hp48gx());
1091        let mut options = fast(XmodemOptions::default());
1092        options.xmodem.crc_attempts = 3;
1093        let mut s = XmodemSession::new(Box::new(peer.clone()), options);
1094        let got = s.receive().unwrap();
1095        assert_eq!(got.check, Check::Checksum);
1096        assert_eq!(got.data, file);
1097        let st = peer.state();
1098        assert_eq!(
1099            &st.written[..4],
1100            &[b"D".to_vec(), b"D".to_vec(), b"D".to_vec(), vec![NAK]]
1101        );
1102    }
1103
1104    #[test]
1105    fn nobody_starts_send_times_out() {
1106        let peer = FakeCalc::receiver(Behaviour {
1107            start: 0,
1108            ..Behaviour::hp49()
1109        });
1110        peer.state().readable.clear();
1111        let mut s = XmodemSession::new(
1112            Box::new(peer),
1113            fast(XmodemOptions::for_model(Model::Hp49G).unwrap()),
1114        );
1115        let start = Instant::now();
1116        let err = s.send(b"x").unwrap_err();
1117        assert!(
1118            matches!(err, Error::Xmodem(xmodem_proto::Error::Timeout)),
1119            "{err:?}"
1120        );
1121        let took = start.elapsed();
1122        assert!(
1123            took >= MIN_START_TIMEOUT && took < Duration::from_secs(3),
1124            "{took:?}"
1125        );
1126    }
1127
1128    #[test]
1129    fn nobody_starts_receive_times_out_with_cans() {
1130        let peer = FakeCalc::sender(
1131            b"x".to_vec(),
1132            Behaviour {
1133                answers: vec![],
1134                ..Behaviour::hp49()
1135            },
1136        );
1137        let mut s = XmodemSession::new(
1138            Box::new(peer.clone()),
1139            fast(XmodemOptions::for_model(Model::Hp49G).unwrap()),
1140        );
1141        let start = Instant::now();
1142        let err = s.receive().unwrap_err();
1143        assert!(
1144            matches!(err, Error::Xmodem(xmodem_proto::Error::Timeout)),
1145            "{err:?}"
1146        );
1147        let took = start.elapsed();
1148        assert!(
1149            took >= MIN_START_TIMEOUT && took < Duration::from_secs(3),
1150            "{took:?}"
1151        );
1152        // Only `D`s for the 49G (no fallback within the window), then CANs.
1153        let st = peer.state();
1154        assert!(st.written.len() > 3);
1155        assert!(
1156            st.written[..st.written.len() - 1]
1157                .iter()
1158                .all(|w| *w == b"D")
1159        );
1160        assert_eq!(st.cans, vec![CAN, CAN, CAN]);
1161    }
1162
1163    /// A line that delivers one good block, then noise forever: block
1164    /// headers whose frames never check out, so the receiver keeps purging
1165    /// and its own timeouts never fire. Only the watchdog ends this.
1166    struct NoisyLine {
1167        reads: usize,
1168        first: Option<Vec<u8>>,
1169    }
1170
1171    impl Transport for NoisyLine {
1172        fn write_packet(&mut self, _packet: &[u8]) -> io::Result<()> {
1173            Ok(())
1174        }
1175
1176        fn read(&mut self, buf: &mut [u8], _timeout: Duration) -> io::Result<usize> {
1177            self.reads += 1;
1178            if self.reads > 20_000 {
1179                return Err(io::Error::other("read cap hit: watchdog never fired"));
1180            }
1181            if let Some(block) = self.first.take() {
1182                buf[..block.len()].copy_from_slice(&block);
1183                return Ok(block.len());
1184            }
1185            std::thread::sleep(Duration::from_millis(1));
1186            let noise = [SOH, 2, 0xFD, 7, 7, 7];
1187            buf[..noise.len()].copy_from_slice(&noise);
1188            Ok(noise.len())
1189        }
1190    }
1191
1192    #[test]
1193    fn continuous_noise_still_ends() {
1194        let mut options = fast(XmodemOptions::default());
1195        options.xmodem.retries = 1;
1196        let first = encode_block(1, BlockSize::B128, b"x", 0, Check::HpCrc).unwrap();
1197        let line = NoisyLine {
1198            reads: 0,
1199            first: Some(first),
1200        };
1201        let mut s = XmodemSession::new(Box::new(line), options);
1202        let start = Instant::now();
1203        let err = s.receive().unwrap_err();
1204        assert!(
1205            matches!(err, Error::Xmodem(xmodem_proto::Error::Timeout)),
1206            "{err:?}"
1207        );
1208        assert!(
1209            start.elapsed() < Duration::from_secs(5),
1210            "{:?}",
1211            start.elapsed()
1212        );
1213    }
1214
1215    #[test]
1216    fn options_for_models() {
1217        assert!(matches!(
1218            XmodemOptions::for_model(Model::Hp48Sx),
1219            Err(Error::Unsupported(_))
1220        ));
1221        let gx = XmodemOptions::for_model(Model::Hp48Gx).unwrap();
1222        assert_eq!(
1223            (gx.xmodem.check, gx.xmodem.block_size),
1224            (Check::Checksum, BlockSize::B128)
1225        );
1226        let g49 = XmodemOptions::for_model(Model::Hp49G).unwrap();
1227        assert_eq!(
1228            (g49.xmodem.check, g49.xmodem.block_size),
1229            (Check::HpCrc, BlockSize::B1k)
1230        );
1231        let clamp = XmodemOptions {
1232            start_timeout: Duration::from_secs(100_000),
1233            ..XmodemOptions::default()
1234        };
1235        assert_eq!(clamp.config().start_timeout, MAX_START_TIMEOUT);
1236        assert_eq!(clamp.config().recv_start_timeout, Some(MAX_START_TIMEOUT));
1237        let zero = XmodemOptions {
1238            start_timeout: Duration::ZERO,
1239            ..XmodemOptions::default()
1240        };
1241        assert_eq!(zero.config().start_timeout, MIN_START_TIMEOUT);
1242    }
1243}