forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeb83b6fTahinli3 months ago495 commits

lib.rs239 lines, 7.7 KiBHistoryRawDownload
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
29mod bits;
30mod huffman;
31mod inflate;
32
33use std::fmt;
34
35use bits::Bits;
36
37/// Everything a compressed stream can get wrong.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub 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
68impl Error {
69 fn corrupt(context: impl Into<String>) -> Error {
70 Error::Corrupt {
71 context: context.into(),
72 }
73 }
74}
75
76impl 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
93impl std::error::Error for Error {}
94
95impl 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)]
107pub 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.
115pub 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.
125pub 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.
136pub 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.
166fn 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.
190fn 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)]
205mod 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}