diff --git a/crates/raw/src/hasselblad.rs b/crates/raw/src/hasselblad.rs index 83f759f742..4eb42755e5 100644 --- a/crates/raw/src/hasselblad.rs +++ b/crates/raw/src/hasselblad.rs @@ -87,13 +87,13 @@ pub(crate) fn rgb_preview(tiff: &Tiff, bytes: &[u8]) -> Option> { && matches!(i.layout, Layout::Strips { .. }) && i.width > 0 && i.height > 0 + // uncompressed: a preview larger than the whole file is not in it, and is passed over before any buffer + // is reserved (strips sharing one offset would otherwise copy a few bytes up to MAX_PREVIEW_BYTES); a + // smaller complete one elsewhere in the file is still taken + && (u64::from(i.width) * u64::from(i.height)).saturating_mul(3) <= MAX_PREVIEW_BYTES.min(bytes.len()) as u64 }) .max_by_key(|i| u64::from(i.width) * u64::from(i.height))?; - let (w, h) = (info.width as usize, info.height as usize); - let size = w.checked_mul(h)?.checked_mul(3)?; - if size > MAX_PREVIEW_BYTES { - return None; - } + let size = info.width as usize * info.height as usize * 3; let mut pixels = Vec::with_capacity(size); for chunk in info.chunks(bytes.len() as u64) { pixels.extend_from_slice(chunk_bytes(bytes, &chunk)?); @@ -297,4 +297,47 @@ mod tests { let tiff = TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap(); assert_eq!(rgb_preview(&Tiff::parse(&tiff).unwrap(), &tiff), None); } + + /// storytold/lightcraft#2561: a preview declaring more pixel bytes than the whole file gives none, refused before its buffer is + /// reserved. Its one-row strips all point at the same 24 bytes, so the copy alone would fill it: a few strips + /// (fewer pixel bytes than the file) still make a preview, a tall grid of them (more than the file) does not. + #[test] + fn preview_larger_than_the_file_gives_none() { + let aliased = |rows: u32| { + let mut ifd0 = rgb_ifd(); + ifd0.image = None; + ifd0.set(t::IMAGE_WIDTH, Value::Long(vec![8])); + ifd0.set(t::IMAGE_LENGTH, Value::Long(vec![rows])); + ifd0.set(t::ROWS_PER_STRIP, Value::Long(vec![1])); + ifd0.set(t::STRIP_OFFSETS, Value::Long(vec![0; rows as usize])); + ifd0.set(t::STRIP_BYTE_COUNTS, Value::Long(vec![24; rows as usize])); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() + }; + let small = aliased(4); + assert!(small.len() > 8 * 4 * 3); + let preview = rgb_preview(&Tiff::parse(&small).unwrap(), &small).expect("a preview within the file's size"); + assert_eq!(wrapped(&preview).0, 8); + let tall = aliased(2000); + assert!(tall.len() < 8 * 2000 * 3); + assert_eq!(rgb_preview(&Tiff::parse(&tall).unwrap(), &tall), None); + } + + /// An oversized RGB IFD is passed over, not the end of the search: beside a 2000-row aliased one (more pixel bytes + /// than the file), the file's complete 4 × 3 RGB image is still the preview. + #[test] + fn an_oversized_rgb_ifd_does_not_hide_a_smaller_complete_one() { + let mut huge = rgb_ifd(); + huge.image = None; + huge.set(t::IMAGE_WIDTH, Value::Long(vec![8])); + huge.set(t::IMAGE_LENGTH, Value::Long(vec![2000])); + huge.set(t::ROWS_PER_STRIP, Value::Long(vec![1])); + huge.set(t::STRIP_OFFSETS, Value::Long(vec![0; 2000])); + huge.set(t::STRIP_BYTE_COUNTS, Value::Long(vec![24; 2000])); + let mut ifd0 = rgb_ifd(); + ifd0.add_sub_ifd(huge); + let bytes = TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap(); + assert!(bytes.len() < 8 * 2000 * 3); + let preview = rgb_preview(&Tiff::parse(&bytes).unwrap(), &bytes).expect("the complete 4 x 3 preview"); + assert_eq!(wrapped(&preview), (4, 3, (0..36).collect(), false)); + } } diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index fa4e4a6150..96bf6763f7 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -82,6 +82,16 @@ pub(crate) fn check_image(data: &[u8], info: &ImageInfo, limits: &Limits) -> Res if available.saturating_mul(2048) < total as u64 { return Err(RawError::Corrupt(format!("{available} bytes of image data cannot hold {total} samples"))); } + // Lossless JPEG codes every sample in a bit at least: ljpeg's per-frame check allows 8 samples per entropy byte plus + // 64 bytes of slack, which a frame's own headers (over 32 bytes with its Huffman table) cover twice over, so 16 + // coded samples per byte, and twice that for 4:2:0 YCbCr (half the samples it fills are coded) (storytold/lightcraft#2554). The + // bytes are counted once per chunk that points at them here: tiles may legitimately share one payload (identical + // tiles written once), and each copy is decoded in full, so every reference brings its payload's samples. The + // unique-byte bound above still caps what a small payload shared by a large grid can make the output reserve. + let referenced = chunks.iter().fold(0u64, |sum, c| sum.saturating_add(chunk_bytes(data, c).map_or(0, |b| b.len() as u64))); + if info.compression == comp::JPEG && referenced.saturating_mul(32) < total as u64 { + return Err(RawError::Corrupt(format!("{referenced} bytes of lossless JPEG data cannot hold {total} samples"))); + } Ok(total) } @@ -593,32 +603,6 @@ mod lossy_tests { assert!(matches!(image(&encode(256, 256)), Err(RawError::Corrupt(_)))); } - /// A Deflate tile that is nearly all padding outside the image (a 4096 × 4096 tile holding one column of a - /// 4097-wide picture) is refused before its nominal buffer is inflated; the writer's largest padded tile - /// (2048 × 2048) is within the slack (`dngwrite`'s clamp test). - #[test] - fn a_deflate_tile_that_is_mostly_padding_is_refused() { - let file = vec![0u8; 8 + 8192]; - let info = ImageInfo { - width: 4097, - height: 4096, - bits_per_sample: vec![8], - samples_per_pixel: 1, - compression: comp::ADOBE_DEFLATE, - photometric: 32803, - planar: 1, - predictor: 1, - sample_format: 1, - new_subfile_type: 0, - layout: Layout::Tiles { tile_width: 4096, tile_height: 4096 }, - offsets: vec![8, 8], - byte_counts: vec![8192, 8192], - }; - let chunks = info.chunks(file.len() as u64); - let edge = decode_chunk(&file, &info, &chunks[1], ByteOrder::Little, Packing::Msb, 1, 8, false, &Limits::default()); - assert!(matches!(edge, Err(RawError::Limit(_))), "{:?}", edge.err()); - } - fn strip_info(compression: u16, offsets: Vec, byte_counts: Vec) -> ImageInfo { ImageInfo { width: 4, @@ -852,3 +836,69 @@ mod lossy_tests { )); } } + +#[cfg(test)] +mod budget_tests { + use super::*; + use crate::ljpeg; + use craft_tiff::image::Layout; + use craft_tiff::tags::photometric; + + /// `w`×`h` CFA image in `tile`×`tile` lossless-JPEG tiles that all point at the same `payload` bytes at offset 0. + fn aliased(w: u32, h: u32, tile: u32, payload: u64) -> ImageInfo { + let n = (w.div_ceil(tile) * h.div_ceil(tile)) as usize; + ImageInfo { + width: w, + height: h, + bits_per_sample: vec![14], + samples_per_pixel: 1, + compression: 7, + photometric: photometric::CFA, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: tile, tile_height: tile }, + offsets: vec![0; n], + byte_counts: vec![payload; n], + } + } + + /// storytold/lightcraft#2554: 16 tiles of 256×256 sharing one 1 KiB payload pass the generic 2048-samples-per-byte bound (1 Mi samples + /// from 1 KiB) but no lossless JPEG holds that many samples in those bytes. + #[test] + fn lossless_jpeg_tiles_sharing_a_payload_are_refused() { + let data = vec![0u8; 1024]; + let info = aliased(1024, 1024, 256, 1024); + assert!(matches!(check_image(&data, &info, &Limits::default()), Err(RawError::Corrupt(_)))); + // the same grid declared as Deflate (~2000 samples per byte at most) still passes this check + let deflate = ImageInfo { compression: 8, ..info }; + assert!(check_image(&data, &deflate, &Limits::default()).is_ok()); + } + + /// Tiles may share one payload (a writer storing identical tiles once): each reference decodes its payload in full, + /// so 32 constant 256×256 lossless-JPEG tiles pointing at one tile's bytes decode (header check and full decode), + /// though the shared bytes alone are far fewer than one bit per sample of the image. + #[test] + fn lossless_jpeg_tiles_sharing_a_real_tile_decode() { + let tile = ljpeg::encode(&vec![300u16; 256 * 256], 256, 256, 1, 12, 1, 0); + let info = ImageInfo { bits_per_sample: vec![12], byte_counts: vec![tile.len() as u64; 32], ..aliased(2048, 1024, 256, 0) }; + // one copy of the bytes holds fewer than 32 samples per byte of the whole grid: a unique-byte bound refused it + assert!((tile.len() as u64) * 32 < 2048 * 1024, "{} bytes", tile.len()); + assert!(read_image_in(crate::Mode::Header, &tile, &info, ByteOrder::Little, Packing::Msb, &Limits::default()).is_ok()); + assert_eq!(read_image(&tile, &info, ByteOrder::Little, Packing::Msb, &Limits::default()), Ok(RawData::U16(vec![300; 2048 * 1024]))); + } + + /// The unique-byte bound still caps a large grid of tiles sharing a small payload: 256 tiles of 256×256 (16 Mi + /// samples) referencing the same 8000 bytes pass the per-reference lossless-JPEG bound (2 MB referenced) but those + /// 8000 bytes cannot hold 16 Mi samples, so nothing is reserved. + #[test] + fn a_huge_grid_sharing_a_small_payload_is_still_refused() { + let data = vec![0u8; 8000]; + let info = aliased(4096, 4096, 256, 8000); + for mode in [crate::Mode::Header, crate::Mode::Full] { + let err = read_image_in(mode, &data, &info, ByteOrder::Little, Packing::Msb, &Limits::default()).unwrap_err(); + assert!(matches!(&err, RawError::Corrupt(m) if m.contains("8000 bytes of image data")), "{err:?}"); + } + } +}