1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use crate::io::uart::Uart;
use anyhow::Result;
use std::io::{Read, Write};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum XmodemError {
    #[error("Cancelled")]
    Cancelled,
    #[error("Exhausted retries: {0}")]
    ExhaustedRetries(usize),
    #[error("Unsupported mode: {0}")]
    UnsupportedMode(String),
}

#[derive(Debug, Clone, Copy)]
#[repr(usize)]
pub enum XmodemBlock {
    Block128 = 128,
    Block1k = 1024,
}

#[derive(Debug)]
pub struct Xmodem {
    pub max_errors: usize,
    pub pad_byte: u8,
    pub block_len: XmodemBlock,
}

impl Default for Xmodem {
    fn default() -> Self {
        Self::new()
    }
}

impl Xmodem {
    const POLYNOMIAL: u16 = 0x1021;
    const CRC: u8 = 0x43;
    const SOH: u8 = 0x01;
    const STX: u8 = 0x02;
    const EOF: u8 = 0x04;
    const ACK: u8 = 0x06;
    const NAK: u8 = 0x15;
    const CAN: u8 = 0x18;

    pub fn new() -> Self {
        Xmodem {
            max_errors: 16,
            pad_byte: 0xff,
            block_len: XmodemBlock::Block1k,
        }
    }

    fn crc16(buf: &[u8]) -> u16 {
        let mut crc = 0u16;
        for byte in buf {
            crc ^= (*byte as u16) << 8;
            for _bit in 0..8 {
                let msb = crc & 0x8000 != 0;
                crc <<= 1;
                if msb {
                    crc ^= Self::POLYNOMIAL;
                }
            }
        }
        crc
    }

    pub fn send(&self, uart: &dyn Uart, data: impl Read) -> Result<()> {
        self.send_start(uart)?;
        self.send_data(uart, data)?;
        self.send_finish(uart)?;
        Ok(())
    }

    fn send_start(&self, uart: &dyn Uart) -> Result<()> {
        let mut ch = 0u8;
        let mut cancels = 0usize;
        // Wait for the XMODEM CRC start sequence.
        loop {
            uart.read(std::slice::from_mut(&mut ch))?;
            match ch {
                Self::CRC => {
                    return Ok(());
                }
                Self::NAK => {
                    return Err(XmodemError::UnsupportedMode("standard checksums".into()).into());
                }
                Self::CAN => {
                    cancels += 1;
                    if cancels >= 2 {
                        return Err(XmodemError::Cancelled.into());
                    }
                }
                _ => {
                    log::info!("Unknown byte received while waiting for XMODEM start: {ch:#x?}");
                }
            }
        }
    }

    fn send_data(&self, uart: &dyn Uart, mut data: impl Read) -> Result<()> {
        let mut block = 0usize;
        let mut errors = 0usize;
        loop {
            block += 1;
            let mut buf = vec![self.pad_byte; self.block_len as usize + 3];
            let n = data.read(&mut buf[3..])?;
            if n == 0 {
                break;
            }

            buf[0] = match self.block_len {
                XmodemBlock::Block128 => Self::SOH,
                XmodemBlock::Block1k => Self::STX,
            };
            buf[1] = block as u8;
            buf[2] = 255 - buf[1];
            let crc = Self::crc16(&buf[3..]);
            buf.push((crc >> 8) as u8);
            buf.push((crc & 0xFF) as u8);
            log::info!("Sending block {block}");

            let mut cancels = 0usize;
            loop {
                uart.write(&buf)?;
                let mut ch = 0u8;
                uart.read(std::slice::from_mut(&mut ch))?;
                match ch {
                    Self::ACK => break,
                    Self::NAK => {
                        log::info!("XMODEM send got NAK.  Retrying.");
                        errors += 1;
                    }
                    Self::CAN => {
                        cancels += 1;
                        if cancels >= 2 {
                            return Err(XmodemError::Cancelled.into());
                        }
                    }
                    _ => {
                        log::info!("Expected ACK. Got {ch:#x}.");
                        errors += 1;
                    }
                }
                if errors >= self.max_errors {
                    return Err(XmodemError::ExhaustedRetries(errors).into());
                }
            }
        }
        Ok(())
    }

    fn send_finish(&self, uart: &dyn Uart) -> Result<()> {
        uart.write(&[Self::EOF])?;
        let mut ch = 0u8;
        uart.read(std::slice::from_mut(&mut ch))?;
        if ch != Self::ACK {
            log::info!("Expected ACK. Got {ch:#x}.");
        }
        Ok(())
    }

