1use std::io::Cursor;
8
9use image::imageops::FilterType;
10use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ImageUse {
15 Icon,
17 Banner,
19 Photo,
21}
22
23impl ImageUse {
24 const fn budgets(self) -> (u32, usize, usize) {
26 match self {
27 ImageUse::Icon => (512, 256 * 1024, 2 * 1024 * 1024),
28 ImageUse::Banner => (1500, 600 * 1024, 3 * 1024 * 1024),
29 ImageUse::Photo => (2560, 1536 * 1024, 8 * 1024 * 1024),
30 }
31 }
32}
33
34#[derive(Debug, Clone)]
36pub struct Prepared {
37 pub bytes: Vec<u8>,
38 pub extension: &'static str,
39}
40
41pub fn mime_for(extension: &str) -> &'static str {
43 match extension {
44 "png" => "image/png",
45 "gif" => "image/gif",
46 "webp" => "image/webp",
47 _ => "image/jpeg",
48 }
49}
50
51fn limits() -> Limits {
52 let mut l = Limits::default();
53 l.max_image_width = Some(16_384);
54 l.max_image_height = Some(16_384);
55 l.max_alloc = Some(256 * 1024 * 1024);
56 l
57}
58
59const MAX_PIXELS: u64 = 50_000_000;
61
62fn header_dims(bytes: &[u8], format: ImageFormat) -> Result<(u32, u32), String> {
64 let mut reader = ImageReader::with_format(Cursor::new(bytes), format);
65 reader.limits(limits());
66 reader.into_dimensions().map_err(|e| format!("read image: {e}"))
67}
68
69const MAX_GIF_CANVAS: u64 = 4096 * 4096;
72
73fn animation(bytes: &[u8]) -> Result<Option<(u32, u32, &'static str)>, String> {
75 match crate::crypto::animated_format(bytes) {
76 Some("gif") => {
77 let (w, h) = header_dims(bytes, ImageFormat::Gif)?;
78 if w as u64 * h as u64 > MAX_GIF_CANVAS {
79 return Err(format!("this GIF declares a {w}x{h} canvas; at most 4096x4096"));
80 }
81 let mut d = image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).map_err(|e| format!("read image: {e}"))?;
82 d.set_limits(limits()).map_err(|e| format!("read image: {e}"))?;
83 let frames = image::AnimationDecoder::into_frames(d).take(2).count();
84 Ok((frames > 1).then_some((w, h, "gif")))
85 }
86 Some("webp") => {
87 let (w, h) = header_dims(bytes, ImageFormat::WebP)?;
88 Ok(Some((w, h, "webp")))
89 }
90 _ => Ok(None),
91 }
92}
93
94fn strip_gif(bytes: &[u8]) -> Option<Vec<u8>> {
98 let mut out = Vec::with_capacity(bytes.len());
99 let screen = bytes.get(..13)?;
100 out.extend_from_slice(screen);
101 let mut i = 13;
102 if screen[10] & 0x80 != 0 {
103 let table = 3 << ((screen[10] & 0x07) + 1);
104 out.extend_from_slice(bytes.get(i..i + table)?);
105 i += table;
106 }
107 let sub_blocks = |mut at: usize| -> Option<usize> {
109 loop {
110 let len = *bytes.get(at)? as usize;
111 at += 1 + len;
112 if len == 0 {
113 return Some(at);
114 }
115 bytes.get(..at)?;
116 }
117 };
118 loop {
119 match *bytes.get(i)? {
120 0x3B => {
121 out.push(0x3B);
122 return Some(out);
123 }
124 0x21 => {
125 let label = *bytes.get(i + 1)?;
126 let end = sub_blocks(i + 2)?;
127 let keep = match label {
128 0xF9 => true,
129 0xFF => matches!(bytes.get(i + 3..i + 14), Some(b"NETSCAPE2.0") | Some(b"ANIMEXTS1.0")),
130 _ => false,
131 };
132 if keep {
133 out.extend_from_slice(bytes.get(i..end)?);
134 }
135 i = end;
136 }
137 0x2C => {
138 let desc = bytes.get(i..i + 10)?;
139 let mut end = i + 10;
140 if desc[9] & 0x80 != 0 {
141 end += 3 << ((desc[9] & 0x07) + 1);
142 }
143 end = sub_blocks(end + 1)?;
144 out.extend_from_slice(bytes.get(i..end)?);
145 i = end;
146 }
147 _ => return None,
148 }
149 }
150}
151
152fn strip_webp(bytes: &[u8]) -> Option<Vec<u8>> {
155 if bytes.get(..4)? != b"RIFF" || bytes.get(8..12)? != b"WEBP" {
156 return None;
157 }
158 let mut out = bytes[..12].to_vec();
159 let mut i = 12;
160 while i < bytes.len() {
161 let fourcc = bytes.get(i..i.checked_add(4)?)?;
162 let size = u32::from_le_bytes(bytes.get(i + 4..i + 8)?.try_into().ok()?) as usize;
163 let end = i.checked_add(8)?.checked_add(size)?.checked_add(size & 1)?;
164 let chunk = bytes.get(i..end.min(bytes.len()))?;
165 match fourcc {
166 b"VP8X" => {
167 let mut c = chunk.to_vec();
168 *c.get_mut(8)? &= !(0x08 | 0x04);
169 out.extend_from_slice(&c);
170 }
171 b"ANIM" | b"ANMF" | b"ALPH" | b"VP8 " | b"VP8L" | b"ICCP" => out.extend_from_slice(chunk),
172 _ => {}
173 }
174 i = end;
175 }
176 let riff = u32::try_from(out.len() - 8).ok()?;
177 out[4..8].copy_from_slice(&riff.to_le_bytes());
178 Some(out)
179}
180
181fn strip_png(bytes: &[u8]) -> Option<Vec<u8>> {
183 const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
184 if bytes.get(..8)? != SIGNATURE {
185 return None;
186 }
187 let mut out = SIGNATURE.to_vec();
188 let mut i = 8;
189 loop {
190 let len = u32::from_be_bytes(bytes.get(i..i + 4)?.try_into().ok()?) as usize;
191 let kind = bytes.get(i + 4..i + 8)?;
192 let end = i.checked_add(12)?.checked_add(len)?;
193 let chunk = bytes.get(i..end)?;
194 let keep = matches!(
195 kind,
196 b"IHDR" | b"PLTE" | b"IDAT" | b"IEND" | b"tRNS" | b"gAMA" | b"cHRM" | b"sRGB" | b"iCCP" | b"sBIT" | b"bKGD" | b"pHYs" | b"acTL" | b"fcTL" | b"fdAT"
197 );
198 if keep {
199 out.extend_from_slice(chunk);
200 }
201 if kind == b"IEND" {
202 return Some(out);
203 }
204 i = end;
205 }
206}
207
208fn orientation_only_exif(orientation: u16) -> Vec<u8> {
210 let mut exif = b"Exif\0\0MM\0*\0\0\0\x08\0\x01".to_vec();
211 exif.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01]);
212 exif.extend_from_slice(&orientation.to_be_bytes());
213 exif.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
214 exif
215}
216
217fn strip_jpeg(bytes: &[u8]) -> Option<Vec<u8>> {
220 if bytes.get(..2)? != [0xFF, 0xD8] {
221 return None;
222 }
223 let orientation = ImageReader::with_format(Cursor::new(bytes), ImageFormat::Jpeg)
224 .into_decoder()
225 .ok()
226 .and_then(|mut d| d.orientation().ok())
227 .map(|o| o.to_exif())
228 .filter(|&o| o > 1);
229 let mut out = vec![0xFF, 0xD8];
230 if let Some(o) = orientation {
231 let exif = orientation_only_exif(o as u16);
232 out.extend_from_slice(&[0xFF, 0xE1]);
233 out.extend_from_slice(&u16::try_from(exif.len() + 2).ok()?.to_be_bytes());
234 out.extend_from_slice(&exif);
235 }
236 let mut i = 2;
237 loop {
238 if *bytes.get(i)? != 0xFF {
239 return None;
240 }
241 let marker = *bytes.get(i + 1)?;
242 match marker {
243 0xD9 => {
245 out.extend_from_slice(&[0xFF, 0xD9]);
246 return Some(out);
247 }
248 0xFF => {
249 i += 1;
250 continue;
251 }
252 _ => {}
253 }
254 let len = u16::from_be_bytes(bytes.get(i + 2..i + 4)?.try_into().ok()?) as usize;
255 let end = i.checked_add(2)?.checked_add(len)?;
256 let segment = bytes.get(i..end)?;
257 let keep = match marker {
258 0xE0 => matches!(segment.get(4..9), Some(b"JFIF\0") | Some(b"JFXX\0")),
259 0xEE => true,
260 0xE2 => segment.get(4..16) == Some(b"ICC_PROFILE\0"),
261 0xE1 | 0xE3..=0xED | 0xEF | 0xFE => false,
262 _ => true,
263 };
264 if keep {
265 out.extend_from_slice(segment);
266 }
267 i = end;
268 if marker == 0xDA {
270 let start = i;
271 loop {
272 if *bytes.get(i)? == 0xFF {
273 match *bytes.get(i + 1)? {
274 0x00 | 0xD0..=0xD7 => i += 2,
275 _ => break,
276 }
277 } else {
278 i += 1;
279 }
280 }
281 out.extend_from_slice(&bytes[start..i]);
282 }
283 }
284}
285
286pub fn strip(bytes: &[u8]) -> Option<Prepared> {
289 match image::guess_format(bytes).ok()? {
290 ImageFormat::Jpeg => strip_jpeg(bytes).map(|bytes| Prepared { bytes, extension: "jpg" }),
291 ImageFormat::Png => strip_png(bytes).map(|bytes| Prepared { bytes, extension: "png" }),
292 ImageFormat::Gif => strip_gif(bytes).map(|bytes| Prepared { bytes, extension: "gif" }),
293 ImageFormat::WebP => strip_webp(bytes).map(|bytes| Prepared { bytes, extension: "webp" }),
294 _ => None,
295 }
296}
297
298fn decode_upright(bytes: &[u8], format: ImageFormat) -> Result<DynamicImage, String> {
299 let mut reader = ImageReader::with_format(Cursor::new(bytes), format);
300 reader.limits(limits());
301 let mut decoder = reader.into_decoder().map_err(|e| format!("decode image: {e}"))?;
302 let orientation = decoder.orientation().map_err(|e| format!("decode image: {e}"))?;
303 let mut img = DynamicImage::from_decoder(decoder).map_err(|e| format!("decode image: {e}"))?;
304 img.apply_orientation(orientation);
305 Ok(img)
306}
307
308fn has_transparency(img: &DynamicImage) -> bool {
309 img.color().has_alpha() && img.to_rgba8().pixels().any(|p| p.0[3] < 255)
310}
311
312fn encode(img: &DynamicImage, png: bool, quality: u8) -> Result<Prepared, String> {
313 let mut out = Vec::new();
314 if png {
315 img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).map_err(|e| format!("encode image: {e}"))?;
316 return Ok(Prepared { bytes: out, extension: "png" });
317 }
318 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality)
319 .encode_image(&img.to_rgb8())
320 .map_err(|e| format!("encode image: {e}"))?;
321 Ok(Prepared { bytes: out, extension: "jpg" })
322}
323
324pub fn prepare(bytes: &[u8], usage: ImageUse) -> Result<Prepared, String> {
327 if crate::svg::looks_like_svg(bytes) {
328 return Err("SVG images aren't supported; use PNG, JPEG, GIF or WebP".into());
329 }
330 let format = image::guess_format(bytes).map_err(|_| "not an image Vector can read (PNG, JPEG, GIF or WebP)".to_string())?;
331 let (max_side, budget, animated_budget) = usage.budgets();
332 if let Some((w, h, extension)) = animation(bytes)? {
333 if bytes.len() <= animated_budget && w <= max_side && h <= max_side {
334 let stripped = if extension == "gif" { strip_gif(bytes) } else { strip_webp(bytes) };
335 let bytes = stripped.ok_or_else(|| format!("this {} couldn't be read to strip its metadata", extension.to_uppercase()))?;
336 return Ok(Prepared { bytes, extension });
337 }
338 return Err(format!(
339 "this animation is too large: at most {max_side}px a side and {} KB",
340 animated_budget / 1024
341 ));
342 }
343 let (w, h) = header_dims(bytes, format)?;
344 if w as u64 * h as u64 > MAX_PIXELS {
345 return Err(format!("this image is {w}x{h}: too many pixels to re-encode"));
346 }
347 let mut img = decode_upright(bytes, format)?;
348 if img.width() > max_side || img.height() > max_side {
349 img = img.resize(max_side, max_side, FilterType::CatmullRom);
350 }
351 let alpha = has_transparency(&img);
352 if format == ImageFormat::Png && !alpha {
354 let out = encode(&img, true, 0)?;
355 if out.bytes.len() <= budget {
356 return Ok(out);
357 }
358 }
359 let qualities: &[u8] = if alpha { &[0] } else { &[85, 75, 65] };
361 for &quality in qualities {
362 let out = encode(&img, alpha, quality)?;
363 if out.bytes.len() <= budget {
364 return Ok(out);
365 }
366 }
367 while img.width().max(img.height()) > 64 {
368 img = img.resize(img.width() * 3 / 4, img.height() * 3 / 4, FilterType::CatmullRom);
369 let out = encode(&img, alpha, 75)?;
370 if out.bytes.len() <= budget {
371 return Ok(out);
372 }
373 }
374 Err(format!("this image can't be brought under {} KB", budget / 1024))
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 fn jpeg_with_exif(w: u32, h: u32) -> Vec<u8> {
382 let img = DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x % 256) as u8, (y % 256) as u8, 90])));
383 let mut plain = Vec::new();
384 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut plain, 90).encode_image(&img).unwrap();
385 let payload = b"Exif\0\0MM\0*\0\0\0\x08\0\0GPS-SECRET";
387 let mut out = plain[..2].to_vec();
388 out.extend_from_slice(&[0xFF, 0xE1]);
389 out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
390 out.extend_from_slice(payload);
391 out.extend_from_slice(&plain[2..]);
392 out
393 }
394
395 #[test]
396 fn a_photo_leaves_without_its_metadata_and_within_its_size() {
397 let raw = jpeg_with_exif(2000, 1000);
398 assert!(raw.windows(10).any(|w| w == b"GPS-SECRET"));
399 let out = prepare(&raw, ImageUse::Icon).unwrap();
400 assert_eq!(out.extension, "jpg");
401 assert!(!out.bytes.windows(10).any(|w| w == b"GPS-SECRET"), "metadata is gone");
402 let back = image::load_from_memory(&out.bytes).unwrap();
403 assert_eq!((back.width(), back.height()), (512, 256));
404 assert!(out.bytes.len() <= 256 * 1024);
405 }
406
407 #[test]
408 fn transparency_stays_png() {
409 let img = DynamicImage::ImageRgba8(image::RgbaImage::from_fn(64, 64, |x, _| image::Rgba([0, 0, 0, if x < 32 { 0 } else { 255 }])));
410 let mut png = Vec::new();
411 img.write_to(&mut Cursor::new(&mut png), ImageFormat::Png).unwrap();
412 assert_eq!(prepare(&png, ImageUse::Icon).unwrap().extension, "png");
413 }
414
415 fn gif(frames: usize, comment: bool) -> Vec<u8> {
416 let mut out = Vec::new();
417 {
418 let mut enc = image::codecs::gif::GifEncoder::new(&mut out);
419 enc.set_repeat(image::codecs::gif::Repeat::Infinite).unwrap();
420 for n in 0..frames {
421 let px = image::RgbaImage::from_pixel(16, 16, image::Rgba([n as u8 * 40, 0, 0, 255]));
422 enc.encode_frame(image::Frame::new(px)).unwrap();
423 }
424 }
425 if comment {
426 let t = out.len() - 1;
428 out.splice(t..t, [0x21, 0xFE, 10, b'G', b'P', b'S', b'-', b'S', b'E', b'C', b'R', b'E', b'T', 0x00]);
429 }
430 out
431 }
432
433 #[test]
434 fn an_animated_gif_keeps_its_frames_and_loses_its_comments() {
435 let raw = gif(3, true);
436 assert!(raw.windows(10).any(|w| w == b"GPS-SECRET"));
437 let out = prepare(&raw, ImageUse::Icon).unwrap();
438 assert_eq!(out.extension, "gif");
439 assert!(!out.bytes.windows(10).any(|w| w == b"GPS-SECRET"));
440 let d = image::codecs::gif::GifDecoder::new(Cursor::new(&out.bytes)).unwrap();
441 assert_eq!(image::AnimationDecoder::into_frames(d).count(), 3, "every frame survives");
442 }
443
444 #[test]
445 fn a_gif_declaring_a_vast_canvas_is_refused_before_any_frame_decodes() {
446 let mut raw = gif(1, false);
447 raw[6..10].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
448 assert!(prepare(&raw, ImageUse::Icon).is_err(), "a 65535x65535 canvas is refused from its header");
449 raw[6..10].copy_from_slice(&[0x00, 0x20, 0x00, 0x20]);
450 assert!(prepare(&raw, ImageUse::Icon).unwrap_err().contains("canvas"), "and so is one past 4096x4096");
451 }
452
453 #[test]
454 fn webp_metadata_chunks_are_cut_and_announced_no_more() {
455 let vp8x = [b"VP8X".as_slice(), &10u32.to_le_bytes(), &[0x0E, 0, 0, 0, 15, 0, 0, 15, 0, 0]].concat();
456 let exif = [b"EXIF".as_slice(), &4u32.to_le_bytes(), b"GPS!"].concat();
457 let anim = [b"ANIM".as_slice(), &6u32.to_le_bytes(), &[0; 6]].concat();
458 let body = [b"WEBP".as_slice(), &vp8x, &exif, &anim].concat();
459 let raw = [b"RIFF".as_slice(), &(body.len() as u32).to_le_bytes(), &body].concat();
460 let out = strip_webp(&raw).unwrap();
461 assert!(!out.windows(4).any(|w| w == b"GPS!" || w == b"EXIF"));
462 assert_eq!(out[20] & 0x0C, 0, "the EXIF and XMP flags are cleared");
463 assert_eq!(u32::from_le_bytes(out[4..8].try_into().unwrap()) as usize, out.len() - 8);
464 }
465
466 #[tokio::test]
467 async fn a_sent_picture_is_compressed_unless_asked_not_to() {
468 let raw = jpeg_with_exif(3000, 1500);
469 let (out, name) = crate::ready_to_send(raw.clone(), "holiday.jpeg", true).await.unwrap();
470 assert_eq!(name, "holiday.jpeg", "a JPEG keeps its own name");
471 assert!(out.len() < raw.len() && !out.windows(10).any(|w| w == b"GPS-SECRET"));
472 assert_eq!(image::load_from_memory(&out).unwrap().width(), 2560);
473
474 let (kept, name) = crate::ready_to_send(raw.clone(), "holiday.jpeg", false).await.unwrap();
475 assert_eq!((kept, name.as_str()), (raw, "holiday.jpeg"), "compress(false) sends the bytes as they are");
476
477 let notes = b"just some text".to_vec();
478 let (same, name) = crate::ready_to_send(notes.clone(), "notes.txt", true).await.unwrap();
479 assert_eq!((same, name.as_str()), (notes, "notes.txt"), "a file that isn't a picture goes untouched");
480 }
481
482 fn rotated_jpeg_with_exif() -> Vec<u8> {
484 let img = DynamicImage::ImageRgb8(image::RgbImage::from_fn(40, 20, |x, _| image::Rgb([x as u8 * 6, 0, 90])));
485 let mut plain = Vec::new();
486 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut plain, 90).encode_image(&img).unwrap();
487 let mut exif = orientation_only_exif(6);
488 exif.extend_from_slice(b"GPS-SECRET");
489 let mut out = plain[..2].to_vec();
490 out.extend_from_slice(&[0xFF, 0xE1]);
491 out.extend_from_slice(&((exif.len() + 2) as u16).to_be_bytes());
492 out.extend_from_slice(&exif);
493 out.extend_from_slice(&[0xFF, 0xFE, 0x00, 0x08]);
494 out.extend_from_slice(b"secret");
495 out.extend_from_slice(&plain[2..]);
496 out.extend_from_slice(b"TRAILER-GPS-SECRET");
498 out
499 }
500
501 #[test]
502 fn a_stripped_jpeg_keeps_its_pixels_and_which_way_is_up_and_nothing_else() {
503 let raw = rotated_jpeg_with_exif();
504 let out = strip(&raw).unwrap();
505 assert_eq!(out.extension, "jpg");
506 assert!(!out.bytes.windows(10).any(|w| w == b"GPS-SECRET") && !out.bytes.windows(6).any(|w| w == b"secret"));
507 assert_eq!(out.bytes[out.bytes.len() - 2..], [0xFF, 0xD9], "nothing after the end of the image");
508 let mut d = ImageReader::with_format(Cursor::new(&out.bytes), ImageFormat::Jpeg).into_decoder().unwrap();
509 assert_eq!(d.orientation().unwrap(), image::metadata::Orientation::Rotate90);
510 assert_eq!(image::load_from_memory(&out.bytes).unwrap().to_rgb8(), image::load_from_memory(&raw).unwrap().to_rgb8(), "not re-encoded");
511 }
512
513 #[test]
514 fn a_stripped_png_and_gif_lose_their_text() {
515 let img = DynamicImage::ImageRgb8(image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])));
516 let mut png = Vec::new();
517 img.write_to(&mut Cursor::new(&mut png), ImageFormat::Png).unwrap();
518 let text = b"Commentlocation: home";
520 let mut chunk = (text.len() as u32).to_be_bytes().to_vec();
521 chunk.extend_from_slice(b"tEXt");
522 chunk.extend_from_slice(text);
523 chunk.extend_from_slice(&[0; 4]);
524 png.splice(33..33, chunk);
525 let out = strip(&png).unwrap();
526 assert!(!out.bytes.windows(4).any(|w| w == b"tEXt"));
527 assert_eq!(image::load_from_memory(&out.bytes).unwrap().to_rgb8(), img.to_rgb8());
528
529 let mut raw = gif(2, false);
531 let t = raw.len() - 1;
532 raw.splice(t..t, [0x21, 0x01, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 6, b'h', b'i', b'd', b'd', b'e', b'n', 0x00]);
533 let out = strip_gif(&raw).unwrap();
534 assert!(!out.windows(6).any(|w| w == b"hidden"));
535 let d = image::codecs::gif::GifDecoder::new(Cursor::new(&out)).unwrap();
536 assert_eq!(image::AnimationDecoder::into_frames(d).count(), 2);
537 }
538
539 #[test]
540 fn a_chart_stays_png() {
541 let img = DynamicImage::ImageRgb8(image::RgbImage::from_fn(800, 400, |x, y| if (x / 40 + y / 40) % 2 == 0 { image::Rgb([255, 255, 255]) } else { image::Rgb([20, 90, 200]) }));
542 let mut png = Vec::new();
543 img.write_to(&mut Cursor::new(&mut png), ImageFormat::Png).unwrap();
544 let out = prepare(&png, ImageUse::Photo).unwrap();
545 assert_eq!(out.extension, "png", "lossless, so its edges stay sharp");
546 }
547
548 #[test]
549 fn svg_and_noise_are_refused() {
550 assert!(prepare(b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>", ImageUse::Icon).is_err());
551 assert!(prepare(b"definitely not an image", ImageUse::Icon).is_err());
552 }
553}