Skip to main content

pdfcer_model/
lib.rs

1//! The pdfcer COS model layer: objects, lexer, parser, filters, xref
2//! tables and streams, object streams, recovery, `Document`, the read-only
3//! `DocumentView`, the writer (full and incremental save), standard-handler
4//! crypto, content-stream parsing and the page tree.
5//!
6//! Depends on nothing else in the workspace; `pdfcer-core` re-exports every
7//! module at its old path (`docs/ARCHITECTURE.md` §3). No GUI and no network
8//! dependency, and it builds for `wasm32-unknown-unknown`.
9//!
10//! # Spec basis for the header probe
11//!
12//! ISO 32000-1:2008 §7.5.2: the first line of a PDF file is `%PDF-` followed
13//! by `1.N`; ISO 32000-2 adds `2.0`. The spec puts the marker at byte 0.
14//! [`HEADER_SCAN_WINDOW`]'s 1024-byte tolerance is **not** spec text: it
15//! matches mainstream readers, which accept the marker after a BOM or stray
16//! whitespace (recorded empirically in `C:\personal_rag\pdf\`). A successful
17//! probe means only "this looks like a PDF and declares version M.N".
18
19// pdfcer-model parses untrusted input, so a panic reachable from library code is
20// a denial-of-service bug, not a style issue. `unwrap`/`expect`/`panic!` and
21// unchecked indexing/slicing are DENIED crate-wide; fallible paths must return
22// `Result` and bounds-dependent accesses must use `.get(..)`-style checked
23// forms. Tests are exempt (a panicking test is just a failing test) via the
24// `#[allow]` on the `tests` module below.
25#![forbid(unsafe_code)]
26#![deny(
27    clippy::unwrap_used,
28    clippy::expect_used,
29    clippy::panic,
30    clippy::indexing_slicing,
31    clippy::unreachable,
32    clippy::todo,
33    clippy::unimplemented
34)]
35
36pub mod content;
37pub mod crypto;
38pub mod document;
39pub mod filters;
40pub mod graph;
41pub mod lexer;
42pub mod linearization;
43pub mod object;
44pub mod objstm;
45pub mod page_tree;
46pub mod parser;
47pub mod recover;
48pub mod span;
49pub mod view;
50pub mod writer;
51pub mod xref;
52
53use std::fmt;
54use std::path::Path;
55
56/// The maximum number of leading bytes scanned for the `%PDF-` header.
57///
58/// Mainstream PDF readers accept the header marker anywhere within the
59/// first 1024 bytes of the file to tolerate leading BOMs/whitespace that
60/// some producers emit (see the module docs' "Spec basis" note). 1024 is
61/// that conventional window; a marker not present within it is treated as
62/// "not a PDF" ([`PdfError::MissingHeader`]).
63///
64/// This is also a cheap first line of the adversarial-input defence
65/// described in docs/ARCHITECTURE.md §10: probing reads at most this many
66/// bytes, so a hostile multi-gigabyte file cannot make the probe itself
67/// allocate or scan without bound.
68pub const HEADER_SCAN_WINDOW: usize = 1024;
69
70/// A PDF version number as declared in the file header (`%PDF-M.N`).
71///
72/// This is the *declared* version from the header, not a judgement about
73/// which features the file actually uses (a file can declare `1.4` yet be
74/// upgraded in a later incremental update via the catalog's `/Version`
75/// entry — that reconciliation is Pass 1+ work, out of scope for the Pass
76/// 0 header probe).
77///
78/// # Examples
79///
80/// ```
81/// use pdfcer_model::PdfVersion;
82///
83/// let v = PdfVersion { major: 1, minor: 7 };
84/// assert_eq!(v.to_string(), "1.7");
85/// ```
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
87pub struct PdfVersion {
88    /// Major version digit (`1` for PDF 1.x, `2` for PDF 2.0).
89    pub major: u8,
90    /// Minor version digit (`0`–`7` for PDF 1.x, `0` for PDF 2.0).
91    pub minor: u8,
92}
93
94impl fmt::Display for PdfVersion {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        write!(f, "{}.{}", self.major, self.minor)
97    }
98}
99
100/// Errors that can arise from the Pass 0 header-probe surface.
101///
102/// Marked `#[non_exhaustive]` so that later Passes can add variants
103/// (tokenizer errors, xref errors, decryption failures, …) without it
104/// being a breaking change for downstream consumers such as `pdfcer`.
105/// Consumers matching on this enum must therefore include a wildcard arm.
106///
107/// Follows the Rust API Guidelines (C-GOOD-ERR): every variant is
108/// `Send + Sync + 'static` and the type implements [`std::error::Error`]
109/// via `thiserror`.
110#[derive(Debug, thiserror::Error)]
111#[non_exhaustive]
112pub enum PdfError {
113    /// The underlying file could not be read (not found, permission
114    /// denied, an I/O failure mid-read, …). Carries the source
115    /// [`std::io::Error`].
116    #[error("I/O error reading PDF: {0}")]
117    Io(#[from] std::io::Error),
118
119    /// No `%PDF-` marker was found within the first
120    /// [`HEADER_SCAN_WINDOW`] bytes — the input is not a PDF (or is
121    /// damaged beyond recognition at its head). `searched` reports how
122    /// many bytes were actually inspected (may be fewer than the window
123    /// for a short file).
124    #[error("not a PDF: no %PDF- header in the first {searched} bytes")]
125    MissingHeader {
126        /// Number of leading bytes actually inspected.
127        searched: usize,
128    },
129
130    /// A `%PDF-` marker was found but the bytes after it were not a
131    /// parseable `M.N` version number. `found` is a lossy-UTF-8 snapshot
132    /// of the offending bytes, for diagnostics.
133    #[error("malformed PDF version after %PDF- marker: {found:?}")]
134    MalformedVersion {
135        /// Lossy-decoded snapshot of the bytes that failed to parse.
136        found: String,
137    },
138}
139
140/// Probe the leading bytes of a candidate PDF and return its declared
141/// version.
142///
143/// Scans up to the first [`HEADER_SCAN_WINDOW`] bytes of `prefix` for the
144/// `%PDF-` marker (tolerating leading BOM/whitespace, per the module
145/// docs), then parses the `M.N` version immediately following it.
146///
147/// This is a *probe*, not full validation: it says only "this looks like a
148/// PDF declaring version M.N", which is the Pass 0 contract. It does not
149/// read the cross-reference table, trailer, or any object.
150///
151/// # Errors
152///
153/// - [`PdfError::MissingHeader`] if no `%PDF-` marker appears within the
154///   scanned window.
155/// - [`PdfError::MalformedVersion`] if the marker is present but not
156///   followed by a parseable `M.N` (e.g. `%PDF-` at end of input, or
157///   `%PDF-x.y`).
158///
159/// # Examples
160///
161/// ```
162/// use pdfcer_model::{probe_header, PdfVersion};
163///
164/// // A normal header at the start of the buffer.
165/// let v = probe_header(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n").unwrap();
166/// assert_eq!(v, PdfVersion { major: 1, minor: 7 });
167///
168/// // PDF 2.0, tolerated after a leading UTF-8 BOM.
169/// let v = probe_header(b"\xEF\xBB\xBF%PDF-2.0\n").unwrap();
170/// assert_eq!(v.to_string(), "2.0");
171///
172/// // Not a PDF at all.
173/// assert!(probe_header(b"GIF89a").is_err());
174/// ```
175pub fn probe_header(prefix: &[u8]) -> Result<PdfVersion, PdfError> {
176    const MARKER: &[u8] = b"%PDF-";
177
178    // Checked-slicing forms per the crate-level `indexing_slicing` policy:
179    // `.get(..N)` in place of `[..N]`, falling back to the full/empty slice
180    // where the range provably cannot be exceeded anyway.
181    let window = prefix.get(..HEADER_SCAN_WINDOW).unwrap_or(prefix);
182    let Some(pos) = find_subslice(window, MARKER) else {
183        return Err(PdfError::MissingHeader {
184            searched: window.len(),
185        });
186    };
187    // `pos` came from `find_subslice`, so `pos + MARKER.len()` is ≤
188    // `window.len()` by construction; the `unwrap_or` arm is unreachable but
189    // keeps the access checked rather than lint-suppressed.
190    parse_version(window.get(pos + MARKER.len()..).unwrap_or(&[]))
191}
192
193/// Probe a COS-family file whose header is NOT `%PDF-` (`Pass 10.2`).
194///
195/// PDF, FDF (§12.7.7) and Adobe's PPKLITE address book
196/// (`addressbook.acrodata`, ISO 32000-1 §7.5 object/xref grammar under a
197/// `%PPKLITE-2.1` header) share the entire COS container — objects, classic
198/// xref, trailer, `startxref`, `%%EOF` — and differ ONLY in the first-line
199/// marker. This is [`probe_header`] with the marker parameterised: it scans the
200/// same bounded window for the FIRST of `markers` that appears and parses the
201/// `M.N` after it. The version token is cosmetic for a non-PDF (PPKLITE's is
202/// `2.1`, unrelated to any PDF version); it is returned so the same
203/// `Document` assembly path can be reused unchanged.
204///
205/// The offsets in a COS xref table are absolute from byte 0, so the header
206/// must be parsed IN PLACE — a caller cannot substitute a `%PDF-` header of a
207/// different length without invalidating every offset. That is why this is a
208/// header-sniff seam, not a rewrite.
209///
210/// # Errors
211///
212/// - [`PdfError::MissingHeader`] if none of `markers` appears in the window.
213/// - [`PdfError::MalformedVersion`] if a marker is present but not followed by
214///   a parseable `M.N`.
215pub fn probe_cos_header(prefix: &[u8], markers: &[&[u8]]) -> Result<PdfVersion, PdfError> {
216    let window = prefix.get(..HEADER_SCAN_WINDOW).unwrap_or(prefix);
217    for marker in markers {
218        if let Some(pos) = find_subslice(window, marker) {
219            return parse_version(window.get(pos + marker.len()..).unwrap_or(&[]));
220        }
221    }
222    Err(PdfError::MissingHeader {
223        searched: window.len(),
224    })
225}
226
227/// Probe a PDF file on disk and return its declared version.
228///
229/// Opens `path`, reads at most [`HEADER_SCAN_WINDOW`] bytes, and delegates
230/// to [`probe_header`]. Never reads more than the window, so it is safe to
231/// call on arbitrarily large (or hostile) files — the read is bounded.
232///
233/// # Errors
234///
235/// - [`PdfError::Io`] if the file cannot be opened or read.
236/// - Otherwise the same errors as [`probe_header`].
237pub fn probe_file(path: &Path) -> Result<PdfVersion, PdfError> {
238    use std::io::Read as _;
239
240    let file = std::fs::File::open(path)?;
241    let mut buf = Vec::with_capacity(HEADER_SCAN_WINDOW);
242    // `.take(N)` bounds the read at the window size regardless of the
243    // file's true length — the decompression-bomb-adjacent defence from
244    // docs/ARCHITECTURE.md §10.1, applied to the probe itself.
245    file.take(HEADER_SCAN_WINDOW as u64).read_to_end(&mut buf)?;
246    probe_header(&buf)
247}
248
249/// Parse an `M.N` version number from the bytes immediately following the
250/// `%PDF-` marker. Canonically both parts are single digits, but this
251/// accepts multi-digit runs defensively and rejects anything that is not
252/// `<digits> '.' <digits>`.
253fn parse_version(bytes: &[u8]) -> Result<PdfVersion, PdfError> {
254    // Only the first few bytes can legitimately belong to the version;
255    // cap the snapshot so a malformed header can't produce a giant `found`
256    // string in the error.
257    let sample = bytes.get(..16).unwrap_or(bytes);
258
259    let (Some(major), major_len) = take_u8(sample) else {
260        return Err(malformed(sample));
261    };
262    // `major_len` counts bytes `take_u8` actually consumed from `sample`, so
263    // both `get` calls below are in-bounds by construction; checked forms per
264    // the crate-level `indexing_slicing` policy.
265    let rest = sample.get(major_len..).unwrap_or(&[]);
266    if rest.first() != Some(&b'.') {
267        return Err(malformed(sample));
268    }
269    let (Some(minor), _) = take_u8(rest.get(1..).unwrap_or(&[])) else {
270        return Err(malformed(sample));
271    };
272    Ok(PdfVersion { major, minor })
273}
274
275/// Consume a leading run of ASCII digits and return its value plus the
276/// number of bytes consumed. Returns `(None, _)` if there was no leading
277/// digit or the value did not fit in a `u8` (no legitimate PDF version
278/// component exceeds a single digit, so overflow here means garbage).
279fn take_u8(bytes: &[u8]) -> (Option<u8>, usize) {
280    let mut value: u32 = 0;
281    let mut consumed = 0;
282    for &b in bytes {
283        if b.is_ascii_digit() {
284            value = value.saturating_mul(10).saturating_add(u32::from(b - b'0'));
285            consumed += 1;
286        } else {
287            break;
288        }
289    }
290    if consumed == 0 {
291        (None, 0)
292    } else {
293        (u8::try_from(value).ok(), consumed)
294    }
295}
296
297/// Build a [`PdfError::MalformedVersion`] with a lossy snapshot of the
298/// offending bytes.
299fn malformed(sample: &[u8]) -> PdfError {
300    PdfError::MalformedVersion {
301        found: String::from_utf8_lossy(sample).into_owned(),
302    }
303}
304
305/// Return the index of the first occurrence of `needle` in `haystack`, or
306/// `None`. A small naive substring search — the search space is bounded by
307/// [`HEADER_SCAN_WINDOW`] (≤ 1 KiB) and `needle` is the 5-byte `%PDF-`
308/// marker, so a specialised algorithm would be pointless here.
309fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
310    if needle.is_empty() || needle.len() > haystack.len() {
311        return None;
312    }
313    haystack
314        .windows(needle.len())
315        .position(|window| window == needle)
316}
317
318#[cfg(test)]
319// Tests are exempt from the panic-free policy: a panicking assertion IS the
320// test-failure mechanism (see the crate-level lint rationale above).
321#[allow(
322    clippy::unwrap_used,
323    clippy::expect_used,
324    clippy::panic,
325    clippy::indexing_slicing
326)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn parses_standard_1_7_header() {
332        let v = probe_header(b"%PDF-1.7\nrest of file").unwrap();
333        assert_eq!(v, PdfVersion { major: 1, minor: 7 });
334    }
335
336    #[test]
337    fn parses_pdf_2_0_header() {
338        let v = probe_header(b"%PDF-2.0\n").unwrap();
339        assert_eq!(v, PdfVersion { major: 2, minor: 0 });
340        assert_eq!(v.to_string(), "2.0");
341    }
342
343    #[test]
344    fn tolerates_leading_bom_before_marker() {
345        // UTF-8 BOM (EF BB BF) preceding the header — a real producer quirk.
346        let v = probe_header(b"\xEF\xBB\xBF%PDF-1.4\n").unwrap();
347        assert_eq!(v, PdfVersion { major: 1, minor: 4 });
348    }
349
350    #[test]
351    fn rejects_non_pdf() {
352        let err = probe_header(b"GIF89a...").unwrap_err();
353        assert!(matches!(err, PdfError::MissingHeader { searched } if searched == 9));
354    }
355
356    #[test]
357    fn rejects_marker_without_version() {
358        let err = probe_header(b"%PDF-").unwrap_err();
359        assert!(matches!(err, PdfError::MalformedVersion { .. }));
360    }
361
362    #[test]
363    fn rejects_marker_with_nondigit_version() {
364        let err = probe_header(b"%PDF-x.y").unwrap_err();
365        assert!(matches!(err, PdfError::MalformedVersion { .. }));
366    }
367
368    #[test]
369    fn missing_header_searched_count_is_capped_at_window() {
370        // A buffer larger than the scan window with no marker: `searched`
371        // must report the window size, not the full buffer length.
372        let big = vec![b'x'; HEADER_SCAN_WINDOW * 4];
373        let err = probe_header(&big).unwrap_err();
374        assert!(
375            matches!(err, PdfError::MissingHeader { searched } if searched == HEADER_SCAN_WINDOW)
376        );
377    }
378
379    #[test]
380    fn version_ordering_is_sensible() {
381        assert!(PdfVersion { major: 1, minor: 4 } < PdfVersion { major: 1, minor: 7 });
382        assert!(PdfVersion { major: 1, minor: 7 } < PdfVersion { major: 2, minor: 0 });
383    }
384}