use crate::{Document, Error};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LimitKind {
InputBytes,
Lines,
Units,
UnitChars,
Context,
XmlDepth,
Depth,
XmlElements,
XmlEntities,
Paragraphs,
Spreadsheet,
ZipEntries,
ZipBytes,
ZipRatio,
ZipMalformed,
OutputBytes,
Skeleton,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LimitError {
pub kind: LimitKind,
pub msg: String,
}
impl fmt::Display for LimitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl LimitError {
pub fn new(kind: LimitKind, msg: impl Into<String>) -> LimitError {
LimitError { kind, msg: msg.into() }
}
}
impl From<LimitError> for Error {
fn from(e: LimitError) -> Error {
Error::Limit(e)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct Limits {
pub max_input_bytes: u64,
pub max_units: usize,
pub max_unit_chars: usize,
pub max_lines: usize,
pub max_xml_depth: usize,
pub max_xml_elements: usize,
pub max_zip_entries: usize,
pub max_zip_bytes: u64,
pub max_zip_entry_bytes: u64,
pub max_zip_ratio: u64,
pub zip_ratio_floor_bytes: u64,
pub max_paragraphs: usize,
pub xlsx_max_cells: usize,
pub xlsx_max_rows: u32,
pub xlsx_max_cell_chars: usize,
pub xlsx_max_total_text_chars: usize,
pub max_context_bytes: u64,
pub max_output_bytes: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_input_bytes: 100 * 1024 * 1024,
max_units: 50_000,
max_unit_chars: 100_000,
max_lines: 20 * 50_000,
max_xml_depth: 256,
max_xml_elements: 4_000_000,
max_zip_entries: 10_000,
max_zip_bytes: 256 * 1024 * 1024,
max_zip_entry_bytes: 256 * 1024 * 1024,
max_zip_ratio: 200,
zip_ratio_floor_bytes: 1024 * 1024,
max_paragraphs: 50_000,
xlsx_max_cells: 500_000,
xlsx_max_rows: 100_000,
xlsx_max_cell_chars: 32_767,
xlsx_max_total_text_chars: 8 * 1024 * 1024,
max_context_bytes: 128 * 1024 * 1024,
max_output_bytes: 1024 * 1024 * 1024,
}
}
}
const UNBOUNDED_COUNT: usize = if usize::BITS >= 64 { usize::MAX >> 12 } else { usize::MAX >> 8 };
const UNBOUNDED_BYTES: u64 = u64::MAX >> 12;
impl Limits {
pub fn new() -> Limits {
Limits::default()
}
pub fn large() -> Limits {
Limits {
max_input_bytes: 4 << 30,
max_units: 20_000_000,
max_unit_chars: 10_000_000,
max_lines: 400_000_000,
max_xml_depth: 256,
max_xml_elements: 400_000_000,
max_zip_entries: 200_000,
max_zip_bytes: 4 << 30,
max_zip_entry_bytes: 2 << 30,
max_zip_ratio: 1000,
zip_ratio_floor_bytes: 1024 * 1024,
max_paragraphs: 20_000_000,
xlsx_max_cells: 200_000_000,
xlsx_max_rows: 1_048_576,
xlsx_max_cell_chars: 32_767,
xlsx_max_total_text_chars: 2_000_000_000,
max_context_bytes: 16 << 30,
max_output_bytes: 32 << 30,
}
}
pub fn unbounded() -> Limits {
Limits {
max_input_bytes: UNBOUNDED_BYTES,
max_units: UNBOUNDED_COUNT,
max_unit_chars: UNBOUNDED_COUNT,
max_lines: UNBOUNDED_COUNT,
max_xml_depth: 256,
max_xml_elements: UNBOUNDED_COUNT,
max_zip_entries: UNBOUNDED_COUNT,
max_zip_bytes: UNBOUNDED_BYTES,
max_zip_entry_bytes: UNBOUNDED_BYTES,
max_zip_ratio: UNBOUNDED_BYTES,
zip_ratio_floor_bytes: 1024 * 1024,
max_paragraphs: UNBOUNDED_COUNT,
xlsx_max_cells: UNBOUNDED_COUNT,
xlsx_max_rows: u32::MAX >> 4,
xlsx_max_cell_chars: UNBOUNDED_COUNT,
xlsx_max_total_text_chars: UNBOUNDED_COUNT,
max_context_bytes: UNBOUNDED_BYTES,
max_output_bytes: UNBOUNDED_BYTES,
}
}
pub fn profile(name: &str) -> Option<Limits> {
match name.trim().to_ascii_lowercase().as_str() {
"hosted" | "default" | "server" => Some(Limits::new()),
"large" | "desktop" | "local" => Some(Limits::large()),
"unbounded" | "none" => Some(Limits::unbounded()),
_ => None,
}
}
pub fn clamped(self) -> Limits {
let u = Limits::unbounded();
Limits {
max_input_bytes: self.max_input_bytes.min(u.max_input_bytes),
max_units: self.max_units.min(u.max_units),
max_unit_chars: self.max_unit_chars.min(u.max_unit_chars),
max_lines: self.max_lines.min(u.max_lines),
max_xml_depth: self.max_xml_depth,
max_xml_elements: self.max_xml_elements.min(u.max_xml_elements),
max_zip_entries: self.max_zip_entries.min(u.max_zip_entries),
max_zip_bytes: self.max_zip_bytes.min(u.max_zip_bytes),
max_zip_entry_bytes: self.max_zip_entry_bytes.min(u.max_zip_entry_bytes),
max_zip_ratio: self.max_zip_ratio.min(u.max_zip_ratio),
zip_ratio_floor_bytes: self.zip_ratio_floor_bytes,
max_paragraphs: self.max_paragraphs.min(u.max_paragraphs),
xlsx_max_cells: self.xlsx_max_cells.min(u.xlsx_max_cells),
xlsx_max_rows: self.xlsx_max_rows.min(u.xlsx_max_rows),
xlsx_max_cell_chars: self.xlsx_max_cell_chars.min(u.xlsx_max_cell_chars),
xlsx_max_total_text_chars: self.xlsx_max_total_text_chars.min(u.xlsx_max_total_text_chars),
max_context_bytes: self.max_context_bytes.min(u.max_context_bytes),
max_output_bytes: self.max_output_bytes.min(u.max_output_bytes),
}
}
pub fn with_max_input_bytes(mut self, v: u64) -> Limits {
self.max_input_bytes = v;
self
}
pub fn with_max_units(mut self, v: usize) -> Limits {
self.max_units = v;
self
}
pub fn with_max_unit_chars(mut self, v: usize) -> Limits {
self.max_unit_chars = v;
self
}
pub fn with_max_lines(mut self, v: usize) -> Limits {
self.max_lines = v;
self
}
pub fn with_max_xml_depth(mut self, v: usize) -> Limits {
self.max_xml_depth = v;
self
}
pub fn with_max_xml_elements(mut self, v: usize) -> Limits {
self.max_xml_elements = v;
self
}
pub fn with_max_zip_entries(mut self, v: usize) -> Limits {
self.max_zip_entries = v;
self
}
pub fn with_max_zip_bytes(mut self, v: u64) -> Limits {
self.max_zip_bytes = v;
self
}
pub fn with_max_zip_entry_bytes(mut self, v: u64) -> Limits {
self.max_zip_entry_bytes = v;
self
}
pub fn with_max_zip_ratio(mut self, v: u64) -> Limits {
self.max_zip_ratio = v;
self
}
pub fn with_zip_ratio_floor_bytes(mut self, v: u64) -> Limits {
self.zip_ratio_floor_bytes = v;
self
}
pub fn with_max_paragraphs(mut self, v: usize) -> Limits {
self.max_paragraphs = v;
self
}
pub fn with_xlsx_max_cells(mut self, v: usize) -> Limits {
self.xlsx_max_cells = v;
self
}
pub fn with_xlsx_max_rows(mut self, v: u32) -> Limits {
self.xlsx_max_rows = v;
self
}
pub fn with_xlsx_max_cell_chars(mut self, v: usize) -> Limits {
self.xlsx_max_cell_chars = v;
self
}
pub fn with_xlsx_max_total_text_chars(mut self, v: usize) -> Limits {
self.xlsx_max_total_text_chars = v;
self
}
pub fn with_max_context_bytes(mut self, v: u64) -> Limits {
self.max_context_bytes = v;
self
}
pub fn with_max_output_bytes(mut self, v: u64) -> Limits {
self.max_output_bytes = v;
self
}
}
pub fn own_cap<T: Ord + Copy>(own: T, hosted: T, caller: T) -> T {
if caller > hosted {
caller
} else {
own.min(caller)
}
}
pub fn own_cap_bytes(own: usize, hosted: u64, caller: u64) -> usize {
let c = usize::try_from(caller).unwrap_or(usize::MAX);
if caller > hosted {
c
} else {
own.min(c)
}
}
fn mb(n: u64) -> String {
if n >= 1024 * 1024 {
format!("{} MB", n / (1024 * 1024))
} else {
format!("{n} bytes")
}
}
pub fn check_input(bytes: &[u8], l: &Limits) -> Result<(), Error> {
if bytes.len() as u64 > l.max_input_bytes {
return Err(LimitError::new(
LimitKind::InputBytes,
format!(
"This file is {} long; the limit is {}. Split it into smaller files.",
mb(bytes.len() as u64),
mb(l.max_input_bytes)
),
)
.into());
}
Ok(())
}
pub fn check_lines(text: &str, l: &Limits) -> Result<(), Error> {
let n = text.bytes().filter(|b| *b == b'\n' || *b == b'\r').count();
if n > l.max_lines {
return Err(LimitError::new(
LimitKind::Lines,
format!("This file has more than {} lines. Split it into smaller files.", l.max_lines),
)
.into());
}
Ok(())
}
pub fn check_unit_count(count: usize, l: &Limits) -> Result<(), Error> {
if count > l.max_units {
return Err(LimitError::new(
LimitKind::Units,
format!("This file has more than {} segments. Split it into smaller files.", l.max_units),
)
.into());
}
Ok(())
}
pub const COMMENT_BASE: usize = 1_000_000;
pub fn check_comment_base(body_end: usize) -> Result<(), Error> {
if body_end > COMMENT_BASE {
return Err(LimitError::new(
LimitKind::Units,
"This file has more than 1,000,000 paragraphs, cells or text boxes and also has comments to translate, \
which is more than Bilingua can number apart. Turn off comment translation or split the file.",
)
.into());
}
Ok(())
}
fn comment_numbers_shared() -> Error {
LimitError::new(
LimitKind::Units,
"This document's comments and body text share numbers, so it cannot be merged safely. Extract the file again without comments.",
)
.into()
}
pub fn check_comment_base_merge(body_end: usize) -> Result<(), Error> {
if body_end > COMMENT_BASE {
return Err(comment_numbers_shared());
}
Ok(())
}
pub fn check_distinct_numbers(numbers: impl IntoIterator<Item = i64>) -> Result<(), Error> {
let mut seen = std::collections::HashSet::new();
if numbers.into_iter().any(|n| !seen.insert(n)) {
return Err(comment_numbers_shared());
}
Ok(())
}
pub fn check_budget(count: usize, per_unit: usize, what: &str, l: &Limits) -> Result<(), Error> {
if count > per_unit.saturating_mul(l.max_units) {
return Err(LimitError::new(
LimitKind::Units,
format!("{what} than a file of {} segments. Split it into smaller files.", l.max_units),
)
.into());
}
Ok(())
}
pub fn check_unit_chars(chars: usize, l: &Limits) -> Result<(), Error> {
if chars > l.max_unit_chars {
return Err(LimitError::new(
LimitKind::UnitChars,
format!(
"This file has a line or paragraph longer than {} characters. Break it into shorter lines.",
l.max_unit_chars
),
)
.into());
}
Ok(())
}
pub fn check_context_bytes(total: u64, l: &Limits) -> Result<(), Error> {
if total > l.max_context_bytes {
return Err(LimitError::new(
LimitKind::Context,
format!(
"This file carries more key, comment and note text than the limit of {} allows. Split it into smaller files.",
mb(l.max_context_bytes)
),
)
.into());
}
Ok(())
}
pub fn unit_context_bytes(c: &crate::UnitContext) -> u64 {
let opt = |s: &Option<String>| s.as_ref().map_or(0, |v| v.len() as u64);
opt(&c.kind)
+ opt(&c.style)
+ opt(&c.key)
+ opt(&c.heading)
+ opt(&c.location)
+ c.notes.iter().map(|n| n.len() as u64).sum::<u64>()
+ c.extra.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum::<u64>()
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ContextBudget {
used: u64,
}
impl ContextBudget {
pub fn new() -> ContextBudget {
ContextBudget::default()
}
pub fn charge(&mut self, bytes: usize, l: &Limits) -> Result<(), Error> {
self.used = self.used.saturating_add(bytes as u64);
check_context_bytes(self.used, l)
}
pub fn used(&self) -> u64 {
self.used
}
}
pub fn check_document(doc: &Document, l: &Limits) -> Result<(), Error> {
check_unit_count(doc.units.len(), l)?;
check_unit_count(doc.segment_count(), l)?;
let mut context: u64 = 0;
for u in &doc.units {
context = context.saturating_add(unit_context_bytes(&u.context));
check_context_bytes(context, l)?;
let chars: usize = u
.segments
.iter()
.flat_map(|s| s.source.iter())
.map(|i| match i {
crate::Inline::Text(t) => t.chars().count(),
crate::Inline::Tag { .. } => 1,
})
.sum();
check_unit_chars(chars, l)?;
}
Ok(())
}
pub const MERGE_REFS_PER_UNIT: usize = 4;
pub const MERGE_TARGET_CHARS_FACTOR: usize = 4;
pub fn check_merge(doc: &Document, l: &Limits) -> Result<(), Error> {
check_document(doc, l)?;
check_target_chars(doc, l)?;
let max_refs = MERGE_REFS_PER_UNIT.saturating_mul(l.max_units);
let max_parts = l.max_lines.saturating_add(max_refs);
let sizes: Vec<u64> = doc.units.iter().map(unit_output_bytes).collect();
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)) };
check_output_estimate(walk.estimate, l)?;
match &doc.skeleton {
crate::Skeleton::Text { parts, .. } => walk.parts(parts, &sizes, max_parts, max_refs, l)?,
crate::Skeleton::Zip { entries, .. } => {
if entries.len() > l.max_zip_entries {
return Err(LimitError::new(
LimitKind::ZipEntries,
format!("This document lists more than {} zip entries. It was not written.", l.max_zip_entries),
)
.into());
}
let mut seen = std::collections::HashSet::with_capacity(entries.len());
for e in entries {
if e.name.starts_with(INTERNAL_ENTRY_PREFIX) {
continue;
}
check_zip_name(&e.name)?;
if !seen.insert(e.name.to_ascii_lowercase()) {
return Err(zip_name_error(&e.name, "is listed twice"));
}
}
for e in entries {
match &e.data {
crate::ZipData::Raw(b) => {
walk.estimate = walk.estimate.saturating_add(b.len() as u64);
check_output_estimate(walk.estimate, l)?;
}
crate::ZipData::Parts(parts) => walk.parts(parts, &sizes, max_parts, max_refs, l)?,
}
}
}
crate::Skeleton::Binary { data, .. } => {
walk.estimate = walk.estimate.saturating_add(data.len() as u64);
check_output_estimate(walk.estimate, l)?;
}
}
Ok(())
}
fn check_target_chars(doc: &Document, l: &Limits) -> Result<(), Error> {
let max = l.max_unit_chars.saturating_mul(MERGE_TARGET_CHARS_FACTOR);
for u in &doc.units {
let chars: usize = u
.segments
.iter()
.flat_map(|s| s.target.iter())
.map(|i| match i {
crate::Inline::Text(t) => t.chars().count(),
crate::Inline::Tag { .. } => 1,
})
.fold(0usize, usize::saturating_add);
if chars > max {
return Err(LimitError::new(
LimitKind::UnitChars,
format!("This document has a translation longer than {max} characters. It was not written."),
)
.into());
}
}
Ok(())
}
pub const INTERNAL_ENTRY_PREFIX: &str = "\0bilingua-";
fn zip_name_error(raw: &str, what: &str) -> Error {
let shown: String = raw.chars().take(80).flat_map(char::escape_debug).collect();
LimitError::new(LimitKind::ZipMalformed, format!("This document has a zip entry name that {what} (\"{shown}\"). It was not written.")).into()
}
pub fn check_zip_name(raw: &str) -> Result<(), Error> {
if raw.is_empty() {
return Err(zip_name_error(raw, "is empty"));
}
if raw.chars().any(char::is_control) {
return Err(zip_name_error(raw, "holds a control character"));
}
if raw.starts_with('/') || raw.contains('\\') {
return Err(zip_name_error(raw, "is an absolute path or uses a backslash"));
}
if raw.contains(':') {
return Err(zip_name_error(raw, "contains a colon"));
}
let body = raw.strip_suffix('/').unwrap_or(raw);
for part in body.split('/') {
if part == ".." {
return Err(zip_name_error(raw, "climbs out of the archive (..)"));
}
if part.is_empty() || part.trim_end_matches(['.', ' ']).is_empty() {
return Err(zip_name_error(raw, "has an empty component or one made of dots or spaces"));
}
}
Ok(())
}
struct SkeletonWalk {
parts: usize,
refs: usize,
per_unit: Vec<usize>,
estimate: u64,
}
impl SkeletonWalk {
fn parts(&mut self, parts: &[crate::SkelPart], sizes: &[u64], max_parts: usize, max_refs: usize, l: &Limits) -> Result<(), Error> {
self.parts = self.parts.saturating_add(parts.len());
if self.parts > max_parts {
return Err(over_skeleton(l));
}
for p in parts {
match p {
crate::SkelPart::Raw(s) => self.estimate = self.estimate.saturating_add(s.len() as u64),
crate::SkelPart::Unit(i) => {
self.refs += 1;
if self.refs > max_refs {
return Err(over_skeleton(l));
}
let Some(n) = self.per_unit.get_mut(*i) else {
return Err(LimitError::new(
LimitKind::Skeleton,
format!("This document's skeleton refers to unit {i}, which the document does not have. It was not written."),
)
.into());
};
*n += 1;
if *n > MERGE_REFS_PER_UNIT {
return Err(LimitError::new(
LimitKind::Skeleton,
format!(
"This document's skeleton writes one unit more than {MERGE_REFS_PER_UNIT} times, more than any extraction makes it. It was not written."
),
)
.into());
}
self.estimate = self.estimate.saturating_add(sizes[*i]);
}
}
}
check_output_estimate(self.estimate, l)
}
}
pub fn check_output(len: usize, l: &Limits) -> Result<(), Error> {
check_output_estimate(len as u64, l)
}
fn check_output_estimate(n: u64, l: &Limits) -> Result<(), Error> {
if n > l.max_output_bytes {
return Err(LimitError::new(
LimitKind::OutputBytes,
format!("This document would write more than {}, the output limit. It was not written.", mb(l.max_output_bytes)),
)
.into());
}
Ok(())
}
fn over_skeleton(l: &Limits) -> Error {
LimitError::new(
LimitKind::Skeleton,
format!(
"This document's skeleton is larger, or refers to its units more often, than a file of {} segments. It was not written.",
l.max_units
),
)
.into()
}
fn unit_output_bytes(u: &crate::Unit) -> u64 {
let inlines = |v: &[crate::Inline]| -> u64 {
v.iter()
.map(|i| match i {
crate::Inline::Text(t) => t.len() as u64,
crate::Inline::Tag { id, kind, display, .. } => {
let code = u.codes.get(id).and_then(|c| match kind {
crate::TagKind::Open => c.open.as_ref(),
crate::TagKind::Close => c.close.as_ref(),
crate::TagKind::Standalone => c.standalone.as_ref(),
});
code.map_or(display.len(), String::len) as u64
}
})
.fold(0u64, u64::saturating_add)
};
u.segments.iter().map(|s| inlines(&s.source).max(inlines(&s.target))).fold(0u64, u64::saturating_add)
}
pub fn check_targets(doc: &Document, counts: bool) -> Result<(), Error> {
for u in &doc.units {
for s in &u.segments {
if !s.target.is_empty() {
crate::check_target_tags(&s.source, &s.target, &u.codes, counts)?;
}
}
}
Ok(())
}
pub fn finish(mut doc: Document, warnings: Vec<crate::Warning>, l: &Limits) -> Result<Document, Error> {
check_document(&doc, l)?;
doc.warnings.extend(warnings);
Ok(doc)
}
fn unsafe_xml(msg: impl Into<String>) -> Error {
LimitError::new(LimitKind::XmlEntities, msg).into()
}
fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
if from >= hay.len() {
return None;
}
hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
}
fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {
hay.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle))
}
fn markup_bytes(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
let le = bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[b'<', 0]);
let be = bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0, b'<']);
if le && !bytes.starts_with(&[0xFF, 0xFE, 0, 0]) {
let (s, _) = encoding_rs::UTF_16LE.decode_without_bom_handling(bytes);
return std::borrow::Cow::Owned(s.into_owned().into_bytes());
}
if be {
let (s, _) = encoding_rs::UTF_16BE.decode_without_bom_handling(bytes);
return std::borrow::Cow::Owned(s.into_owned().into_bytes());
}
std::borrow::Cow::Borrowed(bytes)
}
pub fn check_xml(bytes: &[u8], l: &Limits) -> Result<(), Error> {
check_xml_with(bytes, l, false, false)
}
pub fn check_xml_internal_entities(bytes: &[u8], l: &Limits) -> Result<(), Error> {
check_xml_with(bytes, l, false, true)
}
fn only_plain_internal_entities(doctype: &[u8]) -> bool {
let mut n = 0usize;
let mut from = 0usize;
while let Some(p) = doctype[from..].windows(8).position(|w| w.eq_ignore_ascii_case(b"<!ENTITY")) {
n += 1;
if n > 64 {
return false;
}
let mut j = from + p + 8;
let ws = |j: &mut usize| {
let s = *j;
while *j < doctype.len() && matches!(doctype[*j], b' ' | b'\t' | b'\r' | b'\n') {
*j += 1;
}
*j > s
};
if !ws(&mut j) {
return false;
}
let name_start = j;
while j < doctype.len() && (doctype[j].is_ascii_alphanumeric() || matches!(doctype[j], b'_' | b'-' | b'.' | b':')) {
j += 1;
}
if j == name_start || !ws(&mut j) || j >= doctype.len() {
return false;
}
let q = doctype[j];
if q != b'"' && q != b'\'' {
return false;
}
let Some(len) = doctype[j + 1..].iter().position(|c| *c == q) else { return false };
if len > 1024 || doctype[j + 1..j + 1 + len].contains(&b'&') {
return false;
}
from = j + 1 + len + 1;
}
true
}
pub fn check_xml_keeping_dtd(bytes: &[u8], l: &Limits) -> Result<(), Error> {
check_xml_with(bytes, l, true, false)
}
fn doctype_end(b: &[u8], i: usize) -> usize {
let (mut j, mut sq, mut subset) = (i + 9, 0u8, 0usize);
while j < b.len() {
let c = b[j];
if sq != 0 {
if c == sq {
sq = 0;
}
} else if c == b'"' || c == b'\'' {
sq = c;
} else if subset > 0 && b[j..].starts_with(b"<!--") {
match find(b, j + 4, b"-->") {
Some(e) => j = e + 2,
None => return b.len(),
}
} else if subset > 0 && b[j..].starts_with(b"<?") {
match find(b, j + 2, b"?>") {
Some(e) => j = e + 1,
None => return b.len(),
}
} else if c == b'[' {
subset += 1;
} else if c == b']' {
subset = subset.saturating_sub(1);
} else if c == b'>' && subset == 0 {
break;
}
j += 1;
}
j.min(b.len())
}
fn reader_doctype_end(b: &[u8], i: usize) -> Option<usize> {
let mut balance = 0usize;
for (j, c) in b.iter().enumerate().skip(i + 2) {
match c {
b'<' => balance += 1,
b'>' if balance == 0 => return Some(j),
b'>' => balance -= 1,
_ => {}
}
}
None
}
fn doctype_is_unambiguous(b: &[u8], i: usize, end: usize) -> Option<bool> {
if end >= b.len() || reader_doctype_end(b, i) != Some(end) {
return None;
}
let mut quoted_comment = false;
let special = |s: &[u8], also_quotes: bool| s.iter().any(|c| matches!(c, b'<' | b'>' | b'[' | b']') || (also_quotes && matches!(c, b'"' | b'\'')));
let (mut j, mut subset) = (i + 9, 0usize);
while j < end {
let c = b[j];
if c == b'"' || c == b'\'' {
let q = b[j + 1..end].iter().position(|x| *x == c)?;
if special(&b[j + 1..j + 1 + q], false) {
return None;
}
j += q + 2;
continue;
}
if subset > 0 && b[j..].starts_with(b"<!--") {
let e = find(b, j + 4, b"-->").filter(|e| *e < end)?;
let body = &b[j + 4..e];
if special(body, false) {
return None;
}
quoted_comment |= body.iter().any(|c| matches!(c, b'"' | b'\''));
j = e + 3;
continue;
}
if subset > 0 && b[j..].starts_with(b"<?") {
let e = find(b, j + 2, b"?>").filter(|e| *e < end)?;
if special(&b[j + 2..e], true) {
return None;
}
j = e + 2;
continue;
}
if c == b'[' {
subset += 1;
} else if c == b']' {
subset = subset.saturating_sub(1);
}
j += 1;
}
Some(quoted_comment)
}
fn ambiguous_markup(what: &str) -> Error {
LimitError::new(
LimitKind::XmlElements,
format!("This file has {what}, which XML readers do not agree on, so its elements could not be counted safely. It was not processed."),
)
.into()
}
fn markup_views(bytes: &[u8]) -> Vec<std::borrow::Cow<'_, [u8]>> {
use std::borrow::Cow;
let decode = |e: &'static encoding_rs::Encoding| Cow::Owned(e.decode_without_bom_handling(bytes).0.into_owned().into_bytes());
if (bytes.starts_with(&[0xFF, 0xFE]) && !bytes.starts_with(&[0xFF, 0xFE, 0, 0])) || bytes.starts_with(&[0xFE, 0xFF]) {
return vec![markup_bytes(bytes)];
}
let mut v = vec![Cow::Borrowed(bytes)];
if bytes.starts_with(&[b'<', 0]) || bytes.starts_with(&[0, b'<']) {
v.push(markup_bytes(bytes));
} else if std::str::from_utf8(bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes)).is_err() {
for e in [encoding_rs::SHIFT_JIS, encoding_rs::GB18030, encoding_rs::BIG5] {
v.push(decode(e));
}
}
v
}
fn check_xml_with(bytes: &[u8], l: &Limits, keep_dtd: bool, internal_ok: bool) -> Result<(), Error> {
for view in markup_views(bytes) {
scan_xml(&view, l, keep_dtd, internal_ok)?;
}
Ok(())
}
fn scan_xml(b: &[u8], l: &Limits, keep_dtd: bool, internal_ok: bool) -> Result<(), Error> {
let strict = !keep_dtd;
let (mut i, mut depth, mut elements) = (0usize, 0usize, 0usize);
while i < b.len() {
let Some(p) = b[i..].iter().position(|c| *c == b'<') else { break };
i += p;
let rest = &b[i..];
if rest.starts_with(b"<!--") {
if strict && (rest[4..].starts_with(b">") || rest[4..].starts_with(b"->")) {
return Err(ambiguous_markup("a comment that starts with '>' or '->'"));
}
match find(b, i + 4, b"-->") {
Some(e) => i = e + 3,
None => break,
}
} else if rest.starts_with(b"<![CDATA[") {
match find(b, i + 9, b"]]>") {
Some(e) => i = e + 3,
None => break,
}
} else if rest.starts_with(b"<?") {
if strict && rest[2..].starts_with(b">") {
return Err(ambiguous_markup("a processing instruction with no name ('<?>')"));
}
match find(b, i + 2, b"?>") {
Some(e) => i = e + 2,
None => break,
}
} else if rest.len() >= 9 && rest[..9].eq_ignore_ascii_case(b"<!DOCTYPE") {
let end = doctype_end(b, i);
if !keep_dtd && contains_ci(&b[i..end], b"<!ENTITY") && !(internal_ok && only_plain_internal_entities(&b[i..end])) {
return Err(unsafe_xml(
"This file declares XML entities (a DTD), which could expand without limit or read other files. It was not processed.",
));
}
if strict && end >= b.len() {
return Err(unsafe_xml("This file has a DOCTYPE that is not closed. It was not processed."));
}
if strict {
match doctype_is_unambiguous(b, i, end) {
None => {
return Err(unsafe_xml(
"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.",
))
}
Some(true) if contains_ci(&b[end..], b"<!ENTITY") => {
return Err(unsafe_xml(
"This file declares XML entities, which are not allowed. It was not processed.",
))
}
Some(_) => {}
}
}
i = end + 1;
} else if rest.starts_with(b"<!") {
if rest.len() >= 8 && rest[..8].eq_ignore_ascii_case(b"<!ENTITY") {
return Err(unsafe_xml("This file declares XML entities, which are not allowed. It was not processed."));
}
if strict {
return Err(ambiguous_markup("a markup declaration outside the DOCTYPE"));
}
match find(b, i + 2, b">") {
Some(e) => i = e + 1,
None => break,
}
} else if rest.starts_with(b"</") {
depth = depth.saturating_sub(1);
match find(b, i + 2, b">") {
Some(e) => i = e + 1,
None => break,
}
} else {
let (mut j, mut sq) = (i + 1, 0u8);
let mut end = None;
while j < b.len() {
let c = b[j];
if sq != 0 {
if c == sq {
sq = 0;
}
} else if c == b'"' || c == b'\'' {
sq = c;
} else if c == b'>' {
end = Some(j);
break;
}
j += 1;
}
let Some(e) = end else { break };
elements += 1;
if elements > l.max_xml_elements {
return Err(LimitError::new(
LimitKind::XmlElements,
format!("This file has more than {} XML elements in one part. It was not processed.", l.max_xml_elements),
)
.into());
}
if b[e - 1] != b'/' {
depth += 1;
if depth > l.max_xml_depth {
return Err(LimitError::new(
LimitKind::XmlDepth,
format!("This file nests XML elements more than {} deep. It was not processed.", l.max_xml_depth),
)
.into());
}
}
i = e + 1;
}
}
Ok(())
}
pub fn count_elements(bytes: &[u8], local: &str) -> usize {
let data = markup_bytes(bytes);
let b: &[u8] = &data;
let (mut i, mut n) = (0usize, 0usize);
while let Some(p) = b.get(i..).and_then(|r| r.iter().position(|c| *c == b'<')) {
i += p;
let rest = &b[i + 1..];
if rest.starts_with(b"!--") {
i = find(b, i + 4, b"-->").map_or(b.len(), |e| e + 3);
} else if rest.starts_with(b"![CDATA[") {
i = find(b, i + 9, b"]]>").map_or(b.len(), |e| e + 3);
} else if rest.starts_with(b"?") {
i = find(b, i + 2, b"?>").map_or(b.len(), |e| e + 2);
} else {
let name_end = rest.iter().position(|c| c.is_ascii_whitespace() || *c == b'>' || *c == b'/').unwrap_or(rest.len());
let name = &rest[..name_end];
let lname = name.rsplit(|c| *c == b':').next().unwrap_or(name);
if !name.starts_with(b"/") && !name.starts_with(b"!") && lname == local.as_bytes() {
n += 1;
}
i += 1 + name_end;
}
}
n
}
#[derive(Debug, Clone)]
pub struct ElementCounter {
local: Vec<u8>,
state: CountState,
count: usize,
first: Option<u8>,
started: bool,
utf16: bool,
}
#[derive(Debug, Clone, Copy)]
enum CountState {
Text,
Open,
Bang { n: usize, comment: bool, cdata: bool },
Name { pos: usize, ok: bool, never: bool },
Skip { end: &'static [u8], k: usize },
}
const CDATA_OPEN: &[u8] = b"![CDATA[";
fn skip_step(end: &[u8], k: usize, c: u8) -> usize {
let mut j = (k + 1).min(end.len());
while j > 0 {
if end[j - 1] == c && end[..j - 1] == end[k + 1 - j..k] {
return j;
}
j -= 1;
}
0
}
fn ends_name(c: u8) -> bool {
c.is_ascii_whitespace() || c == b'>' || c == b'/'
}
impl ElementCounter {
pub fn new(local: &str) -> ElementCounter {
ElementCounter { local: local.as_bytes().to_vec(), state: CountState::Text, count: 0, first: None, started: false, utf16: false }
}
pub fn count(&self) -> usize {
self.count
}
pub fn exact(&self) -> bool {
!self.utf16
}
pub fn feed(&mut self, bytes: &[u8]) {
if bytes.is_empty() || self.utf16 {
return;
}
if !self.started {
let held = self.first;
let Some(f) = held.or(bytes.first().copied()) else { return };
let second = if held.is_some() { bytes.first() } else { bytes.get(1) };
let Some(&s) = second else {
self.first = Some(f);
return;
};
self.started = true;
if matches!((f, s), (0xFF, 0xFE) | (b'<', 0) | (0xFE, 0xFF) | (0, b'<')) {
self.utf16 = true;
self.first = None;
return;
}
if let Some(f) = self.first.take() {
self.run(&[f]);
}
}
self.run(bytes);
}
pub fn finish(&mut self) {
if let Some(f) = self.first.take() {
self.started = true;
self.run(&[f]);
}
if let CountState::Name { pos, ok, never } = self.state {
if !never && ok && pos == self.local.len() {
self.count += 1;
}
}
self.state = CountState::Text;
}
fn run(&mut self, b: &[u8]) {
let mut i = 0;
while i < b.len() {
match self.state {
CountState::Text => match b[i..].iter().position(|c| *c == b'<') {
Some(p) => {
i += p + 1;
self.state = CountState::Open;
}
None => return,
},
CountState::Open => match b[i] {
b'!' => {
self.state = CountState::Bang { n: 1, comment: true, cdata: true };
i += 1;
}
b'?' => {
self.state = CountState::Skip { end: b"?>", k: 0 };
i += 1;
}
_ => self.state = CountState::Name { pos: 0, ok: true, never: false },
},
CountState::Bang { n, comment, cdata } => {
let c = b[i];
let n = n + 1;
let comment = comment && n <= 3 && b"!--"[n - 1] == c;
let cdata = cdata && n <= CDATA_OPEN.len() && CDATA_OPEN[n - 1] == c;
i += 1;
self.state = if comment && n == 3 {
CountState::Skip { end: b"-->", k: 0 }
} else if cdata && n == CDATA_OPEN.len() {
CountState::Skip { end: b"]]>", k: 0 }
} else if comment || cdata {
CountState::Bang { n, comment, cdata }
} else if ends_name(c) {
CountState::Text
} else {
CountState::Name { pos: 0, ok: false, never: true }
};
}
CountState::Name { mut pos, mut ok, never } => {
while i < b.len() && !ends_name(b[i]) {
let c = b[i];
if c == b':' {
pos = 0;
ok = true;
} else {
ok = ok && self.local.get(pos) == Some(&c);
pos += 1;
}
i += 1;
}
if i == b.len() {
self.state = CountState::Name { pos, ok, never };
return;
}
if !never && ok && pos == self.local.len() {
self.count += 1;
}
self.state = CountState::Text;
}
CountState::Skip { end, mut k } => {
while i < b.len() && k < end.len() {
k = skip_step(end, k, b[i]);
i += 1;
}
self.state = if k == end.len() { CountState::Text } else { CountState::Skip { end, k } };
}
}
}
}
}
pub fn check_markup(text: &str, l: &Limits) -> Result<(), Error> {
let b = text.as_bytes();
if contains_ci(b, b"<!ENTITY") {
return Err(unsafe_xml("This file declares markup entities, which are not allowed. It was not processed."));
}
let elements = b.windows(2).filter(|w| w[0] == b'<' && (w[1].is_ascii_alphabetic() || w[1] == b'/')).count();
if elements > l.max_xml_elements {
return Err(LimitError::new(
LimitKind::XmlElements,
format!("This file has more than {} markup elements. It was not processed.", l.max_xml_elements),
)
.into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn kind(r: Result<(), Error>) -> Option<LimitKind> {
match r {
Err(Error::Limit(e)) => Some(e.kind),
_ => None,
}
}
#[test]
fn defaults_are_locos_numbers() {
let l = Limits::default();
assert_eq!((l.max_input_bytes, l.max_units, l.max_unit_chars), (100 << 20, 50_000, 100_000));
assert_eq!((l.max_zip_entries, l.max_zip_bytes, l.max_zip_ratio), (10_000, 256 << 20, 200));
}
#[test]
fn pre_parse_budget_scales_with_the_unit_limit() {
let l = Limits { max_units: 10, ..Limits::default() };
assert!(check_budget(200, 20, "This JSON file has far more values", &l).is_ok());
let e = check_budget(201, 20, "This JSON file has far more values", &l).unwrap_err();
assert!(e.to_string().contains("far more values than a file of 10 segments. Split"), "{e}");
assert_eq!(kind(Err(e)), Some(LimitKind::Units));
assert!(check_budget(usize::MAX, usize::MAX, "x", &Limits { max_units: usize::MAX, ..Limits::default() }).is_ok());
}
#[test]
fn input_size_is_checked_against_the_callers_limit() {
let l = Limits { max_input_bytes: 10, ..Limits::default() };
assert!(check_input(&[0; 10], &l).is_ok());
assert_eq!(kind(check_input(&[0; 11], &l)), Some(LimitKind::InputBytes));
}
#[test]
fn xml_entity_bomb_and_xxe_are_refused() {
let bomb = br#"<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;">]><lolz>&lol2;</lolz>"#;
assert_eq!(kind(check_xml(bomb, &Limits::default())), Some(LimitKind::XmlEntities));
let xxe = br#"<!DOCTYPE r [ <!ENTITY x SYSTEM "file:///etc/passwd"> ]><r>&x;</r>"#;
assert_eq!(kind(check_xml(xxe, &Limits::default())), Some(LimitKind::XmlEntities));
let param = br#"<!doctype r [ <!entity % p SYSTEM "http://example.invalid/x.dtd"> %p; ]><r/>"#;
assert_eq!(kind(check_xml(param, &Limits::default())), Some(LimitKind::XmlEntities));
}
#[test]
fn internal_entities_mode_allows_only_plain_literals() {
let l = Limits::default();
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;"/>"#;
assert!(check_xml_internal_entities(ok, &l).is_ok());
assert_eq!(kind(check_xml(ok, &l)), Some(LimitKind::XmlEntities), "the strict check still refuses it");
for bad in [
r#"<!DOCTYPE r [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;">]><r/>"#,
r#"<!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/hosts">]><r/>"#,
r#"<!DOCTYPE r [<!ENTITY x PUBLIC "a" "b">]><r/>"#,
r#"<!DOCTYPE r [<!ENTITY % p "x">]><r/>"#,
r#"<!DOCTYPE r [<!ENTITY x>]><r/>"#,
r#"<!DOCTYPE r [<!ENTITY x "unclosed>]><r/>"#,
r#"<!ENTITY x "y"><r/>"#,
] {
assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
}
let long = format!("<!DOCTYPE r [<!ENTITY x \"{}\">]><r/>", "a".repeat(1025));
assert_eq!(kind(check_xml_internal_entities(long.as_bytes(), &l)), Some(LimitKind::XmlEntities));
for bad in [r#"<!DOCTYPE r [<!ENTITY x "<g/>">]><r/>"#, r#"<!DOCTYPE r [<!ENTITY x "a>b">]><r/>"#] {
assert!(check_xml_internal_entities(bad.as_bytes(), &l).is_err(), "{bad}");
}
let tight = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
let deep = r#"<!DOCTYPE r [<!ENTITY x "y">]><r><a><b>&x;</b></a></r>"#;
assert!(check_xml_internal_entities(deep.as_bytes(), &tight).is_err());
let many: String = (0..65).map(|k| format!("<!ENTITY e{k} \"v\">")).collect();
assert!(check_xml_internal_entities(format!("<!DOCTYPE r [{many}]><r/>").as_bytes(), &l).is_err());
}
#[test]
fn keeping_dtd_allows_declarations_but_not_more_elements_or_depth() {
let l = Limits { max_xml_depth: 8, max_xml_elements: 20, ..Limits::default() };
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>"#;
assert!(check_xml_keeping_dtd(bomb, &l).is_ok());
assert_eq!(kind(check_xml(bomb, &l)), Some(LimitKind::XmlEntities), "the strict check still refuses it");
for dt in [r#"<!DOCTYPE r [ <!-- ' ]> --> <!ENTITY a "x"> ]>"#, r#"<!DOCTYPE r [ <?pi ]> " ?> <!ENTITY a "]>"> ]>"#] {
let deep = format!("{dt}{}{}", "<a>".repeat(9), "</a>".repeat(9));
assert_eq!(kind(check_xml_keeping_dtd(deep.as_bytes(), &l)), Some(LimitKind::XmlDepth), "{dt}");
let wide = format!("{dt}<r>{}</r>", "<b/>".repeat(30));
assert_eq!(kind(check_xml_keeping_dtd(wide.as_bytes(), &l)), Some(LimitKind::XmlElements), "{dt}");
assert_eq!(kind(check_xml(deep.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{dt}");
}
assert_eq!(kind(check_xml_keeping_dtd(br#"<!ENTITY a "x"><r/>"#, &l)), Some(LimitKind::XmlEntities));
}
#[test]
fn a_doctype_the_readers_end_elsewhere_is_refused() {
let l = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
let body = "<r><a><b><c/></b></a></r>";
assert_eq!(kind(check_xml(body.as_bytes(), &l)), Some(LimitKind::XmlDepth));
for pre in [
"<!doctype r SYSTEM '>",
"<!DOCTYPE r SYSTEM \">",
"<!DoCtYpE r PUBLIC 'a>b' 'c'>",
"<!DOCTYPE r [>",
"<!DOCTYPE r [<!-- > -->",
"<!DOCTYPE r [<!-- ] --> <x><y>",
"<!DOCTYPE r [<!-- ' --> <?p ' ?> ]>",
"<!DOCTYPE r SYSTEM 'a[b'>",
"<!DOCTYPE r < >",
"<!DOCTYPE r [ > ]>",
"<!DOCTYPE r",
] {
let k = kind(check_xml(format!("{pre}{body}").as_bytes(), &l));
assert!(matches!(k, Some(LimitKind::XmlEntities | LimitKind::XmlDepth)), "{pre}: {k:?}");
assert!(kind(check_xml(format!("{pre}{body}").as_bytes(), &Limits::default())).is_some(), "{pre} refused even with room");
}
for ok in [
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
"<!doctype html>",
"<!DOCTYPE r []>",
"<!DOCTYPE mb [ <!ELEMENT mb (msg)*> <!ATTLIST msg id CDATA #IMPLIED d CDATA 'x'> <!-- a note --> <?pi data?> ]>",
"<!DOCTYPE r [ <!---->]>",
] {
assert!(check_xml(format!("{ok}<r/>").as_bytes(), &Limits::default()).is_ok(), "{ok}");
}
assert!(check_xml_keeping_dtd(b"<!DOCTYPE r [<!-- > --> ]><r/>", &Limits::default()).is_ok());
}
#[test]
fn a_quote_in_a_comment_of_the_subset_passes_but_hides_no_entity() {
let l = Limits::default();
for ok in [
"<!DOCTYPE r [ <!-- don't edit this file --> <!ELEMENT r ANY> ]><r/>",
"<!DOCTYPE r [ <!-- the \"r\" element --> <!ATTLIST r id CDATA #IMPLIED> <!-- it's 'r' --> ]><r id='a'>x</r>",
"<!DOCTYPE r [<!--'-->]><r/>",
] {
assert!(check_xml(ok.as_bytes(), &l).is_ok(), "{ok}");
assert!(check_xml_internal_entities(ok.as_bytes(), &l).is_ok(), "{ok}");
}
let svg = "<!DOCTYPE svg [ <!-- Adobe's namespaces --> <!ENTITY ns_svg \"http://www.w3.org/2000/svg\"> ]><svg/>";
assert!(check_xml_internal_entities(svg.as_bytes(), &l).is_ok());
assert_eq!(kind(check_xml(svg.as_bytes(), &l)), Some(LimitKind::XmlEntities));
for bad in [
"<!DOCTYPE r [ <!-- don't --> <!ENTITY a \"x\"> ]><r>&a;</r>",
"<!DOCTYPE r [ <!ENTITY a \"x\"> <!-- don't --> ]><r>&a;</r>",
"<!DOCTYPE r [ <!-- ' <!ENTITY a SYSTEM \"file:///etc/passwd\"> ' --> ]><r/>",
"<!DOCTYPE r [ <!-- ' --><!ENTITY % p SYSTEM \"http://example.invalid/x.dtd\"> %p; ]><r/>",
"<!DOCTYPE r [ <!-- ' --> ]><!ENTITY a \"x\"><r/>",
] {
assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
}
for bad in [
"<!DOCTYPE svg [ <!-- ' --> <!ENTITY a \"&b;&b;\"> ]><svg/>",
"<!DOCTYPE svg [ <!-- ' <!ENTITY a SYSTEM \"file:///etc/passwd\"> --> ]><svg/>",
"<!DOCTYPE svg [ <!-- ' --> <!ENTITY % p \"x\"> ]><svg/>",
] {
assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
}
for bad in [
"<!DOCTYPE r [ <!-- ' --> ]><r a='<!ENTITY b \"x\">'/>",
"<!DOCTYPE r [ <!-- \" --> ]><r><!-- <!entity b 'x'> --></r>",
"<!DOCTYPE r [ <!-- ' --> ]><r><![CDATA[<!ENTITY b 'x'>]]></r>",
] {
assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
assert_eq!(kind(check_xml_internal_entities(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
}
for bad in [
"<!DOCTYPE r [ <!-- ' ] --> ]><r/>",
"<!DOCTYPE r [ <!-- \" > --> ]><r/>",
"<!DOCTYPE r [ <!-- ' < --> ]><r/>",
"<!DOCTYPE r [ <!-- ' [ --> ]><r/>",
"<!DOCTYPE r [ <!-- ok --> <?pi don't ?> ]><r/>",
"<!DOCTYPE r [ <!-- ' --> ",
] {
assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlEntities), "{bad}");
}
let tight = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
let deep = "<!DOCTYPE r [ <!-- don't --> ]><r><a><b><c/></b></a></r>";
assert_eq!(kind(check_xml(deep.as_bytes(), &tight)), Some(LimitKind::XmlDepth));
let wide = "<!DOCTYPE r [ <!-- don't --> ]><r><b/><b/><b/><b/></r>";
assert_eq!(kind(check_xml(wide.as_bytes(), &tight)), Some(LimitKind::XmlElements));
}
#[test]
fn every_reading_of_the_bytes_is_scanned() {
let l = Limits { max_xml_depth: 2, max_xml_elements: 3, ..Limits::default() };
let body = "<a><b><c/></b></a>";
let sjis = format!("<?xml version=\"1.0\" encoding=\"Shift_JIS\"?><r><![CDATA[\u{1}]]><!--]]>{body}--></r>");
let mut bytes = sjis.into_bytes();
let p = bytes.iter().position(|c| *c == 1).unwrap();
bytes[p] = 0x81;
assert!(check_xml(&bytes, &l).is_err());
let ok = b"<?xml version=\"1.0\" encoding=\"Shift_JIS\"?><r><![CDATA[\x93\xfa]]>\x96\x7b</r>";
assert!(check_xml(ok, &Limits::default()).is_ok());
let nul = format!("\0<r>{body}</r>");
assert!(check_xml(nul.as_bytes(), &l).is_err());
let mut le = Vec::new();
for u in format!("<r>{body}</r>").encode_utf16() {
le.extend(u.to_le_bytes());
}
assert!(check_xml(&le, &l).is_err());
assert!(check_xml(&le, &Limits::default()).is_ok());
}
#[test]
fn a_comment_or_pi_a_scanner_ends_early_is_refused() {
let l = Limits::default();
for bad in ["<!--><r><a/></r><!-- -->", "<!---><r/><!-- -->", "<?><r/><?x?>", "<r><![IGNORE[ <a/> ]]></r>", "<!ELEMENT r ANY><r/>"] {
assert_eq!(kind(check_xml(bad.as_bytes(), &l)), Some(LimitKind::XmlElements), "{bad}");
}
for ok in ["<r><!----></r>", "<r><!-- - --></r>", "<r><??></r>", "<r><?pi x?></r>"] {
assert!(check_xml(ok.as_bytes(), &l).is_ok(), "{ok}");
}
}
#[test]
fn a_plain_doctype_and_predefined_entities_pass() {
let ok = br#"<?xml version="1.0"?><!DOCTYPE xliff PUBLIC "-//OASIS//DTD XLIFF 1.2//EN" "xliff.dtd"><a>x & y é</a>"#;
assert!(check_xml(ok, &Limits::default()).is_ok());
assert!(check_xml(b"<a><!-- <!ENTITY x 'y'> --><![CDATA[<!ENTITY z 'w'>]]></a>", &Limits::default()).is_ok());
}
#[test]
fn xml_depth_and_element_count_are_bounded() {
let l = Limits { max_xml_depth: 8, max_xml_elements: 20, ..Limits::default() };
let deep = format!("{}{}", "<a>".repeat(9), "</a>".repeat(9));
assert_eq!(kind(check_xml(deep.as_bytes(), &l)), Some(LimitKind::XmlDepth));
let ok = format!("{}{}", "<a>".repeat(8), "</a>".repeat(8));
assert!(check_xml(ok.as_bytes(), &l).is_ok());
let wide = format!("<r>{}</r>", "<b/>".repeat(30));
assert_eq!(kind(check_xml(wide.as_bytes(), &l)), Some(LimitKind::XmlElements));
}
#[test]
fn utf16_xml_is_scanned_too() {
let src = "<!DOCTYPE r [<!ENTITY a 'b'>]><r/>";
let mut v = vec![0xFF, 0xFE];
v.extend(src.encode_utf16().flat_map(|u| u.to_le_bytes()));
assert_eq!(kind(check_xml(&v, &Limits::default())), Some(LimitKind::XmlEntities));
}
#[test]
fn counts_elements_by_local_name() {
let x = b"<w:body><w:p/><w:p w:x='1'>a</w:p><!-- <w:p/> --><w:pPr/><p>x</p></w:body>";
assert_eq!(count_elements(x, "p"), 3);
}
#[test]
fn element_counter_agrees_with_count_elements() {
let mut seed: u64 = 0x5eed_0115;
let mut next = move |n: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((seed >> 33) as usize) % n
};
let pieces: &[&[u8]] = &[
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/>",
b"<w:pPr>", b"</w:p>", b"<!--", b"-->", b"<![CDATA[", b"]]>", b"<?", b"?>", b"<!", b"<!-", b"<![CD", b"<![-", b"<!-[", b"a:p", b"pp",
b"<p", b":p", b"x", b"<!DOCTYPE x>", b"\"", b"'",
];
for round in 0..3000 {
let mut doc = Vec::new();
for _ in 0..next(60) {
doc.extend_from_slice(pieces[next(pieces.len())]);
}
for local in ["p", "pPr"] {
let want = count_elements(&doc, local);
for mode in 0..3 {
let mut c = ElementCounter::new(local);
let mut at = 0;
while at < doc.len() {
let len = match mode {
0 => doc.len(),
1 => 1,
_ => 1 + next(7),
};
let end = (at + len).min(doc.len());
c.feed(&doc[at..end]);
at = end;
assert!(c.count() <= want, "round {round}: {} over {want} after a piece of {:?}", c.count(), String::from_utf8_lossy(&doc));
}
c.finish();
assert!(c.exact());
assert_eq!(c.count(), want, "round {round} mode {mode}: {:?}", String::from_utf8_lossy(&doc));
}
}
}
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>";
let mut c = ElementCounter::new("p");
c.feed(x);
c.finish();
assert_eq!((c.count(), count_elements(x, "p")), (3, 3));
let mut v = vec![0xFF, 0xFE];
v.extend("<w:p/>".encode_utf16().flat_map(|u| u.to_le_bytes()));
let mut c = ElementCounter::new("p");
c.feed(&v[..1]);
c.feed(&v[1..]);
c.finish();
assert!(!c.exact());
assert_eq!(c.count(), 0);
assert_eq!(count_elements(&v, "p"), 1);
}
#[test]
fn own_caps_follow_a_raised_limit_only() {
let h = Limits::new();
assert_eq!(own_cap(500_000, h.max_units, h.max_units), 50_000);
assert_eq!(own_cap(20_000, h.max_units, h.max_units), 20_000);
assert_eq!(own_cap(500_000, h.max_units, 10), 10);
assert_eq!(own_cap_bytes(64 << 20, h.max_input_bytes, h.max_input_bytes), 64 << 20);
assert_eq!(own_cap_bytes(256 << 20, h.max_input_bytes, h.max_input_bytes), 100 << 20);
let l = Limits::large();
assert_eq!(own_cap(500_000, h.max_units, l.max_units), l.max_units);
assert_eq!(own_cap_bytes(64 << 20, h.max_input_bytes, l.max_input_bytes) as u64, l.max_input_bytes);
}
#[test]
fn comment_base_refuses_a_body_that_reaches_it() {
assert!(check_comment_base(0).is_ok());
assert!(check_comment_base(COMMENT_BASE).is_ok());
match check_comment_base(COMMENT_BASE + 1) {
Err(Error::Limit(e)) => {
assert_eq!(e.kind, LimitKind::Units);
assert!(e.msg.contains("more than Bilingua can number apart"), "{e}");
assert!(!e.msg.contains('\u{2014}'), "no em dash: {e}");
}
other => panic!("not a limit error: {other:?}"),
}
assert!(check_comment_base_merge(COMMENT_BASE).is_ok());
assert!(check_distinct_numbers([0, 1, 1_000_000]).is_ok());
for r in [check_comment_base_merge(COMMENT_BASE + 1), check_distinct_numbers([5, 1_000_000, 5])] {
match r {
Err(Error::Limit(e)) => {
assert_eq!(e.kind, LimitKind::Units);
assert!(e.msg.contains("comments and body text share numbers"), "{e}");
assert!(!e.msg.contains('\u{2014}'), "no em dash: {e}");
}
other => panic!("not a limit error: {other:?}"),
}
}
}
#[test]
fn line_budget() {
let l = Limits { max_lines: 5, ..Limits::default() };
assert!(check_lines("a\nb\nc\n", &l).is_ok());
assert_eq!(kind(check_lines(&"\n".repeat(6), &l)), Some(LimitKind::Lines));
}
}