laminapdf-model 0.9.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
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
//! What a document holds beyond its visible pages: metadata, attachments, actions and
//! scripts, annotations, form fields, layers that are off, and objects nothing references
//! (ISO 32000-2 §14.3, §7.11.4, §14.13, §12.6, §12.5, §12.7, §8.11). One scan reads them,
//! each item with its object number, so a report can list them and a sanitiser can find them.
//!
//! The typed models of these structures arrive with the editor rounds; when each lands, the
//! scan reads through it and its results stay the same.

mod actions;
mod forms;
mod objects;

pub use actions::TargetCheck;

use std::collections::{BTreeMap, BTreeSet};

use laminapdf_cos::{Object, Result};

use crate::document::Document;
use crate::outline::ActionKind;
use crate::values::text_of;

/// The XMP metadata packet the catalog's `/Metadata` names (§14.3.2).
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct XmpPacket {
    /// Its stream object.
    pub object: Option<u32>,
    /// Its decoded length in bytes (its stored length when it can't be decoded).
    pub bytes: u64,
    /// The namespace URIs its `xmlns:` attributes declare, in the packet's order, once each.
    pub namespaces: Vec<String>,
}

/// What points at an embedded file.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum EmbeddedFileHolder {
    /// The document's `/EmbeddedFiles` name tree (§7.7.4).
    EmbeddedFiles,
    /// An `/AF` array of associated files (§14.13).
    AssociatedFiles,
    /// A `FileAttachment` annotation's `/FS` (§12.5.6.15).
    Annotation,
}

/// An embedded file: a file specification with an `/EF` entry (§7.11.4).
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EmbeddedFile {
    /// `/UF`, else `/F`, decoded.
    pub name: Option<String>,
    /// `/Params /Size`, else the embedded stream's stored length.
    pub size: Option<u64>,
    /// The embedded stream's `/Subtype` (a MIME type).
    pub mime: Option<String>,
    /// The file specification's object (`None` when it is a direct dictionary).
    pub object: Option<u32>,
    /// What points at it; empty when nothing the scan reads does.
    pub holders: Vec<EmbeddedFileHolder>,
}

/// What fires an action.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Trigger {
    /// The catalog's `/OpenAction`.
    OpenAction,
    /// A key of an `/AA` dictionary (`O`, `C`, `K`, `WC`, …), as written.
    Additional(String),
    /// An annotation's `/A`: activating it.
    Activate,
    /// An entry of the document's `/JavaScript` name tree, by its name.
    NamedScript(String),
}

/// The object an action belongs to.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Owner {
    /// The catalog.
    Document,
    /// A page, by 0-based index.
    Page(usize),
    /// An annotation on a page.
    Annotation {
        /// The page's 0-based index.
        page: usize,
        /// The annotation's object.
        object: Option<u32>,
    },
    /// A form field, by its full name.
    FormField(String),
    /// A bookmark (an outline item), by its object.
    ///
    /// Added in 0.7.0.
    Outline(Option<u32>),
}

/// An action reached from a trigger, directly or through `/Next` (§12.6.4).
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Action {
    /// `/S`.
    pub kind: ActionKind,
    /// What fires it (for an action reached through `/Next`, what fires the first one).
    pub trigger: Trigger,
    /// What it belongs to.
    pub owner: Owner,
    /// Its object (`None` for a direct dictionary).
    pub object: Option<u32>,
    /// For a JavaScript action, the script's length in bytes (a stream that can't be decoded
    /// counts its stored length).
    pub script_bytes: Option<u64>,
    /// An action of a type that stays in the document (a page move, a thread, a rendition, a
    /// movie or sound) whose target is another file or the web, or a named action no standard
    /// defines ([`Document::action_reaches_outside`]).
    ///
    /// Added in 0.7.0.
    pub reaches_outside: bool,
}

/// The action types besides `ActionKind`'s own that stay in the document or play its own media.
const KNOWN_INTERNAL: [&[u8]; 8] = [
    b"Hide",
    b"SetOCGState",
    b"Trans",
    b"GoTo3DView",
    b"Sound",
    b"Movie",
    b"Rendition",
    b"GoToDp",
];

impl Action {
    /// Whether it counts as active content: a script, an action that launches, submits or
    /// imports, one of a type no standard defines, one a trigger fires on its own
    /// (`/OpenAction`, `/AA`, a named script), or one whose type stays in the document but whose
    /// target doesn't ([`Action::reaches_outside`]). Links a person follows by activating them
    /// (`URI` to a web address, `GoToR` to another file) are listed but don't count, as
    /// `laminapdf reveal`'s contract says, although the sanitiser's active-content removal takes
    /// them out too.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn is_active_content(&self) -> bool {
        self.reaches_outside
            || matches!(
                self.kind,
                ActionKind::JavaScript | ActionKind::Launch | ActionKind::SubmitForm | ActionKind::ImportData
            )
            // A type no one knows, or one that runs something (`RichMediaExecute`): what the
            // sanitiser removes.
            || matches!(&self.kind, ActionKind::Other(name) if !KNOWN_INTERNAL.contains(&name.as_slice()))
            || matches!(
                self.trigger,
                Trigger::OpenAction | Trigger::Additional(_) | Trigger::NamedScript(_)
            )
    }
}

/// An annotation on a page (§12.5).
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Annotation {
    /// `/Subtype`, as written.
    pub subtype: String,
    /// The page's 0-based index.
    pub page: usize,
    /// Its object (`None` for a direct dictionary).
    pub object: Option<u32>,
    /// `/T`, the author of a markup annotation, decoded.
    pub author: Option<String>,
    /// `/Contents`, decoded.
    pub contents: Option<String>,
    /// Whether it lies wholly outside the page ([`Document::off_page_annotations`]'s
    /// [`OffPage::Outside`](crate::OffPage::Outside)), where no reader sees it.
    ///
    /// Added in 0.9.0.
    pub off_page: bool,
}

impl Annotation {
    /// Whether this is a link, a widget or a popup: annotations that carry no comment of
    /// their own.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn is_plain(&self) -> bool {
        matches!(self.subtype.as_str(), "Link" | "Widget" | "Popup")
    }
}

/// A terminal form field (§12.7.4).
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FormField {
    /// The full name, the `/T` of each ancestor joined with `.`.
    pub name: String,
    /// `/FT` (`Tx`, `Btn`, `Ch`, `Sig`), own or inherited.
    pub kind: Option<String>,
    /// `/V`: a text string decoded, a name as written, an array's items joined with `, `.
    pub value: Option<String>,
    /// Whether every widget of the field is hidden (`/F` with Hidden or `NoView`).
    pub hidden: bool,
    /// The field's object (`None` for a direct dictionary).
    pub object: Option<u32>,
}

/// What [`Document::disclosure`] finds.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Disclosure {
    /// The catalog's XMP packet.
    pub xmp: Option<XmpPacket>,
    /// Other `/Type /Metadata` streams (object-level metadata, §14.3.2).
    pub metadata_streams: Vec<u32>,
    /// Objects with a `/PieceInfo` dictionary (§14.5).
    pub piece_info: Vec<u32>,
    /// Pages with a `/Thumb` image (§12.3.4), by object.
    pub thumbnails: Vec<u32>,
    /// Embedded files, indirect ones by object number, then direct ones.
    pub attachments: Vec<EmbeddedFile>,
    /// Every action reached from a trigger, once each, up to 10,000.
    pub actions: Vec<Action>,
    /// Past the 10,000 it lists, the walk found an action that counts as active content
    /// ([`Action::is_active_content`]), or the bookmark walk reached its bound: count it as active
    /// content. Many internal links alone never set it.
    ///
    /// Added in 0.7.0.
    pub actions_truncated: bool,
    /// Whether the interactive form holds an XFA form (`/XFA`).
    pub xfa: bool,
    /// Objects that hold active content outside any action, in their own dictionary or a direct
    /// one inside it: a 3D stream's `/OnInstantiate`, a rich-media `/Scripts` list or
    /// `/RichMediaContent`, named renditions (`/Names /Renditions`), a reference XObject's
    /// external file (`/Ref`), an output intent's `/DestOutputProfileRef`, an image's or form's
    /// `/OPI`, a movie annotation whose movie is stored elsewhere; and streams whose data is
    /// read from another file (`/F`, `/FFilter`, `/FDecodeParms`).
    ///
    /// Added in 0.7.0.
    pub active_holders: Vec<u32>,
    /// Annotations, page by page.
    pub annotations: Vec<Annotation>,
    /// Terminal form fields, in the form's order.
    pub fields: Vec<FormField>,
    /// The names of the optional content groups the default configuration turns off (§8.11.4.3).
    pub layers_off: Vec<String>,
    /// In-use objects nothing reachable from the trailer references, object and
    /// cross-reference streams and a linearized file's hint streams aside.
    pub unreferenced: Vec<u32>,
    /// The linearization parameter dictionary's object (Annex F.2), when the file has one.
    pub linearization: Option<u32>,
}

impl Disclosure {
    /// The `Redact` annotations, as `(page, count)` with pages ascending.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn redactions(&self) -> Vec<(usize, u32)> {
        self.per_page(|a| a.subtype == "Redact")
    }

    /// The annotations that lie wholly outside their page ([`Annotation::off_page`]), as
    /// `(page, count)` with pages ascending.
    ///
    /// Added in 0.9.0.
    #[must_use]
    pub fn off_page_annotations(&self) -> Vec<(usize, u32)> {
        self.per_page(|a| a.off_page)
    }

    /// The annotations `chosen` picks, counted page by page.
    fn per_page(&self, chosen: impl Fn(&Annotation) -> bool) -> Vec<(usize, u32)> {
        let mut out: BTreeMap<usize, u32> = BTreeMap::new();
        for annot in self.annotations.iter().filter(|a| chosen(a)) {
            let n = out.entry(annot.page).or_default();
            *n = n.saturating_add(1);
        }
        out.into_iter().collect()
    }
}

