rusty_pdf_core 0.2.0

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Content streams: the operators that draw a page.

use crate::error::{Error, Result};
use crate::object::{Dictionary, Object, Stream};
use crate::parser::{find, is_whitespace, Parser};
use crate::Limits;
use std::borrow::Cow;
use std::fmt;

/// The operators of ISO 32000-2, Annex A: the source of truth for
/// `standard_operator`'s match, which a test holds to it in both directions.
#[cfg(test)]
const OPERATORS: [&str; 73] = [
    "b", "B", "b*", "B*", "BDC", "BI", "BMC", "BT", "BX", "c", "cm", "CS", "cs", "d", "d0", "d1", "Do", "DP", "EI",
    "EMC", "ET", "EX", "f", "F", "f*", "G", "g", "gs", "h", "i", "ID", "j", "J", "K", "k", "l", "m", "M", "MP", "n",
    "q", "Q", "re", "RG", "rg", "ri", "s", "S", "SC", "sc", "SCN", "scn", "sh", "T*", "Tc", "Td", "TD", "Tf", "TJ",
    "Tj", "TL", "Tm", "Tr", "Ts", "Tw", "Tz", "v", "w", "W", "W*", "y", "'", "\"",
];

/// The static name of a standard operator, as one `match`: the compiler
/// builds a decision tree on length and bytes, where a scan of
/// the 73 standard names compared against each token in turn.
fn standard_operator(token: &[u8]) -> Option<&'static str> {
    Some(match token {
        b"b" => "b",
        b"B" => "B",
        b"b*" => "b*",
        b"B*" => "B*",
        b"BDC" => "BDC",
        b"BI" => "BI",
        b"BMC" => "BMC",
        b"BT" => "BT",
        b"BX" => "BX",
        b"c" => "c",
        b"cm" => "cm",
        b"CS" => "CS",
        b"cs" => "cs",
        b"d" => "d",
        b"d0" => "d0",
        b"d1" => "d1",
        b"Do" => "Do",
        b"DP" => "DP",
        b"EI" => "EI",
        b"EMC" => "EMC",
        b"ET" => "ET",
        b"EX" => "EX",
        b"f" => "f",
        b"F" => "F",
        b"f*" => "f*",
        b"G" => "G",
        b"g" => "g",
        b"gs" => "gs",
        b"h" => "h",
        b"i" => "i",
        b"ID" => "ID",
        b"j" => "j",
        b"J" => "J",
        b"K" => "K",
        b"k" => "k",
        b"l" => "l",
        b"m" => "m",
        b"M" => "M",
        b"MP" => "MP",
        b"n" => "n",
        b"q" => "q",
        b"Q" => "Q",
        b"re" => "re",
        b"RG" => "RG",
        b"rg" => "rg",
        b"ri" => "ri",
        b"s" => "s",
        b"S" => "S",
        b"SC" => "SC",
        b"sc" => "sc",
        b"SCN" => "SCN",
        b"scn" => "scn",
        b"sh" => "sh",
        b"T*" => "T*",
        b"Tc" => "Tc",
        b"Td" => "Td",
        b"TD" => "TD",
        b"Tf" => "Tf",
        b"TJ" => "TJ",
        b"Tj" => "Tj",
        b"TL" => "TL",
        b"Tm" => "Tm",
        b"Tr" => "Tr",
        b"Ts" => "Ts",
        b"Tw" => "Tw",
        b"Tz" => "Tz",
        b"v" => "v",
        b"w" => "w",
        b"W" => "W",
        b"W*" => "W*",
        b"y" => "y",
        b"'" => "'",
        b"\"" => "\"",
        _ => return None,
    })
}

/// A content-stream operator: one of the standard operators (no allocation)
/// or, for anything else a file contains, its own text.
///
/// It reads like a string: `op.operator.as_str()`, `op.operator == "Tj"`,
/// `match op.operator.as_str() { … }` and `{}` formatting all work.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Operator(Cow<'static, str>);

impl Operator {
    /// The operator for a token from a content stream. Bytes that are not
    /// UTF-8 are replaced, as before.
    #[must_use]
    pub fn from_bytes(token: &[u8]) -> Self {
        match standard_operator(token) {
            Some(op) => Self(Cow::Borrowed(op)),
            None => Self(Cow::Owned(String::from_utf8_lossy(token).into_owned())),
        }
    }

    /// The operator's text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::ops::Deref for Operator {
    type Target = str;
    fn deref(&self) -> &str {
        &self.0
    }
}

