hatchzip 0.1.11

Extract huge archives in place: the archive shrinks as your files hatch, so you only need room for the output.
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
//! RAR archives, extracted in place file by file and compared byte for byte
//! with what they were made from.
//!
//! Two kinds of archives: sets made by the real RAR (`tests/fixtures/rar/`),
//! and archives of stored files written here, for layouts a fixture can't
//! cover cheaply (big files, hostile names, many volumes). The fixtures hold
//! `sample()` or `small()`; they are rebuilt from the trees the ignored test
//! `write_sample_trees` writes (`HATCHZIP_RAR_SAMPLE_DIR=<empty folder>
//! cargo test -p hatchzip --features rar --test rar -- --ignored`), with RAR
//! 6.24 for Linux, from inside `<folder>/sample` or `<folder>/small`:
//!
//!   sample: rar a -r -idq -ma5 -m3 -v16k     <fixtures>/rar5/set.rar game
//!   sample: rar a -r -idq -ma4 -m3 -v16k -vn <fixtures>/rar4/set.rar game
//!   small:  rar a -r -idq -ma5 -m3 -v4k -psecret <fixtures>/rar5-pw/set.rar game
//!   small:  rar a -r -idq -ma4 -m3 -psecret  <fixtures>/rar4-pw/set.rar game
//!   small:  rar a -r -idq -ma5 -m3 -v4k -s   <fixtures>/rar5-solid/set.rar game
//!   small:  rar a -r -idq -ma4 -m3 -s        <fixtures>/rar4-solid/set.rar game
//!   small:  rar a -r -idq -ma5 -m3 -qo+ -rr5% -zREADME <fixtures>/rar5-extras/set.rar game
//!   small:  rar a -r -idq -ma5 -m3 -hpsecret <fixtures>/rar5-hp/set.rar game
//!   small:  rar a -r -idq -ma5 -m3 -v4k -hpsecret <fixtures>/rar5-hp-set/set.rar game
//!   small:  rar a -r -idq -ma4 -m3 -v4k -hpsecret <fixtures>/rar4-hp-set/set.rar game
//!
//! `README` in the small tree is the archive comment, not part of it. The
//! `-hp-long` fixtures hold one file, `hello.txt` ("hello\n"), made with
//! `rar a -idq -ma4 -m3 "-hp$LONG_PW"` and the same with `-ma5`.

#![cfg(feature = "rar")]

mod common;

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Output;

use common::*;
use tempfile::TempDir;

fn sample() -> Files {
    let mut files = small();
    // Big enough to span volumes of 16 KB, in an order that gives most
    // volumes files of their own.
    for (i, (name, len)) in [
        ("a.pak", 30_000),
        ("b.pak", 20_000),
        ("c.pak", 36_000),
        ("e.pak", 6_000),
    ]
    .into_iter()
    .enumerate()
    {
        files.insert(format!("game/{name}"), noise(len, i as u64 + 1));
    }
    files
}

fn small() -> Files {
    let mut files = Files::new();
    files.insert("game/d.pak".into(), noise(6_000, 9));
    files.insert(
        "game/config/settings.ini".into(),
        b"volume=7\n".repeat(2_000),
    );
    files.insert("game/empty.txt".into(), Vec::new());
    files.insert(
        "game/naïve résumé/日本語.txt".into(),
        "unicode names survive\n".into(),
    );
    for i in 0..10 {
        files.insert(
            format!("game/many/file{i:02}.txt"),
            format!("file number {i}\n").into(),
        );
    }
    files
}

#[test]
#[ignore = "regenerates the fixtures' source trees"]
fn write_sample_trees() {
    let dir = PathBuf::from(std::env::var("HATCHZIP_RAR_SAMPLE_DIR").unwrap());
    for (tree, files) in [("sample", sample()), ("small", small())] {
        for (name, data) in files {
            let path = dir.join(tree).join(name);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, data).unwrap();
        }
        fs::create_dir_all(dir.join(tree).join(EMPTY_DIR)).unwrap();
    }
    fs::write(dir.join("small/README"), "an archive comment\n").unwrap();
}

/// Copies a fixture set into `to` and returns its first volume.
fn copy_set(set: &str, to: &Path) -> PathBuf {
    let from = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/rar")
        .join(set);
    let mut first = None;
    for e in fs::read_dir(&from).unwrap() {
        let e = e.unwrap();
        let name = e.file_name().to_string_lossy().into_owned();
        fs::copy(e.path(), to.join(&name)).unwrap();
        if name == "set.rar" || name == "set.part1.rar" {
            first = Some(to.join(&name));
        }
    }
    first.unwrap_or_else(|| panic!("{set} has no first volume"))
}

/// The volumes in `dir`, sorted, without HatchZip's side files.
fn volumes(dir: &Path) -> Vec<String> {
    let mut v: Vec<String> = fs::read_dir(dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|n| n.starts_with("set.") && !n.contains("hatchzip"))
        .collect();
    v.sort();
    v
}

/// Every volume in `dir` with its bytes.
fn snapshot_dir(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
    volumes(dir)
        .into_iter()
        .map(|n| {
            let p = dir.join(n);
            let bytes = fs::read(&p).unwrap();
            (p, bytes)
        })
        .collect()
}

fn on_disk(dir: &Path) -> u64 {
    volumes(dir)
        .iter()
        .map(|n| fs::metadata(dir.join(n)).unwrap().len())
        .sum()
}

fn committed_len(archive: &Path) -> u64 {
    let [journal, _] = side_files(archive);
    let j: serde_json::Value = serde_json::from_slice(&fs::read(journal).unwrap()).unwrap();
    j["committed_len"].as_u64().unwrap()
}

