Skip to main content

zsync_rs/
control.rs

1//! The `.zsync` control file: parsing, generation and writing.
2//!
3//! A control file is a text header of `Key: value` lines, ended by a blank
4//! line, followed by one binary record per block of the target. Each record
5//! holds the block's rolling checksum and then its MD4 digest, both cut down
6//! to the lengths the `Hash-Lengths` header gives. The rolling checksum is
7//! stored big-endian and loses its high-order bytes first. [`ControlFile`]
8//! holds the parsed form and the same type round-trips through
9//! [`ControlFile::write`], which is how `zsyncmake` produces one.
10
11use std::io::{BufRead, Read, Seek, SeekFrom, Write};
12
13use crate::checksum::{calc_md4, calc_sha1_stream};
14use crate::rsum::{Rsum, calc_rsum_block};
15
16/// Why [`ControlFile::generate`] could not describe a file.
17#[derive(Debug, thiserror::Error)]
18pub enum GenerateError {
19    /// Reading or seeking the input failed.
20    #[error("IO error: {0}")]
21    Io(#[from] std::io::Error),
22    /// The input has no bytes, and a control file cannot describe a target
23    /// with no blocks.
24    #[error("file is empty")]
25    EmptyFile,
26}
27
28/// Why [`ControlFile::write`] failed.
29#[derive(Debug, thiserror::Error)]
30pub enum WriteError {
31    /// The writer reported an error.
32    #[error("IO error: {0}")]
33    Io(#[from] std::io::Error),
34}
35
36/// Why [`ControlFile::parse`] rejected its input.
37#[derive(Debug, thiserror::Error)]
38pub enum ParseError {
39    /// Reading failed, including the block records ending early.
40    #[error("IO error: {0}")]
41    Io(#[from] std::io::Error),
42    /// A header line has no `:`, or a `SHA-1` value is not 40 characters.
43    #[error("Invalid header: {0}")]
44    InvalidHeader(String),
45    /// A header the format requires, named here, is absent.
46    #[error("Missing required field: {0}")]
47    MissingField(String),
48    /// `Blocksize` is not a number or not a power of two.
49    #[error("Invalid blocksize: {0}")]
50    InvalidBlocksize(String),
51    /// `Hash-Lengths` is not three comma-separated numbers within the ranges
52    /// [`HashLengths`] documents.
53    #[error("Invalid hash lengths: {0}")]
54    InvalidHashLengths(String),
55    /// `Length` is not a number, or implies more than 2^26 blocks.
56    #[error("Invalid length: {0}")]
57    InvalidLength(String),
58    /// The input ended before the blank line that closes the header.
59    #[error("Unexpected end of file")]
60    UnexpectedEof,
61    /// The header ran past the given number of bytes without ending.
62    #[error("Header section exceeds {0} bytes")]
63    HeaderTooLarge(u64),
64}
65
66/// The checksums of one target block.
67#[derive(Debug, Clone, Copy)]
68pub struct BlockChecksum {
69    /// The rolling checksum, with any bytes the control file does not store
70    /// left as zero.
71    pub rsum: Rsum,
72    /// The MD4 digest. Only the first [`HashLengths::checksum_bytes`] are
73    /// significant, and the rest are zero.
74    pub checksum: [u8; 16],
75}
76
77/// A parsed control file: what the target is, where to fetch it, and the
78/// checksum of every block.
79#[derive(Debug, Clone)]
80pub struct ControlFile {
81    /// The `zsync` header, naming the version of the tool that wrote the
82    /// file, or empty when the header is absent.
83    pub version: String,
84    /// The suggested name for the target file.
85    pub filename: Option<String>,
86    /// The target's modification time, verbatim from the `MTime` header.
87    pub mtime: Option<String>,
88    /// The block size in bytes, always a power of two.
89    pub blocksize: usize,
90    /// The target's length in bytes.
91    pub length: u64,
92    /// How much of each block checksum the file stores.
93    pub hash_lengths: HashLengths,
94    /// Where the target can be fetched, in the order given. A relative URL
95    /// resolves against the control file's own location.
96    pub urls: Vec<String>,
97    /// The target's SHA-1 as 40 hex digits, verbatim from the `SHA-1` header.
98    pub sha1: Option<String>,
99    /// One entry per block of the target, in order.
100    pub block_checksums: Vec<BlockChecksum>,
101}
102
103/// The `Hash-Lengths` header: how strict matching is and how many checksum
104/// bytes each block record stores.
105///
106/// Shorter checksums make a smaller control file at the cost of more false
107/// candidates, which is why a large target needs longer ones.
108#[derive(Debug, Clone, Copy)]
109pub struct HashLengths {
110    /// How many consecutive blocks must match together before a match is
111    /// accepted, either 1 or 2.
112    pub seq_matches: u8,
113    /// Bytes of rolling checksum stored per block, from 1 to 4.
114    pub rsum_bytes: u8,
115    /// Bytes of MD4 digest stored per block, from 3 to 16.
116    pub checksum_bytes: u8,
117}
118
119/// Full-length checksums with single-block matching, which is what a control
120/// file without a `Hash-Lengths` header means.
121impl Default for HashLengths {
122    fn default() -> Self {
123        Self {
124            seq_matches: 1,
125            rsum_bytes: 4,
126            checksum_bytes: 16,
127        }
128    }
129}
130
131impl ControlFile {
132    /// Parse a control file.
133    ///
134    /// The header section is read through a byte cap. It arrives from the
135    /// network, and both a single unterminated line and an endless run of
136    /// `URL:` lines would otherwise grow without bound, letting the origin
137    /// choose how much memory the client spends before any of it is
138    /// validated. Unknown headers are skipped.
139    ///
140    /// # Errors
141    ///
142    /// Returns a [`ParseError`] naming the first problem found in the header,
143    /// or [`ParseError::Io`] when reading fails or the block records end
144    /// before every block has one.
145    pub fn parse<R: Read>(reader: R) -> Result<Self, ParseError> {
146        /// Generous: real headers are a few hundred bytes, and even a long
147        /// mirror list is far below this.
148        const MAX_HEADER_BYTES: u64 = 1 << 20;
149
150        let mut reader = std::io::BufReader::new(reader);
151        let mut line = String::new();
152
153        let mut version = String::new();
154        let mut filename = None;
155        let mut mtime = None;
156        let mut blocksize = None;
157        let mut length = None;
158        let mut hash_lengths = HashLengths::default();
159        let mut urls = Vec::new();
160        let mut sha1 = None;
161
162        let mut header = (&mut reader).take(MAX_HEADER_BYTES);
163        loop {
164            line.clear();
165            let bytes_read = header.read_line(&mut line)?;
166            if bytes_read == 0 {
167                if header.limit() == 0 {
168                    return Err(ParseError::HeaderTooLarge(MAX_HEADER_BYTES));
169                }
170                return Err(ParseError::UnexpectedEof);
171            }
172
173            let trimmed = line.trim_end_matches(['\n', '\r', ' ']);
174            if trimmed.is_empty() {
175                break;
176            }
177
178            let Some((key, value)) = trimmed.split_once(':') else {
179                return Err(ParseError::InvalidHeader(trimmed.to_string()));
180            };
181
182            let value = value.trim_start_matches(' ');
183
184            match key {
185                "zsync" => {
186                    version = value.to_string();
187                }
188                "Filename" => {
189                    filename = Some(value.to_string());
190                }
191                "MTime" => {
192                    mtime = Some(value.to_string());
193                }
194                "Blocksize" => {
195                    let bs: usize = value
196                        .parse()
197                        .map_err(|_| ParseError::InvalidBlocksize(value.to_string()))?;
198                    if bs == 0 || (bs & (bs - 1)) != 0 {
199                        return Err(ParseError::InvalidBlocksize(value.to_string()));
200                    }
201                    blocksize = Some(bs);
202                }
203                "Length" => {
204                    length = Some(
205                        value
206                            .parse()
207                            .map_err(|_| ParseError::InvalidLength(value.to_string()))?,
208                    );
209                }
210                "URL" => {
211                    urls.push(value.to_string());
212                }
213                "Hash-Lengths" => {
214                    let parts: Vec<&str> = value.split(',').collect();
215                    if parts.len() != 3 {
216                        return Err(ParseError::InvalidHashLengths(value.to_string()));
217                    }
218                    let seq_matches: u8 = parts[0]
219                        .parse()
220                        .map_err(|_| ParseError::InvalidHashLengths(value.to_string()))?;
221                    let rsum_bytes: u8 = parts[1]
222                        .parse()
223                        .map_err(|_| ParseError::InvalidHashLengths(value.to_string()))?;
224                    let checksum_bytes: u8 = parts[2]
225                        .parse()
226                        .map_err(|_| ParseError::InvalidHashLengths(value.to_string()))?;
227
228                    if !(1..=2).contains(&seq_matches)
229                        || !(1..=4).contains(&rsum_bytes)
230                        || !(3..=16).contains(&checksum_bytes)
231                    {
232                        return Err(ParseError::InvalidHashLengths(value.to_string()));
233                    }
234
235                    hash_lengths = HashLengths {
236                        seq_matches,
237                        rsum_bytes,
238                        checksum_bytes,
239                    };
240                }
241                "SHA-1" => {
242                    if value.len() != 40 {
243                        return Err(ParseError::InvalidHeader(
244                            "SHA-1 digest wrong length".to_string(),
245                        ));
246                    }
247                    sha1 = Some(value.to_string());
248                }
249                _ => {}
250            }
251        }
252
253        let blocksize =
254            blocksize.ok_or_else(|| ParseError::MissingField("Blocksize".to_string()))?;
255        let length: u64 = length.ok_or_else(|| ParseError::MissingField("Length".to_string()))?;
256
257        let num_blocks = length.div_ceil(blocksize as u64) as usize;
258
259        // Sanity check: avoid massive allocations from malformed input.
260        // Each block needs (rsum_bytes + checksum_bytes) of data following the header.
261        const MAX_BLOCKS: usize = 64 * 1024 * 1024;
262        if num_blocks > MAX_BLOCKS {
263            return Err(ParseError::InvalidLength(format!(
264                "too many blocks: {num_blocks}"
265            )));
266        }
267
268        let block_checksums = Self::read_block_checksums(&mut reader, num_blocks, hash_lengths)?;
269
270        Ok(Self {
271            version,
272            filename,
273            mtime,
274            blocksize,
275            length,
276            hash_lengths,
277            urls,
278            sha1,
279            block_checksums,
280        })
281    }
282
283    fn read_block_checksums<R: BufRead>(
284        reader: &mut R,
285        num_blocks: usize,
286        hash_lengths: HashLengths,
287    ) -> Result<Vec<BlockChecksum>, ParseError> {
288        // Reserve for what has arrived, not for what was claimed. The count
289        // is derived from a header a few bytes long, so sizing the buffer
290        // from it lets a tiny response reserve gigabytes before a single
291        // checksum is read. Growth is geometric, so a genuinely large file
292        // costs a handful of reallocations and nothing else.
293        const MAX_PREALLOC: usize = 1 << 16;
294        let mut checksums = Vec::with_capacity(num_blocks.min(MAX_PREALLOC));
295        let entry_size = (hash_lengths.rsum_bytes + hash_lengths.checksum_bytes) as usize;
296        let mut buf = vec![0u8; entry_size];
297
298        for _ in 0..num_blocks {
299            reader.read_exact(&mut buf)?;
300
301            let rsum_bytes = hash_lengths.rsum_bytes as usize;
302            let (rsum_a, rsum_b) = match rsum_bytes {
303                1 => (0u16, u16::from(buf[0])),
304                2 => (0u16, u16::from_be_bytes([buf[0], buf[1]])),
305                3 => (u16::from(buf[0]), u16::from_be_bytes([buf[1], buf[2]])),
306                4 => (
307                    u16::from_be_bytes([buf[0], buf[1]]),
308                    u16::from_be_bytes([buf[2], buf[3]]),
309                ),
310                _ => (0, 0),
311            };
312
313            let mut checksum = [0u8; 16];
314            checksum[..hash_lengths.checksum_bytes as usize]
315                .copy_from_slice(&buf[rsum_bytes..entry_size]);
316
317            checksums.push(BlockChecksum {
318                rsum: Rsum {
319                    a: rsum_a,
320                    b: rsum_b,
321                },
322                checksum,
323            });
324        }
325
326        Ok(checksums)
327    }
328
329    /// The number of blocks in the target.
330    pub fn num_blocks(&self) -> usize {
331        self.block_checksums.len()
332    }
333
334    /// Generate a control file by scanning an input file.
335    ///
336    /// Every block is checksummed, with the last one padded with zeros to a
337    /// full block, and the whole input is hashed with SHA-1. A `blocksize` of
338    /// `None` picks 2048 bytes for inputs under 100,000,000 bytes and 4096
339    /// otherwise. A given size must be a power of two, or the result will not
340    /// parse. The hash lengths are derived from the file and block sizes
341    /// with the formulas `zsyncmake` uses, `url` becomes the only URL, and
342    /// the version is written as `0.6.2`.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`GenerateError::EmptyFile`] for an empty input and
347    /// [`GenerateError::Io`] when reading or seeking fails.
348    pub fn generate<R: Read + Seek>(
349        reader: &mut R,
350        filename: &str,
351        url: &str,
352        blocksize: Option<usize>,
353    ) -> Result<Self, GenerateError> {
354        let file_length = reader.seek(SeekFrom::End(0))?;
355        if file_length == 0 {
356            return Err(GenerateError::EmptyFile);
357        }
358        reader.seek(SeekFrom::Start(0))?;
359
360        let blocksize = blocksize.unwrap_or_else(|| auto_blocksize(file_length));
361        let hash_lengths = calculate_hash_lengths(file_length, blocksize);
362        let num_blocks = file_length.div_ceil(blocksize as u64) as usize;
363
364        let mut block_checksums = Vec::with_capacity(num_blocks);
365        let mut buf = vec![0u8; blocksize];
366
367        for i in 0..num_blocks {
368            let is_last = i == num_blocks - 1;
369            let block_len = if is_last {
370                let rem = (file_length % blocksize as u64) as usize;
371                if rem == 0 { blocksize } else { rem }
372            } else {
373                blocksize
374            };
375
376            reader.read_exact(&mut buf[..block_len])?;
377            if block_len < blocksize {
378                buf[block_len..].fill(0);
379            }
380
381            let rsum = calc_rsum_block(&buf);
382            let checksum = calc_md4(&buf);
383            block_checksums.push(BlockChecksum { rsum, checksum });
384        }
385
386        reader.seek(SeekFrom::Start(0))?;
387        let sha1_bytes = calc_sha1_stream(reader)?;
388        let sha1 = sha1_bytes
389            .iter()
390            .fold(String::with_capacity(40), |mut s, b| {
391                use std::fmt::Write;
392                let _ = write!(s, "{b:02x}");
393                s
394            });
395
396        Ok(Self {
397            version: "0.6.2".to_string(),
398            filename: Some(filename.to_string()),
399            mtime: None,
400            blocksize,
401            length: file_length,
402            hash_lengths,
403            urls: vec![url.to_string()],
404            sha1: Some(sha1),
405            block_checksums,
406        })
407    }
408
409    /// Write the control file to a writer.
410    ///
411    /// The block records are written at the lengths [`Self::hash_lengths`]
412    /// gives, so a file written here parses back to the same checksums.
413    ///
414    /// # Errors
415    ///
416    /// Returns [`WriteError::Io`] when the writer fails.
417    pub fn write<W: Write>(&self, writer: &mut W) -> Result<(), WriteError> {
418        writeln!(writer, "zsync: {}", self.version)?;
419        if let Some(ref filename) = self.filename {
420            writeln!(writer, "Filename: {filename}")?;
421        }
422        if let Some(ref mtime) = self.mtime {
423            writeln!(writer, "MTime: {mtime}")?;
424        }
425        writeln!(writer, "Blocksize: {}", self.blocksize)?;
426        writeln!(writer, "Length: {}", self.length)?;
427        writeln!(
428            writer,
429            "Hash-Lengths: {},{},{}",
430            self.hash_lengths.seq_matches,
431            self.hash_lengths.rsum_bytes,
432            self.hash_lengths.checksum_bytes
433        )?;
434        for url in &self.urls {
435            writeln!(writer, "URL: {url}")?;
436        }
437        if let Some(ref sha1) = self.sha1 {
438            writeln!(writer, "SHA-1: {sha1}")?;
439        }
440        writeln!(writer)?;
441
442        let rsum_bytes = self.hash_lengths.rsum_bytes as usize;
443        let checksum_bytes = self.hash_lengths.checksum_bytes as usize;
444
445        for block in &self.block_checksums {
446            let rsum_be = rsum_to_bytes(block.rsum, rsum_bytes);
447            writer.write_all(&rsum_be)?;
448            writer.write_all(&block.checksum[..checksum_bytes])?;
449        }
450
451        Ok(())
452    }
453}
454
455fn rsum_to_bytes(rsum: Rsum, rsum_bytes: usize) -> Vec<u8> {
456    match rsum_bytes {
457        1 => vec![rsum.b as u8],
458        2 => rsum.b.to_be_bytes().to_vec(),
459        3 => {
460            let mut v = Vec::with_capacity(3);
461            v.push(rsum.a as u8);
462            v.extend_from_slice(&rsum.b.to_be_bytes());
463            v
464        }
465        4 => {
466            let mut v = Vec::with_capacity(4);
467            v.extend_from_slice(&rsum.a.to_be_bytes());
468            v.extend_from_slice(&rsum.b.to_be_bytes());
469            v
470        }
471        _ => vec![0; rsum_bytes],
472    }
473}
474
475fn auto_blocksize(file_length: u64) -> usize {
476    if file_length < 100_000_000 {
477        2048
478    } else {
479        4096
480    }
481}
482
483/// Calculate optimal hash lengths based on file size and blocksize.
484fn calculate_hash_lengths(file_length: u64, blocksize: usize) -> HashLengths {
485    let len = file_length as f64;
486    let bs = blocksize as f64;
487    let seq_matches: u8 = if file_length > blocksize as u64 { 2 } else { 1 };
488    let sm = f64::from(seq_matches);
489
490    let rsum_bytes = ((len.ln() + bs.ln()) / 2_f64.ln() - 8.6) / sm / 8.0;
491    let rsum_bytes = (rsum_bytes.ceil() as i32).clamp(2, 4);
492
493    let num_blocks = 1.0 + len / bs;
494    let calc1 = ((20.0 + len.log2() + num_blocks.log2()) / sm / 8.0).ceil();
495    let calc2 = (7.9 + (20.0 + num_blocks.log2())) / 8.0;
496    let checksum_bytes = (calc1.max(calc2) as i32).clamp(4, 16);
497
498    HashLengths {
499        seq_matches,
500        rsum_bytes: rsum_bytes as u8,
501        checksum_bytes: checksum_bytes as u8,
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    /// A stream that never ends and never contains a newline, which is
510    /// what a hostile origin serves to make the client read forever.
511    struct Endless;
512
513    impl std::io::Read for Endless {
514        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
515            buf.fill(b'A');
516            Ok(buf.len())
517        }
518    }
519
520    #[test]
521    fn an_endless_header_is_refused_rather_than_buffered() {
522        // The cap is what makes this terminate at all. Which error comes
523        // out depends on where the cut lands: a line with no separator is
524        // reported as a bad header, a truncated section as an oversized
525        // one. Either is fine; reading forever is not.
526        let err = ControlFile::parse(Endless).expect_err("must not read forever");
527        assert!(
528            matches!(
529                err,
530                ParseError::HeaderTooLarge(_) | ParseError::InvalidHeader(_)
531            ),
532            "expected the header cap to stop parsing, got: {err}"
533        );
534    }
535
536    #[test]
537    fn an_endless_run_of_headers_is_refused() {
538        // Individually valid lines, without end. The cap has to bound the
539        // section, not just a single line.
540        struct ManyUrls;
541        impl std::io::Read for ManyUrls {
542            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
543                let line = b"URL: http://example.invalid/f\n";
544                let mut written = 0;
545                while written + line.len() <= buf.len() {
546                    buf[written..written + line.len()].copy_from_slice(line);
547                    written += line.len();
548                }
549                Ok(written.max(1))
550            }
551        }
552        let err = ControlFile::parse(ManyUrls).expect_err("must not read forever");
553        assert!(
554            matches!(err, ParseError::HeaderTooLarge(_)),
555            "expected a header cap error, got: {err}"
556        );
557    }
558
559    #[test]
560    fn test_parse_minimal() {
561        let mut data = Vec::new();
562        data.extend_from_slice(
563            b"zsync: 0.6.2\nBlocksize: 2048\nLength: 2048\nHash-Lengths: 1,4,16\n\n",
564        );
565        data.extend_from_slice(&[0u8; 20]);
566        let result = ControlFile::parse(&data[..]);
567        assert!(result.is_ok());
568        let cf = result.unwrap();
569        assert_eq!(cf.blocksize, 2048);
570        assert_eq!(cf.length, 2048);
571    }
572
573    #[test]
574    fn test_parse_missing_blocksize() {
575        let data = b"zsync: 0.6.2\nLength: 4096\n\n";
576        let result = ControlFile::parse(&data[..]);
577        assert!(result.is_err());
578    }
579
580    #[test]
581    fn test_parse_invalid_blocksize() {
582        let data = b"zsync: 0.6.2\nBlocksize: 1000\nLength: 4096\n\n";
583        let result = ControlFile::parse(&data[..]);
584        assert!(result.is_err());
585    }
586
587    #[test]
588    fn test_generate_write_roundtrip() {
589        let file_data = vec![42u8; 4096];
590        let mut cursor = std::io::Cursor::new(&file_data);
591
592        let cf = ControlFile::generate(&mut cursor, "test.bin", "test.bin", Some(2048)).unwrap();
593        assert_eq!(cf.blocksize, 2048);
594        assert_eq!(cf.length, 4096);
595        assert_eq!(cf.block_checksums.len(), 2);
596        assert!(cf.sha1.is_some());
597
598        let mut buf = Vec::new();
599        cf.write(&mut buf).unwrap();
600        let parsed = ControlFile::parse(&buf[..]).unwrap();
601
602        assert_eq!(parsed.blocksize, cf.blocksize);
603        assert_eq!(parsed.length, cf.length);
604        assert_eq!(parsed.sha1, cf.sha1);
605        assert_eq!(parsed.block_checksums.len(), cf.block_checksums.len());
606        let rlen = cf.hash_lengths.rsum_bytes as usize;
607        let clen = cf.hash_lengths.checksum_bytes as usize;
608        for (a, b) in parsed.block_checksums.iter().zip(&cf.block_checksums) {
609            let a_bytes = rsum_to_bytes(a.rsum, rlen);
610            let b_bytes = rsum_to_bytes(b.rsum, rlen);
611            assert_eq!(a_bytes, b_bytes);
612            assert_eq!(a.checksum[..clen], b.checksum[..clen]);
613        }
614    }
615
616    #[test]
617    fn test_generate_empty_file() {
618        let file_data: Vec<u8> = vec![];
619        let mut cursor = std::io::Cursor::new(&file_data);
620        let result = ControlFile::generate(&mut cursor, "empty", "empty", None);
621        assert!(result.is_err());
622    }
623
624    #[test]
625    fn test_generate_partial_last_block() {
626        // File not aligned to blocksize
627        let file_data = vec![0xABu8; 3000];
628        let mut cursor = std::io::Cursor::new(&file_data);
629
630        let cf = ControlFile::generate(&mut cursor, "test.bin", "test.bin", Some(2048)).unwrap();
631        assert_eq!(cf.length, 3000);
632        assert_eq!(cf.block_checksums.len(), 2);
633    }
634
635    #[test]
636    fn test_auto_blocksize_small() {
637        assert_eq!(auto_blocksize(1024), 2048);
638        assert_eq!(auto_blocksize(99_999_999), 2048);
639    }
640
641    #[test]
642    fn test_auto_blocksize_large() {
643        assert_eq!(auto_blocksize(100_000_000), 4096);
644        assert_eq!(auto_blocksize(500_000_000), 4096);
645    }
646
647    #[test]
648    fn test_rsum_to_bytes() {
649        let rsum = Rsum {
650            a: 0x1234,
651            b: 0x5678,
652        };
653        assert_eq!(rsum_to_bytes(rsum, 4), vec![0x12, 0x34, 0x56, 0x78]);
654        assert_eq!(rsum_to_bytes(rsum, 2), vec![0x56, 0x78]);
655        assert_eq!(rsum_to_bytes(rsum, 1), vec![0x78]);
656    }
657}