impl From<&str> for Operator {
    fn from(s: &str) -> Self {
        Self::from_bytes(s.as_bytes())
    }
}

impl PartialEq<str> for Operator {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for Operator {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

impl fmt::Debug for Operator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl fmt::Display for Operator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One operator with its operands, as written: `10 20 m` is operator `m`
/// with operands `[10, 20]`.
///
/// An inline image (`BI … ID … EI`) is one operation with operator `BI` and
/// a single [`Object::Stream`] operand: the image dictionary, with its keys
/// as abbreviated in the file, and the image data.
#[derive(Debug, Clone, PartialEq)]
pub struct Operation {
    /// The operator. Operators are ASCII; bytes that are not are replaced.
    pub operator: Operator,
    /// The operands, in order.
    pub operands: Vec<Object>,
}

impl Operation {
    /// An operation from an operator and operands.
    pub fn new(operator: &str, operands: Vec<Object>) -> Self {
        Self { operator: Operator::from(operator), operands }
    }
}

/// A parsed content stream.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Content {
    /// The operations, in drawing order.
    pub operations: Vec<Operation>,
}

/// Most operands kept for one operator. No operator takes more than a few
/// (the largest, `SCN` in a DeviceN space, takes 33); a longer run is junk
/// and its oldest operands are dropped.
const MAX_OPERANDS: usize = 256;

impl Content {
    /// Parse decoded content-stream bytes with default limits.
    pub fn parse(data: &[u8]) -> Result<Self> {
        Self::parse_with(data, &Limits::default())
    }

    /// Parse decoded content-stream bytes.
    ///
    /// Junk between operators is skipped, as viewers skip it. An inline
    /// image whose end cannot be found is an error: everything after it
    /// would be guesswork.
    pub fn parse_with(data: &[u8], limits: &Limits) -> Result<Self> {
        let mut p = Parser::for_content(data, limits.max_nesting);
        let mut operations = Vec::new();
        let mut operands: Vec<Object> = Vec::new();
        loop {
            p.skip_ws();
            if p.at_end() {
                break;
            }
            // A token that starts with a letter or a quote is an operator, or
            // one of the keywords `true`, `false`, `null`: never anything else
            // an object parse could produce. Read it once as a token, instead
            // of failing an object parse first and reading it again.
            if p.peek().is_some_and(|b| b.is_ascii_alphabetic() || b == b'\'' || b == b'"') {
                let token = p.token();
                let keyword = match token {
                    b"true" => Some(Object::Boolean(true)),
                    b"false" => Some(Object::Boolean(false)),
                    b"null" => Some(Object::Null),
                    _ => None,
                };
                match keyword {
                    Some(o) => push_operand(&mut operands, o),
                    None => operator(&mut p, token, &mut operands, &mut operations)?,
                }
                continue;
            }
            let before = p.pos;
            match p.object() {
                Ok(o) => push_operand(&mut operands, o),
                Err(e @ Error::Limit { .. }) => return Err(e),
                Err(_) => {
                    p.pos = before;
                    let token = p.token();
                    if token.is_empty() {
                        // A stray delimiter.
                        p.pos += 1;
                        continue;
                    }
                    operator(&mut p, token, &mut operands, &mut operations)?;
                }
            }
        }
        Ok(Self { operations })
    }

    /// Serialise back to content-stream bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for op in &self.operations {
            if op.operator == "BI" {
                if let Some(Object::Stream(image)) = op.operands.first() {
                    out.extend_from_slice(b"BI");
                    for (key, value) in image.dict.iter() {
                        // `/Length` is ours (`Stream::new` sets it), not
                        // part of an inline image.
                        if key == b"Length" {
                            continue;
                        }
                        out.push(b' ');
                        crate::writer::write_name(&mut out, key);
                        out.push(b' ');
                        crate::writer::write_object(&mut out, value, &|_| 0);
                    }
                    out.extend_from_slice(b"\nID\n");
                    out.extend_from_slice(image.raw());
                    out.extend_from_slice(b"\nEI\n");
                    continue;
                }
            }
            for operand in &op.operands {
                crate::writer::write_object(&mut out, operand, &|_| 0);
                out.push(b' ');
            }
            out.extend_from_slice(op.operator.as_bytes());
            out.push(b'\n');
        }
        out
    }
}

/// Keep an operand for the next operator, dropping the oldest past the cap.
fn push_operand(operands: &mut Vec<Object>, o: Object) {
    if operands.len() >= MAX_OPERANDS {
        operands.remove(0);
    }
    operands.push(o);
}