fn stderr(out: &Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

fn extract_with(archive: &Path, out: &Path, password: Option<&str>) -> Output {
    let (a, o) = (archive.to_str().unwrap(), out.to_str().unwrap());
    let mut args = vec!["extract", a, "-o", o, "--keep-free", "0", "--yes"];
    if let Some(p) = password {
        args.extend(["--password", p]);
    }
    hatchzip(&args, &[])
}

fn extracts(build: impl Fn(&Path) -> PathBuf, files: &Files) {
    let tmp = TempDir::new().unwrap();
    let archive = build(tmp.path());
    let out = tmp.path().join("out");
    assert_ok(&extract(&archive, &out, &[]));
    assert_tree(&out, files);
    assert_consumed(&archive);
    assert!(volumes(tmp.path()).is_empty(), "no volume should be left");
}

/// The run fails and nothing changed: every volume as it was, no side
/// files, no output.
fn refused_untouched(tmp: &Path, out: &Output) {
    let _ = out;
    assert!(!tmp.join("out").exists(), "the output folder was created");
    assert!(
        fs::read_dir(tmp).unwrap().all(|e| !e
            .unwrap()
            .file_name()
            .to_string_lossy()
            .contains("hatchzip")),
        "side files were left"
    );
}

// -- Archives written here --------------------------------------------------
//
// Stored files only, which is all a layout needs. UnRAR reads these like any
// other, and the checksums are the real ones.

#[derive(Clone, Copy, PartialEq)]
enum Naming {
    /// `set.rar`, `set.r00`, `set.r01`, ...
    Old,
    /// `set.part1.rar`, `set.part2.rar`, ...
    Part,
}

struct Entry {
    /// The name as stored in the header. In RAR 4, a UTF-8 name that is not
    /// ASCII gets its Unicode form as well, as RAR writes it; other bytes
    /// are a legacy name in the OEM code page, with no Unicode form.
    name: Vec<u8>,
    data: Vec<u8>,
    dir: bool,
    /// RAR 5 compression information: 0 is RAR 5's algorithm, stored.
    info: u64,
}

fn entry(name: &str, data: Vec<u8>) -> Entry {
    Entry {
        name: name.as_bytes().to_vec(),
        data,
        dir: false,
        info: 0,
    }
}

fn entries_of(files: &Files) -> Vec<Entry> {
    let mut entries: Vec<Entry> = files.iter().map(|(n, d)| entry(n, d.clone())).collect();
    entries.push(Entry {
        name: EMPTY_DIR.as_bytes().to_vec(),
        data: Vec::new(),
        dir: true,
        info: 0,
    });
    entries
}

fn crc16(bytes: &[u8]) -> u16 {
    (crc32fast::hash(bytes) & 0xFFFF) as u16
}

fn block4(kind: u8, flags: u16, body: &[u8]) -> Vec<u8> {
    let mut b = vec![0, 0, kind];
    b.extend(flags.to_le_bytes());
    b.extend(((body.len() + 7) as u16).to_le_bytes());
    b.extend(body);
    let crc = crc16(&b[2..]);
    b[..2].copy_from_slice(&crc.to_le_bytes());
    b
}

fn vint(mut v: u64, out: &mut Vec<u8>) {
    loop {
        let byte = (v & 0x7F) as u8;
        v >>= 7;
        if v == 0 {
            out.push(byte);
            return;
        }
        out.push(byte | 0x80);
    }
}

/// A RAR 5 header: CRC-32, size, then `body` (type and flags first).
fn block5(body: &[u8]) -> Vec<u8> {
    let mut sized = Vec::new();
    vint(body.len() as u64, &mut sized);
    sized.extend(body);
    let mut b = crc32fast::hash(&sized).to_le_bytes().to_vec();
    b.extend(sized);
    b
}

/// The Unicode form of a RAR 4 name, which follows the plain form and a NUL,
/// encoded as RAR does: a high byte, then two-bit opcodes, four to a flags
/// byte from the top bits down, each followed by its operands. 0 is a
/// character below 256, 1 a character in the high byte's page, 2 any UTF-16
/// unit, 3 a run of `n + 2` characters copied from the plain form at the
/// same positions.
fn unicode_name4(plain: &[u8], name: &str) -> Vec<u8> {
    let wide: Vec<u16> = name.encode_utf16().collect();
    let high = wide.iter().map(|&c| c >> 8).find(|&h| h != 0).unwrap_or(0) as u8;
    let mut ops: Vec<(u8, Vec<u8>)> = Vec::new();
    let mut i = 0;
    while i < wide.len() {
        let run = wide[i..]
            .iter()
            .zip(plain.get(i..).unwrap_or_default())
            .take_while(|&(&c, &b)| b.is_ascii() && c == u16::from(b))
            .count()
            .min(0x7F + 2);
        if run >= 3 {
            ops.push((3, vec![(run - 2) as u8]));
            i += run;
            continue;
        }
        let c = wide[i];
        ops.push(match c >> 8 {
            0 => (0, vec![c as u8]),
            h if h == u16::from(high) => (1, vec![c as u8]),
            _ => (2, c.to_le_bytes().to_vec()),
        });
        i += 1;
    }
    let mut out = vec![high];
    for group in ops.chunks(4) {
        let flags = group
            .iter()
            .enumerate()
            .fold(0u8, |f, (k, (op, _))| f | op << (6 - 2 * k));
        out.push(flags);
        for (_, operands) in group {
            out.extend(operands);
        }
    }
    out
}

#[derive(Clone, Copy, PartialEq)]
enum Version {
    Four,
    Five,
}

/// The header of one piece of a file, `chunk` of `total`, followed by it.
fn file_piece(v: Version, e: &Entry, chunk: &[u8], before: bool, after: bool) -> Vec<u8> {
    match v {
        Version::Four => {
            let mut flags = 0x8000u16 | u16::from(before) | u16::from(after) << 1;
            if e.dir {
                flags |= 0xE0;
            }
            let mut name: Vec<u8> = e
                .name
                .iter()
                .map(|&b| if b == b'/' { b'\\' } else { b })
                .collect();
            // Without its Unicode form, UnRAR reads a name in the OEM code
            // page on Windows and as UTF-8 elsewhere.
            if let Ok(text) = std::str::from_utf8(&name).map(str::to_string)
                && !text.is_ascii()
            {
                flags |= 0x200;
                let unicode = unicode_name4(&name, &text);
                name.push(0);
                name.extend(unicode);
            }
            let mut body = Vec::new();
            body.extend((chunk.len() as u32).to_le_bytes());
            body.extend((e.data.len() as u32).to_le_bytes());
            body.push(2); // Windows
            body.extend(crc32fast::hash(&e.data).to_le_bytes());
            body.extend(0x5821_0000u32.to_le_bytes()); // 2024-01-01, DOS time
            body.push(29);
            body.push(0x30); // stored
            body.extend((name.len() as u16).to_le_bytes());
            body.extend(if e.dir { 0x10u32 } else { 0x20 }.to_le_bytes());
            body.extend(&name);
            let mut out = block4(0x74, flags, &body);
            out.extend(chunk);
            out
        }
        Version::Five => {
            let mut body = Vec::new();
            vint(2, &mut body); // file header
            vint(
                0x02 | u64::from(before) << 3 | u64::from(after) << 4,
                &mut body,
            );
            vint(chunk.len() as u64, &mut body);
            vint(u64::from(e.dir) | 0x04, &mut body); // CRC-32 present
            vint(e.data.len() as u64, &mut body);
            vint(if e.dir { 0x10 } else { 0x20 }, &mut body);
            body.extend(crc32fast::hash(&e.data).to_le_bytes());
            vint(e.info, &mut body);
            vint(0, &mut body); // Windows
            vint(e.name.len() as u64, &mut body);
            body.extend(&e.name);
            let mut out = block5(&body);
            out.extend(chunk);
            out
        }
    }
}

/// Writes `entries` as volumes of at most `cap` bytes (one volume if `cap`
/// is `None`), a file running from one into the next as RAR splits it.
fn write_rar(
    dir: &Path,
    v: Version,
    entries: &[Entry],
    cap: Option<usize>,
    naming: Naming,
) -> PathBuf {
    let cap = cap.unwrap_or(usize::MAX / 2);
    let overhead = match v {
        Version::Four => 7 + 13 + 7,
        Version::Five => 8 + 16 + 8,
    };
    let mut volumes: Vec<Vec<u8>> = vec![Vec::new()];
    let room = |vol: &Vec<u8>| cap - overhead - vol.len();
    for e in entries {
        let header = file_piece(v, e, &[], false, false).len() + 2;
        let mut at = 0;
        let mut first = true;
        loop {
            if room(volumes.last().unwrap()) < header + 1 {
                volumes.push(Vec::new());
            }
            let left = room(volumes.last().unwrap()) - header;
            let take = (e.data.len() - at).min(left);
            let last = at + take == e.data.len();
            let chunk = &e.data[at..at + take];
            volumes
                .last_mut()
                .unwrap()
                .extend(file_piece(v, e, chunk, !first, !last));
            at += take;
            first = false;
            if last {
                break;
            }
            volumes.push(Vec::new());
        }
    }

    let count = volumes.len();
    let multi = count > 1;
    let name_of = |i: usize| match naming {
        Naming::Old if i == 0 => "set.rar".to_string(),
        Naming::Old => format!("set.r{:02}", i - 1),
        Naming::Part => format!("set.part{}.rar", i + 1),
    };
    for (i, body) in volumes.iter().enumerate() {
        let more = i + 1 < count;
        let mut file = Vec::new();
        match v {
            Version::Four => {
                let mut main = u16::from(multi);
                if i == 0 {
                    main |= 0x0100;
                }
                if naming == Naming::Part {
                    main |= 0x0010;
                }
                file.extend(b"Rar!\x1A\x07\x00");
                file.extend(block4(0x73, main, &[0; 6]));
                file.extend(body);
                file.extend(block4(0x7B, 0x4000 | u16::from(more), &[]));
            }
            Version::Five => {
                file.extend(b"Rar!\x1A\x07\x01\x00");
                let mut main = Vec::new();
                vint(1, &mut main);
                vint(0, &mut main);
                if multi {
                    vint(0x01 | 0x02, &mut main);
                    vint(i as u64, &mut main);
                } else {
                    vint(0, &mut main);
                }
                file.extend(block5(&main));
                file.extend(body);
                let mut end = Vec::new();
                vint(5, &mut end);
                vint(0, &mut end);
                vint(u64::from(more), &mut end);
                file.extend(block5(&end));
            }
        }
        let name = if multi || naming == Naming::Part {
            name_of(i)
        } else {
            "set.rar".to_string()
        };
        fs::write(dir.join(name), file).unwrap();
    }
    dir.join(if multi || naming == Naming::Part {
        name_of(0)
    } else {
        "set.rar".to_string()
    })
}

/// One RAR 5 volume of stored files followed by a quick open record holding
/// a copy of every file header, as `rar -qo+` writes it. `copy` gets each
/// file's index and header and returns what the record keeps for it.
fn rar5_with_quick_open(
    dir: &Path,
    entries: &[Entry],
    copy: impl Fn(usize, Vec<u8>) -> Vec<u8>,
) -> PathBuf {
    // The main header points at the record with a locator in its extra
    // area. The offset takes three bytes whatever its value, so the record's
    // position doesn't change the main header's length.
    let main = |offset: usize| {
        let mut locator = Vec::new();
        vint(1, &mut locator); // locator
        vint(1, &mut locator); // quick open offset present
        locator.extend([
            0x80 | (offset & 0x7F) as u8,
            0x80 | (offset >> 7 & 0x7F) as u8,
            (offset >> 14) as u8,
        ]);
        let mut extra = Vec::new();
        vint(locator.len() as u64, &mut extra);
        extra.extend(locator);
        let mut body = Vec::new();
        vint(1, &mut body); // main header
        vint(0x01, &mut body); // with an extra area
        vint(extra.len() as u64, &mut body);
        vint(0, &mut body); // archive flags
        body.extend(extra);
        block5(&body)
    };
    let pieces: Vec<Vec<u8>> = entries
        .iter()
        .map(|e| file_piece(Version::Five, e, &e.data, false, false))
        .collect();
    let mut at = 8 + main(0).len();
    let mut starts = Vec::new();
    for p in &pieces {
        starts.push(at);
        at += p.len();
    }
    let record_at = at;

    let mut copies = Vec::new();
    for (i, (piece, e)) in pieces.iter().zip(entries).enumerate() {
        let header = copy(i, piece[..piece.len() - e.data.len()].to_vec());
        let mut body = Vec::new();
        vint(0, &mut body); // flags
        vint((record_at - starts[i]) as u64, &mut body);
        vint(header.len() as u64, &mut body);
        body.extend(header);
        copies.extend(block5(&body));
    }
    let mut service = Vec::new();
    vint(3, &mut service); // service header
    vint(0x02, &mut service); // with data
    vint(copies.len() as u64, &mut service);
    vint(0, &mut service); // no time, no CRC
    vint(copies.len() as u64, &mut service);
    vint(0, &mut service); // attributes
    vint(0, &mut service); // stored
    vint(0, &mut service); // Windows
    vint(2, &mut service);
    service.extend(b"QO");

    let mut file = b"Rar!\x1A\x07\x01\x00".to_vec();
    file.extend(main(record_at - 8));
    file.extend(pieces.concat());
    file.extend(block5(&service));
    file.extend(copies);
    file.extend(block5(&[5, 0, 0]));
    let path = dir.join("set.rar");
    fs::write(&path, file).unwrap();
    path
}

fn two_files() -> (Files, Vec<Entry>) {
    let mut files = Files::new();
    files.insert("a.bin".into(), noise(3000, 1));
    files.insert("b.bin".into(), noise(2000, 2));
    let entries = files.iter().map(|(n, d)| entry(n, d.clone())).collect();
    (files, entries)
}

/// Copies that match what they stand for change nothing.
#[test]
fn a_quick_open_record_written_here_extracts() {
    let tmp = TempDir::new().unwrap();
    let (files, entries) = two_files();
    let archive = rar5_with_quick_open(tmp.path(), &entries, |_, h| h);
    let out = tmp.path().join("out");
    assert_ok(&extract(&archive, &out, &[]));
    for (name, data) in &files {
        assert_eq!(&fs::read(out.join(name)).unwrap(), data, "{name}");
    }
    assert_consumed(&archive);
}

/// Bzip2 is found by its signature, so a RAR behind a bzip2 tar name still
/// extracts as a RAR.
#[test]
fn a_rar_with_a_bzip2_tar_name_extracts_as_a_rar() {
    for name in ["game.tar.bz2", "game.tbz2"] {
        let tmp = TempDir::new().unwrap();
        let (files, entries) = two_files();
        let built = write_rar(tmp.path(), Version::Five, &entries, None, Naming::Old);
        let archive = tmp.path().join(name);
        fs::rename(&built, &archive).unwrap();
        let out = tmp.path().join("out");
        assert_ok(&extract(&archive, &out, &[]));
        for (n, data) in &files {
            assert_eq!(&fs::read(out.join(n)).unwrap(), data, "{name}: {n}");
        }
        assert_consumed(&archive);
    }
}

/// UnRAR reads the copy, HatchZip the header itself. A copy of `a.bin`'s
/// header with a checksum of other data would have UnRAR fail on it once
/// `b.bin` is out and the archive cut down to `a.bin`.
#[test]
fn a_quick_open_copy_that_differs_is_refused_untouched() {
    let tmp = TempDir::new().unwrap();
    let (_, entries) = two_files();
    let archive = rar5_with_quick_open(tmp.path(), &entries, |i, h| {
        if i > 0 {
            return h;
        }
        let other = entry("a.bin", noise(3000, 7));
        let mut piece = file_piece(Version::Five, &other, &other.data, false, false);
        piece.truncate(h.len());
        assert_ne!(piece, h);
        piece
    });
    let before = snapshot_dir(tmp.path());
    let out = extract(&archive, &tmp.path().join("out"), &[]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("does not match the headers it copies"),
        "{}",
        stderr(&out)
    );
    assert_unchanged(&before);
    refused_untouched(tmp.path(), &out);
}

/// RAR 4 marks a size it doesn't know as 0xFFFFFFFF, which UnRAR reads as
/// unknown and HatchZip as 4 GB. Anything but the name read differently is
/// caught before the archive is touched, as a different name is.
#[test]
fn a_header_unrar_reads_differently_is_refused_untouched() {
    let tmp = TempDir::new().unwrap();
    let (_, entries) = two_files();
    let archive = write_rar(tmp.path(), Version::Four, &entries, None, Naming::Old);
    let mut bytes = fs::read(&archive).unwrap();
    // The first file header follows the signature and the main header.
    let at = 7 + 13;
    let size = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]]));
    bytes[at + 11..at + 15].copy_from_slice(&u32::MAX.to_le_bytes());
    let crc = crc16(&bytes[at + 2..at + size]);
    bytes[at..at + 2].copy_from_slice(&crc.to_le_bytes());
    fs::write(&archive, &bytes).unwrap();

    let before = snapshot_dir(tmp.path());
    let out = extract(&archive, &tmp.path().join("out"), &[]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("UnRAR reads the header of 'a.bin' differently"),
        "{}",
        stderr(&out)
    );
    assert_unchanged(&before);
    refused_untouched(tmp.path(), &out);
}

