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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! Multi-patch plan builder.
//!
//! [`PlanBuilder`] consumes one or more [`ZiPatchReader`]s in chain order via
//! [`PlanBuilder::add_patch`] and produces a single [`Plan`] describing the
//! end state. Mid-chain destructive operations — `SqpkFile::RemoveAll`,
//! `SqpkFile::DeleteFile`, and `SqpkFile::AddFile` at `file_offset == 0` —
//! retroactively drop accumulated regions from earlier patches so that the
//! returned plan reflects only the writes that survive.

use std::collections::HashMap;
use std::io::Read;

use crate::apply::path::expansion_folder_id;
use crate::chunk::sqpk::add_data::SqpkAddData;
use crate::chunk::{
    Chunk, SqpackFile, SqpkCommand, SqpkFile, SqpkFileOperation, SqpkHeader, SqpkHeaderTarget,
    TargetHeaderKind, ZiPatchReader,
};
use crate::{Platform, Result, ZiPatchError};
use tracing::{info, info_span, trace};

use super::plan::{
    FilesystemOp, PartExpected, PartSource, PatchRef, PatchSourceKind, PatchType, Plan, Region,
    Target, TargetPath,
};
use super::region_map;

// Offset of a SQPK sub-command body from the start of the SQPK chunk body
// (the body starts with `[inner_size: i32 BE][sub_cmd: u8]` = 5 bytes).
const SQPK_SUB_CMD_BODY_OFFSET: u64 = 5;

// Offset of `header_data` from the start of a SqpkHeader sub-command body.
// Layout: file_kind(1) + header_kind(1) + pad(1) + main_id(2) + sub_id(2) + file_id(4).
const SQPK_HEADER_DATA_OFFSET: u64 = 11;

/// Reject a relative path that escapes the install root.
///
/// The indexed builder is a natural choke point for path-traversal checks: it
/// owns every `Generic` path that enters a plan, plus every relative path
/// fed to a [`FilesystemOp`]. The sequential apply path does not currently
/// enforce this guard — a malicious patch supplying `../../etc/passwd` would
/// land bytes outside the install root — but the indexed plan refuses to
/// build at all, surfacing the bad path at construction time rather than
/// apply time. `SqPack`-encoded targets are structurally constrained by
/// their numeric `(main_id, sub_id, file_id)` triple and skip this check.
///
/// Rejects:
/// - empty path components and `..` components anywhere in the path,
/// - absolute Unix paths (leading `/`),
/// - Windows drive-letter prefixes (`C:\`, `c:/`, etc.).
fn reject_unsafe_relative_path(path: &str) -> Result<()> {
    if path.starts_with('/') || path.starts_with('\\') {
        return Err(ZiPatchError::UnsafeTargetPath(path.to_owned()));
    }
    // Windows drive letter: `[A-Za-z]:` followed by `/` or `\`, or just `[A-Za-z]:`
    // at minimum (`C:` alone is still absolute on Windows).
    let bytes = path.as_bytes();
    if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
        return Err(ZiPatchError::UnsafeTargetPath(path.to_owned()));
    }
    for component in path.split(['/', '\\']) {
        if component == ".." {
            return Err(ZiPatchError::UnsafeTargetPath(path.to_owned()));
        }
    }
    Ok(())
}

// Largest `units` value whose `units * 128` byte length still fits in
// `Region::length: u32`. Used by `push_empty_block_region` to split a single
// huge EmptyBlock into a capped (header-bearing) region plus trailing Zeros
// fillers; see the function body for the byte-equivalence asterisk this
// implies for `units >= 2^25`.
const MAX_UNITS_PER_REGION: u32 = u32::MAX / 128; // 0x01FF_FFFF

/// Accumulating builder for a multi-patch [`Plan`].
///
/// Construct via [`PlanBuilder::new`], feed each patch in chain order via
/// [`PlanBuilder::add_patch`], then consume with [`PlanBuilder::finish`].
/// For single-patch convenience use the freestanding [`build_plan`] function;
/// for one-shot chain construction use [`build_plan_chain`].
#[derive(Debug)]
pub struct PlanBuilder {
    state: BuilderState,
}

