From 1777d299fabf1c95231db350b9d126c9a81bdaea Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Sat, 7 Nov 2026 07:41:15 -0600 Subject: [PATCH 1/2] Read archives that aren't in memory, a byte range at a time ZipReader takes the whole archive as one slice, so a 60 GB archive on a server meant 60 GB in memory. ZipIndex opens an archive of a given length through reads of byte ranges: the end of the archive (one read of up to 65 KB, which also holds the directory when it is small), then the central directory in reads of at most 16 MiB. An entry is read on its own, its local header and then the entry, and a password check takes two small reads. ZipIndex::open and fetch_entry take a blocking read(offset, buf); ZipIndexOpener, header_range, entry_range and password_check_range do the same one step at a time for asynchronous callers. The opener follows ZipReader::new step by step and entry reads share its code, so a new differential test holds the two readers to the same entries, comment, errors, entry bytes and password checks on every fixture (plain, ZIP64, stub-prefixed, ZipCrypto, AES), every truncation and every single-byte corruption, and the fuzz target asserts the same. A 50 GiB test archive opens with one 65 KB read. The test writer gains ZipCrypto, AES-256 and ZIP64 end records. Co-Authored-By: Claude Opus 5.5 --- README.md | 49 ++- examples/bench.rs | 11 + fuzz/fuzz_targets/fuzz_zip.rs | 41 ++- src/index.rs | 592 ++++++++++++++++++++++++++++++++ src/lib.rs | 198 ++++++----- tests/writer.rs | 619 +++++++++++++++++++++++++++++++++- 6 files changed, 1411 insertions(+), 99 deletions(-) create mode 100644 src/index.rs diff --git a/README.md b/README.md index 4cd5c2d..e03a6d3 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # zipview -Read-only ZIP container reader for Rust. Opens an in-memory archive, lists its -entries, inflates the ones you ask for. That is all it does. +Read-only ZIP container reader for Rust. Opens an archive (in memory, or read a +byte range at a time), lists its entries, inflates the ones you ask for. That is +all it does. It **cannot** write an archive, extract to disk, decrypt, or touch the filesystem. That is the point. @@ -16,6 +17,41 @@ for entry in archive.entries() { let xml = archive.read_to_string("docProps/core.xml")?; ``` +## Archives that aren't in memory + +`ZipReader` needs the whole archive as one slice. For one too big to load, or +read over a network, `ZipIndex` reads it a byte range at a time: the end of the +archive and its central directory to open it (one read when the directory is +small, two for most others), then only the bytes of the entries you read. + +```rust +use std::os::unix::fs::FileExt; + +let file = std::fs::File::open("huge.zip")?; +let read = |offset: u64, buf: &mut [u8]| file.read_exact_at(buf, offset); +let index = zipview::ZipIndex::open(file.metadata()?.len(), read)?; + +for entry in index.entries() { + println!("{} — {} bytes", entry.name(), entry.size()); +} +if let Some(entry) = index.by_name("release.nfo") { + let nfo = index.fetch_entry(entry, None, read)?; // two reads: header, entry + let check = index.fetch_password_check(entry, read)?; // two small reads +} +``` + +`read(offset, buf)` can be anything that fills `buf` from the archive: a file +read by offset, HTTP range requests, pieces fetched from elsewhere. Where reads +are asynchronous, `ZipIndexOpener` does the opening one step at a time — each +step names the bytes it needs, and you supply them however you fetch — and +`header_range`, `entry_range` and `password_check_range` do the same for an +entry, with `read_entry` and `password_check` finishing from the bytes. + +In the tests a 50 GiB archive opens with a single 65 KB read. No read is over +16 MiB, so a directory size that lies can't make you allocate more than that at +once, and an entry over the 256 MiB inflate limit is refused before its bytes +are read. + ## Why Written to replace the `zip` crate in a metadata tool that needed about five @@ -93,6 +129,12 @@ so a round-trip cannot pass by sharing a wrong constant. Beyond the usual cases, the suite sweeps **every truncation** of a valid archive and **flips every single byte**, asserting only that nothing panics. +`ZipIndex` follows `ZipReader`'s steps over byte ranges instead of a slice, so +the suite holds the two to the same result on every fixture (plain, ZIP64, +stub-prefixed, ZipCrypto and AES), every truncation and every single-byte +corruption: the same entries, comment and errors, the same bytes or error from +every entry, the same password checks. + ```bash cargo test cargo clippy --all-targets -- -D warnings @@ -109,7 +151,8 @@ cargo +nightly fuzz run fuzz_zip fuzz/corpus/fuzz_zip fuzz/seeds The target both lists *and reads* every entry, because a reader that parsed headers safely but trusted the payload offset would pass an enumeration-only -target. +target. It also opens every input with `ZipIndex` and asserts it agrees with +`ZipReader` on everything. The corpus directory comes **first** and the seeds second: libFuzzer writes new inputs to the first directory it is given and treats the rest as read-only. diff --git a/examples/bench.rs b/examples/bench.rs index 3fc487b..af0ec74 100644 --- a/examples/bench.rs +++ b/examples/bench.rs @@ -174,6 +174,17 @@ fn main() { case("open-20000", rounds, 3, || { zipview::ZipReader::new(&arc_dir).unwrap().len() }); + // The same directory through byte ranges, served from memory. + let read = |offset: u64, buf: &mut [u8]| -> Result<(), zipview::ZipReadError> { + let start = offset as usize; + buf.copy_from_slice(&arc_dir[start..start + buf.len()]); + Ok(()) + }; + case("index-open-20000", rounds, 3, || { + zipview::ZipIndex::open(arc_dir.len() as u64, read) + .unwrap() + .len() + }); let zip_dir = zipview::ZipReader::new(&arc_dir).unwrap(); case("by_name-100", rounds, 3, || { (0..100) diff --git a/fuzz/fuzz_targets/fuzz_zip.rs b/fuzz/fuzz_targets/fuzz_zip.rs index dbf4373..6d3349b 100644 --- a/fuzz/fuzz_targets/fuzz_zip.rs +++ b/fuzz/fuzz_targets/fuzz_zip.rs @@ -19,15 +19,37 @@ //! follows an offset to a local header and inflates. A reader that parsed //! headers safely but trusted the payload offset would pass an //! enumeration-only fuzzer. +//! +//! The same bytes also go through [`ZipIndex`], the reader for archives that +//! aren't in memory, which must agree with [`ZipReader`] on everything: the +//! entries, every entry's bytes or error, every password check. A read it +//! asks for past the end of the input panics. use libfuzzer_sys::fuzz_target; -use zipview::ZipReader; +use zipview::{ZipIndex, ZipReadError, ZipReader}; fuzz_target!(|data: &[u8]| { - let Ok(reader) = ZipReader::new(data) else { - // Rejecting malformed input is correct behaviour, not a finding. - return; + let read = |offset: u64, buf: &mut [u8]| -> Result<(), ZipReadError> { + let start = offset as usize; + buf.copy_from_slice(&data[start..start + buf.len()]); + Ok(()) + }; + let index = ZipIndex::open(data.len() as u64, read); + let reader = match ZipReader::new(data) { + Ok(reader) => reader, + Err(e) => { + // Rejecting malformed input is correct behaviour, not a finding, + // as long as both readers reject it the same way. + assert_eq!(index.err(), Some(e)); + return; + } }; + let index = index.expect("the ranged reader opens what the in-memory one does"); + assert_eq!( + format!("{:?}", reader.entries()), + format!("{:?}", index.entries()) + ); + assert_eq!(reader.comment(), index.comment()); // Archive-level accessors must tolerate whatever parsed. let _ = reader.comment(); @@ -60,7 +82,16 @@ fuzz_target!(|data: &[u8]| { // The payload path: resolves an attacker-controlled offset and // inflates. Errors are expected and ignored. - let _ = reader.read_entry(entry); + let bytes = reader.read_entry(entry); + assert_eq!(bytes, index.fetch_entry(entry, None, read)); + assert_eq!( + reader.read_entry_with_password(entry, Some("password")), + index.fetch_entry(entry, Some("password"), read) + ); + assert_eq!( + reader.password_check(entry), + index.fetch_password_check(entry, read).expect("reads succeed") + ); // Name-based lookup must agree that an enumerated entry exists, and // reading by that name must not panic either. diff --git a/src/index.rs b/src/index.rs new file mode 100644 index 0000000..5362e95 --- /dev/null +++ b/src/index.rs @@ -0,0 +1,592 @@ +// zipview -- read-only ZIP container reader +// Copyright (C) 2026 zipview contributors +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program. If not, see . + +//! Archives that are not in memory, read a byte range at a time. +//! +//! [`ZipIndexOpener`] follows the same steps as [`ZipReader::new`], but asks +//! for each piece of the archive it needs instead of indexing a slice. The +//! tests hold the two to the same entries, comment and errors on every +//! fixture, every truncation of one and every single-byte corruption. + +use super::{ + CENTRAL_HEADER_LEN, CENTRAL_HEADER_SIG, EOCD_LEN, EOCD_SIG, LOCAL_HEADER_LEN, LOCAL_HEADER_SIG, + MAX_EOCD_SEARCH, MAX_INFLATED_SIZE, PasswordCheck, Result, ZIP64_EOCD_SIG, ZIP64_LOCATOR_SIG, + ZipEntry, ZipReadError, ZipReader, local_password_check, read_local_entry, u16_at, u32_at, + u64_at, +}; +use std::borrow::Cow; +use std::ops::Range; + +/// The ZIP64 end record (56 bytes) and its locator (20) sit just before the +/// end record, so the first read takes them along with the longest comment. +const TAIL_LEN: u64 = MAX_EOCD_SEARCH as u64 + 56 + 20; + +/// The most of the central directory asked for in one read. A bigger +/// directory (roughly 150,000 entries and up) takes more reads, and a size +/// field that lies can't make a caller allocate more than this at once. +const DIRECTORY_READ: u64 = 16 * 1024 * 1024; + +/// The longest span [`ZipIndex::entry_range`] asks for: the largest entry +/// [`MAX_INFLATED_SIZE`] lets through, stored or deflated, with its headers. +const MAX_ENTRY_SPAN: u64 = MAX_INFLATED_SIZE + MAX_INFLATED_SIZE / 1024 + 128 * 1024; + +/// The bytes a password check reads after the local header: an AES-256 salt +/// and verifier (18), which covers ZipCrypto's 12-byte header too. +const PASSWORD_CHECK_LEN: u64 = 16 + 2; + +/// The directory of a ZIP archive that isn't in memory: a file too big to +/// load, or one read over a network a range at a time. +/// +/// Opening reads the end of the archive and its central directory (two reads +/// for most archives, one when the directory is small), and reading an entry +/// fetches only that entry's bytes. Nothing else of the archive is read or +/// held. [`ZipIndex::open`] and [`ZipIndex::fetch_entry`] take a blocking +/// `read(offset, buf)`; [`ZipIndexOpener`], [`ZipIndex::entry_range`] and +/// [`ZipIndex::read_entry`] do the same work one read at a time, for callers +/// whose reads are asynchronous or need checking first. +/// +/// ``` +/// # fn main() -> std::io::Result<()> { +/// # let archive: Vec = vec![0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; +/// // Any source of byte ranges: a file read by offset, HTTP range requests... +/// let read = |offset: u64, buf: &mut [u8]| -> std::io::Result<()> { +/// let start = offset as usize; +/// buf.copy_from_slice(&archive[start..start + buf.len()]); +/// Ok(()) +/// }; +/// let index = zipview::ZipIndex::open(archive.len() as u64, read)?; +/// for entry in index.entries() { +/// println!("{} ({} bytes)", entry.name(), entry.size()); +/// } +/// if let Some(entry) = index.by_name("readme.txt") { +/// let bytes = index.fetch_entry(entry, None, read)?; +/// # let _ = bytes; +/// } +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone)] +pub struct ZipIndex { + len: u64, + entries: Vec, + comment: Vec, + offset_shift: u64, +} + +/// Opens a [`ZipIndex`] one read at a time. +/// +/// Call [`step`](Self::step); while it returns [`OpenStep::Read`], read those +/// bytes of the archive however suits (asynchronously, say) and hand them to +/// [`supply`](Self::supply). Each step asks for bytes not yet supplied. +/// +/// ``` +/// use zipview::{OpenStep, ZipIndexOpener}; +/// # fn main() -> Result<(), zipview::ZipReadError> { +/// # let archive: Vec = vec![0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; +/// let mut opener = ZipIndexOpener::new(archive.len() as u64); +/// let index = loop { +/// match opener.step()? { +/// OpenStep::Read(range) => { +/// let bytes = &archive[range.start as usize..range.end as usize]; // or fetch(range).await +/// opener.supply(range.start, bytes)?; +/// } +/// OpenStep::Done(index) => break index, +/// } +/// }; +/// # let _ = index; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone)] +pub struct ZipIndexOpener { + len: u64, + /// Supplied pieces of the archive, at their offsets. + held: Vec<(u64, Vec)>, +} + +/// What [`ZipIndexOpener::step`] wants next. +#[derive(Debug, Clone)] +pub enum OpenStep { + /// These bytes of the archive, for [`ZipIndexOpener::supply`]. + Read(Range), + /// The directory, read. + Done(ZipIndex), +} + +/// Why a step stopped: bytes it needs, or a reason the archive can't open. +enum Halt { + Read(Range), + Fail(ZipReadError), +} + +impl From for Halt { + fn from(e: ZipReadError) -> Self { + Self::Fail(e) + } +} + +type Step = std::result::Result; + +impl ZipIndexOpener { + /// Starts opening an archive of `archive_len` bytes. + pub fn new(archive_len: u64) -> Self { + Self { + len: archive_len, + held: Vec::new(), + } + } + + /// The bytes needed next, or the index once everything it needs has been + /// supplied. `Err` when the archive can't be opened, with the same error + /// [`ZipReader::new`] gives for it. + pub fn step(&self) -> Result { + match self.open() { + Ok(index) => Ok(OpenStep::Done(index)), + Err(Halt::Read(range)) => Ok(OpenStep::Read(range)), + Err(Halt::Fail(e)) => Err(e), + } + } + + /// Hands over `bytes`, read from the archive at `offset`. `BadOffset` + /// when they would run past its end. + pub fn supply(&mut self, offset: u64, bytes: &[u8]) -> Result<()> { + if offset + .checked_add(bytes.len() as u64) + .is_none_or(|end| end > self.len) + { + return Err(ZipReadError::BadOffset); + } + if bytes.is_empty() { + return Ok(()); + } + // A read that continues a piece extends it, so the directory stays + // one slice however many reads it takes. + match self + .held + .iter_mut() + .find(|(start, piece)| start + piece.len() as u64 == offset) + { + Some((_, piece)) => piece.extend_from_slice(bytes), + None => self.held.push((offset, bytes.to_vec())), + } + Ok(()) + } + + /// `n` bytes at `at`, if one supplied piece holds them all. + fn held(&self, at: u64, n: u64) -> Option<&[u8]> { + let end = at.checked_add(n)?; + self.held.iter().find_map(|(start, piece)| { + let from = usize::try_from(at.checked_sub(*start)?).ok()?; + let to = usize::try_from(end - start).ok()?; + piece.get(from..to) + }) + } + + /// `n` bytes at `at`, or a read of exactly those. + fn need(&self, at: u64, n: u64) -> Step<&[u8]> { + self.held(at, n).ok_or(Halt::Read(at..at + n)) + } + + /// Follows [`ZipReader::new`] over the supplied pieces. + fn open(&self) -> Step { + let len = self.len; + if len < EOCD_LEN as u64 { + return Err(ZipReadError::NotAZip.into()); + } + let tail_start = len.saturating_sub(TAIL_LEN); + let tail = self.need(tail_start, len - tail_start)?; + let at = |off: u64| (off - tail_start) as usize; + + // The last end record within reach of the end, as `find_eocd`. + let search_start = len.saturating_sub(MAX_EOCD_SEARCH as u64); + let eocd = (search_start..=len - EOCD_LEN as u64) + .rev() + .find(|&off| u32_at(tail, at(off)) == Ok(EOCD_SIG)) + .ok_or(ZipReadError::NotAZip)?; + + let mut entry_count = u64::from(u16_at(tail, at(eocd) + 10)?); + let mut cd_size = u64::from(u32_at(tail, at(eocd) + 12)?); + let mut cd_offset = u64::from(u32_at(tail, at(eocd) + 16)?); + let comment_len = u64::from(u16_at(tail, at(eocd) + 20)?); + let comment_start = eocd + EOCD_LEN as u64; + let comment_end = (comment_start + comment_len).min(len); + let comment = tail[at(comment_start)..at(comment_end)].to_vec(); + + if entry_count == u64::from(u16::MAX) + || cd_offset == u64::from(u32::MAX) + || cd_size == u64::from(u32::MAX) + { + if let Some((z64_entries, z64_size, z64_offset)) = self.zip64(eocd, tail, tail_start)? { + entry_count = z64_entries; + cd_size = z64_size; + cd_offset = z64_offset; + } + } + + let (cd_start, offset_shift) = self.locate_central_directory(eocd, cd_size, cd_offset)?; + + let mut entries = Vec::new(); + let mut cursor = cd_start; + for _ in 0..entry_count { + if u32_at(self.need_directory(cursor, 4, eocd)?, 0)? != CENTRAL_HEADER_SIG { + break; + } + let fixed = self.need_directory(cursor, CENTRAL_HEADER_LEN as u64, eocd)?; + let name_len = u64::from(u16_at(fixed, 28)?); + let extra_len = u64::from(u16_at(fixed, 30)?); + let header = CENTRAL_HEADER_LEN as u64 + name_len + extra_len; + let bytes = self.need_directory(cursor, header, eocd)?; + let (entry, next) = ZipReader::parse_central_entry(bytes, 0)?; + entries.push(entry); + cursor = cursor + .checked_add(next as u64) + .ok_or(ZipReadError::Truncated)?; + } + + Ok(ZipIndex { + len, + entries, + comment, + offset_shift, + }) + } + + /// As `ZipReader::read_zip64`: the ZIP64 counts, or `None` on any + /// inconsistency. + fn zip64(&self, eocd: u64, tail: &[u8], tail_start: u64) -> Step> { + // The locator's 20 bytes end at the end record, inside the tail. + let Some(locator) = eocd.checked_sub(20) else { + return Ok(None); + }; + let at = (locator - tail_start) as usize; + if u32_at(tail, at) != Ok(ZIP64_LOCATOR_SIG) { + return Ok(None); + } + let Ok(record) = u64_at(tail, at + 8) else { + return Ok(None); + }; + if record.checked_add(56).is_none_or(|end| end > self.len) { + return Ok(None); + } + let bytes = self.need(record, 56)?; + if u32_at(bytes, 0)? != ZIP64_EOCD_SIG { + return Ok(None); + } + Ok(Some(( + u64_at(bytes, 32)?, + u64_at(bytes, 40)?, + u64_at(bytes, 48)?, + ))) + } + + /// As `ZipReader::locate_central_directory`: where the directory starts + /// and how far a self-extracting stub shifts the archive's offsets. + fn locate_central_directory( + &self, + eocd: u64, + cd_size: u64, + cd_offset: u64, + ) -> Step<(u64, u64)> { + if cd_offset <= self.len + && self.signature_at(cd_offset, cd_size, eocd)? == Some(CENTRAL_HEADER_SIG) + { + return Ok((cd_offset, 0)); + } + if let Some(computed) = eocd.checked_sub(cd_size) { + if computed <= self.len + && self.signature_at(computed, cd_size, eocd)? == Some(CENTRAL_HEADER_SIG) + { + return Ok((computed, computed.saturating_sub(cd_offset))); + } + } + if cd_offset > self.len { + return Err(ZipReadError::BadOffset.into()); + } + Ok((cd_offset, 0)) + } + + /// The four bytes at `at`, `None` past the end. When they aren't held, + /// asks for the directory that would start there, which is what the + /// next steps read if they turn out to be a central header. + fn signature_at(&self, at: u64, cd_size: u64, eocd: u64) -> Step> { + if at.checked_add(4).is_none_or(|end| end > self.len) { + return Ok(None); + } + match self.held(at, 4) { + Some(bytes) => Ok(Some(u32_at(bytes, 0)?)), + None => { + // The declared size, though not past the end record the + // directory comes before, nor more than one read's worth. + let want = cd_size + .min(eocd.saturating_sub(at)) + .max(CENTRAL_HEADER_LEN as u64) + .min(DIRECTORY_READ); + Err(Halt::Read(at..at.saturating_add(want).min(self.len))) + } + } + } + + /// `n` bytes of the central directory at `at`. `Truncated` past the end + /// of the archive, as in memory; otherwise, when they aren't held, a read + /// that continues the piece `at` is in. + fn need_directory(&self, at: u64, n: u64, eocd: u64) -> Step<&[u8]> { + let end = at + .checked_add(n) + .filter(|&end| end <= self.len) + .ok_or(ZipReadError::Truncated)?; + if let Some(bytes) = self.held(at, n) { + return Ok(bytes); + } + // Continue the piece `at` starts in, if there is one. + let from = self + .held + .iter() + .filter(|(start, _)| *start <= at) + .map(|(start, piece)| start + piece.len() as u64) + .find(|&piece_end| piece_end > at && piece_end < end) + .unwrap_or(at); + // Up to the end record in reads of at most DIRECTORY_READ, or a + // little past it for a directory whose size field undersells it. + let chunk = eocd.saturating_sub(from).clamp(64 * 1024, DIRECTORY_READ); + Err(Halt::Read( + from..end.max(from.saturating_add(chunk)).min(self.len), + )) + } +} + +impl ZipIndex { + /// Opens an archive of `archive_len` bytes with a blocking + /// `read(offset, buf)`, which must fill `buf` from the archive at + /// `offset`. Each read is at most 16 MiB. + /// + /// Errors come back as `E`: whatever `read` returns, or the archive's + /// [`ZipReadError`] converted (`std::io::Error` converts). + pub fn open>( + archive_len: u64, + mut read: impl FnMut(u64, &mut [u8]) -> std::result::Result<(), E>, + ) -> std::result::Result { + let mut opener = ZipIndexOpener::new(archive_len); + loop { + match opener.step()? { + OpenStep::Read(range) => { + let mut buf = vec![0; (range.end - range.start) as usize]; + read(range.start, &mut buf)?; + opener.supply(range.start, &buf)?; + } + OpenStep::Done(index) => return Ok(index), + } + } + } + + /// The archive's length, as given when opening. + pub fn archive_len(&self) -> u64 { + self.len + } + + /// Number of entries parsed. May be fewer than the archive declared when + /// its central directory is damaged. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// True when no entries parsed. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The archive comment, lossily decoded. + pub fn comment(&self) -> Cow<'_, str> { + String::from_utf8_lossy(&self.comment) + } + + /// All parsed entries, in central-directory order. + pub fn entries(&self) -> &[ZipEntry] { + &self.entries + } + + /// The entry at `index` in central-directory order. + pub fn by_index(&self, index: usize) -> Option<&ZipEntry> { + self.entries.get(index) + } + + /// The first entry whose name matches exactly. + pub fn by_name(&self, name: &str) -> Option<&ZipEntry> { + self.entries.iter().find(|e| e.name == name) + } + + /// Whether an entry with this exact name exists. + pub fn contains(&self, name: &str) -> bool { + self.by_name(name).is_some() + } + + /// The first read toward `entry`'s data: its fixed 30-byte local header + /// (shorter only where the archive ends). Its bytes go to + /// [`entry_range`](Self::entry_range) or + /// [`password_check_range`](Self::password_check_range). + pub fn header_range(&self, entry: &ZipEntry) -> Result> { + let start = entry.local_header_offset.saturating_add(self.offset_shift); + if start > self.len { + return Err(ZipReadError::BadOffset); + } + Ok(start..start.saturating_add(LOCAL_HEADER_LEN as u64).min(self.len)) + } + + /// The bytes of `entry` from its local header to the end of its data, + /// given `header` (the bytes at [`header_range`](Self::header_range)). + /// Read them and pass them to [`read_entry`](Self::read_entry). + /// + /// `EntryTooLarge` for an entry too big to read, before anything else. + pub fn entry_range(&self, entry: &ZipEntry, header: &[u8]) -> Result> { + if entry.uncompressed_size > MAX_INFLATED_SIZE { + return Err(ZipReadError::EntryTooLarge(entry.uncompressed_size)); + } + let start = self.header_range(entry)?.start; + let data_start = local_data_start(header)?; + let end = start + .checked_add(data_start) + .and_then(|v| v.checked_add(entry.compressed_size)) + .ok_or(ZipReadError::BadOffset)? + .min(self.len); + // A compressed size no entry within the limit could have. + if end - start > MAX_ENTRY_SPAN { + return Err(ZipReadError::EntryTooLarge(entry.compressed_size)); + } + Ok(start..end) + } + + /// The bytes [`password_check`](Self::password_check) needs for encrypted + /// `entry`, given `header` (the bytes at + /// [`header_range`](Self::header_range)): the local header and the first + /// 18 bytes of data. `None` when it isn't encrypted or the header is + /// unreadable. + pub fn password_check_range(&self, entry: &ZipEntry, header: &[u8]) -> Option> { + if !entry.is_encrypted() { + return None; + } + let start = self.header_range(entry).ok()?.start; + let data_start = local_data_start(header).ok()?; + let end = start + .checked_add(data_start)? + .checked_add(PASSWORD_CHECK_LEN)? + .min(self.len); + Some(start..end) + } + + /// Decompresses `entry` from `bytes`, the archive's bytes at + /// [`entry_range`](Self::entry_range). + pub fn read_entry(&self, entry: &ZipEntry, bytes: &[u8]) -> Result> { + self.read_entry_with_password(entry, bytes, None) + } + + /// Decompresses `entry` from `bytes` (the archive's bytes at + /// [`entry_range`](Self::entry_range)), decrypting with `password` when + /// encrypted. + pub fn read_entry_with_password( + &self, + entry: &ZipEntry, + bytes: &[u8], + password: Option<&str>, + ) -> Result> { + if entry.uncompressed_size > MAX_INFLATED_SIZE { + return Err(ZipReadError::EntryTooLarge(entry.uncompressed_size)); + } + read_local_entry(bytes, 0, entry, password) + } + + /// The [`PasswordCheck`] for `entry` from `bytes`, the archive's bytes at + /// [`password_check_range`](Self::password_check_range). + pub fn password_check(&self, entry: &ZipEntry, bytes: &[u8]) -> Option { + if !entry.is_encrypted() { + return None; + } + local_password_check(bytes, 0, entry) + } + + /// Reads and decompresses `entry` with a blocking `read(offset, buf)` + /// (see [`open`](Self::open)): two reads, its local header and then the + /// entry itself, decrypting with `password` when encrypted. + pub fn fetch_entry>( + &self, + entry: &ZipEntry, + password: Option<&str>, + mut read: impl FnMut(u64, &mut [u8]) -> std::result::Result<(), E>, + ) -> std::result::Result, E> { + if entry.uncompressed_size > MAX_INFLATED_SIZE { + return Err(ZipReadError::EntryTooLarge(entry.uncompressed_size).into()); + } + let too_large = ZipReadError::EntryTooLarge(entry.compressed_size); + let header = read_range(self.header_range(entry)?, &mut read, too_large.clone())?; + let range = self.entry_range(entry, &header)?; + let bytes = read_range(range, &mut read, too_large)?; + Ok(self.read_entry_with_password(entry, &bytes, password)?) + } + + /// The [`PasswordCheck`] for `entry` with a blocking `read(offset, buf)` + /// (see [`open`](Self::open)): `None` without a read when it isn't + /// encrypted, otherwise two small reads. + pub fn fetch_password_check>( + &self, + entry: &ZipEntry, + mut read: impl FnMut(u64, &mut [u8]) -> std::result::Result<(), E>, + ) -> std::result::Result, E> { + if !entry.is_encrypted() { + return Ok(None); + } + let Ok(range) = self.header_range(entry) else { + return Ok(None); + }; + let too_large = ZipReadError::EntryTooLarge(entry.compressed_size); + let header = read_range(range, &mut read, too_large.clone())?; + let Some(range) = self.password_check_range(entry, &header) else { + return Ok(None); + }; + let bytes = read_range(range, &mut read, too_large)?; + Ok(self.password_check(entry, &bytes)) + } +} + +/// Reads `range` with `read` into a new buffer, failing with `too_large` +/// rather than aborting when the buffer can't be allocated. +fn read_range>( + range: Range, + read: &mut impl FnMut(u64, &mut [u8]) -> std::result::Result<(), E>, + too_large: ZipReadError, +) -> std::result::Result, E> { + let n = usize::try_from(range.end - range.start).map_err(|_| too_large.clone())?; + let mut buf = Vec::new(); + buf.try_reserve_exact(n).map_err(|_| too_large)?; + buf.resize(n, 0); + read(range.start, &mut buf)?; + Ok(buf) +} + +/// Where an entry's data starts, from the start of its local header, given +/// the header's fixed 30 bytes; the same checks, in the same order, as +/// reading it in memory. +fn local_data_start(header: &[u8]) -> Result { + if u32_at(header, 0)? != LOCAL_HEADER_SIG { + return Err(ZipReadError::BadSignature); + } + let name_len = u64::from(u16_at(header, 26)?); + let extra_len = u64::from(u16_at(header, 28)?); + Ok(LOCAL_HEADER_LEN as u64 + name_len + extra_len) +} + +impl From for std::io::Error { + fn from(e: ZipReadError) -> Self { + std::io::Error::new(std::io::ErrorKind::InvalidData, e) + } +} diff --git a/src/lib.rs b/src/lib.rs index c7325ab..233bdc5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,15 @@ //! ask for. That is all it does. It **cannot** write an archive, extract to //! disk, decrypt, or touch the filesystem at all. //! +//! # Archives that aren't in memory +//! +//! [`ZipReader`] needs the whole archive as one slice. [`ZipIndex`] reads one +//! that is too big to load, or that comes over a network, a byte range at a +//! time: the end of the archive and its central directory to open it, then +//! only the bytes of the entries you read. [`ZipIndex::open`] takes a blocking +//! `read(offset, buf)`; [`ZipIndexOpener`] does the same one step at a time, +//! for reads that are asynchronous. +//! //! # Why this exists //! //! It was written to replace the `zip` crate in a metadata tool that needed @@ -116,6 +125,9 @@ #![warn(missing_docs, clippy::undocumented_unsafe_blocks)] mod accel; +mod index; + +pub use index::{OpenStep, ZipIndex, ZipIndexOpener}; use std::borrow::Cow; @@ -570,6 +582,11 @@ impl<'a> ZipReader<'a> { /// Parses one central directory header at `off`, returning it and the /// offset of the next header. + /// + /// Always inlined: with [`ZipIndex`] calling it too, the compiler stops + /// inlining it into [`ZipReader::new`]'s loop, which opens a 20,000-entry + /// directory about 10% slower. + #[inline(always)] fn parse_central_entry(data: &[u8], off: usize) -> Result<(ZipEntry, usize)> { let version_made_by = u16_at(data, off + 4)?; let flags = u16_at(data, off + 8)?; @@ -742,24 +759,7 @@ impl<'a> ZipReader<'a> { self.data, ) .ok()?; - if u32_at(self.data, local).ok()? != LOCAL_HEADER_SIG { - return None; - } - let local_name_len = u16_at(self.data, local + 26).ok()? as usize; - let local_extra_len = u16_at(self.data, local + 28).ok()? as usize; - let extra_start = local - .checked_add(LOCAL_HEADER_LEN)? - .checked_add(local_name_len)?; - let data_start = extra_start.checked_add(local_extra_len)?; - let local_extra = self.data.get(extra_start..data_start)?; - let entry_slice = self.data.get(local..)?; - password_check_at( - entry_slice, - usize::from(entry.flags), - usize::from(entry.compression), - local_extra, - data_start - local, - ) + local_password_check(self.data, local, entry) } /// Decompresses one entry's payload. @@ -785,76 +785,112 @@ impl<'a> ZipReader<'a> { entry.local_header_offset.saturating_add(self.offset_shift), self.data, )?; - if u32_at(self.data, local)? != LOCAL_HEADER_SIG { - return Err(ZipReadError::BadSignature); - } - // Only the variable-length counts are taken from the local header; the - // payload begins after them. - let local_name_len = u16_at(self.data, local + 26)? as usize; - let local_extra_len = u16_at(self.data, local + 28)? as usize; - - let extra_start = local - .checked_add(LOCAL_HEADER_LEN) - .and_then(|v| v.checked_add(local_name_len)) - .ok_or(ZipReadError::BadOffset)?; - let data_start = extra_start - .checked_add(local_extra_len) - .ok_or(ZipReadError::BadOffset)?; - let local_extra = self - .data - .get(extra_start..data_start) - .ok_or(ZipReadError::Truncated)?; + read_local_entry(self.data, local, entry, password) + } +} - let compressed_len = - usize::try_from(entry.compressed_size).map_err(|_| ZipReadError::BadOffset)?; - let data_end = data_start - .checked_add(compressed_len) - .ok_or(ZipReadError::BadOffset)?; - let payload = self - .data - .get(data_start..data_end) - .ok_or(ZipReadError::Truncated)?; +/// The [`PasswordCheck`] of encrypted `entry`, whose local header starts at +/// `local` in `data`. Shared by [`ZipReader`], where `data` is the whole +/// archive, and [`ZipIndex`], where it is the bytes read from the local +/// header on. +fn local_password_check(data: &[u8], local: usize, entry: &ZipEntry) -> Option { + if u32_at(data, local).ok()? != LOCAL_HEADER_SIG { + return None; + } + let local_name_len = u16_at(data, local + 26).ok()? as usize; + let local_extra_len = u16_at(data, local + 28).ok()? as usize; + let extra_start = local + .checked_add(LOCAL_HEADER_LEN)? + .checked_add(local_name_len)?; + let data_start = extra_start.checked_add(local_extra_len)?; + let local_extra = data.get(extra_start..data_start)?; + let entry_slice = data.get(local..)?; + password_check_at( + entry_slice, + usize::from(entry.flags), + usize::from(entry.compression), + local_extra, + data_start - local, + ) +} - let (decrypted_buf, method); - let payload_bytes: &[u8] = if entry.is_encrypted() { - let pw = password - .filter(|s| !s.is_empty()) - .ok_or(ZipReadError::Encrypted)?; - if entry.compression == 99 { - let (strength, actual_method) = entry - .aes_info - .or_else(|| aes_extra(local_extra)) - .ok_or(ZipReadError::UnsupportedCompression(99))?; - decrypted_buf = - decrypt_winzip_aes(pw, strength, payload, Some(entry.compressed_size)) - .ok_or(ZipReadError::BadPassword)?; - method = actual_method; - } else { - let check = if entry.flags & 0x0008 != 0 { - *self.data.get(local + 11).ok_or(ZipReadError::Truncated)? - } else { - (entry.crc32 >> 24) as u8 - }; - decrypted_buf = - decrypt_zipcrypto(pw, check, payload).ok_or(ZipReadError::BadPassword)?; - method = entry.compression; - } - &decrypted_buf +/// Decrypts and decompresses `entry`, whose local header starts at `local` +/// in `data` (see [`local_password_check`] for what `data` is). Sizes come +/// from the central directory, never the local header: a streamed entry +/// stores zeros there and writes the real values to a data descriptor after +/// the payload. +fn read_local_entry( + data: &[u8], + local: usize, + entry: &ZipEntry, + password: Option<&str>, +) -> Result> { + if u32_at(data, local)? != LOCAL_HEADER_SIG { + return Err(ZipReadError::BadSignature); + } + // Only the variable-length counts are taken from the local header; the + // payload begins after them. + let local_name_len = u16_at(data, local + 26)? as usize; + let local_extra_len = u16_at(data, local + 28)? as usize; + + let extra_start = local + .checked_add(LOCAL_HEADER_LEN) + .and_then(|v| v.checked_add(local_name_len)) + .ok_or(ZipReadError::BadOffset)?; + let data_start = extra_start + .checked_add(local_extra_len) + .ok_or(ZipReadError::BadOffset)?; + let local_extra = data + .get(extra_start..data_start) + .ok_or(ZipReadError::Truncated)?; + + let compressed_len = + usize::try_from(entry.compressed_size).map_err(|_| ZipReadError::BadOffset)?; + let data_end = data_start + .checked_add(compressed_len) + .ok_or(ZipReadError::BadOffset)?; + let payload = data + .get(data_start..data_end) + .ok_or(ZipReadError::Truncated)?; + + let (decrypted_buf, method); + let payload_bytes: &[u8] = if entry.is_encrypted() { + let pw = password + .filter(|s| !s.is_empty()) + .ok_or(ZipReadError::Encrypted)?; + if entry.compression == 99 { + let (strength, actual_method) = entry + .aes_info + .or_else(|| aes_extra(local_extra)) + .ok_or(ZipReadError::UnsupportedCompression(99))?; + decrypted_buf = decrypt_winzip_aes(pw, strength, payload, Some(entry.compressed_size)) + .ok_or(ZipReadError::BadPassword)?; + method = actual_method; } else { + let check = if entry.flags & 0x0008 != 0 { + *data.get(local + 11).ok_or(ZipReadError::Truncated)? + } else { + (entry.crc32 >> 24) as u8 + }; + decrypted_buf = + decrypt_zipcrypto(pw, check, payload).ok_or(ZipReadError::BadPassword)?; method = entry.compression; - payload - }; + } + &decrypted_buf + } else { + method = entry.compression; + payload + }; - match method { - 0 => { - if payload_bytes.len() as u64 != entry.uncompressed_size { - return Err(ZipReadError::DecompressionFailed); - } - Ok(payload_bytes.to_vec()) + match method { + 0 => { + if payload_bytes.len() as u64 != entry.uncompressed_size { + return Err(ZipReadError::DecompressionFailed); } - 8 => inflate(payload_bytes, entry.uncompressed_size), - other => Err(ZipReadError::UnsupportedCompression(other)), + Ok(payload_bytes.to_vec()) } + 8 => inflate(payload_bytes, entry.uncompressed_size), + other => Err(ZipReadError::UnsupportedCompression(other)), } } diff --git a/tests/writer.rs b/tests/writer.rs index e5db16e..1d1d2dc 100644 --- a/tests/writer.rs +++ b/tests/writer.rs @@ -5,7 +5,8 @@ //! well, and a ZIP writer pulled in just for fixtures would undo that. //! //! Writes only what the fixtures need: Stored and Deflate entries with chosen -//! DOS timestamps, directory entries, and an archive comment. +//! DOS timestamps, directory entries, an archive comment, ZipCrypto and WinZip +//! AES-256 encryption, and ZIP64 end records ([`zip64`]). #![allow(dead_code)] @@ -15,6 +16,8 @@ const LOCAL_HEADER_SIG: u32 = 0x0403_4b50; const CENTRAL_HEADER_SIG: u32 = 0x0201_4b50; const EOCD_SIG: u32 = 0x0605_4b50; +const ZIP64_EOCD_SIG: u32 = 0x0606_4b50; +const ZIP64_LOCATOR_SIG: u32 = 0x0706_4b50; /// How an entry should be stored. #[derive(Clone, Copy, PartialEq, Eq)] @@ -32,6 +35,13 @@ impl Method { } } +/// How an entry is encrypted, with its password. +#[derive(Clone, Copy)] +pub enum Crypt<'a> { + ZipCrypto(&'a str), + Aes256(&'a str), +} + /// One entry to write. pub struct Entry<'a> { pub name: &'a str, @@ -40,6 +50,7 @@ pub struct Entry<'a> { /// `(year, month, day, hour, minute, second)`. Seconds are rounded /// down to even, as DOS stores them in two-second units. pub modified: Option<(u16, u8, u8, u8, u8, u8)>, + pub crypt: Option>, } impl<'a> Entry<'a> { @@ -49,6 +60,7 @@ impl<'a> Entry<'a> { body, method: Method::Stored, modified: None, + crypt: None, } } pub fn deflated(name: &'a str, body: &'a [u8]) -> Self { @@ -57,12 +69,77 @@ impl<'a> Entry<'a> { body, method: Method::Deflated, modified: None, + crypt: None, } } pub fn at(mut self, y: u16, mo: u8, d: u8, h: u8, mi: u8, s: u8) -> Self { self.modified = Some((y, mo, d, h, mi, s)); self } + pub fn encrypted(mut self, crypt: Crypt<'a>) -> Self { + self.crypt = Some(crypt); + self + } +} + +/// One byte of ZIP's CRC-32 without the inversions: ZipCrypto's key update. +fn crc_step(crc: u32, b: u8) -> u32 { + let mut c = (crc ^ b as u32) & 0xff; + for _ in 0..8 { + c = if c & 1 != 0 { + (c >> 1) ^ 0xEDB8_8320 + } else { + c >> 1 + }; + } + (crc >> 8) ^ c +} + +/// ZipCrypto-encrypts a 12-byte header (random but for its last byte, the +/// CRC's top byte) and `payload`, written from the PKWARE note rather than +/// the reader's code. +fn zipcrypto(password: &str, crc: u32, payload: &[u8]) -> Vec { + let mut keys = [0x1234_5678u32, 0x2345_6789, 0x3456_7890]; + let update = |keys: &mut [u32; 3], b: u8| { + keys[0] = crc_step(keys[0], b); + keys[1] = keys[1] + .wrapping_add(keys[0] & 0xff) + .wrapping_mul(134_775_813) + .wrapping_add(1); + keys[2] = crc_step(keys[2], (keys[1] >> 24) as u8); + }; + for b in password.bytes() { + update(&mut keys, b); + } + let mut header = [0u8; 12]; + for (i, b) in header.iter_mut().enumerate() { + *b = (i as u8).wrapping_mul(37).wrapping_add(payload.len() as u8); + } + header[11] = (crc >> 24) as u8; + header + .iter() + .chain(payload) + .map(|&p| { + let t = keys[2] | 2; + let c = p ^ (t.wrapping_mul(t ^ 1) >> 8) as u8; + update(&mut keys, p); + c + }) + .collect() +} + +/// WinZip AES-256 (AE-2): salt, verifier, the CTR-encrypted payload and a +/// 10-byte authentication code, left zero since the reader doesn't check it. +/// Key derivation and CTR come from the crate: these fixtures test reading +/// through byte ranges, not the cipher. +fn aes256(password: &str, payload: &[u8]) -> Vec { + let salt: Vec = (0..16u8).map(|i| i.wrapping_mul(29) ^ 0x5a).collect(); + let keys = zipview::aes_derive(password.as_bytes(), &salt, 32).expect("derive"); + let mut out = salt; + out.extend_from_slice(&keys[64..66]); + out.extend_from_slice(&zipview::decrypt_winzip_ctr(&keys[..32], payload).expect("ctr")); + out.extend_from_slice(&[0u8; 10]); + out } fn dos_datetime(modified: Option<(u16, u8, u8, u8, u8, u8)>) -> (u16, u16) { @@ -104,6 +181,8 @@ fn deflate(data: &[u8]) -> Vec { pub fn build(entries: &[Entry<'_>], comment: &str) -> Vec { struct Central { name: Vec, + extra: Vec, + flags: u16, method: u16, crc: u32, comp_len: u32, @@ -120,33 +199,59 @@ pub fn build(entries: &[Entry<'_>], comment: &str) -> Vec { for e in entries { let is_dir = e.name.ends_with('/'); let body: &[u8] = if is_dir { &[] } else { e.body }; - let payload = match e.method { + let compressed = match e.method { Method::Stored => body.to_vec(), Method::Deflated => deflate(body), }; let (date, time) = dos_datetime(e.modified); - let crc = crc32(body); + let plain_crc = crc32(body); + // Bit 11 declares the name is UTF-8, which it is here; bit 0 marks + // encryption. + let (payload, method, flags, crc, extra) = match e.crypt { + None => ( + compressed, + e.method.code(), + 0x0800u16, + plain_crc, + Vec::new(), + ), + Some(Crypt::ZipCrypto(pw)) => ( + zipcrypto(pw, plain_crc, &compressed), + e.method.code(), + 0x0801, + plain_crc, + Vec::new(), + ), + Some(Crypt::Aes256(pw)) => { + // 0x9901: AE-2, vendor "AE", strength 3, then the real method. + let mut extra = vec![0x01, 0x99, 7, 0, 2, 0, b'A', b'E', 3]; + extra.extend_from_slice(&e.method.code().to_le_bytes()); + (aes256(pw, &compressed), 99, 0x0801, 0, extra) + } + }; let name = e.name.as_bytes().to_vec(); let offset = out.len() as u32; out.extend_from_slice(&LOCAL_HEADER_SIG.to_le_bytes()); out.extend_from_slice(&20u16.to_le_bytes()); // version needed - // Bit 11 declares the name is UTF-8, which it is here. - out.extend_from_slice(&0x0800u16.to_le_bytes()); - out.extend_from_slice(&e.method.code().to_le_bytes()); + out.extend_from_slice(&flags.to_le_bytes()); + out.extend_from_slice(&method.to_le_bytes()); out.extend_from_slice(&time.to_le_bytes()); out.extend_from_slice(&date.to_le_bytes()); out.extend_from_slice(&crc.to_le_bytes()); out.extend_from_slice(&(payload.len() as u32).to_le_bytes()); out.extend_from_slice(&(body.len() as u32).to_le_bytes()); out.extend_from_slice(&(name.len() as u16).to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); // extra len + out.extend_from_slice(&(extra.len() as u16).to_le_bytes()); out.extend_from_slice(&name); + out.extend_from_slice(&extra); out.extend_from_slice(&payload); centrals.push(Central { name, - method: e.method.code(), + extra, + flags, + method, crc, comp_len: payload.len() as u32, uncomp_len: body.len() as u32, @@ -164,7 +269,7 @@ pub fn build(entries: &[Entry<'_>], comment: &str) -> Vec { // zip crate produced on the platforms these tests ran on. out.extend_from_slice(&0x031eu16.to_le_bytes()); out.extend_from_slice(&20u16.to_le_bytes()); - out.extend_from_slice(&0x0800u16.to_le_bytes()); + out.extend_from_slice(&c.flags.to_le_bytes()); out.extend_from_slice(&c.method.to_le_bytes()); out.extend_from_slice(&c.time.to_le_bytes()); out.extend_from_slice(&c.date.to_le_bytes()); @@ -172,7 +277,7 @@ pub fn build(entries: &[Entry<'_>], comment: &str) -> Vec { out.extend_from_slice(&c.comp_len.to_le_bytes()); out.extend_from_slice(&c.uncomp_len.to_le_bytes()); out.extend_from_slice(&(c.name.len() as u16).to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); // extra + out.extend_from_slice(&(c.extra.len() as u16).to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); // comment out.extend_from_slice(&0u16.to_le_bytes()); // disk out.extend_from_slice(&0u16.to_le_bytes()); // internal attrs @@ -180,6 +285,7 @@ pub fn build(entries: &[Entry<'_>], comment: &str) -> Vec { out.extend_from_slice(&(mode << 16).to_le_bytes()); out.extend_from_slice(&c.offset.to_le_bytes()); out.extend_from_slice(&c.name); + out.extend_from_slice(&c.extra); } let cd_len = out.len() as u32 - cd_offset; @@ -196,6 +302,47 @@ pub fn build(entries: &[Entry<'_>], comment: &str) -> Vec { out } +/// Rewrites a [`build`] archive with ZIP64 end records: the classic end +/// record's counts, size and offset saturated, and the real values in a ZIP64 +/// end record and locator just before it, as writers do past 65,535 entries +/// or 4 GiB. +pub fn zip64(archive: &[u8]) -> Vec { + let eocd = (0..=archive.len() - 22) + .rev() + .find(|&i| archive[i..i + 4] == EOCD_SIG.to_le_bytes()) + .expect("end record"); + let field = |at: usize, n: usize| { + archive[eocd + at..eocd + at + n] + .iter() + .rev() + .fold(0u64, |v, &b| v << 8 | b as u64) + }; + let (entries, cd_size, cd_offset) = (field(10, 2), field(12, 4), field(16, 4)); + let mut out = archive[..eocd].to_vec(); + let record = out.len() as u64; + out.extend_from_slice(&ZIP64_EOCD_SIG.to_le_bytes()); + out.extend_from_slice(&44u64.to_le_bytes()); // size of the rest + out.extend_from_slice(&45u16.to_le_bytes()); // made by + out.extend_from_slice(&45u16.to_le_bytes()); // needed + out.extend_from_slice(&0u32.to_le_bytes()); // this disk + out.extend_from_slice(&0u32.to_le_bytes()); // directory's disk + out.extend_from_slice(&entries.to_le_bytes()); // on this disk + out.extend_from_slice(&entries.to_le_bytes()); + out.extend_from_slice(&cd_size.to_le_bytes()); + out.extend_from_slice(&cd_offset.to_le_bytes()); + out.extend_from_slice(&ZIP64_LOCATOR_SIG.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // record's disk + out.extend_from_slice(&record.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // disks + out.extend_from_slice(&archive[eocd..eocd + 8]); // signature, disks + out.extend_from_slice(&u16::MAX.to_le_bytes()); + out.extend_from_slice(&u16::MAX.to_le_bytes()); + out.extend_from_slice(&u32::MAX.to_le_bytes()); + out.extend_from_slice(&u32::MAX.to_le_bytes()); + out.extend_from_slice(&archive[eocd + 20..]); // comment length, comment + out +} + // --------------------------------------------------------------------------- // Round-trip tests: writer -> reader. // @@ -349,3 +496,455 @@ fn an_unsupported_method_still_enumerates() { Err(ZipReadError::UnsupportedCompression(93)) ); } + +// --------------------------------------------------------------------------- +// Reading through byte ranges: `ZipIndex` against `ZipReader`. +// +// The ranged reader follows the in-memory one step by step, so on any input +// the two must agree: the same entries, comment and errors, the same bytes +// or error from every entry, the same password checks. +// --------------------------------------------------------------------------- + +use std::cell::RefCell; +use zipview::{OpenStep, PasswordCheck, ZipIndex, ZipIndexOpener}; + +/// An archive served a range at a time, recording each read. A read past the +/// end panics, failing the test. +struct Source<'a> { + data: &'a [u8], + reads: RefCell>, +} + +impl<'a> Source<'a> { + fn new(data: &'a [u8]) -> Self { + Self { + data, + reads: RefCell::new(Vec::new()), + } + } + + fn read(&self) -> impl FnMut(u64, &mut [u8]) -> Result<(), ZipReadError> + '_ { + |offset, buf| { + self.reads.borrow_mut().push((offset, buf.len())); + let start = usize::try_from(offset).expect("offset"); + buf.copy_from_slice(&self.data[start..start + buf.len()]); + Ok(()) + } + } + + fn read_count(&self) -> usize { + self.reads.borrow().len() + } +} + +/// Opens `data` both ways and checks they agree, reading every entry with +/// each of `passwords`. +fn assert_same(data: &[u8], passwords: &[Option<&str>]) { + let source = Source::new(data); + let ranged = ZipIndex::open(data.len() as u64, source.read()); + match (ZipReader::new(data), ranged) { + (Err(a), Err(b)) => assert_eq!(a, b, "open errors"), + (Ok(memory), Ok(index)) => { + assert_eq!( + format!("{:?}", memory.entries()), + format!("{:?}", index.entries()) + ); + assert_eq!(memory.comment(), index.comment()); + for entry in memory.entries() { + for &password in passwords { + assert_eq!( + memory.read_entry_with_password(entry, password), + index.fetch_entry(entry, password, source.read()), + "{} with {password:?}", + entry.name() + ); + } + let check: Option = index + .fetch_password_check(entry, source.read()) + .expect("in-memory reads don't fail"); + assert_eq!(memory.password_check(entry), check, "{}", entry.name()); + } + } + (memory, ranged) => panic!( + "in memory {:?}, ranged {:?}", + memory.map(|r| r.len()), + ranged.map(|i| i.len()) + ), + } +} + +const PASSWORDS: [Option<&str>; 3] = [None, Some("secret"), Some("wrong")]; + +fn plain_archive() -> Vec { + let text = "the quick brown fox ".repeat(300); + build( + &[ + Entry::stored("stored.txt", b"hello world"), + Entry::deflated("deflated.xml", text.as_bytes()), + Entry::deflated("dir/", b""), + Entry::stored("empty", b""), + ], + "a comment", + ) +} + +fn zipcrypto_archive() -> Vec { + let text = "jumps over the lazy dog ".repeat(100); + build( + &[ + Entry::stored("zc-stored.txt", b"zipcrypto stored") + .encrypted(Crypt::ZipCrypto("secret")), + Entry::deflated("zc-deflated.xml", text.as_bytes()) + .encrypted(Crypt::ZipCrypto("secret")), + Entry::stored("plain.txt", b"not encrypted"), + ], + "", + ) +} + +fn aes_archive() -> Vec { + let text = "winzip aes payload ".repeat(100); + build( + &[ + Entry::stored("aes-stored.txt", b"aes stored").encrypted(Crypt::Aes256("secret")), + Entry::deflated("aes-deflated.xml", text.as_bytes()).encrypted(Crypt::Aes256("secret")), + ], + "", + ) +} + +fn prefixed(archive: &[u8]) -> Vec { + let mut data = b"#!/bin/sh\necho stub\nexit 0\n".to_vec(); + data.extend_from_slice(archive); + data +} + +#[test] +fn the_writer_encrypts_what_the_reader_decrypts() { + for data in [zipcrypto_archive(), aes_archive()] { + let r = ZipReader::new(&data).expect("parse"); + for e in r.entries() { + let body = r + .read_entry_with_password(e, Some("secret")) + .expect("decrypt"); + assert!(!body.is_empty(), "{}", e.name()); + if e.is_encrypted() { + assert_eq!( + r.read_entry_with_password(e, Some("wrong")), + Err(ZipReadError::BadPassword) + ); + } + } + } + let data = zip64(&plain_archive()); + let r = ZipReader::new(&data).expect("parse zip64"); + assert_eq!(r.len(), 4); + assert_eq!(r.read_to_string("stored.txt").expect("read"), "hello world"); +} + +#[test] +fn ranged_reads_match_in_memory_on_every_fixture() { + let plain = plain_archive(); + let zipcrypto = zipcrypto_archive(); + let aes = aes_archive(); + let fixtures = [ + build(&[], ""), + build(&[Entry::stored("a", b"x")], &"c".repeat(65_000)), + plain.clone(), + zip64(&plain), + prefixed(&plain), + zip64(&prefixed(&plain)), + zipcrypto.clone(), + zip64(&zipcrypto), + aes.clone(), + prefixed(&aes), + ]; + for data in &fixtures { + assert_same(data, &PASSWORDS); + } +} + +#[test] +fn ranged_reads_match_in_memory_on_every_truncation_and_corruption() { + let plain = plain_archive(); + for (data, passwords) in [ + (plain.clone(), &[None][..]), + (zip64(&plain), &[None]), + (prefixed(&plain), &[None]), + (zipcrypto_archive(), &[Some("secret")]), + ] { + for n in 0..=data.len() { + assert_same(&data[..n], passwords); + } + let mut corrupt = data.clone(); + for i in 0..data.len() { + for x in [0xff, 0x01] { + corrupt[i] ^= x; + assert_same(&corrupt, passwords); + corrupt[i] ^= x; + } + } + } +} + +#[test] +fn opening_takes_one_read_for_a_small_directory_and_two_for_a_big_one() { + let small = plain_archive(); + let source = Source::new(&small); + let index = ZipIndex::open(small.len() as u64, source.read()).expect("open"); + assert_eq!(source.read_count(), 1, "the tail holds the whole directory"); + let entry = index.by_name("deflated.xml").expect("entry"); + index.fetch_entry(entry, None, source.read()).expect("read"); + assert_eq!(source.read_count(), 3, "an entry takes two reads"); + + // About 200 KB of directory: past the tail read. + let names: Vec = (0..3000) + .map(|i| format!("dir{}/file-{i:05}.xml", i % 9)) + .collect(); + let entries: Vec> = names + .iter() + .map(|n| Entry::stored(n, n.as_bytes())) + .collect(); + let big = build(&entries, ""); + let source = Source::new(&big); + let index = ZipIndex::open(big.len() as u64, source.read()).expect("open"); + assert_eq!(source.read_count(), 2); + assert_eq!(index.len(), 3000); + assert_same(&big, &[None]); +} + +#[test] +fn a_directory_bigger_than_one_read_is_read_in_pieces() { + // 64,000 entries with 220-byte names: about 17 MB of directory, past + // one 16 MiB read, and still under 65,535 entries. + let names: Vec = (0..64_000) + .map(|i| format!("{}{i:06}", "d/".repeat(107))) + .collect(); + let entries: Vec> = names.iter().map(|n| Entry::stored(n, b"")).collect(); + let data = build(&entries, ""); + let source = Source::new(&data); + let index = ZipIndex::open(data.len() as u64, source.read()).expect("open"); + assert_eq!(index.len(), 64_000); + let reads = source.reads.borrow().clone(); + assert!(reads.len() >= 3, "{reads:?}"); + assert!(reads.iter().all(|&(_, n)| n <= 16 << 20), "{reads:?}"); + let memory = ZipReader::new(&data).expect("parse"); + assert_eq!( + format!("{:?}", memory.entries()), + format!("{:?}", index.entries()) + ); +} + +#[test] +fn the_opener_asks_only_for_bytes_it_lacks() { + let names: Vec = (0..3000).map(|i| format!("f{i:05}")).collect(); + let entries: Vec> = names.iter().map(|n| Entry::stored(n, b"x")).collect(); + let data = build(&entries, ""); + let mut opener = ZipIndexOpener::new(data.len() as u64); + let mut asked: Vec> = Vec::new(); + let index = loop { + match opener.step().expect("step") { + OpenStep::Read(range) => { + assert!(range.start < range.end && range.end <= data.len() as u64); + assert!(!asked.contains(&range), "asked twice for {range:?}"); + let bytes = &data[range.start as usize..range.end as usize]; + opener.supply(range.start, bytes).expect("supply"); + asked.push(range); + } + OpenStep::Done(index) => break index, + } + }; + assert_eq!(index.len(), 3000); + assert_eq!( + opener.supply(data.len() as u64 - 1, b"ab"), + Err(ZipReadError::BadOffset) + ); +} + +/// An archive mostly of zeros it never stores: `pieces` are its real bytes +/// at their offsets, and every read is recorded. +struct Sparse { + len: u64, + pieces: Vec<(u64, Vec)>, + reads: RefCell>, +} + +impl Sparse { + fn read(&self) -> impl FnMut(u64, &mut [u8]) -> Result<(), ZipReadError> + '_ { + |offset, buf| { + assert!(offset + buf.len() as u64 <= self.len, "read past the end"); + self.reads.borrow_mut().push((offset, buf.len())); + buf.fill(0); + for (start, piece) in &self.pieces { + for (i, b) in buf.iter_mut().enumerate() { + let at = offset + i as u64; + if at >= *start && at < start + piece.len() as u64 { + *b = piece[(at - start) as usize]; + } + } + } + Ok(()) + } + } + + fn bytes_read(&self) -> usize { + self.reads.borrow().iter().map(|&(_, n)| n).sum() + } +} + +/// A 50 GiB archive: `big.bin` (50 GiB, stored), then `readme.txt`, then the +/// directory with ZIP64 sizes and offsets. Only the headers are real bytes. +fn fifty_gigabytes() -> Sparse { + const BIG: u64 = 50 << 30; + let le16 = |v: u16| v.to_le_bytes(); + let le32 = |v: u32| v.to_le_bytes(); + let le64 = |v: u64| v.to_le_bytes(); + + // big.bin's local header, with its sizes in a ZIP64 extra field. + let mut head = Vec::new(); + head.extend_from_slice(&le32(LOCAL_HEADER_SIG)); + head.extend_from_slice(&le16(45)); + head.extend_from_slice(&le16(0x0800)); + head.extend_from_slice(&le16(0)); // stored + head.extend_from_slice(&[0; 8]); // time, date, crc + head.extend_from_slice(&le32(u32::MAX)); + head.extend_from_slice(&le32(u32::MAX)); + head.extend_from_slice(&le16(7)); + head.extend_from_slice(&le16(20)); + head.extend_from_slice(b"big.bin"); + head.extend_from_slice(&le16(1)); + head.extend_from_slice(&le16(16)); + head.extend_from_slice(&le64(BIG)); + head.extend_from_slice(&le64(BIG)); + + // readme.txt after the 50 GiB of data, then the directory. + let readme_at = head.len() as u64 + BIG; + let body = b"read me"; + let mut tail = Vec::new(); + tail.extend_from_slice(&le32(LOCAL_HEADER_SIG)); + tail.extend_from_slice(&le16(20)); + tail.extend_from_slice(&le16(0x0800)); + tail.extend_from_slice(&le16(0)); + tail.extend_from_slice(&[0; 4]); + tail.extend_from_slice(&le32(crc32(body))); + tail.extend_from_slice(&le32(body.len() as u32)); + tail.extend_from_slice(&le32(body.len() as u32)); + tail.extend_from_slice(&le16(10)); + tail.extend_from_slice(&le16(0)); + tail.extend_from_slice(b"readme.txt"); + tail.extend_from_slice(body); + + let cd_at = readme_at + tail.len() as u64; + let central = |name: &[u8], crc: u32, size: u32, offset: u32, extra: &[u8]| { + let mut c = Vec::new(); + c.extend_from_slice(&le32(CENTRAL_HEADER_SIG)); + c.extend_from_slice(&le16(0x032d)); + c.extend_from_slice(&le16(45)); + c.extend_from_slice(&le16(0x0800)); + c.extend_from_slice(&le16(0)); + c.extend_from_slice(&[0; 4]); + c.extend_from_slice(&le32(crc)); + c.extend_from_slice(&le32(size)); + c.extend_from_slice(&le32(size)); + c.extend_from_slice(&le16(name.len() as u16)); + c.extend_from_slice(&le16(extra.len() as u16)); + c.extend_from_slice(&[0; 6]); // comment, disk, internal attributes + c.extend_from_slice(&le32(0o100644 << 16)); + c.extend_from_slice(&le32(offset)); + c.extend_from_slice(name); + c.extend_from_slice(extra); + c + }; + let mut big_extra = vec![1, 0, 16, 0]; + big_extra.extend_from_slice(&le64(BIG)); + big_extra.extend_from_slice(&le64(BIG)); + let mut readme_extra = vec![1, 0, 8, 0]; + readme_extra.extend_from_slice(&le64(readme_at)); + let mut cd = central(b"big.bin", 0, u32::MAX, 0, &big_extra); + cd.extend_from_slice(¢ral( + b"readme.txt", + crc32(body), + body.len() as u32, + u32::MAX, + &readme_extra, + )); + let record_at = cd_at + cd.len() as u64; + tail.extend_from_slice(&cd); + tail.extend_from_slice(&le32(ZIP64_EOCD_SIG)); + tail.extend_from_slice(&le64(44)); + tail.extend_from_slice(&le16(45)); + tail.extend_from_slice(&le16(45)); + tail.extend_from_slice(&[0; 8]); + tail.extend_from_slice(&le64(2)); + tail.extend_from_slice(&le64(2)); + tail.extend_from_slice(&le64(cd.len() as u64)); + tail.extend_from_slice(&le64(cd_at)); + tail.extend_from_slice(&le32(ZIP64_LOCATOR_SIG)); + tail.extend_from_slice(&le32(0)); + tail.extend_from_slice(&le64(record_at)); + tail.extend_from_slice(&le32(1)); + tail.extend_from_slice(&le32(EOCD_SIG)); + tail.extend_from_slice(&[0; 4]); + tail.extend_from_slice(&le16(u16::MAX)); + tail.extend_from_slice(&le16(u16::MAX)); + tail.extend_from_slice(&le32(u32::MAX)); + tail.extend_from_slice(&le32(u32::MAX)); + tail.extend_from_slice(&le16(0)); + + Sparse { + len: readme_at + tail.len() as u64, + pieces: vec![(0, head), (readme_at, tail)], + reads: RefCell::new(Vec::new()), + } +} + +#[test] +fn a_fifty_gigabyte_archive_opens_with_one_small_read() { + let archive = fifty_gigabytes(); + let index = ZipIndex::open(archive.len, archive.read()).expect("open"); + assert_eq!(archive.reads.borrow().len(), 1); + assert!(archive.bytes_read() < 70_000, "{}", archive.bytes_read()); + + let big = index.by_name("big.bin").expect("big.bin"); + assert_eq!(big.size(), 50 << 30); + let readme = index.by_name("readme.txt").expect("readme.txt"); + assert_eq!( + index + .fetch_entry(readme, None, archive.read()) + .expect("read"), + b"read me" + ); + // Too big to inflate: refused before any read. + let reads = archive.reads.borrow().len(); + assert_eq!( + index.fetch_entry(big, None, archive.read()), + Err(ZipReadError::EntryTooLarge(50 << 30)) + ); + assert_eq!(archive.reads.borrow().len(), reads); + assert!(archive.bytes_read() < 70_100, "{}", archive.bytes_read()); +} + +#[test] +fn a_lying_directory_size_is_read_at_most_sixteen_mebibytes_at_a_time() { + // A 60 GB archive of zeros but for an end record claiming a 4 GiB + // directory at offset 0, where no central header is. + let len = 60_000_000_000u64; + let mut eocd = Vec::new(); + eocd.extend_from_slice(&EOCD_SIG.to_le_bytes()); + eocd.extend_from_slice(&[0; 4]); + eocd.extend_from_slice(&5u16.to_le_bytes()); + eocd.extend_from_slice(&5u16.to_le_bytes()); + eocd.extend_from_slice(&0xffff_fff0u32.to_le_bytes()); + eocd.extend_from_slice(&0u32.to_le_bytes()); + eocd.extend_from_slice(&0u16.to_le_bytes()); + let archive = Sparse { + len, + pieces: vec![(len - eocd.len() as u64, eocd)], + reads: RefCell::new(Vec::new()), + }; + let index = ZipIndex::open(len, archive.read()).expect("open"); + assert!(index.is_empty()); + let reads = archive.reads.borrow().clone(); + assert!(reads.len() <= 3, "{reads:?}"); + assert!(reads.iter().all(|&(_, n)| n <= 16 << 20), "{reads:?}"); +} From aa68e1f036fedda28f14903181796e278284f209 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:02:53 -0600 Subject: [PATCH 2/2] Parse a big directory once, keeping the walk between reads Every step re-ran the open from the start, so a directory needing several reads was parsed again on each, quadratic in its size (Codex review). The opener now keeps its walk (cursor, count left, entries so far) between reads, drops directory bytes it has parsed, and asks only for the part of a read not yet supplied. Its API becomes next_read / supply / finish. A 21 MB directory supplied in over 300 partial reads now opens in 0.3 s, holding at most the tail and one header between reads. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +- src/index.rs | 274 +++++++++++++++++++++++++++++++++++++----------- src/lib.rs | 2 +- tests/writer.rs | 23 ++-- 4 files changed, 226 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index e03a6d3..497e9ce 100644 --- a/README.md +++ b/README.md @@ -42,10 +42,11 @@ if let Some(entry) = index.by_name("release.nfo") { `read(offset, buf)` can be anything that fills `buf` from the archive: a file read by offset, HTTP range requests, pieces fetched from elsewhere. Where reads -are asynchronous, `ZipIndexOpener` does the opening one step at a time — each -step names the bytes it needs, and you supply them however you fetch — and -`header_range`, `entry_range` and `password_check_range` do the same for an -entry, with `read_entry` and `password_check` finishing from the bytes. +are asynchronous, `ZipIndexOpener` does the opening one read at a time — +`next_read` names the bytes it needs, you `supply` them however you fetch, and +`finish` gives the index — and `header_range`, `entry_range` and +`password_check_range` do the same for an entry, with `read_entry` and +`password_check` finishing from the bytes. In the tests a 50 GiB archive opens with a single 65 KB read. No read is over 16 MiB, so a directory size that lies can't make you allocate more than that at diff --git a/src/index.rs b/src/index.rs index 5362e95..c07587a 100644 --- a/src/index.rs +++ b/src/index.rs @@ -88,24 +88,23 @@ pub struct ZipIndex { /// Opens a [`ZipIndex`] one read at a time. /// -/// Call [`step`](Self::step); while it returns [`OpenStep::Read`], read those -/// bytes of the archive however suits (asynchronously, say) and hand them to -/// [`supply`](Self::supply). Each step asks for bytes not yet supplied. +/// While [`next_read`](Self::next_read) names a range, read those bytes of +/// the archive however suits (asynchronously, say) and hand them to +/// [`supply`](Self::supply); then [`finish`](Self::finish) gives the index. +/// Each read asks for bytes not yet supplied. The central directory is parsed +/// once, as its pieces arrive, and bytes already parsed are dropped, so a big +/// directory isn't held twice. /// /// ``` -/// use zipview::{OpenStep, ZipIndexOpener}; +/// use zipview::ZipIndexOpener; /// # fn main() -> Result<(), zipview::ZipReadError> { /// # let archive: Vec = vec![0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; /// let mut opener = ZipIndexOpener::new(archive.len() as u64); -/// let index = loop { -/// match opener.step()? { -/// OpenStep::Read(range) => { -/// let bytes = &archive[range.start as usize..range.end as usize]; // or fetch(range).await -/// opener.supply(range.start, bytes)?; -/// } -/// OpenStep::Done(index) => break index, -/// } -/// }; +/// while let Some(range) = opener.next_read()? { +/// let bytes = &archive[range.start as usize..range.end as usize]; // or fetch(range).await +/// opener.supply(range.start, bytes)?; +/// } +/// let index = opener.finish()?; /// # let _ = index; /// # Ok(()) /// # } @@ -115,15 +114,21 @@ pub struct ZipIndexOpener { len: u64, /// Supplied pieces of the archive, at their offsets. held: Vec<(u64, Vec)>, + /// The walk over the central directory, once its start is known. + walk: Option, } -/// What [`ZipIndexOpener::step`] wants next. +/// Where the walk over the central directory has got to, kept between reads +/// so each header is parsed once. #[derive(Debug, Clone)] -pub enum OpenStep { - /// These bytes of the archive, for [`ZipIndexOpener::supply`]. - Read(Range), - /// The directory, read. - Done(ZipIndex), +struct Walk { + comment: Vec, + offset_shift: u64, + eocd: u64, + /// Headers still to read, as the end record counts them. + remaining: u64, + cursor: u64, + entries: Vec, } /// Why a step stopped: bytes it needs, or a reason the archive can't open. @@ -146,16 +151,34 @@ impl ZipIndexOpener { Self { len: archive_len, held: Vec::new(), + walk: None, } } - /// The bytes needed next, or the index once everything it needs has been - /// supplied. `Err` when the archive can't be opened, with the same error - /// [`ZipReader::new`] gives for it. - pub fn step(&self) -> Result { - match self.open() { - Ok(index) => Ok(OpenStep::Done(index)), - Err(Halt::Read(range)) => Ok(OpenStep::Read(range)), + /// The bytes to read next, or `None` once everything is in. `Err` when + /// the archive can't be opened, with the error [`ZipReader::new`] gives + /// for it. + pub fn next_read(&mut self) -> Result>> { + let mut walk = match self.walk.take() { + Some(walk) => walk, + None => match self.locate() { + Ok(walk) => walk, + Err(Halt::Read(range)) => return Ok(Some(range)), + Err(Halt::Fail(e)) => return Err(e), + }, + }; + let step = self.walk(&mut walk); + let cursor = walk.cursor; + self.walk = Some(walk); + match step { + Ok(()) => { + self.held = Vec::new(); + Ok(None) + } + Err(Halt::Read(range)) => { + self.forget_before(cursor); + Ok(Some(range)) + } Err(Halt::Fail(e)) => Err(e), } } @@ -185,6 +208,36 @@ impl ZipIndexOpener { Ok(()) } + /// The index, once [`next_read`](Self::next_read) has nothing more to + /// ask for. `Truncated` if it still needs bytes. + pub fn finish(mut self) -> Result { + if self.next_read()?.is_some() { + return Err(ZipReadError::Truncated); + } + let walk = self.walk.ok_or(ZipReadError::Truncated)?; + Ok(ZipIndex { + len: self.len, + entries: walk.entries, + comment: walk.comment, + offset_shift: walk.offset_shift, + }) + } + + /// Drops supplied bytes before `cursor`: the walk never reads behind it. + fn forget_before(&mut self, cursor: u64) { + self.held.retain_mut(|(start, piece)| { + let end = *start + piece.len() as u64; + if end <= cursor { + return false; + } + if *start < cursor { + piece.drain(..(cursor - *start) as usize); + *start = cursor; + } + true + }); + } + /// `n` bytes at `at`, if one supplied piece holds them all. fn held(&self, at: u64, n: u64) -> Option<&[u8]> { let end = at.checked_add(n)?; @@ -195,13 +248,28 @@ impl ZipIndexOpener { }) } - /// `n` bytes at `at`, or a read of exactly those. + /// `n` bytes at `at`, or a read of those not yet supplied. fn need(&self, at: u64, n: u64) -> Step<&[u8]> { - self.held(at, n).ok_or(Halt::Read(at..at + n)) + self.held(at, n) + .ok_or_else(|| Halt::Read(self.unheld(at, at + n)..at + n)) } - /// Follows [`ZipReader::new`] over the supplied pieces. - fn open(&self) -> Step { + /// Where a read for `at..end` starts: past the end of a supplied piece + /// that covers its beginning, so a caller who supplied part of a read is + /// asked for the rest rather than all of it again. + fn unheld(&self, at: u64, end: u64) -> u64 { + self.held + .iter() + .filter(|(start, _)| *start <= at) + .map(|(start, piece)| start + piece.len() as u64) + .filter(|&piece_end| piece_end > at && piece_end < end) + .max() + .unwrap_or(at) + } + + /// Follows [`ZipReader::new`] over the supplied pieces as far as where + /// the central directory starts. + fn locate(&self) -> Step { let len = self.len; if len < EOCD_LEN as u64 { return Err(ZipReadError::NotAZip.into()); @@ -237,31 +305,40 @@ impl ZipIndexOpener { } let (cd_start, offset_shift) = self.locate_central_directory(eocd, cd_size, cd_offset)?; + Ok(Walk { + comment, + offset_shift, + eocd, + remaining: entry_count, + cursor: cd_start, + entries: Vec::new(), + }) + } - let mut entries = Vec::new(); - let mut cursor = cd_start; - for _ in 0..entry_count { - if u32_at(self.need_directory(cursor, 4, eocd)?, 0)? != CENTRAL_HEADER_SIG { + /// Parses central headers from where `walk` left off, as + /// [`ZipReader::new`]'s loop does, until the count runs out, a header + /// signature is missing, or the next header isn't supplied yet. + fn walk(&self, walk: &mut Walk) -> Step<()> { + let eocd = walk.eocd; + while walk.remaining > 0 { + if u32_at(self.need_directory(walk.cursor, 4, eocd)?, 0)? != CENTRAL_HEADER_SIG { + walk.remaining = 0; break; } - let fixed = self.need_directory(cursor, CENTRAL_HEADER_LEN as u64, eocd)?; + let fixed = self.need_directory(walk.cursor, CENTRAL_HEADER_LEN as u64, eocd)?; let name_len = u64::from(u16_at(fixed, 28)?); let extra_len = u64::from(u16_at(fixed, 30)?); let header = CENTRAL_HEADER_LEN as u64 + name_len + extra_len; - let bytes = self.need_directory(cursor, header, eocd)?; + let bytes = self.need_directory(walk.cursor, header, eocd)?; let (entry, next) = ZipReader::parse_central_entry(bytes, 0)?; - entries.push(entry); - cursor = cursor + walk.entries.push(entry); + walk.cursor = walk + .cursor .checked_add(next as u64) .ok_or(ZipReadError::Truncated)?; + walk.remaining -= 1; } - - Ok(ZipIndex { - len, - entries, - comment, - offset_shift, - }) + Ok(()) } /// As `ZipReader::read_zip64`: the ZIP64 counts, or `None` on any @@ -334,7 +411,8 @@ impl ZipIndexOpener { .min(eocd.saturating_sub(at)) .max(CENTRAL_HEADER_LEN as u64) .min(DIRECTORY_READ); - Err(Halt::Read(at..at.saturating_add(want).min(self.len))) + let end = at.saturating_add(want).min(self.len); + Err(Halt::Read(self.unheld(at, end)..end)) } } } @@ -350,14 +428,7 @@ impl ZipIndexOpener { if let Some(bytes) = self.held(at, n) { return Ok(bytes); } - // Continue the piece `at` starts in, if there is one. - let from = self - .held - .iter() - .filter(|(start, _)| *start <= at) - .map(|(start, piece)| start + piece.len() as u64) - .find(|&piece_end| piece_end > at && piece_end < end) - .unwrap_or(at); + let from = self.unheld(at, end); // Up to the end record in reads of at most DIRECTORY_READ, or a // little past it for a directory whose size field undersells it. let chunk = eocd.saturating_sub(from).clamp(64 * 1024, DIRECTORY_READ); @@ -379,16 +450,12 @@ impl ZipIndex { mut read: impl FnMut(u64, &mut [u8]) -> std::result::Result<(), E>, ) -> std::result::Result { let mut opener = ZipIndexOpener::new(archive_len); - loop { - match opener.step()? { - OpenStep::Read(range) => { - let mut buf = vec![0; (range.end - range.start) as usize]; - read(range.start, &mut buf)?; - opener.supply(range.start, &buf)?; - } - OpenStep::Done(index) => return Ok(index), - } + while let Some(range) = opener.next_read()? { + let mut buf = vec![0; (range.end - range.start) as usize]; + read(range.start, &mut buf)?; + opener.supply(range.start, &buf)?; } + Ok(opener.finish()?) } /// The archive's length, as given when opening. @@ -590,3 +657,84 @@ impl From for std::io::Error { std::io::Error::new(std::io::ErrorKind::InvalidData, e) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// An archive of `n` empty stored entries named by `name`. + fn archive(n: usize, name: impl Fn(usize) -> String) -> Vec { + let mut out = Vec::new(); + let mut central = Vec::new(); + for i in 0..n { + let name = name(i); + let offset = out.len() as u32; + out.extend_from_slice(&LOCAL_HEADER_SIG.to_le_bytes()); + out.extend_from_slice(&[20, 0, 0, 0, 0, 0]); // needed, flags, method + out.extend_from_slice(&[0; 16]); // time, date, crc, sizes + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&[0, 0]); // extra + out.extend_from_slice(name.as_bytes()); + central.extend_from_slice(&CENTRAL_HEADER_SIG.to_le_bytes()); + central.extend_from_slice(&[20, 0, 20, 0, 0, 0, 0, 0]); // made by, needed, flags, method + central.extend_from_slice(&[0; 16]); // time, date, crc, sizes + central.extend_from_slice(&(name.len() as u16).to_le_bytes()); + central.extend_from_slice(&[0; 12]); // extra, comment, disk, attributes + central.extend_from_slice(&offset.to_le_bytes()); + central.extend_from_slice(name.as_bytes()); + } + let cd_offset = out.len() as u32; + out.extend_from_slice(¢ral); + out.extend_from_slice(&EOCD_SIG.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&(n as u16).to_le_bytes()); + out.extend_from_slice(&(n as u16).to_le_bytes()); + out.extend_from_slice(&(central.len() as u32).to_le_bytes()); + out.extend_from_slice(&cd_offset.to_le_bytes()); + out.extend_from_slice(&[0, 0]); + out + } + + #[test] + fn a_big_directory_is_parsed_once_and_not_held_twice() { + // 60,000 entries with 300-byte names: about 21 MB of directory. Only + // the first 64 KiB of each read is supplied, so it arrives in over + // 300 pieces; parsing it again on every one would take minutes. + let data = archive(60_000, |i| format!("{i:0>300}")); + let mut opener = ZipIndexOpener::new(data.len() as u64); + let (mut reads, mut parsed) = (0, 0); + while let Some(range) = opener.next_read().expect("next read") { + reads += 1; + if let Some(walk) = &opener.walk { + assert!(walk.entries.len() >= parsed); + parsed = walk.entries.len(); + // What's held is the tail and less than one header of the + // directory: the rest is parsed and dropped. + let held: u64 = opener.held.iter().map(|(_, p)| p.len() as u64).sum(); + assert!(held <= TAIL_LEN + 1024, "{held} bytes held"); + } + let end = range.end.min(range.start + 65_536); + let bytes = &data[range.start as usize..end as usize]; + opener.supply(range.start, bytes).expect("supply"); + } + assert!(reads > 300, "{reads} reads"); + let index = opener.finish().expect("finish"); + assert_eq!(index.len(), 60_000); + assert_eq!(index.entries()[59_999].name(), format!("{:0>300}", 59_999)); + let memory = ZipReader::new(&data).expect("parse"); + assert_eq!( + format!("{:?}", memory.entries()), + format!("{:?}", index.entries()) + ); + } + + #[test] + fn finishing_early_is_an_error() { + let data = archive(3, |i| format!("f{i}")); + let opener = ZipIndexOpener::new(data.len() as u64); + assert_eq!( + opener.finish().map(|i| i.len()), + Err(ZipReadError::Truncated) + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 233bdc5..d27a627 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -127,7 +127,7 @@ mod accel; mod index; -pub use index::{OpenStep, ZipIndex, ZipIndexOpener}; +pub use index::{ZipIndex, ZipIndexOpener}; use std::borrow::Cow; diff --git a/tests/writer.rs b/tests/writer.rs index 1d1d2dc..0acb7de 100644 --- a/tests/writer.rs +++ b/tests/writer.rs @@ -506,7 +506,7 @@ fn an_unsupported_method_still_enumerates() { // --------------------------------------------------------------------------- use std::cell::RefCell; -use zipview::{OpenStep, PasswordCheck, ZipIndex, ZipIndexOpener}; +use zipview::{PasswordCheck, ZipIndex, ZipIndexOpener}; /// An archive served a range at a time, recording each read. A read past the /// end panics, failing the test. @@ -742,23 +742,18 @@ fn the_opener_asks_only_for_bytes_it_lacks() { let data = build(&entries, ""); let mut opener = ZipIndexOpener::new(data.len() as u64); let mut asked: Vec> = Vec::new(); - let index = loop { - match opener.step().expect("step") { - OpenStep::Read(range) => { - assert!(range.start < range.end && range.end <= data.len() as u64); - assert!(!asked.contains(&range), "asked twice for {range:?}"); - let bytes = &data[range.start as usize..range.end as usize]; - opener.supply(range.start, bytes).expect("supply"); - asked.push(range); - } - OpenStep::Done(index) => break index, - } - }; - assert_eq!(index.len(), 3000); + while let Some(range) = opener.next_read().expect("next read") { + assert!(range.start < range.end && range.end <= data.len() as u64); + assert!(!asked.contains(&range), "asked twice for {range:?}"); + let bytes = &data[range.start as usize..range.end as usize]; + opener.supply(range.start, bytes).expect("supply"); + asked.push(range); + } assert_eq!( opener.supply(data.len() as u64 - 1, b"ab"), Err(ZipReadError::BadOffset) ); + assert_eq!(opener.finish().expect("finish").len(), 3000); } /// An archive mostly of zeros it never stores: `pieces` are its real bytes