zipatch-rs 1.2.0

Parser for FFXIV ZiPatch patch files
Documentation
use binrw::{BinRead, BinResult, Endian};
use std::io::Cursor;

use super::SqpackFile;

/// Which `SqPack` file kind a [`SqpkHeader`] targets.
///
/// Encoded as a single ASCII byte in the wire format:
/// `b'D'` → [`Dat`](TargetFileKind::Dat), `b'I'` → [`Index`](TargetFileKind::Index).
/// Any other byte is rejected with a [`binrw::Error::Custom`].
///
/// See `SqpkHeader.cs` in the `XIVLauncher` reference implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetFileKind {
    /// Target is a `.datN` data file.
    Dat,
    /// Target is a `.indexN` index file.
    Index,
}

/// Which header slot a [`SqpkHeader`] writes into.
///
/// `SqPack` files contain two 1024-byte header regions at fixed offsets:
///
/// | Variant | File offset | Description |
/// |---------|------------|-------------|
/// | [`Version`](TargetHeaderKind::Version) | 0 | Version/magic header |
/// | [`Index`](TargetHeaderKind::Index) | 1024 | Index structure header |
/// | [`Data`](TargetHeaderKind::Data) | 1024 | Data structure header |
///
/// Both `Index` and `Data` map to file offset 1024; the distinction is semantic
/// (which file type they accompany) but the write offset is the same for both.
///
/// Encoded as a single ASCII byte: `b'V'` → `Version`, `b'I'` → `Index`,
/// `b'D'` → `Data`. Any other byte is rejected with a [`binrw::Error::Custom`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetHeaderKind {
    /// Version header, written at file offset `0`.
    Version,
    /// Index header, written at file offset `1024`.
    Index,
    /// Data header, written at file offset `1024`.
    Data,
}

/// Resolved file target for a [`SqpkHeader`], tagged by [`TargetFileKind`].
///
/// Wraps the [`SqpackFile`] identifier so that the apply layer can resolve the
/// correct on-disk path without carrying a separate `TargetFileKind` value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SqpkHeaderTarget {
    /// The header is destined for a `.datN` file.
    Dat(SqpackFile),
    /// The header is destined for a `.indexN` file.
    Index(SqpackFile),
}

fn read_file_kind<R: std::io::Read + std::io::Seek>(
    reader: &mut R,
    _: Endian,
    (): (),
) -> BinResult<TargetFileKind> {
    let byte = <u8 as BinRead>::read_options(reader, Endian::Big, ())?;
    match byte {
        b'D' => Ok(TargetFileKind::Dat),
        b'I' => Ok(TargetFileKind::Index),
        _ => Err(binrw::Error::Custom {
            pos: 0,
            err: Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "unknown SqpkHeader file kind",
            )),
        }),
    }
}

fn read_header_kind<R: std::io::Read + std::io::Seek>(
    reader: &mut R,
    _: Endian,
    (): (),
) -> BinResult<TargetHeaderKind> {
    let byte = <u8 as BinRead>::read_options(reader, Endian::Big, ())?;
    match byte {
        b'V' => Ok(TargetHeaderKind::Version),
        b'I' => Ok(TargetHeaderKind::Index),
        b'D' => Ok(TargetHeaderKind::Data),
        _ => Err(binrw::Error::Custom {
            pos: 0,
            err: Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "unknown SqpkHeader header kind",
            )),
        }),
    }
}

fn read_header_target<R: std::io::Read + std::io::Seek>(
    reader: &mut R,
    endian: Endian,
    (file_kind,): (&TargetFileKind,),
) -> BinResult<SqpkHeaderTarget> {
    let f = SqpackFile::read_options(reader, endian, ())?;
    match file_kind {
        TargetFileKind::Dat => Ok(SqpkHeaderTarget::Dat(f)),
        TargetFileKind::Index => Ok(SqpkHeaderTarget::Index(f)),
    }
}

