authoravatarclover caruso<git@paperclover.net>2026-12-01 17:02:48-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 17:13:06-08:00
loga791d487f17137e2647e72ee5a0841e504575f7c
treebc0f7653ca9793fb3cd40ef506ff738debb3f7c5
parent53b5fee5c10ef9042ab298c0666fcc4786fdab77
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): wave 29A media/readback/audio/av_decode hardening


4 files changed, 257 insertions(+), 71 deletions(-)

crates/engine/src/audio.rs+90-13
......@@ -4,7 +4,7 @@
44use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
55use cpal::{FromSample, Sample, SampleFormat, Stream};
66use std::fs::File;
7use std::io::{Cursor, ErrorKind};
7use std::io::ErrorKind;
88use std::path::{Path, PathBuf};
99use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
1010use std::sync::{Arc, Mutex};
......@@ -62,6 +62,14 @@ fn decode_wav_stereo<const N: usize>(
6262 }
6363}
6464
65fn alloc_wav_stereo_samples(total_frames: usize) -> Option<Vec<f32>> {
66 let sample_count = total_frames.checked_mul(2)?;
67 let mut stereo_samples = Vec::new();
68 stereo_samples.try_reserve_exact(sample_count).ok()?;
69 stereo_samples.resize(sample_count, 0.0_f32);
70 Some(stereo_samples)
71}
72
6573/// Fast contiguous WAV loader for standard 1/2-channel PCM & IEEE-float RIFF/WAVE files.
6674/// Returns `Ok(None)` for non-WAV, >2-channel, RF64, compressed, or unusual files so
6775/// callers fall back cleanly to `symphonia`.
......@@ -70,6 +78,13 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
7078 return Ok(None);
7179 }
7280
81 let riff_size = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
82 let scan_end = if riff_size >= 4 {
83 bytes.len().min(8usize.saturating_add(riff_size as usize))
84 } else {
85 bytes.len()
86 };
87
7388 const WAVE_FORMAT_PCM: u16 = 0x0001;
7489 const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003;
7590 const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
......@@ -86,7 +101,7 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
86101 let mut data_slice: Option<&[u8]> = None;
87102 let mut pos = 12usize;
88103
89 while pos + 8 <= bytes.len() {
104 while scan_end.saturating_sub(pos) >= 8 {
90105 let chunk_id = &bytes[pos..pos + 4];
91106 let chunk_size = u32::from_le_bytes([
92107 bytes[pos + 4],
......@@ -98,7 +113,7 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
98113 let Some(payload_end) = payload_start.checked_add(chunk_size) else {
99114 return Ok(None);
100115 };
101 if payload_end > bytes.len() {
116 if payload_end > scan_end {
102117 return Ok(None);
103118 }
104119 let payload = &bytes[payload_start..payload_end];
......@@ -183,7 +198,10 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
183198 data_slice = Some(payload);
184199 }
185200
186 pos = payload_end + (chunk_size & 1);
201 let Some(next_pos) = payload_end.checked_add(chunk_size & 1) else {
202 return Ok(None);
203 };
204 pos = next_pos;
187205 }
188206
189207 let (Some((channels, sample_rate, block_align, sample_fmt)), Some(data)) = (fmt, data_slice)
......@@ -195,7 +213,9 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
195213 let total_frames = data.len() / block_align;
196214 let usable_bytes = total_frames * block_align;
197215 let data = &data[..usable_bytes];
198 let mut stereo_samples = vec![0.0_f32; total_frames * 2];
216 let Some(mut stereo_samples) = alloc_wav_stereo_samples(total_frames) else {
217 return Ok(None);
218 };
199219
200220 match (channels, sample_fmt) {
201221 (1, WavSampleFormat::U8) => {
......@@ -286,24 +306,29 @@ impl AudioTrack {
286306 /// Decodes an audio file (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`, `.aac`) into
287307 /// interleaved stereo `f32` samples.
288308 pub fn load(path: impl AsRef<Path>) -> Result<Self, String> {
309 const MAX_FAST_WAV_BYTES: u64 = 256 * 1024 * 1024;
289310 let path_ref = path.as_ref();
290311 let is_wav = path_ref
291312 .extension()
292313 .and_then(|e| e.to_str())
293314 .is_some_and(|ext| ext.eq_ignore_ascii_case("wav"));
294315
295 let mss = if is_wav {
316 if is_wav
317 && std::fs::metadata(path_ref)
318 .map(|m| m.len())
319 .is_ok_and(|len| len <= MAX_FAST_WAV_BYTES)
320 {
296321 let bytes = std::fs::read(path_ref)
297322 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;
298323 if let Some(track) = try_load_wav_fast(path_ref, &bytes)? {
299324 return Ok(track);
300325 }
301 MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default())
302 } else {
303 let file = File::open(path_ref)
304 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;
305 MediaSourceStream::new(Box::new(file), Default::default())
306 };
326 // Drop `bytes` before opening `File` so we stream instead of holding raw bytes in RAM.
327 }
328
329 let file = File::open(path_ref)
330 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;
331 let mss = MediaSourceStream::new(Box::new(file), Default::default());
307332 Self::load_via_symphonia(path_ref, mss)
308333 }
309334
......@@ -1243,7 +1268,7 @@ mod tests {
12431268 let fast = try_load_wav_fast(&p, &bytes)
12441269 .unwrap_or_else(|e| panic!("{label}: {e}"))
12451270 .unwrap_or_else(|| panic!("{label}: expected fast path"));
1246 let mss = MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default());
1271 let mss = MediaSourceStream::new(Box::new(std::io::Cursor::new(bytes)), Default::default());
12471272 let ref_track = AudioTrack::load_via_symphonia(&p, mss).expect("symphonia fallback");
12481273 assert_eq!(fast.sample_rate, ref_track.sample_rate, "{label} sr");
12491274 assert_eq!(fast.channels, ref_track.channels, "{label} ch");
......@@ -1255,4 +1280,56 @@ mod tests {
12551280 assert_eq!(got_peaks, exp_peaks, "{label} peaks mismatch");
12561281 }
12571282 }
1283
1284 #[test]
1285 fn wav_fast_ignores_trailing_garbage_past_riff_size_and_rejects_overflow() {
1286 // Build a valid minimal mono 16-bit PCM WAV with 4 frames, then append trailing garbage
1287 // past `8 + riff_size` (including a bogus second `data` chunk) and ensure it is ignored.
1288 let data_bytes: Vec<u8> = [0i16, 16384, -16384, 32767]
1289 .into_iter()
1290 .flat_map(|s| s.to_le_bytes())
1291 .collect();
1292 let riff_size = (36 + data_bytes.len()) as u32;
1293 let mut wav = Vec::new();
1294 wav.extend_from_slice(b"RIFF");
1295 wav.extend_from_slice(&riff_size.to_le_bytes());
1296 wav.extend_from_slice(b"WAVEfmt ");
1297 wav.extend_from_slice(&16u32.to_le_bytes());
1298 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1299 wav.extend_from_slice(&1u16.to_le_bytes()); // mono
1300 wav.extend_from_slice(&48000u32.to_le_bytes());
1301 wav.extend_from_slice(&(48000u32 * 2).to_le_bytes());
1302 wav.extend_from_slice(&2u16.to_le_bytes());
1303 wav.extend_from_slice(&16u16.to_le_bytes());
1304 wav.extend_from_slice(b"data");
1305 wav.extend_from_slice(&(data_bytes.len() as u32).to_le_bytes());
1306 wav.extend_from_slice(&data_bytes);
1307
1308 let clean = try_load_wav_fast(Path::new("clean.wav"), &wav)
1309 .expect("clean ok")
1310 .expect("clean fast");
1311
1312 let mut with_trailing = wav.clone();
1313 with_trailing.extend_from_slice(b"data\xff\xff\xff\xffTRAILING_GARBAGE");
1314 let parsed = try_load_wav_fast(Path::new("trailing.wav"), &with_trailing)
1315 .expect("trailing ok")
1316 .expect("trailing fast should ignore bytes past riff_size");
1317 assert_eq!(parsed.samples, clean.samples);
1318 assert_eq!(parsed.sample_rate, 48000);
1319
1320 // Huge `data` chunk size in header must fall back cleanly (`Ok(None)`), never panic.
1321 let mut huge_chunk = wav.clone();
1322 let data_size_offset = 40;
1323 huge_chunk[data_size_offset..data_size_offset + 4]
1324 .copy_from_slice(&u32::MAX.to_le_bytes());
1325 assert!(
1326 try_load_wav_fast(Path::new("huge.wav"), &huge_chunk)
1327 .expect("huge chunk ok")
1328 .is_none()
1329 );
1330
1331 // `total_frames.checked_mul(2)` overflow and oversized reservation must return `None`.
1332 assert!(alloc_wav_stereo_samples(usize::MAX / 2 + 1).is_none());
1333 assert!(alloc_wav_stereo_samples(usize::MAX / 4).is_none());
1334 }
12581335}
crates/engine/src/av_decode.m+7-2
......@@ -30,6 +30,7 @@
3030@property(nonatomic, assign) int64_t lastFrameIdx;
3131@property(nonatomic, strong) NSMutableData *lastFrameRgba;
3232@property(nonatomic, assign) BOOL hasLastFrame;
33@property(nonatomic, assign) BOOL lastFrameIsEof;
3334@end
3435
3536@implementation AvVideoDecoderObj
......@@ -414,6 +415,7 @@ AvVideoDecoder *av_video_open(
414415 obj.lastFrameIdx = -1;
415416 obj.lastFrameRgba = nil;
416417 obj.hasLastFrame = NO;
418 obj.lastFrameIsEof = NO;
417419
418420 // Verify AVAssetReader can actually open and decode this asset/codec.
419421 if (![obj openReaderAtSeconds:0.0]) {
......@@ -515,7 +517,7 @@ int av_video_decode_frame(
515517 // If requesting a frame past EOF (including sequential advance stepping past EOF or
516518 // container duration overestimating the last video sample by > 4 frames), retry from
517519 // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp.
518 if (!chosen && !obj.hasLastFrame && frame_idx > 0) {
520 if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) {
519521 double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts;
520522 double fallbackSec = fmax(0.0, endAnchor - 1.0);
521523 if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) {
......@@ -551,13 +553,16 @@ int av_video_decode_frame(
551553 CFRelease(chosen);
552554
553555 if (ok) {
554 if (hitEof || obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) {
556 if (hitEof || (!obj.lastFrameIsEof && (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4))) {
555557 if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) {
556558 obj.lastFrameRgba = [NSMutableData dataWithLength:required];
557559 }
558560 if (obj.lastFrameRgba.length >= required) {
559561 memcpy(obj.lastFrameRgba.mutableBytes, out_rgba, required);
560562 obj.hasLastFrame = YES;
563 if (hitEof) {
564 obj.lastFrameIsEof = YES;
565 }
561566 }
562567 }
563568 obj.lastFrameIdx = frame_idx;
crates/engine/src/eval/dispatch.rs+20-4
......@@ -83,15 +83,31 @@ impl PendingReadback {
8383 map_res?;
8484 let slice = self.buf.slice(..self.required_bytes);
8585 let data = slice.get_mapped_range()?;
86 let total_bytes = (self.width * self.height * 4) as usize;
86 let total_bytes = (self.width as usize)
87 .checked_mul(self.height as usize)
88 .and_then(|n| n.checked_mul(4))
89 .ok_or("readback buffer size overflow")?;
8790 dst.clear();
8891 dst.reserve(total_bytes);
8992 if self.padded_bpr == self.unpadded_bpr {
90 dst.extend_from_slice(&data[..total_bytes]);
93 let src = data
94 .get(..total_bytes)
95 .ok_or("readback mapped buffer smaller than expected")?;
96 dst.extend_from_slice(src);
9197 } else {
98 let padded_bpr = self.padded_bpr as usize;
99 let unpadded_bpr = self.unpadded_bpr as usize;
92100 for row in 0..self.height as usize {
93 let start = row * self.padded_bpr as usize;
94 dst.extend_from_slice(&data[start..start + self.unpadded_bpr as usize]);
101 let start = row
102 .checked_mul(padded_bpr)
103 .ok_or("readback row offset overflow")?;
104 let end = start
105 .checked_add(unpadded_bpr)
106 .ok_or("readback row end overflow")?;
107 let src = data
108 .get(start..end)
109 .ok_or("readback mapped row out of bounds")?;
110 dst.extend_from_slice(src);
95111 }
96112 }
97113 drop(data);
crates/engine/src/media.rs+140-52
......@@ -134,9 +134,17 @@ fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 {
134134 ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8
135135}
136136
137const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024;
138
139enum PngDecodeOutcome {
140 Decoded(([u32; 2], Vec<u8>, bool)),
141 Fallback,
142 Reject,
143}
144
137145fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(
138146 reader: &mut png::Reader<R>,
139 w: u32,
147 line_size: usize,
140148 out_len: usize,
141149 row_out_bytes: usize,
142150 mut convert_row: F,
......@@ -144,9 +152,12 @@ fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(
144152where
145153 F: FnMut(&[u8], &mut [u8]),
146154{
147 let mut rgba = vec![0u8; out_len];
148 let line_size = reader.output_line_size(w)?;
149 let mut row_buf = vec![0u8; line_size];
155 let mut rgba = Vec::new();
156 rgba.try_reserve_exact(out_len).ok()?;
157 rgba.resize(out_len, 0);
158 let mut row_buf = Vec::new();
159 row_buf.try_reserve_exact(line_size).ok()?;
160 row_buf.resize(line_size, 0);
150161 for dst_row in rgba.chunks_exact_mut(row_out_bytes) {
151162 reader.read_row(&mut row_buf).ok()??;
152163 convert_row(&row_buf, dst_row);
......@@ -155,79 +166,108 @@ where
155166}
156167
157168/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit.
158/// Returns `None` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the
159/// caller falls back cleanly to `image::load_from_memory`.
160fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
169/// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the
170/// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or
171/// oversized PNGs so callers fail immediately without double-decoding or OOM.
172fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome {
161173 const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
162174 if !bytes.starts_with(&PNG_SIGNATURE) {
163 return None;
175 return PngDecodeOutcome::Fallback;
164176 }
165177
166178 let mut decoder = png::Decoder::new_with_limits(
167179 std::io::Cursor::new(bytes),
168180 png::Limits {
169 bytes: 512 * 1024 * 1024,
181 bytes: MAX_PNG_OUTPUT_BYTES,
170182 },
171183 );
172184 decoder.set_ignore_text_chunk(true);
173185 decoder.set_transformations(png::Transformations::EXPAND);
174186
175 let mut reader = decoder.read_info().ok()?;
187 let Ok(mut reader) = decoder.read_info() else {
188 return PngDecodeOutcome::Reject;
189 };
176190 let info = reader.info();
191 let (w, h) = info.size();
192 if w == 0 || h == 0 {
193 return PngDecodeOutcome::Reject;
194 }
195
196 let Some(pixel_count) = (w as usize).checked_mul(h as usize) else {
197 return PngDecodeOutcome::Reject;
198 };
199 let Some(out_len) = pixel_count.checked_mul(4) else {
200 return PngDecodeOutcome::Reject;
201 };
202 if out_len > MAX_PNG_OUTPUT_BYTES {
203 return PngDecodeOutcome::Reject;
204 }
205
177206 if info.interlaced
178207 || info.icc_profile.is_some()
179208 || info.animation_control.is_some()
180209 || info.frame_control.is_some()
181210 {
182 return None;
183 }
184 let (w, h) = info.size();
185 if w == 0 || h == 0 {
186 return None;
211 return PngDecodeOutcome::Fallback;
187212 }
188213
189214 let (color_type, bit_depth) = reader.output_color_type();
190 let pixel_count = (w as usize).checked_mul(h as usize)?;
191 let out_len = pixel_count.checked_mul(4)?;
192 let row_out_bytes = (w as usize).checked_mul(4)?;
215 let Some(row_out_bytes) = (w as usize).checked_mul(4) else {
216 return PngDecodeOutcome::Reject;
217 };
218 let Some(line_size) = reader.output_line_size(w) else {
219 return PngDecodeOutcome::Reject;
220 };
193221
194222 match (color_type, bit_depth) {
195223 (png::ColorType::Rgba, png::BitDepth::Eight) => {
196 let mut rgba = vec![0u8; out_len];
197 reader.next_frame(&mut rgba).ok()?;
198 Some(([w, h], rgba, true))
224 let mut rgba = Vec::new();
225 if rgba.try_reserve_exact(out_len).is_err() {
226 return PngDecodeOutcome::Reject;
227 }
228 rgba.resize(out_len, 0);
229 if reader.next_frame(&mut rgba).is_err() {
230 return PngDecodeOutcome::Reject;
231 }
232 PngDecodeOutcome::Decoded(([w, h], rgba, true))
199233 }
200234 (png::ColorType::Rgb, png::BitDepth::Eight) => {
201 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
235 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
202236 let (src_chunks, _) = src.as_chunks::<3>();
203237 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
204238 for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) {
205239 *dst_px = [r, g, b, 255];
206240 }
207 })?;
208 Some(([w, h], rgba, false))
241 }) else {
242 return PngDecodeOutcome::Reject;
243 };
244 PngDecodeOutcome::Decoded(([w, h], rgba, false))
209245 }
210246 (png::ColorType::Grayscale, png::BitDepth::Eight) => {
211 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
247 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
212248 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
213249 for (&g, dst_px) in src.iter().zip(dst_chunks) {
214250 *dst_px = [g, g, g, 255];
215251 }
216 })?;
217 Some(([w, h], rgba, false))
252 }) else {
253 return PngDecodeOutcome::Reject;
254 };
255 PngDecodeOutcome::Decoded(([w, h], rgba, false))
218256 }
219257 (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => {
220 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
258 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
221259 let (src_chunks, _) = src.as_chunks::<2>();
222260 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
223261 for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) {
224262 *dst_px = [g, g, g, a];
225263 }
226 })?;
227 Some(([w, h], rgba, true))
264 }) else {
265 return PngDecodeOutcome::Reject;
266 };
267 PngDecodeOutcome::Decoded(([w, h], rgba, true))
228268 }
229269 (png::ColorType::Rgba, png::BitDepth::Sixteen) => {
230 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
270 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
231271 let (src_chunks, _) = src.as_chunks::<8>();
232272 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
233273 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
......@@ -238,11 +278,13 @@ fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
238278 u16_be_to_u8_rounded(s[6], s[7]),
239279 ];
240280 }
241 })?;
242 Some(([w, h], rgba, true))
281 }) else {
282 return PngDecodeOutcome::Reject;
283 };
284 PngDecodeOutcome::Decoded(([w, h], rgba, true))
243285 }
244286 (png::ColorType::Rgb, png::BitDepth::Sixteen) => {
245 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
287 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
246288 let (src_chunks, _) = src.as_chunks::<6>();
247289 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
248290 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
......@@ -253,38 +295,46 @@ fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
253295 255,
254296 ];
255297 }
256 })?;
257 Some(([w, h], rgba, false))
298 }) else {
299 return PngDecodeOutcome::Reject;
300 };
301 PngDecodeOutcome::Decoded(([w, h], rgba, false))
258302 }
259303 (png::ColorType::Grayscale, png::BitDepth::Sixteen) => {
260 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
304 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
261305 let (src_chunks, _) = src.as_chunks::<2>();
262306 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
263307 for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) {
264308 let g = u16_be_to_u8_rounded(hi, lo);
265309 *dst_px = [g, g, g, 255];
266310 }
267 })?;
268 Some(([w, h], rgba, false))
311 }) else {
312 return PngDecodeOutcome::Reject;
313 };
314 PngDecodeOutcome::Decoded(([w, h], rgba, false))
269315 }
270316 (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => {
271 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {
317 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
272318 let (src_chunks, _) = src.as_chunks::<4>();
273319 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
274320 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
275321 let g = u16_be_to_u8_rounded(s[0], s[1]);
276322 *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])];
277323 }
278 })?;
279 Some(([w, h], rgba, true))
324 }) else {
325 return PngDecodeOutcome::Reject;
326 };
327 PngDecodeOutcome::Decoded(([w, h], rgba, true))
280328 }
281 _ => None,
329 _ => PngDecodeOutcome::Fallback,
282330 }
283331}
284332
285333fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
286 if let Some(decoded) = decode_png_bytes(bytes) {
287 return Some(decoded);
334 match decode_png_bytes(bytes) {
335 PngDecodeOutcome::Decoded(decoded) => return Some(decoded),
336 PngDecodeOutcome::Reject => return None,
337 PngDecodeOutcome::Fallback => {}
288338 }
289339 let dyn_img = image::load_from_memory(bytes).ok()?;
290340 let has_alpha = dyn_img.color().has_alpha();
......@@ -299,11 +349,7 @@ fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> {
299349 }
300350 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.
301351 match std::fs::read(path) {
302 Ok(bytes) => {
303 if let Some(decoded) = decode_raster_bytes(&bytes) {
304 return Some(decoded);
305 }
306 }
352 Ok(bytes) => return decode_raster_bytes(&bytes),
307353 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
308354 Err(_) => {}
309355 }
......@@ -3898,11 +3944,53 @@ mod tests {
38983944 let expected_size = [dyn_img.width(), dyn_img.height()];
38993945 let expected_rgba = dyn_img.into_rgba8().into_raw();
39003946
3901 let (got_size, got_rgba, got_has_alpha) =
3902 decode_png_bytes(&bytes).unwrap_or_else(|| panic!("direct decode failed for {label}"));
3947 let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) {
3948 PngDecodeOutcome::Decoded(v) => v,
3949 PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => {
3950 panic!("direct decode failed for {label}")
3951 }
3952 };
39033953 assert_eq!(got_size, expected_size, "size mismatch for {label}");
39043954 assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}");
39053955 assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}");
39063956 }
39073957 }
3958
3959 #[test]
3960 fn reject_spoofed_oversized_png_ihdr_without_allocating() {
3961 fn png_crc32(data: &[u8]) -> u32 {
3962 let mut crc = 0xFFFF_FFFFu32;
3963 for &b in data {
3964 crc ^= b as u32;
3965 for _ in 0..8 {
3966 let mask = (crc & 1).wrapping_neg();
3967 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
3968 }
3969 }
3970 !crc
3971 }
3972
3973 fn push_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], payload: &[u8]) {
3974 out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
3975 let crc_start = out.len();
3976 out.extend_from_slice(chunk_type);
3977 out.extend_from_slice(payload);
3978 let crc = png_crc32(&out[crc_start..]);
3979 out.extend_from_slice(&crc.to_be_bytes());
3980 }
3981
3982 let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10];
3983 let mut ihdr = [0u8; 13];
3984 ihdr[0..4].copy_from_slice(&16u32.to_be_bytes());
3985 ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes());
3986 ihdr[8] = 8; // bit depth
3987 ihdr[9] = 6; // RGBA
3988 push_chunk(&mut crafted, b"IHDR", &ihdr);
3989 push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]);
3990 push_chunk(&mut crafted, b"IEND", &[]);
3991 assert_eq!(crafted.len(), 67);
3992
3993 assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject));
3994 assert!(decode_raster_bytes(&crafted).is_none());
3995 }
39083996}