diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 09f7531ff1..911b356793 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -22,4 +22,4 @@ mod pixels; pub(crate) use filters::Stream; #[cfg(test)] -pub(crate) use ops::measured; +pub(crate) use ops::{measured, with_data_limit}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index cada27219a..7f3d37e043 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,4 +1,4 @@ -use super::ops::MAX_DATA; +use super::ops::max_data; use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; use craft_stream_codecs::CcittParams; @@ -44,7 +44,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { out.extend(std::iter::repeat_n(b, 257 - usize::from(n))); } } - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } } @@ -54,7 +54,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { /// zlib data inflated, and how many bytes of `raw` it took. fn flate(raw: &[u8]) -> Res<(Vec, usize)> { let mut z = flate2::Decompress::new(true); - let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(MAX_DATA)); + let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(max_data())); loop { let before = (z.total_in(), z.total_out()); if out.capacity() - out.len() < 64 * 1024 { @@ -62,7 +62,7 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { } let input = raw.get(z.total_in() as usize..).unwrap_or_default(); let status = z.decompress_vec(input, &mut out, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } match status { @@ -79,7 +79,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { let mut out = vec![]; let used = lzw_into(raw, &mut |bytes| { out.extend_from_slice(bytes); - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } Ok(()) @@ -238,10 +238,10 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `EndOfBlock` the rows end at the end-of-block code (EOFB, or RTC in Group 3) regardless of /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an -/// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. +/// `ioerror`. Rows that would take more than [`max_data`] bytes are refused. fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); - let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); + let most = u32::try_from(max_data() / row).unwrap_or(u32::MAX); if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c27dc3c3c6..c83b4dca4d 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -6,7 +6,38 @@ use super::{ }; /// Most bytes one filter or image reads. -pub(super) const MAX_DATA: usize = 1 << 28; +const MAX_DATA: usize = 1 << 28; + +#[cfg(test)] +thread_local! { + /// The most bytes one filter or image reads on this thread ([`MAX_DATA`] unless a test lowered it). + static DATA_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_DATA) }; +} + +/// The most bytes one filter or image reads: [`MAX_DATA`]. +#[cfg(not(test))] +pub(super) const fn max_data() -> usize { + MAX_DATA +} + +/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread. +#[cfg(test)] +pub(super) fn max_data() -> usize { + DATA_LIMIT.get() +} + +/// Runs `f` with [`max_data`] set to `limit` on this thread, and restores it afterwards. +#[cfg(test)] +pub(crate) fn with_data_limit(limit: usize, f: impl FnOnce() -> R) -> R { + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + DATA_LIMIT.set(self.0); + } + } + let _restore = Restore(DATA_LIMIT.replace(limit)); + f() +} /// Decoded bytes the measuring of an image's data left out charges one operation for. A program's /// budget grows by 64 operations for each byte of it, so the data of one image compressed up to @@ -410,7 +441,7 @@ impl Interp<'_> { Stream::Buf { data, pos: 0, rgb } } p @ Obj::Array { .. } => { - let raw = self.gather(&p, MAX_DATA)?; + let raw = self.gather(&p, max_data())?; let (data, _, rgb) = decode(&spec, &raw)?; self.charge_decoded(data.len())?; Stream::Buf { data, pos: 0, rgb } @@ -600,7 +631,7 @@ impl Interp<'_> { if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { return Ok(None); } - let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= max_data()) else { return Ok(None) }; self.alloc(kept)?; // The compressed data: what the filters before the last one decode, or the file itself. let compressed = if head.is_empty() { @@ -618,7 +649,7 @@ impl Interp<'_> { }; let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); // Past the image's data and as much again the data is not an image's: it stops there. - let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let most = row.saturating_mul(s.h).saturating_add(max_data()); let mut sink = |mut chunk: &[u8]| -> Res { while !chunk.is_empty() { let (r, off) = (seen / row.max(1), seen % row.max(1)); @@ -829,7 +860,7 @@ impl Interp<'_> { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); // What is read: an image past the pixel cap is reduced from the samples read. - charged = total.min(MAX_DATA); + charged = total.min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) @@ -838,7 +869,7 @@ impl Interp<'_> { stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - charged = row.saturating_mul(image.h).min(MAX_DATA); + charged = row.saturating_mul(image.h).min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_samples(&raw, image.w, image.h, n, image.bpc) @@ -1020,7 +1051,7 @@ impl Interp<'_> { // skipped), while one within the pixel cap whose samples are still too much data // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane // is refused). - let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= max_data()) else { if step > 1 { return Ok(self.leave_out(&s)); } diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 2324de4eb4..ffc482f0f7 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -686,11 +686,15 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { /// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure /// is called until the data ends; when its first filter decompresses to more than the reader /// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is -/// measured without keeping it. +/// measured without keeping it. The reader holds 1 MiB here, and each filter's data decompresses +/// to 2 MiB: Flate and LZW data is measured in full (run-length data is measured by its run +/// lengths, without decoding it). #[test] fn the_data_of_an_image_too_large_to_hold_is_skipped() { + const LIMIT: usize = 1 << 20; + const DECODED: usize = 2 * LIMIT; let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; - let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + let zeros = crate::ps::deflate(&vec![0u8; DECODED]); // Predicted rows aren't decoded a row at a time: such an image is left out. let mut flate = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); @@ -699,7 +703,7 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { // The same through LZW, which counts the codes up to its end-of-data code. let mut lzw = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec(); - lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true)); + lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; DECODED], true)); lzw.extend(format!("\n{after}").as_bytes()); // Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of // 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in @@ -707,24 +711,29 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { // run's length and stays off by one. let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec(); run_length.extend([2, 200, 200, 200]); - run_length.extend([129u8, 200].repeat((300 << 20) / 128)); + run_length.extend([129u8, 200].repeat(DECODED / 128)); run_length.push(128); run_length.extend(format!("\n{after}").as_bytes()); - for program in [ - format!( - "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ - 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" - ) - .into_bytes(), - flate, - lzw, - run_length, + for (program, measured) in [ + ( + format!( + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + 0, + ), + (flate, DECODED as u64), + (lzw, DECODED as u64), + (run_length, 0), ] { let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); file.extend(&program); file.extend(b"\nshowpage\n%%EOF\n"); - let r = import(&file).unwrap(); + let before = crate::import::data::measured(); + let r = crate::import::data::with_data_limit(LIMIT, || import(&file)).unwrap(); + assert_eq!(crate::import::data::measured() - before, measured, "{text}"); assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); let o = super::tests::objects(&r.document); assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings);