Skip to main content

pdfcer_model/content/
chunked.rs

1//! Windowed reading of content: [`ContentChunks`].
2//!
3//! The renderer reads a page's `/Contents` (or a form, pattern or glyph
4//! procedure) through this rather than [`ContentStream::from_page`], so a
5//! content stream of any size is decoded and tokenized a window at a time
6//! and never held whole.
7//!
8//! Each window ends just after an operator or inline image, so no
9//! operation straddles two windows and a consumer that runs each window's
10//! [`ContentStream::operations`] in turn sees exactly the operations a
11//! whole parse would yield. Tokens ending within a few bytes of the bytes
12//! read so far are held back to the next window, because a number, name or
13//! `EI` cut by the window edge looks complete.
14
15use super::{ContentError, ContentStream, ContentTokenKind, tokenize};
16use crate::filters::{ReadStatus, StreamDecoder};
17use crate::object::{Dict, ObjId, Object};
18use crate::page_tree::Page;
19use crate::view::DocumentView;
20
21/// Bytes aimed for per window.
22const WINDOW: usize = 4 << 20;
23/// Largest window tried before a parse error or operator-less run is final.
24const MAX_WINDOW: usize = 256 << 20;
25/// Tokens ending this close to the bytes read so far wait for more.
26const MARGIN: usize = 16;
27
28/// Why a [`ContentChunks`] stopped before the end of its content.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum ChunkTruncation {
32    /// A stream decoded past its budget
33    /// ([`crate::filters::MAX_DECODE_RATIO`] times its encoded size).
34    Budget,
35    /// No complete operator within the largest window.
36    Overlong,
37}
38
39/// A content stream read a window at a time (module docs).
40///
41/// # Examples
42///
43/// ```
44/// use pdfcer_model::content::ContentChunks;
45/// use pdfcer_model::object::Dict;
46///
47/// let dict = Dict::new();
48/// let mut chunks = ContentChunks::from_stream(&dict, b"0 0 m 10 10 l S");
49/// let mut ops = 0;
50/// while let Some(window) = chunks.next_chunk()? {
51///     ops += window.operations().count();
52/// }
53/// assert_eq!(ops, 3);
54/// # Ok::<(), pdfcer_model::content::ContentError>(())
55/// ```
56#[derive(Debug)]
57pub struct ContentChunks<'a> {
58    sources: Vec<(&'a Dict, &'a [u8])>,
59    next: usize,
60    cur: Option<StreamDecoder<'a>>,
61    started: bool,
62    buf: Vec<u8>,
63    window: usize,
64    ended: bool,
65    pending: Option<ContentError>,
66    truncation: Option<ChunkTruncation>,
67    primed: Option<ContentStream>,
68    emitted: usize,
69    floor: usize,
70}
71
72impl<'a> ContentChunks<'a> {
73    /// A page's `/Contents`, concatenated exactly as
74    /// [`ContentStream::from_page`] concatenates them.
75    ///
76    /// # Errors
77    ///
78    /// [`ContentError::NotAStream`] when a `/Contents` entry does not
79    /// resolve to a stream. Decoding has not started yet.
80    pub fn from_page(view: &DocumentView<'a>, page: &Page) -> Result<Self, ContentError> {
81        let sources = page
82            .contents
83            .iter()
84            .map(|id| stream_of(view, *id))
85            .collect::<Result<_, _>>()?;
86        Ok(Self::new(sources))
87    }
88
89    /// A form XObject's own content, as [`ContentStream::from_form`] reads it.
90    ///
91    /// # Errors
92    ///
93    /// [`ContentError::NotAStream`] when `id` is absent or not a stream.
94    pub fn from_form(view: &DocumentView<'a>, id: ObjId) -> Result<Self, ContentError> {
95        Ok(Self::new(vec![stream_of(view, id)?]))
96    }
97
98    /// One stream given by its dictionary and encoded bytes.
99    #[must_use]
100    pub fn from_stream(dict: &'a Dict, raw: &'a [u8]) -> Self {
101        Self::new(vec![(dict, raw)])
102    }
103
104    fn new(sources: Vec<(&'a Dict, &'a [u8])>) -> Self {
105        Self {
106            sources,
107            next: 0,
108            cur: None,
109            started: false,
110            buf: Vec::new(),
111            window: WINDOW,
112            ended: false,
113            pending: None,
114            truncation: None,
115            primed: None,
116            emitted: 0,
117            floor: crate::filters::MAX_DECODED_LEN,
118        }
119    }
120
121    /// Read the first window now, so a caller can report an error in it
122    /// before committing to the content; [`Self::next_chunk`] then returns
123    /// that window first.
124    ///
125    /// # Errors
126    ///
127    /// As [`Self::next_chunk`] for its first window.
128    pub fn prime(&mut self) -> Result<(), ContentError> {
129        if self.primed.is_none() && self.emitted == 0 {
130            self.primed = self.next_chunk()?;
131        }
132        Ok(())
133    }
134
135    /// Why reading stopped early, once it has.
136    #[must_use]
137    pub fn truncation(&self) -> Option<ChunkTruncation> {
138        self.truncation
139    }
140
141    /// The next window, or `None` after the last.
142    ///
143    /// # Errors
144    ///
145    /// A decode or syntax error. In the first window every error is
146    /// returned, as [`ContentStream::from_page`] would return it. After
147    /// that, a decode error ends the content: the windows decoded before it
148    /// are returned first, then the error once.
149    pub fn next_chunk(&mut self) -> Result<Option<ContentStream>, ContentError> {
150        if let Some(primed) = self.primed.take() {
151            return Ok(Some(primed));
152        }
153        let mut window = self.window;
154        loop {
155            self.fill(window);
156            if self.emitted == 0
157                && let Some(e) = self.pending.take()
158            {
159                self.buf.clear();
160                return Err(e);
161            }
162            if self.buf.is_empty() && self.ended {
163                return self.pending.take().map_or(Ok(None), Err);
164            }
165            let complete = self.ended && self.pending.is_none() && self.truncation.is_none();
166            let mut tokens = Vec::new();
167            let parsed = tokenize(&self.buf, &mut tokens, 0);
168            if complete {
169                let buf = std::mem::take(&mut self.buf);
170                parsed?;
171                self.emitted += 1;
172                return Ok(Some(ContentStream { buf, tokens }));
173            }
174            if let Some(chunk) = self.cut(tokens, window) {
175                self.emitted += 1;
176                return Ok(Some(chunk));
177            }
178            if self.ended {
179                self.buf.clear();
180            } else if window >= MAX_WINDOW {
181                self.ended = true;
182                self.buf.clear();
183                parsed?;
184                self.truncation = Some(ChunkTruncation::Overlong);
185            } else {
186                window = window.max(self.buf.len()).saturating_mul(2);
187            }
188        }
189    }
190
191    /// Split off the bytes and tokens up to the last operator that ends at
192    /// or before `window` (or the first beyond it), outside the margin.
193    fn cut(
194        &mut self,
195        mut tokens: Vec<super::ContentToken>,
196        window: usize,
197    ) -> Option<ContentStream> {
198        let limit = self.buf.len().saturating_sub(MARGIN);
199        let ends = tokens
200            .iter()
201            .filter(|t| {
202                matches!(
203                    t.kind,
204                    ContentTokenKind::Operator | ContentTokenKind::InlineImage { .. }
205                )
206            })
207            .map(|t| t.span.end())
208            .take_while(|&end| end <= limit);
209        let mut cut = None;
210        for end in ends {
211            if cut.is_some() && end > window {
212                break;
213            }
214            cut = Some(end);
215        }
216        let cut = cut?;
217        tokens.retain(|t| t.span.end() <= cut);
218        let rest = self.buf.split_off(cut);
219        let buf = std::mem::replace(&mut self.buf, rest);
220        Some(ContentStream { buf, tokens })
221    }
222
223    /// Decode until `buf` holds `window` bytes or the content ends.
224    fn fill(&mut self, window: usize) {
225        while self.buf.len() < window && !self.ended {
226            if self.cur.is_none() && !self.open_next() {
227                break;
228            }
229            let Some(dec) = self.cur.as_mut() else { break };
230            let before = self.buf.len();
231            let status = dec.read(&mut self.buf);
232            if self.buf.len() > before && !self.started {
233                self.started = true;
234                // ContentStream::from_page's separator, only where there
235                // is something to separate.
236                if self.next > 1 {
237                    self.buf.insert(before, b'\n');
238                }
239            }
240            match status {
241                Ok(ReadStatus::BudgetSpent) => {
242                    self.truncation = Some(ChunkTruncation::Budget);
243                    self.ended = true;
244                }
245                Ok(ReadStatus::End) => self.cur = None,
246                Ok(_) => {}
247                Err(e) => {
248                    self.pending = Some(e.into());
249                    self.ended = true;
250                }
251            }
252        }
253    }
254
255    /// Start the next source; `false` (and ended) when there is none.
256    fn open_next(&mut self) -> bool {
257        let Some(&(dict, raw)) = self.sources.get(self.next) else {
258            self.ended = true;
259            return false;
260        };
261        self.next += 1;
262        self.started = false;
263        match StreamDecoder::with_floor(dict, raw, self.floor) {
264            Ok(dec) => {
265                self.cur = Some(dec);
266                true
267            }
268            Err(e) => {
269                self.pending = Some(e.into());
270                self.ended = true;
271                false
272            }
273        }
274    }
275}
276
277fn stream_of<'a>(view: &DocumentView<'a>, id: ObjId) -> Result<(&'a Dict, &'a [u8]), ContentError> {
278    let Some(Object::Stream(stream)) = view.graph().value(id) else {
279        return Err(ContentError::NotAStream);
280    };
281    let raw = view
282        .slice(stream.data_span)
283        .ok_or(ContentError::NotAStream)?;
284    Ok((&stream.dict, raw))
285}
286
287#[cfg(test)]
288#[allow(
289    clippy::unwrap_used,
290    clippy::expect_used,
291    clippy::panic,
292    clippy::indexing_slicing
293)]
294mod tests {
295    use super::*;
296    use crate::filters::flate;
297    use crate::object::Name;
298
299    /// Every operation's meaning (operand values, operator bytes, inline
300    /// image parameters and data), which a window split must not change.
301    fn ops_of(windows: &[ContentStream]) -> Vec<Vec<String>> {
302        windows
303            .iter()
304            .flat_map(|w| {
305                w.operations().map(move |op| {
306                    op.operands
307                        .iter()
308                        .chain(std::iter::once(op.operator))
309                        .map(|t| match &t.kind {
310                            ContentTokenKind::Operand(o) => format!("{o:?}"),
311                            ContentTokenKind::Operator => {
312                                format!("{:?}", t.span.slice(&w.buf).unwrap())
313                            }
314                            ContentTokenKind::InlineImage { params, data } => {
315                                format!("{params:?} {:?}", data.slice(&w.buf).unwrap())
316                            }
317                        })
318                        .collect()
319                })
320            })
321            .collect()
322    }
323
324    fn drain(mut c: ContentChunks<'_>) -> Vec<ContentStream> {
325        let mut out = Vec::new();
326        while let Some(w) = c.next_chunk().unwrap() {
327            out.push(w);
328        }
329        out
330    }
331
332    fn sample() -> Vec<u8> {
333        let mut s = Vec::new();
334        for i in 0..300u32 {
335            s.extend_from_slice(
336                format!("q {i} 0 0 1 0 0 cm /F1 12 Tf ({i}) Tj [<0041> -{i} (b)] TJ Q\n")
337                    .as_bytes(),
338            );
339            if i % 97 == 0 {
340                s.extend_from_slice(b"BI /W 2 /H 1 /CS /G /BPC 8 ID \x00\xFF EI\n");
341            }
342        }
343        s
344    }
345
346    /// Whether `at` falls inside a `BI … EI` line of [`sample`], where a
347    /// stream split would not be on a token boundary.
348    fn in_inline_image(s: &[u8], at: usize) -> bool {
349        let line = s[..at]
350            .iter()
351            .rposition(|&b| b == b'\n')
352            .map_or(0, |i| i + 1);
353        s[line..].starts_with(b"BI") && !s[line..at].ends_with(b"EI\n")
354    }
355
356    fn flate_dict() -> Dict {
357        let mut d = Dict::new();
358        d.insert(
359            Name::from(b"Filter".as_slice()),
360            Object::Name(Name::from(b"FlateDecode".as_slice())),
361        );
362        d
363    }
364
365    #[test]
366    fn windows_are_invisible_at_every_size() {
367        let plain = sample();
368        let whole = ContentStream::parse(plain.clone()).unwrap();
369        let expected = ops_of(std::slice::from_ref(&whole));
370        let enc = flate::encode(&plain);
371        let dict = flate_dict();
372        for window in [1, 2, 7, 4096] {
373            let mut c = ContentChunks::from_stream(&dict, &enc);
374            c.window = window;
375            let windows = drain(c);
376            assert!(windows.len() > 1 || window > plain.len(), "window {window}");
377            assert_eq!(ops_of(&windows), expected, "window {window}");
378        }
379    }
380
381    #[test]
382    fn an_operator_cut_by_the_read_edge_waits_for_its_tail() {
383        // Unfiltered bytes arrive a decoder chunk at a time, so the first
384        // read ends exactly between the `B` and `T` of `BT`.
385        let mut plain = vec![b' '; crate::filters::CHUNK - 1];
386        plain.extend_from_slice(
387            b"BT /F1 12 Tf ET
388",
389        );
390        let expected = ops_of(&[ContentStream::parse(plain.clone()).unwrap()]);
391        let dict = Dict::new();
392        let mut c = ContentChunks::from_stream(&dict, &plain);
393        c.window = 4096;
394        assert_eq!(ops_of(&drain(c)), expected);
395    }
396
397    #[test]
398    fn streams_are_separated_even_without_trailing_whitespace() {
399        let dict = Dict::new();
400        let sources: Vec<(&Dict, &[u8])> =
401            vec![(&dict, b"0 0 m"), (&dict, b""), (&dict, b"1 1 l S")];
402        let expected = ops_of(&[ContentStream::parse(
403            b"0 0 m
4041 1 l S"
405                .to_vec(),
406        )
407        .unwrap()]);
408        assert_eq!(ops_of(&drain(ContentChunks::new(sources))), expected);
409    }
410
411    #[test]
412    fn split_contents_streams_concatenate_like_from_page() {
413        let plain = sample();
414        let expected = ops_of(&[ContentStream::parse(plain.clone()).unwrap()]);
415        let empty = Dict::new();
416        for part in [1usize, 2, 7, 4096] {
417            // Split on whitespace boundaries only (§7.7.3.3 guarantees token
418            // boundaries; a split inside a token is not a valid page).
419            let mut sources: Vec<(&Dict, &[u8])> = Vec::new();
420            let mut start = 0;
421            while start < plain.len() {
422                let mut end = (start + part).min(plain.len());
423                while end < plain.len()
424                    && (!crate::lexer::is_whitespace(plain[end - 1])
425                        || in_inline_image(&plain, end))
426                {
427                    end += 1;
428                }
429                sources.push((&empty, &plain[start..end]));
430                sources.push((&empty, b""));
431                start = end;
432            }
433            let windows = drain(ContentChunks::new(sources));
434            assert_eq!(ops_of(&windows), expected, "part {part}");
435        }
436    }
437
438    #[test]
439    fn a_bomb_draws_its_prefix_and_reports_truncation() {
440        let line = b"0 0 m 1 1 l S\n";
441        let plain = line.repeat((8 << 20) / line.len());
442        let enc = flate::encode(&plain);
443        let floor = 1 << 20;
444        let budget = floor.max(enc.len() * crate::filters::MAX_DECODE_RATIO);
445        assert!(budget < plain.len(), "the fixture must be a bomb");
446        let dict = flate_dict();
447        let mut c = ContentChunks::from_stream(&dict, &enc);
448        c.floor = floor;
449        let mut ops = 0usize;
450        while let Some(w) = c.next_chunk().unwrap() {
451            ops += w.operations().count();
452        }
453        assert_eq!(c.truncation(), Some(ChunkTruncation::Budget));
454        // Every whole line inside the budget ran; nothing past it did.
455        let lines = budget / line.len();
456        assert!(
457            ops >= (lines - 2) * 3 && ops <= lines * 3,
458            "{ops} vs {lines} lines"
459        );
460    }
461
462    #[test]
463    fn a_later_decode_error_follows_the_windows_before_it() {
464        // Large enough that the damage lies past the first decoded chunk.
465        let plain = sample().repeat(16);
466        let enc = flate::encode(&plain);
467        let cut = &enc[..enc.len() * 3 / 4];
468        let dict = flate_dict();
469        // A whole-stream read reports the damage up front, as today.
470        assert!(ContentChunks::from_stream(&dict, cut).next_chunk().is_err());
471        let mut c = ContentChunks::from_stream(&dict, cut);
472        c.window = 4096;
473        let mut ops = 0;
474        let err = loop {
475            match c.next_chunk() {
476                Ok(Some(w)) => ops += w.operations().count(),
477                Ok(None) => panic!("expected the decode error"),
478                Err(e) => break e,
479            }
480        };
481        assert!(matches!(err, ContentError::Decode(_)), "{err:?}");
482        assert!(ops > 0);
483    }
484
485    #[test]
486    fn a_syntax_error_in_complete_content_is_still_an_error() {
487        let dict = Dict::new();
488        let mut c = ContentChunks::from_stream(&dict, b"0 0 m (unterminated");
489        assert!(c.next_chunk().is_err());
490    }
491}