f-office-opc 0.2.4

Open Packaging Conventions container: ZIP package and relationships, with input limits.
Documentation
//! Where the records of a ZIP file lie, as the package writer needs them: each entry's local
//! header, data and data descriptor, its central record, the central directory and its end
//! record (PKWARE's ZIP file format specification, APPNOTE.TXT, sections 4.3 and 4.4).

use std::ops::Range;

use super::{LayoutFault, WriteError};

/// The signature of a local file header.
pub(super) const LOCAL_SIGNATURE: u32 = 0x0403_4b50;
/// The signature of a central directory record.
pub(super) const CENTRAL_SIGNATURE: u32 = 0x0201_4b50;
/// The signature of the end of central directory record.
const END_SIGNATURE: u32 = 0x0605_4b50;
/// The signature of the ZIP64 end of central directory locator.
const ZIP64_LOCATOR_SIGNATURE: u32 = 0x0706_4b50;
/// The signature that may start a data descriptor.
const DESCRIPTOR_SIGNATURE: u32 = 0x0807_4b50;
/// The bytes of a local file header before its name.
pub(super) const LOCAL_HEADER: usize = 30;
/// The bytes of a central directory record before its name.
pub(super) const CENTRAL_HEADER: usize = 46;
/// The bytes of the end of central directory record before its comment.
const END_RECORD: usize = 22;
/// The bytes of the ZIP64 end of central directory locator.
const ZIP64_LOCATOR: usize = 20;
/// The ID of the ZIP64 extended information extra field.
const ZIP64_EXTRA: u16 = 0x0001;
/// The value of a field of 32 bits that a ZIP64 extra field holds in its place.
const ZIP64_MARK_32: u32 = u32::MAX;
/// The value of a field of 16 bits that a ZIP64 record holds in its place.
const ZIP64_MARK_16: u16 = u16::MAX;
/// The flag of an entry whose CRC and sizes follow its data in a data descriptor.
const DESCRIPTOR_FLAG: u16 = 1 << 3;

/// Where the records of a ZIP file lie.
#[derive(Debug)]
pub(super) struct Layout {
    /// The entries, in the order of the central directory.
    pub entries: Vec<Entry>,
    /// The central directory.
    pub central: Range<usize>,
    /// The end of central directory record with its comment, which ends the file.
    pub end: Range<usize>,
}

/// Where one entry's records lie.
#[derive(Debug)]
pub(super) struct Entry {
    /// The central directory record, with its name, extra field and comment.
    pub record: Range<usize>,
    /// The name in the central directory record.
    pub name: Range<usize>,
    /// The local file header, the data and the data descriptor.
    pub local: Range<usize>,
    /// The extra field of the local file header.
    pub local_extra: Range<usize>,
}

/// The value of 16 bits at `at`, little-endian.
pub(super) fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {
    let field = bytes.get(at..at.checked_add(2)?)?;
    Some(u16::from_le_bytes(field.try_into().ok()?))
}

/// The value of 32 bits at `at`, little-endian.
pub(super) fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
    let field = bytes.get(at..at.checked_add(4)?)?;
    Some(u32::from_le_bytes(field.try_into().ok()?))
}

/// The value of 16 bits at `at` as a length or a count.
fn length_at(bytes: &[u8], at: usize) -> Result<usize, WriteError> {
    u16_at(bytes, at)
        .map(usize::from)
        .ok_or(WriteError::Layout(LayoutFault::Truncated))
}

/// The value of 32 bits at `at` as an offset or a size.
fn offset_at(bytes: &[u8], at: usize) -> Result<usize, WriteError> {
    let value = u32_at(bytes, at).ok_or(WriteError::Layout(LayoutFault::Truncated))?;
    if value == ZIP64_MARK_32 {
        return Err(WriteError::Zip64);
    }
    usize::try_from(value).map_err(|_| WriteError::TooLarge)
}

/// Reads where the records of the ZIP file `bytes` lie.
///
/// # Errors
///
/// Returns [`WriteError::Zip64`] for a file that uses ZIP64, and [`WriteError::Layout`] for
/// records that are not where the end record and the central directory say, that overlap, or
/// that span more than one disk.
pub(super) fn read(bytes: &[u8]) -> Result<Layout, WriteError> {
    let end = end_record(bytes)?;
    let field = |offset: usize| length_at(bytes, end.start + offset);
    if field(4)? != 0 || field(6)? != 0 || field(8)? != field(10)? {
        return Err(WriteError::Layout(LayoutFault::MultiDisk));
    }
    let locator = end.start.checked_sub(ZIP64_LOCATOR);
    let zip64_locator = locator.and_then(|at| u32_at(bytes, at)) == Some(ZIP64_LOCATOR_SIGNATURE);
    if zip64_locator || field(10)? == usize::from(ZIP64_MARK_16) {
        return Err(WriteError::Zip64);
    }
    let size = offset_at(bytes, end.start + 12)?;
    let start = offset_at(bytes, end.start + 16)?;
    let central = start..start.checked_add(size).ok_or(WriteError::TooLarge)?;
    if central.end > end.start {
        return Err(WriteError::Layout(LayoutFault::CentralDirectory));
    }
    let mut entries = Vec::new();
    let mut at = central.start;
    for _ in 0..field(10)? {
        let entry = central_record(bytes, at, &central)?;
        at = entry.record.end;
        entries.push(entry);
    }
    if at != central.end {
        return Err(WriteError::Layout(LayoutFault::CentralDirectory));
    }
    check_apart(&entries)?;
    Ok(Layout {
        entries,
        central,
        end,
    })
}

