Skip to main content

bilingua_model/
guard.rs

1//! Safety limits and the XML guard, one place for every parser (D27 step 5).
2//!
3//! The numbers are Localization OS's (`app/config.py`): a 100 MB input, 50 000 units, 100 000 characters in one
4//! unit, twenty lines per allowed unit, a zip of at most 10 000 entries that unpacks to at most 256 MB with no
5//! entry expanding more than 200 times. The caller can change any of them through `ExtractOptions::limits`.
6//! Each refusal is a [`LimitError`] with a [`LimitKind`] a program can branch on and a short message that is
7//! safe to show to the person who uploaded the file.
8//!
9//! The XML guard ([`check_xml`]) reads no DTD and expands no entity: a document that declares an entity
10//! (internal or external, so the billion-laughs and XXE families) is refused before any parser sees it, and the
11//! element depth and count are bounded. A plain `<!DOCTYPE x>` or `<!DOCTYPE x SYSTEM "x.dtd">` is allowed because
12//! the parsers never fetch or apply it.
13
14use crate::{Document, Error};
15use serde::{Deserialize, Serialize};
16use std::fmt;
17
18/// Which limit a refusal is about.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21#[non_exhaustive]
22pub enum LimitKind {
23    /// The file is too large.
24    InputBytes,
25    /// Too many lines.
26    Lines,
27    /// Too many units or segments.
28    Units,
29    /// A unit is too long.
30    UnitChars,
31    /// XML nested too deeply.
32    XmlDepth,
33    /// Nesting deeper than allowed in a format that is not XML (HTML, JSON, YAML, ...). Uses
34    /// `Limits::max_xml_depth`, which is the nesting cap for every format.
35    Depth,
36    /// Too many XML elements.
37    XmlElements,
38    /// An XML entity declaration (DTD): entity bombs and external entities.
39    XmlEntities,
40    /// More paragraphs in a word-processing file than allowed (empty ones count).
41    Paragraphs,
42    /// A spreadsheet over its cell, row, characters-per-cell or total-text limit.
43    Spreadsheet,
44    /// Too many zip entries.
45    ZipEntries,
46    /// Too many bytes once unpacked.
47    ZipBytes,
48    /// A zip entry expands too much (a zip bomb).
49    ZipRatio,
50    /// A zip whose declared sizes or names are unsafe or do not match its data.
51    ZipMalformed,
52}
53
54/// A file refused for being over a limit or unsafe.
55#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub struct LimitError {
58    /// Which limit.
59    pub kind: LimitKind,
60    /// The message, safe to show the person who uploaded the file.
61    pub msg: String,
62}
63
64impl fmt::Display for LimitError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(&self.msg)
67    }
68}
69
70impl LimitError {
71    /// A limit error of this kind with this message.
72    pub fn new(kind: LimitKind, msg: impl Into<String>) -> LimitError {
73        LimitError { kind, msg: msg.into() }
74    }
75}
76
77impl From<LimitError> for Error {
78    fn from(e: LimitError) -> Error {
79        Error::Limit(e)
80    }
81}
82
83/// The limits one extraction runs under. `Default` is Localization OS's configuration.
84/// Build them with [`Limits::new`] and the `with_*` methods (`Limits::new().with_max_units(500)`); new limits are
85/// added without breaking callers.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(default, deny_unknown_fields)]
88#[non_exhaustive]
89pub struct Limits {
90    /// Largest input file (`MAX_UPLOAD_BYTES`).
91    pub max_input_bytes: u64,
92    /// Most units (and most segments) in a document (`MAX_DOCUMENT_SEGMENTS`).
93    pub max_units: usize,
94    /// Most characters in one unit (`MAX_SEGMENT_CHARS`).
95    pub max_unit_chars: usize,
96    /// Most lines in a text file: twenty per allowed unit, as LocOS's line budget.
97    pub max_lines: usize,
98    /// Deepest XML element nesting (libxml2's own default).
99    pub max_xml_depth: usize,
100    /// Most XML elements in one part.
101    pub max_xml_elements: usize,
102    /// Most entries in a zip (`ZIP_MAX_MEMBERS`).
103    pub max_zip_entries: usize,
104    /// Most bytes all entries of a zip unpack to (`ZIP_MAX_UNCOMPRESSED_BYTES`).
105    pub max_zip_bytes: u64,
106    /// Most bytes one zip entry may unpack to. LocOS has no cap of its own beyond the total, so the default is the
107    /// same 256 MB; a caller may set it lower (or raise both for desktop use).
108    pub max_zip_entry_bytes: u64,
109    /// Largest unpacked/packed ratio of one entry (`ZIP_MAX_RATIO`).
110    pub max_zip_ratio: u64,
111    /// Entries smaller than this are not checked for ratio (`ZIP_RATIO_MIN_BYTES`).
112    pub zip_ratio_floor_bytes: u64,
113    /// Most paragraphs in a DOCX, empty ones included (`DOCX_MAX_PARAGRAPHS`).
114    pub max_paragraphs: usize,
115    /// Most cells in an XLSX (`XLSX_MAX_CELLS`).
116    pub xlsx_max_cells: usize,
117    /// Highest row number in an XLSX (`XLSX_MAX_ROWS`).
118    pub xlsx_max_rows: u32,
119    /// Most characters in one XLSX cell or shared string (`XLSX_MAX_CELL_CHARS`, Excel's own limit).
120    pub xlsx_max_cell_chars: usize,
121    /// Most characters of cell text in an XLSX, repeated shared strings counted every time
122    /// (`XLSX_MAX_TOTAL_TEXT_CHARS`).
123    pub xlsx_max_total_text_chars: usize,
124}
125
126impl Default for Limits {
127    fn default() -> Self {
128        Limits {
129            max_input_bytes: 100 * 1024 * 1024,
130            max_units: 50_000,
131            max_unit_chars: 100_000,
132            max_lines: 20 * 50_000,
133            max_xml_depth: 256,
134            max_xml_elements: 4_000_000,
135            max_zip_entries: 10_000,
136            max_zip_bytes: 256 * 1024 * 1024,
137            max_zip_entry_bytes: 256 * 1024 * 1024,
138            max_zip_ratio: 200,
139            zip_ratio_floor_bytes: 1024 * 1024,
140            max_paragraphs: 50_000,
141            xlsx_max_cells: 500_000,
142            xlsx_max_rows: 100_000,
143            xlsx_max_cell_chars: 32_767,
144            xlsx_max_total_text_chars: 8 * 1024 * 1024,
145        }
146    }
147}
148
149impl Limits {
150    /// Localization OS's limits (the same as `Limits::default()`); change any of them with the `with_*` methods.
151    pub fn new() -> Limits {
152        Limits::default()
153    }
154    /// Sets `max_input_bytes`.
155    pub fn with_max_input_bytes(mut self, v: u64) -> Limits {
156        self.max_input_bytes = v;
157        self
158    }
159    /// Sets `max_units`.
160    pub fn with_max_units(mut self, v: usize) -> Limits {
161        self.max_units = v;
162        self
163    }
164    /// Sets `max_unit_chars`.
165    pub fn with_max_unit_chars(mut self, v: usize) -> Limits {
166        self.max_unit_chars = v;
167        self
168    }
169    /// Sets `max_lines`.
170    pub fn with_max_lines(mut self, v: usize) -> Limits {
171        self.max_lines = v;
172        self
173    }
174    /// Sets `max_xml_depth`.
175    pub fn with_max_xml_depth(mut self, v: usize) -> Limits {
176        self.max_xml_depth = v;
177        self
178    }
179    /// Sets `max_xml_elements`.
180    pub fn with_max_xml_elements(mut self, v: usize) -> Limits {
181        self.max_xml_elements = v;
182        self
183    }
184    /// Sets `max_zip_entries`.
185    pub fn with_max_zip_entries(mut self, v: usize) -> Limits {
186        self.max_zip_entries = v;
187        self
188    }
189    /// Sets `max_zip_bytes`.
190    pub fn with_max_zip_bytes(mut self, v: u64) -> Limits {
191        self.max_zip_bytes = v;
192        self
193    }
194    /// Sets `max_zip_entry_bytes`.
195    pub fn with_max_zip_entry_bytes(mut self, v: u64) -> Limits {
196        self.max_zip_entry_bytes = v;
197        self
198    }
199    /// Sets `max_zip_ratio`.
200    pub fn with_max_zip_ratio(mut self, v: u64) -> Limits {
201        self.max_zip_ratio = v;
202        self
203    }
204    /// Sets `zip_ratio_floor_bytes`.
205    pub fn with_zip_ratio_floor_bytes(mut self, v: u64) -> Limits {
206        self.zip_ratio_floor_bytes = v;
207        self
208    }
209    /// Sets `max_paragraphs`.
210    pub fn with_max_paragraphs(mut self, v: usize) -> Limits {
211        self.max_paragraphs = v;
212        self
213    }
214    /// Sets `xlsx_max_cells`.
215    pub fn with_xlsx_max_cells(mut self, v: usize) -> Limits {
216        self.xlsx_max_cells = v;
217        self
218    }
219    /// Sets `xlsx_max_rows`.
220    pub fn with_xlsx_max_rows(mut self, v: u32) -> Limits {
221        self.xlsx_max_rows = v;
222        self
223    }
224    /// Sets `xlsx_max_cell_chars`.
225    pub fn with_xlsx_max_cell_chars(mut self, v: usize) -> Limits {
226        self.xlsx_max_cell_chars = v;
227        self
228    }
229    /// Sets `xlsx_max_total_text_chars`.
230    pub fn with_xlsx_max_total_text_chars(mut self, v: usize) -> Limits {
231        self.xlsx_max_total_text_chars = v;
232        self
233    }
234}
235
236fn mb(n: u64) -> String {
237    if n >= 1024 * 1024 {
238        format!("{} MB", n / (1024 * 1024))
239    } else {
240        format!("{n} bytes")
241    }
242}
243
244/// Refuses an input over `max_input_bytes`. Call before any other work on the bytes.
245pub fn check_input(bytes: &[u8], l: &Limits) -> Result<(), Error> {
246    if bytes.len() as u64 > l.max_input_bytes {
247        return Err(LimitError::new(
248            LimitKind::InputBytes,
249            format!(
250                "This file is {} long; the limit is {}. Split it into smaller files.",
251                mb(bytes.len() as u64),
252                mb(l.max_input_bytes)
253            ),
254        )
255        .into());
256    }
257    Ok(())
258}
259
260/// Refuses a text with more lines than the line budget, before any per-line work (a file of 100 MB of newlines
261/// would otherwise build a list of 100 million lines).
262pub fn check_lines(text: &str, l: &Limits) -> Result<(), Error> {
263    let n = text.bytes().filter(|b| *b == b'\n' || *b == b'\r').count();
264    if n > l.max_lines {
265        return Err(LimitError::new(
266            LimitKind::Lines,
267            format!("This file has more than {} lines. Split it into smaller files.", l.max_lines),
268        )
269        .into());
270    }
271    Ok(())
272}
273
274/// The running-total check for a parser that counts units as it goes: refuse as soon as `count` passes the cap,
275/// so a hostile file stops early.
276pub fn check_unit_count(count: usize, l: &Limits) -> Result<(), Error> {
277    if count > l.max_units {
278        return Err(LimitError::new(
279            LimitKind::Units,
280            format!("This file has more than {} segments. Split it into smaller files.", l.max_units),
281        )
282        .into());
283    }
284    Ok(())
285}
286
287/// Localization OS's pre-parse budget (#571 and its gate): a text with more than `per_unit` x `max_units` of some
288/// marker (`count`: JSON quotes, or commas and brackets; PO backslashes) is refused before the parser builds
289/// anything, since each marker costs work or memory whether or not it ends in a unit (100 MB of `{},` holds no
290/// text but millions of values). `what` names the file and the marker ("This JSON file has far more values").
291pub fn check_budget(count: usize, per_unit: usize, what: &str, l: &Limits) -> Result<(), Error> {
292    if count > per_unit.saturating_mul(l.max_units) {
293        return Err(LimitError::new(
294            LimitKind::Units,
295            format!("{what} than a file of {} segments. Split it into smaller files.", l.max_units),
296        )
297        .into());
298    }
299    Ok(())
300}
301
302/// Refuses a unit text longer than `max_unit_chars` characters.
303pub fn check_unit_chars(chars: usize, l: &Limits) -> Result<(), Error> {
304    if chars > l.max_unit_chars {
305        return Err(LimitError::new(
306            LimitKind::UnitChars,
307            format!(
308                "This file has a line or paragraph longer than {} characters. Break it into shorter lines.",
309                l.max_unit_chars
310            ),
311        )
312        .into());
313    }
314    Ok(())
315}
316
317/// The check for a finished extraction: unit and segment counts, and the length of every unit.
318pub fn check_document(doc: &Document, l: &Limits) -> Result<(), Error> {
319    check_unit_count(doc.units.len(), l)?;
320    check_unit_count(doc.segment_count(), l)?;
321    for u in &doc.units {
322        let chars: usize = u
323            .segments
324            .iter()
325            .flat_map(|s| s.source.iter())
326            .map(|i| match i {
327                crate::Inline::Text(t) => t.chars().count(),
328                crate::Inline::Tag { .. } => 1,
329            })
330            .sum();
331        check_unit_chars(chars, l)?;
332    }
333    Ok(())
334}
335
336/// What every parser ends with: the document passes `check_document`, and the warnings of the text decode go on it.
337pub fn finish(mut doc: Document, warnings: Vec<crate::Warning>, l: &Limits) -> Result<Document, Error> {
338    check_document(&doc, l)?;
339    doc.warnings.extend(warnings);
340    Ok(doc)
341}
342
343fn unsafe_xml(msg: impl Into<String>) -> Error {
344    LimitError::new(LimitKind::XmlEntities, msg).into()
345}
346
347fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
348    if from >= hay.len() {
349        return None;
350    }
351    hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
352}
353
354fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {
355    hay.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle))
356}
357
358/// Reads XML as bytes, transcoding UTF-16 (BOM or `<` in 16-bit form) so the scan sees ASCII markup.
359fn markup_bytes(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
360    let le = bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[b'<', 0]);
361    let be = bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0, b'<']);
362    if le && !bytes.starts_with(&[0xFF, 0xFE, 0, 0]) {
363        let (s, _) = encoding_rs::UTF_16LE.decode_without_bom_handling(bytes);
364        return std::borrow::Cow::Owned(s.into_owned().into_bytes());
365    }
366    if be {
367        let (s, _) = encoding_rs::UTF_16BE.decode_without_bom_handling(bytes);
368        return std::borrow::Cow::Owned(s.into_owned().into_bytes());
369    }
370    std::borrow::Cow::Borrowed(bytes)
371}
372
373/// The XML guard: scans the markup of one XML part once and refuses
374/// * any `<!ENTITY` declaration (an entity bomb or an external entity; `&amp; &lt; &gt; &quot; &apos;` and
375///   character references are all a document needs),
376/// * nesting deeper than `max_xml_depth`,
377/// * more than `max_xml_elements` elements.
378///
379/// Comments, CDATA sections and processing instructions are skipped, so markup inside them is not counted.
380///
381/// The count is only as good as the reader's agreement on where those regions end, so a part is also refused when
382/// the readers would not agree: a DOCTYPE that never ends, has a `<`, `>` or bracket in a quoted string, a quote or
383/// bracket in a comment of its internal subset, or a `<`/`>` that `quick-xml` pairs differently; a comment that
384/// starts with `>` or `->`; `<?>`; a `<!` declaration outside the DOCTYPE. Every reading a reader may give the
385/// bytes is scanned: UTF-16 and UTF-8 for `<\0` without a byte order mark, and the double-byte code pages for
386/// bytes that are not UTF-8.
387pub fn check_xml(bytes: &[u8], l: &Limits) -> Result<(), Error> {
388    check_xml_with(bytes, l, false, false)
389}
390
391/// Like [`check_xml`], but a DOCTYPE may declare plain internal entities: `<!ENTITY name "literal">` with a literal
392/// that holds no `&` (so no entity expands into another), at most 1024 bytes long, and at most 64 of them. Adobe Illustrator, Inkscape and
393/// Sodipodi SVGs declare a few of these for namespace URIs. External (`SYSTEM`, `PUBLIC`) and parameter (`%`)
394/// entities are refused as before, and every other check of [`check_xml`] still applies. For a reader that never
395/// expands an entity (the SVG filter keeps every `&name;` as typed).
396pub fn check_xml_internal_entities(bytes: &[u8], l: &Limits) -> Result<(), Error> {
397    check_xml_with(bytes, l, false, true)
398}
399
400/// True when every `<!ENTITY` declaration in a DOCTYPE is `<!ENTITY name "literal">` (or single quotes) and the
401/// literal has no `&`; false for an external or parameter entity, a malformed one, or more than 64.
402fn only_plain_internal_entities(doctype: &[u8]) -> bool {
403    let mut n = 0usize;
404    let mut from = 0usize;
405    while let Some(p) = doctype[from..].windows(8).position(|w| w.eq_ignore_ascii_case(b"<!ENTITY")) {
406        n += 1;
407        if n > 64 {
408            return false;
409        }
410        let mut j = from + p + 8;
411        let ws = |j: &mut usize| {
412            let s = *j;
413            while *j < doctype.len() && matches!(doctype[*j], b' ' | b'\t' | b'\r' | b'\n') {
414                *j += 1;
415            }
416            *j > s
417        };
418        if !ws(&mut j) {
419            return false;
420        }
421        let name_start = j;
422        while j < doctype.len() && (doctype[j].is_ascii_alphanumeric() || matches!(doctype[j], b'_' | b'-' | b'.' | b':')) {
423            j += 1;
424        }
425        if j == name_start || !ws(&mut j) || j >= doctype.len() {
426            return false;
427        }
428        let q = doctype[j];
429        if q != b'"' && q != b'\'' {
430            return false;
431        }
432        let Some(len) = doctype[j + 1..].iter().position(|c| *c == q) else { return false };
433        // no `&`: nothing expands into anything; at most 1024 bytes: a few references cannot blow up a reader
434        // that does expand them (the file is written back as it is, for browsers and editors to read)
435        if len > 1024 || doctype[j + 1..j + 1 + len].contains(&b'&') {
436            return false;
437        }
438        from = j + 1 + len + 1;
439    }
440    true
441}
442
443/// Like [`check_xml`] for document formats where a DTD with entity declarations is normal (DocBook, DITA, plain
444/// XML): the declarations are allowed, and the depth and element limits still apply. This is safe only for a reader
445/// that never expands or fetches an entity, as the XML filter family does: it keeps every `&name;` as an opaque
446/// code and writes the DOCTYPE back byte for byte.
447pub fn check_xml_keeping_dtd(bytes: &[u8], l: &Limits) -> Result<(), Error> {
448    check_xml_with(bytes, l, true, false)
449}
450
451/// End of a `<!DOCTYPE ...>` that starts at `i`: the index of its closing `>` (or `b.len()`). Quoted strings, the
452/// `[ ... ]` internal subset and the comments and processing instructions inside it are skipped.
453fn doctype_end(b: &[u8], i: usize) -> usize {
454    let (mut j, mut sq, mut subset) = (i + 9, 0u8, 0usize);
455    while j < b.len() {
456        let c = b[j];
457        if sq != 0 {
458            if c == sq {
459                sq = 0;
460            }
461        } else if c == b'"' || c == b'\'' {
462            sq = c;
463        } else if subset > 0 && b[j..].starts_with(b"<!--") {
464            match find(b, j + 4, b"-->") {
465                Some(e) => j = e + 2,
466                None => return b.len(),
467            }
468        } else if subset > 0 && b[j..].starts_with(b"<?") {
469            match find(b, j + 2, b"?>") {
470                Some(e) => j = e + 1,
471                None => return b.len(),
472            }
473        } else if c == b'[' {
474            subset += 1;
475        } else if c == b']' {
476            subset = subset.saturating_sub(1);
477        } else if c == b'>' && subset == 0 {
478            break;
479        }
480        j += 1;
481    }
482    j.min(b.len())
483}
484
485/// Where `quick-xml` ends the `<!DOCTYPE` that starts at `i`: the first `>` outside a `<` ... `>` pair, quotes,
486/// brackets and comments not looked at (the index of that `>`, or `None` when there is none).
487fn reader_doctype_end(b: &[u8], i: usize) -> Option<usize> {
488    let mut balance = 0usize;
489    for (j, c) in b.iter().enumerate().skip(i + 2) {
490        match c {
491            b'<' => balance += 1,
492            b'>' if balance == 0 => return Some(j),
493            b'>' => balance -= 1,
494            _ => {}
495        }
496    }
497    None
498}
499
500/// True when every XML reader in the workspace ends the DOCTYPE at `i..=end` (`end` from [`doctype_end`]) at the
501/// same `>`. The readers differ in what they skip: `quick-xml` only pairs `<` with `>`; the hand-written scanners
502/// skip quoted strings, some also the `[ ... ]` subset, some the comments or processing instructions inside it. They
503/// all agree when no quoted string holds a `<`, `>`, `[` or `]`, no comment or processing instruction of the subset
504/// holds a quote, a bracket or an angle bracket of its own, and `quick-xml` stops at the same place. Real files meet
505/// that easily (`<!DOCTYPE plist PUBLIC "..." "...">`, an XMB subset of `<!ELEMENT>` and `<!ATTLIST>` declarations).
506fn doctype_is_unambiguous(b: &[u8], i: usize, end: usize) -> bool {
507    if end >= b.len() || reader_doctype_end(b, i) != Some(end) {
508        return false;
509    }
510    let special = |s: &[u8], also_quotes: bool| s.iter().any(|c| matches!(c, b'<' | b'>' | b'[' | b']') || (also_quotes && matches!(c, b'"' | b'\'')));
511    let (mut j, mut subset) = (i + 9, 0usize);
512    while j < end {
513        let c = b[j];
514        if c == b'"' || c == b'\'' {
515            let Some(q) = b[j + 1..end].iter().position(|x| *x == c) else { return false };
516            if special(&b[j + 1..j + 1 + q], false) {
517                return false;
518            }
519            j += q + 2;
520            continue;
521        }
522        if subset > 0 && b[j..].starts_with(b"<!--") {
523            let Some(e) = find(b, j + 4, b"-->").filter(|e| *e < end) else { return false };
524            if special(&b[j + 4..e], true) {
525                return false;
526            }
527            j = e + 3;
528            continue;
529        }
530        if subset > 0 && b[j..].starts_with(b"<?") {
531            let Some(e) = find(b, j + 2, b"?>").filter(|e| *e < end) else { return false };
532            if special(&b[j + 2..e], true) {
533                return false;
534            }
535            j = e + 2;
536            continue;
537        }
538        if c == b'[' {
539            subset += 1;
540        } else if c == b']' {
541            subset = subset.saturating_sub(1);
542        }
543        j += 1;
544    }
545    true
546}
547
548fn ambiguous_markup(what: &str) -> Error {
549    LimitError::new(
550        LimitKind::XmlElements,
551        format!("This file has {what}, which XML readers do not agree on, so its elements could not be counted safely. It was not processed."),
552    )
553    .into()
554}
555
556/// Every way a reader in the workspace may read `bytes` as markup. A UTF-16 byte order mark leaves one reading.
557/// Without one, `<\0` or `\0<` is UTF-16 for the readers that sniff it (EPUB, IDML) but UTF-8 with a NUL for the
558/// ones that decode with [`crate::enc::decode_text`], so both are scanned. Bytes that are not UTF-8 may be read
559/// in a double-byte code page whose second byte can be `[` or `]` (Shift_JIS, GBK/GB18030, Big5: a CDATA section
560/// then ends at another `]]>` than in the bytes), so each of those readings is scanned too.
561fn markup_views(bytes: &[u8]) -> Vec<std::borrow::Cow<'_, [u8]>> {
562    use std::borrow::Cow;
563    let decode = |e: &'static encoding_rs::Encoding| Cow::Owned(e.decode_without_bom_handling(bytes).0.into_owned().into_bytes());
564    if (bytes.starts_with(&[0xFF, 0xFE]) && !bytes.starts_with(&[0xFF, 0xFE, 0, 0])) || bytes.starts_with(&[0xFE, 0xFF]) {
565        return vec![markup_bytes(bytes)];
566    }
567    let mut v = vec![Cow::Borrowed(bytes)];
568    if bytes.starts_with(&[b'<', 0]) || bytes.starts_with(&[0, b'<']) {
569        v.push(markup_bytes(bytes));
570    } else if std::str::from_utf8(bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes)).is_err() {
571        for e in [encoding_rs::SHIFT_JIS, encoding_rs::GB18030, encoding_rs::BIG5] {
572            v.push(decode(e));
573        }
574    }
575    v
576}
577
578fn check_xml_with(bytes: &[u8], l: &Limits, keep_dtd: bool, internal_ok: bool) -> Result<(), Error> {
579    for view in markup_views(bytes) {
580        scan_xml(&view, l, keep_dtd, internal_ok)?;
581    }
582    Ok(())
583}
584
585fn scan_xml(b: &[u8], l: &Limits, keep_dtd: bool, internal_ok: bool) -> Result<(), Error> {
586    let strict = !keep_dtd;
587    let (mut i, mut depth, mut elements) = (0usize, 0usize, 0usize);
588    while i < b.len() {
589        let Some(p) = b[i..].iter().position(|c| *c == b'<') else { break };
590        i += p;
591        let rest = &b[i..];
592        if rest.starts_with(b"<!--") {
593            // `<!-->` and `<!--->` open a comment for XML, but a scanner that looks for `-->` from the `<` reads them
594            // as a whole comment and goes on with what XML still calls comment text
595            if strict && (rest[4..].starts_with(b">") || rest[4..].starts_with(b"->")) {
596                return Err(ambiguous_markup("a comment that starts with '>' or '->'"));
597            }
598            match find(b, i + 4, b"-->") {
599                Some(e) => i = e + 3,
600                None => break,
601            }
602        } else if rest.starts_with(b"<![CDATA[") {
603            match find(b, i + 9, b"]]>") {
604                Some(e) => i = e + 3,
605                None => break,
606            }
607        } else if rest.starts_with(b"<?") {
608            // `<?>` is no processing instruction; a scanner that looks for `?>` from the `<` reads it as one
609            if strict && rest[2..].starts_with(b">") {
610                return Err(ambiguous_markup("a processing instruction with no name ('<?>')"));
611            }
612            match find(b, i + 2, b"?>") {
613                Some(e) => i = e + 2,
614                None => break,
615            }
616        } else if rest.len() >= 9 && rest[..9].eq_ignore_ascii_case(b"<!DOCTYPE") {
617            let end = doctype_end(b, i);
618            if !keep_dtd && contains_ci(&b[i..end], b"<!ENTITY") && !(internal_ok && only_plain_internal_entities(&b[i..end])) {
619                return Err(unsafe_xml(
620                    "This file declares XML entities (a DTD), which could expand without limit or read other files. It was not processed.",
621                ));
622            }
623            // the readers must all end the DOCTYPE where this scan does, or elements (or an ENTITY) could hide in
624            // what one of them calls the DOCTYPE. The keep-DTD readers (the XML filter family) check that themselves.
625            if strict && end >= b.len() {
626                return Err(unsafe_xml("This file has a DOCTYPE that is not closed. It was not processed."));
627            }
628            if strict && !doctype_is_unambiguous(b, i, end) {
629                return Err(unsafe_xml(
630                    "This file has a DOCTYPE with a quoted '<', '>' or bracket, or a comment in its DTD with quotes or brackets, which XML readers do not agree on. It was not processed.",
631                ));
632            }
633            i = end + 1;
634        } else if rest.starts_with(b"<!") {
635            // another declaration outside a DOCTYPE
636            if rest.len() >= 8 && rest[..8].eq_ignore_ascii_case(b"<!ENTITY") {
637                return Err(unsafe_xml("This file declares XML entities, which are not allowed. It was not processed."));
638            }
639            // `quick-xml` reads `<![` to `]]>` and `<!-` to `-->`; XML has no other declaration outside a DOCTYPE
640            if strict {
641                return Err(ambiguous_markup("a markup declaration outside the DOCTYPE"));
642            }
643            match find(b, i + 2, b">") {
644                Some(e) => i = e + 1,
645                None => break,
646            }
647        } else if rest.starts_with(b"</") {
648            depth = depth.saturating_sub(1);
649            match find(b, i + 2, b">") {
650                Some(e) => i = e + 1,
651                None => break,
652            }
653        } else {
654            // a start tag: find '>' outside quotes
655            let (mut j, mut sq) = (i + 1, 0u8);
656            let mut end = None;
657            while j < b.len() {
658                let c = b[j];
659                if sq != 0 {
660                    if c == sq {
661                        sq = 0;
662                    }
663                } else if c == b'"' || c == b'\'' {
664                    sq = c;
665                } else if c == b'>' {
666                    end = Some(j);
667                    break;
668                }
669                j += 1;
670            }
671            let Some(e) = end else { break };
672            elements += 1;
673            if elements > l.max_xml_elements {
674                return Err(LimitError::new(
675                    LimitKind::XmlElements,
676                    format!("This file has more than {} XML elements in one part. It was not processed.", l.max_xml_elements),
677                )
678                .into());
679            }
680            if b[e - 1] != b'/' {
681                depth += 1;
682                if depth > l.max_xml_depth {
683                    return Err(LimitError::new(
684                        LimitKind::XmlDepth,
685                        format!("This file nests XML elements more than {} deep. It was not processed.", l.max_xml_depth),
686                    )
687                    .into());
688                }
689            }
690            i = e + 1;
691        }
692    }
693    Ok(())
694}
695
696/// Counts the start tags whose local name is `local` (`p` for a Word paragraph), comments, CDATA and processing
697/// instructions skipped. Cheap enough to run over every part before a parser builds a tree of it.
698pub fn count_elements(bytes: &[u8], local: &str) -> usize {
699    let data = markup_bytes(bytes);
700    let b: &[u8] = &data;
701    let (mut i, mut n) = (0usize, 0usize);
702    while let Some(p) = b.get(i..).and_then(|r| r.iter().position(|c| *c == b'<')) {
703        i += p;
704        let rest = &b[i + 1..];
705        if rest.starts_with(b"!--") {
706            i = find(b, i + 4, b"-->").map_or(b.len(), |e| e + 3);
707        } else if rest.starts_with(b"![CDATA[") {
708            i = find(b, i + 9, b"]]>").map_or(b.len(), |e| e + 3);
709        } else if rest.starts_with(b"?") {
710            i = find(b, i + 2, b"?>").map_or(b.len(), |e| e + 2);
711        } else {
712            let name_end = rest.iter().position(|c| c.is_ascii_whitespace() || *c == b'>' || *c == b'/').unwrap_or(rest.len());
713            let name = &rest[..name_end];
714            let lname = name.rsplit(|c| *c == b':').next().unwrap_or(name);
715            if !name.starts_with(b"/") && !name.starts_with(b"!") && lname == local.as_bytes() {
716                n += 1;
717            }
718            i += 1 + name_end;
719        }
720    }
721    n
722}
723
724/// The guard for markup that is not strict XML (HTML): no entity declarations, and the element count cap. Depth
725/// of HTML is the parser's own business (unclosed tags make it unknowable from the text).
726pub fn check_markup(text: &str, l: &Limits) -> Result<(), Error> {
727    let b = text.as_bytes();
728    if contains_ci(b, b"<!ENTITY") {
729        return Err(unsafe_xml("This file declares markup entities, which are not allowed. It was not processed."));
730    }
731    let elements = b.windows(2).filter(|w| w[0] == b'<' && (w[1].is_ascii_alphabetic() || w[1] == b'/')).count();
732    if elements > l.max_xml_elements {
733        return Err(LimitError::new(
734            LimitKind::XmlElements,
735            format!("This file has more than {} markup elements. It was not processed.", l.max_xml_elements),
736        )
737        .into());
738    }
739    Ok(())
740}
741
742#[cfg(test)]
743mod tests {
744    use super::*;
745
746    fn kind(r: Result<(), Error>) -> Option<LimitKind> {
747        match r {
748            Err(Error::Limit(e)) => Some(e.kind),
749            _ => None,
750        }
751    }
752
753    #[test]
754    fn defaults_are_locos_numbers() {
755        let l = Limits::default();
756        assert_eq!((l.max_input_bytes, l.max_units, l.max_unit_chars), (100 << 20, 50_000, 100_000));
757        assert_eq!((l.max_zip_entries, l.max_zip_bytes, l.max_zip_ratio), (10_000, 256 << 20, 200));
758    }
759
760    #[test]
761    fn pre_parse_budget_scales_with_the_unit_limit() {
762        let l = Limits { max_units: 10, ..Limits::default() };
763        assert!(check_budget(200, 20, "This JSON file has far more values", &l).is_ok());
764        let e = check_budget(201, 20, "This JSON file has far more values", &l).unwrap_err();
765        assert!(e.to_string().contains("far more values than a file of 10 segments. Split"), "{e}");
766        assert_eq!(kind(Err(e)), Some(LimitKind::Units));
767        assert!(check_budget(usize::MAX, usize::MAX, "x", &Limits { max_units: usize::MAX, ..Limits::default() }).is_ok());
768    }
769
770    #[test]
771    fn input_size_is_checked_against_the_callers_limit() {
772        let l = Limits { max_input_bytes: 10, ..Limits::default() };
773        assert!(check_input(&[0; 10], &l).is_ok());
774        assert_eq!(kind(check_input(&[0; 11], &l)), Some(LimitKind::InputBytes));
775    }
776
777    #[test]
778    fn xml_entity_bomb_and_xxe_are_refused() {
779        let bomb = br#"<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;">]><lolz>&lol2;</lolz>"#;
780        assert_eq!(kind(check_xml(bomb, &Limits::default())), Some(LimitKind::XmlEntities));
781        let xxe = br#"<!DOCTYPE r [ <!ENTITY x SYSTEM "file:///etc/passwd"> ]><r>&x;</r>"#;
782        assert_eq!(kind(check_xml(xxe, &Limits::default())), Some(LimitKind::XmlEntities));
783        let param = br#"<!doctype r [ <!entity % p SYSTEM "http://example.invalid/x.dtd"> %p; ]><r/>"#;
784        assert_eq!(kind(check_xml(param, &Limits::default())), Some(LimitKind::XmlEntities));
785    }
786
787    #[test]
788    fn internal_entities_mode_allows_only_plain_literals() {
789        let l = Limits::default();
790        let ok = br#"<?xml version="1.0"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [ <!ENTITY ns_a "http://ns.example.invalid/a/1.0/"> <!ENTITY b 'x'> ]><svg xmlns:a="&ns_a;"/>"#;
791        assert!(check_xml_internal_entities(ok, &l).is_ok());
792        assert_eq!(kind(check_xml(ok, &l)), Some(LimitKind::XmlEntities), "the strict check still refuses it");
793        for bad in [
794            r#"<!DOCTYPE r [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;">]><r/>"#,
795            r#"<!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/hosts">]><r/>"#,
796            r#"<!DOCTYPE r [<!ENTITY x PUBLIC "a" "b">]><r/>"#,
797            r#"<!DOCTYPE r [<!ENTITY % p "x">]><r/>"#,
798            r#"<!DOCTYPE r [<!ENTITY x>]><r/>"#,
799            r#"<!DOCTYPE r [<!ENTITY x "unclosed>]><r/>"#,
800            r#"<!ENTITY x "y"><r/>"#,
801        ] {
802            assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
803        }
804        let long = format!("<!DOCTYPE r [<!ENTITY x \"{}\">]><r/>", "a".repeat(1025));
805        assert_eq!(kind(check_xml_internal_entities(long.as_bytes(), &l)), Some(LimitKind::XmlEntities));
806        // a literal never carries markup: a quoted '<' or '>' in the DOCTYPE is refused
807        for bad in [r#"<!DOCTYPE r [<!ENTITY x "<g/>">]><r/>"#, r#"<!DOCTYPE r [<!ENTITY x "a>b">]><r/>"#] {
808            assert!(check_xml_internal_entities(bad.as_bytes(), &l).is_err(), "{bad}");
809        }
810        // declared entities do not lift the depth and element limits
811        let tight = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
812        let deep = r#"<!DOCTYPE r [<!ENTITY x "y">]><r><a><b>&x;</b></a></r>"#;
813        assert!(check_xml_internal_entities(deep.as_bytes(), &tight).is_err());
814        let many: String = (0..65).map(|k| format!("<!ENTITY e{k} \"v\">")).collect();
815        assert!(check_xml_internal_entities(format!("<!DOCTYPE r [{many}]><r/>").as_bytes(), &l).is_err());
816    }
817
818    #[test]
819    fn keeping_dtd_allows_declarations_but_not_more_elements_or_depth() {
820        let l = Limits { max_xml_depth: 8, max_xml_elements: 20, ..Limits::default() };
821        let bomb = br#"<!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;"><!ENTITY % p SYSTEM "http://example.invalid/x.dtd"> %p;]><lolz>&lol2;</lolz>"#;
822        assert!(check_xml_keeping_dtd(bomb, &l).is_ok());
823        assert_eq!(kind(check_xml(bomb, &l)), Some(LimitKind::XmlEntities), "the strict check still refuses it");
824        // a quote, a '>' or a ']' in a comment or a PI of the subset does not end the DOCTYPE early or late
825        for dt in [r#"<!DOCTYPE r [ <!-- ' ]> --> <!ENTITY a "x"> ]>"#, r#"<!DOCTYPE r [ <?pi ]> " ?> <!ENTITY a "]>"> ]>"#] {
826            let deep = format!("{dt}{}{}", "<a>".repeat(9), "</a>".repeat(9));
827            assert_eq!(kind(check_xml_keeping_dtd(deep.as_bytes(), &l)), Some(LimitKind::XmlDepth), "{dt}");
828            let wide = format!("{dt}<r>{}</r>", "<b/>".repeat(30));
829            assert_eq!(kind(check_xml_keeping_dtd(wide.as_bytes(), &l)), Some(LimitKind::XmlElements), "{dt}");
830            assert_eq!(kind(check_xml(deep.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{dt}");
831        }
832        // an ENTITY declaration outside a DOCTYPE is refused in both modes
833        assert_eq!(kind(check_xml_keeping_dtd(br#"<!ENTITY a "x"><r/>"#, &l)), Some(LimitKind::XmlEntities));
834    }
835
836    #[test]
837    fn a_doctype_the_readers_end_elsewhere_is_refused() {
838        let l = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
839        let body = "<r><a><b><c/></b></a></r>";
840        assert_eq!(kind(check_xml(body.as_bytes(), &l)), Some(LimitKind::XmlDepth));
841        for pre in [
842            "<!doctype r SYSTEM '>",
843            "<!DOCTYPE r SYSTEM \">",
844            "<!DoCtYpE r PUBLIC 'a>b' 'c'>",
845            "<!DOCTYPE r [>",
846            "<!DOCTYPE r [<!-- > -->",
847            "<!DOCTYPE r [<!-- ] --> <x><y>",
848            "<!DOCTYPE r [<!-- ' --> <?p ' ?> ]>",
849            "<!DOCTYPE r SYSTEM 'a[b'>",
850            "<!DOCTYPE r < >",
851            "<!DOCTYPE r [ > ]>",
852            "<!DOCTYPE r",
853        ] {
854            let k = kind(check_xml(format!("{pre}{body}").as_bytes(), &l));
855            assert!(matches!(k, Some(LimitKind::XmlEntities | LimitKind::XmlDepth)), "{pre}: {k:?}");
856            assert!(kind(check_xml(format!("{pre}{body}").as_bytes(), &Limits::default())).is_some(), "{pre} refused even with room");
857        }
858        // what real files carry still passes
859        for ok in [
860            "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
861            "<!doctype html>",
862            "<!DOCTYPE r []>",
863            "<!DOCTYPE mb [ <!ELEMENT mb (msg)*> <!ATTLIST msg id CDATA #IMPLIED d CDATA 'x'> <!-- a note --> <?pi data?> ]>",
864            "<!DOCTYPE r [ <!---->]>",
865        ] {
866            assert!(check_xml(format!("{ok}<r/>").as_bytes(), &Limits::default()).is_ok(), "{ok}");
867        }
868        // the keep-DTD check leaves this to its reader (the XML filter family refuses a mismatch itself)
869        assert!(check_xml_keeping_dtd(b"<!DOCTYPE r [<!-- > --> ]><r/>", &Limits::default()).is_ok());
870    }
871
872    #[test]
873    fn every_reading_of_the_bytes_is_scanned() {
874        let l = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
875        let body = "<a><b><c/></b></a>";
876        // 0x81 0x5D is one Shift_JIS / GBK character: the bytes end the CDATA at `]]>`, the decoded text later
877        let sjis = format!("<?xml version=\"1.0\" encoding=\"Shift_JIS\"?><r><![CDATA[\u{1}]]><!--]]>{body}--></r>");
878        let mut bytes = sjis.into_bytes();
879        let p = bytes.iter().position(|c| *c == 1).unwrap();
880        bytes[p] = 0x81;
881        assert!(check_xml(&bytes, &l).is_err());
882        // a valid double-byte file still passes
883        let ok = b"<?xml version=\"1.0\" encoding=\"Shift_JIS\"?><r><![CDATA[\x93\xfa]]>\x96\x7b</r>";
884        assert!(check_xml(ok, &Limits::default()).is_ok());
885        // a NUL first: UTF-16BE for one reader, UTF-8 for another
886        let nul = format!("\0<r>{body}</r>");
887        assert!(check_xml(nul.as_bytes(), &l).is_err());
888        let mut le = Vec::new();
889        for u in format!("<r>{body}</r>").encode_utf16() {
890            le.extend(u.to_le_bytes());
891        }
892        assert!(check_xml(&le, &l).is_err());
893        assert!(check_xml(&le, &Limits::default()).is_ok());
894    }
895
896    #[test]
897    fn a_comment_or_pi_a_scanner_ends_early_is_refused() {
898        let l = Limits::default();
899        for bad in ["<!--><r><a/></r><!-- -->", "<!---><r/><!-- -->", "<?><r/><?x?>", "<r><![IGNORE[ <a/> ]]></r>", "<!ELEMENT r ANY><r/>"] {
900            assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlElements), "{bad}");
901        }
902        for ok in ["<r><!----></r>", "<r><!-- - --></r>", "<r><??></r>", "<r><?pi x?></r>"] {
903            assert!(check_xml(ok.as_bytes(), &l).is_ok(), "{ok}");
904        }
905    }
906
907    #[test]
908    fn a_plain_doctype_and_predefined_entities_pass() {
909        let ok = br#"<?xml version="1.0"?><!DOCTYPE xliff PUBLIC "-//OASIS//DTD XLIFF 1.2//EN" "xliff.dtd"><a>x &amp; y &#233;</a>"#;
910        assert!(check_xml(ok, &Limits::default()).is_ok());
911        // an ENTITY inside a comment or CDATA is only text
912        assert!(check_xml(b"<a><!-- <!ENTITY x 'y'> --><![CDATA[<!ENTITY z 'w'>]]></a>", &Limits::default()).is_ok());
913    }
914
915    #[test]
916    fn xml_depth_and_element_count_are_bounded() {
917        let l = Limits { max_xml_depth: 8, max_xml_elements: 20, ..Limits::default() };
918        let deep = format!("{}{}", "<a>".repeat(9), "</a>".repeat(9));
919        assert_eq!(kind(check_xml(deep.as_bytes(), &l)), Some(LimitKind::XmlDepth));
920        let ok = format!("{}{}", "<a>".repeat(8), "</a>".repeat(8));
921        assert!(check_xml(ok.as_bytes(), &l).is_ok());
922        let wide = format!("<r>{}</r>", "<b/>".repeat(30));
923        assert_eq!(kind(check_xml(wide.as_bytes(), &l)), Some(LimitKind::XmlElements));
924    }
925
926    #[test]
927    fn utf16_xml_is_scanned_too() {
928        let src = "<!DOCTYPE r [<!ENTITY a 'b'>]><r/>";
929        let mut v = vec![0xFF, 0xFE];
930        v.extend(src.encode_utf16().flat_map(|u| u.to_le_bytes()));
931        assert_eq!(kind(check_xml(&v, &Limits::default())), Some(LimitKind::XmlEntities));
932    }
933
934    #[test]
935    fn counts_elements_by_local_name() {
936        let x = b"<w:body><w:p/><w:p w:x='1'>a</w:p><!-- <w:p/> --><w:pPr/><p>x</p></w:body>";
937        assert_eq!(count_elements(x, "p"), 3);
938    }
939
940    #[test]
941    fn line_budget() {
942        let l = Limits { max_lines: 5, ..Limits::default() };
943        assert!(check_lines("a\nb\nc\n", &l).is_ok());
944        assert_eq!(kind(check_lines(&"\n".repeat(6), &l)), Some(LimitKind::Lines));
945    }
946}