[meta] Metadata: read and strip EXIF/GPS/XMP/IPTC (JPEG, PNG, WebP, GIF, TIFF) and PDF info/XMP

This commit is contained in:
2026-11-16 13:27:47 +01:00
parent 2c1611b34a
commit ede068f7c9
17 changed files with 2914 additions and 88 deletions
+225
View File
@@ -0,0 +1,225 @@
//! EXIF (a TIFF-structured block) to report items, through kamadak-exif.
use exif::{Context, Exif, Field, In, Reader, Tag, Value};
use crate::{Ctx, Group, guarded};
/// Lists the fields of a raw EXIF block (starting at the TIFF header) and returns the Orientation (1..=8) if one
/// could be read. Damage becomes a warning, never an error.
pub(crate) fn read_block(raw: &[u8], ctx: &mut Ctx) -> Option<u16> {
ctx.push(Group::Exif, "EXIF block", crate::bytes_label(raw.len()));
let parsed = guarded(|| {
let mut reader = Reader::new();
reader.continue_on_error(true);
match reader.read_raw(raw.to_vec()) {
Ok(exif) => Ok((exif, false)),
Err(e) => e.distill_partial_result(|_| {}).map(|exif| (exif, true)),
}
});
let exif = match parsed {
Some(Ok((exif, partial))) => {
if partial {
ctx.warn("Part of the EXIF data is damaged; what could be read is listed. All of it is removed.");
}
exif
}
Some(Err(_)) | None => {
ctx.warn("The EXIF data is damaged and could not be read. It is removed all the same.");
return None;
}
};
list(&exif, ctx)
}
/// Lists an already parsed EXIF (also used for TIFF files, whose own tags are EXIF-structured).
pub(crate) fn list(exif: &Exif, ctx: &mut Ctx) -> Option<u16> {
let mut orientation = None;
let mut lat = None;
let mut lon = None;
let mut make = None;
let mut model = None;
let mut thumbnail = false;
let mut rest: Vec<(Group, String, String)> = Vec::new();
for field in exif.fields() {
if field.ifd_num != In::PRIMARY {
thumbnail = true;
continue;
}
let tag = field.tag;
if is_structural(tag) {
continue;
}
match tag {
Tag::Orientation => {
orientation =
field.value.get_uint(0).and_then(|v| u16::try_from(v).ok()).filter(|v| (1..=8).contains(v))
}
Tag::GPSLatitude => lat = dms(&field.value),
Tag::GPSLongitude => lon = dms(&field.value),
Tag::Make => make = ascii(&field.value),
Tag::Model => model = ascii(&field.value),
_ => {}
}
rest.push((group_of(tag), tag.to_string(), value_text(field, exif)));
}
let negative = |ref_tag: Tag, neg: u8| {
exif.get_field(ref_tag, In::PRIMARY)
.and_then(|f| ascii(&f.value))
.is_some_and(|s| s.as_bytes().first().is_some_and(|c| c.eq_ignore_ascii_case(&neg)))
};
if let (Some(la), Some(lo)) = (lat, lon) {
let (ns, ew) = (
if negative(Tag::GPSLatitudeRef, b'S') { "S" } else { "N" },
if negative(Tag::GPSLongitudeRef, b'W') { "W" } else { "E" },
);
ctx.push(Group::Gps, "Location", format!("{} {ns}, {} {ew}", coord(la), coord(lo)));
}
let camera = match (make.as_deref(), model.as_deref()) {
(Some(ma), Some(mo)) if mo.to_lowercase().starts_with(&ma.to_lowercase()) => Some(mo.to_string()),
(Some(ma), Some(mo)) => Some(format!("{ma} {mo}")),
(Some(x), None) | (None, Some(x)) => Some(x.to_string()),
(None, None) => None,
};
if let Some(c) = camera.filter(|c| !c.is_empty()) {
ctx.push(Group::Camera, "Camera", c);
}
for (g, name, value) in rest {
ctx.push(g, name, value);
}
if thumbnail {
ctx.push(Group::Exif, "Embedded thumbnail", "yes (a small copy of the picture)");
}
orientation
}
fn group_of(tag: Tag) -> Group {
match tag.context() {
Context::Gps => return Group::Gps,
Context::Tiff | Context::Exif => {}
_ => return Group::Exif,
}
match tag {
Tag::Make | Tag::Model | Tag::BodySerialNumber | Tag::LensSpecification | Tag::LensMake | Tag::LensModel => {
Group::Camera
}
Tag::LensSerialNumber => Group::Camera,
Tag::Artist | Tag::Copyright | Tag::CameraOwnerName => Group::Author,
Tag::Software => Group::Software,
Tag::DateTime
| Tag::DateTimeOriginal
| Tag::DateTimeDigitized
| Tag::OffsetTime
| Tag::OffsetTimeOriginal
| Tag::OffsetTimeDigitized
| Tag::SubSecTime
| Tag::SubSecTimeOriginal
| Tag::SubSecTimeDigitized => Group::Dates,
Tag::UserComment | Tag::ImageDescription => Group::Comment,
_ => match (tag.context(), tag.number()) {
// HostComputer, ProcessingSoftware
(Context::Tiff, 0x013C | 0x000B) => Group::Software,
// XPTitle, XPComment, XPAuthor, XPKeywords, XPSubject (Windows)
(Context::Tiff, 0x9C9B..=0x9C9F) => Group::Comment,
_ => Group::Exif,
},
}
}
/// Tags that describe the pixel layout, not the picture's story; not listed.
fn is_structural(tag: Tag) -> bool {
if tag.context() != Context::Tiff {
return false;
}
matches!(
tag.number(),
0x00FE..=0x0103
| 0x0106
| 0x0107
| 0x010A
| 0x0111
| 0x0115..=0x011C
| 0x0128
| 0x013D..=0x0140
| 0x0142..=0x0145
| 0x014A
| 0x0152
| 0x0153
| 0x0201
| 0x0202
| 0x0211..=0x0214
| 0x8769
| 0x8773
| 0x8825
| 0xA005
)
}
fn value_text(field: &Field, exif: &Exif) -> String {
match &field.value {
Value::Ascii(_) => ascii(&field.value).unwrap_or_default(),
Value::Undefined(v, _) if field.tag == Tag::MakerNote => {
format!("{} (the camera maker's private data)", crate::bytes_label(v.len()))
}
Value::Byte(v) | Value::Undefined(v, _) if v.len() > 64 && !is_text_like(field.tag) => {
crate::bytes_label(v.len())
}
v if value_len(v) > 64 => format!("{} values", value_len(v)),
_ => guarded(|| field.display_value().with_unit(exif).to_string()).unwrap_or_default(),
}
}
fn is_text_like(tag: Tag) -> bool {
tag == Tag::UserComment || (tag.context() == Context::Tiff && (0x9C9B..=0x9C9F).contains(&tag.number()))
}
fn value_len(v: &Value) -> usize {
match v {
Value::Byte(x) | Value::Undefined(x, _) => x.len(),
Value::Ascii(x) => x.len(),
Value::Short(x) => x.len(),
Value::Long(x) => x.len(),
Value::Rational(x) => x.len(),
Value::SByte(x) => x.len(),
Value::SShort(x) => x.len(),
Value::SLong(x) => x.len(),
Value::SRational(x) => x.len(),
Value::Float(x) => x.len(),
Value::Double(x) => x.len(),
Value::Unknown(..) => 0,
}
}
fn ascii(v: &Value) -> Option<String> {
match v {
Value::Ascii(parts) => {
let s: Vec<String> =
parts.iter().map(|p| crate::text::lossy(p).trim().to_string()).filter(|p| !p.is_empty()).collect();
Some(s.join("; "))
}
_ => None,
}
}
/// Degrees, minutes, seconds as rationals to decimal degrees.
fn dms(v: &Value) -> Option<f64> {
let Value::Rational(parts) = v else { return None };
if parts.is_empty() {
return None;
}
let mut deg = 0.0;
for (r, scale) in parts.iter().zip([1.0, 60.0, 3600.0]) {
if r.denom == 0 {
return None;
}
deg += f64::from(r.num) / f64::from(r.denom) / scale;
}
(deg.is_finite() && deg <= 180.0).then_some(deg)
}
fn coord(v: f64) -> String {
let s = format!("{v:.5}");
let s = s.trim_end_matches('0').trim_end_matches('.');
s.to_string()
}
+200
View File
@@ -0,0 +1,200 @@
//! GIF at the block level: every frame (and the animation) is copied byte for byte; comment extensions and
//! application extensions other than looping and ICC colour are dropped.
use crate::{Ctx, Group, MetaError, text, xmp};
const MAX_BLOCKS: usize = 1_000_000;
#[derive(Clone, Copy, PartialEq, Eq)]
enum BlockKind {
/// Header, screen descriptor, global colour table.
Head,
Image,
Comment,
/// An application extension and its 11-byte identifier.
App([u8; 11]),
/// Graphic control, plain text and unknown extensions.
OtherExtension,
}
struct Block {
kind: BlockKind,
span: (usize, usize),
/// For extensions: where the data sub-blocks start.
body: usize,
}
struct Parsed {
blocks: Vec<Block>,
trailer_end: Option<usize>,
error: Option<MetaError>,
}
/// Skips data sub-blocks from `pos`; returns the position after the zero-length terminator.
fn skip_sub_blocks(b: &[u8], mut pos: usize) -> Option<usize> {
loop {
let n = usize::from(*b.get(pos)?);
pos += 1;
if n == 0 {
return Some(pos);
}
pos += n;
if pos > b.len() {
return None;
}
}
}
fn parse(b: &[u8]) -> Parsed {
let mut p = Parsed { blocks: Vec::new(), trailer_end: None, error: None };
let Some(&packed) = b.get(10) else {
p.error = Some(MetaError::truncated());
return p;
};
let mut pos = 13;
if packed & 0x80 != 0 {
pos += 3 << ((packed & 7) + 1);
}
if pos > b.len() {
p.error = Some(MetaError::truncated());
return p;
}
p.blocks.push(Block { kind: BlockKind::Head, span: (0, pos), body: pos });
loop {
if p.blocks.len() >= MAX_BLOCKS {
p.error = Some(MetaError::Damaged("it has too many blocks".into()));
break;
}
let start = pos;
let Some(&intro) = b.get(pos) else {
p.error = Some(MetaError::truncated());
break;
};
let parsed = match intro {
0x3B => {
p.trailer_end = Some(pos + 1);
break;
}
0x21 => {
let label = b.get(pos + 1).copied();
let body = pos + 2;
let kind = match label {
Some(0xFE) => Some(BlockKind::Comment),
Some(0xFF) => match (b.get(body), b.get(body + 1..body + 12)) {
(Some(11), Some(id)) => {
let mut a = [0u8; 11];
a.copy_from_slice(id);
Some(BlockKind::App(a))
}
_ => Some(BlockKind::App([0; 11])),
},
Some(_) => Some(BlockKind::OtherExtension),
None => None,
};
kind.and_then(|k| skip_sub_blocks(b, body).map(|end| (k, end, body)))
}
0x2C => {
let after_descriptor = pos + 10;
b.get(pos + 9).and_then(|&packed| {
let mut q = after_descriptor;
if packed & 0x80 != 0 {
q += 3 << ((packed & 7) + 1);
}
// LZW minimum code size, then the image data sub-blocks.
q += 1;
if q > b.len() {
return None;
}
skip_sub_blocks(b, q).map(|end| (BlockKind::Image, end, q))
})
}
_ => {
p.error = Some(MetaError::Damaged("a block has an unknown type".into()));
break;
}
};
let Some((kind, end, body)) = parsed else {
p.error = Some(MetaError::truncated());
break;
};
p.blocks.push(Block { kind, span: (start, end), body });
pos = end;
}
p
}
/// Kept application extensions: animation looping and the ICC colour profile.
fn app_kept(id: &[u8; 11]) -> bool {
id == b"NETSCAPE2.0" || id == b"ANIMEXTS1.0" || id == b"ICCRGBG1012"
}
/// The bytes of an extension's sub-blocks, joined (without the length bytes).
fn joined(b: &[u8], from: usize, to: usize) -> Vec<u8> {
let mut out = Vec::new();
let mut pos = from;
while let Some(&n) = b.get(pos) {
let n = usize::from(n);
if n == 0 || pos + 1 + n > to {
break;
}
out.extend_from_slice(&b[pos + 1..pos + 1 + n]);
pos += 1 + n;
}
out
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
let parsed = parse(b);
let mut frames = 0usize;
for blk in &parsed.blocks {
match blk.kind {
BlockKind::Image => frames += 1,
BlockKind::Comment => ctx.push(Group::Comment, "Comment", text::lossy(&joined(b, blk.body, blk.span.1))),
BlockKind::App(id) if &id == b"XMP DataXMP" => {
// XMP is stored raw (its bytes double as sub-block lengths), followed by a 258-byte "magic trailer".
let raw = &b[(blk.body + 12).min(blk.span.1)..blk.span.1];
let packet = &raw[..raw.len().saturating_sub(258)];
xmp::read_packet(packet, Group::Xmp, "XMP packet", ctx);
}
BlockKind::App(id) if !app_kept(&id) => {
let name = text::latin1(&id[..8]).trim().to_string();
let label =
if name.is_empty() { "Application data".into() } else { format!("Application data ({name})") };
ctx.push(Group::Other, label, crate::bytes_label(blk.span.1 - blk.span.0));
}
_ => {}
}
}
if let Some(end) = parsed.trailer_end
&& b.len() > end
{
ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end));
}
if let Some(e) = parsed.error {
if frames == 0 && parsed.blocks.len() <= 1 {
return Err(e);
}
ctx.warn(format!("{e} Only part of it could be read."));
}
Ok(())
}
pub(crate) fn strip(b: &[u8]) -> Result<Vec<u8>, MetaError> {
let parsed = parse(b);
if let Some(e) = parsed.error {
return Err(e);
}
let mut out = Vec::with_capacity(b.len());
for blk in &parsed.blocks {
let keep = match blk.kind {
BlockKind::Head | BlockKind::Image | BlockKind::OtherExtension => true,
BlockKind::Comment => false,
BlockKind::App(id) => app_kept(&id),
};
if keep {
out.extend_from_slice(&b[blk.span.0..blk.span.1]);
}
}
out.push(0x3B);
Ok(out)
}
+101
View File
@@ -0,0 +1,101 @@
//! Photoshop image resource blocks ("Photoshop 3.0", 8BIM) and the IPTC-IIM records inside them.
use crate::{Ctx, Group, text};
pub(crate) const PHOTOSHOP_SIGNATURE: &[u8] = b"Photoshop 3.0\0";
/// Reads an APP13 payload (starting with "Photoshop 3.0\0").
pub(crate) fn read_photoshop(payload: &[u8], ctx: &mut Ctx) {
ctx.push(Group::Iptc, "Photoshop block", crate::bytes_label(payload.len()));
let Some(mut b) = payload.strip_prefix(PHOTOSHOP_SIGNATURE) else {
ctx.warn("A Photoshop block has an unknown layout; it is removed all the same.");
return;
};
let mut others = 0usize;
while b.len() >= 4 {
if &b[..4] != b"8BIM" {
ctx.warn("Part of the Photoshop block is damaged; it is removed all the same.");
break;
}
let Some(id) = text::be16(b, 4) else { break };
let Some(&name_len) = b.get(6) else { break };
// Pascal string, the whole (length byte + name) padded to an even size.
let name_total = (1 + usize::from(name_len) + 1) & !1;
let size_at = 6 + name_total;
let Some(size) = text::be32(b, size_at) else { break };
let data_at = size_at + 4;
let Some(data) = usize::try_from(size).ok().and_then(|s| b.get(data_at..data_at.checked_add(s)?)) else {
ctx.warn("A Photoshop block ends too early; it is removed all the same.");
break;
};
match id {
0x0404 => read_iim(data, ctx),
0x0409 | 0x040C => ctx.push(Group::Other, "Photoshop thumbnail", crate::bytes_label(data.len())),
0x0422 | 0x0423 => {
crate::exif_items::read_block(data, ctx);
}
0x0424 => crate::xmp::read_packet(data, Group::Xmp, "XMP packet (in Photoshop block)", ctx),
_ => others += 1,
}
let next = data_at + data.len() + (data.len() & 1);
b = b.get(next..).unwrap_or(&[]);
}
if others > 0 {
ctx.push(Group::Other, "Photoshop resources", format!("{others}"));
}
}
/// IPTC-IIM datasets: 0x1C, record, dataset, length (u16, or an extended length), data.
pub(crate) fn read_iim(mut b: &[u8], ctx: &mut Ctx) {
while let [0x1C, record, dataset, ..] = *b {
let Some(len) = text::be16(b, 3) else { break };
let (len, head) = if len & 0x8000 != 0 {
// Extended dataset: the low 15 bits give how many bytes the real length takes.
let n = usize::from(len & 0x7FFF);
if n == 0 || n > 4 {
break;
}
let Some(bytes) = b.get(5..5 + n) else { break };
(bytes.iter().fold(0usize, |acc, &x| (acc << 8) | usize::from(x)), 5 + n)
} else {
(usize::from(len), 5)
};
let Some(data) = b.get(head..head.saturating_add(len)) else {
ctx.warn("The IPTC data ends too early; it is removed all the same.");
break;
};
if record == 2 && dataset != 0 {
let name = dataset_name(dataset).map_or_else(|| format!("IPTC 2:{dataset}"), str::to_string);
ctx.push(Group::Iptc, name, text::lossy(data));
}
b = &b[head + len..];
}
}
fn dataset_name(d: u8) -> Option<&'static str> {
Some(match d {
5 => "Object name",
25 => "Keyword",
40 => "Special instructions",
55 => "Date created",
60 => "Time created",
62 => "Digital creation date",
65 => "Originating program",
80 => "By-line (author)",
85 => "By-line title",
90 => "City",
92 => "Sub-location",
95 => "Province or state",
100 => "Country code",
101 => "Country",
103 => "Transmission reference",
105 => "Headline",
110 => "Credit",
115 => "Source",
116 => "Copyright notice",
118 => "Contact",
120 => "Caption",
122 => "Caption writer",
_ => return None,
})
}
+249
View File
@@ -0,0 +1,249 @@
//! JPEG at the segment level: the image data (tables, frame header, scans) is copied byte for byte.
use crate::{Ctx, Group, MetaError, exif_items, iptc, text, xmp};
const EXIF_SIG: &[u8] = b"Exif\0";
const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";
const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0";
const ICC_SIG: &[u8] = b"ICC_PROFILE\0";
const JFIF_SIG: &[u8] = b"JFIF\0";
const ADOBE_SIG: &[u8] = b"Adobe";
/// A file with more segments than this is refused (each costs a few bytes of memory).
const MAX_SEGMENTS: usize = 100_000;
struct Segment {
marker: u8,
/// The whole segment in the file, from its 0xFF to the end of its payload (and, for SOS, its scan data).
span: (usize, usize),
/// The payload after the two length bytes (empty for markers without one).
payload: (usize, usize),
}
#[derive(Default)]
struct Parsed {
segments: Vec<Segment>,
/// The position just after the end-of-image marker, if there is one.
eoi_end: Option<usize>,
/// A segment header runs past the end of the file.
truncated: bool,
/// Something other than a marker where a marker must be, or too many segments.
damaged: Option<&'static str>,
}
fn parse(b: &[u8]) -> Parsed {
let mut p = Parsed::default();
let len = b.len();
let mut pos = 2;
loop {
if p.segments.len() >= MAX_SEGMENTS {
p.damaged = Some("it has too many segments");
break;
}
if pos >= len {
p.truncated = true;
break;
}
if b[pos] != 0xFF {
p.damaged = Some("a segment does not start where it should");
break;
}
let start = pos;
while pos < len && b[pos] == 0xFF {
pos += 1;
}
let Some(&marker) = b.get(pos) else {
p.truncated = true;
break;
};
pos += 1;
match marker {
0xD9 => {
p.eoi_end = Some(pos);
break;
}
0x01 | 0xD0..=0xD7 => p.segments.push(Segment { marker, span: (start, pos), payload: (pos, pos) }),
0x00 | 0xD8 => {
p.damaged = Some("a segment marker is invalid");
break;
}
_ => {
let Some(seg_len) = text::be16(b, pos) else {
p.truncated = true;
break;
};
let seg_len = usize::from(seg_len);
if seg_len < 2 {
p.damaged = Some("a segment length is invalid");
break;
}
let end = pos + seg_len;
if end > len {
p.truncated = true;
break;
}
let payload = (pos + 2, end);
pos = end;
if marker == 0xDA {
pos = scan_end(b, pos);
}
p.segments.push(Segment { marker, span: (start, pos), payload });
if pos >= len {
// The scan data runs to the end: a file cut off inside the image data. Kept as it is.
break;
}
}
}
}
p
}
/// The end of entropy-coded data: the next 0xFF that starts a marker other than a restart marker.
fn scan_end(b: &[u8], mut i: usize) -> usize {
while i + 1 < b.len() {
if b[i] == 0xFF {
match b[i + 1] {
0x00 | 0xD0..=0xD7 => {
i += 2;
continue;
}
0xFF => {
i += 1;
continue;
}
_ => return i,
}
}
i += 1;
}
b.len()
}
fn payload<'a>(b: &'a [u8], s: &Segment) -> &'a [u8] {
b.get(s.payload.0..s.payload.1).unwrap_or(&[])
}
/// The raw EXIF (TIFF header onwards) of an APP1 Exif payload.
fn exif_raw(p: &[u8]) -> Option<&[u8]> {
if p.starts_with(EXIF_SIG) { p.get(6..) } else { None }
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
let parsed = parse(b);
for s in &parsed.segments {
let p = payload(b, s);
match s.marker {
0xE0 if p.starts_with(JFIF_SIG) => {
if p.get(12).copied().unwrap_or(0) != 0 && p.get(13).copied().unwrap_or(0) != 0 {
ctx.push(Group::Other, "JFIF thumbnail", crate::bytes_label(p.len().saturating_sub(14)));
}
}
0xE1 if p.starts_with(EXIF_SIG) => {
exif_items::read_block(exif_raw(p).unwrap_or(&[]), ctx);
}
0xE1 if p.starts_with(XMP_SIG) => xmp::read_packet(&p[XMP_SIG.len()..], Group::Xmp, "XMP packet", ctx),
0xE1 if p.starts_with(XMP_EXT_SIG) => {
ctx.push(Group::Xmp, "Extended XMP part", crate::bytes_label(p.len()))
}
0xE2 if p.starts_with(ICC_SIG) => {}
0xE2 if p.starts_with(b"MPF\0") => {
ctx.push(Group::Other, "Multi-picture index (MPF)", crate::bytes_label(p.len()))
}
0xED if p.starts_with(iptc::PHOTOSHOP_SIGNATURE) => iptc::read_photoshop(p, ctx),
0xEE if p.starts_with(ADOBE_SIG) => {}
0xE0..=0xEF => {
let n = s.marker - 0xE0;
let id = block_id(p);
let name = if id.is_empty() { format!("APP{n} block") } else { format!("APP{n} block ({id})") };
ctx.push(Group::Other, name, crate::bytes_label(p.len()));
}
0xFE => ctx.push(Group::Comment, "Comment", text::lossy(p)),
_ => {}
}
}
if let Some(end) = parsed.eoi_end
&& b.len() > end
{
ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end));
}
if parsed.truncated {
ctx.warn("The file ends too early (truncated); only part of it could be read.");
}
if let Some(why) = parsed.damaged {
ctx.warn(format!("The file is damaged ({why}); only part of it could be read."));
}
Ok(())
}
/// The printable ASCII name at the start of an APPn payload, e.g. "Ducky".
fn block_id(p: &[u8]) -> String {
p.iter().take(24).take_while(|c| c.is_ascii_graphic() || **c == b' ').map(|&c| c as char).collect()
}
pub(crate) fn strip(b: &[u8]) -> Result<Vec<u8>, MetaError> {
let parsed = parse(b);
if parsed.truncated {
return Err(MetaError::truncated());
}
if let Some(why) = parsed.damaged {
return Err(MetaError::Damaged(why.into()));
}
// The orientation of the first EXIF block, if it can be read; a damaged block gives none.
let orientation = parsed
.segments
.iter()
.filter(|s| s.marker == 0xE1)
.find_map(|s| exif_raw(payload(b, s)))
.and_then(|raw| exif_items::read_block(raw, &mut Ctx::default()))
.filter(|&o| o != 1);
let mut out = Vec::with_capacity(b.len());
out.extend_from_slice(&[0xFF, 0xD8]);
let mut orientation_pending = orientation;
for s in &parsed.segments {
let p = payload(b, s);
let is_jfif = s.marker == 0xE0 && p.starts_with(JFIF_SIG);
let keep = match s.marker {
0xE2 => p.starts_with(ICC_SIG),
0xEE => p.starts_with(ADOBE_SIG),
0xE0 => is_jfif,
0xE1 | 0xE3..=0xED | 0xEF | 0xFE => false,
_ => true,
};
if !keep {
continue;
}
// The orientation block goes after JFIF (which must come first) and before everything else kept.
if !is_jfif && let Some(o) = orientation_pending.take() {
out.extend_from_slice(&orientation_segment(o));
}
if is_jfif && p.len() > 14 {
// Rewrite without the thumbnail: version, units and density stay.
out.extend_from_slice(&[0xFF, 0xE0, 0x00, 16]);
out.extend_from_slice(&p[..12]);
out.extend_from_slice(&[0, 0]);
} else {
out.extend_from_slice(&b[s.span.0..s.span.1]);
}
}
if let Some(o) = orientation_pending {
out.extend_from_slice(&orientation_segment(o));
}
if parsed.eoi_end.is_some() {
out.extend_from_slice(&[0xFF, 0xD9]);
}
Ok(out)
}
/// A minimal APP1 Exif segment holding only the Orientation tag (big-endian TIFF, one IFD, one entry).
fn orientation_segment(o: u16) -> Vec<u8> {
let mut s = Vec::with_capacity(36);
s.extend_from_slice(&[0xFF, 0xE1, 0x00, 34]);
s.extend_from_slice(b"Exif\0\0");
s.extend_from_slice(b"MM\0\x2A\0\0\0\x08");
s.extend_from_slice(&[0x00, 0x01]);
s.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01]);
s.extend_from_slice(&o.to_be_bytes());
s.extend_from_slice(&[0, 0]);
s.extend_from_slice(&[0, 0, 0, 0]);
s
}
+321
View File
@@ -0,0 +1,321 @@
//! pictor-meta: read and strip metadata (EXIF, GPS, XMP, IPTC, comments) from photos, and document info and XMP
//! from PDFs.
//!
//! This is the Toolbox's "Metadata" face: [`read`] shows what is in a file, [`strip`] returns a cleaned copy.
//! Bytes go in and bytes come out; the original is never touched.
//!
//! Every input is treated as hostile: the parsers here never index without a bounds check, never allocate from a
//! size read out of the file without a cap, and third-party parsers are run behind a panic guard.
//!
//! What is kept, per format:
//! - JPEG: container-level, the image data is copied byte for byte. Kept: JFIF APP0 (its thumbnail removed),
//! ICC_PROFILE APP2, Adobe APP14, every non-APP segment. Everything after the end-of-image marker is dropped
//! (MPF secondary images, vendor trailers). An EXIF Orientation other than 1 is written back as a minimal EXIF.
//! - PNG: container-level. Dropped: eXIf, tEXt, zTXt, iTXt, tIME and anything after IEND.
//! - WebP: container-level. Dropped: EXIF and XMP chunks; the VP8X flags are cleared to match.
//! - GIF: container-level (every frame and the animation survive). Dropped: comment extensions, XMP and other
//! application extensions except looping (NETSCAPE2.0, ANIMEXTS1.0) and ICC colour (ICCRGBG1012).
//! - TIFF: decoded and re-encoded (uncompressed) with the `image` crate; single-page only.
//! - PDF: trailer /Info, every /Metadata and /PieceInfo removed, orphaned objects pruned, saved fresh by lopdf.
mod exif_items;
mod gif;
mod iptc;
mod jpeg;
mod pdf;
mod png;
mod text;
mod tiff;
mod webp;
mod xmp;
use serde::Serialize;
/// Inputs larger than this are refused (512 MiB).
pub const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024;
/// A report never holds more items than this; the rest is summarised in a warning.
pub const MAX_ITEMS: usize = 5000;
/// Caps applied while reading and stripping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
/// Inputs larger than this are refused with [`MetaError::TooLarge`].
pub max_input_bytes: u64,
/// The most memory a decoded image (TIFF re-encode) may take.
pub max_decoded_bytes: u64,
/// The most bytes a single PDF stream may decompress to while loading or reading XMP.
pub max_pdf_stream_bytes: usize,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_input_bytes: MAX_INPUT_BYTES,
max_decoded_bytes: 1024 * 1024 * 1024,
max_pdf_stream_bytes: 64 * 1024 * 1024,
}
}
}
/// The file type, detected from the content (magic bytes), never from the file name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Kind {
Jpeg,
Png,
WebP,
Tiff,
Gif,
Pdf,
}
/// What a metadata item is about; the UI shows one heading per group.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub enum Group {
/// Technical EXIF fields (exposure, lens settings, thumbnails, ...).
Exif,
/// Location: GPS coordinates, altitude, direction. The summary item is named "Location".
Gps,
/// The device: make, model, serial numbers, lens. The summary item is named "Camera".
Camera,
/// Who made it: artist, author, copyright, owner.
Author,
/// Which program made or edited it.
Software,
/// When it was made or changed.
Dates,
/// An XMP packet in an image and the values found in it.
Xmp,
/// IPTC / Photoshop information (caption, by-line, keywords, ...).
Iptc,
/// Free-text comments and descriptions.
Comment,
/// A PDF's document information dictionary (title, subject, keywords, custom keys).
PdfInfo,
/// XMP metadata streams inside a PDF.
PdfXmp,
/// Anything else that is not image data: vendor blocks, trailing data, private application data.
Other,
}
impl Group {
/// Every group, in display order.
pub const ALL: [Group; 12] = [
Group::Gps,
Group::Camera,
Group::Author,
Group::Software,
Group::Dates,
Group::Exif,
Group::Xmp,
Group::Iptc,
Group::Comment,
Group::PdfInfo,
Group::PdfXmp,
Group::Other,
];
/// A plain-English heading for the UI.
pub fn label(self) -> &'static str {
match self {
Group::Exif => "EXIF",
Group::Gps => "Location (GPS)",
Group::Camera => "Camera",
Group::Author => "Author",
Group::Software => "Software",
Group::Dates => "Dates",
Group::Xmp => "XMP",
Group::Iptc => "IPTC",
Group::Comment => "Comments",
Group::PdfInfo => "Document information",
Group::PdfXmp => "Document XMP",
Group::Other => "Other",
}
}
}
/// One piece of metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Item {
pub group: Group,
pub name: String,
pub value: String,
}
/// What [`read`] found.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report {
pub kind: Kind,
pub items: Vec<Item>,
/// Plain-English notes about damaged or unreadable parts; reading went on past them.
pub warnings: Vec<String>,
}
impl Report {
/// The groups that have at least one item, in display order.
pub fn groups(&self) -> Vec<Group> {
Group::ALL.into_iter().filter(|g| self.items.iter().any(|i| i.group == *g)).collect()
}
/// The first item with this name in this group.
pub fn find(&self, group: Group, name: &str) -> Option<&Item> {
self.items.iter().find(|i| i.group == group && i.name == name)
}
}
/// The cleaned file from [`strip`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stripped {
pub bytes: Vec<u8>,
/// The groups that had items before and fewer (or none) after, in display order.
pub removed: Vec<Group>,
}
/// Errors shown to the user.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum MetaError {
#[error("The file is empty.")]
Empty,
#[error("The file is too large ({size_mib} MiB); the limit for the metadata tools is {limit_mib} MiB.")]
TooLarge { size_mib: u64, limit_mib: u64 },
#[error("The metadata tools do not support {0}.")]
Unsupported(String),
#[error("This PDF is password-protected. Unlock it first.")]
Encrypted,
#[error("The file is damaged: {0}.")]
Damaged(String),
#[error("The image is too large to process: {0}.")]
TooBig(String),
#[error("The cleaned file could not be written: {0}.")]
Write(String),
}
impl MetaError {
pub(crate) fn truncated() -> Self {
MetaError::Damaged("it ends too early (truncated)".into())
}
}
/// Reads the metadata in a JPEG, PNG, WebP, TIFF, GIF or PDF, with the default [`Limits`].
pub fn read(bytes: &[u8]) -> Result<Report, MetaError> {
read_with(bytes, &Limits::default())
}
/// Reads the metadata with explicit caps.
pub fn read_with(bytes: &[u8], limits: &Limits) -> Result<Report, MetaError> {
let kind = detect(bytes, limits)?;
let mut ctx = Ctx::default();
match kind {
Kind::Jpeg => jpeg::read(bytes, &mut ctx)?,
Kind::Png => png::read(bytes, &mut ctx)?,
Kind::WebP => webp::read(bytes, &mut ctx)?,
Kind::Tiff => tiff::read(bytes, &mut ctx)?,
Kind::Gif => gif::read(bytes, &mut ctx)?,
Kind::Pdf => pdf::read(bytes, limits, &mut ctx)?,
}
Ok(ctx.into_report(kind))
}
/// Returns a copy without metadata, with the default [`Limits`].
pub fn strip(bytes: &[u8]) -> Result<Stripped, MetaError> {
strip_with(bytes, &Limits::default())
}
/// Returns a copy without metadata, with explicit caps.
pub fn strip_with(bytes: &[u8], limits: &Limits) -> Result<Stripped, MetaError> {
let kind = detect(bytes, limits)?;
let out = match kind {
Kind::Jpeg => jpeg::strip(bytes)?,
Kind::Png => png::strip(bytes)?,
Kind::WebP => webp::strip(bytes)?,
Kind::Tiff => tiff::strip(bytes, limits)?,
Kind::Gif => gif::strip(bytes)?,
Kind::Pdf => pdf::strip(bytes, limits)?,
};
// Which groups went away: compare what a read sees before and after. A read that fails counts as empty.
let before = read_with(bytes, limits).map(|r| r.items).unwrap_or_default();
let after = read_with(&out, limits).map(|r| r.items).unwrap_or_default();
let count = |items: &[Item], g: Group| items.iter().filter(|i| i.group == g).count();
let removed = Group::ALL.into_iter().filter(|g| count(&before, *g) > count(&after, *g)).collect();
Ok(Stripped { bytes: out, removed })
}
/// Detects the kind from magic bytes and applies the size cap.
pub fn detect(bytes: &[u8], limits: &Limits) -> Result<Kind, MetaError> {
if bytes.is_empty() {
return Err(MetaError::Empty);
}
let size = bytes.len() as u64;
if size > limits.max_input_bytes {
const MIB: u64 = 1024 * 1024;
return Err(MetaError::TooLarge { size_mib: size.div_ceil(MIB), limit_mib: limits.max_input_bytes / MIB });
}
let kind = if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
Kind::Jpeg
} else if bytes.starts_with(&png::SIGNATURE) {
Kind::Png
} else if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
Kind::WebP
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
Kind::Tiff
} else if bytes.starts_with(b"II+\0") || bytes.starts_with(b"MM\0+") {
return Err(MetaError::Unsupported("BigTIFF files".into()));
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
Kind::Gif
} else if text::find(&bytes[..bytes.len().min(1024)], b"%PDF-").is_some() {
Kind::Pdf
} else {
return Err(MetaError::Unsupported("this kind of file (only JPEG, PNG, WebP, TIFF, GIF and PDF)".into()));
};
Ok(kind)
}
/// Collects items and warnings while a format reader runs.
#[derive(Default)]
pub(crate) struct Ctx {
items: Vec<Item>,
warnings: Vec<String>,
dropped: usize,
}
const MAX_VALUE_CHARS: usize = 500;
const MAX_NAME_CHARS: usize = 120;
impl Ctx {
pub(crate) fn push(&mut self, group: Group, name: impl AsRef<str>, value: impl AsRef<str>) {
if self.items.len() >= MAX_ITEMS {
self.dropped += 1;
return;
}
self.items.push(Item {
group,
name: text::clip(name.as_ref(), MAX_NAME_CHARS),
value: text::clip(value.as_ref(), MAX_VALUE_CHARS),
});
}
pub(crate) fn warn(&mut self, msg: impl Into<String>) {
let msg = msg.into();
if self.warnings.len() < 50 && !self.warnings.contains(&msg) {
self.warnings.push(msg);
}
}
fn into_report(mut self, kind: Kind) -> Report {
if self.dropped > 0 {
let n = self.dropped;
self.warn(format!("{n} more metadata items were found but are not listed."));
}
Report { kind, items: self.items, warnings: self.warnings }
}
}
/// Runs a third-party parser behind a panic guard: a panic becomes `None`.
pub(crate) fn guarded<T>(f: impl FnOnce() -> T) -> Option<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok()
}
/// Formats a byte count for the UI.
pub(crate) fn bytes_label(n: usize) -> String {
if n == 1 { "1 byte".into() } else { format!("{n} bytes") }
}
+158
View File
@@ -0,0 +1,158 @@
//! PDF through lopdf: the trailer's /Info dictionary and XMP /Metadata streams.
use lopdf::{Dictionary, Document, LoadOptions, Object};
use crate::{Ctx, Group, Limits, MetaError, guarded, text, xmp};
/// Deeper nesting than this is not walked (lopdf's parser already stops at 100).
const MAX_DEPTH: usize = 128;
/// XMP streams are read up to this size for the report.
const MAX_XMP_BYTES: usize = 4 * 1024 * 1024;
// LoadOptions is non-exhaustive: it cannot be built with a struct literal.
#[allow(clippy::field_reassign_with_default)]
fn load(b: &[u8], limits: &Limits) -> Result<Document, MetaError> {
let mut options = LoadOptions::default();
options.max_decompressed_size = Some(limits.max_pdf_stream_bytes);
let declares_encryption = || text::find(b, b"/Encrypt").is_some();
let doc = match guarded(|| Document::load_mem_with_options(b, options)) {
Some(Ok(doc)) => doc,
Some(Err(_)) | None if declares_encryption() => return Err(MetaError::Encrypted),
Some(Err(_)) | None => return Err(MetaError::Damaged("the PDF structure cannot be read".into())),
};
if doc.was_encrypted() || doc.trailer.has(b"Encrypt") {
return Err(MetaError::Encrypted);
}
if doc.catalog().is_err() {
return Err(MetaError::Damaged("the PDF has no readable document catalog".into()));
}
Ok(doc)
}
fn deref<'a>(doc: &'a Document, o: &'a Object) -> &'a Object {
match o {
Object::Reference(id) => doc.get_object(*id).unwrap_or(&Object::Null),
other => other,
}
}
fn value_text(doc: &Document, o: &Object) -> String {
match deref(doc, o) {
Object::String(bytes, _) => text::pdf_text(bytes),
Object::Name(n) => text::lossy(n),
Object::Integer(i) => i.to_string(),
Object::Real(r) => r.to_string(),
Object::Boolean(v) => v.to_string(),
Object::Null => String::new(),
_ => "(complex value)".into(),
}
}
pub(crate) fn read(b: &[u8], limits: &Limits, ctx: &mut Ctx) -> Result<(), MetaError> {
let doc = load(b, limits)?;
if let Some(info) = doc.trailer.get(b"Info").ok().map(|o| deref(&doc, o)).and_then(|o| o.as_dict().ok()) {
for (key, value) in info.iter() {
let key = text::lossy(key);
let mut shown = value_text(&doc, value);
let group = match key.as_str() {
"Author" => Group::Author,
"Creator" | "Producer" => Group::Software,
"CreationDate" | "ModDate" => {
shown = text::pdf_date(&shown);
Group::Dates
}
_ => Group::PdfInfo,
};
ctx.push(group, key, shown);
}
}
let catalog_xmp = doc.catalog().ok().and_then(|c| c.get(b"Metadata").ok()).map(|o| deref(&doc, o));
if let Some(Object::Stream(stream)) = catalog_xmp {
let content = if stream.filters().map(|f| f.is_empty()).unwrap_or(true) {
Some(stream.content.clone())
} else {
guarded(|| stream.decompressed_content_with_limit(MAX_XMP_BYTES)).and_then(Result::ok)
};
match content {
Some(c) => xmp::read_packet(&c, Group::PdfXmp, "Document XMP packet", ctx),
None => ctx.push(Group::PdfXmp, "Document XMP packet", "present (could not be decompressed)"),
}
} else if catalog_xmp.is_some() {
ctx.push(Group::PdfXmp, "Document XMP packet", "present (damaged)");
}
let catalog_id = doc.trailer.get(b"Root").and_then(Object::as_reference).ok();
let (mut with_xmp, mut with_piece_info) = (0usize, 0usize);
for (id, obj) in &doc.objects {
let mut found = (0, 0);
count_keys(obj, 0, &mut found);
if Some(*id) == catalog_id {
found.0 = found.0.saturating_sub(1);
}
with_xmp += usize::from(found.0 > 0);
with_piece_info += usize::from(found.1 > 0);
}
if with_xmp > 0 {
ctx.push(Group::PdfXmp, "XMP on pages, images or other objects", format!("{with_xmp} objects"));
}
if with_piece_info > 0 {
ctx.push(Group::Other, "Private application data (PieceInfo)", format!("{with_piece_info} objects"));
}
Ok(())
}
/// Counts /Metadata and /PieceInfo keys in an object and the dictionaries nested directly in it.
fn count_keys(o: &Object, depth: usize, found: &mut (usize, usize)) {
if depth > MAX_DEPTH {
return;
}
let dict = match o {
Object::Dictionary(d) => d,
Object::Stream(s) => &s.dict,
Object::Array(items) => {
items.iter().for_each(|i| count_keys(i, depth + 1, found));
return;
}
_ => return,
};
found.0 += usize::from(dict.has(b"Metadata"));
found.1 += usize::from(dict.has(b"PieceInfo"));
dict.iter().for_each(|(_, v)| count_keys(v, depth + 1, found));
}
fn scrub(o: &mut Object, depth: usize) {
if depth > MAX_DEPTH {
return;
}
match o {
Object::Dictionary(d) => scrub_dict(d, depth),
Object::Stream(s) => scrub_dict(&mut s.dict, depth),
Object::Array(items) => items.iter_mut().for_each(|i| scrub(i, depth + 1)),
_ => {}
}
}
fn scrub_dict(d: &mut Dictionary, depth: usize) {
d.remove(b"Metadata");
d.remove(b"PieceInfo");
d.iter_mut().for_each(|(_, v)| scrub(v, depth + 1));
}
pub(crate) fn strip(b: &[u8], limits: &Limits) -> Result<Vec<u8>, MetaError> {
let mut doc = load(b, limits)?;
let out = guarded(move || {
doc.trailer.remove(b"Info");
scrub_dict(&mut doc.trailer, 0);
doc.objects.values_mut().for_each(|o| scrub(o, 0));
doc.prune_objects();
let mut out = Vec::with_capacity(b.len());
doc.save_to(&mut out).map(|_| out)
});
match out {
Some(Ok(bytes)) => Ok(bytes),
Some(Err(e)) => Err(MetaError::Write(e.to_string())),
None => Err(MetaError::Write("the PDF writer failed".into())),
}
}
+171
View File
@@ -0,0 +1,171 @@
//! PNG at the chunk level: kept chunks are copied byte for byte (with their CRCs).
use crate::{Ctx, Group, MetaError, exif_items, text, xmp};
pub(crate) const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
const MAX_CHUNKS: usize = 1_000_000;
/// Chunks that carry metadata and are dropped.
const DROPPED: [&[u8; 4]; 5] = [b"eXIf", b"tEXt", b"zTXt", b"iTXt", b"tIME"];
struct Chunk {
kind: [u8; 4],
/// From the length field to the end of the CRC.
span: (usize, usize),
data: (usize, usize),
}
#[derive(Default)]
struct Parsed {
chunks: Vec<Chunk>,
/// The position after IEND, if there is one.
iend_end: Option<usize>,
error: Option<MetaError>,
}
fn parse(b: &[u8]) -> Parsed {
let mut p = Parsed::default();
let mut pos = SIGNATURE.len();
while pos < b.len() {
if p.chunks.len() >= MAX_CHUNKS {
p.error = Some(MetaError::Damaged("it has too many chunks".into()));
break;
}
let (Some(len), Some(kind)) = (text::be32(b, pos), b.get(pos + 4..pos + 8)) else {
p.error = Some(MetaError::truncated());
break;
};
if len > 0x7FFF_FFFF {
p.error = Some(MetaError::Damaged("a chunk has an impossible length".into()));
break;
}
let data_start = pos + 8;
let Some(end) = data_start.checked_add(len as usize).and_then(|e| e.checked_add(4)).filter(|&e| e <= b.len())
else {
p.error = Some(MetaError::truncated());
break;
};
let kind = [kind[0], kind[1], kind[2], kind[3]];
p.chunks.push(Chunk { kind, span: (pos, end), data: (data_start, end - 4) });
pos = end;
if &kind == b"IEND" {
p.iend_end = Some(end);
break;
}
}
if p.error.is_none() && p.iend_end.is_none() {
p.error = Some(MetaError::truncated());
}
p
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
let parsed = parse(b);
for c in &parsed.chunks {
let data = b.get(c.data.0..c.data.1).unwrap_or(&[]);
match &c.kind {
b"eXIf" => {
let raw = if data.starts_with(b"Exif\0\0") { &data[6..] } else { data };
exif_items::read_block(raw, ctx);
}
b"tEXt" => {
let (key, value) = split_nul(data);
let key = text::latin1(key);
ctx.push(text_group(&key), key_label(&key), text::latin1(value));
}
b"zTXt" => {
let (key, value) = split_nul(data);
let key = text::latin1(key);
let value = format!("compressed text, {}", crate::bytes_label(value.len().saturating_sub(1)));
ctx.push(text_group(&key), key_label(&key), value);
}
b"iTXt" => read_itxt(data, ctx),
b"tIME" if data.len() >= 7 => {
let year = u16::from_be_bytes([data[0], data[1]]);
let value =
format!("{year:04}-{:02}-{:02} {:02}:{:02}:{:02}", data[2], data[3], data[4], data[5], data[6]);
ctx.push(Group::Dates, "Last modified", value);
}
b"tIME" => ctx.push(Group::Dates, "Last modified", "(damaged)"),
_ => {}
}
}
if let Some(end) = parsed.iend_end
&& b.len() > end
{
ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end));
}
if let Some(e) = parsed.error {
if parsed.chunks.is_empty() {
return Err(e);
}
ctx.warn(format!("{e} Only part of it could be read."));
}
Ok(())
}
fn read_itxt(data: &[u8], ctx: &mut Ctx) {
let (key, rest) = split_nul(data);
let key = text::latin1(key);
let (Some(&compressed), Some(_method)) = (rest.first(), rest.get(1)) else {
ctx.push(text_group(&key), key_label(&key), "(damaged)");
return;
};
let rest = rest.get(2..).unwrap_or(&[]);
let (_lang, rest) = split_nul(rest);
let (_translated, value) = split_nul(rest);
if key == "XML:com.adobe.xmp" {
if compressed == 0 {
xmp::read_packet(value, Group::Xmp, "XMP packet", ctx);
} else {
ctx.push(Group::Xmp, "XMP packet (compressed)", crate::bytes_label(value.len()));
}
return;
}
let shown = if compressed == 0 {
String::from_utf8_lossy(value).into_owned()
} else {
format!("compressed text, {}", crate::bytes_label(value.len()))
};
ctx.push(text_group(&key), key_label(&key), shown);
}
fn split_nul(b: &[u8]) -> (&[u8], &[u8]) {
match b.iter().position(|&c| c == 0) {
Some(i) => (&b[..i], &b[i + 1..]),
None => (b, &[]),
}
}
fn key_label(key: &str) -> String {
if key.is_empty() { "Text".into() } else { key.to_string() }
}
fn text_group(key: &str) -> Group {
match key.to_ascii_lowercase().as_str() {
"author" | "copyright" | "artist" => Group::Author,
"software" => Group::Software,
"source" => Group::Camera,
"creation time" | "date" => Group::Dates,
"title" | "description" | "comment" | "disclaimer" | "warning" => Group::Comment,
"xml:com.adobe.xmp" | "raw profile type xmp" => Group::Xmp,
"raw profile type exif" | "raw profile type app1" => Group::Exif,
"raw profile type iptc" | "raw profile type 8bim" => Group::Iptc,
_ => Group::Other,
}
}
pub(crate) fn strip(b: &[u8]) -> Result<Vec<u8>, MetaError> {
let parsed = parse(b);
if let Some(e) = parsed.error {
return Err(e);
}
let mut out = Vec::with_capacity(b.len());
out.extend_from_slice(&SIGNATURE);
for c in &parsed.chunks {
if !DROPPED.contains(&&c.kind) {
out.extend_from_slice(&b[c.span.0..c.span.1]);
}
}
Ok(out)
}
+187
View File
@@ -0,0 +1,187 @@
//! Small byte and text helpers shared by the format readers.
/// The first position of `needle` in `hay`.
pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || needle.len() > hay.len() {
return None;
}
hay.windows(needle.len()).position(|w| w == needle)
}
pub(crate) fn be16(b: &[u8], at: usize) -> Option<u16> {
let s = b.get(at..at.checked_add(2)?)?;
Some(u16::from_be_bytes([s[0], s[1]]))
}
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
let s = b.get(at..at.checked_add(4)?)?;
Some(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
}
pub(crate) fn le32(b: &[u8], at: usize) -> Option<u32> {
let s = b.get(at..at.checked_add(4)?)?;
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
/// Cuts a string to `max` characters, adding an ellipsis, and replaces control characters with spaces.
pub(crate) fn clip(s: &str, max: usize) -> String {
let mut out = String::with_capacity(s.len().min(max * 4));
for (n, c) in s.chars().enumerate() {
if n == max {
out.push('…');
break;
}
out.push(if c.is_control() { ' ' } else { c });
}
out.trim().to_string()
}
/// Bytes as text: UTF-8 where valid, otherwise Latin-1; trailing NULs dropped.
pub(crate) fn lossy(b: &[u8]) -> String {
let b = trim_nul(b);
match std::str::from_utf8(b) {
Ok(s) => s.to_string(),
Err(_) => latin1(b),
}
}
pub(crate) fn latin1(b: &[u8]) -> String {
trim_nul(b).iter().map(|&c| c as char).collect()
}
fn trim_nul(mut b: &[u8]) -> &[u8] {
while let [rest @ .., 0] = b {
b = rest;
}
b
}
/// A PDF text string: UTF-16BE (or LE) with a byte order mark, UTF-8 with a BOM, or PDFDocEncoding.
pub(crate) fn pdf_text(b: &[u8]) -> String {
if let Some(rest) = b.strip_prefix(&[0xFE, 0xFF]) {
let units = rest.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c));
return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect();
}
if let Some(rest) = b.strip_prefix(&[0xFF, 0xFE]) {
let units = rest.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c));
return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect();
}
if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
return String::from_utf8_lossy(rest).into_owned();
}
b.iter().map(|&c| pdf_doc_char(c)).collect()
}
fn pdf_doc_char(c: u8) -> char {
const LOW: [char; 8] =
['\u{02D8}', '\u{02C7}', '\u{02C6}', '\u{02D9}', '\u{02DD}', '\u{02DB}', '\u{02DA}', '\u{02DC}'];
const HIGH: [char; 33] = [
'\u{2022}', '\u{2020}', '\u{2021}', '\u{2026}', '\u{2014}', '\u{2013}', '\u{0192}', '\u{2044}', '\u{2039}',
'\u{203A}', '\u{2212}', '\u{2030}', '\u{201E}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{201A}',
'\u{2122}', '\u{FB01}', '\u{FB02}', '\u{0141}', '\u{0152}', '\u{0160}', '\u{0178}', '\u{017D}', '\u{0131}',
'\u{0142}', '\u{0153}', '\u{0161}', '\u{017E}', '\u{FFFD}', '\u{20AC}',
];
match c {
0x18..=0x1F => LOW[usize::from(c - 0x18)],
0x7F | 0xAD => '\u{FFFD}',
0x80..=0xA0 => HIGH[usize::from(c - 0x80)],
_ => c as char,
}
}
/// Makes "D:20240501102030+02'00'" readable as "2024-05-01 10:20:30 +02:00"; anything else is returned as is.
pub(crate) fn pdf_date(s: &str) -> String {
let body = s.strip_prefix("D:").unwrap_or(s);
let digits: String = body.chars().take_while(|c| c.is_ascii_digit()).collect();
if digits.len() < 4 || !s.starts_with("D:") {
return s.to_string();
}
let part = |from: usize, to: usize, default: &str| digits.get(from..to).unwrap_or(default).to_string();
let mut out = format!(
"{}-{}-{} {}:{}:{}",
part(0, 4, "0000"),
part(4, 6, "01"),
part(6, 8, "01"),
part(8, 10, "00"),
part(10, 12, "00"),
part(12, 14, "00")
);
let rest: String = body.chars().skip(digits.chars().count()).collect();
let rest = rest.trim();
if rest.starts_with('Z') {
out.push_str(" UTC");
} else if rest.starts_with('+') || rest.starts_with('-') {
let tz: String = rest.chars().filter(|c| c.is_ascii_digit()).take(4).collect();
if tz.len() == 4 {
out.push_str(&format!(" {}{}:{}", &rest[..1], &tz[..2], &tz[2..]));
}
}
out
}
/// Decodes the five XML entities and numeric character references.
pub(crate) fn xml_unescape(s: &str) -> String {
if !s.contains('&') {
return s.to_string();
}
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('&') {
out.push_str(&rest[..i]);
rest = &rest[i..];
let end = rest.find(';').filter(|&e| e <= 12);
let decoded = end.and_then(|e| {
let ent = &rest[1..e];
let c = match ent {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
_ if ent.starts_with("#x") || ent.starts_with("#X") => {
u32::from_str_radix(&ent[2..], 16).ok().and_then(char::from_u32)
}
_ if ent.starts_with('#') => ent[1..].parse::<u32>().ok().and_then(char::from_u32),
_ => None,
};
c.map(|c| (c, e))
});
match decoded {
Some((c, e)) => {
out.push(c);
rest = &rest[e + 1..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pdf_strings() {
assert_eq!(pdf_text(&[0xFE, 0xFF, 0x00, 0x4A, 0x00, 0xE1]), "Já");
assert_eq!(pdf_text(b"Caf\xE9 \x84"), "Café —");
assert_eq!(pdf_date("D:20240501102030+02'00'"), "2024-05-01 10:20:30 +02:00");
assert_eq!(pdf_date("D:2024"), "2024-01-01 00:00:00");
assert_eq!(pdf_date("yesterday"), "yesterday");
}
#[test]
fn unescape() {
assert_eq!(xml_unescape("a &amp; b &#x41;&#66; &bogus; &"), "a & b AB &bogus; &");
}
#[test]
fn clipping() {
assert_eq!(clip("abcdef", 3), "abc…");
assert_eq!(clip("a\nb", 10), "a b");
}
}
+75
View File
@@ -0,0 +1,75 @@
//! TIFF: tags read through kamadak-exif (a TIFF file is itself EXIF-structured); stripping decodes the pixels and
//! writes a fresh, uncompressed TIFF with only the layout tags, through the `image` crate.
use std::io::Cursor;
use crate::{Ctx, Limits, MetaError, exif_items, guarded, text};
/// Whether the first IFD links to a second one (a multi-page TIFF, or one with a thumbnail page).
fn has_second_ifd(b: &[u8]) -> Option<bool> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| -> Option<u16> {
let s = b.get(at..at.checked_add(2)?)?;
Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) })
};
let u32_at = |at: usize| -> Option<u32> { if le { text::le32(b, at) } else { text::be32(b, at) } };
let ifd = u32_at(4)? as usize;
let count = usize::from(u16_at(ifd)?);
let next_at = ifd.checked_add(2)?.checked_add(count.checked_mul(12)?)?;
Some(u32_at(next_at)? != 0)
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
if has_second_ifd(b) == Some(true) {
ctx.warn("This TIFF has more than one page; removing metadata works on single-page TIFF files only.");
}
let parsed = guarded(|| {
let mut reader = exif::Reader::new();
reader.continue_on_error(true);
match reader.read_raw(b.to_vec()) {
Ok(exif) => Ok((exif, false)),
Err(e) => e.distill_partial_result(|_| {}).map(|exif| (exif, true)),
}
});
match parsed {
Some(Ok((exif, partial))) => {
if partial {
ctx.warn("Part of the TIFF tags are damaged; what could be read is listed.");
}
exif_items::list(&exif, ctx);
Ok(())
}
Some(Err(_)) | None => Err(MetaError::Damaged("its TIFF tags cannot be read".into())),
}
}
pub(crate) fn strip(b: &[u8], limits: &Limits) -> Result<Vec<u8>, MetaError> {
match has_second_ifd(b) {
Some(true) => return Err(MetaError::Unsupported("multi-page TIFF files".into())),
Some(false) => {}
None => return Err(MetaError::Damaged("its TIFF structure cannot be read".into())),
}
let decoded = guarded(|| {
let mut reader = image::ImageReader::with_format(Cursor::new(b), image::ImageFormat::Tiff);
let mut l = image::Limits::default();
l.max_alloc = Some(limits.max_decoded_bytes);
reader.limits(l);
reader.decode()
})
.ok_or_else(|| MetaError::Damaged("the image data cannot be decoded".into()))?;
let img = decoded.map_err(|e| match e {
image::ImageError::Limits(_) => MetaError::TooBig("it needs more memory than allowed".into()),
image::ImageError::Unsupported(_) => MetaError::Unsupported("this kind of TIFF image".into()),
_ => MetaError::Damaged("the image data cannot be decoded".into()),
})?;
let mut out = Cursor::new(Vec::new());
guarded(|| img.write_to(&mut out, image::ImageFormat::Tiff))
.ok_or_else(|| MetaError::Write("the TIFF encoder failed".into()))?
.map_err(|e| match e {
image::ImageError::Unsupported(_) => {
MetaError::Unsupported("this kind of TIFF image (pixel format)".into())
}
other => MetaError::Write(other.to_string()),
})?;
Ok(out.into_inner())
}
+105
View File
@@ -0,0 +1,105 @@
//! WebP at the RIFF chunk level: EXIF and XMP chunks are dropped, VP8X flags cleared to match, the rest copied.
use crate::{Ctx, Group, MetaError, exif_items, text, xmp};
const MAX_CHUNKS: usize = 1_000_000;
const FLAG_EXIF: u8 = 0x08;
const FLAG_XMP: u8 = 0x04;
struct Chunk {
id: [u8; 4],
/// From the id to the end of the data, including the pad byte when there is one.
span: (usize, usize),
data: (usize, usize),
}
struct Parsed {
chunks: Vec<Chunk>,
/// Bytes after the RIFF container.
trailing: usize,
error: Option<MetaError>,
}
fn parse(b: &[u8]) -> Parsed {
let mut p = Parsed { chunks: Vec::new(), trailing: 0, error: None };
let declared = text::le32(b, 4).map_or(0, |s| s as usize).saturating_add(8);
let end = if declared > b.len() {
p.error = Some(MetaError::truncated());
b.len()
} else {
p.trailing = b.len() - declared;
declared
};
let mut pos = 12;
while pos < end {
if p.chunks.len() >= MAX_CHUNKS {
p.error = Some(MetaError::Damaged("it has too many chunks".into()));
break;
}
let (Some(id), Some(size)) = (b.get(pos..pos + 4), text::le32(b, pos + 4)) else {
p.error = Some(MetaError::truncated());
break;
};
let data_start = pos + 8;
let Some(data_end) = data_start.checked_add(size as usize).filter(|&e| e <= end) else {
p.error = Some(MetaError::truncated());
break;
};
// Odd sizes are followed by a pad byte; a missing pad at the very end is tolerated.
let span_end = (data_end + (size as usize & 1)).min(end);
p.chunks.push(Chunk { id: [id[0], id[1], id[2], id[3]], span: (pos, span_end), data: (data_start, data_end) });
pos = span_end;
}
p
}
fn is_dropped(id: &[u8; 4]) -> bool {
id == b"EXIF" || id == b"XMP "
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
let parsed = parse(b);
for c in &parsed.chunks {
let data = &b[c.data.0..c.data.1];
match &c.id {
b"EXIF" => {
let raw = if data.starts_with(b"Exif\0\0") { &data[6..] } else { data };
exif_items::read_block(raw, ctx);
}
b"XMP " => xmp::read_packet(data, Group::Xmp, "XMP packet", ctx),
_ => {}
}
}
if parsed.trailing > 0 {
ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(parsed.trailing));
}
if let Some(e) = parsed.error {
if parsed.chunks.is_empty() {
return Err(e);
}
ctx.warn(format!("{e} Only part of it could be read."));
}
Ok(())
}
pub(crate) fn strip(b: &[u8]) -> Result<Vec<u8>, MetaError> {
let parsed = parse(b);
if let Some(e) = parsed.error {
return Err(e);
}
let mut out = Vec::with_capacity(b.len());
out.extend_from_slice(b"RIFF\0\0\0\0WEBP");
for c in parsed.chunks.iter().filter(|c| !is_dropped(&c.id)) {
let start = out.len();
out.extend_from_slice(&b[c.span.0..c.span.1]);
if &c.id == b"VP8X" && c.data.1 > c.data.0 {
out[start + 8] &= !(FLAG_EXIF | FLAG_XMP);
}
if (c.span.1 - c.span.0) % 2 == 1 {
out.push(0);
}
}
let riff_size = u32::try_from(out.len() - 8).map_err(|_| MetaError::Write("the file is too large".into()))?;
out[4..8].copy_from_slice(&riff_size.to_le_bytes());
Ok(out)
}
+138
View File
@@ -0,0 +1,138 @@
//! A small, bounded scan of an XMP packet for the properties people care about. Not an XML parser: it looks for
//! `prefix:name="value"` attributes and `<prefix:name>...</prefix:name>` elements and takes the text inside.
use crate::{Ctx, Group, text};
const PROPS: &[(&str, &str)] = &[
("dc:creator", "Creator"),
("dc:rights", "Rights"),
("dc:title", "Title"),
("dc:description", "Description"),
("dc:subject", "Keywords"),
("xmp:CreatorTool", "Creator tool"),
("xmp:CreateDate", "Created"),
("xmp:ModifyDate", "Modified"),
("xmp:MetadataDate", "Metadata date"),
("pdf:Producer", "Producer"),
("pdf:Keywords", "Keywords"),
("photoshop:AuthorsPosition", "Author's position"),
("photoshop:CaptionWriter", "Caption writer"),
("photoshop:City", "City"),
("photoshop:State", "State"),
("photoshop:Country", "Country"),
("photoshop:Credit", "Credit"),
("photoshop:Source", "Source"),
("photoshop:DateCreated", "Date created"),
("Iptc4xmpCore:Location", "Location"),
("xmpRights:Owner", "Rights owner"),
("exif:GPSLatitude", "GPS latitude"),
("exif:GPSLongitude", "GPS longitude"),
("exif:DateTimeOriginal", "Taken"),
("tiff:Make", "Camera make"),
("tiff:Model", "Camera model"),
("tiff:Artist", "Artist"),
("aux:SerialNumber", "Camera serial number"),
("aux:Lens", "Lens"),
("exifEX:BodySerialNumber", "Camera serial number"),
("xmpMM:DocumentID", "Document ID"),
("xmpMM:OriginalDocumentID", "Original document ID"),
("xmpMM:InstanceID", "Instance ID"),
("stEvt:softwareAgent", "Edited with"),
];
/// Adds an item for the packet itself and one per property found.
pub(crate) fn read_packet(packet: &[u8], group: Group, what: &str, ctx: &mut Ctx) {
ctx.push(group, what, crate::bytes_label(packet.len()));
let s = String::from_utf8_lossy(packet);
for &(prop, label) in PROPS {
if let Some(v) = find_value(&s, prop).filter(|v| !v.is_empty()) {
ctx.push(group, format!("{label} ({prop})"), v);
}
}
}
fn find_value(s: &str, prop: &str) -> Option<String> {
element_value(s, prop).or_else(|| attribute_value(s, prop))
}
fn attribute_value(s: &str, prop: &str) -> Option<String> {
let mut from = 0;
while let Some(i) = s.get(from..)?.find(prop) {
let at = from + i;
from = at + prop.len();
let before_ok = s[..at].chars().next_back().is_some_and(char::is_whitespace);
let after = s[from..].trim_start();
let Some(after) = after.strip_prefix('=') else { continue };
let after = after.trim_start();
let Some(quote) = after.chars().next().filter(|c| *c == '"' || *c == '\'') else { continue };
if !before_ok {
continue;
}
let body = &after[1..];
let end = body.find(quote)?;
return Some(text::xml_unescape(body[..end].trim()));
}
None
}
fn element_value(s: &str, prop: &str) -> Option<String> {
let open = format!("<{prop}");
let close = format!("</{prop}>");
let mut from = 0;
while let Some(i) = s.get(from..)?.find(&open) {
let start = from + i + open.len();
from = start;
let next = s[start..].chars().next()?;
if !(next == '>' || next == '/' || next.is_whitespace()) {
continue;
}
let tag_end = start + s[start..].find('>')?;
if s[..tag_end].ends_with('/') {
// <prefix:name rdf:resource="..."/> or an empty element: nothing to show here.
continue;
}
let end = tag_end + s[tag_end..].find(&close)?;
let inner = &s[tag_end + 1..end];
return Some(text_nodes(inner));
}
None
}
/// The text between tags, trimmed, joined with "; ".
fn text_nodes(inner: &str) -> String {
let mut parts: Vec<String> = Vec::new();
let mut rest = inner;
loop {
let (txt, after) = match rest.find('<') {
Some(i) => (&rest[..i], Some(&rest[i..])),
None => (rest, None),
};
let t = txt.trim();
if !t.is_empty() {
parts.push(text::xml_unescape(t));
}
match after.and_then(|a| a.find('>').map(|j| &a[j + 1..])) {
Some(next) => rest = next,
None => break,
}
}
parts.join("; ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_both_forms() {
let x = r#"<rdf:Description xmp:CreatorTool="Tool &amp; Co" tiff:Make='Apple'>
<dc:creator><rdf:Seq><rdf:li>Jan</rdf:li><rdf:li>Eva</rdf:li></rdf:Seq></dc:creator>
<dc:creatorX>no</dc:creatorX></rdf:Description>"#;
assert_eq!(find_value(x, "dc:creator").as_deref(), Some("Jan; Eva"));
assert_eq!(find_value(x, "xmp:CreatorTool").as_deref(), Some("Tool & Co"));
assert_eq!(find_value(x, "tiff:Make").as_deref(), Some("Apple"));
assert_eq!(find_value(x, "dc:title"), None);
assert_eq!(find_value("<dc:creator", "dc:creator"), None);
assert_eq!(find_value(" dc:creator=", "dc:creator"), None);
}
}