zipatch-rs 1.2.0

Parser for FFXIV ZiPatch patch files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::io::Cursor;
use zipatch_rs::chunk::{ApplyFreeSpace, FileHeader, SqpkAddData, SqpkCommand};
use zipatch_rs::test_utils::{make_chunk, make_patch};
use zipatch_rs::{Chunk, ZiPatchError, ZiPatchReader};

#[test]
fn parses_fhdr_v2_then_eof() {
    let mut body = Vec::new();
    body.extend_from_slice(&(2u32 << 16).to_le_bytes());
    body.extend_from_slice(b"D000");
    body.extend_from_slice(&1u32.to_be_bytes());
    body.extend_from_slice(&[0u8; 8]);

    let data = make_patch(&[make_chunk(b"FHDR", &body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();

    let Chunk::FileHeader(FileHeader::V2(h)) = reader.next().unwrap().unwrap() else {
        panic!("expected FileHeader::V2");
    };
    assert_eq!(h.patch_type, *b"D000");
    assert_eq!(h.entry_files, 1);

    assert!(reader.next().is_none());
    assert!(reader.is_complete());
}

#[test]
fn rejects_bad_magic() {
    assert!(ZiPatchReader::new(Cursor::new(b"not a patch file at all")).is_err());
}

#[test]
fn checksum_verification_enabled_accepts_valid_chunk() {
    let mut body = Vec::new();
    body.extend_from_slice(&(2u32 << 16).to_le_bytes());
    body.extend_from_slice(b"D000");
    body.extend_from_slice(&1u32.to_be_bytes());
    body.extend_from_slice(&[0u8; 8]);

    let data = make_patch(&[make_chunk(b"FHDR", &body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data))
        .unwrap()
        .verify_checksums();
    assert!(matches!(
        reader.next().unwrap().unwrap(),
        Chunk::FileHeader(_)
    ));
}

#[test]
fn accepts_zeroed_crc_when_unverified() {
    let mut body = Vec::new();
    body.extend_from_slice(&(2u32 << 16).to_le_bytes());
    body.extend_from_slice(b"D000");
    body.extend_from_slice(&1u32.to_be_bytes());
    body.extend_from_slice(&[0u8; 8]);

    let mut chunk = make_chunk(b"FHDR", &body);
    // zero out the trailing CRC bytes
    let len = chunk.len();
    chunk[len - 4..].fill(0);

    let data = make_patch(&[chunk, make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data))
        .unwrap()
        .skip_checksum_verification();
    assert!(matches!(
        reader.next().unwrap().unwrap(),
        Chunk::FileHeader(_)
    ));
}

#[test]
fn rejects_crc_mismatch() {
    let mut body = Vec::new();
    body.extend_from_slice(&(2u32 << 16).to_le_bytes());
    body.extend_from_slice(b"D000");
    body.extend_from_slice(&0u32.to_be_bytes());
    body.extend_from_slice(&[0u8; 8]);

    let mut chunk = make_chunk(b"FHDR", &body);
    let last = chunk.len() - 1;
    chunk[last] ^= 0xFF;

    let data = make_patch(&[chunk, make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    let err = reader.next().unwrap().unwrap_err();
    let ZiPatchError::ChecksumMismatch { tag, .. } = err else {
        panic!("expected ChecksumMismatch, got {err:?}");
    };
    assert_eq!(&tag, b"FHDR");
}

#[test]
fn rejects_unknown_tag() {
    let data = make_patch(&[make_chunk(b"ZZZZ", &[]), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    assert!(matches!(
        reader.next().unwrap(),
        Err(ZiPatchError::UnknownChunkTag(_))
    ));
}

#[test]
fn iterator_stops_after_error() {
    let mut body = Vec::new();
    body.extend_from_slice(&(2u32 << 16).to_le_bytes());
    body.extend_from_slice(b"D000");
    body.extend_from_slice(&0u32.to_be_bytes());
    body.extend_from_slice(&[0u8; 8]);

    let mut chunk = make_chunk(b"FHDR", &body);
    let last = chunk.len() - 1;
    chunk[last] ^= 0xFF;

    let data = make_patch(&[chunk, make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    assert!(reader.next().unwrap().is_err());
    assert!(reader.next().is_none());
}

#[test]
fn was_complete_true_after_eof() {
    let data = make_patch(&[make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    assert!(reader.next().is_none());
    assert!(reader.is_complete());
    assert!(reader.next().is_none());
}

#[test]
fn parses_aply_chunk() {
    let mut body = Vec::new();
    body.extend_from_slice(&1u32.to_be_bytes()); // kind = IgnoreMissing
    body.extend_from_slice(&[0u8; 4]); // padding
    body.extend_from_slice(&1u32.to_be_bytes()); // value = true

    let data = make_patch(&[make_chunk(b"APLY", &body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    assert!(matches!(
        reader.next().unwrap().unwrap(),
        Chunk::ApplyOption(_)
    ));
}

#[test]
fn parses_apfs_chunk() {
    let mut body = Vec::new();
    body.extend_from_slice(&0u64.to_be_bytes()); // unknown_a
    body.extend_from_slice(&0u64.to_be_bytes()); // unknown_b

    let data = make_patch(&[make_chunk(b"APFS", &body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    let chunk = reader.next().unwrap().unwrap();
    assert!(matches!(
        chunk,
        Chunk::ApplyFreeSpace(ApplyFreeSpace {
            unknown_a: 0,
            unknown_b: 0
        })
    ));
}

#[test]
fn parses_deld_chunk() {
    let mut body = Vec::new();
    body.extend_from_slice(&4u32.to_be_bytes()); // name_len
    body.extend_from_slice(b"test");

    let data = make_patch(&[make_chunk(b"DELD", &body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    assert!(matches!(
        reader.next().unwrap().unwrap(),
        Chunk::DeleteDirectory(_)
    ));
}

#[test]
fn parses_sqpk_chunk() {
    // Minimal TargetInfo SQPK body
    let mut cmd_body = Vec::new();
    cmd_body.extend_from_slice(&[0u8; 3]); // reserved
    cmd_body.extend_from_slice(&0u16.to_be_bytes()); // platform Win32
    cmd_body.extend_from_slice(&(-1i16).to_be_bytes()); // region Global
    cmd_body.extend_from_slice(&0i16.to_be_bytes()); // not debug
    cmd_body.extend_from_slice(&0u16.to_be_bytes()); // version
    cmd_body.extend_from_slice(&0u64.to_le_bytes()); // deleted_data_size
    cmd_body.extend_from_slice(&0u64.to_le_bytes()); // seek_count

    let total_size = (5 + cmd_body.len()) as i32;
    let mut sqpk_body = Vec::new();
    sqpk_body.extend_from_slice(&total_size.to_be_bytes()); // inner_size
    sqpk_body.push(b'T'); // command = TargetInfo
    sqpk_body.extend_from_slice(&cmd_body);

    let data = make_patch(&[make_chunk(b"SQPK", &sqpk_body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();
    assert!(matches!(
        reader.next().unwrap().unwrap(),
        Chunk::Sqpk(SqpkCommand::TargetInfo(_))
    ));
}

#[test]
fn parses_fhdr_v3() {
    let mut body = Vec::new();
    body.extend_from_slice(&(3u32 << 16).to_le_bytes());
    body.extend_from_slice(b"D000");
    body.extend_from_slice(&5u32.to_be_bytes());
    body.extend_from_slice(&7u32.to_be_bytes());
    body.extend_from_slice(&3u32.to_be_bytes());
    body.extend_from_slice(&2u32.to_be_bytes()); // delete_data_size lo
    body.extend_from_slice(&1u32.to_be_bytes()); // delete_data_size hi → 2 | (1<<32)
    body.extend_from_slice(&10u32.to_be_bytes());
    body.extend_from_slice(&0u32.to_be_bytes());
    body.extend_from_slice(&100u32.to_be_bytes());
    body.extend_from_slice(&20u32.to_be_bytes());
    body.extend_from_slice(&5u32.to_be_bytes());
    body.extend_from_slice(&8u32.to_be_bytes());
    body.extend_from_slice(&12u32.to_be_bytes());
    body.extend_from_slice(&30u32.to_be_bytes());
    body.extend_from_slice(&[0u8; 0xB8]);

    let data = make_patch(&[make_chunk(b"FHDR", &body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();

    let Chunk::FileHeader(FileHeader::V3(h)) = reader.next().unwrap().unwrap() else {
        panic!("expected FileHeader::V3");
    };
    assert_eq!(h.patch_type, *b"D000");
    assert_eq!(h.entry_files, 5);
    assert_eq!(h.add_directories, 7);
    assert_eq!(h.delete_directories, 3);
    assert_eq!(h.delete_data_size, 2 | (1u64 << 32));
    assert_eq!(h.commands, 100);
    assert_eq!(h.sqpk_add_commands, 20);
    assert_eq!(h.sqpk_file_commands, 30);
}

// ---------------------------------------------------------------------------
// SQPK 'A' (SqpkAddData) fast-path tests
//
// `parse_sqpk_add_data_fast` is only reached through `ZiPatchReader` when the
// outer chunk tag is `SQPK`, the body is large enough, and the sub-command
// byte is `A`.  These helpers build a full on-wire SQPK 'A' frame so we can
// drive the fast path end-to-end and also exercise its two distinct error arms.
// ---------------------------------------------------------------------------

/// Build a complete SQPK 'A' chunk body from the given field values plus an
/// inline data payload of `data_bytes_raw * 128` zero bytes.
///
/// Layout (all big-endian unless noted):
///   inner_size (i32) | 'A' | 3 pad | main_id (u16) | sub_id (u16)
///   | file_id (u32) | block_offset_raw (u32) | data_bytes_raw (u32)
///   | block_delete_number_raw (u32) | data ([u8; data_bytes])
fn make_sqpk_add_data_body(
    main_id: u16,
    sub_id: u16,
    file_id: u32,
    block_offset_raw: u32,
    data_bytes_raw: u32,
    block_delete_number_raw: u32,
) -> Vec<u8> {
    let data_len = (data_bytes_raw as usize) * 128;
    // Total body = 4 (inner_size) + 1 (sub_cmd) + 23 (fixed header) + data_len
    let total = 5 + 23 + data_len;

    let mut body = Vec::with_capacity(total);
    body.extend_from_slice(&(total as i32).to_be_bytes()); // inner_size
    body.push(b'A'); // sub-command
    body.extend_from_slice(&[0u8; 3]); // 3 bytes padding
    body.extend_from_slice(&main_id.to_be_bytes());
    body.extend_from_slice(&sub_id.to_be_bytes());
    body.extend_from_slice(&file_id.to_be_bytes());
    body.extend_from_slice(&block_offset_raw.to_be_bytes());
    body.extend_from_slice(&data_bytes_raw.to_be_bytes());
    body.extend_from_slice(&block_delete_number_raw.to_be_bytes());
    body.extend(std::iter::repeat(0u8).take(data_len)); // inline payload
    body
}

#[test]
fn parses_sqpk_add_data_chunk_via_zipatch_reader() {
    // End-to-end test for the SQPK 'A' zero-copy fast path
    // (`parse_sqpk_add_data_fast`).  A full patch buffer containing a valid
    // SQPK 'A' chunk is fed to ZiPatchReader; we assert on every field so we
    // know the fast path reconstructed the struct correctly.
    //
    // data_bytes_raw = 1  →  data_bytes = 128  →  128 zero bytes of inline payload
    let sqpk_body = make_sqpk_add_data_body(
        1, // main_id
        2, // sub_id
        3, // file_id
        4, // block_offset_raw → block_offset = 4 * 128 = 512
        1, // data_bytes_raw → data_bytes = 128
        0, // block_delete_number_raw → 0
    );

    let data = make_patch(&[make_chunk(b"SQPK", &sqpk_body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();

    let Chunk::Sqpk(SqpkCommand::AddData(cmd)) = reader.next().unwrap().unwrap() else {
        panic!("expected Chunk::Sqpk(SqpkCommand::AddData(_))");
    };
    let SqpkAddData {
        target_file,
        block_offset,
        data_bytes,
        block_delete_number,
        data,
    } = *cmd;

    assert_eq!(target_file.main_id, 1);
    assert_eq!(target_file.sub_id, 2);
    assert_eq!(target_file.file_id, 3);
    assert_eq!(block_offset, 512); // 4 << 7
    assert_eq!(data_bytes, 128); // 1 << 7
    assert_eq!(block_delete_number, 0);
    assert_eq!(data.len(), 128);
    assert!(data.iter().all(|&b| b == 0));

    assert!(reader.next().is_none());
    assert!(reader.is_complete());
}

#[test]
fn sqpk_add_data_fast_path_inner_size_mismatch_returns_invalid_field() {
    // The fast path validates that the SQPK `inner_size` (first 4 bytes of the
    // body, interpreted as an i32 BE) equals the outer chunk body length.
    // Build a chunk where inner_size is deliberately wrong.
    //
    // We produce a valid-looking SQPK 'A' body but overwrite the first 4 bytes
    // with a wrong inner_size before wrapping it in the outer chunk frame.
    let mut sqpk_body = make_sqpk_add_data_body(0, 0, 0, 0, 0, 0);
    // Overwrite inner_size with (total + 99) — always wrong.
    let wrong_size = (sqpk_body.len() as i32) + 99;
    sqpk_body[0..4].copy_from_slice(&wrong_size.to_be_bytes());

    let data = make_patch(&[make_chunk(b"SQPK", &sqpk_body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();

    match reader.next().unwrap() {
        Err(ZiPatchError::InvalidField { context }) => {
            assert!(
                context.contains("inner size"),
                "error context must mention 'inner size', got: {context}"
            );
        }
        other => panic!("expected InvalidField for inner_size mismatch, got {other:?}"),
    }
}

#[test]
fn sqpk_add_data_fast_path_data_bytes_mismatch_returns_invalid_field() {
    // The fast path validates that `data_bytes_raw << 7` equals the remaining
    // body length after the fixed header.  Build a valid body, then inflate
    // `data_bytes_raw` so it claims more payload than is actually present.
    let mut sqpk_body = make_sqpk_add_data_body(0, 0, 0, 0, 0, 0);

    // `data_bytes_raw` occupies bytes 5 + 3 + 2 + 2 + 4 + 4 = offset 20..24
    // (0-indexed in the SQPK body): inner_size(4) + sub_cmd(1) + pad(3) +
    // main_id(2) + sub_id(2) + file_id(4) + block_offset_raw(4) = 20.
    let data_bytes_raw_offset = 20;
    let inflated: u32 = 999; // claims 999*128 bytes of payload — far more than we have
    sqpk_body[data_bytes_raw_offset..data_bytes_raw_offset + 4]
        .copy_from_slice(&inflated.to_be_bytes());

    let data = make_patch(&[make_chunk(b"SQPK", &sqpk_body), make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();

    match reader.next().unwrap() {
        Err(ZiPatchError::InvalidField { context }) => {
            assert!(
                context.contains("data_bytes"),
                "error context must mention 'data_bytes', got: {context}"
            );
        }
        other => panic!("expected InvalidField for data_bytes mismatch, got {other:?}"),
    }
}

#[test]
fn sqpk_add_data_fast_path_crc_mismatch_returns_checksum_mismatch() {
    // The fast path feeds three disjoint byte ranges into the CRC32 hasher
    // (tag || prefix || header || data).  Flip one bit in the trailing CRC
    // field and confirm ChecksumMismatch is returned with the SQPK tag.
    let sqpk_body = make_sqpk_add_data_body(0, 0, 0, 0, 1, 0); // 128-byte payload

    // make_chunk produces a valid CRC; flip the last byte.
    let mut chunk = make_chunk(b"SQPK", &sqpk_body);
    let last = chunk.len() - 1;
    chunk[last] ^= 0xFF;

    let data = make_patch(&[chunk, make_chunk(b"EOF_", &[])]);
    let mut reader = ZiPatchReader::new(Cursor::new(data)).unwrap();

    match reader.next().unwrap() {
        Err(ZiPatchError::ChecksumMismatch { tag, .. }) => {
            assert_eq!(&tag, b"SQPK", "ChecksumMismatch must carry the SQPK tag");
        }
        other => panic!("expected ChecksumMismatch, got {other:?}"),
    }
}