// -- Extraction --------------------------------------------------------------

#[test]
fn rar5_volumes_made_by_rar() {
    extracts(|d| copy_set("rar5", d), &sample());
}

#[test]
fn rar4_volumes_made_by_rar() {
    extracts(|d| copy_set("rar4", d), &sample());
}

#[test]
fn quick_open_data_recovery_record_and_comment() {
    extracts(|d| copy_set("rar5-extras", d), &small());
}

#[test]
fn rar4_written_here_with_both_namings() {
    for naming in [Naming::Old, Naming::Part] {
        extracts(
            |d| {
                write_rar(
                    d,
                    Version::Four,
                    &entries_of(&sample()),
                    Some(20_000),
                    naming,
                )
            },
            &sample(),
        );
    }
}

#[test]
fn one_rar5_file_written_here() {
    extracts(
        |d| write_rar(d, Version::Five, &entries_of(&sample()), None, Naming::Old),
        &sample(),
    );
}

#[test]
fn any_volume_name_finds_the_set() {
    let tmp = TempDir::new().unwrap();
    copy_set("rar5", tmp.path());
    let out = hatchzip(
        &["list", tmp.path().join("set.part2.rar").to_str().unwrap()],
        &[],
    );
    assert_ok(&out);
    assert!(String::from_utf8_lossy(&out.stdout).contains("a.pak"));
}

