rusty_pdf_core 0.2.1

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
//! Cross-reference data: classic tables, cross-reference streams, hybrid
//! files, `/Prev` chains — and the scan that rebuilds all of it when it is
//! missing or wrong.

use crate::error::{Error, Result};
use crate::filters;
use crate::object::{Dictionary, Object};
use crate::parser::{find, is_regular, is_whitespace, rfind, Parser};
use crate::Limits;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

/// Where an object lives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Loc {
    /// At a byte offset in the file.
    Offset(usize),
    /// Inside object stream `container`, at position `index`.
    Compressed { container: u32, index: u32 },
}

/// The cross-reference data of a whole file, newest definition per object.
#[derive(Debug, Default)]
pub(crate) struct Xref {
    /// Object number to (generation, location). Free entries are not kept: a
    /// reference to one resolves to null like any other missing object.
    pub(crate) entries: BTreeMap<u32, (u16, Loc)>,
    pub(crate) trailer: Dictionary,
    /// Offset of the newest cross-reference section (for `/Prev` on an
    /// incremental save).
    pub(crate) start: usize,
    /// Whether the newest section is a cross-reference stream.
    pub(crate) stream: bool,
}

/// The table under construction while sections are read newest first: the
/// first word on an object number is the last word.
#[derive(Debug, Default)]
pub(crate) struct Building {
    /// `None` for a number a newer section marked free: an older section's
    /// entry for it describes an object that has since been deleted. One map
    /// for both, so each entry costs one search, not three.
    entries: BTreeMap<u32, Option<(u16, Loc)>>,
}

impl Building {
    /// Record what a section says about `num`: a location, or `None` for a
    /// free entry. Ignored when a newer section already spoke.
    fn add(&mut self, num: u32, entry: Option<(u16, Loc)>, limits: &Limits) -> Result<()> {
        if let std::collections::btree_map::Entry::Vacant(slot) = self.entries.entry(num) {
            slot.insert(entry);
            if self.entries.len() > limits.max_objects {
                return Err(Error::Limit { what: "object count", limit: limits.max_objects as u64 });
            }
        }
        Ok(())
    }

    /// The live entries, freed numbers dropped.
    fn finish(self) -> BTreeMap<u32, (u16, Loc)> {
        self.entries.into_iter().filter_map(|(n, e)| e.map(|e| (n, e))).collect()
    }

    #[cfg(test)]
    fn get(&self, num: u32) -> Option<&(u16, Loc)> {
        self.entries.get(&num).and_then(Option::as_ref)
    }
}

fn xref_error<T>(m: impl Into<String>) -> Result<T> {
    Err(Error::Xref(m.into()))
}

/// The offset named by the last `startxref` in the file.
fn startxref(data: &[u8]) -> Result<usize> {
    let at = rfind(data, b"startxref", data.len()).ok_or_else(|| Error::Xref("no startxref".into()))?;
    let mut p = Parser::new(data, at + 9, 0);
    p.skip_ws();
    p.unsigned()
        .and_then(|v| usize::try_from(v).ok())
        .filter(|v| *v < data.len())
        .ok_or_else(|| Error::Xref("startxref has no usable offset".into()))
}

/// Read the cross-reference chain the file declares. Any inconsistency is an
/// error; the caller falls back to [`scan`].
pub(crate) fn read(data: &Arc<[u8]>, limits: &Limits) -> Result<Xref> {
    let start = startxref(data)?;
    let mut xref = Xref { start, ..Xref::default() };
    let mut table = Building::default();
    let mut visited = BTreeSet::new();
    // Sections to read, newest first. A hybrid section queues its `/XRefStm`
    // ahead of its `/Prev`, which is the lookup order 7.5.8.4 gives.
    let mut queue = vec![start];
    let mut first = true;
    while let Some(offset) = queue.pop() {
        if !visited.insert(offset) {
            // A `/Prev` loop. Everything reachable is already read.
            continue;
        }
        if visited.len() > limits.max_xref_sections {
            return Err(Error::Limit { what: "cross-reference sections", limit: limits.max_xref_sections as u64 });
        }
        let mut p = Parser::new(data, offset, limits.max_nesting);
        p.skip_ws();
        let (trailer, is_stream) = if p.eat_keyword(b"xref") {
            (read_table(&mut p, &mut table, limits)?, false)
        } else {
            (read_stream(data, offset, &mut table, limits)?, true)
        };
        if first {
            xref.stream = is_stream;
            first = false;
        }
        let next = |key: &[u8]| {
            trailer
                .get_i64(key)
                .and_then(|v| usize::try_from(v).ok())
                .filter(|v| *v < data.len())
        };
        // Pushed in reverse: the stack pops `/XRefStm` before `/Prev`.
        if let Some(prev) = next(b"Prev") {
            queue.push(prev);
        }
        if !is_stream {
            if let Some(hybrid) = next(b"XRefStm") {
                queue.push(hybrid);
            }
        }
        merge_trailer(&mut xref.trailer, trailer);
    }
    if !xref.trailer.has(b"Root") {
        return xref_error("trailer has no /Root");
    }
    xref.entries = table.finish();
    Ok(xref)
}

