use image::ImageFormat;
use image::metadata::Orientation;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stripped {
pub bytes: Vec<u8>,
pub orientation: Option<Orientation>,
pub removed: bool,
}
impl Stripped {
#[must_use]
pub fn needs_turning(&self) -> bool {
self.orientation
.is_some_and(|orientation| orientation != Orientation::NoTransforms)
}
}
pub fn strip(data: &[u8]) -> Result<Stripped, String> {
match image::guess_format(data) {
Ok(ImageFormat::Jpeg) => strip_jpeg(data),
Ok(ImageFormat::Png) => strip_png(data),
Ok(ImageFormat::WebP) => strip_webp(data),
Ok(ImageFormat::Gif) => Ok(Stripped {
bytes: data.to_vec(),
orientation: None,
removed: false,
}),
Ok(other) => Err(format!(
"it is {}, which atpmcp cannot remove metadata from",
other.to_mime_type()
)),
Err(_) => Err("its format is not one atpmcp can remove metadata from".to_string()),
}
}
fn orientation_in(exif: &[u8]) -> Option<Orientation> {
Orientation::from_exif_chunk(exif.strip_prefix(b"Exif\0\0").unwrap_or(exif))
}
fn unreadable(format: &str) -> String {
format!("its {format} structure could not be read")
}
fn keep_jpeg_segment(marker: u8, payload: &[u8]) -> bool {
match marker {
0xE0 => true,
0xE2 => payload.starts_with(b"ICC_PROFILE\0"),
0xEE => true,
0xE1 | 0xE3..=0xED | 0xEF => false,
0xFE => false,
_ => true,
}
}
fn strip_jpeg(data: &[u8]) -> Result<Stripped, String> {
let bad = || unreadable("JPEG");
if !data.starts_with(&[0xFF, 0xD8]) {
return Err(bad());
}
let mut out = Vec::with_capacity(data.len());
out.extend_from_slice(&[0xFF, 0xD8]);
let mut orientation = None;
let mut removed = false;
let mut at = 2;
loop {
if data.get(at) != Some(&0xFF) {
return Err(bad());
}
while data.get(at) == Some(&0xFF) {
at += 1;
}
let marker = *data.get(at).ok_or_else(bad)?;
at += 1;
match marker {
0xD9 => {
out.extend_from_slice(&[0xFF, 0xD9]);
removed |= at < data.len();
break;
}
0x01 | 0xD0..=0xD7 => {
out.extend_from_slice(&[0xFF, marker]);
continue;
}
0xD8 => return Err(bad()),
_ => {}
}
let length = data
.get(at..at + 2)
.map(|bytes| usize::from(u16::from_be_bytes([bytes[0], bytes[1]])))
.ok_or_else(bad)?;
let end = at + length;
if length < 2 || end > data.len() {
return Err(bad());
}
let payload = &data[at + 2..end];
if marker == 0xE1 && payload.starts_with(b"Exif\0\0") {
orientation = orientation.or_else(|| orientation_in(payload));
}
if keep_jpeg_segment(marker, payload) {
out.extend_from_slice(&[0xFF, marker]);
out.extend_from_slice(&data[at..end]);
} else {
removed = true;
}
at = end;
if marker == 0xDA {
let start = at;
loop {
match (data.get(at), data.get(at + 1)) {
(Some(0xFF), Some(next)) if *next != 0x00 && !(0xD0..=0xD7).contains(next) => {
break;
}
(Some(_), Some(_)) => at += 1,
_ => return Err(bad()),
}
}
out.extend_from_slice(&data[start..at]);
}
}
Ok(Stripped {
bytes: out,
orientation,
removed,
})
}
fn keep_png_chunk(kind: &[u8]) -> bool {
kind.first().is_some_and(u8::is_ascii_uppercase)
|| matches!(
kind,
b"tRNS"
| b"cHRM"
| b"gAMA"
| b"iCCP"
| b"sBIT"
| b"sRGB"
| b"cICP"
| b"mDCV"
| b"mDCv"
| b"cLLI"
| b"cLLi"
| b"bKGD"
| b"hIST"
| b"pHYs"
| b"sPLT"
| b"acTL"
| b"fcTL"
| b"fdAT"
)
}
fn strip_png(data: &[u8]) -> Result<Stripped, String> {
const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
let bad = || unreadable("PNG");
if !data.starts_with(SIGNATURE) {
return Err(bad());
}
let mut out = SIGNATURE.to_vec();
let mut orientation = None;
let mut removed = false;
let mut at = SIGNATURE.len();
loop {
let header = data.get(at..at + 8).ok_or_else(bad)?;
let length = usize::try_from(u32::from_be_bytes([
header[0], header[1], header[2], header[3],
]))
.map_err(|_| bad())?;
let kind = &header[4..8];
let end = at
.checked_add(12)
.and_then(|end| end.checked_add(length))
.filter(|end| *end <= data.len())
.ok_or_else(bad)?;
if kind == b"eXIf" {
orientation = orientation_in(&data[at + 8..at + 8 + length]);
}
if keep_png_chunk(kind) {
out.extend_from_slice(&data[at..end]);
} else {
removed = true;
}
at = end;
if kind == b"IEND" {
removed |= at < data.len();
break;
}
}
Ok(Stripped {
bytes: out,
orientation,
removed,
})
}
const WEBP_EXIF_FLAG: u8 = 0x08;
const WEBP_XMP_FLAG: u8 = 0x04;
fn strip_webp(data: &[u8]) -> Result<Stripped, String> {
let bad = || unreadable("WebP");
if data.len() < 12 || &data[0..4] != b"RIFF" || &data[8..12] != b"WEBP" {
return Err(bad());
}
let riff_size = usize::try_from(u32::from_le_bytes([data[4], data[5], data[6], data[7]]))
.map_err(|_| bad())?;
let riff_end = riff_size
.checked_add(8)
.filter(|end| *end <= data.len())
.ok_or_else(bad)?;
let mut chunks = Vec::with_capacity(riff_size);
let mut flags_at = None;
let mut orientation = None;
let mut removed = riff_end < data.len();
let mut at = 12;
while at + 8 <= riff_end {
let fourcc = &data[at..at + 4];
let size = usize::try_from(u32::from_le_bytes([
data[at + 4],
data[at + 5],
data[at + 6],
data[at + 7],
]))
.map_err(|_| bad())?;
let end = at
.checked_add(8)
.and_then(|end| end.checked_add(size))
.filter(|end| *end <= riff_end)
.ok_or_else(bad)?;
let payload = &data[at + 8..end];
let padded = end + (size & 1);
match fourcc {
b"EXIF" => {
orientation = orientation_in(payload);
removed = true;
}
b"VP8X" | b"ICCP" | b"ANIM" | b"ANMF" | b"ALPH" | b"VP8 " | b"VP8L" => {
if fourcc == b"VP8X" && size > 0 {
flags_at = Some(chunks.len() + 8);
}
chunks.extend_from_slice(&data[at..end]);
if size & 1 == 1 {
chunks.push(0);
}
}
_ => removed = true,
}
at = padded;
}
if at < riff_end {
return Err(bad());
}
if let Some(flags_at) = flags_at {
chunks[flags_at] &= !(WEBP_EXIF_FLAG | WEBP_XMP_FLAG);
}
let size = u32::try_from(chunks.len() + 4).map_err(|_| bad())?;
let mut out = Vec::with_capacity(chunks.len() + 12);
out.extend_from_slice(b"RIFF");
out.extend_from_slice(&size.to_le_bytes());
out.extend_from_slice(b"WEBP");
out.extend_from_slice(&chunks);
Ok(Stripped {
bytes: out,
orientation,
removed,
})
}
#[cfg(test)]
pub(crate) mod tests {
use std::io::Cursor;
use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::PngEncoder;
use image::codecs::webp::WebPEncoder;
use image::{DynamicImage, ImageEncoder, Rgb, RgbImage};
use super::*;
pub(crate) const SECRET: &[u8] = b"GPS-SECRET-40.0N-83.0W";
pub(crate) const ICC: &[u8] = b"ICC-PROFILE-STAND-IN";
pub(crate) fn exif(orientation: u16) -> Vec<u8> {
let mut exif = vec![
b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0,
];
exif.extend_from_slice(&orientation.to_le_bytes());
exif.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
exif.extend_from_slice(SECRET);
exif
}
pub(crate) fn picture() -> RgbImage {
RgbImage::from_fn(24, 16, |x, y| Rgb([(x * 10) as u8, (y * 15) as u8, 90]))
}
pub(crate) fn jpeg_with_metadata(orientation: u16) -> Vec<u8> {
let mut jpeg = Vec::new();
let mut encoder = JpegEncoder::new_with_quality(&mut jpeg, 90);
encoder.set_exif_metadata(exif(orientation)).unwrap();
encoder.set_icc_profile(ICC.to_vec()).unwrap();
encoder.encode_image(&picture()).unwrap();
let segment = |marker: u8, payload: &[u8]| {
let mut segment = vec![0xFF, marker];
segment.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
segment.extend_from_slice(payload);
segment
};
let mut extra = segment(0xFE, SECRET);
extra.extend(segment(0xED, SECRET));
jpeg.splice(2..2, extra);
jpeg.extend_from_slice(SECRET);
jpeg
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack
.windows(needle.len())
.any(|window| window == needle)
}
fn pixels(bytes: &[u8]) -> Vec<u8> {
image::load_from_memory(bytes)
.expect("decodes")
.to_rgba8()
.into_raw()
}
#[test]
fn a_jpeg_loses_its_metadata_and_keeps_its_picture_and_profile() {
let jpeg = jpeg_with_metadata(1);
let stripped = strip(&jpeg).expect("stripped");
assert!(stripped.removed);
assert!(!contains(&stripped.bytes, SECRET));
assert!(!contains(&stripped.bytes, b"Exif\0\0"));
assert!(contains(&stripped.bytes, ICC), "the colour profile stays");
assert_eq!(pixels(&stripped.bytes), pixels(&jpeg), "the same picture");
assert_eq!(stripped.orientation, Some(Orientation::NoTransforms));
assert!(!stripped.needs_turning());
}
#[test]
fn a_jpegs_orientation_is_reported() {
let stripped = strip(&jpeg_with_metadata(6)).expect("stripped");
assert_eq!(stripped.orientation, Some(Orientation::Rotate90));
assert!(stripped.needs_turning());
}
#[test]
fn a_jpeg_without_metadata_is_unchanged() {
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, 90)
.encode_image(&picture())
.unwrap();
let stripped = strip(&jpeg).expect("stripped");
assert!(!stripped.removed);
assert_eq!(stripped.bytes, jpeg);
assert_eq!(stripped.orientation, None);
}
#[test]
fn a_truncated_jpeg_is_refused() {
let jpeg = jpeg_with_metadata(1);
let error = strip(&jpeg[..jpeg.len() / 2]).expect_err("refused");
assert!(error.contains("JPEG structure"), "{error}");
}
fn png_chunk(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
let mut chunk = u32::try_from(payload.len()).unwrap().to_be_bytes().to_vec();
chunk.extend_from_slice(kind);
chunk.extend_from_slice(payload);
let crc = crate::thumbnail::tests::crc32(&chunk[4..]);
chunk.extend_from_slice(&crc.to_be_bytes());
chunk
}
#[test]
fn a_png_loses_its_metadata_and_keeps_its_picture_and_profile() {
let mut png = Vec::new();
let mut encoder = PngEncoder::new(&mut png);
encoder.set_exif_metadata(exif(1)).unwrap();
encoder.set_icc_profile(ICC.to_vec()).unwrap();
let picture = picture();
encoder
.write_image(
picture.as_raw(),
picture.width(),
picture.height(),
image::ExtendedColorType::Rgb8,
)
.unwrap();
let mut extra = png_chunk(b"tEXt", &[b"Comment\0".as_slice(), SECRET].concat());
extra.extend(png_chunk(b"tIME", &[7, 234, 11, 18, 12, 0, 0]));
extra.extend(png_chunk(b"prVt", SECRET));
png.splice(33..33, extra);
png.extend_from_slice(SECRET);
let stripped = strip(&png).expect("stripped");
assert!(stripped.removed);
assert!(!contains(&stripped.bytes, SECRET));
assert!(!contains(&stripped.bytes, b"tIME"));
assert!(!contains(&stripped.bytes, b"eXIf"));
assert!(
contains(&stripped.bytes, b"iCCP"),
"the colour profile stays"
);
assert_eq!(pixels(&stripped.bytes), pixels(&png));
assert_eq!(stripped.orientation, Some(Orientation::NoTransforms));
}
#[test]
fn a_webp_loses_its_metadata_and_keeps_its_picture_and_profile() {
let mut webp = Vec::new();
let mut encoder = WebPEncoder::new_lossless(&mut webp);
encoder.set_exif_metadata(exif(3)).unwrap();
encoder.set_icc_profile(ICC.to_vec()).unwrap();
let picture = picture();
encoder
.write_image(
picture.as_raw(),
picture.width(),
picture.height(),
image::ExtendedColorType::Rgb8,
)
.unwrap();
assert!(contains(&webp, SECRET), "the fixture carries EXIF");
let stripped = strip(&webp).expect("stripped");
assert!(stripped.removed);
assert!(!contains(&stripped.bytes, SECRET));
assert!(!contains(&stripped.bytes, b"EXIF"));
assert!(contains(&stripped.bytes, ICC), "the colour profile stays");
let size = u32::from_le_bytes(stripped.bytes[4..8].try_into().unwrap());
assert_eq!(size as usize, stripped.bytes.len() - 8);
let vp8x = stripped
.bytes
.windows(4)
.position(|w| w == b"VP8X")
.unwrap();
assert_eq!(
stripped.bytes[vp8x + 8] & (WEBP_EXIF_FLAG | WEBP_XMP_FLAG),
0
);
assert_eq!(pixels(&stripped.bytes), pixels(&webp));
assert_eq!(stripped.orientation, Some(Orientation::Rotate180));
}
#[test]
fn a_gif_is_used_as_served_and_other_formats_are_refused() {
let mut gif = Vec::new();
DynamicImage::ImageRgb8(picture())
.write_to(&mut Cursor::new(&mut gif), ImageFormat::Gif)
.unwrap();
let stripped = strip(&gif).expect("a GIF");
assert_eq!(stripped.bytes, gif);
assert!(!stripped.removed);
let bmp = b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0";
let error = strip(bmp).expect_err("refused");
assert!(error.contains("image/bmp"), "{error}");
assert!(strip(b"not an image").is_err());
}
}