/// UnRAR opens the volumes by name, which on Linux goes through its own
/// conversion of the path.
#[test]
fn a_set_in_a_folder_with_a_non_ascii_name() {
    extracts(
        |d| {
            let folder = d.join("Téléchargements 下载");
            fs::create_dir(&folder).unwrap();
            copy_set("rar5", &folder)
        },
        &sample(),
    );
}

#[test]
fn rar5_list_json_from_later_volume_reports_first_volume() {
    let tmp = TempDir::new().unwrap();
    let first = copy_set("rar5", tmp.path());
    let later = tmp.path().join("set.part2.rar");
    let before = snapshot_dir(tmp.path());

    assert_json_listing(&later, &first);
    assert_unchanged(&before);
}

#[test]
fn rar5_list_json_reports_archive_metadata_and_entries() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5", tmp.path());
    let before = snapshot_dir(tmp.path());

    assert_json_listing(&archive, &archive);
    assert_unchanged(&before);
}

#[test]
fn rar4_list_json_reports_archive_metadata_and_entries() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar4", tmp.path());
    let before = snapshot_dir(tmp.path());

    assert_json_listing(&archive, &archive);
    assert_unchanged(&before);
}

#[test]
fn test_reads_every_file() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar4", tmp.path());
    let before = snapshot_dir(tmp.path());
    let out = hatchzip(&["test", archive.to_str().unwrap()], &[]);
    assert_ok(&out);
    assert_unchanged(&before);
}

// -- Space is freed file by file ----------------------------------------------

/// Stops a run after each number of commits in turn and checks that every
/// commit gave space back: what is on disk is exactly what the journal says
/// is left, and it shrinks with every commit, inside a volume as well as a
/// volume at a time.
fn frees_after_every_batch(build: impl Fn(&Path) -> PathBuf) {
    frees_after_every_batch_with(build, &[]);
}

/// [`frees_after_every_batch`], with `env` for every run, such as the
/// password.
fn frees_after_every_batch_with(build: impl Fn(&Path) -> PathBuf, env: &[(&str, &str)]) {
    let mut last = u64::MAX;
    let mut commits = 0;
    for after in 1u32.. {
        let tmp = TempDir::new().unwrap();
        let archive = build(tmp.path());
        let original = on_disk(tmp.path());
        let n = after.to_string();
        let mut crash = env.to_vec();
        crash.extend([
            ("HATCHZIP_BATCH_ENTRIES", "1"),
            ("HATCHZIP_CRASH_AT", "after-extract"),
            ("HATCHZIP_CRASH_AFTER", &n),
        ]);
        let crashed = extract(&archive, &tmp.path().join("out"), &crash);
        if crashed.status.success() {
            break;
        }
        // `after` batches are committed and truncated; the next is not.
        let left = on_disk(tmp.path());
        assert_eq!(left, committed_len(&archive), "after {after} commits");
        assert!(
            left < last,
            "commit {after} freed nothing: {left} of {original}"
        );
        last = left;
        commits = after;
    }
    assert!(commits > 3, "only {commits} commits");
}

#[test]
fn space_is_freed_after_every_file_in_a_set() {
    frees_after_every_batch(|d| copy_set("rar5", d));
    frees_after_every_batch(|d| copy_set("rar4", d));
}

#[test]
fn space_is_freed_after_every_file_in_a_single_volume() {
    frees_after_every_batch(|d| {
        write_rar(d, Version::Five, &entries_of(&sample()), None, Naming::Old)
    });
    frees_after_every_batch(|d| {
        write_rar(d, Version::Four, &entries_of(&sample()), None, Naming::Old)
    });
}

/// A file that runs over four volumes keeps them all until it is out, even
/// after the files behind it are, and they then go together.
#[test]
fn a_split_file_keeps_its_volumes_until_it_is_out() {
    let big = noise(70_000, 7);
    let entries = vec![
        entry("game/first.txt", b"first\n".to_vec()),
        entry("game/big.bin", big.clone()),
        entry("game/after.bin", noise(15_000, 8)),
        entry("game/last.txt", b"last\n".to_vec()),
    ];
    let build = |d: &Path| write_rar(d, Version::Five, &entries, Some(20_000), Naming::Part);
    let tmp = TempDir::new().unwrap();
    let archive = build(tmp.path());
    let all = volumes(tmp.path());
    assert!(all.len() >= 5, "{all:?}");
    // Two commits: last.txt, then after.bin. big.bin is next.
    let crashed = extract(
        &archive,
        &tmp.path().join("out"),
        &[
            ("HATCHZIP_BATCH_ENTRIES", "1"),
            ("HATCHZIP_CRASH_AT", "after-extract"),
            ("HATCHZIP_CRASH_AFTER", "2"),
        ],
    );
    assert!(!crashed.status.success());
    let left = volumes(tmp.path());
    // big.bin starts in volume 1 and ends in volume 4, where after.bin
    // begins; that volume is cut, not deleted. The run stopped after
    // writing big.bin, before committing it.
    let out = tmp.path().join("out");
    assert!(out.join("game/after.bin").exists());
    assert!(left.len() >= 4, "a volume big.bin needs is gone: {left:?}");
    let cut = on_disk(tmp.path());
    assert_eq!(cut, committed_len(&archive));
    assert_eq!(left[..], all[..left.len()], "what is left is a prefix");

    assert_ok(&extract(&archive, &out, &[]));
    assert_eq!(fs::read(out.join("game/big.bin")).unwrap(), big);
    assert_consumed(&archive);
}

// -- Crashes ---------------------------------------------------------------------

/// Kills the run at both crash points after every number of commits the run
/// makes, the last one included, and checks that a resume finishes it.
fn crash_everywhere(build: impl Fn(&Path) -> PathBuf, files: &Files) {
    crash_everywhere_with(build, files, &[]);
}

