portable-network-archive 0.32.2

Portable-Network-Archive cli
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
#[cfg(feature = "memmap")]
use crate::command::core::{run_entries, run_entries_stoppable};
use crate::ext::*;
#[cfg(any(unix, windows))]
use crate::utils::fs::lchown;
use crate::{
    cli::{DateTime, FileArgsCompat, MissingTimePolicy, PasswordArgs},
    command::{
        Command, ask_password,
        core::{
            AclStrategy, FflagsStrategy, KeepOptions, MacMetadataStrategy, ModeStrategy,
            OwnerOptions, OwnerStrategy, PathFilter, PathTransformers, PathnameEditor,
            PermissionStrategyResolver, ProcessAction, SafeWriter, TimeFilterResolver, TimeFilters,
            TimestampStrategy, TimestampStrategyResolver, Umask, XattrStrategy, apply_chroot,
            collect_split_archives,
            path_lock::OrderedPathLocks,
            re::{bsd::SubstitutionRule, gnu::TransformRule},
            read_paths, run_process_archive, run_process_archive_stoppable,
        },
    },
    utils::{
        self, BsdGlobMatcher, PathWithCwd, VCS_FILES,
        fmt::DurationDisplay,
        fs::{Group, User},
    },
};
use anyhow::Context;
use clap::{ArgGroup, Parser, ValueHint};
use pna::{DataKind, EntryName, EntryReference, NormalEntry, Permission, ReadOptions, prelude::*};
#[cfg(target_os = "macos")]
use std::os::macos::fs::FileTimesExt;
#[cfg(windows)]
use std::os::windows::fs::FileTimesExt;
use std::{
    borrow::Cow,
    env, fs,
    io::{self, prelude::*},
    path::{Component, Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Instant,
};

#[derive(Parser, Clone, Debug)]
#[command(
    group(
        ArgGroup::new("from-input")
            .args(["files_from", "exclude_from"])
            .multiple(true)
    ),
    group(ArgGroup::new("null-requires").arg("null").requires("from-input")),
    group(ArgGroup::new("keep-timestamp-flag").args(["keep_timestamp", "no_keep_timestamp"])),
    group(ArgGroup::new("keep-permission-flag").args(["keep_permission", "no_keep_permission"])),
    group(ArgGroup::new("keep-xattr-flag").args(["keep_xattr", "no_keep_xattr"])),
    group(ArgGroup::new("keep-acl-flag").args(["keep_acl", "no_keep_acl"])),
    group(ArgGroup::new("path-transform").args(["substitutions", "transforms"])),
    group(ArgGroup::new("owner-flag").args(["same_owner", "no_same_owner"])),
    group(ArgGroup::new("user-flag").args(["numeric_owner", "uname"])),
    group(ArgGroup::new("group-flag").args(["numeric_owner", "gname"])),
    group(ArgGroup::new("ctime-older-than-source").args(["older_ctime", "older_ctime_than"])),
    group(ArgGroup::new("ctime-newer-than-source").args(["newer_ctime", "newer_ctime_than"])),
    group(ArgGroup::new("mtime-older-than-source").args(["older_mtime", "older_mtime_than"])),
    group(ArgGroup::new("mtime-newer-than-source").args(["newer_mtime", "newer_mtime_than"])),
    group(ArgGroup::new("ctime-filter").args(["older_ctime", "older_ctime_than", "newer_ctime", "newer_ctime_than"]).multiple(true)),
    group(ArgGroup::new("mtime-filter").args(["older_mtime", "older_mtime_than", "newer_mtime", "newer_mtime_than"]).multiple(true)),
    group(
        ArgGroup::new("overwrite-flag")
            .args(["overwrite", "no_overwrite", "keep_newer_files", "keep_old_files"])
    ),
    group(ArgGroup::new("safe-writes-flag").args(["safe_writes", "no_safe_writes"])),
    group(ArgGroup::new("unsafe-links-flag").args(["allow_unsafe_links", "no_allow_unsafe_links"])),
)]
pub(crate) struct ExtractCommand {
    #[arg(long, help = "Overwrite file")]
    overwrite: bool,
    #[arg(
        long,
        help = "Do not overwrite files. This is the inverse option of --overwrite"
    )]
    no_overwrite: bool,
    #[arg(
        long,
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Skip extracting files if a newer version already exists"
    )]
    keep_newer_files: bool,
    #[arg(
        long,
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Skip extracting files if they already exist"
    )]
    keep_old_files: bool,
    #[arg(long, value_name = "DIRECTORY", help = "Output directory of extracted files", value_hint = ValueHint::DirPath)]
    out_dir: Option<PathBuf>,
    #[command(flatten)]
    pub(crate) password: PasswordArgs,
    #[arg(
        long,
        visible_alias = "preserve-timestamps",
        help = "Restore the timestamp of the files"
    )]
    pub(crate) keep_timestamp: bool,
    #[arg(
        long,
        visible_alias = "no-preserve-timestamps",
        help = "Do not restore timestamp of files. This is the inverse option of --preserve-timestamps"
    )]
    pub(crate) no_keep_timestamp: bool,
    #[arg(
        long,
        value_name = "DATETIME",
        help = "Overrides the modification time"
    )]
    mtime: Option<DateTime>,
    #[arg(
        long,
        requires = "mtime",
        help = "Clamp the modification time of the entries to the specified time by --mtime"
    )]
    clamp_mtime: bool,
    #[arg(long, value_name = "DATETIME", help = "Overrides the creation time")]
    ctime: Option<DateTime>,
    #[arg(
        long,
        requires = "ctime",
        help = "Clamp the creation time of the entries to the specified time by --ctime"
    )]
    clamp_ctime: bool,
    #[arg(long, value_name = "DATETIME", help = "Overrides the access time")]
    atime: Option<DateTime>,
    #[arg(
        long,
        requires = "atime",
        help = "Clamp the access time of the entries to the specified time by --atime"
    )]
    clamp_atime: bool,
    #[arg(
        long,
        visible_alias = "preserve-permissions",
        help = "Restore the permissions of the files"
    )]
    #[cfg_attr(windows, arg(requires = "unstable", help_heading = "Unstable Options"))]
    keep_permission: bool,
    #[arg(
        long,
        visible_alias = "no-preserve-permissions",
        help = "Do not restore permissions of files. This is the inverse option of --preserve-permissions"
    )]
    #[cfg_attr(windows, arg(requires = "unstable", help_heading = "Unstable Options"))]
    no_keep_permission: bool,
    #[arg(
        long,
        visible_alias = "preserve-xattrs",
        help = "Restore the extended attributes of the files"
    )]
    pub(crate) keep_xattr: bool,
    #[arg(
        long,
        visible_alias = "no-preserve-xattrs",
        help = "Do not restore extended attributes of files. This is the inverse option of --preserve-xattrs"
    )]
    pub(crate) no_keep_xattr: bool,
    #[arg(
        long,
        visible_alias = "preserve-acls",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Restore ACLs"
    )]
    keep_acl: bool,
    #[arg(
        long,
        visible_alias = "no-preserve-acls",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Do not restore ACLs. This is the inverse option of --keep-acl"
    )]
    no_keep_acl: bool,
    #[arg(long, value_name = "NAME", help = "Restore user from given name")]
    uname: Option<String>,
    #[arg(long, value_name = "NAME", help = "Restore group from given name")]
    gname: Option<String>,
    #[arg(
        long,
        value_name = "ID",
        help = "Overrides the user id in the archive; the user name in the archive will be ignored"
    )]
    uid: Option<u32>,
    #[arg(
        long,
        value_name = "ID",
        help = "Overrides the group id in the archive; the group name in the archive will be ignored"
    )]
    gid: Option<u32>,
    #[arg(
        long,
        help = "This is equivalent to --uname \"\" --gname \"\". It causes user and group names in the archive to be ignored in favor of the numeric user and group ids."
    )]
    numeric_owner: bool,
    #[arg(
        long,
        value_name = "DATETIME",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Only include files and directories older than the specified date. This compares ctime entries."
    )]
    older_ctime: Option<DateTime>,
    #[arg(
        long,
        value_name = "DATETIME",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Only include files and directories older than the specified date. This compares mtime entries."
    )]
    older_mtime: Option<DateTime>,
    #[arg(
        long,
        value_name = "DATETIME",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Only include files and directories newer than the specified date. This compares ctime entries."
    )]
    newer_ctime: Option<DateTime>,
    #[arg(
        long,
        value_name = "DATETIME",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Only include files and directories newer than the specified date. This compares mtime entries."
    )]
    newer_mtime: Option<DateTime>,
    #[arg(
        long,
        value_name = "file",
        requires = "unstable",
        visible_alias = "newer-than",
        help_heading = "Unstable Options",
        help = "Only include files and directories newer than the specified file. This compares ctime entries."
    )]
    newer_ctime_than: Option<PathBuf>,
    #[arg(
        long,
        value_name = "file",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Only include files and directories newer than the specified file. This compares mtime entries."
    )]
    newer_mtime_than: Option<PathBuf>,
    #[arg(
        long,
        value_name = "file",
        requires = "unstable",
        visible_alias = "older-than",
        help_heading = "Unstable Options",
        help = "Only include files and directories older than the specified file. This compares ctime entries."
    )]
    older_ctime_than: Option<PathBuf>,
    #[arg(
        long,
        value_name = "file",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Only include files and directories older than the specified file. This compares mtime entries."
    )]
    older_mtime_than: Option<PathBuf>,
    #[arg(
        long,
        requires_all = ["unstable", "ctime-filter"],
        help = "Behavior for entries without ctime when time filtering (unstable). Values: include, exclude, now, epoch, or a datetime. [default: include]"
    )]
    missing_ctime: Option<MissingTimePolicy>,
    #[arg(
        long,
        requires_all = ["unstable", "mtime-filter"],
        help = "Behavior for entries without mtime when time filtering (unstable). Values: include, exclude, now, epoch, or a datetime. [default: include]"
    )]
    missing_mtime: Option<MissingTimePolicy>,
    #[arg(
        long,
        value_name = "PATTERN",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Process only files or directories that match the specified pattern. Note that exclusions specified with --exclude take precedence over inclusions"
    )]
    include: Vec<String>,
    #[arg(
        long,
        value_name = "PATTERN",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Exclude path glob",
        value_hint = ValueHint::AnyPath
    )]
    exclude: Vec<String>,
    #[arg(
        long,
        value_name = "FILE",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Read exclude files from given path",
        value_hint = ValueHint::FilePath
    )]
    exclude_from: Option<PathBuf>,
    #[arg(
        long,
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Exclude files or directories internally used by version control systems (`Arch`, `Bazaar`, `CVS`, `Darcs`, `Mercurial`, `RCS`, `SCCS`, `SVN`, `git`)"
    )]
    exclude_vcs: bool,
    #[arg(
        long,
        value_name = "FILE",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Read extraction patterns from given path",
        value_hint = ValueHint::FilePath
    )]
    files_from: Option<PathBuf>,
    #[arg(
        long,
        help = "Filenames or patterns are separated by null characters, not by newlines"
    )]
    null: bool,
    #[arg(
        long,
        value_name = "N",
        help = "Remove the specified number of leading path elements. Path names with fewer elements will be silently skipped"
    )]
    strip_components: Option<usize>,
    #[arg(
        short = 's',
        value_name = "PATTERN",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Modify file or archive member names according to pattern that like BSD tar -s option"
    )]
    substitutions: Option<Vec<SubstitutionRule>>,
    #[arg(
        long = "transform",
        visible_alias = "xform",
        value_name = "PATTERN",
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Modify file or archive member names according to pattern that like GNU tar -transform option"
    )]
    transforms: Option<Vec<TransformRule>>,
    #[arg(
        long,
        help = "Try extracting files with the same ownership as exists in the archive"
    )]
    same_owner: bool,
    #[arg(long, help = "Extract files as yourself")]
    no_same_owner: bool,
    #[arg(
        short = 'C',
        long = "cd",
        visible_aliases = ["directory"],
        value_name = "DIRECTORY",
        help = "Change directories after opening the archive but before extracting entries from the archive",
        value_hint = ValueHint::DirPath
    )]
    working_dir: Option<PathBuf>,
    #[arg(
        long,
        help = "chroot() to the current directory after processing any --cd options and before extracting any files (requires root privileges)"
    )]
    chroot: bool,
    #[arg(
        long,
        help = "Allow extracting symbolic links and hard links that contain root or parent paths"
    )]
    allow_unsafe_links: bool,
    #[arg(
        long,
        help = "Do not allow extracting symbolic links and hard links that contain root or parent paths (default)"
    )]
    no_allow_unsafe_links: bool,
    #[arg(
        long,
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Extract files atomically via temp file and rename"
    )]
    safe_writes: bool,
    #[arg(
        long,
        requires = "unstable",
        help_heading = "Unstable Options",
        help = "Disable atomic extraction. This is the inverse option of --safe-writes"
    )]
    no_safe_writes: bool,
    #[command(flatten)]
    pub(crate) file: FileArgsCompat,
}

