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