exarch-core 0.8.0

Memory-safe archive extraction library with security validation
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
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
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
//! Filesystem view used by path, symlink and hardlink validation.
//!
//! Extraction validates against the real destination ([`HostFs`]); `verify`
//! validates against an in-memory model of what extraction would create
//! ([`VirtualTree`]) so that an untrusted archive never causes a write.
//!
//! # Limitations
//!
//! [`VirtualTree`] models only the archive's own entries. It cannot account
//! for files, directories or links already present in the extraction
//! destination, so a verification PASS does not guarantee that extraction into
//! a non-empty destination succeeds. Further differences from the host
//! filesystem:
//!
//! - symlink chains are cut off after [`MAX_SYMLINK_HOPS`] hops, a per-OS
//!   constant that matches `std::fs::canonicalize` on the supported hosts
//!   (macOS 33, glibc 40, musl 39, Windows 63 unverified, other Unix 32); a
//!   different filesystem or kernel configuration can still disagree;
//! - name lengths use per-OS limits ([`MAX_COMPONENT_LEN`], [`MAX_PATH_LEN`]:
//!   Linux 4095, macOS and other Unix 1023, Windows 32767 UTF-16 units); a
//!   symlink target is checked against [`MAX_SYMLINK_TARGET_LEN`] only (Windows
//!   4091 UTF-16 units). A filesystem with tighter limits can still refuse a
//!   name the model accepts;
//! - on macOS names are compared after NFD and a per-character
//!   upper/lower/upper case fold, on Windows after the same fold without
//!   normalisation, and elsewhere exactly. The fold is an approximation of the
//!   host's table: two names it merges but the host keeps apart (for example
//!   `i` and dotless `ı`) are reported as a name collision, never silently
//!   merged;
//! - [`PathModel::Portable`] replaces the per-OS rules with the strictest of
//!   them on every host (see its docs). `zip.rs` still strips drive-relative
//!   names under `allow_absolute_paths` by the host's rules, so a Portable sink
//!   on Linux refuses what Windows would strip: it fails closed;
//! - a path that leaves the root and re-enters it is reported as an escape
//!   (`Containment::Escapes`), although the host would resolve it inside;
//! - only extraction that skips an existing entry is modelled; with overwrite
//!   semantics extraction keeps the last entry at a path, which cannot be
//!   modelled here;
//! - the first entry at a path wins, mirroring extraction that skips an
//!   existing file; the one exception is a symlink over an earlier file, which
//!   replaces it so that verification stays conservative for extraction that
//!   overwrites existing files.

use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;

use crate::ArchiveError;
use crate::QuotaResource;
use crate::SecurityConfig;
use crate::closed_enum::closed_enum;
use crate::types::DestDir;

/// Maximum number of symlinks followed while resolving a single path, as the
/// host's `realpath` allows it.
#[cfg(target_os = "macos")]
pub const MAX_SYMLINK_HOPS: usize = 33;

/// Maximum number of symlinks followed while resolving a single path, as the
/// host's `realpath` allows it.
#[cfg(all(target_os = "linux", target_env = "musl"))]
pub const MAX_SYMLINK_HOPS: usize = 39;

/// Maximum number of symlinks followed while resolving a single path, as the
/// host's `realpath` allows it.
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub const MAX_SYMLINK_HOPS: usize = 40;

/// Maximum number of symlinks followed while resolving a single path, as the
/// host's `realpath` allows it.
#[cfg(target_os = "windows")]
pub const MAX_SYMLINK_HOPS: usize = 63;

/// Maximum number of symlinks followed while resolving a single path. A low
/// guess can only turn a PASS into a false FAIL.
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
pub const MAX_SYMLINK_HOPS: usize = 32;

/// Longest single path component the host accepts (`NAME_MAX`), in bytes, or
/// in UTF-16 units on Windows.
pub const MAX_COMPONENT_LEN: usize = 255;

/// Longest relative path the host accepts (`PATH_MAX` less the terminator), in
/// bytes.
#[cfg(target_os = "linux")]
pub const MAX_PATH_LEN: usize = 4095;

/// Longest relative path the host accepts, in UTF-16 units.
///
/// 32767 is the documented limit of an extended-length path. A symlink target
/// is bounded much lower, see [`MAX_SYMLINK_TARGET_LEN`].
#[cfg(target_os = "windows")]
pub const MAX_PATH_LEN: usize = 32767;

/// Longest relative path the host accepts (`PATH_MAX` less the terminator), in
/// bytes. A low guess can only turn a PASS into a false FAIL.
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
pub const MAX_PATH_LEN: usize = 1023;

/// Longest symlink target the host accepts, in UTF-16 units.
///
/// `CreateSymbolicLinkW` stores the substitute and print names in a 16 KiB
/// reparse buffer after a 20-byte header. Extraction only creates relative
/// targets (a `Prefix` or `RootDir` component is rejected), where both names
/// are equal, so `2 * 2n <= 16384 - 20` gives `n <= 4091`. Absolute targets
/// (`\??\` prefix) would allow fewer units but are never created.
#[cfg(target_os = "windows")]
pub const MAX_SYMLINK_TARGET_LEN: usize = 4091;

/// Longest symlink target the host accepts (`PATH_MAX` less the terminator),
/// in bytes.
#[cfg(not(target_os = "windows"))]
pub const MAX_SYMLINK_TARGET_LEN: usize = MAX_PATH_LEN;

/// Longest symlink target in bytes that can pass the
/// [`MAX_SYMLINK_TARGET_LEN`] check; the read and allocation cap for targets
/// stored as bytes.
///
/// On Windows a UTF-16 unit takes at most 3 UTF-8 bytes, so a byte cap never
/// rejects a target the unit check accepts.
#[cfg(target_os = "windows")]
pub const MAX_SYMLINK_TARGET_BYTES: usize = MAX_SYMLINK_TARGET_LEN * 3;

/// Longest symlink target in bytes that can pass the
/// [`MAX_SYMLINK_TARGET_LEN`] check; the read and allocation cap for targets
/// stored as bytes.
#[cfg(not(target_os = "windows"))]
pub const MAX_SYMLINK_TARGET_BYTES: usize = MAX_SYMLINK_TARGET_LEN;

closed_enum! {
    /// The kind of link a target belongs to; the host limits them differently.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::LinkKind;
    ///
    /// assert_eq!(LinkKind::Symlink.as_str(), "symlink");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum LinkKind {
        /// A symbolic link; `symlink(2)` bounds only the whole target
        Symlink => "symlink",
        /// A hard link; the target is resolved as a path, so components count too
        Hardlink => "hardlink",
    }
}

closed_enum! {
    /// The path semantics an [`EntrySink`](crate::EntrySink) is validated
    /// against.
    ///
    /// `Host` applies the rules of the platform running the extraction. On a
    /// Windows host that means the component rules of `Portable` (every
    /// character Windows refuses, reserved names, `:`, trailing dot or space);
    /// on other hosts component names are not restricted.
    /// `Portable` applies the strictest rules of every supported platform, on
    /// every host, for a sink whose storage is read elsewhere:
    ///
    /// - names fold as on macOS (canonical decomposition plus a case fold), so
    ///   two spellings of one name are one name;
    /// - a component with a backslash, one of `<>"|?*`, a control character, a
    ///   `:`, a trailing dot or space, a reserved Windows device name (unless
    ///   `windows_reserved_names` is allowed) or bytes that are not UTF-8 is
    ///   refused;
    /// - a component is at most 255 and a path or symlink target at most 1023,
    ///   counted in UTF-8 bytes and in UTF-16 units alike, and a symlink chain
    ///   is cut off after 32 hops.
    ///
    /// On a Windows host `\` already separates the components of an entry
    /// name when the path is parsed, so it is split there and not refused as a
    /// backslash; every other host refuses it. Not modelled: 8.3 short names
    /// and the legacy 260-unit `MAX_PATH`.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::PathModel;
    ///
    /// assert_eq!(PathModel::default(), PathModel::Host);
    /// assert_eq!(PathModel::Portable.as_str(), "portable");
    /// ```
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum PathModel {
        /// The rules of the platform running the extraction.
        #[default]
        Host => "host",
        /// The strictest rules of every supported platform.
        Portable => "portable",
    }
}

/// The length limits of a [`PathModel`].
#[derive(Debug, Clone, Copy)]
struct NameLimits {
    component: usize,
    path: usize,
    symlink_target: usize,
    hops: usize,
}

impl PathModel {
    const fn limits(self) -> NameLimits {
        match self {
            Self::Host => NameLimits {
                component: MAX_COMPONENT_LEN,
                path: MAX_PATH_LEN,
                symlink_target: MAX_SYMLINK_TARGET_LEN,
                hops: MAX_SYMLINK_HOPS,
            },
            Self::Portable => NameLimits {
                component: 255,
                path: 1023,
                symlink_target: 1023,
                hops: 32,
            },
        }
    }

    fn name_len(self, name: &OsStr) -> usize {
        match self {
            Self::Host => name_len(name),
            Self::Portable => portable_name_len(name),
        }
    }