/// Keep the newest value of every trailer key; older sections only fill gaps.
fn merge_trailer(into: &mut Dictionary, older: Dictionary) {
    for (k, v) in older.iter() {
        if !into.has(k) {
            into.set(k, v.clone());
        }
    }
}

/// A classic table; `xref` is already consumed. Returns the trailer.
fn read_table(p: &mut Parser<'_>, table: &mut Building, limits: &Limits) -> Result<Dictionary> {
    loop {
        p.skip_ws();
        if p.eat_keyword(b"trailer") {
            return match p.object()? {
                Object::Dictionary(d) => Ok(d),
                _ => xref_error("trailer is not a dictionary"),
            };
        }
        let (Some(first), Some(count)) = (p.unsigned(), {
            p.skip_ws();
            p.unsigned()
        }) else {
            return xref_error("malformed table subsection");
        };
        // The loop is bounded by the data: every entry consumes bytes, and a
        // malformed one ends the read.
        for i in 0..count {
            p.skip_ws();
            let offset = p.unsigned();
            p.skip_ws();
            let generation = p.unsigned();
            p.skip_ws();
            let (Some(offset), Some(generation)) = (offset, generation) else {
                return xref_error("malformed table entry");
            };
            let kind = p.token();
            let Some(num) = first.checked_add(i).and_then(|n| u32::try_from(n).ok()) else {
                return xref_error("object number out of range");
            };
            match kind {
                b"n" => {
                    if let Ok(offset) = usize::try_from(offset) {
                        let generation = u16::try_from(generation).unwrap_or(u16::MAX);
                        table.add(num, Some((generation, Loc::Offset(offset))), limits)?;
                    }
                }
                b"f" => table.add(num, None, limits)?,
                _ => return xref_error("malformed table entry"),
            }
        }
    }
}

/// A cross-reference stream at `offset`. Returns its dictionary, which is
/// the trailer.
fn read_stream(data: &Arc<[u8]>, offset: usize, table: &mut Building, limits: &Limits) -> Result<Dictionary> {
    let mut p = Parser::new(data, offset, limits.max_nesting);
    // `/Length` must be direct here: nothing can be resolved before the
    // cross-reference data exists. An indirect one falls back to `endstream`.
    let (_, object) = p.indirect_object(data, &mut |l| l.as_i64().ok().and_then(|v| usize::try_from(v).ok()))?;
    let Object::Stream(stream) = object else {
        return xref_error("no cross-reference table or stream at startxref");
    };
    if !stream.dict.is_type(b"XRef") {
        return xref_error("stream at startxref is not /Type /XRef");
    }
    add_stream_entries(&stream.dict, stream.raw(), table, limits)?;
    Ok(stream.dict)
}

