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