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    /// Too much key, note and other context text on the units (`Limits::max_context_bytes`).
32    Context,
33    /// XML nested too deeply.
34    XmlDepth,
35    /// Nesting deeper than allowed in a format that is not XML (HTML, JSON, YAML, ...). Uses
36    /// `Limits::max_xml_depth`, which is the nesting cap for every format.
37    Depth,
38    /// Too many XML elements.
39    XmlElements,
40    /// An XML entity declaration (DTD): entity bombs and external entities.
41    XmlEntities,
42    /// More paragraphs in a word-processing file than allowed (empty ones count).
43    Paragraphs,
44    /// A spreadsheet over its cell, row, characters-per-cell or total-text limit.
45    Spreadsheet,
46    /// Too many zip entries.
47    ZipEntries,
48    /// Too many bytes once unpacked.
49    ZipBytes,
50    /// A zip entry expands too much (a zip bomb).
51    ZipRatio,
52    /// A zip whose declared sizes or names are unsafe or do not match its data.
53    ZipMalformed,
54    /// A merge would write more than `Limits::max_output_bytes`.
55    OutputBytes,
56    /// A stored document's skeleton is larger, or refers to its units more often (in all, or to any one unit), than
57    /// any extraction makes it, or refers to a unit the document does not have. Merge only.
58    Skeleton,
59}
60
61/// A file refused for being over a limit or unsafe.
62#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct LimitError {
65    /// Which limit.
66    pub kind: LimitKind,
67    /// The message, safe to show the person who uploaded the file.
68    pub msg: String,
69}
70
71impl fmt::Display for LimitError {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.msg)
74    }
75}
76
77impl LimitError {
78    /// A limit error of this kind with this message.
79    pub fn new(kind: LimitKind, msg: impl Into<String>) -> LimitError {
80        LimitError { kind, msg: msg.into() }
81    }
82}
83
84impl From<LimitError> for Error {
85    fn from(e: LimitError) -> Error {
86        Error::Limit(e)
87    }
88}
89
90/// The limits one extraction runs under. `Default` is Localization OS's configuration.
91/// Build them with [`Limits::new`] and the `with_*` methods (`Limits::new().with_max_units(500)`); new limits are
92/// added without breaking callers.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(default, deny_unknown_fields)]
95#[non_exhaustive]
96pub struct Limits {
97    /// Largest input file (`MAX_UPLOAD_BYTES`).
98    pub max_input_bytes: u64,
99    /// Most units (and most segments) in a document (`MAX_DOCUMENT_SEGMENTS`).
100    pub max_units: usize,
101    /// Most characters in one unit (`MAX_SEGMENT_CHARS`).
102    pub max_unit_chars: usize,
103    /// Most lines in a text file: twenty per allowed unit, as LocOS's line budget.
104    pub max_lines: usize,
105    /// Deepest XML element nesting (libxml2's own default).
106    pub max_xml_depth: usize,
107    /// Most XML elements in one part.
108    pub max_xml_elements: usize,
109    /// Most entries in a zip (`ZIP_MAX_MEMBERS`).
110    pub max_zip_entries: usize,
111    /// Most bytes all entries of a zip unpack to (`ZIP_MAX_UNCOMPRESSED_BYTES`).
112    pub max_zip_bytes: u64,
113    /// Most bytes one zip entry may unpack to. LocOS has no cap of its own beyond the total, so the default is the
114    /// same 256 MB; a caller may set it lower (or raise both for desktop use).
115    pub max_zip_entry_bytes: u64,
116    /// Largest unpacked/packed ratio of one entry (`ZIP_MAX_RATIO`).
117    pub max_zip_ratio: u64,
118    /// Entries smaller than this are not checked for ratio (`ZIP_RATIO_MIN_BYTES`).
119    pub zip_ratio_floor_bytes: u64,
120    /// Most paragraphs in a DOCX, empty ones included (`DOCX_MAX_PARAGRAPHS`).
121    pub max_paragraphs: usize,
122    /// Most cells in an XLSX (`XLSX_MAX_CELLS`).
123    pub xlsx_max_cells: usize,
124    /// Highest row number in an XLSX (`XLSX_MAX_ROWS`).
125    pub xlsx_max_rows: u32,
126    /// Most characters in one XLSX cell or shared string (`XLSX_MAX_CELL_CHARS`, Excel's own limit).
127    pub xlsx_max_cell_chars: usize,
128    /// Most characters of cell text in an XLSX, repeated shared strings counted every time
129    /// (`XLSX_MAX_TOTAL_TEXT_CHARS`).
130    pub xlsx_max_total_text_chars: usize,
131    /// Most bytes of context the units of one document may carry together: keys, notes, headings, locations and
132    /// the other strings of `UnitContext`. A string the file holds once and a parser copies into many units counts
133    /// once per copy, so one long key or comment over many units cannot multiply the input.
134    pub max_context_bytes: u64,
135    /// Most bytes one merge may write (1 GB). Only a merge reads it: an ordinary file never comes near it, so it
136    /// bounds what a stored Document that was changed by hand can make a merge produce.
137    pub max_output_bytes: u64,
138}
139
140impl Default for Limits {
141    fn default() -> Self {
142        Limits {
143            max_input_bytes: 100 * 1024 * 1024,
144            max_units: 50_000,
145            max_unit_chars: 100_000,
146            max_lines: 20 * 50_000,
147            max_xml_depth: 256,
148            max_xml_elements: 4_000_000,
149            max_zip_entries: 10_000,
150            max_zip_bytes: 256 * 1024 * 1024,
151            max_zip_entry_bytes: 256 * 1024 * 1024,
152            max_zip_ratio: 200,
153            zip_ratio_floor_bytes: 1024 * 1024,
154            max_paragraphs: 50_000,
155            xlsx_max_cells: 500_000,
156            xlsx_max_rows: 100_000,
157            xlsx_max_cell_chars: 32_767,
158            xlsx_max_total_text_chars: 8 * 1024 * 1024,
159            max_context_bytes: 128 * 1024 * 1024,
160            max_output_bytes: 1024 * 1024 * 1024,
161        }
162    }
163}
164
165/// The largest count or size the `unbounded` profile allows (and [`Limits::clamped`] keeps any limit to): far beyond any real file, and small enough that the
166/// budgets formats derive from a limit (`40 * max_units`, `20 * max_units` lines) cannot overflow.
167/// On a 32-bit target (WASM) it is about 16 million, so `200 * max_units` still fits.
168const UNBOUNDED_COUNT: usize = if usize::BITS >= 64 { usize::MAX >> 12 } else { usize::MAX >> 8 };
169const UNBOUNDED_BYTES: u64 = u64::MAX >> 12;
170
171impl Limits {
172    /// Localization OS's limits (the same as `Limits::default()`); change any of them with the `with_*` methods.
173    /// These are the limits for a server that takes uploads from people it does not know (`hosted`).
174    pub fn new() -> Limits {
175        Limits::default()
176    }
177
178    /// The limits for a person's own files on their own machine (the CLI, the desktop app, a batch job): large
179    /// enough for any ordinary document (a 4 GB input, 20 million units or paragraphs, every row Excel allows,
180    /// 200 million cells), so big manuals, spreadsheets and pages are processed at the cost of memory. The
181    /// structural guards stay: XML nesting depth, zip entry count, a zip that unpacks to at most 4 GB (2 GB per
182    /// part, more than a full million-row sheet needs) and a ratio check that still stops a zip bomb (1000:1
183    /// instead of 200:1). It is the CLI's default, so it must stay safe for a downloaded attachment.
184    pub fn large() -> Limits {
185        Limits {
186            max_input_bytes: 4 << 30,
187            max_units: 20_000_000,
188            max_unit_chars: 10_000_000,
189            max_lines: 400_000_000,
190            max_xml_depth: 256,
191            max_xml_elements: 400_000_000,
192            max_zip_entries: 200_000,
193            max_zip_bytes: 4 << 30,
194            max_zip_entry_bytes: 2 << 30,
195            max_zip_ratio: 1000,
196            zip_ratio_floor_bytes: 1024 * 1024,
197            max_paragraphs: 20_000_000,
198            xlsx_max_cells: 200_000_000,
199            xlsx_max_rows: 1_048_576,
200            xlsx_max_cell_chars: 32_767,
201            xlsx_max_total_text_chars: 2_000_000_000,
202            max_context_bytes: 16 << 30,
203            max_output_bytes: 32 << 30,
204        }
205    }
206
207    /// No size or count limits at all: only what the machine's memory allows. The XML depth limit stays (it
208    /// protects the stack, and no real document nests 256 elements deep). Use it only for trusted files.
209    pub fn unbounded() -> Limits {
210        Limits {
211            max_input_bytes: UNBOUNDED_BYTES,
212            max_units: UNBOUNDED_COUNT,
213            max_unit_chars: UNBOUNDED_COUNT,
214            max_lines: UNBOUNDED_COUNT,
215            max_xml_depth: 256,
216            max_xml_elements: UNBOUNDED_COUNT,
217            max_zip_entries: UNBOUNDED_COUNT,
218            max_zip_bytes: UNBOUNDED_BYTES,
219            max_zip_entry_bytes: UNBOUNDED_BYTES,
220            max_zip_ratio: UNBOUNDED_BYTES,
221            zip_ratio_floor_bytes: 1024 * 1024,
222            max_paragraphs: UNBOUNDED_COUNT,
223            xlsx_max_cells: UNBOUNDED_COUNT,
224            xlsx_max_rows: u32::MAX >> 4,
225            xlsx_max_cell_chars: UNBOUNDED_COUNT,
226            xlsx_max_total_text_chars: UNBOUNDED_COUNT,
227            max_context_bytes: UNBOUNDED_BYTES,
228            max_output_bytes: UNBOUNDED_BYTES,
229        }
230    }
231
232    /// A profile by name, any case: `hosted` (the default, [`Limits::new`]; also `default`, `server`), `large`
233    /// ([`Limits::large`]; also `desktop`, `local`) or `unbounded` ([`Limits::unbounded`]; also `none`). `None`
234    /// for any other name.
235    pub fn profile(name: &str) -> Option<Limits> {
236        match name.trim().to_ascii_lowercase().as_str() {
237            "hosted" | "default" | "server" => Some(Limits::new()),
238            "large" | "desktop" | "local" => Some(Limits::large()),
239            "unbounded" | "none" => Some(Limits::unbounded()),
240            _ => None,
241        }
242    }
243
244    /// The same limits with every count and size kept to what [`Limits::unbounded`] allows, so no budget a
245    /// format derives from a limit (`200 * max_units`, `10 * max_units as i64`) can overflow. Extract and merge
246    /// apply it to the caller's limits; it changes nothing under `hosted` or `large`.
247    pub fn clamped(self) -> Limits {
248        let u = Limits::unbounded();
249        Limits {
250            max_input_bytes: self.max_input_bytes.min(u.max_input_bytes),
251            max_units: self.max_units.min(u.max_units),
252            max_unit_chars: self.max_unit_chars.min(u.max_unit_chars),
253            max_lines: self.max_lines.min(u.max_lines),
254            max_xml_depth: self.max_xml_depth,
255            max_xml_elements: self.max_xml_elements.min(u.max_xml_elements),
256            max_zip_entries: self.max_zip_entries.min(u.max_zip_entries),
257            max_zip_bytes: self.max_zip_bytes.min(u.max_zip_bytes),
258            max_zip_entry_bytes: self.max_zip_entry_bytes.min(u.max_zip_entry_bytes),
259            max_zip_ratio: self.max_zip_ratio.min(u.max_zip_ratio),
260            zip_ratio_floor_bytes: self.zip_ratio_floor_bytes,
261            max_paragraphs: self.max_paragraphs.min(u.max_paragraphs),
262            xlsx_max_cells: self.xlsx_max_cells.min(u.xlsx_max_cells),
263            xlsx_max_rows: self.xlsx_max_rows.min(u.xlsx_max_rows),
264            xlsx_max_cell_chars: self.xlsx_max_cell_chars.min(u.xlsx_max_cell_chars),
265            xlsx_max_total_text_chars: self.xlsx_max_total_text_chars.min(u.xlsx_max_total_text_chars),
266            max_context_bytes: self.max_context_bytes.min(u.max_context_bytes),
267            max_output_bytes: self.max_output_bytes.min(u.max_output_bytes),
268        }
269    }
270    /// Sets `max_input_bytes`.
271    pub fn with_max_input_bytes(mut self, v: u64) -> Limits {
272        self.max_input_bytes = v;
273        self
274    }
275    /// Sets `max_units`.
276    pub fn with_max_units(mut self, v: usize) -> Limits {
277        self.max_units = v;
278        self
279    }
280    /// Sets `max_unit_chars`.
281    pub fn with_max_unit_chars(mut self, v: usize) -> Limits {
282        self.max_unit_chars = v;
283        self
284    }
285    /// Sets `max_lines`.
286    pub fn with_max_lines(mut self, v: usize) -> Limits {
287        self.max_lines = v;
288        self
289    }
290    /// Sets `max_xml_depth`.
291    pub fn with_max_xml_depth(mut self, v: usize) -> Limits {
292        self.max_xml_depth = v;
293        self
294    }
295    /// Sets `max_xml_elements`.
296    pub fn with_max_xml_elements(mut self, v: usize) -> Limits {
297        self.max_xml_elements = v;
298        self
299    }
300    /// Sets `max_zip_entries`.
301    pub fn with_max_zip_entries(mut self, v: usize) -> Limits {
302        self.max_zip_entries = v;
303        self
304    }
305    /// Sets `max_zip_bytes`.
306    pub fn with_max_zip_bytes(mut self, v: u64) -> Limits {
307        self.max_zip_bytes = v;
308        self
309    }
310    /// Sets `max_zip_entry_bytes`.
311    pub fn with_max_zip_entry_bytes(mut self, v: u64) -> Limits {
312        self.max_zip_entry_bytes = v;
313        self
314    }
315    /// Sets `max_zip_ratio`.
316    pub fn with_max_zip_ratio(mut self, v: u64) -> Limits {
317        self.max_zip_ratio = v;
318        self
319    }
320    /// Sets `zip_ratio_floor_bytes`.
321    pub fn with_zip_ratio_floor_bytes(mut self, v: u64) -> Limits {
322        self.zip_ratio_floor_bytes = v;
323        self
324    }
325    /// Sets `max_paragraphs`.
326    pub fn with_max_paragraphs(mut self, v: usize) -> Limits {
327        self.max_paragraphs = v;
328        self
329    }
330    /// Sets `xlsx_max_cells`.
331    pub fn with_xlsx_max_cells(mut self, v: usize) -> Limits {
332        self.xlsx_max_cells = v;
333        self
334    }
335    /// Sets `xlsx_max_rows`.
336    pub fn with_xlsx_max_rows(mut self, v: u32) -> Limits {
337        self.xlsx_max_rows = v;
338        self
339    }
340    /// Sets `xlsx_max_cell_chars`.
341    pub fn with_xlsx_max_cell_chars(mut self, v: usize) -> Limits {
342        self.xlsx_max_cell_chars = v;
343        self
344    }
345    /// Sets `xlsx_max_total_text_chars`.
346    pub fn with_xlsx_max_total_text_chars(mut self, v: usize) -> Limits {
347        self.xlsx_max_total_text_chars = v;
348        self
349    }
350    /// Sets `max_context_bytes`.
351    pub fn with_max_context_bytes(mut self, v: u64) -> Limits {
352        self.max_context_bytes = v;
353        self
354    }
355    /// Sets `max_output_bytes`.
356    pub fn with_max_output_bytes(mut self, v: u64) -> Limits {
357        self.max_output_bytes = v;
358        self
359    }
360}
361
362/// A format crate's own cap under the caller's limit for the same thing. While the caller's number is at or below
363/// the hosted one (`hosted`, the field of [`Limits::new`]) the cap is the smaller of the crate's own and the
364/// caller's, so a server gets exactly the crate's numbers it always had; once the caller raised it above the
365/// hosted number (`Limits::large`, `Limits::unbounded`, a desktop's own choice) the caller's number decides, so a
366/// raised profile raises every format.
367pub fn own_cap<T: Ord + Copy>(own: T, hosted: T, caller: T) -> T {
368    if caller > hosted {
369        caller
370    } else {
371        own.min(caller)
372    }
373}
374
375/// [`own_cap`] for a byte cap kept as `usize` against a `u64` limit.
376pub fn own_cap_bytes(own: usize, hosted: u64, caller: u64) -> usize {
377    let c = usize::try_from(caller).unwrap_or(usize::MAX);
378    if caller > hosted {
379        c
380    } else {
381        own.min(c)
382    }
383}
384
385fn mb(n: u64) -> String {
386    if n >= 1024 * 1024 {
387        format!("{} MB", n / (1024 * 1024))
388    } else {
389        format!("{n} bytes")
390    }
391}
392
393/// Refuses an input over `max_input_bytes`. Call before any other work on the bytes.
394pub fn check_input(bytes: &[u8], l: &Limits) -> Result<(), Error> {
395    if bytes.len() as u64 > l.max_input_bytes {
396        return Err(LimitError::new(
397            LimitKind::InputBytes,
398            format!(
399                "This file is {} long; the limit is {}. Split it into smaller files.",
400                mb(bytes.len() as u64),
401                mb(l.max_input_bytes)
402            ),
403        )
404        .into());
405    }
406    Ok(())
407}
408
409/// Refuses a text with more lines than the line budget, before any per-line work (a file of 100 MB of newlines
410/// would otherwise build a list of 100 million lines).
411pub fn check_lines(text: &str, l: &Limits) -> Result<(), Error> {
412    let n = text.bytes().filter(|b| *b == b'\n' || *b == b'\r').count();
413    if n > l.max_lines {
414        return Err(LimitError::new(
415            LimitKind::Lines,
416            format!("This file has more than {} lines. Split it into smaller files.", l.max_lines),
417        )
418        .into());
419    }
420    Ok(())
421}
422
423/// The running-total check for a parser that counts units as it goes: refuse as soon as `count` passes the cap,
424/// so a hostile file stops early.
425pub fn check_unit_count(count: usize, l: &Limits) -> Result<(), Error> {
426    if count > l.max_units {
427        return Err(LimitError::new(
428            LimitKind::Units,
429            format!("This file has more than {} segments. Split it into smaller files.", l.max_units),
430        )
431        .into());
432    }
433    Ok(())
434}
435
436/// LocOS's `office_comments.COMMENT_BASE`: the Office formats (ODF, PPTX, VSDX, XLSX) number comment units from
437/// here, above every body paragraph, cell or text box, so a file read without comments keeps its numbers.
438pub const COMMENT_BASE: usize = 1_000_000;
439
440/// BILI-126: refuses a file whose body numbers reach [`COMMENT_BASE`] while it has comment units. `body_end` is one
441/// past the highest body number, counted the way the format numbers its body (empty slots too where they count).
442/// No body gets there under the hosted limits' unit cap; under `Limits::large()` one can, and a comment would then
443/// share its number with a body unit, so a merge could write a comment's translation into the body or the reverse.
444/// Refusing keeps LocOS's one numbering for every file below the line rather than a second scheme for the few above
445/// it. Call it before the first comment unit is made; a merge calls [`check_comment_base_merge`].
446pub fn check_comment_base(body_end: usize) -> Result<(), Error> {
447    if body_end > COMMENT_BASE {
448        return Err(LimitError::new(
449            LimitKind::Units,
450            "This file has more than 1,000,000 paragraphs, cells or text boxes and also has comments to translate, \
451             which is more than Bilingua can number apart. Turn off comment translation or split the file.",
452        )
453        .into());
454    }
455    Ok(())
456}
457
458/// The merge-time refusal of BILI-126: the document's comments and body share numbers. An extraction never makes
459/// such a document, so it was changed by hand or put together from another file.
460fn comment_numbers_shared() -> Error {
461    LimitError::new(
462        LimitKind::Units,
463        "This document's comments and body text share numbers, so it cannot be merged safely. Extract the file again without comments.",
464    )
465    .into()
466}
467
468/// [`check_comment_base`] for a merge that writes comments by number: a document with comment units over a body
469/// that reaches [`COMMENT_BASE`] is refused.
470pub fn check_comment_base_merge(body_end: usize) -> Result<(), Error> {
471    if body_end > COMMENT_BASE {
472        return Err(comment_numbers_shared());
473    }
474    Ok(())
475}
476
477/// BILI-126: refuses a merge whose units carry one number twice (`numbers`: every unit's LocOS number), whatever
478/// their kind or hidden fields, so a hand edit that strips a comment's marks cannot slip a comment into the body.
479pub fn check_distinct_numbers(numbers: impl IntoIterator<Item = i64>) -> Result<(), Error> {
480    let mut seen = std::collections::HashSet::new();
481    if numbers.into_iter().any(|n| !seen.insert(n)) {
482        return Err(comment_numbers_shared());
483    }
484    Ok(())
485}
486
487/// Localization OS's pre-parse budget (#571 and its gate): a text with more than `per_unit` x `max_units` of some
488/// marker (`count`: JSON quotes, or commas and brackets; PO backslashes) is refused before the parser builds
489/// anything, since each marker costs work or memory whether or not it ends in a unit (100 MB of `{},` holds no
490/// text but millions of values). `what` names the file and the marker ("This JSON file has far more values").
491pub fn check_budget(count: usize, per_unit: usize, what: &str, l: &Limits) -> Result<(), Error> {
492    if count > per_unit.saturating_mul(l.max_units) {
493        return Err(LimitError::new(
494            LimitKind::Units,
495            format!("{what} than a file of {} segments. Split it into smaller files.", l.max_units),
496        )
497        .into());
498    }
499    Ok(())
500}
501
502/// Refuses a unit text longer than `max_unit_chars` characters.
503pub fn check_unit_chars(chars: usize, l: &Limits) -> Result<(), Error> {
504    if chars > l.max_unit_chars {
505        return Err(LimitError::new(
506            LimitKind::UnitChars,
507            format!(
508                "This file has a line or paragraph longer than {} characters. Break it into shorter lines.",
509                l.max_unit_chars
510            ),
511        )
512        .into());
513    }
514    Ok(())
515}
516
517/// Refuses a running total of context bytes over `max_context_bytes`.
518pub fn check_context_bytes(total: u64, l: &Limits) -> Result<(), Error> {
519    if total > l.max_context_bytes {
520        return Err(LimitError::new(
521            LimitKind::Context,
522            format!(
523                "This file carries more key, comment and note text than the limit of {} allows. Split it into smaller files.",
524                mb(l.max_context_bytes)
525            ),
526        )
527        .into());
528    }
529    Ok(())
530}
531
532/// The bytes of context one unit carries: every string of its `UnitContext`.
533pub fn unit_context_bytes(c: &crate::UnitContext) -> u64 {
534    let opt = |s: &Option<String>| s.as_ref().map_or(0, |v| v.len() as u64);
535    opt(&c.kind)
536        + opt(&c.style)
537        + opt(&c.key)
538        + opt(&c.heading)
539        + opt(&c.location)
540        + c.notes.iter().map(|n| n.len() as u64).sum::<u64>()
541        + c.extra.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum::<u64>()
542}
543
544/// The running context budget for a parser that copies a shared string (a key path, a section name, a comment)
545/// into many units: charge every copy before it is made, so a hostile file is refused before the memory is
546/// taken. `check_document` applies the same cap to the finished document as the safety net.
547#[derive(Debug, Clone, Copy, Default)]
548pub struct ContextBudget {
549    used: u64,
550}
551
552impl ContextBudget {
553    /// A budget with nothing charged.
554    pub fn new() -> ContextBudget {
555        ContextBudget::default()
556    }
557    /// Charges `bytes` more of context and refuses once the total passes `max_context_bytes`.
558    pub fn charge(&mut self, bytes: usize, l: &Limits) -> Result<(), Error> {
559        self.used = self.used.saturating_add(bytes as u64);
560        check_context_bytes(self.used, l)
561    }
562    /// The bytes charged so far.
563    pub fn used(&self) -> u64 {
564        self.used
565    }
566}
567
568/// The check for a finished extraction: unit and segment counts, the length of every unit, and the context
569/// bytes of all units together.
570pub fn check_document(doc: &Document, l: &Limits) -> Result<(), Error> {
571    check_unit_count(doc.units.len(), l)?;
572    check_unit_count(doc.segment_count(), l)?;
573    let mut context: u64 = 0;
574    for u in &doc.units {
575        context = context.saturating_add(unit_context_bytes(&u.context));
576        check_context_bytes(context, l)?;
577        let chars: usize = u
578            .segments
579            .iter()
580            .flat_map(|s| s.source.iter())
581            .map(|i| match i {
582                crate::Inline::Text(t) => t.chars().count(),
583                crate::Inline::Tag { .. } => 1,
584            })
585            .sum();
586        check_unit_chars(chars, l)?;
587    }
588    Ok(())
589}
590
591/// How often a skeleton may refer to units: in all, per allowed unit (`max_units`), and to any one unit.
592/// Extraction writes each unit into the skeleton once or a few times; a stored Document that refers to one unit
593/// many more times would make a merge write that unit over and over (a small Document, a large output).
594pub const MERGE_REFS_PER_UNIT: usize = 4;
595
596/// How long a stored target may be, as a multiple of `max_unit_chars` (a source over that one is refused at
597/// extract; a translation may be longer than its source, but not without bound).
598pub const MERGE_TARGET_CHARS_FACTOR: usize = 4;
599
600/// The checks a merge runs on a stored Document before writing it (BILI-105). A Document is the caller's data, and
601/// a host should keep a stored one where only it can write it, but it is plain JSON between extract and merge, so
602/// these bound what one that was edited by hand can make a merge do, under the caller's merge limits
603/// (`MergeOptions::limits`):
604/// * the checks of an extraction ([`check_document`]): units and segments within `max_units`, every unit's source
605///   within `max_unit_chars`, the context within `max_context_bytes`; and every unit's target within
606///   [`MERGE_TARGET_CHARS_FACTOR`] x `max_unit_chars`;
607/// * no more zip entries than `max_zip_entries`, and every zip entry name one the zip reader gives
608///   ([`check_zip_name`]), none listed twice (case and `\` against `/` ignored, as the reader compares them);
609/// * at most [`MERGE_REFS_PER_UNIT`] x `max_units` unit slots in all, at most [`MERGE_REFS_PER_UNIT`] to any one
610///   unit, none to a unit the document does not have, and `max_lines` + the slot cap skeleton parts
611///   ([`LimitKind::Skeleton`]);
612/// * an estimate of the output (the skeleton's own bytes, each unit slot counted at its unit's size, and the units
613///   once more for formats that rebuild from them) within `max_output_bytes`.
614///
615/// An ordinary extraction is far inside every one of these.
616pub fn check_merge(doc: &Document, l: &Limits) -> Result<(), Error> {
617    check_document(doc, l)?;
618    check_target_chars(doc, l)?;
619    let max_refs = MERGE_REFS_PER_UNIT.saturating_mul(l.max_units);
620    let max_parts = l.max_lines.saturating_add(max_refs);
621    let sizes: Vec<u64> = doc.units.iter().map(unit_output_bytes).collect();
622    let mut walk = SkeletonWalk { parts: 0, refs: 0, per_unit: vec![0; sizes.len()], estimate: sizes.iter().fold(0u64, |a, b| a.saturating_add(*b)) };
623    check_output_estimate(walk.estimate, l)?;
624    match &doc.skeleton {
625        crate::Skeleton::Text { parts, .. } => walk.parts(parts, &sizes, max_parts, max_refs, l)?,
626        crate::Skeleton::Zip { entries, .. } => {
627            if entries.len() > l.max_zip_entries {
628                return Err(LimitError::new(
629                    LimitKind::ZipEntries,
630                    format!("This document lists more than {} zip entries. It was not written.", l.max_zip_entries),
631                )
632                .into());
633            }
634            let mut seen = std::collections::HashSet::with_capacity(entries.len());
635            for e in entries {
636                // a format's own records (`\0bilingua-docx-meta`, ...) are never written as entries: the zip
637                // writers refuse a name with a control character, so one changed by hand cannot reach the output
638                if e.name.starts_with(INTERNAL_ENTRY_PREFIX) {
639                    continue;
640                }
641                check_zip_name(&e.name)?;
642                if !seen.insert(e.name.to_ascii_lowercase()) {
643                    return Err(zip_name_error(&e.name, "is listed twice"));
644                }
645            }
646            for e in entries {
647                match &e.data {
648                    crate::ZipData::Raw(b) => {
649                        walk.estimate = walk.estimate.saturating_add(b.len() as u64);
650                        check_output_estimate(walk.estimate, l)?;
651                    }
652                    crate::ZipData::Parts(parts) => walk.parts(parts, &sizes, max_parts, max_refs, l)?,
653                }
654            }
655        }
656        crate::Skeleton::Binary { data, .. } => {
657            walk.estimate = walk.estimate.saturating_add(data.len() as u64);
658            check_output_estimate(walk.estimate, l)?;
659        }
660    }
661    Ok(())
662}
663
664/// Refuses a stored target longer than [`MERGE_TARGET_CHARS_FACTOR`] x `max_unit_chars` (codes count one each,
665/// as in [`check_document`]).
666fn check_target_chars(doc: &Document, l: &Limits) -> Result<(), Error> {
667    let max = l.max_unit_chars.saturating_mul(MERGE_TARGET_CHARS_FACTOR);
668    for u in &doc.units {
669        let chars: usize = u
670            .segments
671            .iter()
672            .flat_map(|s| s.target.iter())
673            .map(|i| match i {
674                crate::Inline::Text(t) => t.chars().count(),
675                crate::Inline::Tag { .. } => 1,
676            })
677            .fold(0usize, usize::saturating_add);
678        if chars > max {
679            return Err(LimitError::new(
680                LimitKind::UnitChars,
681                format!("This document has a translation longer than {max} characters. It was not written."),
682            )
683            .into());
684        }
685    }
686    Ok(())
687}
688
689/// The prefix of the zip skeleton entries a format keeps for itself (its metadata, the original archive), which no
690/// writer puts in the output archive.
691pub const INTERNAL_ENTRY_PREFIX: &str = "\0bilingua-";
692
693fn zip_name_error(raw: &str, what: &str) -> Error {
694    // the name is the caller's own data; shown escaped and cut short
695    let shown: String = raw.chars().take(80).flat_map(char::escape_debug).collect();
696    LimitError::new(LimitKind::ZipMalformed, format!("This document has a zip entry name that {what} (\"{shown}\"). It was not written.")).into()
697}
698
699/// Refuses a zip entry name the zip reader never gives (BILI-105): a stored Document's names are written into the
700/// output archive, so one that was changed by hand must not reach it. A name the reader gives is relative, uses
701/// `/`, and has no empty, `.` or `..` component, no component made only of dots and spaces, no colon and no
702/// control character; a folder ends in `/`. Duplicates are checked over the whole list by [`check_merge`].
703pub fn check_zip_name(raw: &str) -> Result<(), Error> {
704    if raw.is_empty() {
705        return Err(zip_name_error(raw, "is empty"));
706    }
707    if raw.chars().any(char::is_control) {
708        return Err(zip_name_error(raw, "holds a control character"));
709    }
710    if raw.starts_with('/') || raw.contains('\\') {
711        return Err(zip_name_error(raw, "is an absolute path or uses a backslash"));
712    }
713    if raw.contains(':') {
714        return Err(zip_name_error(raw, "contains a colon"));
715    }
716    let body = raw.strip_suffix('/').unwrap_or(raw);
717    for part in body.split('/') {
718        if part == ".." {
719            return Err(zip_name_error(raw, "climbs out of the archive (..)"));
720        }
721        if part.is_empty() || part.trim_end_matches(['.', ' ']).is_empty() {
722            return Err(zip_name_error(raw, "has an empty component or one made of dots or spaces"));
723        }
724    }
725    Ok(())
726}
727
728/// The running totals of [`check_merge`] over every part list of a skeleton.
729struct SkeletonWalk {
730    parts: usize,
731    refs: usize,
732    /// References so far to each unit.
733    per_unit: Vec<usize>,
734    estimate: u64,
735}
736
737impl SkeletonWalk {
738    fn parts(&mut self, parts: &[crate::SkelPart], sizes: &[u64], max_parts: usize, max_refs: usize, l: &Limits) -> Result<(), Error> {
739        self.parts = self.parts.saturating_add(parts.len());
740        if self.parts > max_parts {
741            return Err(over_skeleton(l));
742        }
743        for p in parts {
744            match p {
745                crate::SkelPart::Raw(s) => self.estimate = self.estimate.saturating_add(s.len() as u64),
746                crate::SkelPart::Unit(i) => {
747                    self.refs += 1;
748                    if self.refs > max_refs {
749                        return Err(over_skeleton(l));
750                    }
751                    let Some(n) = self.per_unit.get_mut(*i) else {
752                        return Err(LimitError::new(
753                            LimitKind::Skeleton,
754                            format!("This document's skeleton refers to unit {i}, which the document does not have. It was not written."),
755                        )
756                        .into());
757                    };
758                    *n += 1;
759                    if *n > MERGE_REFS_PER_UNIT {
760                        return Err(LimitError::new(
761                            LimitKind::Skeleton,
762                            format!(
763                                "This document's skeleton writes one unit more than {MERGE_REFS_PER_UNIT} times, more than any extraction makes it. It was not written."
764                            ),
765                        )
766                        .into());
767                    }
768                    self.estimate = self.estimate.saturating_add(sizes[*i]);
769                }
770            }
771        }
772        check_output_estimate(self.estimate, l)
773    }
774}
775
776/// Refuses merge output over `max_output_bytes` (the facade calls it on what the writer returned).
777pub fn check_output(len: usize, l: &Limits) -> Result<(), Error> {
778    check_output_estimate(len as u64, l)
779}
780
781fn check_output_estimate(n: u64, l: &Limits) -> Result<(), Error> {
782    if n > l.max_output_bytes {
783        return Err(LimitError::new(
784            LimitKind::OutputBytes,
785            format!("This document would write more than {}, the output limit. It was not written.", mb(l.max_output_bytes)),
786        )
787        .into());
788    }
789    Ok(())
790}
791
792fn over_skeleton(l: &Limits) -> Error {
793    LimitError::new(
794        LimitKind::Skeleton,
795        format!(
796            "This document's skeleton is larger, or refers to its units more often, than a file of {} segments. It was not written.",
797            l.max_units
798        ),
799    )
800    .into()
801}
802
803/// What writing one unit costs at least: per segment the larger of its source and target, each code counted at
804/// its stored markup.
805fn unit_output_bytes(u: &crate::Unit) -> u64 {
806    let inlines = |v: &[crate::Inline]| -> u64 {
807        v.iter()
808            .map(|i| match i {
809                crate::Inline::Text(t) => t.len() as u64,
810                crate::Inline::Tag { id, kind, display, .. } => {
811                    let code = u.codes.get(id).and_then(|c| match kind {
812                        crate::TagKind::Open => c.open.as_ref(),
813                        crate::TagKind::Close => c.close.as_ref(),
814                        crate::TagKind::Standalone => c.standalone.as_ref(),
815                    });
816                    code.map_or(display.len(), String::len) as u64
817                }
818            })
819            .fold(0u64, u64::saturating_add)
820    };
821    u.segments.iter().map(|s| inlines(&s.source).max(inlines(&s.target))).fold(0u64, u64::saturating_add)
822}
823
824/// Checks every stored target's tags as a merge reads them (BILI-105): a tag must be one of its segment's source
825/// tags (same id and kind) or have its markup in the unit's `codes`. With `counts`, a paired tag may also appear no more often than in the source, the
826/// rule of [`Document::set_target_repeating`](crate::Document::set_target_repeating); without it repeats pass.
827pub fn check_targets(doc: &Document, counts: bool) -> Result<(), Error> {
828    for u in &doc.units {
829        for s in &u.segments {
830            if !s.target.is_empty() {
831                crate::check_target_tags(&s.source, &s.target, &u.codes, counts)?;
832            }
833        }
834    }
835    Ok(())
836}
837
838/// What every parser ends with: the document passes `check_document`, and the warnings of the text decode go on it.
839pub fn finish(mut doc: Document, warnings: Vec<crate::Warning>, l: &Limits) -> Result<Document, Error> {
840    check_document(&doc, l)?;
841    doc.warnings.extend(warnings);
842    Ok(doc)
843}
844
845fn unsafe_xml(msg: impl Into<String>) -> Error {
846    LimitError::new(LimitKind::XmlEntities, msg).into()
847}
848
849fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
850    if from >= hay.len() {
851        return None;
852    }
853    hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
854}
855
856fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {
857    hay.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle))
858}
859
860/// Reads XML as bytes, transcoding UTF-16 (BOM or `<` in 16-bit form) so the scan sees ASCII markup.
861fn markup_bytes(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
862    let le = bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[b'<', 0]);
863    let be = bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0, b'<']);
864    if le && !bytes.starts_with(&[0xFF, 0xFE, 0, 0]) {
865        let (s, _) = encoding_rs::UTF_16LE.decode_without_bom_handling(bytes);
866        return std::borrow::Cow::Owned(s.into_owned().into_bytes());
867    }
868    if be {
869        let (s, _) = encoding_rs::UTF_16BE.decode_without_bom_handling(bytes);
870        return std::borrow::Cow::Owned(s.into_owned().into_bytes());
871    }
872    std::borrow::Cow::Borrowed(bytes)
873}
874
875/// The XML guard: scans the markup of one XML part once and refuses
876/// * any `<!ENTITY` declaration (an entity bomb or an external entity; `&amp; &lt; &gt; &quot; &apos;` and
877///   character references are all a document needs),
878/// * nesting deeper than `max_xml_depth`,
879/// * more than `max_xml_elements` elements.
880///
881/// Comments, CDATA sections and processing instructions are skipped, so markup inside them is not counted.
882///
883/// The count is only as good as the reader's agreement on where those regions end, so a part is also refused when
884/// the readers would not agree: a DOCTYPE that never ends, has a `<`, `>` or bracket in a quoted string, a bracket
885/// or angle bracket in a comment of its internal subset (a quote there is fine, but then no `<!ENTITY` may follow
886/// the DOCTYPE anywhere), a quote in a processing instruction of the subset, or a `<`/`>` that `quick-xml` pairs
887/// differently; a comment that
888/// starts with `>` or `->`; `<?>`; a `<!` declaration outside the DOCTYPE. Every reading a reader may give the
889/// bytes is scanned: UTF-16 and UTF-8 for `<\0` without a byte order mark, and the double-byte code pages for
890/// bytes that are not UTF-8.
891pub fn check_xml(bytes: &[u8], l: &Limits) -> Result<(), Error> {
892    check_xml_with(bytes, l, false, false)
893}
894
895/// Like [`check_xml`], but a DOCTYPE may declare plain internal entities: `<!ENTITY name "literal">` with a literal
896/// that holds no `&` (so no entity expands into another), at most 1024 bytes long, and at most 64 of them. Adobe Illustrator, Inkscape and
897/// Sodipodi SVGs declare a few of these for namespace URIs. External (`SYSTEM`, `PUBLIC`) and parameter (`%`)
898/// entities are refused as before, and every other check of [`check_xml`] still applies. For a reader that never
899/// expands an entity (the SVG filter keeps every `&name;` as typed).
900pub fn check_xml_internal_entities(bytes: &[u8], l: &Limits) -> Result<(), Error> {
901    check_xml_with(bytes, l, false, true)
902}
903
904/// True when every `<!ENTITY` declaration in a DOCTYPE is `<!ENTITY name "literal">` (or single quotes) and the
905/// literal has no `&`; false for an external or parameter entity, a malformed one, or more than 64.
906fn only_plain_internal_entities(doctype: &[u8]) -> bool {
907    let mut n = 0usize;
908    let mut from = 0usize;
909    while let Some(p) = doctype[from..].windows(8).position(|w| w.eq_ignore_ascii_case(b"<!ENTITY")) {
910        n += 1;
911        if n > 64 {
912            return false;
913        }
914        let mut j = from + p + 8;
915        let ws = |j: &mut usize| {
916            let s = *j;
917            while *j < doctype.len() && matches!(doctype[*j], b' ' | b'\t' | b'\r' | b'\n') {
918                *j += 1;
919            }
920            *j > s
921        };
922        if !ws(&mut j) {
923            return false;
924        }
925        let name_start = j;
926        while j < doctype.len() && (doctype[j].is_ascii_alphanumeric() || matches!(doctype[j], b'_' | b'-' | b'.' | b':')) {
927            j += 1;
928        }
929        if j == name_start || !ws(&mut j) || j >= doctype.len() {
930            return false;
931        }
932        let q = doctype[j];
933        if q != b'"' && q != b'\'' {
934            return false;
935        }
936        let Some(len) = doctype[j + 1..].iter().position(|c| *c == q) else { return false };
937        // no `&`: nothing expands into anything; at most 1024 bytes: a few references cannot blow up a reader
938        // that does expand them (the file is written back as it is, for browsers and editors to read)
939        if len > 1024 || doctype[j + 1..j + 1 + len].contains(&b'&') {
940            return false;
941        }
942        from = j + 1 + len + 1;
943    }
944    true
945}
946
947/// Like [`check_xml`] for document formats where a DTD with entity declarations is normal (DocBook, DITA, plain
948/// XML): the declarations are allowed, and the depth and element limits still apply. This is safe only for a reader
949/// that never expands or fetches an entity, as the XML filter family does: it keeps every `&name;` as an opaque
950/// code and writes the DOCTYPE back byte for byte.
951pub fn check_xml_keeping_dtd(bytes: &[u8], l: &Limits) -> Result<(), Error> {
952    check_xml_with(bytes, l, true, false)
953}
954
955/// End of a `<!DOCTYPE ...>` that starts at `i`: the index of its closing `>` (or `b.len()`). Quoted strings, the
956/// `[ ... ]` internal subset and the comments and processing instructions inside it are skipped.
957fn doctype_end(b: &[u8], i: usize) -> usize {
958    let (mut j, mut sq, mut subset) = (i + 9, 0u8, 0usize);
959    while j < b.len() {
960        let c = b[j];
961        if sq != 0 {
962            if c == sq {
963                sq = 0;
964            }
965        } else if c == b'"' || c == b'\'' {
966            sq = c;
967        } else if subset > 0 && b[j..].starts_with(b"<!--") {
968            match find(b, j + 4, b"-->") {
969                Some(e) => j = e + 2,
970                None => return b.len(),
971            }
972        } else if subset > 0 && b[j..].starts_with(b"<?") {
973            match find(b, j + 2, b"?>") {
974                Some(e) => j = e + 1,
975                None => return b.len(),
976            }
977        } else if c == b'[' {
978            subset += 1;
979        } else if c == b']' {
980            subset = subset.saturating_sub(1);
981        } else if c == b'>' && subset == 0 {
982            break;
983        }
984        j += 1;
985    }
986    j.min(b.len())
987}
988
989/// Where `quick-xml` ends the `<!DOCTYPE` that starts at `i`: the first `>` outside a `<` ... `>` pair, quotes,
990/// brackets and comments not looked at (the index of that `>`, or `None` when there is none).
991fn reader_doctype_end(b: &[u8], i: usize) -> Option<usize> {
992    let mut balance = 0usize;
993    for (j, c) in b.iter().enumerate().skip(i + 2) {
994        match c {
995            b'<' => balance += 1,
996            b'>' if balance == 0 => return Some(j),
997            b'>' => balance -= 1,
998            _ => {}
999        }
1000    }
1001    None
1002}
1003
1004/// `Some` when every XML reader in the workspace ends the DOCTYPE at `i..=end` (`end` from [`doctype_end`]) at
1005/// the same `>`. The readers differ in what they skip: `quick-xml` only pairs `<` with `>` (and skips the comments
1006/// of the subset whole); the hand-written scanners skip quoted strings, some also the `[ ... ]` subset, some the
1007/// comments or processing instructions inside it. They all agree when no quoted string holds a `<`, `>`, `[` or
1008/// `]`, no comment or processing instruction of the subset holds a bracket or an angle bracket of its own, no
1009/// processing instruction a quote, and `quick-xml` stops at the same place. Real files meet that easily
1010/// (`<!DOCTYPE plist PUBLIC "..." "...">`, an XMB subset of `<!ELEMENT>` and `<!ATTLIST>` declarations).
1011///
1012/// A quote in a comment of the subset (`<!-- don't edit -->`, BILI-60) ends the DOCTYPE in the same place for
1013/// every reader that skips the comment; `Some(true)` says the DOCTYPE has one, so the caller can make sure a
1014/// scanner that pairs that quote instead could not find an entity declaration in what follows.
1015fn doctype_is_unambiguous(b: &[u8], i: usize, end: usize) -> Option<bool> {
1016    if end >= b.len() || reader_doctype_end(b, i) != Some(end) {
1017        return None;
1018    }
1019    let mut quoted_comment = false;
1020    let special = |s: &[u8], also_quotes: bool| s.iter().any(|c| matches!(c, b'<' | b'>' | b'[' | b']') || (also_quotes && matches!(c, b'"' | b'\'')));
1021    let (mut j, mut subset) = (i + 9, 0usize);
1022    while j < end {
1023        let c = b[j];
1024        if c == b'"' || c == b'\'' {
1025            let q = b[j + 1..end].iter().position(|x| *x == c)?;
1026            if special(&b[j + 1..j + 1 + q], false) {
1027                return None;
1028            }
1029            j += q + 2;
1030            continue;
1031        }
1032        if subset > 0 && b[j..].starts_with(b"<!--") {
1033            let e = find(b, j + 4, b"-->").filter(|e| *e < end)?;
1034            let body = &b[j + 4..e];
1035            if special(body, false) {
1036                return None;
1037            }
1038            quoted_comment |= body.iter().any(|c| matches!(c, b'"' | b'\''));
1039            j = e + 3;
1040            continue;
1041        }
1042        if subset > 0 && b[j..].starts_with(b"<?") {
1043            let e = find(b, j + 2, b"?>").filter(|e| *e < end)?;
1044            if special(&b[j + 2..e], true) {
1045                return None;
1046            }
1047            j = e + 2;
1048            continue;
1049        }
1050        if c == b'[' {
1051            subset += 1;
1052        } else if c == b']' {
1053            subset = subset.saturating_sub(1);
1054        }
1055        j += 1;
1056    }
1057    Some(quoted_comment)
1058}
1059
1060fn ambiguous_markup(what: &str) -> Error {
1061    LimitError::new(
1062        LimitKind::XmlElements,
1063        format!("This file has {what}, which XML readers do not agree on, so its elements could not be counted safely. It was not processed."),
1064    )
1065    .into()
1066}
1067
1068/// Every way a reader in the workspace may read `bytes` as markup. A UTF-16 byte order mark leaves one reading.
1069/// Without one, `<\0` or `\0<` is UTF-16 for the readers that sniff it (EPUB, IDML) but UTF-8 with a NUL for the
1070/// ones that decode with [`crate::enc::decode_text`], so both are scanned. Bytes that are not UTF-8 may be read
1071/// in a double-byte code page whose second byte can be `[` or `]` (Shift_JIS, GBK/GB18030, Big5: a CDATA section
1072/// then ends at another `]]>` than in the bytes), so each of those readings is scanned too.
1073fn markup_views(bytes: &[u8]) -> Vec<std::borrow::Cow<'_, [u8]>> {
1074    use std::borrow::Cow;
1075    let decode = |e: &'static encoding_rs::Encoding| Cow::Owned(e.decode_without_bom_handling(bytes).0.into_owned().into_bytes());
1076    if (bytes.starts_with(&[0xFF, 0xFE]) && !bytes.starts_with(&[0xFF, 0xFE, 0, 0])) || bytes.starts_with(&[0xFE, 0xFF]) {
1077        return vec![markup_bytes(bytes)];
1078    }
1079    let mut v = vec![Cow::Borrowed(bytes)];
1080    if bytes.starts_with(&[b'<', 0]) || bytes.starts_with(&[0, b'<']) {
1081        v.push(markup_bytes(bytes));
1082    } else if std::str::from_utf8(bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes)).is_err() {
1083        for e in [encoding_rs::SHIFT_JIS, encoding_rs::GB18030, encoding_rs::BIG5] {
1084            v.push(decode(e));
1085        }
1086    }
1087    v
1088}
1089
1090fn check_xml_with(bytes: &[u8], l: &Limits, keep_dtd: bool, internal_ok: bool) -> Result<(), Error> {
1091    for view in markup_views(bytes) {
1092        scan_xml(&view, l, keep_dtd, internal_ok)?;
1093    }
1094    Ok(())
1095}
1096
1097fn scan_xml(b: &[u8], l: &Limits, keep_dtd: bool, internal_ok: bool) -> Result<(), Error> {
1098    let strict = !keep_dtd;
1099    let (mut i, mut depth, mut elements) = (0usize, 0usize, 0usize);
1100    while i < b.len() {
1101        let Some(p) = b[i..].iter().position(|c| *c == b'<') else { break };
1102        i += p;
1103        let rest = &b[i..];
1104        if rest.starts_with(b"<!--") {
1105            // `<!-->` and `<!--->` open a comment for XML, but a scanner that looks for `-->` from the `<` reads them
1106            // as a whole comment and goes on with what XML still calls comment text
1107            if strict && (rest[4..].starts_with(b">") || rest[4..].starts_with(b"->")) {
1108                return Err(ambiguous_markup("a comment that starts with '>' or '->'"));
1109            }
1110            match find(b, i + 4, b"-->") {
1111                Some(e) => i = e + 3,
1112                None => break,
1113            }
1114        } else if rest.starts_with(b"<![CDATA[") {
1115            match find(b, i + 9, b"]]>") {
1116                Some(e) => i = e + 3,
1117                None => break,
1118            }
1119        } else if rest.starts_with(b"<?") {
1120            // `<?>` is no processing instruction; a scanner that looks for `?>` from the `<` reads it as one
1121            if strict && rest[2..].starts_with(b">") {
1122                return Err(ambiguous_markup("a processing instruction with no name ('<?>')"));
1123            }
1124            match find(b, i + 2, b"?>") {
1125                Some(e) => i = e + 2,
1126                None => break,
1127            }
1128        } else if rest.len() >= 9 && rest[..9].eq_ignore_ascii_case(b"<!DOCTYPE") {
1129            let end = doctype_end(b, i);
1130            if !keep_dtd && contains_ci(&b[i..end], b"<!ENTITY") && !(internal_ok && only_plain_internal_entities(&b[i..end])) {
1131                return Err(unsafe_xml(
1132                    "This file declares XML entities (a DTD), which could expand without limit or read other files. It was not processed.",
1133                ));
1134            }
1135            // the readers must all end the DOCTYPE where this scan does, or elements (or an ENTITY) could hide in
1136            // what one of them calls the DOCTYPE. The keep-DTD readers (the XML filter family) check that themselves.
1137            if strict && end >= b.len() {
1138                return Err(unsafe_xml("This file has a DOCTYPE that is not closed. It was not processed."));
1139            }
1140            if strict {
1141                match doctype_is_unambiguous(b, i, end) {
1142                    None => {
1143                        return Err(unsafe_xml(
1144                            "This file has a DOCTYPE with a quoted '<', '>' or bracket, or a comment in its DTD with brackets, which XML readers do not agree on. It was not processed.",
1145                        ))
1146                    }
1147                    // a scanner that pairs the comment's quote with a later one would still be in the subset
1148                    // after the DOCTYPE: no `<!ENTITY` may follow anywhere, even in an attribute, comment or CDATA
1149                    Some(true) if contains_ci(&b[end..], b"<!ENTITY") => {
1150                        return Err(unsafe_xml(
1151                            "This file declares XML entities, which are not allowed. It was not processed.",
1152                        ))
1153                    }
1154                    Some(_) => {}
1155                }
1156            }
1157            i = end + 1;
1158        } else if rest.starts_with(b"<!") {
1159            // another declaration outside a DOCTYPE
1160            if rest.len() >= 8 && rest[..8].eq_ignore_ascii_case(b"<!ENTITY") {
1161                return Err(unsafe_xml("This file declares XML entities, which are not allowed. It was not processed."));
1162            }
1163            // `quick-xml` reads `<![` to `]]>` and `<!-` to `-->`; XML has no other declaration outside a DOCTYPE
1164            if strict {
1165                return Err(ambiguous_markup("a markup declaration outside the DOCTYPE"));
1166            }
1167            match find(b, i + 2, b">") {
1168                Some(e) => i = e + 1,
1169                None => break,
1170            }
1171        } else if rest.starts_with(b"</") {
1172            depth = depth.saturating_sub(1);
1173            match find(b, i + 2, b">") {
1174                Some(e) => i = e + 1,
1175                None => break,
1176            }
1177        } else {
1178            // a start tag: find '>' outside quotes
1179            let (mut j, mut sq) = (i + 1, 0u8);
1180            let mut end = None;
1181            while j < b.len() {
1182                let c = b[j];
1183                if sq != 0 {
1184                    if c == sq {
1185                        sq = 0;
1186                    }
1187                } else if c == b'"' || c == b'\'' {
1188                    sq = c;
1189                } else if c == b'>' {
1190                    end = Some(j);
1191                    break;
1192                }
1193                j += 1;
1194            }
1195            let Some(e) = end else { break };
1196            elements += 1;
1197            if elements > l.max_xml_elements {
1198                return Err(LimitError::new(
1199                    LimitKind::XmlElements,
1200                    format!("This file has more than {} XML elements in one part. It was not processed.", l.max_xml_elements),
1201                )
1202                .into());
1203            }
1204            if b[e - 1] != b'/' {
1205                depth += 1;
1206                if depth > l.max_xml_depth {
1207                    return Err(LimitError::new(
1208                        LimitKind::XmlDepth,
1209                        format!("This file nests XML elements more than {} deep. It was not processed.", l.max_xml_depth),
1210                    )
1211                    .into());
1212                }
1213            }
1214            i = e + 1;
1215        }
1216    }
1217    Ok(())
1218}
1219
1220/// Counts the start tags whose local name is `local` (`p` for a Word paragraph), comments, CDATA and processing
1221/// instructions skipped. Cheap enough to run over every part before a parser builds a tree of it.
1222pub fn count_elements(bytes: &[u8], local: &str) -> usize {
1223    let data = markup_bytes(bytes);
1224    let b: &[u8] = &data;
1225    let (mut i, mut n) = (0usize, 0usize);
1226    while let Some(p) = b.get(i..).and_then(|r| r.iter().position(|c| *c == b'<')) {
1227        i += p;
1228        let rest = &b[i + 1..];
1229        if rest.starts_with(b"!--") {
1230            i = find(b, i + 4, b"-->").map_or(b.len(), |e| e + 3);
1231        } else if rest.starts_with(b"![CDATA[") {
1232            i = find(b, i + 9, b"]]>").map_or(b.len(), |e| e + 3);
1233        } else if rest.starts_with(b"?") {
1234            i = find(b, i + 2, b"?>").map_or(b.len(), |e| e + 2);
1235        } else {
1236            let name_end = rest.iter().position(|c| c.is_ascii_whitespace() || *c == b'>' || *c == b'/').unwrap_or(rest.len());
1237            let name = &rest[..name_end];
1238            let lname = name.rsplit(|c| *c == b':').next().unwrap_or(name);
1239            if !name.starts_with(b"/") && !name.starts_with(b"!") && lname == local.as_bytes() {
1240                n += 1;
1241            }
1242            i += 1 + name_end;
1243        }
1244    }
1245    n
1246}
1247
1248/// [`count_elements`] fed in pieces, as a part inflates out of a zip (BILI-115): after the last piece and
1249/// [`ElementCounter::finish`], [`ElementCounter::count`] is exactly what `count_elements` gives for the whole part,
1250/// and after any piece it is at most that (a start tag is counted only once its name has ended, a region is skipped
1251/// only once its opening is known), so a running total over several parts can refuse a file before the rest of it
1252/// is read without refusing one the whole-part count accepts. Memory is a few bytes whatever the input.
1253///
1254/// A part that starts as UTF-16 (`count_elements` transcodes those) is not counted: [`ElementCounter::exact`] is
1255/// then false, `count` stays 0 (below the real count, so still safe for an early refusal) and the caller counts
1256/// the whole part with `count_elements` instead.
1257#[derive(Debug, Clone)]
1258pub struct ElementCounter {
1259    local: Vec<u8>,
1260    state: CountState,
1261    count: usize,
1262    /// The first byte, held until the second shows whether the part is UTF-16.
1263    first: Option<u8>,
1264    started: bool,
1265    utf16: bool,
1266}
1267
1268#[derive(Debug, Clone, Copy)]
1269enum CountState {
1270    /// Character data: looking for the next `<`.
1271    Text,
1272    /// Just after a `<`.
1273    Open,
1274    /// After `<!`: `n` bytes (from the `!`) that are still a prefix of `!--` (`comment`) or of `![CDATA[` (`cdata`).
1275    Bang { n: usize, comment: bool, cdata: bool },
1276    /// In a tag name: `pos` bytes since its last `:`, `ok` while those equal the start of the local name; `never`
1277    /// for a name that starts with `!` (not an element).
1278    Name { pos: usize, ok: bool, never: bool },
1279    /// In a comment, CDATA section or processing instruction: `k` bytes of its terminator matched.
1280    Skip { end: &'static [u8], k: usize },
1281}
1282
1283const CDATA_OPEN: &[u8] = b"![CDATA[";
1284
1285/// The bytes of `end` matched after one more byte `c`, when `k` were matched before (the longest prefix of `end`
1286/// that ends the text read so far; the terminators are at most three bytes long).
1287fn skip_step(end: &[u8], k: usize, c: u8) -> usize {
1288    let mut j = (k + 1).min(end.len());
1289    while j > 0 {
1290        if end[j - 1] == c && end[..j - 1] == end[k + 1 - j..k] {
1291            return j;
1292        }
1293        j -= 1;
1294    }
1295    0
1296}
1297
1298/// A byte that ends a tag name for `count_elements`.
1299fn ends_name(c: u8) -> bool {
1300    c.is_ascii_whitespace() || c == b'>' || c == b'/'
1301}
1302
1303impl ElementCounter {
1304    /// A counter of the start tags whose local name is `local`.
1305    pub fn new(local: &str) -> ElementCounter {
1306        ElementCounter { local: local.as_bytes().to_vec(), state: CountState::Text, count: 0, first: None, started: false, utf16: false }
1307    }
1308
1309    /// The elements counted so far.
1310    pub fn count(&self) -> usize {
1311        self.count
1312    }
1313
1314    /// False when the part is UTF-16, which this counter leaves to [`count_elements`].
1315    pub fn exact(&self) -> bool {
1316        !self.utf16
1317    }
1318
1319    /// The next bytes of the part.
1320    pub fn feed(&mut self, bytes: &[u8]) {
1321        if bytes.is_empty() || self.utf16 {
1322            return;
1323        }
1324        if !self.started {
1325            // `markup_bytes` decides on the first two bytes
1326            let held = self.first;
1327            let Some(f) = held.or(bytes.first().copied()) else { return };
1328            let second = if held.is_some() { bytes.first() } else { bytes.get(1) };
1329            let Some(&s) = second else {
1330                self.first = Some(f);
1331                return;
1332            };
1333            self.started = true;
1334            if matches!((f, s), (0xFF, 0xFE) | (b'<', 0) | (0xFE, 0xFF) | (0, b'<')) {
1335                self.utf16 = true;
1336                self.first = None;
1337                return;
1338            }
1339            if let Some(f) = self.first.take() {
1340                self.run(&[f]);
1341            }
1342        }
1343        self.run(bytes);
1344    }
1345
1346    /// The end of the part: a tag name still open at the end is counted as `count_elements` counts it.
1347    pub fn finish(&mut self) {
1348        if let Some(f) = self.first.take() {
1349            self.started = true;
1350            self.run(&[f]);
1351        }
1352        if let CountState::Name { pos, ok, never } = self.state {
1353            if !never && ok && pos == self.local.len() {
1354                self.count += 1;
1355            }
1356        }
1357        self.state = CountState::Text;
1358    }
1359
1360    fn run(&mut self, b: &[u8]) {
1361        let mut i = 0;
1362        while i < b.len() {
1363            match self.state {
1364                CountState::Text => match b[i..].iter().position(|c| *c == b'<') {
1365                    Some(p) => {
1366                        i += p + 1;
1367                        self.state = CountState::Open;
1368                    }
1369                    None => return,
1370                },
1371                CountState::Open => match b[i] {
1372                    b'!' => {
1373                        self.state = CountState::Bang { n: 1, comment: true, cdata: true };
1374                        i += 1;
1375                    }
1376                    b'?' => {
1377                        self.state = CountState::Skip { end: b"?>", k: 0 };
1378                        i += 1;
1379                    }
1380                    // the byte is the name's first (or ends an empty name): the name state reads it
1381                    _ => self.state = CountState::Name { pos: 0, ok: true, never: false },
1382                },
1383                CountState::Bang { n, comment, cdata } => {
1384                    let c = b[i];
1385                    let n = n + 1;
1386                    // the whole prefix must still match: `<![-` is no comment
1387                    let comment = comment && n <= 3 && b"!--"[n - 1] == c;
1388                    let cdata = cdata && n <= CDATA_OPEN.len() && CDATA_OPEN[n - 1] == c;
1389                    i += 1;
1390                    self.state = if comment && n == 3 {
1391                        CountState::Skip { end: b"-->", k: 0 }
1392                    } else if cdata && n == CDATA_OPEN.len() {
1393                        CountState::Skip { end: b"]]>", k: 0 }
1394                    } else if comment || cdata {
1395                        CountState::Bang { n, comment, cdata }
1396                    } else if ends_name(c) {
1397                        // a name such as `!x` ended here: never an element (the byte is not a `<`, so the text
1398                        // scan loses nothing by not seeing it)
1399                        CountState::Text
1400                    } else {
1401                        CountState::Name { pos: 0, ok: false, never: true }
1402                    };
1403                }
1404                CountState::Name { mut pos, mut ok, never } => {
1405                    while i < b.len() && !ends_name(b[i]) {
1406                        let c = b[i];
1407                        if c == b':' {
1408                            pos = 0;
1409                            ok = true;
1410                        } else {
1411                            ok = ok && self.local.get(pos) == Some(&c);
1412                            pos += 1;
1413                        }
1414                        i += 1;
1415                    }
1416                    if i == b.len() {
1417                        self.state = CountState::Name { pos, ok, never };
1418                        return;
1419                    }
1420                    // the byte that ends the name is left to the text scan, where `count_elements` resumes
1421                    if !never && ok && pos == self.local.len() {
1422                        self.count += 1;
1423                    }
1424                    self.state = CountState::Text;
1425                }
1426                CountState::Skip { end, mut k } => {
1427                    while i < b.len() && k < end.len() {
1428                        k = skip_step(end, k, b[i]);
1429                        i += 1;
1430                    }
1431                    self.state = if k == end.len() { CountState::Text } else { CountState::Skip { end, k } };
1432                }
1433            }
1434        }
1435    }
1436}
1437
1438/// The guard for markup that is not strict XML (HTML): no entity declarations, and the element count cap. Depth
1439/// of HTML is the parser's own business (unclosed tags make it unknowable from the text).
1440pub fn check_markup(text: &str, l: &Limits) -> Result<(), Error> {
1441    let b = text.as_bytes();
1442    if contains_ci(b, b"<!ENTITY") {
1443        return Err(unsafe_xml("This file declares markup entities, which are not allowed. It was not processed."));
1444    }
1445    let elements = b.windows(2).filter(|w| w[0] == b'<' && (w[1].is_ascii_alphabetic() || w[1] == b'/')).count();
1446    if elements > l.max_xml_elements {
1447        return Err(LimitError::new(
1448            LimitKind::XmlElements,
1449            format!("This file has more than {} markup elements. It was not processed.", l.max_xml_elements),
1450        )
1451        .into());
1452    }
1453    Ok(())
1454}
1455
1456#[cfg(test)]
1457mod tests {
1458    use super::*;
1459
1460    fn kind(r: Result<(), Error>) -> Option<LimitKind> {
1461        match r {
1462            Err(Error::Limit(e)) => Some(e.kind),
1463            _ => None,
1464        }
1465    }
1466
1467    #[test]
1468    fn defaults_are_locos_numbers() {
1469        let l = Limits::default();
1470        assert_eq!((l.max_input_bytes, l.max_units, l.max_unit_chars), (100 << 20, 50_000, 100_000));
1471        assert_eq!((l.max_zip_entries, l.max_zip_bytes, l.max_zip_ratio), (10_000, 256 << 20, 200));
1472    }
1473
1474    #[test]
1475    fn pre_parse_budget_scales_with_the_unit_limit() {
1476        let l = Limits { max_units: 10, ..Limits::default() };
1477        assert!(check_budget(200, 20, "This JSON file has far more values", &l).is_ok());
1478        let e = check_budget(201, 20, "This JSON file has far more values", &l).unwrap_err();
1479        assert!(e.to_string().contains("far more values than a file of 10 segments. Split"), "{e}");
1480        assert_eq!(kind(Err(e)), Some(LimitKind::Units));
1481        assert!(check_budget(usize::MAX, usize::MAX, "x", &Limits { max_units: usize::MAX, ..Limits::default() }).is_ok());
1482    }
1483
1484    #[test]
1485    fn input_size_is_checked_against_the_callers_limit() {
1486        let l = Limits { max_input_bytes: 10, ..Limits::default() };
1487        assert!(check_input(&[0; 10], &l).is_ok());
1488        assert_eq!(kind(check_input(&[0; 11], &l)), Some(LimitKind::InputBytes));
1489    }
1490
1491    #[test]
1492    fn xml_entity_bomb_and_xxe_are_refused() {
1493        let bomb = br#"<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;">]><lolz>&lol2;</lolz>"#;
1494        assert_eq!(kind(check_xml(bomb, &Limits::default())), Some(LimitKind::XmlEntities));
1495        let xxe = br#"<!DOCTYPE r [ <!ENTITY x SYSTEM "file:///etc/passwd"> ]><r>&x;</r>"#;
1496        assert_eq!(kind(check_xml(xxe, &Limits::default())), Some(LimitKind::XmlEntities));
1497        let param = br#"<!doctype r [ <!entity % p SYSTEM "http://example.invalid/x.dtd"> %p; ]><r/>"#;
1498        assert_eq!(kind(check_xml(param, &Limits::default())), Some(LimitKind::XmlEntities));
1499    }
1500
1501    #[test]
1502    fn internal_entities_mode_allows_only_plain_literals() {
1503        let l = Limits::default();
1504        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;"/>"#;
1505        assert!(check_xml_internal_entities(ok, &l).is_ok());
1506        assert_eq!(kind(check_xml(ok, &l)), Some(LimitKind::XmlEntities), "the strict check still refuses it");
1507        for bad in [
1508            r#"<!DOCTYPE r [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;">]><r/>"#,
1509            r#"<!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/hosts">]><r/>"#,
1510            r#"<!DOCTYPE r [<!ENTITY x PUBLIC "a" "b">]><r/>"#,
1511            r#"<!DOCTYPE r [<!ENTITY % p "x">]><r/>"#,
1512            r#"<!DOCTYPE r [<!ENTITY x>]><r/>"#,
1513            r#"<!DOCTYPE r [<!ENTITY x "unclosed>]><r/>"#,
1514            r#"<!ENTITY x "y"><r/>"#,
1515        ] {
1516            assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
1517        }
1518        let long = format!("<!DOCTYPE r [<!ENTITY x \"{}\">]><r/>", "a".repeat(1025));
1519        assert_eq!(kind(check_xml_internal_entities(long.as_bytes(), &l)), Some(LimitKind::XmlEntities));
1520        // a literal never carries markup: a quoted '<' or '>' in the DOCTYPE is refused
1521        for bad in [r#"<!DOCTYPE r [<!ENTITY x "<g/>">]><r/>"#, r#"<!DOCTYPE r [<!ENTITY x "a>b">]><r/>"#] {
1522            assert!(check_xml_internal_entities(bad.as_bytes(), &l).is_err(), "{bad}");
1523        }
1524        // declared entities do not lift the depth and element limits
1525        let tight = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
1526        let deep = r#"<!DOCTYPE r [<!ENTITY x "y">]><r><a><b>&x;</b></a></r>"#;
1527        assert!(check_xml_internal_entities(deep.as_bytes(), &tight).is_err());
1528        let many: String = (0..65).map(|k| format!("<!ENTITY e{k} \"v\">")).collect();
1529        assert!(check_xml_internal_entities(format!("<!DOCTYPE r [{many}]><r/>").as_bytes(), &l).is_err());
1530    }
1531
1532    #[test]
1533    fn keeping_dtd_allows_declarations_but_not_more_elements_or_depth() {
1534        let l = Limits { max_xml_depth: 8, max_xml_elements: 20, ..Limits::default() };
1535        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>"#;
1536        assert!(check_xml_keeping_dtd(bomb, &l).is_ok());
1537        assert_eq!(kind(check_xml(bomb, &l)), Some(LimitKind::XmlEntities), "the strict check still refuses it");
1538        // a quote, a '>' or a ']' in a comment or a PI of the subset does not end the DOCTYPE early or late
1539        for dt in [r#"<!DOCTYPE r [ <!-- ' ]> --> <!ENTITY a "x"> ]>"#, r#"<!DOCTYPE r [ <?pi ]> " ?> <!ENTITY a "]>"> ]>"#] {
1540            let deep = format!("{dt}{}{}", "<a>".repeat(9), "</a>".repeat(9));
1541            assert_eq!(kind(check_xml_keeping_dtd(deep.as_bytes(), &l)), Some(LimitKind::XmlDepth), "{dt}");
1542            let wide = format!("{dt}<r>{}</r>", "<b/>".repeat(30));
1543            assert_eq!(kind(check_xml_keeping_dtd(wide.as_bytes(), &l)), Some(LimitKind::XmlElements), "{dt}");
1544            assert_eq!(kind(check_xml(deep.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{dt}");
1545        }
1546        // an ENTITY declaration outside a DOCTYPE is refused in both modes
1547        assert_eq!(kind(check_xml_keeping_dtd(br#"<!ENTITY a "x"><r/>"#, &l)), Some(LimitKind::XmlEntities));
1548    }
1549
1550    #[test]
1551    fn a_doctype_the_readers_end_elsewhere_is_refused() {
1552        let l = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
1553        let body = "<r><a><b><c/></b></a></r>";
1554        assert_eq!(kind(check_xml(body.as_bytes(), &l)), Some(LimitKind::XmlDepth));
1555        for pre in [
1556            "<!doctype r SYSTEM '>",
1557            "<!DOCTYPE r SYSTEM \">",
1558            "<!DoCtYpE r PUBLIC 'a>b' 'c'>",
1559            "<!DOCTYPE r [>",
1560            "<!DOCTYPE r [<!-- > -->",
1561            "<!DOCTYPE r [<!-- ] --> <x><y>",
1562            "<!DOCTYPE r [<!-- ' --> <?p ' ?> ]>",
1563            "<!DOCTYPE r SYSTEM 'a[b'>",
1564            "<!DOCTYPE r < >",
1565            "<!DOCTYPE r [ > ]>",
1566            "<!DOCTYPE r",
1567        ] {
1568            let k = kind(check_xml(format!("{pre}{body}").as_bytes(), &l));
1569            assert!(matches!(k, Some(LimitKind::XmlEntities | LimitKind::XmlDepth)), "{pre}: {k:?}");
1570            assert!(kind(check_xml(format!("{pre}{body}").as_bytes(), &Limits::default())).is_some(), "{pre} refused even with room");
1571        }
1572        // what real files carry still passes
1573        for ok in [
1574            "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
1575            "<!doctype html>",
1576            "<!DOCTYPE r []>",
1577            "<!DOCTYPE mb [ <!ELEMENT mb (msg)*> <!ATTLIST msg id CDATA #IMPLIED d CDATA 'x'> <!-- a note --> <?pi data?> ]>",
1578            "<!DOCTYPE r [ <!---->]>",
1579        ] {
1580            assert!(check_xml(format!("{ok}<r/>").as_bytes(), &Limits::default()).is_ok(), "{ok}");
1581        }
1582        // the keep-DTD check leaves this to its reader (the XML filter family refuses a mismatch itself)
1583        assert!(check_xml_keeping_dtd(b"<!DOCTYPE r [<!-- > --> ]><r/>", &Limits::default()).is_ok());
1584    }
1585
1586    #[test]
1587    fn a_quote_in_a_comment_of_the_subset_passes_but_hides_no_entity() {
1588        // BILI-60: every reader skips a comment of the subset whole (quick-xml, the guard, the XML family), so an
1589        // apostrophe in it changes no reading
1590        let l = Limits::default();
1591        for ok in [
1592            "<!DOCTYPE r [ <!-- don't edit this file --> <!ELEMENT r ANY> ]><r/>",
1593            "<!DOCTYPE r [ <!-- the \"r\" element --> <!ATTLIST r id CDATA #IMPLIED> <!-- it's 'r' --> ]><r id='a'>x</r>",
1594            "<!DOCTYPE r [<!--'-->]><r/>",
1595        ] {
1596            assert!(check_xml(ok.as_bytes(), &l).is_ok(), "{ok}");
1597            assert!(check_xml_internal_entities(ok.as_bytes(), &l).is_ok(), "{ok}");
1598        }
1599        let svg = "<!DOCTYPE svg [ <!-- Adobe's namespaces --> <!ENTITY ns_svg \"http://www.w3.org/2000/svg\"> ]><svg/>";
1600        assert!(check_xml_internal_entities(svg.as_bytes(), &l).is_ok());
1601        assert_eq!(kind(check_xml(svg.as_bytes(), &l)), Some(LimitKind::XmlEntities));
1602        // an entity declaration next to, inside or after such a comment is still refused
1603        for bad in [
1604            "<!DOCTYPE r [ <!-- don't --> <!ENTITY a \"x\"> ]><r>&a;</r>",
1605            "<!DOCTYPE r [ <!ENTITY a \"x\"> <!-- don't --> ]><r>&a;</r>",
1606            "<!DOCTYPE r [ <!-- ' <!ENTITY a SYSTEM \"file:///etc/passwd\"> ' --> ]><r/>",
1607            "<!DOCTYPE r [ <!-- ' --><!ENTITY % p SYSTEM \"http://example.invalid/x.dtd\"> %p; ]><r/>",
1608            "<!DOCTYPE r [ <!-- ' --> ]><!ENTITY a \"x\"><r/>",
1609        ] {
1610            assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
1611        }
1612        for bad in [
1613            "<!DOCTYPE svg [ <!-- ' --> <!ENTITY a \"&b;&b;\"> ]><svg/>",
1614            "<!DOCTYPE svg [ <!-- ' <!ENTITY a SYSTEM \"file:///etc/passwd\"> --> ]><svg/>",
1615            "<!DOCTYPE svg [ <!-- ' --> <!ENTITY % p \"x\"> ]><svg/>",
1616        ] {
1617            assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
1618        }
1619        // a reader that pairs quotes but does not skip comments would read the subset on to the next quote: an
1620        // ENTITY anywhere after such a DOCTYPE (an attribute, a comment, CDATA) could be a declaration to it
1621        for bad in [
1622            "<!DOCTYPE r [ <!-- ' --> ]><r a='<!ENTITY b \"x\">'/>",
1623            "<!DOCTYPE r [ <!-- \" --> ]><r><!-- <!entity b 'x'> --></r>",
1624            "<!DOCTYPE r [ <!-- ' --> ]><r><![CDATA[<!ENTITY b 'x'>]]></r>",
1625        ] {
1626            assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
1627            assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
1628        }
1629        // a bracket or an angle bracket in the comment, or a quote in a processing instruction, is still refused
1630        for bad in [
1631            "<!DOCTYPE r [ <!-- ' ] --> ]><r/>",
1632            "<!DOCTYPE r [ <!-- \" > --> ]><r/>",
1633            "<!DOCTYPE r [ <!-- ' < --> ]><r/>",
1634            "<!DOCTYPE r [ <!-- ' [ --> ]><r/>",
1635            "<!DOCTYPE r [ <!-- ok --> <?pi don't ?> ]><r/>",
1636            "<!DOCTYPE r [ <!-- ' --> ",
1637        ] {
1638            assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
1639        }
1640        // and the elements after it are counted as before
1641        let tight = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
1642        let deep = "<!DOCTYPE r [ <!-- don't --> ]><r><a><b><c/></b></a></r>";
1643        assert_eq!(kind(check_xml(deep.as_bytes(), &tight)), Some(LimitKind::XmlDepth));
1644        let wide = "<!DOCTYPE r [ <!-- don't --> ]><r><b/><b/><b/><b/></r>";
1645        assert_eq!(kind(check_xml(wide.as_bytes(), &tight)), Some(LimitKind::XmlElements));
1646    }
1647
1648    #[test]
1649    fn every_reading_of_the_bytes_is_scanned() {
1650        let l = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
1651        let body = "<a><b><c/></b></a>";
1652        // 0x81 0x5D is one Shift_JIS / GBK character: the bytes end the CDATA at `]]>`, the decoded text later
1653        let sjis = format!("<?xml version=\"1.0\" encoding=\"Shift_JIS\"?><r><![CDATA[\u{1}]]><!--]]>{body}--></r>");
1654        let mut bytes = sjis.into_bytes();
1655        let p = bytes.iter().position(|c| *c == 1).unwrap();
1656        bytes[p] = 0x81;
1657        assert!(check_xml(&bytes, &l).is_err());
1658        // a valid double-byte file still passes
1659        let ok = b"<?xml version=\"1.0\" encoding=\"Shift_JIS\"?><r><![CDATA[\x93\xfa]]>\x96\x7b</r>";
1660        assert!(check_xml(ok, &Limits::default()).is_ok());
1661        // a NUL first: UTF-16BE for one reader, UTF-8 for another
1662        let nul = format!("\0<r>{body}</r>");
1663        assert!(check_xml(nul.as_bytes(), &l).is_err());
1664        let mut le = Vec::new();
1665        for u in format!("<r>{body}</r>").encode_utf16() {
1666            le.extend(u.to_le_bytes());
1667        }
1668        assert!(check_xml(&le, &l).is_err());
1669        assert!(check_xml(&le, &Limits::default()).is_ok());
1670    }
1671
1672    #[test]
1673    fn a_comment_or_pi_a_scanner_ends_early_is_refused() {
1674        let l = Limits::default();
1675        for bad in ["<!--><r><a/></r><!-- -->", "<!---><r/><!-- -->", "<?><r/><?x?>", "<r><![IGNORE[ <a/> ]]></r>", "<!ELEMENT r ANY><r/>"] {
1676            assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlElements), "{bad}");
1677        }
1678        for ok in ["<r><!----></r>", "<r><!-- - --></r>", "<r><??></r>", "<r><?pi x?></r>"] {
1679            assert!(check_xml(ok.as_bytes(), &l).is_ok(), "{ok}");
1680        }
1681    }
1682
1683    #[test]
1684    fn a_plain_doctype_and_predefined_entities_pass() {
1685        let ok = br#"<?xml version="1.0"?><!DOCTYPE xliff PUBLIC "-//OASIS//DTD XLIFF 1.2//EN" "xliff.dtd"><a>x &amp; y &#233;</a>"#;
1686        assert!(check_xml(ok, &Limits::default()).is_ok());
1687        // an ENTITY inside a comment or CDATA is only text
1688        assert!(check_xml(b"<a><!-- <!ENTITY x 'y'> --><![CDATA[<!ENTITY z 'w'>]]></a>", &Limits::default()).is_ok());
1689    }
1690
1691    #[test]
1692    fn xml_depth_and_element_count_are_bounded() {
1693        let l = Limits { max_xml_depth: 8, max_xml_elements: 20, ..Limits::default() };
1694        let deep = format!("{}{}", "<a>".repeat(9), "</a>".repeat(9));
1695        assert_eq!(kind(check_xml(deep.as_bytes(), &l)), Some(LimitKind::XmlDepth));
1696        let ok = format!("{}{}", "<a>".repeat(8), "</a>".repeat(8));
1697        assert!(check_xml(ok.as_bytes(), &l).is_ok());
1698        let wide = format!("<r>{}</r>", "<b/>".repeat(30));
1699        assert_eq!(kind(check_xml(wide.as_bytes(), &l)), Some(LimitKind::XmlElements));
1700    }
1701
1702    #[test]
1703    fn utf16_xml_is_scanned_too() {
1704        let src = "<!DOCTYPE r [<!ENTITY a 'b'>]><r/>";
1705        let mut v = vec![0xFF, 0xFE];
1706        v.extend(src.encode_utf16().flat_map(|u| u.to_le_bytes()));
1707        assert_eq!(kind(check_xml(&v, &Limits::default())), Some(LimitKind::XmlEntities));
1708    }
1709
1710    #[test]
1711    fn counts_elements_by_local_name() {
1712        let x = b"<w:body><w:p/><w:p w:x='1'>a</w:p><!-- <w:p/> --><w:pPr/><p>x</p></w:body>";
1713        assert_eq!(count_elements(x, "p"), 3);
1714    }
1715
1716    /// BILI-115: the streaming counter gives `count_elements`'s number for the whole part whatever the pieces it is
1717    /// fed in, and never more than that number after any piece.
1718    #[test]
1719    fn element_counter_agrees_with_count_elements() {
1720        let mut seed: u64 = 0x5eed_0115;
1721        let mut next = move |n: usize| {
1722            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1723            ((seed >> 33) as usize) % n
1724        };
1725        let pieces: &[&[u8]] = &[
1726            b"<", b">", b"/", b"!", b"-", b"--", b"[", b"]", b"]]", b"?", b":", b" ", b"\n", b"p", b"w:p", b"<w:p>", b"<w:p/>",
1727            b"<w:pPr>", b"</w:p>", b"<!--", b"-->", b"<![CDATA[", b"]]>", b"<?", b"?>", b"<!", b"<!-", b"<![CD", b"<![-", b"<!-[", b"a:p", b"pp",
1728            b"<p", b":p", b"x", b"<!DOCTYPE x>", b"\"", b"'",
1729        ];
1730        for round in 0..3000 {
1731            let mut doc = Vec::new();
1732            for _ in 0..next(60) {
1733                doc.extend_from_slice(pieces[next(pieces.len())]);
1734            }
1735            for local in ["p", "pPr"] {
1736                let want = count_elements(&doc, local);
1737                // whole, one byte at a time, and random pieces
1738                for mode in 0..3 {
1739                    let mut c = ElementCounter::new(local);
1740                    let mut at = 0;
1741                    while at < doc.len() {
1742                        let len = match mode {
1743                            0 => doc.len(),
1744                            1 => 1,
1745                            _ => 1 + next(7),
1746                        };
1747                        let end = (at + len).min(doc.len());
1748                        c.feed(&doc[at..end]);
1749                        at = end;
1750                        assert!(c.count() <= want, "round {round}: {} over {want} after a piece of {:?}", c.count(), String::from_utf8_lossy(&doc));
1751                    }
1752                    c.finish();
1753                    assert!(c.exact());
1754                    assert_eq!(c.count(), want, "round {round} mode {mode}: {:?}", String::from_utf8_lossy(&doc));
1755                }
1756            }
1757        }
1758        let x = b"<w:body><w:p/><w:p w:x='1'>a</w:p><!-- <w:p/> --><w:pPr/><p>x</p><![CDATA[<w:p>]]><?pi <w:p>?></w:body>";
1759        let mut c = ElementCounter::new("p");
1760        c.feed(x);
1761        c.finish();
1762        assert_eq!((c.count(), count_elements(x, "p")), (3, 3));
1763        // a UTF-16 part is left to `count_elements`
1764        let mut v = vec![0xFF, 0xFE];
1765        v.extend("<w:p/>".encode_utf16().flat_map(|u| u.to_le_bytes()));
1766        let mut c = ElementCounter::new("p");
1767        c.feed(&v[..1]);
1768        c.feed(&v[1..]);
1769        c.finish();
1770        assert!(!c.exact());
1771        assert_eq!(c.count(), 0);
1772        assert_eq!(count_elements(&v, "p"), 1);
1773    }
1774
1775    #[test]
1776    fn own_caps_follow_a_raised_limit_only() {
1777        let h = Limits::new();
1778        // hosted and lowered: the smaller of the crate's own and the caller's, as before
1779        assert_eq!(own_cap(500_000, h.max_units, h.max_units), 50_000);
1780        assert_eq!(own_cap(20_000, h.max_units, h.max_units), 20_000);
1781        assert_eq!(own_cap(500_000, h.max_units, 10), 10);
1782        assert_eq!(own_cap_bytes(64 << 20, h.max_input_bytes, h.max_input_bytes), 64 << 20);
1783        assert_eq!(own_cap_bytes(256 << 20, h.max_input_bytes, h.max_input_bytes), 100 << 20);
1784        // raised: the caller's
1785        let l = Limits::large();
1786        assert_eq!(own_cap(500_000, h.max_units, l.max_units), l.max_units);
1787        assert_eq!(own_cap_bytes(64 << 20, h.max_input_bytes, l.max_input_bytes) as u64, l.max_input_bytes);
1788    }
1789
1790    #[test]
1791    fn comment_base_refuses_a_body_that_reaches_it() {
1792        // BILI-126: body numbers 0..=999_999 leave the comment numbers free; one more and the first comment collides
1793        assert!(check_comment_base(0).is_ok());
1794        assert!(check_comment_base(COMMENT_BASE).is_ok());
1795        match check_comment_base(COMMENT_BASE + 1) {
1796            Err(Error::Limit(e)) => {
1797                assert_eq!(e.kind, LimitKind::Units);
1798                assert!(e.msg.contains("more than Bilingua can number apart"), "{e}");
1799                assert!(!e.msg.contains('\u{2014}'), "no em dash: {e}");
1800            }
1801            other => panic!("not a limit error: {other:?}"),
1802        }
1803        // the merge side: the same line, and one number on two units, each with the merge's own message
1804        assert!(check_comment_base_merge(COMMENT_BASE).is_ok());
1805        assert!(check_distinct_numbers([0, 1, 1_000_000]).is_ok());
1806        for r in [check_comment_base_merge(COMMENT_BASE + 1), check_distinct_numbers([5, 1_000_000, 5])] {
1807            match r {
1808                Err(Error::Limit(e)) => {
1809                    assert_eq!(e.kind, LimitKind::Units);
1810                    assert!(e.msg.contains("comments and body text share numbers"), "{e}");
1811                    assert!(!e.msg.contains('\u{2014}'), "no em dash: {e}");
1812                }
1813                other => panic!("not a limit error: {other:?}"),
1814            }
1815        }
1816    }
1817
1818    #[test]
1819    fn line_budget() {
1820        let l = Limits { max_lines: 5, ..Limits::default() };
1821        assert!(check_lines("a\nb\nc\n", &l).is_ok());
1822        assert_eq!(kind(check_lines(&"\n".repeat(6), &l)), Some(LimitKind::Lines));
1823    }
1824}