/// Decode a cross-reference stream's entries into `table`.
fn add_stream_entries(dict: &Dictionary, raw: &[u8], table: &mut Building, limits: &Limits) -> Result<()> {
    let mut bytes: std::borrow::Cow<'_, [u8]> = std::borrow::Cow::Borrowed(raw);
    let names: Vec<&[u8]> = match dict.get(b"Filter") {
        Some(Object::Name(n)) => vec![n],
        Some(Object::Array(a)) => a.iter().filter_map(|o| o.as_name().ok()).collect(),
        _ => Vec::new(),
    };
    for (i, name) in names.iter().enumerate() {
        let parms = match dict.get(b"DecodeParms") {
            Some(Object::Dictionary(d)) if i == 0 => Some(d),
            Some(Object::Array(a)) => a.get(i).and_then(|o| o.as_dict().ok()),
            _ => None,
        };
        bytes = std::borrow::Cow::Owned(filters::decode(name, parms, &bytes, filters::Cap::strict(limits.max_xref_stream_bytes))?.0);
    }

    let widths: Vec<usize> = dict
        .get(b"W")
        .and_then(|w| w.as_array().ok())
        .map(|w| {
            w.iter()
                .map(|o| o.as_i64().ok().and_then(|v| usize::try_from(v).ok()).filter(|v| *v <= 8))
                .collect::<Option<Vec<_>>>()
        })
        .unwrap_or_default()
        .filter(|w| w.len() >= 3)
        .ok_or_else(|| Error::Xref("cross-reference stream has no usable /W".into()))?;
    let (w0, w1, w2) = (widths[0], widths[1], widths[2]);
    let row = w0 + w1 + w2;
    if row == 0 {
        return xref_error("cross-reference stream rows are empty");
    }
    let size = dict.get_i64(b"Size").unwrap_or(0);
    let index: Vec<i64> = match dict.get(b"Index").and_then(|i| i.as_array().ok()) {
        Some(a) => a.iter().filter_map(|o| o.as_i64().ok()).collect(),
        None => vec![0, size],
    };
    let field = |bytes: &[u8]| bytes.iter().fold(0u64, |acc, b| acc << 8 | u64::from(*b));
    let mut rows = bytes.chunks_exact(row);
    for pair in index.as_chunks::<2>().0.iter() {
        let (Ok(first), Ok(count)) = (u32::try_from(pair[0]), u64::try_from(pair[1])) else {
            return xref_error("cross-reference stream /Index out of range");
        };
        for i in 0..count {
            // Bounded by the decoded data, not by the declared count.
            let Some(r) = rows.next() else { return Ok(()) };
            let Some(num) = u32::try_from(i).ok().and_then(|i| first.checked_add(i)) else {
                return Ok(());
            };
            let kind = if w0 == 0 { 1 } else { field(&r[..w0]) };
            let (a, b) = (field(&r[w0..w0 + w1]), field(&r[w0 + w1..]));
            let entry = match kind {
                0 => Some(None),
                1 => usize::try_from(a)
                    .ok()
                    .map(|off| Some((u16::try_from(b).unwrap_or(u16::MAX), Loc::Offset(off)))),
                2 => match (u32::try_from(a), u32::try_from(b)) {
                    (Ok(container), Ok(index)) => Some(Some((0, Loc::Compressed { container, index }))),
                    _ => None,
                },
                // An unknown entry type is a reference to null (7.5.8.3).
                _ => None,
            };
            if let Some(entry) = entry {
                table.add(num, entry, limits)?;
            }
        }
    }
    Ok(())
}

/// Whether an object header for `num` starts at `offset`.
pub(crate) fn header_at(data: &[u8], offset: usize, num: u32) -> bool {
    if offset >= data.len() {
        return false;
    }
    let mut p = Parser::new(data, offset, 0);
    p.indirect_header().is_ok_and(|id| id.0 == num)
}

/// What a scan of the raw bytes found.
#[derive(Debug, Default)]
pub(crate) struct Scan {
    /// Object number to (generation, offset of the header), last one in the
    /// file winning.
    pub(crate) objects: BTreeMap<u32, (u16, usize)>,
    /// Object streams, as (object number, offset), in file order.
    pub(crate) object_streams: Vec<(u32, usize)>,
    /// Trailer information recovered from `trailer` dictionaries and
    /// cross-reference stream dictionaries, newest winning.
    pub(crate) trailer: Dictionary,
    /// The last `/Type /Catalog` object seen, for a file with no trailer.
    pub(crate) catalog: Option<(u32, u16)>,
}

