Skip to content

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

fix(content): end inline images where the renderer ends them

aionggb72078871a30
diff --git a/Cargo.lock b/Cargo.lock
index a95014924..e318b7a77 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4042,6 +4042,7 @@ version = "0.11.0"
name = "pdfcraft-content"
version = "0.11.0"
dependencies = [
+ "hayro-syntax",
"pdfcraft-cos",
]
diff --git a/crates/content/Cargo.toml b/crates/content/Cargo.toml
index c553df0b8..e6b4c28a4 100644
--- a/crates/content/Cargo.toml
+++ b/crates/content/Cargo.toml
@@ -10,3 +10,6 @@ workspace = true
[dependencies]
pdfcraft-cos = { workspace = true }
+# The renderer's content tokenizer, already in the tree through pdfcraft-cos: inline images end
+# where the renderer ends them.
+hayro-syntax = { workspace = true }
diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rs
index eb126ffa2..097ec2689 100644
--- a/crates/content/src/lib.rs
+++ b/crates/content/src/lib.rs
@@ -60,6 +60,10 @@ pub struct Parsed {
pub ops: Vec<Op>,
/// Bytes that could not be read as operands or operators.
pub skipped: usize,
+ /// Inline images the renderer's tokenizer reads no image for (it stops, or finds no `EI` it
+ /// accepts). Their end here is a guess, so the operators after them may not be the ones the
+ /// page draws.
+ pub ambiguous_images: usize,
/// For [`Pieces::parse`]: per piece, whether a comment runs into it from the piece before
/// and whether one runs out of it into the next. Only boundaries are recorded, so the size
/// depends on the number of pieces, not of comments.
@@ -142,19 +146,27 @@ fn parse_pieces(data: &[u8], ends: &[usize]) -> Parsed {
start.get_or_insert(at);
operands.push(Object::Null);
}
- b"BI" => match inline_image(data, lx.pos) {
- Ok((dict, img, end)) => {
- lx.pos = end;
- out.ops.push(Op { op: b"BI".to_vec(), operands: Vec::new(), inline: Some((dict, img)), span: start.take().unwrap_or(at)..end });
- operands.clear();
+ b"BI" => {
+ let image = inline_image(data, at, lx.pos);
+ out.ambiguous_images += usize::from(image.ambiguous);
+ let end = image.end;
+ lx.pos = end;
+ match image.image {
+ Some((dict, img)) => {
+ out.ops.push(Op {
+ op: b"BI".to_vec(),
+ operands: Vec::new(),
+ inline: Some((dict, img)),
+ span: start.take().unwrap_or(at)..end,
+ });
+ }
+ None => {
+ out.skipped += end.saturating_sub(at);
+ start = None;
+ }
}
- Err(end) => {
- out.skipped += end.saturating_sub(at);
- lx.pos = end;
- start = None;
- operands.clear();
- }
- },
+ operands.clear();
+ }
_ => {
let s = start.take().unwrap_or(at);
out.ops.push(Op { op: kw.to_vec(), operands: std::mem::take(&mut operands), inline: None, span: s..lx.pos });
@@ -198,11 +210,29 @@ fn comment_edges(data: &[u8], trivia: std::ops::Range<usize>, ends: &[usize], bo
}
}
-/// Read an inline image starting after `BI`: (parameters, data, position after `EI`). `Err` holds
-/// the position after the `EI` (or the end of the stream) of an image whose parameters can't be read.
-fn inline_image(data: &[u8], pos: usize) -> Result<(Dict, Vec<u8>, usize), usize> {
+/// An inline image as [`inline_image`] reads it.
+struct Inline {
+ /// Its parameters and data; `None` when the parameters can't be read.
+ image: Option<(Dict, Vec<u8>)>,
+ /// The position after its `EI` (or the end of the stream).
+ end: usize,
+ /// The renderer's tokenizer reads no image here, so `end` is this parser's guess.
+ ambiguous: bool,
+}
+
+/// Read the inline image whose `BI` keyword starts at `bi` (its parameters start at `pos`).
+///
+/// Filtered image data has no length, and `EI` can occur inside it, so where it ends is a
+/// heuristic choice among `EI` candidates. The renderer's choice decides which operators the
+/// page draws after the image, and redaction must see the same ones, so the end is taken from
+/// the renderer's tokenizer (hayro-syntax) rather than worked out here by another rule. Only
+/// when that tokenizer reads no image does this parser fall back to its own rules, and the
+/// image is marked ambiguous.
+fn inline_image(data: &[u8], bi: usize, pos: usize) -> Inline {
let mut lx = Lexer::new(data, pos);
let mut dict = Dict::new();
+ let mut readable = true;
+ let mut stop = pos;
loop {
lx.skip_ws();
if lx.eat_keyword(b"ID") {
@@ -216,22 +246,68 @@ fn inline_image(data: &[u8], pos: usize) -> Result<(Dict, Vec<u8>, usize), usize
let Some((k, v)) = entry else {
// A stream that ends inside the parameters is cut short, not unreadable: keep what was read.
if at >= data.len() {
- return Ok((dict, Vec::new(), data.len()));
+ return Inline { image: Some((dict, Vec::new())), end: data.len(), ambiguous: false };
}
- // Without an `EI` after it, the image runs to the end of the stream.
- return Err(end_of_image(data, at, b"").map_or(data.len(), |(_, end)| end));
+ readable = false;
+ stop = at;
+ break;
};
dict.set(k, v);
}
+ if let Some((start, end_data, end)) = renderer_image_end(data, bi) {
+ // Where the renderer ends the data at an `EI` found by its heuristic, one whitespace byte
+ // before that `EI` separates it from the data.
+ let mut samples = data.get(start..end_data).unwrap_or_default();
+ if data.get(end_data..).is_some_and(|rest| rest.starts_with(b"EI"))
+ && let Some((last, rest)) = samples.split_last()
+ && is_ws(*last)
+ {
+ samples = rest;
+ }
+ return Inline { image: readable.then(|| (dict, samples.to_vec())), end, ambiguous: false };
+ }
+ if !readable {
+ // Without an `EI` after it, the image runs to the end of the stream.
+ return Inline { image: None, end: end_of_image(data, stop, b"").map_or(data.len(), |(_, end)| end), ambiguous: true };
+ }
// One whitespace byte separates ID from the data.
let begin = (lx.pos + 1).min(data.len());
let end = unfiltered_image_end(data, begin, &dict)
.or_else(|| declared_image_end(data, begin, &dict))
.or_else(|| image_data_end(data, begin, filter_eod(&dict)));
- Ok(match end {
- Some((end_data, end)) => (dict, data[begin..end_data].to_vec(), end),
- None => (dict, data[begin..].to_vec(), data.len()),
- })
+ let (image, end) = match end {
+ Some((end_data, end)) => (data.get(begin..end_data).unwrap_or_default().to_vec(), end),
+ None => (data.get(begin..).unwrap_or_default().to_vec(), data.len()),
+ };
+ Inline { image: Some((dict, image)), end, ambiguous: true }
+}
+
+/// Where the renderer's tokenizer ends the inline image whose `BI` starts at `bi`: the start and
+/// end of its data and the position after its `EI`. `None` when it reads no image there (its
+/// parameters don't read, or no `EI` passes its checks).
+fn renderer_image_end(data: &[u8], bi: usize) -> Option<(usize, usize, usize)> {
+ use hayro_syntax::content::TypedIter;
+ use hayro_syntax::content::ops::{InlineImage, TypedInstruction};
+ let tail = data.get(bi..)?;
+ let mut iter = TypedIter::new(tail);
+ let (start, len) = match iter.next()? {
+ TypedInstruction::InlineImage(InlineImage(stream)) => match stream.raw_data() {
+ // The data is a slice of `tail`: its offset is where it starts.
+ std::borrow::Cow::Borrowed(samples) => ((samples.as_ptr() as usize).checked_sub(tail.as_ptr() as usize)?, samples.len()),
+ std::borrow::Cow::Owned(_) => return None,
+ },
+ _ => return None,
+ };
+ let end_data = start.checked_add(len)?;
+ // `committed` is past the whitespace after `EI`; the image ends at the `EI`.
+ let mut end = iter.committed();
+ while end > end_data && tail.get(end - 1).is_some_and(|b| is_ws(*b)) {
+ end -= 1;
+ }
+ if end < end_data.checked_add(2)? || tail.get(end - 2..end) != Some(b"EI") {
+ return None;
+ }
+ Some((bi.checked_add(start)?, bi.checked_add(end_data)?, bi.checked_add(end)?))
}
/// The end-of-data marker (`>` for ASCIIHex, `~>` for ASCII85) of the outer stream filter, if any.
diff --git a/crates/content/src/tests.rs b/crates/content/src/tests.rs
index 094a0665d..c9abef834 100644
--- a/crates/content/src/tests.rs
+++ b/crates/content/src/tests.rs
@@ -102,10 +102,11 @@ fn unfiltered_inline_masks_default_to_one_bit_and_indexed_images_have_one_compon
let parsed = inline_pixels(parameters.as_bytes(), b" EI ");
assert_eq!(parsed.ops[1].inline.as_ref().unwrap().1, b" EI ");
assert_eq!(parsed.ops.len(), 3);
- // Indexed samples permit at most 8 bits, even though device spaces permit 16.
+ // Indexed samples permit at most 8 bits, even though device spaces permit 16, so the
+ // length is unknown, and the renderer takes the second `EI`.
let invalid = parameters.replace("/W 4", "/W 2").replace("/BPC 8", "/BPC 16");
let parsed = inline_pixels(invalid.as_bytes(), b" EI ");
- assert!(parsed.ops[1].inline.as_ref().unwrap().1.is_empty());
+ assert_eq!(parsed.ops[1].inline.as_ref().unwrap().1, b" EI ");
}
}
@@ -127,7 +128,7 @@ fn unfiltered_inline_image_terminator_must_follow_its_samples() {
}
#[test]
-fn filtered_unknown_and_damaged_inline_images_keep_the_existing_fallback() {
+fn filtered_unknown_and_damaged_inline_images_end_where_the_renderer_ends_them() {
for parameters in [
b"/W 4 /H 1 /BPC 8 /CS /G /F /A85".as_slice(),
b"/W 4 /H 1 /BPC 8 /CS /ResourceColor",
@@ -142,12 +143,20 @@ fn filtered_unknown_and_damaged_inline_images_keep_the_existing_fallback() {
b"/W 9223372036854775807 /H 9223372036854775807 /BPC 16 /CS /CMYK",
b"/W 9223372036854775807 /H 2 /BPC 8 /CS /G",
] {
+ // What follows the first `EI` (`!!~>`) does not read as content, so the renderer takes
+ // the later one.
let parsed = inline_pixels(parameters, b"! EI !!~>");
- assert_eq!(parsed.ops[1].inline.as_ref().unwrap().1, b"!", "{}", String::from_utf8_lossy(parameters));
+ let label = String::from_utf8_lossy(parameters);
+ assert_eq!(parsed.ops[1].inline.as_ref().unwrap().1, b"! EI !!~>", "{label}");
+ assert_eq!(parsed.ops.iter().map(|op| op.op.as_slice()).collect::<Vec<_>>(), [b"q".as_slice(), b"BI", b"Q"], "{label}");
+ assert_eq!(parsed.ambiguous_images, 0, "{label}");
}
- // A short payload still uses the tolerant recovery, including when there is no EI.
- for src in [b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc\nEI Q".as_slice(), b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc"] {
- assert_eq!(parse(src).ops[0].inline.as_ref().unwrap().1, b"abc");
+ // A short payload is read whole; without an `EI`, the renderer reads no image and this
+ // parser's end is a guess.
+ for (src, ambiguous) in [(b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc\nEI Q".as_slice(), 0), (b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc", 1)] {
+ let parsed = parse(src);
+ assert_eq!(parsed.ops[0].inline.as_ref().unwrap().1, b"abc");
+ assert_eq!(parsed.ambiguous_images, ambiguous);
}
}
@@ -459,3 +468,38 @@ fn ascii85_inline_image_does_not_terminate_at_gt_ei_inside_payload() {
assert_eq!(img, b"!!!!>EI !!~>");
}
}
+
+/// The operators the renderer's tokenizer reads from `data`.
+fn renderer_operators(data: &[u8]) -> Vec<Vec<u8>> {
+ let mut iter = hayro_syntax::content::UntypedIter::new(data);
+ let mut out = Vec::new();
+ while let Some(instruction) = iter.next() {
+ out.push(instruction.operator.as_ref().to_vec());
+ }
+ out
+}
+
+/// Inline images end where the renderer ends them, so both read the same operators after one:
+/// an `EI` without whitespace before it in the data, upper-case text ending in "EI" after the
+/// image, and an `EI` inside compressed bytes (#3579).
+#[test]
+fn inline_images_end_where_the_renderer_ends_them() {
+ let flate: Vec<u8> = (0..FLATE_WITH_EI.len()).step_by(2).map(|i| u8::from_str_radix(&FLATE_WITH_EI[i..i + 2], 16).unwrap()).collect();
+ let mut stored = b"q BI /W 64 /H 1 /BPC 8 /CS /G /F /Fl ID ".to_vec();
+ stored.extend_from_slice(&flate);
+ stored.extend_from_slice(b"\nEI Q BT /F1 24 Tf 72 200 Td (AFTER) Tj ET");
+ let fixtures: [&[u8]; 6] = [
+ b"BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7FEI 1 0 0 1 200 0 cm EI BT /F1 10 Tf 10 100 Td (SECRET) Tj ET",
+ b"BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7F> EI BT /F1 10 Tf 10 100 Td (ZWEI) Tj (EIN FREI BEI) Tj ET",
+ b"q BI /W 2 /H 1 /CS /G /BPC 8 /F /AHx ID 7F7F> EI Q BT (DREI) Tj ET BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 00> EI",
+ b"BI /W 4 /H 1 /BPC 8 /CS /G /F /A85 ID ! EI !!~>\nEI Q",
+ b"q BI /W 4 /H 1 /BPC 8 /CS /G ID EI \nEI Q",
+ &stored,
+ ];
+ for data in fixtures {
+ let parsed = parse(data);
+ let ours: Vec<Vec<u8>> = parsed.ops.iter().map(|op| op.op.clone()).collect();
+ assert_eq!(ours, renderer_operators(data), "{}", String::from_utf8_lossy(data));
+ assert_eq!((parsed.skipped, parsed.ambiguous_images), (0, 0), "{}", String::from_utf8_lossy(data));
+ }
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 8937cf678..3012a1f3f 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2320,6 +2320,30 @@ fn the_renderer_check_refuses_text_still_shown_under_a_mark() {
assert!(refused(&cos), "the labelled input stream was not checked");
}
+/// Inline image data `7FEI 1 0 0 1 200 0 cm` holds an `EI` the renderer ends the image at, so it
+/// runs the `cm` and shows SECRET 200 pt to the right. Redaction reads the image the same way, so
+/// a mark drawn over the word as shown takes it out of the file.
+#[test]
+fn text_after_an_inline_image_is_redacted_where_the_page_shows_it() {
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let page = one_line_page(
+ "/Font << /F1 4 0 R >>",
+ "BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7FEI 1 0 0 1 200 0 cm EI BT /F1 10 Tf 10 100 Td (SECRET) Tj ET",
+ );
+ let id = s.open("inline.pdf", None, Arc::new(page), None).unwrap();
+ mark_shown_text(&mut s, id, "SECRET");
+ s.apply(id, Edit::ApplyRedactions { pages: None }).unwrap();
+ assert!(!page_texts(&s, id).concat().contains("SECRET"));
+ let saved = s.save_bytes(id).unwrap();
+ let held = |d: &[u8]| d.windows(6).any(|w| w == b"SECRET");
+ assert!(!held(&saved), "the saved file holds the redacted word");
+ let reopened = pdfcraft_cos::Document::open(saved).unwrap();
+ assert!(
+ !reopened.scan_objects().any(|(_, o)| matches!(&*o, pdfcraft_cos::Object::Stream(st) if st.decoded().is_ok_and(|d| held(&d)))),
+ "a saved stream holds the redacted word"
+ );
+}
+
/// A word whose font and size an ExtGState /Font entry (`gs`) sets is placed where the renderer
/// draws it, so a mark drawn over it as displayed takes it out of the file.
#[test]
diff --git a/crates/redact/src/interp.rs b/crates/redact/src/interp.rs
index fca3a1da8..b4186fd4e 100644
--- a/crates/redact/src/interp.rs
+++ b/crates/redact/src/interp.rs
@@ -74,6 +74,10 @@ pub(crate) struct Output {
/// Apply mode met vertical-writing text (which it cannot remove) while a redaction region was
/// in force: the operation must fail closed rather than leave that text under the mark.
pub vertical: bool,
+ /// The content holds an inline image the renderer reads no image for
+ /// ([`pdfcraft_content::Parsed::ambiguous_images`]): what this scope placed after it may not
+ /// be what the page shows, so a redaction must not trust it.
+ pub ambiguous: bool,
pub tag_changes: Vec<(ObjRef, ObjRef, HashSet<i64>, HashSet<i64>)>,
pub error: Option<CosError>,
}
@@ -789,6 +793,7 @@ fn process_from(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<u8>],
// next. Parse them joined, then give each operator back to the piece its keyword is in.
let joined = Pieces::join(streams);
let mut parsed = joined.parse();
+ out.ambiguous = parsed.ambiguous_images > 0;
// A rewritten piece loses its comments, so keep where they began and ended: a comment that
// ran on into the next piece still hides that piece's first line.
let comment_edges = joined.comment_edges(&parsed);
@@ -1293,6 +1298,7 @@ fn xobject(
scope.fonts = saved_fonts;
out.residue += inner.residue;
out.vertical |= inner.vertical;
+ out.ambiguous |= inner.ambiguous;
out.doomed.extend_from_slice(&inner.doomed);
out.retired_properties.extend(inner.retired_properties);
out.tag_changes.extend(inner.tag_changes);
diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs
index 97d5bcd9f..e67b373a1 100644
--- a/crates/redact/src/lib.rs
+++ b/crates/redact/src/lib.rs
@@ -411,6 +411,12 @@ pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Reda
if out.vertical {
return Err(RedactError::VerticalText(pi + 1));
}
+ // An inline image the renderer reads no image for (no `EI` it accepts, or parameters it
+ // can't read): where the page's operators resume after it is a guess, so neither removal
+ // nor the verify pass can be trusted on this page.
+ if out.ambiguous {
+ return Err(RedactError::Unreadable(pi + 1));
+ }
doomed_xobjects.extend_from_slice(&out.doomed);
retired_properties.extend(out.retired_properties);
let mut new_list = list.clone();
diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs
index ebc95f451..e35d4f907 100644
--- a/crates/redact/src/tests.rs
+++ b/crates/redact/src/tests.rs
@@ -2462,6 +2462,7 @@ fn unused_descriptions_in_shared_or_inherited_resources_are_retired() {
}
mod descriptions;
+mod inline_images;
mod limits;
mod property_retirement;
mod surviving_references;
diff --git a/crates/redact/src/tests/inline_images.rs b/crates/redact/src/tests/inline_images.rs
new file mode 100644
index 000000000..77fd4dc2d
--- /dev/null
+++ b/crates/redact/src/tests/inline_images.rs
@@ -0,0 +1,34 @@
+//! Inline image data ends where the renderer ends it, so the operators after it are the ones the
+//! page draws.
+
+use super::*;
+
+/// The image data `7FEI 1 0 0 1 200 0 cm` holds an `EI` straight after `7F`. The renderer ends
+/// the image there (text follows, so what comes after reads as content) and runs the `cm`,
+/// drawing SECRET at x = 210, not 10.
+const FAKE_EI: &[u8] = b"BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7FEI 1 0 0 1 200 0 cm EI BT /F1 10 Tf 10 100 Td (SECRET) Tj ET";
+
+#[test]
+fn text_after_an_inline_image_is_redacted_where_the_renderer_draws_it() {
+ let mut doc = one_page(FAKE_EI, "", vec![]);
+ assert_eq!(under(&mut doc, 0, &[[5.0, 95.0, 45.0, 110.0]]), 0, "nothing is drawn at x = 10");
+ mark(&mut doc, 0, &[[205.0, 95.0, 245.0, 110.0]], "");
+ assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
+ assert!(!content(&doc, 0).contains("SECRET"));
+}
+
+#[test]
+fn an_inline_image_with_one_possible_end_is_redacted() {
+ let mut doc = one_page(b"BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7F> EI BT /F1 10 Tf 10 100 Td (SECRET) Tj ET", "", vec![]);
+ mark(&mut doc, 0, &[[5.0, 95.0, 45.0, 110.0]], "");
+ assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
+ assert!(!content(&doc, 0).contains("SECRET"));
+}
+
+/// Without an `EI` the renderer accepts, where the operators resume is a guess: refused.
+#[test]
+fn a_page_whose_inline_image_the_renderer_cannot_end_is_refused() {
+ let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (SECRET) Tj ET BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7F", "", vec![]);
+ mark(&mut doc, 0, &[[5.0, 95.0, 45.0, 110.0]], "");
+ assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(1)));
+}