/// [`crash_everywhere`], with `env` for every run, such as the password.
fn crash_everywhere_with(build: impl Fn(&Path) -> PathBuf, files: &Files, env: &[(&str, &str)]) {
    for point in ["after-extract", "after-journal"] {
        for after in 0u32.. {
            let tmp = TempDir::new().unwrap();
            let archive = build(tmp.path());
            let out = tmp.path().join("out");
            let n = after.to_string();
            let mut crash = env.to_vec();
            crash.extend([
                ("HATCHZIP_BATCH_ENTRIES", "1"),
                ("HATCHZIP_CRASH_AT", point),
                ("HATCHZIP_CRASH_AFTER", &n),
            ]);
            let crashed = extract(&archive, &out, &crash);
            if crashed.status.success() {
                assert!(after > 0, "{point} never crashed");
                break;
            }
            let resumed = extract(&archive, &out, env);
            assert!(
                resumed.status.success(),
                "{point}#{after}: the resume failed\n{}",
                stderr(&resumed)
            );
            assert_tree(&out, files);
            assert_consumed(&archive);
        }
    }
}

#[test]
fn crash_at_every_commit_rar5_set() {
    crash_everywhere(|d| copy_set("rar5", d), &sample());
}

#[test]
fn crash_at_every_commit_rar4_set() {
    crash_everywhere(|d| copy_set("rar4", d), &sample());
}

#[test]
fn crash_at_every_commit_rar5_single_volume() {
    crash_everywhere(
        |d| write_rar(d, Version::Five, &entries_of(&sample()), None, Naming::Old),
        &sample(),
    );
}

#[test]
fn crash_at_every_commit_rar4_single_volume() {
    crash_everywhere(
        |d| write_rar(d, Version::Four, &entries_of(&sample()), None, Naming::Old),
        &sample(),
    );
}

#[test]
fn crash_at_every_commit_with_quick_open_data() {
    crash_everywhere(|d| copy_set("rar5-extras", d), &small());
}

/// Every run commits one file and dies right after its journal write, until
/// one finishes.
#[test]
fn crash_after_every_journal_write_in_a_row() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5", tmp.path());
    let out = tmp.path().join("out");
    let crash = [
        ("HATCHZIP_BATCH_ENTRIES", "1"),
        ("HATCHZIP_CRASH_AT", "after-journal"),
        ("HATCHZIP_CRASH_AFTER", "0"),
    ];
    let mut last = String::new();
    for _ in 0..40 {
        let r = extract(&archive, &out, &crash);
        if r.status.success() {
            assert_tree(&out, &sample());
            assert_consumed(&archive);
            return;
        }
        last = stderr(&r);
    }
    panic!("never finished; the last run said:\n{last}");
}

// -- One big stored file -------------------------------------------------------

/// A stored file in one volume is plain bytes, so it is streamed like a tar
/// entry: its space is freed while it is written, at resume points that
/// survive a crash at each of their steps.
#[test]
fn a_big_stored_file_frees_space_as_it_goes() {
    const STEP: &str = "1048576";
    let mut files = small();
    files.insert("game/huge.bin".into(), noise(8_000_000, 11));
    let build = |d: &Path| write_rar(d, Version::Five, &entries_of(&files), None, Naming::Old);
    for point in [
        "stream-after-sync",
        "stream-after-journal",
        "stream-after-punch",
    ] {
        for after in [0u32, 3] {
            let tmp = TempDir::new().unwrap();
            let archive = build(tmp.path());
            let out = tmp.path().join("out");
            let n = after.to_string();
            let env = [
                ("HATCHZIP_STREAM_STEP", STEP),
                ("HATCHZIP_BATCH_ENTRIES", "1"),
            ];
            let mut crash = env.to_vec();
            crash.extend([("HATCHZIP_CRASH_AT", point), ("HATCHZIP_CRASH_AFTER", &n)]);
            let crashed = extract(&archive, &out, &crash);
            assert!(
                !crashed.status.success(),
                "{point}#{after} should have crashed"
            );
            let journal: serde_json::Value =
                serde_json::from_slice(&fs::read(&side_files(&archive)[0]).unwrap()).unwrap();
            if point != "stream-after-sync" || after > 0 {
                assert!(
                    !journal["resume"].is_null(),
                    "{point}#{after}: no resume point was saved"
                );
            }
            #[cfg(unix)]
            if point == "stream-after-punch" {
                use std::os::unix::fs::MetadataExt;
                let m = fs::metadata(&archive).unwrap();
                let freed = (after as u64 + 1) * 1_048_576 - 2 * 65_536;
                assert!(
                    m.blocks() * 512 + freed <= m.len().next_multiple_of(4096),
                    "{point}#{after}: {} of {} bytes still allocated",
                    m.blocks() * 512,
                    m.len()
                );
            }
            assert_ok(&extract(&archive, &out, &env));
            assert_tree(&out, &files);
            assert_consumed(&archive);
        }
    }
}

// -- Passwords -------------------------------------------------------------------

const PW: &str = "secret";

/// Archives made with "Encrypt file names" (`-hp`): their headers are
/// encrypted too.
const HP_SETS: [&str; 3] = ["rar5-hp", "rar5-hp-set", "rar4-hp-set"];

#[test]
fn password_protected_sets_extract_with_the_password() {
    for set in ["rar5-pw", "rar4-pw"].into_iter().chain(HP_SETS) {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let out = tmp.path().join("out");
        assert_ok(&extract_with(&archive, &out, Some(PW)));
        assert_tree(&out, &small());
        assert_consumed(&archive);
    }
}

/// A wrong password is "incorrect password", exit 5, for RAR 5 (by its check
/// value) and RAR 4 (by decoding a file, or the first encrypted header), and
/// nothing changes.
#[test]
fn a_wrong_or_missing_password_changes_nothing() {
    for set in ["rar5-pw", "rar4-pw"].into_iter().chain(HP_SETS) {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let before = snapshot_dir(tmp.path());
        for password in [None, Some("wrong"), Some("Secret")] {
            let out = extract_with(&archive, &tmp.path().join("out"), password);
            assert_eq!(
                out.status.code(),
                Some(5),
                "{set} {password:?}: {}",
                stderr(&out)
            );
            if password.is_some() {
                assert!(
                    stderr(&out).contains("incorrect password"),
                    "{set}: {}",
                    stderr(&out)
                );
            }
            assert_unchanged(&before);
            refused_untouched(tmp.path(), &out);
        }
    }
}

// -- Encrypted file names ------------------------------------------------------------

const WITH_PW: [(&str, &str); 1] = [("HATCHZIP_PASSWORD", PW)];

/// Nothing of an archive with encrypted file names can be read without the
/// password, not even its list, and a wrong one is caught before any file
/// is decoded. `test` checks it with the password.
#[test]
fn encrypted_file_names_need_the_password_to_list_and_test() {
    for set in HP_SETS {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let a = archive.to_str().unwrap();
        let before = snapshot_dir(tmp.path());
        for args in [vec!["list", a], vec!["test", a]] {
            assert_eq!(hatchzip(&args, &[]).status.code(), Some(5), "{set}");
            let wrong = hatchzip(&args, &[("HATCHZIP_PASSWORD", "Secret")]);
            assert_eq!(wrong.status.code(), Some(5), "{set}");
            assert!(stderr(&wrong).contains("incorrect password"), "{set}");
            assert_ok(&hatchzip(&args, &WITH_PW));
        }
        let listed = hatchzip(&["list", a, "--password", PW], &[]);
        assert!(String::from_utf8_lossy(&listed.stdout).contains("日本語.txt"));
        assert_unchanged(&before);
        assert_no_side_files(&archive);
    }
}

#[test]
fn space_is_freed_after_every_file_with_encrypted_names() {
    for set in HP_SETS {
        frees_after_every_batch_with(|d| copy_set(set, d), &WITH_PW);
    }
}