impl Command for ExtractCommand {
    #[inline]
    fn execute(self, _ctx: &crate::cli::GlobalContext) -> anyhow::Result<()> {
        extract_archive(self)
    }
}
#[hooq::hooq(anyhow)]
fn extract_archive(args: ExtractCommand) -> anyhow::Result<()> {
    let password = ask_password(args.password).with_context(|| "reading password")?;
    let start = Instant::now();
    let archive = args.file.archive();
    log::info!("Extract archive {}", PathWithCwd::new(&archive));

    let archives = collect_split_archives(&archive)
        .with_context(|| format!("opening archive '{}'", PathWithCwd::new(&archive)))?;

    let mut exclude = args.exclude;
    if let Some(p) = args.exclude_from {
        exclude.extend(
            read_paths(&p, args.null).with_context(|| {
                format!("reading exclude patterns from {}", PathWithCwd::new(&p))
            })?,
        );
    }
    let vcs_patterns = args
        .exclude_vcs
        .then(|| VCS_FILES.iter().copied())
        .into_iter()
        .flatten();
    let filter = PathFilter::new(
        args.include.iter().map(|s| s.as_str()),
        exclude.iter().map(|s| s.as_str()).chain(vcs_patterns),
    );

    let mut files = args.file.files();
    if let Some(path) = &args.files_from {
        files.extend(
            read_paths(path, args.null)
                .with_context(|| format!("reading file list from {}", PathWithCwd::new(path)))?,
        );
    }

    let time_filters = TimeFilterResolver {
        newer_ctime_than: args.newer_ctime_than.as_deref(),
        older_ctime_than: args.older_ctime_than.as_deref(),
        newer_ctime: args.newer_ctime.map(|it| it.to_system_time()),
        older_ctime: args.older_ctime.map(|it| it.to_system_time()),
        newer_mtime_than: args.newer_mtime_than.as_deref(),
        older_mtime_than: args.older_mtime_than.as_deref(),
        newer_mtime: args.newer_mtime.map(|it| it.to_system_time()),
        older_mtime: args.older_mtime.map(|it| it.to_system_time()),
        missing_ctime: args.missing_ctime.unwrap_or(MissingTimePolicy::Include),
        missing_mtime: args.missing_mtime.unwrap_or(MissingTimePolicy::Include),
    }
    .resolve()?;
    let overwrite_strategy = OverwriteStrategy::from_flags(
        args.overwrite,
        args.no_overwrite,
        args.keep_newer_files,
        args.keep_old_files,
        OverwriteStrategy::Never,
    );
    let (mode_strategy, owner_strategy) = PermissionStrategyResolver {
        keep_permission: args.keep_permission,
        no_keep_permission: args.no_keep_permission,
        same_owner: !args.no_same_owner,
        uname: args.uname,
        gname: args.gname,
        uid: args.uid,
        gid: args.gid,
        numeric_owner: args.numeric_owner,
    }
    .resolve();
    let keep_options = KeepOptions {
        timestamp_strategy: TimestampStrategyResolver {
            keep_timestamp: args.keep_timestamp,
            no_keep_timestamp: args.no_keep_timestamp,
            default_preserve: false,
            mtime: args.mtime.map(|it| it.to_system_time()),
            clamp_mtime: args.clamp_mtime,
            ctime: args.ctime.map(|it| it.to_system_time()),
            clamp_ctime: args.clamp_ctime,
            atime: args.atime.map(|it| it.to_system_time()),
            clamp_atime: args.clamp_atime,
        }
        .resolve(),
        mode_strategy,
        owner_strategy,
        xattr_strategy: XattrStrategy::from_flags(args.keep_xattr, args.no_keep_xattr, false),
        acl_strategy: AclStrategy::from_flags(args.keep_acl, args.no_keep_acl),
        fflags_strategy: FflagsStrategy::Never,
        mac_metadata_strategy: MacMetadataStrategy::Never,
    };
    let output_options = OutputOption {
        overwrite_strategy,
        allow_unsafe_links: args.allow_unsafe_links,
        out_dir: args.out_dir,
        to_stdout: false,
        filter,
        keep_options,
        pathname_editor: PathnameEditor::new(
            args.strip_components,
            PathTransformers::new(args.substitutions, args.transforms),
            false,
            false,
        ),
        ordered_path_locks: Arc::new(OrderedPathLocks::default()),
        unlink_first: false,
        time_filters,
        safe_writes: args.safe_writes && !args.no_safe_writes,
        verbose: false,
        absolute_paths: false,
        warned_lead_slash: Arc::new(AtomicBool::new(false)),
    };
    if let Some(working_dir) = args.working_dir {
        env::set_current_dir(&working_dir)
            .with_context(|| format!("changing directory to {}", PathWithCwd::new(&working_dir)))?;
    }
    apply_chroot(args.chroot)?;
    #[cfg(not(feature = "memmap"))]
    run_extract_archive_reader(
        archives
            .into_iter()
            .map(|it| io::BufReader::with_capacity(64 * 1024, it)),
        files,
        || password.as_deref(),
        output_options,
        true,
        false,
        false,
    )
    .with_context(|| format!("extracting entries from '{}'", PathWithCwd::new(&archive)))?;

    #[cfg(feature = "memmap")]
    let mmaps = archives
        .into_iter()
        .map(utils::mmap::Mmap::try_from)
        .collect::<io::Result<Vec<_>>>()
        .with_context(|| format!("memory-mapping archive '{}'", PathWithCwd::new(&archive)))?;
    #[cfg(feature = "memmap")]
    let archives = mmaps.iter().map(|m| m.as_ref());

    #[cfg(feature = "memmap")]
    run_extract_archive(
        archives,
        files,
        || password.as_deref(),
        output_options,
        true,
        false,
    )
    .with_context(|| format!("extracting entries from '{}'", PathWithCwd::new(&archive)))?;
    log::info!(
        "Successfully extracted an archive in {}",
        DurationDisplay(start.elapsed())
    );
    Ok(())
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OverwriteStrategy {
    Never,
    Always,
    KeepNewer,
    KeepOlder,
}

impl OverwriteStrategy {
    pub(crate) const fn from_flags(
        overwrite: bool,
        no_overwrite: bool,
        keep_newer: bool,
        keep_older: bool,
        default_strategy: Self,
    ) -> Self {
        if overwrite {
            Self::Always
        } else if no_overwrite {
            Self::Never
        } else if keep_newer {
            Self::KeepNewer
        } else if keep_older {
            Self::KeepOlder
        } else {
            default_strategy
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct OutputOption<'a> {
    pub(crate) overwrite_strategy: OverwriteStrategy,
    pub(crate) allow_unsafe_links: bool,
    pub(crate) out_dir: Option<PathBuf>,
    pub(crate) to_stdout: bool,
    pub(crate) filter: PathFilter<'a>,
    pub(crate) keep_options: KeepOptions,
    pub(crate) pathname_editor: PathnameEditor,
    pub(crate) ordered_path_locks: Arc<OrderedPathLocks>,
    pub(crate) unlink_first: bool,
    pub(crate) time_filters: TimeFilters,
    pub(crate) safe_writes: bool,
    pub(crate) verbose: bool,
    pub(crate) absolute_paths: bool,
    pub(crate) warned_lead_slash: Arc<AtomicBool>,
}

pub(crate) fn run_extract_archive_reader<'a, 'p, Provider>(
    reader: impl IntoIterator<Item = impl Read> + Send,
    files: Vec<String>,
    mut password_provider: Provider,
    args: OutputOption<'a>,
    no_recursive: bool,
    fast_read: bool,
    allow_concatenated_archives: bool,
) -> anyhow::Result<()>
where
    Provider: FnMut() -> Option<&'p [u8]> + Send,
{
    let password = password_provider();
    let patterns = files;
    let mut globs =
        BsdGlobMatcher::new(patterns.iter().map(|it| it.as_str())).with_no_recursive(no_recursive);

    let mut link_entries = Vec::new();

    #[cfg(not(target_family = "wasm"))]
    {
        let (tx, rx) = std::sync::mpsc::channel();
        rayon::scope_fifo(|s| -> anyhow::Result<()> {
            if fast_read && !globs.is_empty() {
                run_process_archive_stoppable(
                    reader,
                    password_provider,
                    |entry| {
                        let item = entry.map_err(|e| {
                            io::Error::new(e.kind(), format!("reading archive entry: {e}"))
                        })?;
                        let item_path = item.name().to_string();
                        let name =
                            match filter_entry_fast_read(&item, &item_path, &mut globs, &args) {
                                FastReadFilterAction::Skip(action) => return Ok(action),
                                FastReadFilterAction::Accept(name) => name,
                            };
                        if args.verbose {
                            eprintln!("x {}", name);
                        }
                        if args.to_stdout {
                            extract_entry_to_stdout(&item, password)?;
                            if globs.all_matched() {
                                return Ok(ProcessAction::Stop);
                            }
                            return Ok(ProcessAction::Continue);
                        }
                        if matches!(
                            item.header().data_kind(),
                            DataKind::SymbolicLink | DataKind::HardLink
                        ) {
                            link_entries.push((name, item));
                            if globs.all_matched() {
                                return Ok(ProcessAction::Stop);
                            }
                            return Ok(ProcessAction::Continue);
                        }
                        if item.header().data_kind() == DataKind::Directory {
                            extract_entry(item, &name, password, &args).map_err(|e| {
                                io::Error::new(e.kind(), format!("extracting {item_path}: {e}"))
                            })?;
                            if globs.all_matched() {
                                return Ok(ProcessAction::Stop);
                            }
                            return Ok(ProcessAction::Continue);
                        }
                        let path = build_output_path(args.out_dir.as_deref(), name.as_path());
                        let ticket = args.ordered_path_locks.register(&path);
                        let tx = tx.clone();
                        let args = args.clone();
                        let all_matched = globs.all_matched();
                        s.spawn_fifo(move |_| {
                            let _guard = ticket.wait_for_turn();
                            tx.send(
                                extract_entry(item, &name, password, &args)
                                    .with_context(|| format!("extracting {}", item_path)),
                            )
                            .unwrap_or_else(|_| unreachable!("receiver is held by scope owner"));
                        });
                        if all_matched {
                            return Ok(ProcessAction::Stop);
                        }
                        Ok(ProcessAction::Continue)
                    },
                    allow_concatenated_archives,
                )
                .with_context(|| "streaming archive entries")?;
            } else {
                run_process_archive(
                    reader,
                    password_provider,
                    |entry| {
                        let item = entry.map_err(|e| {
                            io::Error::new(e.kind(), format!("reading archive entry: {e}"))
                        })?;
                        let Some(name) = filter_entry(&item, &mut globs, &args) else {
                            return Ok(());
                        };
                        if args.verbose {
                            eprintln!("x {}", name);
                        }
                        if args.to_stdout {
                            return extract_entry_to_stdout(&item, password);
                        }
                        if matches!(
                            item.header().data_kind(),
                            DataKind::SymbolicLink | DataKind::HardLink
                        ) {
                            link_entries.push((name, item));
                            return Ok(());
                        }
                        if item.header().data_kind() == DataKind::Directory {
                            let item_path = item.name().to_string();
                            extract_entry(item, &name, password, &args).map_err(|e| {
                                io::Error::new(e.kind(), format!("extracting {item_path}: {e}"))
                            })?;
                            return Ok(());
                        }
                        let path = build_output_path(args.out_dir.as_deref(), name.as_path());
                        let ticket = args.ordered_path_locks.register(&path);
                        let item_path = item.name().to_string();
                        let tx = tx.clone();
                        let args = args.clone();
                        s.spawn_fifo(move |_| {
                            let _guard = ticket.wait_for_turn();
                            tx.send(
                                extract_entry(item, &name, password, &args)
                                    .with_context(|| format!("extracting {}", item_path)),
                            )
                            .unwrap_or_else(|_| unreachable!("receiver is held by scope owner"));
                        });
                        Ok(())
                    },
                    allow_concatenated_archives,
                )
                .with_context(|| "streaming archive entries")?;
            }
            drop(tx);
            Ok(())
        })?;
        for result in rx {
            result?;
        }
    }

    #[cfg(target_family = "wasm")]
    {
        if fast_read && !globs.is_empty() {
            run_process_archive_stoppable(
                reader,
                password_provider,
                |entry| {
                    let item = entry.map_err(|e| {
                        io::Error::new(e.kind(), format!("reading archive entry: {e}"))
                    })?;
                    let item_path = item.name().to_string();
                    let name = match filter_entry_fast_read(&item, &item_path, &mut globs, &args) {
                        FastReadFilterAction::Skip(action) => return Ok(action),
                        FastReadFilterAction::Accept(name) => name,
                    };
                    if args.verbose {
                        eprintln!("x {}", name);
                    }
                    if args.to_stdout {
                        extract_entry_to_stdout(&item, password)?;
                        if globs.all_matched() {
                            return Ok(ProcessAction::Stop);
                        }
                        return Ok(ProcessAction::Continue);
                    }
                    if matches!(
                        item.header().data_kind(),
                        DataKind::SymbolicLink | DataKind::HardLink
                    ) {
                        link_entries.push((name, item));
                        if globs.all_matched() {
                            return Ok(ProcessAction::Stop);
                        }
                        return Ok(ProcessAction::Continue);
                    }
                    extract_entry(item, &name, password, &args).map_err(|e| {
                        io::Error::new(e.kind(), format!("extracting {}: {e}", item_path))
                    })?;
                    if globs.all_matched() {
                        return Ok(ProcessAction::Stop);
                    }
                    Ok(ProcessAction::Continue)
                },
                allow_concatenated_archives,
            )
            .with_context(|| "streaming archive entries")?;
        } else {
            run_process_archive(
                reader,
                password_provider,
                |entry| {
                    let item = entry.map_err(|e| {
                        io::Error::new(e.kind(), format!("reading archive entry: {e}"))
                    })?;
                    let Some(name) = filter_entry(&item, &mut globs, &args) else {
                        return Ok(());
                    };
                    if args.verbose {
                        eprintln!("x {}", name);
                    }
                    if args.to_stdout {
                        return extract_entry_to_stdout(&item, password);
                    }
                    if matches!(
                        item.header().data_kind(),
                        DataKind::SymbolicLink | DataKind::HardLink
                    ) {
                        link_entries.push((name, item));
                        return Ok(());
                    }
                    extract_entry(item, &name, password, &args).map_err(|e| {
                        io::Error::new(e.kind(), format!("extracting {}: {e}", name))
                    })?;
                    Ok(())
                },
                allow_concatenated_archives,
            )
            .with_context(|| "streaming archive entries")?;
        }
    }

    for (name, item) in link_entries {
        extract_entry(item, &name, password, &args)
            .with_context(|| format!("extracting deferred link {name}"))?;
    }

    globs.ensure_all_matched()?;
    Ok(())
}

#[cfg(feature = "memmap")]
#[hooq::hooq(anyhow)]
pub(crate) fn run_extract_archive<'a, 'd, 'p, Provider>(
    archives: impl IntoIterator<Item = &'d [u8]> + Send,
    files: Vec<String>,
    mut password_provider: Provider,
    args: OutputOption<'a>,
    no_recursive: bool,
    fast_read: bool,
) -> anyhow::Result<()>
where
    Provider: FnMut() -> Option<&'p [u8]> + Send,
{
    let password = password_provider();
    let mut globs =
        BsdGlobMatcher::new(files.iter().map(|it| it.as_str())).with_no_recursive(no_recursive);

    let mut link_entries: Vec<(EntryName, NormalEntry<Vec<u8>>)> = Vec::new();

    let (tx, rx) = std::sync::mpsc::channel();

    rayon::scope_fifo(|s| -> anyhow::Result<()> {
        if fast_read && !globs.is_empty() {
            #[hooq::skip_all]
            run_entries_stoppable(archives, password_provider, |entry| {
                let item = entry
                    .map_err(|e| io::Error::new(e.kind(), format!("reading archive entry: {e}")))?;
                let item_path = item.name().to_string();
                let name = match filter_entry_fast_read(&item, &item_path, &mut globs, &args) {
                    FastReadFilterAction::Skip(action) => return Ok(action),
                    FastReadFilterAction::Accept(name) => name,
                };
                if args.verbose {
                    eprintln!("x {}", name);
                }
                if args.to_stdout {
                    extract_entry_to_stdout(&item, password)?;
                    if globs.all_matched() {
                        return Ok(ProcessAction::Stop);
                    }
                    return Ok(ProcessAction::Continue);
                }
                if matches!(
                    item.header().data_kind(),
                    DataKind::SymbolicLink | DataKind::HardLink
                ) {
                    link_entries.push((name, item.into()));
                    if globs.all_matched() {
                        return Ok(ProcessAction::Stop);
                    }
                    return Ok(ProcessAction::Continue);
                }
                if item.header().data_kind() == DataKind::Directory {
                    extract_entry(item, &name, password, &args).map_err(|e| {
                        io::Error::new(e.kind(), format!("extracting {item_path}: {e}"))
                    })?;
                    if globs.all_matched() {
                        return Ok(ProcessAction::Stop);
                    }
                    return Ok(ProcessAction::Continue);
                }
                let path = build_output_path(args.out_dir.as_deref(), name.as_path());
                let ticket = args.ordered_path_locks.register(&path);
                let tx = tx.clone();
                let args = args.clone();
                let all_matched = globs.all_matched();
                s.spawn_fifo(move |_| {
                    let _guard = ticket.wait_for_turn();
                    tx.send(
                        extract_entry(item, &name, password, &args)
                            .with_context(|| format!("extracting {}", item_path)),
                    )
                    .unwrap_or_else(|_| unreachable!("receiver is held by scope owner"));
                });
                if all_matched {
                    return Ok(ProcessAction::Stop);
                }
                Ok(ProcessAction::Continue)
            })
            .with_context(|| "streaming archive entries")?;
        } else {
            #[hooq::skip_all]
            run_entries(archives, password_provider, |entry| {
                let item = entry
                    .map_err(|e| io::Error::new(e.kind(), format!("reading archive entry: {e}")))?;
                let Some(name) = filter_entry(&item, &mut globs, &args) else {
                    return Ok(());
                };
                if args.verbose {
                    eprintln!("x {}", name);
                }
                if args.to_stdout {
                    return extract_entry_to_stdout(&item, password);
                }
                if matches!(
                    item.header().data_kind(),
                    DataKind::SymbolicLink | DataKind::HardLink
                ) {
                    link_entries.push((name, item.into()));
                    return Ok(());
                }
                if item.header().data_kind() == DataKind::Directory {
                    let item_path = item.name().to_string();
                    extract_entry(item, &name, password, &args).map_err(|e| {
                        io::Error::new(e.kind(), format!("extracting {item_path}: {e}"))
                    })?;
                    return Ok(());
                }
                let path = build_output_path(args.out_dir.as_deref(), name.as_path());
                let ticket = args.ordered_path_locks.register(&path);
                let item_path = item.name().to_string();
                let tx = tx.clone();
                let args = args.clone();
                s.spawn_fifo(move |_| {
                    let _guard = ticket.wait_for_turn();
                    tx.send(
                        extract_entry(item, &name, password, &args)
                            .with_context(|| format!("extracting {}", item_path)),
                    )
                    .unwrap_or_else(|_| unreachable!("receiver is held by scope owner"));
                });
                Ok(())
            })
            .with_context(|| "streaming archive entries")?;
        }
        drop(tx);
        Ok(())
    })?;
    for result in rx {
        result?;
    }

    for (name, item) in link_entries {
        extract_entry(item, &name, password, &args)
            .with_context(|| format!("extracting deferred link {name}"))?;
    }
    globs.ensure_all_matched()?;
    Ok(())
}

#[inline]
fn entry_matches_time_filters<T>(item: &NormalEntry<T>, filters: &TimeFilters) -> bool
where
    T: AsRef<[u8]>,
    pna::RawChunk<T>: Chunk,
{
    let metadata = item.metadata();
    filters.matches_or_inactive(metadata.created_time(), metadata.modified_time())
}

fn filter_entry<T: AsRef<[u8]>>(
    item: &NormalEntry<T>,
    globs: &mut BsdGlobMatcher<'_>,
    args: &OutputOption<'_>,
) -> Option<EntryName>
where
    pna::RawChunk<T>: Chunk,
{
    let item_name = item.name();
    if !globs.is_empty() && !globs.matches(item_name) {
        log::debug!("Skip: {item_name}");
        return None;
    }
    if args.filter.excluded(item_name) {
        log::debug!("Skip: {item_name}");
        return None;
    }
    if !entry_matches_time_filters(item, &args.time_filters) {
        log::debug!("Skip: {item_name}");
        return None;
    }
    let name = args.pathname_editor.edit_entry_name(item_name.as_path());
    if name.is_none() {
        log::debug!("Skip: {item_name}");
    }
    name
}

enum FastReadFilterAction {
    Accept(EntryName),
    Skip(ProcessAction),
}

fn filter_entry_fast_read<T: AsRef<[u8]>>(
    item: &NormalEntry<T>,
    item_path: &str,
    globs: &mut BsdGlobMatcher<'_>,
    args: &OutputOption<'_>,
) -> FastReadFilterAction
where
    pna::RawChunk<T>: Chunk,
{
    if !globs.matches_any_pattern(item_path) {
        log::debug!("Skip: {item_path}");
        return FastReadFilterAction::Skip(ProcessAction::Continue);
    }
    if args.filter.excluded(item.name()) {
        log::debug!("Skip: {item_path}");
        return FastReadFilterAction::Skip(ProcessAction::Continue);
    }
    if !entry_matches_time_filters(item, &args.time_filters) {
        log::debug!("Skip: {item_path}");
        return if globs.all_matched() {
            FastReadFilterAction::Skip(ProcessAction::Stop)
        } else {
            FastReadFilterAction::Skip(ProcessAction::Continue)
        };
    }
    let Some(name) = args.pathname_editor.edit_entry_name(item.name().as_path()) else {
        log::debug!("Skip: {item_path}");
        return FastReadFilterAction::Skip(ProcessAction::Continue);
    };
    globs.mark_satisfied(item_path);
    FastReadFilterAction::Accept(name)
}

/// Result of checking whether extraction should proceed for a given path.
#[derive(Debug, Clone, Copy)]
enum ExtractionDecision {
    /// Proceed with extraction; `remove_existing` indicates if existing file should be removed first
    Proceed { remove_existing: bool },
    /// Skip extraction (e.g., keep-newer/keep-older strategies)
    Skip,
}

/// Checks overwrite strategy and prepares the target path for extraction.
///
/// This function:
/// 1. Checks if a file/directory already exists at the target path
/// 2. Applies the overwrite strategy to decide whether to proceed
/// 3. Prepares parent directories
/// 4. Handles conflicts between entry types (e.g., file vs directory)
///
/// Returns `ExtractionDecision::Skip` if extraction should be skipped,
/// or `ExtractionDecision::Proceed` with information about whether to remove existing files.
fn check_and_prepare_target<T>(
    path: &Path,
    entry_kind: DataKind,
    item: &NormalEntry<T>,
    overwrite_strategy: OverwriteStrategy,
    unlink_first: bool,
    secure_symlinks: bool,
) -> io::Result<ExtractionDecision>
where
    T: AsRef<[u8]>,
{
    let metadata = match fs::symlink_metadata(path) {
        Ok(meta) => Some(meta),
        Err(err) if err.kind() == io::ErrorKind::NotFound => None,
        Err(err) if err.kind() == io::ErrorKind::NotADirectory => None,
        Err(err) => return Err(err),
    };

    // Check overwrite strategy
    if let Some(existing) = &metadata {
        match overwrite_strategy {
            OverwriteStrategy::Never if !unlink_first => {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!("{} already exists", path.display()),
                ));
            }
            OverwriteStrategy::KeepOlder if !unlink_first => {
                log::debug!(
                    "Skipped extracting {}: existing one kept by --keep-older",
                    path.display()
                );
                return Ok(ExtractionDecision::Skip);
            }
            OverwriteStrategy::KeepNewer if !unlink_first => {
                if is_existing_newer(existing, item) {
                    log::debug!(
                        "Skipped extracting {}: newer one already exists (--keep-newer)",
                        path.display()
                    );
                    return Ok(ExtractionDecision::Skip);
                }
            }
            _ => (),
        }
    }

    // Determine what cleanup is needed
    let (had_existing, existing_is_dir) = metadata
        .as_ref()
        .map(|meta| {
            // When -P is active and the existing item is a symlink, follow it to check
            // if the target is a directory (matches bsdtar's stat()-based check).
            let is_dir = if !secure_symlinks && meta.is_symlink() {
                fs::metadata(path).is_ok_and(|m| m.is_dir())
            } else {
                meta.is_dir()
            };
            (true, is_dir)
        })
        .unwrap_or((false, false));
    let unlink_existing =
        unlink_first && had_existing && (entry_kind != DataKind::Directory || !existing_is_dir);
    let should_overwrite_existing = matches!(
        overwrite_strategy,
        OverwriteStrategy::Always | OverwriteStrategy::KeepNewer
    ) && had_existing;

    // Remove existing if unlink_first mode
    if unlink_existing {
        utils::io::ignore_not_found(utils::fs::remove_path(path))?;
    }

    // Create parent directories
    if let Some(parent) = path.parent() {
        ensure_directory_components(parent, unlink_first, secure_symlinks)?;
    }

    // Handle type conflicts (symlink blocking file, file blocking directory)
    if let Some(meta) = metadata
        && (meta.is_symlink() || (meta.is_file() && entry_kind == DataKind::Directory))
    {
        let follow_symlink = !secure_symlinks
            && meta.is_symlink()
            && entry_kind == DataKind::Directory
            && path.metadata().is_ok_and(|m| m.is_dir());
        if !follow_symlink {
            match utils::fs::remove_path(path) {
                Ok(()) => {}
                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                // Concurrent extraction already replaced with directory
                Err(e) if e.kind() == io::ErrorKind::IsADirectory => {}
                Err(e) => return Err(e),
            }
        }
    }

    let remove_existing = should_overwrite_existing && !unlink_existing;
    Ok(ExtractionDecision::Proceed { remove_existing })
}

