1use crate::{Document, Error};
15use serde::{Deserialize, Serialize};
16use std::fmt;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21#[non_exhaustive]
22pub enum LimitKind {
23 InputBytes,
25 Lines,
27 Units,
29 UnitChars,
31 XmlDepth,
33 Depth,
36 XmlElements,
38 XmlEntities,
40 Paragraphs,
42 Spreadsheet,
44 ZipEntries,
46 ZipBytes,
48 ZipRatio,
50 ZipMalformed,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub struct LimitError {
58 pub kind: LimitKind,
60 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(default, deny_unknown_fields)]
88#[non_exhaustive]
89pub struct Limits {
90 pub max_input_bytes: u64,
92 pub max_units: usize,
94 pub max_unit_chars: usize,
96 pub max_lines: usize,
98 pub max_xml_depth: usize,
100 pub max_xml_elements: usize,
102 pub max_zip_entries: usize,
104 pub max_zip_bytes: u64,
106 pub max_zip_entry_bytes: u64,
109 pub max_zip_ratio: u64,
111 pub zip_ratio_floor_bytes: u64,
113 pub max_paragraphs: usize,
115 pub xlsx_max_cells: usize,
117 pub xlsx_max_rows: u32,
119 pub xlsx_max_cell_chars: usize,
121 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 pub fn new() -> Limits {
152 Limits::default()
153 }
154 pub fn with_max_input_bytes(mut self, v: u64) -> Limits {
156 self.max_input_bytes = v;
157 self
158 }
159 pub fn with_max_units(mut self, v: usize) -> Limits {
161 self.max_units = v;
162 self
163 }
164 pub fn with_max_unit_chars(mut self, v: usize) -> Limits {
166 self.max_unit_chars = v;
167 self
168 }
169 pub fn with_max_lines(mut self, v: usize) -> Limits {
171 self.max_lines = v;
172 self
173 }
174 pub fn with_max_xml_depth(mut self, v: usize) -> Limits {
176 self.max_xml_depth = v;
177 self
178 }
179 pub fn with_max_xml_elements(mut self, v: usize) -> Limits {
181 self.max_xml_elements = v;
182 self
183 }
184 pub fn with_max_zip_entries(mut self, v: usize) -> Limits {
186 self.max_zip_entries = v;
187 self
188 }
189 pub fn with_max_zip_bytes(mut self, v: u64) -> Limits {
191 self.max_zip_bytes = v;
192 self
193 }
194 pub fn with_max_zip_entry_bytes(mut self, v: u64) -> Limits {
196 self.max_zip_entry_bytes = v;
197 self
198 }
199 pub fn with_max_zip_ratio(mut self, v: u64) -> Limits {
201 self.max_zip_ratio = v;
202 self
203 }
204 pub fn with_zip_ratio_floor_bytes(mut self, v: u64) -> Limits {
206 self.zip_ratio_floor_bytes = v;
207 self
208 }
209 pub fn with_max_paragraphs(mut self, v: usize) -> Limits {
211 self.max_paragraphs = v;
212 self
213 }
214 pub fn with_xlsx_max_cells(mut self, v: usize) -> Limits {
216 self.xlsx_max_cells = v;
217 self
218 }
219 pub fn with_xlsx_max_rows(mut self, v: u32) -> Limits {
221 self.xlsx_max_rows = v;
222 self
223 }
224 pub fn with_xlsx_max_cell_chars(mut self, v: usize) -> Limits {
226 self.xlsx_max_cell_chars = v;
227 self
228 }
229 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
244pub 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
260pub 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
274pub 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
287pub 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
302pub 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
317pub 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
336pub 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
358fn 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
373pub fn check_xml(bytes: &[u8], l: &Limits) -> Result<(), Error> {
388 check_xml_with(bytes, l, false, false)
389}
390
391pub fn check_xml_internal_entities(bytes: &[u8], l: &Limits) -> Result<(), Error> {
397 check_xml_with(bytes, l, false, true)
398}
399
400fn 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 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
443pub fn check_xml_keeping_dtd(bytes: &[u8], l: &Limits) -> Result<(), Error> {
448 check_xml_with(bytes, l, true, false)
449}
450
451fn 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
485fn 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
500fn 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
556fn 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 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 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 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 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 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 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
696pub 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
724pub 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 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 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 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 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 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 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 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 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 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 & y é</a>"#;
910 assert!(check_xml(ok, &Limits::default()).is_ok());
911 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}