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;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct XmpPacket {
pub object: Option<u32>,
pub bytes: u64,
pub namespaces: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum EmbeddedFileHolder {
EmbeddedFiles,
AssociatedFiles,
Annotation,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EmbeddedFile {
pub name: Option<String>,
pub size: Option<u64>,
pub mime: Option<String>,
pub object: Option<u32>,
pub holders: Vec<EmbeddedFileHolder>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Trigger {
OpenAction,
Additional(String),
Activate,
NamedScript(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Owner {
Document,
Page(usize),
Annotation {
page: usize,
object: Option<u32>,
},
FormField(String),
Outline(Option<u32>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Action {
pub kind: ActionKind,
pub trigger: Trigger,
pub owner: Owner,
pub object: Option<u32>,
pub script_bytes: Option<u64>,
pub reaches_outside: bool,
}
const KNOWN_INTERNAL: [&[u8]; 8] = [
b"Hide",
b"SetOCGState",
b"Trans",
b"GoTo3DView",
b"Sound",
b"Movie",
b"Rendition",
b"GoToDp",
];
impl Action {
#[must_use]
pub fn is_active_content(&self) -> bool {
self.reaches_outside
|| matches!(
self.kind,
ActionKind::JavaScript | ActionKind::Launch | ActionKind::SubmitForm | ActionKind::ImportData
)
|| matches!(&self.kind, ActionKind::Other(name) if !KNOWN_INTERNAL.contains(&name.as_slice()))
|| matches!(
self.trigger,
Trigger::OpenAction | Trigger::Additional(_) | Trigger::NamedScript(_)
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Annotation {
pub subtype: String,
pub page: usize,
pub object: Option<u32>,
pub author: Option<String>,
pub contents: Option<String>,
pub off_page: bool,
}
impl Annotation {
#[must_use]
pub fn is_plain(&self) -> bool {
matches!(self.subtype.as_str(), "Link" | "Widget" | "Popup")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FormField {
pub name: String,
pub kind: Option<String>,
pub value: Option<String>,
pub hidden: bool,
pub object: Option<u32>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Disclosure {
pub xmp: Option<XmpPacket>,
pub metadata_streams: Vec<u32>,
pub piece_info: Vec<u32>,
pub thumbnails: Vec<u32>,
pub attachments: Vec<EmbeddedFile>,
pub actions: Vec<Action>,
pub actions_truncated: bool,
pub xfa: bool,
pub active_holders: Vec<u32>,
pub annotations: Vec<Annotation>,
pub fields: Vec<FormField>,
pub layers_off: Vec<String>,
pub unreferenced: Vec<u32>,
pub linearization: Option<u32>,
}
impl Disclosure {
#[must_use]
pub fn redactions(&self) -> Vec<(usize, u32)> {
self.per_page(|a| a.subtype == "Redact")
}
#[must_use]
pub fn off_page_annotations(&self) -> Vec<(usize, u32)> {
self.per_page(|a| a.off_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 {
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()? {
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())
}
pub fn disclosure(&self) -> Result<Disclosure> {
self.disclosure_within(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)
}
}
const TARGET_STEPS: u64 = 16_000_000;
struct Scan<'d> {
doc: &'d Document,
out: Disclosure,
seen_actions: BTreeSet<u32>,
targets: TargetCheck,
}
impl Scan<'_> {
fn read(&self, obj: &Object) -> Result<Option<std::sync::Arc<Object>>> {
self.doc.read(obj)
}
}
fn name_of(obj: &Object) -> Option<String> {
match obj {
Object::Name(n) => Some(String::from_utf8_lossy(n.as_bytes()).into_owned()),
_ => None,
}
}
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;
#[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]));
}
}