[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
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "pictor-meta"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[dependencies]
thiserror.workspace = true
serde.workspace = true
image.workspace = true
kamadak-exif.workspace = true
lopdf.workspace = true
[dev-dependencies]
# Used only to build WebP and PNG fixtures in tests; the library walks containers itself.
img-parts.workspace = true
+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);
}
}
+283
View File
@@ -0,0 +1,283 @@
//! Fixtures built in code: nothing binary lives in git.
#![allow(dead_code)]
use std::io::Cursor;
use exif::experimental::Writer;
use exif::{Field, In, Rational, Tag, Value};
use image::{ImageEncoder, RgbImage, RgbaImage};
pub const AUTHOR: &str = "Jan Novak Fixtureauthor";
pub const MAKE: &str = "Apple";
pub const MODEL: &str = "iPhone 15";
pub const SOFTWARE: &str = "PhotoEditor 17.1 Fixture";
pub const COMMENT: &str = "Holiday at the secret cottage";
pub const XMP_NS: &str = "http://ns.adobe.com/xap";
pub fn rgb(w: u32, h: u32) -> RgbImage {
RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 13 + y * 7) as u8, (x * 31) as u8 ^ (y * 5) as u8, (y * 17) as u8]))
}
pub fn rgba(w: u32, h: u32) -> RgbaImage {
RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 29) as u8, (y * 41) as u8, (x ^ y) as u8 * 9, 128 + (x as u8)]))
}
pub fn ascii(tag: Tag, s: &str) -> Field {
Field { tag, ifd_num: In::PRIMARY, value: Value::Ascii(vec![s.as_bytes().to_vec()]) }
}
pub fn rationals(tag: Tag, v: &[(u32, u32)]) -> Field {
Field {
tag,
ifd_num: In::PRIMARY,
value: Value::Rational(v.iter().map(|&(num, denom)| Rational { num, denom }).collect()),
}
}
pub fn short(tag: Tag, v: &[u16]) -> Field {
Field { tag, ifd_num: In::PRIMARY, value: Value::Short(v.to_vec()) }
}
/// GPS 50.08 N, 14.42 E; Apple iPhone 15; software; artist; date taken; Orientation 6.
pub fn photo_fields() -> Vec<Field> {
vec![
ascii(Tag::Make, MAKE),
ascii(Tag::Model, MODEL),
ascii(Tag::Software, SOFTWARE),
ascii(Tag::Artist, AUTHOR),
ascii(Tag::DateTimeOriginal, "2024:05:01 10:20:30"),
short(Tag::Orientation, &[6]),
ascii(Tag::GPSLatitudeRef, "N"),
rationals(Tag::GPSLatitude, &[(50, 1), (4, 1), (48, 1)]),
ascii(Tag::GPSLongitudeRef, "E"),
rationals(Tag::GPSLongitude, &[(14, 1), (25, 1), (12, 1)]),
]
}
/// A raw EXIF block (TIFF header onwards).
pub fn exif_tiff(fields: &[Field]) -> Vec<u8> {
let mut w = Writer::new();
for f in fields {
w.push_field(f);
}
let mut c = Cursor::new(Vec::new());
w.write(&mut c, false).expect("exif writer");
c.into_inner()
}
pub fn xmp_packet() -> String {
format!(
r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xmp="{XMP_NS}/1.0/"
xmp:CreatorTool="{SOFTWARE}">
<dc:creator><rdf:Seq><rdf:li>{AUTHOR}</rdf:li></rdf:Seq></dc:creator>
</rdf:Description></rdf:RDF></x:xmpmeta>
<?xpacket end="w"?>"#
)
}
/// Photoshop 3.0 + 8BIM 0x0404 with an IPTC by-line (2:80).
pub fn photoshop_iptc() -> Vec<u8> {
let mut iim = vec![0x1C, 2, 80];
iim.extend_from_slice(&(AUTHOR.len() as u16).to_be_bytes());
iim.extend_from_slice(AUTHOR.as_bytes());
let mut p = b"Photoshop 3.0\0".to_vec();
p.extend_from_slice(b"8BIM");
p.extend_from_slice(&0x0404u16.to_be_bytes());
p.extend_from_slice(&[0, 0]); // empty name, padded
p.extend_from_slice(&(iim.len() as u32).to_be_bytes());
p.extend_from_slice(&iim);
if iim.len() % 2 == 1 {
p.push(0);
}
p
}
pub fn segment(marker: u8, payload: &[u8]) -> Vec<u8> {
let mut s = vec![0xFF, marker];
s.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
s.extend_from_slice(payload);
s
}
pub fn plain_jpeg() -> Vec<u8> {
let img = rgb(24, 16);
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)
.write_image(img.as_raw(), 24, 16, image::ExtendedColorType::Rgb8)
.expect("jpeg encode");
out
}
/// A JPEG with the given extra segments inserted right after SOI.
pub fn jpeg_with(segments: &[Vec<u8>]) -> Vec<u8> {
let plain = plain_jpeg();
let mut out = plain[..2].to_vec();
for s in segments {
out.extend_from_slice(s);
}
out.extend_from_slice(&plain[2..]);
out
}
pub fn exif_app1(raw: &[u8]) -> Vec<u8> {
let mut p = b"Exif\0\0".to_vec();
p.extend_from_slice(raw);
segment(0xE1, &p)
}
pub fn xmp_app1() -> Vec<u8> {
let mut p = b"http://ns.adobe.com/xap/1.0/\0".to_vec();
p.extend_from_slice(xmp_packet().as_bytes());
segment(0xE1, &p)
}
/// The full test photo: EXIF (GPS, camera, author, software, date, Orientation 6), XMP, IPTC, a comment.
pub fn photo_jpeg() -> Vec<u8> {
jpeg_with(&[
exif_app1(&exif_tiff(&photo_fields())),
xmp_app1(),
segment(0xED, &photoshop_iptc()),
segment(0xFE, COMMENT.as_bytes()),
])
}
pub fn plain_png() -> Vec<u8> {
let img = rgba(9, 7);
let mut out = Vec::new();
image::codecs::png::PngEncoder::new(&mut out)
.write_image(img.as_raw(), 9, 7, image::ExtendedColorType::Rgba8)
.expect("png encode");
out
}
/// PNG with eXIf, iTXt XMP, tEXt Author and Software, tIME.
pub fn photo_png() -> Vec<u8> {
use img_parts::Bytes;
use img_parts::png::{Png, PngChunk};
let mut png = Png::from_bytes(Bytes::from(plain_png())).expect("png parse");
let mut itxt = b"XML:com.adobe.xmp\0\0\0\0\0".to_vec();
itxt.extend_from_slice(xmp_packet().as_bytes());
let mut author = b"Author\0".to_vec();
author.extend_from_slice(AUTHOR.as_bytes());
let mut software = b"Software\0".to_vec();
software.extend_from_slice(SOFTWARE.as_bytes());
let chunks = [
PngChunk::new(*b"eXIf", Bytes::from(exif_tiff(&photo_fields()))),
PngChunk::new(*b"iTXt", Bytes::from(itxt)),
PngChunk::new(*b"tEXt", Bytes::from(author)),
PngChunk::new(*b"tEXt", Bytes::from(software)),
PngChunk::new(*b"tIME", Bytes::from_static(&[0x07, 0xE8, 5, 1, 10, 20, 30])),
];
for (i, c) in chunks.into_iter().enumerate() {
png.chunks_mut().insert(1 + i, c);
}
png.encoder().bytes().to_vec()
}
pub fn plain_webp() -> Vec<u8> {
let img = rgba(10, 6);
let mut out = Vec::new();
image::codecs::webp::WebPEncoder::new_lossless(&mut out)
.write_image(img.as_raw(), 10, 6, image::ExtendedColorType::Rgba8)
.expect("webp encode");
out
}
/// VP8X WebP with EXIF and XMP chunks (built with img-parts, which also sets the VP8X flags).
pub fn photo_webp() -> Vec<u8> {
use img_parts::riff::{RiffChunk, RiffContent};
use img_parts::webp::{CHUNK_XMP, WebP};
use img_parts::{Bytes, ImageEXIF};
let mut webp = WebP::from_bytes(Bytes::from(plain_webp())).expect("webp parse");
webp.chunks_mut().push(RiffChunk::new(CHUNK_XMP, RiffContent::Data(Bytes::from(xmp_packet().into_bytes()))));
webp.set_exif(Some(Bytes::from(exif_tiff(&photo_fields()))));
webp.encoder().bytes().to_vec()
}
/// A 5x4 RGB TIFF written by the EXIF writer, with Make, Model, Software and Artist tags.
pub fn photo_tiff() -> (Vec<u8>, RgbImage) {
let (w, h) = (5u32, 4u32);
let img = rgb(w, h);
let fields = vec![
Field { tag: Tag::ImageWidth, ifd_num: In::PRIMARY, value: Value::Long(vec![w]) },
Field { tag: Tag::ImageLength, ifd_num: In::PRIMARY, value: Value::Long(vec![h]) },
short(Tag::BitsPerSample, &[8, 8, 8]),
short(Tag::Compression, &[1]),
short(Tag::PhotometricInterpretation, &[2]),
short(Tag::SamplesPerPixel, &[3]),
Field { tag: Tag::RowsPerStrip, ifd_num: In::PRIMARY, value: Value::Long(vec![h]) },
short(Tag::PlanarConfiguration, &[1]),
ascii(Tag::Make, MAKE),
ascii(Tag::Model, MODEL),
ascii(Tag::Software, SOFTWARE),
ascii(Tag::Artist, AUTHOR),
];
let strip: &[u8] = img.as_raw();
let strips = [strip];
let mut wr = Writer::new();
for f in &fields {
wr.push_field(f);
}
wr.set_strips(&strips, In::PRIMARY);
let mut c = Cursor::new(Vec::new());
wr.write(&mut c, false).expect("tiff writer");
(c.into_inner(), img)
}
/// A two-frame looping GIF with a comment extension and an XMP application extension.
pub fn photo_gif() -> Vec<u8> {
use image::codecs::gif::{GifEncoder, Repeat};
use image::{Delay, Frame};
let mut out = Vec::new();
{
let mut enc = GifEncoder::new(&mut out);
enc.set_repeat(Repeat::Infinite).expect("repeat");
let a = RgbaImage::from_fn(6, 5, |x, y| {
if (x + y) % 2 == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }
});
let b = RgbaImage::from_fn(6, 5, |x, _| {
if x < 3 { image::Rgba([0, 255, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) }
});
let d = Delay::from_numer_denom_ms(100, 1);
enc.encode_frames(vec![Frame::from_parts(a, 0, 0, d), Frame::from_parts(b, 0, 0, d)]).expect("gif encode");
}
assert_eq!(out.last(), Some(&0x3B));
out.pop();
// Comment extension.
out.extend_from_slice(&[0x21, 0xFE, COMMENT.len() as u8]);
out.extend_from_slice(COMMENT.as_bytes());
out.push(0);
// XMP application extension: raw packet plus the 258-byte magic trailer.
out.extend_from_slice(&[0x21, 0xFF, 11]);
out.extend_from_slice(b"XMP DataXMP");
out.extend_from_slice(xmp_packet().as_bytes());
out.push(1);
out.extend((0..=255u8).rev());
out.push(0);
out.push(0x3B);
out
}
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
hay.windows(needle.len()).any(|w| w == needle)
}
/// A deterministic xorshift generator.
pub struct XorShift(pub u64);
impl XorShift {
pub fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
pub fn below(&mut self, n: usize) -> usize {
if n == 0 { 0 } else { (self.next() % n as u64) as usize }
}
}
+196
View File
@@ -0,0 +1,196 @@
mod common;
use common::*;
use pictor_meta::{Group, MetaError, read, strip};
fn malformed_exif_blocks() -> Vec<(&'static str, Vec<u8>)> {
let mut truncated_ifd = b"MM\0*\0\0\0\x08\0\x05".to_vec();
truncated_ifd.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00]); // half an entry
let offset_beyond = b"MM\0*\xFF\xFF\xFF\x00".to_vec();
let mut huge_count = b"II*\0\x08\0\0\0\xFF\xFF".to_vec();
huge_count.extend_from_slice(&[0x0F, 0x01, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x10, 0x00, 0x00, 0x00]);
let mut value_beyond = b"MM\0*\0\0\0\x08\0\x01".to_vec();
value_beyond.extend_from_slice(&[0x01, 0x0F, 0x00, 0x02, 0x7F, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x10, 0x00]);
value_beyond.extend_from_slice(&[0, 0, 0, 0]);
vec![
("truncated IFD", truncated_ifd),
("IFD offset beyond the segment", offset_beyond),
("huge entry count", huge_count),
("value offset beyond the segment", value_beyond),
("not TIFF at all", b"garbage!".to_vec()),
("empty", Vec::new()),
]
}
#[test]
fn malformed_exif_is_reported_and_still_removed() {
let plain = image::load_from_memory(&plain_jpeg()).unwrap().to_rgb8();
for (what, block) in malformed_exif_blocks() {
let jpeg = jpeg_with(&[exif_app1(&block), segment(0xFE, COMMENT.as_bytes())]);
match read(&jpeg) {
Ok(r) => {
assert!(r.find(Group::Exif, "EXIF block").is_some(), "{what}");
assert!(!r.warnings.is_empty() || r.items.len() <= 3, "{what}: {:?}", r);
}
Err(e) => assert!(matches!(e, MetaError::Damaged(_)), "{what}: {e:?}"),
}
let s = strip(&jpeg).unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(!contains(&s.bytes, b"Exif\0"), "{what}: EXIF block removed, no orientation kept");
assert!(!contains(&s.bytes, COMMENT.as_bytes()), "{what}");
assert!(s.removed.contains(&Group::Exif), "{what}");
assert_eq!(image::load_from_memory(&s.bytes).unwrap().to_rgb8(), plain, "{what}");
}
}
#[test]
fn truncated_jpeg_never_panics() {
let jpeg = photo_jpeg();
for cut in [3, 4, 5, 20, 100, 300, jpeg.len() / 2, jpeg.len() - 40, jpeg.len() - 2, jpeg.len() - 1] {
let b = &jpeg[..cut];
let _ = read(b);
match strip(b) {
Ok(s) => {
assert!(!contains(&s.bytes, AUTHOR.as_bytes()), "cut {cut}");
assert!(!contains(&s.bytes, b"Exif\0\0MM\0*\0\0\0\x08\0\x0b"), "cut {cut}");
}
Err(e) => assert!(matches!(e, MetaError::Damaged(_)), "cut {cut}: {e:?}"),
}
}
}
#[test]
fn truncated_png_never_panics() {
let png = photo_png();
for cut in [8, 9, 12, 20, 33, 60, png.len() / 2, png.len() - 4, png.len() - 1] {
let b = &png[..cut];
if let Ok(r) = read(b) {
assert!(!r.warnings.is_empty(), "cut {cut}: a truncated PNG gives a warning");
}
assert!(matches!(strip(b), Err(MetaError::Damaged(_))), "cut {cut}");
}
}
#[test]
fn png_chunk_with_impossible_length() {
let mut b = png::SIGNATURE.to_vec();
b.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xF0]);
b.extend_from_slice(b"tEXt");
b.extend_from_slice(&[0x41; 32]);
assert!(read(&b).is_err());
assert!(matches!(strip(&b), Err(MetaError::Damaged(_))));
// The same after a valid IHDR.
let mut good = plain_png();
good.truncate(33);
good.extend_from_slice(&b[8..]);
let r = read(&good).unwrap();
assert!(!r.warnings.is_empty());
assert!(matches!(strip(&good), Err(MetaError::Damaged(_))));
}
#[test]
fn hostile_container_lengths() {
// WebP: RIFF size and chunk size far beyond the data.
let mut webp = b"RIFF\xF0\xFF\xFF\xFFWEBPVP8X\xFF\xFF\xFF\x7F".to_vec();
webp.extend_from_slice(&[0; 10]);
let _ = read(&webp);
assert!(strip(&webp).is_err());
// GIF: a colour table flag with no table, then nothing.
assert!(strip(b"GIF89a\x01\0\x01\0\xF7\0\0").is_err());
let _ = read(b"GIF89a\x01\0\x01\0\xF7\0\0");
// GIF: an extension that never ends.
assert!(strip(b"GIF89a\x01\0\x01\0\0\0\0\x21\xFE\xFF\x41\x41").is_err());
// TIFF: IFD offset beyond the file, huge count.
for t in [&b"II*\0\xFF\xFF\xFF\xFF"[..], b"MM\0*\0\0\0\x08\xFF\xFF\0\0", b"II*\0\x08\0\0\0"] {
let _ = read(t);
assert!(strip(t).is_err());
}
// JPEG: a segment length below 2, a length past the end, garbage between segments.
for j in [&b"\xFF\xD8\xFF\xE1\x00\x01"[..], b"\xFF\xD8\xFF\xE1\xFF\xFFExif", b"\xFF\xD8\xFF\xE0\x00\x04ab\x13\x37"]
{
let _ = read(j);
assert!(matches!(strip(j), Err(MetaError::Damaged(_))));
}
}
#[test]
fn empty_and_random_bytes() {
assert_eq!(read(&[]), Err(MetaError::Empty));
assert_eq!(strip(&[]), Err(MetaError::Empty));
let mut rng = XorShift(0x9E37_79B9_7F4A_7C15);
let prefixes: [&[u8]; 7] =
[b"", b"\xFF\xD8\xFF", &png::SIGNATURE, b"RIFF\x40\0\0\0WEBP", b"II*\0", b"GIF89a", b"%PDF-1.7\n"];
for prefix in prefixes {
for len in [1usize, 7, 64, 4096] {
let mut b = prefix.to_vec();
b.extend((0..len).map(|_| rng.next() as u8));
let _ = read(&b);
let _ = strip(&b);
}
}
}
/// Mutates every fixture a few hundred times (deterministically) and runs read and strip on each.
#[test]
fn mutation_fuzz_never_panics() {
let (tiff, _) = photo_tiff();
let fixtures: Vec<(&str, Vec<u8>)> = vec![
("jpeg", photo_jpeg()),
("png", photo_png()),
("webp", photo_webp()),
("tiff", tiff),
("gif", photo_gif()),
("pdf", pdf_fixture()),
];
let mut rng = XorShift(0x2545_F491_4F6C_DD1D);
for (name, original) in &fixtures {
for round in 0..300 {
let mut b = original.clone();
for _ in 0..1 + rng.below(8) {
let at = rng.below(b.len());
match rng.below(4) {
0 => b[at] = 0xFF,
1 => b[at] = 0x00,
_ => b[at] = rng.next() as u8,
}
}
if rng.below(5) == 0 {
let keep = rng.below(b.len()).max(1);
b.truncate(keep);
}
if rng.below(8) == 0 && b.len() > 16 {
let at = rng.below(b.len() - 4);
b[at..at + 4].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xF0]);
}
let _ = read(&b);
if let Ok(s) = strip(&b) {
assert!(!s.bytes.is_empty(), "{name} round {round}");
}
}
}
}
/// A small PDF with /Info, built with lopdf.
fn pdf_fixture() -> Vec<u8> {
use lopdf::{Document, Object, Stream, dictionary};
let mut doc = Document::with_version("1.5");
let pages_id = doc.new_object_id();
let xmp = doc.add_object(Stream::new(dictionary! { "Type" => "Metadata" }, xmp_packet().into_bytes()));
let content = doc.add_object(Stream::new(dictionary! {}, b"0 0 m 10 10 l S".to_vec()));
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => content });
doc.objects.insert(
pages_id,
Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }),
);
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp });
let info = doc.add_object(dictionary! { "Author" => Object::string_literal(AUTHOR) });
doc.trailer.set("Root", catalog);
doc.trailer.set("Info", info);
let mut out = Vec::new();
doc.save_to(&mut out).unwrap();
out
}
mod png {
pub const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
}
+219
View File
@@ -0,0 +1,219 @@
mod common;
use std::io::Cursor;
use common::*;
use pictor_meta::{Group, Kind, MetaError, read, strip};
fn values(r: &pictor_meta::Report, g: Group) -> Vec<String> {
r.items.iter().filter(|i| i.group == g).map(|i| i.value.clone()).collect()
}
/// What an exiftool-style reader still sees: all EXIF fields in the file, through kamadak-exif.
fn exif_fields(bytes: &[u8]) -> Vec<(exif::Tag, String)> {
match exif::Reader::new().read_from_container(&mut Cursor::new(bytes)) {
Ok(e) => e.fields().map(|f| (f.tag, f.display_value().to_string())).collect(),
Err(_) => Vec::new(),
}
}
fn assert_no_leaks(bytes: &[u8]) {
for needle in [XMP_NS, "Photoshop 3.0", AUTHOR, MODEL, SOFTWARE, COMMENT, "2024:05:01"] {
assert!(!contains(bytes, needle.as_bytes()), "stripped file still contains {needle:?}");
}
}
#[test]
fn jpeg_read_lists_gps_camera_author_software() {
let r = read(&photo_jpeg()).unwrap();
assert_eq!(r.kind, Kind::Jpeg);
assert_eq!(r.find(Group::Gps, "Location").unwrap().value, "50.08 N, 14.42 E");
assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15");
assert!(values(&r, Group::Author).contains(&AUTHOR.to_string()));
assert!(values(&r, Group::Software).contains(&SOFTWARE.to_string()));
assert!(values(&r, Group::Iptc).contains(&AUTHOR.to_string()), "IPTC by-line: {:?}", r.items);
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()), "XMP dc:creator: {:?}", r.items);
assert!(values(&r, Group::Comment).contains(&COMMENT.to_string()));
assert!(r.find(Group::Exif, "Orientation").is_some());
assert!(!values(&r, Group::Dates).is_empty());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
#[test]
fn jpeg_strip_keeps_only_orientation_and_pixels() {
let original = photo_jpeg();
let s = strip(&original).unwrap();
for g in [
Group::Gps,
Group::Camera,
Group::Author,
Group::Software,
Group::Dates,
Group::Xmp,
Group::Iptc,
Group::Comment,
] {
assert!(s.removed.contains(&g), "{g:?} not in removed {:?}", s.removed);
}
let fields = exif_fields(&s.bytes);
assert_eq!(fields.len(), 1, "only Orientation may remain: {fields:?}");
assert_eq!(fields[0].0, exif::Tag::Orientation);
let exif = exif::Reader::new().read_from_container(&mut Cursor::new(&s.bytes)).unwrap();
let o = exif.get_field(exif::Tag::Orientation, exif::In::PRIMARY).unwrap();
assert_eq!(o.value.get_uint(0), Some(6));
assert_no_leaks(&s.bytes);
assert!(!contains(&s.bytes, MAKE.as_bytes()));
let before = image::load_from_memory(&original).unwrap().to_rgb8();
let after = image::load_from_memory(&s.bytes).unwrap().to_rgb8();
assert_eq!(before, after);
// The stripped file reads clean, and stripping again changes nothing.
let r = read(&s.bytes).unwrap();
assert_eq!(r.groups(), vec![Group::Exif], "{:?}", r.items);
assert_eq!(strip(&s.bytes).unwrap().bytes, s.bytes);
}
#[test]
fn jpeg_without_orientation_gets_no_exif() {
let mut fields = photo_fields();
fields.retain(|f| f.tag != exif::Tag::Orientation);
let original = jpeg_with(&[exif_app1(&exif_tiff(&fields))]);
let s = strip(&original).unwrap();
assert!(!contains(&s.bytes, b"Exif\0"));
assert_eq!(s.bytes, plain_jpeg(), "an untouched JPEG body is byte-identical");
}
#[test]
fn jpeg_keeps_icc_and_adobe_drops_other_app_segments() {
let mut icc = b"ICC_PROFILE\0\x01\x01".to_vec();
icc.extend_from_slice(&[7u8; 40]);
let adobe = b"Adobe\0\x64\0\0\0\0\x01".to_vec();
let original = jpeg_with(&[
segment(0xE2, &icc),
segment(0xEE, &adobe),
segment(0xEC, b"Ducky\0\x01\x02"),
segment(0xE2, b"MPF\0II*\0"),
segment(0xEF, b"secret"),
]);
let r = read(&original).unwrap();
assert!(r.items.iter().any(|i| i.name.contains("Ducky")));
let s = strip(&original).unwrap();
assert!(contains(&s.bytes, &icc));
assert!(contains(&s.bytes, &adobe));
assert!(!contains(&s.bytes, b"Ducky") && !contains(&s.bytes, b"MPF\0") && !contains(&s.bytes, b"secret"));
assert_eq!(s.removed, vec![Group::Other]);
}
#[test]
fn jpeg_drops_data_after_end_of_image() {
let mut original = photo_jpeg();
original.extend_from_slice(b"\xFF\xD8 hidden second image with GPS");
let r = read(&original).unwrap();
assert!(r.find(Group::Other, "Data after the end of the image").is_some());
let s = strip(&original).unwrap();
assert!(s.bytes.ends_with(&[0xFF, 0xD9]));
assert!(!contains(&s.bytes, b"hidden"));
}
#[test]
fn png_strip_drops_text_exif_xmp_and_keeps_pixels() {
let original = photo_png();
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Png);
assert_eq!(r.find(Group::Gps, "Location").unwrap().value, "50.08 N, 14.42 E");
assert_eq!(r.find(Group::Author, "Author").unwrap().value, AUTHOR);
assert_eq!(r.find(Group::Software, "Software").unwrap().value, SOFTWARE);
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()));
assert_eq!(r.find(Group::Dates, "Last modified").unwrap().value, "2024-05-01 10:20:30");
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
for chunk in [b"eXIf", b"tEXt", b"iTXt", b"tIME"] {
assert!(!contains(&s.bytes, chunk));
}
assert!(exif_fields(&s.bytes).is_empty());
assert!(read(&s.bytes).unwrap().items.is_empty());
assert_eq!(s.bytes, plain_png(), "the remaining chunks are copied byte for byte");
let before = image::load_from_memory(&original).unwrap().to_rgba8();
let after = image::load_from_memory(&s.bytes).unwrap().to_rgba8();
assert_eq!(before, after);
for g in [Group::Gps, Group::Camera, Group::Author, Group::Software, Group::Xmp, Group::Dates] {
assert!(s.removed.contains(&g), "{g:?}");
}
}
#[test]
fn webp_strip_drops_exif_xmp_and_fixes_flags() {
let original = photo_webp();
assert!(contains(&original, b"VP8X") && contains(&original, b"EXIF") && contains(&original, b"XMP "));
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::WebP);
assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15");
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()));
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
assert!(!contains(&s.bytes, b"EXIF") && !contains(&s.bytes, b"XMP "));
let vp8x = s.bytes.windows(4).position(|w| w == b"VP8X").expect("VP8X kept");
let flags = s.bytes[vp8x + 8];
assert_eq!(flags & 0x0C, 0, "EXIF and XMP flags cleared");
let riff = u32::from_le_bytes(s.bytes[4..8].try_into().unwrap()) as usize;
assert_eq!(riff + 8, s.bytes.len());
let before = image::load_from_memory(&original).unwrap().to_rgba8();
let after = image::load_from_memory(&s.bytes).unwrap().to_rgba8();
assert_eq!(before, after);
assert_eq!(before, rgba(10, 6), "lossless fixture");
}
#[test]
fn tiff_strip_removes_tags_and_keeps_pixels() {
let (original, img) = photo_tiff();
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Tiff);
assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15");
assert!(values(&r, Group::Author).contains(&AUTHOR.to_string()));
assert!(values(&r, Group::Software).contains(&SOFTWARE.to_string()));
assert_eq!(image::load_from_memory(&original).unwrap().to_rgb8(), img);
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
assert!(!contains(&s.bytes, MAKE.as_bytes()));
assert_eq!(image::load_from_memory(&s.bytes).unwrap().to_rgb8(), img);
assert!(read(&s.bytes).unwrap().items.is_empty(), "{:?}", read(&s.bytes).unwrap().items);
for g in [Group::Camera, Group::Author, Group::Software] {
assert!(s.removed.contains(&g));
}
}
#[test]
fn gif_strip_keeps_every_frame() {
use image::AnimationDecoder;
use image::codecs::gif::GifDecoder;
let original = photo_gif();
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Gif);
assert!(values(&r, Group::Comment).contains(&COMMENT.to_string()));
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()), "{:?}", r.items);
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
assert!(contains(&s.bytes, b"NETSCAPE2.0"), "looping kept");
let frames = |b: &[u8]| -> Vec<image::RgbaImage> {
let d = GifDecoder::new(Cursor::new(b.to_vec())).unwrap();
d.into_frames().collect_frames().unwrap().into_iter().map(|f| f.into_buffer()).collect()
};
let (a, b) = (frames(&original), frames(&s.bytes));
assert_eq!(a.len(), 2);
assert_eq!(a, b);
assert_eq!(s.removed, vec![Group::Xmp, Group::Comment]);
}
#[test]
fn unknown_and_empty_inputs_are_typed_errors() {
assert_eq!(read(&[]), Err(MetaError::Empty));
assert!(matches!(read(b"BM\0\0 not supported"), Err(MetaError::Unsupported(_))));
assert!(matches!(strip(b"hello world"), Err(MetaError::Unsupported(_))));
let small = pictor_meta::Limits { max_input_bytes: 10, ..Default::default() };
assert!(matches!(pictor_meta::read_with(&photo_jpeg(), &small), Err(MetaError::TooLarge { .. })));
}
+180
View File
@@ -0,0 +1,180 @@
mod common;
use common::*;
use lopdf::{Document, Object, Stream, StringFormat, dictionary};
use pictor_meta::{Group, Kind, MetaError, read, strip};
const PDF_AUTHOR: &str = "Jan Novák";
fn utf16be(s: &str) -> Vec<u8> {
let mut v = vec![0xFE, 0xFF];
s.encode_utf16().for_each(|u| v.extend_from_slice(&u.to_be_bytes()));
v
}
fn xmp_for_pdf() -> String {
xmp_packet().replace(AUTHOR, PDF_AUTHOR)
}
/// One page drawing one image XObject; /Info with a UTF-16BE author; XMP on the catalog and on the image;
/// /PieceInfo on the page.
fn build(modern: bool) -> Vec<u8> {
let mut doc = Document::with_version("1.5");
let pages_id = doc.new_object_id();
let meta = || dictionary! { "Type" => "Metadata", "Subtype" => "XML" };
let xmp_doc = doc.add_object(Stream::new(meta(), xmp_for_pdf().into_bytes()).with_compression(false));
let xmp_img = doc.add_object(Stream::new(meta(), xmp_for_pdf().into_bytes()).with_compression(false));
let img = doc.add_object(Stream::new(
dictionary! {
"Type" => "XObject", "Subtype" => "Image", "Width" => 2, "Height" => 2,
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Metadata" => xmp_img,
},
vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255],
));
let content = doc.add_object(Stream::new(dictionary! {}, b"q 100 0 0 100 50 50 cm /Im1 Do Q".to_vec()));
let page = doc.add_object(dictionary! {
"Type" => "Page", "Parent" => pages_id, "Contents" => content,
"Resources" => dictionary! { "XObject" => dictionary! { "Im1" => img } },
"MediaBox" => vec![0.into(), 0.into(), 200.into(), 200.into()],
"PieceInfo" => dictionary! { "Illustrator" => dictionary! { "Private" => Object::string_literal("secret private") } },
});
doc.objects.insert(
pages_id,
Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }),
);
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp_doc });
let info = doc.add_object(dictionary! {
"Author" => Object::String(utf16be(PDF_AUTHOR), StringFormat::Hexadecimal),
"Producer" => Object::string_literal("Fixture Producer 1.0"),
"Creator" => Object::string_literal(SOFTWARE),
"Title" => Object::string_literal("Secret plans"),
"CreationDate" => Object::string_literal("D:20240501102030+02'00'"),
"Department" => Object::string_literal("Custom department"),
});
doc.trailer.set("Root", catalog);
doc.trailer.set("Info", info);
let mut out = Vec::new();
if modern {
doc.save_modern(&mut out).unwrap()
} else {
doc.save_to(&mut out).unwrap()
}
out
}
fn any_metadata_key(o: &Object) -> bool {
match o {
Object::Dictionary(d) => {
d.has(b"Metadata") || d.has(b"PieceInfo") || d.iter().any(|(_, v)| any_metadata_key(v))
}
Object::Stream(s) => {
s.dict.has(b"Metadata") || s.dict.has_type(b"Metadata") || s.dict.iter().any(|(_, v)| any_metadata_key(v))
}
Object::Array(a) => a.iter().any(any_metadata_key),
_ => false,
}
}
fn first_page_content(bytes: &[u8]) -> Vec<u8> {
let doc = Document::load_mem(bytes).unwrap();
let page = *doc.get_pages().values().next().unwrap();
doc.get_page_content(page)
}
fn assert_clean(bytes: &[u8]) {
let doc = Document::load_mem(bytes).unwrap();
assert!(!doc.trailer.has(b"Info"), "trailer /Info removed");
for (id, o) in &doc.objects {
assert!(!any_metadata_key(o), "object {id:?} still has metadata: {o:?}");
}
let lower = String::from_utf8_lossy(bytes).to_lowercase();
for needle in [
"Novák",
"Fixture Producer",
"Secret plans",
"Custom department",
"secret private",
XMP_NS,
"adobe:ns:meta",
SOFTWARE,
] {
assert!(!contains(bytes, needle.as_bytes()), "raw bytes still contain {needle:?}");
}
assert!(!contains(bytes, &utf16be("Jan")[2..]), "UTF-16 author");
assert!(!lower.contains("feff004a"), "hex UTF-16 author");
}
#[test]
fn pdf_read_lists_info_and_xmp() {
let original = build(false);
assert!(contains(&original, XMP_NS.as_bytes()), "fixture has XMP");
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Pdf);
assert_eq!(r.find(Group::Author, "Author").unwrap().value, PDF_AUTHOR);
assert_eq!(r.find(Group::Software, "Producer").unwrap().value, "Fixture Producer 1.0");
assert_eq!(r.find(Group::Software, "Creator").unwrap().value, SOFTWARE);
assert_eq!(r.find(Group::PdfInfo, "Title").unwrap().value, "Secret plans");
assert_eq!(r.find(Group::PdfInfo, "Department").unwrap().value, "Custom department");
assert_eq!(r.find(Group::Dates, "CreationDate").unwrap().value, "2024-05-01 10:20:30 +02:00");
assert_eq!(r.find(Group::PdfXmp, "Creator (dc:creator)").unwrap().value, PDF_AUTHOR);
assert_eq!(r.find(Group::PdfXmp, "Creator tool (xmp:CreatorTool)").unwrap().value, SOFTWARE);
assert_eq!(r.find(Group::PdfXmp, "XMP on pages, images or other objects").unwrap().value, "1 objects");
assert!(r.find(Group::Other, "Private application data (PieceInfo)").is_some());
}
#[test]
fn pdf_strip_removes_info_and_every_xmp_stream() {
let original = build(false);
let s = strip(&original).unwrap();
assert_clean(&s.bytes);
assert_eq!(first_page_content(&original), first_page_content(&s.bytes));
let doc = Document::load_mem(&s.bytes).unwrap();
let images =
doc.objects.values().filter(|o| matches!(o, Object::Stream(st) if st.dict.has_type(b"XObject"))).count();
assert_eq!(images, 1, "the image is kept");
assert!(read(&s.bytes).unwrap().items.is_empty());
for g in [Group::Author, Group::Software, Group::Dates, Group::PdfInfo, Group::PdfXmp, Group::Other] {
assert!(s.removed.contains(&g), "{g:?}");
}
}
#[test]
fn pdf_with_object_streams_is_stripped_too() {
let original = build(true);
let r = read(&original).unwrap();
assert_eq!(r.find(Group::Author, "Author").unwrap().value, PDF_AUTHOR);
let s = strip(&original).unwrap();
assert_clean(&s.bytes);
assert_eq!(first_page_content(&original), first_page_content(&s.bytes));
}
#[test]
fn encrypted_pdf_is_refused() {
let mut doc = Document::load_mem(&build(false)).unwrap();
let enc = doc.add_object(dictionary! {
"Filter" => "Standard", "V" => 1, "R" => 2, "Length" => 40, "P" => -4,
"O" => Object::String(vec![0x11; 32], StringFormat::Hexadecimal),
"U" => Object::String(vec![0x22; 32], StringFormat::Hexadecimal),
});
doc.trailer.set("Encrypt", enc);
doc.trailer.set(
"ID",
vec![
Object::String(vec![1; 16], StringFormat::Hexadecimal),
Object::String(vec![1; 16], StringFormat::Hexadecimal),
],
);
let mut bytes = Vec::new();
doc.save_to(&mut bytes).unwrap();
assert_eq!(read(&bytes), Err(MetaError::Encrypted));
assert_eq!(strip(&bytes), Err(MetaError::Encrypted));
assert_eq!(MetaError::Encrypted.to_string(), "This PDF is password-protected. Unlock it first.");
}
#[test]
fn unparseable_pdf_is_a_typed_error() {
for bytes in [&b"%PDF-1.7\n1 0 obj << /Type /Catalog"[..], b"%PDF-", b"%PDF-1.4\n%%EOF\n"] {
assert!(matches!(read(bytes), Err(MetaError::Damaged(_))), "{:?}", read(bytes));
assert!(matches!(strip(bytes), Err(MetaError::Damaged(_))));
}
}
+88 -88
View File
@@ -1,88 +1,88 @@
# Dependencies and their licences
Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used.
The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the
OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial.
## The allowed set, as checked by `scripts/deps.mjs`
| Licence (SPDX) | Why it is allowed |
| :-- | :-- |
| MIT, MIT-0 | named in the brief |
| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief |
| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") |
| Zlib | named in the brief |
| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) |
| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence |
| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) |
| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain |
An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the
script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback").
## Direct dependencies
| Crate | Version | Licence | Used by | For |
| :-- | :-- | :-- | :-- | :-- |
| thiserror | 2 | MIT OR Apache-2.0 | all | error types |
| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports |
| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol |
| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) |
| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) |
| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding |
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF |
| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) |
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects |
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
## Binaries (fetched, never in git)
| Binary | Licence | Fetched by |
| :-- | :-- | :-- |
| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned |
### pdfium
Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256
`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches
pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside
the dll (the app's installer copies them). Read from those files on 2026-11-16:
| Component inside pdfium.dll | Licence | In the allowed set? |
| :-- | :-- | :-- |
| the binary build (bblanchon/pdfium-binaries) | MIT | yes |
| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes |
| abseil, highway | Apache-2.0 | yes |
| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes |
| fast_float, simdutf | MIT | yes |
| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) |
| OpenJPEG | BSD-2-Clause | yes |
| zlib | Zlib | yes |
| HarfBuzz | "Old MIT" | yes (MIT family) |
| ICU | Unicode-3.0 | **interpretation** (see above) |
| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive |
| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) |
| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." |
None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked
"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF
support depends on pdfium, which the brief chose).
## OS codecs (not bundled)
| Codec | Provided by | Used for |
| :-- | :-- | :-- |
| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled |
## Every crate in Cargo.lock
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
<!-- deps:begin -->
<!-- deps:end -->
# Dependencies and their licences
Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used.
The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the
OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial.
## The allowed set, as checked by `scripts/deps.mjs`
| Licence (SPDX) | Why it is allowed |
| :-- | :-- |
| MIT, MIT-0 | named in the brief |
| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief |
| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") |
| Zlib | named in the brief |
| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) |
| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence |
| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) |
| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain |
An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the
script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback").
## Direct dependencies
| Crate | Version | Licence | Used by | For |
| :-- | :-- | :-- | :-- | :-- |
| thiserror | 2 | MIT OR Apache-2.0 | all | error types |
| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports |
| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol |
| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) |
| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) |
| img-parts | 0.4 (dev) | MIT OR Apache-2.0 | meta tests | building PNG and WebP fixtures (meta walks the containers with its own bounds-checked parsers) |
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF |
| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) |
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects |
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
## Binaries (fetched, never in git)
| Binary | Licence | Fetched by |
| :-- | :-- | :-- |
| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned |
### pdfium
Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256
`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches
pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside
the dll (the app's installer copies them). Read from those files on 2026-11-16:
| Component inside pdfium.dll | Licence | In the allowed set? |
| :-- | :-- | :-- |
| the binary build (bblanchon/pdfium-binaries) | MIT | yes |
| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes |
| abseil, highway | Apache-2.0 | yes |
| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes |
| fast_float, simdutf | MIT | yes |
| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) |
| OpenJPEG | BSD-2-Clause | yes |
| zlib | Zlib | yes |
| HarfBuzz | "Old MIT" | yes (MIT family) |
| ICU | Unicode-3.0 | **interpretation** (see above) |
| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive |
| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) |
| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." |
None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked
"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF
support depends on pdfium, which the brief chose).
## OS codecs (not bundled)
| Codec | Provided by | Used for |
| :-- | :-- | :-- |
| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled |
## Every crate in Cargo.lock
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
<!-- deps:begin -->
<!-- deps:end -->