Skip to main content

pdfcer_model/filters/
stream.rs

1//! Windowed decoding of one stream: [`StreamDecoder`].
2//!
3//! A consumer that can work on a stream a piece at a time (the renderer's
4//! content interpreter) reads it through this instead of
5//! [`super::decode_stream`], so a legitimately huge stream is neither
6//! refused by [`MAX_DECODED_LEN`] nor held whole in memory.
7//!
8//! Only the **last** stage of the `/Filter` chain streams. Earlier stages,
9//! a last stage with a `/Predictor`, and the filters that cannot expand
10//! (`ASCIIHexDecode`, `ASCII85Decode`) are decoded whole under the ordinary
11//! ceiling and then served from memory. A real chain is one stage, so this
12//! costs nothing in practice and keeps one decoder per filter.
13
14use std::borrow::Cow;
15
16use super::{FilterError, MAX_DECODED_LEN, Pull, brotli, flate, lzw, predictor, runlength};
17use crate::object::Dict;
18
19/// How far a streamed decode may expand its input: the budget is
20/// `max(MAX_DECODED_LEN, MAX_DECODE_RATIO × encoded length)`.
21///
22/// 64 is above the expansion of any real content stream (text and vector
23/// operators compress roughly 3–10×) and far below a decompression bomb's
24/// (Flate reaches about 1000×). It is pdfcer policy; the standard sets no
25/// such limit (ISO 32000-2 Annex C lists none for decoded stream size).
26pub const MAX_DECODE_RATIO: usize = 64;
27
28/// Outcome of one [`StreamDecoder::read`].
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum ReadStatus {
32    /// Bytes were appended and the stream has more.
33    More,
34    /// The stream ended; the call may still have appended bytes.
35    End,
36    /// The budget ([`StreamDecoder::limit`]) is spent: output stops at
37    /// exactly the limit and the rest of the stream is never decoded.
38    BudgetSpent,
39}
40
41enum Source<'a> {
42    Bytes { data: Cow<'a, [u8]>, pos: usize },
43    Pull(Box<dyn Pull + 'a>),
44}
45
46/// Decodes one stream a chunk at a time under a ratio budget.
47///
48/// # Examples
49///
50/// ```
51/// use pdfcer_model::filters::{ReadStatus, StreamDecoder};
52/// use pdfcer_model::object::Dict;
53///
54/// let dict = Dict::new(); // no /Filter: the raw bytes are the data
55/// let mut dec = StreamDecoder::new(&dict, b"0 0 m 1 1 l S")?;
56/// let mut out = Vec::new();
57/// while dec.read(&mut out)? == ReadStatus::More {}
58/// assert_eq!(out, b"0 0 m 1 1 l S");
59/// # Ok::<(), pdfcer_model::filters::FilterError>(())
60/// ```
61pub struct StreamDecoder<'a> {
62    src: Source<'a>,
63    produced: usize,
64    limit: usize,
65    done: bool,
66}
67
68impl std::fmt::Debug for StreamDecoder<'_> {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.debug_struct("StreamDecoder")
71            .field("produced", &self.produced)
72            .field("limit", &self.limit)
73            .field("done", &self.done)
74            .finish_non_exhaustive()
75    }
76}
77
78impl<'a> StreamDecoder<'a> {
79    /// Prepare to decode `raw` (the stream's encoded bytes) per `dict`'s
80    /// `/Filter` and `/DecodeParms`.
81    ///
82    /// # Errors
83    ///
84    /// [`FilterError`] from parsing the filter chain, or from a stage this
85    /// decodes whole (module docs) — the same errors
86    /// [`super::decode_stream`] would report for it.
87    pub fn new(dict: &Dict, raw: &'a [u8]) -> Result<Self, FilterError> {
88        Self::with_floor(dict, raw, MAX_DECODED_LEN)
89    }
90
91    /// [`Self::new`] with a smaller budget floor, so a test can reach the
92    /// budget without decoding a quarter of a gigabyte.
93    pub(crate) fn with_floor(
94        dict: &Dict,
95        raw: &'a [u8],
96        floor: usize,
97    ) -> Result<Self, FilterError> {
98        let limit = floor.max(raw.len().saturating_mul(MAX_DECODE_RATIO));
99        let src = source(dict, raw)?;
100        Ok(Self {
101            src,
102            produced: 0,
103            limit,
104            done: false,
105        })
106    }
107
108    /// The most bytes this decoder will ever produce.
109    #[must_use]
110    pub fn limit(&self) -> usize {
111        self.limit
112    }
113
114    /// Append the next chunk (about 64 KiB) of decoded bytes to `out`.
115    ///
116    /// # Errors
117    ///
118    /// [`FilterError::Corrupt`] or [`FilterError::Truncated`] when the
119    /// stream is damaged part-way. Bytes decoded before the damage were
120    /// returned by earlier calls; the decoder is finished after an error.
121    pub fn read(&mut self, out: &mut Vec<u8>) -> Result<ReadStatus, FilterError> {
122        if self.done {
123            return Ok(ReadStatus::End);
124        }
125        if self.produced >= self.limit {
126            return Ok(ReadStatus::BudgetSpent);
127        }
128        let before = out.len();
129        let finished = match &mut self.src {
130            Source::Bytes { data, pos } => {
131                let rest = data.get(*pos..).unwrap_or(&[]);
132                let take = rest.len().min(super::CHUNK);
133                out.extend_from_slice(rest.get(..take).unwrap_or(&[]));
134                *pos += take;
135                *pos >= data.len()
136            }
137            Source::Pull(p) => p.pull(out).inspect_err(|_| self.done = true)?,
138        };
139        self.produced += out.len() - before;
140        if self.produced > self.limit {
141            out.truncate(out.len() - (self.produced - self.limit));
142            self.produced = self.limit;
143            self.done = !finished;
144            return Ok(if finished {
145                ReadStatus::End
146            } else {
147                ReadStatus::BudgetSpent
148            });
149        }
150        self.done = finished;
151        Ok(if finished {
152            ReadStatus::End
153        } else {
154            ReadStatus::More
155        })
156    }
157}
158
159/// Build the source for the last stage, decoding everything before it whole.
160fn source<'a>(dict: &Dict, raw: &'a [u8]) -> Result<Source<'a>, FilterError> {
161    let filters = super::filter_names(dict)?;
162    let Some((last, _)) = filters.split_last() else {
163        return Ok(Source::Bytes {
164            data: Cow::Borrowed(raw),
165            pos: 0,
166        });
167    };
168    let n = filters.len();
169    let mut notes = super::FilterNotes::default();
170    let input: Cow<'a, [u8]> = if n > 1 {
171        Cow::Owned(super::decode_prefix(dict, raw, n - 1, &mut notes)?)
172    } else {
173        Cow::Borrowed(raw)
174    };
175    let parms = super::decode_parms_for(dict, n - 1, n);
176    let predicted = predictor::Params::from_dict(parms)?.is_some();
177    let pull: Box<dyn Pull + 'a> = match last.as_slice() {
178        _ if predicted => return whole(last, parms, input, &mut notes),
179        b"FlateDecode" | b"Fl" => Box::new(flate::Inflate::new(input)),
180        b"BrotliDecode" => Box::new(brotli::Unbrotli::new(input)),
181        b"LZWDecode" | b"LZW" => Box::new(lzw::Lzw::new(input, lzw::early_change(parms))),
182        b"RunLengthDecode" | b"RL" => Box::new(runlength::RunLength::new(input)),
183        _ => return whole(last, parms, input, &mut notes),
184    };
185    Ok(Source::Pull(pull))
186}
187
188fn whole<'a>(
189    name: &[u8],
190    parms: Option<&Dict>,
191    input: Cow<'_, [u8]>,
192    notes: &mut super::FilterNotes,
193) -> Result<Source<'a>, FilterError> {
194    Ok(Source::Bytes {
195        data: Cow::Owned(super::apply_one(name, parms, &input, notes)?),
196        pos: 0,
197    })
198}
199
200#[cfg(test)]
201#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
202mod tests {
203    use super::*;
204    use crate::object::{Name, Object};
205
206    fn read_all(dict: &Dict, raw: &[u8]) -> (Vec<u8>, ReadStatus) {
207        let mut dec = StreamDecoder::new(dict, raw).unwrap();
208        let mut out = Vec::new();
209        loop {
210            match dec.read(&mut out).unwrap() {
211                ReadStatus::More => {}
212                status => return (out, status),
213            }
214        }
215    }
216
217    fn with_filter(name: &str) -> Dict {
218        let mut d = Dict::new();
219        d.insert(
220            Name::from(b"Filter".as_slice()),
221            Object::Name(Name::from(name.as_bytes())),
222        );
223        d
224    }
225
226    fn sample() -> Vec<u8> {
227        (0..300_000u32)
228            .flat_map(|i| format!("{} {} m ", i % 97, i % 31).into_bytes())
229            .collect()
230    }
231
232    #[test]
233    fn every_streamed_filter_matches_the_whole_decode() {
234        let plain = sample();
235        let cases = [
236            ("FlateDecode", flate::encode(&plain)),
237            ("RunLengthDecode", runlength::encode(&plain)),
238        ];
239        for (name, enc) in cases {
240            let dict = with_filter(name);
241            let (got, status) = read_all(&dict, &enc);
242            assert_eq!(status, ReadStatus::End, "{name}");
243            assert_eq!(
244                got,
245                super::super::decode_stream(&dict, &enc).unwrap(),
246                "{name}"
247            );
248            assert_eq!(got, plain, "{name}");
249        }
250    }
251
252    #[test]
253    fn a_bomb_stops_at_exactly_the_budget() {
254        // 300 MiB of zeros deflates to ~300 KiB: about 1000x.
255        let enc = flate::encode(&vec![0u8; 300 << 20]);
256        let dict = with_filter("FlateDecode");
257        let (got, status) = read_all(&dict, &enc);
258        assert_eq!(status, ReadStatus::BudgetSpent);
259        assert_eq!(got.len(), MAX_DECODED_LEN.max(enc.len() * MAX_DECODE_RATIO));
260        assert!(got.iter().all(|&b| b == 0));
261    }
262
263    #[test]
264    fn the_budget_is_the_ratio_once_that_exceeds_the_ceiling() {
265        let raw = vec![b' '; 5 << 20];
266        let dec = StreamDecoder::new(&Dict::new(), &raw).unwrap();
267        assert_eq!(dec.limit(), raw.len() * MAX_DECODE_RATIO);
268        assert!(dec.limit() > MAX_DECODED_LEN);
269    }
270
271    #[test]
272    fn truncation_is_an_error_after_the_prefix() {
273        let plain = sample();
274        let enc = flate::encode(&plain);
275        let cut = enc.get(..enc.len() / 2).unwrap();
276        let mut dec = StreamDecoder::new(&with_filter("FlateDecode"), cut).unwrap();
277        let mut out = Vec::new();
278        let err = loop {
279            match dec.read(&mut out) {
280                Ok(ReadStatus::More) => {}
281                Ok(s) => panic!("expected an error, got {s:?}"),
282                Err(e) => break e,
283            }
284        };
285        assert!(matches!(err, FilterError::Truncated { .. }), "{err:?}");
286        assert!(!out.is_empty() && plain.starts_with(&out));
287        assert_eq!(dec.read(&mut out).unwrap(), ReadStatus::End);
288    }
289}