212 lines
7.1 KiB
Rust
212 lines
7.1 KiB
Rust
//! Internal references of a sanitised tree (owner brief R3 §5: internal references and the
|
||
//! complexity of `<use>`). The sanitiser already keeps only `#id` targets; here every
|
||
//! `href` / `xlink:href` and every `url(#id)` becomes an edge to the first element holding
|
||
//! that id (document order, as browsers resolve it). A cycle through tree and reference edges
|
||
//! is refused, and so is a document whose expanded size passes the budget: each reference
|
||
//! adds the expanded size of its target, so 256 `<use>` of a large group, nested uses or a
|
||
//! clip path instantiated many times are all counted. The walk is iterative (reference
|
||
//! chains are not bounded by the depth cap) and saturating, with an early exit.
|
||
|
||
use std::collections::HashMap;
|
||
|
||
use super::sanitize::{local_reference_text, url_targets};
|
||
use super::tree::{Element, Node, SvgRejection};
|
||
|
||
/// Expanded elements a drawing may instantiate (the product's drawing: a few thousand).
|
||
pub const MAX_EXPANDED_ELEMENTS: u64 = 50_000;
|
||
|
||
struct Flat {
|
||
edges: Vec<usize>,
|
||
}
|
||
|
||
/// Checks the reference graph of `root`; answers the expanded element count.
|
||
pub fn check_references(root: &Element) -> Result<u64, SvgRejection> {
|
||
let (flat, refs) = flatten(root);
|
||
let ids = first_ids(root);
|
||
let mut graph: Vec<Flat> = flat;
|
||
for (node, targets) in refs {
|
||
for id in targets {
|
||
if let Some(&target) = ids.get(id.as_str()) {
|
||
graph[node].edges.push(target);
|
||
}
|
||
}
|
||
}
|
||
expanded_size(&graph)
|
||
}
|
||
|
||
/// Elements in document order with their child edges, and the reference ids of each.
|
||
fn flatten(root: &Element) -> (Vec<Flat>, Vec<(usize, Vec<String>)>) {
|
||
let mut flat = Vec::new();
|
||
let mut refs = Vec::new();
|
||
push_element(root, &mut flat, &mut refs);
|
||
(flat, refs)
|
||
}
|
||
|
||
fn push_element(
|
||
element: &Element,
|
||
flat: &mut Vec<Flat>,
|
||
refs: &mut Vec<(usize, Vec<String>)>,
|
||
) -> usize {
|
||
let index = flat.len();
|
||
flat.push(Flat { edges: Vec::new() });
|
||
let targets = reference_ids(element);
|
||
if !targets.is_empty() {
|
||
refs.push((index, targets));
|
||
}
|
||
for child in &element.children {
|
||
if let Node::Element(child) = child {
|
||
let child_index = push_element(child, flat, refs);
|
||
flat[index].edges.push(child_index);
|
||
}
|
||
}
|
||
index
|
||
}
|
||
|
||
/// First element of each id, in document order (the same order `flatten` numbers them).
|
||
fn first_ids(root: &Element) -> HashMap<&str, usize> {
|
||
let mut ids = HashMap::new();
|
||
let mut counter = 0;
|
||
collect_ids(root, &mut counter, &mut ids);
|
||
ids
|
||
}
|
||
|
||
fn collect_ids<'a>(element: &'a Element, counter: &mut usize, ids: &mut HashMap<&'a str, usize>) {
|
||
if let Some(id) = element.attr("id") {
|
||
ids.entry(id).or_insert(*counter);
|
||
}
|
||
*counter += 1;
|
||
for child in element.element_children() {
|
||
collect_ids(child, counter, ids);
|
||
}
|
||
}
|
||
|
||
/// Ids named by `href`, `xlink:href` (`#id`) and every `url(#id)` of the element.
|
||
fn reference_ids(element: &Element) -> Vec<String> {
|
||
let mut ids = Vec::new();
|
||
for attr in &element.attrs {
|
||
if attr.qname == "href" || attr.qname == "xlink:href" {
|
||
if let Some(id) = local_reference_text(&attr.value).strip_prefix('#') {
|
||
ids.push(id.to_owned());
|
||
}
|
||
continue;
|
||
}
|
||
ids.extend(url_targets(&attr.value));
|
||
}
|
||
ids
|
||
}
|
||
|
||
/// Post-order walk with an explicit stack: grey = on the current path (a cycle when met
|
||
/// again), black = size known.
|
||
fn expanded_size(graph: &[Flat]) -> Result<u64, SvgRejection> {
|
||
#[derive(Clone, Copy, PartialEq)]
|
||
enum Mark {
|
||
White,
|
||
Grey,
|
||
Black,
|
||
}
|
||
if graph.is_empty() {
|
||
return Ok(0);
|
||
}
|
||
let mut mark = vec![Mark::White; graph.len()];
|
||
let mut size = vec![0_u64; graph.len()];
|
||
let mut stack: Vec<(usize, usize)> = vec![(0, 0)];
|
||
mark[0] = Mark::Grey;
|
||
while let Some(&mut (node, ref mut next)) = stack.last_mut() {
|
||
if let Some(&target) = graph[node].edges.get(*next) {
|
||
*next += 1;
|
||
match mark[target] {
|
||
Mark::Grey => return Err(SvgRejection::ReferenceCycle),
|
||
Mark::White => {
|
||
mark[target] = Mark::Grey;
|
||
stack.push((target, 0));
|
||
}
|
||
Mark::Black => {}
|
||
}
|
||
continue;
|
||
}
|
||
let total = graph[node]
|
||
.edges
|
||
.iter()
|
||
.fold(1_u64, |sum, &t| sum.saturating_add(size[t]));
|
||
if total > MAX_EXPANDED_ELEMENTS {
|
||
return Err(SvgRejection::TooComplex);
|
||
}
|
||
size[node] = total;
|
||
mark[node] = Mark::Black;
|
||
stack.pop();
|
||
}
|
||
Ok(size[0])
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::anatomy::svg::tree::parse_svg;
|
||
|
||
fn check(body: &str) -> Result<u64, SvgRejection> {
|
||
let text = format!(
|
||
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">{body}</svg>"
|
||
);
|
||
let root = parse_svg(&text).unwrap_or_else(|e| panic!("{e:?}"));
|
||
check_references(&root)
|
||
}
|
||
|
||
#[test]
|
||
fn counts_each_reference_as_its_target_expanded() {
|
||
// root + path + 3 uses each expanding the path (1): 1 + 1 + 3 × 2
|
||
assert_eq!(
|
||
check("<path id=\"p\"/><use href=\"#p\"/><use href=\"#p\"/><use xlink:href=\"#p\"/>"),
|
||
Ok(8)
|
||
);
|
||
// a dangling reference adds nothing; a colour is not a reference
|
||
assert_eq!(check("<path fill=\"url(#none)\"/>"), Ok(2));
|
||
assert_eq!(
|
||
check("<g id=\"ff9500\"><path fill=\"#ff9500\"/></g>"),
|
||
Ok(3)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn refuses_cycles_through_use_paint_and_clip_paths() {
|
||
assert_eq!(
|
||
check("<g id=\"a\"><use href=\"#a\"/></g>"),
|
||
Err(SvgRejection::ReferenceCycle)
|
||
);
|
||
assert_eq!(
|
||
check("<g id=\"a\"><use href=\"#b\"/></g><g id=\"b\"><use href=\"#a\"/></g>"),
|
||
Err(SvgRejection::ReferenceCycle)
|
||
);
|
||
assert_eq!(
|
||
check(
|
||
"<clipPath id=\"c\"><use href=\"#g\"/></clipPath><g id=\"g\"><path clip-path=\"url(#c)\"/></g>"
|
||
),
|
||
Err(SvgRejection::ReferenceCycle)
|
||
);
|
||
assert_eq!(
|
||
check(
|
||
"<linearGradient id=\"a\" xlink:href=\"#b\"/><linearGradient id=\"b\" xlink:href=\"#a\"/>"
|
||
),
|
||
Err(SvgRejection::ReferenceCycle)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn refuses_an_expansion_over_the_budget_without_overflow() {
|
||
// 8 levels × 30 uses: 30^8 instances; refused early, no overflow.
|
||
let mut body = String::from("<path id=\"l0\"/>");
|
||
for level in 1..=8 {
|
||
body.push_str(&format!(
|
||
"<g id=\"l{level}\">{}</g>",
|
||
format!("<use href=\"#l{}\"/>", level - 1).repeat(30)
|
||
));
|
||
}
|
||
assert_eq!(check(&body), Err(SvgRejection::TooComplex));
|
||
// 200 uses of a 300-element group: 60,000 > 50,000
|
||
let group = format!("<g id=\"big\">{}</g>", "<path/>".repeat(299));
|
||
assert_eq!(
|
||
check(&format!("{group}{}", "<use href=\"#big\"/>".repeat(200))),
|
||
Err(SvgRejection::TooComplex)
|
||
);
|
||
}
|
||
}
|