formats/xml/mod.rs
1// xml -- XML for JFLib, one reader in two kinds, and a bounded tree on top. New native functionality;
2// no DTD, no I/O, no XInclude, nothing is ever fetched.
3//
4// Reader (reader.rs) the strict pull reader: well-formed XML 1.0 with namespaces; events,
5// positions, the raw text of an element (skip); DOCTYPE refused
6// Lenient (lenient.rs) the forgiving reader of files from editors (SVG, fontconfig, theme parts):
7// tokens, nothing is an error, a DOCTYPE's internal entities with a budget
8// parse(text) -> Node a tree of the strict subset for interchange formats: element-only or
9// text-only nodes, names expanded to their namespaces; comments, processing
10// instructions, CDATA and mixed content refused (Unsupported); bounded
11// (Limits: bytes, elements, nesting; the names it keeps)
12// escape(text), valid_char(c) for writers
13//
14// Every reader of the library is one of these two (img_svg, diagram_io, diagram_core's theme parts,
15// text's fontconfig files): one place to fuzz, one set of limits per caller.
16use alloc::{string::String, vec::Vec};
17
18pub mod lenient;
19pub mod reader;
20
21pub use lenient::{Lenient, Token};
22pub use reader::{Attr, Event, ReadError, Reader, Start, NS_XML, NS_XMLNS};
23
24/// Expanded XML name (prefixes are not identities).
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct Name {
27 pub ns: String,
28 pub local: String,
29}
30/// Element-only or text-only node; mixed content is rejected by this subset reader.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct Node {
33 pub name: Name,
34 pub attrs: Vec<(Name, String)>,
35 pub text: String,
36 pub children: Vec<Node>,
37}
38impl Node {
39 /// Test an expanded name.
40 pub fn is(&self, ns: &str, local: &str) -> bool {
41 self.name.ns == ns && self.name.local == local
42 }
43 /// Attribute lookup; the default namespace never applies to unprefixed attributes.
44 pub fn attr(&self, ns: &str, local: &str) -> Option<&str> {
45 self.attrs
46 .iter()
47 .find(|(n, _)| n.ns == ns && n.local == local)
48 .map(|(_, v)| v.as_str())
49 }
50}
51/// Syntax error, resource limit, or an intentionally unsupported XML construct.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum Error {
55 /// not well-formed (or, for the tree, a name it cannot keep)
56 Syntax,
57 /// a limit of the tree: bytes, elements, nesting, attributes, the names it keeps
58 Limit,
59 /// a construct the reader does not take: a DOCTYPE or other declaration, an encoding other
60 /// than UTF-8 and UTF-16, XML other than 1.0; for the tree also comments, processing
61 /// instructions, CDATA and mixed content
62 Unsupported,
63 /// (Reader) more open elements than its depth
64 Depth,
65 /// (Reader) more attributes on one element than allowed, or more than 64 namespace bindings
66 /// in scope
67 Attributes,
68}
69/// What one parse may take: the text's bytes, its elements, their nesting. The default
70/// (4 MiB, 30000 elements, 48 levels) is `parse`'s; a reader whose own model bounds its
71/// documents otherwise names what that model can expand to (`parse_with`).
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct Limits {
74 pub bytes: usize,
75 pub nodes: usize,
76 pub depth: usize,
77}
78impl Default for Limits {
79 fn default() -> Self {
80 Self { bytes: 4 * 1024 * 1024, nodes: 30000, depth: 48 }
81 }
82}
83/// XML 1.0 character validity (also used before emitting document text).
84pub fn valid_char(c: char) -> bool {
85 matches!(c as u32, 9 | 10 | 13 | 0x20..=0xd7ff | 0xe000..=0xfffd | 0x10000..=0x10ffff)
86}
87/// Escape text/attribute content, including CR so it survives XML newline normalization.
88pub fn escape(s: &str) -> Result<String, Error> {
89 let mut out = String::new();
90 for c in s.chars() {
91 if !valid_char(c) {
92 return Err(Error::Syntax);
93 }
94 match c {
95 '&' => out.push_str("&"),
96 '<' => out.push_str("<"),
97 '>' => out.push_str(">"),
98 '"' => out.push_str("""),
99 '\'' => out.push_str("'"),
100 '\r' => out.push_str(" "),
101 '\n' => out.push_str(" "),
102 '\t' => out.push_str("	"),
103 _ => out.push(c),
104 }
105 }
106 Ok(out)
107}
108/// Parse a bounded XML subset into a tree. DTDs, processing instructions, comments, CDATA and
109/// mixed content are explicitly rejected (Unsupported). No resources are ever resolved or fetched.
110pub fn parse(s: &str) -> Result<Node, Error> {
111 parse_with(s, Limits::default())
112}
113
114// the bindings' bytes one element may have in scope (prefixes and URIs)
115const SCOPE_BYTES: usize = 4096;
116// the attributes of one element, namespace declarations included
117const TREE_ATTRS: usize = 64;
118
119/// `parse` within other limits than the default ones. The tree is built from the strict Reader
120/// without recursion; a limit of the reader (nesting, attributes, bindings) is Limit here.
121pub fn parse_with(s: &str, lim: Limits) -> Result<Node, Error> {
122 if s.len() > lim.bytes {
123 return Err(Error::Limit);
124 }
125 let mut r = Reader::new(s, lim.depth.saturating_add(1), TREE_ATTRS);
126 // the open elements and the bytes of the bindings each one made
127 let mut stack: Vec<(Node, usize)> = Vec::new();
128 let (mut nodes, mut kept, mut scope) = (0usize, 0usize, 0usize);
129 // every name holds a copy of its namespace URI, so a long URI and many names would multiply a
130 // small text: the names the tree keeps are bounded too
131 let kept_max = lim.bytes.saturating_mul(16);
132 let mut root = None;
133 loop {
134 let ev = r.next().map_err(|e| match e.error {
135 Error::Depth | Error::Attributes => Error::Limit,
136 e => e,
137 })?;
138 match ev {
139 Event::Start(st) => {
140 nodes += 1;
141 if nodes > lim.nodes {
142 return Err(Error::Limit);
143 }
144 let own: usize = st.attrs.iter().filter(|a| a.ns == NS_XMLNS).map(|a| a.local.len() + a.value.len()).sum();
145 scope += own;
146 if scope > SCOPE_BYTES {
147 return Err(Error::Limit);
148 }
149 let name = Name { ns: String::from(&*st.ns), local: String::from(st.local) };
150 kept = kept.saturating_add(name.ns.len() + name.local.len());
151 let mut attrs = Vec::with_capacity(st.attrs.len());
152 for a in st.attrs.iter().filter(|a| a.ns != NS_XMLNS) {
153 kept = kept.saturating_add(a.ns.len() + a.local.len());
154 attrs.push((Name { ns: String::from(&*a.ns), local: String::from(a.local) }, String::from(&*a.value)));
155 }
156 if kept > kept_max {
157 return Err(Error::Limit);
158 }
159 stack.push((Node { name, attrs, text: String::new(), children: Vec::new() }, own));
160 }
161 Event::End { .. } => {
162 let Some((mut node, own)) = stack.pop() else { return Err(Error::Syntax) };
163 scope -= own;
164 if !node.children.is_empty() {
165 if !node.text.trim_matches([' ', '\t', '\r', '\n']).is_empty() {
166 return Err(Error::Unsupported);
167 }
168 node.text.clear();
169 }
170 match stack.last_mut() {
171 Some((parent, _)) => parent.children.push(node),
172 None => root = Some(node),
173 }
174 }
175 Event::Text(t) => {
176 if let Some((node, _)) = stack.last_mut() {
177 node.text.push_str(&t);
178 }
179 }
180 Event::CData(_) | Event::Comment(_) | Event::Pi { .. } => return Err(Error::Unsupported),
181 Event::Eof => return root.ok_or(Error::Syntax),
182 }
183 }
184}