impl Default for PlanBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl PlanBuilder {
    /// Start a new, empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: BuilderState::new(),
        }
    }

    /// Read `reader` to completion, appending the patch to the chain.
    ///
    /// Mid-chain destructive ops (`RemoveAll`, `DeleteFile`,
    /// `AddFile@file_offset=0`) retroactively prune accumulated regions from
    /// earlier patches at this point.
    ///
    /// # Errors
    ///
    /// - [`ZiPatchError::DuplicatePatch`] if `name` matches a patch already
    ///   added to this builder. The chain protocol is order-sensitive; adding
    ///   the same patch twice is almost always a caller bug.
    /// - Any parser error surfaced by `reader.next()`.
    /// - Any semantic error raised while consuming a chunk — currently
    ///   [`ZiPatchError::NegativeFileOffset`], emitted to match the sequential
    ///   apply path's rejection of `SqpkFile::AddFile` chunks with a negative
    ///   `file_offset`.
    ///
    /// # Panics
    ///
    /// Panics if the chain grows past `u32::MAX` patches, or if
    /// [`ZiPatchReader::current_chunk_body_offset`] returns `None` after a
    /// successful `next()` (an internal invariant of the reader — a panic
    /// here would only indicate a bug in this crate).
    pub fn add_patch<R: Read>(
        &mut self,
        name: impl Into<String>,
        mut reader: ZiPatchReader<R>,
    ) -> Result<()> {
        let name = name.into();
        let span = info_span!("build_plan_patch", patch = %name);
        let _enter = span.enter();
        self.state.begin_patch(name)?;
        let mut chunks: usize = 0;
        while let Some(chunk) = reader.next() {
            let chunk = chunk?;
            let body_offset = reader
                .current_chunk_body_offset()
                .expect("body offset is set whenever next() yielded Some(Ok(_))");
            self.state.consume_chunk(chunk, body_offset)?;
            chunks += 1;
        }
        info!(
            chunks,
            targets = self.state.target_order.len(),
            fs_ops = self.state.fs_ops.len(),
            "plan: patch consumed"
        );
        Ok(())
    }

    /// Consume the builder and return the accumulated [`Plan`].
    #[must_use]
    pub fn finish(self) -> Plan {
        self.state.finalize()
    }
}

/// Single-patch convenience: build a [`Plan`] from one [`ZiPatchReader`].
///
/// Equivalent to:
/// ```ignore
/// let mut b = PlanBuilder::new();
/// b.add_patch(name, reader)?;
/// Ok(b.finish())
/// ```
///
/// # Errors
///
/// Propagates any parser error surfaced by `reader.next()`.
pub fn build_plan<R: Read>(
    reader: ZiPatchReader<R>,
    patch_name: impl Into<String>,
) -> Result<Plan> {
    let mut b = PlanBuilder::new();
    b.add_patch(patch_name, reader)?;
    Ok(b.finish())
}

/// Multi-patch convenience: build a [`Plan`] from a chain of `(name, reader)`
/// pairs in chain order.
///
/// # Errors
///
/// Propagates the first error from any [`PlanBuilder::add_patch`] call, which
/// includes parser errors and [`ZiPatchError::DuplicatePatch`] if two entries
/// in the chain share a `name`.
pub fn build_plan_chain<R, I, N>(patches: I) -> Result<Plan>
where
    I: IntoIterator<Item = (N, ZiPatchReader<R>)>,
    N: Into<String>,
    R: Read,
{
    let mut b = PlanBuilder::new();
    for (name, reader) in patches {
        b.add_patch(name, reader)?;
    }
    let plan = b.finish();
    let region_count: usize = plan.targets.iter().map(|t| t.regions.len()).sum();
    info!(
        patches = plan.patches.len(),
        targets = plan.targets.len(),
        regions = region_count,
        fs_ops = plan.fs_ops.len(),
        "plan: chain built"
    );
    Ok(plan)
}

#[derive(Debug)]
struct BuilderState {
    platform: Platform,
    patches: Vec<PatchRef>,
    // Index of the patch currently being consumed; set by begin_patch and read
    // when constructing PartSource::Patch values.
    current_patch: u32,
    fs_ops: Vec<FilesystemOp>,
    targets: HashMap<TargetPath, Vec<Region>>,
    target_order: Vec<TargetPath>,
}

