1use alloc::{string::String, vec::Vec};
4
5#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct Name {
8 pub ns: String,
9 pub local: String,
10}
11#[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 pub fn is(&self, ns: &str, local: &str) -> bool {
22 self.name.ns == ns && self.name.local == local
23 }
24 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum Error {
36 Syntax,
37 Limit,
38 Unsupported,
39}
40#[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}
54pub fn valid_char(c: char) -> bool {
56 matches!(c as u32, 9 | 10 | 13 | 0x20..=0xd7ff | 0xe000..=0xfffd | 0x10000..=0x10ffff)
57}
58pub 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("&"),
67 '<' => out.push_str("<"),
68 '>' => out.push_str(">"),
69 '"' => out.push_str("""),
70 '\'' => out.push_str("'"),
71 '\r' => out.push_str(" "),
72 '\n' => out.push_str(" "),
73 '\t' => out.push_str("	"),
74 _ => out.push(c),
75 }
76 }
77 Ok(out)
78}
79fn unescape(s: &str) -> Result<String, Error> {
80 if s.contains('<') || s.contains("]]>") {
81 return Err(Error::Syntax);
82 }
83 let mut out = String::new();
84 let mut rest = s;
85 while let Some(at) = rest.find('&') {
86 out.push_str(&rest[..at]);
87 rest = &rest[at + 1..];
88 let end = rest.find(';').ok_or(Error::Syntax)?;
89 let e = &rest[..end];
90 let c = match e {
91 "amp" => '&',
92 "lt" => '<',
93 "gt" => '>',
94 "quot" => '"',
95 "apos" => '\'',
96 _ => {
97 let (digits, radix) = if let Some(d) = e.strip_prefix("#x") {
98 (d, 16)
99 } else if let Some(d) = e.strip_prefix('#') {
100 (d, 10)
101 } else {
102 return Err(Error::Unsupported);
103 };
104 if digits.is_empty()
105 || !digits.bytes().all(|b| {
106 if radix == 16 {
107 b.is_ascii_hexdigit()
108 } else {
109 b.is_ascii_digit()
110 }
111 })
112 {
113 return Err(Error::Syntax);
114 }
115 char::from_u32(u32::from_str_radix(digits, radix).map_err(|_| Error::Syntax)?)
116 .ok_or(Error::Syntax)?
117 }
118 };
119 if !valid_char(c) {
120 return Err(Error::Syntax);
121 }
122 out.push(c);
123 rest = &rest[end + 1..];
124 }
125 out.push_str(rest);
126 Ok(out)
127}
128type Namespaces = Vec<(String, String)>;
129fn expand(q: &str, namespaces: &Namespaces, attr: bool) -> Result<Name, Error> {
130 let (prefix, local) = q.split_once(':').unwrap_or(("", q));
131 if local.is_empty() || local.contains(':') {
132 return Err(Error::Syntax);
133 }
134 let ns = if prefix.is_empty() && attr {
135 ""
136 } else if prefix == "xml" {
137 "http://www.w3.org/XML/1998/namespace"
138 } else {
139 match namespaces.iter().rev().find(|(p, _)| p == prefix) {
140 Some((_, n)) => n.as_str(),
141 None if prefix.is_empty() => "",
142 _ => return Err(Error::Syntax),
143 }
144 };
145 Ok(Name {
146 ns: String::from(ns),
147 local: String::from(local),
148 })
149}
150struct Parser<'a> {
151 s: &'a str,
152 pos: usize,
153 nodes: usize,
154 lim: Limits,
155}
156impl<'a> Parser<'a> {
157 fn rest(&self) -> &'a str {
158 &self.s[self.pos..]
159 }
160 fn eat(&mut self, s: &str) -> bool {
161 if self.rest().starts_with(s) {
162 self.pos += s.len();
163 true
164 } else {
165 false
166 }
167 }
168 fn ws(&mut self) {
169 while self
170 .rest()
171 .as_bytes()
172 .first()
173 .is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
174 {
175 self.pos += 1;
176 }
177 }
178 fn name(&mut self) -> Result<&'a str, Error> {
179 let start = self.pos;
180 if !self
181 .rest()
182 .as_bytes()
183 .first()
184 .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
185 {
186 return Err(Error::Syntax);
187 }
188 while self
189 .rest()
190 .as_bytes()
191 .first()
192 .is_some_and(|b| b.is_ascii_alphanumeric() || b"_:.-".contains(b))
193 {
194 self.pos += 1;
195 }
196 Ok(&self.s[start..self.pos])
197 }
198 fn node(&mut self, ns: &Namespaces, depth: usize) -> Result<Node, Error> {
199 self.nodes += 1;
200 if depth > self.lim.depth || self.nodes > self.lim.nodes {
201 return Err(Error::Limit);
202 }
203 if !self.eat("<") {
204 return Err(Error::Syntax);
205 }
206 if self.rest().starts_with(['!', '?']) {
207 return Err(Error::Unsupported);
208 }
209 let q = self.name()?;
210 let mut scope = ns.clone();
211 let mut attrs = Vec::new();
212 let empty;
213 loop {
214 let before = self.pos;
215 self.ws();
216 if self.eat("/>") {
217 empty = true;
218 break;
219 }
220 if self.eat(">") {
221 empty = false;
222 break;
223 }
224 if before == self.pos || attrs.len() >= 64 {
225 return Err(Error::Syntax);
226 }
227 let name = self.name()?;
228 self.ws();
229 if !self.eat("=") {
230 return Err(Error::Syntax);
231 }
232 self.ws();
233 let quote = if self.eat("\"") {
234 '"'
235 } else if self.eat("'") {
236 '\''
237 } else {
238 return Err(Error::Syntax);
239 };
240 let end = self.rest().find(quote).ok_or(Error::Syntax)?;
241 let value = unescape(&self.rest()[..end].replace(['\n', '\t'], " "))?;
242 self.pos += end + 1;
243 if attrs.iter().any(|(n, _)| *n == name) {
244 return Err(Error::Syntax);
245 }
246 if name == "xmlns" || name.starts_with("xmlns:") {
247 let prefix = name.strip_prefix("xmlns:").unwrap_or("");
248 if prefix == "xmlns"
249 || (!prefix.is_empty() && value.is_empty())
250 || value == "http://www.w3.org/2000/xmlns/"
251 || (prefix == "xml") != (value == "http://www.w3.org/XML/1998/namespace")
252 {
253 return Err(Error::Syntax);
254 }
255 scope.push((String::from(prefix), value.clone()));
256 if scope.len() > 64
257 || scope.iter().map(|(p, n)| p.len() + n.len()).sum::<usize>() > 4096
258 {
259 return Err(Error::Limit);
260 }
261 }
262 attrs.push((name, value));
263 }
264 let mut node = Node {
265 name: expand(q, &scope, false)?,
266 attrs: Vec::new(),
267 text: String::new(),
268 children: Vec::new(),
269 };
270 for (q, v) in attrs {
271 if q == "xmlns" || q.starts_with("xmlns:") {
272 continue;
273 }
274 let n = expand(q, &scope, true)?;
275 if node.attrs.iter().any(|(a, _)| *a == n) {
276 return Err(Error::Syntax);
277 }
278 node.attrs.push((n, v));
279 }
280 if empty {
281 return Ok(node);
282 }
283 loop {
284 if self.eat("</") {
285 let end = self.name()?;
286 self.ws();
287 if end != q || !self.eat(">") {
288 return Err(Error::Syntax);
289 }
290 break;
291 }
292 if self.rest().starts_with('<') {
293 node.children.push(self.node(&scope, depth + 1)?);
294 } else {
295 let end = self.rest().find('<').ok_or(Error::Syntax)?;
296 node.text.push_str(&unescape(&self.rest()[..end])?);
297 self.pos += end;
298 }
299 }
300 if !node.children.is_empty() {
301 if !node.text.trim_matches([' ', '\t', '\r', '\n']).is_empty() {
302 return Err(Error::Unsupported);
303 }
304 node.text.clear();
305 }
306 Ok(node)
307 }
308}
309pub fn parse(s: &str) -> Result<Node, Error> {
312 parse_with(s, Limits::default())
313}
314pub fn parse_with(s: &str, lim: Limits) -> Result<Node, Error> {
316 if s.len() > lim.bytes {
317 return Err(Error::Limit);
318 }
319 if !s.chars().all(valid_char) {
320 return Err(Error::Syntax);
321 }
322 let normalized = s
323 .strip_prefix('\u{feff}')
324 .unwrap_or(s)
325 .replace("\r\n", "\n")
326 .replace('\r', "\n");
327 let mut p = Parser {
328 s: &normalized,
329 pos: 0,
330 nodes: 0,
331 lim,
332 };
333 if p.eat("<?xml ") {
334 let end = p.rest().find("?>").ok_or(Error::Syntax)?;
335 let decl = &p.rest()[..end];
336 let declaration = alloc::format!("<declaration {decl}/>");
337 let mut dp = Parser {
338 s: &declaration,
339 pos: 0,
340 nodes: 0,
341 lim,
342 };
343 let dn = dp.node(&Vec::new(), 0)?;
344 if dn.attrs.is_empty()
345 || dn.attrs[0].0.local != "version"
346 || dn.attrs[0].1 != "1.0"
347 || !dp.rest().is_empty()
348 {
349 return Err(Error::Unsupported);
350 }
351 let mut last = 0;
352 for (name, value) in &dn.attrs {
353 let order = match name.local.as_str() {
354 "version" if value == "1.0" => 1,
355 "encoding"
356 if matches!(
357 value.as_str(),
358 "UTF-8" | "utf-8" | "UTF-16" | "utf-16" | "UTF-16LE" | "UTF-16BE"
359 ) =>
360 {
361 2
362 }
363 "standalone" if matches!(value.as_str(), "yes" | "no") => 3,
364 _ => return Err(Error::Unsupported),
365 };
366 if !name.ns.is_empty() || order <= last {
367 return Err(Error::Syntax);
368 }
369 last = order;
370 }
371 p.pos += end + 2;
372 }
373 p.ws();
374 let node = p.node(&Vec::new(), 0)?;
375 p.ws();
376 if !p.rest().is_empty() {
377 return Err(Error::Syntax);
378 }
379 Ok(node)
380}