Skip to main content

simee_bundle/
tar.rs

1//! The single-file form: a plain, uncompressed ustar archive of the bundle directory, read and
2//! written entry by entry so neither side holds more than one chunk.
3
4use std::io::{Read, Write};
5
6use crate::{Error, Result};
7
8const BLOCK: usize = 512;
9
10/// Writes regular-file entries, then the two zero blocks that end an archive.
11pub struct TarWriter<W: Write> {
12    out: W,
13    written: u64,
14}
15
16impl<W: Write> TarWriter<W> {
17    pub fn new(out: W) -> TarWriter<W> {
18        TarWriter { out, written: 0 }
19    }
20
21    /// Bytes written so far.
22    pub fn written(&self) -> u64 {
23        self.written
24    }
25
26    /// Appends file `name` (at most 100 bytes: the bundle's names are) holding `data`.
27    pub fn entry(&mut self, name: &str, data: &[u8]) -> Result<()> {
28        if name.len() > 100 {
29            return Err(Error::Tar(format!("entry name `{name}` is longer than 100 bytes")));
30        }
31        let mut h = [0u8; BLOCK];
32        h[..name.len()].copy_from_slice(name.as_bytes());
33        octal(&mut h[100..108], 0o644);
34        octal(&mut h[108..116], 0);
35        octal(&mut h[116..124], 0);
36        octal(&mut h[124..136], data.len() as u64);
37        octal(&mut h[136..148], 0);
38        h[156] = b'0';
39        h[257..263].copy_from_slice(b"ustar\0");
40        h[263..265].copy_from_slice(b"00");
41        h[148..156].fill(b' ');
42        let sum: u32 = h.iter().map(|&b| u32::from(b)).sum();
43        h[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
44        let pad = (BLOCK - data.len() % BLOCK) % BLOCK;
45        self.out.write_all(&h).map_err(Error::Write)?;
46        self.out.write_all(data).map_err(Error::Write)?;
47        self.out.write_all(&[0u8; BLOCK][..pad]).map_err(Error::Write)?;
48        self.written += (BLOCK + data.len() + pad) as u64;
49        Ok(())
50    }
51
52    /// Ends the archive and returns the writer.
53    pub fn finish(mut self) -> Result<W> {
54        self.out.write_all(&[0u8; 2 * BLOCK]).map_err(Error::Write)?;
55        self.written += 2 * BLOCK as u64;
56        self.out.flush().map_err(Error::Write)?;
57        Ok(self.out)
58    }
59}
60
61/// `n` as zero-padded octal digits filling `field` but its last byte (a NUL).
62fn octal(field: &mut [u8], n: u64) {
63    let last = field.len() - 1;
64    let digits = format!("{n:0last$o}");
65    field[..last].copy_from_slice(digits.as_bytes());
66    field[last] = 0;
67}
68
69fn parse_octal(field: &[u8]) -> Option<u64> {
70    let text = std::str::from_utf8(field).ok()?;
71    let digits = text.trim_matches(|c: char| c == '\0' || c == ' ');
72    if digits.is_empty() { Some(0) } else { u64::from_str_radix(digits, 8).ok() }
73}
74
75/// Reads an archive's regular files in order, each into memory (at most `max` bytes: a bundle's
76/// entries are the manifest and chunks). Directory entries are skipped; any other kind (links,
77/// devices, extended headers) is refused.
78pub struct TarReader<R: Read> {
79    input: R,
80    done: bool,
81}
82
83impl<R: Read> TarReader<R> {
84    pub fn new(input: R) -> TarReader<R> {
85        TarReader { input, done: false }
86    }
87
88    /// The next file's name and contents, or None at the end of the archive.
89    pub fn next_entry(&mut self, max: u64) -> Result<Option<(String, Vec<u8>)>> {
90        loop {
91            if self.done {
92                return Ok(None);
93            }
94            let mut h = [0u8; BLOCK];
95            match read_full(&mut self.input, &mut h)? {
96                0 => return Err(Error::Tar("the archive ends without its end blocks".into())),
97                BLOCK => {}
98                _ => return Err(Error::Tar("the archive ends inside a header".into())),
99            }
100            if h.iter().all(|&b| b == 0) {
101                self.done = true;
102                return Ok(None);
103            }
104            let stored = parse_octal(&h[148..156]).ok_or_else(|| Error::Tar("bad header checksum field".into()))?;
105            let sum: u64 = h.iter().enumerate().map(|(i, &b)| if (148..156).contains(&i) { 32 } else { u64::from(b) }).sum();
106            if sum != stored {
107                return Err(Error::Tar("header checksum mismatch".into()));
108            }
109            let field = |r: std::ops::Range<usize>| {
110                let f = &h[r];
111                String::from_utf8_lossy(&f[..f.iter().position(|&b| b == 0).unwrap_or(f.len())]).into_owned()
112            };
113            let (name, prefix) = (field(0..100), field(345..500));
114            let name = if prefix.is_empty() { name } else { format!("{prefix}/{name}") };
115            let size = parse_octal(&h[124..136]).ok_or_else(|| Error::Tar(format!("{name}: bad size")))?;
116            let kind = h[156];
117            if kind == b'5' {
118                if size != 0 {
119                    return Err(Error::Tar(format!("{name}: a directory with data")));
120                }
121                continue;
122            }
123            if kind != b'0' && kind != 0 {
124                return Err(Error::Tar(format!("{name}: entry type `{}` (only regular files and directories)", kind as char)));
125            }
126            if size > max {
127                return Err(Error::Tar(format!("{name}: {size} bytes is more than {max}")));
128            }
129            let mut data = vec![0u8; size as usize];
130            if read_full(&mut self.input, &mut data)? != data.len() {
131                return Err(Error::Tar(format!("{name}: the archive ends inside it")));
132            }
133            let pad = (BLOCK - data.len() % BLOCK) % BLOCK;
134            let mut skip = [0u8; BLOCK];
135            if read_full(&mut self.input, &mut skip[..pad])? != pad {
136                return Err(Error::Tar(format!("{name}: the archive ends inside its padding")));
137            }
138            return Ok(Some((name, data)));
139        }
140    }
141}
142
143/// Reads until `buf` is full or the input ends; how many bytes it got.
144fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
145    let mut got = 0;
146    while got < buf.len() {
147        match r.read(&mut buf[got..]) {
148            Ok(0) => break,
149            Ok(n) => got += n,
150            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
151            Err(e) => return Err(Error::Read(e)),
152        }
153    }
154    Ok(got)
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn entries_round_trip_in_order_with_padding() {
163        let mut w = TarWriter::new(Vec::new());
164        w.entry("manifest.json", b"{}").expect("entry");
165        w.entry("chunks/ab/abcd", &[7u8; 1000]).expect("entry");
166        w.entry("empty", b"").expect("entry");
167        let written = w.written();
168        let bytes = w.finish().expect("finish");
169        assert_eq!(bytes.len() as u64, written + 2 * BLOCK as u64, "the end blocks come last");
170        assert_eq!(bytes.len() % BLOCK, 0);
171        let mut r = TarReader::new(bytes.as_slice());
172        assert_eq!(r.next_entry(1 << 20).expect("read"), Some(("manifest.json".into(), b"{}".to_vec())));
173        assert_eq!(r.next_entry(1 << 20).expect("read"), Some(("chunks/ab/abcd".into(), vec![7u8; 1000])));
174        assert_eq!(r.next_entry(1 << 20).expect("read"), Some(("empty".into(), Vec::new())));
175        assert_eq!(r.next_entry(1 << 20).expect("read"), None);
176    }
177
178    #[test]
179    fn damaged_or_foreign_archives_are_refused() {
180        let mut w = TarWriter::new(Vec::new());
181        w.entry("a", &[1u8; 10]).expect("entry");
182        let good = w.finish().expect("finish");
183        // A flipped byte in the header fails its checksum.
184        let mut bad = good.clone();
185        bad[0] = b'b';
186        assert!(TarReader::new(bad.as_slice()).next_entry(100).expect_err("checksum").to_string().contains("checksum"));
187        // Truncated inside the data, and with no end blocks.
188        assert!(TarReader::new(&good[..BLOCK + 5]).next_entry(100).is_err());
189        let mut r = TarReader::new(&good[..2 * BLOCK]);
190        r.next_entry(100).expect("first").expect("entry");
191        assert!(r.next_entry(100).is_err(), "no end blocks");
192        // More than the reader allows.
193        assert!(TarReader::new(good.as_slice()).next_entry(5).is_err());
194        // A symlink entry.
195        let mut link = good.clone();
196        link[156] = b'2';
197        link[148..156].fill(b' ');
198        let sum: u32 = link[..BLOCK].iter().map(|&b| u32::from(b)).sum();
199        link[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
200        assert!(TarReader::new(link.as_slice()).next_entry(100).expect_err("link").to_string().contains("entry type"));
201    }
202}