Cotton code
492 lines · 20.0 KB · RustRaw
//! A read-only ZIP reader for the one job the `.zip` route needs — the port of//! `packages/import-core/src/zip.ts`.//!//! Pull `_chat.txt` out of a WhatsApp share-sheet export and list the media//! files sitting next to it. It reads the CENTRAL DIRECTORY rather than//! streaming local headers, which is what makes it safe: the central directory//! always carries correct sizes, so archives written with data descriptors//! (sizes deferred to after the payload) parse correctly.//!//! Two ways in://!//!   * whole-archive: [`list_zip_entries`] / [`read_zip_entry`] — what the node//!     CLI uses; it has the file in memory anyway.//!   * ranged: [`list_zip_entries_ranged`] / [`read_zip_entry_ranged`] over a//!     [`ZipRangeReader`] — what the phone uses. A WhatsApp export can be//!     hundreds of MB; the app reads the tail (central directory) and then only//!     the byte range of each entry it actually needs, so peak memory is one//!     media file, not the archive.//!//! Deliberately NOT supported, each failing loudly rather than silently: ZIP64//! (a WhatsApp chat export is never 4 GB), encrypted entries, and compression//! methods other than store/deflate.//!//! ## Why this is a hand-written walk and not the `zip` crate//!//! The TypeScript is a hand-rolled central-directory reader whose exact//! TOLERANCE for odd archives is the behaviour, not an implementation detail.//! It scans backwards for the end-of-central-directory record over the last//! 64 KiB + 22 bytes; it REFUSES a ZIP64 archive with a sentence telling the//! owner to unzip it themselves rather than half-reading one; it trusts the//! directory's sizes over the local header's while still validating the local//! signature; and it names the offending entry in every refusal. A general//! ZIP crate makes different choices at each of those points — it would accept//! ZIP64, and it would word (or not word) the refusals differently — and the//! phone and the CLI would then disagree about which archives are importable.//! So the walk is ported line for line and only the INFLATE is delegated, to//! `miniz_oxide`, which is the same raw-DEFLATE algorithm `fflate` implements.use std::fmt;/// The four signatures, little-endian as they sit on disk.const EOCD_SIGNATURE: u32 = 0x0605_4b50;const CENTRAL_SIGNATURE: u32 = 0x0201_4b50;const LOCAL_SIGNATURE: u32 = 0x0403_4b50;const EOCD_MIN_SIZE: u64 = 22;/// Max comment length (0xFFFF) plus the fixed EOCD record.const EOCD_MAX_SEARCH: u64 = 0xffff + EOCD_MIN_SIZE;const ZIP64_SENTINEL_32: u32 = 0xffff_ffff;const ZIP64_SENTINEL_16: u16 = 0xffff;const METHOD_STORE: u16 = 0;const METHOD_DEFLATE: u16 = 8;const FLAG_ENCRYPTED: u16 = 0x0001;/// The local file header is 30 fixed bytes before name + extra.const LOCAL_HEADER_SIZE: u64 = 30;/// One record from the central directory.////// The numbers are `u64` where the TypeScript holds JavaScript numbers. Every/// one is read out of the file as a `u16` or a `u32`, so no value can overflow/// the wider type; widening them here is what lets `offset + length` be/// computed without a wrap, on an archive whose directory a stranger wrote.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ZipEntry {    pub name: String,    pub compressed_size: u64,    pub uncompressed_size: u64,    pub method: u16,    pub flags: u16,    pub local_header_offset: u64,}/// Where one entry's payload sits in the archive.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ZipDataRange {    pub offset: u64,    pub length: u64,}/// Random access into an archive too large to hold in memory.////// `read` returns exactly `length` bytes at `offset`. A SHORT read is a reader/// bug, not a condition callers handle — the TypeScript says so in a comment/// and then slices the result, which in JavaScript silently produces a short/// buffer. Rust would panic on that slice, and a pure library in a server may/// not panic on data a stranger's archive steered it to, so the port checks/// the length and answers [`ZipError::Reader`] instead. That is the one place/// this file is stricter than the TypeScript.////// The trait is SYNCHRONOUS where the TypeScript is `async`. This crate has no/// runtime and may not have one; a caller that reads over the network does its/// awaiting at its own boundary and hands this an object that already has the/// bytes, or blocks. Nothing in the algorithm is concurrent — every read is/// needed before the next step can be decided.pub trait ZipRangeReader {    /// The archive's total length in bytes.    fn size(&self) -> u64;    /// Exactly `length` bytes at `offset`, or an error.    fn read(&self, offset: u64, length: u64) -> Result<Vec<u8>, ZipError>;}/// Every refusal this reader can make.////// `Format`'s `Display` is the TypeScript's sentence VERBATIM, so a handler can/// hand it straight to the error envelope — several of these are shown to the/// owner, and the ZIP64 one is an INSTRUCTION ("unzip it yourself and point the/// importer at the extracted folder instead") that only helps if it survives/// the port intact.#[derive(Debug, Clone, PartialEq, Eq)]pub enum ZipError {    /// `ZipFormatError` — the archive is not one this reader can open.    Format(String),    /// The [`ZipRangeReader`] could not serve a range it was asked for.    Reader(String),    /// The DEFLATE stream would not inflate. The TypeScript lets `fflate`'s own    /// error escape here rather than wrapping it in a `ZipFormatError`, so this    /// is a separate variant rather than another `Format`.    Inflate(String),}impl fmt::Display for ZipError {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        match self {            ZipError::Format(message) => f.write_str(message),            ZipError::Reader(message) => f.write_str(message),            ZipError::Inflate(message) => f.write_str(message),        }    }}impl std::error::Error for ZipError {}fn format_error(message: impl Into<String>) -> ZipError {    ZipError::Format(message.into())}/// `DataView.getUint16(offset, true)` — little-endian, `None` past the end.////// The TypeScript's `DataView` THROWS a `RangeError` on an out-of-bounds read;/// every call site here is already inside a bounds check that the TypeScript/// performs first, so `None` reaches a refusal rather than a panic.fn u16_le(bytes: &[u8], offset: usize) -> Option<u16> {    let slice = bytes.get(offset..offset + 2)?;    Some(u16::from_le_bytes([slice[0], slice[1]]))}/// `DataView.getUint32(offset, true)`.fn u32_le(bytes: &[u8], offset: usize) -> Option<u32> {    let slice = bytes.get(offset..offset + 4)?;    Some(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))}/// `strFromU8` — fflate's UTF-8 decoder, which in Node is `TextDecoder`.////// A `TextDecoder` without `fatal: true` substitutes U+FFFD for an invalid/// sequence, which is exactly `String::from_utf8_lossy`. An entry name is/// therefore never a reason to refuse an archive: a WhatsApp export written on/// a phone with a CP437 filename still lists, it just lists with a replacement/// character where the byte was.fn str_from_u8(bytes: &[u8]) -> String {    String::from_utf8_lossy(bytes).into_owned()}/// Scan BACKWARDS for the end-of-central-directory signature.////// Backwards because the record sits at the very end unless the archive/// carries a comment, and the comment may itself contain the signature — the/// LAST match is the real one. The loop starts at `tail.len() - 22` and stops/// at 0; a tail shorter than 22 bytes never enters it, and falls straight/// through to the refusal.fn find_end_of_central_directory(tail: &[u8]) -> Result<usize, ZipError> {    if tail.len() >= EOCD_MIN_SIZE as usize {        let mut offset = tail.len() - EOCD_MIN_SIZE as usize;        loop {            if u32_le(tail, offset) == Some(EOCD_SIGNATURE) {                return Ok(offset);            }            if offset == 0 {                break;            }            offset -= 1;        }    }    Err(format_error(        "Not a zip file (no end-of-central-directory record found).",    ))}struct CentralDirectoryLocation {    total_entries: u64,    central_offset: u64,    central_size: u64,}fn read_eocd(tail: &[u8], eocd_offset: usize) -> Result<CentralDirectoryLocation, ZipError> {    let total_entries = u16_le(tail, eocd_offset + 10)        .ok_or_else(|| format_error("Corrupt end-of-central-directory record."))?;    let central_size = u32_le(tail, eocd_offset + 12)        .ok_or_else(|| format_error("Corrupt end-of-central-directory record."))?;    let central_offset = u32_le(tail, eocd_offset + 16)        .ok_or_else(|| format_error("Corrupt end-of-central-directory record."))?;    if central_offset == ZIP64_SENTINEL_32 || total_entries == ZIP64_SENTINEL_16 {        return Err(format_error(            "This is a ZIP64 archive, which this reader does not support. Unzip it yourself and point the importer at the extracted folder instead.",        ));    }    Ok(CentralDirectoryLocation {        total_entries: u64::from(total_entries),        central_offset: u64::from(central_offset),        central_size: u64::from(central_size),    })}/// Parse `total_entries` central-directory records out of `directory` (a byte/// slice that STARTS at the central directory).////// Shared by the whole-archive and ranged paths so the two can never drift —/// which is the property `zip.test.ts` exists to hold, entry for entry and byte/// for byte.fn parse_central_entries(directory: &[u8], total_entries: u64) -> Result<Vec<ZipEntry>, ZipError> {    let mut entries: Vec<ZipEntry> = Vec::new();    let mut cursor: usize = 0;    for index in 0..total_entries {        let corrupt = || {            format_error(format!(                "Corrupt central directory at entry {} of {total_entries}.",                index + 1            ))        };        if cursor + 46 > directory.len() || u32_le(directory, cursor) != Some(CENTRAL_SIGNATURE) {            return Err(corrupt());        }        let flags = u16_le(directory, cursor + 8).ok_or_else(corrupt)?;        let method = u16_le(directory, cursor + 10).ok_or_else(corrupt)?;        let compressed_size = u32_le(directory, cursor + 20).ok_or_else(corrupt)?;        let uncompressed_size = u32_le(directory, cursor + 24).ok_or_else(corrupt)?;        let name_length = u16_le(directory, cursor + 28).ok_or_else(corrupt)? as usize;        let extra_length = u16_le(directory, cursor + 30).ok_or_else(corrupt)? as usize;        let comment_length = u16_le(directory, cursor + 32).ok_or_else(corrupt)? as usize;        let local_header_offset = u32_le(directory, cursor + 42).ok_or_else(corrupt)?;        // `subarray` CLAMPS in JavaScript rather than throwing, so a truncated        // final record yields a short name rather than an error. Reproduced        // with a saturating end.        let name_start = cursor + 46;        let name_end = (name_start + name_length).min(directory.len());        let name = str_from_u8(&directory[name_start..name_end]);        entries.push(ZipEntry {            name,            compressed_size: u64::from(compressed_size),            uncompressed_size: u64::from(uncompressed_size),            method,            flags,            local_header_offset: u64::from(local_header_offset),        });        cursor += 46 + name_length + extra_length + comment_length;    }    Ok(entries)}/// The ceiling on what one entry may inflate to.////// The central directory declares an entry's uncompressed size, and this/// reader trusts that declaration for the allocation — but a hostile archive/// can declare 4 GiB, so the limit is the DECLARED size plus a page of slack/// rather than an open-ended `decompress_to_vec`. `fflate`'s `inflateSync`/// grows its own buffer without a bound; a phone that swaps to death is a/// jetsam kill, so the port is deliberately stricter here and says so.fn inflate_limit(entry: &ZipEntry) -> usize {    usize::try_from(entry.uncompressed_size.saturating_add(4096)).unwrap_or(usize::MAX)}fn inflate_entry(entry: &ZipEntry, data: &[u8]) -> Result<Vec<u8>, ZipError> {    if entry.method == METHOD_STORE {        return Ok(data.to_vec());    }    if entry.method == METHOD_DEFLATE {        return miniz_oxide::inflate::decompress_to_vec_with_limit(data, inflate_limit(entry))            .map_err(|error| {                ZipError::Inflate(format!(                    "\"{}\" could not be inflated ({:?}).",                    entry.name, error.status                ))            });    }    Err(format_error(format!(        "\"{}\" uses compression method {}, which this reader does not support.",        entry.name, entry.method    )))}fn assert_readable(entry: &ZipEntry) -> Result<(), ZipError> {    if (entry.flags & FLAG_ENCRYPTED) != 0 {        return Err(format_error(format!(            "\"{}\" is encrypted; this reader cannot open it.",            entry.name        )));    }    Ok(())}/// Every entry in the archive, from the central directory.pub fn list_zip_entries(bytes: &[u8]) -> Result<Vec<ZipEntry>, ZipError> {    let len = bytes.len() as u64;    let tail_start = len.saturating_sub(EOCD_MAX_SEARCH);    let tail = &bytes[tail_start as usize..];    let eocd_in_tail = find_end_of_central_directory(tail)?;    let location = read_eocd(tail, eocd_in_tail)?;    let eocd_absolute = tail_start + eocd_in_tail as u64;    if location.central_offset > eocd_absolute {        return Err(format_error(            "Corrupt central directory (starts past its own end record).",        ));    }    parse_central_entries(        &bytes[location.central_offset as usize..eocd_absolute as usize],        location.total_entries,    )}/// Decompress one entry from a whole in-memory archive.pub fn read_zip_entry(bytes: &[u8], entry: &ZipEntry) -> Result<Vec<u8>, ZipError> {    assert_readable(entry)?;    if entry.local_header_offset + LOCAL_HEADER_SIZE > bytes.len() as u64 {        return Err(format_error(format!(            "\"{}\" points past the end of the file.",            entry.name        )));    }    let header_at = entry.local_header_offset as usize;    if u32_le(bytes, header_at) != Some(LOCAL_SIGNATURE) {        return Err(format_error(format!(            "\"{}\" has no local file header where the directory says it does.",            entry.name        )));    }    let name_length = u64::from(u16_le(bytes, header_at + 26).unwrap_or(0));    let extra_length = u64::from(u16_le(bytes, header_at + 28).unwrap_or(0));    let data_start = entry.local_header_offset + LOCAL_HEADER_SIZE + name_length + extra_length;    // `bytes.subarray(dataStart, dataStart + compressedSize)` CLAMPS in    // JavaScript. A truncated archive therefore hands a SHORT payload to the    // inflater and fails there, with the inflater's own message, rather than    // failing here — reproduced with a saturating range so the two agree about    // which error a half-downloaded export produces.    let begin = (data_start as usize).min(bytes.len());    let end = ((data_start + entry.compressed_size) as usize).min(bytes.len());    inflate_entry(entry, &bytes[begin..end])}/// Every entry in the archive, reading only the tail of the file.pub fn list_zip_entries_ranged<R: ZipRangeReader + ?Sized>(    reader: &R,) -> Result<Vec<ZipEntry>, ZipError> {    let size = reader.size();    if size < EOCD_MIN_SIZE {        return Err(format_error(            "Not a zip file (too small to hold an end-of-central-directory record).",        ));    }    let tail_length = size.min(EOCD_MAX_SEARCH);    let tail_start = size - tail_length;    let tail = read_exact(reader, tail_start, tail_length)?;    let eocd_in_tail = find_end_of_central_directory(&tail)?;    let location = read_eocd(&tail, eocd_in_tail)?;    let eocd_absolute = tail_start + eocd_in_tail as u64;    if location.central_offset + location.central_size > eocd_absolute        || location.central_offset > size    {        return Err(format_error(            "Corrupt central directory (does not sit before its own end record).",        ));    }    // The directory may already be inside the tail we read; reuse it if so.    let directory: Vec<u8> = if location.central_offset >= tail_start {        let begin = (location.central_offset - tail_start) as usize;        let end = (eocd_absolute - tail_start) as usize;        tail[begin..end].to_vec()    } else {        read_exact(            reader,            location.central_offset,            eocd_absolute - location.central_offset,        )?    };    parse_central_entries(&directory, location.total_entries)}/// `reader.read`, with the short-read check the TypeScript's contract assumes/// but does not perform.fn read_exact<R: ZipRangeReader + ?Sized>(    reader: &R,    offset: u64,    length: u64,) -> Result<Vec<u8>, ZipError> {    let bytes = reader.read(offset, length)?;    if bytes.len() as u64 != length {        return Err(ZipError::Reader(format!(            "short read: asked for {length} bytes at {offset}, got {}.",            bytes.len()        )));    }    Ok(bytes)}/// True when the entry's payload is the file's bytes as-is (method "store").pub fn is_stored_entry(entry: &ZipEntry) -> bool {    entry.method == METHOD_STORE}/// Where one entry's PAYLOAD sits in the archive — validated against the local/// header, exactly as [`read_zip_entry_ranged`] validates before reading.////// Exists for the streaming extractor: a phone copying a STORED 80 MB video out/// of an export should read it in windows straight to disk, never as one 80 MB/// buffer — and the payload offset is the one fact it needs that the central/// directory alone does not carry (the local header's name/extra lengths can/// differ from the directory's).pub fn zip_entry_data_range<R: ZipRangeReader + ?Sized>(    reader: &R,    entry: &ZipEntry,) -> Result<ZipDataRange, ZipError> {    assert_readable(entry)?;    let size = reader.size();    if entry.local_header_offset + LOCAL_HEADER_SIZE > size {        return Err(format_error(format!(            "\"{}\" points past the end of the file.",            entry.name        )));    }    let header = read_exact(reader, entry.local_header_offset, LOCAL_HEADER_SIZE)?;    if u32_le(&header, 0) != Some(LOCAL_SIGNATURE) {        return Err(format_error(format!(            "\"{}\" has no local file header where the directory says it does.",            entry.name        )));    }    let name_length = u64::from(u16_le(&header, 26).unwrap_or(0));    let extra_length = u64::from(u16_le(&header, 28).unwrap_or(0));    let data_start = entry.local_header_offset + LOCAL_HEADER_SIZE + name_length + extra_length;    if data_start + entry.compressed_size > size {        return Err(format_error(format!(            "\"{}\" data runs past the end of the file.",            entry.name        )));    }    Ok(ZipDataRange {        offset: data_start,        length: entry.compressed_size,    })}/// Decompress one entry, reading only that entry's byte range.pub fn read_zip_entry_ranged<R: ZipRangeReader + ?Sized>(    reader: &R,    entry: &ZipEntry,) -> Result<Vec<u8>, ZipError> {    let range = zip_entry_data_range(reader, entry)?;    // A zero-length entry is never read at all — asking a reader for zero bytes    // is the kind of request a phone's file layer answers with an error.    let data = if range.length == 0 {        Vec::new()    } else {        read_exact(reader, range.offset, range.length)?    };    inflate_entry(entry, &data)}/// Directory entries and macOS resource forks are never content.pub fn is_content_entry(entry: &ZipEntry) -> bool {    if entry.name.ends_with('/') {        return false;    }    // `name.split("/").pop() ?? name` — a `split` on a non-empty separator    // never yields an empty list in JavaScript, so the `??` arm is    // unreachable; `rsplit` gives the same last segment.    let base = entry.name.rsplit('/').next().unwrap_or(&entry.name);    !entry.name.starts_with("__MACOSX/") && !base.starts_with("._") && base != ".DS_Store"}#[cfg(test)]#[path = "zip_tests.rs"]mod tests;