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//!
12//! [`Gzip`] wraps the same raw inflate in gzip members: it parses their
13//! headers, checks each trailer's CRC-32 and length, and can also restart at
14//! the start of any member, where nothing from before is needed.
15
16use std::ffi::CStr;
17use std::io::{Read, Seek, SeekFrom};
18
19use anyhow::{Context, Result, anyhow, bail};
20use libz_rs_sys as z;
21
22use super::storage::Reader;
23use super::{Codec, Stream};
24
25/// How much output from just before a resume point a decoder needs to start
26/// there: the deflate window.
27pub const WINDOW: usize = 32 * 1024;
28
29const INPUT_BUF: usize = 1024 * 1024;
30
31pub struct Decoder {
32    inner: Inner,
33}
34
35enum Inner {
36    Stored(Stored),
37    Deflate(Inflate),
38}
39
40impl Decoder {
41    /// Starts decoding `stream` at `bit`, counted in bits from the start of
42    /// the archive: the start of the data, or a point an earlier run
43    /// recorded. `window` is the output just before that point, up to
44    /// [`WINDOW`] bytes.
45    pub fn new(reader: Reader, stream: &Stream, bit: u64, window: &[u8]) -> Result<Self> {
46        let end = stream.data_start + stream.packed;
47        if bit / 8 < stream.data_start || bit / 8 > end {
48            bail!("the journal's resume point lies outside the file's data");
49        }
50        let inner = match stream.codec {
51            Codec::Stored => {
52                if !bit.is_multiple_of(8) {
53                    bail!("the journal's resume point lies inside a byte of stored data");
54                }
55                Inner::Stored(Stored {
56                    reader,
57                    pos: bit / 8,
58                    end,
59                })
60            }
61            Codec::Deflate => Inner::Deflate(Inflate::new(reader, bit, end, window, INPUT_BUF)?),
62        };
63        Ok(Self { inner })
64    }
65
66    /// Decodes into `buf`. Returns 0 only at the end of the data.
67    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
68        match &mut self.inner {
69            Inner::Stored(s) => s.read(buf),
70            Inner::Deflate(d) => d.read(buf),
71        }
72    }
73
74    /// Where decoding could restart, in bits from the start of the archive,
75    /// if it can be stopped right after the output handed out so far.
76    pub fn restart_point(&self) -> Option<u64> {
77        match &self.inner {
78            Inner::Stored(s) => Some(s.pos * 8),
79            Inner::Deflate(d) => d.restart_point(),
80        }
81    }
82}
83
84struct Stored {
85    reader: Reader,
86    pos: u64,
87    end: u64,
88}
89
90impl Stored {
91    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
92        let n = (self.end - self.pos).min(buf.len() as u64) as usize;
93        if n == 0 {
94            return Ok(0);
95        }
96        self.reader.seek(SeekFrom::Start(self.pos))?;
97        self.reader
98            .read_exact(&mut buf[..n])
99            .context("reading the archive")?;
100        self.pos += n as u64;
101        Ok(n)
102    }
103}
104
105/// A raw inflate over the archive that reports block boundaries.
106struct Inflate {
107    /// Boxed because zlib's state keeps a pointer back to it.
108    strm: Box<z::z_stream>,
109    reader: Reader,
110    input: Vec<u8>,
111    /// The next archive offset to read into `input`.
112    next_read: u64,
113    end: u64,
114    /// Archive offset of the first byte handed to zlib, and how many bytes
115    /// it has taken since. Counted here because zlib's own `total_in` is 32
116    /// bits on Windows.
117    fed_from: u64,
118    taken: u64,
119    /// `data_type` after the last call, which says whether zlib stopped
120    /// right after a block and how many bits it holds unread.
121    data_type: i32,
122    done: bool,
123}
124
125impl Inflate {
126    /// `input` is the size of the input buffer: [`INPUT_BUF`], except in
127    /// tests that make every boundary fall across a refill.
128    fn new(mut reader: Reader, bit: u64, end: u64, window: &[u8], input: usize) -> Result<Self> {
129        let byte = bit / 8;
130        let skip = (bit % 8) as u32;
131        // A point inside a byte: the bits below `skip` belong to the block
132        // before, the rest are fed in by hand.
133        let partial = if skip == 0 {
134            None
135        } else {
136            let mut b = [0u8];
137            reader.seek(SeekFrom::Start(byte))?;
138            reader.read_exact(&mut b).context("reading the archive")?;
139            Some(b[0] >> skip)
140        };
141        let start = if partial.is_some() { byte + 1 } else { byte };
142        let mut strm = Box::new(z::z_stream::default());
143        // Negative window bits: raw deflate, no zlib or gzip wrapper.
144        let ret = unsafe {
145            z::inflateInit2_(
146                &mut *strm,
147                -15,
148                z::zlibVersion(),
149                size_of::<z::z_stream>() as i32,
150            )
151        };
152        if ret != z::Z_OK {
153            bail!("starting the deflate decoder failed ({ret})");
154        }
155        // Constructed right away so that every error below still ends the
156        // decoder.
157        let mut me = Self {
158            strm,
159            reader,
160            input: vec![0; input],
161            next_read: start,
162            end,
163            fed_from: start,
164            taken: 0,
165            data_type: 0,
166            done: false,
167        };
168        if let Some(bits) = partial {
169            let ret = unsafe { z::inflatePrime(&mut *me.strm, (8 - skip) as i32, i32::from(bits)) };
170            if ret != z::Z_OK {
171                bail!("resuming the deflate decoder failed ({ret})");
172            }
173        }
174        if !window.is_empty() {
175            let ret = unsafe {
176                z::inflateSetDictionary(&mut *me.strm, window.as_ptr(), window.len() as u32)
177            };
178            if ret != z::Z_OK {
179                bail!("resuming the deflate decoder failed ({ret})");
180            }
181        }
182        Ok(me)
183    }
184
185    /// Fills the input buffer if zlib has taken all of it.
186    fn refill(&mut self) -> Result<()> {
187        if self.strm.avail_in == 0 && self.next_read < self.end {
188            let n = (self.end - self.next_read).min(self.input.len() as u64) as usize;
189            self.reader.seek(SeekFrom::Start(self.next_read))?;
190            self.reader
191                .read_exact(&mut self.input[..n])
192                .context("reading the archive")?;
193            self.next_read += n as u64;
194            self.strm.next_in = self.input.as_ptr();
195            self.strm.avail_in = n as u32;
196        }
197        Ok(())
198    }
199
200    /// The archive offset of the next byte zlib has not taken.
201    fn pos(&self) -> u64 {
202        self.fed_from + self.taken
203    }
204
205    /// Takes one byte of input past zlib, for the gzip framing between
206    /// deflate streams. `None` at the end of the archive.
207    fn raw_byte(&mut self) -> Result<Option<u8>> {
208        self.refill()?;
209        if self.strm.avail_in == 0 {
210            return Ok(None);
211        }
212        // SAFETY: `avail_in` bytes from `next_in` lie inside `self.input`.
213        let b = unsafe { *self.strm.next_in };
214        self.strm.next_in = unsafe { self.strm.next_in.add(1) };
215        self.strm.avail_in -= 1;
216        self.taken += 1;
217        Ok(Some(b))
218    }
219
220    /// After the end of a deflate stream: hands back the whole bytes zlib
221    /// pulled into its bit buffer without using them, so that [`pos`] is the
222    /// first byte after the deflate data.
223    ///
224    /// [`pos`]: Self::pos
225    fn give_back_unused(&mut self) {
226        // zlib skips to a byte boundary after the last block, so what it
227        // holds is whole bytes. zlib-rs was seen to hold none, at every
228        // member end of the unit tests with buffers down to one byte; zlib
229        // may, so this stays.
230        let unused = (self.data_type & 63) as u64 / 8;
231        // SAFETY: `next_in` points into `self.input`.
232        let in_buffer = unsafe { self.strm.next_in.offset_from(self.input.as_ptr()) } as u64;
233        if unused <= in_buffer {
234            self.strm.next_in = unsafe { self.strm.next_in.sub(unused as usize) };
235            self.strm.avail_in += unused as u32;
236            self.taken -= unused;
237        } else {
238            // They came from an earlier fill of the buffer: read them again.
239            let at = self.pos() - unused;
240            self.fed_from = at;
241            self.taken = 0;
242            self.next_read = at;
243            self.strm.avail_in = 0;
244        }
245    }
246
247    /// Starts a new raw deflate stream at [`pos`](Self::pos), keeping the
248    /// input already read.
249    fn restart(&mut self) -> Result<()> {
250        let ret = unsafe { z::inflateReset(&mut *self.strm) };
251        if ret != z::Z_OK {
252            bail!("restarting the deflate decoder failed ({ret})");
253        }
254        self.done = false;
255        self.data_type = 0;
256        Ok(())
257    }
258
259    /// The output just before the current position that the rest of the
260    /// stream may refer back to, up to [`WINDOW`] bytes.
261    fn window(&self) -> Result<Vec<u8>> {
262        let mut window = vec![0; WINDOW];
263        let mut len = 0u32;
264        // SAFETY: the buffer holds WINDOW bytes, the most zlib ever copies.
265        let ret = unsafe { z::inflateGetDictionary(&*self.strm, window.as_mut_ptr(), &mut len) };
266        if ret != z::Z_OK || len as usize > WINDOW {
267            bail!("reading the deflate window failed ({ret})");
268        }
269        window.truncate(len as usize);
270        Ok(window)
271    }
272
273    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
274        if self.done || buf.is_empty() {
275            return Ok(0);
276        }
277        let len = buf.len().min(u32::MAX as usize);
278        let buf = &mut buf[..len];
279        loop {
280            self.refill()?;
281            let avail_in = self.strm.avail_in;
282            self.strm.next_out = buf.as_mut_ptr();
283            self.strm.avail_out = buf.len() as u32;
284            // Z_BLOCK makes inflate return at every block boundary, the only
285            // places a deflate stream can be resumed from.
286            let ret = unsafe { z::inflate(&mut *self.strm, z::Z_BLOCK) };
287            self.taken += u64::from(avail_in - self.strm.avail_in);
288            let produced = buf.len() - self.strm.avail_out as usize;
289            self.data_type = self.strm.data_type;
290            match ret {
291                z::Z_STREAM_END => {
292                    self.done = true;
293                    return Ok(produced);
294                }
295                z::Z_OK => {}
296                z::Z_BUF_ERROR if self.strm.avail_in == 0 && self.next_read >= self.end => {
297                    bail!("its compressed data ends early");
298                }
299                z::Z_BUF_ERROR => {}
300                _ => bail!("its compressed data is damaged ({})", self.message()),
301            }
302            if produced > 0 {
303                if self.data_type & 192 == 192 {
304                    // The last block just ended. zlib reports the end of the
305                    // stream on the next call, which outputs nothing; taking
306                    // it now lets a gzip member end on this read, so the
307                    // start of the next one is a point to resume from.
308                    self.finish()?;
309                }
310                return Ok(produced);
311            }
312        }
313    }
314
315    fn finish(&mut self) -> Result<()> {
316        let mut scratch = [0u8; 1];
317        let avail_in = self.strm.avail_in;
318        self.strm.next_out = scratch.as_mut_ptr();
319        self.strm.avail_out = 1;
320        let ret = unsafe { z::inflate(&mut *self.strm, z::Z_BLOCK) };
321        self.taken += u64::from(avail_in - self.strm.avail_in);
322        self.data_type = self.strm.data_type;
323        match ret {
324            z::Z_STREAM_END if self.strm.avail_out == 1 => {
325                self.done = true;
326                Ok(())
327            }
328            _ => bail!("its compressed data is damaged ({})", self.message()),
329        }
330    }
331
332    fn restart_point(&self) -> Option<u64> {
333        // 128: stopped right after a block ended. 64: that was the last one,
334        // so there is nothing to restart into.
335        if self.done || self.data_type & 128 == 0 || self.data_type & 64 != 0 {
336            return None;
337        }
338        // The low bits count bits zlib took from the input but hasn't used:
339        // the tail end of the bytes it took last.
340        let held = (self.data_type & 63) as u64;
341        Some((self.fed_from + self.taken) * 8 - held)
342    }
343
344    fn message(&self) -> String {
345        if self.strm.msg.is_null() {
346            return "unknown error".into();
347        }
348        unsafe { CStr::from_ptr(self.strm.msg) }
349            .to_string_lossy()
350            .into_owned()
351    }
352}
353
354impl Drop for Inflate {
355    fn drop(&mut self) {
356        unsafe {
357            z::inflateEnd(&mut *self.strm);
358        }
359    }
360}
361
362/// Where a gzip stream can be decoded from again.
363#[derive(Clone, Debug, PartialEq, Eq)]
364pub struct GzPoint {
365    /// In bits from the start of the archive.
366    pub bit: u64,
367    /// `bit` is where a member's header begins, so nothing from before is
368    /// needed. Otherwise it is a deflate block boundary inside a member.
369    pub member_start: bool,
370    /// CRC-32 and length of the member's output before the point, which its
371    /// trailer is checked against.
372    pub crc: u32,
373    pub len: u64,
374    /// The member's output just before the point, up to [`WINDOW`] bytes.
375    pub window: Vec<u8>,
376}
377
378impl GzPoint {
379    pub fn start() -> Self {
380        Self {
381            bit: 0,
382            member_start: true,
383            crc: 0,
384            len: 0,
385            window: Vec::new(),
386        }
387    }
388}
389
390/// A gzip stream of one or more members (RFC 1952), decoded from the front
391/// or from a [`GzPoint`]. Each member's CRC-32 and length are checked against
392/// its trailer as it ends; `read` returns 0 only once every member is
393/// verified.
394pub struct Gzip {
395    z: Inflate,
396    /// Inside a member's deflate data, rather than before a header.
397    in_member: bool,
398    crc: crc32fast::Hasher,
399    len: u64,
400    done: bool,
401}
402
403impl Gzip {
404    /// Decodes the gzip stream that fills the archive up to `end`, from `at`.
405    pub fn new(reader: Reader, end: u64, at: &GzPoint) -> Result<Self> {
406        Self::with_input(reader, end, at, INPUT_BUF)
407    }
408
409    fn with_input(reader: Reader, end: u64, at: &GzPoint, input: usize) -> Result<Self> {
410        if at.bit / 8 > end || (at.member_start && !at.bit.is_multiple_of(8)) {
411            bail!("the journal's resume point lies outside the compressed data");
412        }
413        let window: &[u8] = if at.member_start { &[] } else { &at.window };
414        Ok(Self {
415            z: Inflate::new(reader, at.bit, end, window, input)?,
416            in_member: !at.member_start,
417            crc: crc32fast::Hasher::new_with_initial(at.crc),
418            len: at.len,
419            done: false,
420        })
421    }
422
423    /// Decodes into `buf`. Returns 0 only at the end of the stream.
424    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
425        if buf.is_empty() {
426            return Ok(0);
427        }
428        loop {
429            if self.done {
430                return Ok(0);
431            }
432            if !self.in_member {
433                if !self.header()? {
434                    self.done = true;
435                    return Ok(0);
436                }
437                self.in_member = true;
438                self.crc = crc32fast::Hasher::new();
439                self.len = 0;
440            }
441            let n = self.z.read(buf)?;
442            self.crc.update(&buf[..n]);
443            self.len += n as u64;
444            if self.z.done {
445                self.z.give_back_unused();
446                self.trailer()?;
447                self.z.restart()?;
448                self.in_member = false;
449            }
450            if n > 0 {
451                return Ok(n);
452            }
453        }
454    }
455
456    /// Where decoding could restart, in bits, if it is stopped right after
457    /// the output handed out so far, and whether that is a member's start.
458    /// Cheap; [`restart_point`](Self::restart_point) adds the window.
459    pub fn restart_bit(&self) -> Option<(u64, bool)> {
460        if self.done {
461            None
462        } else if !self.in_member {
463            Some((self.z.pos() * 8, true))
464        } else {
465            self.z.restart_point().map(|bit| (bit, false))
466        }
467    }
468
469    pub fn restart_point(&self) -> Result<Option<GzPoint>> {
470        let Some((bit, member_start)) = self.restart_bit() else {
471            return Ok(None);
472        };
473        if member_start {
474            return Ok(Some(GzPoint {
475                bit,
476                ..GzPoint::start()
477            }));
478        }
479        Ok(Some(GzPoint {
480            bit,
481            member_start,
482            crc: self.crc.clone().finalize(),
483            len: self.len,
484            window: self.z.window()?,
485        }))
486    }
487
488    fn byte(&mut self) -> Result<u8> {
489        self.z
490            .raw_byte()?
491            .ok_or_else(|| anyhow!("the compressed data ends early"))
492    }
493
494    /// Parses a member header. Returns false at the end of the stream: the
495    /// end of the archive, or zeros up to it, which some tools pad with.
496    fn header(&mut self) -> Result<bool> {
497        let at = self.z.pos();
498        let Some(first) = self.z.raw_byte()? else {
499            return Ok(false);
500        };
501        if first == 0 {
502            while let Some(b) = self.z.raw_byte()? {
503                if b != 0 {
504                    bail!("unexpected data follows the compressed data at byte {at}");
505                }
506            }
507            return Ok(false);
508        }
509        let unexpected = || anyhow!("unexpected data follows the compressed data at byte {at}");
510        if first != 0x1F {
511            return Err(unexpected());
512        }
513        let mut head = vec![first];
514        // The second magic byte, then the method, which is always deflate.
515        for want in [0x8B, 8] {
516            match self.z.raw_byte()? {
517                Some(b) if b == want => head.push(b),
518                _ => return Err(unexpected()),
519            }
520        }
521        for _ in 3..10 {
522            head.push(self.byte()?);
523        }
524        let flags = head[3];
525        if flags & 0xE0 != 0 {
526            bail!("the gzip member at byte {at} uses header flags that are not defined");
527        }
528        if flags & 4 != 0 {
529            let (a, b) = (self.byte()?, self.byte()?);
530            head.extend([a, b]);
531            for _ in 0..u16::from_le_bytes([a, b]) {
532                let b = self.byte()?;
533                head.push(b);
534            }
535        }
536        // The file name, then the comment, each ending in a zero byte.
537        for flag in [8, 16] {
538            if flags & flag != 0 {
539                loop {
540                    let b = self.byte()?;
541                    head.push(b);
542                    if b == 0 {
543                        break;
544                    }
545                }
546            }
547        }
548        if flags & 2 != 0 {
549            let check = u16::from_le_bytes([self.byte()?, self.byte()?]);
550            if check != crc32fast::hash(&head) as u16 {
551                bail!("the gzip member at byte {at} has a damaged header (CRC mismatch)");
552            }
553        }
554        Ok(true)
555    }
556
557    fn trailer(&mut self) -> Result<()> {
558        let mut t = [0u8; 8];
559        for b in &mut t {
560            *b = self.byte()?;
561        }
562        if u32::from_le_bytes([t[0], t[1], t[2], t[3]]) != self.crc.clone().finalize() {
563            bail!("the decompressed data is damaged (CRC mismatch)");
564        }
565        // ISIZE is the length modulo 2^32.
566        if u32::from_le_bytes([t[4], t[5], t[6], t[7]]) != self.len as u32 {
567            bail!("the decompressed data is damaged (length mismatch)");
568        }
569        Ok(())
570    }
571}
572
573#[cfg(test)]
574mod tests {
575    use super::*;
576    use crate::archive::storage::Storage;
577
578    /// Text-like data: matches reach back across block boundaries, so a
579    /// wrong window or bit position can't go unnoticed.
580    fn text(len: usize) -> Vec<u8> {
581        let words: Vec<&[u8]> = b"the archive frees its bytes behind the decoder while every \
582            resume point stays durable and nothing is lost 0123456789 zran inflate prime"
583            .split(|b| *b == b' ')
584            .collect();
585        let mut x: u64 = 0x2545_F491_4F6C_DD1D;
586        let mut out = Vec::with_capacity(len + 16);
587        while out.len() < len {
588            x ^= x << 13;
589            x ^= x >> 7;
590            x ^= x << 17;
591            out.extend_from_slice(words[(x % words.len() as u64) as usize]);
592            out.push(if x & 0x700 == 0 { b'\n' } else { b' ' });
593            if x & 0xF000 == 0 {
594                // Bursts of noise force stored blocks in between.
595                out.extend((0..300).map(|i| (x >> (i % 56)) as u8));
596            }
597        }
598        out.truncate(len);
599        out
600    }
601
602    fn deflate_raw(data: &[u8], level: i32) -> Vec<u8> {
603        let mut strm = z::z_stream::default();
604        unsafe {
605            let ret = z::deflateInit2_(
606                &mut strm,
607                level,
608                z::Z_DEFLATED,
609                -15,
610                8,
611                z::Z_DEFAULT_STRATEGY,
612                z::zlibVersion(),
613                size_of::<z::z_stream>() as i32,
614            );
615            assert_eq!(ret, z::Z_OK);
616            let mut out = vec![0u8; data.len() + data.len() / 100 + 1024];
617            strm.next_in = data.as_ptr();
618            strm.avail_in = data.len() as u32;
619            strm.next_out = out.as_mut_ptr();
620            strm.avail_out = out.len() as u32;
621            assert_eq!(z::deflate(&mut strm, z::Z_FINISH), z::Z_STREAM_END);
622            out.truncate(out.len() - strm.avail_out as usize);
623            z::deflateEnd(&mut strm);
624            out
625        }
626    }
627
628    fn decode_all(d: &mut Decoder) -> Vec<u8> {
629        let mut out = Vec::new();
630        let mut buf = vec![0; 64 * 1024];
631        loop {
632            let n = d.read(&mut buf).unwrap();
633            if n == 0 {
634                return out;
635            }
636            out.extend_from_slice(&buf[..n]);
637        }
638    }
639
640    /// Records every restart point of a deflate stream, then starts a fresh
641    /// decoder at each one, as a resumed run does, and checks it produces
642    /// exactly the rest of the data.
643    #[test]
644    fn deflate_resumes_from_every_block_boundary() {
645        let dir = std::env::temp_dir().join(format!("hatchzip-inflate-{}", std::process::id()));
646        fs_err(std::fs::create_dir_all(&dir));
647        let data = text(6_000_000);
648        for level in [6, 9, 1] {
649            let packed = deflate_raw(&data, level);
650            // Something in front, so offsets are absolute as in a real archive.
651            let prefix = 777u64;
652            let path = dir.join(format!("stream-{level}"));
653            let mut file = vec![0xEE; prefix as usize];
654            file.extend_from_slice(&packed);
655            file.extend_from_slice(b"trailing bytes that are not deflate");
656            std::fs::write(&path, &file).unwrap();
657            let storage = Storage::open(&path, false).unwrap();
658            let stream = Stream {
659                data_start: prefix,
660                packed: packed.len() as u64,
661                codec: Codec::Deflate,
662                crc: None,
663            };
664
665            let mut d = Decoder::new(storage.reader(None), &stream, prefix * 8, &[]).unwrap();
666            let mut points = Vec::new();
667            let mut written = 0;
668            let mut buf = vec![0; 100_000];
669            loop {
670                let n = d.read(&mut buf).unwrap();
671                if n == 0 {
672                    break;
673                }
674                assert_eq!(buf[..n], data[written..written + n]);
675                written += n;
676                if let Some(bit) = d.restart_point() {
677                    points.push((bit, written));
678                }
679            }
680            assert_eq!(written, data.len());
681            if level == 1 {
682                // zlib-rs, like zlib-ng, writes level 1 as one single block,
683                // which has no point to resume from but its start.
684                assert!(points.is_empty(), "level 1 grew {} points", points.len());
685                continue;
686            }
687            assert!(
688                points.len() >= 10,
689                "level {level}: only {} points",
690                points.len()
691            );
692            assert!(
693                points.iter().any(|(bit, _)| bit % 8 != 0),
694                "level {level}: no point inside a byte"
695            );
696
697            for (bit, at) in points.iter().copied() {
698                let window = &data[at.saturating_sub(WINDOW)..at];
699                let mut d = Decoder::new(storage.reader(None), &stream, bit, window).unwrap();
700                assert!(
701                    decode_all(&mut d) == data[at..],
702                    "level {level}: resuming at bit {bit} (output {at}) went wrong"
703                );
704            }
705        }
706        std::fs::remove_dir_all(&dir).unwrap();
707    }
708
709    fn fs_err(r: std::io::Result<()>) {
710        r.unwrap()
711    }
712
713    #[test]
714    fn truncated_and_damaged_deflate_is_an_error() {
715        let dir = std::env::temp_dir().join(format!("hatchzip-damaged-{}", std::process::id()));
716        std::fs::create_dir_all(&dir).unwrap();
717        let data = text(500_000);
718        let packed = deflate_raw(&data, 6);
719        let path = dir.join("stream");
720        std::fs::write(&path, &packed).unwrap();
721        let storage = Storage::open(&path, false).unwrap();
722        let short = Stream {
723            data_start: 0,
724            packed: packed.len() as u64 / 2,
725            codec: Codec::Deflate,
726            crc: None,
727        };
728        let mut d = Decoder::new(storage.reader(None), &short, 0, &[]).unwrap();
729        let mut buf = vec![0; 1 << 16];
730        let err = loop {
731            match d.read(&mut buf) {
732                Ok(0) => panic!("a cut stream decoded to the end"),
733                Ok(_) => {}
734                Err(e) => break e,
735            }
736        };
737        assert!(format!("{err:#}").contains("ends early"), "{err:#}");
738        std::fs::remove_dir_all(&dir).unwrap();
739    }
740
741    /// One gzip member, with the optional header fields `flags` asks for.
742    fn gzip_member(data: &[u8], level: i32, flags: u8) -> Vec<u8> {
743        let mut head = vec![0x1F, 0x8B, 8, flags, 1, 2, 3, 4, 0, 3];
744        if flags & 4 != 0 {
745            head.extend(5u16.to_le_bytes());
746            head.extend(b"extra");
747        }
748        if flags & 8 != 0 {
749            head.extend(b"name.tar\0");
750        }
751        if flags & 16 != 0 {
752            head.extend(b"a comment\0");
753        }
754        if flags & 2 != 0 {
755            let check = crc32fast::hash(&head) as u16;
756            head.extend(check.to_le_bytes());
757        }
758        head.extend(deflate_raw(data, level));
759        head.extend(crc32fast::hash(data).to_le_bytes());
760        head.extend((data.len() as u32).to_le_bytes());
761        head
762    }
763
764    fn gzip_decode_all(g: &mut Gzip) -> Result<Vec<u8>> {
765        let mut out = Vec::new();
766        let mut buf = vec![0; 64 * 1024];
767        loop {
768            let n = g.read(&mut buf)?;
769            if n == 0 {
770                return Ok(out);
771            }
772            out.extend_from_slice(&buf[..n]);
773        }
774    }
775
776    fn open_gzip(path: &std::path::Path, at: &GzPoint) -> Gzip {
777        let storage = Storage::open(path, false).unwrap();
778        let len = storage.original_len();
779        Gzip::new(storage.reader(None), len, at).unwrap()
780    }
781
782    /// A multi-member stream, with every optional header field, an empty
783    /// member and zero padding at the end: decoded whole, then resumed from
784    /// every point it reports, member starts included, with the CRC-32 and
785    /// length checks carried across the resume.
786    #[test]
787    fn gzip_resumes_from_every_point_across_members() {
788        let dir = std::env::temp_dir().join(format!("hatchzip-gzip-{}", std::process::id()));
789        std::fs::create_dir_all(&dir).unwrap();
790        let data = text(3_000_000);
791        let mut file = gzip_member(&data[..1_000_000], 6, 8);
792        file.extend(gzip_member(&[], 6, 0));
793        file.extend(gzip_member(&data[1_000_000..1_700_000], 9, 2 | 4 | 16));
794        file.extend(gzip_member(&data[1_700_000..1_700_100], 6, 0));
795        file.extend(gzip_member(&data[1_700_100..], 6, 0));
796        file.extend([0u8; 1000]);
797        let path = dir.join("multi.gz");
798        std::fs::write(&path, &file).unwrap();
799
800        let mut g = open_gzip(&path, &GzPoint::start());
801        let mut points = Vec::new();
802        let mut written = 0;
803        let mut buf = vec![0; 100_000];
804        loop {
805            let n = g.read(&mut buf).unwrap();
806            if n == 0 {
807                break;
808            }
809            assert_eq!(buf[..n], data[written..written + n]);
810            written += n;
811            if let Some(p) = g.restart_point().unwrap() {
812                points.push((p, written));
813            }
814        }
815        assert_eq!(written, data.len());
816        let starts = points.iter().filter(|(p, _)| p.member_start).count();
817        assert!(starts >= 3, "only {starts} member starts");
818        assert!(points.len() - starts >= 5, "only {} points", points.len());
819        assert!(points.iter().any(|(p, _)| p.bit % 8 != 0));
820
821        for (p, at) in &points {
822            let mut g = open_gzip(&path, p);
823            let rest = gzip_decode_all(&mut g).unwrap();
824            assert!(
825                rest == data[*at..],
826                "resuming at {p:?} (output {at}) went wrong"
827            );
828        }
829        std::fs::remove_dir_all(&dir).unwrap();
830    }
831
832    #[test]
833    fn gzip_checks_every_trailer_and_what_follows() {
834        let dir = std::env::temp_dir().join(format!("hatchzip-gzbad-{}", std::process::id()));
835        std::fs::create_dir_all(&dir).unwrap();
836        let data = text(200_000);
837        let one = gzip_member(&data, 6, 0);
838        let path = dir.join("bad.gz");
839        let fails = |bytes: &[u8]| -> String {
840            std::fs::write(&path, bytes).unwrap();
841            let mut g = open_gzip(&path, &GzPoint::start());
842            match gzip_decode_all(&mut g) {
843                Ok(_) => String::new(),
844                Err(e) => format!("{e:#}"),
845            }
846        };
847
848        let mut two = one.clone();
849        two.extend(&one);
850        assert_eq!(fails(&two), "");
851
852        let n = one.len();
853        let mut bad_crc = one.clone();
854        bad_crc[n - 8] ^= 1;
855        assert!(fails(&bad_crc).contains("CRC mismatch"));
856        let mut bad_len = one.clone();
857        bad_len[n - 1] ^= 1;
858        assert!(fails(&bad_len).contains("length mismatch"));
859        // Damage in a later member is found too.
860        let mut late = one.clone();
861        late.extend(&bad_crc);
862        assert!(fails(&late).contains("CRC mismatch"));
863        assert!(fails(&one[..n - 3]).contains("ends early"));
864        let mut garbage = one.clone();
865        garbage.extend(b"\0\0junk");
866        assert!(fails(&garbage).contains("unexpected data"));
867        let mut hcrc = gzip_member(&data, 6, 2);
868        hcrc[10] ^= 1;
869        assert!(fails(&hcrc).contains("damaged header"));
870        std::fs::remove_dir_all(&dir).unwrap();
871    }
872
873    /// With a tiny input buffer every header, trailer and stream end falls
874    /// across a refill, including the bytes zlib pulled in past the end of
875    /// a deflate stream, which then come from an earlier fill.
876    #[test]
877    fn gzip_framing_survives_any_input_buffer_size() {
878        let dir = std::env::temp_dir().join(format!("hatchzip-gzsmall-{}", std::process::id()));
879        std::fs::create_dir_all(&dir).unwrap();
880        let data = text(120_000);
881        let mut file = Vec::new();
882        let mut from = 0;
883        for (i, to) in [1, 5_000, 5_000, 40_000, 40_007, 120_000]
884            .into_iter()
885            .enumerate()
886        {
887            file.extend(gzip_member(
888                &data[from..to],
889                [1, 6, 9][i % 3],
890                [0, 8, 30][i % 3],
891            ));
892            from = to;
893        }
894        let path = dir.join("small.gz");
895        std::fs::write(&path, &file).unwrap();
896        let storage = Storage::open(&path, false).unwrap();
897        for input in [1, 2, 3, 7, 64, 1000, 70_000] {
898            for output in [1, 5, 4096] {
899                let mut g = Gzip::with_input(
900                    storage.reader(None),
901                    file.len() as u64,
902                    &GzPoint::start(),
903                    input,
904                )
905                .unwrap();
906                let mut got = Vec::new();
907                let mut buf = vec![0; output];
908                loop {
909                    let n = g.read(&mut buf).unwrap();
910                    if n == 0 {
911                        break;
912                    }
913                    got.extend_from_slice(&buf[..n]);
914                }
915                assert!(got == data, "buffers {input}/{output}: wrong output");
916            }
917        }
918        std::fs::remove_dir_all(&dir).unwrap();
919    }
920}