Skip to main content

zipatch_rs/chunk/sqpk/
mod.rs

1//! SQPK chunk sub-commands and their dispatcher.
2//!
3//! A `ZiPatch` file is made up of top-level chunks; the `SQPK` chunk type is the
4//! workhorse — it covers the vast majority of the data in any patch file.
5//! Inside each `SQPK` chunk sits a one-byte sub-command tag that selects the
6//! specific archive operation to perform.
7//!
8//! # Sub-command overview
9//!
10//! | Tag | Type | Purpose |
11//! |-----|------|---------|
12//! | `A` | [`SqpkAddData`] | Write a data payload into a `.dat` file at a block offset |
13//! | `D` | [`SqpkDeleteData`] | Overwrite a block range with empty-block markers |
14//! | `E` | [`SqpkExpandData`] | Grow a `.dat` file by adding empty-block markers |
15//! | `H` | [`SqpkHeader`] | Write a 1024-byte `SqPack` header |
16//! | `T` | [`SqpkTargetInfo`] | Declare the target platform and region |
17//! | `F` | [`SqpkFile`] | File-level operation (add, delete, directory creation) |
18//! | `I` | [`SqpkIndex`] | Index entry metadata (not applied directly to disk) |
19//! | `X` | [`SqpkPatchInfo`] | Patch install metadata (not applied directly to disk) |
20//!
21//! Unknown sub-command bytes are surfaced as [`ParseError::UnknownSqpkCommand`].
22//!
23//! # Wire format
24//!
25//! The SQPK chunk body begins with a 4-byte big-endian `i32` (`inner_size`) that
26//! must equal the total body length, followed immediately by the 1-byte sub-command
27//! tag. The remaining bytes starting at offset 5 form the sub-command body and are
28//! forwarded to the per-command parser.
29//!
30//! ```text
31//! ┌────────────────────────────────────────────────────┐
32//! │ inner_size   : i32 BE  (== body.len())             │  bytes 0–3
33//! │ sub-command  : u8      ('A','D','E','H','T','F',…)  │  byte  4
34//! │ sub-cmd body : [u8]    (varies by sub-command)      │  bytes 5–…
35//! └────────────────────────────────────────────────────┘
36//! ```
37//!
38//! # Block-offset units
39//!
40//! Unless otherwise noted, offsets in SQPK sub-commands are stored as raw `u32`
41//! values that must be multiplied by 128 (`<< 7`) to obtain byte offsets. The
42//! shift is applied automatically during parsing by the `#[br(map = ...)]`
43//! attributes on each struct field; by the time a parsed struct reaches calling
44//! code, all `block_offset` fields are already in bytes.
45
46pub(crate) mod add_data;
47pub(crate) mod delete_data;
48pub(crate) mod expand_data;
49pub(crate) mod file;
50pub(crate) mod header;
51pub(crate) mod index;
52pub(crate) mod target_info;
53
54pub(crate) use add_data::SqpkAddData;
55pub(crate) use delete_data::SqpkDeleteData;
56pub(crate) use expand_data::SqpkExpandData;
57pub use file::SqpkCompressedBlock;
58pub(crate) use file::{SqpkFile, SqpkFileOperation};
59pub(crate) use header::{SqpkHeader, SqpkHeaderTarget, TargetHeaderKind};
60pub(crate) use index::{SqpkIndex, SqpkPatchInfo};
61pub(crate) use target_info::SqpkTargetInfo;
62
63use crate::reader::ReadExt;
64use crate::{ParseError, ParseResult as Result};
65use binrw::BinRead;
66use std::io::Cursor;
67
68/// Identifier of a `SqPack` file targeted by a SQPK command.
69///
70/// `SqPack` files live under
71/// `<game_root>/sqpack/<expansion>/<main_id:02x><sub_id:04x>.<platform>.<kind>`.
72/// The three fields together uniquely address one file on disk; see the
73/// `apply::path` module for how they are combined into filesystem paths.
74#[derive(BinRead, Debug, Clone, PartialEq, Eq, Hash)]
75#[br(big)]
76pub struct SqpackFileId {
77    /// Category/repository identifier — the first two hex digits of the filename
78    /// stem (e.g. `04` in `040100.win32.dat0`).
79    ///
80    /// Encoded as a big-endian `u16` (2 bytes) in the wire format.
81    pub main_id: u16,
82    /// Sub-category identifier — the next four hex digits of the filename stem
83    /// (e.g. `0100` in `040100.win32.dat0`).
84    ///
85    /// Encoded as a big-endian `u16` (2 bytes). The **high byte** (`sub_id >> 8`)
86    /// selects the expansion folder: `0` → `ffxiv`, `1` → `ex1`, `2` → `ex2`, etc.
87    pub sub_id: u16,
88    /// File index within the category, used to derive the numeric suffix:
89    ///
90    /// - For `.dat` files: appended directly as the decimal `N` in `.datN`.
91    /// - For `.index` files: `0` produces no suffix (`.index`); `1` or higher
92    ///   appends the value directly (`.index1`, `.index2`, …).
93    ///
94    /// Encoded as a big-endian `u32` (4 bytes).
95    pub file_id: u32,
96}
97
98/// Sub-command of a `SQPK` chunk; the variant is selected by the command byte.
99///
100/// Each variant wraps the parsed body of its corresponding sub-command.
101/// `AddData` and `File` are heap-allocated to keep the enum from inflating the
102/// stack when used in iterators — `SqpkAddData` can carry a large inline data
103/// `Vec`, and `SqpkFile` carries both a path and a `Vec` of compressed blocks.
104///
105/// Two variants — `Index` and `PatchInfo` — carry metadata consumed by the
106/// indexed `ZiPatch` reader (not yet implemented) and have no direct filesystem
107/// effect; their [`SqpkCommand::apply`] arms return `Ok(())` immediately.
108///
109/// Unknown sub-command bytes are never silently ignored: they surface as
110/// [`ParseError::UnknownSqpkCommand`] during parsing.
111#[derive(Debug)]
112pub enum SqpkCommand {
113    /// SQPK `A` — write a data payload into a `.dat` file at a block offset,
114    /// then zero a trailing range of blocks. See [`SqpkAddData`].
115    AddData(Box<SqpkAddData>),
116    /// SQPK `D` — overwrite a contiguous block range with empty-block markers,
117    /// logically freeing those blocks in the `SqPack` archive. See [`SqpkDeleteData`].
118    DeleteData(SqpkDeleteData),
119    /// SQPK `E` — extend a `.dat` file into previously unallocated space by
120    /// writing empty-block markers. See [`SqpkExpandData`].
121    ExpandData(SqpkExpandData),
122    /// SQPK `H` — write a 1024-byte `SqPack` header into a `.dat` or `.index`
123    /// file at offset 0 (version header) or 1024 (secondary header). See [`SqpkHeader`].
124    Header(SqpkHeader),
125    /// SQPK `T` — declares the target platform and region for all subsequent
126    /// path-resolution operations in this patch. See [`SqpkTargetInfo`].
127    TargetInfo(SqpkTargetInfo),
128    /// SQPK `F` — file-level operation: add a file from inline block payloads,
129    /// delete a file, remove all files in an expansion folder, or create a
130    /// directory tree. See [`SqpkFile`] and [`SqpkFileOperation`].
131    File(Box<SqpkFile>),
132    /// SQPK `I` — add or remove a single `SqPack` index entry. Carries the
133    /// index hash and block location for use by the indexed `ZiPatch` reader;
134    /// has no direct apply effect. See [`SqpkIndex`].
135    Index(SqpkIndex),
136    /// SQPK `X` — patch install info: status, version, and declared post-patch
137    /// install size. Metadata only; not applied to the filesystem. See [`SqpkPatchInfo`].
138    PatchInfo(SqpkPatchInfo),
139}
140
141/// Parse a SQPK chunk body into a [`SqpkCommand`] variant.
142///
143/// `body` must be the raw bytes of the entire SQPK chunk body (everything after
144/// the outer chunk header that the [`crate::chunk`] layer strips). The first
145/// 4 bytes are a big-endian `i32` (`inner_size`) that is validated against
146/// `body.len()`; byte 4 is the sub-command tag; bytes 5 onward are forwarded to
147/// the per-command parser.
148///
149/// # Errors
150///
151/// - [`ParseError::InvalidField`] — the `inner_size` field does not equal
152///   `body.len()`.
153/// - [`ParseError::UnknownSqpkCommand`] — the sub-command byte is not one of
154///   the recognised tags (`A`, `D`, `E`, `H`, `T`, `F`, `I`, `X`).
155/// - Any [`ParseError`] returned by the per-command parser (e.g.
156///   [`ParseError::Decode`] for a truncated sub-command body, or
157///   [`ParseError::UnknownFileOperation`] for an unrecognised `F` operation byte).
158pub(crate) fn parse_sqpk(body: &[u8]) -> Result<SqpkCommand> {
159    let mut c = Cursor::new(body);
160    let inner_size = c.read_i32_be()? as usize;
161    if inner_size != body.len() {
162        return Err(ParseError::InvalidField {
163            context: "SQPK inner size mismatch",
164        });
165    }
166    let command = c.read_u8()?;
167    let cmd_body = &body[5..];
168
169    match command {
170        b'T' => Ok(SqpkCommand::TargetInfo(target_info::parse(cmd_body)?)),
171        b'I' => Ok(SqpkCommand::Index(index::parse_index(cmd_body)?)),
172        b'X' => Ok(SqpkCommand::PatchInfo(index::parse_patch_info(cmd_body)?)),
173        b'A' => Ok(SqpkCommand::AddData(Box::new(add_data::parse(cmd_body)?))),
174        b'D' => Ok(SqpkCommand::DeleteData(delete_data::parse(cmd_body)?)),
175        b'E' => Ok(SqpkCommand::ExpandData(expand_data::parse(cmd_body)?)),
176        b'H' => Ok(SqpkCommand::Header(header::parse(cmd_body)?)),
177        b'F' => Ok(SqpkCommand::File(Box::new(file::parse(cmd_body)?))),
178        _ => Err(ParseError::UnknownSqpkCommand(command)),
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::{SqpkCommand, parse_sqpk};
185
186    fn make_sqpk_body(command: u8, cmd_body: &[u8]) -> Vec<u8> {
187        let total = 5 + cmd_body.len();
188        let mut out = Vec::with_capacity(total);
189        out.extend_from_slice(&(total as i32).to_be_bytes());
190        out.push(command);
191        out.extend_from_slice(cmd_body);
192        out
193    }
194
195    #[test]
196    fn parses_target_info() {
197        let mut cmd_body = Vec::new();
198        cmd_body.extend_from_slice(&[0u8; 3]); // reserved
199        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // platform Win32
200        cmd_body.extend_from_slice(&(-1i16).to_be_bytes()); // region Global
201        cmd_body.extend_from_slice(&0i16.to_be_bytes()); // not debug
202        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // version
203        cmd_body.extend_from_slice(&1234u64.to_le_bytes()); // deleted_data_size
204        cmd_body.extend_from_slice(&5678u64.to_le_bytes()); // seek_count
205
206        let body = make_sqpk_body(b'T', &cmd_body);
207        match parse_sqpk(&body).unwrap() {
208            SqpkCommand::TargetInfo(t) => {
209                assert_eq!(t.platform_id, 0);
210                assert_eq!(t.region, -1);
211                assert!(!t.is_debug);
212                assert_eq!(t.deleted_data_size, 1234);
213                assert_eq!(t.seek_count, 5678);
214            }
215            other => panic!("expected SqpkCommand::TargetInfo, got {other:?}"),
216        }
217    }
218
219    #[test]
220    fn rejects_inner_size_mismatch() {
221        let mut body = Vec::new();
222        body.extend_from_slice(&999i32.to_be_bytes()); // wrong inner_size
223        body.push(b'T');
224        assert!(parse_sqpk(&body).is_err());
225    }
226
227    #[test]
228    fn rejects_unknown_command() {
229        let body = make_sqpk_body(b'Z', &[]);
230        assert!(parse_sqpk(&body).is_err());
231    }
232
233    fn index_cmd_body() -> Vec<u8> {
234        let mut v = Vec::new();
235        v.push(b'A'); // IndexCommand::Add
236        v.push(0u8); // is_synonym = false
237        v.push(0u8); // alignment
238        v.extend_from_slice(&0u16.to_be_bytes()); // main_id
239        v.extend_from_slice(&0u16.to_be_bytes()); // sub_id
240        v.extend_from_slice(&0u32.to_be_bytes()); // file_id
241        v.extend_from_slice(&0u64.to_be_bytes()); // file_hash
242        v.extend_from_slice(&0u32.to_be_bytes()); // block_offset
243        v.extend_from_slice(&0u32.to_be_bytes()); // block_number
244        v
245    }
246
247    #[test]
248    fn parses_index_command() {
249        let body = make_sqpk_body(b'I', &index_cmd_body());
250        assert!(matches!(parse_sqpk(&body).unwrap(), SqpkCommand::Index(_)));
251    }
252
253    #[test]
254    fn parses_patch_info_command() {
255        let mut cmd_body = Vec::new();
256        cmd_body.push(0u8); // status
257        cmd_body.push(0u8); // version
258        cmd_body.push(0u8); // alignment
259        cmd_body.extend_from_slice(&0u64.to_be_bytes()); // install_size
260        let body = make_sqpk_body(b'X', &cmd_body);
261        assert!(matches!(
262            parse_sqpk(&body).unwrap(),
263            SqpkCommand::PatchInfo(_)
264        ));
265    }
266
267    #[test]
268    fn index_command_truncated_body_returns_error() {
269        // Empty `I` body — index::parse_index must error, exercising the `?` arm.
270        let body = make_sqpk_body(b'I', &[]);
271        assert!(parse_sqpk(&body).is_err());
272    }
273
274    #[test]
275    fn patch_info_command_truncated_body_returns_error() {
276        // Empty `X` body — index::parse_patch_info must error, exercising the `?` arm.
277        let body = make_sqpk_body(b'X', &[]);
278        assert!(parse_sqpk(&body).is_err());
279    }
280
281    #[test]
282    fn parses_add_data_command() {
283        let mut cmd_body = Vec::new();
284        cmd_body.extend_from_slice(&[0u8; 3]); // pad
285        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // main_id
286        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // sub_id
287        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // file_id
288        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // block_offset_raw
289        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // data_bytes_raw = 0 → no data
290        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // block_delete_number_raw
291        let body = make_sqpk_body(b'A', &cmd_body);
292        assert!(matches!(
293            parse_sqpk(&body).unwrap(),
294            SqpkCommand::AddData(_)
295        ));
296    }
297
298    #[test]
299    fn parses_delete_data_command() {
300        let mut cmd_body = Vec::new();
301        cmd_body.extend_from_slice(&[0u8; 3]); // pad
302        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // main_id
303        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // sub_id
304        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // file_id
305        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // block_offset_raw
306        cmd_body.extend_from_slice(&1u32.to_be_bytes()); // block_count
307        cmd_body.extend_from_slice(&[0u8; 4]); // reserved
308        let body = make_sqpk_body(b'D', &cmd_body);
309        assert!(matches!(
310            parse_sqpk(&body).unwrap(),
311            SqpkCommand::DeleteData(_)
312        ));
313    }
314
315    #[test]
316    fn parses_expand_data_command() {
317        let mut cmd_body = Vec::new();
318        cmd_body.extend_from_slice(&[0u8; 3]); // pad
319        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // main_id
320        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // sub_id
321        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // file_id
322        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // block_offset_raw
323        cmd_body.extend_from_slice(&1u32.to_be_bytes()); // block_count
324        cmd_body.extend_from_slice(&[0u8; 4]); // reserved
325        let body = make_sqpk_body(b'E', &cmd_body);
326        assert!(matches!(
327            parse_sqpk(&body).unwrap(),
328            SqpkCommand::ExpandData(_)
329        ));
330    }
331
332    #[test]
333    fn parses_header_command() {
334        let mut cmd_body = Vec::new();
335        cmd_body.push(b'D'); // file_kind = Dat
336        cmd_body.push(b'V'); // header_kind = Version
337        cmd_body.push(0u8); // alignment
338        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // main_id
339        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // sub_id
340        cmd_body.extend_from_slice(&0u32.to_be_bytes()); // file_id
341        cmd_body.extend_from_slice(&[0u8; 1024]); // header_data
342        let body = make_sqpk_body(b'H', &cmd_body);
343        assert!(matches!(parse_sqpk(&body).unwrap(), SqpkCommand::Header(_)));
344    }
345
346    #[test]
347    fn parses_file_command() {
348        let mut cmd_body = Vec::new();
349        cmd_body.push(b'A'); // operation = AddFile
350        cmd_body.extend_from_slice(&[0u8; 2]); // alignment
351        cmd_body.extend_from_slice(&0u64.to_be_bytes()); // file_offset
352        cmd_body.extend_from_slice(&0u64.to_be_bytes()); // file_size
353        cmd_body.extend_from_slice(&1u32.to_be_bytes()); // path_len = 1
354        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // expansion_id
355        cmd_body.extend_from_slice(&[0u8; 2]); // padding
356        cmd_body.push(b'\0'); // path = ""
357        let body = make_sqpk_body(b'F', &cmd_body);
358        assert!(matches!(parse_sqpk(&body).unwrap(), SqpkCommand::File(_)));
359    }
360}