From c795c08e0b4b770d71ab8833f8b8c2d392f9525f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 23 Nov 2026 11:32:56 -0500 Subject: [PATCH 1/2] fix(render): count SVG marker images more tightly and fairly before reading them (#2713) Part of #2713 (bounds on reading; the refusal phrases follow in their own PR). - A marker counts only on the vertices of the shapes that set it (by attribute, style or inheritance, a 's copy included), or on all of them when a style sheet sets one: an icon with an unused marker is no longer refused. - Whether a style sets a marker is read with simplecss, as usvg reads it, so a class like .marker-dot sets none and a comment before the colon still counts. - Matching the style sheets' rules is bounded by the steps simplecss's own matcher takes (CSS_STEPS), on each copy as usvg matches them, which also bounds descendant selectors deep down. The sheets are parsed once. - A gradient past two stops costs its stops at each pixel (STOPS). - An arc may come to at most 200 cubic curves (was 1,000). - A polyline's points are its pairs of numbers as svgtypes reads them. - A radius in % is resolved against the largest viewport; 0 in any unit is 0. - A subtree counted shallow is checked again where a reaches it deeper. --- Cargo.lock | 1 + Cargo.toml | 5 +- crates/render/Cargo.toml | 1 + crates/render/src/picture/svg.rs | 571 ++++++++++++++++++++++++++----- 4 files changed, 495 insertions(+), 83 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d05d95d5f5..a5861c999f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5431,6 +5431,7 @@ dependencies = [ "rustgis-map", "rustgis-tiles", "serde_json", + "simplecss", "subsetter", "svgtypes", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index 13115d528d..05c097ae1e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,9 +56,10 @@ tiny-skia = "0.12" # Picture markers drawn from SVG (opengeos/RustGIS#2266): no text, fonts, compressed SVG or raster # images, so an SVG reads no files and passes no image caps. 0.50 bounds how deep it nests. resvg = { version = "0.50", default-features = false } -# What resvg's reader (usvg) builds an SVG's paths and arcs with, read ahead to bound it -# (crates/render/src/picture/svg.rs): the versions it already brings in. +# What resvg's reader (usvg) builds an SVG's paths and arcs with and matches its style sheets with, +# read ahead to bound it (crates/render/src/picture/svg.rs): the versions it already brings in. svgtypes = "0.16" +simplecss = "0.2.2" kurbo = "0.13" # GPU map backend: vertex data shared with wgpu in ui-egui (derive only; unsafe stays forbidden). bytemuck = { version = "1", features = ["derive"] } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 06aa8b6e6e..431c747cf0 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -15,6 +15,7 @@ rustgis-map = { workspace = true } tiny-skia = { workspace = true } resvg = { workspace = true } svgtypes = { workspace = true } +simplecss = { workspace = true } kurbo = { workspace = true } bytemuck = { workspace = true } lyon = { workspace = true } diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 88bad2dc6b..1bce8c5ddf 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -45,9 +45,18 @@ pub(super) const ELEMENTS: u64 = 10_000; /// thousand. pub(super) const POINTS: u64 = 200_000; /// The most cubic curves one arc may come to once read ([`cubics`]): an icon's arcs come to a few -/// (a radius of 10⁶ to 13), and the reader moves each of an arc's curves across all the others -/// still to go (svgtypes' `SimplifyingPathParser`), so one of millions never finishes. -const ARC_CUBICS: f64 = 1_000.0; +/// (a radius of 10⁶ comes to 16 a whole turn, 10¹² to 150), and the reader moves each of an arc's +/// curves across all the others still to go (svgtypes' `SimplifyingPathParser`), which grows as +/// their square: one of millions never finishes. +const ARC_CUBICS: f64 = 200.0; +/// The most steps matching the style sheets' rules to the elements may take ([`css_steps`]): +/// each element is tried against each rule, and a selector's descendant (`a b`) against every +/// element above it, again for each descendant before it, so a few of them deep down come to +/// millions (`x g g g g g g rect` 40 levels down took 0.5 s). A step is some 11 ns (measured: a +/// class rule on an element, two steps, 22 ns), so ~11 ms: some 500,000 rules tried on elements, +/// 200 class rules on 2,500 elements. An attribute's value matched costs a step each 64 bytes too, +/// and each node walked back past to a sibling one. Icons take thousands of steps. +const CSS_STEPS: u64 = 1_000_000; /// The most XML nodes (elements, text, comments) read before giving up, a bound on reading the /// text itself: [`ELEMENTS`] and the text and spaces between them. const XML_NODES: u32 = 4 * ELEMENTS as u32; @@ -56,9 +65,13 @@ const XML_NODES: u32 = 4 * ELEMENTS as u32; const DEPTH: u32 = 64; /// What each element and each segment costs whatever its size, in units. const NODE: u64 = 100; +/// Each `STOPS` of a gradient's stops cost a unit a pixel, past two: tiny-skia then goes through +/// them all at each pixel (its `gradient` stage), some 0.7 ns a stop (measured: 1,000 stops 695 ns a pixel, +/// 100 stops 93 ns, 2 stops 21 ns). +const STOPS: u64 = 16; -/// SVG text `text` read into a tree: within [`XML_NODES`], [`ELEMENTS`] and [`POINTS`], its root -/// an ``, with no images resolved and no files read. +/// SVG text `text` read into a tree: within [`XML_NODES`], [`ELEMENTS`], [`POINTS`] and +/// [`CSS_STEPS`], its root an ``, with no images resolved and no files read. pub(super) fn read(text: &str) -> Result { let xml = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: XML_NODES, ..Default::default() }; let doc = roxmltree::Document::parse_with_options(text, xml).map_err(|e| match e { @@ -71,7 +84,7 @@ pub(super) fn read(text: &str) -> Result { if doc.descendants().any(undrawn) { return Err(Refusal::Undrawn); } - if elements(&doc).is_none() || nested_markers(&doc) { + if with_sheet(&doc, |sheet| elements(&doc, sheet).is_none() || nested_markers(&doc, sheet)) { return Err(Refusal::TooMuch); } let opt = usvg::Options { @@ -129,20 +142,152 @@ fn undrawn(n: roxmltree::Node) -> bool { /// isn't read here), or, through a `` in the marker, from anything the copy it makes holds or /// that holds it. So any of those naming a marker counts. One marker can only nest itself, a cycle /// usvg drops (it follows a ``'s copy too). -fn nested_markers(doc: &roxmltree::Document) -> bool { +fn nested_markers(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> bool { let markers: Vec<_> = doc.descendants().filter(|n| n.has_tag_name("marker")).collect(); if markers.len() < 2 { return false; } - let carries = |n: roxmltree::Node| { - n.attributes().any(|a| { - matches!(a.name(), "marker" | "marker-start" | "marker-mid" | "marker-end") - || (a.name() == "style" && a.value().to_ascii_lowercase().contains("marker")) - }) - }; - let sheet = doc.descendants().filter(|n| n.has_tag_name("style")).any(|n| sheet_of(n).to_ascii_lowercase().contains("marker")); let uses = markers.iter().any(|m| m.descendants().any(|n| n.has_tag_name("use"))); - sheet || markers.iter().any(|m| m.ancestors().any(carries) || m.descendants().any(carries)) || (uses && doc.descendants().any(carries)) + sheet_sets_marker(sheet) + || markers.iter().any(|m| m.ancestors().any(names_marker) || m.descendants().any(names_marker)) + || (uses && doc.descendants().any(names_marker)) +} + +/// Whether element `n` sets a marker on what it draws and holds, by attribute or in its `style`. +fn names_marker(n: roxmltree::Node) -> bool { + n.attributes().any(|a| { + sets_marker(a.name(), a.value()) + || (a.name() == "style" && simplecss::DeclarationTokenizer::from(a.value()).any(|d| sets_marker(d.name, d.value))) + }) +} + +/// Whether property `name` of `value` sets a marker: a marker property naming one (`url(#id)`), read +/// as usvg reads it; `none` sets none. +fn sets_marker(name: &str, value: &str) -> bool { + is_marker(name) && svgtypes::FuncIRI::from_str(value).is_ok() +} + +/// Whether style sheet `sheet` sets a marker, on whatever its selectors reach. +fn sheet_sets_marker(sheet: &simplecss::StyleSheet) -> bool { + sheet.rules.iter().any(|r| r.declarations.iter().any(|d| sets_marker(d.name, d.value))) +} + +/// The ids of the markers a marker property names (`url(#id)`), by attribute, in a `style` or in +/// style sheet `sheet`, read as usvg reads them: no other is drawn. +fn named_markers(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> std::collections::HashSet { + let mut ids = std::collections::HashSet::new(); + let mut take = |v: &str| { + if let Ok(iri) = svgtypes::FuncIRI::from_str(v) { + ids.insert(iri.0.to_string()); + } + }; + for a in doc.descendants().flat_map(|n| n.attributes()) { + if is_marker(a.name()) { + take(a.value()); + } else if a.name() == "style" { + simplecss::DeclarationTokenizer::from(a.value()).filter(|d| is_marker(d.name)).for_each(|d| take(d.value)); + } + } + sheet.rules.iter().flat_map(|r| &r.declarations).filter(|d| is_marker(d.name)).for_each(|d| take(d.value)); + ids +} + +/// Whether property `name` sets a marker, read as usvg reads a style's declarations (with +/// simplecss: past comments and spaces before the colon); ASCII case aside, to be safe (usvg +/// takes only lower case). +fn is_marker(name: &str) -> bool { + ["marker", "marker-start", "marker-mid", "marker-end"].iter().any(|m| name.eq_ignore_ascii_case(m)) +} + +/// The steps matching `sheet`'s rules to element `n` takes, as usvg matches them before reading +/// it (each rule tried with simplecss's own matcher, each step counted), on top of the `spent` +/// that matching other elements took; `None` past [`CSS_STEPS`] in all, where it is stopped. +fn css_steps(n: roxmltree::Node, sheet: &simplecss::StyleSheet, spent: u64) -> Option { + let steps = std::cell::Cell::new(spent); + for rule in &sheet.rules { + steps.set(steps.get() + 1); + rule.selector.matches(&Stepped(n, &steps)); + if steps.get() > CSS_STEPS { + return None; + } + } + Some(steps.get() - spent) +} + +/// An element as simplecss matches it, each step it takes counted in the cell; past +/// [`CSS_STEPS`] it has nothing above or before it and matches nothing, so the matching ends. +struct Stepped<'a, 'input>(roxmltree::Node<'a, 'input>, &'a std::cell::Cell); + +impl<'a, 'input> Stepped<'a, 'input> { + /// Counts a step: whether it is still within [`CSS_STEPS`]. + fn step(&self) -> bool { + self.steps(1) + } + + /// Counts `n` steps: whether they are still within [`CSS_STEPS`]. + fn steps(&self, n: u64) -> bool { + self.1.set(self.1.get().saturating_add(n)); + self.1.get() <= CSS_STEPS + } + + /// The element `to` gives, a step away; none past [`CSS_STEPS`]. + fn hop(&self, to: impl FnOnce(roxmltree::Node<'a, 'input>) -> Option>) -> Option { + if !self.step() { + return None; + } + to(self.0).map(|n| Stepped(n, self.1)) + } +} + +impl simplecss::Element for Stepped<'_, '_> { + fn parent_element(&self) -> Option { + self.hop(|n| n.parent_element()) + } + + fn prev_sibling_element(&self) -> Option { + // Each node walked back past is a step: comments between siblings are walked too. + let mut back = self.0.prev_sibling(); + while let Some(n) = back { + if !self.step() { + return None; + } + if n.is_element() { + return Some(Stepped(n, self.1)); + } + back = n.prev_sibling(); + } + None + } + + fn has_local_name(&self, name: &str) -> bool { + self.step() && self.0.tag_name().name() == name + } + + fn attribute_matches(&self, name: &str, operator: simplecss::AttributeOperator) -> bool { + // Matched along its value, a step each 64 bytes, before it is read. + match self.0.attribute(name) { + Some(v) => self.steps(1 + v.len() as u64 / 64) && operator.matches(v), + None => { + self.step(); + false + } + } + } + + fn pseudo_class_matches(&self, class: simplecss::PseudoClass) -> bool { + self.step() && matches!(class, simplecss::PseudoClass::FirstChild) && self.prev_sibling_element().is_none() + } +} + +/// `f` of `doc`'s style sheets, read once as usvg reads them (`resolve_css`), every `