impl BuilderState {
    fn new() -> Self {
        Self {
            platform: Platform::Win32,
            patches: Vec::new(),
            current_patch: 0,
            fs_ops: Vec::new(),
            targets: HashMap::new(),
            target_order: Vec::new(),
        }
    }

    fn begin_patch(&mut self, name: String) -> Result<()> {
        if self.patches.iter().any(|p| p.name == name) {
            return Err(ZiPatchError::DuplicatePatch { name });
        }
        let idx = u32::try_from(self.patches.len()).expect("more than u32::MAX patches");
        self.current_patch = idx;
        self.patches.push(PatchRef {
            name,
            patch_type: None,
        });
        Ok(())
    }

    fn current_patch_ref_mut(&mut self) -> &mut PatchRef {
        let idx = self.current_patch as usize;
        &mut self.patches[idx]
    }

    fn consume_chunk(&mut self, chunk: Chunk, body_offset: u64) -> Result<()> {
        match chunk {
            Chunk::FileHeader(fh) => {
                let pt = PatchType::from_tag(*fh.patch_type());
                self.current_patch_ref_mut().patch_type = Some(pt);
                trace!(version = fh.version(), "plan: file header");
            }
            Chunk::ApplyOption(opt) => {
                trace!(kind = ?opt.kind, value = opt.value, "plan: apply option (ignored in v1)");
            }
            Chunk::ApplyFreeSpace(_) => {
                trace!("plan: apply free space (ignored in v1)");
            }
            Chunk::AddDirectory(ad) => {
                reject_unsafe_relative_path(&ad.name)?;
                self.fs_ops.push(FilesystemOp::EnsureDir(ad.name));
            }
            Chunk::DeleteDirectory(dd) => {
                reject_unsafe_relative_path(&dd.name)?;
                self.fs_ops.push(FilesystemOp::DeleteDir(dd.name));
            }
            Chunk::Sqpk(cmd) => self.consume_sqpk(cmd, body_offset)?,
            // ZiPatchReader consumes `EOF_` internally and never yields it,
            // but the match still has to cover the variant.
            Chunk::EndOfFile => {}
        }
        Ok(())
    }

    fn consume_sqpk(&mut self, cmd: SqpkCommand, body_offset: u64) -> Result<()> {
        match cmd {
            SqpkCommand::TargetInfo(t) => {
                self.platform = match t.platform_id {
                    0 => Platform::Win32,
                    1 => Platform::Ps3,
                    2 => Platform::Ps4,
                    id => Platform::Unknown(id),
                };
                trace!(platform = ?self.platform, "plan: target info");
            }
            SqpkCommand::PatchInfo(_) | SqpkCommand::Index(_) => {
                trace!("plan: SQPK metadata-only chunk (ignored in v1)");
            }
            SqpkCommand::AddData(c) => self.consume_add_data(&c, body_offset),
            SqpkCommand::DeleteData(c) => {
                self.push_empty_block_region(&c.target_file, c.block_offset, c.block_count);
            }
            SqpkCommand::ExpandData(c) => {
                self.push_empty_block_region(&c.target_file, c.block_offset, c.block_count);
            }
            SqpkCommand::Header(c) => self.consume_header(&c, body_offset),
            SqpkCommand::File(c) => self.consume_file(*c, body_offset)?,
        }
        Ok(())
    }