#[test]
fn crash_at_every_commit_rar5_encrypted_names() {
    crash_everywhere_with(|d| copy_set("rar5-hp", d), &small(), &WITH_PW);
}

#[test]
fn crash_at_every_commit_rar5_encrypted_names_set() {
    crash_everywhere_with(|d| copy_set("rar5-hp-set", d), &small(), &WITH_PW);
}

#[test]
fn crash_at_every_commit_rar4_encrypted_names_set() {
    crash_everywhere_with(|d| copy_set("rar4-hp-set", d), &small(), &WITH_PW);
}

/// The password is never written down, so a resume asks for it again, and
/// a wrong one changes nothing of what is left.
#[test]
fn a_resumed_run_with_encrypted_names_needs_the_password_again() {
    for set in HP_SETS {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let out = tmp.path().join("out");
        let crashed = extract(
            &archive,
            &out,
            &[
                ("HATCHZIP_PASSWORD", PW),
                ("HATCHZIP_BATCH_ENTRIES", "1"),
                // Not after the journal write: a resume finishes that
                // truncation before it opens the archive.
                ("HATCHZIP_CRASH_AT", "after-extract"),
                ("HATCHZIP_CRASH_AFTER", "3"),
            ],
        );
        assert!(!crashed.status.success());
        let journal = fs::read_to_string(&side_files(&archive)[0]).unwrap();
        assert!(!journal.contains(PW));
        let before = snapshot_dir(tmp.path());
        for password in [None, Some("wrong")] {
            let r = extract_with(&archive, &out, password);
            assert_eq!(r.status.code(), Some(5), "{set}: {}", stderr(&r));
            assert_unchanged(&before);
        }
        assert_ok(&extract_with(&archive, &out, Some(PW)));
        assert_tree(&out, &small());
        assert_consumed(&archive);
    }
}

/// Kept, the archive never changes, through a crash and its resume too.
#[test]
fn encrypted_file_names_extract_while_kept() {
    for set in HP_SETS {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let before = snapshot_dir(tmp.path());
        let out = tmp.path().join("out");
        let (a, o) = (archive.to_str().unwrap(), out.to_str().unwrap());
        let args = ["extract", a, "-o", o, "--keep-free", "0", "--keep-archive"];
        let crashed = hatchzip(
            &args,
            &[
                ("HATCHZIP_PASSWORD", PW),
                ("HATCHZIP_BATCH_ENTRIES", "1"),
                ("HATCHZIP_CRASH_AT", "after-journal"),
                ("HATCHZIP_CRASH_AFTER", "2"),
            ],
        );
        assert!(!crashed.status.success());
        assert_unchanged(&before);
        assert_ok(&hatchzip(&args, &WITH_PW));
        assert_tree(&out, &small());
        assert_unchanged(&before);
        assert_no_side_files(&archive);
    }
}

/// A password long enough that RAR 4's key derivation hashes whole blocks
/// of it, where RAR keeps a quirk of RAR 2.9's SHA-1, and with characters
/// outside ASCII, which RAR 4 hashes as UTF-16 and RAR 5 as UTF-8.
#[test]
fn a_long_password_with_non_ascii_characters() {
    const LONG_PW: &str = "correct horse battery staple, ünïcödé 日本語";
    for set in ["rar4-hp-long", "rar5-hp-long"] {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let out = tmp.path().join("out");
        let before = snapshot_dir(tmp.path());
        let wrong = extract_with(&archive, &out, Some(&LONG_PW[..LONG_PW.len() - 3]));
        assert_eq!(wrong.status.code(), Some(5), "{set}: {}", stderr(&wrong));
        assert_unchanged(&before);
        assert_ok(&extract_with(&archive, &out, Some(LONG_PW)));
        assert_eq!(fs::read(out.join("hello.txt")).unwrap(), b"hello\n");
        assert_eq!(fs::read_dir(&out).unwrap().count(), 1);
        assert_consumed(&archive);
    }
}

/// Once the password is proven, a header that fails its checksum is damage
/// (exit 4), not a wrong password: in RAR 5 by the check value of the
/// archive encryption header, in RAR 4 by the headers of the first volume.
#[test]
fn a_damaged_encrypted_header_is_refused_untouched_as_damage() {
    // The second volume's main header, after the signature and the archive
    // encryption header (38 bytes) and the main header's IV; in RAR 4 after
    // the signature, the plain main header and the salt of the next one.
    for (set, volume, at) in [
        ("rar5-hp-set", "set.part2.rar", 8 + 38 + 16 + 2),
        ("rar5-hp-set", "set.part1.rar", 8 + 38 + 16 + 2),
        ("rar4-hp-set", "set.part2.rar", 7 + 13 + 8 + 2),
    ] {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let path = tmp.path().join(volume);
        let mut bytes = fs::read(&path).unwrap();
        bytes[at] ^= 0xFF;
        fs::write(&path, bytes).unwrap();
        let before = snapshot_dir(tmp.path());
        let out = extract_with(&archive, &tmp.path().join("out"), Some(PW));
        assert_eq!(
            out.status.code(),
            Some(4),
            "{set} {volume}: {}",
            stderr(&out)
        );
        assert_unchanged(&before);
        refused_untouched(tmp.path(), &out);
    }
}

/// UnRAR refuses a set whose volumes disagree on encrypted file names, so
/// that no volume can be swapped for one with other files; so does HatchZip.
#[test]
fn volumes_that_disagree_on_encrypted_names_are_refused_untouched() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5-hp-set", tmp.path());
    let other =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rar/rar5-pw/set.part2.rar");
    fs::copy(other, tmp.path().join("set.part2.rar")).unwrap();
    let before = snapshot_dir(tmp.path());
    let out = extract_with(&archive, &tmp.path().join("out"), Some(PW));
    assert_eq!(out.status.code(), Some(4), "{}", stderr(&out));
    assert!(
        stderr(&out).contains("encrypted file names"),
        "{}",
        stderr(&out)
    );
    assert_unchanged(&before);
    refused_untouched(tmp.path(), &out);
}

/// Restore takes no password, which an archive with encrypted file names
/// needs to be listed and closed again, so it is refused and the
/// extraction can still be completed.
#[test]
fn restore_refuses_encrypted_file_names_and_extract_completes() {
    for set in ["rar5-hp-set", "rar4-hp-set"] {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let out = tmp.path().join("out");
        let crashed = extract(
            &archive,
            &out,
            &[
                ("HATCHZIP_PASSWORD", PW),
                ("HATCHZIP_BATCH_ENTRIES", "1"),
                ("HATCHZIP_CRASH_AT", "after-extract"),
                ("HATCHZIP_CRASH_AFTER", "3"),
            ],
        );
        assert!(!crashed.status.success());
        let before = snapshot_dir(tmp.path());
        let r = hatchzip(
            &[
                "restore",
                archive.to_str().unwrap(),
                "-o",
                out.to_str().unwrap(),
            ],
            &WITH_PW,
        );
        assert_eq!(r.status.code(), Some(1), "{set}: {}", stderr(&r));
        assert!(
            stderr(&r).contains("encrypted file names"),
            "{}",
            stderr(&r)
        );
        assert_unchanged(&before);
        assert!(side_files(&archive)[0].exists(), "the progress was lost");

        assert_ok(&extract_with(&archive, &out, Some(PW)));
        assert_tree(&out, &small());
        assert_consumed(&archive);
    }
}

// -- Refused before anything is touched -------------------------------------------