/// Caller must hold a [`PathOrderGuard`](super::core::path_lock::PathOrderGuard)
/// for the entry's output path to guarantee archive-order writes.
pub(crate) fn extract_entry<'a, T>(
    item: NormalEntry<T>,
    item_path: &EntryName,
    password: Option<&'a [u8]>,
    OutputOption {
        overwrite_strategy,
        allow_unsafe_links,
        out_dir,
        to_stdout: _,
        filter: _,
        keep_options,
        pathname_editor,
        ordered_path_locks: _,
        unlink_first,
        time_filters: _,
        safe_writes,
        verbose: _,
        absolute_paths,
        warned_lead_slash,
    }: &OutputOption<'a>,
) -> io::Result<()>
where
    T: AsRef<[u8]>,
    pna::RawChunk<T>: Chunk,
{
    log::debug!("Extract: {}", item.name());
    let path = build_output_path(out_dir.as_deref(), item_path.as_path());

    let entry_kind = item.header().data_kind();

    log::debug!("start: {}", path.display());

    let secure_symlinks = !absolute_paths;
    // Check overwrite strategy and prepare target
    let ExtractionDecision::Proceed { remove_existing } = check_and_prepare_target(
        &path,
        entry_kind,
        &item,
        *overwrite_strategy,
        *unlink_first,
        secure_symlinks,
    )?
    else {
        return Ok(());
    };

    match entry_kind {
        DataKind::File => {
            if *safe_writes {
                let mut safe_writer = SafeWriter::new(&path)?;
                {
                    let mut writer =
                        io::BufWriter::with_capacity(64 * 1024, safe_writer.as_file_mut());
                    let mut reader = item.reader(ReadOptions::with_password(password))?;
                    io::copy(&mut reader, &mut writer)?;
                    writer.flush()?;
                }
                restore_timestamps(safe_writer.as_file_mut(), item.metadata(), keep_options)?;
                safe_writer.persist()?;
            } else {
                if remove_existing {
                    utils::io::ignore_not_found(utils::fs::remove_path(&path))?;
                }
                let file = utils::fs::file_create(&path, remove_existing)?;
                let mut writer = io::BufWriter::with_capacity(64 * 1024, file);
                let mut reader = item.reader(ReadOptions::with_password(password))?;
                io::copy(&mut reader, &mut writer)?;
                let mut file = writer.into_inner().map_err(|e| e.into_error())?;
                restore_timestamps(&mut file, item.metadata(), keep_options)?;
            }
        }
        DataKind::Directory => {
            ensure_directory_components(&path, *unlink_first, secure_symlinks)?;
        }
        DataKind::SymbolicLink => {
            let reader = item.reader(ReadOptions::with_password(password))?;
            let original = io::read_to_string(reader)?;
            let original = pathname_editor.edit_symlink(original.as_ref());
            if !allow_unsafe_links && is_unsafe_link(&original) {
                log::warn!(
                    "Skipped extracting a symbolic link that contains an unsafe link. If you need to extract it, use `--allow-unsafe-links`."
                );
                return Ok(());
            }
            // Symlinks/hardlinks cannot be atomically replaced; remove existing path first
            if *safe_writes || remove_existing {
                utils::io::ignore_not_found(utils::fs::remove_path(&path))?;
            }
            utils::fs::symlink(original, &path)?;
        }
        DataKind::HardLink => {
            let reader = item.reader(ReadOptions::with_password(password))?;
            let original = io::read_to_string(reader)?;
            let Some((original, had_root)) = pathname_editor.edit_hardlink(original.as_ref())
            else {
                log::warn!(
                    "Skipped extracting a hard link that pointed at a file which was skipped.: {}",
                    original
                );
                return Ok(());
            };
            if had_root && !warned_lead_slash.swap(true, Ordering::Relaxed) {
                eprintln!("bsdtar: Removing leading '/' from member names");
            }
            if !allow_unsafe_links && is_unsafe_link(&original) {
                log::warn!(
                    "Skipped extracting a hard link that contains an unsafe link. If you need to extract it, use `--allow-unsafe-links`."
                );
                return Ok(());
            }
            let original = if let Some(out_dir) = out_dir {
                Cow::from(out_dir.join(original))
            } else {
                Cow::from(original.as_path())
            };
            // Symlinks/hardlinks cannot be atomically replaced; remove existing path first
            if *safe_writes || remove_existing {
                utils::io::ignore_not_found(utils::fs::remove_path(&path))?;
            }
            fs::hard_link(original, &path)?;
        }
    }
    restore_metadata(&item, &path, keep_options)?;
    log::debug!("end: {}", path.display());
    Ok(())
}