    pub fn receive(&self, uart: &dyn Uart, data: &mut impl Write) -> Result<()> {
        // Send the byte indicating the protocol we want (Xmodem-CRC).
        uart.write(&[Self::CRC])?;

        let mut block = 1u8;
        let mut errors = 0usize;
        loop {
            // The first byte of the packet is the packet type which indicates the block size.
            let mut byte = 0u8;
            uart.read(std::slice::from_mut(&mut byte))?;
            let block_len = match byte {
                Self::SOH => 128,
                Self::STX => 1024,
                Self::EOF => {
                    // End of file.  Send an ACK.
                    uart.write(&[Self::ACK])?;
                    break;
                }
                _ => {
                    return Err(XmodemError::UnsupportedMode(format!(
                        "bad start of packet: {byte:?}"
                    ))
                    .into());
                }
            };

            // The next two bytes are the block number and its complement.
            let mut bnum = 0u8;
            let mut bcom = 0u8;
            uart.read(std::slice::from_mut(&mut bnum))?;
            uart.read(std::slice::from_mut(&mut bcom))?;
            let cancel = block != bnum || bnum != 255 - bcom;

            // The next `block_len` bytes are the packet itself.
            let mut buffer = Vec::new();
            buffer.resize(block_len, 0);
            let mut total = 0;
            while total < block_len {
                let n = uart.read(&mut buffer[total..])?;
                total += n;
            }

            // The final two bytes are the CRC16.
            let mut crc1 = 0u8;
            let mut crc2 = 0u8;
            uart.read(std::slice::from_mut(&mut crc1))?;
            uart.read(std::slice::from_mut(&mut crc2))?;
            let crc = u16::from_be_bytes([crc1, crc2]);

            // If we should cancel, do it now.
            if cancel {
                uart.write(&[Self::CAN, Self::CAN])?;
                return Err(XmodemError::Cancelled.into());
            }
            if Self::crc16(&buffer) == crc {
                // CRC was good; send an ACK and keep the data.
                uart.write(&[Self::ACK])?;
                data.write_all(&buffer)?;
                block = block.wrapping_add(1);
            } else {
                uart.write(&[Self::NAK])?;
                errors += 1;
            }
            if errors >= self.max_errors {
                return Err(XmodemError::ExhaustedRetries(errors).into());
            }
        }
        Ok(())
    }
}

// The xmodem tests depend on the lrzsz package which contains the classic
// XMODEM/YMODEM/ZMODEM file transfer programs dating back to the 1980s and
// 1990s.
#[cfg(test)]
mod test {
    use super::*;
    use crate::util::testing::{ChildUart, TransferState};
    use crate::util::tmpfilename;

    #[rustfmt::skip]
    const GETTYSBURG: &str =
r#"Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to the
proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation,
or any nation so conceived and so dedicated, can long endure. We are met
on a great battle-field of that war. We have come to dedicate a portion
of that field, as a final resting place for those who here gave their
lives that that nation might live. It is altogether fitting and proper
that we should do this.
But, in a larger sense, we can not dedicate -- we can not consecrate --
we can not hallow -- this ground. The brave men, living and dead, who
struggled here, have consecrated it, far above our poor power to add or
detract. The world will little note, nor long remember what we say here,
but it can never forget what they did here. It is for us the living,
rather, to be dedicated here to the unfinished work which they who
fought here have thus far so nobly advanced. It is rather for us to be
here dedicated to the great task remaining before us -- that from these
honored dead we take increased devotion to that cause for which they gave
the last full measure of devotion -- that we here highly resolve that
these dead shall not have died in vain -- that this nation, under God,
shall have a new birth of freedom -- and that government of the people,
by the people, for the people, shall not perish from the earth.
Abraham Lincoln
November 19, 1863
"#;

    #[test]
    fn test_xmodem_send() -> Result<()> {
        let filename = tmpfilename("test_xmodem_send");
        let child = ChildUart::spawn(&["rx", "--with-crc", &filename])?;
        let xmodem = Xmodem::new();
        let gettysburg = GETTYSBURG.as_bytes();
        xmodem.send(&child, gettysburg)?;
        assert!(child.wait()?.success());
        let result = std::fs::read(&filename)?;
        // The file should be a multiple of the block size.
        assert_eq!(result.len() % 1024, 0);
        assert!(result.len() >= gettysburg.len());
        assert_eq!(&result[..gettysburg.len()], gettysburg);
        Ok(())
    }

