mod encrypt;
pub use encrypt::strip_crypt_filter;
mod load;
mod location;
mod objstm;
mod options;
mod pages;
mod repair;
mod revisions;
pub use revisions::{Revision, revision_starts};
mod warning;
mod window;
mod xref;
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::fmt;
use std::ops;
use std::sync::Arc;
pub use encrypt::{Encryption, Encryptor};
use encrypt::{Password, Security};
use load::ObjStmMembers;
pub use load::Resolved;
pub use location::ObjectLocation;
pub use options::OpenOptions;
pub use pages::{DirectPath, Inherited, Page, PathSegment};
pub use warning::Warning;
use warning::WarningLog;
pub use xref::XREF_STREAM_KEYS;
use xref::{XrefEntry, XrefTable};
use laminapdf_syntax::crypt::{PasswordKind, Permissions};
use laminapdf_syntax::{DecodeBudget, Dict, Limits, ObjRef, Object, Parser, find};
use crate::error::{Error, Result, tolerant};
use crate::overlay::{InOverlay, Overlay, OverlayEntry};
use crate::source::{ByteSource, Fetch, Pending, Source, WINDOW};
use window::{Reach, parse_at, within_read_window};
const HEADER_SEARCH: usize = 1024;
const _: () = assert!(WINDOW >= HEADER_SEARCH + b"%PDF-".len() + 8);
const TAIL: usize = 1024;
const HEADER_PROBE: usize = 32;
const PROBE_GAP: usize = 256;
#[expect(
clippy::struct_excessive_bools,
reason = "independent facts about the opened file, not states of one machine"
)]
pub struct Document {
source: Source,
entries: BTreeMap<u32, XrefEntry>,
max_object_number: Option<u32>,
free_head: u32,
trailer: Dict,
revisions: usize,
section_offsets: Vec<usize>,
section_objects: Vec<xref::SectionObjects>,
repaired: bool,
has_xref_stream: bool,
newest_is_stream: bool,
startxref: Option<usize>,
header_version: Option<String>,
limits: Limits,
strict: bool,
warnings: RefCell<WarningLog>,
call_depth: Cell<usize>,
budget: Cell<DecodeBudget>,
objstm_cache: RefCell<BTreeMap<u32, ObjStmMembers>>,
object_cache: RefCell<BTreeMap<u32, Arc<Object>>>,
security: Option<Security>,
overlay: Overlay,
open_password: Option<zeroize::Zeroizing<Vec<u8>>>,
}
const _: () = {
const fn assert_send<T: Send>() {}
assert_send::<Document>();
assert_send::<Page>();
assert_send::<Error>();
};
impl fmt::Debug for Document {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Document")
.field("source", &self.source)
.field("objects", &self.entries.len())
.field("revisions", &self.revisions)
.field("repaired", &self.repaired)
.field("header_version", &self.header_version)
.field("strict", &self.strict)
.field("encryption", &self.encryption())
.finish_non_exhaustive()
}
}
struct Call<'d> {
doc: &'d Document,
}
impl Drop for Call<'_> {
fn drop(&mut self) {
self.doc.call_depth.set(self.doc.call_depth.get().saturating_sub(1));
}
}
fn read_header_version(data: &[u8], header_pos: usize) -> Option<String> {
let start = header_pos + b"%PDF-".len();
let rest = data.get(start..)?;
let len = rest
.iter()
.take(8)
.take_while(|b| b.is_ascii_digit() || **b == b'.')
.count();
let v = std::str::from_utf8(rest.get(..len)?).ok()?;
(!v.is_empty()).then(|| v.to_owned())
}
fn entries_are_valid(source: &Source, table: &XrefTable, limits: &Limits) -> Result<bool> {
let matches = |data: &[u8], pos: usize, num: u32, gen_nr: u16| {
let mut parser = Parser::new(data, pos).with_limits(limits);
let ok = parser
.object_header()
.is_ok_and(|id| id.num == num && id.gen_nr == gen_nr);
(ok, parser.reached_end())
};
let mut probes: Vec<(usize, u32, u16)> = table
.entries
.iter()
.filter_map(|(&num, entry)| match *entry {
XrefEntry::InFile { offset, gen_nr } => Some((offset, num, gen_nr)),
XrefEntry::Free | XrefEntry::InStream { .. } => None,
})
.collect();
if let Some(data) = source.in_memory() {
return Ok(probes
.into_iter()
.all(|(offset, num, gen_nr)| matches(data, offset, num, gen_nr).0));
}
probes.sort_unstable();
let total = source.len()?;
let mut spans: Vec<ops::Range<usize>> = Vec::new();
for &(offset, ..) in &probes {
let probe = offset.min(total)..offset.saturating_add(HEADER_PROBE).min(total);
match spans.last_mut() {
Some(span) if probe.start <= span.end.saturating_add(PROBE_GAP) => span.end = span.end.max(probe.end),
_ => spans.push(probe),
}
}
let mut pending = Pending::default();
let mut windows = Vec::new();
for span in spans {
match source.read(span.start, span.len(), Fetch::Exact) {
Ok(window) => windows.push(window),
Err(e) => {
pending.absorb(e)?;
if pending.is_full() {
break;
}
}
}
}
let mut next = 0;
for (offset, num, gen_nr) in probes {
while windows
.get(next)
.is_some_and(|w| w.end() <= offset.min(total) && w.start() < w.end())
{
next += 1;
}
let Some(window) = windows.get(next).filter(|w| w.start() <= offset.min(total)) else {
continue;
};
let (mut ok, reached_end) = matches(window.bytes(), offset - window.start(), num, gen_nr);
if reached_end && !window.at_end() {
let probe = parse_at(source, offset, Reach::Probe(2 * HEADER_PROBE), limits, |v| {
matches(v.data, v.pos, num, gen_nr)
});
match within_read_window(probe) {
Ok(again) => ok = again.unwrap_or(false),
Err(e) => {
pending.absorb(e)?;
continue;
}
}
}
if !ok {
return Ok(false);
}
}
pending.finish()?;
Ok(true)
}
struct Base {
source: Source,
header_version: Option<String>,
limits: Limits,
strict: bool,
}
impl Document {
pub fn open(source: impl Into<Source>, options: OpenOptions) -> Result<Self> {
Self::open_with(source.into(), options, None)
}
#[expect(
clippy::needless_pass_by_value,
reason = "ADR 0005's signature: the options are moved in (they may carry a password)"
)]
pub(crate) fn open_with(source: Source, options: OpenOptions, known: Option<&Security>) -> Result<Self> {
let len = source.len()?;
if len == 0 {
return Err(Error::NotPdf("empty input"));
}
source.prefetch(&[(0, WINDOW), (len.saturating_sub(TAIL), TAIL)])?;
let limits = *options.limits();
let strict = options.strict();
let mut log = WarningLog::default();
let header_version = parse_at(&source, 0, Reach::Object, &limits, |v| {
let data = v.data;
let head = data.get(..data.len().min(HEADER_SEARCH)).unwrap_or_default();
let version = find(head, b"%PDF-", 0).and_then(|pos| read_header_version(data, pos));
(version, false)
})?;
if header_version.is_none() {
log.raise(Warning::MissingHeader, &limits, strict)?;
}
let base = || Base {
source: source.clone(),
header_version: header_version.clone(),
limits,
strict,
};
let mut budget = DecodeBudget::new(&limits);
let startxref = tolerant(xref::find_startxref(&source, &limits))?;
let loaded = match startxref {
Some(start) => tolerant(xref::load(&source, start, &limits, &mut budget))?,
None => None,
};
let loaded = match loaded {
Some(table) if table.trailer.contains_key("Root") && entries_are_valid(&source, &table, &limits)? => {
Some(table)
}
_ => None,
};
if let Some(table) = loaded {
let mut doc = Self::new(base(), table, startxref, log.clone())?;
let unlocked = match doc.read_security(Password::Any(options.password()), known) {
Ok(security) => security.map_or(Ok(()), |s| doc.install_security(s)),
Err(e) => Err(e),
};
let checked = unlocked.and_then(|()| {
let _call = doc.call();
doc.budget.set(budget);
let checked = doc.catalog();
budget = doc.budget.get();
checked
});
let damaged = || {
doc.warnings()
.iter()
.any(|w| matches!(w, Warning::DictionaryKeySkipped { object: Some(_) }))
};
match checked {
Ok(_) if !damaged() => {
doc.open_password = options.password().map(|p| zeroize::Zeroizing::new(p.to_vec()));
return Ok(doc);
}
Err(e) if e.must_propagate() || e.is_security_refusal() => return Err(e),
Ok(_) | Err(_) => {}
}
}
log.raise(Warning::XrefRepaired, &limits, strict)?;
let scan = repair::scan(&source, &limits)?;
let security = {
let in_file = Self::new(base(), scan.in_file_table(), None, WarningLog::default())?;
let security = in_file.read_security(Password::Any(options.password()), known)?;
for warning in in_file.warnings() {
log.raise(warning, &limits, strict)?;
}
security
};
let (table, malformed) = scan.finish(&source, &limits, &mut budget, security.as_ref())?;
let mut doc = Self::new(base(), table, None, log)?;
if let Some(security) = security {
doc.install_security(security)?;
}
for object in malformed {
doc.warn(Warning::AesPaddingInvalid { object })?;
}
doc.repaired = true;
doc.open_password = options.password().map(|p| zeroize::Zeroizing::new(p.to_vec()));
Ok(doc)
}
#[must_use]
pub fn reopen_options(&self) -> OpenOptions {
let options = OpenOptions::new().with_limits(self.limits).with_strict(self.strict);
match &self.open_password {
Some(password) => options.with_password(password.to_vec()),
None => options,
}
}
#[must_use]
pub fn empty(version: Option<&str>, options: &OpenOptions) -> Self {
let base = Base {
source: Source::from(Vec::new()),
header_version: version.map(str::to_owned),
limits: *options.limits(),
strict: options.strict(),
};
Self::from_parts(base, XrefTable::default(), None, WarningLog::default(), 0, None)
}
fn new(base: Base, mut table: XrefTable, startxref: Option<usize>, mut log: WarningLog) -> Result<Self> {
let (limits, strict) = (base.limits, base.strict);
for offset in std::mem::take(&mut table.ignored_xref_streams) {
log.raise(Warning::XrefStmIgnored { offset }, &limits, strict)?;
}
let dropped = std::mem::take(&mut table.dropped_objects);
let max_object_number = table.entries.keys().chain(&dropped).max().copied();
for object in dropped {
log.raise(Warning::ObjectNumberOutOfRange { object }, &limits, strict)?;
}
let skipped = std::mem::take(&mut table.skipped);
if skipped.trailer_keys {
log.raise(Warning::DictionaryKeySkipped { object: None }, &limits, strict)?;
}
if skipped.xref_characters {
log.raise(Warning::FilterCharactersSkipped { object: None }, &limits, strict)?;
}
let free_head = table.free_head.unwrap_or(0);
Ok(Self::from_parts(
base,
table,
startxref,
log,
free_head,
max_object_number,
))
}
fn from_parts(
base: Base,
table: XrefTable,
startxref: Option<usize>,
log: WarningLog,
free_head: u32,
max_object_number: Option<u32>,
) -> Self {
let Base {
source,
header_version,
limits,
strict,
} = base;
Self {
source,
entries: table.entries,
max_object_number,
free_head,
trailer: table.trailer,
revisions: table.sections,
section_offsets: table.section_offsets,
section_objects: table.section_objects,
repaired: false,
has_xref_stream: table.has_xref_stream,
newest_is_stream: table.newest_is_stream,
startxref,
header_version,
limits,
strict,
warnings: RefCell::new(log),
call_depth: Cell::new(0),
budget: Cell::new(DecodeBudget::new(&limits)),
objstm_cache: RefCell::new(BTreeMap::new()),
object_cache: RefCell::new(BTreeMap::new()),
overlay: Overlay::default(),
open_password: None,
security: None,
}
}
fn read_security(&self, password: Password<'_>, known: Option<&Security>) -> Result<Option<Security>> {
let Some(encrypt) = self.trailer.get("Encrypt") else {
return Ok(None);
};
let _call = self.call();
let dict = match self.resolve_nested(encrypt, 4)? {
Object::Dict(dict) => dict,
Object::Null => return Ok(None),
_ => return Err(encrypt::invalid("/Encrypt is not a dictionary")),
};
let id = match self.trailer.get("ID") {
Some(id) => self.resolve_nested(id, 2)?,
None => Object::Null,
};
let id0 = match id.as_array().and_then(<[Object]>::first) {
Some(Object::String(s)) => s.bytes.as_slice(),
_ => &[],
};
Security::unlock(&dict, encrypt.as_ref().map(|r| r.num), id0, password, known).map(Some)
}
fn install_security(&mut self, security: Security) -> Result<()> {
let perms_valid = security.perms_valid();
self.security = Some(security);
self.object_cache.get_mut().clear();
self.objstm_cache.get_mut().clear();
if perms_valid {
Ok(())
} else {
self.warn(Warning::PermsMismatch)
}
}
fn call(&self) -> Call<'_> {
let depth = self.call_depth.get();
if depth == 0 {
self.budget.set(DecodeBudget::new(&self.limits));
}
self.call_depth.set(depth + 1);
Call { doc: self }
}
fn warn(&self, warning: Warning) -> Result<()> {
self.warnings.borrow_mut().raise(warning, &self.limits, self.strict)
}
pub fn report(&self, warning: Warning) -> Result<()> {
self.warn(warning)
}
#[must_use]
pub fn trailer(&self) -> &Dict {
self.overlay.trailer().unwrap_or(&self.trailer)
}
#[must_use]
pub const fn base_trailer(&self) -> &Dict {
&self.trailer
}
#[must_use]
pub const fn revisions(&self) -> usize {
self.revisions
}
#[must_use]
pub fn xref_section_offsets(&self) -> &[usize] {
&self.section_offsets
}
#[must_use]
pub const fn is_encrypted(&self) -> bool {
self.security.is_some()
}
#[must_use]
pub fn encryption(&self) -> Option<&Encryption> {
self.security.as_ref().map(Security::info)
}
#[must_use]
pub fn encryptor(&self) -> Option<Encryptor> {
self.security.as_ref().map(Encryptor::keep)
}
#[must_use]
pub fn permissions(&self) -> Option<Permissions> {
self.security.as_ref().map(Security::permissions)
}
#[must_use]
pub fn matched_password(&self) -> Option<PasswordKind> {
self.security.as_ref().map(Security::matched)
}
#[must_use]
pub fn may_change_security(&self) -> bool {
self.security.as_ref().is_none_or(Security::may_change)
}
#[must_use]
pub fn may_copy_out(&self) -> bool {
self.security.as_ref().is_none_or(Security::may_copy_out)
}
pub fn authenticate_owner(&mut self, password: &[u8]) -> Result<()> {
let Some(security) = self.security.as_mut() else {
return Ok(());
};
let other = security.unlock_owner(password)?;
security.confirm_owner(&other)
}
#[must_use]
pub const fn was_repaired(&self) -> bool {
self.repaired
}
#[must_use]
pub const fn has_xref_stream(&self) -> bool {
self.has_xref_stream
}
#[must_use]
pub fn warnings(&self) -> Vec<Warning> {
self.warnings.borrow().list().to_vec()
}
#[must_use]
pub const fn limits(&self) -> &Limits {
&self.limits
}
#[must_use]
pub const fn is_strict(&self) -> bool {
self.strict
}
#[must_use]
pub fn header_version(&self) -> Option<&str> {
self.header_version.as_deref()
}
#[must_use]
pub const fn startxref(&self) -> Option<usize> {
self.startxref
}
#[must_use]
pub fn data(&self) -> Option<&[u8]> {
self.source.in_memory()
}
pub fn whole_input(&self) -> Result<Cow<'_, [u8]>> {
self.source.whole()
}
#[must_use]
pub fn source(&self) -> &Arc<dyn ByteSource> {
self.source.get()
}
#[must_use]
pub const fn newest_section_is_stream(&self) -> bool {
self.newest_is_stream
}
pub const fn max_object_number(&self) -> Option<u32> {
self.max_object_number
}
pub fn object_numbers(&self) -> impl Iterator<Item = u32> + '_ {
let base = self
.entries
.iter()
.filter(|(n, e)| {
!matches!(e, XrefEntry::Free) && !matches!(self.overlay.get(**n), Some(OverlayEntry::Deleted))
})
.map(|(&n, _)| n);
let new = self
.overlay
.iter()
.filter(|(_, e)| matches!(e, OverlayEntry::New(_)))
.map(|(n, _)| n);
base.chain(new)
}
pub fn catalog(&self) -> Result<Dict> {
let _call = self.call();
let root = self.trailer().get("Root").ok_or(Error::MissingRoot)?;
match &*self.deref(root)? {
Object::Dict(d) => Ok(d.clone()),
_ => Err(Error::Type {
expected: "dictionary",
context: "/Root",
}),
}
}
}
impl Document {
pub(crate) const fn overlay_ref(&self) -> &Overlay {
&self.overlay
}
pub(crate) const fn overlay_mut(&mut self) -> &mut Overlay {
&mut self.overlay
}
fn load_current(&self, num: u32, gen_nr: Option<u16>) -> Result<Arc<Object>> {
match self.overlay_value(num, gen_nr) {
InOverlay::Value(o) => Ok(Arc::clone(o)),
InOverlay::Absent => {
if let Some(generation) = gen_nr
&& !self.overlay_generation_matches(num, generation)
{
self.warn(Warning::StaleGeneration {
object: num,
generation,
})?;
}
Ok(Arc::new(Object::Null))
}
InOverlay::NoEntry => self.load(num, gen_nr, &mut Vec::new()),
}
}
#[must_use]
pub fn base_generation(&self, num: u32) -> Option<u16> {
self.entries
.get(&num)
.filter(|e| !matches!(e, XrefEntry::Free))
.map(|e| e.gen_nr())
}
#[must_use]
pub const fn free_list_head(&self) -> u32 {
self.free_head
}
pub(crate) fn carry_warnings(&self, older: &Self) {
let mut merged = WarningLog::default();
let old = older.warnings.borrow();
let own = self.warnings.borrow();
for warning in old.list().iter().chain(own.list()) {
let _accepted = merged.raise(*warning, &self.limits, false);
}
drop((old, own));
*self.warnings.borrow_mut() = merged;
}
pub(crate) fn base_has(&self, r: ObjRef) -> bool {
self.entries
.get(&r.num)
.is_some_and(|e| !matches!(e, XrefEntry::Free) && e.matches_gen(r.gen_nr))
}
pub(crate) fn base_value(&self, num: u32) -> Result<Arc<Object>> {
let _call = self.call();
match self.load(num, None, &mut Vec::new()) {
Ok(base) => Ok(base),
Err(e) if e.must_propagate() => Err(e),
Err(_) => Ok(Arc::new(Object::Null)),
}
}
}