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 Context,
33 XmlDepth,
35 Depth,
38 XmlElements,
40 XmlEntities,
42 Paragraphs,
44 Spreadsheet,
46 ZipEntries,
48 ZipBytes,
50 ZipRatio,
52 ZipMalformed,
54 OutputBytes,
56 Skeleton,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct LimitError {
65 pub kind: LimitKind,
67 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(default, deny_unknown_fields)]
95#[non_exhaustive]
96pub struct Limits {
97 pub max_input_bytes: u64,
99 pub max_units: usize,
101 pub max_unit_chars: usize,
103 pub max_lines: usize,
105 pub max_xml_depth: usize,
107 pub max_xml_elements: usize,
109 pub max_zip_entries: usize,
111 pub max_zip_bytes: u64,
113 pub max_zip_entry_bytes: u64,
116 pub max_zip_ratio: u64,
118 pub zip_ratio_floor_bytes: u64,
120 pub max_paragraphs: usize,
122 pub xlsx_max_cells: usize,
124 pub xlsx_max_rows: u32,
126 pub xlsx_max_cell_chars: usize,
128 pub xlsx_max_total_text_chars: usize,
131 pub max_context_bytes: u64,
135 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
165const 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 pub fn new() -> Limits {
175 Limits::default()
176 }
177
178 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 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 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 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 pub fn with_max_input_bytes(mut self, v: u64) -> Limits {
272 self.max_input_bytes = v;
273 self
274 }
275 pub fn with_max_units(mut self, v: usize) -> Limits {
277 self.max_units = v;
278 self
279 }
280 pub fn with_max_unit_chars(mut self, v: usize) -> Limits {
282 self.max_unit_chars = v;
283 self
284 }
285 pub fn with_max_lines(mut self, v: usize) -> Limits {
287 self.max_lines = v;
288 self
289 }
290 pub fn with_max_xml_depth(mut self, v: usize) -> Limits {
292 self.max_xml_depth = v;
293 self
294 }
295 pub fn with_max_xml_elements(mut self, v: usize) -> Limits {
297 self.max_xml_elements = v;
298 self
299 }
300 pub fn with_max_zip_entries(mut self, v: usize) -> Limits {
302 self.max_zip_entries = v;
303 self
304 }
305 pub fn with_max_zip_bytes(mut self, v: u64) -> Limits {
307 self.max_zip_bytes = v;
308 self
309 }
310 pub fn with_max_zip_entry_bytes(mut self, v: u64) -> Limits {
312 self.max_zip_entry_bytes = v;
313 self
314 }
315 pub fn with_max_zip_ratio(mut self, v: u64) -> Limits {
317 self.max_zip_ratio = v;
318 self
319 }
320 pub fn with_zip_ratio_floor_bytes(mut self, v: u64) -> Limits {
322 self.zip_ratio_floor_bytes = v;
323 self
324 }
325 pub fn with_max_paragraphs(mut self, v: usize) -> Limits {
327 self.max_paragraphs = v;
328 self
329 }
330 pub fn with_xlsx_max_cells(mut self, v: usize) -> Limits {
332 self.xlsx_max_cells = v;
333 self
334 }
335 pub fn with_xlsx_max_rows(mut self, v: u32) -> Limits {
337 self.xlsx_max_rows = v;
338 self
339 }
340 pub fn with_xlsx_max_cell_chars(mut self, v: usize) -> Limits {
342 self.xlsx_max_cell_chars = v;
343 self
344 }
345 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 pub fn with_max_context_bytes(mut self, v: u64) -> Limits {
352 self.max_context_bytes = v;
353 self
354 }
355 pub fn with_max_output_bytes(mut self, v: u64) -> Limits {
357 self.max_output_bytes = v;
358 self
359 }
360}
361
362pub 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
375pub 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
393pub 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
409pub 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
423pub 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
436pub const COMMENT_BASE: usize = 1_000_000;
439
440pub 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
458fn 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
468pub 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
477pub 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
487pub 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
502pub 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
517pub 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
532pub 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#[derive(Debug, Clone, Copy, Default)]
548pub struct ContextBudget {
549 used: u64,
550}
551
552impl ContextBudget {
553 pub fn new() -> ContextBudget {
555 ContextBudget::default()
556 }
557 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 pub fn used(&self) -> u64 {
564 self.used
565 }
566}
567
568pub 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
591pub const MERGE_REFS_PER_UNIT: usize = 4;
595
596pub const MERGE_TARGET_CHARS_FACTOR: usize = 4;
599
600pub 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 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
664fn 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
689pub const INTERNAL_ENTRY_PREFIX: &str = "\0bilingua-";
692
693fn zip_name_error(raw: &str, what: &str) -> Error {
694 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
699pub 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
728struct SkeletonWalk {
730 parts: usize,
731 refs: usize,
732 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
776pub 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
803fn 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
824pub 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
838pub 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
860fn 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
875pub fn check_xml(bytes: &[u8], l: &Limits) -> Result<(), Error> {
892 check_xml_with(bytes, l, false, false)
893}
894
895pub fn check_xml_internal_entities(bytes: &[u8], l: &Limits) -> Result<(), Error> {
901 check_xml_with(bytes, l, false, true)
902}
903
904fn 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 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
947pub fn check_xml_keeping_dtd(bytes: &[u8], l: &Limits) -> Result<(), Error> {
952 check_xml_with(bytes, l, true, false)
953}
954
955fn 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
989fn 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
1004fn 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
1068fn 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 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 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 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 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 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 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 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
1220pub 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#[derive(Debug, Clone)]
1258pub struct ElementCounter {
1259 local: Vec<u8>,
1260 state: CountState,
1261 count: usize,
1262 first: Option<u8>,
1264 started: bool,
1265 utf16: bool,
1266}
1267
1268#[derive(Debug, Clone, Copy)]
1269enum CountState {
1270 Text,
1272 Open,
1274 Bang { n: usize, comment: bool, cdata: bool },
1276 Name { pos: usize, ok: bool, never: bool },
1279 Skip { end: &'static [u8], k: usize },
1281}
1282
1283const CDATA_OPEN: &[u8] = b"![CDATA[";
1284
1285fn 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
1298fn ends_name(c: u8) -> bool {
1300 c.is_ascii_whitespace() || c == b'>' || c == b'/'
1301}
1302
1303impl ElementCounter {
1304 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 pub fn count(&self) -> usize {
1311 self.count
1312 }
1313
1314 pub fn exact(&self) -> bool {
1316 !self.utf16
1317 }
1318
1319 pub fn feed(&mut self, bytes: &[u8]) {
1321 if bytes.is_empty() || self.utf16 {
1322 return;
1323 }
1324 if !self.started {
1325 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 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 _ => 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 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 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 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
1438pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 & y é</a>"#;
1686 assert!(check_xml(ok, &Limits::default()).is_ok());
1687 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 #[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 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 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 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 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 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 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}