    fn consume_add_data(&mut self, c: &SqpkAddData, body_offset: u64) {
        let data_abs_offset =
            body_offset + SQPK_SUB_CMD_BODY_OFFSET + SqpkAddData::DATA_SOURCE_OFFSET;
        let data_bytes = u32::try_from(c.data_bytes)
            .expect("SqpkAddData::data_bytes is bounded by the parser's 512 MiB chunk size limit");
        let path = dat_target(&c.target_file);
        self.push_region(
            &path,
            Region {
                target_offset: c.block_offset,
                length: data_bytes,
                source: PartSource::Patch {
                    patch_idx: self.current_patch,
                    offset: data_abs_offset,
                    kind: PatchSourceKind::Raw { len: data_bytes },
                    decoded_skip: 0,
                },
                expected: PartExpected::SizeOnly,
            },
        );
        if c.block_delete_number > 0 {
            // `block_delete_number` is wire-decoded as `(raw_u32 << 7)` and so
            // can legally reach ~549 GiB — well beyond `u32::MAX`. The on-disk
            // operation is just zero-fill (see `write_zeros` in
            // `apply/sqpk.rs`) and adjacent `Zeros` regions are
            // semantically equivalent to a single zero run, so split the run
            // into `u32::MAX`-sized chunks instead of widening `Region::length`.
            let mut remaining = c.block_delete_number;
            let mut cursor = c.block_offset + c.data_bytes;
            while remaining > 0 {
                let chunk = u32::try_from(remaining.min(u64::from(u32::MAX)))
                    .expect("clamped to u32::MAX above");
                self.push_region(
                    &path,
                    Region {
                        target_offset: cursor,
                        length: chunk,
                        source: PartSource::Zeros,
                        expected: PartExpected::Zeros,
                    },
                );
                cursor += u64::from(chunk);
                remaining -= u64::from(chunk);
            }
        }
    }

    fn push_empty_block_region(&mut self, target_file: &SqpackFile, offset: u64, units: u32) {
        let path = dat_target(target_file);
        // `units * 128` is the byte length of the region. For `units` up to
        // `u32::MAX / 128 == 0x01FF_FFFF` this fits in a `u32` and we emit a
        // single `EmptyBlock` region whose applier writes the canonical
        // SqPack empty-block header followed by `units*128 - 20` zero bytes.
        //
        // For `units >= 2^25` the byte count overflows `Region::length: u32`.
        // The wire format permits arbitrary `u32` `block_count` values, even
        // though no real ZiPatch ever uses one that large — guard against the
        // pathological case rather than silently saturating. We split into:
        //   1. One `EmptyBlock { units: cap }` region of `cap*128` bytes
        //      (where `cap = u32::MAX / 128`), so the canonical 20-byte
        //      empty-block header is written exactly as the sequential path
        //      would write it.
        //   2. Successive `u32::MAX`-sized `Zeros` regions covering the
        //      remaining `(units - cap) * 128` bytes.
        //
        // This means the header's `block_number - 1` field reflects only the
        // first capped chunk rather than the full original `units` count —
        // an unavoidable byte-equivalence asterisk for the unreachable
        // `units >= 2^25` case (mirroring the same family of `u32`-width
        // splits already used by `consume_add_data`'s zero-fill path).
        if units <= MAX_UNITS_PER_REGION {
            self.push_region(
                &path,
                Region {
                    target_offset: offset,
                    length: units * 128,
                    source: PartSource::EmptyBlock { units },
                    expected: PartExpected::EmptyBlock { units },
                },
            );
            return;
        }

        let cap = MAX_UNITS_PER_REGION;
        let cap_bytes = u64::from(cap) * 128;
        self.push_region(
            &path,
            Region {
                target_offset: offset,
                length: cap * 128,
                source: PartSource::EmptyBlock { units: cap },
                expected: PartExpected::EmptyBlock { units: cap },
            },
        );

        let total_bytes = u64::from(units) * 128;
        let mut cursor = offset + cap_bytes;
        let mut remaining = total_bytes - cap_bytes;
        while remaining > 0 {
            let chunk = u32::try_from(remaining.min(u64::from(u32::MAX)))
                .expect("clamped to u32::MAX above");
            self.push_region(
                &path,
                Region {
                    target_offset: cursor,
                    length: chunk,
                    source: PartSource::Zeros,
                    expected: PartExpected::Zeros,
                },
            );
            cursor += u64::from(chunk);
            remaining -= u64::from(chunk);
        }
    }

