diff --git a/crates/metadata/src/edit/resolution.rs b/crates/metadata/src/edit/resolution.rs index 450ea4a25d..4da5521dc3 100644 --- a/crates/metadata/src/edit/resolution.rs +++ b/crates/metadata/src/edit/resolution.rs @@ -419,6 +419,7 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> { let mut out = Vec::new(); let mut from = 0; while let Some(k) = xmp.get(from..).and_then(|s| s.find(key)).map(|k| k + from) { + searched(k + key.len() - from); from = k + key.len(); // An attribute or an opening tag of exactly this name (not ``, not `xkey`). if !xmp.get(..k).and_then(|h| h.chars().next_back()).is_some_and(|c| c == '<' || c.is_ascii_whitespace()) { @@ -443,13 +444,34 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> { // attribute re-ran this full-suffix `find(close)` for every occurrence, which is // quadratic in the packet size. A missing close means the value is unterminated, so // no later value can parse either; stop scanning in that case. - let Some(len) = value.find(close) else { break }; + let Some(len) = value.find(close) else { + // the search read the rest of the packet, and no key search follows + searched(value.len()); + from = xmp.len(); + break; + }; + searched(len + close.len_utf8()); out.push((start, start + len)); from = start + len + close.len_utf8(); } + searched(xmp.len().saturating_sub(from)); out } +// The bytes of the packet `xmp_values` searches for a key or a closing quote, on this thread. +#[cfg(test)] +std::thread_local! { + static SEARCHED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn searched(count: usize) { + #[cfg(test)] + SEARCHED.with(|searched| searched.set(searched.get().saturating_add(count))); + #[cfg(not(test))] + let _ = count; +} + /// An XMP rational (`300/1`) or plain number. fn xmp_number(s: &str) -> Option { let s = s.trim(); @@ -780,3 +802,22 @@ pub fn resolution(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> #[cfg(test)] mod complexity_tests; + +#[cfg(test)] +mod xmp_scan_tests { + use super::*; + + /// Property-like text repeated through a packet is searched once: each property's values are + /// found in one pass, not a search of the rest of the packet from every occurrence. + #[test] + fn repeated_property_text_is_searched_once_for_each_property() { + let decoys = " tiff:ResolutionUnit>".repeat(50_000); + for key in [XMP_X, XMP_Y, XMP_UNIT] { + SEARCHED.with(|searched| searched.set(0)); + let _ = xmp_values(&decoys, key); + let read = SEARCHED.with(std::cell::Cell::get); + assert!(read <= decoys.len(), "{key}: {read} bytes searched in {}", decoys.len()); + } + assert_eq!(xmp_resolution(&decoys), None); + } +} diff --git a/crates/metadata/src/xmp.rs b/crates/metadata/src/xmp.rs index 9730bfdd0d..c09489237f 100644 --- a/crates/metadata/src/xmp.rs +++ b/crates/metadata/src/xmp.rs @@ -567,7 +567,7 @@ fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn build_path(path: String) -> String { + #[cfg(test)] + PATH_BYTES.with(|bytes| bytes.set(bytes.get().saturating_add(path.len()))); + path +} + /// Charge one flattened key's length to the key budget; `false` when the budget is spent (the /// property is then left out, like other elements a limit has cut) and the map is marked partial. fn take_key_bytes(key: &str, budget: &mut usize, dropped: &mut bool) -> bool { @@ -596,8 +610,11 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap = arr .children .iter() @@ -614,32 +631,39 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap = p.attrs.iter().filter(|(k, _)| !is_rdf_meta_attr(k)).collect(); if !field_attrs.is_empty() && p.children.is_empty() && p.text.trim().is_empty() { for (k, v) in field_attrs { - let full = format!("{struct_prefix}{k}"); + // the budget is checked before the path is built, as for a description's attributes + if *budget < prefix.len().saturating_add(p.name.len()).saturating_add(1).saturating_add(k.len()) { + *truncated = true; + continue; + } + let full = build_path(format!("{prefix}{}/{k}", p.name)); if take_key_bytes(&full, budget, truncated) { props.entry(full).or_default().push(v.clone()); } } return; } + let key = path(); let v = p.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| p.text.trim().to_string()); if take_key_bytes(&key, budget, truncated) { props.entry(key).or_default().push(v); diff --git a/crates/metadata/src/xmp/tests.rs b/crates/metadata/src/xmp/tests.rs index c3c3181c9e..1440741f30 100644 --- a/crates/metadata/src/xmp/tests.rs +++ b/crates/metadata/src/xmp/tests.rs @@ -886,9 +886,39 @@ fn paths_are_not_built_past_the_key_budget() { doc.push_str(&format!("")); } doc.push_str(""); - let t = std::time::Instant::now(); + PATH_BYTES.with(|bytes| bytes.set(0)); let _ = parse_xmp(&doc); - assert!(t.elapsed().as_secs() < 10, "took {:?}", t.elapsed()); + // Each path built is charged to the budget, or is a charged struct path and its "/". + let built = PATH_BYTES.with(std::cell::Cell::get); + let structs = 100_004; + assert!(built <= 2 * MAX_KEY_BYTES + structs, "{built} bytes of paths built"); +} + +/// A field attribute whose path no longer fits the budget, while its element's own path still +/// does, left the budget as it was: each of its siblings then copied the long ancestor path again. +#[test] +fn field_paths_past_the_key_budget_are_not_built_for_each_sibling() { + // One struct of n letters, then a field that spends the budget down to n + 10 bytes: room for + // the path of `lc:e` under the struct (n + 8 bytes) but not for that of its field `lc:f` + // (n + 13). + let n = 200_000; + let level = "n".repeat(n); + let drain = "a".repeat(MAX_KEY_BYTES - 3 * n - 25); + let mut doc = format!( + "", + LC.uri + ); + for _ in 0..20_000 { + doc.push_str(""); + } + doc.push_str(&format!("")); + PATH_BYTES.with(|bytes| bytes.set(0)); + let data = parse_xmp(&doc).unwrap_or_else(|e| panic!("{e}")); + assert!(data.properties_truncated); + assert!(data.properties.contains_key(&format!("lc:{level}/lc:d/lc:{drain}"))); + assert!(!data.properties.contains_key(&format!("lc:{level}/lc:e/lc:f"))); + let built = PATH_BYTES.with(std::cell::Cell::get); + assert!(built <= 2 * MAX_KEY_BYTES, "{built} bytes of paths built"); } /// The caller's namespace is declared where the read-only `crs` sits in the table, is known to the diff --git a/crates/metadata/src/xmp_merge.rs b/crates/metadata/src/xmp_merge.rs index 76759f680f..ac8fbe22fe 100644 --- a/crates/metadata/src/xmp_merge.rs +++ b/crates/metadata/src/xmp_merge.rs @@ -97,6 +97,12 @@ fn pos(r: &quick_xml::Reader<&[u8]>) -> usize { usize::try_from(r.buffer_position()).unwrap_or(usize::MAX) } +// Each attribute name `scan` looks up in its set of the tag's names, on this thread. +#[cfg(test)] +std::thread_local! { + static NAME_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Locate the descriptions, their top-level properties and `` in a packet. fn scan(s: &str, extra: &[XmpNamespace]) -> Result { let mut reader = quick_xml::Reader::from_reader(s.as_bytes()); @@ -124,6 +130,8 @@ fn scan(s: &str, extra: &[XmpNamespace]) -> Result { for a in e.attributes().with_checks(false) { let a = a.map_err(|e| XmpError::Xml(e.to_string()))?; let k = String::from_utf8_lossy(a.key.as_ref()).into_owned(); + #[cfg(test)] + NAME_CHECKS.with(|checks| checks.set(checks.get().saturating_add(1))); if !seen.insert(k.clone()) { return Err(XmpError::Xml(format!("repeated attribute {k}"))); } @@ -490,11 +498,10 @@ mod tests { #[test] fn many_attributes_scan_in_linear_time() { - // quick-xml's duplicate-name check compares each attribute with all earlier ones: 200 000 attributes on - // one description took over 20 s to scan, about 30 ms with the set. Four times the attributes must take - // about four times as long, not sixteen. A ratio of the fastest runs holds on a loaded machine, where - // a fixed bound does not. - let packet = |n: usize| { + // A duplicate-name check that compares each attribute with all earlier ones took over 20 s for + // 200 000 attributes on one description. The scan looks each name up once in a set of the tag's + // names, and leaves quick-xml's own check off. + let packet = |n: usize, repeat: &str| { let mut s = String::from( "\ "); s }; - let run = |s: &str, n: usize| { - let t = std::time::Instant::now(); - let found = scan(s, &[]).unwrap(); - let took = t.elapsed(); + for n in [20_000, 80_000] { + NAME_CHECKS.with(|checks| checks.set(0)); + let found = scan(&packet(n, ""), &[]).unwrap(); assert_eq!(found.descs[0].attrs.len(), n + 2, "every attribute is read"); - took - }; - let (n, small_packet, large_packet) = (20_000, packet(20_000), packet(80_000)); - // interleaved, so a burst of load slows both sizes rather than one; the fastest run of each counts - let (mut small, mut large) = (std::time::Duration::MAX, std::time::Duration::MAX); - for _ in 0..3 { - small = small.min(run(&small_packet, n)); - large = large.min(run(&large_packet, 4 * n)); + // one lookup for each attribute of the three tags: xmlns:x, xmlns:rdf, rdf:about, xmlns:foo and the n + assert_eq!(NAME_CHECKS.with(std::cell::Cell::get), n + 4); + // the set, not quick-xml, finds a name given twice + let repeated = scan(&packet(n, " foo:a0=\"again\""), &[]).map(|_| ()).unwrap_err(); + assert_eq!(repeated, XmpError::Xml("repeated attribute foo:a0".into())); } - let ratio = large.as_secs_f64() / small.as_secs_f64().max(1e-6); - assert!(ratio < 10.0, "4x the attributes took {ratio:.1}x as long ({small:?}, then {large:?})"); } #[test]