/// The end of central directory record: the last one whose comment ends the file.
fn end_record(bytes: &[u8]) -> Result<Range<usize>, WriteError> {
    let last = bytes
        .len()
        .checked_sub(END_RECORD)
        .ok_or(WriteError::Layout(LayoutFault::NoEndRecord))?;
    let first = last.saturating_sub(usize::from(u16::MAX));
    (first..=last)
        .rev()
        .find(|&at| {
            u32_at(bytes, at) == Some(END_SIGNATURE)
                && u16_at(bytes, at + 20).map(usize::from) == Some(last - at)
        })
        .map(|at| at..bytes.len())
        .ok_or(WriteError::Layout(LayoutFault::NoEndRecord))
}

/// The central directory record at `at`, which must lie in `central`, with its local entry.
fn central_record(bytes: &[u8], at: usize, central: &Range<usize>) -> Result<Entry, WriteError> {
    if u32_at(bytes, at) != Some(CENTRAL_SIGNATURE) {
        return Err(WriteError::Layout(LayoutFault::CentralDirectory));
    }
    let name = at + CENTRAL_HEADER..at + CENTRAL_HEADER + length_at(bytes, at + 28)?;
    let extra = name.end..name.end + length_at(bytes, at + 30)?;
    let record = at..extra.end + length_at(bytes, at + 32)?;
    if record.end > central.end || length_at(bytes, at + 34)? != 0 {
        return Err(WriteError::Layout(LayoutFault::CentralDirectory));
    }
    if has_zip64_field(bytes, &extra) || u32_at(bytes, at + 24) == Some(ZIP64_MARK_32) {
        return Err(WriteError::Zip64);
    }
    let compressed = offset_at(bytes, at + 20)?;
    let flags = u16_at(bytes, at + 8).ok_or(WriteError::Layout(LayoutFault::Truncated))?;
    let (local, local_extra) = local_entry(bytes, offset_at(bytes, at + 42)?, (compressed, flags))?;
    if local.end > central.start {
        return Err(WriteError::Layout(LayoutFault::LocalHeader));
    }
    Ok(Entry {
        record,
        name,
        local,
        local_extra,
    })
}

/// The local entry at `at` whose data has `compressed` bytes and whose flags are `flags`: its
/// header, data and data descriptor, with the header's extra field.
fn local_entry(
    bytes: &[u8],
    at: usize,
    (compressed, flags): (usize, u16),
) -> Result<(Range<usize>, Range<usize>), WriteError> {
    if u32_at(bytes, at) != Some(LOCAL_SIGNATURE) {
        return Err(WriteError::Layout(LayoutFault::LocalHeader));
    }
    let name_end = at + LOCAL_HEADER + length_at(bytes, at + 26)?;
    let extra = name_end..name_end + length_at(bytes, at + 28)?;
    if has_zip64_field(bytes, &extra) {
        return Err(WriteError::Zip64);
    }
    let data_end = extra
        .end
        .checked_add(compressed)
        .ok_or(WriteError::TooLarge)?;
    let descriptor = if flags & DESCRIPTOR_FLAG == 0 {
        0
    } else if u32_at(bytes, data_end) == Some(DESCRIPTOR_SIGNATURE) {
        16
    } else {
        12
    };
    let end = data_end + descriptor;
    if end > bytes.len() {
        return Err(WriteError::Layout(LayoutFault::LocalHeader));
    }
    Ok((at..end, extra))
}

/// Whether the extra field `extra` holds a ZIP64 extended information field.
fn has_zip64_field(bytes: &[u8], extra: &Range<usize>) -> bool {
    let mut at = extra.start;
    while at + 4 <= extra.end {
        let (Some(id), Some(size)) = (u16_at(bytes, at), u16_at(bytes, at + 2)) else {
            return false;
        };
        if id == ZIP64_EXTRA {
            return true;
        }
        at += 4 + usize::from(size);
    }
    false
}

/// Checks that no two entries' local records overlap.
fn check_apart(entries: &[Entry]) -> Result<(), WriteError> {
    let mut locals: Vec<&Range<usize>> = entries.iter().map(|entry| &entry.local).collect();
    locals.sort_by_key(|local| local.start);
    if locals.windows(2).any(|pair| match pair {
        [before, after] => after.start < before.end,
        _ => false,
    }) {
        return Err(WriteError::Layout(LayoutFault::Overlap));
    }
    Ok(())
}