Skip to main content

hatchzip_core/archive/
resumable.rs

1//! Decoders that can stop, have their position recorded in the journal, and
2//! start again from that position in a later process. That is what lets the
3//! engine free the archive bytes behind a large file while it is still being
4//! extracted: once a position is durable, nothing before it is ever read
5//! again.
6//!
7//! Stored data can restart at any byte. Deflate can restart at any block
8//! boundary, the technique of zlib's `examples/zran.c`: a block boundary may
9//! fall inside a byte, so the position is kept in bits, and the decoder
10//! needs the 32 KiB of output before it, which back-references reach into.
11
12use std::ffi::CStr;
13use std::io::{Read, Seek, SeekFrom};
14
15use anyhow::{Context, Result, bail};
16use libz_rs_sys as z;
17
18use super::storage::Reader;
19use super::{Codec, Stream};
20
21/// How much output from just before a resume point a decoder needs to start
22/// there: the deflate window.
23pub const WINDOW: usize = 32 * 1024;
24
25const INPUT_BUF: usize = 1024 * 1024;
26
27pub struct Decoder {
28    inner: Inner,
29}
30
31enum Inner {
32    Stored(Stored),
33    Deflate(Inflate),
34}
35
36impl Decoder {
37    /// Starts decoding `stream` at `bit`, counted in bits from the start of
38    /// the archive: the start of the data, or a point an earlier run
39    /// recorded. `window` is the output just before that point, up to
40    /// [`WINDOW`] bytes.
41    pub fn new(reader: Reader, stream: &Stream, bit: u64, window: &[u8]) -> Result<Self> {
42        let end = stream.data_start + stream.packed;
43        if bit / 8 < stream.data_start || bit / 8 > end {
44            bail!("the journal's resume point lies outside the file's data");
45        }
46        let inner = match stream.codec {
47            Codec::Stored => {
48                if !bit.is_multiple_of(8) {
49                    bail!("the journal's resume point lies inside a byte of stored data");
50                }
51                Inner::Stored(Stored {
52                    reader,
53                    pos: bit / 8,
54                    end,
55                })
56            }
57            Codec::Deflate => Inner::Deflate(Inflate::new(reader, bit, end, window)?),
58        };
59        Ok(Self { inner })
60    }
61
62    /// Decodes into `buf`. Returns 0 only at the end of the data.
63    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
64        match &mut self.inner {
65            Inner::Stored(s) => s.read(buf),
66            Inner::Deflate(d) => d.read(buf),
67        }
68    }
69
70    /// Where decoding could restart, in bits from the start of the archive,
71    /// if it can be stopped right after the output handed out so far.
72    pub fn restart_point(&self) -> Option<u64> {
73        match &self.inner {
74            Inner::Stored(s) => Some(s.pos * 8),
75            Inner::Deflate(d) => d.restart_point(),
76        }
77    }
78}
79
80struct Stored {
81    reader: Reader,
82    pos: u64,
83    end: u64,
84}
85
86impl Stored {
87    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
88        let n = (self.end - self.pos).min(buf.len() as u64) as usize;
89        if n == 0 {
90            return Ok(0);
91        }
92        self.reader.seek(SeekFrom::Start(self.pos))?;
93        self.reader
94            .read_exact(&mut buf[..n])
95            .context("reading the archive")?;
96        self.pos += n as u64;
97        Ok(n)
98    }
99}
100
101/// A raw inflate over the archive that reports block boundaries.
102struct Inflate {
103    /// Boxed because zlib's state keeps a pointer back to it.
104    strm: Box<z::z_stream>,
105    reader: Reader,
106    input: Vec<u8>,
107    /// The next archive offset to read into `input`.
108    next_read: u64,
109    end: u64,
110    /// Archive offset of the first byte handed to zlib, and how many bytes
111    /// it has taken since. Counted here because zlib's own `total_in` is 32
112    /// bits on Windows.
113    fed_from: u64,
114    taken: u64,
115    /// `data_type` after the last call, which says whether zlib stopped
116    /// right after a block and how many bits it holds unread.
117    data_type: i32,
118    done: bool,
119}
120
121impl Inflate {
122    fn new(mut reader: Reader, bit: u64, end: u64, window: &[u8]) -> Result<Self> {
123        let byte = bit / 8;
124        let skip = (bit % 8) as u32;
125        // A point inside a byte: the bits below `skip` belong to the block
126        // before, the rest are fed in by hand.
127        let partial = if skip == 0 {
128            None
129        } else {
130            let mut b = [0u8];
131            reader.seek(SeekFrom::Start(byte))?;
132            reader.read_exact(&mut b).context("reading the archive")?;
133            Some(b[0] >> skip)
134        };
135        let start = if partial.is_some() { byte + 1 } else { byte };
136        let mut strm = Box::new(z::z_stream::default());
137        // Negative window bits: raw deflate, no zlib or gzip wrapper.
138        let ret = unsafe {
139            z::inflateInit2_(
140                &mut *strm,
141                -15,
142                z::zlibVersion(),
143                size_of::<z::z_stream>() as i32,
144            )
145        };
146        if ret != z::Z_OK {
147            bail!("starting the deflate decoder failed ({ret})");
148        }
149        // Constructed right away so that every error below still ends the
150        // decoder.
151        let mut me = Self {
152            strm,
153            reader,
154            input: vec![0; INPUT_BUF],
155            next_read: start,
156            end,
157            fed_from: start,
158            taken: 0,
159            data_type: 0,
160            done: false,
161        };
162        if let Some(bits) = partial {
163            let ret = unsafe { z::inflatePrime(&mut *me.strm, (8 - skip) as i32, i32::from(bits)) };
164            if ret != z::Z_OK {
165                bail!("resuming the deflate decoder failed ({ret})");
166            }
167        }
168        if !window.is_empty() {
169            let ret = unsafe {
170                z::inflateSetDictionary(&mut *me.strm, window.as_ptr(), window.len() as u32)
171            };
172            if ret != z::Z_OK {
173                bail!("resuming the deflate decoder failed ({ret})");
174            }
175        }
176        Ok(me)
177    }
178
179    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
180        if self.done || buf.is_empty() {
181            return Ok(0);
182        }
183        let len = buf.len().min(u32::MAX as usize);
184        let buf = &mut buf[..len];
185        loop {
186            if self.strm.avail_in == 0 && self.next_read < self.end {
187                let n = (self.end - self.next_read).min(self.input.len() as u64) as usize;
188                self.reader.seek(SeekFrom::Start(self.next_read))?;
189                self.reader
190                    .read_exact(&mut self.input[..n])
191                    .context("reading the archive")?;
192                self.next_read += n as u64;
193                self.strm.next_in = self.input.as_ptr();
194                self.strm.avail_in = n as u32;
195            }
196            let avail_in = self.strm.avail_in;
197            self.strm.next_out = buf.as_mut_ptr();
198            self.strm.avail_out = buf.len() as u32;
199            // Z_BLOCK makes inflate return at every block boundary, the only
200            // places a deflate stream can be resumed from.
201            let ret = unsafe { z::inflate(&mut *self.strm, z::Z_BLOCK) };
202            self.taken += u64::from(avail_in - self.strm.avail_in);
203            let produced = buf.len() - self.strm.avail_out as usize;
204            self.data_type = self.strm.data_type;
205            match ret {
206                z::Z_STREAM_END => {
207                    self.done = true;
208                    return Ok(produced);
209                }
210                z::Z_OK => {}
211                z::Z_BUF_ERROR if self.strm.avail_in == 0 && self.next_read >= self.end => {
212                    bail!("its compressed data ends early");
213                }
214                z::Z_BUF_ERROR => {}
215                _ => bail!("its compressed data is damaged ({})", self.message()),
216            }
217            if produced > 0 {
218                return Ok(produced);
219            }
220        }
221    }
222
223    fn restart_point(&self) -> Option<u64> {
224        // 128: stopped right after a block ended. 64: that was the last one,
225        // so there is nothing to restart into.
226        if self.done || self.data_type & 128 == 0 || self.data_type & 64 != 0 {
227            return None;
228        }
229        // The low bits count bits zlib took from the input but hasn't used:
230        // the tail end of the bytes it took last.
231        let held = (self.data_type & 63) as u64;
232        Some((self.fed_from + self.taken) * 8 - held)
233    }
234
235    fn message(&self) -> String {
236        if self.strm.msg.is_null() {
237            return "unknown error".into();
238        }
239        unsafe { CStr::from_ptr(self.strm.msg) }
240            .to_string_lossy()
241            .into_owned()
242    }
243}
244
245impl Drop for Inflate {
246    fn drop(&mut self) {
247        unsafe {
248            z::inflateEnd(&mut *self.strm);
249        }
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate::archive::storage::Storage;
257
258    /// Text-like data: matches reach back across block boundaries, so a
259    /// wrong window or bit position can't go unnoticed.
260    fn text(len: usize) -> Vec<u8> {
261        let words: Vec<&[u8]> = b"the archive frees its bytes behind the decoder while every \
262            resume point stays durable and nothing is lost 0123456789 zran inflate prime"
263            .split(|b| *b == b' ')
264            .collect();
265        let mut x: u64 = 0x2545_F491_4F6C_DD1D;
266        let mut out = Vec::with_capacity(len + 16);
267        while out.len() < len {
268            x ^= x << 13;
269            x ^= x >> 7;
270            x ^= x << 17;
271            out.extend_from_slice(words[(x % words.len() as u64) as usize]);
272            out.push(if x & 0x700 == 0 { b'\n' } else { b' ' });
273            if x & 0xF000 == 0 {
274                // Bursts of noise force stored blocks in between.
275                out.extend((0..300).map(|i| (x >> (i % 56)) as u8));
276            }
277        }
278        out.truncate(len);
279        out
280    }
281
282    fn deflate_raw(data: &[u8], level: i32) -> Vec<u8> {
283        let mut strm = z::z_stream::default();
284        unsafe {
285            let ret = z::deflateInit2_(
286                &mut strm,
287                level,
288                z::Z_DEFLATED,
289                -15,
290                8,
291                z::Z_DEFAULT_STRATEGY,
292                z::zlibVersion(),
293                size_of::<z::z_stream>() as i32,
294            );
295            assert_eq!(ret, z::Z_OK);
296            let mut out = vec![0u8; data.len() + data.len() / 100 + 1024];
297            strm.next_in = data.as_ptr();
298            strm.avail_in = data.len() as u32;
299            strm.next_out = out.as_mut_ptr();
300            strm.avail_out = out.len() as u32;
301            assert_eq!(z::deflate(&mut strm, z::Z_FINISH), z::Z_STREAM_END);
302            out.truncate(out.len() - strm.avail_out as usize);
303            z::deflateEnd(&mut strm);
304            out
305        }
306    }
307
308    fn decode_all(d: &mut Decoder) -> Vec<u8> {
309        let mut out = Vec::new();
310        let mut buf = vec![0; 64 * 1024];
311        loop {
312            let n = d.read(&mut buf).unwrap();
313            if n == 0 {
314                return out;
315            }
316            out.extend_from_slice(&buf[..n]);
317        }
318    }
319
320    /// Records every restart point of a deflate stream, then starts a fresh
321    /// decoder at each one, as a resumed run does, and checks it produces
322    /// exactly the rest of the data.
323    #[test]
324    fn deflate_resumes_from_every_block_boundary() {
325        let dir = std::env::temp_dir().join(format!("hatchzip-inflate-{}", std::process::id()));
326        fs_err(std::fs::create_dir_all(&dir));
327        let data = text(6_000_000);
328        for level in [6, 9, 1] {
329            let packed = deflate_raw(&data, level);
330            // Something in front, so offsets are absolute as in a real archive.
331            let prefix = 777u64;
332            let path = dir.join(format!("stream-{level}"));
333            let mut file = vec![0xEE; prefix as usize];
334            file.extend_from_slice(&packed);
335            file.extend_from_slice(b"trailing bytes that are not deflate");
336            std::fs::write(&path, &file).unwrap();
337            let storage = Storage::open(&path, false).unwrap();
338            let stream = Stream {
339                data_start: prefix,
340                packed: packed.len() as u64,
341                codec: Codec::Deflate,
342                crc: None,
343            };
344
345            let mut d = Decoder::new(storage.reader(None), &stream, prefix * 8, &[]).unwrap();
346            let mut points = Vec::new();
347            let mut written = 0;
348            let mut buf = vec![0; 100_000];
349            loop {
350                let n = d.read(&mut buf).unwrap();
351                if n == 0 {
352                    break;
353                }
354                assert_eq!(buf[..n], data[written..written + n]);
355                written += n;
356                if let Some(bit) = d.restart_point() {
357                    points.push((bit, written));
358                }
359            }
360            assert_eq!(written, data.len());
361            if level == 1 {
362                // zlib-rs, like zlib-ng, writes level 1 as one single block,
363                // which has no point to resume from but its start.
364                assert!(points.is_empty(), "level 1 grew {} points", points.len());
365                continue;
366            }
367            assert!(
368                points.len() >= 10,
369                "level {level}: only {} points",
370                points.len()
371            );
372            assert!(
373                points.iter().any(|(bit, _)| bit % 8 != 0),
374                "level {level}: no point inside a byte"
375            );
376
377            for (bit, at) in points.iter().copied() {
378                let window = &data[at.saturating_sub(WINDOW)..at];
379                let mut d = Decoder::new(storage.reader(None), &stream, bit, window).unwrap();
380                assert!(
381                    decode_all(&mut d) == data[at..],
382                    "level {level}: resuming at bit {bit} (output {at}) went wrong"
383                );
384            }
385        }
386        std::fs::remove_dir_all(&dir).unwrap();
387    }
388
389    fn fs_err(r: std::io::Result<()>) {
390        r.unwrap()
391    }
392
393    #[test]
394    fn truncated_and_damaged_deflate_is_an_error() {
395        let dir = std::env::temp_dir().join(format!("hatchzip-damaged-{}", std::process::id()));
396        std::fs::create_dir_all(&dir).unwrap();
397        let data = text(500_000);
398        let packed = deflate_raw(&data, 6);
399        let path = dir.join("stream");
400        std::fs::write(&path, &packed).unwrap();
401        let storage = Storage::open(&path, false).unwrap();
402        let short = Stream {
403            data_start: 0,
404            packed: packed.len() as u64 / 2,
405            codec: Codec::Deflate,
406            crc: None,
407        };
408        let mut d = Decoder::new(storage.reader(None), &short, 0, &[]).unwrap();
409        let mut buf = vec![0; 1 << 16];
410        let err = loop {
411            match d.read(&mut buf) {
412                Ok(0) => panic!("a cut stream decoded to the end"),
413                Ok(_) => {}
414                Err(e) => break e,
415            }
416        };
417        assert!(format!("{err:#}").contains("ends early"), "{err:#}");
418        std::fs::remove_dir_all(&dir).unwrap();
419    }
420}