diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 7c0aa4a74b..f3493555c9 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -71,9 +71,157 @@ fn export(s: &mut Session, p: Value) -> (Vec, Vec) { (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 { + let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::().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::().ok()?; + let count = words.next()?.parse::().ok()?; + for index in 0..count { + let at = words.next()?.parse::().ok()?; + let entry_generation = words.next()?.parse::().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 { + 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::>()[..] { + [n, "endobj"] => n.parse::().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::().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<>\nendobj\n6 0 obj\n<>\nstream\nq/BMx/S/Transparency\nendstream\nendobj\ntrailer\n<>\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + assert_eq!(transparency(b"<>>>>>"), vec!["blend modes", "opacity"]); + // A `(` in image data starts no string, and nested and escaped parentheses end where the + // string does. + let pdf = b"<>\nstream\n(\x00(\nendstream\n<>\n<>"; + 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<>\nstream\nendstream (/BM\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let pdf = b"1 0 obj\n<>\nstream\nabc\r\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + let pdf = b"1 0 obj\n<>\nstream\nabcendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"; + 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<>>>\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<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\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<>\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<>\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<>\nendobj\n"); + let pages_at = pdf.len(); + pdf.extend_from_slice(b"4 0 obj\n<>\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<>\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<>"; + assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err()); + for length in [2, 20, 999, usize::MAX] { + let pdf = format!("1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"); + 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::().map(String::as_str)); + assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); + } +}