mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Tests: the PDF 1.3 transparency check reads dictionaries only
pdf_1_3_flattens_all_transparency_and_looks_the_same failed now and then because its transparency check searched the whole file for `/BM`. The file ID, written in the trailer and the XMP stream, is base64 that changes with the export time, so some exports had an ID that spells `/BM` and the check reported a blend mode in a flat file. The check now leaves out literal strings and stream data. A stream is found only by the whole `stream` keyword, not a name such as `/stream`, and its data is skipped by the stream dictionary's own `/Length`, read from the outermost dictionary and from its object when it is indirect. A length that does not end at `endstream`, or a stream with no `endstream`, fails the check. Every dictionary key it looked for is still checked. A new test covers an ID and an XMP packet that spell the keys, nested and escaped parentheses, `endstream` inside stream data, nested and indirect lengths, and wrong lengths. The helper comes from #10537.
This commit is contained in:
1 parent
9ad67bd067
commit
937817609d
1 file changed
+213
-2
@@ -71,9 +71,157 @@ fn export(s: &mut Session, p: Value) -> (Vec<u8>, Vec<String>) {
|
||||
(bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect())
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries.
|
||||
/// Whether `b` ends a PDF token: white space or a delimiter.
|
||||
fn ends_token(b: u8) -> bool {
|
||||
b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b)
|
||||
}
|
||||
|
||||
/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the
|
||||
/// `startxref` at `startxref` and following `/Prev`.
|
||||
fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option<usize> {
|
||||
let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::<usize>().ok()?;
|
||||
let mut visited = vec![];
|
||||
loop {
|
||||
if visited.contains(&offset) {
|
||||
return None;
|
||||
}
|
||||
visited.push(offset);
|
||||
let table = String::from_utf8_lossy(pdf.get(offset..)?);
|
||||
let mut words = table.split_ascii_whitespace();
|
||||
if words.next()? != "xref" {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
let first = words.next()?;
|
||||
if first == "trailer" {
|
||||
break;
|
||||
}
|
||||
let first = first.parse::<usize>().ok()?;
|
||||
let count = words.next()?.parse::<usize>().ok()?;
|
||||
for index in 0..count {
|
||||
let at = words.next()?.parse::<usize>().ok()?;
|
||||
let entry_generation = words.next()?.parse::<usize>().ok()?;
|
||||
let status = words.next()?;
|
||||
if first.checked_add(index)? == number {
|
||||
return (status == "n" && entry_generation == generation).then_some(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
let trailer = table.split_once("trailer")?.1.split_once(">>")?.0;
|
||||
let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty());
|
||||
words.find(|&w| w == "Prev")?;
|
||||
offset = words.next()?.parse().ok()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary
|
||||
/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None`
|
||||
/// when it is missing or cannot be read.
|
||||
fn stream_length(text: &[u8], pdf: &[u8]) -> Option<usize> {
|
||||
let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3);
|
||||
let dict = &text[from..];
|
||||
let mut i = dict.windows(2).position(|w| w == b"<<")? + 2;
|
||||
let mut depth = 1usize;
|
||||
let mut length = None;
|
||||
while i < dict.len() && depth > 0 {
|
||||
let rest = &dict[i..];
|
||||
if rest.starts_with(b"<<") {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
} else if rest.starts_with(b">>") {
|
||||
depth -= 1;
|
||||
i += 2;
|
||||
} else if rest[0] == b'<' {
|
||||
// A hex string.
|
||||
i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1);
|
||||
} else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) {
|
||||
let value = String::from_utf8_lossy(&rest[7..]);
|
||||
let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect();
|
||||
length = match words[..] {
|
||||
// `n g R` is an indirect length: the integer in object `n g`.
|
||||
[n, g, "R", ..] => {
|
||||
let header = format!("{n} {g} obj");
|
||||
let read_length = |at: usize| {
|
||||
let body = String::from_utf8_lossy(&pdf[at + header.len()..]);
|
||||
match body.split_ascii_whitespace().take(2).collect::<Vec<_>>()[..] {
|
||||
[n, "endobj"] => n.parse::<usize>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") {
|
||||
let at =
|
||||
xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref");
|
||||
let object = pdf.get(at..).expect("stream /Length xref offset is outside the file");
|
||||
assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object");
|
||||
read_length(at)
|
||||
} else {
|
||||
pdf.windows(header.len())
|
||||
.enumerate()
|
||||
// An object header starts a line, and the length object holds one integer.
|
||||
.filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n')))
|
||||
.find_map(|(at, _)| read_length(at))
|
||||
}
|
||||
}
|
||||
[n, ..] => n.parse::<usize>().ok(),
|
||||
[] => None,
|
||||
};
|
||||
i += 7;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
length
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out:
|
||||
/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time
|
||||
/// and can spell `/BM`.
|
||||
fn transparency(pdf: &[u8]) -> Vec<&'static str> {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
let mut text = Vec::with_capacity(pdf.len());
|
||||
let mut i = 0;
|
||||
while i < pdf.len() {
|
||||
let rest = &pdf[i..];
|
||||
// A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name.
|
||||
let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>';
|
||||
if keyword_start && rest.starts_with(b"endstream") {
|
||||
text.extend_from_slice(b"endstream");
|
||||
i += b"endstream".len();
|
||||
} else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) {
|
||||
// Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to
|
||||
// `endstream`); its bytes are not PDF syntax.
|
||||
let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 };
|
||||
i = match stream_length(&text, pdf) {
|
||||
Some(n) => {
|
||||
let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream");
|
||||
while matches!(pdf.get(end), Some(b'\r' | b'\n')) {
|
||||
end += 1;
|
||||
}
|
||||
assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream");
|
||||
end
|
||||
}
|
||||
None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"),
|
||||
};
|
||||
} else if rest[0] == b'(' {
|
||||
// A literal string: balanced parentheses, with `\` escaping the next byte.
|
||||
let mut depth = 0usize;
|
||||
while i < pdf.len() {
|
||||
match pdf[i] {
|
||||
b'\\' => i += 1,
|
||||
b'(' => depth += 1,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
text.push(rest[0]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&text);
|
||||
let mut found = vec![];
|
||||
for (what, there) in [
|
||||
("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")),
|
||||
@@ -193,3 +341,66 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() {
|
||||
s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check
|
||||
/// reads the file's dictionaries only, not its strings or its XMP packet.
|
||||
#[test]
|
||||
fn the_transparency_check_skips_strings_and_metadata() {
|
||||
let pdf = b"%PDF-1.3\n5 0 obj\n<</Title(a/BM/SMask/CA 0.5)>>\nendobj\n6 0 obj\n<</Type/Metadata>>\nstream\n<?xpacket begin=\"\"?><x>q/BMx/S/Transparency</x><?xpacket end=\"r\"?>\nendstream\nendobj\ntrailer\n<</ID[(hIX/BMcE)(hIX/BMcE)]>>\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
assert_eq!(transparency(b"<</ExtGState<</G<</BM/Multiply/CA 0.5>>>>>>"), vec!["blend modes", "opacity"]);
|
||||
// A `(` in image data starts no string, and nested and escaped parentheses end where the
|
||||
// string does.
|
||||
let pdf = b"<</Length 3>>\nstream\n(\x00(\nendstream\n<</T(a(b)c\\)d)/SMask 9 0 R>>\n<</S/Transparency>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]);
|
||||
// Stream data is skipped by its length, even when it holds `endstream` itself.
|
||||
let pdf = b"1 0 obj\n<</Length 15>>\nstream\nendstream (/BM\nendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 13>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabc\r\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabcendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// Only the stream dictionary's own `/Length` counts, not one in a nested dictionary.
|
||||
let pdf = b"1 0 obj\n<</Length 4/DecodeParms<</Length 1>>>>\nstream\n/BM \nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
// `stream` inside a name is not the keyword.
|
||||
let pdf = b"1 0 obj\n<</Type/Upstream\n/BM/Multiply>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Type/stream\n/SMask 9 0 R>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// An indirect length is read from its object, so `endstream` in the data does not end it.
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let payload = b"2 0 obj\n13\nendobj\nendstream /BM";
|
||||
let mut pdf = b"%PDF-1.3\n".to_vec();
|
||||
let stream_at = pdf.len();
|
||||
pdf.extend_from_slice(b"1 0 obj\n<</Length 2 0 R>>\nstream\n");
|
||||
pdf.extend_from_slice(payload);
|
||||
pdf.extend_from_slice(b"\nendstream\nendobj\n");
|
||||
let length_at = pdf.len();
|
||||
pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes());
|
||||
let catalog_at = pdf.len();
|
||||
pdf.extend_from_slice(b"3 0 obj\n<</Type/Catalog/Pages 4 0 R>>\nendobj\n");
|
||||
let pages_at = pdf.len();
|
||||
pdf.extend_from_slice(b"4 0 obj\n<</Type/Pages/Kids[]/Count 0>>\nendobj\n");
|
||||
let xref_at = pdf.len();
|
||||
pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n");
|
||||
for at in [stream_at, length_at, catalog_at, pages_at] {
|
||||
pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<</Size 5/Root 3 0 R>>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes());
|
||||
assert_eq!(transparency(&pdf), Vec::<&str>::new());
|
||||
// A stream with no length and no `endstream` fails rather than hiding the rest of the file.
|
||||
let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<</SMask 9 0 R>>";
|
||||
assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err());
|
||||
for length in [2, 20, 999, usize::MAX] {
|
||||
let pdf = format!("1 0 obj\n<</Length {length}>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R/BM/Multiply>>");
|
||||
let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic");
|
||||
let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::<String>().map(String::as_str));
|
||||
assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user