    /// Rejects entry names this model refuses with `ENAMETOOLONG`.
    ///
    /// # Errors
    ///
    /// Returns an error if the path or any of its components is too long.
    pub(crate) fn check_name_lengths(self, path: &Path) -> io::Result<()> {
        let limits = self.limits();
        let too_long = self.name_len(path.as_os_str()) > limits.path
            || path
                .components()
                .any(|c| self.name_len(c.as_os_str()) > limits.component);
        if too_long {
            return Err(name_too_long());
        }
        Ok(())
    }

    /// Rejects a link target this model refuses with `ENAMETOOLONG`.
    ///
    /// # Errors
    ///
    /// Returns an error if the target is too long for `kind`.
    pub(crate) fn check_link_target_length(self, target: &Path, kind: LinkKind) -> io::Result<()> {
        match kind {
            LinkKind::Symlink
                if self.name_len(target.as_os_str()) > self.limits().symlink_target =>
            {
                Err(name_too_long())
            }
            LinkKind::Symlink => Ok(()),
            LinkKind::Hardlink => self.check_name_lengths(target),
        }
    }
}

/// A name's length in UTF-8 bytes, which is never below its length in UTF-16
/// units, so one limit holds in both.
fn portable_name_len(name: &OsStr) -> usize {
    name.to_string_lossy().len()
}

#[cfg(windows)]
fn name_len(name: &OsStr) -> usize {
    std::os::windows::ffi::OsStrExt::encode_wide(name).count()
}

#[cfg(not(windows))]
fn name_len(name: &OsStr) -> usize {
    name.as_encoded_bytes().len()
}

/// Rejects entry names the host would refuse with `ENAMETOOLONG`.
///
/// # Errors
///
/// Returns an error if the path or any of its components is too long.
pub fn check_name_lengths(path: &Path) -> io::Result<()> {
    PathModel::Host.check_name_lengths(path)
}

/// Rejects a link target the host would refuse with `ENAMETOOLONG`.
///
/// A symlink target is checked against [`MAX_SYMLINK_TARGET_LEN`] only, as
/// `symlink(2)` does; a hardlink target is checked like an entry name.
///
/// # Errors
///
/// Returns an error if the target is too long for `kind`.
pub fn check_link_target_length(target: &Path, kind: LinkKind) -> io::Result<()> {
    PathModel::Host.check_link_target_length(target, kind)
}

/// The error for a name beyond the host's limits.
#[must_use]
pub fn name_too_long() -> io::Error {
    io::Error::new(io::ErrorKind::InvalidFilename, "file name too long")
}

/// A root directory that a validator resolves entry paths against.
///
/// Implemented only by [`DestDir`] (the real destination) and [`VirtualRoot`]
/// (the in-memory model), and tied to its [`FsView`] through
/// [`FsView::Root`], so a root can never be paired with the wrong view.
pub trait ModelRoot {
    /// The root as a path.
    fn as_path(&self) -> &Path;
}

impl ModelRoot for DestDir {
    fn as_path(&self) -> &Path {
        Self::as_path(self)
    }
}

#[cfg(windows)]
const VIRTUAL_ROOT: &str = r"C:\exarch-virtual-root";
#[cfg(not(windows))]
const VIRTUAL_ROOT: &str = "/exarch-virtual-root";

/// The root of a [`VirtualTree`]: a fixed path that is never touched on disk.
///
/// Distinct from [`DestDir`], which promises an existing, canonical, writable
/// directory, so a virtual root can never reach a helper that writes to the
/// host filesystem.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VirtualRoot(PathBuf);

impl VirtualRoot {
    /// Creates the fixed virtual root.
    #[must_use]
    pub fn new() -> Self {
        Self(PathBuf::from(VIRTUAL_ROOT))
    }

    #[cfg(test)]
    pub(crate) fn at(path: &str) -> Self {
        Self(PathBuf::from(path))
    }
}

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

impl ModelRoot for VirtualRoot {
    fn as_path(&self) -> &Path {
        &self.0
    }
}

/// Where a canonicalized path ended up relative to the root of its view.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Containment {
    /// Inside the root, at this canonical path.
    Within(PathBuf),
    /// Outside the root, or not provably inside it.
    Escapes,
}

/// Filesystem probes needed while validating archive entries.
pub trait FsView {
    /// The root type a validator resolves paths against in this view.
    type Root: ModelRoot;

    /// The path semantics validation applies in this view.
    fn path_model(&self) -> PathModel;

    /// Returns `true` if `path` exists, following symlinks.
    fn exists(&self, path: &Path) -> bool;

    /// Returns `true` if `path` exists and is a directory, following symlinks.
    fn is_dir(&self, path: &Path) -> bool;

    /// Returns whether `path` itself is a symlink, without following it.
    ///
    /// # Errors
    ///
    /// Returns an error if `path` cannot be inspected (for example, it does
    /// not exist).
    fn is_symlink(&self, path: &Path) -> io::Result<bool>;

    /// Resolves `path` to its canonical form and says whether that lies inside
    /// `root`.
    ///
    /// # Errors
    ///
    /// Returns an error if a component is missing or the chain cannot be
    /// resolved.
    fn canonicalize(&self, path: &Path, root: &Self::Root) -> io::Result<Containment>;
}

/// Case-insensitive path prefix check for macOS/Windows.
///
/// On case-insensitive filesystems (macOS, Windows), attackers can bypass
/// path validation using different case (e.g., `../../USERS/victim/.ssh/`).
///
/// Compares `path` and `base` component-by-component rather than as raw
/// strings, so a shared name prefix without a component boundary (e.g. base
/// `/tmp/dest` against sibling `/tmp/destevil`) is correctly rejected. See
/// GHSA-wcmx-7f9h-5mv5.
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub fn paths_start_with(path: &Path, base: &Path) -> bool {
    let mut path_components = path.components();
    for base_component in base.components() {
        let Some(path_component) = path_components.next() else {
            return false;
        };
        let path_str = path_component.as_os_str().to_string_lossy().to_lowercase();
        let base_str = base_component.as_os_str().to_string_lossy().to_lowercase();
        if path_str != base_str {
            return false;
        }
    }
    true
}

/// Case-sensitive path prefix check for Unix (not macOS).
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub fn paths_start_with(path: &Path, base: &Path) -> bool {
    path.starts_with(base)
}

/// The real filesystem.
#[derive(Debug, Clone, Copy, Default)]
pub struct HostFs;

impl FsView for HostFs {
    type Root = DestDir;

    fn path_model(&self) -> PathModel {
        PathModel::Host
    }

    fn exists(&self, path: &Path) -> bool {
        path.exists()
    }

    fn is_dir(&self, path: &Path) -> bool {
        path.is_dir()
    }

    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
        std::fs::symlink_metadata(path).map(|m| m.file_type().is_symlink())
    }

    fn canonicalize(&self, path: &Path, root: &DestDir) -> io::Result<Containment> {
        let canonical = std::fs::canonicalize(path)?;
        Ok(if paths_start_with(&canonical, root.as_path()) {
            Containment::Within(canonical)
        } else {
            Containment::Escapes
        })
    }
}

/// How two colliding names differ, which sets how serious the collision is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CollisionKind {
    /// Both are directories and neither holds anything in the archive, so the
    /// merge changes nothing
    Directories,
    /// Both are directories and at least one holds entries, which then land in
    /// one directory and can overwrite each other
    DirectoriesWithContents,
    /// Both are files, so one silently replaces or is skipped for the other
    Files,
    /// The kinds differ or a symlink is involved, so later entries can
    /// resolve differently than the archive intends
    Mixed,
}

/// Two entry names that differ exactly but are one name on the host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NameCollision {
    /// Path of the node that was there first
    pub existing: PathBuf,
    /// Path of the entry that hit it
    pub incoming: PathBuf,
    /// How the two differ
    pub kind: CollisionKind,
}

impl CollisionKind {
    fn of(existing: &Node, incoming: &Node, existing_has_contents: bool) -> Self {
        match (existing, incoming) {
            (Node::Dir, Node::Dir) if existing_has_contents => Self::DirectoriesWithContents,
            (Node::Dir, Node::Dir) => Self::Directories,
            (Node::File, Node::File) => Self::Files,
            _ => Self::Mixed,
        }
    }
}

/// What already occupies a path an insert collided with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Occupant {
    /// A regular file or materialized hardlink.
    File,
    /// A directory.
    Directory,
    /// A symlink, readable or opaque.
    Symlink,
}

impl Occupant {
    /// The noun used in reports.
    pub(crate) const fn noun(self) -> &'static str {
        match self {
            Self::File => "file",
            Self::Directory => "directory",
            Self::Symlink => "symlink",
        }
    }

    /// The text of a refusal to replace this occupant at `rel`, shared by the
    /// host extraction error and the `verify` model so both name the entry and
    /// the occupant in the same words.
    pub(crate) fn refusal(self, rel: &Path) -> String {
        format!(
            "refusing to replace the existing {} at {}",
            self.noun(),
            rel.components().collect::<PathBuf>().display()
        )
    }
}

/// A failed [`VirtualTree::try_insert`].
#[derive(Debug)]
pub struct Conflict {
    /// The error `insert` would report.
    pub(crate) error: io::Error,
    /// `None` when the failure is in the parent chain, not at the path itself.
    pub(crate) occupant: Option<Occupant>,
}