    fn consume_header(&mut self, c: &SqpkHeader, body_offset: u64) {
        let header_abs_offset = body_offset + SQPK_SUB_CMD_BODY_OFFSET + SQPK_HEADER_DATA_OFFSET;
        let target_offset: u64 = match c.header_kind {
            TargetHeaderKind::Version => 0,
            TargetHeaderKind::Index | TargetHeaderKind::Data => 1024,
        };
        let path = match &c.target {
            SqpkHeaderTarget::Dat(f) => dat_target(f),
            SqpkHeaderTarget::Index(f) => index_target(f),
        };
        self.push_region(
            &path,
            Region {
                target_offset,
                length: 1024,
                source: PartSource::Patch {
                    patch_idx: self.current_patch,
                    offset: header_abs_offset,
                    kind: PatchSourceKind::Raw { len: 1024 },
                    decoded_skip: 0,
                },
                expected: PartExpected::SizeOnly,
            },
        );
    }

    fn consume_file(&mut self, c: SqpkFile, body_offset: u64) -> Result<()> {
        // Every SqpkFile op carries a relative path that lands in either a
        // TargetPath::Generic or a FilesystemOp (DeleteFile / MakeDirTree).
        // Reject path-traversal sequences here, before any plan state is mutated,
        // so a malicious `../../...` payload cannot construct a plan that would
        // write outside the install root at apply time.
        reject_unsafe_relative_path(&c.path)?;
        match c.operation {
            SqpkFileOperation::AddFile => {
                // Build the `TargetPath::Generic` once and keep its inner
                // `String` accessible by name so the offset-0 truncate-hint
                // branch can clone it without re-matching on the enum.
                // Pre-polish code matched `&path` with an `unreachable!()` else
                // arm; the unreachability was a *call-site* invariant (the
                // enum was constructed two lines above) rather than a type
                // invariant, so a future refactor that swapped out `Generic`
                // could silently turn the panic into a runtime hazard. Binding
                // `inner_path` to the raw string up front and reconstructing
                // the enum value next to it makes the invariant structural.
                let inner_path: String = c.path;
                let path = TargetPath::Generic(inner_path.clone());
                if c.file_offset == 0 {
                    // AddFile at offset 0 truncates the target. Drop any
                    // accumulated regions from earlier patches and emit a
                    // DeleteFile hint so a stale on-disk file (from outside
                    // the chain, e.g. a pre-existing install) is removed
                    // before the new regions land.
                    self.drop_target(&path);
                    self.fs_ops.push(FilesystemOp::DeleteFile(inner_path));
                }
                // Match the sequential apply's rejection of a negative
                // `file_offset` (see `apply/sqpk.rs` AddFile arm). Building a
                // plan from a malformed patch must surface the same error the
                // sequential path would raise at apply time — silently zeroing
                // a negative offset would corrupt the target.
                let mut cursor = u64::try_from(c.file_offset)
                    .map_err(|_| ZiPatchError::NegativeFileOffset(c.file_offset))?;
                for (i, block) in c.blocks.iter().enumerate() {
                    let block_source_offset = c.block_source_offsets[i];
                    let abs_offset = body_offset + SQPK_SUB_CMD_BODY_OFFSET + block_source_offset;
                    let decompressed_len = u32::try_from(block.decompressed_size())
                        .expect("block decompressed_size bounded by chunk size limit");
                    let kind = if block.is_compressed() {
                        PatchSourceKind::Deflated {
                            compressed_len: u32::try_from(block.data_len())
                                .expect("block data_len bounded by chunk size limit"),
                            decompressed_len,
                        }
                    } else {
                        PatchSourceKind::Raw {
                            len: decompressed_len,
                        }
                    };
                    self.push_region(
                        &path,
                        Region {
                            target_offset: cursor,
                            length: decompressed_len,
                            source: PartSource::Patch {
                                patch_idx: self.current_patch,
                                offset: abs_offset,
                                kind,
                                decoded_skip: 0,
                            },
                            expected: PartExpected::SizeOnly,
                        },
                    );
                    cursor += u64::from(decompressed_len);
                }
            }
            SqpkFileOperation::RemoveAll => {
                self.fs_ops
                    .push(FilesystemOp::RemoveAllInExpansion(c.expansion_id));
                self.drop_targets_under_expansion(c.expansion_id);
            }
            SqpkFileOperation::DeleteFile => {
                let path = TargetPath::Generic(c.path.clone());
                self.drop_target(&path);
                self.fs_ops.push(FilesystemOp::DeleteFile(c.path));
            }
            SqpkFileOperation::MakeDirTree => {
                self.fs_ops.push(FilesystemOp::MakeDirTree(c.path));
            }
        }
        Ok(())
    }