#[inline]
fn build_output_path<'a>(out_dir: Option<&'a Path>, item_path: &'a Path) -> Cow<'a, Path> {
    let path = if let Some(out_dir) = out_dir {
        Cow::from(out_dir.join(item_path))
    } else {
        Cow::Borrowed(item_path)
    };
    if path.as_os_str().is_empty() {
        Cow::Borrowed(".".as_ref())
    } else {
        path
    }
}

/// Applies preserved timestamps from archive metadata to an open output file when timestamp preservation is enabled.
///
/// When the configured timestamp strategy is enabled, sets the file's accessed and modified times (and on supported platforms, created time)
/// from the provided archive `metadata`. Timestamps may be overridden or clamped according to the strategy's configuration.
/// No changes are made when timestamp strategy is disabled.
#[inline]
fn restore_timestamps(
    file: &mut fs::File,
    metadata: &pna::Metadata,
    keep_options: &KeepOptions,
) -> io::Result<()> {
    if let TimestampStrategy::Preserve {
        mtime,
        ctime: _ctime,
        atime,
    } = keep_options.timestamp_strategy
    {
        let mut times = fs::FileTimes::new();
        if let Some(accessed) = atime.resolve(metadata.accessed_time()) {
            times = times.set_accessed(accessed);
        }
        if let Some(modified) = mtime.resolve(metadata.modified_time()) {
            times = times.set_modified(modified);
        }
        #[cfg(any(windows, target_os = "macos"))]
        if let Some(created) = _ctime.resolve(metadata.created_time()) {
            times = times.set_created(created);
        }
        file.set_times(times)?;
    }
    Ok(())
}