impl Conflict {
    pub(crate) fn already_exists(occupant: Occupant) -> Self {
        Self {
            error: io::Error::from(io::ErrorKind::AlreadyExists),
            occupant: Some(occupant),
        }
    }

    /// [`already_exists`](Self::already_exists) whose error names `rel` and
    /// the occupant.
    pub(crate) fn already_exists_at(occupant: Occupant, rel: &Path) -> Self {
        Self {
            error: io::Error::new(io::ErrorKind::AlreadyExists, occupant.refusal(rel)),
            occupant: Some(occupant),
        }
    }
}

impl From<io::Error> for Conflict {
    fn from(error: io::Error) -> Self {
        Self {
            error,
            occupant: None,
        }
    }
}

/// Bound on the names a [`VirtualTree`] stores.
///
/// A name is charged when a node is added and when a differently spelled
/// alias of a node is remembered, whatever the kind of the entry, so a flood
/// of directory entries or case variants cannot grow the tree without limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeBudget {
    max: usize,
    used: usize,
}

impl NodeBudget {
    /// A budget of `max_file_count * max_path_depth + 1` names: enough for
    /// `max_file_count` files, each at the deepest allowed path with no name
    /// shared. Explicit directory entries and aliases spend it too although
    /// `max_file_count` does not count directories, so an archive of many
    /// directories can exhaust it while within the file limit; raise
    /// `max_file_count` or `max_path_depth` to allow more. Unbounded if either
    /// is `usize::MAX`.
    #[must_use]
    pub fn from_config<State>(config: &SecurityConfig<State>) -> Self {
        let max = if config.max_file_count == usize::MAX || config.max_path_depth == usize::MAX {
            usize::MAX
        } else {
            config
                .max_file_count
                .saturating_mul(config.max_path_depth)
                .saturating_add(1)
        };
        Self { max, used: 0 }
    }

    #[cfg(test)]
    pub(crate) const fn unbounded() -> Self {
        Self {
            max: usize::MAX,
            used: 0,
        }
    }

    #[cfg(test)]
    pub(crate) const fn with_max(max: usize) -> Self {
        Self { max, used: 0 }
    }

    fn charge(&mut self) -> Result<(), NodeBudgetExceeded> {
        if self.used >= self.max {
            return Err(NodeBudgetExceeded { max: self.max });
        }
        self.used += 1;
        Ok(())
    }
}

/// A [`NodeBudget`] that ran out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeBudgetExceeded {
    max: usize,
}

impl From<NodeBudgetExceeded> for ArchiveError {
    fn from(exceeded: NodeBudgetExceeded) -> Self {
        Self::QuotaExceeded {
            resource: QuotaResource::TreeNodes { max: exceeded.max },
        }
    }
}

/// Whether a [`VirtualTree`] keeps the name collisions it detects.
///
/// `verify` reports them; a sink only needs the merged path, so recording
/// there would grow memory with every case variant for nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CollisionRecording {
    /// Keep collisions for [`VirtualTree::take_collisions`] and
    /// [`VirtualTree::take_empty_merges`].
    Record,
    /// Merge the names and forget that they collided.
    Discard,
}

/// Why a [`VirtualTree`] refused to place a node.
#[derive(Debug)]
pub enum PlaceError {
    /// Extraction would fail or change what a path resolves to.
    Conflict(Conflict),
    /// The tree is full.
    Budget(NodeBudgetExceeded),
}

impl PlaceError {
    #[cfg(test)]
    pub(crate) fn into_conflict(self) -> Conflict {
        match self {
            Self::Conflict(conflict) => conflict,
            Self::Budget(exceeded) => panic!("unexpected budget error: {exceeded:?}"),
        }
    }
}

impl From<Conflict> for PlaceError {
    fn from(conflict: Conflict) -> Self {
        Self::Conflict(conflict)
    }
}

impl From<io::Error> for PlaceError {
    fn from(error: io::Error) -> Self {
        Self::Conflict(error.into())
    }
}

impl From<NodeBudgetExceeded> for PlaceError {
    fn from(exceeded: NodeBudgetExceeded) -> Self {
        Self::Budget(exceeded)
    }
}

type FoldFn = for<'a> fn(&'a OsStr) -> Cow<'a, OsStr>;

/// The kind of a node in the in-memory tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Node {
    /// A directory.
    Dir,
    /// A regular file or materialized hardlink.
    File,
    /// A symlink with its target exactly as stored in the archive.
    Symlink(PathBuf),
    /// A symlink whose target was not read, so nothing can be resolved through
    /// it: it exists, but a path that runs through it or lands on it while
    /// being resolved is an error.
    OpaqueSymlink,
}

#[derive(Debug)]
struct TreeNode {
    kind: Node,
    /// The component exactly as the archive spells it.
    name: OsString,
    /// The directory holding this node; the root is its own parent.
    parent: usize,
    /// Only populated for directories; every spelling seen so far (the node's
    /// own and its aliases) mapped to the child, so a repeated spelling is
    /// found without folding it.
    children: HashMap<OsString, usize>,
    /// Folded component to child; empty on hosts that compare names exactly.
    folded: HashMap<OsString, usize>,
    /// Pairs of spellings of this directory that merged while it was empty: if
    /// it later gains an entry the merge stops being harmless.
    empty_merges: Vec<(PathBuf, PathBuf)>,
}

impl TreeNode {
    fn new(kind: Node, name: &OsStr, parent: usize) -> Self {
        Self {
            kind,
            name: name.to_os_string(),
            parent,
            children: HashMap::new(),
            folded: HashMap::new(),
            empty_merges: Vec::new(),
        }
    }
}

const ROOT: usize = 0;

enum Resolved {
    Inside { rel: PathBuf, id: usize },
    Outside,
}

/// Where an insert put its node.
struct Landed {
    parent: usize,
    /// The node that already held the name, if any.
    existing: Option<usize>,
}

/// A child found by name.
#[derive(Clone, Copy)]
struct Found {
    id: usize,
    /// Found only through the fold: the archive spells it differently.
    alias: bool,
}

/// In-memory model of the destination directory built from archive entries.
///
/// Stored as a per-directory component trie, so a lookup or insert costs
/// O(bytes of the path) regardless of how many entries share a prefix. A name
/// is folded only the first time it is seen; repeats, such as the parents of
/// every entry in a directory, hit the exact-spelling map.
///
/// Every name it stores is charged to a [`NodeBudget`].
pub struct VirtualTree {
    root: PathBuf,
    nodes: Vec<TreeNode>,
    model: PathModel,
    fold: FoldFn,
    budget: NodeBudget,
    recording: CollisionRecording,
    collisions: Vec<NameCollision>,
    /// Directories holding at least one empty merge.
    empty_merge_nodes: Vec<usize>,
}

impl VirtualTree {
    /// Creates an empty tree rooted at `root` that applies `model`.
    pub fn new(
        root: &VirtualRoot,
        model: PathModel,
        budget: NodeBudget,
        recording: CollisionRecording,
    ) -> Self {
        let fold = match model {
            PathModel::Host => fold,
            PathModel::Portable => portable_fold,
        };
        Self::build(root, model, fold, budget, recording)
    }

    #[cfg(test)]
    pub(crate) fn for_test(root: &VirtualRoot) -> Self {
        Self::with_fold(root, fold)
    }

    #[cfg(test)]
    pub(crate) fn with_fold(root: &VirtualRoot, fold: FoldFn) -> Self {
        Self::build(
            root,
            PathModel::Host,
            fold,
            NodeBudget::unbounded(),
            CollisionRecording::Record,
        )
    }

    fn build(
        root: &VirtualRoot,
        model: PathModel,
        fold: FoldFn,
        budget: NodeBudget,
        recording: CollisionRecording,
    ) -> Self {
        Self {
            root: root.as_path().to_path_buf(),
            nodes: vec![TreeNode::new(Node::Dir, OsStr::new(""), ROOT)],
            model,
            fold,
            budget,
            recording,
            collisions: Vec::new(),
            empty_merge_nodes: Vec::new(),
        }
    }

    /// Records `node` at `rel` (relative to the root), creating missing
    /// parents as directories and following in-root symlinked parents the way
    /// `create_dir_all` does.
    ///
    /// Names that differ exactly but fold to one key are one name on the host.
    /// Each such pair is recorded once as a [`NameCollision`] (see
    /// [`take_collisions`](Self::take_collisions)) and then handled like an
    /// exact repeat, so a merge is never silent.
    ///
    /// The first node at a path wins, matching extraction that skips an
    /// existing entry. A symlink over a file is ambiguous (extraction skips
    /// it by default but replaces the file when overwriting): the file is
    /// replaced so later entries are checked against the riskier tree, and an
    /// error is returned so the archive is never reported as safe. A symlink
    /// over a directory or a symlink with a different target is refused the
    /// same way, but the existing node stays; a symlink with the same target is
    /// an unchanged duplicate.
    ///
    /// # Errors
    ///
    /// Returns a conflict where extraction can fail: a parent that is a file or
    /// a dangling symlink, a parent chain that loops or leaves the root, a
    /// directory entry over an existing non-directory, a symlink over an
    /// earlier file, directory or symlink with another target, or a file over
    /// an earlier directory (`IsADirectory`) or symlink.
    ///
    /// A failure also names what already occupies the path, so a caller can
    /// tell what overwriting would do. A tree that is out of budget refuses
    /// with [`PlaceError::Budget`].
    pub(crate) fn try_insert(&mut self, rel: &Path, node: Node) -> Result<(), PlaceError> {
        self.insert_node(rel, node).map(drop)
    }

