Files
Pictor-public/crates/meta/src/lib.rs
T

322 lines
11 KiB
Rust

//! 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") }
}