diff --git a/apps/photocraft/src/icon_theme.rs b/apps/photocraft/src/icon_theme.rs index 562dcf76e3a..66647cd1db1 100644 --- a/apps/photocraft/src/icon_theme.rs +++ b/apps/photocraft/src/icon_theme.rs @@ -45,21 +45,28 @@ pub fn base_dirs(var: &dyn Fn(&str) -> Option) -> Vec { dirs } -/// One `[section]` of an `index.theme`, as (key, value) pairs. -fn section<'a>(index: &'a str, name: &str) -> Vec<(&'a str, &'a str)> { - let mut inside = false; - let mut pairs = vec![]; +/// Every `[section]` of an `index.theme` as (key, value) pairs, in one pass; the first section +/// of a name wins. (Looking each directory's section up by rescanning the file multiplied its +/// size by the number of directories.) +fn sections(index: &str) -> std::collections::HashMap<&str, Vec<(&str, &str)>> { + let mut all = std::collections::HashMap::new(); + let mut current: Option> = None; + let mut name = ""; for line in index.lines().map(str::trim) { if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { - if inside { - break; + if let Some(done) = current.take() { + all.entry(name).or_insert(done); } - inside = s == name; - } else if inside && let Some((k, v)) = line.split_once('=') { + name = s; + current = Some(vec![]); + } else if let (Some(pairs), Some((k, v))) = (current.as_mut(), line.split_once('=')) { pairs.push((k.trim(), v.trim())); } } - pairs + if let Some(done) = current { + all.entry(name).or_insert(done); + } + all } fn list(value: Option<&str>) -> impl Iterator { @@ -156,13 +163,14 @@ impl IconTheme { // The first index wins; a theme can still be spread over several base directories. let Some(index) = roots.iter().find_map(|r| read_small(&r.join("index.theme"))) else { continue }; let index = String::from_utf8_lossy(&index); - let head = section(&index, "Icon Theme"); + let all = sections(&index); + let head = all.get("Icon Theme").map_or(&[][..], Vec::as_slice); let get = |k: &str| head.iter().find(|(key, _)| *key == k).map(|(_, v)| *v); let mut subdirs: Vec<((i64, i64), &str)> = list(get("Directories")) .chain(list(get("ScaledDirectories"))) .filter(|d| !d.split('/').any(|part| part == ".." || part.is_empty())) .take(MAX_DIRS) - .map(|d| (distance(§ion(&index, d)), d)) + .map(|d| (distance(all.get(d).map_or(&[][..], Vec::as_slice)), d)) .collect(); subdirs.sort_by_key(|(key, _)| *key); // Not checked for existence: a theme lists hundreds, and the search stops at a hit. @@ -193,7 +201,8 @@ impl IconTheme { /// unreadable SVG or an absurd size. pub fn rasterize_mask(svg: &[u8], px: u32) -> Option> { use resvg::{tiny_skia, usvg}; - if !(1..=256).contains(&px) { + // usvg inflates gzip (`.svgz`) input without a decoded-size limit, and icons are plain `.svg`. + if !(1..=256).contains(&px) || svg.starts_with(&[0x1f, 0x8b]) { return None; } // Glyphs are paths: no `` is loaded, so an icon can't make us read another file @@ -287,6 +296,19 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + #[test] + fn sections_are_read_once_and_the_first_of_a_name_wins() { + let all = sections("stray=1\n[A]\nSize=16\n[B]\nSize=22\n[A]\nSize=48\n"); + assert_eq!(all["A"], vec![("Size", "16")]); + assert_eq!(all["B"], vec![("Size", "22")]); + assert!(!all.contains_key("")); + } + + #[test] + fn a_gzip_icon_is_refused() { + assert_eq!(rasterize_mask(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0], 16), None); + } + #[test] fn distance_follows_the_spec() { assert_eq!(distance(&[("Size", "16"), ("Type", "Fixed")]), (0, 1)); diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs index d8e11c44746..0f975c7eee3 100644 --- a/crates/codecs/src/codecs/tiff/decode.rs +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -496,6 +496,104 @@ fn multiband_layout(photometric: u64, has_alpha: bool, gray_alpha: bool) -> Chan } } +const TAG_PREDICTOR: u16 = 317; +const TAG_JPEG_TABLES: u16 = 347; +/// Marker segments looked at before a JPEG chunk's frame header. Real chunks hold a handful +/// (SOI, DRI, SOF, DHT, DQT, SOS); the cap keeps chunks that all point at one long run of +/// segments from costing chunks x segments. +const MAX_JPEG_CHUNK_MARKERS: usize = 256; + +/// Fill bytes (`0xFF` runs before a marker) all JPEG chunks of a TIFF may scan together. Each +/// distinct chunk offset rescans its own run, so this bounds the total work. +const MAX_JPEG_FILL_BYTES: usize = 1 << 24; + +/// The frame header (width, height, components) of a JPEG stream: `Ok(None)` when it has none +/// before its first scan, `Err` when more than [`MAX_JPEG_CHUNK_MARKERS`] segments come first. +fn jpeg_frame(b: &[u8], fill: &mut usize) -> Result, CodecError> { + if b.get(..2) != Some(&[0xFF, 0xD8][..]) { + return Ok(None); + } + jpeg_frame_from(b, 2, fill) +} + +/// [`jpeg_frame`] from byte `start` on, with no SOI check. `fill` counts the fill bytes scanned. +fn jpeg_frame_from(b: &[u8], start: usize, fill: &mut usize) -> Result, CodecError> { + let be16 = |at: usize| b.get(at..at + 2).and_then(|v| <[u8; 2]>::try_from(v).ok()).map(|v| usize::from(u16::from_be_bytes(v))); + let mut i = start; + for _ in 0..MAX_JPEG_CHUNK_MARKERS { + while b.get(i) == Some(&0xFF) && b.get(i + 1) == Some(&0xFF) { + i += 1; + *fill += 1; + if *fill > MAX_JPEG_FILL_BYTES { + return Err(CodecError::LimitExceeded("JPEG strips or tiles scan too many fill bytes".into())); + } + } + if b.get(i) != Some(&0xFF) { + return Ok(None); + } + let Some(&code) = b.get(i + 1) else { return Ok(None) }; + match code { + 0xC0..=0xCF if !matches!(code, 0xC4 | 0xC8 | 0xCC) => { + let frame = be16(i + 5).zip(be16(i + 7)).zip(b.get(i + 9)); + return Ok(frame.map(|((h, w), &nc)| (w, h, usize::from(nc)))); + } + 0xD9 | 0xDA => return Ok(None), + 0x01 | 0xD0..=0xD8 => i += 2, + _ => match be16(i + 2) { + Some(len) => i += 2 + len, + None => return Ok(None), + }, + } + } + Err(err("a JPEG strip or tile has too many marker segments before its frame header")) +} + +/// Refuses JPEG strips or tiles whose embedded frame is larger than the strip or tile +/// (`nominal`, unclipped) or whose decoded frame exceeds `cap` bytes. Chunks sharing an offset +/// are checked once. +fn check_jpeg_chunks( + f: &File<'_>, + offsets: &ifd::Entry, + sizes: &ifd::Entry, + expected: u64, + tables: Option<&[u8]>, + nominal: (usize, usize), + cap: usize, +) -> Result<(), CodecError> { + // The list below holds 16 bytes per chunk; bound it by the scratch cap, not only by the file size. + if expected.saturating_mul(16) > cap as u64 { + return Err(CodecError::LimitExceeded(format!("{expected} JPEG strips or tiles"))); + } + // Reserve exactly the budgeted length: collecting from filter_map could over-allocate past `cap`. + let mut chunks: Vec<(u64, u64)> = Vec::with_capacity(expected as usize); + chunks.extend((0..expected).filter_map(|i| Some((f.uint(offsets, i)?, f.uint(sizes, i)?)))); + chunks.sort_unstable(); + // Entries sharing an offset but not a byte count are different chunks: check each one. + chunks.dedup(); + let len = f.b.len() as u64; + let mut fill = 0; + for (at, n) in chunks { + let end = at.saturating_add(n).min(len); + let Some(data) = usize::try_from(at).ok().zip(usize::try_from(end).ok()).and_then(|(a, e)| f.b.get(a..e)) else { continue }; + let mut frame = match jpeg_frame(data, &mut fill)? { + Some(frame) => Some(frame), + None => tables.map(|t| jpeg_frame(t, &mut fill)).transpose()?.flatten(), + }; + // Without SOI, the tiff crate drops the chunk's first two bytes, so a frame at offset 2 is decoded. + if frame.is_none() && data.get(..2) != Some(&[0xFF, 0xD8][..]) { + frame = jpeg_frame_from(data, 2, &mut fill)?; + } + let Some((w, h, nc)) = frame else { continue }; + if w > nominal.0 || h > nominal.1 { + return Err(err(format!("a {w}x{h} JPEG frame in a {}x{} strip or tile", nominal.0, nominal.1))); + } + if w.checked_mul(h).and_then(|px| px.checked_mul(nc.max(1))).is_none_or(|bytes| bytes > cap) { + return Err(CodecError::LimitExceeded(format!("a {w}x{h} JPEG strip or tile"))); + } + } + Ok(()) +} + /// The chunk tables must match the geometry. Checked in 64 bits, before the `tiff` crate does /// the same arithmetic in narrower types. fn check_chunk_tables(f: &File<'_>, dir: &Ifd, (w, h): (u32, u32), spp: u64, planar: bool, tiled: bool) -> Result<(u64, u64, u64), CodecError> { @@ -673,6 +771,14 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result = dir.entries.iter().map(|e| e.tag).filter(|t| ifd::STRUCTURAL_TAGS.contains(t)).collect(); + structural.sort_unstable(); + if let Some(w) = structural.windows(2).find(|w| w[0] == w[1]) { + return Err(err(format!("tag {} appears more than once", w[0]))); + } let need = |tag: u16, name: &str| f.tag_uint(dir, tag).ok_or_else(|| err(format!("missing or unreadable {name}"))); let w = u32::try_from(need(ifd::TAG_WIDTH, "ImageWidth")?).map_err(|_| err("ImageWidth out of range"))?; let h = u32::try_from(need(ifd::TAG_HEIGHT, "ImageLength")?).map_err(|_| err("ImageLength out of range"))?; @@ -844,6 +950,25 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result scratch_cap) { + return Err(CodecError::LimitExceeded(format!("a {cw} sample wide predicted tile row"))); + } + } + // JPEG-compressed chunks (compression 7) are decoded by the `tiff` crate into a whole JPEG + // image sized by the embedded frame header, with no limits, before the chunk's bytes are + // taken. The frame must fit the strip or tile it stands for, as libtiff requires, and the + // scratch cap. + if compression == 7 { + let tables = dir.get(TAG_JPEG_TABLES).and_then(|e| f.data(e)); + let (nominal_w, nominal_h) = + (cw, if tiled { ch } else { f.tag_uint(dir, ifd::TAG_ROWS_PER_STRIP).and_then(|r| usize::try_from(r).ok()).unwrap_or(hu) }); + check_jpeg_chunks(f, offsets, sizes, expected, tables, (nominal_w, nominal_h), scratch_cap)?; + } // One chunk as the decoder actually reads it: a tile keeps its declared size at an edge, // which can be more than the clipped image bytes above. let scratch_bytes = cw.saturating_mul(ch).saturating_mul(chunk_spp).saturating_mul(src.bytes()); diff --git a/crates/codecs/tests/it/tiff_regressions.rs b/crates/codecs/tests/it/tiff_regressions.rs index 8fcb1e570ca..5c8c09ce1a4 100644 --- a/crates/codecs/tests/it/tiff_regressions.rs +++ b/crates/codecs/tests/it/tiff_regressions.rs @@ -174,3 +174,39 @@ fn default_tiff_is_baseline() { assert_eq!(decode(&bytes).expect("decode").data(), img.data(), "{layout:?}: round trip"); } } + +fn refusal(bytes: &[u8]) -> String { + match decode(bytes) { + Err(e) => e.to_string(), + Ok(i) => panic!("decoded a {}x{} image", i.width(), i.height()), + } +} + +#[test] +fn a_repeated_structural_tag_is_refused() { + // SamplesPerPixel 1 first (what the directory checks read), 64 last (what the backend reads). + let dir = strips(4, 1, 8, 1, 1, 1, &[1, 2, 3, 4]).tag(277, SHORT, &[64]); + let bytes = build(true, false, &[dir], &[0]).bytes; + let e = refusal(&bytes); + assert!(e.contains("277 appears more than once"), "{e}"); +} + +#[test] +fn a_jpeg_strip_larger_than_its_strip_is_refused() { + let mut jpeg = Vec::new(); + jpeg_encoder::Encoder::new(&mut jpeg, 95).encode(&[100u8; 64 * 64], 64, 64, jpeg_encoder::ColorType::Luma).expect("encode the JPEG strip"); + let mut dir = with_compression(strips(16, 16, 8, 1, 1, 16, &[0; 256]), 7); + dir.chunks = vec![jpeg]; + let e = refusal(&build(true, false, &[dir], &[0]).bytes); + assert!(e.contains("64x64 JPEG frame in a 16x16 strip"), "{e}"); +} + +#[test] +fn a_float_predicted_tile_row_wider_than_the_scratch_cap_is_refused() { + // A 16x16 32-bit float image in one tile 2^25 samples wide: the floating-point predictor + // would make the backend allocate a 128 MiB row for it. + let mut dir = Dir { entries: base(16, 16, 32, 1, 1), chunks: vec![vec![0; 64]], tiled: true }; + dir = with_compression(dir, 8).tag(317, SHORT, &[3]).tag(322, LONG, &[1 << 25]).tag(323, LONG, &[16]).tag(339, SHORT, &[3]); + let e = refusal(&build(true, false, &[dir], &[0]).bytes); + assert!(e.contains("predicted tile row"), "{e}"); +} diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index b3411b7a0bb..21d9f07e69d 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -31,6 +31,9 @@ const MAX_AIRBRUSH_DABS_PER_SEGMENT: usize = 512; /// Most steps one distance-spaced segment emits: two far-apart points at a quarter-pixel spacing /// would otherwise be billions of steps, all buffered before the first is drawn. const MAX_DISTANCE_STEPS_PER_SEGMENT: usize = 1 << 20; +/// Most steps one stroke emits in total, over all its segments and spacing modes; later ones are +/// dropped (a real stroke is orders of magnitude shorter). +const MAX_STEPS_PER_STROKE: u64 = 1 << 21; /// The dab centre of the pixel-grid cell holding `v` (see [`PathWalker::pixel_grid`]): the /// pixel's centre for `offset` 0.5, the nearest pixel corner for 0. A value within rounding @@ -339,6 +342,9 @@ impl PathWalker { } fn emit(&mut self, point: StrokePoint, out: &mut impl FnMut(StepInput)) { + if self.step >= MAX_STEPS_PER_STROKE { + return; + } if let Some(g) = self.grid { self.cell = Some((grid_cell(point.x, g), grid_cell(point.y, g))); } @@ -373,7 +379,7 @@ impl PathWalker { None => { if !self.grid.is_some_and(|g| self.grid_steps(&a, &p, g, out)) { let mut emitted = 0usize; - while self.next_at <= len + 1e-9 && emitted < MAX_DISTANCE_STEPS_PER_SEGMENT { + while self.next_at <= len + 1e-9 && emitted < MAX_DISTANCE_STEPS_PER_SEGMENT && self.step < MAX_STEPS_PER_STROKE { let q = lerp_pt(&a, &p, (self.next_at / len).min(1.0)); self.emit(q, out); self.next_at += step_len(&q).max(0.25); @@ -389,7 +395,7 @@ impl PathWalker { self.speed_acc += dt; let max_n = (len / MIN_SPEED_STEP).ceil().max(1.0) as usize; let mut n = 0; - while self.speed_acc >= iv && n < max_n { + while self.speed_acc >= iv && n < max_n && self.step < MAX_STEPS_PER_STROKE { self.speed_acc -= iv; let f = ((dt - self.speed_acc) / dt).clamp(0.0, 1.0); self.emit(lerp_pt(&a, &p, f), out); @@ -871,6 +877,27 @@ mod walker_budget_tests { assert!(steps.get() > before && steps.get() - before <= 11, "{} more steps", steps.get() - before); } + #[test] + fn a_stroke_of_many_far_segments_stops_at_the_total_cap() { + let steps = std::cell::Cell::new(0u64); + let mut count = |_: StepInput| steps.set(steps.get() + 1); + let mut walker = PathWalker::new(None); + let quarter = |_: &StrokePoint| 0.25; + walker.push(StrokePoint::new(0.0, 0.0, 1.0), &quarter, &mut count); + for i in 1..=8 { + walker.push(StrokePoint::new(1.0e9 * f64::from(i), 0.0, 1.0), &quarter, &mut count); + } + assert!(steps.get() <= MAX_STEPS_PER_STROKE, "{}", steps.get()); + // Speed spacing over absurd timestamps stops too, without iterating billions of times. + let mut speed = PathWalker::new(None).speed_spacing(1.0); + speed.push(StrokePoint::new(0.0, 0.0, 1.0), &quarter, &mut count); + let mut far = StrokePoint::new(1.0e9, 0.0, 1.0); + far.time = 1.0e12; + let before = steps.get(); + speed.push(far, &quarter, &mut count); + assert!(steps.get() - before <= MAX_STEPS_PER_STROKE, "{}", steps.get() - before); + } + #[test] fn a_segment_ending_at_the_cap_keeps_its_carry_over() { let steps = std::cell::Cell::new(0usize); diff --git a/crates/text/src/cjk.rs b/crates/text/src/cjk.rs index 1fe0f12534a..b8b1a8041ce 100644 --- a/crates/text/src/cjk.rs +++ b/crates/text/src/cjk.rs @@ -577,7 +577,12 @@ fn family_name_matches(font: &skrifa::FontRef<'_>, family: &str, budget: &mut us fn face_tables_are_readable(font: &skrifa::raw::FontRef<'_>) -> bool { let directory = font.table_directory(); let records = directory.table_records(); - !records.is_empty() && records.len() == usize::from(directory.num_tables()) && records.iter().all(|record| font.table_data(record.tag()).is_some()) + // Each record's own range against the file, in one pass: `table_data(tag)` searches the + // (unsorted) directory per tag, which is quadratic in the table count. + let len = u64::try_from(font.data().len()).unwrap_or(u64::MAX); + !records.is_empty() + && records.len() == usize::from(directory.num_tables()) + && records.iter().all(|record| u64::from(record.offset()) + u64::from(record.length()) <= len) } /// Whether face `index` of a font file or collection has a complete, in-bounds table directory. @@ -604,7 +609,7 @@ pub fn font_file_is_readable(bytes: &[u8]) -> bool { match FileRef::new(bytes) { Ok(FileRef::Font(font)) => face_tables_are_readable(&font), - Ok(FileRef::Collection(faces)) => faces.iter().any(|face| face.is_ok_and(|font| face_tables_are_readable(&font))), + Ok(FileRef::Collection(faces)) => faces.iter().take(MAX_COLLECTION_FACES).any(|face| face.is_ok_and(|font| face_tables_are_readable(&font))), Err(_) => false, } } @@ -885,6 +890,28 @@ mod tests { assert!(!font_file_is_readable(&missing_table), "a complete directory cannot point outside the file"); } + #[test] + fn a_directory_of_many_tables_is_validated_in_one_pass() { + // 60000 distinct tags, all in range: a per-tag directory search would be quadratic. + let n = 60_000u32; + let mut font = 0x0001_0000u32.to_be_bytes().to_vec(); + font.extend((n as u16).to_be_bytes()); + font.extend([0u8; 6]); + let data_at = 12 + 16 * n; + for i in 0..n { + font.extend([b'a' + (i / 26 / 26 / 26 % 26) as u8, b'a' + (i / 26 / 26 % 26) as u8, b'a' + (i / 26 % 26) as u8, b'a' + (i % 26) as u8]); + font.extend(0u32.to_be_bytes()); + font.extend(data_at.to_be_bytes()); + font.extend(4u32.to_be_bytes()); + } + font.extend([0u8; 4]); + let start = std::time::Instant::now(); + assert!(font_file_is_readable(&font)); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); + font[20..24].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(!font_file_is_readable(&font)); + } + /// A readable collection can contain a malformed non-selected face, so the file-level check /// must not stand in for validating the face a caller selects. The selected face keeps a valid /// `cmap` (coverage succeeds) and `name` (family lookup succeeds) while another table points diff --git a/crates/ui-egui/src/tools/vector_ui/pen_enter_deselects_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_enter_deselects_tests.rs index 589a2b5e07a..47bc54d80c3 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_enter_deselects_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_enter_deselects_tests.rs @@ -35,7 +35,7 @@ fn listed(h: &Harness<'static, PhotocraftApp>) -> bool { } fn make_buttons_enabled(h: &Harness<'static, PhotocraftApp>) -> [bool; 2] { - ["Make Selection", "Make Shape"].map(|label| !h.get_by_label(label).accesskit_node().is_disabled()) + ["Selection…", "Shape"].map(|label| !h.get_by_label(label).accesskit_node().is_disabled()) } #[test] diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 4408808642f..866c354c299 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -386,7 +386,20 @@ fn fetch_pngsuite() -> Result<(), String> { PNGSUITE_MANIFEST, |archive| { let mut curl = Command::new("curl"); - curl.args(["-fsSL", "--retry", "3", "--max-filesize", &PNGSUITE_MAX_ARCHIVE_BYTES.to_string(), "-A", USER_AGENT, "-o", "-", PNGSUITE_URL]); + curl.args([ + "-fsSL", + "--proto-redir", + "=https", + "--retry", + "3", + "--max-filesize", + &PNGSUITE_MAX_ARCHIVE_BYTES.to_string(), + "-A", + USER_AGENT, + "-o", + "-", + PNGSUITE_URL, + ]); download_pngsuite(curl, archive) }, |archive, files| {