    /// [`try_insert`](Self::try_insert) that also returns where the node
    /// landed: the path relative to the root with every symlinked parent
    /// resolved and every component spelled as the tree first stored it, so two
    /// spellings of one name give one path.
    pub(crate) fn place(&mut self, rel: &Path, node: Node) -> Result<PathBuf, PlaceError> {
        Ok(self
            .insert_node(rel, node)?
            .map_or_else(PathBuf::new, |landed| {
                let leaf = landed.existing.map_or_else(
                    || rel.file_name(),
                    |id| Some(self.node(id).name.as_os_str()),
                );
                let mut resolved = self.path_of(landed.parent);
                resolved.extend(leaf);
                resolved
            }))
    }

    /// The path of node `id` relative to the root, spelled by the stored names.
    fn path_of(&self, mut id: usize) -> PathBuf {
        let mut names = Vec::new();
        while id != ROOT {
            let node = self.node(id);
            names.push(node.name.as_os_str());
            id = node.parent;
        }
        names.into_iter().rev().collect()
    }

    fn insert_node(&mut self, rel: &Path, node: Node) -> Result<Option<Landed>, PlaceError> {
        let Some(name) = rel.file_name() else {
            return Ok(None);
        };
        let parent = self.ensure_dir(rel.parent().unwrap_or_else(|| Path::new("")))?;
        let existing = self.lookup(parent, name);
        if let Some(found) = existing {
            self.settle_alias(parent, found, name, &node, rel, false)?;
        }
        let existing = existing.map(|f| f.id);
        let outcome = match (existing, node) {
            (None, node) => {
                self.add_child(parent, name, node)?;
                Ok(())
            }
            (Some(id), Node::Dir) => match self.node(id).kind {
                Node::Dir => Ok(()),
                Node::File => Err(Conflict::already_exists_at(Occupant::File, rel)),
                Node::OpaqueSymlink => Err(Conflict::already_exists_at(Occupant::Symlink, rel)),
                Node::Symlink(_) => {
                    if self.resolves_to_dir(&self.root.join(rel)) {
                        Ok(())
                    } else {
                        Err(Conflict::already_exists_at(Occupant::Symlink, rel))
                    }
                }
            },
            (Some(id), node @ (Node::Symlink(_) | Node::OpaqueSymlink)) => {
                match self.node(id).kind {
                    Node::File => {
                        self.node_mut(id).kind = node;
                        Err(Conflict::already_exists(Occupant::File))
                    }
                    Node::Dir => Err(Conflict::already_exists(Occupant::Directory)),
                    Node::Symlink(ref kept) if matches!(&node, Node::Symlink(t) if t == kept) => {
                        Ok(())
                    }
                    Node::Symlink(_) | Node::OpaqueSymlink => {
                        Err(Conflict::already_exists(Occupant::Symlink))
                    }
                }
            }
            (Some(id), Node::File) => match self.node(id).kind {
                Node::File => Ok(()),
                Node::Dir => Err(Conflict {
                    error: io::Error::from(io::ErrorKind::IsADirectory),
                    occupant: Some(Occupant::Directory),
                }),
                Node::Symlink(_) | Node::OpaqueSymlink => {
                    Err(Conflict::already_exists(Occupant::Symlink))
                }
            },
        };
        outcome
            .map(|()| Some(Landed { parent, existing }))
            .map_err(PlaceError::Conflict)
    }

    #[cfg(test)]
    pub(crate) fn insert(&mut self, rel: &Path, node: Node) -> io::Result<()> {
        self.try_insert(rel, node)
            .map_err(|err| err.into_conflict().error)
    }

    /// What an earlier entry left at `rel`, without following a link at the
    /// path itself; a parent link is followed as extraction would.
    pub(crate) fn occupant(&self, rel: &Path) -> Option<Occupant> {
        let name = rel.file_name()?;
        let parent = match self.resolve(&self.root.join(rel.parent()?)) {
            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir => id,
            _ => return None,
        };
        let found = self.lookup(parent, name)?;
        Some(match self.node(found.id).kind {
            Node::Dir => Occupant::Directory,
            Node::File => Occupant::File,
            Node::Symlink(_) | Node::OpaqueSymlink => Occupant::Symlink,
        })
    }

    /// Returns `true` if `path` resolves, through symlinks, to a directory.
    pub fn resolves_to_dir(&self, path: &Path) -> bool {
        matches!(
            self.resolve(path),
            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir
        )
    }

    /// Drains the name collisions recorded by inserts since the last call.
    ///
    /// Merges of directories that hold nothing are not included: they are
    /// harmless unless an entry lands in the directory later, so they wait for
    /// [`take_empty_merges`](Self::take_empty_merges).
    pub(crate) fn take_collisions(&mut self) -> Vec<NameCollision> {
        std::mem::take(&mut self.collisions)
    }

    /// Drains the merges of directories that are still empty.
    pub(crate) fn take_empty_merges(&mut self) -> Vec<NameCollision> {
        let nodes = std::mem::take(&mut self.empty_merge_nodes);
        nodes
            .into_iter()
            .flat_map(|id| std::mem::take(&mut self.node_mut(id).empty_merges))
            .map(|(existing, incoming)| NameCollision {
                existing,
                incoming,
                kind: CollisionKind::Directories,
            })
            .collect()
    }

    /// Handles a child found by a differently spelled name: remembers the
    /// spelling, so the pair is reported once, and records the collision.
    ///
    /// `incoming_has_contents` is true when the spelling is used as the parent
    /// of an entry, which makes a directory merge harmful at once; an empty
    /// merge is flagged so it is upgraded if the directory gains an entry.
    fn settle_alias(
        &mut self,
        parent: usize,
        found: Found,
        name: &OsStr,
        incoming_node: &Node,
        incoming: &Path,
        incoming_has_contents: bool,
    ) -> Result<(), NodeBudgetExceeded> {
        if !found.alias {
            return Ok(());
        }
        self.budget.charge()?;
        self.node_mut(parent)
            .children
            .insert(name.to_os_string(), found.id);
        if self.recording == CollisionRecording::Discard {
            return Ok(());
        }
        let existing = self.node(found.id);
        let has_contents = incoming_has_contents || !existing.children.is_empty();
        let kind = CollisionKind::of(&existing.kind, incoming_node, has_contents);
        let existing_path = incoming.with_file_name(&existing.name);
        if kind == CollisionKind::Directories {
            let node = self.node_mut(found.id);
            node.empty_merges
                .push((existing_path, incoming.to_path_buf()));
            self.empty_merge_nodes.push(found.id);
            return Ok(());
        }
        self.collisions.push(NameCollision {
            existing: existing_path,
            incoming: incoming.to_path_buf(),
            kind,
        });
        Ok(())
    }

    fn node(&self, id: usize) -> &TreeNode {
        &self.nodes[id]
    }

    fn node_mut(&mut self, id: usize) -> &mut TreeNode {
        &mut self.nodes[id]
    }

    fn lookup(&self, parent: usize, name: &OsStr) -> Option<Found> {
        if self.model.name_len(name) > self.model.limits().component {
            return None;
        }
        let node = self.node(parent);
        if let Some(&id) = node.children.get(name) {
            return Some(Found { id, alias: false });
        }
        match (self.fold)(name) {
            Cow::Borrowed(_) => None,
            Cow::Owned(key) => node.folded.get(&key).map(|&id| Found { id, alias: true }),
        }
    }

    fn child(&self, parent: usize, name: &OsStr) -> Option<usize> {
        self.lookup(parent, name).map(|found| found.id)
    }

    /// Adds a node under `parent`.
    fn add_child(
        &mut self,
        parent: usize,
        name: &OsStr,
        kind: Node,
    ) -> Result<usize, NodeBudgetExceeded> {
        self.budget.charge()?;
        let id = self.nodes.len();
        self.nodes.push(TreeNode::new(kind, name, parent));
        let key = match (self.fold)(name) {
            Cow::Borrowed(_) => None,
            Cow::Owned(key) => Some(key),
        };
        let upgrade = {
            let parent_node = self.node_mut(parent);
            parent_node.children.insert(name.to_os_string(), id);
            if let Some(key) = key {
                parent_node.folded.insert(key, id);
            }
            std::mem::take(&mut parent_node.empty_merges)
        };
        for (existing, incoming) in upgrade {
            self.collisions.push(NameCollision {
                existing,
                incoming,
                kind: CollisionKind::DirectoriesWithContents,
            });
        }
        Ok(id)
    }