#[test]
fn solid_archives_are_refused_in_place_and_extract_when_kept() {
    for set in ["rar5-solid", "rar4-solid"] {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let before = snapshot_dir(tmp.path());
        let out = extract(&archive, &tmp.path().join("out"), &[]);
        assert!(!out.status.success());
        let err = stderr(&out);
        assert!(
            err.contains("solid") && err.contains("--keep-archive"),
            "{err}"
        );
        assert_unchanged(&before);
        refused_untouched(tmp.path(), &out);

        let kept = hatchzip(
            &[
                "extract",
                archive.to_str().unwrap(),
                "-o",
                tmp.path().join("out").to_str().unwrap(),
                "--keep-free",
                "0",
                "--keep-archive",
            ],
            &[],
        );
        assert_ok(&kept);
        assert_tree(&tmp.path().join("out"), &small());
        assert_unchanged(&before);
        assert_no_side_files(&archive);
    }
}

/// Kept, a solid set is one unit; a crash in it resumes from the start of
/// the set and the archive stays as it was.
#[test]
fn a_kept_solid_archive_resumes_after_a_crash() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5-solid", tmp.path());
    let before = snapshot_dir(tmp.path());
    let out = tmp.path().join("out");
    let args = |a: &Path, o: &Path| {
        vec![
            "extract".to_string(),
            a.to_string_lossy().into_owned(),
            "-o".into(),
            o.to_string_lossy().into_owned(),
            "--keep-free".into(),
            "0".into(),
            "--keep-archive".into(),
        ]
    };
    let a = args(&archive, &out);
    let a: Vec<&str> = a.iter().map(String::as_str).collect();
    let crashed = hatchzip(&a, &[("HATCHZIP_CRASH_AT", "after-extract")]);
    assert!(!crashed.status.success());
    assert_unchanged(&before);
    assert_ok(&hatchzip(&a, &[]));
    assert_tree(&out, &small());
    assert_unchanged(&before);
}

#[test]
fn rar5_solid_check_json_reports_in_place_refusal() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5-solid", tmp.path());

    let run = hatchzip(
        &[
            "check",
            archive.to_str().unwrap(),
            "--json",
            "--keep-free",
            "0",
        ],
        &[],
    );

    assert_eq!(run.status.code(), Some(1));
    assert!(!run.stderr.is_empty());

    let document: serde_json::Value = serde_json::from_slice(&run.stdout).unwrap();

    assert_eq!(document["version"], 1);

    let archives = document["archives"].as_array().unwrap();
    assert_eq!(archives.len(), 1);

    let result = &archives[0];
    let plan = &result["space_plan"];

    assert!(result["error"].is_null());
    assert!(plan["fits_in_place"].is_null());
    assert!(plan["fits_with_archive_kept"].is_boolean());

    let refusal = plan["in_place_refusal_reason"].as_str().unwrap();
    assert!(refusal.contains("solid"), "{refusal}");
}

#[test]
fn rar4_solid_check_json_reports_in_place_refusal() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar4-solid", tmp.path());

    let run = hatchzip(
        &[
            "check",
            archive.to_str().unwrap(),
            "--json",
            "--keep-free",
            "0",
        ],
        &[],
    );

    assert_eq!(run.status.code(), Some(1));
    assert!(!run.stderr.is_empty());

    let document: serde_json::Value = serde_json::from_slice(&run.stdout).unwrap();

    assert_eq!(document["version"], 1);

    let archives = document["archives"].as_array().unwrap();
    assert_eq!(archives.len(), 1);

    let result = &archives[0];
    let plan = &result["space_plan"];

    assert!(result["error"].is_null());
    assert!(plan["fits_in_place"].is_null());
    assert!(plan["fits_with_archive_kept"].is_boolean());

    let refusal = plan["in_place_refusal_reason"].as_str().unwrap();
    assert!(refusal.contains("solid"), "{refusal}");
}
#[test]
fn a_missing_volume_is_refused_untouched() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5", tmp.path());
    fs::remove_file(tmp.path().join("set.part4.rar")).unwrap();
    let before = snapshot_dir(tmp.path());
    let out = extract(&archive, &tmp.path().join("out"), &[]);
    assert!(!out.status.success());
    assert_unchanged(&before);
    refused_untouched(tmp.path(), &out);
}

#[test]
fn a_damaged_header_is_refused_untouched_as_damage() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5", tmp.path());
    let third = tmp.path().join("set.part3.rar");
    let mut bytes = fs::read(&third).unwrap();
    // Inside the first file header after the signature and main header.
    bytes[40] ^= 0xFF;
    fs::write(&third, bytes).unwrap();
    let before = snapshot_dir(tmp.path());
    let out = extract(&archive, &tmp.path().join("out"), &[]);
    assert_eq!(out.status.code(), Some(4), "{}", stderr(&out));
    assert_unchanged(&before);
    refused_untouched(tmp.path(), &out);
}

/// Names that would land outside the output folder are refused before
/// anything is touched, in RAR 4 (`\` separators) and RAR 5 (`/`).
#[test]
fn hostile_names_are_refused_untouched() {
    for (v, name) in [
        (Version::Four, "..\\evil.txt"),
        (Version::Four, "game\\..\\..\\evil.txt"),
        (Version::Four, "C:\\evil.txt"),
        (Version::Five, "../evil.txt"),
        (Version::Five, "game/../../evil.txt"),
        (Version::Five, "game/a\0b.txt"),
    ] {
        let tmp = TempDir::new().unwrap();
        let mut entries = entries_of(&small());
        entries.insert(0, entry(name, b"evil\n".to_vec()));
        let archive = write_rar(tmp.path(), v, &entries, None, Naming::Old);
        let before = snapshot_dir(tmp.path());
        let out = extract(&archive, &tmp.path().join("out"), &[]);
        assert!(!out.status.success(), "{name:?} was extracted");
        assert_unchanged(&before);
        refused_untouched(tmp.path(), &out);
        assert!(!tmp.path().join("evil.txt").exists());
    }
}

/// A leading slash is dropped, as tar does, and a `\` inside a RAR 5 name
/// is part of the name, which WinRAR writes as `_` on Windows; so does
/// HatchZip, everywhere.
#[test]
fn absolute_names_and_backslashes_land_inside() {
    let tmp = TempDir::new().unwrap();
    let mut entries = entries_of(&small());
    entries.push(entry("/game/rooted.txt", b"rooted\n".to_vec()));
    entries.push(entry("game/back\\slash.txt", b"slash\n".to_vec()));
    let archive = write_rar(tmp.path(), Version::Five, &entries, None, Naming::Old);
    let out = tmp.path().join("out");
    assert_ok(&extract(&archive, &out, &[]));
    let mut files = small();
    files.insert("game/rooted.txt".into(), b"rooted\n".to_vec());
    files.insert("game/back_slash.txt".into(), b"slash\n".to_vec());
    assert_tree(&out, &files);
}

/// Two names that differ only in case would race on a case-insensitive
/// disk, and are refused there as for every format.
#[test]
fn names_differing_only_in_case_depend_on_the_destination() {
    let tmp = TempDir::new().unwrap();
    let mut entries = entries_of(&small());
    entries.push(entry("game/D.PAK", b"other\n".to_vec()));
    let archive = write_rar(tmp.path(), Version::Five, &entries, None, Naming::Old);
    let out = tmp.path().join("out");
    if hatchzip_core::session::case_sensitive(tmp.path()) {
        assert_ok(&extract(&archive, &out, &[]));
        let mut files = small();
        files.insert("game/D.PAK".into(), b"other\n".to_vec());
        assert_tree(&out, &files);
        return;
    }
    let before = snapshot_dir(tmp.path());
    let run = extract(&archive, &out, &[]);
    assert!(!run.status.success());
    assert_unchanged(&before);
    refused_untouched(tmp.path(), &run);
}