/// Restores file metadata (permissions, extended attributes, ACLs, and macOS metadata) for an extracted entry according to the provided keep options.
///
/// - Ownership is restored when `owner_strategy` is `Preserve`
/// - Mode bits are restored when `mode_strategy` is `Preserve`
/// - These are independent: `--keep-permission --no-same-owner` restores mode but not ownership
fn restore_metadata<T>(
    item: &NormalEntry<T>,
    path: &Path,
    keep_options: &KeepOptions,
) -> io::Result<()>
where
    T: AsRef<[u8]>,
{
    if let Some(p) = item.metadata().permission() {
        // Restore ownership when owner_strategy is Preserve (independent of mode)
        if let OwnerStrategy::Preserve { options } = &keep_options.owner_strategy {
            restore_owner(path, p, options)?;
        }
        // Restore mode bits when configured.
        match keep_options.mode_strategy {
            ModeStrategy::Preserve => restore_mode(path, p)?,
            ModeStrategy::Masked(mask) => restore_mode_masked(path, p, mask)?,
            ModeStrategy::Never => {}
        }
    }
    // On macOS, when mac_metadata_strategy is Always and the entry has mac_metadata,
    // AppleDouble restoration via copyfile() will include xattrs and ACLs.
    // Skip separate handling to avoid duplication.
    #[cfg(target_os = "macos")]
    let skip_xattr_acl = matches!(
        keep_options.mac_metadata_strategy,
        MacMetadataStrategy::Always
    ) && item.mac_metadata().is_some();
    #[cfg(not(target_os = "macos"))]
    let skip_xattr_acl = false;

    #[cfg(unix)]
    if !skip_xattr_acl && matches!(keep_options.xattr_strategy, XattrStrategy::Always) {
        match utils::os::unix::fs::xattrs::set_xattrs(path, item.xattrs()) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::Unsupported => {
                log::warn!(
                    "Extended attributes are not supported on filesystem for '{}': {}",
                    path.display(),
                    e
                );
            }
            Err(e) => return Err(e),
        }
    }
    #[cfg(not(unix))]
    if let XattrStrategy::Always = keep_options.xattr_strategy {
        log::warn!("Currently extended attribute is not supported on this platform.");
    }
    #[cfg(feature = "acl")]
    if !skip_xattr_acl {
        restore_acls(path, item.acl()?, keep_options.acl_strategy)?;
    }
    #[cfg(not(feature = "acl"))]
    if let AclStrategy::Always = keep_options.acl_strategy {
        log::warn!("Please enable `acl` feature and rebuild and install pna.");
    }
    if let FflagsStrategy::Always = keep_options.fflags_strategy {
        let flags = item.fflags();
        if !flags.is_empty() {
            match utils::fs::set_flags(path, &flags) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::Unsupported => {
                    log::warn!(
                        "File flags are not supported on filesystem for '{}': {}",
                        path.display(),
                        e
                    );
                }
                Err(e) => return Err(e),
            }
        }
    }
    // macOS metadata (AppleDouble) - restores xattrs, ACLs, resource forks via copyfile()
    #[cfg(target_os = "macos")]
    if matches!(
        keep_options.mac_metadata_strategy,
        MacMetadataStrategy::Always
    ) && let Some(apple_double_data) = item.mac_metadata()
    {
        match utils::os::unix::fs::copyfile::unpack_apple_double(apple_double_data, path) {
            Ok(()) => {
                log::debug!("Unpacked macOS metadata for '{}'", path.display());
            }
            Err(e) => {
                log::warn!(
                    "Failed to restore macOS metadata for '{}': {}",
                    path.display(),
                    e
                );
            }
        }
    }
    #[cfg(not(target_os = "macos"))]
    if matches!(
        keep_options.mac_metadata_strategy,
        MacMetadataStrategy::Always
    ) && item.mac_metadata().is_some()
    {
        log::warn!(
            "macOS metadata present but cannot be restored on this platform: '{}'",
            path.display()
        );
    }
    Ok(())
}