/// Close an operation: `token` is its operator, the operands so far its
/// operands. `BI` starts an inline image, which is read whole.
fn operator(p: &mut Parser<'_>, token: &[u8], operands: &mut Vec<Object>, operations: &mut Vec<Operation>) -> Result<()> {
    if token == b"BI" {
        let image = inline_image(p)?;
        operands.clear();
        operations.push(Operation { operator: Operator::from("BI"), operands: vec![Object::Stream(image)] });
    } else {
        // `operands` is a scratch that keeps its capacity: each operation gets
        // an exact-size vector (none at all when it has no operands) and
        // nothing regrows per operator.
        let mut exact = Vec::with_capacity(operands.len());
        exact.append(operands);
        operations.push(Operation { operator: Operator::from_bytes(token), operands: exact });
    }
    Ok(())
}

/// An inline image; `BI` is already consumed.
fn inline_image(p: &mut Parser<'_>) -> Result<Stream> {
    let mut dict = Dictionary::new();
    loop {
        p.skip_ws();
        if p.at_end() {
            return Err(Error::Syntax { offset: p.pos, message: "inline image has no ID" });
        }
        if p.eat_keyword(b"ID") {
            break;
        }
        match p.object() {
            Ok(Object::Name(key)) => {
                p.skip_ws();
                let before = p.pos;
                match p.object() {
                    Ok(value) => dict.set(key, value),
                    Err(e @ Error::Limit { .. }) => return Err(e),
                    Err(_) => p.pos = before,
                }
            }
            Ok(_) => {}
            Err(e @ Error::Limit { .. }) => return Err(e),
            Err(_) => {
                if p.token().is_empty() {
                    p.pos += 1;
                }
            }
        }
    }
    // One white-space character separates `ID` from the data.
    if p.peek().is_some_and(is_whitespace) {
        p.pos += 1;
    }
    let start = p.pos.min(p.data.len());
    let end = inline_image_end(p.data, start, &dict)
        .ok_or(Error::Syntax { offset: start, message: "inline image has no EI" })?;
    p.pos = end.1;
    Ok(Stream::new(dict, p.data[start..end.0].to_vec()))
}

/// Where an inline image's data ends, and where parsing resumes after `EI`.
fn inline_image_end(data: &[u8], start: usize, dict: &Dictionary) -> Option<(usize, usize)> {
    // Unfiltered data has a length the dictionary determines; trust it when
    // `EI` is where it says.
    if let Some(len) = unfiltered_length(dict) {
        if let Some(end) = start.checked_add(len).filter(|e| *e <= data.len()) {
            let mut probe = Parser::for_content(data, 0);
            probe.pos = end;
            probe.skip_ws();
            if probe.eat_keyword(b"EI") {
                return Some((end, probe.pos));
            }
        }
    }
    // Otherwise the first `EI` that stands alone and is followed by what
    // looks like content-stream text, not more binary.
    let mut from = start;
    while let Some(at) = find(data, b"EI", from) {
        from = at + 1;
        let alone = (at == start || is_whitespace(data[at - 1]))
            && data.get(at + 2).copied().is_none_or(is_whitespace);
        if !alone {
            continue;
        }
        let tail = &data[at + 2..data.len().min(at + 2 + 16)];
        let texty = tail.iter().all(|b| is_whitespace(*b) || (0x20..0x7F).contains(b));
        if texty {
            let end = if at > start { at - 1 } else { at };
            return Some((end.max(start), at + 2));
        }
    }
    None
}