    fn ensure_dir(&mut self, rel: &Path) -> Result<usize, PlaceError> {
        let mut current = ROOT;
        let mut walked = PathBuf::new();
        for component in rel.components() {
            let name = match component {
                Component::Normal(name) => name,
                Component::CurDir => continue,
                _ => return Err(io::Error::from(io::ErrorKind::InvalidInput).into()),
            };
            walked.push(name);
            current = match self.lookup(current, name) {
                None => self.add_child(current, name, Node::Dir)?,
                Some(found) => {
                    self.settle_alias(current, found, name, &Node::Dir, &walked, true)?;
                    match self.node(found.id).kind {
                        Node::Dir => found.id,
                        Node::File => {
                            return Err(io::Error::from(io::ErrorKind::NotADirectory).into());
                        }
                        Node::OpaqueSymlink => return Err(unread_target_error().into()),
                        Node::Symlink(_) => match self.resolve(&self.root.join(&walked))? {
                            Resolved::Inside { id, .. } if self.node(id).kind == Node::Dir => id,
                            Resolved::Inside { .. } => {
                                return Err(io::Error::from(io::ErrorKind::NotADirectory).into());
                            }
                            Resolved::Outside => {
                                return Err(
                                    io::Error::other("path leaves the extraction root").into()
                                );
                            }
                        },
                    }
                }
            };
        }
        Ok(current)
    }

    fn resolve(&self, path: &Path) -> io::Result<Resolved> {
        let Ok(rel) = path.strip_prefix(&self.root) else {
            return Ok(Resolved::Outside);
        };
        let mut pending: VecDeque<Component<'_>> = rel.components().collect();
        let mut stack = vec![ROOT];
        let mut current = PathBuf::new();
        let mut hops = 0;

        while let Some(component) = pending.pop_front() {
            match component {
                Component::CurDir => {}
                Component::ParentDir => {
                    if stack.len() == 1 {
                        return Ok(Resolved::Outside);
                    }
                    stack.pop();
                    current.pop();
                }
                Component::Normal(name) => {
                    let top = stack.last().copied().unwrap_or(ROOT);
                    let Some(id) = self.child(top, name) else {
                        return Err(io::Error::from(io::ErrorKind::NotFound));
                    };
                    match &self.node(id).kind {
                        Node::Dir => {
                            stack.push(id);
                            current.push(&self.node(id).name);
                        }
                        Node::File => {
                            if !pending.is_empty() {
                                return Err(io::Error::from(io::ErrorKind::NotADirectory));
                            }
                            stack.push(id);
                            current.push(&self.node(id).name);
                        }
                        Node::OpaqueSymlink => {
                            if !pending.is_empty() {
                                return Err(unread_target_error());
                            }
                            stack.push(id);
                            current.push(&self.node(id).name);
                        }
                        Node::Symlink(target) => {
                            hops += 1;
                            if hops > self.model.limits().hops {
                                return Err(io::Error::other("too many levels of symbolic links"));
                            }
                            if target.has_root()
                                || target.components().next().is_some_and(is_prefix)
                            {
                                return Ok(Resolved::Outside);
                            }
                            for part in target.components().rev() {
                                pending.push_front(part);
                            }
                        }
                    }
                }
                Component::RootDir | Component::Prefix(_) => {
                    return Ok(Resolved::Outside);
                }
            }
        }
        Ok(Resolved::Inside {
            rel: current,
            id: stack.last().copied().unwrap_or(ROOT),
        })
    }
}

impl FsView for VirtualTree {
    type Root = VirtualRoot;

    fn path_model(&self) -> PathModel {
        self.model
    }

    fn exists(&self, path: &Path) -> bool {
        matches!(self.resolve(path), Ok(Resolved::Inside { .. }))
    }

    fn is_dir(&self, path: &Path) -> bool {
        self.resolves_to_dir(path)
    }

    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
        let not_found = || io::Error::from(io::ErrorKind::NotFound);
        let Ok(rel) = path.strip_prefix(&self.root) else {
            return Err(not_found());
        };
        let Some(name) = rel.file_name() else {
            return Ok(false);
        };
        let parent = self
            .root
            .join(rel.parent().unwrap_or_else(|| Path::new("")));
        let Resolved::Inside { id: parent, .. } = self.resolve(&parent)? else {
            return Err(not_found());
        };
        let id = self.child(parent, name).ok_or_else(not_found)?;
        Ok(matches!(
            self.node(id).kind,
            Node::Symlink(_) | Node::OpaqueSymlink
        ))
    }

    fn canonicalize(&self, path: &Path, _: &VirtualRoot) -> io::Result<Containment> {
        match self.resolve(path)? {
            Resolved::Inside { id, .. } if self.node(id).kind == Node::OpaqueSymlink => {
                Err(unread_target_error())
            }
            Resolved::Inside { rel, .. } => Ok(Containment::Within(self.root.join(rel))),
            Resolved::Outside => Ok(Containment::Escapes),
        }
    }
}

fn unread_target_error() -> io::Error {
    io::Error::other("path runs through a symlink whose target was not read")
}

fn is_prefix(component: Component<'_>) -> bool {
    matches!(component, Component::Prefix(_))
}

/// Compares names the way the host does, as far as it can be modelled.
///
/// Non-UTF-8 names are folded lossily, which can only merge more names, and a
/// merge of differently spelled names is always reported.
#[cfg(target_os = "macos")]
fn fold(name: &OsStr) -> Cow<'_, OsStr> {
    portable_fold(name)
}

#[cfg(target_os = "windows")]
fn fold(name: &OsStr) -> Cow<'_, OsStr> {
    let text = name.to_string_lossy();
    let folded = if text.is_ascii() {
        text.to_ascii_uppercase()
    } else {
        fold_unicode(&text)
    };
    Cow::Owned(OsString::from(folded))
}

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn fold(name: &OsStr) -> Cow<'_, OsStr> {
    Cow::Borrowed(name)
}

/// The fold of [`PathModel::Portable`], the same on every host: the key
/// macOS uses.
fn portable_fold(name: &OsStr) -> Cow<'_, OsStr> {
    let text = name.to_string_lossy();
    let folded = if text.is_ascii() {
        text.to_ascii_uppercase()
    } else {
        decomposed_fold(&text)
    };
    Cow::Owned(OsString::from(folded))
}

/// APFS compares canonically decomposed names case-insensitively.
fn decomposed_fold(text: &str) -> String {
    use unicode_normalization::UnicodeNormalization;
    upper_lower_upper(text.nfd())
}

/// NTFS compares names case-insensitively without normalisation.
#[cfg(target_os = "windows")]
fn fold_unicode(text: &str) -> String {
    upper_lower_upper(text.chars())
}