/// Restore POSIX/Windows ACLs on a filesystem path when ACL preservation is enabled.
///
/// When `acl_strategy` is `AclStrategy::Always`, selects the ACL entries that match the current
/// platform if present, otherwise uses the first available platform-tagged ACL set, and applies
/// them to `path`. Empty ACL lists are ignored.
///
/// On platforms without ACL support, this emits a warning and returns successfully.
/// On supported platforms, if the target filesystem does not support ACLs (e.g., FAT32),
/// a warning is logged for that path and the operation continues.
#[cfg(feature = "acl")]
fn restore_acls(path: &Path, acls: Acls, acl_strategy: AclStrategy) -> io::Result<()> {
    #[cfg(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "macos",
        windows
    ))]
    if let AclStrategy::Always = acl_strategy {
        use crate::chunk::{AcePlatform, Acl, acl_convert_current_platform};
        use itertools::Itertools;

        let platform = AcePlatform::CURRENT;
        if let Some((platform, acl)) = acls.into_iter().find_or_first(|(p, _)| p.eq(&platform))
            && !acl.is_empty()
        {
            match utils::acl::set_facl(
                path,
                acl_convert_current_platform(Acl {
                    platform,
                    entries: acl,
                }),
            ) {
                Ok(()) => {}
                Err(e) if e.kind() == io::ErrorKind::Unsupported => {
                    log::warn!(
                        "ACL not supported on this filesystem, skipping '{}': {}",
                        path.display(),
                        e
                    );
                }
                Err(e) => return Err(e),
            }
        }
    }
    #[cfg(not(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "macos",
        windows
    )))]
    if let AclStrategy::Always = acl_strategy {
        log::warn!("Currently acl is not supported on this platform.");
    }
    Ok(())
}

