zip: add SeekableArchive streaming reader and seekable entry-count guard (#2406)

This commit is contained in:
Dylan M. Taylor
2026-11-19 12:27:57 -05:00
committed by GitHub
parent d7c9632bfb
commit 5c496f6e96
3 changed files with 392 additions and 5 deletions
+96 -1
View File
@@ -8,6 +8,8 @@
//! reader's limit is refused before `zip` parses anything. Anything else that is wrong is left for
//! `zip` to report.
use std::io::{Read, Seek, SeekFrom};
use crate::Error;
const EOCD: &[u8; 4] = b"PK\x05\x06";
@@ -74,6 +76,86 @@ pub fn check_entry_count(bytes: &[u8], max_entries: u64) -> Result<(), Error> {
Ok(())
}
/// Like [`check_entry_count`], but reads only the trailing end records and any referenced ZIP64
/// end record from a seekable stream without buffering the archive in memory.
pub fn check_entry_count_seekable<R: Read + Seek>(reader: &mut R, max_entries: u64) -> Result<(), Error> {
let io_err = |e: std::io::Error| Error::NotZip(e.to_string());
let len = reader.seek(SeekFrom::End(0)).map_err(io_err)?;
let tail_len = len.min(22 + u64::from(u16::MAX));
let tail_start = len - tail_len;
let tail_len_usize = usize::try_from(tail_len).map_err(|_| Error::NotZip("tail too large".into()))?;
reader.seek(SeekFrom::Start(tail_start)).map_err(io_err)?;
let mut tail = vec![0u8; tail_len_usize];
reader.read_exact(&mut tail).map_err(io_err)?;
let u16_at = |b: &[u8], at: usize| b.get(at..at.checked_add(2)?).map(|s| u16::from_le_bytes([s[0], s[1]]));
let u32_at = |b: &[u8], at: usize| b.get(at..at.checked_add(4)?).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]));
let u64_at = |b: &[u8], at: usize| b.get(at..at.checked_add(8)?).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(u64::from_le_bytes);
let refuse =
|n: u64| -> Result<(), Error> { if n > max_entries { Err(Error::TooManyEntries { declared: n, limit: max_entries }) } else { Ok(()) } };
let mut end = tail.len();
let mut seen = 0;
while let Some(at) = tail.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) {
end = at;
seen += 1;
if seen > MAX_END_RECORDS {
return Err(Error::TooManyEndRecords(MAX_END_RECORDS));
}
let Some(comment) = u16_at(&tail, at + 20) else { continue };
if at + 22 + usize::from(comment) > tail.len() {
continue;
}
let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(&tail, at + 8), u16_at(&tail, at + 10), u32_at(&tail, at + 16)) else {
continue;
};
let zip64 = total == u16::MAX || u32_at(&tail, at + 12) == Some(u32::MAX) || cd_offset == u32::MAX;
if zip64
&& let Some(locator) = at.checked_sub(20)
&& tail.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice())
{
let (Some(eocd64), Some(disks)) = (u64_at(&tail, locator + 8), u32_at(&tail, locator + 16)) else { continue };
let locator_pos = tail_start + locator as u64;
if eocd64 >= locator_pos || disks > 1 {
continue;
}
let span = (locator_pos - eocd64).min(65_536);
let mut buf;
let slice = if let Some(in_tail) = eocd64.checked_sub(tail_start).and_then(|o| usize::try_from(o).ok()) {
tail.get(in_tail..locator).unwrap_or_default()
} else {
let span_usize = usize::try_from(span).unwrap_or(65_536);
reader.seek(SeekFrom::Start(eocd64)).map_err(io_err)?;
buf = vec![0u8; span_usize];
reader.read_exact(&mut buf).map_err(io_err)?;
&buf
};
for (i, _) in slice.windows(4).enumerate().filter(|(_, w)| *w == EOCD64) {
refuse(u64_at(slice, i + 24).unwrap_or(0).max(u64_at(slice, i + 32).unwrap_or(0)))?;
}
continue;
}
if total == 0 {
return Ok(());
}
let cd = u64::from(cd_offset);
let at_pos = tail_start + at as u64;
if cd < at_pos {
let has_cd = if let Some(in_tail) = cd.checked_sub(tail_start).and_then(|o| usize::try_from(o).ok()) {
tail.get(in_tail..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER))
} else {
let mut sig = [0u8; 4];
reader.seek(SeekFrom::Start(cd)).map_err(io_err)?;
reader.read_exact(&mut sig).is_ok() && &sig == CENTRAL_HEADER
};
if has_cd {
return refuse(u64::from(on_disk.max(total)));
}
}
}
Ok(())
}
/// A package of one empty stored file, `a`, whose central directory lists it `entries` times (at
/// most as many as fit in 64 MiB) under a ZIP64 end record that declares them all: `zip`
/// parses and keeps every one of them before its caller can count them. Regression input for the
@@ -125,7 +207,8 @@ pub fn zip64_entry_count_sample(entries: u64) -> Vec<u8> {
#[cfg(test)]
mod tests {
use super::{CENTRAL_HEADER, EOCD, check_entry_count as check, zip64_entry_count_sample};
use super::{CENTRAL_HEADER, EOCD, check_entry_count as check, check_entry_count_seekable, zip64_entry_count_sample};
use crate::Error;
/// A plain package's tail: one central header at 0, then an end record declaring `entries`.
@@ -200,4 +283,16 @@ mod tests {
let f: Vec<u8> = (0..20).flat_map(|_| EOCD.iter().copied().chain(record)).collect();
assert_eq!(check(&f, 20_000), Err(Error::TooManyEndRecords(16)));
}
#[test]
fn seekable_entry_count_matches_in_memory_guard() {
use std::io::Cursor;
let sample = zip64_entry_count_sample(20_001);
assert_eq!(check_entry_count_seekable(&mut Cursor::new(&sample), 20_000), Err(Error::TooManyEntries { declared: 20_001, limit: 20_000 }));
assert!(check_entry_count_seekable(&mut Cursor::new(zip64_entry_count_sample(5)), 20_000).is_ok());
let padded = plain(30_000, &vec![b'c'; 65_000]);
assert_eq!(check_entry_count_seekable(&mut Cursor::new(&padded), 20_000), Err(Error::TooManyEntries { declared: 30_000, limit: 20_000 }));
}
}
+2 -2
View File
@@ -34,11 +34,11 @@ mod seekable;
mod write;
pub use archive::{Archive, Limits};
pub use guard::check_entry_count;
#[cfg(any(test, feature = "test-support"))]
pub use guard::zip64_entry_count_sample;
pub use guard::{check_entry_count, check_entry_count_seekable};
pub use metadata_reader::{Indexing, MetadataReader};
pub use seekable::{InspectError, inspect_seekable};
pub use seekable::{EntryReader, InspectError, SeekableArchive, SeekableLimits, inspect_seekable};
pub use write::{Compression, Writer};
/// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256
+294 -2
View File
@@ -1,6 +1,9 @@
//! Checks for an already indexed, seekable ZIP archive.
//! Checks and streaming reader for seekable ZIP archives.
use std::io::{Read, Seek};
use std::borrow::Cow;
use std::io::{self, Read, Seek};
use crate::{Budget, Error, MetadataReader, check_entry_count_seekable};
/// Why an indexed seekable archive exceeded its caller's limits.
#[derive(Debug, thiserror::Error)]
@@ -33,6 +36,222 @@ pub fn inspect_seekable<R: Read + Seek>(archive: &mut zip::ZipArchive<R>, max_en
Ok(())
}
/// What a [`SeekableArchive`] refuses to exceed. All numbers are the caller's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SeekableLimits {
/// Most entries the archive may declare.
pub max_entries: u64,
/// Most bytes of trailing metadata (central directory and end records) read while indexing.
pub max_metadata_bytes: u64,
/// Most bytes all the entries read from the archive may expand to together.
pub max_total_bytes: u64,
}
/// A seekable ZIP archive that indexes only the trailing metadata and streams entry payloads
/// without buffering the archive or large entries in memory.
pub struct SeekableArchive<R: Read + Seek> {
zip: zip::ZipArchive<MetadataReader<R>>,
budget: Budget,
}
impl<R: Read + Seek> SeekableArchive<R> {
/// Indexes the trailing metadata of `reader`. The declared entry count is checked before `zip`
/// allocates for the central directory, and indexing is bounded by
/// [`SeekableLimits::max_metadata_bytes`].
pub fn open(mut reader: R, limits: SeekableLimits) -> Result<Self, Error> {
check_entry_count_seekable(&mut reader, limits.max_entries)?;
let (meta_reader, indexing) = MetadataReader::new(reader, limits.max_metadata_bytes).map_err(|e| Error::NotZip(e.to_string()))?;
let zip = zip::ZipArchive::new(meta_reader).map_err(|e| Error::NotZip(e.to_string()))?;
indexing.finish();
let found = zip.len() as u64;
if found > limits.max_entries {
return Err(Error::TooManyEntries { declared: found, limit: limits.max_entries });
}
Ok(Self { zip, budget: Budget::new("archive", limits.max_total_bytes) })
}
/// The number of distinct entry names.
pub fn len(&self) -> usize {
self.zip.len()
}
pub fn is_empty(&self) -> bool {
self.zip.is_empty()
}
/// The name at `index`, copied on demand.
pub fn entry_name(&mut self, index: usize) -> Result<Option<String>, Error> {
if index >= self.zip.len() {
return Ok(None);
}
let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?;
let name = file.name().map_err(|error| Error::NotZip(error.to_string()))?;
Ok(Some(name.into_owned()))
}
/// Whether the entry at `index` is a directory according to ZIP filename conventions.
pub fn entry_is_dir(&mut self, index: usize) -> Result<Option<bool>, Error> {
if index >= self.zip.len() {
return Ok(None);
}
let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?;
Ok(Some(file.is_dir()))
}
/// Declared decoded and compressed sizes at `index`, without name lookup.
pub fn entry_sizes(&mut self, index: usize) -> Result<Option<(u64, u64)>, Error> {
if index >= self.zip.len() {
return Ok(None);
}
let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?;
Ok(Some((file.size(), file.compressed_size())))
}
/// Do two entries' compressed data ranges overlap?
pub fn has_overlapping_files(&mut self) -> Result<bool, Error> {
self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string()))
}
/// The entry names in the archive's order, folders included. Non-UTF-8 names are omitted.
pub fn names(&self) -> impl Iterator<Item = Cow<'_, str>> {
self.zip.file_names().filter_map(Result::ok)
}
/// Is there an entry `name` (exactly as stored)?
pub fn contains(&self, name: &str) -> bool {
self.zip.index_for_name(name).is_some()
}
/// The size entry `name` declares. It is a claim, not a measurement.
pub fn declared_size(&mut self, name: &str) -> Option<u64> {
let index = self.zip.index_for_name(name)?;
self.zip.by_index_raw(index).ok().map(|f| f.size())
}
/// The size entry `name` takes in the archive, compressed.
pub fn compressed_size(&mut self, name: &str) -> Option<u64> {
let index = self.zip.index_for_name(name)?;
self.zip.by_index_raw(index).ok().map(|f| f.compressed_size())
}
/// Is `name` stored without compression?
pub fn is_stored(&mut self, name: &str) -> Option<bool> {
let index = self.zip.index_for_name(name)?;
self.zip.by_index_raw(index).ok().map(|f| f.compression() == zip::CompressionMethod::Stored)
}
/// Open entry `name` for streaming reads, or `None` when there is no such entry.
///
/// The entry may declare and expand to at most `max` bytes, and at most what is left of
/// [`SeekableLimits::max_total_bytes`]. The returned [`EntryReader`] enforces the size cap and
/// verifies the CRC-32 on EOF, charging [`Self::budget`] only when the full entry is read.
pub fn open_entry(&mut self, name: &str, max: u64) -> Result<Option<EntryReader<'_, R>>, Error> {
let Some(index) = self.zip.index_for_name(name) else { return Ok(None) };
self.open_entry_index_named(index, name, max)
}
/// Open the entry at `index` for streaming reads under the same rules as [`Self::open_entry`].
pub fn open_entry_index(&mut self, index: usize, max: u64) -> Result<Option<EntryReader<'_, R>>, Error> {
if index >= self.zip.len() {
return Ok(None);
}
let name = self.entry_name(index)?.unwrap_or_default();
self.open_entry_index_named(index, &name, max)
}
fn open_entry_index_named(&mut self, index: usize, name: &str, max: u64) -> Result<Option<EntryReader<'_, R>>, Error> {
let file = self.zip.by_index(index).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?;
let declared = file.size();
if declared > max {
return Err(Error::EntryTooLarge { name: name.to_string(), limit: max });
}
if declared > self.budget.remaining() {
return Err(Error::BudgetSpent { name: name.to_string(), limit: self.budget.limit() });
}
Ok(Some(EntryReader { file, budget: &mut self.budget, declared, limit: declared, read: 0, finished: false }))
}
/// Read all bytes of entry `name` into memory, or `None` when there is no such entry.
pub fn read(&mut self, name: &str, max: u64) -> Result<Option<Vec<u8>>, Error> {
let Some(index) = self.zip.index_for_name(name) else { return Ok(None) };
self.read_index_named(index, name, max)
}
/// Read all bytes of the entry at `index` into memory.
pub fn read_index(&mut self, index: usize, max: u64) -> Result<Option<Vec<u8>>, Error> {
if index >= self.zip.len() {
return Ok(None);
}
let name = self.entry_name(index)?.unwrap_or_default();
self.read_index_named(index, &name, max)
}
fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result<Option<Vec<u8>>, Error> {
let Some(mut reader) = self.open_entry_index_named(index, name, max)? else { return Ok(None) };
let mut out = Vec::with_capacity(usize::try_from(reader.declared).unwrap_or(64 * 1024).min(64 * 1024));
reader.read_to_end(&mut out).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?;
Ok(Some(out))
}
/// The total budget: what the entries read so far have used, and what is left.
pub fn budget(&self) -> &Budget {
&self.budget
}
/// The total budget, for a caller with its own charging rule.
pub fn budget_mut(&mut self) -> &mut Budget {
&mut self.budget
}
}
/// Streaming reader for a single entry opened from [`SeekableArchive`].
///
/// Enforces the declared and caller-provided byte limits and charges the archive's [`Budget`]
/// once the full entry has been read and its CRC-32 verified.
pub struct EntryReader<'a, R: Read> {
file: zip::read::ZipFile<'a, MetadataReader<R>>,
budget: &'a mut Budget,
declared: u64,
limit: u64,
read: u64,
finished: bool,
}
impl<R: Read> EntryReader<'_, R> {
/// The uncompressed size declared by the entry header.
pub fn declared_size(&self) -> u64 {
self.declared
}
}
impl<R: Read> Read for EntryReader<'_, R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.finished || buf.is_empty() {
return Ok(0);
}
let remaining = self.limit.saturating_sub(self.read);
let max_read = usize::try_from(remaining.saturating_add(1)).unwrap_or(usize::MAX).min(buf.len());
let n = self.file.read(&mut buf[..max_read])?;
if n == 0 {
if self.read < self.declared {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!("entry ended after {} bytes, declared {}", self.read, self.declared),
));
}
self.budget.charge(self.read).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
self.finished = true;
return Ok(0);
}
let next = self.read.saturating_add(n as u64);
if next > self.limit {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("entry exceeds declared size of {} bytes", self.limit)));
}
self.read = next;
Ok(n)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
@@ -72,4 +291,77 @@ mod tests {
let empty = zip::ZipWriter::new(Cursor::new(Vec::new())).finish().unwrap().into_inner();
assert!(inspect_seekable(&mut zip::ZipArchive::new(Cursor::new(empty)).unwrap(), 0, 0).is_ok());
}
#[test]
fn seekable_archive_streams_stored_and_deflated_entries_within_limits() {
let mut writer = crate::Writer::new();
let big: Vec<u8> = (0..50_000u32).flat_map(|i| (i % 251).to_le_bytes()).collect();
writer.add("a.bin", &big, crate::Compression::Deflated).unwrap();
writer.add("b.bin", b"hello stored", crate::Compression::Stored).unwrap();
let bytes = writer.finish().unwrap();
let limits = SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 250_000 };
let mut archive = SeekableArchive::open(Cursor::new(bytes), limits).unwrap();
assert_eq!(archive.len(), 2);
assert!(archive.contains("a.bin"));
assert_eq!(archive.declared_size("a.bin"), Some(big.len() as u64));
// Stream in small chunks without loading via Vec in one shot.
let mut reader = archive.open_entry("a.bin", big.len() as u64).unwrap().unwrap();
let mut out = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let n = reader.read(&mut chunk).unwrap();
if n == 0 {
break;
}
out.extend_from_slice(&chunk[..n]);
}
assert_eq!(out, big);
drop(reader);
assert_eq!(archive.budget().used(), big.len() as u64);
let b = archive.read("b.bin", 100).unwrap().unwrap();
assert_eq!(b, b"hello stored");
assert_eq!(archive.budget().used(), big.len() as u64 + 12);
}
#[test]
fn seekable_archive_enforces_entry_count_size_budget_and_crc() {
let sample = crate::zip64_entry_count_sample(20_001);
let err = SeekableArchive::open(
Cursor::new(sample),
SeekableLimits { max_entries: 20_000, max_metadata_bytes: 16 << 20, max_total_bytes: 1 << 20 },
)
.err()
.unwrap();
assert!(matches!(err, Error::TooManyEntries { declared: 20_001, limit: 20_000 }), "{err:?}");
let mut writer = crate::Writer::new();
writer.add("cat.lrcat", &[7u8; 1024], crate::Compression::Deflated).unwrap();
let bytes = writer.finish().unwrap();
// Entry larger than per-entry max is refused before reading.
let mut archive =
SeekableArchive::open(Cursor::new(&bytes), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 2048 })
.unwrap();
assert!(matches!(archive.open_entry("cat.lrcat", 1023), Err(Error::EntryTooLarge { limit: 1023, .. })));
assert_eq!(archive.budget().used(), 0);
// Entry larger than remaining budget is refused.
let mut tight =
SeekableArchive::open(Cursor::new(&bytes), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 512 }).unwrap();
assert!(matches!(tight.open_entry("cat.lrcat", 2048), Err(Error::BudgetSpent { limit: 512, .. })));
// Corrupted payload fails CRC check and does not charge budget.
let mut bad = bytes.clone();
bad[45] ^= 0xFF;
let mut bad_archive =
SeekableArchive::open(Cursor::new(&bad), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 2048 }).unwrap();
let mut reader = bad_archive.open_entry("cat.lrcat", 2048).unwrap().unwrap();
let mut sink = Vec::new();
assert!(reader.read_to_end(&mut sink).is_err());
drop(reader);
assert_eq!(bad_archive.budget().used(), 0);
}
}