use std::collections::HashMap;
use std::sync::Arc;
use crate::object::{Dictionary, NameTable, ObjectError, ObjectId, PdfObject, PdfStream};
use crate::security::{
Cipher, EncryptDict, EncryptionScheme, Permissions, SecurityContext, SecurityError,
StandardHandler,
};
use crate::source::PdfSource;
use crate::structure::{DocumentStructure, RecoveryEvent, StructureError};
mod links;
mod ocg;
mod outline;
mod pages;
mod resolve;
mod samples;
pub use links::{DocumentLink, DocumentLinkTarget, DocumentLinks};
pub use ocg::OcgConfig;
pub use outline::{
DestinationFit, DocumentDestination, DocumentOutline, DocumentOutlineItem, OutlineIssue,
};
use resolve::Resolver;
pub(crate) use samples::ImageSampleSession;
#[derive(Debug, Clone)]
pub struct DocumentLimits {
pub syntax: crate::syntax::SyntaxLimits,
pub max_reference_chain: usize,
pub max_decoded_bytes_per_context: usize,
pub max_pages: u32,
pub max_revisions: usize,
pub max_objects: u32,
pub preserve_section_entries: bool,
}
impl Default for DocumentLimits {
fn default() -> Self {
Self {
syntax: crate::syntax::SyntaxLimits::default(),
max_reference_chain: 128,
max_decoded_bytes_per_context: 1 << 30, max_pages: 0,
max_revisions: 4096,
max_objects: 8 * 1024 * 1024,
preserve_section_entries: false,
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum DocumentError {
#[error(transparent)]
Structure(#[from] StructureError),
#[error(transparent)]
Object(#[from] ObjectError),
#[error(transparent)]
Security(#[from] crate::security::SecurityError),
#[error("page index {0} out of range")]
PageOutOfRange(u32),
#[error("limit exceeded: {0}")]
LimitExceeded(&'static str),
#[error("not implemented yet: {0} (see skeleton-blueprint.md §7)")]
NotImplemented(&'static str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PageIndex(pub u32);
pub const ANNOT_FLAG_HIDDEN: u32 = 1 << 1;
pub const ANNOT_FLAG_NOVIEW: u32 = 1 << 5;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnnotationColor {
Gray(f32),
Rgb([f32; 3]),
Cmyk([f32; 4]),
}
#[derive(Debug, Clone)]
pub struct PageAnnotation {
pub subtype: Option<crate::object::NameId>,
pub source: Option<ObjectId>,
pub rect: [f64; 4],
pub flags: u32,
pub appearance: Option<PdfObject>,
pub appearance_state: Option<crate::object::NameId>,
pub destination: Option<PdfObject>,
pub action: Option<PdfObject>,
pub quad_points: std::sync::Arc<[[f64; 8]]>,
pub color: Option<AnnotationColor>,
pub opacity: f32,
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>,
}
impl PageAnnotation {
pub fn hidden_for_display(&self) -> bool {
self.flags & (ANNOT_FLAG_HIDDEN | ANNOT_FLAG_NOVIEW) != 0
}
}
#[derive(Debug, Clone)]
pub struct PageRef {
pub index: PageIndex,
pub object: Option<ObjectId>,
pub media_box: [f64; 4],
pub crop_box: [f64; 4],
pub bleed_box: [f64; 4],
pub trim_box: [f64; 4],
pub art_box: [f64; 4],
pub rotate: u16,
pub resources: Option<PdfObject>,
pub contents: Option<PdfObject>,
pub annotations: Arc<[PageAnnotation]>,
}
#[derive(Debug, Default)]
pub struct PageTreeIndex {
pages: Box<[PageRef]>,
}
impl PageTreeIndex {
pub fn from_pages(pages: Box<[PageRef]>) -> Self {
Self { pages }
}
pub fn page_count(&self) -> u32 {
self.pages.len() as u32
}
pub fn page(&self, index: PageIndex) -> Option<&PageRef> {
self.pages.get(index.0 as usize)
}
pub fn iter(&self) -> impl Iterator<Item = &PageRef> {
self.pages.iter()
}
pub fn index_for_object(&self, object: ObjectId) -> Option<PageIndex> {
self.pages
.iter()
.find(|page| page.object == Some(object))
.map(|page| page.index)
}
}
#[derive(Debug)]
pub struct ParseContext {
recursion: Vec<ObjectId>,
pub decoded_bytes_used: usize,
pub objects_visited: usize,
#[cfg(feature = "profiling")]
pub object_cache_hits: usize,
#[cfg(feature = "profiling")]
pub object_cache_misses: usize,
#[cfg(feature = "profiling")]
pub object_stream_cache_hits: usize,
#[cfg(feature = "profiling")]
pub object_stream_inflates: usize,
cache: HashMap<ObjectId, Arc<PdfObject>>,
objstm: HashMap<u32, Arc<ObjStmCached>>,
cache_bytes: usize,
large_entries: Vec<ObjectId>,
cache_budget: usize,
pub recovery: Vec<RecoveryEvent>,
cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
}
pub const DEFAULT_PARSE_CACHE_BUDGET: usize = 256 << 20;
pub const LARGE_OWNED_STREAM_BYTES: usize = 64 << 10;
const CACHE_ENTRY_BYTES: usize = 64;
fn is_large_owned_stream(value: &PdfObject) -> bool {
matches!(value, PdfObject::Stream(stream)
if matches!(&stream.data, crate::object::StreamData::Owned(bytes)
if bytes.len() > LARGE_OWNED_STREAM_BYTES))
}
fn cached_object_bytes(value: &PdfObject) -> usize {
match value {
PdfObject::Stream(stream) => match &stream.data {
crate::object::StreamData::Owned(bytes) => CACHE_ENTRY_BYTES + bytes.len(),
crate::object::StreamData::InSource { .. } => CACHE_ENTRY_BYTES,
},
_ => CACHE_ENTRY_BYTES,
}
}
fn cached_objstm_bytes(entry: &ObjStmCached) -> usize {
CACHE_ENTRY_BYTES + entry.data.len()
}
#[derive(Debug)]
pub(crate) struct ObjStmCached {
pub(crate) data: Vec<u8>,
pub(crate) layout: crate::structure::objstm::ObjectStreamLayout,
}
impl ParseContext {
pub fn new() -> Self {
Self {
recursion: Vec::with_capacity(16),
decoded_bytes_used: 0,
objects_visited: 0,
#[cfg(feature = "profiling")]
object_cache_hits: 0,
#[cfg(feature = "profiling")]
object_cache_misses: 0,
#[cfg(feature = "profiling")]
object_stream_cache_hits: 0,
#[cfg(feature = "profiling")]
object_stream_inflates: 0,
cache: HashMap::new(),
objstm: HashMap::new(),
cache_bytes: 0,
large_entries: Vec::new(),
cache_budget: DEFAULT_PARSE_CACHE_BUDGET,
recovery: Vec::new(),
cancellation: None,
}
}
pub fn with_cache_budget(bytes: usize) -> Self {
let mut context = Self::new();
context.cache_budget = bytes;
context
}
pub fn cached_bytes(&self) -> usize {
self.cache_bytes
}
pub fn begin_job(&mut self) {
self.recursion.clear();
self.decoded_bytes_used = 0;
self.objects_visited = 0;
#[cfg(feature = "profiling")]
{
self.object_cache_hits = 0;
self.object_cache_misses = 0;
self.object_stream_cache_hits = 0;
self.object_stream_inflates = 0;
}
self.recovery.clear();
self.cancellation = None;
if self.cache_bytes > self.cache_budget {
self.cache.clear();
self.objstm.clear();
self.cache_bytes = 0;
self.large_entries.clear();
}
for id in std::mem::take(&mut self.large_entries) {
if self
.cache
.get(&id)
.is_some_and(|v| is_large_owned_stream(v))
&& let Some(old) = self.cache.remove(&id)
{
self.cache_bytes = self.cache_bytes.saturating_sub(cached_object_bytes(&old));
}
}
}
pub fn set_cancellation_flag(
&mut self,
cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
) {
self.cancellation = cancellation;
}
pub fn is_cancelled(&self) -> bool {
self.cancellation
.as_ref()
.is_some_and(|cancelled| cancelled.load(std::sync::atomic::Ordering::Acquire))
}
fn cache_get(&self, id: ObjectId) -> Option<Arc<PdfObject>> {
self.cache.get(&id).cloned()
}
fn cache_put(&mut self, id: ObjectId, value: Arc<PdfObject>) {
if is_large_owned_stream(&value) {
self.large_entries.push(id);
}
self.cache_bytes = self.cache_bytes.saturating_add(cached_object_bytes(&value));
if let Some(old) = self.cache.insert(id, value) {
self.cache_bytes = self.cache_bytes.saturating_sub(cached_object_bytes(&old));
}
}
fn objstm_get(&self, container: u32) -> Option<Arc<ObjStmCached>> {
self.objstm.get(&container).cloned()
}
fn objstm_put(&mut self, container: u32, entry: Arc<ObjStmCached>) {
self.cache_bytes = self.cache_bytes.saturating_add(cached_objstm_bytes(&entry));
if let Some(old) = self.objstm.insert(container, entry) {
self.cache_bytes = self.cache_bytes.saturating_sub(cached_objstm_bytes(&old));
}
}
pub fn enter(&mut self, id: ObjectId, limits: &DocumentLimits) -> Result<(), DocumentError> {
if self.recursion.contains(&id) {
return Err(ObjectError::ReferenceCycle(id).into());
}
if self.recursion.len() >= limits.max_reference_chain {
return Err(DocumentError::LimitExceeded("max_reference_chain"));
}
self.recursion.push(id);
Ok(())
}
pub fn exit(&mut self, id: ObjectId) {
debug_assert_eq!(self.recursion.last(), Some(&id));
self.recursion.pop();
}
pub fn note_recovery(&mut self, message: String) {
self.recovery.push(RecoveryEvent::Other(message));
}
}
impl Default for ParseContext {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct ObjectRepository {
}
impl ObjectRepository {
pub fn new() -> Self {
Self {}
}
pub fn resolve(
&self,
snapshot: &DocumentSnapshot,
id: ObjectId,
ctx: &mut ParseContext,
) -> Result<Arc<PdfObject>, DocumentError> {
snapshot.resolver().resolve(id, ctx)
}
}
impl Default for ObjectRepository {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub struct DocumentSnapshot {
inner: Arc<SnapshotInner>,
}
#[derive(Debug)]
struct SnapshotInner {
source: Arc<dyn PdfSource>,
structure: DocumentStructure,
names: NameTable,
pages: PageTreeIndex,
objects: ObjectRepository,
security: Option<SecurityContext>,
limits: DocumentLimits,
ocg: OcgConfig,
extensions: ExtensionMap,
}
#[derive(Default)]
struct ExtensionMap {
slots: std::sync::Mutex<HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>>,
}
impl std::fmt::Debug for ExtensionMap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let count = self
.slots
.lock()
.map(|slots| slots.len())
.unwrap_or_else(|poisoned| poisoned.into_inner().len());
f.debug_struct("ExtensionMap")
.field("slots", &count)
.finish()
}
}
impl DocumentSnapshot {
pub fn open(source: Arc<dyn PdfSource>, limits: DocumentLimits) -> Result<Self, DocumentError> {
Self::open_with_password(source, limits, None)
}
pub fn open_with_password(
source: Arc<dyn PdfSource>,
limits: DocumentLimits,
password: Option<&str>,
) -> Result<Self, DocumentError> {
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: limits.preserve_section_entries,
};
type Parts = (
Option<SecurityContext>,
PageTreeIndex,
ocg::OcgConfig,
pages::WalkStats,
);
let build_parts = |structure: &DocumentStructure,
ctx: &mut ParseContext|
-> Result<Parts, DocumentError> {
let security = {
let plain = Resolver {
source: source.as_ref(),
structure,
names: &names,
limits: &limits,
security: None,
};
build_security(&plain, structure, &names, ctx, password)?
};
let resolver = Resolver {
source: source.as_ref(),
structure,
names: &names,
limits: &limits,
security: security.as_ref(),
};
let (pages, stats) = pages::build_page_tree(&resolver, ctx)?;
let ocg = ocg::parse_ocproperties(&resolver, ctx);
Ok((security, pages, ocg, stats))
};
let try_build = |structure: DocumentStructure|
-> Result<(DocumentStructure, ParseContext, Parts), DocumentError> {
let mut ctx = ParseContext::new();
let parts = build_parts(&structure, &mut ctx)?;
Ok((structure, ctx, parts))
};
let rebuild =
|| crate::structure::load_structure_rebuilt(source.as_ref(), &names, &structure_limits);
let (
mut structure,
mut ctx,
(mut security, mut pages, mut ocg, mut stats),
rebuilt_already,
) = match crate::structure::load_structure(source.as_ref(), &names, &structure_limits) {
Ok(s) => match try_build(s) {
Ok((s, c, p)) => (s, c, p, false),
Err(build_err) => match rebuild() {
Ok(r) => match try_build(r) {
Ok((s, c, p)) => (s, c, p, true),
Err(_) => return Err(build_err),
},
Err(_) => return Err(build_err),
},
},
Err(load_err) => match rebuild() {
Ok(r) => match try_build(r) {
Ok((s, c, p)) => (s, c, p, true),
Err(_) => return Err(load_err.into()),
},
Err(_) => return Err(load_err.into()),
},
};
if !rebuilt_already
&& stats.lost_subtrees > 0
&& let Ok(rebuilt) = rebuild()
{
let mut ctx2 = ParseContext::new();
if let Ok((sec2, pages2, ocg2, stats2)) = build_parts(&rebuilt, &mut ctx2) {
let (pages2, candidate_stats) = if stats2.real_pages == 0 {
let resolver = Resolver {
source: source.as_ref(),
structure: &rebuilt,
names: &names,
limits: &limits,
security: sec2.as_ref(),
};
let orphans = pages::recover_orphan_pages(&resolver, &mut ctx2);
if orphans.page_count() > 0 {
let orphan_count = orphans.page_count() as usize;
(
orphans,
pages::WalkStats {
real_pages: orphan_count,
lost_subtrees: 0,
},
)
} else {
(pages2, stats2)
}
} else {
(pages2, stats2)
};
let improves = candidate_stats.real_pages > stats.real_pages
|| (candidate_stats.real_pages == stats.real_pages
&& candidate_stats.lost_subtrees < stats.lost_subtrees);
if improves {
structure = rebuilt;
security = sec2;
pages = pages2;
ocg = ocg2;
ctx = ctx2;
stats = candidate_stats;
}
}
}
if rebuilt_already && stats.real_pages == 0 {
let resolver = Resolver {
source: source.as_ref(),
structure: &structure,
names: &names,
limits: &limits,
security: security.as_ref(),
};
let orphans = pages::recover_orphan_pages(&resolver, &mut ctx);
if orphans.page_count() > 0 {
pages = orphans;
}
}
if !ctx.recovery.is_empty() {
let mut all = structure.recovery.into_vec();
all.append(&mut ctx.recovery);
structure.recovery = all.into_boxed_slice();
}
let mut snapshot = Self::from_parts(source, structure, names, pages, security, limits);
if let Some(inner) = Arc::get_mut(&mut snapshot.inner) {
inner.ocg = ocg;
}
Ok(snapshot)
}
#[cfg(feature = "profiling")]
pub fn open_profiled(
source: Arc<dyn PdfSource>,
limits: DocumentLimits,
) -> Result<(Self, crate::profiling::ProfileReport), DocumentError> {
let start = std::time::Instant::now();
let snapshot = Self::open(source, limits)?;
let mut profile = crate::profiling::ProfileReport::new();
profile.add_duration("document.open", start.elapsed());
profile.increment("document.pages", snapshot.page_count() as u64);
profile.increment(
"document.recovery_events",
snapshot.recovery_events().len() as u64,
);
Ok((snapshot, profile))
}
fn resolver(&self) -> Resolver<'_> {
Resolver {
source: self.inner.source.as_ref(),
structure: &self.inner.structure,
names: &self.inner.names,
limits: &self.inner.limits,
security: self.inner.security.as_ref(),
}
}
pub fn decode_stream_data(
&self,
stream: &PdfStream,
ctx: &mut ParseContext,
) -> Result<Vec<u8>, DocumentError> {
self.resolver().decode_stream_data(stream, ctx)
}
pub fn decode_stream_data_to_codec(
&self,
stream: &PdfStream,
ctx: &mut ParseContext,
) -> Result<(Vec<u8>, Option<String>), DocumentError> {
self.resolver().decode_stream_data_to_codec(stream, ctx)
}
pub fn from_parts(
source: Arc<dyn PdfSource>,
structure: DocumentStructure,
names: NameTable,
pages: PageTreeIndex,
security: Option<SecurityContext>,
limits: DocumentLimits,
) -> Self {
Self {
inner: Arc::new(SnapshotInner {
source,
structure,
names,
pages,
objects: ObjectRepository::new(),
security,
limits,
ocg: OcgConfig::default(),
extensions: ExtensionMap::default(),
}),
}
}
pub fn extension<T: Default + Send + Sync + 'static>(&self) -> Arc<T> {
let mut slots = self
.inner
.extensions
.slots
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let slot = slots
.entry(std::any::TypeId::of::<T>())
.or_insert_with(|| Arc::new(T::default()));
match Arc::clone(slot).downcast::<T>() {
Ok(typed) => typed,
Err(_) => {
let fresh: Arc<T> = Arc::new(T::default());
*slot = Arc::clone(&fresh) as Arc<dyn std::any::Any + Send + Sync>;
fresh
}
}
}
pub fn ocg_visible(&self, id: ObjectId) -> bool {
self.inner.ocg.visible(id)
}
pub fn source(&self) -> &Arc<dyn PdfSource> {
&self.inner.source
}
pub fn structure(&self) -> &DocumentStructure {
&self.inner.structure
}
pub fn names(&self) -> &NameTable {
&self.inner.names
}
pub fn page_count(&self) -> u32 {
self.inner.pages.page_count()
}
pub fn page(&self, index: PageIndex) -> Result<&PageRef, DocumentError> {
self.inner
.pages
.page(index)
.ok_or(DocumentError::PageOutOfRange(index.0))
}
pub fn outline(&self, ctx: &mut ParseContext) -> DocumentOutline {
outline::extract(self, ctx)
}
pub fn links(&self, ctx: &mut ParseContext) -> DocumentLinks {
links::extract(self, ctx)
}
pub fn objects(&self) -> &ObjectRepository {
&self.inner.objects
}
pub fn security(&self) -> Option<&SecurityContext> {
self.inner.security.as_ref()
}
pub fn limits(&self) -> &DocumentLimits {
&self.inner.limits
}
pub fn recovery_events(&self) -> &[RecoveryEvent] {
&self.inner.structure.recovery
}
}
fn build_security(
resolver: &Resolver<'_>,
structure: &DocumentStructure,
names: &NameTable,
ctx: &mut ParseContext,
password: Option<&str>,
) -> Result<Option<SecurityContext>, DocumentError> {
let encrypt_obj = match structure.trailer.encrypt {
Some(id) => resolver.resolve(id, ctx)?,
None => match structure.trailer.dict.get(names.known.encrypt) {
Some(PdfObject::Dictionary(d)) => Arc::new(PdfObject::Dictionary(Arc::clone(d))),
_ => return Ok(None),
},
};
let Some(dict) = encrypt_obj.as_dict() else {
return Ok(None);
};
let file_id = structure
.trailer
.file_id
.as_ref()
.map(|id| id[0].as_bytes().to_vec())
.unwrap_or_default();
let (enc, scheme) = parse_encrypt_dict(dict, file_id, names);
let v5 = enc.r == 5 || enc.r == 6 || enc.v == 5;
if !v5 && (enc.r > 6 || enc.v > 5) {
return Err(SecurityError::UnsupportedScheme(scheme).into());
}
let authenticated = StandardHandler::with_password(&enc, "")
.or_else(|| password.and_then(|pw| StandardHandler::with_password(&enc, pw)));
if let Some((handler, role)) = authenticated {
if let Some(mismatch) = handler.verify_perms(&enc) {
ctx.note_recovery(format!("encryption /Perms cross-check failed: {mismatch}"));
}
return Ok(Some(
SecurityContext::standard(scheme, Permissions(enc.p as u32), handler)
.with_password_role(role),
));
}
if matches!(scheme, EncryptionScheme::None)
&& let Some(handler) = StandardHandler::open(&enc)
{
return Ok(Some(SecurityContext::standard(
scheme,
Permissions(enc.p as u32),
handler,
)));
}
Err(match password {
Some(_) => SecurityError::IncorrectPassword.into(),
None => SecurityError::PasswordRequired.into(),
})
}
enum CryptFilterMethod {
V2,
AesV2,
AesV3,
Identity,
}
pub fn parse_encrypt_dict(
dict: &Dictionary,
file_id: Vec<u8>,
names: &NameTable,
) -> (EncryptDict, EncryptionScheme) {
let get_int = |key: &[u8]| {
names
.lookup(key)
.and_then(|id| dict.get(id))
.and_then(PdfObject::as_int)
};
let get_bytes = |key: &[u8]| -> Vec<u8> {
names
.lookup(key)
.and_then(|id| dict.get(id))
.and_then(|o| match o {
PdfObject::String(s) => Some(s.as_bytes().to_vec()),
_ => None,
})
.unwrap_or_default()
};
let get_bool = |key: &[u8]| {
names
.lookup(key)
.and_then(|id| dict.get(id))
.and_then(|o| match o {
PdfObject::Boolean(b) => Some(*b),
_ => None,
})
};
let v = get_int(b"V").unwrap_or(0);
let r = get_int(b"R").unwrap_or(0);
let length_bits = get_int(b"Length").unwrap_or(40);
let rc4_key_bytes = (length_bits.clamp(40, 128) / 8) as usize;
let (cipher, key_bytes, scheme) = match v {
1 => (Cipher::Rc4, 5, EncryptionScheme::Rc4 { key_bits: 40 }),
2 | 3 => (
Cipher::Rc4,
rc4_key_bytes,
EncryptionScheme::Rc4 {
key_bits: (rc4_key_bytes * 8) as u16,
},
),
4 => match crypt_filter_method(dict, names) {
CryptFilterMethod::AesV2 => (Cipher::Aes128, 16, EncryptionScheme::Aes128),
CryptFilterMethod::V2 => (
Cipher::Rc4,
rc4_key_bytes,
EncryptionScheme::Rc4 {
key_bits: (rc4_key_bytes * 8) as u16,
},
),
CryptFilterMethod::Identity => (Cipher::None, rc4_key_bytes, EncryptionScheme::None),
CryptFilterMethod::AesV3 => (Cipher::Aes128, 32, EncryptionScheme::Aes256),
},
_ => (Cipher::Aes128, 32, EncryptionScheme::Aes256),
};
let enc = EncryptDict {
v,
r,
o: get_bytes(b"O"),
u: get_bytes(b"U"),
ue: get_bytes(b"UE"),
oe: get_bytes(b"OE"),
p: get_int(b"P").unwrap_or(0) as i32,
perms: get_bytes(b"Perms"),
key_bytes,
encrypt_metadata: get_bool(b"EncryptMetadata").unwrap_or(true),
cipher,
file_id,
};
(enc, scheme)
}
fn crypt_filter_method(dict: &Dictionary, names: &NameTable) -> CryptFilterMethod {
let name_is = |id, s: &[u8]| &*names.resolve(id) == s;
let Some(stmf) = names
.lookup(b"StmF")
.and_then(|id| dict.get(id))
.and_then(PdfObject::as_name)
else {
return CryptFilterMethod::Identity;
};
if name_is(stmf, b"Identity") {
return CryptFilterMethod::Identity;
}
let Some(cf) = names
.lookup(b"CF")
.and_then(|id| dict.get(id))
.and_then(PdfObject::as_dict)
else {
return CryptFilterMethod::Identity;
};
let Some(entry) = cf.get(stmf).and_then(PdfObject::as_dict) else {
return CryptFilterMethod::Identity;
};
let Some(cfm) = names
.lookup(b"CFM")
.and_then(|id| entry.get(id))
.and_then(PdfObject::as_name)
else {
return CryptFilterMethod::Identity;
};
if name_is(cfm, b"AESV2") {
CryptFilterMethod::AesV2
} else if name_is(cfm, b"AESV3") {
CryptFilterMethod::AesV3
} else if name_is(cfm, b"V2") {
CryptFilterMethod::V2
} else {
CryptFilterMethod::Identity
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const fn assert_send_sync<T: Send + Sync>() {}
const _: () = assert_send_sync::<DocumentSnapshot>();
#[test]
fn parse_context_detects_cycles_and_depth() {
let limits = DocumentLimits {
max_reference_chain: 2,
..Default::default()
};
let mut ctx = ParseContext::new();
let a = ObjectId::new(1, 0);
let b = ObjectId::new(2, 0);
ctx.enter(a, &limits).unwrap();
assert!(matches!(
ctx.enter(a, &limits),
Err(DocumentError::Object(ObjectError::ReferenceCycle(_)))
));
ctx.enter(b, &limits).unwrap();
assert!(matches!(
ctx.enter(ObjectId::new(3, 0), &limits),
Err(DocumentError::LimitExceeded(_))
));
ctx.exit(b);
ctx.exit(a);
}
#[test]
fn begin_job_resets_job_state_but_keeps_worker_caches() {
let mut ctx = ParseContext::new();
let id = ObjectId::new(7, 0);
ctx.recursion.push(id);
ctx.decoded_bytes_used = 123;
ctx.objects_visited = 9;
ctx.recovery
.push(RecoveryEvent::Other("previous page".into()));
ctx.cache.insert(id, Arc::new(PdfObject::Null));
ctx.begin_job();
assert!(ctx.recursion.is_empty());
assert_eq!(ctx.decoded_bytes_used, 0);
assert_eq!(ctx.objects_visited, 0);
assert!(ctx.recovery.is_empty());
assert!(ctx.cache.contains_key(&id));
}
fn owned_stream(len: usize) -> Arc<PdfObject> {
Arc::new(PdfObject::Stream(Arc::new(crate::object::PdfStream {
dict: crate::object::Dictionary::default(),
data: crate::object::StreamData::Owned(Arc::from(vec![7u8; len])),
})))
}
#[test]
fn begin_job_enforces_the_cache_budget() {
let mut ctx = ParseContext::with_cache_budget(10_000);
ctx.cache_put(ObjectId::new(1, 0), owned_stream(4_000));
ctx.cache_put(ObjectId::new(2, 0), Arc::new(PdfObject::Null));
assert_eq!(ctx.cached_bytes(), 4_000 + 2 * CACHE_ENTRY_BYTES);
ctx.cache_put(ObjectId::new(1, 0), owned_stream(5_000));
assert_eq!(ctx.cached_bytes(), 5_000 + 2 * CACHE_ENTRY_BYTES);
ctx.begin_job();
assert_eq!(ctx.cache.len(), 2, "under budget: kept");
ctx.objstm_put(
9,
Arc::new(ObjStmCached {
data: vec![0; 6_000],
layout: crate::structure::objstm::ObjectStreamLayout {
members: Vec::new(),
},
}),
);
assert!(ctx.cached_bytes() > 10_000);
assert!(ctx.cache_get(ObjectId::new(1, 0)).is_some());
ctx.begin_job();
assert_eq!(ctx.cached_bytes(), 0);
assert!(ctx.cache.is_empty() && ctx.objstm.is_empty());
}
#[test]
fn large_decrypted_bodies_do_not_outlive_their_job() {
let mut ctx = ParseContext::new();
let large = ObjectId::new(1, 0);
let small = ObjectId::new(2, 0);
ctx.cache_put(large, owned_stream(LARGE_OWNED_STREAM_BYTES + 1));
ctx.cache_put(small, owned_stream(LARGE_OWNED_STREAM_BYTES));
assert!(ctx.cache_get(large).is_some(), "cached within its job");
let before = ctx.cached_bytes();
ctx.begin_job();
assert!(ctx.cache_get(large).is_none());
assert!(ctx.cache_get(small).is_some());
assert_eq!(
ctx.cached_bytes(),
before - (CACHE_ENTRY_BYTES + LARGE_OWNED_STREAM_BYTES + 1)
);
ctx.cache_put(large, owned_stream(LARGE_OWNED_STREAM_BYTES + 1));
ctx.cache_put(large, Arc::new(PdfObject::Null));
ctx.begin_job();
assert!(ctx.cache_get(large).is_some());
assert_eq!(
ctx.cached_bytes(),
2 * CACHE_ENTRY_BYTES + LARGE_OWNED_STREAM_BYTES
);
}
#[test]
fn begin_job_clears_a_previous_jobs_cancellation_flag() {
let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(true));
let mut context = ParseContext::new();
context.set_cancellation_flag(Some(cancelled));
assert!(context.is_cancelled());
context.begin_job();
assert!(!context.is_cancelled());
}
}