/// Resolves the user and group to use for ownership restoration.
///
/// Priority:
/// 1. Override uid/gid if specified
/// 2. Override uname/gname if specified, searching by name
/// 3. Archive's uname/gname with fallback to archive's uid/gid
fn resolve_owner(
    permission: &Permission,
    uname_override: Option<&str>,
    gname_override: Option<&str>,
    uid_override: Option<u32>,
    gid_override: Option<u32>,
) -> (Option<User>, Option<Group>) {
    let user = if let Some(uid) = uid_override {
        User::from_uid(uid.into()).ok()
    } else {
        let name = uname_override.unwrap_or(permission.uname());
        search_owner(name, permission.uid()).ok()
    };
    let group = if let Some(gid) = gid_override {
        Group::from_gid(gid.into()).ok()
    } else {
        let name = gname_override.unwrap_or(permission.gname());
        search_group(name, permission.gid()).ok()
    };
    (user, group)
}

/// Restores file ownership (uid/gid) for an extracted entry.
/// Called when `OwnerStrategy::Preserve` is set.
#[inline]
fn restore_owner(path: &Path, p: &Permission, options: &OwnerOptions) -> io::Result<()> {
    #[cfg(any(unix, windows))]
    {
        let (user, group) = resolve_owner(
            p,
            options.uname.as_deref(),
            options.gname.as_deref(),
            options.uid,
            options.gid,
        );
        match lchown(path, user, group) {
            Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
                log::warn!("failed to restore owner of {}: {}", path.display(), e)
            }
            r => r?,
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, p, options);
        log::warn!("Currently ownership restoration is not supported on this platform.");
    }
    Ok(())
}