    fn push_region(&mut self, path: &TargetPath, region: Region) {
        if region.length == 0 {
            return;
        }
        // Hot path: target already exists. A single `get_mut` lookup with an
        // early return halves the per-region HashMap work vs the original
        // `contains_key` + `get_mut` pair, and avoids cloning the `TargetPath`
        // entirely (the `Generic` variant wraps a `String`, so clones allocate).
        if let Some(regions) = self.targets.get_mut(path) {
            region_map::insert(regions, region);
            return;
        }
        let owned = path.clone();
        self.target_order.push(owned.clone());
        let regions = self.targets.entry(owned).or_default();
        region_map::insert(regions, region);
    }

    /// Drop every accumulated region (and the target's bookkeeping entry) for
    /// a single target. Used by `DeleteFile` and by `AddFile@0` for the
    /// truncate-then-rewrite case.
    fn drop_target(&mut self, path: &TargetPath) {
        self.targets.remove(path);
        self.target_order.retain(|tp| tp != path);
    }

    /// Drop every accumulated target that falls under the expansion folder
    /// `sqpack/<exp>/` or `movie/<exp>/`. Used by `RemoveAll`.
    fn drop_targets_under_expansion(&mut self, expansion_id: u16) {
        let folder = expansion_folder_id(expansion_id);
        let sqpack_prefix = format!("sqpack/{folder}/");
        let movie_prefix = format!("movie/{folder}/");

        // Take `target_order` out so the retain closure can mutate
        // `self.targets` without a split-borrow conflict. One pass instead of
        // building a `HashSet<TargetPath>` of cloned keys and then running two
        // separate retains over both maps.
        let mut order = std::mem::take(&mut self.target_order);
        order.retain(|tp| {
            if target_falls_under(tp, expansion_id, &sqpack_prefix, &movie_prefix) {
                self.targets.remove(tp);
                false
            } else {
                true
            }
        });
        self.target_order = order;
    }

    fn finalize(self) -> Plan {
        let BuilderState {
            platform,
            patches,
            current_patch: _,
            fs_ops,
            mut targets,
            target_order,
        } = self;

        let mut out_targets = Vec::with_capacity(target_order.len());
        for path in target_order {
            let regions = targets.remove(&path).unwrap_or_default();
            let final_size = regions
                .last()
                .map_or(0, |r| r.target_offset + u64::from(r.length));
            debug_assert!(
                regions
                    .windows(2)
                    .all(|w| w[0].target_offset + u64::from(w[0].length) <= w[1].target_offset),
                "regions must be sorted and non-overlapping after build"
            );
            out_targets.push(Target {
                path,
                final_size,
                regions,
            });
        }

        Plan {
            schema_version: Plan::CURRENT_SCHEMA_VERSION,
            platform,
            patches,
            targets: out_targets,
            fs_ops,
        }
    }
}

fn target_falls_under(
    tp: &TargetPath,
    expansion_id: u16,
    sqpack_prefix: &str,
    movie_prefix: &str,
) -> bool {
    match tp {
        TargetPath::SqpackDat { sub_id, .. } | TargetPath::SqpackIndex { sub_id, .. } => {
            (sub_id >> 8) == expansion_id
        }
        TargetPath::Generic(path) => {
            path.starts_with(sqpack_prefix) || path.starts_with(movie_prefix)
        }
    }
}

fn dat_target(f: &SqpackFile) -> TargetPath {
    TargetPath::SqpackDat {
        main_id: f.main_id,
        sub_id: f.sub_id,
        file_id: f.file_id,
    }
}

