1use crate::settings::limit;
5use html5ever::interface::{ElementFlags, NodeOrText, QuirksMode, TreeSink};
6use html5ever::tendril::{StrTendril, TendrilSink};
7use html5ever::tokenizer::TokenizerOpts;
8use html5ever::tree_builder::TreeBuilderOpts;
9use html5ever::{Attribute, LocalName, ParseOpts, QualName, parse_document, parse_fragment};
10use std::borrow::Cow;
11use std::cell::RefCell;
12use std::time::{Duration, Instant};
13
14const FEED: usize = 64 * 1024;
15
16pub enum Kid {
17 Text(String),
18 Node(usize),
19}
20
21impl Kid {
22 pub fn node(&self) -> Option<usize> {
24 if let Kid::Node(c) = self { Some(*c) } else { None }
25 }
26}
27
28pub struct Node {
29 pub tag: String,
30 pub attrs: Vec<(String, String)>,
31 pub kids: Vec<Kid>,
32 pub parent: Option<usize>,
33}
34
35impl Node {
36 pub fn attr(&self, k: &str) -> Option<&str> {
37 self.attrs.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str())
38 }
39
40 pub fn label(&self) -> String {
42 let set = |k| self.attr(k).filter(|v| !v.is_empty());
43 match (set("id"), set("type")) {
44 (Some(id), _) => format!("{}#{id}", self.tag),
45 (None, Some(ty)) => format!("{}[{ty}]", self.tag),
46 (None, None) => self.tag.clone(),
47 }
48 }
49}
50
51pub struct Tree {
53 pub nodes: Vec<Node>,
54 pub meta: Vec<(String, String)>,
55 pub json: Vec<(String, String, bool)>,
57 pub title: String,
58 pub cut: usize,
59}
60
61pub enum Visit<'a> {
63 Node(&'a Node),
64 Text(&'a str),
65}
66
67impl Tree {
68 pub fn meta(&self, k: &str) -> Option<&str> {
69 self.meta.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str())
70 }
71
72 pub fn walk<'a>(&'a self, id: usize, skip: &'a [&str]) -> impl Iterator<Item = Visit<'a>> {
75 let mut stack = vec![Visit::Node(&self.nodes[id])];
76 std::iter::from_fn(move || {
77 let step = stack.pop()?;
78 if let Visit::Node(n) = step {
79 stack.extend(n.kids.iter().rev().filter_map(|k| match k {
80 Kid::Text(s) => Some(Visit::Text(s)),
81 Kid::Node(c) => Some(&self.nodes[*c]).filter(|c| !skip.contains(&c.tag.as_str())).map(Visit::Node),
82 }));
83 }
84 Some(step)
85 })
86 }
87
88 pub fn texts<'a>(&'a self, id: usize, skip: &'a [&str]) -> impl Iterator<Item = &'a str> {
90 self.walk(id, skip).filter_map(|s| if let Visit::Text(t) = s { Some(t) } else { None })
91 }
92}
93
94struct Sink {
96 nodes: RefCell<Vec<Node>>,
97 names: RefCell<Vec<QualName>>,
98}
99
100impl Sink {
101 fn new_node(&self, tag: String, q: QualName, attrs: Vec<(String, String)>) -> usize {
102 let mut n = self.nodes.borrow_mut();
103 n.push(Node { tag, attrs, kids: Vec::new(), parent: None });
104 self.names.borrow_mut().push(q);
105 n.len() - 1
106 }
107
108 fn detach(&self, id: usize) {
109 let mut n = self.nodes.borrow_mut();
110 if let Some(p) = n[id].parent.take() {
111 n[p].kids.retain(|k| !matches!(k, Kid::Node(c) if *c == id));
112 }
113 }
114
115 fn insert(&self, parent: usize, at: usize, child: NodeOrText<usize>) {
117 match child {
118 NodeOrText::AppendText(t) => {
119 let mut n = self.nodes.borrow_mut();
120 let kids = &mut n[parent].kids;
121 if at > 0
122 && let Some(Kid::Text(s)) = kids.get_mut(at - 1)
123 {
124 s.push_str(&t);
125 } else if let Some(Kid::Text(s)) = kids.get_mut(at) {
126 s.insert_str(0, &t);
127 } else {
128 kids.insert(at, Kid::Text(t.to_string()));
129 }
130 }
131 NodeOrText::AppendNode(c) => {
132 self.detach(c);
133 let mut n = self.nodes.borrow_mut();
134 if n[c].tag.starts_with('#') {
135 return;
136 }
137 let at = at.min(n[parent].kids.len());
138 n[parent].kids.insert(at, Kid::Node(c));
139 n[c].parent = Some(parent);
140 }
141 }
142 }
143}
144
145fn qname(local: &str) -> QualName {
146 QualName::new(None, html5ever::ns!(), LocalName::from(local))
147}
148
149impl TreeSink for Sink {
150 type Handle = usize;
151 type Output = Self;
152 type ElemName<'a> = std::cell::Ref<'a, QualName>;
153
154 fn finish(self) -> Self {
155 self
156 }
157 fn parse_error(&self, _msg: Cow<'static, str>) {}
158 fn get_document(&self) -> usize {
159 0
160 }
161 fn elem_name<'a>(&'a self, target: &'a usize) -> Self::ElemName<'a> {
162 std::cell::Ref::map(self.names.borrow(), |v| &v[*target])
163 }
164 fn create_element(&self, name: QualName, attrs: Vec<Attribute>, flags: ElementFlags) -> usize {
165 let a = attrs.into_iter().map(|a| (a.name.local.to_string(), a.value.to_string())).collect();
166 let id = self.new_node(name.local.to_string(), name, a);
167 if flags.template {
168 self.new_node("#fragment".into(), qname("#fragment"), Vec::new());
170 }
171 id
172 }
173 fn create_comment(&self, _text: StrTendril) -> usize {
174 self.new_node("#comment".into(), qname("#comment"), Vec::new())
175 }
176 fn create_pi(&self, _target: StrTendril, _data: StrTendril) -> usize {
177 self.new_node("#pi".into(), qname("#pi"), Vec::new())
178 }
179 fn append(&self, parent: &usize, child: NodeOrText<usize>) {
180 let at = self.nodes.borrow()[*parent].kids.len();
181 self.insert(*parent, at, child);
182 }
183 fn append_based_on_parent_node(&self, element: &usize, prev: &usize, child: NodeOrText<usize>) {
184 if self.nodes.borrow()[*element].parent.is_some() {
185 self.append_before_sibling(element, child);
186 } else {
187 self.append(prev, child);
188 }
189 }
190 fn append_doctype_to_document(&self, _: StrTendril, _: StrTendril, _: StrTendril) {}
191 fn get_template_contents(&self, target: &usize) -> usize {
192 target + 1
193 }
194 fn same_node(&self, x: &usize, y: &usize) -> bool {
195 x == y
196 }
197 fn set_quirks_mode(&self, _mode: QuirksMode) {}
198 fn append_before_sibling(&self, sibling: &usize, new_node: NodeOrText<usize>) {
199 let Some(p) = self.nodes.borrow()[*sibling].parent else { return };
200 let at = self.nodes.borrow()[p].kids.iter().position(|k| matches!(k, Kid::Node(c) if c == sibling));
201 if let Some(i) = at {
202 self.insert(p, i, new_node);
203 }
204 }
205 fn add_attrs_if_missing(&self, target: &usize, attrs: Vec<Attribute>) {
206 let mut n = self.nodes.borrow_mut();
207 for a in attrs {
208 let k = a.name.local.to_string();
209 if n[*target].attr(&k).is_none() {
210 n[*target].attrs.push((k, a.value.to_string()));
211 }
212 }
213 }
214 fn remove_from_parent(&self, target: &usize) {
215 self.detach(*target);
216 }
217 fn reparent_children(&self, node: &usize, new_parent: &usize) {
218 let mut n = self.nodes.borrow_mut();
219 let kids = std::mem::take(&mut n[*node].kids);
220 for c in kids.iter().filter_map(Kid::node) {
221 n[c].parent = Some(*new_parent);
222 }
223 n[*new_parent].kids.extend(kids);
224 }
225}
226
227#[cfg(test)]
228thread_local!(pub static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
229
230pub fn parse(h: &str) -> Tree {
232 #[cfg(test)]
233 PARSES.with(|n| n.set(n.get() + 1));
234 let sink = Sink { nodes: RefCell::new(Vec::new()), names: RefCell::new(Vec::new()) };
235 sink.new_node("#document".into(), qname("#document"), Vec::new());
236 let opts = ParseOpts {
237 tree_builder: TreeBuilderOpts { scripting_enabled: false, ..Default::default() },
238 ..Default::default()
239 };
240 let mut p = parse_document(sink, opts);
241 let (t0, mut at, budget) = (Instant::now(), 0, Duration::from_secs(limit("parse_budget_s")));
243 while at < h.len() && t0.elapsed() < budget {
244 let mut e = (at + FEED).min(h.len());
245 while !h.is_char_boundary(e) {
246 e += 1;
247 }
248 p.process(StrTendril::from_slice(&h[at..e]));
249 at = e;
250 }
251 let sink = p.finish();
252 flatten(sink.nodes.into_inner(), h.len() - at)
253}
254
255fn flatten(mut nodes: Vec<Node>, cut: usize) -> Tree {
257 let mut t = Tree { nodes: Vec::new(), meta: Vec::new(), json: Vec::new(), title: String::new(), cut };
258 let mut stack = vec![(0usize, 0usize)];
259 let max_depth: usize = limit("max_depth");
262 while let Some((id, depth)) = stack.pop() {
263 let kids = std::mem::take(&mut nodes[id].kids);
264 let n = &nodes[id];
265 match n.tag.as_str() {
266 "meta" => {
267 let get = |k: &str| n.attr(k).filter(|v| !v.is_empty());
268 let key = get("property").or_else(|| get("name")).or_else(|| get("itemprop")).map(str::to_lowercase);
269 if let (Some(key), Some(content)) = (key, get("content"))
270 && t.meta(&key).is_none()
271 {
272 t.meta.push((key, content.to_string()));
273 }
274 }
275 "script" | "style" => {
276 let text: String =
277 kids.iter().filter_map(|k| if let Kid::Text(s) = k { Some(s.as_str()) } else { None }).collect();
278 let ty = n.attr("type").unwrap_or("").to_lowercase();
279 let data = ty.contains("json") || n.attr("id").is_some_and(|id| id.ends_with("__"));
280 if n.tag == "script" && !text.is_empty() && data {
281 t.json.push((n.label(), text, ty.contains("ld+json")));
282 }
283 continue; }
285 "title" if t.title.is_empty() => {
286 if let Some(Kid::Text(s)) = kids.first() {
287 t.title = py_strip(s).to_string();
288 }
289 }
290 _ => {}
291 }
292 let mut kids = kids;
293 if n.tag == "template" {
294 stack.push((id + 1, depth.min(max_depth - 1) + 1)); }
296 if depth == max_depth {
297 kids = spill(&mut nodes, kids, id, &mut t.title);
298 }
299 stack.extend(kids.iter().rev().filter_map(Kid::node).map(|c| (c, depth + 1)));
300 nodes[id].kids = kids;
301 }
302 t.nodes = nodes;
303 t
304}
305
306fn spill(nodes: &mut [Node], kids: Vec<Kid>, owner: usize, title: &mut String) -> Vec<Kid> {
310 let mut out = Vec::with_capacity(kids.len());
311 let mut todo: Vec<Kid> = kids.into_iter().rev().collect();
312 while let Some(k) = todo.pop() {
313 let Kid::Node(c) = k else {
314 out.push(k);
315 continue;
316 };
317 nodes[c].parent = Some(owner);
318 out.push(Kid::Node(c));
319 if matches!(nodes[c].tag.as_str(), "script" | "style") {
320 continue;
321 }
322 let below = std::mem::take(&mut nodes[c].kids);
323 if nodes[c].tag == "title"
324 && title.is_empty()
325 && let Some(Kid::Text(s)) = below.first()
326 {
327 *title = py_strip(s).to_string();
328 }
329 todo.extend(below.into_iter().rev());
330 }
331 out
332}
333
334pub fn py_space(c: char) -> bool {
336 c.is_whitespace() || ('\x1c'..='\x1f').contains(&c)
337}
338
339pub fn py_strip(s: &str) -> &str {
340 s.trim_matches(py_space)
341}
342
343pub fn unescape(s: &str) -> String {
347 if !s.contains('&') {
348 return s.to_string();
349 }
350 let sink = Sink { nodes: RefCell::new(Vec::new()), names: RefCell::new(Vec::new()) };
351 sink.new_node("#document".into(), qname("#document"), Vec::new());
352 let opts =
353 ParseOpts { tokenizer: TokenizerOpts { discard_bom: false, ..Default::default() }, ..Default::default() };
354 let textarea = QualName::new(None, html5ever::ns!(html), LocalName::from("textarea"));
355 let nodes = parse_fragment(sink, opts, textarea, Vec::new(), false).one(s).nodes.into_inner();
356 nodes.into_iter().flat_map(|n| n.kids).filter_map(|k| if let Kid::Text(t) = k { Some(t) } else { None }).collect()
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362
363 #[test]
364 fn unescape_matches_cpython() {
365 assert_eq!(unescape("a & b <c>"), "a & b <c>");
366 assert_eq!(unescape("©2026 x"), "©2026 x");
367 assert_eq!(unescape("AB�€"), "AB\u{fffd}€");
368 assert_eq!(unescape("&nosuch; & &#;"), "&nosuch; & &#;");
369 assert_eq!(unescape("¬it; <b>&</b></textarea>"), "¬it; <b>&</b></textarea>");
370 assert_eq!(unescape("a\r\nb"), "a\nb\u{1}");
372 }
373
374 fn tags(t: &Tree, id: usize) -> Vec<&str> {
375 t.nodes[id].kids.iter().filter_map(Kid::node).map(|c| t.nodes[c].tag.as_str()).collect()
376 }
377
378 #[test]
379 fn tree_rules() {
380 let t = parse(
381 "<title> T </title><meta property=og:title content=X><p>a<div>b</div><ul><li>1<li>2</ul>\
382 <script type='application/ld+json'>{\"a\":1}</script><!-- c --><a href=\"x\" title='y>z' hidden>t</a>",
383 );
384 assert_eq!((t.title.as_str(), t.meta("og:title"), t.json.iter().filter(|j| j.2).count()), ("T", Some("X"), 1));
385 let body = t.nodes.iter().position(|n| n.tag == "body").unwrap();
386 assert_eq!(tags(&t, body), ["p", "div", "ul", "script", "a"]); let a = t.nodes.iter().find(|n| n.tag == "a").unwrap();
388 assert_eq!((a.attr("title"), a.attr("hidden")), (Some("y>z"), Some("")));
389 }
390
391 #[test]
392 fn depth_is_capped_and_hostile_input_ends() {
393 let max_depth: usize = limit("max_depth");
394 let deep = format!("{}x", "<div>".repeat(3 * max_depth));
395 let t = parse(&deep);
396 let (mut stack, mut max) = (vec![(0usize, 0usize)], 0);
398 while let Some((i, d)) = stack.pop() {
399 max = max.max(d);
400 stack.extend(t.nodes[i].kids.iter().filter_map(Kid::node).map(|c| (c, d + 1)));
401 }
402 assert!(max > max_depth / 2 && max <= max_depth + 1, "depth {max}");
403 let fastest = |n: usize| {
406 let nest = format!("{}x", "<b>".repeat(n));
407 let run = |_| {
408 let t0 = Instant::now();
409 let cut = parse(&nest).cut;
410 (t0.elapsed(), cut)
411 };
412 (0..3).map(run).min().unwrap_or_default()
413 };
414 let (small, big) = (fastest(25_000), fastest(100_000));
415 assert!(small.1 == 0 && big.1 == 0 && big.0 < small.0 * 8, "spill is one pass: {small:?} → {big:?}");
416 let hostile = format!("{}{}", "<div>".repeat(3999), "</q>".repeat(200_000));
417 let t0 = Instant::now();
418 let _ = parse(&hostile);
419 assert!(t0.elapsed() < Duration::from_secs(limit::<u64>("parse_budget_s") + 3), "{:?}", t0.elapsed());
421 }
422}