use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::path::Path;
use crate::linearization::{self, Linearization};
use crate::object::{Dict, IndirectObject, ObjId, Object, Provenance};
use crate::objstm::{ObjStmError, ObjectStream};
use crate::parser::{ParseError, Parser, StreamLengthPolicy, TerminatorPolicy};
use crate::recover::{self, RecoveryReport};
use crate::view::DocumentView;
use crate::xref::{self, SectionShape, XrefEntry, XrefError, XrefErrorKind, XrefTable};
mod encryption_refusal;
use crate::{PdfError, PdfVersion};
pub use encryption_refusal::EncryptedRefusal;
pub const MAX_RESOLVE_DEPTH: usize = 32;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DocError {
#[error("I/O error reading PDF: {0}")]
Io(#[from] std::io::Error),
#[error("{0}")]
Encryption(#[from] crate::crypto::EncryptionUnsupported),
#[error("this document is password-protected; supply the user or owner password")]
PasswordRequired,
#[error(
"this document is password-protected; the password supplied contains non-ASCII characters, \
and pdfcer does not apply the RFC 4013 (SASLprep) normalisation that /R 5 specifies before \
hashing — so a correct password can be rejected here"
)]
PasswordRequiresNormalisation,
#[error(
"this document is password-protected (AES-256 /R 6); authentication failed. If the password is correct, the cause may be ambiguity A13 in ISO 32000-2 Algorithm 2.B's loop-exit test -- pdfcer uses the reading pypdf and Acrobat write, and a file written under the other reading would not open"
)]
PasswordRequiredR6,
#[error(transparent)]
Header(PdfError),
#[error(transparent)]
Xref(#[from] XrefError),
#[error("object {id} (xref offset {offset}): {source}")]
BadObject {
id: ObjId,
offset: u64,
source: ParseError,
},
#[error("object at xref offset {offset} declares {found}, xref expected {expected}")]
ObjectIdMismatch {
expected: ObjId,
found: ObjId,
offset: u64,
},
#[error("object {num} is compressed in object stream {container}, which is not present")]
ObjectStreamMissing {
container: ObjId,
num: u32,
},
#[error("object stream {container}: {source}")]
ObjectStream {
container: ObjId,
source: ObjStmError,
},
#[error(
"object stream {container} index {index} holds object {found}, xref expected object {expected}"
)]
ObjectStreamIdMismatch {
container: ObjId,
index: u32,
expected: u32,
found: u32,
},
#[error("trailer /Root missing or not a reference to a dictionary")]
NoCatalog,
#[error("cross-reference recovery failed: {0}")]
Recovery(#[from] crate::recover::RecoverError),
}
#[derive(Debug, Clone)]
pub struct Document {
buf: Vec<u8>,
header_version: PdfVersion,
xref: XrefTable,
trailer: Dict,
objects: HashMap<ObjId, IndirectObject>,
base_startxref: u64,
section_shape: SectionShape,
linearization: Linearization,
highest_object_number: u32,
suppressed_by_size: usize,
hybrid: crate::xref::HybridPartition,
anomalies: Vec<LoadAnomaly>,
recovery: Option<RecoveryReport>,
encryption: Option<DocumentEncryption>,
}
#[derive(Clone, Copy)]
enum Credential<'a> {
Password(Option<&'a [u8]>),
Reuse(&'a DocumentEncryption),
}
#[derive(Debug, Clone)]
pub struct DocumentEncryption {
pub config: crate::crypto::EncryptionConfig,
pub auth: crate::crypto::AuthKind,
pub perms: crate::crypto::PermsCheck,
key: crate::crypto::FileKey,
encrypt_dict_id: Option<u32>,
ciphertext: std::sync::Arc<[u8]>,
rc4_append: crate::writer::Rc4Append,
}
impl DocumentEncryption {
pub(crate) fn file_key(&self) -> &crate::crypto::FileKey {
&self.key
}
pub(crate) fn encrypt_dict_id(&self) -> Option<u32> {
self.encrypt_dict_id
}
pub(crate) fn ciphertext(&self) -> &[u8] {
&self.ciphertext
}
#[must_use]
pub fn appendable(&self) -> bool {
!self.uses_rc4() || self.rc4_append == crate::writer::Rc4Append::Preserve
}
#[must_use]
pub fn uses_rc4(&self) -> bool {
use crate::crypto::Cipher;
[self.key.string_cipher(), self.key.stream_cipher()].contains(&Cipher::Rc4)
}
#[must_use]
pub fn rc4_append(&self) -> crate::writer::Rc4Append {
self.rc4_append
}
#[must_use]
pub fn grants(&self, bit: crate::crypto::PermissionBit) -> bool {
self.auth == crate::crypto::AuthKind::Owner
|| self.config.permissions().granted(bit) == Some(true)
}
}
impl Document {
pub fn load(path: &Path) -> Result<Self, DocError> {
Self::from_bytes(std::fs::read(path)?)
}
pub fn load_with_password(path: &Path, password: Option<&[u8]>) -> Result<Self, DocError> {
Self::from_bytes_with_password(std::fs::read(path)?, password)
}
pub fn load_with_options(
path: &Path,
password: Option<&[u8]>,
options: LoadOptions,
) -> Result<Self, DocError> {
Self::from_bytes_with_options(std::fs::read(path)?, password, options)
}
pub fn from_bytes(buf: Vec<u8>) -> Result<Self, DocError> {
Self::from_bytes_with_password(buf, None)
}
#[doc(hidden)] pub fn from_cos_bytes(buf: Vec<u8>, markers: &[&[u8]]) -> Result<Self, DocError> {
let header_version = crate::probe_cos_header(&buf, markers).map_err(DocError::Header)?;
let loaded = xref::load_xref_chain(&buf).map_err(DocError::Xref)?;
let hybrid = loaded.hybrid_partition();
Self::assemble(
buf,
header_version,
loaded.table,
loaded.trailer,
loaded.startxref,
loaded.newest_shape,
loaded.highest_object_number,
loaded.suppressed_by_size,
hybrid,
None,
Credential::Password(None),
LoadOptions::default(),
)
}
pub fn from_bytes_with_password(
buf: Vec<u8>,
password: Option<&[u8]>,
) -> Result<Self, DocError> {
Self::from_bytes_with_options(buf, password, LoadOptions::default())
}
pub fn from_bytes_with_options(
buf: Vec<u8>,
password: Option<&[u8]>,
options: LoadOptions,
) -> Result<Self, DocError> {
Self::from_bytes_inner(buf, Credential::Password(password), options)
}
pub fn reopen_appended(&self, buf: Vec<u8>) -> Result<Self, DocError> {
let credential = match &self.encryption {
Some(e) => Credential::Reuse(e),
None => Credential::Password(None),
};
Self::from_bytes_inner(buf, credential, LoadOptions::default())
}
fn from_bytes_inner(
buf: Vec<u8>,
credential: Credential<'_>,
options: LoadOptions,
) -> Result<Self, DocError> {
match crate::probe_header(&buf) {
Ok(header_version) => match xref::load_xref_chain(&buf) {
Ok(loaded) => {
let hybrid = loaded.hybrid_partition();
Self::assemble(
buf,
header_version,
loaded.table,
loaded.trailer,
loaded.startxref,
loaded.newest_shape,
loaded.highest_object_number,
loaded.suppressed_by_size,
hybrid,
None,
credential,
options,
)
}
Err(e) => match recover::recovery_reason_for(&e.kind) {
None => Err(DocError::Xref(e)),
Some(reason) => match recover::recover(&buf, reason) {
Ok(rec) => Self::assemble_recovered(buf, Some(header_version), rec),
Err(recover::RecoverError::Encrypted) => Err(DocError::Xref(XrefError {
offset: 0,
kind: XrefErrorKind::EncryptionUnsupported,
})),
Err(other) => Err(DocError::Recovery(other)),
},
},
},
Err(header_err) => match recover::recover(&buf, recover::RecoveryReason::MissingHeader)
{
Ok(rec) => Self::assemble_recovered(buf, None, rec),
Err(_) => Err(DocError::Header(header_err)),
},
}
}
#[allow(clippy::too_many_arguments)] fn assemble(
mut buf: Vec<u8>,
header_version: PdfVersion,
table: XrefTable,
trailer: Dict,
base_startxref: u64,
section_shape: SectionShape,
highest_object_number: u32,
suppressed_by_size: usize,
hybrid: crate::xref::HybridPartition,
recovery: Option<RecoveryReport>,
credential: Credential<'_>,
options: LoadOptions,
) -> Result<Self, DocError> {
let length_policy = if recovery.is_some() {
StreamLengthPolicy::RecoverFromEndstream
} else {
options.stream_lengths
};
let terminator_policy = if recovery.is_some() {
TerminatorPolicy::RecoverAtNextHeader
} else {
options.terminators
};
let mut anomalies: Vec<LoadAnomaly> = Vec::new();
let mut objects: HashMap<ObjId, IndirectObject> = HashMap::new();
let mut compressed: Vec<(u32, u32, u32)> = Vec::new();
for (num, entry) in table.iter() {
match entry {
XrefEntry::InUse { offset, generation } => {
let id = ObjId::new(num, generation);
let parsed = parse_object_at(
&buf,
&table,
offset,
length_policy,
terminator_policy,
options.duplicate_keys,
);
let (io, repairs) = match parsed {
Ok(pair) => pair,
Err(source) => {
if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
return Err(DocError::BadObject { id, offset, source });
}
anomalies.push(LoadAnomaly::ObjectUnreadable {
object: id,
reason: source.to_string(),
});
continue;
}
};
if repairs.stream_lengths > 0 {
anomalies.push(LoadAnomaly::StreamLengthRecovered { object: id });
}
if repairs.missing_endobj > 0 {
anomalies.push(LoadAnomaly::MissingEndobjRecovered { object: id });
}
anomalies.extend(repairs.duplicate_keys.into_iter().map(|rec| {
LoadAnomaly::DuplicateDictKey {
object: Some(id),
key: rec.key,
kept: rec.kept,
discarded: rec.discarded,
}
}));
if io.id != id {
if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
return Err(DocError::ObjectIdMismatch {
expected: id,
found: io.id,
offset,
});
}
anomalies.push(LoadAnomaly::ObjectUnreadable {
object: id,
reason: format!(
"the cross-reference table points at offset {offset}, where the file declares {} instead",
io.id
),
});
continue;
}
objects.insert(id, io);
}
XrefEntry::InStream { stream_num, index } => {
compressed.push((num, stream_num, index));
}
_ => {}
}
}
let encryption = Self::decrypt_in_place(&mut buf, &trailer, &mut objects, credential)?;
compressed.sort_unstable();
Self::load_compressed(
&buf,
&compressed,
&mut objects,
options.unreadable_objects,
&mut anomalies,
)?;
let linearization = linearization::detect(&buf);
Ok(Self {
buf,
header_version,
xref: table,
trailer,
objects,
base_startxref,
section_shape,
linearization,
highest_object_number,
suppressed_by_size,
hybrid,
anomalies,
recovery,
encryption,
})
}
fn decrypt_in_place(
buf: &mut [u8],
trailer: &Dict,
objects: &mut HashMap<ObjId, IndirectObject>,
credential: Credential<'_>,
) -> Result<Option<DocumentEncryption>, DocError> {
use crate::crypto::{EncryptionConfig, EncryptionUnsupported, apply};
let Some(entry) = trailer.get(b"Encrypt") else {
return Ok(None);
};
let (encrypt_dict, encrypt_dict_id) = match entry {
Object::Dict(d) => (d.clone(), None),
Object::Reference(id) => match objects.get(id).map(|o| &o.value) {
Some(Object::Dict(d)) => (d.clone(), Some(id.num)),
_ => {
return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
"/Encrypt names an object that is not a dictionary",
)));
}
},
_ => {
return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
"/Encrypt is neither a dictionary nor a reference",
)));
}
};
let snapshot: HashMap<ObjId, Object> = objects
.iter()
.map(|(id, io)| (*id, io.value.clone()))
.collect();
let resolve = move |id: ObjId| snapshot.get(&id).cloned();
let config = EncryptionConfig::parse(&encrypt_dict, &resolve)?;
let id0: Vec<u8> = match trailer.get(b"ID") {
Some(Object::Array(items)) => match items.first() {
Some(Object::String(s)) => s.clone(),
_ => Vec::new(),
},
_ => Vec::new(),
};
let authenticated = match credential {
Credential::Password(password) => config.authenticate(password, &id0),
Credential::Reuse(e) => Some((e.key.clone(), e.auth)),
};
let Some((key, auth)) = authenticated else {
return Err(match credential {
Credential::Password(Some(pw)) if config.password_may_need_normalisation(pw) => {
DocError::PasswordRequiresNormalisation
}
_ if config.revision == 6 => DocError::PasswordRequiredR6,
_ => DocError::PasswordRequired,
});
};
let perms = config.check_perms(&key);
let ciphertext: std::sync::Arc<[u8]> = std::sync::Arc::from(&*buf);
for (id, obj) in objects.iter_mut() {
if apply::skip(obj, encrypt_dict_id, config.encrypt_metadata).is_some() {
continue;
}
if key.streams_encrypted()
&& let Object::Stream(stream) = &mut obj.value
{
let span = stream.data_span;
let end = span.start.saturating_add(span.len);
if let Some(cipher_text) = buf.get(span.start..end) {
let plain = key.decrypt_stream(*id, cipher_text);
if plain.len() <= span.len
&& let Some(slot) = buf.get_mut(span.start..span.start + plain.len())
{
slot.copy_from_slice(&plain);
stream.data_span.len = plain.len();
}
}
}
if key.strings_encrypted() {
apply::decrypt_strings(&mut obj.value, *id, &key);
}
}
Ok(Some(DocumentEncryption {
config,
auth,
perms,
key,
encrypt_dict_id,
ciphertext,
rc4_append: crate::writer::Rc4Append::Refuse,
}))
}
#[must_use]
pub fn encryption(&self) -> Option<&DocumentEncryption> {
self.encryption.as_ref()
}
pub fn set_rc4_append(&mut self, policy: crate::writer::Rc4Append) {
if let Some(enc) = self.encryption.as_mut() {
enc.rc4_append = policy;
}
}
#[doc(hidden)] pub fn clear_encryption(&mut self) {
self.encryption = None;
self.trailer.remove(b"Encrypt");
}
fn assemble_recovered(
buf: Vec<u8>,
header_override: Option<PdfVersion>,
rec: recover::RecoveredXref,
) -> Result<Self, DocError> {
let version = header_override.unwrap_or(rec.version);
Self::assemble(
buf,
version,
rec.table,
rec.trailer,
0,
SectionShape::Classic { xref_stm: None },
rec.highest_object_number,
0,
crate::xref::HybridPartition::default(),
Some(rec.report),
Credential::Password(None),
LoadOptions::default(),
)
}
fn load_compressed(
buf: &[u8],
compressed: &[(u32, u32, u32)],
objects: &mut HashMap<ObjId, IndirectObject>,
policy: UnreadableObjectPolicy,
anomalies: &mut Vec<LoadAnomaly>,
) -> Result<(), DocError> {
let mut cache: HashMap<u32, ObjectStream> = HashMap::new();
macro_rules! give_up_on {
($num:expr, $reason:expr, $err:expr) => {{
if policy == UnreadableObjectPolicy::Refuse {
return Err($err);
}
anomalies.push(LoadAnomaly::ObjectUnreadable {
object: ObjId::new($num, 0),
reason: $reason,
});
continue;
}};
}
for &(num, stream_num, index) in compressed {
let container = ObjId::new(stream_num, 0);
let objstm = match cache.entry(stream_num) {
Entry::Occupied(slot) => slot.into_mut(),
Entry::Vacant(slot) => {
let Some(io) = objects.get(&container) else {
give_up_on!(
num,
format!("its object stream {container} is not in the file"),
DocError::ObjectStreamMissing { container, num }
)
};
let Object::Stream(stream) = &io.value else {
give_up_on!(
num,
format!(
"object {container} is named as its container but is not a stream"
),
DocError::ObjectStream {
container,
source: ObjStmError::NotAStream,
}
)
};
let Some(raw) = stream.data_span.slice(buf) else {
give_up_on!(
num,
format!("its object stream {container} declares data outside the file"),
DocError::ObjectStream {
container,
source: ObjStmError::DataOutOfRange,
}
)
};
match ObjectStream::parse(&stream.dict, raw) {
Ok(parsed) => slot.insert(parsed),
Err(source) => give_up_on!(
num,
format!("its object stream {container} could not be decoded: {source}"),
DocError::ObjectStream { container, source }
),
}
}
};
let idx = usize::try_from(index).unwrap_or(usize::MAX);
let (found, value) = match objstm.object_at(idx) {
Ok(pair) => pair,
Err(source) => give_up_on!(
num,
format!(
"index {index} of object stream {container} could not be read: {source}"
),
DocError::ObjectStream { container, source }
),
};
if found != num {
give_up_on!(
num,
format!(
"object stream {container} stores object {found} at index {index}, where the cross-reference table promised {num}"
),
DocError::ObjectStreamIdMismatch {
container,
index,
expected: num,
found,
}
)
}
let id = ObjId::new(num, 0);
objects.insert(
id,
IndirectObject {
id,
value,
provenance: Provenance::ObjectStream { container, index },
},
);
}
Ok(())
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.buf
}
#[must_use]
pub fn view(&self) -> DocumentView<'_> {
DocumentView::new(self, self.bytes(), self.version())
}
#[must_use]
pub const fn trailer(&self) -> &Dict {
&self.trailer
}
#[must_use]
pub const fn xref(&self) -> &XrefTable {
&self.xref
}
#[must_use]
pub fn version(&self) -> PdfVersion {
let catalog_version = self
.catalog()
.ok()
.and_then(|cat| cat.get(b"Version"))
.and_then(Object::as_name)
.and_then(|n| parse_version_name(n.as_bytes()));
match catalog_version {
Some(v) if v > self.header_version => v,
_ => self.header_version,
}
}
#[must_use]
pub fn get(&self, id: ObjId) -> Option<&IndirectObject> {
self.objects.get(&id)
}
#[must_use]
pub fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object {
const NULL: &Object = &Object::Null;
let mut current = obj;
for _ in 0..MAX_RESOLVE_DEPTH {
match current {
Object::Reference(id) => match self.get(*id) {
Some(io) => current = &io.value,
None => return NULL,
},
other => return other,
}
}
NULL
}
pub fn catalog(&self) -> Result<&Dict, DocError> {
self.trailer
.get(b"Root")
.map(|root| self.resolve(root))
.and_then(Object::as_dict)
.ok_or(DocError::NoCatalog)
}
#[must_use]
pub fn object_count(&self) -> usize {
self.objects.len()
}
pub fn objects(&self) -> impl Iterator<Item = &IndirectObject> {
self.objects.values()
}
#[must_use]
pub const fn base_startxref(&self) -> u64 {
self.base_startxref
}
#[must_use]
pub const fn section_shape(&self) -> SectionShape {
self.section_shape
}
#[must_use]
pub const fn is_hybrid(&self) -> bool {
matches!(
self.section_shape,
SectionShape::Classic { xref_stm: Some(_) }
)
}
#[must_use]
pub fn load_anomalies(&self) -> &[LoadAnomaly] {
&self.anomalies
}
#[must_use]
pub const fn hybrid_partition(&self) -> &crate::xref::HybridPartition {
&self.hybrid
}
#[must_use]
pub const fn recovery(&self) -> Option<&RecoveryReport> {
self.recovery.as_ref()
}
#[must_use]
pub const fn loaded_via_recovery(&self) -> bool {
self.recovery.is_some()
}
#[must_use]
pub const fn linearization(&self) -> Linearization {
self.linearization
}
pub fn save_incremental(
&self,
path: &Path,
dirty: &crate::writer::DirtySet,
options: &crate::writer::SaveOptions,
) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
let (bytes, report) = crate::writer::save_incremental(self, dirty, options)?;
std::fs::write(path, &bytes)?;
Ok(report)
}
pub fn save_full(
&self,
path: &Path,
dirty: &crate::writer::DirtySet,
options: &crate::writer::SaveOptions,
) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
let (bytes, report) = crate::writer::save_full(self, dirty, options)?;
std::fs::write(path, &bytes)?;
Ok(report)
}
#[must_use]
pub fn next_object_number(&self) -> Option<u32> {
let from_objects = self.objects.keys().map(|id| id.num).max().unwrap_or(0);
let from_size = self
.trailer
.get(b"Size")
.and_then(Object::as_int)
.and_then(|s| u32::try_from(s.saturating_sub(1)).ok())
.unwrap_or(0);
let from_section = match self.section_shape {
SectionShape::Stream { id, .. } => id.num,
_ => 0,
};
self.highest_object_number
.max(from_objects)
.max(from_size)
.max(from_section)
.checked_add(1)
.filter(|n| *n != 0)
}
#[must_use]
pub const fn suppressed_object_count(&self) -> usize {
self.suppressed_by_size
}
}
pub(crate) fn parse_object_at(
buf: &[u8],
table: &XrefTable,
offset: u64,
policy: StreamLengthPolicy,
terminator: TerminatorPolicy,
duplicates: crate::parser::DuplicateKeyPolicy,
) -> Result<(IndirectObject, ParseRepairs), ParseError> {
let offset = usize::try_from(offset).unwrap_or(usize::MAX);
let mut resolve_length = |id: ObjId| -> Option<i64> {
let XrefEntry::InUse {
offset: len_offset,
generation,
} = table.get(id.num)?
else {
return None;
};
if generation != id.generation {
return None;
}
let len_offset = usize::try_from(len_offset).ok()?;
let io = Parser::at(buf, len_offset)
.parse_indirect_object(&mut |_| None)
.ok()?;
(io.id == id).then_some(())?;
io.value.as_int()
};
let mut parser = Parser::at(buf, offset)
.with_stream_length_policy(policy)
.with_terminator_policy(terminator)
.with_duplicate_key_policy(duplicates);
let io = parser.parse_indirect_object(&mut resolve_length)?;
Ok((
io,
ParseRepairs {
duplicate_keys: parser.duplicate_keys().to_vec(),
stream_lengths: parser.stream_lengths_recovered(),
missing_endobj: parser.missing_endobj_recovered(),
},
))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadOptions {
pub duplicate_keys: crate::parser::DuplicateKeyPolicy,
pub stream_lengths: StreamLengthPolicy,
pub terminators: TerminatorPolicy,
pub unreadable_objects: UnreadableObjectPolicy,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnreadableObjectPolicy {
#[default]
TreatAsUndefined,
Refuse,
}
impl Default for LoadOptions {
fn default() -> Self {
Self::new()
}
}
impl LoadOptions {
#[must_use]
pub fn new() -> Self {
Self {
duplicate_keys: crate::parser::DuplicateKeyPolicy::KeepLast,
stream_lengths: StreamLengthPolicy::RecoverFromEndstream,
terminators: TerminatorPolicy::RecoverAtNextHeader,
unreadable_objects: UnreadableObjectPolicy::TreatAsUndefined,
}
}
#[must_use]
pub const fn strict() -> Self {
Self {
duplicate_keys: crate::parser::DuplicateKeyPolicy::Refuse,
stream_lengths: StreamLengthPolicy::Strict,
terminators: TerminatorPolicy::Strict,
unreadable_objects: UnreadableObjectPolicy::Refuse,
}
}
#[must_use]
pub const fn with_duplicate_keys(mut self, policy: crate::parser::DuplicateKeyPolicy) -> Self {
self.duplicate_keys = policy;
self
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LoadAnomaly {
DuplicateDictKey {
object: Option<ObjId>,
key: Vec<u8>,
kept: Object,
discarded: Object,
},
StreamLengthRecovered {
object: ObjId,
},
MissingEndobjRecovered {
object: ObjId,
},
ObjectUnreadable {
object: ObjId,
reason: String,
},
}
impl LoadAnomaly {
#[must_use]
pub const fn object(&self) -> Option<ObjId> {
match self {
Self::DuplicateDictKey { object, .. } => *object,
Self::StreamLengthRecovered { object }
| Self::MissingEndobjRecovered { object }
| Self::ObjectUnreadable { object, .. } => Some(*object),
}
}
#[must_use]
pub const fn kind(&self) -> &'static str {
match self {
Self::DuplicateDictKey { .. } => "duplicate_dict_key",
Self::StreamLengthRecovered { .. } => "stream_length_recovered",
Self::MissingEndobjRecovered { .. } => "missing_endobj_recovered",
Self::ObjectUnreadable { .. } => "object_unreadable",
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct ParseRepairs {
pub duplicate_keys: Vec<crate::parser::DuplicateKeyRecord>,
pub stream_lengths: usize,
pub missing_endobj: usize,
}
fn parse_version_name(name: &[u8]) -> Option<PdfVersion> {
let text = std::str::from_utf8(name).ok()?;
let (major, minor) = text.split_once('.')?;
Some(PdfVersion {
major: major.parse().ok()?,
minor: minor.parse().ok()?,
})
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
fn build_pdf(objects: &[(u32, &str)], trailer_extra: &str) -> Vec<u8> {
let mut buf = b"%PDF-1.4\n".to_vec();
let mut offsets: Vec<(u32, usize)> = Vec::new();
for (num, body) in objects {
offsets.push((*num, buf.len()));
buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_at = buf.len();
let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
buf.extend_from_slice(b"0000000000 65535 f\r\n");
for num in 1..=max_num {
match offsets.iter().find(|(n, _)| *n == num) {
Some((_, off)) => {
buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
}
None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
}
}
buf.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R {trailer_extra}>>\nstartxref\n{xref_at}\n%%EOF\n",
max_num + 1
)
.as_bytes(),
);
buf
}
fn minimal_doc() -> Vec<u8> {
build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [] /Count 0 >>"),
],
"",
)
}
#[test]
fn loads_minimal_document() {
let doc = Document::from_bytes(minimal_doc()).unwrap();
assert_eq!(doc.object_count(), 2);
assert_eq!(doc.version().to_string(), "1.4");
let cat = doc.catalog().unwrap();
assert_eq!(
cat.get(b"Type").unwrap().as_name().unwrap().as_bytes(),
b"Catalog"
);
}
#[test]
fn resolve_follows_references_and_nulls_dangling() {
let doc = Document::from_bytes(minimal_doc()).unwrap();
let cat = doc.catalog().unwrap();
let pages = doc.resolve(cat.get(b"Pages").unwrap());
assert_eq!(
pages.as_dict().unwrap().get(b"Count").unwrap().as_int(),
Some(0)
);
let dangling = Object::Reference(ObjId::new(17, 0));
assert_eq!(*doc.resolve(&dangling), Object::Null);
let stale = Object::Reference(ObjId::new(2, 9));
assert_eq!(*doc.resolve(&stale), Object::Null);
}
#[test]
fn reference_cycle_resolves_to_null() {
let doc = Document::from_bytes(build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [] /Count 0 >>"),
(3, "3 0 R"),
],
"",
))
.unwrap();
let cyc = Object::Reference(ObjId::new(3, 0));
assert_eq!(*doc.resolve(&cyc), Object::Null);
}
#[test]
fn provenance_spans_recover_source_bytes() {
let doc = Document::from_bytes(minimal_doc()).unwrap();
let io = doc.get(ObjId::new(1, 0)).unwrap();
let raw = io.file_span().unwrap().slice(doc.bytes()).unwrap();
assert!(raw.starts_with(b"1 0 obj"));
assert!(raw.ends_with(b"endobj"));
}
#[test]
fn catalog_version_upgrades_header() {
let doc = Document::from_bytes(build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /Version /1.7 >>"),
(2, "<< /Type /Pages /Kids [] /Count 0 >>"),
],
"",
))
.unwrap();
assert_eq!(doc.version().to_string(), "1.7");
}
#[test]
fn catalog_version_cannot_downgrade_header() {
let mut bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /Version /1.2 >>"),
(2, "<< /Type /Pages /Kids [] /Count 0 >>"),
],
"",
);
let pos = bytes.windows(3).position(|w| w == b"1.4").unwrap();
bytes[pos..pos + 3].copy_from_slice(b"1.6");
let doc = Document::from_bytes(bytes).unwrap();
assert_eq!(doc.version().to_string(), "1.6");
}
#[test]
fn an_object_id_mismatch_is_recorded_by_default_and_refused_under_strict() {
let bytes = minimal_doc();
let text = String::from_utf8(bytes.clone()).unwrap();
let obj1_off = text.find("1 0 obj").unwrap();
let obj2_off = text.find("2 0 obj").unwrap();
let entry = format!("{obj2_off:010} 00000 n");
let entry_pos = text.find(&entry).unwrap();
let mut corrupted = bytes;
corrupted[entry_pos..entry_pos + 10].copy_from_slice(format!("{obj1_off:010}").as_bytes());
let doc = Document::from_bytes(corrupted.clone())
.expect("a table/body disagreement about ONE object is not an unreadable file");
assert!(doc.get(ObjId::new(2, 0)).is_none());
assert!(
doc.load_anomalies().iter().any(|a| matches!(
a,
LoadAnomaly::ObjectUnreadable { object, .. } if *object == ObjId::new(2, 0)
)),
"{:?}",
doc.load_anomalies()
);
let err =
Document::from_bytes_with_options(corrupted, None, LoadOptions::strict()).unwrap_err();
assert!(matches!(err, DocError::ObjectIdMismatch { .. }));
}
#[test]
fn missing_root_is_no_catalog() {
let mut buf = b"%PDF-1.4\n".to_vec();
let xref_at = buf.len();
buf.extend_from_slice(b"xref\n0 1\n0000000000 65535 f\r\n");
buf.extend_from_slice(
format!("trailer\n<< /Size 1 >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
);
let doc = Document::from_bytes(buf).unwrap();
assert!(matches!(doc.catalog(), Err(DocError::NoCatalog)));
}
#[test]
fn stream_with_indirect_length_loads_end_to_end() {
let doc = Document::from_bytes(build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [] /Count 0 >>"),
(3, "<< /Length 4 0 R >>\nstream\nhello wo\nendstream"),
(4, "8"),
],
"",
))
.unwrap();
let io = doc.get(ObjId::new(3, 0)).unwrap();
let Object::Stream(s) = &io.value else {
panic!("not a stream");
};
assert_eq!(s.data_span.slice(doc.bytes()).unwrap(), b"hello wo");
}
}