Skip to content

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

Content streams: step over a malformed token instead of ending the page

Hamza30ed249a2806
diff --git a/crates/render/src/raster/tests.rs b/crates/render/src/raster/tests.rs
index 36299d74f..696eaddb6 100644
--- a/crates/render/src/raster/tests.rs
+++ b/crates/render/src/raster/tests.rs
@@ -7035,3 +7035,76 @@ fn test_clip_only_text_raster_preserves_clipping_without_painting() {
assert!(pixels.contains(&[0, 0, 255, 255]), "fill shows through the 7 Tr clip");
assert!(pixels.contains(&white), "the clip is text-shaped, not the whole page");
}
+
+/// A malformed token in a content stream used to end the stream there, so the renderer, text
+/// extraction, Find and search-based redaction lost the rest of the page while the edit
+/// reader, MuPDF and pdftotext read it (#3565, #3568). Each token below is now stepped over.
+#[test]
+fn a_malformed_token_does_not_end_the_content_stream() {
+ // One token between two text objects. `BEFORE` is drawn before it, `AFTER` after.
+ let page = |token: &str| {
+ let stream = format!("BT /F1 8 Tf 2 30 Td (BEFORE) Tj ET {token} BT /F1 8 Tf 2 10 Td (AFTER) Tj ET");
+ let mut pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 60 40] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >> endobj\n5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\n".to_vec();
+ pdf.extend_from_slice(format!("4 0 obj << /Length {} >> stream\n", stream.len()).as_bytes());
+ pdf.extend_from_slice(stream.as_bytes());
+ pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");
+ let mut renderer = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
+ let text = renderer.render(RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() });
+ assert!(text.error.is_none(), "{token}: {:?}", text.error);
+ text.text.expect("a text layer").plain_text()
+ };
+
+ for token in [
+ // A `re` with three operands: the typed iterator used to abort on a path operator it
+ // could not dispatch, which is what #3568 reports.
+ "20 10 10 re",
+ // More operands than the limit (ISO 32000-2 Annex C gives 10): the instruction is
+ // dropped, not the stream.
+ "0 0 0 0 0 0 0 0 0 0 0 g",
+ // A stray delimiter: the lexer could not read an operator and jumped to the end.
+ ")",
+ // The same with no space after it. Stepping over the regular characters that follow a
+ // delimiter ate the next operator, so the page lost its second text object
+ // (#3636 review); only the delimiter is stepped over.
+ ")BT ET",
+ // A malformed `#` escape in a name, so neither an object nor an operator read.
+ "/C#2 gs",
+ // And the well-formed forms still work.
+ "20 10 10 5 re n",
+ "0.5 g",
+ ] {
+ let text = page(token);
+ assert!(text.contains("BEFORE"), "{token}: {text:?}");
+ assert!(text.contains("AFTER"), "{token}: the rest of the page was lost: {text:?}");
+ assert!(text.find("BEFORE") < text.find("AFTER"), "{token}: the page is read in order: {text:?}");
+ }
+}
+
+/// Content after an inline image whose data holds `EI` is still read. This pins the property
+/// but does **not** exercise the look-ahead gating added for #3636's review: accepting a false
+/// `EI` truncates the image, while the text after the real one is read either way, and this
+/// assertion passes with the gating removed. Showing the truncation needs valid ASCII85 data
+/// that contains `EI`, which this fixture does not have.
+#[test]
+fn content_after_an_inline_image_holding_ei_is_still_read() {
+ // An ASCII85 image whose data holds `EI\n`, then an `re` with three operands and twenty
+ // `q`s -- enough steps to satisfy the look-ahead's counter if the bad `re` were skipped --
+ // before the real `EI`. `AFTER` is drawn once the image is over.
+ let stream = b"q 100 0 0 100 10 10 cm BI /W 4 /H 4 /CS /G /BPC 8 /F /A85 ID EI
+20 10 10 re q q q q q q q q q q q q q q q q q q q q EI Q BT /F1 8 Tf 2 4 Td (AFTER) Tj ET"
+ .to_vec();
+ let mut pdf =
+ b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 120 120] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >> endobj\n5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\n"
+ .to_vec();
+ pdf.extend_from_slice(format!("4 0 obj << /Length {} >> stream\n", stream.len()).as_bytes());
+ pdf.extend_from_slice(&stream);
+ pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");
+
+ let mut renderer = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
+ let text = renderer.render(RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() });
+ assert!(text.error.is_none(), "{:?}", text.error);
+ let page = text.text.expect("a text layer").plain_text();
+ // The image ran to the real `EI`, so the text after it is the page's only text: the first
+ // `EI` inside the data was not taken for the end.
+ assert!(page.contains("AFTER"), "the content after the image was lost: {page:?}");
+}
diff --git a/vendor/hayro-syntax/src/content/mod.rs b/vendor/hayro-syntax/src/content/mod.rs
index e37044c5d..33c0e5bd0 100644
--- a/vendor/hayro-syntax/src/content/mod.rs
+++ b/vendor/hayro-syntax/src/content/mod.rs
@@ -117,6 +117,15 @@ const MAX_EI_LOOKAHEAD_STEPS: u32 = 256;
pub trait ContentTokenizer<'a> {
/// Return the next instruction, or `None` after the content stream ends or becomes invalid.
fn next_instruction<'b>(&'b mut self) -> Option<Instruction<'b, 'a>>;
+
+ /// PdfCraft patch: whether this tokenizer is only judging whether bytes read as content, as
+ /// the look-ahead past a candidate `EI` does. Such a pass must not recover from a malformed
+ /// token: its whole purpose is to find out whether the bytes are content, and answering
+ /// "yes, once the bad parts are skipped" of an inline image's data would cut the image at a
+ /// false `EI` (#3636 review).
+ fn judging_only(&self) -> bool {
+ false
+ }
}
/// An iterator over operators in the PDF content streams, providing raw access to the
@@ -181,6 +190,11 @@ impl<'a> UntypedIter<'a> {
self.committed = self.skip_blanks_and_comments();
}
+ // PdfCraft patch: set when this instruction carried more operands than the limit. Its
+ // operator is then dropped with them, rather than applied to the ones that did fit
+ // (#3568).
+ let mut overflowed = false;
+
while !self.reader.at_end() {
// I believe booleans/null never appear as an operator?
if matches!(
@@ -198,14 +212,31 @@ impl<'a> UntypedIter<'a> {
if self.undecided() {
return None;
}
- self.stack.push(object)?;
+ if self.stack.push(object).is_none() {
+ overflowed = true;
+ }
} else if self.reader.read_without_context::<Operator<'_>>().is_some() {
if self.undecided() {
return None;
}
self.stack.clear();
+ } else if self.undecided() {
+ return None;
+ } else if !self.lookahead && self.reader.peek_byte() == Some(b'/') && self.skip_bad_token() {
+ // PdfCraft patch: a name the lexer cannot read -- a malformed `#` escape, as
+ // in `/C#2 gs` -- used to end the stream, losing the rest of the page. Step
+ // over it and carry on, as the edit reader and other readers do (#3568).
+ //
+ // Only a name. An operand that is well formed but refused by a resource cap
+ // (a dictionary nested past the limit) still ends the stream, which is what
+ // `dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap` in
+ // pdfcraft's renderer asserts: reading on there would draw a page whose
+ // content was deliberately not parsed.
+ warn!("skipped an unreadable name in content stream");
+ self.stack.clear();
+ overflowed = false;
+ continue;
} else {
- self.undecided();
return None;
}
} else {
@@ -218,6 +249,14 @@ impl<'a> UntypedIter<'a> {
warn!("failed to read operator in content stream");
+ // PdfCraft patch: a stray delimiter (`)`, say) ended the stream here, so
+ // the rest of the page was lost. Step over it and carry on (#3568).
+ if !self.lookahead && self.skip_bad_token() {
+ self.stack.clear();
+ overflowed = false;
+ continue;
+ }
+
self.reader.jump_to_end();
return None;
}
@@ -443,6 +482,17 @@ impl<'a> UntypedIter<'a> {
}
}
+ if overflowed && !self.lookahead {
+ // PdfCraft patch: see `overflowed` above. ISO 32000-2 Annex C gives 10 as the
+ // historical operand limit; past it the instruction is dropped whole.
+ warn!("dropped an instruction with more operands than the limit");
+ self.stack.clear();
+ overflowed = false;
+ self.committed = self.reader.offset();
+ self.reader.skip_white_spaces_and_comments();
+ continue;
+ }
+
self.operator = Some(operator);
self.committed = self.reader.offset();
// PdfCraft patch (28): operands in reading order, if some were dropped.
@@ -484,6 +534,36 @@ impl<'a> UntypedIter<'a> {
open_comment.unwrap_or(self.reader.offset())
}
+ /// PdfCraft patch: step over one token the lexer could not read, so the rest of the stream is
+ /// still read instead of the page ending there. A delimiter stands alone; anything else runs
+ /// to the next delimiter or space. At least one byte is always consumed when this returns
+ /// true, so the loop in `next` cannot spin (#3568).
+ fn skip_bad_token(&mut self) -> bool {
+ let before = self.reader.offset();
+ match self.reader.peek_byte() {
+ None => return false,
+ // Never step over a good token: called where the blanks after the last one have not
+ // been skipped yet, there is nothing bad here to skip. Skipping ` BT` cost the page
+ // its second text object while this was being written.
+ Some(b) if is_white_space_character(b) || b == b'%' => {}
+ // A name reads to the next delimiter, malformed escapes included.
+ Some(b'/') => {
+ let _ = skip_name_like(&mut self.reader, true);
+ }
+ // A token of regular characters runs to the next delimiter or space.
+ Some(b) if is_regular_character(b) => {
+ self.reader.forward_while(is_regular_character);
+ }
+ // A delimiter stands alone. Consuming what follows it would eat the next operator:
+ // `)BT` cost the page its second text object while this was being written
+ // (#3636 review).
+ Some(_) => self.reader.forward(),
+ }
+ // Land on the next token, as the end of the loop in `next` does.
+ self.reader.skip_white_spaces_and_comments();
+ self.reader.offset() > before
+ }
+
/// PdfCraft patch: whether the instruction being read ran into the end of a window, so it
/// cannot be decided yet. Records that more data is needed.
fn undecided(&mut self) -> bool {
@@ -499,6 +579,10 @@ impl<'a> ContentTokenizer<'a> for UntypedIter<'a> {
fn next_instruction<'b>(&'b mut self) -> Option<Instruction<'b, 'a>> {
self.next()
}
+
+ fn judging_only(&self) -> bool {
+ self.lookahead
+ }
}
@@ -557,6 +641,8 @@ where
/// Return the next typed instruction.
#[allow(clippy::should_implement_trait)]
pub fn next(&mut self) -> Option<TypedInstruction<'_, 'a>> {
+ // Read before the instruction borrows the tokenizer.
+ let judging = self.untyped.judging_only();
let op = self.untyped.next_instruction()?;
// TODO: Explore whether dispatching can be made more efficient.
match TypedInstruction::dispatch(&op) {
@@ -565,22 +651,22 @@ where
// operator was used, let's abort completely, otherwise we might end up drawing random stuff.
// However, for other operators it could be worth it to just skip it but keep attempting
// to read other content operators.
+ // PdfCraft patch: a path operator whose operands do not fit it contributes nothing to
+ // the path, so skipping it leaves the path as it was -- the same state the abort
+ // below used to leave it in, except that the rest of the page is still read. Ending
+ // the stream here lost every later operator, and with it the rest of the page, its
+ // text and anything a redaction search would have matched (#3568).
None => {
- if [
- &b"m"[..],
- &b"l"[..],
- &b"c"[..],
- &b"v"[..],
- &b"y"[..],
- &b"h"[..],
- &b"re"[..],
- ]
- .contains(&op.operator.0.deref())
+ // A pass that is only judging whether bytes read as content must still stop at a
+ // path operator it cannot dispatch: counting it as a step would let an inline
+ // image's data pass for a content stream and cut the image at a false `EI`
+ // (#3636 review).
+ if judging
+ && [&b"m"[..], &b"l"[..], &b"c"[..], &b"v"[..], &b"y"[..], &b"h"[..], &b"re"[..]].contains(&op.operator.0.deref())
{
- None
- } else {
- Some(TypedInstruction::Fallback(op.operator))
+ return None;
}
+ Some(TypedInstruction::Fallback(op.operator))
}
}
}