use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use crate::content::PageCompiler;
use crate::document::{DocumentLimits, DocumentSnapshot, PageIndex, ParseContext};
use crate::object::{Dictionary, NameId, NameTable, ObjectId, PdfObject, decode_text_string_lossy};
use crate::source::PdfSource;
use crate::structure::{ObjectLocation, RecoveryEvent};
mod byterange;
mod metrics;
mod xmp;
pub use byterange::{
ByteRangeAssessment, ByteRangeSpan, ByteRangeValidity, assess as assess_byte_range,
};
pub use metrics::{FontRecord, ImageRecord, PageMetrics};
pub use xmp::{XmpHistoryEvent, XmpLineage};
#[derive(Debug, Clone)]
pub enum OpenOutcome {
Ok,
Recovered { how: Vec<String> },
Failed { error: String },
}
#[derive(Debug, Clone)]
pub struct EncryptionInfo {
pub version: i64,
pub revision: i64,
pub method: String,
pub user_password_empty: bool,
}
#[derive(Debug, Clone)]
pub struct HeaderInfo {
pub major: u8,
pub minor: u8,
pub header_offset: u64,
}
#[derive(Debug, Clone, Default)]
pub struct DocumentIdentity {
pub id_permanent: Option<String>,
pub id_changing: Option<String>,
pub info: BTreeMap<String, String>,
pub has_xmp_metadata: bool,
pub xmp: Option<XmpLineage>,
}
#[derive(Debug, Clone)]
pub struct SignatureInfo {
pub field_name: Option<String>,
pub field_object: Option<ObjectId>,
pub value_object: Option<ObjectId>,
pub filter: Option<String>,
pub sub_filter: Option<String>,
pub signed_at: Option<String>,
pub byte_range: Vec<i64>,
pub covers_whole_file: bool,
pub byte_range_validity: ByteRangeValidity,
pub covered_ranges: Vec<ByteRangeSpan>,
pub byte_range_detail: Option<String>,
pub docmdp: Option<DocMdpInfo>,
pub fieldmdp: Option<FieldMdpInfo>,
}
#[derive(Debug, Clone)]
pub struct DocMdpInfo {
pub p: Option<i64>,
}
#[derive(Debug, Clone)]
pub struct FieldMdpInfo {
pub p: Option<i64>,
pub action: Option<String>,
pub fields: Option<Vec<String>>,
}
#[derive(Debug, Clone, Default)]
pub struct SignatureInventory {
pub signatures: Vec<SignatureInfo>,
pub unsigned_fields: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XrefSectionKind {
Classic,
Stream,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct XrefEntryCounts {
pub total: u32,
pub live: u32,
pub compressed: u32,
pub free: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XrefEntryLocation {
Offset(u64),
InObjectStream {
container: u32,
index: u32,
},
Free,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XrefEntryFacts {
pub id: ObjectId,
pub location: XrefEntryLocation,
}
#[derive(Debug, Clone)]
pub struct XrefSectionFacts {
pub offset: u64,
pub kind: XrefSectionKind,
pub entry_counts: XrefEntryCounts,
pub entries: Vec<XrefEntryFacts>,
pub prev: Option<u64>,
pub auxiliary_of: Option<u32>,
pub recovery: Vec<String>,
}
#[derive(Debug, Clone, Default)]
pub struct XrefHealth {
pub recovery_used: bool,
pub rebuilt: bool,
pub revision_count: usize,
pub sections: Vec<XrefSectionFacts>,
}
#[derive(Debug, Clone)]
pub enum CompileStatus {
Ok {
op_count: usize,
},
Degraded {
op_count: usize,
detail: String,
},
Failed {
error: String,
},
}
#[derive(Debug, Clone)]
pub struct MarkedContentRecord {
pub tag: String,
pub open_offset: usize,
pub close_offset: Option<usize>,
pub bbox: Option<[f64; 4]>,
}
#[derive(Debug, Clone)]
pub struct PageStatus {
pub index: u32,
pub media_box_present: bool,
pub compile: CompileStatus,
pub metrics: Option<PageMetrics>,
pub marked_content: Vec<MarkedContentRecord>,
}
#[derive(Debug, Clone)]
pub struct AnnotationRecord {
pub page: u32,
pub object: Option<ObjectId>,
pub subtype: Option<String>,
pub contents: Option<String>,
pub name: Option<String>,
pub modified: Option<String>,
pub creation_date: Option<String>,
pub author: Option<String>,
pub subject: Option<String>,
pub intent: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct AnnotationInventory {
pub count_per_subtype: BTreeMap<String, u32>,
pub annotations: Vec<AnnotationRecord>,
}
impl AnnotationInventory {
pub fn total(&self) -> u32 {
self.count_per_subtype.values().sum()
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct FeatureFlags {
pub has_acroform: bool,
pub has_xfa: bool,
pub has_javascript: bool,
pub has_outlines: bool,
pub has_optional_content: bool,
pub uses_object_streams: bool,
pub has_embedded_files: bool,
}
#[derive(Debug, Clone)]
pub struct DocumentReport {
pub open: OpenOutcome,
pub header: Option<HeaderInfo>,
pub linearized: bool,
pub encryption: Option<EncryptionInfo>,
pub xref: XrefHealth,
pub identity: DocumentIdentity,
pub pages: Vec<PageStatus>,
pub annotations: AnnotationInventory,
pub signatures: SignatureInventory,
pub features: FeatureFlags,
pub fonts: Vec<FontRecord>,
pub images: Vec<ImageRecord>,
}
const MAX_PARENT_HOPS: usize = 64;
pub fn examine(source: Arc<dyn PdfSource>, limits: DocumentLimits) -> DocumentReport {
examine_with_password(source, limits, None)
}
pub fn examine_with_password(
source: Arc<dyn PdfSource>,
limits: DocumentLimits,
password: Option<&str>,
) -> DocumentReport {
let mut audit_limits = limits.clone();
audit_limits.preserve_section_entries = true;
match DocumentSnapshot::open_with_password(Arc::clone(&source), audit_limits, password) {
Ok(snapshot) => examine_snapshot(&snapshot, None),
Err(err) => examine_failed(source, limits, err.to_string()),
}
}
pub fn examine_snapshot(snapshot: &DocumentSnapshot, pages: Option<&[u32]>) -> DocumentReport {
let recovery = snapshot.recovery_events();
let open = if recovery.is_empty() {
OpenOutcome::Ok
} else {
OpenOutcome::Recovered {
how: recovery.iter().map(describe_recovery).collect(),
}
};
let xref = XrefHealth {
recovery_used: !recovery.is_empty(),
rebuilt: recovery
.iter()
.any(|e| matches!(e, RecoveryEvent::XrefRebuilt)),
revision_count: snapshot.structure().sections.len(),
sections: translate_sections(&snapshot.structure().sections),
};
let mut ctx = ParseContext::new();
let encryption = read_encryption(snapshot, &mut ctx);
let linearized = detect_linearized(snapshot, &mut ctx);
let (pages, fonts, images) = examine_pages(snapshot, pages);
let annotations = inventory_annotations(snapshot, &mut ctx);
let features = read_features(snapshot, &mut ctx);
let identity = read_identity(snapshot, &mut ctx);
let signatures = inventory_signatures(snapshot, &mut ctx);
DocumentReport {
open,
header: Some(read_header(snapshot.structure())),
linearized,
encryption,
xref,
identity,
pages,
annotations,
signatures,
features,
fonts,
images,
}
}
fn examine_failed(
source: Arc<dyn PdfSource>,
limits: DocumentLimits,
error: String,
) -> DocumentReport {
let mut report = DocumentReport {
open: OpenOutcome::Failed { error },
header: None,
linearized: false,
encryption: None,
xref: XrefHealth::default(),
identity: DocumentIdentity::default(),
pages: Vec::new(),
annotations: AnnotationInventory::default(),
signatures: SignatureInventory::default(),
features: FeatureFlags::default(),
fonts: Vec::new(),
images: Vec::new(),
};
let names = NameTable::new();
let structure_limits = crate::structure::StructureLimits {
syntax: limits.syntax.clone(),
max_revisions: limits.max_revisions,
max_objects: limits.max_objects,
max_decoded_bytes: limits.max_decoded_bytes_per_context,
preserve_section_entries: true,
};
let Ok(structure) =
crate::structure::load_structure(source.as_ref(), &names, &structure_limits)
else {
return report;
};
report.xref = XrefHealth {
recovery_used: !structure.recovery.is_empty(),
rebuilt: structure
.recovery
.iter()
.any(|e| matches!(e, RecoveryEvent::XrefRebuilt)),
revision_count: structure.sections.len(),
sections: translate_sections(&structure.sections),
};
report.features.uses_object_streams = xref_uses_object_streams(&structure.xref);
report.header = Some(read_header(&structure));
read_file_id(&structure.trailer, &mut report.identity);
let snapshot = DocumentSnapshot::from_parts(
source,
structure,
names,
crate::document::PageTreeIndex::default(),
None,
limits,
);
let mut ctx = ParseContext::new();
report.encryption = read_encryption(&snapshot, &mut ctx);
report.linearized = detect_linearized(&snapshot, &mut ctx);
report
}
fn describe_recovery(event: &RecoveryEvent) -> String {
match event {
RecoveryEvent::StartXrefRecovered { reported, used } => match reported {
Some(r) => format!("startxref pointed at {r}; recovered chain at {used}"),
None => format!("startxref missing; recovered chain at {used}"),
},
RecoveryEvent::ObjectOffsetRepaired {
id,
declared,
actual,
} => {
format!("object {id} xref offset {declared} wrong; found at {actual}")
}
RecoveryEvent::StreamLengthRepaired {
id,
declared,
actual,
} => {
format!("stream {id} /Length {declared:?} wrong; actual {actual}")
}
RecoveryEvent::ReferenceGenerationRepaired {
id,
referenced,
offset,
} => {
format!(
"object {id} reference {referenced} R at offset {offset} omitted generation; assumed 0"
)
}
RecoveryEvent::XrefRebuilt => "cross-reference table rebuilt by full object scan".into(),
RecoveryEvent::SizeRepaired { declared, actual } => {
format!("trailer /Size {declared} wrong; actual {actual}")
}
RecoveryEvent::Other(s) => s.clone(),
}
}
fn translate_sections(sections: &[crate::structure::XrefSection]) -> Vec<XrefSectionFacts> {
sections
.iter()
.map(|section| XrefSectionFacts {
offset: section.offset,
kind: match section.kind {
crate::structure::XrefSectionKind::Classic => XrefSectionKind::Classic,
crate::structure::XrefSectionKind::Stream => XrefSectionKind::Stream,
},
entry_counts: XrefEntryCounts {
total: section.entry_counts.total,
live: section.entry_counts.live,
compressed: section.entry_counts.compressed,
free: section.entry_counts.free,
},
entries: section
.entries
.iter()
.map(|entry| XrefEntryFacts {
id: entry.id,
location: match entry.location {
ObjectLocation::Offset(offset) => XrefEntryLocation::Offset(offset),
ObjectLocation::InObjectStream { container, index } => {
XrefEntryLocation::InObjectStream { container, index }
}
ObjectLocation::Free => XrefEntryLocation::Free,
},
})
.collect(),
prev: section.prev,
auxiliary_of: section.auxiliary_of,
recovery: section.recovery.iter().map(describe_recovery).collect(),
})
.collect()
}
fn resolve(
snapshot: &DocumentSnapshot,
id: ObjectId,
ctx: &mut ParseContext,
) -> Option<Arc<PdfObject>> {
snapshot.objects().resolve(snapshot, id, ctx).ok()
}
fn resolve_value(
snapshot: &DocumentSnapshot,
value: &PdfObject,
ctx: &mut ParseContext,
) -> Option<Arc<PdfObject>> {
match value {
PdfObject::Reference(id) => resolve(snapshot, *id, ctx),
other => Some(Arc::new(other.clone())),
}
}
fn dict_get_resolved(
snapshot: &DocumentSnapshot,
dict: &Dictionary,
key: NameId,
ctx: &mut ParseContext,
) -> Option<Arc<PdfObject>> {
resolve_value(snapshot, dict.get(key)?, ctx)
}
fn read_header(structure: &crate::structure::DocumentStructure) -> HeaderInfo {
HeaderInfo {
major: structure.version.major,
minor: structure.version.minor,
header_offset: structure.header_offset,
}
}
fn detect_linearized(snapshot: &DocumentSnapshot, ctx: &mut ParseContext) -> bool {
let first = snapshot
.structure()
.xref
.live_entries()
.filter_map(|entry| match entry.location {
ObjectLocation::Offset(offset) => Some((offset, entry.id)),
ObjectLocation::InObjectStream { .. } | ObjectLocation::Free => None,
})
.min_by_key(|(offset, _)| *offset);
let Some((_, id)) = first else {
return false;
};
let Some(object) = resolve(snapshot, id, ctx) else {
return false;
};
let Some(dict) = object.as_dict() else {
return false;
};
let key = snapshot.names().intern(b"Linearized");
dict.contains_key(key)
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
const HEX: &[u8; 16] = b"0123456789abcdef";
out.push(HEX[(byte >> 4) as usize] as char);
out.push(HEX[(byte & 0x0f) as usize] as char);
}
out
}
fn read_file_id(trailer: &crate::structure::Trailer, identity: &mut DocumentIdentity) {
if let Some([permanent, changing]) = trailer.file_id.as_ref() {
identity.id_permanent = Some(hex(permanent.as_bytes()));
identity.id_changing = Some(hex(changing.as_bytes()));
}
}
fn read_identity(snapshot: &DocumentSnapshot, ctx: &mut ParseContext) -> DocumentIdentity {
let mut identity = DocumentIdentity::default();
let structure = snapshot.structure();
read_file_id(&structure.trailer, &mut identity);
let names = snapshot.names();
if let Some(info_id) = structure.trailer.info
&& let Some(info) = resolve(snapshot, info_id, ctx)
&& let Some(info) = info.as_dict()
{
for (key, value) in info.iter() {
let Some(value) = resolve_value(snapshot, value, ctx) else {
continue;
};
let PdfObject::String(text) = value.as_ref() else {
continue;
};
let key = String::from_utf8_lossy(&names.resolve(key)).into_owned();
identity
.info
.insert(key, String::from_utf8_lossy(text.as_bytes()).into_owned());
}
}
let root = structure.trailer.root;
if let Some(catalog) = resolve(snapshot, root, ctx)
&& let Some(catalog) = catalog.as_dict()
&& let Some(metadata_key) = names.lookup(b"Metadata")
&& let Some(metadata) = dict_get_resolved(snapshot, catalog, metadata_key, ctx)
&& !matches!(metadata.as_ref(), PdfObject::Null)
{
identity.has_xmp_metadata = true;
if let PdfObject::Stream(stream) = metadata.as_ref()
&& let Ok(packet) = snapshot.decode_stream_data(stream, ctx)
{
let lineage = xmp::parse(&packet);
if !lineage.is_empty() {
identity.xmp = Some(lineage);
}
}
}
identity
}
fn inventory_signatures(snapshot: &DocumentSnapshot, ctx: &mut ParseContext) -> SignatureInventory {
let mut inventory = SignatureInventory::default();
let names = snapshot.names();
let root = snapshot.structure().trailer.root;
let Some(catalog) = resolve(snapshot, root, ctx) else {
return inventory;
};
let Some(catalog) = catalog.as_dict() else {
return inventory;
};
let Some(acroform_key) = names.lookup(b"AcroForm") else {
return inventory;
};
let Some(acroform) = dict_get_resolved(snapshot, catalog, acroform_key, ctx) else {
return inventory;
};
let Some(acroform) = acroform.as_dict() else {
return inventory;
};
let Some(fields_key) = names.lookup(b"Fields") else {
return inventory;
};
let Some(fields) = dict_get_resolved(snapshot, acroform, fields_key, ctx) else {
return inventory;
};
let source_len = snapshot.source().len();
let mut seen = 0usize;
collect_signature_fields(
snapshot,
&fields,
None,
source_len,
&mut inventory,
&mut seen,
ctx,
);
inventory
}
const MAX_FORM_FIELDS: usize = 65_536;
fn collect_signature_fields(
snapshot: &DocumentSnapshot,
node: &PdfObject,
field_id: Option<ObjectId>,
source_len: u64,
inventory: &mut SignatureInventory,
seen: &mut usize,
ctx: &mut ParseContext,
) {
if *seen >= MAX_FORM_FIELDS {
return;
}
let names = snapshot.names();
if let PdfObject::Array(entries) = node {
for entry in entries.iter() {
let Some(field) = resolve_value(snapshot, entry, ctx) else {
continue;
};
collect_signature_fields(
snapshot,
&field,
entry.as_reference(),
source_len,
inventory,
seen,
ctx,
);
}
return;
}
let Some(field) = node.as_dict() else {
return;
};
*seen += 1;
let is_signature = names
.lookup(b"FT")
.and_then(|k| field.get(k))
.and_then(PdfObject::as_name)
.is_some_and(|n| names.resolve(n).as_ref() == b"Sig");
if is_signature {
let value_id = names
.lookup(b"V")
.and_then(|k| field.get(k))
.and_then(PdfObject::as_reference);
match names
.lookup(b"V")
.and_then(|k| dict_get_resolved(snapshot, field, k, ctx))
.filter(|v| !matches!(v.as_ref(), PdfObject::Null))
{
Some(value) => {
if let Some(sig) = value.as_dict() {
inventory.signatures.push(read_signature(
snapshot, field, field_id, sig, value_id, source_len, ctx,
));
}
}
None => inventory.unsigned_fields += 1,
}
}
if let Some(kids) = names
.lookup(b"Kids")
.and_then(|k| dict_get_resolved(snapshot, field, k, ctx))
{
collect_signature_fields(snapshot, &kids, None, source_len, inventory, seen, ctx);
}
}
fn read_signature(
snapshot: &DocumentSnapshot,
field: &Dictionary,
field_id: Option<ObjectId>,
sig: &Dictionary,
value_id: Option<ObjectId>,
source_len: u64,
ctx: &mut ParseContext,
) -> SignatureInfo {
let names = snapshot.names();
let text = |dict: &Dictionary, key: &[u8], ctx: &mut ParseContext| -> Option<String> {
let k = names.lookup(key)?;
let value = dict_get_resolved(snapshot, dict, k, ctx)?;
match value.as_ref() {
PdfObject::String(s) => Some(String::from_utf8_lossy(s.as_bytes()).into_owned()),
PdfObject::Name(n) => Some(String::from_utf8_lossy(&names.resolve(*n)).into_owned()),
_ => None,
}
};
let entries: Vec<Option<i64>> = names
.lookup(b"ByteRange")
.and_then(|k| dict_get_resolved(snapshot, sig, k, ctx))
.and_then(|v| match v.as_ref() {
PdfObject::Array(entries) => Some(
entries
.iter()
.map(|e| resolve_value(snapshot, e, ctx).and_then(|resolved| resolved.as_int()))
.collect(),
),
_ => None,
})
.unwrap_or_default();
let byte_range: Vec<i64> = entries.iter().filter_map(|entry| *entry).collect();
let assessment = byterange::assess(&entries, source_len);
let (docmdp, fieldmdp) = read_transform_policies(snapshot, sig, ctx);
SignatureInfo {
field_name: text(field, b"T", ctx),
field_object: field_id,
value_object: value_id,
filter: text(sig, b"Filter", ctx),
sub_filter: text(sig, b"SubFilter", ctx),
signed_at: text(sig, b"M", ctx),
byte_range,
covers_whole_file: assessment.validity == ByteRangeValidity::Valid,
byte_range_validity: assessment.validity,
covered_ranges: assessment.covered,
byte_range_detail: assessment.detail,
docmdp,
fieldmdp,
}
}
fn read_transform_policies(
snapshot: &DocumentSnapshot,
sig: &Dictionary,
ctx: &mut ParseContext,
) -> (Option<DocMdpInfo>, Option<FieldMdpInfo>) {
let names = snapshot.names();
let mut docmdp = None;
let mut fieldmdp = None;
let Some(reference_key) = names.lookup(b"Reference") else {
return (None, None);
};
let Some(reference) = dict_get_resolved(snapshot, sig, reference_key, ctx) else {
return (None, None);
};
let PdfObject::Array(entries) = reference.as_ref() else {
return (None, None);
};
for entry in entries.iter() {
let Some(sig_ref) = resolve_value(snapshot, entry, ctx) else {
continue;
};
let Some(sig_ref) = sig_ref.as_dict() else {
continue;
};
let method = names
.lookup(b"TransformMethod")
.and_then(|key| sig_ref.get(key))
.and_then(PdfObject::as_name)
.map(|name| names.resolve(name));
let Some(method) = method else {
continue;
};
if method.as_ref() == b"DocMDP" && docmdp.is_none() {
docmdp = Some(DocMdpInfo {
p: read_docmdp_p(snapshot, sig_ref, ctx),
});
} else if method.as_ref() == b"FieldMDP" && fieldmdp.is_none() {
fieldmdp = Some(read_fieldmdp_params(snapshot, sig_ref, ctx));
}
}
(docmdp, fieldmdp)
}
fn transform_params(
snapshot: &DocumentSnapshot,
sig_ref: &Dictionary,
ctx: &mut ParseContext,
) -> Option<Arc<PdfObject>> {
let key = snapshot.names().lookup(b"TransformParams")?;
let params = dict_get_resolved(snapshot, sig_ref, key, ctx)?;
if params.as_dict().is_some() {
Some(params)
} else {
None
}
}
fn read_docmdp_p(
snapshot: &DocumentSnapshot,
sig_ref: &Dictionary,
ctx: &mut ParseContext,
) -> Option<i64> {
let params = transform_params(snapshot, sig_ref, ctx)?;
let params = params.as_dict()?;
snapshot
.names()
.lookup(b"P")
.and_then(|key| dict_get_resolved(snapshot, params, key, ctx))
.and_then(|value| value.as_int())
}
fn read_fieldmdp_params(
snapshot: &DocumentSnapshot,
sig_ref: &Dictionary,
ctx: &mut ParseContext,
) -> FieldMdpInfo {
let mut info = FieldMdpInfo {
p: None,
action: None,
fields: None,
};
let Some(params) = transform_params(snapshot, sig_ref, ctx) else {
return info;
};
let Some(params) = params.as_dict() else {
return info;
};
let names = snapshot.names();
info.action = names
.lookup(b"Action")
.and_then(|key| params.get(key))
.and_then(PdfObject::as_name)
.map(|name| String::from_utf8_lossy(&names.resolve(name)).into_owned());
info.fields = names.lookup(b"Fields").and_then(|key| {
let value = dict_get_resolved(snapshot, params, key, ctx)?;
let PdfObject::Array(entries) = value.as_ref() else {
return None;
};
let mut names_out = Vec::new();
for entry in entries.iter() {
let Some(field) = resolve_value(snapshot, entry, ctx) else {
continue;
};
if let PdfObject::String(text) = field.as_ref() {
names_out.push(decode_text_string_lossy(text.as_bytes()));
}
}
Some(names_out)
});
info.p = names
.lookup(b"P")
.and_then(|key| dict_get_resolved(snapshot, params, key, ctx))
.and_then(|value| value.as_int());
info
}
fn read_encryption(snapshot: &DocumentSnapshot, ctx: &mut ParseContext) -> Option<EncryptionInfo> {
let encrypt_ref = snapshot.structure().trailer.encrypt;
let names = snapshot.names();
let dict: Option<Arc<PdfObject>> = match encrypt_ref {
Some(id) => resolve(snapshot, id, ctx),
None => None,
};
let dict = dict?;
let dict = dict.as_dict()?;
let get_int = |key: &[u8], ctx: &mut ParseContext| -> i64 {
names
.lookup(key)
.and_then(|k| dict_get_resolved(snapshot, dict, k, ctx))
.and_then(|v| v.as_int())
.unwrap_or(0)
};
let version = get_int(b"V", ctx);
let revision = get_int(b"R", ctx);
let length_bits = {
let l = get_int(b"Length", ctx);
if l == 0 { 40 } else { l }
};
let method = match (version, revision) {
(5, _) | (_, 5 | 6) => "AES-256".to_owned(),
(4, _) => {
if crypt_filter_is_aes(snapshot, dict, ctx) {
"AES-128".to_owned()
} else {
"RC4-128".to_owned()
}
}
(1, _) => "RC4-40".to_owned(),
(2, _) => format!("RC4-{length_bits}"),
_ => "unknown".to_owned(),
};
let user_password_empty = {
let file_id = snapshot
.structure()
.trailer
.file_id
.as_ref()
.map(|id| id[0].as_bytes().to_vec())
.unwrap_or_default();
let (enc, _scheme) = crate::document::parse_encrypt_dict(dict, file_id, names);
crate::security::StandardHandler::verify_password(&enc, "").is_some()
};
Some(EncryptionInfo {
version,
revision,
method,
user_password_empty,
})
}
fn crypt_filter_is_aes(
snapshot: &DocumentSnapshot,
encrypt: &Dictionary,
ctx: &mut ParseContext,
) -> bool {
let names = snapshot.names();
let Some(cf_key) = names.lookup(b"CF") else {
return false;
};
let Some(cf) = dict_get_resolved(snapshot, encrypt, cf_key, ctx) else {
return false;
};
let Some(cf) = cf.as_dict() else { return false };
let Some(stdcf_key) = names.lookup(b"StdCF") else {
return false;
};
let Some(stdcf) = dict_get_resolved(snapshot, cf, stdcf_key, ctx) else {
return false;
};
let Some(stdcf) = stdcf.as_dict() else {
return false;
};
let Some(cfm_key) = names.lookup(b"CFM") else {
return false;
};
let Some(cfm) = stdcf.get(cfm_key).and_then(PdfObject::as_name) else {
return false;
};
let cfm = names.resolve(cfm);
cfm.as_ref() == b"AESV2" || cfm.as_ref() == b"AESV3"
}
fn examine_pages(
snapshot: &DocumentSnapshot,
selected: Option<&[u32]>,
) -> (Vec<PageStatus>, Vec<FontRecord>, Vec<ImageRecord>) {
let every_page: Vec<u32>;
let indices = match selected {
Some(indices) => indices,
None => {
every_page = (0..snapshot.page_count()).collect();
&every_page
}
};
let compiler = PageCompiler::new().with_annotations(true);
let mut out = Vec::with_capacity(indices.len());
let mut inventory = metrics::Inventory::new();
for &index in indices {
let mut ctx = ParseContext::new();
let media_box_present = page_has_media_box(snapshot, index, &mut ctx);
let repairs_before = ctx.recovery.len();
let (compile, metrics) =
match compiler.compile_semantic(snapshot, PageIndex(index), &mut ctx) {
Ok(page) => {
let op_count = page.ops.len();
let metrics = inventory.absorb_page(snapshot, &page);
let compile = if ctx.recovery.len() > repairs_before {
let detail = ctx.recovery[repairs_before..]
.iter()
.map(describe_recovery)
.collect::<Vec<_>>()
.join("; ");
CompileStatus::Degraded { op_count, detail }
} else {
CompileStatus::Ok { op_count }
};
(compile, Some(metrics))
}
Err(e) => (
CompileStatus::Failed {
error: e.to_string(),
},
None,
),
};
let mut marker_ctx = ParseContext::new();
let marked_content =
match compiler.marked_content_spans(snapshot, PageIndex(index), &mut marker_ctx) {
Ok(spans) => spans
.into_iter()
.map(|span| MarkedContentRecord {
tag: span.tag,
open_offset: span.open_offset,
close_offset: span.close_offset,
bbox: span.bbox.map(|b| [b.x0, b.y0, b.x1, b.y1]),
})
.collect(),
Err(_) => Vec::new(),
};
out.push(PageStatus {
index,
media_box_present,
compile,
metrics,
marked_content,
});
}
let (fonts, images) = inventory.into_parts();
(out, fonts, images)
}
fn page_has_media_box(snapshot: &DocumentSnapshot, index: u32, ctx: &mut ParseContext) -> bool {
let Ok(page_ref) = snapshot.page(PageIndex(index)) else {
return false;
};
let names = snapshot.names();
let media_box = names.known.media_box;
let parent = names.known.parent;
let Some(object) = page_ref.object else {
return false;
};
let mut current = resolve(snapshot, object, ctx);
for _ in 0..MAX_PARENT_HOPS {
let Some(obj) = current else { return false };
let Some(dict) = obj.as_dict() else {
return false;
};
if dict.contains_key(media_box) {
return true;
}
current = dict
.get(parent)
.and_then(|p| resolve_value(snapshot, p, ctx));
}
false
}
fn inventory_annotations(
snapshot: &DocumentSnapshot,
ctx: &mut ParseContext,
) -> AnnotationInventory {
let names = snapshot.names();
let annots_key = names.intern(b"Annots");
let mut inventory = AnnotationInventory::default();
for index in 0..snapshot.page_count() {
let Ok(page_ref) = snapshot.page(PageIndex(index)) else {
continue;
};
let Some(page_id) = page_ref.object else {
continue;
};
let Some(page_obj) = resolve(snapshot, page_id, ctx) else {
continue;
};
let Some(page_dict) = page_obj.as_dict() else {
continue;
};
let Some(annots) = dict_get_resolved(snapshot, page_dict, annots_key, ctx) else {
continue;
};
let PdfObject::Array(entries) = annots.as_ref() else {
continue;
};
for entry in entries.iter() {
let object = entry.as_reference();
let Some(annot) = resolve_value(snapshot, entry, ctx) else {
continue;
};
let Some(annot) = annot.as_dict() else {
continue;
};
let subtype = annot
.get(names.known.subtype)
.and_then(PdfObject::as_name)
.map(|n| String::from_utf8_lossy(&names.resolve(n)).into_owned());
*inventory
.count_per_subtype
.entry(subtype.clone().unwrap_or_else(|| "(none)".to_owned()))
.or_insert(0) += 1;
inventory.annotations.push(AnnotationRecord {
page: index,
object,
subtype,
contents: annot_text(snapshot, annot, b"Contents", ctx),
name: annot_text(snapshot, annot, b"NM", ctx),
modified: annot_text(snapshot, annot, b"M", ctx),
creation_date: annot_text(snapshot, annot, b"CreationDate", ctx),
author: annot_text(snapshot, annot, b"T", ctx),
subject: annot_text(snapshot, annot, b"Subj", ctx),
intent: annot_intent(snapshot, annot, ctx),
});
}
}
inventory
}
fn annot_text(
snapshot: &DocumentSnapshot,
dict: &Dictionary,
key: &[u8],
ctx: &mut ParseContext,
) -> Option<String> {
let names = snapshot.names();
let key = names.lookup(key)?;
let value = dict_get_resolved(snapshot, dict, key, ctx)?;
match value.as_ref() {
PdfObject::String(text) => Some(decode_text_string_lossy(text.as_bytes())),
_ => None,
}
}
fn annot_intent(
snapshot: &DocumentSnapshot,
dict: &Dictionary,
ctx: &mut ParseContext,
) -> Option<String> {
let names = snapshot.names();
let key = names.lookup(b"IT")?;
let value = dict_get_resolved(snapshot, dict, key, ctx)?;
match value.as_ref() {
PdfObject::Name(id) => Some(String::from_utf8_lossy(&names.resolve(*id)).into_owned()),
_ => None,
}
}
fn read_features(snapshot: &DocumentSnapshot, ctx: &mut ParseContext) -> FeatureFlags {
let names = snapshot.names();
let mut flags = FeatureFlags {
uses_object_streams: xref_uses_object_streams(&snapshot.structure().xref),
..FeatureFlags::default()
};
let root = snapshot.structure().trailer.root;
let Some(catalog) = resolve(snapshot, root, ctx) else {
return flags;
};
let Some(catalog) = catalog.as_dict() else {
return flags;
};
let has = |snapshot: &DocumentSnapshot,
dict: &Dictionary,
key: &[u8],
ctx: &mut ParseContext|
-> Option<Arc<PdfObject>> {
let k = names.lookup(key)?;
let v = dict_get_resolved(snapshot, dict, k, ctx)?;
if matches!(v.as_ref(), PdfObject::Null) {
None
} else {
Some(v)
}
};
if let Some(acroform) = has(snapshot, catalog, b"AcroForm", ctx) {
flags.has_acroform = true;
if let Some(acroform) = acroform.as_dict() {
flags.has_xfa = has(snapshot, acroform, b"XFA", ctx).is_some();
}
}
flags.has_outlines = has(snapshot, catalog, b"Outlines", ctx).is_some();
flags.has_optional_content = has(snapshot, catalog, b"OCProperties", ctx).is_some();
if let Some(names_dict) = has(snapshot, catalog, b"Names", ctx)
&& let Some(names_dict) = names_dict.as_dict()
{
flags.has_javascript = has(snapshot, names_dict, b"JavaScript", ctx).is_some();
flags.has_embedded_files = has(snapshot, names_dict, b"EmbeddedFiles", ctx).is_some();
}
flags
}
fn xref_uses_object_streams(xref: &crate::structure::XrefMap) -> bool {
(0..xref.size()).any(|n| {
matches!(
xref.locate(ObjectId::new(n, 0)),
ObjectLocation::InObjectStream { .. }
)
})
}
impl DocumentReport {
pub fn summary(&self) -> String {
let mut s = String::new();
match &self.open {
OpenOutcome::Ok => writeln_ok(&mut s, "open: ok"),
OpenOutcome::Recovered { how } => {
writeln_ok(
&mut s,
&format!("open: recovered ({} repair(s))", how.len()),
);
for h in how {
writeln_ok(&mut s, &format!(" - {h}"));
}
}
OpenOutcome::Failed { error } => writeln_ok(&mut s, &format!("open: FAILED: {error}")),
}
match &self.header {
None => writeln_ok(&mut s, "header: not found"),
Some(h) => {
let line = format!("header: %PDF-{}.{}", h.major, h.minor);
let line = if h.header_offset == 0 {
line
} else {
format!("{line} [{} bytes of leading garbage]", h.header_offset)
};
writeln_ok(&mut s, &line);
}
}
writeln_ok(&mut s, &format!("linearized: {}", self.linearized));
writeln_ok(
&mut s,
&format!(
"xref: revisions={} recovery_used={} rebuilt={}",
self.xref.revision_count, self.xref.recovery_used, self.xref.rebuilt
),
);
match &self.encryption {
None => writeln_ok(&mut s, "encryption: none"),
Some(e) => writeln_ok(
&mut s,
&format!(
"encryption: {} (V={} R={}) empty-user-password={}",
e.method, e.version, e.revision, e.user_password_empty
),
),
}
let f = &self.features;
writeln_ok(
&mut s,
&format!(
"features: acroform={} xfa={} javascript={} outlines={} \
optional-content={} object-streams={} embedded-files={}",
f.has_acroform,
f.has_xfa,
f.has_javascript,
f.has_outlines,
f.has_optional_content,
f.uses_object_streams,
f.has_embedded_files
),
);
let id = &self.identity;
if let (Some(permanent), Some(changing)) = (&id.id_permanent, &id.id_changing) {
writeln_ok(
&mut s,
&format!("id: permanent={permanent} changing={changing}"),
);
}
if id.has_xmp_metadata {
writeln_ok(&mut s, "metadata: /Info + XMP");
}
for (key, value) in &id.info {
writeln_ok(&mut s, &format!(" /{key}: {value}"));
}
if let Some(xmp) = &id.xmp {
writeln_ok(&mut s, "xmp lineage:");
for (label, value) in [
("DocumentID", &xmp.document_id),
("InstanceID", &xmp.instance_id),
("OriginalDocumentID", &xmp.original_document_id),
("DerivedFrom.documentID", &xmp.derived_from_document_id),
("DerivedFrom.instanceID", &xmp.derived_from_instance_id),
] {
if let Some(value) = value {
writeln_ok(&mut s, &format!(" {label}: {value}"));
}
}
for event in &xmp.history {
let action = event.action.as_deref().unwrap_or("(no action)");
let when = event.when.as_deref().unwrap_or("(no time)");
let agent = event.software_agent.as_deref().unwrap_or("(no agent)");
writeln_ok(&mut s, &format!(" history: {action} {when} by {agent}"));
}
}
writeln_ok(&mut s, &format!("pages: {}", self.pages.len()));
for p in &self.pages {
let line = match &p.compile {
CompileStatus::Ok { op_count } => {
format!(" page {}: ok ({op_count} ops)", p.index)
}
CompileStatus::Degraded { op_count, detail } => {
format!(" page {}: degraded ({op_count} ops): {detail}", p.index)
}
CompileStatus::Failed { error } => {
format!(" page {}: FAILED: {error}", p.index)
}
};
let line = if p.media_box_present {
line
} else {
format!("{line} [no /MediaBox — defaulted]")
};
let line = match &p.metrics {
Some(m) => format!(
"{line} text={} vis={} images={} fonts={} coverage={}/10000",
m.text_runs, m.visible_text_runs, m.images, m.fonts, m.image_coverage_bps
),
None => line,
};
writeln_ok(&mut s, &line);
}
writeln_ok(
&mut s,
&format!(
"inventories: {} font(s), {} image(s)",
self.fonts.len(),
self.images.len()
),
);
if self.annotations.count_per_subtype.is_empty() {
writeln_ok(&mut s, "annotations: none");
} else {
writeln_ok(
&mut s,
&format!("annotations: {} total", self.annotations.total()),
);
for (subtype, count) in &self.annotations.count_per_subtype {
writeln_ok(&mut s, &format!(" {subtype}: {count}"));
}
}
let sigs = &self.signatures;
if sigs.signatures.is_empty() && sigs.unsigned_fields == 0 {
writeln_ok(&mut s, "signatures: none");
} else {
writeln_ok(
&mut s,
&format!(
"signatures: {} signed, {} unsigned field(s)",
sigs.signatures.len(),
sigs.unsigned_fields
),
);
for sig in &sigs.signatures {
let name = sig.field_name.as_deref().unwrap_or("(unnamed)");
let sub_filter = sig.sub_filter.as_deref().unwrap_or("(no /SubFilter)");
writeln_ok(&mut s, &format!(" {name}: {sub_filter}"));
let coverage = if sig.covers_whole_file {
"covers whole file".to_owned()
} else {
format!("DOES NOT cover whole file; /ByteRange {:?}", sig.byte_range)
};
writeln_ok(&mut s, &format!(" {coverage}"));
}
}
s
}
}
fn writeln_ok(s: &mut String, line: &str) {
let _ = writeln!(s, "{line}");
}