Skip to main content

formats/xml/
lenient.rs

1// lenient -- the forgiving reader of formats::xml: what a browser or an editor would still show
2//
3//   Lenient::new(text) / with_limits(text, attrs, entities, expand)
4//   l.next() -> Token          Start { name, attrs (raw values), empty }, End { name }, Text (raw), CData, Eof
5//   l.decode(raw, &mut out)    a raw text or attribute value with its references replaced
6//   l.truncated()              the input ended inside a tag, or the entities' budget was spent
7//
8// For files from editors, which are often sloppy (SVG, fontconfig, theme parts): nothing is an error.
9// Tokens: a start tag (its name as written, at most `attrs` attributes: a repeated one counts, the first
10// stays; a value in ' or ", unquoted to the next blank or '>', none for a bare name; a stray quote, '=' or
11// '/' is skipped; '<' ends a broken tag), an end tag (its name; the rest up to '>' is skipped), text up to
12// the next '<' (a lone '<' that starts no tag is text), CDATA as written.  Skipped: the XML declaration and
13// processing instructions, comments, every `<!...>` declaration; a DOCTYPE's internal subset gives the
14// entities: its `<!ENTITY name "value">` declarations (general ones; parameter and external entities are
15// skipped; the first declaration of a name stays; at most `entities`, values of at most 64 KiB, with
16// character references and the five predefined entities replaced, other references kept as written so no
17// entity grows exponentially).  An unterminated construct ends the document there.
18//
19// References (decode): the five predefined entities, character references (decimal, x or X; a number that
20// is no character, or 0, gives U+FFFD), the DOCTYPE's entities while `expand` bytes of their values have
21// not been used up (beyond: the reference is dropped and truncated() set); an unknown entity stays as
22// written, and so does an '&' that has no ';' within 63 bytes before the next '&'.  Nesting, a second
23// root, mismatched end tags and limits on elements are the caller's: it builds the tree it needs.
24
25use alloc::string::String;
26use alloc::vec::Vec;
27
28/// the default limit of attributes per start tag
29pub const ATTRS: usize = 512;
30/// the default limit of entity declarations in a DOCTYPE
31pub const ENTITIES: usize = 256;
32/// the default budget of bytes that entity references may produce in all
33pub const EXPAND: usize = 32 << 20;
34
35/// what the lenient reader found next
36#[derive(Clone, Debug, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum Token<'a> {
39    /// a start tag: its name as written and its attributes with their raw values ("" for none)
40    Start { name: &'a str, attrs: Vec<(&'a str, &'a str)>, empty: bool },
41    /// an end tag
42    End { name: &'a str },
43    /// character data as written (decode replaces the references)
44    Text(&'a str),
45    /// a CDATA section's content as written
46    CData(&'a str),
47    /// the end of the text
48    Eof,
49}
50
51/// the forgiving reader (see the top of this file)
52pub struct Lenient<'a> {
53    s: &'a str,
54    i: usize,
55    ents: Vec<(String, String)>,
56    expanded: usize,
57    truncated: bool,
58    max_attrs: usize,
59    max_ents: usize,
60    max_expand: usize,
61}
62
63fn is_blank(c: u8) -> bool {
64    matches!(c, b' ' | b'\t' | b'\r' | b'\n')
65}
66
67fn name_end(c: u8) -> bool {
68    is_blank(c) || matches!(c, b'/' | b'>' | b'=' | b'<' | b'"' | b'\'')
69}
70
71fn find(s: &[u8], from: usize, pat: &[u8]) -> Option<usize> {
72    if pat.is_empty() || from >= s.len() {
73        return None;
74    }
75    let first = pat[0];
76    let mut i = from;
77    while i + pat.len() <= s.len() {
78        if s[i] == first && &s[i..i + pat.len()] == pat {
79            return Some(i);
80        }
81        i += 1;
82    }
83    None
84}
85
86// a repeated attribute (not well-formed): the first one stays.  Sorted once per element; a search per
87// attribute would cost up to `attrs` steps for each attribute of the file
88fn dedup_first(attrs: &mut Vec<(&str, &str)>) {
89    if attrs.len() <= 8 {
90        let mut k = 1;
91        while k < attrs.len() {
92            if attrs[..k].iter().any(|(x, _)| *x == attrs[k].0) {
93                attrs.remove(k);
94            } else {
95                k += 1;
96            }
97        }
98        return;
99    }
100    let mut ix: Vec<u32> = (0..attrs.len() as u32).collect();
101    ix.sort_unstable_by(|&a, &b| attrs[a as usize].0.cmp(attrs[b as usize].0).then(a.cmp(&b)));
102    let mut dup = alloc::vec![false; attrs.len()];
103    for w in ix.windows(2) {
104        if attrs[w[0] as usize].0 == attrs[w[1] as usize].0 {
105            dup[w[1] as usize] = true;
106        }
107    }
108    let mut k = 0;
109    attrs.retain(|_| {
110        k += 1;
111        !dup[k - 1]
112    });
113}
114
115impl<'a> Lenient<'a> {
116    /// a reader of `s` with the default limits (ATTRS, ENTITIES, EXPAND)
117    pub fn new(s: &'a str) -> Self {
118        Self::with_limits(s, ATTRS, ENTITIES, EXPAND)
119    }
120
121    /// a reader with at most `attrs` attributes per start tag, `entities` entity declarations and `expand`
122    /// bytes of entity values in all
123    pub fn with_limits(s: &'a str, attrs: usize, entities: usize, expand: usize) -> Self {
124        Lenient { s, i: 0, ents: Vec::new(), expanded: 0, truncated: false, max_attrs: attrs, max_ents: entities, max_expand: expand }
125    }
126
127    /// whether the input ended inside a tag or the entities' budget was spent
128    pub fn truncated(&self) -> bool {
129        self.truncated
130    }
131
132    /// the offset the reader is at
133    pub fn pos(&self) -> usize {
134        self.i
135    }
136
137    /// a raw text or attribute value (from a token) with its references replaced, appended to `out`
138    pub fn decode(&mut self, raw: &str, out: &mut String) {
139        let b = raw.as_bytes();
140        let mut i = 0;
141        let mut start = 0;
142        while i < b.len() {
143            if b[i] != b'&' {
144                i += 1;
145                continue;
146            }
147            // a bare '&' must not swallow a real reference after it ("AT&T &amp; Co")
148            let Some(semi) = b[i + 1..].iter().take(63).position(|&c| c == b';' || c == b'&').filter(|&k| b[i + 1 + k] == b';').map(|k| k + 1) else {
149                i += 1;
150                continue;
151            };
152            out.push_str(&raw[start..i]);
153            let name = &raw[i + 1..i + semi];
154            let mut done = true;
155            match name {
156                "lt" => out.push('<'),
157                "gt" => out.push('>'),
158                "amp" => out.push('&'),
159                "quot" => out.push('"'),
160                "apos" => out.push('\''),
161                _ if name.starts_with('#') => {
162                    let nb = name.as_bytes();
163                    let (digits, radix) = if nb.get(1).map(|c| c | 32) == Some(b'x') { (&name[2..], 16) } else { (&name[1..], 10) };
164                    let v = u32::from_str_radix(digits, radix).ok();
165                    out.push(v.and_then(char::from_u32).filter(|&c| c != '\0').unwrap_or('\u{FFFD}'));
166                }
167                _ => {
168                    // sorted by name: no walk over all of them per reference
169                    match self.ents.binary_search_by(|(n, _)| n.as_str().cmp(name)).ok() {
170                        Some(k) if self.expanded + self.ents[k].1.len() <= self.max_expand => {
171                            self.expanded += self.ents[k].1.len();
172                            out.push_str(&self.ents[k].1);
173                        }
174                        Some(_) => self.truncated = true,
175                        None => done = false,
176                    }
177                }
178            }
179            if !done {
180                // an unknown entity stays as written
181                out.push_str(&raw[i..i + semi + 1]);
182            }
183            i += semi + 1;
184            start = i;
185        }
186        out.push_str(&raw[start..]);
187    }
188
189    // <!DOCTYPE ... [ subset ] >: the entity declarations of the subset
190    fn doctype(&mut self) {
191        let src: &'a str = self.s;
192        let s = src.as_bytes();
193        let mut i = self.i;
194        let mut depth = 0;
195        while i < s.len() {
196            match s[i] {
197                b'[' => depth += 1,
198                b']' => depth -= 1,
199                b'"' | b'\'' => {
200                    let q = s[i];
201                    i += 1;
202                    while i < s.len() && s[i] != q {
203                        i += 1;
204                    }
205                }
206                b'<' if depth > 0 && s[i..].starts_with(b"<!ENTITY") => {
207                    // the declaration ends at the first ">" outside quotes
208                    let mut end = i + 8;
209                    let mut q = 0u8;
210                    while end < s.len() && (q != 0 || s[end] != b'>') {
211                        if q == 0 && (s[end] == b'"' || s[end] == b'\'') {
212                            q = s[end];
213                        } else if s[end] == q {
214                            q = 0;
215                        }
216                        end += 1;
217                    }
218                    self.entity(&src[i + 8..end]);
219                    i = end;
220                }
221                b'<' if depth > 0 && s[i..].starts_with(b"<!--") => {
222                    i = find(s, i + 4, b"-->").map_or(s.len(), |e| e + 2);
223                }
224                b'>' if depth <= 0 => {
225                    self.i = i + 1;
226                    return;
227                }
228                _ => {}
229            }
230            i += 1;
231        }
232        self.i = s.len();
233    }
234
235    // name "value" (general entities only; parameter entities and external ones are skipped)
236    fn entity(&mut self, decl: &str) {
237        let d = decl.as_bytes();
238        let mut i = 0;
239        while i < d.len() && is_blank(d[i]) {
240            i += 1;
241        }
242        if d.get(i) == Some(&b'%') {
243            return;
244        }
245        let n0 = i;
246        while i < d.len() && !is_blank(d[i]) {
247            i += 1;
248        }
249        let name = &decl[n0..i];
250        while i < d.len() && is_blank(d[i]) {
251            i += 1;
252        }
253        let Some(&q) = d.get(i) else { return };
254        if q != b'"' && q != b'\'' {
255            return;
256        }
257        let v0 = i + 1;
258        let Some(len) = d[v0..].iter().position(|&c| c == q) else { return };
259        if name.is_empty() || self.ents.len() >= self.max_ents || len > 65536 {
260            return;
261        }
262        let mut val = String::new();
263        // character references inside the value; other entities are not expanded again
264        let saved = core::mem::take(&mut self.ents);
265        self.decode(&decl[v0..v0 + len], &mut val);
266        self.ents = saved;
267        // sorted by name; the first declaration of a name stays
268        if let Err(at) = self.ents.binary_search_by(|(n, _)| n.as_str().cmp(name)) {
269            self.ents.insert(at, (String::from(name), val));
270        }
271    }
272
273    fn end_tag(&mut self) -> Token<'a> {
274        let src: &'a str = self.s;
275        let s = src.as_bytes();
276        let n0 = self.i + 2;
277        let mut j = n0;
278        while j < s.len() && !name_end(s[j]) {
279            j += 1;
280        }
281        let name = &src[n0..j];
282        self.i = find(s, j, b">").map_or(s.len(), |e| e + 1);
283        Token::End { name }
284    }
285
286    fn start_tag(&mut self) -> Token<'a> {
287        let src: &'a str = self.s;
288        let s = src.as_bytes();
289        let n0 = self.i + 1;
290        let mut j = n0;
291        while j < s.len() && !name_end(s[j]) {
292            j += 1;
293        }
294        let name = &src[n0..j];
295        let mut attrs: Vec<(&'a str, &'a str)> = Vec::new();
296        let mut empty = false;
297        let mut i = j;
298        loop {
299            while i < s.len() && is_blank(s[i]) {
300                i += 1;
301            }
302            if i >= s.len() {
303                self.truncated = true;
304                break;
305            }
306            match s[i] {
307                b'>' => {
308                    i += 1;
309                    break;
310                }
311                b'/' => {
312                    if s.get(i + 1) == Some(&b'>') {
313                        empty = true;
314                        i += 2;
315                        break;
316                    }
317                    i += 1;
318                    continue;
319                }
320                b'<' => break, // a broken tag: the next one starts here
321                _ => {}
322            }
323            let a0 = i;
324            while i < s.len() && !name_end(s[i]) {
325                i += 1;
326            }
327            if i == a0 {
328                i += 1; // a stray quote or '='
329                continue;
330            }
331            let an = &src[a0..i];
332            while i < s.len() && is_blank(s[i]) {
333                i += 1;
334            }
335            let mut val = "";
336            if s.get(i) == Some(&b'=') {
337                i += 1;
338                while i < s.len() && is_blank(s[i]) {
339                    i += 1;
340                }
341                val = match s.get(i) {
342                    Some(&q) if q == b'"' || q == b'\'' => {
343                        let v0 = i + 1;
344                        let end = s[v0..].iter().position(|&c| c == q).map_or(s.len(), |k| v0 + k);
345                        i = (end + 1).min(s.len());
346                        &src[v0..end]
347                    }
348                    _ => {
349                        let v0 = i;
350                        while i < s.len() && !is_blank(s[i]) && s[i] != b'>' {
351                            i += 1;
352                        }
353                        &src[v0..i]
354                    }
355                };
356            }
357            if attrs.len() < self.max_attrs {
358                attrs.push((an, val));
359            }
360        }
361        dedup_first(&mut attrs);
362        self.i = i;
363        Token::Start { name, attrs, empty }
364    }
365
366    /// the next token (Eof at the end, and from then on)
367    pub fn next(&mut self) -> Token<'a> {
368        let src: &'a str = self.s;
369        let s = src.as_bytes();
370        while self.i < s.len() {
371            let i = self.i;
372            if s[i] != b'<' {
373                let end = s[i..].iter().position(|&c| c == b'<').map_or(s.len(), |k| i + k);
374                self.i = end;
375                return Token::Text(&src[i..end]);
376            }
377            let rest = &s[i..];
378            if rest.starts_with(b"<?") {
379                self.i = find(s, i + 2, b"?>").map_or(s.len(), |e| e + 2);
380            } else if rest.starts_with(b"<!--") {
381                self.i = find(s, i + 4, b"-->").map_or(s.len(), |e| e + 3);
382            } else if rest.starts_with(b"<![CDATA[") {
383                let end = find(s, i + 9, b"]]>").unwrap_or(s.len());
384                self.i = (end + 3).min(s.len());
385                return Token::CData(&src[i + 9..end]);
386            } else if rest.len() >= 9 && rest[..9].eq_ignore_ascii_case(b"<!DOCTYPE") {
387                self.i = i + 9;
388                self.doctype();
389            } else if rest.starts_with(b"<!") {
390                self.i = find(s, i + 2, b">").map_or(s.len(), |e| e + 1);
391            } else if rest.starts_with(b"</") {
392                return self.end_tag();
393            } else if rest.len() > 1 && !name_end(rest[1]) {
394                return self.start_tag();
395            } else {
396                self.i = i + 1;
397                return Token::Text(&src[i..i + 1]); // a lone '<'
398            }
399        }
400        Token::Eof
401    }
402}