/// The data length of an inline image with no filter, if the dictionary
/// determines it.
fn unfiltered_length(dict: &Dictionary) -> Option<usize> {
    if dict.has(b"F") || dict.has(b"Filter") {
        return None;
    }
    let get = |short: &[u8], long: &[u8]| dict.get(short).or_else(|| dict.get(long));
    let int = |o: &Object| o.as_i64().ok().and_then(|v| usize::try_from(v).ok());
    let width = get(b"W", b"Width").and_then(int)?;
    let height = get(b"H", b"Height").and_then(int)?;
    let mask = get(b"IM", b"ImageMask").and_then(|o| o.as_bool().ok()).unwrap_or(false);
    let (components, bits) = if mask {
        (1, 1)
    } else {
        let bits = get(b"BPC", b"BitsPerComponent").and_then(int)?;
        let components = match get(b"CS", b"ColorSpace")?.as_name().ok()? {
            b"G" | b"DeviceGray" | b"CalGray" | b"I" | b"Indexed" => 1,
            b"RGB" | b"DeviceRGB" | b"CalRGB" => 3,
            b"CMYK" | b"DeviceCMYK" => 4,
            _ => return None,
        };
        (components, bits)
    };
    let row = width.checked_mul(components)?.checked_mul(bits)?.div_ceil(8);
    row.checked_mul(height)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ops(data: &[u8]) -> Vec<(String, usize)> {
        Content::parse(data)
            .unwrap()
            .operations
            .into_iter()
            .map(|o| (o.operator.to_string(), o.operands.len()))
            .collect()
    }

    #[test]
    fn operators_and_operands() {
        let c = Content::parse(b"q 1 0 0 1 10 20 cm /Im1 Do Q BT /F1 12 Tf (Hi) Tj [(a) -20 (b)] TJ ET").unwrap();
        let names: Vec<&str> = c.operations.iter().map(|o| o.operator.as_str()).collect();
        assert_eq!(names, ["q", "cm", "Do", "Q", "BT", "Tf", "Tj", "TJ", "ET"]);
        assert_eq!(c.operations[1].operands.len(), 6);
        assert_eq!(c.operations[2].operands[0], Object::name("Im1"));
        assert_eq!(c.operations[6].operands[0], Object::string("Hi"));
        // `f*`, `'`, `"` and `T*` are single tokens.
        assert_eq!(ops(b"f* T* (a) ' 1 2 (b) \""), [("f*".into(), 0), ("T*".into(), 0), ("'".into(), 1), ("\"".into(), 3)]);
    }

    #[test]
    fn junk_is_skipped_not_fatal() {
        assert_eq!(ops(b"} ) 1 0 0 rg >"), [("rg".into(), 3)]);
        assert_eq!(ops(b""), []);
        assert_eq!(ops(b"   % only a comment"), []);
    }

    #[test]
    fn inline_images() {
        // Unfiltered: the length comes from the dictionary, so data that
        // contains ` EI ` is not cut short.
        let c = Content::parse(b"q BI /W 2 /H 2 /BPC 8 /CS /G ID \x00 EI\nEI Q").unwrap();
        assert_eq!(c.operations.len(), 3);
        let image = c.operations[1].operands[0].as_stream().unwrap();
        assert_eq!(image.raw(), b"\x00 EI");
        assert_eq!(image.dict.get_i64(b"W"), Some(2));
        // Filtered: ends at the first free-standing EI followed by text.
        let c = Content::parse(b"BI /W 9 /H 9 /F /Fl ID \x01\xFFEI\x02 EI\x80 EI Q").unwrap();
        let image = c.operations[0].operands[0].as_stream().unwrap();
        assert_eq!(image.raw(), b"\x01\xFFEI\x02 EI\x80");
        assert_eq!(c.operations[1].operator, "Q");
        assert!(Content::parse(b"BI /W 1 /H 1 /F /Fl ID \x00\x01\x02").is_err());
    }

    #[test]
    fn standard_operators_are_static_and_others_are_kept() {
        let c = Content::parse(b"q 1 0 0 1 0 0 cm Q foo").unwrap();
        assert!(matches!(c.operations[0].operator.0, Cow::Borrowed("q")));
        assert!(matches!(c.operations[2].operator.0, Cow::Borrowed("Q")));
        assert!(matches!(&c.operations[3].operator.0, Cow::Owned(s) if s == "foo"));
        assert_eq!(c.operations[1].operator, "cm");
        assert_eq!(c.operations[1].operator.as_str(), "cm");
        assert_eq!(format!("{}", c.operations[1].operator), "cm");
        assert_eq!(OPERATORS.len(), 73);
        // The match and the list agree, both ways.
        for op in OPERATORS {
            assert_eq!(standard_operator(op.as_bytes()), Some(op));
        }
        assert_eq!(standard_operator(b"foo"), None);
        assert_eq!(standard_operator(b""), None);
    }

    #[test]
    fn round_trip() {
        let src = b"q 1 0 0 1 10.5 -20 cm /Im1 Do Q BT /F1 12 Tf (a\\(b) Tj ET BI /W 1 /H 1 /BPC 8 /CS /G ID \x7f\nEI f";
        let first = Content::parse(src).unwrap();
        let second = Content::parse(&first.encode()).unwrap();
        assert_eq!(first, second);
    }
}