diff --git a/crates/automation/tests/it/hostile_args.rs b/crates/automation/tests/it/hostile_args.rs index fe30268b39..c772d8ffa0 100644 --- a/crates/automation/tests/it/hostile_args.rs +++ b/crates/automation/tests/it/hostile_args.rs @@ -563,6 +563,99 @@ fn no_tool_panics_when_the_viewer_sees_fewer_pages_than_the_file_has() { assert!(failures.is_empty(), "{} failure(s); the first is: {}", failures.len(), failures.first().map_or("", String::as_str)); } +/// Which structure of the form refers to itself: the page tree, the named destinations, or the +/// name tree. +#[derive(Clone, Copy, Debug, PartialEq)] +enum CyclicXfa { + Pages, + Dests, + Names, +} + +/// A dynamic XFA form (#9027) in which `cyclic` refers to itself: the relayout run on open used +/// to walk that cycle forever. The other structures are normal. The layout fails with a note and +/// the document opens anyway; the point is that it answers at all. +fn cyclic_xfa_pdf(cyclic: CyclicXfa) -> Vec { + let xdp = pdfcraft_xfa::fixtures::template(1); + let (page_kids, dests_key, names_key) = match cyclic { + CyclicXfa::Pages => ("3 0 R 2 0 R", "", ""), + CyclicXfa::Dests => ("3 0 R", " /Dests 6 0 R", ""), + CyclicXfa::Names => ("3 0 R", "", " /Names 7 0 R"), + }; + let objs: Vec<(u32, String)> = vec![ + (1, format!("<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >>{dests_key}{names_key} >>")), + (2, format!("<< /Type /Pages /Kids [{page_kids}] /Count 1 >>")), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>".into()), + (4, "<< /Length 44 >>\nstream\nBT /F1 12 Tf 72 700 Td (Please wait...) Tj ET\nendstream".into()), + (5, format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len())), + (6, "<< /cyc 8 0 R >>".into()), + (7, "<< /Dests 9 0 R >>".into()), + (8, "<< /D 8 0 R >>".into()), + (9, "<< /Names [(end) 3 0 R] /Kids [9 0 R] >>".into()), + ]; + let size = 10; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = vec![None; size]; + for (num, body) in &objs { + if let Some(slot) = offsets.get_mut(*num as usize) { + *slot = Some(out.len()); + } + out.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes()); + for offset in offsets.iter().skip(1) { + out.extend_from_slice( + match offset { + Some(o) => format!("{o:010} 00000 n \n"), + None => "0000000000 65535 f \n".to_string(), + } + .as_bytes(), + ); + } + out.extend_from_slice(format!("trailer << /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes()); + out +} + +#[test] +fn no_tool_hangs_on_a_cyclic_xfa_form() { + // #9027: a dynamic form whose page tree, destination, or name tree refers to itself used to + // make the relayout run on open walk the cycle forever. Opening must answer (the layout + // fails with a note and the document opens anyway), and every tool must answer with a + // result or an error. + for cyclic in [CyclicXfa::Pages, CyclicXfa::Dests, CyclicXfa::Names] { + let root = tmp(&format!("cyclic-xfa-{cyclic:?}")); + let pdf = cyclic_xfa_pdf(cyclic); + let mut failures = Vec::new(); + for def in tools() { + // Written again for every tool: tools that save write to `in.pdf`, the plausible path. + std::fs::write(root.join("in.pdf"), &pdf).expect("fixture"); + let mut a = Automation::new().with_root(&root).expect("root"); + let opened = a.call("doc_open", &json!({ "path": "in.pdf" })).expect("open the cyclic form"); + let doc = opened + .into_iter() + .find_map(|c| match c { + pdfcraft_automation::Content::Json(v) => v["doc"].as_u64(), + pdfcraft_automation::Content::Png { .. } => None, + }) + .expect("the opened document has an id"); + if let Err(e) = guarded(&mut a, def.name, &Value::Object(plausible_with(&def, Some(doc)))) { + failures.push(e); + } + } + for f in &failures { + eprintln!(" {f}"); + } + let _ = std::fs::remove_dir_all(&root); + assert!( + failures.is_empty(), + "on a cyclic {cyclic:?} form: {} failure(s); the first is: {}", + failures.len(), + failures.first().map_or("", String::as_str) + ); + } +} + /// `source_widget` is 1-based and counted against the source's widgets: no value of it but the /// source's one widget (or null, which is the default), nor the key without `source_field`, /// panics or adds a field. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 43d0a248ce..10f0e8cb02 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9854,6 +9854,106 @@ fn xfa_text_growth_then_a_script_relayout_both_add_pages() { saves_and_reopens(&mut s, id, 3); } +/// Bookmarks and named destinations that name a dynamic form's page follow the pages a +/// re-layout replaces them with: the placeholder page is laid out onto a real one, and +/// typing into a growable field lays the form out onto a second; each time, the bookmarks +/// and the named destinations resolve to the first of the pages the layout wrote, not the +/// page it replaced. +#[test] +fn xfa_relayout_keeps_bookmarks_and_named_destinations_on_the_pages_it_writes() { + let before = r#""#; + let template = pdfcraft_xfa::fixtures::presence_growth_template(false, before, "", ""); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("dests.pdf", None, Arc::new(pdfcraft_xfa::fixtures::dests_shell(&template)), None).unwrap(); + assert_eq!(s.get(id).unwrap().info.pages.len(), 1, "{:?}", s.take_js_output(id).errors); + let pages = dest_pages(&s, id); + assert_eq!(pages, vec![Some(0); 4], "the bookmarks and named destinations are on the first page the layout wrote"); + let notes: String = (1..=60).map(|i| format!("line {i}\n")).collect(); + s.apply(id, Edit::SetFieldValue { name: "notes".into(), value: FieldValue::Text(notes) }).unwrap(); + assert_eq!(s.get(id).unwrap().info.pages.len(), 2); + let pages = dest_pages(&s, id); + assert_eq!(pages, vec![Some(0); 4], "the bookmarks and named destinations follow the first page to the second layout"); + saves_and_reopens(&mut s, id, 2); +} + +/// The position, in the page tree, of the page each of the document's bookmarks and named +/// destinations names: the `/Dests` entry, the `/Names` tree entry, and the two `/Outlines` +/// items (one with a `/Dest`, one with a `GoTo` action). `None` when one names a page the +/// page tree does not hold. +fn dest_pages(s: &Session, id: DocId) -> Vec> { + use pdfcraft_cos::{ObjRef, Object}; + let doc = s.get(id).unwrap(); + let cos = pdfcraft_cos::Document::open(doc.bytes.clone()).unwrap(); + let catalog = cos.get(cos.root().unwrap()).as_dict().cloned().unwrap(); + let pages = catalog + .get(b"Pages") + .and_then(Object::as_ref) + .map(|r| cos.get(r)) + .and_then(|p| p.as_dict().and_then(|d| d.get(b"Kids")).map(|k| cos.resolve(k))) + .and_then(|k| k.as_array().cloned()) + .unwrap_or_default(); + let pages: Vec = pages.iter().filter_map(Object::as_ref).collect(); + let pos = |v: &Object| { + let resolved = cos.resolve(v); + let page_ref = match resolved.as_array() { + Some(arr) => arr.first().and_then(Object::as_ref), + None => Object::as_ref(&resolved), + }; + page_ref.and_then(|p| pages.iter().position(|x| *x == p)) + }; + let mut out = Vec::new(); + if let Some(dests) = catalog.get(b"Dests").map(|d| cos.resolve(d)).and_then(|d| d.as_dict().cloned()) { + for (_, v) in dests.iter() { + out.push(pos(v)); + } + } + if let Some(names) = catalog.get(b"Names").map(|n| cos.resolve(n)).and_then(|n| n.as_dict().cloned()) { + for (cat, node) in names.iter() { + if cat.as_slice() == b"Dests" || cat.as_slice() == b"Pages" { + let Some(entries) = + cos.resolve(node).as_dict().and_then(|d| d.get(b"Names")).map(|n| cos.resolve(n)).and_then(|n| n.as_array().cloned()) + else { + continue; + }; + for i in (0..entries.len() / 2 * 2).step_by(2) { + if let Some(v) = entries.get(i + 1) { + out.push(pos(v)); + } + } + } + } + } + let Some(first) = + catalog.get(b"Outlines").map(|o| cos.resolve(o)).and_then(|o| o.as_dict().and_then(|d| d.get(b"First")).and_then(Object::as_ref)) + else { + return out; + }; + let mut stack = vec![first]; + while let Some(r) = stack.pop() { + let Some(d) = cos.get(r).as_dict().cloned() else { + continue; + }; + if let Some(dest) = d.get(b"Dest") { + out.push(pos(dest)); + } + if let Some(a) = d.get(b"A") + && cos.resolve(a).as_dict().is_some_and(|d| d.name(b"S") == Some(b"GoTo")) + && let Some(dest) = cos.resolve(a).as_dict().and_then(|d| d.get(b"D")) + { + out.push(pos(dest)); + } + if let Some(next) = d.get(b"Next").and_then(Object::as_ref) { + stack.push(next); + } + if let Some(kids) = d.get(b"Kids").map(|k| cos.resolve(k)).and_then(|k| k.as_array().cloned()) { + for k in kids.iter().filter_map(Object::as_ref).rev() { + stack.push(k); + } + } + } + out +} + #[test] fn xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets() { for fixed in [false, true] { diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index fb7d2228b8..f1506cbf65 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -987,6 +987,30 @@ pub fn shell(xdp: &str) -> Vec { assemble(objs) } +/// [`shell`] with bookmarks and named destinations that name the placeholder page: a +/// `/Outlines` item with a `/Dest`, one with a `GoTo` action, a `/Dests` entry, and a +/// `/Names` tree entry, all at the page. +pub fn dests_shell(xdp: &str) -> Vec { + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >> /Outlines 6 0 R /Dests 7 0 R /Names 8 0 R >>" + .to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>".to_vec(), + b"<< /Length 44 >>\nstream\nBT /F1 12 Tf 72 700 Td (Please wait...) Tj ET\nendstream".to_vec(), + format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(), + b"<< /Type /Outlines /Count 2 /First 9 0 R /Last 10 0 R >>".to_vec(), + b"<< /top 11 0 R >>".to_vec(), + b"<< /Dests 12 0 R >>".to_vec(), + b"<< /Title (Top) /Parent 6 0 R /Next 10 0 R /Dest [3 0 R /Fit] >>".to_vec(), + b"<< /Title (Go) /Parent 6 0 R /Prev 9 0 R /A 13 0 R >>".to_vec(), + b"[3 0 R /Fit]".to_vec(), + b"<< /Names [(end) 14 0 R] >>".to_vec(), + b"<< /S /GoTo /D [3 0 R /Fit] >>".to_vec(), + b"[3 0 R /Fit]".to_vec(), + ]; + assemble(objs) +} + /// [`shell`] with usage rights: the catalog's `/Perms` holds a `/UR3` signature (a stand-in /// dictionary, nothing verifies it), beside `others` (`/DocMDP 6 0 R`, say: object 6 is a /// signature dictionary too). `indirect` puts `/Perms` in an object of its own. diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs index b597cbd85d..74627c5135 100644 --- a/crates/xfa/src/pdf.rs +++ b/crates/xfa/src/pdf.rs @@ -1121,6 +1121,41 @@ fn earlier_images(doc: &Document, pages: ObjRef) -> HashMap<[u8; 32], ObjRef> { out } +/// The pages under `pages`, in reading order: a `/Pages` node's kids, nested ones descended, +/// up to the bound the other page searches here use. A tree that lists a node twice (a cycle) +/// or holds more than [`MAX_PAGES_SEARCHED`] pages is an error: the list would be short, and a +/// destination naming a page it omits would keep a stale reference. +fn page_list(doc: &Document, pages: ObjRef) -> Result, XfaError> { + let mut out = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![pages]; + while let Some(r) = stack.pop() { + if !seen.insert(r) { + return Err(XfaError::Malformed("the document's page tree lists a node twice".into())); + } + let obj = doc.get(r); + let Some(d) = obj.as_dict() else { + continue; + }; + if d.name(b"Type") == Some(b"Pages") || d.get(b"Kids").is_some() { + let kids = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default(); + for k in kids.iter().filter_map(Object::as_ref).rev() { + stack.push(k); + } + } else { + // The bound counts pages accepted, so a tree of exactly the bound followed by an + // empty node is still walked. + if out.len() >= MAX_PAGES_SEARCHED { + return Err(XfaError::TooLarge(format!( + "the document's page tree holds more than {MAX_PAGES_SEARCHED} pages; its bookmarks and named destinations would not be remapped" + ))); + } + out.push(r); + } + } + Ok(out) +} + /// Write laid-out `form` into `doc`: its pages replace the document's, its widgets join the /// AcroForm's fields (a box the file holds a signature for keeps it), and the AcroForm is marked /// laid out. What was written, with any warnings, comes back. @@ -1142,6 +1177,14 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result let kept_widgets = widgets::capture(doc, &catalog, pages_ref); // Pictures embedded by earlier passes, from the pages this pass replaces. let images = earlier_images(doc, pages_ref); + // The pages this pass replaces, in order: bookmarks and named destinations that name them + // are pointed at the replacements, by page position, after the new pages are written. + // A page tree the walk cannot list (a cycle, a node listed twice, past the bound) is + // reported, not fatal: the layout is written and its destinations are left as they were. + let (old_pages, remap_skipped) = match page_list(doc, pages_ref) { + Ok(pages) => (pages, None), + Err(why) => (Vec::new(), Some(why.to_string())), + }; let (signed, taken) = existing_fields(doc, &catalog); let groups = earlier_groups(doc, &catalog); let mut em = Emitter { @@ -1191,12 +1234,25 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result catalog_changed |= register_groups(doc, &mut catalog, &groups, used)?; } let count = kids.len(); + // Bookmarks and named destinations that named the pages above are pointed at the + // replacements, by page position (one the layout dropped goes to the last page). + let new_pages: Vec = kids.iter().filter_map(Object::as_ref).collect(); doc.update_dict(pages_ref, |d| { d.set(b"Type".to_vec(), Object::name("Pages")); d.set(b"Kids".to_vec(), Object::Array(kids)); d.set(b"Count".to_vec(), Object::Int(count as i64)); d.remove(b"Parent"); })?; + let remap_skipped = match remap_destinations(doc, &mut catalog, &old_pages, &new_pages) { + Ok(changed) => { + catalog_changed |= changed; + remap_skipped + } + Err(why) => Some(why.to_string()), + }; + if let Some(why) = remap_skipped { + warnings.push(format!("bookmarks and named destinations were not all pointed at the new pages: {why}")); + } // AcroForm: keep what is there (the XFA packets above all), add our fields and fonts. let acro_ref = catalog.get(b"AcroForm").and_then(Object::as_ref); let mut acro = match catalog.get(b"AcroForm") { @@ -1252,6 +1308,285 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result Ok(Written { pages: count, fields: field_count, warnings, usage_rights }) } +/// Point bookmarks and named destinations at the pages a layout wrote: `old` (what the +/// document had) maps to `new` by page position, and a destination that named a page the +/// layout dropped is pointed at the last page written (the form shrank). A destination that +/// named a page the layout left alone, or a target that is not a page, is left alone. +/// A bookmark list or name tree past [`MAX_PAGES_SEARCHED`], or a destination or name tree +/// that refers to itself, is an error. The bookmark walk is checked before anything is written, +/// but a name or destination walk can fail after earlier ones were written, so the document may +/// be partly remapped: `write_form` reports that as a warning and keeps the layout. +/// Returns whether `catalog` itself changed (a direct `/Dests` or `/Names`). +fn remap_destinations(doc: &mut Document, catalog: &mut Dict, old: &[ObjRef], new: &[ObjRef]) -> Result { + if old.is_empty() { + return Ok(false); + } + let Some(&last) = new.last() else { + return Ok(false); + }; + let map: HashMap = old.iter().enumerate().map(|(i, o)| (*o, if i < new.len() { new[i] } else { last })).collect(); + let mut catalog_changed = false; + // /Dests: the named destinations, direct or indirect. + let dests_at = catalog.get(b"Dests").and_then(Object::as_ref); + if let Some(mut dests) = catalog.get(b"Dests").map(|d| doc.resolve(d)).and_then(|d| d.as_dict().cloned()) { + let mut updates: Vec<(Vec, Object)> = Vec::new(); + for (name, v) in dests.iter() { + let mut seen = HashSet::new(); + if let Some(new) = remap_dest(doc, v, &map, &mut seen)? { + updates.push((name.clone(), new)); + } + } + if !updates.is_empty() { + for (name, new) in updates { + dests.set(name, new); + } + match dests_at { + Some(r) => doc.set(r, Object::Dict(dests)), + None => { + catalog.set(b"Dests".to_vec(), Object::Dict(dests)); + catalog_changed = true; + } + } + } + } + // /Outlines: the bookmark items, from /First (each item's /Next, /First and /Kids too). + let first = catalog.get(b"Outlines").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().and_then(|d| d.get(b"First")).and_then(Object::as_ref)); + if let Some(first) = first { + let mut items = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![first]; + while let Some(r) = stack.pop() { + // Listed twice (its /Kids and /First both name it): remapped once, and not + // counted against the bound again. + if !seen.insert(r) { + continue; + } + if items.len() >= MAX_PAGES_SEARCHED { + return Err(XfaError::TooLarge(format!( + "the document's bookmarks hold more than {MAX_PAGES_SEARCHED} items; they would not all be remapped" + ))); + } + items.push(r); + if let Some(next) = doc.get(r).as_dict().and_then(|d| d.get(b"Next")).and_then(Object::as_ref) { + stack.push(next); + } + // A child, the spec's way: the item's /First. + if let Some(child) = doc.get(r).as_dict().and_then(|d| d.get(b"First")).and_then(Object::as_ref) { + stack.push(child); + } + let kids = + doc.get(r).as_dict().and_then(|d| d.get(b"Kids")).map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default(); + for k in kids.iter().filter_map(Object::as_ref).rev() { + stack.push(k); + } + } + for r in items { + let Some(mut d) = doc.get(r).as_dict().cloned() else { + continue; + }; + let mut changed = false; + if let Some(dest) = d.get(b"Dest") { + let mut seen = HashSet::new(); + if let Some(new) = remap_dest(doc, dest, &map, &mut seen)? { + d.set(b"Dest".to_vec(), new); + changed = true; + } + } + if let Some(a) = d.get(b"A") { + let mut seen = HashSet::new(); + if let Some(new) = remap_action(doc, a, &map, &mut seen)? { + d.set(b"A".to_vec(), new); + changed = true; + } + } + if changed { + doc.set(r, Object::Dict(d)); + } + } + } + // /Names: the Dests and Pages categories, a tree each: the Dests one's values are + // destinations, the Pages one's are page references. + let names_at = catalog.get(b"Names").and_then(Object::as_ref); + if let Some(mut names) = catalog.get(b"Names").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) { + let mut updates: Vec<(Vec, Object)> = Vec::new(); + for (cat, node) in names.iter() { + let pages = cat.as_slice() == b"Pages"; + if cat.as_slice() == b"Dests" || pages { + let mut seen = HashSet::new(); + if let Some(new) = remap_name_tree(doc, node, &map, &mut seen, pages)? { + updates.push((cat.clone(), new)); + } + } + } + if !updates.is_empty() { + for (cat, new) in updates { + names.set(cat, new); + } + match names_at { + Some(r) => doc.set(r, Object::Dict(names)), + None => { + catalog.set(b"Names".to_vec(), Object::Dict(names)); + catalog_changed = true; + } + } + } + } + Ok(catalog_changed) +} + +/// Remap the page a destination value names through `map`: an array whose first element +/// names a page, a dictionary with `/D`, or an indirect reference to either. An indirect one +/// is updated where it is, so nothing comes back for the caller to put back. A string is a +/// name in the document's `/Dests` (remapped there first), so it is left alone. `seen` +/// holds the references this value's `/D` chain has followed: a repeat is a cycle, an error. +fn remap_dest(doc: &mut Document, v: &Object, map: &HashMap, seen: &mut HashSet) -> Result, XfaError> { + match v { + Object::Array(a) => { + let mut a = a.clone(); + let changed = a.first().and_then(Object::as_ref).and_then(|r| map.get(&r)).is_some_and(|t| { + a[0] = Object::Ref(*t); + true + }); + Ok(changed.then_some(Object::Array(a))) + } + Object::Dict(d) => { + let Some(dest) = d.get(b"D") else { + return Ok(None); + }; + let Some(new) = remap_dest(doc, dest, map, seen)? else { + return Ok(None); + }; + let mut d = d.clone(); + d.set(b"D".to_vec(), new); + Ok(Some(Object::Dict(d))) + } + Object::Ref(r) => { + if !seen.insert(*r) { + return Err(XfaError::Malformed("a destination's /D chain is cyclic".into())); + } + let resolved = doc.resolve(v); + match &*resolved { + Object::Array(_) | Object::Dict(_) => { + if let Some(new) = remap_dest(doc, &resolved, map, seen)? { + doc.set(*r, new); + } + } + _ => {} + } + Ok(None) + } + _ => Ok(None), + } +} + +/// Remap the page a `/Pages` name tree value names through `map`: it is a page reference, +/// remapped where it is. +fn remap_page_ref(v: &Object, map: &HashMap) -> Option { + v.as_ref().and_then(|r| map.get(&r)).map(|t| Object::Ref(*t)) +} + +/// Remap the `/D` of a `GoTo` action through `map`; an indirect action is updated where it +/// is, so nothing comes back for the caller to put back. +fn remap_action(doc: &mut Document, a: &Object, map: &HashMap, seen: &mut HashSet) -> Result, XfaError> { + let resolved = doc.resolve(a); + let Some(d) = resolved.as_dict() else { + return Ok(None); + }; + let mut d = d.clone(); + if d.name(b"S") != Some(b"GoTo") { + return Ok(None); + } + let Some(dest) = d.get(b"D") else { + return Ok(None); + }; + let Some(new) = remap_dest(doc, dest, map, seen)? else { + return Ok(None); + }; + d.set(b"D".to_vec(), new); + match a.as_ref() { + Some(r) => { + doc.set(r, Object::Dict(d)); + Ok(None) + } + None => Ok(Some(Object::Dict(d))), + } +} + +/// Remap the values in a name tree node through `map` (destinations, or page references +/// where `pages`); an indirect node is updated where it is, so nothing comes back for the +/// caller to put back. A direct one comes back for the caller (the `/Names` dictionary) to +/// put back. `seen` holds the nodes this walk has reached: a repeat is a `/Kids` cycle, an +/// error. +fn remap_name_tree( + doc: &mut Document, + node: &Object, + map: &HashMap, + seen: &mut HashSet, + pages: bool, +) -> Result, XfaError> { + if let Some(r) = node.as_ref() + && !seen.insert(r) + { + return Err(XfaError::Malformed("a name tree's /Kids chain is cyclic".into())); + } + let resolved = doc.resolve(node); + let Some(d) = resolved.as_dict() else { + return Ok(None); + }; + let mut d = d.clone(); + let mut changed = false; + if let Some(names) = d.get(b"Names").map(|n| doc.resolve(n)).and_then(|n| n.as_array().cloned()) { + let mut names = names; + for i in (0..names.len() / 2 * 2).step_by(2) { + if let Some(v) = names.get(i + 1) { + let new = if pages { + remap_page_ref(v, map) + } else { + let mut value_seen = HashSet::new(); + remap_dest(doc, v, map, &mut value_seen)? + }; + if let Some(new) = new { + names[i + 1] = new; + changed = true; + } + } + } + if changed { + match d.get(b"Names").and_then(Object::as_ref) { + Some(r) => doc.set(r, Object::Array(names)), + None => d.set(b"Names".to_vec(), Object::Array(names)), + } + } + } + if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) { + let mut kids = kids; + let mut kids_changed = false; + for k in kids.iter_mut() { + if let Some(new) = remap_name_tree(doc, k, map, seen, pages)? { + *k = new; + kids_changed = true; + } + } + if kids_changed { + match d.get(b"Kids").and_then(Object::as_ref) { + Some(r) => doc.set(r, Object::Array(kids)), + None => d.set(b"Kids".to_vec(), Object::Array(kids)), + } + changed = true; + } + } + if !changed { + return Ok(None); + } + match node.as_ref() { + Some(r) => { + doc.set(r, Object::Dict(d)); + Ok(None) + } + None => Ok(Some(Object::Dict(d))), + } +} + /// Add the screen-only and print-only `groups` this layout drew in (`used`) to the document's /// optional content properties, keeping its own layers as they are: each goes in `/OCGs`; in the /// default configuration the print-only one starts off (the screen-only one starts on when the @@ -1547,4 +1882,277 @@ mod tests { assert_eq!(em.doc.object_numbers().len(), before, "no new object for a repeated picture"); assert_eq!(em.image_xobject(&picture(last), "image/png"), Some(again)); } + + /// A document with `pages` page objects (empty dictionaries) under one `/Pages` node, + /// which also lists itself when `cyclic`. + fn page_tree(doc: &mut Document, pages: usize, cyclic: bool) -> ObjRef { + let mut kids = (0..pages).map(|_| Object::Ref(doc.add(Object::Dict(Dict::new())))).collect::>(); + let node = doc.add(Object::Null); + if cyclic { + kids.push(Object::Ref(node)); + } + let mut d = Dict::new(); + d.set(b"Type".to_vec(), Object::name("Pages")); + d.set(b"Kids".to_vec(), Object::Array(kids)); + doc.set(node, Object::Dict(d)); + node + } + + #[test] + fn a_cyclic_page_tree_terminates_with_an_error() { + // #9027: a `/Pages` node that lists itself walked forever; the search now stops with + // an error, before any destination is remapped. + let mut doc = Document::new_empty(); + let pages = page_tree(&mut doc, 1, true); + let err = page_list(&doc, pages).unwrap_err(); + assert!(matches!(err, XfaError::Malformed(_)), "{err:?}"); + } + + #[test] + fn a_page_tree_past_the_search_limit_errors_before_replacement() { + // A destination naming a page the search omits would keep a stale reference; the + // search errors instead, and exactly the bound is still walked. + let mut doc = Document::new_empty(); + let pages = page_tree(&mut doc, MAX_PAGES_SEARCHED + 1, false); + let err = page_list(&doc, pages).unwrap_err(); + assert!(matches!(err, XfaError::TooLarge(_)), "{err:?}"); + let mut doc = Document::new_empty(); + let pages = page_tree(&mut doc, MAX_PAGES_SEARCHED, false); + assert_eq!(page_list(&doc, pages).unwrap().len(), MAX_PAGES_SEARCHED); + } + + /// A document whose catalog's `/Dests` entry `cyc` is a dictionary whose `/D` is itself. + fn cyclic_dests(doc: &mut Document) -> Dict { + let dest = doc.add(Object::Null); + let mut d = Dict::new(); + d.set(b"D".to_vec(), Object::Ref(dest)); + doc.set(dest, Object::Dict(d)); + let mut dests = Dict::new(); + dests.set(b"cyc".to_vec(), Object::Ref(dest)); + let mut catalog = Dict::new(); + catalog.set(b"Dests".to_vec(), Object::Dict(dests)); + catalog + } + + #[test] + fn a_cyclic_destination_terminates_with_an_error() { + // #9027: a destination whose `/D` chain is a cycle walked forever; the remap now + // stops with an error, before any destination is replaced. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = cyclic_dests(&mut doc); + let err = remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap_err(); + assert!(matches!(err, XfaError::Malformed(_)), "{err:?}"); + } + + /// A document whose catalog's `/Names` `Dests` tree is a node whose `/Kids` is itself. + fn cyclic_name_tree(doc: &mut Document, value: Object) -> Dict { + let node = doc.add(Object::Null); + let mut d = Dict::new(); + d.set(b"Names".to_vec(), Object::Array(vec![Object::String(PdfString::literal("end")), value])); + d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(node)])); + doc.set(node, Object::Dict(d)); + let mut names = Dict::new(); + names.set(b"Dests".to_vec(), Object::Ref(node)); + let mut catalog = Dict::new(); + catalog.set(b"Names".to_vec(), Object::Dict(names)); + catalog + } + + #[test] + fn a_cyclic_name_tree_terminates_with_an_error() { + // #9027: a name tree whose `/Kids` is a cycle walked forever; the remap now stops + // with an error, before any destination is replaced. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = cyclic_name_tree(&mut doc, Object::Ref(old)); + let err = remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap_err(); + assert!(matches!(err, XfaError::Malformed(_)), "{err:?}"); + } + + /// A document whose catalog's `/Outlines` is a `/Next` chain of `count` items. + fn bookmark_chain(doc: &mut Document, count: usize) -> Dict { + let items: Vec = (0..count).map(|_| doc.add(Object::Dict(Dict::new()))).collect(); + for (a, b) in items.iter().zip(items.iter().skip(1)) { + let mut d = doc.get(*a).as_dict().cloned().unwrap(); + d.set(b"Next".to_vec(), Object::Ref(*b)); + doc.set(*a, Object::Dict(d)); + } + let mut outlines = Dict::new(); + outlines.set(b"First".to_vec(), Object::Ref(items[0])); + let mut catalog = Dict::new(); + catalog.set(b"Outlines".to_vec(), Object::Dict(outlines)); + catalog + } + + #[test] + fn a_bookmark_list_past_the_search_limit_errors_before_replacement() { + // A bookmark the search omits would not be remapped; the search errors instead, and + // exactly the bound is still walked. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = bookmark_chain(&mut doc, MAX_PAGES_SEARCHED + 1); + let err = remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap_err(); + assert!(matches!(err, XfaError::TooLarge(_)), "{err:?}"); + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = bookmark_chain(&mut doc, MAX_PAGES_SEARCHED); + assert!(!remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap()); + } + + #[test] + fn an_outline_item_reaches_its_first_child() { + // #9027: a child is the parent's /First (the spec's way); the walk follows it, so + // the child's destination is remapped too. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let child = doc.add({ + let mut d = Dict::new(); + d.set(b"Dest".to_vec(), Object::Array(vec![Object::Ref(old), Object::name("Fit")])); + d + }); + let parent = doc.add({ + let mut d = Dict::new(); + d.set(b"First".to_vec(), Object::Ref(child)); + d + }); + let mut catalog = Dict::new(); + let mut outlines = Dict::new(); + outlines.set(b"First".to_vec(), Object::Ref(parent)); + catalog.set(b"Outlines".to_vec(), Object::Dict(outlines)); + remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap(); + let obj = doc.get(child); + let dest = obj.as_dict().unwrap().get(b"Dest").unwrap(); + assert_eq!(dest.as_array().unwrap().first().and_then(Object::as_ref), Some(new), "the child's destination follows the page"); + } + + #[test] + fn a_pages_name_tree_entry_points_at_the_replacement() { + // #9027: a `/Pages` name tree value is a page reference, not a destination; it is + // remapped through the map directly. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let names = doc.add(Object::Array(vec![Object::String(PdfString::literal("end")), Object::Ref(old)])); + let node = doc.add({ + let mut d = Dict::new(); + d.set(b"Names".to_vec(), Object::Ref(names)); + d + }); + let mut catalog = Dict::new(); + let mut names_cat = Dict::new(); + names_cat.set(b"Pages".to_vec(), Object::Ref(node)); + catalog.set(b"Names".to_vec(), Object::Dict(names_cat)); + remap_destinations(&mut doc, &mut catalog, &[old], &[new]).unwrap(); + let obj = doc.get(names); + let arr = obj.as_array().unwrap(); + assert_eq!(arr.get(1).and_then(Object::as_ref), Some(new), "the /Pages entry follows the page"); + } + + /// `old_n` old pages mapped onto `new_n` new ones, each old page named by a bookmark, a + /// `/Dests` entry and a `/Names` `Dests` entry; returns the page each of the three ended up on. + fn remap_every_kind(old_n: usize, new_n: usize) -> (Vec, Vec<[Option; 3]>) { + let mut doc = Document::new_empty(); + let old: Vec = (0..old_n).map(|_| doc.add(Object::Dict(Dict::new()))).collect(); + let new: Vec = (0..new_n).map(|_| doc.add(Object::Dict(Dict::new()))).collect(); + let dest = |page: ObjRef| Object::Array(vec![Object::Ref(page), Object::name("Fit")]); + let items: Vec = old + .iter() + .map(|o| { + let mut d = Dict::new(); + d.set(b"Dest".to_vec(), dest(*o)); + doc.add(Object::Dict(d)) + }) + .collect(); + for (a, b) in items.iter().zip(items.iter().skip(1)) { + let mut d = doc.get(*a).as_dict().cloned().unwrap(); + d.set(b"Next".to_vec(), Object::Ref(*b)); + doc.set(*a, Object::Dict(d)); + } + let mut outlines = Dict::new(); + outlines.set(b"First".to_vec(), Object::Ref(items[0])); + let mut dests = Dict::new(); + let mut names = Vec::new(); + for (i, o) in old.iter().enumerate() { + dests.set(format!("d{i}").into_bytes(), dest(*o)); + names.push(Object::String(PdfString::literal(format!("n{i}")))); + names.push(dest(*o)); + } + let mut tree = Dict::new(); + tree.set(b"Names".to_vec(), Object::Array(names)); + let mut names_cat = Dict::new(); + names_cat.set(b"Dests".to_vec(), Object::Dict(tree)); + let mut catalog = Dict::new(); + catalog.set(b"Outlines".to_vec(), Object::Dict(outlines)); + catalog.set(b"Dests".to_vec(), Object::Dict(dests)); + catalog.set(b"Names".to_vec(), Object::Dict(names_cat)); + remap_destinations(&mut doc, &mut catalog, &old, &new).unwrap(); + let first = |o: &Object| o.as_array().and_then(|a| a.first()).and_then(Object::as_ref); + let got = (0..old_n) + .map(|i| { + let bookmark = doc.get(items[i]).as_dict().and_then(|d| d.get(b"Dest")).and_then(first); + let named = catalog.get(b"Dests").and_then(Object::as_dict).and_then(|d| d.get(format!("d{i}").as_bytes())).and_then(first); + let tree = catalog.get(b"Names").and_then(Object::as_dict).and_then(|d| d.get(b"Dests")).and_then(Object::as_dict); + let in_tree = tree.and_then(|t| t.get(b"Names")).and_then(Object::as_array).and_then(|a| a.get(i * 2 + 1)).and_then(first); + [bookmark, named, in_tree] + }) + .collect(); + (new, got) + } + + #[test] + fn a_shrinking_layout_sends_the_dropped_pages_destinations_to_the_last_page() { + // #9027: 3 old pages, 2 new: page 0 and 1 follow by position, and page 2 (dropped) + // lands on the last new page, for a bookmark, a /Dests entry and a /Names entry alike. + let (new, got) = remap_every_kind(3, 2); + assert_eq!(got[0], [Some(new[0]); 3]); + assert_eq!(got[1], [Some(new[1]); 3]); + assert_eq!(got[2], [Some(new[1]); 3]); + } + + #[test] + fn a_growing_layout_keeps_each_destination_on_its_own_position() { + // #9027: 2 old pages, 3 new: each follows its position; the extra new page is unnamed. + let (new, got) = remap_every_kind(2, 3); + assert_eq!(got[0], [Some(new[0]); 3]); + assert_eq!(got[1], [Some(new[1]); 3]); + } + + #[test] + fn a_page_tree_of_exactly_the_bound_then_an_empty_node_is_still_walked() { + // The bound counts pages accepted, not nodes popped: an empty /Pages node after a + // full tree is not a page. + let mut doc = Document::new_empty(); + let full = page_tree(&mut doc, MAX_PAGES_SEARCHED, false); + let empty = page_tree(&mut doc, 0, false); + let mut root = Dict::new(); + root.set(b"Type".to_vec(), Object::name("Pages")); + root.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(full), Object::Ref(empty)])); + let root = doc.add(Object::Dict(root)); + assert_eq!(page_list(&doc, root).unwrap().len(), MAX_PAGES_SEARCHED); + } + + #[test] + fn a_bookmark_listed_twice_at_the_bound_is_not_a_new_item() { + // The item bound is for distinct items: with exactly the bound of them, the first + // named again by the last item's /Kids is a repeat and does not make the list too large. + let mut doc = Document::new_empty(); + let old = doc.add(Object::Dict(Dict::new())); + let new = doc.add(Object::Dict(Dict::new())); + let mut catalog = bookmark_chain(&mut doc, MAX_PAGES_SEARCHED); + let first = catalog.get(b"Outlines").and_then(Object::as_dict).and_then(|o| o.get(b"First")).and_then(Object::as_ref).unwrap(); + let mut last = first; + while let Some(next) = doc.get(last).as_dict().and_then(|d| d.get(b"Next")).and_then(Object::as_ref) { + last = next; + } + let mut d = doc.get(last).as_dict().cloned().unwrap(); + d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(first)])); + doc.set(last, Object::Dict(d)); + assert!(remap_destinations(&mut doc, &mut catalog, &[old], &[new]).is_ok()); + } }