use pdfcer_model::filters;
use pdfcer_model::object::Dict;
use pdfcer_model::view::DocumentView;
use crate::ImageCodecError;
use crate::peak::{bits_per_component, dim, sample_components};
pub(crate) fn expected_len(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
let width = dim(doc, dict, b"Width", b"W")?;
let height = dim(doc, dict, b"Height", b"H")?;
let row = width
.checked_mul(sample_components(doc, dict)?)?
.checked_mul(bits_per_component(doc, dict)?)?
.div_ceil(8);
row.checked_mul(height)
}
fn max_output(names: &[Vec<u8>], have: u64) -> Option<u128> {
let (mut num, mut den) = (u128::from(have), 1u128);
for name in names {
let (n, d) = match name.as_slice() {
b"FlateDecode" | b"Fl" => (1032, 1),
b"RunLengthDecode" | b"RL" => (64, 1),
b"ASCII85Decode" | b"A85" => (4, 1),
b"ASCIIHexDecode" | b"AHx" => (1, 2),
_ => return None,
};
num = num.checked_mul(n)?;
den = den.checked_mul(d)?;
}
Some(num / den)
}
pub(crate) fn check(names: &[Vec<u8>], raw: &[u8], expected: u64) -> Result<(), ImageCodecError> {
let compresses = names.iter().any(|n| {
matches!(
n.as_slice(),
b"FlateDecode" | b"Fl" | b"RunLengthDecode" | b"RL"
)
});
if !compresses {
return Ok(());
}
let have = u64::try_from(raw.len()).unwrap_or(u64::MAX);
let Some(max) = max_output(names, have) else {
return Ok(());
};
if u128::from(expected) <= max {
return Ok(());
}
Err(ImageCodecError::DeclaredSizeExceedsStream {
expected_bytes: expected,
max_bytes: u64::try_from(max).unwrap_or(u64::MAX),
have_bytes: have,
})
}
pub(crate) fn decode(
dict: &Dict,
raw: &[u8],
take: usize,
expected: Option<u64>,
notes: &mut filters::FilterNotes,
cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, filters::FilterError> {
match expected.and_then(|n| usize::try_from(n).ok()) {
Some(n) => filters::decode_prefix_bounded(dict, raw, take, n, notes, cancelled),
None => filters::decode_prefix_polled(dict, raw, take, notes, cancelled),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn n(s: &[u8]) -> Vec<u8> {
s.to_vec()
}
#[test]
fn expansions_multiply_along_the_chain() {
assert_eq!(max_output(&[], 10), Some(10));
assert_eq!(max_output(&[n(b"FlateDecode")], 10), Some(10_320));
assert_eq!(max_output(&[n(b"A85"), n(b"Fl")], 10), Some(41_280));
assert_eq!(max_output(&[n(b"AHx")], 11), Some(5));
assert_eq!(max_output(&[n(b"RL")], 2), Some(128));
}
#[test]
fn lzw_or_brotli_anywhere_leaves_the_chain_unbounded() {
assert_eq!(max_output(&[n(b"LZWDecode")], 10), None);
assert_eq!(max_output(&[n(b"Fl"), n(b"BrotliDecode")], 10), None);
}
#[test]
fn the_bound_is_inclusive() {
let fl = [n(b"FlateDecode")];
assert!(check(&fl, &[0; 10], 10_320).is_ok());
let key = check(&fl, &[0; 10], 10_321)
.err()
.and_then(|e| e.refusal_key());
assert_eq!(key, Some("image/evidence/stream"));
}
}