/// Rebuild the cross-reference data by reading the whole file for object
/// headers. This is the repair path: it trusts nothing but `N G obj`.
pub(crate) fn scan(data: &Arc<[u8]>, limits: &Limits) -> Result<Scan> {
    let mut out = Scan::default();
    let mut trailers: Vec<Dictionary> = Vec::new();
    let mut pos = 0usize;
    let mut work = 0usize;
    let work_budget = data.len().saturating_mul(8).saturating_add(1 << 20);
    while let Some(hit) = find(data, b"obj", pos) {
        pos = hit + 3;
        // `endobj`, `xobj...`: not a header.
        if data.get(hit + 3).copied().is_some_and(is_regular) {
            continue;
        }
        let Some(start) = header_start(data, hit) else { continue };
        let mut p = Parser::new(data, start, limits.max_nesting);
        let Ok((num, generation)) = p.indirect_header() else { continue };
        if out.objects.len() >= limits.max_objects && !out.objects.contains_key(&num) {
            return Err(Error::Limit { what: "object count", limit: limits.max_objects as u64 });
        }
        out.objects.insert(num, (generation, start));
        // Read the object to step over its body (stream data and strings may
        // contain anything, including text that looks like object headers)
        // and to see what it is.
        //
        // An object with no terminator can run to the end of the file, and a
        // file can hold many of them, so the reading is budgeted: past a few
        // passes' worth of bytes, headers are still recorded but bodies are
        // no longer read. That keeps the whole scan linear in the file size.
        if work > work_budget {
            continue;
        }
        let mut p = Parser::new(data, start, limits.max_nesting);
        let parsed = p.indirect_object(data, &mut |l| l.as_i64().ok().and_then(|v| usize::try_from(v).ok()));
        let end = p.pos.min(data.len());
        work = work.saturating_add(end.saturating_sub(start));
        if let Ok((_, object)) = parsed {
            let terminated = data[..end].ends_with(b"endobj");
            if terminated || matches!(object, Object::Stream(_)) {
                pos = pos.max(end);
            }
            if let Object::Stream(s) = &object {
                if s.dict.is_type(b"ObjStm") {
                    out.object_streams.push((num, start));
                } else if s.dict.is_type(b"XRef") {
                    trailers.push(s.dict.clone());
                }
            } else if let Object::Dictionary(d) = &object {
                if d.is_type(b"Catalog") {
                    out.catalog = Some((num, generation));
                }
            }
        }
    }
    // `trailer` dictionaries of classic sections.
    let mut pos = 0usize;
    while let Some(hit) = find(data, b"trailer", pos) {
        pos = hit + 7;
        let mut p = Parser::new(data, hit + 7, limits.max_nesting);
        let parsed = p.object();
        work = work.saturating_add(p.pos.min(data.len()).saturating_sub(hit));
        if let Ok(Object::Dictionary(d)) = parsed {
            trailers.push(d);
        }
        if trailers.len() > limits.max_xref_sections || work > work_budget {
            break;
        }
    }
    // Newest last in file order; newest wins. Offsets in the old data
    // (`/Prev`, `/XRefStm`) describe a table that is being discarded.
    for t in trailers.into_iter().rev() {
        merge_trailer(&mut out.trailer, t);
    }
    for key in [&b"Prev"[..], b"XRefStm", b"W", b"Index", b"Filter", b"DecodeParms", b"Length", b"Type"] {
        out.trailer.remove(key);
    }
    if out.objects.is_empty() {
        return Err(Error::NotPdf);
    }
    Ok(out)
}

/// Given the position of `obj`, the position where `N G obj` starts.
fn header_start(data: &[u8], obj_at: usize) -> Option<usize> {
    let mut i = obj_at;
    let back_ws = |i: &mut usize| {
        let before = *i;
        while *i > 0 && is_whitespace(data[*i - 1]) {
            *i -= 1;
        }
        *i < before
    };
    let back_digits = |i: &mut usize| {
        let before = *i;
        while *i > 0 && data[*i - 1].is_ascii_digit() {
            *i -= 1;
        }
        *i < before
    };
    // White space between the generation and `obj` is optional in practice.
    back_ws(&mut i);
    if !back_digits(&mut i) || !back_ws(&mut i) || !back_digits(&mut i) {
        return None;
    }
    // The object number must start a token.
    if i > 0 && is_regular(data[i - 1]) {
        return None;
    }
    Some(i)
}

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

    #[test]
    fn header_start_finds_the_number() {
        let d = b"junk\n12 0 obj\n<<>>";
        assert_eq!(header_start(d, 9), Some(5));
        assert_eq!(header_start(b"endobj", 3), None);
        assert_eq!(header_start(b"x12 0 obj", 6), None);
        assert_eq!(header_start(b"0 obj", 2), None);
    }

    #[test]
    fn xref_stream_rows() {
        let mut entries = Building::default();
        let dict = crate::dictionary! {
            "W" => vec![Object::Integer(1), Object::Integer(2), Object::Integer(1)],
            "Size" => 3,
        };
        let raw = [0, 0, 0, 255, 1, 0, 17, 0, 2, 0, 9, 4];
        add_stream_entries(&dict, &raw, &mut entries, &Limits::default()).unwrap();
        assert_eq!(entries.get(0), None);
        assert_eq!(entries.get(1), Some(&(0, Loc::Offset(17))));
        assert_eq!(entries.get(2), Some(&(0, Loc::Compressed { container: 9, index: 4 })));
        // A free entry in a newer section hides an older definition.
        let older = crate::dictionary! {
            "W" => vec![Object::Integer(1), Object::Integer(2), Object::Integer(1)],
            "Size" => 2,
        };
        add_stream_entries(&older, &[1, 0, 5, 0, 1, 0, 6, 0], &mut entries, &Limits::default()).unwrap();
        assert_eq!(entries.get(0), None);
        assert_eq!(entries.get(1), Some(&(0, Loc::Offset(17))));
    }
}