    #[test]
    fn test_xmodem_send_with_errors() -> Result<()> {
        let filename = tmpfilename("test_xmodem_send_with_errors");
        let child = ChildUart::spawn_corrupt(
            &["rx", "--with-crc", &filename],
            TransferState::default(),
            TransferState::new(&[3, 136]),
        )?;
        let xmodem = Xmodem {
            max_errors: 2,
            pad_byte: 0,
            block_len: XmodemBlock::Block128,
        };
        let gettysburg = GETTYSBURG.as_bytes();
        let err = xmodem.send(&child, gettysburg);
        assert!(err.is_err());
        assert_eq!(err.unwrap_err().to_string(), "Exhausted retries: 2");
        Ok(())
    }

    #[test]
    fn test_xmodem_checksum_mode() -> Result<()> {
        let filename = tmpfilename("test_xmodem_checksum_mode");
        let child = ChildUart::spawn(&["rx", &filename])?;
        let xmodem = Xmodem::new();
        let gettysburg = GETTYSBURG.as_bytes();
        let result = xmodem.send(&child, gettysburg);
        assert_eq!(child.wait()?.success(), false);
        assert!(result.is_err());
        let err = result.unwrap_err().downcast::<XmodemError>().unwrap();
        assert_eq!(err.to_string(), "Unsupported mode: standard checksums");
        Ok(())
    }

    #[test]
    fn test_xmodem_recv() -> Result<()> {
        let filename = tmpfilename("test_xmodem_recv");
        let gettysburg = GETTYSBURG.as_bytes();
        std::fs::write(&filename, gettysburg)?;
        let child = ChildUart::spawn(&["sx", &filename])?;
        let xmodem = Xmodem::new();
        let mut result = Vec::new();
        xmodem.receive(&child, &mut result)?;
        assert!(child.wait()?.success());
        // The received data should be a multiple of the block size.
        assert_eq!(result.len() % 128, 0);
        assert!(result.len() >= gettysburg.len());
        assert_eq!(&result[..gettysburg.len()], gettysburg);
        Ok(())
    }

    #[test]
    fn test_xmodem1k_recv() -> Result<()> {
        let filename = tmpfilename("test_xmodem1k_recv");
        let gettysburg = GETTYSBURG.as_bytes();
        std::fs::write(&filename, gettysburg)?;
        let child = ChildUart::spawn(&["sx", "--1k", &filename])?;
        let xmodem = Xmodem::new();
        let mut result = Vec::new();
        xmodem.receive(&child, &mut result)?;
        assert!(child.wait()?.success());
        // The received data should be a multiple of the block size.
        // Even though we're using 1K blocks, the lrzsz programs use
        // shorter blocks for the last bit of the data.
        assert_eq!(result.len() % 128, 0);
        assert!(result.len() >= gettysburg.len());
        assert_eq!(&result[..gettysburg.len()], gettysburg);
        Ok(())
    }

    #[test]
    fn test_xmodem_recv_with_errors() -> Result<()> {
        let filename = tmpfilename("test_xmodem_recv_with_errors");
        let gettysburg = GETTYSBURG.as_bytes();
        std::fs::write(&filename, gettysburg)?;
        let child = ChildUart::spawn_corrupt(
            &["sx", &filename],
            TransferState::new(&[3, 136]),
            TransferState::default(),
        )?;
        let xmodem = Xmodem {
            max_errors: 2,
            pad_byte: 0,
            block_len: XmodemBlock::Block128,
        };
        let mut result = Vec::new();
        let err = xmodem.receive(&child, &mut result);
        assert!(err.is_err());
        assert_eq!(err.unwrap_err().to_string(), "Exhausted retries: 2");
        Ok(())
    }

    #[test]
    fn test_xmodem_recv_with_cancel() -> Result<()> {
        let filename = tmpfilename("test_xmodem_recv_with_cancel");
        let gettysburg = GETTYSBURG.as_bytes();
        std::fs::write(&filename, gettysburg)?;
        let child = ChildUart::spawn_corrupt(
            &["sx", &filename],
            TransferState::new(&[1, 134]),
            TransferState::default(),
        )?;
        let xmodem = Xmodem {
            max_errors: 2,
            pad_byte: 0,
            block_len: XmodemBlock::Block128,
        };
        let mut result = Vec::new();
        let err = xmodem.receive(&child, &mut result);
        assert!(err.is_err());
        assert_eq!(err.unwrap_err().to_string(), "Cancelled");
        Ok(())
    }
}