/// Full per-character case folding built from the standard library only.
///
/// Upper-casing first merges `ß` with `ẞ`, lower-casing merges the final
/// sigma and `ϴ` with `θ`, and the last upper-casing makes the key stable.
fn upper_lower_upper(chars: impl Iterator<Item = char>) -> String {
    chars
        .flat_map(char::to_uppercase)
        .flat_map(char::to_lowercase)
        .flat_map(char::to_uppercase)
        .collect()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::assert_matches;

    fn tree() -> VirtualTree {
        VirtualTree::with_fold(&VirtualRoot::at("/dest"), fold)
    }

    fn put(t: &mut VirtualTree, path: &str, node: Node) {
        t.insert(Path::new(path), node).unwrap();
    }

    fn canon(t: &VirtualTree, path: &str) -> io::Result<Containment> {
        t.canonicalize(Path::new(path), &VirtualRoot::at("/dest"))
    }

    fn within(t: &VirtualTree, path: &str) -> PathBuf {
        match canon(t, path).unwrap() {
            Containment::Within(p) => p,
            Containment::Escapes => panic!("{path} escapes"),
        }
    }

    fn sym(target: &str) -> Node {
        Node::Symlink(PathBuf::from(target))
    }

    #[test]
    fn insert_creates_implicit_parents() {
        let mut t = tree();
        put(&mut t, "a/b/c.txt", Node::File);
        assert!(t.exists(Path::new("/dest/a/b")));
        assert!(t.exists(Path::new("/dest/a/b/c.txt")));
        assert!(!t.exists(Path::new("/dest/a/x")));
    }

    #[test]
    fn missing_component_is_not_found() {
        let t = tree();
        let err = canon(&t, "/dest/nope").unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::NotFound);
    }

    #[test]
    fn in_root_chain_resolves_to_final_location() {
        let mut t = tree();
        put(&mut t, "real", Node::Dir);
        put(&mut t, "b", sym("real"));
        put(&mut t, "a", sym("b"));
        assert_eq!(within(&t, "/dest/a"), PathBuf::from("/dest/real"));
    }

    #[test]
    fn chain_leaving_root_escapes() {
        let mut t = tree();
        put(&mut t, "y", sym("."));
        put(&mut t, "d", sym("y/.."));
        put(&mut t, "e", sym("d/.."));
        assert_eq!(canon(&t, "/dest/e/secret").unwrap(), Containment::Escapes);
    }

    #[test]
    fn a_path_that_leaves_the_root_and_reenters_it_still_escapes() {
        let mut t = VirtualTree::for_test(&VirtualRoot::new());
        put(&mut t, "up", sym(".."));
        put(&mut t, "abs", sym("/exarch-virtual-root/x"));
        let root = VirtualRoot::new();
        for target in [
            "/exarch-virtual-root/up/exarch-virtual-root/x",
            "/exarch-virtual-root/abs",
        ] {
            assert_eq!(
                t.canonicalize(Path::new(target), &root).unwrap(),
                Containment::Escapes,
                "{target}"
            );
        }
    }

    #[test]
    fn symlink_loop_is_an_error() {
        let mut t = tree();
        put(&mut t, "a", sym("b"));
        put(&mut t, "b", sym("a"));
        assert!(canon(&t, "/dest/a").is_err());
    }

    #[test]
    fn long_chain_hits_hop_limit() {
        let mut t = tree();
        put(&mut t, "l0", Node::Dir);
        for i in 1..=MAX_SYMLINK_HOPS + 1 {
            put(&mut t, &format!("l{i}"), sym(&format!("l{}", i - 1)));
        }
        let over = format!("/dest/l{}", MAX_SYMLINK_HOPS + 1);
        let at = format!("/dest/l{MAX_SYMLINK_HOPS}");
        assert!(canon(&t, &over).is_err());
        assert!(canon(&t, &at).is_ok());
    }

    #[cfg(any(unix, windows))]
    fn make_symlink(target: &str, link: &Path) -> io::Result<()> {
        #[cfg(unix)]
        return std::os::unix::fs::symlink(target, link);
        #[cfg(windows)]
        return std::os::windows::fs::symlink_dir(target, link);
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn hop_limit_matches_host_canonicalize() {
        let temp = tempfile::TempDir::new().unwrap();
        // The temp dir itself may sit behind a symlink (/var on macOS), which
        // would spend one hop of the chain below.
        let root = temp.path().canonicalize().unwrap();
        std::fs::create_dir(root.join("l0")).unwrap();

        let mut resolvable = 0;
        for i in 1..=MAX_SYMLINK_HOPS + 8 {
            let linked = make_symlink(&format!("l{}", i - 1), &root.join(format!("l{i}")));
            assert!(linked.is_ok(), "cannot create symlinks here: {linked:?}");
            if std::fs::canonicalize(root.join(format!("l{i}"))).is_err() {
                break;
            }
            resolvable = i;
        }
        assert_eq!(resolvable, MAX_SYMLINK_HOPS, "host and model limits differ");

        let mut t = tree();
        put(&mut t, "l0", Node::Dir);
        for i in 1..=resolvable + 1 {
            put(&mut t, &format!("l{i}"), sym(&format!("l{}", i - 1)));
        }
        assert!(canon(&t, &format!("/dest/l{resolvable}")).is_ok());
        assert!(canon(&t, &format!("/dest/l{}", resolvable + 1)).is_err());
    }

    fn ascii_upper(name: &OsStr) -> Cow<'_, OsStr> {
        Cow::Owned(OsString::from(name.to_string_lossy().to_ascii_uppercase()))
    }

    fn folding_tree() -> VirtualTree {
        VirtualTree::with_fold(&VirtualRoot::at("/dest"), ascii_upper)
    }

    #[test]
    fn place_resolves_in_root_symlinked_parents() {
        let mut t = tree();
        put(&mut t, "real", Node::Dir);
        put(&mut t, "alias", sym("real"));
        let placed = t.place(Path::new("alias/f"), Node::File).unwrap();
        assert_eq!(placed, PathBuf::from("real/f"));
    }

    #[test]
    fn place_spells_a_folded_name_as_first_stored() {
        let mut t = folding_tree();
        assert_eq!(
            t.place(Path::new("a/x"), Node::File).unwrap(),
            PathBuf::from("a/x")
        );
        assert_eq!(
            t.place(Path::new("A/x"), Node::File).unwrap(),
            PathBuf::from("a/x")
        );
        assert_eq!(within(&t, "/dest/A/X"), PathBuf::from("/dest/a/x"));
    }

    #[test]
    fn place_of_the_root_is_empty_and_conflicts_leave_no_path() {
        let mut t = tree();
        assert_eq!(t.place(Path::new(""), Node::Dir).unwrap(), PathBuf::new());
        put(&mut t, "f", Node::File);
        assert!(t.place(Path::new("f"), Node::Dir).is_err());
        assert!(t.place(Path::new("f/g"), Node::File).is_err());
    }

    fn budgeted(max: usize, recording: CollisionRecording) -> VirtualTree {
        VirtualTree::build(
            &VirtualRoot::at("/dest"),
            PathModel::Host,
            ascii_upper,
            NodeBudget::with_max(max),
            recording,
        )
    }

    #[test]
    fn node_budget_refuses_the_key_after_the_last() {
        let mut t = budgeted(3, CollisionRecording::Record);
        for name in ["a", "b", "c"] {
            put(&mut t, name, Node::Dir);
        }
        let err = t.try_insert(Path::new("d"), Node::Dir).unwrap_err();
        assert_matches!(err, PlaceError::Budget(NodeBudgetExceeded { max: 3 }));
        assert!(!t.exists(Path::new("/dest/d")));
    }

    #[test]
    fn node_budget_charges_implicit_parents() {
        let mut t = budgeted(2, CollisionRecording::Record);
        let err = t.try_insert(Path::new("a/b/c"), Node::File).unwrap_err();
        assert_matches!(err, PlaceError::Budget(_));
    }

    #[test]
    fn node_budget_charges_alias_spellings_once() {
        let mut t = budgeted(3, CollisionRecording::Discard);
        put(&mut t, "dir", Node::Dir);
        put(&mut t, "Dir", Node::Dir);
        put(&mut t, "Dir", Node::Dir);
        put(&mut t, "DIR", Node::Dir);
        let err = t.try_insert(Path::new("dIr"), Node::Dir).unwrap_err();
        assert_matches!(err, PlaceError::Budget(_));
    }

    #[test]
    fn discard_keeps_no_collision_records_after_a_flood() {
        let mut t = budgeted(usize::MAX, CollisionRecording::Discard);
        put(&mut t, "d/f", Node::File);
        for spelling in ["D", "d", "Dd"] {
            let _ = t.insert(Path::new(spelling), Node::Dir);
        }
        put(&mut t, "D/g", Node::File);
        put(&mut t, "Dir", Node::Dir);
        put(&mut t, "dir", Node::Dir);
        put(&mut t, "dir/x", Node::File);
        assert!(t.take_collisions().is_empty());
        assert!(t.take_empty_merges().is_empty());
        assert!(t.exists(Path::new("/dest/D/f")));
    }

    #[test]
    fn unbounded_config_budget_never_trips() {
        let config = crate::SecurityConfig::default()
            .with_max_file_count(usize::MAX)
            .with_max_path_depth(8);
        let mut t = VirtualTree::build(
            &VirtualRoot::at("/dest"),
            PathModel::Host,
            fold,
            NodeBudget::from_config(&config),
            CollisionRecording::Discard,
        );
        for i in 0..1000 {
            put(&mut t, &format!("d{i}"), Node::Dir);
        }
    }

    #[test]
    fn config_budget_is_files_times_depth_plus_one() {
        let config = crate::SecurityConfig::default()
            .with_max_file_count(10)
            .with_max_path_depth(4);
        assert_eq!(NodeBudget::from_config(&config).max, 41);
    }

    fn collisions_of(t: &mut VirtualTree) -> Vec<(String, String, CollisionKind)> {
        t.take_collisions()
            .into_iter()
            .map(|c| {
                (
                    c.existing.display().to_string().replace('\\', "/"),
                    c.incoming.display().to_string().replace('\\', "/"),
                    c.kind,
                )
            })
            .collect()
    }

    #[test]
    fn exact_repeat_is_not_a_collision() {
        let mut t = folding_tree();
        put(&mut t, "a/f", Node::File);
        put(&mut t, "a/f", Node::File);
        assert!(t.take_collisions().is_empty());
    }

    #[test]
    fn differently_spelled_files_collide() {
        let mut t = folding_tree();
        put(&mut t, "d/a.txt", Node::File);
        put(&mut t, "d/A.txt", Node::File);
        assert_eq!(
            collisions_of(&mut t),
            [("d/a.txt".into(), "d/A.txt".into(), CollisionKind::Files)]
        );
        assert!(t.take_collisions().is_empty());
    }

    #[test]
    fn differently_spelled_parent_directories_collide() {
        let mut t = folding_tree();
        put(&mut t, "Images/x", Node::File);
        put(&mut t, "images/y", Node::File);
        assert_eq!(
            collisions_of(&mut t),
            [(
                "Images".into(),
                "images".into(),
                CollisionKind::DirectoriesWithContents
            )]
        );
    }

    #[test]
    fn a_spelling_is_reported_once_however_many_entries_use_it() {
        let mut t = folding_tree();
        put(&mut t, "Images/a", Node::File);
        for i in 0..100 {
            put(&mut t, &format!("images/f{i}"), Node::File);
        }
        assert_eq!(collisions_of(&mut t).len(), 1);
    }

    #[test]
    fn empty_directories_merge_harmlessly_until_one_gains_an_entry() {
        let mut t = folding_tree();
        put(&mut t, "Dir", Node::Dir);
        put(&mut t, "dir", Node::Dir);
        assert!(collisions_of(&mut t).is_empty());
        put(&mut t, "Dir/f", Node::File);
        put(&mut t, "dir/g", Node::File);
        assert_eq!(
            collisions_of(&mut t),
            [(
                "Dir".into(),
                "dir".into(),
                CollisionKind::DirectoriesWithContents
            )]
        );
    }

    #[test]
    fn empty_merges_are_reported_once_when_nothing_lands_in_them() {
        let mut t = folding_tree();
        put(&mut t, "Dir", Node::Dir);
        put(&mut t, "dir", Node::Dir);
        put(&mut t, "other", Node::File);
        let merges: Vec<_> = t
            .take_empty_merges()
            .into_iter()
            .map(|c| {
                (
                    c.existing.display().to_string(),
                    c.incoming.display().to_string(),
                    c.kind,
                )
            })
            .collect();
        assert_eq!(
            merges,
            [("Dir".into(), "dir".into(), CollisionKind::Directories)]
        );
        assert!(t.take_empty_merges().is_empty());
    }

    #[test]
    fn directory_entry_over_a_directory_with_contents_is_not_harmless() {
        let mut t = folding_tree();
        put(&mut t, "Dir/f", Node::File);
        put(&mut t, "dir", Node::Dir);
        assert_eq!(
            collisions_of(&mut t),
            [(
                "Dir".into(),
                "dir".into(),
                CollisionKind::DirectoriesWithContents
            )]
        );
    }

    #[test]
    fn names_are_folded_once_however_often_they_repeat() {
        use std::sync::atomic::AtomicUsize;
        use std::sync::atomic::Ordering;

        static CALLS: AtomicUsize = AtomicUsize::new(0);
        fn counting(name: &OsStr) -> Cow<'_, OsStr> {
            CALLS.fetch_add(1, Ordering::Relaxed);
            ascii_upper(name)
        }

        let mut t = VirtualTree::with_fold(&VirtualRoot::at("/dest"), counting);
        for i in 0..500 {
            put(&mut t, &format!("a/b/c/d/file{i}"), Node::File);
        }
        // Four directories and 500 files, each folded to look up and to store;
        // a fold per parent per entry would be about 2500 calls.
        assert!(CALLS.load(Ordering::Relaxed) <= 2 * 504 + 8);
    }

    #[test]
    fn collision_across_kinds_or_with_a_symlink_is_mixed() {
        let mut t = folding_tree();
        put(&mut t, "a", Node::File);
        let _ = t.insert(Path::new("A"), Node::Dir);
        put(&mut t, "link", sym("a"));
        let _ = t.insert(Path::new("LINK"), Node::File);
        assert_eq!(
            collisions_of(&mut t),
            [
                ("a".into(), "A".into(), CollisionKind::Mixed),
                ("link".into(), "LINK".into(), CollisionKind::Mixed)
            ]
        );
    }

    #[test]
    fn symlink_over_an_existing_dir_is_refused_and_keeps_the_dir() {
        let mut t = folding_tree();
        put(&mut t, "d/f", Node::File);
        let err = t.insert(Path::new("d"), sym("sub")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        let err = t.insert(Path::new("d"), Node::OpaqueSymlink).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert!(t.resolves_to_dir(&t.root.join("d")));
    }

    #[test]
    fn collision_is_recorded_when_insert_fails() {
        let mut t = folding_tree();
        put(&mut t, "y", Node::File);
        let err = t.insert(Path::new("Y"), sym(".")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert_eq!(
            collisions_of(&mut t),
            [("y".into(), "Y".into(), CollisionKind::Mixed)]
        );
    }

    #[cfg(target_os = "macos")]
    mod macos {
        use super::super::fold;
        use super::*;

        fn key(s: &str) -> OsString {
            fold(OsStr::new(s)).into_owned()
        }

        #[test]
        fn special_case_pairs_fold_equal() {
            assert_eq!(key("\u{df}"), key("\u{1e9e}"));
            assert_eq!(key("\u{3b8}"), key("\u{3f4}"));
            assert_eq!(key("\u{3b8}"), key("\u{3d1}"));
            assert_eq!(key("\u{3c2}"), key("\u{3a3}"));
        }

        #[test]
        fn canonically_equivalent_names_fold_equal() {
            assert_eq!(key("caf\u{e9}"), key("cafe\u{301}"));
            assert_eq!(key("\u{ac00}"), key("\u{1100}\u{1161}"));
        }

        #[test]
        fn nfc_and_nfd_spellings_collide_in_the_tree() {
            let mut t = tree();
            put(&mut t, "caf\u{e9}", Node::File);
            put(&mut t, "cafe\u{301}", Node::File);
            assert_eq!(t.take_collisions().len(), 1);
        }

        #[test]
        fn fold_never_under_merges_what_apfs_treats_as_equal() {
            let temp = tempfile::TempDir::new().unwrap();
            let root = temp.path().canonicalize().unwrap();
            let mut seen = std::collections::HashSet::new();
            let mut under = Vec::new();
            // Blocks with case or normalisation behaviour; the Hangul block is
            // sampled because it decomposes algorithmically.
            let candidates = (0x1..=0x3000)
                .chain((0xAC00..=0xD7A3).step_by(11))
                .chain(0xF900..=0xFFFF)
                .chain(0x1_0400..=0x1_044F)
                .chain(0x1_E900..=0x1_E943);
            for code in candidates {
                let Some(c) = char::from_u32(code).filter(|c| !matches!(c, '/' | '.')) else {
                    continue;
                };
                let name = c.to_string();
                let path = root.join(&name);
                let host_equal = path.symlink_metadata().is_ok();
                if !host_equal && std::fs::File::create_new(&path).is_err() {
                    continue;
                }
                let model_seen = !seen.insert(key(&name));
                if host_equal && !model_seen {
                    under.push(format!("U+{code:04X}"));
                }
            }
            assert!(under.is_empty(), "under-merged: {under:?}");
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn fold_covers_ntfs_simple_uppercase() {
        use std::collections::HashMap;

        let mut by_upper: HashMap<char, OsString> = HashMap::new();
        for code in 0x1..=0x1_FFFFu32 {
            let Some(c) = char::from_u32(code) else {
                continue;
            };
            let mut upper = c.to_uppercase();
            let simple = match (upper.next(), upper.next()) {
                (Some(u), None) => u,
                _ => c,
            };
            let key = fold(OsStr::new(&c.to_string())).into_owned();
            let expected = by_upper.entry(simple).or_insert_with(|| key.clone());
            assert_eq!(*expected, key, "U+{code:04X}");
        }
    }

    #[test]
    fn dangling_symlink_does_not_exist_but_is_a_symlink() {
        let mut t = tree();
        put(&mut t, "d", sym("missing"));
        assert!(!t.exists(Path::new("/dest/d")));
        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
    }

    #[test]
    fn opaque_symlink_exists_and_is_a_symlink_but_not_a_directory() {
        let mut t = tree();
        put(&mut t, "d", Node::OpaqueSymlink);
        assert!(t.exists(Path::new("/dest/d")));
        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
        assert!(!t.resolves_to_dir(Path::new("/dest/d")));
    }

    #[test]
    fn nothing_resolves_through_an_opaque_symlink() {
        let mut t = tree();
        put(&mut t, "d", Node::OpaqueSymlink);
        assert!(canon(&t, "/dest/d").is_err());
        assert!(canon(&t, "/dest/d/x").is_err());
        assert!(t.insert(Path::new("d/f"), Node::File).is_err());
    }

    #[test]
    fn a_chain_ending_at_an_opaque_symlink_does_not_resolve() {
        let mut t = tree();
        put(&mut t, "d", Node::OpaqueSymlink);
        put(&mut t, "l", sym("d"));
        assert!(canon(&t, "/dest/l").is_err());
    }

    #[test]
    fn opaque_symlink_keeps_its_place_like_a_symlink() {
        let mut t = tree();
        put(&mut t, "d", Node::OpaqueSymlink);
        assert_eq!(
            t.insert(Path::new("d"), Node::Dir).unwrap_err().kind(),
            io::ErrorKind::AlreadyExists
        );
        assert_eq!(
            t.insert(Path::new("d"), Node::File).unwrap_err().kind(),
            io::ErrorKind::AlreadyExists
        );
        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());

        put(&mut t, "f", Node::File);
        assert!(t.insert(Path::new("f"), Node::OpaqueSymlink).is_err());
        assert!(t.is_symlink(Path::new("/dest/f")).unwrap());
    }

    #[test]
    fn opaque_symlink_collision_is_mixed() {
        let mut t = folding_tree();
        put(&mut t, "link", Node::OpaqueSymlink);
        let _ = t.insert(Path::new("LINK"), Node::File);
        assert_eq!(
            collisions_of(&mut t),
            [("link".into(), "LINK".into(), CollisionKind::Mixed)]
        );
    }

    #[test]
    fn is_symlink_follows_symlinked_parents() {
        let mut t = tree();
        put(&mut t, "real/inner", sym("x"));
        put(&mut t, "alias", sym("real"));
        assert!(t.is_symlink(Path::new("/dest/alias/inner")).unwrap());
        assert!(!t.is_symlink(Path::new("/dest/real")).unwrap());
        assert!(t.is_symlink(Path::new("/dest/none")).is_err());
    }

    #[test]
    fn insert_through_symlinked_parent_lands_at_resolved_location() {
        let mut t = tree();
        put(&mut t, "real", Node::Dir);
        put(&mut t, "alias", sym("real"));
        put(&mut t, "alias/f", Node::File);
        assert!(t.exists(Path::new("/dest/real/f")));
    }

    #[test]
    fn insert_dir_keeps_existing_symlink() {
        let mut t = tree();
        put(&mut t, "real", Node::Dir);
        put(&mut t, "alias", sym("real"));
        put(&mut t, "alias", Node::Dir);
        assert!(t.is_symlink(Path::new("/dest/alias")).unwrap());
    }

    #[test]
    fn file_never_replaces_existing_symlink() {
        let mut t = tree();
        put(&mut t, "y", sym("."));
        let err = t.insert(Path::new("y"), Node::File).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert!(t.is_symlink(Path::new("/dest/y")).unwrap());
    }

    #[test]
    fn symlink_over_symlink_is_refused_and_keeps_the_first() {
        let mut t = tree();
        put(&mut t, "real", Node::Dir);
        put(&mut t, "d", sym("real"));
        for node in [sym("other"), Node::OpaqueSymlink] {
            let conflict = t
                .try_insert(Path::new("d"), node)
                .unwrap_err()
                .into_conflict();
            assert_eq!(conflict.error.kind(), io::ErrorKind::AlreadyExists);
            assert_eq!(conflict.occupant, Some(Occupant::Symlink));
        }
        assert_eq!(within(&t, "/dest/d"), PathBuf::from("/dest/real"));
    }

    #[test]
    fn symlink_repeating_the_same_target_is_an_unchanged_duplicate() {
        let mut t = tree();
        put(&mut t, "d", sym("real"));
        put(&mut t, "d", sym("real"));
        assert!(t.try_insert(Path::new("d"), Node::OpaqueSymlink).is_err());
    }

    #[test]
    fn file_over_dir_is_refused_with_is_a_directory() {
        let mut t = tree();
        put(&mut t, "d/f", Node::File);
        let conflict = t
            .try_insert(Path::new("d"), Node::File)
            .unwrap_err()
            .into_conflict();
        assert_eq!(conflict.error.kind(), io::ErrorKind::IsADirectory);
        assert_eq!(conflict.occupant, Some(Occupant::Directory));
    }

    #[test]
    fn file_over_file_is_kept_silently() {
        let mut t = tree();
        put(&mut t, "f", Node::File);
        put(&mut t, "f", Node::File);
        assert_eq!(t.occupant(Path::new("f")), Some(Occupant::File));
    }

    #[test]
    fn occupant_names_what_sits_at_the_path_itself() {
        let mut t = tree();
        put(&mut t, "real/f", Node::File);
        put(&mut t, "alias", sym("real"));
        assert_eq!(t.occupant(Path::new("real")), Some(Occupant::Directory));
        assert_eq!(t.occupant(Path::new("alias")), Some(Occupant::Symlink));
        assert_eq!(t.occupant(Path::new("alias/f")), Some(Occupant::File));
        assert_eq!(t.occupant(Path::new("none")), None);
    }

    #[test]
    fn symlink_replaces_earlier_file() {
        let mut t = tree();
        put(&mut t, "y", Node::File);
        let err = t.insert(Path::new("y"), sym(".")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert!(t.is_symlink(Path::new("/dest/y")).unwrap());
    }

    #[test]
    fn dir_over_file_is_an_error() {
        let mut t = tree();
        put(&mut t, "f", Node::File);
        let err = t.insert(Path::new("f"), Node::Dir).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
    }

    #[test]
    fn insert_under_file_is_an_error() {
        let mut t = tree();
        put(&mut t, "f", Node::File);
        let err = t.insert(Path::new("f/g"), Node::File).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::NotADirectory);
    }

    #[test]
    fn insert_under_chain_leaving_root_is_an_error() {
        let mut t = tree();
        put(&mut t, "out", sym(".."));
        assert!(t.insert(Path::new("out/f"), Node::File).is_err());
        assert!(!t.exists(Path::new("/dest/out/f")));
    }

    #[test]
    fn resolves_to_dir_distinguishes_files_and_directories() {
        let mut t = tree();
        put(&mut t, "d/f", Node::File);
        put(&mut t, "alias", sym("d"));
        assert!(t.resolves_to_dir(Path::new("/dest/d")));
        assert!(t.resolves_to_dir(Path::new("/dest/alias")));
        assert!(!t.resolves_to_dir(Path::new("/dest/d/f")));
    }

    #[test]
    fn overlong_component_is_never_found() {
        let mut t = tree();
        put(&mut t, "d", Node::Dir);
        let long = "a".repeat(1 << 20);
        let err = canon(&t, &format!("/dest/d/{long}")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::NotFound);
    }

    #[test]
    fn name_length_limits() {
        assert!(check_name_lengths(Path::new("a/b")).is_ok());
        let long_name = "a".repeat(255 + 1);
        assert!(check_name_lengths(Path::new(&long_name)).is_err());
        let long_path = path_of_len(HOST_PATH_LIMIT + 1);
        assert!(check_name_lengths(Path::new(&long_path)).is_err());
        assert!(check_name_lengths(Path::new(&path_of_len(HOST_PATH_LIMIT))).is_ok());
    }

    use crate::test_utils::HOST_PATH_LIMIT;
    use crate::test_utils::path_of_len;

    #[test]
    fn link_target_length_boundaries() {
        let symlink_limit = path_of_len(MAX_SYMLINK_TARGET_LEN);
        let symlink_over = path_of_len(MAX_SYMLINK_TARGET_LEN + 1);
        assert!(check_link_target_length(Path::new(&symlink_limit), LinkKind::Symlink).is_ok());
        assert!(check_link_target_length(Path::new(&symlink_over), LinkKind::Symlink).is_err());

        let at_limit = path_of_len(HOST_PATH_LIMIT);
        assert_eq!(at_limit.len(), HOST_PATH_LIMIT);
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        assert!(check_link_target_length(Path::new(&at_limit), LinkKind::Hardlink).is_ok());
        assert!(check_link_target_length(Path::new(&over), LinkKind::Hardlink).is_err());
    }

    #[test]
    fn symlink_target_limits_match_the_host() {
        assert_eq!(
            MAX_SYMLINK_TARGET_LEN,
            if cfg!(windows) { 4091 } else { HOST_PATH_LIMIT }
        );
        assert_eq!(
            MAX_SYMLINK_TARGET_BYTES,
            if cfg!(windows) {
                4091 * 3
            } else {
                HOST_PATH_LIMIT
            }
        );
    }

    /// Finds the longest relative symlink target the host creates and checks
    /// that [`MAX_SYMLINK_TARGET_LEN`] does not exceed it.
    #[cfg(windows)]
    #[test]
    fn symlink_target_limit_is_accepted_by_the_host() {
        use std::os::windows::fs::symlink_file;

        let temp = tempfile::TempDir::new().unwrap();
        let mut counter = 0_u32;
        let mut creates = |len: usize| -> io::Result<bool> {
            counter += 1;
            let link = temp.path().join(format!("l{counter}"));
            let mut target = "abcdefg\\".repeat((len - 1) / 8);
            target.push_str(&"a".repeat(len - target.len()));
            match symlink_file(&target, &link) {
                Ok(()) => Ok(true),
                Err(e) if e.raw_os_error() == Some(1314) => Err(e),
                Err(_) => Ok(false),
            }
        };

        match creates(1) {
            Ok(_) => {}
            Err(e) => {
                assert!(
                    std::env::var_os("CI").is_none(),
                    "symlink creation needs a privilege on CI: {e}"
                );
                eprintln!("skipped: symlink creation is not permitted: {e}");
                return;
            }
        }

        let (mut ok, mut bad) = (1_usize, 32767_usize);
        while bad - ok > 1 {
            let mid = ok + (bad - ok) / 2;
            if creates(mid).unwrap() {
                ok = mid;
            } else {
                bad = mid;
            }
        }
        eprintln!("largest relative symlink target: {ok} UTF-16 units");
        assert!(MAX_SYMLINK_TARGET_LEN <= ok, "host limit is {ok}");
    }

    #[test]
    fn symlink_target_ignores_component_limit() {
        let long_component = "a".repeat(255 + 45);
        let target = Path::new(&long_component);
        assert!(check_link_target_length(target, LinkKind::Symlink).is_ok());
        assert!(check_link_target_length(target, LinkKind::Hardlink).is_err());
        assert!(check_name_lengths(target).is_err());
    }

    #[cfg(any(target_os = "macos", target_os = "windows"))]
    #[test]
    fn keys_are_case_insensitive_on_case_folding_hosts() {
        let mut t = tree();
        put(&mut t, "Dir/File", Node::File);
        assert!(t.exists(Path::new("/dest/dir/file")));
    }

    #[test]
    fn host_fs_probes_the_real_filesystem() {
        let temp = tempfile::TempDir::new().unwrap();
        assert!(HostFs.exists(temp.path()));
        assert!(!HostFs.is_symlink(temp.path()).unwrap());
        let root = DestDir::new(temp.path().to_path_buf()).unwrap();
        assert!(
            HostFs
                .canonicalize(&temp.path().join("nope"), &root)
                .is_err()
        );
    }
}