/// SQPK `H` command body: write a 1024-byte `SqPack` header into a target file.
///
/// Every `SqPack` file (both `.dat` and `.index`) begins with one or two
/// 1024-byte header blocks at fixed offsets. The `H` command replaces one of
/// these headers atomically as part of a patch.
///
/// ## Wire format (all big-endian unless noted)
///
/// ```text
/// ┌──────────────────────────────────────────────────────────────┐
/// │ file_kind   : u8      b'D' = Dat, b'I' = Index              │  byte 0
/// │ header_kind : u8      b'V' = Version, b'I' = Index, b'D' = Data │  byte 1
/// │ <padding>   : u8      (reserved, always 0)                   │  byte 2
/// │ main_id     : u16 BE  SqPack category ID                     │  bytes 3–4
/// │ sub_id      : u16 BE  SqPack sub-category ID                 │  bytes 5–6
/// │ file_id     : u32 BE  dat/index file index                   │  bytes 7–10
/// │ header_data : [u8; 1024]  raw header bytes                   │  bytes 11–1034
/// └──────────────────────────────────────────────────────────────┘
/// ```
///
/// ## Apply behaviour
///
/// - [`TargetHeaderKind::Version`] → write `header_data` at file offset **0**.
/// - [`TargetHeaderKind::Index`] or [`TargetHeaderKind::Data`] → write at
///   file offset **1024**.
///
/// The target file is opened via the apply context's handle cache; the write
/// does not truncate or resize the file.
///
/// ## Reference
///
/// See `SqpkHeader.cs` in the `XIVLauncher` reference implementation.
///
/// # Errors
///
/// Parsing returns [`crate::ZiPatchError::BinrwError`] if:
/// - `file_kind` is not `b'D'` or `b'I'`.
/// - `header_kind` is not `b'V'`, `b'I'`, or `b'D'`.
/// - The body is too short to contain a full 1024-byte `header_data`.
#[derive(BinRead, Debug, Clone, PartialEq, Eq)]
#[br(big)]
pub struct SqpkHeader {
    /// Whether the operation targets a `.dat` or `.index` file.
    ///
    /// Parsed from a single ASCII byte: `b'D'` → `Dat`, `b'I'` → `Index`.
    #[br(parse_with = read_file_kind)]
    pub file_kind: TargetFileKind,
    /// Which of the two header slots to overwrite.
    ///
    /// Parsed from a single ASCII byte: `b'V'` → `Version` (offset 0),
    /// `b'I'` → `Index` (offset 1024), `b'D'` → `Data` (offset 1024).
    #[br(parse_with = read_header_kind)]
    pub header_kind: TargetHeaderKind,
    /// The target `SqPack` file, tagged by [`file_kind`](SqpkHeader::file_kind)
    /// so the apply layer can resolve the correct path without carrying a
    /// separate kind value.
    ///
    /// Preceded by 1 byte of alignment padding in the wire format.
    #[br(pad_before = 1, parse_with = read_header_target, args(&file_kind))]
    pub target: SqpkHeaderTarget,
    /// The 1024-byte block to write into the target file's header slot.
    ///
    /// The content follows the `SqPack` header structure defined by Square
    /// Enix; this crate treats it as an opaque byte array and writes it
    /// verbatim.
    #[br(count = 1024)]
    pub header_data: Vec<u8>,
}

pub(crate) fn parse(body: &[u8]) -> crate::Result<SqpkHeader> {
    Ok(SqpkHeader::read_be(&mut Cursor::new(body))?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_header_dat_version() {
        let mut body = Vec::new();
        body.push(b'D'); // file_kind = Dat
        body.push(b'V'); // header_kind = Version
        body.push(0u8); // alignment
        body.extend_from_slice(&10u16.to_be_bytes()); // main_id
        body.extend_from_slice(&20u16.to_be_bytes()); // sub_id
        body.extend_from_slice(&0u32.to_be_bytes()); // file_id
        body.extend_from_slice(&[0xCCu8; 1024]); // header_data

        let cmd = parse(&body).unwrap();
        assert!(matches!(cmd.file_kind, TargetFileKind::Dat));
        assert!(matches!(cmd.header_kind, TargetHeaderKind::Version));
        match cmd.target {
            SqpkHeaderTarget::Dat(f) => {
                assert_eq!(f.main_id, 10);
                assert_eq!(f.sub_id, 20);
            }
            other @ SqpkHeaderTarget::Index(_) => {
                panic!("expected SqpkHeaderTarget::Dat, got {other:?}")
            }
        }
        assert_eq!(cmd.header_data.len(), 1024);
    }

    #[test]
    fn rejects_unknown_file_kind() {
        let mut body = Vec::new();
        body.push(b'Z'); // invalid
        body.push(b'V');
        body.push(0u8);
        body.extend_from_slice(&[0u8; 8 + 1024]);
        assert!(parse(&body).is_err());
    }

    #[test]
    fn rejects_unknown_header_kind() {
        let mut body = Vec::new();
        body.push(b'D');
        body.push(b'Z'); // invalid header_kind
        body.push(0u8);
        body.extend_from_slice(&[0u8; 8 + 1024]);
        assert!(parse(&body).is_err());
    }

    #[test]
    fn parses_header_index_file() {
        let mut body = Vec::new();
        body.push(b'I'); // file_kind = Index
        body.push(b'I'); // header_kind = Index
        body.push(0u8);
        body.extend_from_slice(&7u16.to_be_bytes()); // main_id
        body.extend_from_slice(&8u16.to_be_bytes()); // sub_id
        body.extend_from_slice(&0u32.to_be_bytes()); // file_id
        body.extend_from_slice(&[0xBBu8; 1024]);

        let cmd = parse(&body).unwrap();
        assert!(matches!(cmd.file_kind, TargetFileKind::Index));
        assert!(matches!(cmd.header_kind, TargetHeaderKind::Index));
        match cmd.target {
            SqpkHeaderTarget::Index(f) => {
                assert_eq!(f.main_id, 7);
                assert_eq!(f.sub_id, 8);
            }
            other @ SqpkHeaderTarget::Dat(_) => {
                panic!("expected SqpkHeaderTarget::Index, got {other:?}")
            }
        }
        assert_eq!(cmd.header_data.len(), 1024);
    }

    #[test]
    fn header_data_truncated() {
        let mut body = Vec::new();
        body.push(b'D');
        body.push(b'V');
        body.push(0u8);
        body.extend_from_slice(&[0u8; 8]);
        body.extend_from_slice(&[0u8; 512]); // only 512, need 1024
        assert!(parse(&body).is_err());
    }
}