Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge PR #1850: fix(cos): check object-stream member numbers and offsets (#1815)

aiongg898a57ddc662
diff --cc crates/cos/src/document.rs
index 639edf582,97c832eb2..5be7c0420
--- a/crates/cos/src/document.rs
+++ b/crates/cos/src/document.rs
@@@ -1173,21 -1119,9 +1179,21 @@@ impl Document
if let Some(s) = self.objstms.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
return Ok(s.clone());
}
- let Object::Stream(s) = &*self.try_get(num)? else { return Err(CosError::MissingObject(num)) };
+ // A file entry that cannot place the stream (one that says it is itself compressed
+ // inside another stream, as in #2367, or points nowhere) is tried by the stream's own
+ // header, as a plain object with a wrong offset is. An edited or freed stream, in the
+ // overlay or in a saved revision's table, is what that says it is: the file's copy
+ // must not come back.
+ let loaded = match self.try_get(num) {
+ Ok(o) if matches!(*o, Object::Stream(_)) => o,
+ _ if self.overlay.contains_key(&num) || matches!(self.xref_entry(num), Some(XrefEntry::Free { .. })) => {
+ return Err(CosError::MissingObject(num));
+ }
+ _ => Arc::new(self.scan_for(num).map(|(id, o)| self.decrypted(id, o)).ok_or(CosError::MissingObject(num))?),
+ };
+ let Object::Stream(s) = &*loaded else { return Err(CosError::MissingObject(num)) };
let n = s.dict.int(b"N").unwrap_or(0).clamp(0, 1_000_000) as usize;
- let first = s.dict.int(b"First").unwrap_or(0).max(0) as usize;
+ let first = usize::try_from(s.dict.int(b"First").unwrap_or(0).max(0)).ok();
let data = s.decoded_within(self.stream_limit)?;
let mut lx = Lexer::new(&data, 0);
let mut index = Vec::with_capacity(n);