Skip to main content

base/
xml.rs

1// Bounded, namespace-aware XML subset for interchange. No DTD, entities, I/O or XInclude.
2// New native functionality; deliberately rejects constructs it cannot represent losslessly.
3use alloc::{string::String, vec::Vec};
4
5/// Expanded XML name (prefixes are not identities).
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct Name {
8    pub ns: String,
9    pub local: String,
10}
11/// Element-only or text-only node; mixed content is rejected by this subset reader.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct Node {
14    pub name: Name,
15    pub attrs: Vec<(Name, String)>,
16    pub text: String,
17    pub children: Vec<Node>,
18}
19impl Node {
20    /// Test an expanded name.
21    pub fn is(&self, ns: &str, local: &str) -> bool {
22        self.name.ns == ns && self.name.local == local
23    }
24    /// Attribute lookup; the default namespace never applies to unprefixed attributes.
25    pub fn attr(&self, ns: &str, local: &str) -> Option<&str> {
26        self.attrs
27            .iter()
28            .find(|(n, _)| n.ns == ns && n.local == local)
29            .map(|(_, v)| v.as_str())
30    }
31}
32/// Syntax error, resource limit, or an intentionally unsupported XML construct.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum Error {
36    Syntax,
37    Limit,
38    Unsupported,
39}
40/// What one parse may take: the text's bytes, its elements, their nesting. The default
41/// (4 MiB, 30000 elements, 48 levels) is `parse`'s; a reader whose own model bounds its
42/// documents otherwise names what that model can expand to (`parse_with`).
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct Limits {
45    pub bytes: usize,
46    pub nodes: usize,
47    pub depth: usize,
48}
49impl Default for Limits {
50    fn default() -> Self {
51        Self { bytes: 4 * 1024 * 1024, nodes: 30000, depth: 48 }
52    }
53}
54/// XML 1.0 character validity (also used before emitting document text).
55pub fn valid_char(c: char) -> bool {
56    matches!(c as u32, 9 | 10 | 13 | 0x20..=0xd7ff | 0xe000..=0xfffd | 0x10000..=0x10ffff)
57}
58/// Escape text/attribute content, including CR so it survives XML newline normalization.
59pub fn escape(s: &str) -> Result<String, Error> {
60    let mut out = String::new();
61    for c in s.chars() {
62        if !valid_char(c) {
63            return Err(Error::Syntax);
64        }
65        match c {
66            '&' => out.push_str("&amp;"),
67            '<' => out.push_str("&lt;"),
68            '>' => out.push_str("&gt;"),
69            '"' => out.push_str("&quot;"),
70            '\'' => out.push_str("&apos;"),
71            '\r' => out.push_str("&#13;"),
72            '\n' => out.push_str("&#10;"),
73            '\t' => out.push_str("&#9;"),
74            _ => out.push(c),
75        }
76    }
77    Ok(out)
78}
79// references decoded; text: element content, where a literal "]]>" is not allowed (it is in
80// an attribute value)
81fn unescape(s: &str, text: bool) -> Result<String, Error> {
82    if s.contains('<') || (text && s.contains("]]>")) {
83        return Err(Error::Syntax);
84    }
85    let mut out = String::new();
86    let mut rest = s;
87    while let Some(at) = rest.find('&') {
88        out.push_str(&rest[..at]);
89        rest = &rest[at + 1..];
90        let end = rest.find(';').ok_or(Error::Syntax)?;
91        let e = &rest[..end];
92        let c = match e {
93            "amp" => '&',
94            "lt" => '<',
95            "gt" => '>',
96            "quot" => '"',
97            "apos" => '\'',
98            _ => {
99                let (digits, radix) = if let Some(d) = e.strip_prefix("#x") {
100                    (d, 16)
101                } else if let Some(d) = e.strip_prefix('#') {
102                    (d, 10)
103                } else {
104                    return Err(Error::Unsupported);
105                };
106                if digits.is_empty()
107                    || !digits.bytes().all(|b| {
108                        if radix == 16 {
109                            b.is_ascii_hexdigit()
110                        } else {
111                            b.is_ascii_digit()
112                        }
113                    })
114                {
115                    return Err(Error::Syntax);
116                }
117                char::from_u32(u32::from_str_radix(digits, radix).map_err(|_| Error::Syntax)?)
118                    .ok_or(Error::Syntax)?
119            }
120        };
121        if !valid_char(c) {
122            return Err(Error::Syntax);
123        }
124        out.push(c);
125        rest = &rest[end + 1..];
126    }
127    out.push_str(rest);
128    Ok(out)
129}
130type Namespaces = Vec<(String, String)>;
131// an NCName of the subset: a letter or '_' first, then letters, digits, '_', '.', '-'
132fn ncname(s: &str) -> bool {
133    s.as_bytes().first().is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
134        && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
135}
136fn expand(q: &str, namespaces: &Namespaces, attr: bool) -> Result<Name, Error> {
137    let (prefix, local) = q.split_once(':').unwrap_or(("", q));
138    if !ncname(local) || (!prefix.is_empty() && !ncname(prefix)) {
139        return Err(Error::Syntax);
140    }
141    let ns = if prefix.is_empty() && attr {
142        ""
143    } else if prefix == "xml" {
144        "http://www.w3.org/XML/1998/namespace"
145    } else {
146        match namespaces.iter().rev().find(|(p, _)| p == prefix) {
147            Some((_, n)) => n.as_str(),
148            None if prefix.is_empty() => "",
149            _ => return Err(Error::Syntax),
150        }
151    };
152    Ok(Name {
153        ns: String::from(ns),
154        local: String::from(local),
155    })
156}
157struct Parser<'a> {
158    s: &'a str,
159    pos: usize,
160    nodes: usize,
161    lim: Limits,
162    // bytes of the names the tree keeps: each element and attribute name holds a copy of its
163    // namespace URI, so a long URI and many names would multiply a small text
164    kept: usize,
165}
166impl<'a> Parser<'a> {
167    fn keep(&mut self, n: &Name) -> Result<(), Error> {
168        self.kept = self.kept.saturating_add(n.ns.len() + n.local.len());
169        if self.kept > self.lim.bytes.saturating_mul(16) {
170            return Err(Error::Limit);
171        }
172        Ok(())
173    }
174    fn rest(&self) -> &'a str {
175        &self.s[self.pos..]
176    }
177    fn eat(&mut self, s: &str) -> bool {
178        if self.rest().starts_with(s) {
179            self.pos += s.len();
180            true
181        } else {
182            false
183        }
184    }
185    fn ws(&mut self) {
186        while self
187            .rest()
188            .as_bytes()
189            .first()
190            .is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
191        {
192            self.pos += 1;
193        }
194    }
195    fn name(&mut self) -> Result<&'a str, Error> {
196        let start = self.pos;
197        if !self
198            .rest()
199            .as_bytes()
200            .first()
201            .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
202        {
203            return Err(Error::Syntax);
204        }
205        while self
206            .rest()
207            .as_bytes()
208            .first()
209            .is_some_and(|b| b.is_ascii_alphanumeric() || b"_:.-".contains(b))
210        {
211            self.pos += 1;
212        }
213        Ok(&self.s[start..self.pos])
214    }
215    fn node(&mut self, ns: &Namespaces, depth: usize) -> Result<Node, Error> {
216        self.nodes += 1;
217        if depth > self.lim.depth || self.nodes > self.lim.nodes {
218            return Err(Error::Limit);
219        }
220        if !self.eat("<") {
221            return Err(Error::Syntax);
222        }
223        if self.rest().starts_with(['!', '?']) {
224            return Err(Error::Unsupported);
225        }
226        let q = self.name()?;
227        let mut scope = ns.clone();
228        let mut attrs = Vec::new();
229        let empty;
230        loop {
231            let before = self.pos;
232            self.ws();
233            if self.eat("/>") {
234                empty = true;
235                break;
236            }
237            if self.eat(">") {
238                empty = false;
239                break;
240            }
241            if before == self.pos || attrs.len() >= 64 {
242                return Err(Error::Syntax);
243            }
244            let name = self.name()?;
245            self.ws();
246            if !self.eat("=") {
247                return Err(Error::Syntax);
248            }
249            self.ws();
250            let quote = if self.eat("\"") {
251                '"'
252            } else if self.eat("'") {
253                '\''
254            } else {
255                return Err(Error::Syntax);
256            };
257            let end = self.rest().find(quote).ok_or(Error::Syntax)?;
258            let value = unescape(&self.rest()[..end].replace(['\n', '\t'], " "), false)?;
259            self.pos += end + 1;
260            if attrs.iter().any(|(n, _)| *n == name) {
261                return Err(Error::Syntax);
262            }
263            if name == "xmlns" || name.starts_with("xmlns:") {
264                let prefix = name.strip_prefix("xmlns:").unwrap_or("");
265                // "xmlns:" declares a prefix: one there must be (an empty one is no default
266                // namespace), and a valid one
267                if (name != "xmlns" && !ncname(prefix))
268                    || prefix == "xmlns"
269                    || (!prefix.is_empty() && value.is_empty())
270                    || value == "http://www.w3.org/2000/xmlns/"
271                    || (prefix == "xml") != (value == "http://www.w3.org/XML/1998/namespace")
272                {
273                    return Err(Error::Syntax);
274                }
275                scope.push((String::from(prefix), value.clone()));
276                if scope.len() > 64
277                    || scope.iter().map(|(p, n)| p.len() + n.len()).sum::<usize>() > 4096
278                {
279                    return Err(Error::Limit);
280                }
281            }
282            attrs.push((name, value));
283        }
284        let mut node = Node {
285            name: expand(q, &scope, false)?,
286            attrs: Vec::new(),
287            text: String::new(),
288            children: Vec::new(),
289        };
290        self.keep(&node.name)?;
291        for (q, v) in attrs {
292            if q == "xmlns" || q.starts_with("xmlns:") {
293                continue;
294            }
295            let n = expand(q, &scope, true)?;
296            self.keep(&n)?;
297            if node.attrs.iter().any(|(a, _)| *a == n) {
298                return Err(Error::Syntax);
299            }
300            node.attrs.push((n, v));
301        }
302        if empty {
303            return Ok(node);
304        }
305        loop {
306            if self.eat("</") {
307                let end = self.name()?;
308                self.ws();
309                if end != q || !self.eat(">") {
310                    return Err(Error::Syntax);
311                }
312                break;
313            }
314            if self.rest().starts_with('<') {
315                node.children.push(self.node(&scope, depth + 1)?);
316            } else {
317                let end = self.rest().find('<').ok_or(Error::Syntax)?;
318                node.text.push_str(&unescape(&self.rest()[..end], true)?);
319                self.pos += end;
320            }
321        }
322        if !node.children.is_empty() {
323            if !node.text.trim_matches([' ', '\t', '\r', '\n']).is_empty() {
324                return Err(Error::Unsupported);
325            }
326            node.text.clear();
327        }
328        Ok(node)
329    }
330}
331// the inside of "<?xml ... ?>": version="1.0", then optionally encoding and standalone, in this
332// order, each after white space, values as written (a reference or another attribute is no
333// declaration)
334fn xml_decl(d: &str, lim: Limits) -> Result<(), Error> {
335    let mut p = Parser { s: d, pos: 0, nodes: 0, lim, kept: 0 };
336    let mut last = 0;
337    loop {
338        let before = p.pos;
339        p.ws();
340        if p.rest().is_empty() {
341            break;
342        }
343        if before == p.pos {
344            return Err(Error::Syntax); // no white space before the attribute
345        }
346        let name = p.name()?;
347        p.ws();
348        if !p.eat("=") {
349            return Err(Error::Syntax);
350        }
351        p.ws();
352        let quote = if p.eat("\"") {
353            '"'
354        } else if p.eat("'") {
355            '\''
356        } else {
357            return Err(Error::Syntax);
358        };
359        let end = p.rest().find(quote).ok_or(Error::Syntax)?;
360        let value = &p.rest()[..end];
361        p.pos += end + 1;
362        let order = match name {
363            "version" if value == "1.0" => 1,
364            "encoding" if matches!(value, "UTF-8" | "utf-8" | "UTF-16" | "utf-16" | "UTF-16LE" | "UTF-16BE") => 2,
365            "standalone" if matches!(value, "yes" | "no") => 3,
366            _ => return Err(Error::Unsupported),
367        };
368        if order <= last || (last == 0 && order != 1) {
369            return Err(if last == 0 { Error::Unsupported } else { Error::Syntax });
370        }
371        last = order;
372    }
373    if last == 0 {
374        return Err(Error::Unsupported); // no version
375    }
376    Ok(())
377}
378/// Parse a bounded XML subset. DTDs, processing instructions, comments, CDATA and mixed
379/// content are explicitly rejected. No resources are ever resolved or fetched.
380pub fn parse(s: &str) -> Result<Node, Error> {
381    parse_with(s, Limits::default())
382}
383/// `parse` within other limits than the default ones.
384pub fn parse_with(s: &str, lim: Limits) -> Result<Node, Error> {
385    if s.len() > lim.bytes {
386        return Err(Error::Limit);
387    }
388    if !s.chars().all(valid_char) {
389        return Err(Error::Syntax);
390    }
391    let normalized = s
392        .strip_prefix('\u{feff}')
393        .unwrap_or(s)
394        .replace("\r\n", "\n")
395        .replace('\r', "\n");
396    let mut p = Parser {
397        s: &normalized,
398        pos: 0,
399        nodes: 0,
400        lim,
401        kept: 0,
402    };
403    // the declaration: "<?xml" and white space (a space, a tab, a line break), read as it is
404    // written -- no references, no namespace attributes
405    let r = p.rest().as_bytes();
406    if r.starts_with(b"<?xml") && r.get(5).is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n')) {
407        p.pos += 5;
408        let end = p.rest().find("?>").ok_or(Error::Syntax)?;
409        xml_decl(&p.rest()[..end], lim)?;
410        p.pos += end + 2;
411    }
412    p.ws();
413    let node = p.node(&Vec::new(), 0)?;
414    p.ws();
415    if !p.rest().is_empty() {
416        return Err(Error::Syntax);
417    }
418    Ok(node)
419}