//! A small owned XML tree over quick-xml, for OPF, NCX, nav, FB2 and well-formed XHTML. Entity declarations are //! refused; only XML's and HTML's named entities and numeric references resolve; depth is capped while building, //! with an explicit stack, so no input recurses. use crate::{FormatError, Limits, Result, entities}; use quick_xml::XmlVersion; use quick_xml::events::{BytesStart, Event}; #[derive(Clone, Debug)] pub(crate) enum XNode { El(XEl), Text(String), } #[derive(Clone, Debug, Default)] pub(crate) struct XEl { /// The qualified name as written (`dc:title`). pub name: String, pub attrs: Vec<(String, String)>, pub children: Vec, } pub(crate) fn local(q: &str) -> &str { q.rsplit(':').next().unwrap_or(q) } impl XEl { pub fn new(name: &str) -> XEl { XEl { name: name.to_owned(), ..XEl::default() } } pub fn local(&self) -> &str { local(&self.name) } pub fn is(&self, l: &str) -> bool { self.local().eq_ignore_ascii_case(l) } /// An attribute by exact qualified name, else by local name. pub fn attr(&self, name: &str) -> Option<&str> { self.attrs .iter() .find(|(k, _)| k == name) .or_else(|| self.attrs.iter().find(|(k, _)| local(k).eq_ignore_ascii_case(local(name)))) .map(|(_, v)| v.as_str()) } pub fn elements(&self) -> impl Iterator { self.children.iter().filter_map(|c| if let XNode::El(e) = c { Some(e) } else { None }) } pub fn child(&self, l: &str) -> Option<&XEl> { self.elements().find(|e| e.is(l)) } pub fn children_named<'s>(&'s self, l: &'s str) -> impl Iterator + 's { self.elements().filter(move |e| e.is(l)) } /// Every descendant element in document order (iterative). pub fn descendants(&self) -> Vec<&XEl> { let mut out = Vec::new(); let mut stack: Vec<&XEl> = self.elements().collect::>().into_iter().rev().collect(); while let Some(e) = stack.pop() { out.push(e); let kids: Vec<&XEl> = e.elements().collect(); stack.extend(kids.into_iter().rev()); } out } pub fn find(&self, l: &str) -> Option<&XEl> { self.descendants().into_iter().find(|e| e.is(l)) } /// All text below, in order (iterative). pub fn text(&self) -> String { let mut s = String::new(); let mut stack: Vec<&XNode> = self.children.iter().rev().collect(); while let Some(n) = stack.pop() { match n { XNode::Text(t) => s.push_str(t), XNode::El(e) => stack.extend(e.children.iter().rev()), } } s } pub fn push_text(&mut self, t: &str) { if t.is_empty() { return; } if let Some(XNode::Text(last)) = self.children.last_mut() { last.push_str(t); } else { self.children.push(XNode::Text(t.to_owned())); } } } fn element(e: &BytesStart) -> XEl { let name = e.name().as_ref().to_owned(); let mut attrs = Vec::new(); for a in e.attributes().with_checks(false).flatten() { let key = a.key.as_ref().to_owned(); let value = match a.normalized_value_with(XmlVersion::Implicit1_0, 16, entities::resolve) { Ok(v) => v.into_owned(), Err(_) => a.value.to_string(), }; attrs.push((key, value)); } XEl { name, attrs, children: Vec::new() } } /// Parses a whole document and returns its root element. pub(crate) fn parse(s: &str, limits: &Limits) -> Result { if s.len() > limits.max_xml { return Err(FormatError::TooLarge(format!("an XML document over {} MiB", limits.max_xml >> 20))); } let mut r = quick_xml::Reader::from_str(s); { let c = r.config_mut(); c.check_end_names = true; c.trim_text(false); } let mut stack: Vec = Vec::new(); let mut skip = 0usize; let mut root: Option = None; loop { let ev = r.read_event().map_err(|e| FormatError::Malformed(format!("XML at byte {}: {e}", r.buffer_position())))?; match ev { Event::Eof => break, Event::DocType(t) => { let d = t.xml10_content().to_ascii_lowercase(); if d.contains(" { if root.is_some() { return Err(FormatError::Malformed("XML: content after the root element".into())); } if skip > 0 || stack.len() >= limits.max_depth { skip += 1; } else { stack.push(element(&e)); } } Event::Empty(e) => { if skip == 0 && stack.len() < limits.max_depth { let el = element(&e); match stack.last_mut() { Some(top) => top.children.push(XNode::El(el)), None if root.is_none() => root = Some(el), None => return Err(FormatError::Malformed("XML: two root elements".into())), } } } Event::End(_) => { if skip > 0 { skip -= 1; } else if let Some(done) = stack.pop() { match stack.last_mut() { Some(top) => top.children.push(XNode::El(done)), None => root = Some(done), } } } Event::Text(t) => { if let Some(top) = stack.last_mut() { top.push_text(&t.xml10_content()); } } Event::CData(t) => { if let Some(top) = stack.last_mut() { top.push_text(&t.xml10_content()); } } Event::GeneralRef(g) => { if let Some(top) = stack.last_mut() { let resolved: String = if g.is_char_ref() { match g.resolve_char_ref() { Ok(Some(c)) => c.to_string(), _ => String::new(), } } else { let name = g.xml10_content(); match entities::resolve(&name) { Some(v) => v.to_owned(), None => format!("&{name};"), } }; top.push_text(&resolved); } } _ => {} } } if !stack.is_empty() { return Err(FormatError::Malformed("XML: the document ends inside an element".into())); } root.ok_or_else(|| FormatError::Malformed("XML: no root element".into())) } #[cfg(test)] mod tests { use super::*; #[test] fn entities_and_depth() { let l = Limits { max_depth: 3, ..Limits::default() }; let root = parse("x& A&unknown;deep", &l).unwrap(); assert_eq!(root.text(), "x&\u{a0}A&unknown;deep"); assert!(root.find("d").is_none()); let err = parse("]>&x;", &l).unwrap_err(); assert!(matches!(err, FormatError::Unsafe(_))); } }