Skip to main content

pdf/read/
content.rs

1// The operators of a content stream (ISO 32000-1, 7.8.2): operands, then the operator.  An
2// inline image (BI ... ID data EI) comes as one operator "BI" with two operands, its
3// dictionary and its data.  Damaged content gives what can be read: an unknown token is skipped,
4// operands beyond MAX_OPERANDS are dropped, and the stream ends where the bytes end.
5
6use super::lex::{self, Lexer, Tok};
7use super::object::{Dict, Object};
8use alloc::vec::Vec;
9
10/// the most operands kept for one operator (a TJ array is one operand)
11pub const MAX_OPERANDS: usize = 4096;
12
13/// one operator with its operands
14#[derive(Clone, Debug, PartialEq)]
15pub struct Op<'a> {
16    /// the operator: b"Tj", b"re", b"BI" (an inline image), ...
17    pub operator: &'a [u8],
18    pub operands: Vec<Object>,
19}
20
21/// the operators of content-stream bytes, in order
22pub struct Ops<'a> {
23    lx: Lexer<'a>,
24    /// the bytes after EI candidates that may still be looked at (their windows overlap; when
25    /// none are left, an EI between white space ends an image)
26    after_budget: usize,
27}
28
29impl<'a> Ops<'a> {
30    pub fn new(content: &'a [u8]) -> Ops<'a> {
31        Ops { lx: Lexer::new(content, 0), after_budget: content.len().saturating_mul(4).saturating_add(1 << 16) }
32    }
33
34    /// the inline image after BI: its dictionary up to ID, its data up to EI
35    fn inline_image(&mut self) -> (Dict, Vec<u8>) {
36        let mut d = Dict::new();
37        loop {
38            match self.lx.next() {
39                Tok::Kw(b"ID") | Tok::Eof => break,
40                Tok::Name(k) => {
41                    let t = self.lx.next();
42                    if t == Tok::Kw(b"ID") {
43                        break;
44                    }
45                    if let Ok(v) = self.lx.value_of(t) {
46                        d.map_mut().insert(super::object::Name(k), v);
47                    }
48                }
49                _ => {}
50            }
51            self.lx.reset_budget();
52        }
53        let b = self.lx.b;
54        // one white-space byte after ID
55        let start = (self.lx.pos + 1).min(b.len());
56        // PDF 2.0 gives the length; else EI between white space, with operators after it
57        if let Some(n) = d.get("L").or_else(|| d.get("Length")).and_then(Object::as_int).and_then(|n| usize::try_from(n).ok()) {
58            if let Some(end) = start.checked_add(n).filter(|&e| e <= b.len()) {
59                let mut l = Lexer::new(b, end);
60                if l.next() == Tok::Kw(b"EI") {
61                    self.lx.pos = l.pos;
62                    return (d, b[start..end].to_vec());
63                }
64            }
65        }
66        let mut i = start;
67        while let Some(p) = lex::find(b, b"EI", i) {
68            i = p + 2;
69            let before = p == start || lex::is_ws(b[p - 1]);
70            let after = b.get(p + 2).is_none_or(|&c| lex::is_ws(c) || lex::is_delim(c));
71            if before && after && plausible_after(&b[p + 2..], &mut self.after_budget) {
72                let end = if p > start && lex::is_ws(b[p - 1]) { p - 1 } else { p };
73                self.lx.pos = p + 2;
74                return (d, b[start..end.max(start)].to_vec());
75            }
76        }
77        self.lx.pos = b.len();
78        (d, b[start..].to_vec())
79    }
80}
81
82/// how far after an EI the content is looked at: each candidate costs at most this much (a
83/// hex string after each of millions of EIs was read to its end for each of them)
84const AFTER_WINDOW: usize = 256;
85
86/// the operators of content streams (ISO 32000-1, Annex A)
87const OPERATORS: &[&[u8]] = &[
88    b"b", b"B", b"b*", b"B*", b"BDC", b"BI", b"BMC", b"BT", b"BX", b"c", b"cm", b"CS", b"cs", b"d", b"d0", b"d1", b"Do", b"DP", b"EI", b"EMC", b"ET", b"EX", b"f",
89    b"F", b"f*", b"G", b"g", b"gs", b"h", b"i", b"ID", b"j", b"J", b"K", b"k", b"l", b"m", b"M", b"MP", b"n", b"q", b"Q", b"re", b"RG", b"rg", b"ri", b"s", b"S",
90    b"SC", b"sc", b"SCN", b"scn", b"sh", b"T*", b"Tc", b"Td", b"TD", b"Tf", b"Tj", b"TJ", b"TL", b"Tm", b"Tr", b"Ts", b"Tw", b"Tz", b"v", b"w", b"W", b"W*",
91    b"y", b"'", b"\"",
92];
93
94/// the bytes after an EI read as content again: the next tokens are operands and operators
95/// (binary image data that happens to hold "EI" rarely does).  Only AFTER_WINDOW bytes are read,
96/// a token cut by the window's end counts as content, and what all the candidates of a content
97/// stream read together is bounded (`budget`; when it is spent, an EI between white space ends
98/// the image as in the simpler readers): the windows of candidates close together overlap
99fn plausible_after(rest: &[u8], budget: &mut usize) -> bool {
100    if *budget == 0 {
101        return true;
102    }
103    let cut = rest.len() > AFTER_WINDOW;
104    let win = &rest[..rest.len().min(AFTER_WINDOW)];
105    let mut lx = Lexer::new(win, 0);
106    let r = after_tokens(&mut lx, cut);
107    *budget = budget.saturating_sub(lx.pos.max(1));
108    r
109}
110
111fn after_tokens(lx: &mut Lexer, cut: bool) -> bool {
112    let end = lx.b.len();
113    for _ in 0..8 {
114        lx.reset_budget();
115        let t = lx.next();
116        // a token that reaches the window's end may go on after it
117        if cut && lx.pos >= end {
118            return true;
119        }
120        match t {
121            Tok::Eof => return true,
122            Tok::Kw(k) if matches!(k, b"true" | b"false" | b"null") => {}
123            Tok::Kw(k) => {
124                if !OPERATORS.contains(&k) {
125                    return false;
126                }
127            }
128            Tok::BraceOpen | Tok::BraceClose | Tok::ArrClose | Tok::DictClose => return false,
129            t => {
130                let ok = lx.value_of(t).is_ok();
131                if cut && lx.pos >= end {
132                    return true;
133                }
134                if !ok {
135                    return false;
136                }
137            }
138        }
139    }
140    true
141}
142
143impl<'a> Iterator for Ops<'a> {
144    type Item = Op<'a>;
145
146    fn next(&mut self) -> Option<Op<'a>> {
147        let mut operands = Vec::new();
148        loop {
149            self.lx.reset_budget();
150            let t = self.lx.next();
151            match t {
152                Tok::Eof => {
153                    return None;
154                }
155                Tok::Kw(b"BI") => {
156                    let (d, data) = self.inline_image();
157                    return Some(Op { operator: b"BI", operands: alloc::vec![Object::Dict(d), Object::String(data)] });
158                }
159                Tok::Kw(k) if matches!(k, b"true" | b"false" | b"null") => {
160                    if let Ok(v) = self.lx.value_of(Tok::Kw(k)) {
161                        if operands.len() < MAX_OPERANDS {
162                            operands.push(v);
163                        }
164                    }
165                }
166                Tok::Kw(k) if k.len() <= 3 || k.iter().all(|c| c.is_ascii_alphabetic() || *c == b'*' || *c == b'\'' || *c == b'"') => {
167                    return Some(Op { operator: k, operands });
168                }
169                Tok::Kw(_) | Tok::ArrClose | Tok::DictClose | Tok::BraceOpen | Tok::BraceClose => {
170                    // a stray token of damaged content
171                }
172                t => {
173                    if let Ok(v) = self.lx.value_of(t) {
174                        if operands.len() < MAX_OPERANDS {
175                            operands.push(v);
176                        }
177                    }
178                }
179            }
180        }
181    }
182}