/// Extracts a set whose volume 1 holds `first`, followed by two files big
/// enough to make later units that commit, and delete volumes, first. The
/// run must either finish or fail with every volume still there.
fn finishes_or_changes_nothing(first: Entry) -> bool {
    let tmp = TempDir::new().unwrap();
    let entries = vec![
        first,
        entry("game/a.pak", noise(30_000, 1)),
        entry("game/b.pak", noise(30_000, 2)),
    ];
    let archive = write_rar(
        tmp.path(),
        Version::Four,
        &entries,
        Some(20_000),
        Naming::Part,
    );
    let before = snapshot_dir(tmp.path());
    let out = extract(
        &archive,
        &tmp.path().join("out"),
        &[("HATCHZIP_BATCH_ENTRIES", "1")],
    );
    if out.status.success() {
        return true;
    }
    assert_unchanged(&before);
    false
}

/// RAR 2 and 3 stored a name that fits the OEM code page without its
/// Unicode form. Here, Latin-1 "café.txt".
#[test]
fn a_name_without_its_unicode_form() {
    finishes_or_changes_nothing(Entry {
        name: b"game\\caf\xe9.txt".to_vec(),
        data: b"oem\n".to_vec(),
        dir: false,
        info: 0,
    });
}

/// Refused as not supported (exit 1), not as damage, and untouched.
fn refused_as_unsupported(archive: &Path, dir: &Path, says: &str) {
    let before = snapshot_dir(dir);
    let out = extract(archive, &dir.join("out"), &[]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    assert!(stderr(&out).contains(says), "{}", stderr(&out));
    assert_unchanged(&before);
    refused_untouched(dir, &out);
}

/// RAR 7 can compress with dictionaries up to 64 GB, which UnRAR refuses
/// past 4 GB unless asked, and which need that much memory. Refused when
/// the archive is opened, not when the file comes up.
#[test]
fn a_dictionary_over_4_gb_is_refused_untouched() {
    let tmp = TempDir::new().unwrap();
    let mut entries = entries_of(&small());
    // Algorithm version 1 (RAR 7), dictionary 128 KB << 16: 8 GB.
    entries.push(Entry {
        info: 1 | 16 << 10,
        ..entry("game/huge-dictionary.bin", b"data\n".to_vec())
    });
    let archive = write_rar(tmp.path(), Version::Five, &entries, None, Naming::Old);
    refused_as_unsupported(&archive, tmp.path(), "8 GB dictionary");
}

/// Longer than the 1023 characters of UnRAR's `FileNameW`; read in full
/// through `FileNameEx`.
#[test]
fn a_name_longer_than_1024_characters_extracts() {
    let dir = "d".repeat(240);
    let name = format!("game/{dir}/{dir}/{dir}/{dir}/{dir}/deep.txt");
    assert!(name.len() > 1024);
    let finished = finishes_or_changes_nothing(entry(&name, b"deep\n".to_vec()));
    // macOS can't create a path this long (1024 bytes at most), so there it
    // must be refused with the archive untouched instead.
    assert!(finished || cfg!(target_os = "macos"));
}

/// Volumes of an older, longer set with the same name sit after the last
/// volume of this one. The last volume says no more follow, so they are not
/// part of it and must be left alone.
#[test]
fn volumes_after_the_last_one_are_not_part_of_the_set() {
    let tmp = TempDir::new().unwrap();
    let set = |dir: &str, n: u64| -> Vec<Entry> {
        (1..=n)
            .map(|i| entry(&format!("{dir}/f{i}.bin"), noise(15_000, i)))
            .collect()
    };
    write_rar(
        tmp.path(),
        Version::Four,
        &set("old", 5),
        Some(20_000),
        Naming::Part,
    );
    let old = volumes(tmp.path()).len();
    let archive = write_rar(
        tmp.path(),
        Version::Four,
        &set("new", 2),
        Some(20_000),
        Naming::Part,
    );
    let new = (1..)
        .take_while(|i| {
            fs::read(tmp.path().join(format!("set.part{i}.rar")))
                .is_ok_and(|b| b.windows(3).any(|w| w == b"new"))
        })
        .count();
    assert!(old > new, "the old set must be longer");
    let stray = tmp.path().join(format!("set.part{}.rar", new + 1));
    let before = fs::read(&stray).unwrap();

    let r = extract(&archive, &tmp.path().join("out"), &[]);
    assert!(
        !r.status.success(),
        "a set with a stray volume was extracted"
    );
    assert!(
        stderr(&r).contains("belongs to another one"),
        "{}",
        stderr(&r)
    );
    assert_eq!(fs::read(&stray).unwrap(), before);
}

/// `.z01` is a split ZIP, not a RAR volume, unless a `.rar` of the same
/// name is next to it.
#[test]
fn a_z01_file_is_not_taken_for_a_rar_volume() {
    let tmp = TempDir::new().unwrap();
    let z01 = tmp.path().join("game.z01");
    fs::write(&z01, b"PK\x07\x08 not a rar").unwrap();
    let out = hatchzip(&["list", z01.to_str().unwrap()], &[]);
    assert!(!out.status.success());
    assert!(!stderr(&out).contains("game.rar"), "{}", stderr(&out));
}

// -- Restore -----------------------------------------------------------------------

/// A half-extracted set is turned back into one any tool opens, holding the
/// files not yet extracted; extracting it again gives the rest.
#[test]
fn restore_gives_back_a_set_holding_the_rest() {
    for (set, files) in [
        ("rar5", sample()),
        ("rar4", sample()),
        ("rar5-extras", small()),
    ] {
        let tmp = TempDir::new().unwrap();
        let archive = copy_set(set, tmp.path());
        let out = tmp.path().join("out");
        let crashed = extract(
            &archive,
            &out,
            &[
                ("HATCHZIP_BATCH_ENTRIES", "1"),
                ("HATCHZIP_CRASH_AT", "after-extract"),
                ("HATCHZIP_CRASH_AFTER", "3"),
            ],
        );
        assert!(!crashed.status.success());
        assert_ok(&hatchzip(
            &[
                "restore",
                archive.to_str().unwrap(),
                "-o",
                out.to_str().unwrap(),
            ],
            &[],
        ));
        assert_no_side_files(&archive);
        assert_ok(&hatchzip(&["test", archive.to_str().unwrap()], &[]));

        let more = tmp.path().join("more");
        assert_ok(&extract(&archive, &more, &[]));
        // The two folders together hold every file, once.
        for (name, data) in &files {
            let a = fs::read(out.join(name)).ok();
            let b = fs::read(more.join(name)).ok();
            assert!(
                a.is_some() != b.is_some(),
                "{set}: {name} in both or neither"
            );
            assert_eq!(a.or(b).as_ref(), Some(data), "{set}: {name}");
        }
    }
}

/// Killed after it appends the end header, restore is undone by the next
/// run, which either restores again or continues the extraction.
#[test]
fn an_interrupted_restore_can_be_run_again() {
    let tmp = TempDir::new().unwrap();
    let archive = copy_set("rar5", tmp.path());
    let out = tmp.path().join("out");
    let crashed = extract(
        &archive,
        &out,
        &[
            ("HATCHZIP_BATCH_ENTRIES", "1"),
            ("HATCHZIP_CRASH_AT", "after-extract"),
            ("HATCHZIP_CRASH_AFTER", "4"),
        ],
    );
    assert!(!crashed.status.success());
    let a = archive.to_str().unwrap();
    let r = hatchzip(
        &["restore", a, "-o", out.to_str().unwrap()],
        &[("HATCHZIP_CRASH_AT", "restore-appended")],
    );
    assert!(!r.status.success());
    // Continuing the extraction instead.
    assert_ok(&extract(&archive, &out, &[]));
    assert_tree(&out, &sample());
    assert_consumed(&archive);
}