impl Document {
    /// The embedded files for the disclosure, from the attachments' own walk over every object
    /// ([`Document::attachments`]' holders, `/AF` on any object, and files nothing holds): the
    /// indirect ones by object number, then the direct ones in the order found.
    fn embedded_files(&self) -> Result<Vec<EmbeddedFile>> {
        let mut indirect: BTreeMap<u32, EmbeddedFile> = BTreeMap::new();
        let mut direct = Vec::new();
        for found in self.every_file_spec()? {
            // A file specification without `/EF` names a file elsewhere: nothing embedded.
            if found
                .spec
                .get("EF")
                .and_then(|ef| self.read(ef).ok().flatten())
                .is_none_or(|ef| ef.as_dict().is_none())
            {
                continue;
            }
            let stored = crate::attachments::embedded_stream(self, &found.spec)?.and_then(|s| match &*s {
                Object::Stream(s) => Some(len(s.data.len())),
                _ => None,
            });
            let a = found.attachment;
            let mut holders: Vec<EmbeddedFileHolder> = a
                .holders
                .iter()
                .map(|h| match h {
                    crate::AttachmentHolder::EmbeddedFiles => EmbeddedFileHolder::EmbeddedFiles,
                    crate::AttachmentHolder::FileAttachment { .. } => EmbeddedFileHolder::Annotation,
                    _ => EmbeddedFileHolder::AssociatedFiles,
                })
                .collect();
            holders.sort_unstable();
            holders.dedup();
            let object = match found.at {
                crate::FileSpecAt::Object(r) => Some(r.num),
                _ => None,
            };
            let file = EmbeddedFile {
                name: a.name,
                size: a.size.or(stored),
                mime: a.mime,
                object,
                holders,
            };
            match object {
                Some(num) => {
                    indirect.insert(num, file);
                }
                None => direct.push(file),
            }
        }
        Ok(indirect.into_values().chain(direct).collect())
    }

    /// What the document holds beyond its visible pages ([`Disclosure`]). It reads every
    /// object once, within the [`Limits`](crate::Limits); anything it can't read counts as
    /// absent, as ADR 0003's tolerant paths do.
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::DataPending`], [`laminapdf_cos::Error::Source`] and
    /// [`laminapdf_cos::Error::Strict`]: the errors that must propagate.
    ///
    /// Added in 0.2.0.
    pub fn disclosure(&self) -> Result<Disclosure> {
        self.disclosure_within(TARGET_STEPS)
    }

    /// [`Document::disclosure`] with the action target checks bounded at `target_steps`.
    fn disclosure_within(&self, target_steps: u64) -> Result<Disclosure> {
        let mut targets = TargetCheck::new();
        targets.set_limit(target_steps);
        let mut scan = Scan {
            doc: self,
            out: Disclosure::default(),
            seen_actions: BTreeSet::new(),
            targets,
        };
        let catalog = self.catalog()?;
        scan.objects(&catalog)?;
        scan.document_actions(&catalog)?;
        scan.pages()?;
        scan.fields(&catalog)?;
        scan.outlines(&catalog)?;
        scan.layers(&catalog)?;
        scan.out.attachments = self.embedded_files()?;
        Ok(scan.out)
    }
}

/// The most steps the action target checks of one scan take in all
/// ([`TargetCheck::set_limit`]): past it, every action whose type may leave the file counts as
/// reaching outside, so reveal fails closed on a file built to make the checks slow.
const TARGET_STEPS: u64 = 16_000_000;

/// The scan's state.
struct Scan<'d> {
    doc: &'d Document,
    out: Disclosure,
    /// Action objects already listed.
    seen_actions: BTreeSet<u32>,
    /// What checking action targets has learned.
    targets: TargetCheck,
}

impl Scan<'_> {
    /// `obj` resolved tolerantly.
    fn read(&self, obj: &Object) -> Result<Option<std::sync::Arc<Object>>> {
        self.doc.read(obj)
    }
}

/// A name's bytes, as written.
fn name_of(obj: &Object) -> Option<String> {
    match obj {
        Object::Name(n) => Some(String::from_utf8_lossy(n.as_bytes()).into_owned()),
        _ => None,
    }
}

/// `n` as a byte count.
fn len(n: usize) -> u64 {
    u64::try_from(n).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests {
    use laminapdf_test_fixtures::classic_with_root;

    use crate::document::Document;

    /// Past the scan's bound on target checks, an action whose type may leave the file counts
    /// as reaching outside: reveal fails closed.
    #[test]
    fn past_its_bound_the_target_check_answers_yes() {
        let doc = Document::open(
            classic_with_root(
                &[
                    "<< /Type /Catalog /Pages 2 0 R /OpenAction 3 0 R >>",
                    "<< /Type /Pages /Kids [] /Count 0 >>",
                    "<< /S /Rendition /OP 0 /R << /S /MR /C << /S /MCD /CT (video/mp4) >> >> >>",
                ],
                "",
            ),
            laminapdf_cos::OpenOptions::default(),
        )
        .unwrap();
        let reaches = |steps| {
            doc.disclosure_within(steps)
                .unwrap()
                .actions
                .iter()
                .map(|a| a.reaches_outside)
                .collect::<Vec<_>>()
        };
        assert_eq!((reaches(2), reaches(1_000)), (vec![true], vec![false]));
    }
}