diff --git a/crates/ec-inflate/Cargo.toml b/crates/ec-inflate/Cargo.toml new file mode 100644 index 00000000..a138dca6 --- /dev/null +++ b/crates/ec-inflate/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "ec-inflate" +description = "DEFLATE (RFC 1951) and zlib (RFC 1950) decompression with a hard ceiling on the output." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true + +[dev-dependencies] +flate2 = "1" diff --git a/crates/ec-inflate/src/bits.rs b/crates/ec-inflate/src/bits.rs new file mode 100644 index 00000000..13e238f4 --- /dev/null +++ b/crates/ec-inflate/src/bits.rs @@ -0,0 +1,112 @@ +//! LSB-first bit buffer sized for table-driven Huffman decoding. +//! +//! DEFLATE reads its bits low-end first and its Huffman codes high-bit first, +//! so decoding wants to *look* at the next fifteen bits before knowing how many +//! of them belong to the code. [`ec_core::BitReaderLsb`] has no peek and refills +//! one bit at a time, so this is its own accumulator: up to 64 bits in a `u64`, +//! refilled a byte at a time, peeked without consuming. +//! +//! Past the end of the input the buffer reads as zeros; a code that would need +//! those zeros fails at [`Bits::consume`] with [`Error::Truncated`]. Nothing +//! here ever indexes out of bounds or panics on short input. + +use crate::Error; + +pub(crate) struct Bits<'a> { + src: &'a [u8], + /// Index of the next byte to pull into `buf`. + pos: usize, + /// The lowest `count` bits are real; everything above is zero padding. + buf: u64, + count: u32, +} + +impl<'a> Bits<'a> { + pub(crate) fn new(src: &'a [u8]) -> Bits<'a> { + Bits { + src, + pos: 0, + buf: 0, + count: 0, + } + } + + /// Top the accumulator up to at least 57 bits, input permitting. + /// + /// Away from the end of the input that is one unaligned 64-bit load: the + /// eight bytes are OR'd in above what is already there and the cursor moves + /// by however many of them fit, which is the whole cost of a symbol for + /// most symbols. + #[inline] + pub(crate) fn refill(&mut self) { + if let Some(next) = self.src.get(self.pos..self.pos + 8) { + let bytes = u64::from_le_bytes(next.try_into().expect("an eight byte slice")); + self.buf |= bytes << self.count; + self.pos += ((63 - self.count) >> 3) as usize; + self.count |= 56; + return; + } + while self.count <= 56 && self.pos < self.src.len() { + self.buf |= (self.src[self.pos] as u64) << self.count; + self.pos += 1; + self.count += 8; + } + } + + /// The next `n` bits (`n <= 32`), zero-padded past end of input. + #[inline] + pub(crate) fn peek(&self, n: u32) -> u32 { + self.peek_at(0, n) + } + + /// The `n` bits sitting `skip` bits ahead (`skip + n <= 32`). + #[inline] + pub(crate) fn peek_at(&self, skip: u32, n: u32) -> u32 { + ((self.buf >> skip) & ((1u64 << n) - 1)) as u32 + } + + /// Drop `n` bits already accounted for by a peek. + #[inline] + pub(crate) fn consume(&mut self, n: u32) -> Result<(), Error> { + if n > self.count { + return Err(Error::Truncated); + } + self.buf >>= n; + self.count -= n; + Ok(()) + } + + /// Read `n` bits (`n <= 32`) as a value. + #[inline] + pub(crate) fn take(&mut self, n: u32) -> Result { + if n == 0 { + return Ok(0); + } + self.refill(); + let value = self.peek(n); + self.consume(n)?; + Ok(value) + } + + /// Drop the partial byte and hand back the byte offset now current. + /// + /// The accumulator is emptied, so the caller can read whole bytes straight + /// out of the source slice (stored blocks, the zlib trailer). + pub(crate) fn align(&mut self) -> usize { + let whole = (self.count / 8) as usize; + self.buf = 0; + self.count = 0; + self.pos -= whole; + self.pos + } + + /// Move the byte cursor after a direct read from the source slice. + pub(crate) fn seek(&mut self, pos: usize) { + debug_assert_eq!(self.count, 0, "seek on an unaligned reader"); + self.pos = pos; + } + + pub(crate) fn src(&self) -> &'a [u8] { + self.src + } +} diff --git a/crates/ec-inflate/src/huffman.rs b/crates/ec-inflate/src/huffman.rs new file mode 100644 index 00000000..1a217f25 --- /dev/null +++ b/crates/ec-inflate/src/huffman.rs @@ -0,0 +1,160 @@ +//! Canonical Huffman decoding through a two-level lookup table. +//! +//! A code is at most fifteen bits, so one flat 32768-entry table would decode +//! in a single load — and cost more to build than most Matroska blocks cost to +//! inflate. Instead the first `root_bits` bits index a small root table; the +//! few codes longer than that point at a sub-table indexed by their remaining +//! bits. Both levels are one indexed load, so no code is ever walked bit by bit. +//! +//! Codes are stored bit-reversed, because DEFLATE packs a code high bit first +//! into a stream that is read low bit first: reversing at build time turns +//! decoding into "peek `root_bits`, index". + +use crate::Error; +use crate::bits::Bits; + +/// Longest code RFC 1951 permits. +pub(crate) const MAX_BITS: u32 = 15; + +/// Entry layout: `0` is "no code here"; otherwise bit 31 marks a sub-table +/// link (`sub_bits` in 24..28, offset in 0..24) and a leaf holds the symbol in +/// 4..20 with its code length in 0..4. +const SUB_FLAG: u32 = 1 << 31; + +pub(crate) struct Table { + root_bits: u32, + root: Vec, + subs: Vec, +} + +impl Table { + /// Build from one code length per symbol (`0` = symbol absent). + /// + /// `root_bits` is the first-level width; codes longer than it get a + /// sub-table. An over-subscribed set is always corrupt. An incomplete one + /// is corrupt too, except for the single-code case RFC 1951 allows for a + /// distance tree that a stream never actually uses. + pub(crate) fn new(lengths: &[u16], root_bits: u32) -> Result { + let mut count = [0u32; MAX_BITS as usize + 1]; + let mut max_len = 0; + for &l in lengths { + if l as u32 > MAX_BITS { + return Err(Error::corrupt("Huffman code length above 15")); + } + if l > 0 { + count[l as usize] += 1; + max_len = max_len.max(l as u32); + } + } + if max_len == 0 { + // No symbols at all: legal to declare, corrupt to use. + return Ok(Table { + root_bits: 1, + root: vec![0; 2], + subs: Vec::new(), + }); + } + + let mut left = 1i64; + let mut total = 0u32; + for &at_length in count.iter().skip(1) { + left = (left << 1) - at_length as i64; + if left < 0 { + return Err(Error::corrupt("over-subscribed Huffman code")); + } + total += at_length; + } + if left > 0 && total > 1 { + return Err(Error::corrupt("incomplete Huffman code")); + } + + let mut next = [0u32; MAX_BITS as usize + 2]; + let mut code = 0u32; + for l in 1..=MAX_BITS as usize { + code = (code + count[l - 1]) << 1; + next[l] = code; + } + let mut codes = vec![0u32; lengths.len()]; + for (sym, &l) in lengths.iter().enumerate() { + if l > 0 { + codes[sym] = next[l as usize]; + next[l as usize] += 1; + } + } + + let root_bits = root_bits.min(max_len).max(1); + let root_mask = (1u32 << root_bits) - 1; + let mut root = vec![0u32; 1 << root_bits]; + let mut subs = Vec::new(); + + // How wide each sub-table has to be, before anything is written into it. + let mut sub_len = vec![0u32; 1 << root_bits]; + for (sym, &l) in lengths.iter().enumerate() { + let l = l as u32; + if l > root_bits { + let prefix = (reverse(codes[sym], l) & root_mask) as usize; + sub_len[prefix] = sub_len[prefix].max(l - root_bits); + } + } + for (prefix, &bits) in sub_len.iter().enumerate() { + if bits > 0 { + let offset = subs.len() as u32; + subs.resize(subs.len() + (1 << bits), 0); + root[prefix] = SUB_FLAG | (bits << 24) | offset; + } + } + + for (sym, &l) in lengths.iter().enumerate() { + let l = l as u32; + if l == 0 { + continue; + } + let rev = reverse(codes[sym], l); + let leaf = ((sym as u32) << 4) | l; + if l <= root_bits { + let mut i = rev; + while i < 1 << root_bits { + root[i as usize] = leaf; + i += 1 << l; + } + } else { + let link = root[(rev & root_mask) as usize]; + let bits = (link >> 24) & 0xf; + let offset = (link & 0x00ff_ffff) as usize; + let mut i = rev >> root_bits; + while i < 1 << bits { + subs[offset + i as usize] = leaf; + i += 1 << (l - root_bits); + } + } + } + + Ok(Table { + root_bits, + root, + subs, + }) + } + + /// Decode one symbol, consuming exactly its code. + #[inline] + pub(crate) fn decode(&self, bits: &mut Bits) -> Result { + bits.refill(); + let mut entry = self.root[bits.peek(self.root_bits) as usize]; + if entry & SUB_FLAG != 0 { + let width = (entry >> 24) & 0xf; + let offset = (entry & 0x00ff_ffff) as usize; + entry = self.subs[offset + bits.peek_at(self.root_bits, width) as usize]; + } + if entry == 0 { + return Err(Error::corrupt("Huffman code not in the tree")); + } + bits.consume(entry & 0xf)?; + Ok((entry >> 4) as u16) + } +} + +/// The low `n` bits of `code`, reversed. +fn reverse(code: u32, n: u32) -> u32 { + code.reverse_bits() >> (32 - n) +} diff --git a/crates/ec-inflate/src/inflate.rs b/crates/ec-inflate/src/inflate.rs new file mode 100644 index 00000000..584bb8ec --- /dev/null +++ b/crates/ec-inflate/src/inflate.rs @@ -0,0 +1,213 @@ +//! The RFC 1951 block loop. + +use std::sync::OnceLock; + +use crate::Error; +use crate::bits::Bits; +use crate::huffman::Table; + +/// First-level table width for the literal/length and code-length alphabets. +const LIT_ROOT: u32 = 9; +/// Distances have thirty symbols; a narrower root keeps the table cache-warm. +const DIST_ROOT: u32 = 6; + +/// Match length per literal/length symbol 257..=285, plus its extra-bit count. +const LEN_BASE: [u16; 29] = [ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, + 163, 195, 227, 258, +]; +const LEN_EXTRA: [u32; 29] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, +]; +/// Match distance per distance symbol 0..=29, plus its extra-bit count. +const DIST_BASE: [u32; 30] = [ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, + 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, +]; +const DIST_EXTRA: [u32; 30] = [ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, + 13, +]; +/// The order dynamic blocks list their code-length code lengths in. +const CODE_LENGTH_ORDER: [usize; 19] = [ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15, +]; + +/// The fixed literal/length and distance trees of RFC 1951 §3.2.6, built once. +fn fixed_tables() -> &'static (Table, Table) { + static FIXED: OnceLock<(Table, Table)> = OnceLock::new(); + FIXED.get_or_init(|| { + let mut lit = [0u16; 288]; + for (sym, l) in lit.iter_mut().enumerate() { + *l = match sym { + 0..=143 => 8, + 144..=255 => 9, + 256..=279 => 7, + _ => 8, + }; + } + // All thirty-two distance slots are five bits wide; 30 and 31 decode to + // symbols that no valid stream uses, and are refused below. + let dist = [5u16; 32]; + ( + Table::new(&lit, LIT_ROOT).expect("fixed literal tree is well formed"), + Table::new(&dist, DIST_ROOT).expect("fixed distance tree is well formed"), + ) + }) +} + +/// Decode every block of a raw DEFLATE stream into `out`, stopping at the final +/// one; returns the byte offset just past the stream. +pub(crate) fn blocks(bits: &mut Bits, out: &mut Vec, limit: usize) -> Result { + loop { + let last = bits.take(1)? == 1; + match bits.take(2)? { + 0 => stored(bits, out, limit)?, + 1 => { + let (lit, dist) = fixed_tables(); + compressed(bits, out, limit, lit, dist)?; + } + 2 => { + let (lit, dist) = dynamic_tables(bits)?; + compressed(bits, out, limit, &lit, &dist)?; + } + _ => return Err(Error::corrupt("reserved DEFLATE block type 3")), + } + if last { + return Ok(bits.align()); + } + } +} + +/// §3.2.4 stored block: byte-aligned, length and its complement, then raw bytes. +fn stored(bits: &mut Bits, out: &mut Vec, limit: usize) -> Result<(), Error> { + let pos = bits.align(); + let src = bits.src(); + let header = src.get(pos..pos + 4).ok_or(Error::Truncated)?; + let len = u16::from_le_bytes([header[0], header[1]]); + let nlen = u16::from_le_bytes([header[2], header[3]]); + if len != !nlen { + return Err(Error::corrupt( + "stored block length does not match its complement", + )); + } + let len = len as usize; + let body = src.get(pos + 4..pos + 4 + len).ok_or(Error::Truncated)?; + reserve(out, len, limit)?; + out.extend_from_slice(body); + bits.seek(pos + 4 + len); + Ok(()) +} + +/// §3.2.7 dynamic block header: the code-length code, then the two trees it codes. +fn dynamic_tables(bits: &mut Bits) -> Result<(Table, Table), Error> { + let hlit = bits.take(5)? as usize + 257; + let hdist = bits.take(5)? as usize + 1; + let hclen = bits.take(4)? as usize + 4; + + let mut cl_lengths = [0u16; 19]; + for &slot in CODE_LENGTH_ORDER.iter().take(hclen) { + cl_lengths[slot] = bits.take(3)? as u16; + } + let cl_table = Table::new(&cl_lengths, LIT_ROOT)?; + + let mut lengths = vec![0u16; hlit + hdist]; + let mut i = 0; + while i < lengths.len() { + let (value, run) = match cl_table.decode(bits)? { + sym @ 0..=15 => (sym, 1), + 16 => { + let prev = *lengths + .get(i.wrapping_sub(1)) + .ok_or_else(|| Error::corrupt("code-length repeat with nothing to repeat"))?; + (prev, 3 + bits.take(2)? as usize) + } + 17 => (0, 3 + bits.take(3)? as usize), + 18 => (0, 11 + bits.take(7)? as usize), + _ => return Err(Error::corrupt("code-length symbol above 18")), + }; + if i + run > lengths.len() { + return Err(Error::corrupt("code-length run past the end of the tables")); + } + lengths[i..i + run].fill(value); + i += run; + } + + let lit = Table::new(&lengths[..hlit], LIT_ROOT)?; + let dist = Table::new(&lengths[hlit..], DIST_ROOT)?; + Ok((lit, dist)) +} + +/// The literal/match loop shared by fixed and dynamic blocks. +fn compressed( + bits: &mut Bits, + out: &mut Vec, + limit: usize, + lit: &Table, + dist: &Table, +) -> Result<(), Error> { + loop { + let sym = lit.decode(bits)?; + match sym { + 0..=255 => { + if out.len() == limit { + return Err(Error::LimitExceeded { limit }); + } + out.push(sym as u8); + } + 256 => return Ok(()), + 257..=285 => { + let index = sym as usize - 257; + let length = LEN_BASE[index] as usize + bits.take(LEN_EXTRA[index])? as usize; + let dsym = dist.decode(bits)? as usize; + if dsym >= DIST_BASE.len() { + return Err(Error::corrupt("distance symbol 30 or 31")); + } + let distance = DIST_BASE[dsym] as usize + bits.take(DIST_EXTRA[dsym])? as usize; + if distance > out.len() { + return Err(Error::corrupt("match distance reaches before the output")); + } + reserve(out, length, limit)?; + copy_match(out, distance, length); + } + _ => return Err(Error::corrupt("literal/length symbol 286 or 287")), + } + } +} + +/// LZ77 back-reference. +/// +/// An overlapping match — `distance` one is how DEFLATE spells a run of the +/// same byte — is defined byte by byte, but it does not have to be *copied* +/// byte by byte: each pass copies everything already settled, so the window +/// doubles and a 258-byte run costs eight `memcpy`s rather than 258 pushes. +#[inline] +fn copy_match(out: &mut Vec, distance: usize, length: usize) { + let end = out.len(); + out.resize(end + length, 0); + let (head, tail) = out.split_at_mut(end); + let pattern = &head[end - distance..]; + if distance >= length { + tail.copy_from_slice(&pattern[..length]); + return; + } + tail[..distance].copy_from_slice(pattern); + let mut filled = distance; + while filled < length { + let take = filled.min(length - filled); + let (done, rest) = tail.split_at_mut(filled); + rest[..take].copy_from_slice(&done[..take]); + filled += take; + } +} + +/// The ceiling, checked before every write: a crafted stream must fail, not +/// take all the memory there is. +#[inline] +fn reserve(out: &mut Vec, extra: usize, limit: usize) -> Result<(), Error> { + if out.len() + extra > limit { + return Err(Error::LimitExceeded { limit }); + } + out.reserve(extra); + Ok(()) +} diff --git a/crates/ec-inflate/src/lib.rs b/crates/ec-inflate/src/lib.rs new file mode 100644 index 00000000..abbb2b9b --- /dev/null +++ b/crates/ec-inflate/src/lib.rs @@ -0,0 +1,239 @@ +//! DEFLATE (RFC 1951) and zlib (RFC 1950) decompression. +//! +//! Two entry points, both one-shot over a complete buffer: [`inflate`] for a +//! raw DEFLATE stream (what PNG's `IDAT` chain and Matroska header stripping +//! hand over) and [`inflate_zlib`] for the same thing inside a zlib wrapper, +//! header checked and Adler-32 verified. +//! +//! Contracts worth knowing before implementing against this crate: +//! +//! - Every call carries a `limit`, the largest output it may produce. A stream +//! that would exceed it stops with [`Error::LimitExceeded`]; a compressed +//! megabyte of zeros is not allowed to become a gigabyte of memory. Pass +//! `usize::MAX` to mean "no ceiling", and mean it. +//! - Malformed input is an error, never a panic. Truncation is +//! [`Error::Truncated`], anything else the format forbids is +//! [`Error::Corrupt`] naming what was wrong. +//! - Decoding is table-driven through a two-level lookup: no Huffman code is +//! walked bit by bit, and the fixed trees are built once per process. +//! +//! Decoder state lives in one struct threaded through the block loop, so +//! resuming across buffer boundaries stays a change to the entry points rather +//! than a rewrite; today the public API is one-shot because both callers are. +//! +//! No async, no unsafe, no external dependencies. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod bits; +mod huffman; +mod inflate; + +use std::fmt; + +use bits::Bits; + +/// Everything a compressed stream can get wrong. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// The stream ended in the middle of a code, a block or the trailer. + Truncated, + /// The stream violates RFC 1950/1951. + Corrupt { + /// What was wrong, e.g. "over-subscribed Huffman code". + context: String, + }, + /// Decompressing further would pass the caller's ceiling. + LimitExceeded { + /// The ceiling that was hit, in bytes. + limit: usize, + }, + /// The zlib trailer disagrees with the data that was decompressed. + Adler32Mismatch { + /// Checksum stored in the trailer. + expected: u32, + /// Checksum of the output actually produced. + actual: u32, + }, + /// A zlib feature this crate does not implement. + Unsupported { + /// The construct that was refused, e.g. "zlib preset dictionary". + what: String, + /// Why it is refused. + why: String, + }, +} + +impl Error { + fn corrupt(context: impl Into) -> Error { + Error::Corrupt { + context: context.into(), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Truncated => write!(f, "truncated deflate stream"), + Error::Corrupt { context } => write!(f, "corrupt deflate stream: {context}"), + Error::LimitExceeded { limit } => { + write!(f, "decompressed output exceeded the {limit} byte limit") + } + Error::Adler32Mismatch { expected, actual } => write!( + f, + "zlib adler32 mismatch: stream says {expected:#010x}, output is {actual:#010x}" + ), + Error::Unsupported { what, why } => write!(f, "unsupported {what}: {why}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for ec_core::Error { + fn from(error: Error) -> ec_core::Error { + match error { + Error::Truncated => ec_core::Error::NeedMore, + Error::Unsupported { what, why } => ec_core::Error::Unsupported { what, why }, + other => ec_core::Error::corrupt(other.to_string()), + } + } +} + +/// Which wrapper, if any, surrounds the DEFLATE data. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Format { + /// Bare RFC 1951 blocks. + Raw, + /// RFC 1950: two header bytes, the blocks, an Adler-32 trailer. + Zlib, +} + +/// Decompress a raw DEFLATE stream, producing at most `limit` bytes. +pub fn inflate(input: &[u8], limit: usize) -> Result, Error> { + let mut out = Vec::new(); + inflate_into(input, &mut out, limit, Format::Raw)?; + Ok(out) +} + +/// Decompress a zlib stream, producing at most `limit` bytes. +/// +/// The two header bytes are checked and the Adler-32 trailer is verified +/// against the output. +pub fn inflate_zlib(input: &[u8], limit: usize) -> Result, Error> { + let mut out = Vec::new(); + inflate_into(input, &mut out, limit, Format::Zlib)?; + Ok(out) +} + +/// Decompress onto the end of an existing buffer. +/// +/// `limit` bounds the total length of `out`, not the bytes added. On failure +/// `out` keeps whatever was decompressed before the error, which is what a +/// caller reporting partial progress wants. +pub fn inflate_into( + input: &[u8], + out: &mut Vec, + limit: usize, + format: Format, +) -> Result<(), Error> { + let start = out.len(); + let body = match format { + Format::Raw => input, + Format::Zlib => zlib_header(input)?, + }; + let mut bits = Bits::new(body); + let end = inflate::blocks(&mut bits, out, limit)?; + if format == Format::Zlib { + let trailer: [u8; 4] = body + .get(end..) + .and_then(|rest| rest.get(..4)) + .ok_or(Error::Truncated)? + .try_into() + .expect("a four byte slice"); + let expected = u32::from_be_bytes(trailer); + let actual = adler32(&out[start..]); + if expected != actual { + return Err(Error::Adler32Mismatch { expected, actual }); + } + } + Ok(()) +} + +/// Validate the RFC 1950 header and hand back the DEFLATE data behind it. +fn zlib_header(input: &[u8]) -> Result<&[u8], Error> { + let (&cmf, &flg) = match (input.first(), input.get(1)) { + (Some(cmf), Some(flg)) => (cmf, flg), + _ => return Err(Error::Truncated), + }; + if cmf & 0x0f != 8 { + return Err(Error::corrupt("zlib compression method is not deflate")); + } + if cmf >> 4 > 7 { + return Err(Error::corrupt("zlib window size above 32 KiB")); + } + if !(cmf as u16 * 256 + flg as u16).is_multiple_of(31) { + return Err(Error::corrupt("zlib header check bits do not divide by 31")); + } + if flg & 0x20 != 0 { + return Err(Error::Unsupported { + what: "zlib preset dictionary".into(), + why: "no caller in this family uses FDICT".into(), + }); + } + Ok(&input[2..]) +} + +/// RFC 1950 §9. Chunked so the sums cannot overflow between reductions. +fn adler32(data: &[u8]) -> u32 { + const BASE: u32 = 65521; + let (mut a, mut b) = (1u32, 0u32); + for chunk in data.chunks(5552) { + for &byte in chunk { + a += byte as u32; + b += a; + } + a %= BASE; + b %= BASE; + } + (b << 16) | a +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn adler32_matches_the_rfc_example() { + // zlib's own documented value for "abc" and the empty string. + assert_eq!(adler32(b""), 1); + assert_eq!(adler32(b"abc"), 0x024d_0127); + // Long input exercises the chunked reduction. + assert_eq!(adler32(&vec![0xa5; 100_000]), 0x5afa_d3d6); + } + + #[test] + fn zlib_header_is_checked() { + assert!(matches!(zlib_header(&[]), Err(Error::Truncated))); + assert!(matches!(zlib_header(&[0x78]), Err(Error::Truncated))); + assert!(matches!( + zlib_header(&[0x79, 0x9c]), + Err(Error::Corrupt { .. }) + )); + assert!(matches!( + zlib_header(&[0x88, 0x9c]), + Err(Error::Corrupt { .. }) + )); + assert!(matches!( + zlib_header(&[0x78, 0x9d]), + Err(Error::Corrupt { .. }) + )); + assert!(matches!( + zlib_header(&[0x78, 0xbb]), + Err(Error::Unsupported { .. }) + )); + assert_eq!(zlib_header(&[0x78, 0x9c, 1, 2]).unwrap(), &[1, 2]); + } +} diff --git a/crates/ec-inflate/tests/inflate.rs b/crates/ec-inflate/tests/inflate.rs new file mode 100644 index 00000000..cd36fd0d --- /dev/null +++ b/crates/ec-inflate/tests/inflate.rs @@ -0,0 +1,215 @@ +//! Round-trip, ceiling and malformed-input tests. +//! +//! flate2's default backend *is* miniz_oxide, so compressing here at every +//! level exercises exactly the encoder whose output edith has to inflate; the +//! comparison is against the original bytes, which is stricter than agreeing +//! with another decoder. + +use std::io::Write; + +use ec_inflate::{Error, Format, inflate, inflate_into, inflate_zlib}; +use flate2::Compression; +use flate2::write::{DeflateEncoder, ZlibEncoder}; + +const NO_LIMIT: usize = usize::MAX; + +/// xorshift64*, so the "random" inputs are the same on every run. +fn pseudo_random(seed: u64, len: usize) -> Vec { + let mut state = seed | 1; + (0..len) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 33) as u8 + }) + .collect() +} + +/// The shapes that pull DEFLATE down different paths: stored blocks, long +/// matches, far distances, literal-only blocks. +fn corpus() -> Vec<(&'static str, Vec)> { + let mut mixed = pseudo_random(7, 40_000); + mixed.extend_from_slice(&mixed.clone()[..20_000]); + mixed.extend(std::iter::repeat_n(b'x', 5_000)); + vec![ + ("empty", Vec::new()), + ("one byte", vec![0x42]), + ( + "text", + "the quick brown fox jumps over the lazy dog. " + .repeat(2_000) + .into_bytes(), + ), + ("zeros", vec![0u8; 200_000]), + ("random", pseudo_random(1, 100_000)), + ("run of one", vec![0xab; 3]), + ("mixed", mixed), + ] +} + +fn zlib(data: &[u8], level: u32) -> Vec { + let mut encoder = ZlibEncoder::new(Vec::new(), Compression::new(level)); + encoder.write_all(data).unwrap(); + encoder.finish().unwrap() +} + +fn raw(data: &[u8], level: u32) -> Vec { + let mut encoder = DeflateEncoder::new(Vec::new(), Compression::new(level)); + encoder.write_all(data).unwrap(); + encoder.finish().unwrap() +} + +#[test] +fn round_trips_every_level_bit_exactly() { + for (name, data) in corpus() { + for level in 0..=9 { + let got = inflate_zlib(&zlib(&data, level), NO_LIMIT) + .unwrap_or_else(|e| panic!("zlib {name} level {level}: {e}")); + assert_eq!(got, data, "zlib {name} level {level}"); + + let got = inflate(&raw(&data, level), NO_LIMIT) + .unwrap_or_else(|e| panic!("raw {name} level {level}: {e}")); + assert_eq!(got, data, "raw {name} level {level}"); + } + } +} + +#[test] +fn limit_is_a_boundary_not_a_panic() { + let data = "a limit is checked before every write. " + .repeat(500) + .into_bytes(); + let stream = zlib(&data, 6); + + assert_eq!(inflate_zlib(&stream, data.len()).unwrap(), data); + assert_eq!( + inflate_zlib(&stream, data.len() - 1), + Err(Error::LimitExceeded { + limit: data.len() - 1 + }) + ); + assert_eq!( + inflate_zlib(&stream, 0), + Err(Error::LimitExceeded { limit: 0 }) + ); + + // Stored blocks take a different write path, so they get their own check. + let stored = zlib(&data, 0); + assert_eq!(inflate_zlib(&stored, data.len()).unwrap(), data); + assert!(inflate_zlib(&stored, data.len() - 1).is_err()); + + // What was decompressed before the ceiling survives, for callers reporting + // partial progress. + let mut partial = Vec::new(); + let error = inflate_into(&stream, &mut partial, 4_096, Format::Zlib).unwrap_err(); + assert_eq!(error, Error::LimitExceeded { limit: 4_096 }); + assert!(!partial.is_empty() && partial.len() <= 4_096); + assert_eq!(partial[..], data[..partial.len()]); +} + +#[test] +fn adler32_mismatch_is_detected() { + let data = b"the trailer has to be checked, or the ceiling is the only guard".to_vec(); + let mut stream = zlib(&data, 6); + let last = stream.len() - 1; + stream[last] ^= 0xff; + assert!(matches!( + inflate_zlib(&stream, NO_LIMIT), + Err(Error::Adler32Mismatch { .. }) + )); + + // The same bytes as raw deflate have no trailer to disagree with. + let body = &zlib(&data, 6)[2..]; + assert_eq!(inflate(body, NO_LIMIT).unwrap(), data); +} + +#[test] +fn truncation_is_an_error() { + let data = pseudo_random(3, 20_000); + let stream = zlib(&data, 6); + for cut in [0, 1, 2, 3, 10, 100, stream.len() - 5, stream.len() - 1] { + assert!( + inflate_zlib(&stream[..cut], NO_LIMIT).is_err(), + "cut at {cut} should not decode" + ); + } +} + +#[test] +fn malformed_input_never_panics() { + let data = "content encodings carry whatever the muxer felt like" + .repeat(40) + .into_bytes(); + let seeds: Vec> = vec![ + zlib(&data, 9), + zlib(&data, 0), + zlib(&data, 1), + raw(&data, 6), + ]; + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + + let mut decoded = 0usize; + for i in 0..10_000 { + let seed = &seeds[i % seeds.len()]; + let mut stream = seed.clone(); + // One to four bit-level mutations, plus the occasional truncation. + for _ in 0..=(next() % 4) { + let at = (next() as usize) % stream.len(); + stream[at] ^= 1 << (next() % 8); + } + if next() % 4 == 0 { + stream.truncate((next() as usize) % seed.len()); + } + let limit = if next() % 8 == 0 { 1_024 } else { 1 << 20 }; + if inflate_zlib(&stream, limit).is_ok() { + decoded += 1; + } + // Raw entry too: no header to reject the garbage early. + let _ = inflate(&stream, limit); + } + // Bit flips inside the compressed body land in a valid stream sometimes; + // if *nothing* ever decoded the loop would be testing the header check only. + assert!(decoded > 0, "no mutated stream ever decoded"); + + for len in [0, 1, 2, 3, 8, 64, 1_000] { + let garbage = pseudo_random(len as u64 + 11, len); + let _ = inflate_zlib(&garbage, NO_LIMIT); + let _ = inflate(&garbage, NO_LIMIT); + } +} + +#[test] +fn refuses_what_it_does_not_implement() { + // FDICT set: header check bits still valid, preset dictionary unsupported. + assert!(matches!( + inflate_zlib(&[0x78, 0xbb, 0, 0, 0, 0, 0, 0], NO_LIMIT), + Err(Error::Unsupported { .. }) + )); + // Block type 3 is reserved. + assert!(matches!( + inflate(&[0b111, 0, 0, 0], NO_LIMIT), + Err(Error::Corrupt { .. }) + )); + // Stored block whose complement does not match. + assert!(matches!( + inflate( + &[0x01, 0x05, 0x00, 0x05, 0x00, b'h', b'e', b'l', b'l', b'o'], + NO_LIMIT + ), + Err(Error::Corrupt { .. }) + )); +} + +#[test] +fn stored_block_decodes_by_hand() { + // Final stored block, len 5, ~len, "hello": the one case with no Huffman. + let stream = [0x01, 0x05, 0x00, 0xfa, 0xff, b'h', b'e', b'l', b'l', b'o']; + assert_eq!(inflate(&stream, NO_LIMIT).unwrap(), b"hello"); +} diff --git a/shims/miniz_oxide/Cargo.toml b/shims/miniz_oxide/Cargo.toml new file mode 100644 index 00000000..c7e63c1d --- /dev/null +++ b/shims/miniz_oxide/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "miniz_oxide" +description = "Compatibility shim: the miniz_oxide surface edith consumes, served by ec-inflate." +version = "0.8.9" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-inflate = { path = "../../crates/ec-inflate", version = "0.1.0" } diff --git a/shims/miniz_oxide/src/lib.rs b/shims/miniz_oxide/src/lib.rs new file mode 100644 index 00000000..d673786f --- /dev/null +++ b/shims/miniz_oxide/src/lib.rs @@ -0,0 +1,134 @@ +//! Compatibility shim carrying the `miniz_oxide` name and version, over +//! [`ec_inflate`]. +//! +//! Only the surface a caller in this family actually consumes is here — edith's +//! Matroska `ContentEncodings` path uses exactly +//! [`inflate::decompress_to_vec_zlib_with_limit`] and the `Display` of the error +//! it returns. Field names, statuses and message strings match miniz_oxide +//! 0.8.9 so a `[patch.crates-io]` swap needs no source change; anything else the +//! upstream crate exposes is deliberately absent, so a new use shows up as a +//! compile error rather than as silently different behaviour. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +/// Decompression, as `miniz_oxide::inflate`. +pub mod inflate { + use ec_inflate::Error; + + /// Return status codes, as miniz_oxide spells them. + #[repr(i8)] + #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] + pub enum TINFLStatus { + /// More input was expected but the caller said there is no more. + FailedCannotMakeProgress = -4, + /// The output buffer is an invalid size. + BadParam = -3, + /// Decompression went fine but the Adler-32 did not match. + Adler32Mismatch = -2, + /// Failed to decompress due to invalid data. + Failed = -1, + /// Finished decompression without issues. + Done = 0, + /// The decompressor needs more input data to continue. + NeedsMoreInput = 1, + /// There is still pending data that did not fit in the output buffer. + HasMoreOutput = 2, + } + + /// Failure of a `decompress_to_vec*` call, with the data decoded so far. + #[derive(Debug)] + pub struct DecompressError { + /// Decompressor status on failure. + pub status: TINFLStatus, + /// The currently decompressed data, if any. + pub output: Vec, + } + + impl core::fmt::Display for DecompressError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(match self.status { + TINFLStatus::FailedCannotMakeProgress => "Truncated input stream", + TINFLStatus::BadParam => "Invalid output buffer size", + TINFLStatus::Adler32Mismatch => "Adler32 checksum mismatch", + TINFLStatus::Failed => "Invalid input data", + TINFLStatus::Done => "", + TINFLStatus::NeedsMoreInput => "Truncated input stream", + TINFLStatus::HasMoreOutput => "Output size exceeded the specified limit", + }) + } + } + + impl std::error::Error for DecompressError {} + + /// Decompress zlib-wrapped data, growing the output to at most `max_size`. + /// + /// Over the limit the error carries [`TINFLStatus::HasMoreOutput`] and the + /// bytes decompressed so far, as upstream does. + pub fn decompress_to_vec_zlib_with_limit( + input: &[u8], + max_size: usize, + ) -> Result, DecompressError> { + let mut output = Vec::new(); + match ec_inflate::inflate_into(input, &mut output, max_size, ec_inflate::Format::Zlib) { + Ok(()) => Ok(output), + Err(error) => Err(DecompressError { + status: match error { + Error::Truncated => TINFLStatus::FailedCannotMakeProgress, + Error::LimitExceeded { .. } => TINFLStatus::HasMoreOutput, + Error::Adler32Mismatch { .. } => TINFLStatus::Adler32Mismatch, + Error::Corrupt { .. } | Error::Unsupported { .. } => TINFLStatus::Failed, + }, + output, + }), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + /// `zlib.compress(b"edith reads this out of a Matroska ContentEncodings block" * 4, 9)`. + const STREAM: [u8; 66] = [ + 0x78, 0xda, 0xd5, 0xcb, 0xc1, 0x0d, 0x80, 0x30, 0x0c, 0x03, 0xc0, 0x55, 0xbc, 0x0b, + 0xe2, 0xc9, 0x10, 0xa1, 0x09, 0xb4, 0x2a, 0x8a, 0xa5, 0xc6, 0xec, 0xcf, 0x1c, 0xdc, + 0xff, 0xc2, 0x87, 0x3a, 0x56, 0x98, 0x17, 0xd4, 0x47, 0x81, 0xaf, 0xc0, 0x0b, 0x86, + 0xc3, 0xb4, 0x58, 0xd3, 0xb0, 0x31, 0x15, 0xa9, 0x3d, 0x1b, 0x7d, 0xe4, 0x5d, 0x38, + 0x1f, 0xb6, 0x19, 0xff, 0x89, 0x1f, 0xb5, 0xdd, 0x54, 0x95, + ]; + const PLAIN: &[u8] = b"edith reads this out of a Matroska ContentEncodings block"; + + /// The call site: engine/src/demux.rs, `Unpack::Zlib`. + #[test] + fn decompresses_under_the_limit() { + let out = decompress_to_vec_zlib_with_limit(&STREAM, 64 << 20).unwrap(); + assert_eq!(out.len(), PLAIN.len() * 4); + assert_eq!(&out[..PLAIN.len()], PLAIN); + } + + #[test] + fn over_the_limit_reports_has_more_output_with_partial_data() { + let error = decompress_to_vec_zlib_with_limit(&STREAM, 64).unwrap_err(); + assert_eq!(error.status, TINFLStatus::HasMoreOutput); + assert!(error.output.len() <= 64); + assert_eq!( + error.to_string(), + "Output size exceeded the specified limit" + ); + } + + #[test] + fn a_broken_stream_reports_its_status() { + let mut broken = STREAM; + let last = broken.len() - 1; + broken[last] ^= 0xff; + let error = decompress_to_vec_zlib_with_limit(&broken, 64 << 20).unwrap_err(); + assert_eq!(error.status, TINFLStatus::Adler32Mismatch); + assert_eq!(error.to_string(), "Adler32 checksum mismatch"); + + let error = decompress_to_vec_zlib_with_limit(&STREAM[..20], 64 << 20).unwrap_err(); + assert_eq!(error.status, TINFLStatus::FailedCannotMakeProgress); + assert_eq!(error.to_string(), "Truncated input stream"); + } + } +}