/// Restores file mode bits (permissions like 0755) for an extracted entry.
/// Called when `ModeStrategy::Preserve` is set.
#[inline]
fn restore_mode(path: &Path, p: &Permission) -> io::Result<()> {
    #[cfg(any(unix, windows))]
    {
        utils::fs::chmod(path, p.permissions())?;
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, p);
        log::warn!(
            "Skipping mode restoration for '{}': not supported on this platform.",
            path.display()
        );
    }
    Ok(())
}

/// Restores file mode bits with umask applied and suid/sgid/sticky cleared.
#[inline]
fn restore_mode_masked(path: &Path, p: &Permission, umask: Umask) -> io::Result<()> {
    #[cfg(any(unix, windows))]
    {
        utils::fs::chmod(path, umask.apply(p.permissions()))?;
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, p, umask);
        log::warn!(
            "Skipping mode restoration for '{}': not supported on this platform.",
            path.display()
        );
    }
    Ok(())
}

fn is_existing_newer<T>(metadata: &fs::Metadata, item: &NormalEntry<T>) -> bool
where
    T: AsRef<[u8]>,
{
    if let (Ok(existing_modified), Some(entry_modified)) =
        (metadata.modified(), item.metadata().modified_time())
    {
        existing_modified >= entry_modified
    } else {
        false
    }
}

fn extract_entry_to_stdout<T>(item: &NormalEntry<T>, password: Option<&[u8]>) -> io::Result<()>
where
    T: AsRef<[u8]>,
    pna::RawChunk<T>: Chunk,
{
    if !matches!(item.header().data_kind(), DataKind::File) {
        return Ok(());
    }

    let mut reader = item.reader(ReadOptions::with_password(password))?;
    let mut stdout = io::stdout().lock();
    io::copy(&mut reader, &mut stdout)?;
    stdout.flush()?;
    Ok(())
}

fn ensure_directory_components(
    path: &Path,
    unlink_first: bool,
    secure_symlinks: bool,
) -> io::Result<()> {
    if path.as_os_str().is_empty() {
        return Ok(());
    }
    if !secure_symlinks {
        match fs::create_dir_all(path) {
            Ok(()) => return Ok(()),
            // Symlink to non-directory in path or at final component
            Err(err)
                if err.kind() == io::ErrorKind::NotADirectory
                    || err.kind() == io::ErrorKind::AlreadyExists => {}
            Err(err) => return Err(err),
        }
    }
    let mut current = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => continue,
            Component::ParentDir => {
                current.pop();
                continue;
            }
            Component::RootDir | Component::Prefix(_) | Component::Normal(_) => {
                current.push(component.as_os_str());
            }
        }
        if current.as_os_str().is_empty() {
            continue;
        }
        match fs::symlink_metadata(&current) {
            Ok(meta) => {
                if meta.is_dir() {
                    continue;
                }
                if !secure_symlinks
                    && meta.is_symlink()
                    && fs::metadata(&current).is_ok_and(|m| m.is_dir())
                {
                    continue;
                }
                if secure_symlinks && meta.is_symlink() && !unlink_first {
                    return Err(io::Error::other(format!(
                        "Cannot extract through symlink {}",
                        current.display()
                    )));
                }
                if unlink_first {
                    utils::fs::remove_path_all(&current)?;
                } else {
                    match utils::fs::remove_path(&current) {
                        Ok(()) => {}
                        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                        // Concurrent extraction already replaced with directory
                        Err(e) if e.kind() == io::ErrorKind::IsADirectory => continue,
                        Err(e) => return Err(e),
                    }
                }
            }
            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
            Err(err) => return Err(err),
        }
        if let Err(err) = fs::create_dir(&current)
            && err.kind() != io::ErrorKind::AlreadyExists
        {
            return Err(err);
        }
    }
    Ok(())
}

fn search_owner(name: &str, id: u64) -> io::Result<User> {
    let user = User::from_name(name);
    if user.is_ok() {
        return user;
    }
    User::from_uid((id as u32).into())
}

fn search_group(name: &str, id: u64) -> io::Result<Group> {
    let group = Group::from_name(name);
    if group.is_ok() {
        return group;
    }
    Group::from_gid((id as u32).into())
}

#[inline]
fn is_unsafe_link(reference: &EntryReference) -> bool {
    crate::command::core::path::is_unsafe_link_path(reference.as_str())
}