fn index_target(f: &SqpackFile) -> TargetPath {
    TargetPath::SqpackIndex {
        main_id: f.main_id,
        sub_id: f.sub_id,
        file_id: f.file_id,
    }
}

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

    fn synthetic_sqpack_file() -> SqpackFile {
        SqpackFile {
            main_id: 1,
            sub_id: 2,
            file_id: 0,
        }
    }

    /// `block_delete_number` is wire-decoded as `(raw_u32 << 7)` and can reach
    /// ~549 GiB. A naive `u32::try_from(...).expect(...)` would panic on any
    /// raw value `>= 2^25`. Use a value that is comfortably above `u32::MAX`
    /// to force at least two chunks of splitting.
    #[test]
    fn consume_add_data_splits_huge_block_delete_into_u32_chunks() {
        let mut state = BuilderState::new();
        state.begin_patch("synthetic".into()).unwrap();

        let huge: u64 = u64::from(u32::MAX) + 1024; // forces a second chunk
        let cmd = SqpkAddData {
            target_file: synthetic_sqpack_file(),
            block_offset: 0,
            data_bytes: 128,
            block_delete_number: huge,
            data: vec![0xAA; 128],
        };
        // body_offset value is irrelevant for the zero-fill split path.
        state.consume_add_data(&cmd, 0);

        let plan = state.finalize();
        assert_eq!(plan.targets.len(), 1);
        let regions = &plan.targets[0].regions;
        // 1 raw payload region + 2 Zeros regions (u32::MAX + remainder).
        assert_eq!(regions.len(), 3);

        assert_eq!(regions[0].target_offset, 0);
        assert_eq!(regions[0].length, 128);
        assert!(matches!(regions[0].source, PartSource::Patch { .. }));

        // First zero chunk is exactly u32::MAX, starting right after data.
        assert_eq!(regions[1].target_offset, 128);
        assert_eq!(regions[1].length, u32::MAX);
        assert!(matches!(regions[1].source, PartSource::Zeros));

        // Second zero chunk holds the remainder, starting where the first ends.
        assert_eq!(regions[2].target_offset, 128 + u64::from(u32::MAX));
        assert_eq!(regions[2].length, 1024);
        assert!(matches!(regions[2].source, PartSource::Zeros));

        assert_eq!(plan.targets[0].final_size, 128 + huge);
    }

    /// `SqpkFile::AddFile` with a negative `file_offset` must surface
    /// `ZiPatchError::NegativeFileOffset` instead of being silently zeroed —
    /// matches the sequential apply path's rejection in `apply/sqpk.rs`.
    #[test]
    fn consume_file_rejects_negative_file_offset() {
        use crate::chunk::{SqpkFile, SqpkFileOperation};

        let mut state = BuilderState::new();
        state.begin_patch("synthetic".into()).unwrap();

        let cmd = SqpkFile {
            operation: SqpkFileOperation::AddFile,
            file_offset: -1,
            file_size: 0,
            expansion_id: 0,
            path: "synthetic/path".into(),
            block_source_offsets: Vec::new(),
            blocks: Vec::new(),
        };
        let err = state
            .consume_file(cmd, 0)
            .expect_err("negative file_offset must error");
        match err {
            ZiPatchError::NegativeFileOffset(v) => assert_eq!(v, -1),
            other => panic!("unexpected error variant: {other:?}"),
        }
    }

    /// `EmptyBlock` regions whose byte length fits in `u32` must round-trip
    /// as a single `EmptyBlock` region — the split path only kicks in for
    /// pathological `units >= 2^25`.
    #[test]
    fn push_empty_block_region_emits_single_region_when_in_range() {
        let mut state = BuilderState::new();
        state.begin_patch("synthetic".into()).unwrap();

        state.push_empty_block_region(&synthetic_sqpack_file(), 0, 8);

        let plan = state.finalize();
        assert_eq!(plan.targets.len(), 1);
        let regions = &plan.targets[0].regions;
        assert_eq!(regions.len(), 1);
        assert_eq!(regions[0].length, 8 * 128);
        assert!(matches!(
            regions[0].source,
            PartSource::EmptyBlock { units: 8 }
        ));
        assert!(matches!(
            regions[0].expected,
            PartExpected::EmptyBlock { units: 8 }
        ));
    }

    /// `EmptyBlock` with `units * 128 > u32::MAX` must split into a capped
    /// `EmptyBlock` region (header-bearing) followed by `Zeros` fillers.
    /// Verifies both the total bytes covered and the region kind shapes —
    /// this prevents the v1.0 silent saturation of `Region::length`.
    #[test]
    fn push_empty_block_region_splits_when_bytes_exceed_u32_max() {
        let mut state = BuilderState::new();
        state.begin_patch("synthetic".into()).unwrap();

        // `units = 2^25` produces exactly `2^32` bytes — one byte past
        // `u32::MAX` — the smallest input that triggers the split.
        let units: u32 = 1 << 25; // 2^25
        state.push_empty_block_region(&synthetic_sqpack_file(), 0, units);

        let plan = state.finalize();
        assert_eq!(plan.targets.len(), 1);
        let regions = &plan.targets[0].regions;

        // First region: capped EmptyBlock with the header.
        let cap_units: u32 = u32::MAX / 128;
        let cap_bytes: u64 = u64::from(cap_units) * 128;
        assert_eq!(regions[0].target_offset, 0);
        assert_eq!(regions[0].length, cap_units * 128);
        match regions[0].source {
            PartSource::EmptyBlock { units: u } => assert_eq!(u, cap_units),
            ref other => panic!("expected EmptyBlock, got {other:?}"),
        }

        // Tail: one or more Zeros regions covering the remaining bytes.
        let total_bytes: u64 = u64::from(units) * 128;
        let mut covered: u64 = cap_bytes;
        for region in &regions[1..] {
            assert_eq!(region.target_offset, covered);
            assert!(matches!(region.source, PartSource::Zeros));
            assert!(matches!(region.expected, PartExpected::Zeros));
            covered += u64::from(region.length);
        }
        assert_eq!(covered, total_bytes);
        assert_eq!(plan.targets[0].final_size, total_bytes);

        for region in &regions[1..] {
            assert!(region.length <= u32::MAX);
        }
    }

    // ---- path traversal validation ----

    #[test]
    fn reject_unsafe_relative_path_accepts_safe_paths() {
        for safe in [
            "sqpack/ffxiv/000000.win32.dat0",
            "movie/ffxiv/opening.bk2",
            "boot/launcher.exe",
            "a/b/c.txt",
            "single",
        ] {
            assert!(
                reject_unsafe_relative_path(safe).is_ok(),
                "safe path rejected: {safe}"
            );
        }
    }

    #[test]
    fn reject_unsafe_relative_path_rejects_traversal_and_absolute() {
        for bad in [
            "../etc/passwd",
            "..\\etc\\passwd",
            "sqpack/../../etc/passwd",
            "a/b/../../../etc/passwd",
            "/etc/passwd",
            "\\\\server\\share\\file",
            "C:/Windows/system32",
            "c:\\Windows\\system32",
            "C:",
        ] {
            let err = reject_unsafe_relative_path(bad)
                .expect_err(&format!("unsafe path accepted: {bad}"));
            match err {
                ZiPatchError::UnsafeTargetPath(s) => assert_eq!(s, bad),
                other => panic!("expected UnsafeTargetPath, got {other:?}"),
            }
        }
    }

    #[test]
    fn consume_file_rejects_path_traversal() {
        let mut state = BuilderState::new();
        state.begin_patch("synthetic".into()).unwrap();
        let cmd = SqpkFile {
            operation: SqpkFileOperation::AddFile,
            file_offset: 0,
            file_size: 0,
            expansion_id: 0,
            path: "../../etc/passwd".into(),
            block_source_offsets: Vec::new(),
            blocks: Vec::new(),
        };
        let err = state
            .consume_file(cmd, 0)
            .expect_err("must reject traversal");
        assert!(matches!(err, ZiPatchError::UnsafeTargetPath(_)));
    }

    /// Re-adding a patch with the same name must surface
    /// `ZiPatchError::DuplicatePatch` rather than silently appending a second
    /// `PatchRef`. Exercised at the `BuilderState` boundary; the public-API
    /// equivalent (via `PlanBuilder::add_patch`) is covered in
    /// `tests/index_chain.rs`.
    #[test]
    fn begin_patch_rejects_duplicate_name() {
        let mut state = BuilderState::new();
        state.begin_patch("p1".into()).unwrap();
        let err = state
            .begin_patch("p1".into())
            .expect_err("duplicate name must error");
        match err {
            ZiPatchError::DuplicatePatch { name } => assert_eq!(name, "p1"),
            other => panic!("expected DuplicatePatch, got {other:?}"),
        }
    }
}