use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};
use crate::error::{RejectKind, Rejection};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
max_bytes: usize,
max_depth: usize,
max_elements: usize,
}
impl Limits {
pub const MAX_BYTES_CAP: usize = 64 * 1024 * 1024;
pub const MAX_DEPTH_CAP: usize = 32;
pub const MAX_ELEMENTS_CAP: usize = 4_000_000;
#[must_use]
pub fn with_max_bytes(mut self, n: usize) -> Self {
self.max_bytes = n.clamp(1, Self::MAX_BYTES_CAP);
self
}
#[must_use]
pub fn with_max_depth(mut self, n: usize) -> Self {
self.max_depth = n.clamp(1, Self::MAX_DEPTH_CAP);
self
}
#[must_use]
pub fn with_max_elements(mut self, n: usize) -> Self {
self.max_elements = n.clamp(1, Self::MAX_ELEMENTS_CAP);
self
}
#[must_use]
pub fn max_bytes(&self) -> usize {
self.max_bytes
}
#[must_use]
pub fn max_depth(&self) -> usize {
self.max_depth
}
#[must_use]
pub fn max_elements(&self) -> usize {
self.max_elements
}
}
impl Default for Limits {
fn default() -> Self {
Self {
max_bytes: 4 * 1024 * 1024,
max_depth: 16,
max_elements: 250_000,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Element {
pub name: String,
pub attrs: Vec<(String, String)>,
pub children: Vec<Element>,
}
fn limits(message: String) -> Rejection {
Rejection::new(RejectKind::Limits, "[decoder limits]", message)
}
fn malformed(e: impl std::fmt::Display) -> Rejection {
Rejection::schema(
"[UFTP §4.2] well-formed UTF-8 XML",
format!("The document is not well-formed XML: {e}."),
)
}
struct Scopes(Vec<Vec<(String, String)>>);
impl Scopes {
fn lookup(&self, prefix: &str) -> Option<&str> {
if prefix == "xml" {
return Some("http://www.w3.org/XML/1998/namespace");
}
self.0
.iter()
.rev()
.flat_map(|s| s.iter().rev())
.find(|(p, _)| p == prefix)
.map(|(_, u)| u.as_str())
}
}
struct Tag {
name: String,
namespaced: bool,
attrs: Vec<(String, String)>,
bindings: Vec<(String, String)>,
}
fn read_tag(start: &BytesStart<'_>, scopes: &Scopes) -> Result<Tag, Rejection> {
let qname: String = start.name().as_ref().to_owned();
let mut bindings = Vec::new();
let mut raw = Vec::new();
for attr in start.attributes() {
let attr = attr.map_err(malformed)?;
let key: String = attr.key.as_ref().to_owned();
let value = attr
.normalized_value(XmlVersion::Implicit1_0)
.map_err(malformed)?
.into_owned();
if let Some(bad) = value.chars().find(|&c| !crate::xml::writer::is_xml_char(c)) {
return Err(malformed(format!(
"attribute {key} contains U+{:04X}, which XML does not allow",
u32::from(bad),
key = crate::error::quote(&key)
)));
}
if key == "xmlns" {
bindings.push((String::new(), value));
} else if let Some(p) = key.strip_prefix("xmlns:") {
if value.is_empty() {
return Err(malformed(format!(
"namespace prefix {p} is bound to an empty name",
p = crate::error::quote(&p)
)));
}
bindings.push((p.to_owned(), value));
} else {
raw.push((key, value));
}
}
let with_own = |prefix: &str| -> Option<String> {
bindings
.iter()
.rev()
.find(|(p, _)| p == prefix)
.map(|(_, u)| u.clone())
.or_else(|| scopes.lookup(prefix).map(str::to_owned))
};
let (name, namespaced) = if let Some((prefix, local)) = qname.split_once(':') {
if with_own(prefix).is_none() {
return Err(malformed(format!(
"prefix {prefix} of <{qname}> is not bound to a namespace",
prefix = crate::error::quote(&prefix),
qname = crate::error::name(&qname)
)));
}
(local.to_owned(), true)
} else {
(qname.clone(), with_own("").is_some_and(|u| !u.is_empty()))
};
let mut attrs = Vec::new();
for (key, value) in raw {
match key.split_once(':') {
Some((prefix, _)) => {
if with_own(prefix).is_none() {
return Err(malformed(format!(
"prefix {prefix} of attribute {key} is not bound to a namespace",
prefix = crate::error::quote(&prefix),
key = crate::error::quote(&key)
)));
}
}
None => attrs.push((key, value)),
}
}
Ok(Tag {
name,
namespaced,
attrs,
bindings,
})
}
#[allow(clippy::too_many_lines)] pub(crate) fn parse(bytes: &[u8], limits: &Limits) -> Result<Element, Rejection> {
if bytes.len() > limits.max_bytes {
return Err(self::limits(format!(
"The document has {} bytes; the limit is {}.",
bytes.len(),
limits.max_bytes
)));
}
let text = std::str::from_utf8(bytes).map_err(|e| {
Rejection::schema(
"[UFTP §4.2] messages use UTF-8",
format!(
"The document is not UTF-8 (invalid byte at offset {}).",
e.valid_up_to()
),
)
})?;
let mut reader = Reader::from_str(text);
let config = reader.config_mut();
config.check_end_names = true;
config.expand_empty_elements = false;
let mut scopes = Scopes(Vec::new());
let mut stack: Vec<Option<Element>> = Vec::new();
let mut root: Option<Element> = None;
let mut elements = 0usize;
let mut seen_decl = false;
let mut seen_any = false;
loop {
let event = reader.read_event().map_err(malformed)?;
match event {
Event::Decl(decl) => {
if seen_decl || seen_any {
return Err(malformed("the XML declaration is not at the start"));
}
seen_decl = true;
if let Some(enc) = decl.encoding() {
let enc = enc.map_err(malformed)?;
if !enc.eq_ignore_ascii_case("utf-8") {
return Err(Rejection::schema(
"[UFTP §4.2] messages use UTF-8",
format!(
"The document declares encoding {enc}.",
enc = crate::error::quote(&enc)
),
));
}
}
}
Event::DocType(_) => {
return Err(Rejection::schema(
"[XML] no DOCTYPE or entity declarations",
"The document contains a DOCTYPE; UFTP messages never do, and entity declarations are refused.",
));
}
Event::PI(_) => {
return Err(Rejection::schema(
"[XML] no processing instructions",
"The document contains a processing instruction; only the XML declaration is allowed.",
));
}
Event::Start(ref start) | Event::Empty(ref start) => {
seen_any = true;
if root.is_some() && stack.is_empty() {
return Err(malformed("there is more than one root element"));
}
elements += 1;
if elements > limits.max_elements {
return Err(self::limits(format!(
"The document has more than {} elements.",
limits.max_elements
)));
}
if stack.len() + 1 > limits.max_depth {
return Err(self::limits(format!(
"The document is nested deeper than {} levels.",
limits.max_depth
)));
}
let empty = matches!(event, Event::Empty(_));
let tag = read_tag(start, &scopes)?;
let in_extension = stack.iter().any(Option::is_none);
let node = if in_extension || tag.namespaced {
if stack.is_empty() {
return Err(Rejection::schema(
"[XSD] UFTP messages are in no namespace (SS-08)",
format!(
"The root element <{}> is in a namespace; UFTP elements are not.",
crate::error::name(&tag.name)
),
));
}
None
} else {
Some(Element {
name: tag.name,
attrs: tag.attrs,
children: Vec::new(),
})
};
if empty {
close(&mut stack, &mut root, node);
} else {
scopes.0.push(tag.bindings);
stack.push(node);
}
}
Event::End(_) => {
scopes.0.pop();
let node = stack
.pop()
.ok_or_else(|| malformed("an end tag has no start"))?;
close(&mut stack, &mut root, node);
}
Event::Text(t) => {
let in_uftp = stack.last().is_some_and(Option::is_some);
let blank = t.as_ref().bytes().all(|b| b.is_ascii_whitespace());
if !blank && (in_uftp || stack.is_empty()) {
return Err(Rejection::schema(
"[XSD] UFTP elements have no text content",
"The document has text where UFTP allows none.",
));
}
}
Event::GeneralRef(_) | Event::CData(_) => {
let in_uftp = stack.last().is_some_and(Option::is_some);
if in_uftp || stack.is_empty() {
return Err(Rejection::schema(
"[XSD] UFTP elements have no text content",
"The document has text where UFTP allows none.",
));
}
}
Event::Comment(_) => {}
Event::Eof => break,
}
}
if !stack.is_empty() {
return Err(malformed("the document ends inside an element"));
}
root.ok_or_else(|| malformed("the document has no root element"))
}
fn close(stack: &mut [Option<Element>], root: &mut Option<Element>, node: Option<Element>) {
match stack.last_mut() {
Some(Some(parent)) => {
if let Some(child) = node {
parent.children.push(child);
}
}
Some(None) => {}
None => *root = node,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn p(s: &str) -> Result<Element, Rejection> {
parse(s.as_bytes(), &Limits::default())
}
#[test]
fn plain_tree() {
let e =
p(r#"<?xml version="1.0" encoding="UTF-8"?><A x="1"><B y="<2"/><B/></A>"#).unwrap();
assert_eq!(e.name, "A");
assert_eq!(e.attrs, vec![("x".into(), "1".into())]);
assert_eq!(e.children.len(), 2);
assert_eq!(e.children[0].attrs[0].1, "<2");
}
#[test]
fn doctype_refused() {
let r = p(r#"<!DOCTYPE A [<!ENTITY x "y">]><A/>"#).unwrap_err();
assert_eq!(r.rule_ref(), "[XML] no DOCTYPE or entity declarations");
}
#[test]
fn undeclared_entity_refused() {
assert!(p(r#"<A x="&x;"/>"#).is_err());
}
#[test]
fn extension_elements_skipped() {
let e = p(r#"<A xmlns:e="urn:ext"><e:X><Y/></e:X><B/><Z xmlns="urn:other"/></A>"#).unwrap();
assert_eq!(e.children.len(), 1);
assert_eq!(e.children[0].name, "B");
}
#[test]
fn namespaced_root_refused() {
assert!(p(r#"<A xmlns="urn:x"/>"#).is_err());
}
#[test]
fn depth_and_count_limits() {
let deep = format!("{}{}", "<A>".repeat(40), "</A>".repeat(40));
assert_eq!(p(&deep).unwrap_err().kind(), RejectKind::Limits);
let many = format!("<A>{}</A>", "<B/>".repeat(20));
let r = parse(many.as_bytes(), &Limits::default().with_max_elements(10)).unwrap_err();
assert_eq!(r.kind(), RejectKind::Limits);
}
#[test]
fn forbidden_characters_refused() {
assert!(p("<A x=\"�\"/>").is_err());
assert!(p("<A x=\"\"/>").is_err());
assert!(p("<A x=\"a\u{1}b\"/>").is_err());
assert!(p("<A x=\"\"/>").is_err());
assert_eq!(
p("<A x=\"	\u{10348}\"/>").unwrap().attrs[0].1,
"\t\u{10348}"
);
}
#[test]
fn text_refused() {
assert!(p("<A>hello</A>").is_err());
assert!(p("<A>\n <B/>\n</A>").is_ok());
}
}