self_update 1.3.2

Self updates for standalone executables
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
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
/*!

[![crates.io:clin](https://img.shields.io/crates/v/self_update.svg?label=self_update)](https://crates.io/crates/self_update)
[![docs](https://docs.rs/self_update/badge.svg)](https://docs.rs/self_update)


`self_update` provides updaters for updating rust executables in-place from various release
distribution backends.

Supported backends: **GitHub**, **GitLab**, **Gitea**, **Gitee**, **S3** (Amazon S3, Google GCS,
DigitalOcean Spaces, or any S3-compatible endpoint), and **Manifest** (any static file server).
The forge and S3 backends each expose a `ReleaseList` builder alongside the `Update`
(configure -> build -> update) API; the manifest backend exposes `Update` only.

## Quick start

```rust
use self_update::cargo_crate_version;

fn update() -> Result<(), Box<dyn std::error::Error>> {
    let status = self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .show_download_progress(true)
        .current_version(cargo_crate_version!())
        .build()?
        .update()?;
    println!("Update status: `{}`!", status.version());
    Ok(())
}
```

> **Upgrading from 0.x?** 1.0 makes a focused set of breaking changes to clean up the public
> API. See the [1.0 migration guide](https://github.com/jaemk/self_update/blob/master/docs/migrations/0.x-to-1.0-human.md)
> for a step-by-step walkthrough, or the
> [agent-oriented guide](https://github.com/jaemk/self_update/blob/master/docs/migrations/0.x-to-1.0.md)
> for automated migration tooling.

> **Running unattended (daemon / CI / service)?** The defaults are interactive: `show_output`
> is `true` and `no_confirm` is `false`, so `update()` prints a release-status block to stdout
> and then **blocks on an interactive `yes/no` prompt** waiting on stdin. With no terminal
> attached this stalls (or aborts). For any non-interactive caller set `.no_confirm(true)` to
> skip the prompt, and usually `.show_output(false)` to silence the status block. These are
> settings only -- the defaults are unchanged. Note the status block is printed *before* the
> confirmation prompt, so suppressing one does not suppress the other.

## Usage

### Features

At least one HTTP client must be selected. A build with **no** client -- for example
`default-features = false` with only a TLS feature such as `features = ["rustls"]` -- fails to
compile with `no HTTP client selected - enable at least one of the reqwest (default) or ureq
features`. Add a client explicitly, e.g. `default-features = false, features = ["ureq", "rustls",
"github"]`. Multiple clients and multiple TLS backends may coexist (reqwest is preferred when both
are present):

* `reqwest` (default): use the [`reqwest`](https://docs.rs/reqwest) HTTP client;
* `ureq`: use the [`ureq`](https://docs.rs/ureq) HTTP client, either alongside reqwest or as a drop-in replacement (set `default-features = false` to drop reqwest);
* `rustls` (default): [pure-Rust TLS](https://github.com/rustls/rustls); does _not_ support 32-bit macOS;
* `native-tls`: opt-in native/OpenSSL TLS for the selected client;
* `native-tls-vendored`: build OpenSSL from source and link it statically (for targets where a usable system OpenSSL is awkward, e.g. musl or some cross-compiles); implies `native-tls`, applies to the reqwest client;

Note that enabling a client with neither TLS feature compiles (plain-`http` release hosts remain
reachable) but any `https` URL then fails at request time with a transport error; enable `rustls`
or `native-tls` for `https`.

The following [cargo features](https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section)
are enabled by default:

* `github`: the GitHub Releases backend;
* `progress-bar`: terminal download progress bar;

The following are opt-in; activate the one(s) your release files need:

* `gitlab`: the GitLab Releases backend;
* `gitea`: the Gitea Releases backend;
* `gitee`: the Gitee Releases backend;
* `s3`: the S3-compatible backend (Amazon S3, GCS, DigitalOcean Spaces, etc.);
* `s3-auth`: sign S3 requests (AWS SigV4) for private buckets; implies `s3`;
* `manifest`: the static-file manifest backend; fetches releases from a `manifest.json` served by any HTTP endpoint; no new dependencies;
* `archive-tar`: support for _tar_ archive format;
* `archive-zip`: support for _zip_ archive format;
* `compression-tar-gz`: support for _gzip_ compression (`.tar.gz`, `.tgz`, plain `.gz`);
* `compression-tar-xz`: support for _xz_ compression (`.tar.xz`, `.txz`, plain `.xz`); pure-Rust, no C `liblzma` dependency;
* `compression-zip-deflate`: support for _zip_'s _deflate_ compression format;
* `compression-zip-bzip2`: support for _zip_'s _bzip2_ compression format;
* `signatures`: use [zipsign](https://github.com/Kijewski/zipsign) to verify `.zip` and `.tar.gz` artifacts. Artifacts are assumed to have been signed using zipsign;
* `checksums`: verify a downloaded artifact against a SHA-256/SHA-512 checksum before installing it -- automatically against the digest github publishes per release asset, and/or against a known checksum you pass in (e.g. from a `SHA256SUMS` file); see [Checksum verification](#checksum-verification) below;
* `async`: add async (`*_async`) update methods alongside the unchanged blocking API; tokio-only, requires `reqwest` (ureq and reqwest can coexist -- reqwest serves the async path, and the sync API prefers reqwest when both are present); see [Async](#async) below.

`github` is the only backend in the default feature set. The S3 backend requires the `s3` feature; `s3-auth` implies `s3`. `gitlab`, `gitea`, `gitee`, and `manifest` each require their own feature.

### Example

Run the following example to see `self_update` in action:

`cargo run --example github --features "signatures archive-tar compression-tar-gz"`.

There are equivalent examples for the other backends (`gitlab`, `gitea`, `gitee`, `s3`), e.g.:

`cargo run --example gitlab --features "gitlab archive-tar compression-tar-gz"`.

Amazon S3, Google GCS, and DigitalOcean Spaces, as well as any S3 compatible server are also supported
through the `S3` backend to check for new releases.  Provided a `bucket_name`
and `asset_prefix` string, `self_update` will look up all matching files using the following format
as a convention for the filenames: `[directory/]<asset name>-<semver>-<platform/target>.<extension>`.
Leading directories will be stripped from the file name allowing the use of subdirectories in the S3 bucket,
and any file not matching the format, or not matching the provided prefix string, will be ignored.

```rust
# #[cfg(feature = "s3")]
# mod s3_example {
use self_update::cargo_crate_version;

fn update() -> Result<(), Box<dyn ::std::error::Error>> {
    let status = self_update::backends::s3::Update::configure()
        // .endpoint(self_update::backends::s3::Endpoint::GCS)
        // .endpoint("https://s3.example.com")
        .bucket_name("self_update_releases")
        .asset_prefix("something/self_update")
        .region("eu-west-2")
        .bin_name("self_update_example")
        // To authenticate (requires the `s3-auth` feature), read the credentials at
        // runtime rather than baking them into the binary with `env!`:
        // .access_key((std::env::var("AWS_ACCESS_KEY_ID")?, std::env::var("AWS_SECRET_ACCESS_KEY")?))
        .show_download_progress(true)
        .current_version(cargo_crate_version!())
        .build()?
        .update()?;
    println!("S3 Update status: `{}`!", status.version());
    Ok(())
}
# }
```

The `manifest` backend (`manifest` feature) serves releases from a `manifest.json` file hosted
on any static file server. The tool author publishes the manifest at a stable URL; assets may be
absolute URLs or relative paths resolved against that URL. Asset `digest` fields (`sha256:<hex>`)
plug into the existing checksum verification path when the `checksums` feature is on. See
`specs/ref-manifest-backend.md` for the full schema.

```rust
# #[cfg(feature = "manifest")]
# mod manifest_example {
use self_update::cargo_crate_version;

fn update() -> Result<(), Box<dyn std::error::Error>> {
    let status = self_update::backends::manifest::Update::configure()
        .manifest_url("https://example.net/releases/manifest.json")
        .bin_name("app")
        .current_version(cargo_crate_version!())
        .build()?
        .update()?;
    println!("Manifest update status: `{}`!", status.version());
    Ok(())
}
# }
```

Separate utilities are also exposed (**NOTE**: the following example extracts a `.tar.gz`, which
_requires_ both the `archive-tar` and `compression-tar-gz` features -- `archive-tar` reads the tar
archive and `compression-tar-gz` decodes the gzip layer; see the [features](#features) section
above). It downloads, extracts, and replaces the running binary
by hand; the staging directory and the in-place replacement use the [`tempfile`](https://crates.io/crates/tempfile)
and [`self_replace`](https://crates.io/crates/self-replace) crates, which you add as your own dependencies
(they are no longer re-exported from `self_update`):

```rust
# #[cfg(feature = "archive-tar")]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    let releases = self_update::backends::github::ReleaseList::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .build()?
        .fetch()?;
    println!("found releases:");
    println!("{:#?}\n", releases);

    // get the first available release (`fetch` returns a `Releases`; `latest()` is the first entry)
    let latest = releases.latest().unwrap();
    let asset = latest
        .asset_for(&self_update::get_target(), None)
        .unwrap();

    let tmp_dir = tempfile::Builder::new()
            .prefix("self_update")
            .tempdir_in(::std::env::current_dir()?)?;
    let tmp_tarball_path = tmp_dir.path().join(asset.name());
    let tmp_tarball = ::std::fs::File::create(&tmp_tarball_path)?;

    self_update::Download::from_url(asset.download_url())
        .request_header(self_update::http::header::ACCEPT, "application/octet-stream")
        .download_to(&tmp_tarball)?;

    let bin_name = std::path::PathBuf::from("self_update_bin");
    self_update::Extract::from_source(&tmp_tarball_path)
        .archive(self_update::ArchiveKind::Tar(Some(self_update::Compression::Gz)))
        .extract_file(&tmp_dir.path(), &bin_name)?;

    let new_exe = tmp_dir.path().join(bin_name);
    self_replace::self_replace(new_exe)?;

    Ok(())
}
```

### Multi-file / non-executable install

The high-level `update()` flow replaces a single executable. To update a tool that ships **more
than one file** (a binary plus sidecar libraries/resources), or to install files that aren't the
running executable, download and extract the whole archive yourself and then install the files
with `MoveAll`, which applies a set of `(source -> dest)` moves **transactionally**: either every
move succeeds, or — on the first failure — all already-applied moves are rolled back, so a failed
update can't leave a half-installed tool. Because it uses `rename` (which can't cross
filesystems), the source files, every destination, and the temp dir must all be on the same
filesystem.

**NOTE**: this example extracts a `.tar.gz`, which requires both the `archive-tar` and
`compression-tar-gz` features.

```rust
# #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    let tmp_dir = tempfile::TempDir::new()?;
    let tarball_path = tmp_dir.path().join("release.tar.gz");
    // ... download the archive to `tarball_path` (see the example above) ...

    // The extracted files are renamed into place, so the staging dir (the move sources) and the
    // stash dir must be on the same filesystem as the destinations — create both next to them
    // rather than in $TMPDIR. The `/usr/local` paths below are illustrative; use destinations
    // and temp dirs you have write access to (these may require elevated privileges).
    let staging = tempfile::TempDir::new_in("/usr/local")?;
    self_update::Extract::from_source(&tarball_path)
        .archive(self_update::ArchiveKind::Tar(Some(self_update::Compression::Gz)))
        .extract_into(staging.path())?;

    // Install several files atomically (all-or-nothing).
    let stash = tempfile::TempDir::new_in("/usr/local")?;
    self_update::MoveAll::from_temp(stash.path())
        .add(staging.path().join("app"), "/usr/local/bin/app")
        .add(staging.path().join("libapp.so"), "/usr/local/lib/libapp.so")
        .commit()?;
    Ok(())
}
```

### Bundle installs (macOS `.app`)

A macOS application is a *directory* bundle, so replacing only the executable inside
`MyApp.app/Contents/MacOS/` leaves stale resources behind and breaks the bundle's code signature.
Set `bundle_path_in_archive` to name the bundle directory inside the release archive and the whole
tree is installed as one unit:

```rust
# #[cfg(feature = "github")]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    self_update::backends::github::Update::configure()
        .repo_owner("me")
        .repo_name("myapp")
        .bin_name("myapp")
        .current_version(self_update::cargo_crate_version!())
        // The bundle directory inside the archive; `{{ bin }}` / `{{ target }}` / `{{ version }}`
        // substitutions work here exactly as in `bin_path_in_archive`.
        .bundle_path_in_archive("MyApp.app")
        // Optional on macOS: defaults to the nearest `.app` ancestor of the running executable.
        .bundle_install_path("/Applications/MyApp.app")
        .build()?
        .update()?;
    Ok(())
}
```

How the swap works, and what it guarantees:

- The archive is extracted in full into a temporary directory **inside the install path's parent**,
  so every rename is on one filesystem (there is no cross-device fallback, and the parent needs
  room for one more copy of the bundle). A symlinked `bundle_install_path` is resolved first, so the
  tree behind the link is replaced, the link survives, and staging still lands beside the real tree.
- The installed tree is stashed, then the staged tree is renamed into place. A failure at any step
  restores the original bundle, and the error names the bundle path. Once the final rename lands the
  update is committed.
- When the running executable lives inside the bundle it is renamed aside first, so the old tree
  holds no running image. After a successful update the running executable's path holds the new
  bundle's executable, and the process can relaunch itself with `restart()` (see
  [Restarting after an update](#restarting-after-an-update)).
- Bundle mode replaces a directory, so combining it with an explicit `bin_install_path` or
  `bin_path_in_archive` is rejected by `build()` (`Error::ConflictingConfig`), and setting
  `bundle_install_path` without `bundle_path_in_archive` is an `Error::MissingField` rather than a
  silently discarded path. `bin_name` is still required: it selects the asset and feeds `{{ bin }}`.
- The `verify_binary` hook receives the **staged bundle root**, which is what
  `codesign --verify --deep` wants; a rejection aborts before anything is replaced.
- The crate never signs, notarizes, or staples: ship an already-signed (and, for Gatekeeper,
  notarized) `.app` and the swap preserves exactly what you shipped. A quarantined app running from
  a read-only App Translocation mount cannot update itself in place; that is detected up front as
  `Error::AppTranslocated`, and the fix is to move the app (which clears the quarantine) and
  relaunch it.

Directory bundles on linux and windows go through the same code path. On windows the swap fails,
and rolls back, if the process holds files inside the bundle open beyond its own executable (a DLL
loaded from the bundle, for example). `.deb` / `.msi` packages are a different shape entirely --
hand the downloaded file to `dpkg -i` / `msiexec /i` yourself; the crate's replace-and-verify
semantics do not apply to a system installer.

### Checksum verification

With the `checksums` feature, the crate verifies the downloaded artifact against a digest
**before** installing — a mismatch aborts the update. Two sources of digests, independently
applied (when both apply, both must pass):

- **Release-published digests, automatic.** GitHub publishes a `sha256:<hex>` digest per release
  asset; the updater verifies the download against it whenever the selected asset carries one.
  This is on by default with the `checksums` feature — no configuration needed — and can be
  disabled with `verify_release_digest(false)`. The other backends' APIs publish no digest, so
  the check is a no-op there (a custom `ReleaseSource` can supply one via
  `ReleaseAsset::with_digest`). Note this is an *integrity* check only — the forge recomputes
  the digest if an asset is replaced — so it is not a substitute for the `signatures` feature.
- **A known digest you pass explicitly** (e.g. one published in a `SHA256SUMS` file alongside
  the release) via `verify_checksum`. The algorithm is chosen by the `Checksum` variant
  (`Sha256` / `Sha512`).
- **A digest resolved from a sums asset of the same release**, via
  `checksum_from_asset("SHA256SUMS")`. The named asset is fetched before the artifact is
  downloaded, and the entry for the selected asset supplies the digest. The usual `SHA256SUMS`
  shapes are accepted (coreutils text and binary modes, leading paths, the BSD tag form, `#`
  comments, and a whole-file bare digest), and the algorithm comes from the digest's length, so a
  `SHA512SUMS` asset needs no extra configuration. A release with no such asset, or no entry for
  the artifact, is an `Error::ChecksumSourceInvalid` rather than a skipped check. This is the one
  to reach for on gitlab / gitea / s3, whose APIs publish no per-asset digest.

Both complement the `signatures` feature (zipsign), which verifies authenticity rather than a
published digest.

```rust
# #[cfg(feature = "checksums")]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        // hex digest, obtained out of band (e.g. parsed from the release's SHA256SUMS)
        .verify_checksum(self_update::Checksum::Sha256("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08".into()))
        .build()?
        .update()?;
    Ok(())
}
```

Or let the updater fetch and parse the release's own sums asset:

```rust
# #[cfg(feature = "checksums")]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .checksum_from_asset("SHA256SUMS")
        .build()?
        .update()?;
    Ok(())
}
```

### Verification hooks

Two hooks let you gate an update with your own check. They differ in *what file they see*, which is
the whole reason both exist:

- `verify_archive(|archive: &Path| ..)` runs on the **downloaded archive**, after the crate's own
  content gates (checksum, release digest, signature) and before anything is extracted. This is
  where an external attestation or signature check belongs, since those are issued over the released
  file itself: `gh attestation verify <archive> --repo owner/repo`, `cosign verify-blob`, and so on.
  A rejection is `Error::ArchiveVerificationRejected`.
- `verify_binary(|new_exe: &Path| ..)` runs on the **extracted binary**, immediately before it
  replaces the installed one. This is where a smoke test belongs, typically running
  `new_exe --version` and checking the output. A rejection is `Error::VerificationRejected`.

Either returning `Err(..)` aborts the update with nothing installed. Full order:
`verify_checksum` -> release digest -> signature -> `verify_archive` -> extract -> `verify_binary`
-> replace.

```rust
fn update() -> Result<(), Box<dyn std::error::Error>> {
    self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .verify_archive(|archive: &std::path::Path| {
            let ok = std::process::Command::new("gh")
                .args(["attestation", "verify"])
                .arg(archive)
                .args(["--repo", "jaemk/self_update"])
                .status()
                .map(|s| s.success())
                .unwrap_or(false);
            if ok {
                Ok(())
            } else {
                Err(self_update::Error::archive_verification_rejected(
                    "no build-provenance attestation for this artifact",
                ))
            }
        })
        .build()?
        .update()?;
    Ok(())
}
```

### Checking for an update without installing

To check whether a newer release exists without downloading or installing anything, call
`is_update_available()` on the built updater. It fetches the release listing and returns the newest
strictly-newer `Release` (or `None` when up to date):

```rust
fn check() -> Result<(), Box<dyn std::error::Error>> {
    let update = self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .build()?;

    match update.is_update_available()? {
        Some(release) => println!("update available: {}", release.version()),
        None => println!("already up to date"),
    }
    Ok(())
}
```

### Restarting after an update

After `update()` returns [`VersionStatus::Updated`](crate::VersionStatus::Updated) the on-disk
executable has been replaced, but the running process keeps executing the old code until it exits.
To relaunch into the new binary immediately, use the [`restart`](crate::restart) module:
`restart::restart()` re-runs with the current arguments, and `restart::restart_with(args)` re-runs
with a fresh argument list (e.g. to drop an `--upgrade` flag so the new process does not update
again). On unix the process image is replaced with `exec` (the PID is preserved); on windows the new
binary is spawned and the current process exits. See the module docs for the platform details.

### Permissions

The crate never escalates privileges. There is no sudo re-exec, no polkit interaction, and no UAC
prompt. Privilege escalation is always the caller's choice.

An install into an unwritable location fails with
[`Error::InstallPathNotWritable`](crate::errors::Error::InstallPathNotWritable) naming the path
(the configured `bin_install_path`). Any other IO failure at the install step surfaces as
[`Error::Io`](crate::errors::Error::Io) with a message naming the install path, so the path is
visible in the error regardless of the kind.

Setting `check_install_path_writable(true)` on the builder opts into a preflight probe that runs
immediately before the download. Only a definite `PermissionDenied` refusal errors early;
indeterminate results (a missing parent directory, an unusual filesystem) are treated as "proceed"
and let the real install step surface the outcome. The default is `false`.

```rust,no_run
fn update() -> Result<(), Box<dyn std::error::Error>> {
    match self_update::backends::github::Update::configure()
        .repo_owner("owner")
        .repo_name("repo")
        .bin_name("app")
        .current_version(self_update::cargo_crate_version!())
        .check_install_path_writable(true)
        .build()?
        .update()
    {
        Ok(status) => println!("updated: {}", status.version()),
        Err(self_update::Error::InstallPathNotWritable { .. }) => {
            // The install path is not writable by this process. Elevation is the
            // application's choice: re-run under sudo, spawn a UAC-elevated child, etc.
            // Use the `restart` module for the exec/spawn mechanics when relaunching
            // with a modified argument list.
            eprintln!("install path not writable; re-run with elevated privileges");
        }
        Err(e) => return Err(e.into()),
    }
    Ok(())
}
```

### Periodic update checks

Every `update()` / `is_update_available()` call makes a network request. To avoid checking on every
run, gate the check behind [`UpdateCheckGuard`](crate::check_interval::UpdateCheckGuard), a small
stamp-file guard: `should_check()` reports whether the configured interval has elapsed since the
last recorded check, and `record_check()` stamps the current time. The caller owns the stamp-file
path. It is a guard, not a scheduler -- no threads or timers, and no extra dependencies. See the
[`check_interval`](crate::check_interval) module for the semantics.

### Authentication

Every forge backend's `Update` **and** `ReleaseList` builder -- github, gitlab, gitea, gitee, eight
builders in all -- takes an authorization token. A token is what reaches a private repository at
all, and what lifts the host's anonymous request budget (see
[Rate limits and `Error::RateLimited`](#rate-limits-and-errorratelimited) below). There are two
setters:

* `auth_token(t)` -- a token your application already holds.
* `auth_token_from_env()` -- take it from the backend's conventional environment variables, using
  the first that is set and non-empty (surrounding whitespace is trimmed); a variable that *is* set
  but is not valid UTF-8 is treated the same as unset, since it could not become an HTTP header
  value either way:
  * **github**: `GH_TOKEN`, then `GITHUB_TOKEN` (matching the `gh` CLI's documented precedence).
  * **gitlab**: `GITLAB_TOKEN`.
  * **gitea**: `GITEA_TOKEN`.
  * **gitee**: `GITEE_TOKEN`.

The lookup happens when you call `auth_token_from_env()`, not at request time: it reads the process
environment exactly once, at that call. A `std::env::set_var` made afterward -- before `build()`,
before `update()` -- has no effect on an already-built value; call the setter again (or set the
variable earlier) if that ordering matters to you.

```rust
# #[cfg(feature = "github")]
# fn run() -> Result<(), Box<dyn std::error::Error>> {
let status = self_update::backends::github::Update::configure()
    .repo_owner("jaemk")
    .repo_name("self_update")
    .bin_name("self_update_example")
    .current_version(self_update::cargo_crate_version!())
    // Uses a token when the environment supplies one; unauthenticated when it does not.
    .auth_token_from_env()
    .build()?
    .update()?;
# let _ = status;
# Ok(())
# }
```

**Precedence: an explicit `auth_token(..)` always wins, in either call order.** The environment is a
*fallback* that only fills an unset token, so `auth_token(t).auth_token_from_env()` and
`auth_token_from_env().auth_token(t)` both end up with `t`, and an ambient `*_TOKEN` can never
displace the credential your application provisioned. When no variable is set the call is a no-op --
the token is left as it was and the request goes out exactly as before -- so it is safe to place
unconditionally in an application that also runs outside CI or a corporate network.

`has_auth_token()` (on the same eight builders) reports whether an authorization token is
*configured* on this builder, from either setter. This is configuration, not a prediction: at
request time the token is withheld unless the URL's host matches the configured API host or an
`allow_auth_host` entry over https (loopback is allowed over plain http, for a local mirror or a
test stub), and a user-supplied `Authorization` header via `request_header` takes precedence over
it, silently. On gitea an env-sourced token is additionally withheld unless the configured host was
acknowledged (below). None of that is reflected by `has_auth_token()` -- it reports presence only,
never validity and never the value -- the builders' `Debug` renders the token as `"<token>"`, so
logging a builder does not leak an ambient CI credential.

Reading the environment is opt-in: the crate never does it on its own, since the configured API base
can be a self-hosted host and sending a user's token there should be your decision. Two caveats to
"safe to call unconditionally":

- A variable that is *set* but stale, expired, revoked, or scoped to a different resource makes the
  request **fail** where an anonymous request against a public repository would have succeeded --
  typically a generic `Error::Unauthorized`, with nothing in the error naming the environment as the
  cause. If a working update check starts failing right after you add `auth_token_from_env()`,
  check the variable's value first.
- A token that *is* picked up but cannot be encoded as an HTTP header value (a stray newline, for
  example) is not caught by `build()` -- it surfaces as
  [`Error::InvalidAuthToken`](crate::errors::Error::InvalidAuthToken) at **request** time, and that
  error's message does not mention the environment either.

Both of the crate's own diagnostics about the token it picked up -- the "using the auth token from
$X" pickup and the off-host warning below -- are emitted via `log::debug!` / `log::warn!` only.
Neither prints anything on its own; they are invisible unless your application has installed a
`log` implementation (`env_logger`, `tracing-log`, etc.).

**The variable set does not change with the host.** A custom `api_base_url` / `host` -- GitHub
Enterprise, a self-hosted GitLab -- is still served by exactly the variables above, so an ambient
`GITHUB_TOKEN` is sent to whatever host the builder points at. When an env-sourced token is about to
be bound to a host other than the backend's canonical one (`api.github.com`, `gitlab.com`,
`gitee.com`), `build()` emits a `log::warn!` naming the host, and still sends the token -- on
github/gitlab/gitee this is a warning, not a block. If the off-canonical host is a deliberate GitHub
Enterprise / self-hosted GitLab target, either silence the warning by acknowledging the host with
`allow_auth_host(..)`, or skip the environment lookup and set the token explicitly instead:
`auth_token(std::env::var("GITLAB_TOKEN")?)`. Note also that `gh` reads `GH_ENTERPRISE_TOKEN` /
`GITHUB_ENTERPRISE_TOKEN` for a GitHub Enterprise host and this crate does not, so an enterprise
`api_base_url` still needs one of the variables above (or an explicit `auth_token(..)`).

**gitea is the exception to warn-and-send.** It is always self-hosted, so it has no canonical host
to compare an env-sourced token's destination against. Rather than send `GITEA_TOKEN` to whatever
host the application happens to be pointed at with no signal at all, gitea *withholds* the token
instead: the request goes out anonymous, `build()` still returns `Ok`, and a `log::warn!` names the
host and the same two remedies as above. Get it sent anyway by acknowledging the host, either with
`allow_auth_host(host)` or by setting the token explicitly with `auth_token(..)` (which always takes
precedence, on every backend).

GitHub answers **404**, not 401 or 403, when a token cannot see a private repository -- it hides the
repository's existence rather than distinguishing "forbidden" from "not found". That 404 surfaces as
[`Error::NotFound`](crate::errors::Error::NotFound), so a repository you can normally read looks
like it does not exist rather than like a permission problem; check the token's scope before
assuming a typo in the repo name. Reading a private repository's releases needs the classic `repo`
scope (a fine-grained token needs `Contents: Read-only`) -- the "no scopes needed" note below is for
lifting a *public* repository's rate limit only.

`CI_JOB_TOKEN` is deliberately **not** read on gitlab, even though every GitLab CI job exports it:
this backend sends `Authorization: Bearer`, which is not GitLab's job-token mechanism (the
`JOB-TOKEN` header / `job_token` parameter), and job tokens are project-scoped -- reading it would
turn a working anonymous fetch of a public project into a 401/403 inside CI. Pass it explicitly with
`auth_token(..)` if you want it.

### Rate limits and `Error::RateLimited`

A rate-limited response surfaces as [`Error::RateLimited`](crate::errors::Error::RateLimited),
distinct from the `Error::Unauthorized` a genuine credential failure produces -- the rule below is
the same on **every** backend, not just github (the numbers in [GitHub rate
limits](#github-rate-limits) below are github-specific; the classification is not). A response with
headers in hand is classified as `RateLimited` when it is a **429** (RFC 6585 defines that status as
rate limiting, so it always lands here, with or without quota headers), or a **403** carrying either
a zero remaining-quota header (`x-ratelimit-remaining: 0`, or gitlab's `RateLimit-Remaining: 0`) or a
usable `Retry-After` -- that last case is GitHub's *secondary* rate limit, which answers 403 +
`Retry-After` while `x-ratelimit-remaining` is still nonzero. A bare 403 with no such header stays
`Unauthorized`.

Back off by [`Error::rate_limit_delay()`](crate::errors::Error::rate_limit_delay), which resolves
the wait to an `Option<Duration>`: the server's `Retry-After` when it sent one, otherwise
`reset_at` minus now, and `None` when the window has already elapsed or nothing is known. Reading
the raw fields instead is the footgun -- on GitHub's *primary* limit only `x-ratelimit-reset` is
sent, so `retry_after.unwrap_or_default()` sleeps zero and burns more quota. Both server-supplied
values are clamped to a 24h ceiling; beyond it they resolve to `None`, so a hostile `Retry-After`
cannot park an update channel indefinitely -- but the wait can legitimately be *up to* that 24h
ceiling, so blocking a thread on it is rarely the right call for an interactive application (see the
example below).

The retry/backoff setters do **not** apply to a `RateLimited` response. `Error::RateLimited` is
never retried: the wait is the server's to dictate (`Retry-After`, or the reset header), and it can
be far longer than any backoff this crate would apply, so the error is returned immediately and the
decision to sleep, reschedule, or give up stays with the caller instead of being spent inside the
loop.

```rust
# #[cfg(feature = "github")]
fn check() -> Result<(), Box<dyn std::error::Error>> {
    let update = self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("self_update_example")
        .current_version(self_update::cargo_crate_version!())
        .auth_token_from_env()
        .build()?;

    match update.update() {
        Ok(status) => println!("update status: `{}`", status.version()),
        Err(err @ self_update::Error::RateLimited { .. }) => {
            // rate_limit_delay() can resolve to a wait as long as 24h, so blocking this thread on
            // it is rarely the right call for an interactive app. Skip this run and let the next
            // scheduled check (e.g. through `UpdateCheckGuard` above) try again, rather than
            // sleeping here -- if you do want to block instead, sleep on `err.rate_limit_delay()`
            // and retry `update.update()` yourself.
            let _ = err.rate_limit_delay();
            println!("rate limited; retrying on the next scheduled check");
        }
        Err(err) => return Err(err.into()),
    }
    Ok(())
}
```

### GitHub rate limits

Requests to the GitHub REST API are rate limited by GitHub itself, not by this crate:

- **Unauthenticated** requests are limited to **60 per hour per source IP**; **authenticated**
  requests (a token via `auth_token` / `auth_token_from_env`, see
  [Authentication](#authentication)) get **5000 per hour**. A token needs no scopes to raise the
  limit for a public repository (a private repository needs the scope noted above regardless of the
  limit).
- That budget is counted **per source IP, not per application**. Behind a shared egress IP -- a
  NAT'd corporate network, a CI runner pool, a VPN exit -- it is pooled across everyone on that IP
  and can be spent entirely by other people, so a lightly-used application still sees 403s there.
- An update check costs **one** API request (the latest-release lookup, or one request per page of a
  paginated listing). The asset **download** itself is a CDN redirect and does not count against the
  core API limit.
- To avoid it: set a token, and check less often -- the
  [`UpdateCheckGuard`](crate::check_interval::UpdateCheckGuard) above throttles how often you check.

### Listing releases (`ReleaseList`)

Each built-in backend exposes a `ReleaseList` builder for fetching the list of available releases
without performing an update. There is **no single unifying `self_update::ReleaseList` type**:
every backend has its own, distinct `ReleaseList` (the fields and request shape differ per host),
so they are reached through their backend modules rather than re-exported at the crate root:

* `backends::github::ReleaseList`
* `backends::gitlab::ReleaseList`
* `backends::gitea::ReleaseList`
* `backends::gitee::ReleaseList`
* `backends::s3::ReleaseList`

The `manifest` backend has no separate `ReleaseList` struct. Its `ManifestSource` is a
`ReleaseSource` implementation that can be used directly, or listing can be driven through the
inherent verbs (`get_latest_release`, `get_newer_releases`, `is_update_available`) on a built
`manifest::Update`.

The custom backend has no `ReleaseList` by design: listing is performed entirely by your
`ReleaseSource` (or `AsyncReleaseSource`) implementation, which already returns
`Release` values directly.

### Custom backends

To update from a host the built-in backends (`github`, `gitlab`, `gitea`, `gitee`, `s3`, `manifest`) don't cover —
another forge, a private artifact registry, a plain HTTP directory — implement the
`ReleaseSource` trait and drive a full update through the `backends::custom` backend, which reuses
the crate's compare → select-asset → download → verify → extract → install flow. Only
`get_releases` (the fetch that says *where releases come from*) is required;
`get_latest_release` / `get_release_version` are derived from it by default and can be overridden
when the host has cheaper dedicated endpoints. You build `Release`s with `Release::builder` and
`ReleaseAsset::new`; the `ReleaseUpdate` trait stays sealed.

`ReleaseSource` is **synchronous**. For a natively-async source, implement `AsyncReleaseSource`
(the same fetches as `async fn`) and drive it through
`backends::custom::AsyncUpdate` + `build_async()`; to reuse a
`Clone` sync source from the async API, wrap it in
`backends::custom::Blocking`.

```rust
use self_update::{Release, ReleaseAsset, ReleaseSource, cargo_crate_version};

struct MyHost;
impl ReleaseSource for MyHost {
    fn get_releases(&self) -> self_update::Result<Vec<Release>> {
        Ok(vec![Release::builder()
            .version("1.2.3")
            .asset(ReleaseAsset::new("app-x86_64-unknown-linux-gnu.tar.gz", "https://host/app.tar.gz"))
            .build()?])
    }
}

fn update() -> Result<(), Box<dyn std::error::Error>> {
    let status = self_update::backends::custom::Update::configure()
        .source(MyHost)
        .bin_name("app")
        .current_version(cargo_crate_version!())
        .build()?
        .update()?;
    println!("custom backend update status: `{}`!", status.version());
    Ok(())
}
```

### Async

With the `async` feature, every built-in backend's `Update` builder gains a `build_async()` that
returns a distinct `AsyncUpdate` wrapper (one per backend). Its async (`*_async`) verbs —
`update_async()`, `update_extended_async()`, `get_latest_release_async()`,
`get_newer_releases_async()`, `get_release_version_async()`, and `is_update_available_async()` — are
**inherent methods** on that wrapper, so a `tokio` application can update without wrapping the
blocking calls in `spawn_blocking` and without importing any trait. Crucially, the `AsyncUpdate`
wrapper does **not** expose the blocking verbs: calling `.update()` on an async-built updater is a
compile error, so the old footgun of accidentally running a blocking update from an async context
is gone. The blocking API is unchanged; the async path is purely additive. It is **tokio-only and
requires `reqwest`** -- ureq and reqwest can coexist (reqwest serves the async path, and the sync
API prefers reqwest when both are present); the only invalid configuration is `async` without
`reqwest`. Network IO becomes async, and the extract/replace tail runs on
`tokio::task::spawn_blocking` so it does not block the executor.

```rust
# #[cfg(feature = "async")]
async fn update() -> Result<(), Box<dyn std::error::Error>> {
    let status = self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .build_async()?
        .update_async()
        .await?;
    println!("Update status: `{}`!", status.version());
    Ok(())
}
```

The `AsyncUpdate` wrapper exposes only the `*_async` verbs; the blocking `update()` is not a method
on it, so accidentally calling it from async code does not compile. The following block is
`compile_fail` for exactly that reason — `update` is not a method on the async wrapper (this block
is intentionally not feature-gated: gating it behind `cfg(feature = "async")` would make it an empty,
successfully-compiling doctest in the crate's no-`async` test lanes, which a `compile_fail` block
must never do):

```rust,compile_fail
fn wont_compile() -> Result<(), Box<dyn std::error::Error>> {
    let updater = self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .build_async()?;
    // `update()` is the BLOCKING verb; it is not exposed on the async `AsyncUpdate` wrapper.
    updater.update()?;
    Ok(())
}
```

### Proxies

Both clients honor the `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` environment variables. When the
proxy requires credentials that you would rather not put in the environment, set it on the builder
instead — the URL may embed them, and they are sent to the proxy as `Proxy-Authorization`:

```rust
# #[cfg(feature = "github")]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .proxy("http://corp-user:s3cret@proxy.corp.example:8080")
        .build()?
        .update()?;
    Ok(())
}
```

The proxy applies to every request the updater makes, the release listing and the asset download
alike, and [`Download`](crate::Download) has the same `proxy` setter for standalone downloads. The
password is redacted from the builder's `Debug` output and from any error it produces, so neither
leaks into your logs. An unparseable URL surfaces as
[`Error::InvalidProxy`](crate::errors::Error::InvalidProxy) from `build()`.

Only HTTP CONNECT proxies are supported (SOCKS is out of scope — inject your own client for that).
On the reqwest client this proxy is applied alongside the environment variables (reqwest tries its
configured proxies in order, first match wins); on a ureq-only build the agent has a single proxy
slot, so the configured proxy replaces the env-var one. A client injected via `http_client` /
`reqwest_client` / `ureq_agent` owns its own proxy configuration and ignores this setter.

### Custom HTTP client

The `.timeout()` / `.request_header()` / `.retries()` / `.proxy()` / `.add_root_certificate()`
builder knobs cover most transport needs, but for full control — mTLS, connection pooling, redirect
policy, SOCKS proxies, or simply reusing your application's existing client — you can hand the crate
a **pre-built client**.
It is used for both the release listing and the download. The client-specific convenience setters
are `reqwest_client` (a blocking `reqwest::blocking::Client`, used by the blocking API),
`reqwest_async_client` (an async `reqwest::Client`, used by the `*_async` verbs), and `ureq_agent`
(a `ureq::Agent`); each wraps your client behind the crate's object-safe HTTP transport trait. The
compiled client crate(s) are re-exported (`self_update::reqwest` / `self_update::ureq`) so you don't
need a separate dependency to name the type. (Since the transport is a runtime trait seam, `reqwest`
and `ureq` are no longer mutually exclusive — both can be enabled, and the sync API prefers reqwest
when both are present.) For test doubles or fully custom transport, inject any type that implements
the object-safe trait directly via `.http_client(Arc<dyn HttpClient>)` (sync) or
`.http_client_async(Arc<dyn AsyncHttpClient>)` (async); see the [`http_client`](crate::http_client)
module for the trait definitions.

When you inject a client, `.request_header()` still applies, and `.retries()` still applies to the
release-listing requests and to the download's request-establishment phase (a mid-stream failure
is not retried, as that would corrupt the partially-written destination), and for `reqwest` the per-request
`.timeout()` is layered on too; but `HTTP(S)_PROXY` env and the crate's TLS feature are left entirely
to your client (and a `ureq::Agent` owns its own timeout, so `.timeout()` does not apply to an
injected agent — configure it on the agent). `reqwest_client` feeds the sync verbs and
`reqwest_async_client` the async ones — injecting only one and calling the other half just uses the
crate's per-call client for that half.

A fully custom transport also owns the job of **classifying** a non-2xx response. Prefer
[`Error::http_status_error_with_headers(status, url, &headers)`](crate::errors::Error::http_status_error_with_headers)
over the header-blind [`Error::http_status_error`](crate::errors::Error::http_status_error): the
header-blind form still maps a **429** to
[`Error::RateLimited`](crate::errors::Error::RateLimited) -- the status alone is the signal. What it
cannot do is promote a **403** (with no headers in hand a 403 stays `Unauthorized`) or recover the
`reset_at` / `retry_after` fields, so `rate_limit_delay()` on one of its errors is always `None`.
See [Rate limits and `Error::RateLimited`](#rate-limits-and-errorratelimited) above for the full
classification rule. The built-in reqwest and ureq clients (including an injected `ureq::Agent`)
all use the header-aware form, so they classify identically.

```rust
# #[cfg(feature = "reqwest")]
fn update() -> Result<(), Box<dyn std::error::Error>> {
    let client = self_update::reqwest::blocking::Client::builder()
        // .add_root_certificate(...) / .proxy(...) / .danger_accept_invalid_certs(...) etc.
        .build()?;
    self_update::backends::github::Update::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .bin_name("github")
        .current_version(self_update::cargo_crate_version!())
        .reqwest_client(client)
        .build()?
        .update()?;
    Ok(())
}
```

### Troubleshooting

**Cross-compilation (`cross` / `cargo-cross`).** `rustls` is the default TLS backend, so
no additional configuration is needed for cross-compilation: a build on default features
already uses rustls. If you have explicitly switched to `native-tls` and want to revert,
remove the `native-tls` feature; `rustls` is active by default.

**TLS certificate errors on Linux (`native-tls` / OpenSSL).** With the native-TLS backend,
OpenSSL finds the system CA bundle on its own on most distributions. In a minimal environment where
it can't (some containers, `musl` static builds, or a non-standard cert layout) a request may fail
with a certificate-verification error. Point OpenSSL at the bundle by exporting `SSL_CERT_FILE`
(and, if needed, `SSL_CERT_DIR`) before running your program — the paths vary by distribution, e.g.
on a Debian/Ubuntu base:

```bash
export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
export SSL_CERT_DIR=/etc/ssl/certs
```

Alternatively build with the `rustls` feature, which uses a bundled root store and does not depend
on the system OpenSSL cert layout.

**TLS certificate errors behind a corporate proxy (`ureq` + `rustls`).** Many company networks
terminate outbound HTTPS at an intercepting proxy that re-signs traffic with an internal CA. That CA
is installed in the machine's trust store, so `curl` and the system browsers accept it, but the
ureq client's default root store is `RootCerts::WebPki` (Mozilla's bundled roots), which ignores the
machine entirely, so every request fails to verify. Enable the `native-certs` feature to move the
ureq client onto the OS trust store instead:

```toml
self_update = { version = "1.3", features = ["ureq", "rustls", "native-certs"] }
```

The reqwest client needs nothing and is not affected by the feature: its rustls setup already
verifies through `rustls-platform-verifier`, and its native-tls setup uses the system store by
definition. On a reqwest-only build `native-certs` is a no-op that pulls in no extra dependency, so
it is safe to enable unconditionally in a crate that offers both clients.
`native-certs` has no effect on an injected `ureq::Agent` either, since that agent owns its own TLS
config, so set `RootCerts::PlatformVerifier` on it yourself. On Linux the OS trust store honors
`SSL_CERT_FILE` / `SSL_CERT_DIR`, so those env vars work as an escape hatch once the feature is on.
To trust exactly one internal CA and nothing else, skip the feature and pass the certificate to
[`add_root_certificate`](crate::backends::github::UpdateBuilder::add_root_certificate). Note that on
a ureq build that *replaces* the trust store rather than adding to it.

**The proxy needs a username and password.** `HTTP_PROXY` / `HTTPS_PROXY` cover an unauthenticated
proxy, but if yours demands credentials, pass them on the builder with
[`proxy`](crate::backends::github::UpdateBuilder::proxy) (see [Proxies](#proxies) above) rather than
adding `reqwest` or `ureq` as a direct dependency just to build a client with a proxy on it.

*/

// Enable the `doc_cfg` feature on docs.rs (nightly-only, guarded by the `docsrs` cfg set via
// `rustdoc-args = ["--cfg", "docsrs"]` in Cargo.toml). Stable builds are unaffected because
// the cfg is never set outside of the docs.rs environment.
#![cfg_attr(docsrs, feature(doc_cfg))]
// Keep the crate's rustdoc intra-doc links honest: an unresolved `[link]` in any doc comment is a
// hard error, not a silent warning. The full-crate check is the final barrier during a doc build.
#![deny(rustdoc::broken_intra_doc_links)]

// The HTTP transport is now an object-safe trait seam (`http_client::HttpClient`), so `reqwest` and
// `ureq` are no longer mutually exclusive — both client impls can be compiled and one is selected at
// runtime via `default_client()` (reqwest preferred when both are on). The genuine no-client case is
// a `compile_error!` in `http_client/mod.rs`. TLS features can also coexist: when both `native-tls`
// and `rustls` are enabled the per-call builders prefer rustls.

// The async API is reqwest-only — ureq has no async story. With the trait seam the two clients are
// no longer mutually exclusive, so `async` + `ureq` together is fine (async uses reqwest for the
// async path, ureq serves the sync path). The genuine bad case is `async` without the `reqwest`
// client at all; the `async` feature already implies `reqwest` (see Cargo.toml), so this guard only
// fires if that implication is ever broken.
#[cfg(all(feature = "async", not(feature = "reqwest")))]
compile_error!("feature `async` requires the `reqwest` client - `ureq` has no async API");

pub use http;
// Re-export the crates whose types appear in the async transport-trait signatures
// (`AsyncHttpClient` / `AsyncHttpResponse` name `BoxFuture`, `BoxStream`, and `Bytes`), so a
// custom async transport can be implemented without adding `futures-util`/`bytes` as direct
// dependencies (and without a version-skew risk against the ones this crate links).
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use bytes;
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use futures_util;
// Re-export the selected HTTP client so callers can name the types accepted by the client-injection
// setters (`reqwest_client` / `reqwest_async_client` / `ureq_agent`) without a separate dependency.
#[cfg(feature = "reqwest")]
#[cfg_attr(docsrs, doc(cfg(feature = "reqwest")))]
pub use reqwest;
#[cfg(feature = "signatures")]
#[cfg_attr(docsrs, doc(cfg(feature = "signatures")))]
pub use update::verify_signature;
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use update::{AsyncReleaseSource, AsyncReleaseUpdate};
pub use update::{
    Release, ReleaseAsset, ReleaseBuilder, ReleaseSource, ReleaseStatus, ReleaseUpdate, Releases,
    UpdateConfig, UpdateStrategy,
};
#[cfg(feature = "ureq")]
#[cfg_attr(docsrs, doc(cfg(feature = "ureq")))]
pub use ureq;

/// Re-export of the [`zipsign_api`] crate, whose [`PUBLIC_KEY_LENGTH`] constant defines the
/// size of the ed25519 verifying keys accepted by the `verifying_keys` builder methods.
///
/// [`PUBLIC_KEY_LENGTH`]: zipsign_api::PUBLIC_KEY_LENGTH
#[cfg(feature = "signatures")]
#[cfg_attr(docsrs, doc(cfg(feature = "signatures")))]
pub use zipsign_api;

/// An ed25519ph verifying key used to validate a signed download (see the `signatures` feature).
///
/// This is a convenience alias for the fixed-size key array accepted by the `verifying_keys`
/// builder methods, so consumers don't need to depend on `zipsign-api` directly.
///
/// # Compile-time embedding
///
/// The typical way to supply a key is to embed it at compile time:
///
/// ```rust,ignore
/// const VERIFYING_KEY: self_update::VerifyingKey =
///     *include_bytes!("path/to/key.pub");
/// ```
///
/// The file must be exactly 32 raw bytes (the ed25519 public key in wire format).
/// zipsign key files are raw 32-byte ed25519 public keys, not PEM.
/// If the file length does not match, Rust will emit a compile error because
/// the array size is fixed at `PUBLIC_KEY_LENGTH` (32).
///
/// # Key rotation
///
/// When rotating signing keys, sign new releases with both the old key and the
/// new key.  Old binaries, which embed only the old key, can still verify and
/// update because the archive carries both signatures.  zipsign uses any-of
/// semantics: verification passes as soon as any (key, signature) pair matches.
/// New binaries embed only the new key.  Once the transition window has passed
/// and no old binaries remain in the field, releases only need the new key's
/// signature.
#[cfg(feature = "signatures")]
#[cfg_attr(docsrs, doc(cfg(feature = "signatures")))]
pub type VerifyingKey = [u8; zipsign_api::PUBLIC_KEY_LENGTH];

#[cfg(feature = "progress-bar")]
use indicatif::{ProgressBar, ProgressStyle as IndicatifProgressStyle};
use log::debug;
#[cfg(feature = "progress-bar")]
use std::cmp::min;
use std::fs;
use std::io;
use std::path;

#[macro_use]
mod macros;
pub mod backends;
pub mod check_interval;
#[cfg(feature = "checksums")]
mod checksum;
pub mod errors;
pub mod http_client;
pub mod restart;
mod tls;
pub mod update;
pub mod version;

/// An opaque TLS root CA certificate, supplied to a backend builder or a [`Download`] via the
/// `add_root_certificate` setter so the crate-built HTTP client trusts a private/internal CA.
/// Construct with [`Certificate::from_pem`](crate::Certificate::from_pem) or
/// [`Certificate::from_der`](crate::Certificate::from_der); the bytes are validated when the client
/// is built, not at construction.
pub use tls::Certificate;

/// Re-export the crate's [`Error`] and [`Result`] at the crate root,
/// so consumers (and `ReleaseSource` implementors) can write `self_update::Result<T>` /
/// `self_update::Error` without naming the `errors` module.
pub use errors::{Error, Result};

/// A checksum variant (`Sha256` / `Sha512`) used with `verify_checksum` to validate a downloaded
/// artifact against a known digest before installation. Requires the `checksums` feature.
#[cfg(feature = "checksums")]
#[cfg_attr(docsrs, doc(cfg(feature = "checksums")))]
pub use checksum::Checksum;

use http_client::header;

/// The User-Agent sent on the crate's own requests (API listings and downloads) when the caller
/// has not set one via `request_header`. One shared value so every backend and the standalone
/// [`Download`] identify themselves the same way regardless of the compiled HTTP client.
pub(crate) const DEFAULT_USER_AGENT: &str = concat!("self-update/", env!("CARGO_PKG_VERSION"));

#[cfg(feature = "progress-bar")]
pub(crate) const DEFAULT_PROGRESS_TEMPLATE: &str =
    "[{elapsed_precise}] [{bar:40}] {bytes}/{total_bytes} ({eta}) {msg}";
#[cfg(feature = "progress-bar")]
pub(crate) const DEFAULT_PROGRESS_CHARS: &str = "=>-";

/// The download progress-bar style: an `indicatif` `template` plus the `chars` it renders the bar
/// with. Requires the `progress-bar` feature.
///
/// This is a typed pair so the two strings can't be transposed at a call site (the previous setter
/// took two `impl Into<String>` args in template-then-chars order, which were easy to swap). Build
/// one with [`ProgressStyle::new`] and pass it to the `Update` builder's `progress_style` or
/// [`Download::progress_style`].
///
/// ```
/// # #[cfg(feature = "progress-bar")] {
/// let style = self_update::ProgressStyle::new(
///     "[{bar:40}] {bytes}/{total_bytes}",
///     "=>-",
/// );
/// # let _ = style;
/// # }
/// ```
#[cfg(feature = "progress-bar")]
#[cfg_attr(docsrs, doc(cfg(feature = "progress-bar")))]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ProgressStyle {
    /// The `indicatif` progress-bar template (see `indicatif::ProgressStyle::template`).
    pub template: String,
    /// The characters used to render the bar (see `indicatif::ProgressStyle::progress_chars`).
    pub chars: String,
}

#[cfg(feature = "progress-bar")]
impl ProgressStyle {
    /// Construct a `ProgressStyle` from a `template` and its progress `chars`.
    pub fn new(template: impl Into<String>, chars: impl Into<String>) -> Self {
        Self {
            template: template.into(),
            chars: chars.into(),
        }
    }
}

/// Get the current target triple.
///
/// Returns a target triple (e.g. `x86_64-unknown-linux-gnu` or `i686-pc-windows-msvc`)
pub fn get_target() -> &'static str {
    env!("TARGET")
}

/// Flush a message to stdout and check if they respond `yes`.
/// Interprets a blank response as yes.
///
/// * Errors:
///     * Io flushing
///     * User entered anything other than enter/Y/y
fn confirm(msg: &str) -> Result<()> {
    print_flush!("{}", msg);

    let mut s = String::new();
    // EOF (closed stdin: a daemon, `</dev/null`, CI) reads zero bytes. Treat it as a decline, not a
    // blank-line "yes", so an unattended caller that forgot `no_confirm` aborts rather than silently
    // proceeding with a self-replacement.
    if io::stdin().read_line(&mut s)? == 0 {
        return Err(Error::Aborted);
    }
    let s = s.trim().to_lowercase();
    if !s.is_empty() && s != "y" {
        return Err(Error::Aborted);
    }
    Ok(())
}

/// The lightweight result of [`update`](update::ReleaseUpdate::update) (and its async sibling
/// `update_async`): it carries only the version tag of the latest release.
///
/// Wrapped `String`s are version tags.
///
/// This is the lightweight counterpart of [`ReleaseStatus`], the richer
/// result of [`update_extended`](update::ReleaseUpdate::update_extended) which carries the full
/// [`Release`] (name, date, body, assets). Reach for `VersionStatus` when the
/// version string is all you need; reach for `ReleaseStatus` when you need the installed release's
/// details.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum VersionStatus {
    UpToDate(String),
    Updated(String),
}
impl VersionStatus {
    /// Return the version tag
    pub fn version(&self) -> &str {
        use VersionStatus::*;
        match *self {
            UpToDate(ref s) => s,
            Updated(ref s) => s,
        }
    }

    /// Returns `true` if `VersionStatus::UpToDate`
    pub fn is_up_to_date(&self) -> bool {
        matches!(*self, VersionStatus::UpToDate(_))
    }

    /// Returns `true` if `VersionStatus::Updated`
    pub fn is_updated(&self) -> bool {
        matches!(*self, VersionStatus::Updated(_))
    }
}

impl std::fmt::Display for VersionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use VersionStatus::*;
        match *self {
            UpToDate(ref s) => write!(f, "UpToDate({})", s),
            Updated(ref s) => write!(f, "Updated({})", s),
        }
    }
}

/// The archive format of a release asset, as detected from its file extension.
///
/// `#[non_exhaustive]`, and the `Tar`/`Zip` variants are gated on the `archive-tar` / `archive-zip`
/// features: if the matching feature is off the variant does not exist and `detect_archive` for
/// that extension returns [`Error::ArchiveNotEnabled`] instead.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum ArchiveKind {
    /// A tarball, optionally compressed (e.g. `.tar`, `.tar.gz`, `.tar.xz`). Requires `archive-tar`.
    #[cfg(feature = "archive-tar")]
    #[cfg_attr(docsrs, doc(cfg(feature = "archive-tar")))]
    Tar(Option<Compression>),
    /// A bare file, optionally compressed (e.g. a plain binary, or a `.gz` / `.xz` of one).
    Plain(Option<Compression>),
    /// A zip archive (`.zip`). Requires `archive-zip`.
    #[cfg(feature = "archive-zip")]
    #[cfg_attr(docsrs, doc(cfg(feature = "archive-zip")))]
    Zip,
}

impl std::fmt::Display for ArchiveKind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            #[cfg(feature = "archive-tar")]
            ArchiveKind::Tar(Some(Compression::Gz)) => write!(f, "tar.gz"),
            #[cfg(feature = "archive-tar")]
            ArchiveKind::Tar(Some(Compression::Xz)) => write!(f, "tar.xz"),
            #[cfg(feature = "archive-tar")]
            ArchiveKind::Tar(None) => write!(f, "tar"),
            ArchiveKind::Plain(Some(Compression::Gz)) => write!(f, "gz"),
            ArchiveKind::Plain(Some(Compression::Xz)) => write!(f, "xz"),
            ArchiveKind::Plain(None) => write!(f, "plain"),
            #[cfg(feature = "archive-zip")]
            ArchiveKind::Zip => write!(f, "zip"),
        }
    }
}

/// A compression codec applied to an [`ArchiveKind`]. `#[non_exhaustive]`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Compression {
    /// gzip (`.gz`); decoding the stream requires the `compression-tar-gz` feature.
    Gz,
    /// xz / LZMA2 (`.xz`); decoding the stream requires the `compression-tar-xz` feature.
    Xz,
}

fn detect_archive(path: &path::Path) -> Result<ArchiveKind> {
    let ext = path.extension();

    debug!("Detecting archive type using extension: {:?}", ext);

    let res = match ext {
        Some(extension) if extension == std::ffi::OsStr::new("zip") => {
            #[cfg(feature = "archive-zip")]
            {
                debug!("Detected .zip archive");
                Ok(ArchiveKind::Zip)
            }
            #[cfg(not(feature = "archive-zip"))]
            {
                Err(Error::ArchiveNotEnabled("zip".to_string()))
            }
        }
        Some(extension) if extension == std::ffi::OsStr::new("tar") => {
            #[cfg(feature = "archive-tar")]
            {
                debug!("Detected .tar archive");
                Ok(ArchiveKind::Tar(None))
            }
            #[cfg(not(feature = "archive-tar"))]
            {
                Err(Error::ArchiveNotEnabled("tar".to_string()))
            }
        }
        Some(extension) if extension == std::ffi::OsStr::new("tgz") => {
            #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
            {
                debug!("Detected .tgz archive");
                Ok(ArchiveKind::Tar(Some(Compression::Gz)))
            }
            #[cfg(all(feature = "archive-tar", not(feature = "compression-tar-gz")))]
            {
                Err(Error::CompressionNotEnabled("gz".to_string()))
            }
            #[cfg(not(feature = "archive-tar"))]
            {
                Err(Error::ArchiveNotEnabled("tar".to_string()))
            }
        }
        Some(extension) if extension == std::ffi::OsStr::new("gz") => match path
            .file_stem()
            .map(path::Path::new)
            .and_then(|f| f.extension())
        {
            Some(extension) if extension == std::ffi::OsStr::new("tar") => {
                #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
                {
                    debug!("Detected .tar.gz archive");
                    Ok(ArchiveKind::Tar(Some(Compression::Gz)))
                }
                #[cfg(all(feature = "archive-tar", not(feature = "compression-tar-gz")))]
                {
                    Err(Error::CompressionNotEnabled("gz".to_string()))
                }
                #[cfg(not(feature = "archive-tar"))]
                {
                    Err(Error::ArchiveNotEnabled("tar".to_string()))
                }
            }
            // A plain `.gz` single-file asset: decoding the gzip layer requires the
            // `compression-tar-gz` feature. Without it, refuse rather than installing the still
            // compressed bytes as the binary.
            _ => {
                #[cfg(feature = "compression-tar-gz")]
                {
                    Ok(ArchiveKind::Plain(Some(Compression::Gz)))
                }
                #[cfg(not(feature = "compression-tar-gz"))]
                {
                    Err(Error::CompressionNotEnabled("gz".to_string()))
                }
            }
        },
        Some(extension) if extension == std::ffi::OsStr::new("txz") => {
            #[cfg(all(feature = "archive-tar", feature = "compression-tar-xz"))]
            {
                debug!("Detected .txz archive");
                Ok(ArchiveKind::Tar(Some(Compression::Xz)))
            }
            #[cfg(all(feature = "archive-tar", not(feature = "compression-tar-xz")))]
            {
                Err(Error::CompressionNotEnabled("xz".to_string()))
            }
            #[cfg(not(feature = "archive-tar"))]
            {
                Err(Error::ArchiveNotEnabled("tar".to_string()))
            }
        }
        Some(extension) if extension == std::ffi::OsStr::new("xz") => match path
            .file_stem()
            .map(path::Path::new)
            .and_then(|f| f.extension())
        {
            Some(extension) if extension == std::ffi::OsStr::new("tar") => {
                #[cfg(all(feature = "archive-tar", feature = "compression-tar-xz"))]
                {
                    debug!("Detected .tar.xz archive");
                    Ok(ArchiveKind::Tar(Some(Compression::Xz)))
                }
                #[cfg(all(feature = "archive-tar", not(feature = "compression-tar-xz")))]
                {
                    Err(Error::CompressionNotEnabled("xz".to_string()))
                }
                #[cfg(not(feature = "archive-tar"))]
                {
                    Err(Error::ArchiveNotEnabled("tar".to_string()))
                }
            }
            // A plain `.xz` single-file asset: decoding the xz layer requires the
            // `compression-tar-xz` feature. Without it, refuse rather than installing the still
            // compressed bytes as the binary.
            _ => {
                #[cfg(feature = "compression-tar-xz")]
                {
                    Ok(ArchiveKind::Plain(Some(Compression::Xz)))
                }
                #[cfg(not(feature = "compression-tar-xz"))]
                {
                    Err(Error::CompressionNotEnabled("xz".to_string()))
                }
            }
        },
        _ => Ok(ArchiveKind::Plain(None)),
    };

    debug!("Detected archive type: {:?}", res);

    res
}

/// Extract contents of an encoded archive (e.g. tar.gz) file to a specified directory
///
/// * Errors:
///     * Io - opening files
///     * Io - gzip decoding
///     * Io - archive unpacking
#[derive(Debug)]
#[non_exhaustive]
pub struct Extract {
    source: path::PathBuf,
    archive: Option<ArchiveKind>,
}
/// A [`Read`](io::Read) over an archive's bytes with any single compression layer (`.gz`, `.xz`)
/// transparently decoded, so the tar/plain readers above it see the decompressed stream. `Plain`
/// is the undecoded passthrough. Each compressed variant exists only when its `compression-tar-*`
/// feature is enabled; [`detect_archive`] rejects a compression whose feature is off before this
/// is ever built. The gzip layer decodes as a stream; the xz layer is decoded up front into memory
/// (the `lzma-rs` decoder is one-shot), which is fine for the modestly sized release artifacts this
/// crate downloads to a temp file.
enum ArchiveReader {
    Plain(fs::File),
    // Boxed: a `GzDecoder` is far larger than the other variants, so an unboxed variant would bloat
    // every `ArchiveReader` to its size (clippy::large_enum_variant).
    #[cfg(feature = "compression-tar-gz")]
    Gz(Box<flate2::read::GzDecoder<fs::File>>),
    #[cfg(feature = "compression-tar-xz")]
    Xz(io::Cursor<Vec<u8>>),
}

impl io::Read for ArchiveReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            ArchiveReader::Plain(r) => r.read(buf),
            #[cfg(feature = "compression-tar-gz")]
            ArchiveReader::Gz(r) => r.read(buf),
            #[cfg(feature = "compression-tar-xz")]
            ArchiveReader::Xz(r) => r.read(buf),
        }
    }
}

impl Extract {
    /// Create an `Extract`or from a source path. Accepts anything path-like (`&Path`, `PathBuf`,
    /// `&str`, …), storing an owned [`PathBuf`](std::path::PathBuf).
    pub fn from_source(source: impl AsRef<path::Path>) -> Extract {
        Self {
            source: source.as_ref().to_path_buf(),
            archive: None,
        }
    }

    /// Specify an archive format of the source being extracted. If not specified, the
    /// archive format will determined from the file extension.
    pub fn archive(&mut self, kind: ArchiveKind) -> &mut Self {
        self.archive = Some(kind);
        self
    }

    #[allow(unused_variables)]
    fn get_archive_reader(
        source: fs::File,
        compression: Option<Compression>,
    ) -> Result<ArchiveReader> {
        match compression {
            None => Ok(ArchiveReader::Plain(source)),
            #[cfg(feature = "compression-tar-gz")]
            Some(Compression::Gz) => Ok(ArchiveReader::Gz(Box::new(flate2::read::GzDecoder::new(
                source,
            )))),
            #[cfg(feature = "compression-tar-xz")]
            Some(Compression::Xz) => {
                // `lzma-rs` is a one-shot decoder (no streaming `Read` adapter), so decode the
                // whole `.xz` stream into memory and hand the tar/plain layer a cursor over it.
                let mut input = io::BufReader::new(source);
                let mut decoded = Vec::new();
                lzma_rs::xz_decompress(&mut input, &mut decoded).map_err(|e| Error::Internal {
                    message: format!("failed to decode xz stream: {e}"),
                    source: None,
                })?;
                Ok(ArchiveReader::Xz(io::Cursor::new(decoded)))
            }
            // A compression whose decoder feature is disabled is rejected by `detect_archive`
            // before extraction, so this is unreachable in practice.
            #[allow(unreachable_patterns)]
            Some(_) => Err(Error::CompressionNotEnabled("unsupported".to_string())),
        }
    }

    /// Extract an entire source archive into a specified path. If the source is a single compressed
    /// file and not an archive, it will be extracted into a file with the same name inside of
    /// `into_dir`.
    ///
    /// # Symlink handling
    ///
    /// Zip entries that are symbolic links (their unix mode carries `S_IFLNK`) are restored as
    /// real symlinks on unix, with the link target read from the entry contents. This preserves
    /// directory trees that rely on symlinks (for example a macOS `.app` bundle whose
    /// `Frameworks/*/Versions/Current` links are load-bearing for code signatures) instead of
    /// materializing the target string as a regular file. A symlink target that would escape the
    /// extraction root -- an absolute target, or a relative target whose `..` components resolve
    /// above `into_dir` -- is rejected with an error, mirroring the zip-slip defense applied to
    /// entry names.
    ///
    /// That per-entry target check is purely lexical, so it cannot see a symlinked intermediate
    /// directory that aliases an entry's parent to a shallower physical path (the classic
    /// symlinked-parent traversal: an entry `d/sl -> ..` followed by `d/sl/evil -> ../../x`, where
    /// the second link is lexically in-bounds yet physically lands above the root). As a backstop,
    /// for every zip entry -- symlink or regular file -- after its parent directories are
    /// materialized the physical parent is canonicalized and must equal the canonical extraction
    /// root joined with the entry's lexical parent; any descent through a symlinked ancestor (or a
    /// canonicalize failure) is rejected with an `Error::Internal`, while descent through real
    /// directories is unaffected.
    ///
    /// On non-unix platforms (creating symlinks requires elevated privileges on Windows) symlink
    /// entries are written as regular files containing the target path. Tar archives restore
    /// symlinks via `tar`'s own unpack logic.
    pub fn extract_into(&self, into_dir: impl AsRef<path::Path>) -> Result<()> {
        let into_dir = into_dir.as_ref();
        let source = fs::File::open(&self.source)?;
        let archive = match self.archive {
            Some(archive) => archive,
            None => detect_archive(&self.source)?,
        };

        // We cannot use a feature flag in a match arm. To bypass this the code block is
        // isolated in a closure and called accordingly.
        let extract_into_plain_or_tar = |source: fs::File, compression: Option<Compression>| {
            let mut reader = Self::get_archive_reader(source, compression)?;

            match archive {
                ArchiveKind::Plain(_) => {
                    match fs::create_dir_all(into_dir) {
                        Ok(_) => (),
                        Err(e) => {
                            if e.kind() != io::ErrorKind::AlreadyExists {
                                return Err(Error::Io(e));
                            }
                        }
                    }
                    let file_name = self.source.file_name().ok_or_else(|| Error::Internal {
                        message: "Extractor source has no file-name".to_string(),
                        source: None,
                    })?;
                    let mut out_path = into_dir.join(file_name);
                    out_path.set_extension("");
                    let mut out_file = fs::File::create(&out_path)?;
                    io::copy(&mut reader, &mut out_file)?;
                }
                #[cfg(feature = "archive-tar")]
                ArchiveKind::Tar(_) => {
                    let mut archive = tar::Archive::new(reader);
                    archive.unpack(into_dir)?;
                }
                #[allow(unreachable_patterns)]
                _ => unreachable!(
                    "detect_archive() returns in case the proper feature flag is not enabled"
                ),
            };

            Ok(())
        };

        match archive {
            #[cfg(feature = "archive-tar")]
            ArchiveKind::Plain(compression) | ArchiveKind::Tar(compression) => {
                extract_into_plain_or_tar(source, compression)?;
            }
            #[cfg(not(feature = "archive-tar"))]
            ArchiveKind::Plain(compression) => {
                extract_into_plain_or_tar(source, compression)?;
            }
            #[cfg(feature = "archive-zip")]
            ArchiveKind::Zip => {
                let mut archive = zip::ZipArchive::new(source)?;

                // The destination must exist so its canonical (symlink-free) form can be
                // captured once up front. Each entry's physical parent is later checked against
                // this root to reject any descent through a symlinked directory (the
                // symlinked-parent traversal that a per-entry lexical check cannot catch).
                fs::create_dir_all(into_dir)?;
                let canonical_root = fs::canonicalize(into_dir)?;

                for i in 0..archive.len() {
                    let mut file = archive.by_index(i)?;

                    // Reject entries whose name would escape `into_dir` (zip-slip). `enclosed_name`
                    // returns `None` for an absolute path or one containing `..`.
                    let Some(rel_path) = file.enclosed_name() else {
                        return Err(Error::Internal {
                            message: format!(
                                "zip entry has an unsafe path: {:?}",
                                String::from_utf8_lossy(file.name_raw())
                            ),
                            source: None,
                        });
                    };
                    let output_path = into_dir.join(&rel_path);

                    if file.is_dir() {
                        fs::create_dir_all(&output_path)?;
                        continue;
                    }
                    if let Some(parent_dir) = output_path.parent() {
                        match fs::create_dir_all(parent_dir) {
                            Ok(()) => {}
                            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
                            Err(e) => return Err(Error::Io(e)),
                        }

                        // Physical-parent verification (symlinked-parent traversal defense).
                        // The per-entry lexical target check cannot catch an intermediate
                        // symlinked directory (e.g. an earlier `d/sl -> ..` entry) that aliases
                        // this entry's parent to a shallower real path, which would let a later
                        // entry be created outside the root through the alias. After the parents
                        // are materialized, require the parent to canonicalize to exactly its
                        // expected location: the canonical root joined with the entry's lexical
                        // (only-`Normal`) parent. A prefix/`start_with` check alone is
                        // insufficient -- `d/sl` canonicalizes to the root, which trivially lies
                        // within the root -- so compare for equality: real directories match
                        // their lexical path, while any symlinked ancestor resolves elsewhere and
                        // is rejected. A canonicalize failure is treated as a rejection too,
                        // matching the zip-slip/escape error style. This guards both the
                        // symlink-creation path and the regular-file path below.
                        let lexical_parent =
                            rel_path.parent().unwrap_or_else(|| path::Path::new(""));
                        let expected_parent = canonical_root.join(lexical_parent);
                        let physical_parent =
                            fs::canonicalize(parent_dir).map_err(|e| Error::Internal {
                                message: format!(
                                    "could not resolve the parent directory of zip entry {:?}: {}",
                                    String::from_utf8_lossy(file.name_raw()),
                                    e
                                ),
                                source: Some(Box::new(e)),
                            })?;
                        if physical_parent != expected_parent {
                            return Err(Error::Internal {
                                message: format!(
                                    "zip entry {:?} descends through a symlinked directory that escapes the extraction dir",
                                    String::from_utf8_lossy(file.name_raw())
                                ),
                                source: None,
                            });
                        }
                    }

                    // On unix, restore a symlink entry as a real symlink instead of writing its
                    // target string out as a regular file. The escaping-target check mirrors the
                    // `enclosed_name` zip-slip defense above. On non-unix targets this block is
                    // compiled out and the entry falls through to the regular-file path.
                    #[cfg(unix)]
                    if file.is_symlink() {
                        use std::ffi::OsStr;
                        use std::io::Read;
                        use std::os::unix::ffi::OsStrExt;

                        let entry_name = String::from_utf8_lossy(file.name_raw()).into_owned();
                        let mut target_bytes = Vec::new();
                        file.read_to_end(&mut target_bytes)?;
                        let target = path::Path::new(OsStr::from_bytes(&target_bytes));

                        // The link lives at `into_dir/rel_path`; a relative target resolves against
                        // the link's parent directory. Reject any target (absolute, or `..`
                        // climbing above `into_dir`) whose lexical resolution escapes the root.
                        let link_parent = rel_path.parent().unwrap_or_else(|| path::Path::new(""));
                        if symlink_target_escapes(link_parent, target) {
                            return Err(Error::Internal {
                                message: format!(
                                    "zip symlink entry {:?} points outside the extraction dir: {:?}",
                                    entry_name, target
                                ),
                                source: None,
                            });
                        }

                        // A duplicate entry may already have created a file/link here; `symlink`
                        // fails on an existing path, so remove it first (regular-file entries
                        // truncate via `File::create`, so match that "last entry wins" behavior).
                        match fs::remove_file(&output_path) {
                            Ok(()) => {}
                            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                            Err(e) => return Err(Error::Io(e)),
                        }
                        std::os::unix::fs::symlink(target, &output_path)?;
                        // A symlink carries no meaningful permission bits of its own; do not call
                        // `set_permissions` (it would follow the link and alter the target).
                        continue;
                    }

                    let mut output = fs::File::create(&output_path)?;
                    io::copy(&mut file, &mut output)?;
                    // Preserve the archived unix permission mode (notably the executable bit) so a
                    // binary extracted from a zip is runnable when installed to a custom path.
                    // Mask off the setuid/setgid/sticky bits (`0o7000`): a crafted archive must not
                    // be able to install a setuid binary, so only the standard `rwx` permission
                    // bits (`0o777`) are honored.
                    #[cfg(unix)]
                    if let Some(mode) = file.unix_mode() {
                        use std::os::unix::fs::PermissionsExt;
                        fs::set_permissions(
                            &output_path,
                            fs::Permissions::from_mode(mode & 0o777),
                        )?;
                    }
                }
            }
        };
        Ok(())
    }

    /// Extract a single file from a source and save to a file of the same name in `into_dir`.
    /// If the source is a single compressed file, it will be saved with the name `file_to_extract`
    /// in the specified `into_dir`.
    ///
    /// The lookup ignores a leading `./` on either side, so `bin_path_in_archive("app")` finds an
    /// entry stored as `./app`. `tar -czf a.tar.gz -C dir .` (the usual "archive this directory"
    /// invocation) names every entry that way, and the archive is otherwise indistinguishable from
    /// one built with `tar -czf a.tar.gz *`.
    ///
    /// If the named zip entry is a symbolic link (its unix mode carries `S_IFLNK`), extraction
    /// fails with an error rather than writing the link's target string out as the requested file:
    /// this API returns a single concrete file, and silently substituting the target path text for
    /// the payload would be surprising. Callers who need symlinks preserved should use
    /// [`extract_into`](Self::extract_into), which restores them as real links on unix.
    pub fn extract_file<T: AsRef<path::Path>>(
        &self,
        into_dir: impl AsRef<path::Path>,
        file_to_extract: T,
    ) -> Result<()> {
        let into_dir = into_dir.as_ref();
        let file_to_extract = file_to_extract.as_ref();
        let source = fs::File::open(&self.source)?;
        let archive = match self.archive {
            Some(archive) => archive,
            None => detect_archive(&self.source)?,
        };

        debug!(
            "Attempting to extract {:?} file from {:?}",
            file_to_extract, self.source
        );

        // We cannot use a feature flag in a match arm. To bypass this the code block is
        // isolated in a closure and called accordingly.
        let extract_file_plain_or_tar = |source: fs::File, compression: Option<Compression>| {
            let mut reader = Self::get_archive_reader(source, compression)?;

            match archive {
                ArchiveKind::Plain(_) => {
                    debug!("Copying file directly");
                    match fs::create_dir_all(into_dir) {
                        Ok(_) => (),
                        Err(e) => {
                            if e.kind() != io::ErrorKind::AlreadyExists {
                                return Err(Error::Io(e));
                            }
                        }
                    }
                    let file_name = file_to_extract.file_name().ok_or_else(|| Error::Internal {
                        message: "Extractor source has no file-name".to_string(),
                        source: None,
                    })?;
                    let out_path = into_dir.join(file_name);
                    let mut out_file = fs::File::create(out_path)?;
                    io::copy(&mut reader, &mut out_file)?;
                }
                #[cfg(feature = "archive-tar")]
                ArchiveKind::Tar(_) => {
                    debug!("Extracting from tar");

                    let mut archive = tar::Archive::new(reader);
                    let mut entry = archive
                        .entries()?
                        .filter_map(|e| e.ok())
                        .find(|e| {
                            let p = e.path();
                            debug!("Archive path: {:?}", p);
                            p.ok()
                                .filter(|p| archive_path_matches(p, file_to_extract))
                                .is_some()
                        })
                        .ok_or_else(|| Error::Internal {
                            message: format!(
                                "Could not find the required path in the archive: {:?}",
                                file_to_extract
                            ),
                            source: None,
                        })?;
                    entry.unpack_in(into_dir)?;
                }
                #[allow(unreachable_patterns)]
                _ => unreachable!(
                    "detect_archive() returns in case the proper feature flag is not enabled"
                ),
            };

            Ok(())
        };

        match archive {
            #[cfg(feature = "archive-tar")]
            ArchiveKind::Plain(compression) | ArchiveKind::Tar(compression) => {
                extract_file_plain_or_tar(source, compression)?;
            }
            #[cfg(not(feature = "archive-tar"))]
            ArchiveKind::Plain(compression) => {
                extract_file_plain_or_tar(source, compression)?;
            }
            #[cfg(feature = "archive-zip")]
            ArchiveKind::Zip => {
                let mut archive = zip::ZipArchive::new(source)?;
                let file_name = file_to_extract.to_str().ok_or_else(|| Error::Internal {
                    message: format!(
                        "cannot extract file with a non-UTF-8 path: {:?}",
                        file_to_extract
                    ),
                    source: None,
                })?;
                // `by_name` is an exact string match, so resolve the entry through the same
                // `./`-tolerant comparison the tar arm uses. Falling back to the requested name
                // when nothing matches keeps the original `ZipError::FileNotFound` for the
                // genuinely-missing case. An entry whose name fails to decode cannot match the
                // UTF-8 `file_name`, so it is skipped.
                let entry_name = archive
                    .file_names()
                    .filter_map(|name| name.ok())
                    .find(|name| {
                        archive_path_matches(path::Path::new(name.as_ref()), file_to_extract)
                    })
                    .map(std::borrow::Cow::into_owned)
                    .unwrap_or_else(|| file_name.to_string());
                let mut file = archive.by_name(&entry_name)?;

                let Some(rel_path) = file.enclosed_name() else {
                    return Err(Error::Internal {
                        message: format!(
                            "zip entry has an unsafe path: {:?}",
                            String::from_utf8_lossy(file.name_raw())
                        ),
                        source: None,
                    });
                };
                // A symlink entry has no regular-file payload; its "contents" are the link target
                // path. Rather than write that target string out as `file_to_extract`, reject it
                // (see the rustdoc): use `extract_into` to restore symlinks. Rejecting on every
                // platform keeps the single-file API's behavior uniform.
                if file.is_symlink() {
                    return Err(Error::Internal {
                        message: format!(
                            "zip entry {:?} is a symlink; use extract_into to restore symlinks",
                            String::from_utf8_lossy(file.name_raw())
                        ),
                        source: None,
                    });
                }

                let output_path = into_dir.join(rel_path);
                if let Some(parent_dir) = output_path.parent()
                    && let Err(e) = fs::create_dir_all(parent_dir)
                    && e.kind() != io::ErrorKind::AlreadyExists
                {
                    return Err(Error::Io(e));
                }

                let mut output = fs::File::create(&output_path)?;
                io::copy(&mut file, &mut output)?;
                // Preserve the archived unix permission mode so the extracted binary is runnable,
                // but mask off the setuid/setgid/sticky bits (`0o7000`) so a crafted archive cannot
                // install a setuid binary; only the standard `rwx` bits (`0o777`) are honored.
                #[cfg(unix)]
                if let Some(mode) = file.unix_mode() {
                    use std::os::unix::fs::PermissionsExt;
                    fs::set_permissions(&output_path, fs::Permissions::from_mode(mode & 0o777))?;
                }
            }
        };
        Ok(())
    }
}

/// Whether an archive entry's path names the file the caller asked for, ignoring a leading `./` on
/// either side.
///
/// `tar -czf archive.tar.gz -C dir .` stores every entry as `./name`, while `tar -czf archive.tar.gz
/// *` stores it as `name`; the caller writes `bin_path_in_archive` the way the file is named and
/// cannot be expected to know which invocation produced the release artifact. Only a leading `./`
/// is stripped: interior components are compared exactly, so this cannot match a different file.
fn archive_path_matches(entry: &path::Path, wanted: &path::Path) -> bool {
    fn strip_curdir(p: &path::Path) -> &path::Path {
        p.strip_prefix(".").unwrap_or(p)
    }
    strip_curdir(entry) == strip_curdir(wanted)
}

/// Lexically decide whether a zip symlink target escapes the extraction root.
///
/// `link_parent` is the link entry's parent directory expressed relative to the extraction root
/// (derived from the already zip-slip-checked entry name, so it contains only normal components).
/// `target` is the raw link target read from the entry contents. Returns `true` if the target is
/// absolute or if resolving its `..`/`.` components against `link_parent` climbs above the root.
/// This is a purely lexical check (no filesystem access), matching the intent of the
/// `enclosed_name` defense used for entry names.
#[cfg(all(feature = "archive-zip", unix))]
fn symlink_target_escapes(link_parent: &path::Path, target: &path::Path) -> bool {
    use std::path::Component;

    // Seed the virtual stack with the link's parent directory (only normal components).
    let mut depth: usize = 0;
    for comp in link_parent.components() {
        match comp {
            Component::Normal(_) => depth += 1,
            Component::CurDir => {}
            // `link_parent` comes from an enclosed (relative, `..`-free) name, so other
            // components should not occur; treat any as unsafe to be conservative.
            _ => return true,
        }
    }

    for comp in target.components() {
        match comp {
            Component::Normal(_) => depth += 1,
            Component::CurDir => {}
            Component::ParentDir => {
                // Climbing above the root escapes the extraction dir.
                let Some(next) = depth.checked_sub(1) else {
                    return true;
                };
                depth = next;
            }
            // An absolute target (root dir or a drive prefix) always escapes.
            Component::RootDir | Component::Prefix(_) => return true,
        }
    }

    false
}

/// Moves a file from the given path to the specified destination.
///
/// `source` and `dest` must be on the same filesystem.
/// If `replace_using_temp` is specified, the destination file will be
/// replaced using the given temporary path.
/// If the existing `dest` file is a currently running long running program,
/// `replace_using_temp` may run into errors cleaning up the temp dir.
/// If that's the case for your use-case, consider not specifying a temp dir to use.
///
/// * Errors:
///     * Io - copying / renaming
#[derive(Debug)]
#[non_exhaustive]
pub struct Move {
    source: path::PathBuf,
    temp: Option<path::PathBuf>,
}
impl Move {
    /// Specify source file. Accepts anything path-like, storing an owned
    /// [`PathBuf`](std::path::PathBuf).
    pub fn from_source(source: impl AsRef<path::Path>) -> Move {
        Self {
            source: source.as_ref().to_path_buf(),
            temp: None,
        }
    }

    /// If specified and the destination file already exists, the "destination"
    /// file will be moved to the given temporary location before the "source"
    /// file is moved to the "destination" file.
    ///
    /// In the event of an `io` error while renaming "source" to "destination",
    /// the temporary file will be moved back to "destination".
    ///
    /// The `temp` dir must be explicitly provided since `rename` operations require
    /// files to live on the same filesystem.
    pub fn replace_using_temp(&mut self, temp: impl AsRef<path::Path>) -> &mut Self {
        self.temp = Some(temp.as_ref().to_path_buf());
        self
    }

    /// Move source file to specified destination
    pub fn to_dest(&self, dest: impl AsRef<path::Path>) -> Result<()> {
        let dest = dest.as_ref();
        match self.temp.as_deref() {
            // Move the existing dest to a temp location so we can move it back if
            // there's an error. If the existing `dest` file is a long running program,
            // this may prevent the temp dir from being cleaned up.
            Some(temp) if dest.exists() => {
                fs::rename(dest, temp)?;
                if let Err(e) = fs::rename(&self.source, dest) {
                    fs::rename(temp, dest)?;
                    return Err(Error::from(e));
                }
            }
            // No temp set, or nothing to preserve at `dest`: just move source into place.
            _ => {
                rename_or_copy(&self.source, dest)?;
            }
        };
        Ok(())
    }
}

/// Rename `source` onto `dest`, falling back to copy when the two are on different filesystems.
///
/// The extraction temp dir is often a tmpfs on Linux while `bin_install_path` lives on the root
/// filesystem, so a plain `fs::rename` returns `CrossesDevices` (EXDEV). On that error the source is
/// copied to a temporary file beside `dest` (same filesystem, so the following rename is atomic),
/// renamed over `dest`, and the original source removed. `fs::copy` preserves the source's
/// permission mode.
fn rename_or_copy(source: &path::Path, dest: &path::Path) -> Result<()> {
    match fs::rename(source, dest) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
            let tmp = match dest.file_name() {
                Some(name) => {
                    let mut n = name.to_os_string();
                    n.push(".self_update.tmp");
                    dest.with_file_name(n)
                }
                None => return Err(Error::from(e)),
            };
            fs::copy(source, &tmp)?;
            if let Err(rename_err) = fs::rename(&tmp, dest) {
                let _ = fs::remove_file(&tmp);
                return Err(Error::from(rename_err));
            }
            let _ = fs::remove_file(source);
            Ok(())
        }
        Err(e) => Err(Error::from(e)),
    }
}

/// Transactionally install a *set* of files: either every `(source -> dest)` move is applied, or
/// — on the first failure — all already-applied moves are rolled back, restoring every
/// destination to its prior contents. Use it to update a tool that ships more than one file (a
/// binary plus sidecar libraries/resources) without risking a half-applied update.
///
/// This is the multi-file analogue of [`Move`]. It relies on `rename`, so **every source, every
/// destination, and the `temp` directory must live on the same filesystem** (the same constraint
/// [`Move::replace_using_temp`] has) — in particular the staging dir holding the files you `add`
/// must be co-located with the destinations, not in `$TMPDIR`. The `temp` directory is used to
/// stash each displaced destination so it can be restored on rollback; a [`tempfile::TempDir`] is a
/// convenient choice.
///
/// [`commit`](Self::commit) drains the queued moves as it applies them, so a `MoveAll` is
/// single-use: a second `commit` has nothing left to do and is a no-op returning `Ok(())`. Rollback
/// is best-effort — if a rollback step itself fails it is logged via `log::error!` rather than
/// surfaced, and the error returned to the caller is always the original one that triggered the
/// rollback.
///
/// ```no_run
/// # fn run() -> Result<(), Box<dyn std::error::Error>> {
/// // The stash dir must be on the same filesystem as the destinations (rename can't cross
/// // filesystems), so create it next to them rather than in $TMPDIR.
/// let tmp = tempfile::TempDir::new_in("/usr/local")?;
/// // `new_bin` / `new_lib` are files you already extracted into a staging dir, which must
/// // also be on the destination filesystem (the sources are renamed into place too).
/// let staging = tempfile::TempDir::new_in("/usr/local")?;
/// let new_bin = staging.path().join("app");
/// let new_lib = staging.path().join("libapp.so");
/// self_update::MoveAll::from_temp(tmp.path())
///     .add(new_bin, "/usr/local/bin/app")
///     .add(new_lib, "/usr/local/lib/libapp.so")
///     .commit()?; // all-or-nothing
/// # Ok(())
/// # }
/// ```
///
/// * Errors:
///     * Io - renaming a source into place or stashing an existing destination
#[derive(Debug)]
#[must_use = "queued moves are only applied when `.commit()` is called"]
#[non_exhaustive]
pub struct MoveAll {
    temp: path::PathBuf,
    moves: Vec<(path::PathBuf, path::PathBuf)>,
}

impl MoveAll {
    /// Start a transactional install, stashing displaced destinations under `temp` so they can be
    /// restored if a later move fails. `temp` must be on the same filesystem as every destination.
    /// Accepts anything path-like, storing an owned [`PathBuf`](std::path::PathBuf).
    pub fn from_temp(temp: impl AsRef<path::Path>) -> Self {
        Self {
            temp: temp.as_ref().to_path_buf(),
            moves: Vec::new(),
        }
    }

    /// Queue a `source -> dest` move. Moves are applied by [`commit`](Self::commit) in the order
    /// added.
    pub fn add(
        &mut self,
        source: impl AsRef<path::Path>,
        dest: impl AsRef<path::Path>,
    ) -> &mut Self {
        self.moves
            .push((source.as_ref().to_path_buf(), dest.as_ref().to_path_buf()));
        self
    }

    /// Apply every queued move. On success all destinations have been replaced. On the first
    /// failure, every already-applied move (and the failing one's partial state) is rolled back so
    /// each destination is left with its original contents, and the underlying error is returned.
    ///
    /// The queued moves are drained as they are applied, so calling `commit` again is a no-op that
    /// returns `Ok(())`.
    pub fn commit(&mut self) -> Result<()> {
        // Drain the queue so a second `commit` is a no-op rather than re-running already-applied
        // moves against now-missing sources.
        let moves = std::mem::take(&mut self.moves);

        // For each applied move we remember the destination and where its previous contents (if
        // any) were stashed, so a later failure can restore them in reverse order.
        let mut applied: Vec<Applied> = Vec::with_capacity(moves.len());

        for (i, (source, dest)) in moves.iter().enumerate() {
            // Stash an existing destination so we can move it back on rollback.
            let stash = if dest.exists() {
                let stash = self.temp.join(format!("self_update-stash-{i}"));
                if let Err(e) = fs::rename(dest, &stash) {
                    rollback(&applied);
                    return Err(Error::from(e));
                }
                Some(stash)
            } else {
                None
            };

            // Move the new file into place.
            if let Err(e) = fs::rename(source, dest) {
                // Undo this step's stash before rolling back the earlier ones.
                if let Some(stash) = &stash
                    && let Err(restore_err) = fs::rename(stash, dest)
                {
                    log::error!(
                        "failed to restore {} from stash {} during rollback: {}",
                        dest.display(),
                        stash.display(),
                        restore_err
                    );
                }
                rollback(&applied);
                return Err(Error::from(e));
            }

            applied.push(Applied {
                dest: dest.clone(),
                stash,
            });
        }

        Ok(())
    }
}

/// A move that [`MoveAll::commit`] has applied, retained so it can be undone on a later failure.
#[derive(Debug)]
struct Applied {
    dest: path::PathBuf,
    stash: Option<path::PathBuf>,
}

/// Best-effort rollback of already-applied moves, in reverse order. For a destination that
/// previously existed, the stashed original is `rename`d back over the newly installed file — a
/// single atomic replace (the same technique [`Move::replace_using_temp`] uses), so the original
/// is never deleted before its restore can fail. For a destination that didn't previously exist
/// (a fresh install), the newly installed file is simply removed. Rollback failures are logged
/// rather than propagated — the original error that triggered the rollback is what callers see.
fn rollback(applied: &[Applied]) {
    for entry in applied.iter().rev() {
        match &entry.stash {
            // Previously existed: atomically restore the original over the new file.
            Some(stash) => {
                if let Err(e) = fs::rename(stash, &entry.dest) {
                    log::error!(
                        "failed to restore {} from stash {} during rollback: {}",
                        entry.dest.display(),
                        stash.display(),
                        e
                    );
                }
            }
            // Fresh install (nothing to restore): remove the file we added.
            None => {
                if let Err(e) = fs::remove_file(&entry.dest) {
                    log::error!(
                        "failed to remove {} during rollback: {}",
                        entry.dest.display(),
                        e
                    );
                }
            }
        }
    }
}

/// A download-progress callback: `(bytes_downloaded_so_far, total_bytes_if_known)`.
pub(crate) type DynProgressFn = dyn Fn(u64, Option<u64>) + Send + Sync;

/// Wrapper around a [`DynProgressFn`] so structs holding one can still derive `Clone`/`Debug`.
#[derive(Clone)]
pub(crate) struct ProgressCallback(pub(crate) std::sync::Arc<DynProgressFn>);

impl std::fmt::Debug for ProgressCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ProgressCallback(..)")
    }
}

/// A post-update verification callback: given the path to the freshly-extracted binary (before it
/// is installed), returns `Ok(())` to accept it or `Err(..)` to reject it (aborting the update). A
/// returned error's message is carried as the reason of the resulting
/// [`Error::VerificationRejected`](errors::Error::VerificationRejected).
pub(crate) type DynVerifyFn = dyn Fn(&std::path::Path) -> Result<()> + Send + Sync;

/// Wrapper around a [`DynVerifyFn`] so structs holding one can still derive `Clone`/`Debug`.
#[derive(Clone)]
pub(crate) struct VerifyCallback(pub(crate) std::sync::Arc<DynVerifyFn>);

impl std::fmt::Debug for VerifyCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("VerifyCallback(..)")
    }
}

/// A custom asset-selection callback: given the release's assets, returns the asset to download
/// (or `None` to fail the update). Overrides the built-in target/identifier substring matching.
pub(crate) type DynAssetMatcher = dyn Fn(&[ReleaseAsset]) -> Option<ReleaseAsset> + Send + Sync;

/// Wrapper around a [`DynAssetMatcher`] so structs holding one can still derive `Clone`/`Debug`.
#[derive(Clone)]
pub(crate) struct AssetMatcher(pub(crate) std::sync::Arc<DynAssetMatcher>);

impl std::fmt::Debug for AssetMatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("AssetMatcher(..)")
    }
}

/// Download things into files
///
/// With optional progress bar
#[non_exhaustive]
pub struct Download {
    show_progress: bool,
    url: String,
    headers: http_client::header::HeaderMap,
    #[cfg(feature = "progress-bar")]
    progress_template: String,
    #[cfg(feature = "progress-bar")]
    progress_chars: String,
    timeout: Option<std::time::Duration>,
    on_progress: Option<ProgressCallback>,
    /// Optional cap on the number of bytes streamed into `dest`. `None` (the default) means no cap,
    /// preserving prior unbounded behavior. When set, the streaming download aborts with an error as
    /// soon as the total bytes written would exceed this many bytes.
    max_download_size: Option<u64>,
    /// Number of times to retry establishing the download request (before any bytes are streamed)
    /// with exponential backoff. `0` (the default) means a single attempt, preserving the prior
    /// no-retry behavior. A failure that occurs *after* streaming has begun is not retried (it would
    /// corrupt the partially-written destination).
    retries: u32,
    retry_base_delay: std::time::Duration,
    retry_max_delay: std::time::Duration,
    /// Optional user-supplied sync HTTP client (used through the trait); `None` => crate default.
    client: Option<std::sync::Arc<dyn http_client::HttpClient>>,
    /// Optional user-supplied async HTTP client; `None` => crate default. Async is reqwest-only.
    #[cfg(feature = "async")]
    async_client: Option<std::sync::Arc<dyn http_client::AsyncHttpClient>>,
    /// Custom TLS root CA certificates to bake into the crate-built client when no client was
    /// injected (see [`add_root_certificate`](Self::add_root_certificate)).
    root_certificates: Vec<Certificate>,
    /// Programmatic proxy URL the crate-built client routes through when no client was injected
    /// (see [`proxy`](Self::proxy)). `None` leaves proxying to the client's own env-var support.
    proxy: Option<String>,
    /// First error from a `request_header(name, value)` argument that wasn't a valid HTTP header.
    /// Deferred like the builders' `request_header` so the setter stays infallible; surfaced from
    /// [`download_to`](Self::download_to) as an `Error::InvalidHeader`.
    header_error: Option<String>,
}

impl std::fmt::Debug for Download {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("Download");
        s.field("show_progress", &self.show_progress)
            .field("url", &self.url)
            .field("headers", &self.headers);
        #[cfg(feature = "progress-bar")]
        s.field("progress_template", &self.progress_template)
            .field("progress_chars", &self.progress_chars);
        s.field("timeout", &self.timeout)
            .field(
                "on_progress",
                &self.on_progress.as_ref().map(|_| "<callback>"),
            )
            .field("max_download_size", &self.max_download_size)
            .field("client", &self.client.as_ref().map(|_| "<http_client>"));
        #[cfg(feature = "async")]
        s.field(
            "async_client",
            &self.async_client.as_ref().map(|_| "<async_http_client>"),
        );
        s.field(
            "root_certificates",
            &format_args!("<{} root_certificates>", self.root_certificates.len()),
        );
        // The proxy URL may embed credentials; print it with the password redacted (see
        // `RequestConfig`'s `Debug`, which does the same for the builders).
        s.field(
            "proxy",
            &self.proxy.as_deref().map(errors::redact_proxy_url),
        );
        s.finish()
    }
}

/// Build the error returned when a streaming download exceeds its configured
/// [`max_download_size`](Download::max_download_size) cap. Reported as an [`Error::Io`] with a
/// message naming the cap so the failure mode is unambiguous.
fn max_download_size_exceeded(cap: u64) -> Error {
    Error::Io(io::Error::other(format!(
        "download exceeded the configured max_download_size cap of {cap} bytes"
    )))
}

impl Download {
    /// Specify download url. Accepts anything string-like (`&str`, `String`, …).
    pub fn from_url(url: impl Into<String>) -> Self {
        Self {
            show_progress: false,
            url: url.into(),
            headers: http_client::header::HeaderMap::new(),
            #[cfg(feature = "progress-bar")]
            progress_template: DEFAULT_PROGRESS_TEMPLATE.to_string(),
            #[cfg(feature = "progress-bar")]
            progress_chars: DEFAULT_PROGRESS_CHARS.to_string(),
            timeout: None,
            on_progress: None,
            max_download_size: None,
            retries: 0,
            retry_base_delay: std::time::Duration::from_millis(100),
            retry_max_delay: std::time::Duration::from_millis(3200),
            client: None,
            #[cfg(feature = "async")]
            async_client: None,
            root_certificates: vec![],
            proxy: None,
            header_error: None,
        }
    }

    /// Toggle the download progress bar. Named to match the `Update` builder's setter of the same
    /// name.
    pub fn show_download_progress(&mut self, b: bool) -> &mut Self {
        self.show_progress = b;
        self
    }

    /// Set a timeout for the download request. Defaults to no timeout.
    pub fn timeout(&mut self, timeout: std::time::Duration) -> &mut Self {
        self.timeout = Some(timeout);
        self
    }

    /// Cap the number of bytes this download will stream into `dest`. Once the running total of
    /// written bytes exceeds `max_bytes`, the download aborts with an [`Error`] instead of writing
    /// an unbounded amount (useful to defend against a server that streams far more than the
    /// advertised `Content-Length`). Defaults to no cap, so existing behavior is unchanged.
    pub fn max_download_size(&mut self, max_bytes: u64) -> &mut Self {
        self.max_download_size = Some(max_bytes);
        self
    }

    /// Register a callback invoked as the download streams, with
    /// `(bytes_downloaded_so_far, total_bytes)` — `total_bytes` is `None` when the server does
    /// not send a `Content-Length`. Independent of the terminal progress bar
    /// ([`show_download_progress`](Self::show_download_progress)); use it to drive a GUI, structured logging, or
    /// any non-terminal progress display. The callback is `Fn`, so track state via interior
    /// mutability (e.g. an `AtomicU64` or a channel).
    pub fn progress_callback(
        &mut self,
        callback: impl Fn(u64, Option<u64>) + Send + Sync + 'static,
    ) -> &mut Self {
        self.on_progress = Some(ProgressCallback(std::sync::Arc::new(callback)));
        self
    }

    /// Internal: set the progress callback from an already-wrapped `Arc` (used by the update
    /// flow to forward an `Update`'s callback to its download).
    pub(crate) fn set_progress_callback_arc(
        &mut self,
        callback: std::sync::Arc<DynProgressFn>,
    ) -> &mut Self {
        self.on_progress = Some(ProgressCallback(callback));
        self
    }

    /// Internal: drop any progress callback and terminal bar (used for the update flow's
    /// side-fetches, e.g. a `SHA256SUMS` asset, which are not the download the caller is tracking).
    #[cfg(feature = "checksums")]
    pub(crate) fn clear_progress_reporting(&mut self) -> &mut Self {
        self.on_progress = None;
        self.show_progress = false;
        self
    }

    /// Set the progress style, as a typed [`ProgressStyle`] (template + chars) so the two strings
    /// can't be transposed.
    #[cfg(feature = "progress-bar")]
    pub fn progress_style(&mut self, style: ProgressStyle) -> &mut Self {
        self.progress_template = style.template;
        self.progress_chars = style.chars;
        self
    }

    /// Replace the entire download request `HeaderMap`. To add a single header without discarding
    /// the others, use [`request_header`](Self::request_header) instead.
    pub fn replace_headers(&mut self, headers: http_client::header::HeaderMap) -> &mut Self {
        self.headers = headers;
        self
    }

    /// Internal: set the download request-establishment retry budget and backoff (used by the
    /// update flow to forward an `Update`'s configured `retries`/`retry_backoff` to the download).
    pub(crate) fn set_retries(
        &mut self,
        retries: u32,
        base: std::time::Duration,
        max: std::time::Duration,
    ) -> &mut Self {
        self.retries = retries;
        self.retry_base_delay = base;
        self.retry_max_delay = max;
        self
    }

    /// Internal: set the injected HTTP clients from already-built `Arc`s (used by the update flow to
    /// forward an `Update`'s injected client to its download).
    pub(crate) fn set_http_client(
        &mut self,
        client: Option<std::sync::Arc<dyn http_client::HttpClient>>,
        #[cfg(feature = "async")] async_client: Option<
            std::sync::Arc<dyn http_client::AsyncHttpClient>,
        >,
    ) -> &mut Self {
        self.client = client;
        #[cfg(feature = "async")]
        {
            self.async_client = async_client;
        }
        self
    }

    /// Add a custom TLS root CA certificate the crate-built HTTP client will trust. Call multiple
    /// times to add more than one. Ignored when an HTTP client is injected via `set_http_client`
    /// (the injected client owns its own TLS config). A malformed certificate surfaces as an
    /// [`Error::InvalidCertificate`] from [`download_to`](Self::download_to).
    ///
    /// **ureq-only builds**: when the `reqwest` feature is disabled, the crate-built ureq client
    /// trusts *only* the supplied certificates (replacing the default Mozilla root set). Supply all
    /// CA certificates you need, including any public roots, or inject a `ureq::Agent` via
    /// `set_http_client` with a merged root set instead.
    pub fn add_root_certificate(&mut self, cert: Certificate) -> &mut Self {
        self.root_certificates.push(cert);
        self
    }

    /// Internal: the configured custom root CA certificates (used by tests to confirm cert
    /// forwarding). Empty unless [`add_root_certificate`](Self::add_root_certificate) was called.
    #[cfg(test)]
    pub(crate) fn root_certificates(&self) -> &[Certificate] {
        &self.root_certificates
    }

    /// Route this download through an HTTP proxy, given as a URL that may embed credentials
    /// (`http://user:pass@proxy.corp:8080`). Calling it more than once replaces the previous URL.
    /// Ignored when an HTTP client is injected via `set_http_client` (the injected client owns its
    /// own proxy config). An unparseable URL surfaces as an [`Error::InvalidProxy`] from
    /// [`download_to`](Self::download_to), with the password redacted from the message.
    ///
    /// On the reqwest client this proxy is applied alongside `HTTP(S)_PROXY` / `NO_PROXY`; on a
    /// ureq-only build it replaces the env-var proxy (the agent has a single proxy slot). Only HTTP
    /// CONNECT proxies are supported. An `Update` forwards its own
    /// [`proxy`](crate::backends::github::UpdateBuilder::proxy) setting here, so the download goes
    /// through the same proxy as the release listing.
    pub fn proxy(&mut self, url: impl Into<String>) -> &mut Self {
        self.proxy = Some(url.into());
        self
    }

    /// Internal: the configured proxy URL (used by tests to confirm proxy forwarding). `None`
    /// unless [`proxy`](Self::proxy) was called.
    #[cfg(test)]
    pub(crate) fn configured_proxy(&self) -> Option<&str> {
        self.proxy.as_deref()
    }

    /// The transport configuration (custom roots + proxy) a crate-built client is materialized
    /// from, shared by the sync and async download paths.
    fn client_config(&self) -> http_client::ClientConfig<'_> {
        http_client::ClientConfig {
            certs: &self.root_certificates,
            proxy: self.proxy.as_deref(),
        }
    }

    /// Map a client-build failure to the error naming the setter that caused it: a proxy-parse
    /// failure to [`proxy`](Self::proxy), anything else to
    /// [`add_root_certificate`](Self::add_root_certificate) -- except when no certificates were
    /// supplied, where a generic build failure can only have come from the proxy config (mirrors
    /// `RequestConfig::build_client`).
    fn client_config_error(&self, e: http_client::ClientConfigError) -> Error {
        match e {
            http_client::ClientConfigError::Proxy(source) => Error::InvalidProxy { source },
            http_client::ClientConfigError::Other(source) if self.root_certificates.is_empty() => {
                Error::InvalidProxy { source }
            }
            http_client::ClientConfigError::Other(source) => Error::InvalidCertificate { source },
        }
    }

    /// Set a download request header, inserting into the existing `HeaderMap`. To add a single
    /// header without discarding the others; to replace the whole map use
    /// [`replace_headers`](Self::replace_headers).
    ///
    /// Accepts anything that converts into a header name/value, so both typed values and plain
    /// strings work: `.request_header("X-Foo", "bar")` or
    /// `.request_header(self_update::http::header::ACCEPT, "application/octet-stream")`. The setter
    /// is infallible; a name or value that is not a valid HTTP header is deferred and surfaced from
    /// [`download_to`](Self::download_to) as an
    /// [`Error::InvalidHeader`], matching the builders'
    /// `request_header` verb.
    pub fn request_header<N, V>(&mut self, name: N, value: V) -> &mut Self
    where
        N: ::core::convert::TryInto<http_client::header::HeaderName>,
        V: ::core::convert::TryInto<http_client::header::HeaderValue>,
    {
        match (name.try_into(), value.try_into()) {
            (Ok(name), Ok(value)) => {
                self.headers.insert(name, value);
            }
            _ => {
                if self.header_error.is_none() {
                    self.header_error =
                        Some("invalid HTTP header passed to `request_header`".to_string());
                }
            }
        }
        self
    }

    /// Surface a deferred `request_header` conversion failure as an `Error::InvalidHeader`.
    fn check_header_error(&self) -> Result<()> {
        if let Some(msg) = &self.header_error {
            return Err(Error::InvalidHeader {
                source: Box::new(errors::MessageError(msg.clone())),
            });
        }
        Ok(())
    }

    /// Download the file behind the given `url` into the specified `dest`.
    /// Show a sliding progress bar if specified.
    /// If the resource doesn't specify a content-length, the progress bar will not be shown
    ///
    /// * Errors:
    ///     * HTTP client network errors
    ///     * Unsuccessful response status
    ///     * Progress-bar errors
    ///     * Reading from response to `BufReader`-buffer
    ///     * Writing from `BufReader`-buffer to `File`
    pub fn download_to<T: io::Write>(&self, mut dest: T) -> Result<()> {
        use io::BufRead;
        self.check_header_error()?;
        let mut headers = self.headers.clone();
        if !headers.contains_key(header::USER_AGENT) {
            headers.insert(
                header::USER_AGENT,
                DEFAULT_USER_AGENT.parse().expect("invalid user-agent"),
            );
        }

        let default;
        let built;
        let config = self.client_config();
        let client: &dyn http_client::HttpClient = match self.client.as_deref() {
            Some(c) => c,
            None if !config.is_empty() => {
                // No injected client but custom root CAs and/or a proxy were supplied: build a
                // client honoring them. A malformed cert or proxy URL surfaces here as
                // `Error::InvalidCertificate` / `Error::InvalidProxy`.
                built = http_client::build_configured_client(config)
                    .map_err(|e| self.client_config_error(e))?;
                &*built
            }
            None => {
                default = http_client::default_client();
                &*default
            }
        };
        // Retry only the request-establishment phase (before any bytes are streamed): a failure
        // after streaming begins would corrupt the partially-written destination. With the default
        // `retries == 0` this is a single attempt.
        let resp = backends::retry(
            self.retries,
            self.retry_base_delay,
            self.retry_max_delay,
            || client.get(&self.url, &headers, self.timeout),
            |e, backoff| {
                log::warn!(
                    "self_update: download request to {} failed ({e}); retrying in {backoff}ms",
                    crate::errors::redact_url(&self.url)
                );
                std::thread::sleep(std::time::Duration::from_millis(backoff));
            },
        )?;
        let size = resp
            .headers()
            .get(http_client::header::CONTENT_LENGTH)
            .map(|val| {
                val.to_str()
                    .map(|s| s.parse::<u64>().unwrap_or(0))
                    .unwrap_or(0)
            })
            .unwrap_or(0);
        // `http_client::get` already errored on a non-success status (see `download_to_async`).
        let total = if size == 0 { None } else { Some(size) };
        #[cfg(feature = "progress-bar")]
        let show_progress = if size == 0 { false } else { self.show_progress };

        let mut src = io::BufReader::new(resp.body());
        let mut downloaded: u64 = 0;
        #[cfg(feature = "progress-bar")]
        let mut bar = if show_progress {
            let style = IndicatifProgressStyle::default_bar()
                .template(&self.progress_template)
                .map_err(|e| Error::InvalidProgressStyle {
                    source: Box::new(e),
                })?
                .progress_chars(&self.progress_chars);
            let pb = ProgressBar::new(size);
            pb.set_style(style);
            Some(pb)
        } else {
            None
        };
        loop {
            let n = {
                let buf = src.fill_buf()?;
                dest.write_all(buf)?;
                buf.len()
            };
            if n == 0 {
                break;
            }
            src.consume(n);
            downloaded += n as u64;
            if let Some(cap) = self.max_download_size
                && downloaded > cap
            {
                return Err(max_download_size_exceeded(cap));
            }

            #[cfg(feature = "progress-bar")]
            if let Some(ref mut bar) = bar {
                bar.set_position(min(downloaded, size));
            }
            if let Some(ref cb) = self.on_progress {
                (cb.0)(downloaded, total);
            }
        }
        #[cfg(feature = "progress-bar")]
        if let Some(ref mut bar) = bar {
            bar.finish_with_message("Done");
        }
        Ok(())
    }

    /// Async sibling of [`download_to`](Self::download_to): stream the download into `dest` using
    /// the async (reqwest) transport, driving the same progress bar / callback. `dest` is a
    /// synchronous writer (chunks are written as they arrive); file IO is not offloaded.
    #[cfg(feature = "async")]
    pub async fn download_to_async<T: io::Write>(&self, mut dest: T) -> Result<()> {
        use futures_util::StreamExt;

        self.check_header_error()?;
        let mut headers = self.headers.clone();
        if !headers.contains_key(header::USER_AGENT) {
            headers.insert(
                header::USER_AGENT,
                DEFAULT_USER_AGENT.parse().expect("invalid user-agent"),
            );
        }

        let default;
        let built;
        let config = self.client_config();
        let client: &dyn http_client::AsyncHttpClient = match self.async_client.as_deref() {
            Some(c) => c,
            None if !config.is_empty() => {
                // No injected async client but custom root CAs and/or a proxy were supplied: build
                // one honoring them. A malformed cert or proxy URL surfaces here as
                // `Error::InvalidCertificate` / `Error::InvalidProxy`.
                built = http_client::build_configured_async_client(config)
                    .map_err(|e| self.client_config_error(e))?;
                &*built
            }
            None => {
                default = http_client::default_async_client();
                &*default
            }
        };
        // Retry only the request-establishment phase (see `download_to`).
        let resp = backends::retry_async(
            self.retries,
            self.retry_base_delay,
            self.retry_max_delay,
            || client.get(&self.url, &headers, self.timeout),
            |e, backoff| {
                log::warn!(
                    "self_update: download request to {} failed ({e}); retrying in {backoff}ms",
                    crate::errors::redact_url(&self.url)
                );
            },
            |backoff| tokio::time::sleep(std::time::Duration::from_millis(backoff)),
        )
        .await?;
        let size = resp
            .headers()
            .get(http_client::header::CONTENT_LENGTH)
            .map(|val| {
                val.to_str()
                    .map(|s| s.parse::<u64>().unwrap_or(0))
                    .unwrap_or(0)
            })
            .unwrap_or(0);
        // `get_async` already errored on a non-success status.
        let total = if size == 0 { None } else { Some(size) };
        #[cfg(feature = "progress-bar")]
        let show_progress = if size == 0 { false } else { self.show_progress };

        let mut downloaded: u64 = 0;
        #[cfg(feature = "progress-bar")]
        let mut bar = if show_progress {
            let style = IndicatifProgressStyle::default_bar()
                .template(&self.progress_template)
                .map_err(|e| Error::InvalidProgressStyle {
                    source: Box::new(e),
                })?
                .progress_chars(&self.progress_chars);
            let pb = ProgressBar::new(size);
            pb.set_style(style);
            Some(pb)
        } else {
            None
        };

        let mut stream = resp.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            dest.write_all(&chunk)?;
            downloaded += chunk.len() as u64;
            if let Some(cap) = self.max_download_size
                && downloaded > cap
            {
                return Err(max_download_size_exceeded(cap));
            }

            #[cfg(feature = "progress-bar")]
            if let Some(ref mut bar) = bar {
                bar.set_position(min(downloaded, size));
            }
            if let Some(ref cb) = self.on_progress {
                (cb.0)(downloaded, total);
            }
        }
        #[cfg(feature = "progress-bar")]
        if let Some(ref mut bar) = bar {
            bar.finish_with_message("Done");
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "compression-tar-gz")]
    use flate2::{self, write::GzEncoder};
    #[allow(unused_imports)]
    use std::{
        fs::{self, File},
        io::{self, Read, Write},
        path::{Path, PathBuf},
    };

    #[test]
    fn version_status_is_up_to_date() {
        assert!(VersionStatus::UpToDate("1.2.3".to_string()).is_up_to_date());
        assert!(!VersionStatus::Updated("1.2.3".to_string()).is_up_to_date());
        // `is_updated()` is the complement.
        assert!(VersionStatus::Updated("1.2.3".to_string()).is_updated());
        assert!(!VersionStatus::UpToDate("1.2.3".to_string()).is_updated());
    }

    #[test]
    fn version_status_version_accessor() {
        // version() returns the wrapped string for both variants.
        assert_eq!(
            VersionStatus::UpToDate("1.0.0".to_string()).version(),
            "1.0.0"
        );
        assert_eq!(
            VersionStatus::Updated("2.0.0".to_string()).version(),
            "2.0.0"
        );
    }

    #[test]
    fn version_status_display() {
        // Display is human-readable, not Debug form.
        assert_eq!(
            VersionStatus::UpToDate("1.0.0".to_string()).to_string(),
            "UpToDate(1.0.0)"
        );
        assert_eq!(
            VersionStatus::Updated("2.0.0".to_string()).to_string(),
            "Updated(2.0.0)"
        );
    }

    // `ArchiveKind` renders a friendly, human-readable name via `Display` (used in error messages),
    // not the `Debug` form (which leaks the enum shape like `Tar(Some(Gz))`).
    #[test]
    fn archive_kind_display_is_human_readable() {
        assert_eq!(ArchiveKind::Plain(None).to_string(), "plain");
        assert_eq!(ArchiveKind::Plain(Some(Compression::Gz)).to_string(), "gz");
        assert_eq!(ArchiveKind::Plain(Some(Compression::Xz)).to_string(), "xz");
        #[cfg(feature = "archive-tar")]
        {
            assert_eq!(ArchiveKind::Tar(None).to_string(), "tar");
            assert_eq!(
                ArchiveKind::Tar(Some(Compression::Gz)).to_string(),
                "tar.gz"
            );
            assert_eq!(
                ArchiveKind::Tar(Some(Compression::Xz)).to_string(),
                "tar.xz"
            );
        }
        #[cfg(feature = "archive-zip")]
        assert_eq!(ArchiveKind::Zip.to_string(), "zip");
    }

    // A3/A4/A12/A5: the ergonomic argument types are accepted. These are compile-locks plus light
    // assertions: `Download::from_url` takes `impl Into<String>`; `Extract::from_source` /
    // `Move::from_source` / `MoveAll::from_temp` take `impl AsRef<Path>` (now lifetime-free); the
    // Download header verb is `request_header`; and `progress_style` takes a typed `ProgressStyle`.
    #[test]
    fn ergonomic_constructors_accept_owned_and_borrowed_paths_and_strings() {
        // from_url accepts &str and String.
        let _ = Download::from_url("https://example.com/a.bin");
        let _ = Download::from_url(String::from("https://example.com/b.bin"));

        // Extract::from_source accepts &str, PathBuf, and &Path — and the struct holds no lifetime.
        let _: Extract = Extract::from_source("some/path.tar.gz");
        let _: Extract = Extract::from_source(PathBuf::from("some/path.tar.gz"));
        let owned = PathBuf::from("some/path.tar.gz");
        let _: Extract = Extract::from_source(owned.as_path());

        // Move::from_source / replace_using_temp accept path-like; the type is lifetime-free.
        let mut mv: Move = Move::from_source("src");
        mv.replace_using_temp("tmp");

        // MoveAll::from_temp accepts path-like; lifetime-free.
        let _: MoveAll = MoveAll::from_temp("tmp-dir");
    }

    #[cfg(feature = "progress-bar")]
    #[test]
    fn progress_style_newtype_threads_template_and_chars() {
        // A5: `ProgressStyle::new(template, chars)` builds the typed pair and the Download setter
        // threads both fields through (no transposable two-arg setter).
        let style = ProgressStyle::new("[{bar:40}] {bytes}", "#>-");
        assert_eq!(style.template, "[{bar:40}] {bytes}");
        assert_eq!(style.chars, "#>-");

        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        dl.progress_style(style);
        assert_eq!(dl.progress_template, "[{bar:40}] {bytes}");
        assert_eq!(dl.progress_chars, "#>-");
    }

    #[test]
    fn download_header_accepts_str_name_and_value() {
        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        // Plain string literals must convert into a valid name/value.
        dl.request_header("x-custom-header", "custom-value");
        let stored = dl
            .headers
            .get("x-custom-header")
            .expect("header should be inserted");
        assert_eq!(stored, "custom-value");
    }

    #[test]
    fn download_header_accepts_typed_name_and_value() {
        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        // The typed `HeaderName` / `&str` value form still works.
        dl.request_header(http_client::header::ACCEPT, "application/octet-stream");
        assert_eq!(
            dl.headers.get(http_client::header::ACCEPT).unwrap(),
            "application/octet-stream"
        );
    }

    #[test]
    fn download_header_overwrites_on_repeated_name() {
        // B5: `header()` inserts into the existing map. Calling it twice with the same name must
        // keep the *last* value (insert semantics), not append or keep the first.
        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        dl.request_header("x-dup", "first");
        dl.request_header("x-dup", "second");
        // `get` returns the (single) value; `get_all` must contain exactly one entry.
        assert_eq!(dl.headers.get("x-dup").unwrap(), "second");
        assert_eq!(
            dl.headers.get_all("x-dup").iter().count(),
            1,
            "a repeated header name must overwrite, not accumulate"
        );
    }

    #[test]
    fn replace_headers_wholesale_replaces_after_header_calls() {
        // B5: after building up headers with `header()`, `replace_headers` must discard them all
        // and install only the supplied map (it is a whole-map setter, not a merge).
        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        dl.request_header("x-old-a", "a");
        dl.request_header("x-old-b", "b");

        let mut fresh = http_client::header::HeaderMap::new();
        fresh.insert("x-new", "n".parse().unwrap());
        dl.replace_headers(fresh);

        assert!(
            dl.headers.get("x-old-a").is_none(),
            "replace_headers must drop previously-added headers"
        );
        assert!(dl.headers.get("x-old-b").is_none());
        assert_eq!(dl.headers.get("x-new").unwrap(), "n");
        assert_eq!(
            dl.headers.len(),
            1,
            "replace_headers installs exactly the supplied map"
        );

        // And `header()` still works after a replace, inserting into the new map.
        dl.request_header("x-after", "y");
        assert_eq!(dl.headers.get("x-after").unwrap(), "y");
        assert_eq!(dl.headers.get("x-new").unwrap(), "n");
    }

    #[test]
    fn download_header_rejects_invalid_value() {
        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        // A newline is not a valid header value. The setter is infallible (deferred): the bad
        // header is not inserted, and the error surfaces from `download_to`.
        dl.request_header("x-ok", "bad\nvalue");
        assert!(
            dl.headers.get("x-ok").is_none(),
            "the bad header must not be inserted"
        );
        let err = dl
            .download_to(Vec::<u8>::new())
            .expect_err("a deferred invalid header must surface from download_to");
        assert!(
            matches!(err, Error::InvalidHeader { .. }),
            "expected Error::InvalidHeader, got {:?}",
            err
        );
    }

    #[test]
    fn download_header_rejects_invalid_name() {
        let mut dl = Download::from_url("https://example.com/app.tar.gz");
        // A space is not valid in a header name. The setter is infallible (deferred); the invalid
        // name is rejected before any value insertion, so the map stays empty and the error
        // surfaces from download_to.
        dl.request_header("inva lid", "ok");
        assert!(
            dl.headers.is_empty(),
            "an invalid header name must not leave a partial value inserted"
        );
        let err = dl
            .download_to(Vec::<u8>::new())
            .expect_err("a deferred invalid header name must surface from download_to");
        assert!(matches!(err, Error::InvalidHeader { .. }));
    }

    #[test]
    fn detect_plain() {
        assert_eq!(
            ArchiveKind::Plain(None),
            detect_archive(&PathBuf::from("Something.exe")).unwrap()
        );
    }

    #[test]
    fn move_all_commits_every_move() {
        let dir = tempfile::tempdir().unwrap();
        let temp = tempfile::tempdir().unwrap();

        // Two new files to install over two existing destinations.
        let src_a = dir.path().join("src_a");
        let src_b = dir.path().join("src_b");
        fs::write(&src_a, b"new-a").unwrap();
        fs::write(&src_b, b"new-b").unwrap();
        let dst_a = dir.path().join("dst_a");
        let dst_b = dir.path().join("dst_b");
        fs::write(&dst_a, b"old-a").unwrap();
        fs::write(&dst_b, b"old-b").unwrap();

        MoveAll::from_temp(temp.path())
            .add(&src_a, &dst_a)
            .add(&src_b, &dst_b)
            .commit()
            .unwrap();

        assert_eq!(fs::read(&dst_a).unwrap(), b"new-a");
        assert_eq!(fs::read(&dst_b).unwrap(), b"new-b");
    }

    #[test]
    fn move_all_rolls_back_on_failure() {
        let dir = tempfile::tempdir().unwrap();
        let temp = tempfile::tempdir().unwrap();

        // Three moves: the first two are valid and overwrite existing destinations (so both are
        // stashed and applied), the third points at a non-existent source so its move fails. This
        // drives the already-applied first two back through `rollback()` (the stash-restore path).
        let src_a = dir.path().join("src_a");
        let src_b = dir.path().join("src_b");
        fs::write(&src_a, b"new-a").unwrap();
        fs::write(&src_b, b"new-b").unwrap();
        let missing_src = dir.path().join("does_not_exist");

        let dst_a = dir.path().join("dst_a");
        let dst_b = dir.path().join("dst_b");
        let dst_c = dir.path().join("dst_c");
        fs::write(&dst_a, b"old-a").unwrap();
        fs::write(&dst_b, b"old-b").unwrap();
        fs::write(&dst_c, b"old-c").unwrap();

        let res = MoveAll::from_temp(temp.path())
            .add(&src_a, &dst_a)
            .add(&src_b, &dst_b)
            .add(&missing_src, &dst_c)
            .commit();
        assert!(res.is_err(), "a failing move must abort the transaction");

        // Every destination is restored to its original contents — both the applied moves
        // (rolled back via the stash) and the one whose move failed mid-step.
        assert_eq!(
            fs::read(&dst_a).unwrap(),
            b"old-a",
            "the first applied move must be rolled back"
        );
        assert_eq!(
            fs::read(&dst_b).unwrap(),
            b"old-b",
            "the second applied move must be rolled back"
        );
        assert_eq!(
            fs::read(&dst_c).unwrap(),
            b"old-c",
            "the failed move's stashed destination must be restored"
        );
    }

    #[test]
    fn move_all_installs_fresh_destinations() {
        let dir = tempfile::tempdir().unwrap();
        let temp = tempfile::tempdir().unwrap();

        // Destination does not pre-exist (fresh install, no stash needed).
        let src = dir.path().join("src");
        fs::write(&src, b"fresh").unwrap();
        let dst = dir.path().join("new_dst");

        MoveAll::from_temp(temp.path())
            .add(&src, &dst)
            .commit()
            .unwrap();
        assert_eq!(fs::read(&dst).unwrap(), b"fresh");
    }

    #[test]
    fn move_all_second_commit_is_a_noop() {
        let dir = tempfile::tempdir().unwrap();
        let temp = tempfile::tempdir().unwrap();

        let src = dir.path().join("src");
        fs::write(&src, b"new").unwrap();
        let dst = dir.path().join("dst");
        fs::write(&dst, b"old").unwrap();

        let mut mover = MoveAll::from_temp(temp.path());
        mover.add(&src, &dst);
        mover.commit().unwrap();
        assert_eq!(fs::read(&dst).unwrap(), b"new");

        // The queue was drained, so a second commit does nothing and succeeds (rather than trying
        // to re-apply the move against the now-missing source and erroring out).
        mover.commit().unwrap();
        assert_eq!(fs::read(&dst).unwrap(), b"new");
    }

    #[test]
    fn download_invokes_progress_callback() {
        use std::net::TcpListener;
        use std::sync::{Arc, Mutex};

        // Serve a known-length body from a loopback server (no external network).
        let body = "x".repeat(20_000);
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let served = body.clone();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut buf = [0u8; 1024];
            let _ = stream.read(&mut buf);
            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                served.len(),
                served
            );
            let _ = stream.write_all(resp.as_bytes());
        });

        let progress = Arc::new(Mutex::new(Vec::<(u64, Option<u64>)>::new()));
        let sink_progress = progress.clone();
        let mut out = Vec::new();
        Download::from_url(format!("http://{addr}/file"))
            .progress_callback(move |downloaded, total| {
                sink_progress.lock().unwrap().push((downloaded, total));
            })
            .download_to(&mut out)
            .unwrap();

        assert_eq!(out.len(), 20_000);
        let calls = progress.lock().unwrap();
        assert!(!calls.is_empty(), "callback should have been invoked");
        // `total` reflects the Content-Length on every call.
        assert!(calls.iter().all(|(_, total)| *total == Some(20_000)));
        // `downloaded` is monotonically non-decreasing and reaches the full size.
        let mut last = 0u64;
        for (downloaded, _) in calls.iter() {
            assert!(*downloaded >= last);
            last = *downloaded;
        }
        assert_eq!(calls.last().unwrap().0, 20_000);
    }

    /// Read one HTTP message head (through the blank line) a byte at a time, so nothing of a
    /// following tunneled request is swallowed. Returns the head verbatim.
    fn read_http_head(stream: &mut impl Read) -> String {
        let mut buf = Vec::new();
        let mut byte = [0u8; 1];
        while stream.read(&mut byte).unwrap_or(0) == 1 {
            buf.push(byte[0]);
            if buf.ends_with(b"\r\n\r\n") {
                break;
            }
        }
        String::from_utf8_lossy(&buf).to_string()
    }

    /// A loopback HTTP proxy stub. Serves `body` for whatever the client asks for, and reports the
    /// head of the first request it received (the one carrying `Proxy-Authorization`) over the
    /// returned channel. Handles both proxying styles the two clients use for a plain-http target:
    /// reqwest sends an absolute-form `GET http://host/path`, while ureq opens a
    /// `CONNECT host:80` tunnel first and sends the request through it.
    ///
    /// Returns `(authority, request_head_rx)` where `authority` is `127.0.0.1:<port>`.
    fn proxy_stub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let authority = listener.local_addr().unwrap().to_string();
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let head = read_http_head(&mut stream);
            let _ = tx.send(head.clone());
            if head.starts_with("CONNECT") {
                // Accept the tunnel, then read the request the client sends through it. The target
                // is plain http, so nothing is negotiated on top and the stub can answer directly.
                let _ = stream.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
                let _ = read_http_head(&mut stream);
            }
            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                body.len(),
                body
            );
            let _ = stream.write_all(resp.as_bytes());
            let _ = stream.flush();
        });
        (authority, rx)
    }

    /// `Proxy-Authorization` for `corpuser:hunter2`, i.e. `base64("corpuser:hunter2")`. Both
    /// clients render the credentials embedded in the proxy URL into this header.
    const PROXY_BASIC_CREDS: &str = "Y29ycHVzZXI6aHVudGVyMg==";

    /// The proxy setter must actually route the download through the proxy *and* pass the
    /// credentials embedded in its URL. The target host is `.invalid` (RFC 2606: never resolvable),
    /// so the download can only succeed by going through the proxy -- a setter that silently did
    /// nothing would fail to resolve instead of quietly downloading direct.
    #[test]
    fn download_routes_through_a_configured_proxy_with_credentials() {
        let (authority, requests) = proxy_stub("proxied-body");
        let mut out = Vec::new();
        Download::from_url("http://target.invalid/file")
            .proxy(format!("http://corpuser:hunter2@{authority}"))
            .download_to(&mut out)
            .expect("the download must succeed through the proxy");
        assert_eq!(
            String::from_utf8_lossy(&out),
            "proxied-body",
            "the body must come back through the proxy"
        );
        let head = requests
            .recv_timeout(std::time::Duration::from_secs(10))
            .expect("the proxy must have received the request");
        assert!(
            head.contains("target.invalid"),
            "the proxy must be asked for the target host (absolute-form GET or CONNECT), got: {head}"
        );
        assert!(
            head.to_lowercase().contains("proxy-authorization") && head.contains(PROXY_BASIC_CREDS),
            "the credentials embedded in the proxy URL must be sent to the proxy, got: {head}"
        );
    }

    /// Async sibling of `download_routes_through_a_configured_proxy_with_credentials`: the async
    /// download path builds its own client, so it needs its own proof that the proxy is applied.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn download_async_routes_through_a_configured_proxy_with_credentials() {
        let (authority, requests) = proxy_stub("proxied-body-async");
        let mut out = Vec::new();
        Download::from_url("http://target.invalid/file")
            .proxy(format!("http://corpuser:hunter2@{authority}"))
            .download_to_async(&mut out)
            .await
            .expect("the async download must succeed through the proxy");
        assert_eq!(String::from_utf8_lossy(&out), "proxied-body-async");
        let head = requests
            .recv_timeout(std::time::Duration::from_secs(10))
            .expect("the proxy must have received the async request");
        assert!(head.contains("target.invalid"), "got: {head}");
        assert!(
            head.to_lowercase().contains("proxy-authorization") && head.contains(PROXY_BASIC_CREDS),
            "the async lane must send the proxy credentials too, got: {head}"
        );
    }

    /// An injected client owns its own proxy configuration, so `.proxy()` must not silently build a
    /// second client over the top of it (CORP-3-6). Proven by injecting a client that answers
    /// without any network at all: if the proxy setter rebuilt the client, the request would go to
    /// the (unbound) proxy address and fail instead of returning the canned body.
    #[test]
    fn an_injected_client_wins_over_a_configured_proxy() {
        let requested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let client = std::sync::Arc::new(DlClient {
            body: b"from-injected-client".to_vec(),
            content_length: Some(20),
            requested: requested.clone(),
        });
        let mut out = Vec::new();
        let mut download = Download::from_url("http://target.invalid/file");
        download.proxy("http://127.0.0.1:1/");
        download.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        download
            .download_to(&mut out)
            .expect("the injected client must serve the download");
        assert_eq!(String::from_utf8_lossy(&out), "from-injected-client");
        assert_eq!(requested.lock().unwrap().len(), 1);
    }

    /// A proxy URL that neither client can parse must surface as `Error::InvalidProxy` from
    /// `download_to` -- not as a transport error, and not as `InvalidCertificate` (no certificate
    /// was ever supplied). The message must carry the redacted URL, never the password.
    #[test]
    fn download_rejects_an_unparseable_proxy_url() {
        let mut out = Vec::new();
        let err = Download::from_url("http://target.invalid/file")
            .proxy("http://corpuser:hunter2@ not a proxy url")
            .download_to(&mut out)
            .expect_err("an unparseable proxy URL must be an error");
        assert!(
            matches!(err, Error::InvalidProxy { .. }),
            "expected Error::InvalidProxy, got {err:?}"
        );
        let rendered = err.to_string();
        assert!(
            !rendered.contains("hunter2"),
            "the proxy password must not appear in the error, got: {rendered}"
        );
        assert!(
            rendered.contains("REDACTED"),
            "the error must name the (redacted) proxy URL, got: {rendered}"
        );
    }

    /// `Download`'s hand-written `Debug` must redact the proxy password, the same way
    /// `RequestConfig`'s does for the builders: an application dumping its `Download` into a log
    /// must not leak the credential.
    #[test]
    fn download_debug_redacts_the_proxy_password() {
        let mut download = Download::from_url("http://example.com/file");
        download.proxy("http://corpuser:hunter2@proxy.corp:8080");
        let rendered = format!("{download:?}");
        assert!(
            !rendered.contains("hunter2"),
            "the proxy password must never appear in Debug output, got: {rendered}"
        );
        assert!(
            rendered.contains("http://corpuser:REDACTED@proxy.corp:8080"),
            "the proxy must still be identifiable in the dump, got: {rendered}"
        );
    }

    /// A test-double [`HttpResponse`](http_client::HttpResponse) returning a canned body and a
    /// configurable `Content-Length`. Used to prove `download_to` streams the injected client's
    /// body through the trait (`headers()` + `body()`), not a real network response.
    struct DlResponse {
        body: Vec<u8>,
        headers: http_client::header::HeaderMap,
    }

    impl http_client::HttpResponse for DlResponse {
        fn headers(&self) -> &http_client::header::HeaderMap {
            &self.headers
        }
        fn body(self: Box<Self>) -> Box<dyn io::Read> {
            Box::new(io::Cursor::new(self.body))
        }
    }

    /// A test-double [`HttpClient`](http_client::HttpClient) (neither reqwest nor ureq) that records
    /// the requested URL and returns a canned [`DlResponse`].
    struct DlClient {
        body: Vec<u8>,
        content_length: Option<u64>,
        requested: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
    }

    impl http_client::HttpClient for DlClient {
        fn get(
            &self,
            url: &str,
            _headers: &http_client::header::HeaderMap,
            _timeout: Option<std::time::Duration>,
        ) -> Result<Box<dyn http_client::HttpResponse>> {
            self.requested.lock().unwrap().push(url.to_string());
            let mut headers = http_client::header::HeaderMap::new();
            if let Some(len) = self.content_length {
                headers.insert(
                    http_client::header::CONTENT_LENGTH,
                    len.to_string().parse().unwrap(),
                );
            }
            Ok(Box::new(DlResponse {
                body: self.body.clone(),
                headers,
            }))
        }
    }

    /// A flaky [`HttpClient`](http_client::HttpClient) that fails the first `fail_times` GETs with a
    /// transport error, then succeeds — to prove `download_to` retries the request-establishment
    /// phase when a retry budget is configured (B9).
    struct FlakyDlClient {
        body: Vec<u8>,
        fail_times: std::sync::atomic::AtomicU32,
        attempts: std::sync::Arc<std::sync::atomic::AtomicU32>,
    }

    impl http_client::HttpClient for FlakyDlClient {
        fn get(
            &self,
            _url: &str,
            _headers: &http_client::header::HeaderMap,
            _timeout: Option<std::time::Duration>,
        ) -> Result<Box<dyn http_client::HttpResponse>> {
            use std::sync::atomic::Ordering;
            self.attempts.fetch_add(1, Ordering::SeqCst);
            if self.fail_times.load(Ordering::SeqCst) > 0 {
                self.fail_times.fetch_sub(1, Ordering::SeqCst);
                return Err(Error::HttpStatus {
                    status: 503,
                    url: "u".into(),
                });
            }
            let mut headers = http_client::header::HeaderMap::new();
            headers.insert(
                http_client::header::CONTENT_LENGTH,
                self.body.len().to_string().parse().unwrap(),
            );
            Ok(Box::new(DlResponse {
                body: self.body.clone(),
                headers,
            }))
        }
    }

    #[test]
    fn download_retries_request_establishment_with_configured_budget() {
        // B9: with a retry budget, `download_to` re-establishes the request after a transient
        // failure (before any bytes are streamed) and ultimately succeeds. Two failures then a
        // success => three attempts. A short base/cap keeps the test fast.
        use std::sync::atomic::{AtomicU32, Ordering};
        let body = b"payload-after-retries".to_vec();
        let attempts = std::sync::Arc::new(AtomicU32::new(0));
        let client = std::sync::Arc::new(FlakyDlClient {
            body: body.clone(),
            fail_times: AtomicU32::new(2),
            attempts: attempts.clone(),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/asset.bin");
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        dl.set_retries(
            3,
            std::time::Duration::from_millis(1),
            std::time::Duration::from_millis(2),
        );
        dl.download_to(&mut out).unwrap();

        assert_eq!(out, body, "the download succeeds after retrying");
        assert_eq!(
            attempts.load(Ordering::SeqCst),
            3,
            "two failed attempts plus the successful third"
        );
    }

    #[test]
    fn download_without_retry_budget_does_not_retry() {
        // With the default `retries == 0`, a single failure is fatal (one attempt, no retry).
        use std::sync::atomic::{AtomicU32, Ordering};
        let attempts = std::sync::Arc::new(AtomicU32::new(0));
        let client = std::sync::Arc::new(FlakyDlClient {
            body: b"never-reached".to_vec(),
            fail_times: AtomicU32::new(5),
            attempts: attempts.clone(),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/asset.bin");
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        let res = dl.download_to(&mut out);
        assert!(
            res.is_err(),
            "no retry budget => the first failure is fatal"
        );
        assert_eq!(
            attempts.load(Ordering::SeqCst),
            1,
            "exactly one attempt with retries == 0"
        );
    }

    // -----------------------------------------------------------------------
    // The download path routes its request-establishment retries through
    // `backends::retry`, so it inherits that loop's `Error::RateLimited`
    // short-circuit. Nothing pinned that from this side: a future `download_to`
    // that grew its own retry loop (or dropped back to a bare `client.get`
    // wrapper) would silently start hammering an exhausted quota again. These
    // two tests count the requests that actually reach the wire, with a real
    // loopback server and the crate's default client, so the whole
    // classify-then-short-circuit chain is exercised. The 500 control is what
    // keeps the pair honest: a short-circuit firing on EVERY error would pass
    // the rate-limit test alone.
    // -----------------------------------------------------------------------

    /// Bind a loopback stub that answers EVERY connection with the same fixed response and counts
    /// the requests it served. `status_line` is e.g. `"403 Forbidden"`; `extra_headers` is a block
    /// of CRLF-terminated header lines (possibly empty). Every response carries `Connection: close`,
    /// so one connection is one request and the counter is the exact number of requests the client
    /// issued. It accepts in a loop, so a retried request is served (and counted) rather than
    /// hanging. Mirrors the `counting_stub` in `backends::mod`'s tests.
    fn counting_stub(
        status_line: &str,
        extra_headers: &str,
    ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
        use std::net::TcpListener;
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}/asset.bin", listener.local_addr().unwrap());
        let hits = std::sync::Arc::new(AtomicUsize::new(0));
        let counter = hits.clone();
        let status_line = status_line.to_string();
        let extra_headers = extra_headers.to_string();
        std::thread::spawn(move || {
            loop {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                if n == 0 {
                    continue;
                }
                counter.fetch_add(1, Ordering::SeqCst);
                let body = "stub";
                let out = format!(
                    "HTTP/1.1 {status_line}\r\n{extra_headers}Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        (base, hits)
    }

    /// A `Download` for `url` with `retries` retries and a 1ms backoff, so the control test that
    /// really does spend its whole budget stays fast (the backoff *values* are covered by the
    /// `retry_backoff_*` tests in `backends`; here only the request COUNT matters).
    fn download_with_retries(url: &str, retries: u32) -> Download {
        let mut dl = Download::from_url(url);
        dl.set_retries(
            retries,
            std::time::Duration::from_millis(1),
            std::time::Duration::from_millis(1),
        );
        dl
    }

    #[test]
    fn download_issues_exactly_one_request_for_a_rate_limited_response() {
        // A 403 reporting a spent quota must put exactly ONE request on the wire even with a
        // retry budget of 3: `download_to` retries through `backends::retry`, which returns a
        // `RateLimited` immediately instead of re-issuing requests against an exhausted (and,
        // behind a shared egress IP, shared) budget.
        let (url, hits) = counting_stub("403 Forbidden", "x-ratelimit-remaining: 0\r\n");
        let mut out = Vec::new();
        let res = download_with_retries(&url, 3).download_to(&mut out);
        assert!(
            matches!(res, Err(Error::RateLimited { status: 403, .. })),
            "a 403 with a spent quota must surface as RateLimited, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "a rate-limited download must not be retried: exactly one request may reach the server"
        );
    }

    #[test]
    fn download_spends_the_whole_retry_budget_for_a_server_error() {
        // The control for the test above. A 500 is not rate limiting, so the download's retry
        // budget is still spent in full: 1 initial attempt + 3 retries = 4 requests on the wire.
        let (url, hits) = counting_stub("500 Internal Server Error", "");
        let mut out = Vec::new();
        let res = download_with_retries(&url, 3).download_to(&mut out);
        assert!(
            matches!(res, Err(Error::HttpStatus { status: 500, .. })),
            "a 500 must surface as HttpStatus, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits.load(std::sync::atomic::Ordering::SeqCst),
            4,
            "a non-rate-limited download failure must still consume the retry budget (1 + 3)"
        );
    }

    #[test]
    fn download_to_uses_injected_http_client_through_the_trait() {
        // Gap #4 (sync Download path): an arbitrary `Arc<dyn HttpClient>` that is NOT reqwest/ureq,
        // injected via `.http_client(...)`, must actually drive `download_to` — the streamed body
        // comes from the fake and the fake records the requested URL. No network is touched (the URL
        // is non-routable).
        let requested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = b"injected-binary-payload".to_vec();
        let client = std::sync::Arc::new(DlClient {
            body: body.clone(),
            content_length: Some(body.len() as u64),
            requested: requested.clone(),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/asset.bin");
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        dl.download_to(&mut out).unwrap();

        assert_eq!(out, body, "download_to streamed the injected client's body");
        let urls = requested.lock().unwrap();
        assert_eq!(
            urls.len(),
            1,
            "exactly one GET went through the injected client"
        );
        assert_eq!(urls[0], "https://nonroutable.invalid/asset.bin");
    }

    #[test]
    fn download_to_handles_injected_client_without_content_length() {
        // When the injected response carries no Content-Length, `download_to` must still stream the
        // whole body to completion (size defaults to 0 -> no progress bar, `total == None`) and the
        // progress callback still fires with `total = None`.
        let requested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = b"no-length-body".to_vec();
        let client = std::sync::Arc::new(DlClient {
            body: body.clone(),
            content_length: None,
            requested: requested.clone(),
        });

        let totals = std::sync::Arc::new(std::sync::Mutex::new(Vec::<Option<u64>>::new()));
        let sink = totals.clone();
        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/asset.bin");
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        dl.progress_callback(move |_d, total| sink.lock().unwrap().push(total));
        dl.download_to(&mut out).unwrap();

        assert_eq!(
            out, body,
            "the full body is streamed even with no Content-Length"
        );
        let totals = totals.lock().unwrap();
        assert!(
            totals.iter().all(|t| t.is_none()),
            "with no Content-Length the callback's total must be None, got {:?}",
            totals
        );
    }

    // --- S1: presigned-URL redaction in the download retry warning ---------------------------

    /// A `log::Log` that captures every record's formatted message into a shared global buffer.
    /// Tests filter the buffer by a unique URL host so a single global logger can serve them all.
    struct CaptureLogger;
    static CAPTURE_LOGGER: CaptureLogger = CaptureLogger;

    fn log_capture() -> &'static std::sync::Mutex<Vec<String>> {
        static BUF: std::sync::OnceLock<std::sync::Mutex<Vec<String>>> = std::sync::OnceLock::new();
        BUF.get_or_init(|| std::sync::Mutex::new(Vec::new()))
    }

    impl log::Log for CaptureLogger {
        fn enabled(&self, _: &log::Metadata) -> bool {
            true
        }
        fn log(&self, record: &log::Record) {
            log_capture()
                .lock()
                .unwrap()
                .push(format!("{}", record.args()));
        }
        fn flush(&self) {}
    }

    fn install_capture_logger() {
        static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
        INIT.get_or_init(|| {
            // Ignore an error if another harness already set the global logger.
            let _ = log::set_logger(&CAPTURE_LOGGER);
            log::set_max_level(log::LevelFilter::Warn);
        });
    }

    #[test]
    fn download_retry_warning_redacts_presigned_signature() {
        // S1: a download that retries must not leak a presigned S3 `X-Amz-Signature` /
        // `X-Amz-Credential` into the retry warning. Drive `download_to` with a flaky client (one
        // failure, then success) so the retry closure fires exactly one `log::warn!`, and assert the
        // captured line carries neither secret. On the pre-fix code (which logged the raw
        // `self.url`) the signature would appear verbatim and this test fails.
        use std::sync::atomic::AtomicU32;

        install_capture_logger();
        let sig = "abc123-secret-signature-value";
        let cred = "AKIAREDACTTESTONLY";
        let host = "s3-redact-retry-test.invalid";
        let url = format!(
            "https://{host}/app.tar.gz?X-Amz-Credential={cred}%2F20260101\
             &X-Amz-Expires=300&X-Amz-Signature={sig}&X-Amz-SignedHeaders=host"
        );

        let attempts = std::sync::Arc::new(AtomicU32::new(0));
        let client = std::sync::Arc::new(FlakyDlClient {
            body: b"ok".to_vec(),
            fail_times: AtomicU32::new(1),
            attempts: attempts.clone(),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url(url);
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        dl.set_retries(
            1,
            std::time::Duration::from_millis(1),
            std::time::Duration::from_millis(2),
        );
        dl.download_to(&mut out).unwrap();

        let lines: Vec<String> = log_capture()
            .lock()
            .unwrap()
            .iter()
            .filter(|l| l.contains(host))
            .cloned()
            .collect();
        assert!(
            !lines.is_empty(),
            "the retry closure should have logged a warning for {host}"
        );
        for line in &lines {
            assert!(
                !line.contains(sig),
                "presigned signature leaked into the retry warning: {line}"
            );
            assert!(
                !line.contains(cred),
                "presigned credential leaked into the retry warning: {line}"
            );
        }
    }

    // --- S3: extracted zip modes must not carry setuid/setgid/sticky --------------------------

    #[cfg(all(unix, feature = "archive-zip"))]
    #[test]
    fn extract_zip_masks_setuid_setgid_sticky_bits() {
        // S3: a zip entry archived with a setuid mode (0o4755) must NOT install a setuid file; the
        // extractor masks the mode to `& 0o777`, so the setuid/setgid/sticky bits are dropped while
        // the ordinary rwx bits survive. On the pre-fix code (`from_mode(mode)`) the installed file
        // would be setuid and this test fails.
        use std::io::Write as _;
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let zip_path = tmp.path().join("archive.zip");
        {
            let file = fs::File::create(&zip_path).unwrap();
            let mut zip = zip::ZipWriter::new(file);
            let opts = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored)
                .unix_permissions(0o4755);
            zip.start_file("payload", opts).unwrap();
            zip.write_all(b"#!/bin/sh\n").unwrap();
            zip.finish().unwrap();
        }

        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir).unwrap();
        let mut ex = Extract::from_source(&zip_path);
        ex.archive(ArchiveKind::Zip);
        ex.extract_into(&out_dir).unwrap();

        let extracted = out_dir.join("payload");
        let mode = fs::metadata(&extracted).unwrap().permissions().mode();
        assert_eq!(
            mode & 0o7000,
            0,
            "extracted file must carry no setuid/setgid/sticky bits, got mode {mode:o}"
        );
        assert_eq!(
            mode & 0o777,
            0o755,
            "the ordinary rwx bits should be preserved, got mode {mode:o}"
        );
    }

    // --- S4: optional max_download_size cap ---------------------------------------------------

    #[test]
    fn download_max_download_size_aborts_when_body_exceeds_cap() {
        // S4: a body larger than the configured cap aborts the streaming download with an error
        // naming the cap, instead of writing an unbounded amount to `dest`.
        let body = vec![0u8; 4096];
        let client = std::sync::Arc::new(DlClient {
            body: body.clone(),
            content_length: Some(body.len() as u64),
            requested: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/big.bin");
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        dl.max_download_size(1024);
        let res = dl.download_to(&mut out);
        assert!(res.is_err(), "a body over the cap must error");
        let msg = res.unwrap_err().to_string();
        assert!(
            msg.contains("max_download_size"),
            "the error should name the cap: {msg}"
        );
    }

    #[test]
    fn download_max_download_size_allows_body_under_cap() {
        // S4: with the default (no cap) unchanged, an explicit cap larger than the body still lets
        // the whole body download successfully.
        let body = vec![7u8; 512];
        let client = std::sync::Arc::new(DlClient {
            body: body.clone(),
            content_length: Some(body.len() as u64),
            requested: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/small.bin");
        dl.set_http_client(
            Some(client),
            #[cfg(feature = "async")]
            None,
        );
        dl.max_download_size(1024);
        dl.download_to(&mut out).unwrap();
        assert_eq!(out, body, "a body under the cap downloads in full");
    }

    /// Async test-double response: yields the body as a single `bytes_stream` chunk and as `text`.
    #[cfg(feature = "async")]
    struct DlAsyncResponse {
        body: Vec<u8>,
        headers: http_client::header::HeaderMap,
    }

    #[cfg(feature = "async")]
    impl http_client::AsyncHttpResponse for DlAsyncResponse {
        fn headers(&self) -> &http_client::header::HeaderMap {
            &self.headers
        }
        fn text(self: Box<Self>) -> futures_util::future::BoxFuture<'static, Result<String>> {
            Box::pin(async move { Ok(String::from_utf8_lossy(&self.body).into_owned()) })
        }
        fn bytes_stream(
            self: Box<Self>,
        ) -> futures_util::stream::BoxStream<'static, Result<bytes::Bytes>> {
            Box::pin(futures_util::stream::once(async move {
                Ok(bytes::Bytes::from(self.body))
            }))
        }
    }

    /// Async test-double client (not reqwest) that records the URL and returns [`DlAsyncResponse`].
    #[cfg(feature = "async")]
    struct DlAsyncClient {
        body: Vec<u8>,
        content_length: Option<u64>,
        requested: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[cfg(feature = "async")]
    impl http_client::AsyncHttpClient for DlAsyncClient {
        fn get<'a>(
            &'a self,
            url: &'a str,
            _headers: &'a http_client::header::HeaderMap,
            _timeout: Option<std::time::Duration>,
        ) -> futures_util::future::BoxFuture<'a, Result<Box<dyn http_client::AsyncHttpResponse>>>
        {
            self.requested.lock().unwrap().push(url.to_string());
            let mut headers = http_client::header::HeaderMap::new();
            if let Some(len) = self.content_length {
                headers.insert(
                    http_client::header::CONTENT_LENGTH,
                    len.to_string().parse().unwrap(),
                );
            }
            let body = self.body.clone();
            Box::pin(async move {
                Ok(Box::new(DlAsyncResponse { body, headers })
                    as Box<dyn http_client::AsyncHttpResponse>)
            })
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn download_to_async_uses_injected_async_client_through_the_trait() {
        // Gap #4 (async Download path): an injected `Arc<dyn AsyncHttpClient>` (not reqwest) must
        // drive `download_to_async` via `bytes_stream()`, independently of the sync injection path.
        let requested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = b"async-injected-payload".to_vec();
        let client = std::sync::Arc::new(DlAsyncClient {
            body: body.clone(),
            content_length: Some(body.len() as u64),
            requested: requested.clone(),
        });

        let mut out = Vec::new();
        let mut dl = Download::from_url("https://nonroutable.invalid/asset.bin");
        dl.set_http_client(None, Some(client));
        dl.download_to_async(&mut out).await.unwrap();

        assert_eq!(
            out, body,
            "download_to_async streamed the injected client's body"
        );
        let urls = requested.lock().unwrap();
        assert_eq!(
            urls.len(),
            1,
            "exactly one async GET went through the injected client"
        );
        assert_eq!(urls[0], "https://nonroutable.invalid/asset.bin");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn sync_and_async_injection_are_independent() {
        // Setting only the async client must leave the sync client unset (and vice versa), proving
        // the two injection slots are independent: a `download_to_async` with only an async client
        // injected uses it, and does not fall back to / require the sync slot.
        let requested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = b"only-async".to_vec();
        let async_client = std::sync::Arc::new(DlAsyncClient {
            body: body.clone(),
            content_length: Some(body.len() as u64),
            requested: requested.clone(),
        });

        let mut dl = Download::from_url("https://nonroutable.invalid/asset.bin");
        dl.set_http_client(None, Some(async_client));
        // The sync slot was never set.
        assert!(
            dl.client.is_none(),
            "injecting an async client must not populate the sync client slot"
        );
        assert!(dl.async_client.is_some(), "the async slot is populated");

        let mut out = Vec::new();
        dl.download_to_async(&mut out).await.unwrap();
        assert_eq!(out, body);
    }

    // Regression: `progress_callback` (the byte-level hook) must still fire even when the
    // `progress-bar` feature is disabled. The terminal `indicatif` bar and the callback are
    // orthogonal; disabling the former must not silence the latter.
    #[cfg(not(feature = "progress-bar"))]
    #[test]
    fn progress_callback_fires_without_progress_bar_feature() {
        use std::net::TcpListener;
        use std::sync::{Arc, Mutex};

        let body = "y".repeat(8_000);
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let served = body.clone();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut buf = [0u8; 1024];
            let _ = stream.read(&mut buf);
            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                served.len(),
                served
            );
            let _ = stream.write_all(resp.as_bytes());
        });

        let calls = Arc::new(Mutex::new(Vec::<(u64, Option<u64>)>::new()));
        let sink = calls.clone();
        let mut out = Vec::new();
        Download::from_url(format!("http://{addr}/file"))
            // `show_download_progress(true)` is intentionally set: with progress-bar OFF it
            // must be a no-op, while the callback below must still fire.
            .show_download_progress(true)
            .progress_callback(move |downloaded, total| {
                sink.lock().unwrap().push((downloaded, total));
            })
            .download_to(&mut out)
            .unwrap();

        assert_eq!(out.len(), 8_000);
        let calls = calls.lock().unwrap();
        assert!(
            !calls.is_empty(),
            "progress_callback must fire even with progress-bar feature disabled"
        );
        assert!(
            calls.iter().all(|(_, total)| *total == Some(8_000)),
            "total should reflect Content-Length"
        );
        assert_eq!(
            calls.last().unwrap().0,
            8_000,
            "final byte count should equal body length"
        );
    }

    #[cfg(feature = "compression-tar-gz")]
    #[test]
    fn detect_plain_gz() {
        assert_eq!(
            ArchiveKind::Plain(Some(Compression::Gz)),
            detect_archive(&PathBuf::from("Something.exe.gz")).unwrap()
        );
    }

    // Without the gzip feature, a plain `.gz` asset must be rejected with `CompressionNotEnabled`,
    // not silently detected as a decodable archive (which would install the compressed bytes).
    #[cfg(not(feature = "compression-tar-gz"))]
    #[test]
    fn detect_plain_gz_without_feature_errors() {
        assert!(matches!(
            detect_archive(&PathBuf::from("Something.exe.gz")),
            Err(Error::CompressionNotEnabled(_))
        ));
    }

    #[cfg(not(feature = "archive-tar"))]
    #[test]
    #[ignore]
    fn detect_tar_gz() {
        println!("WARNING: Please enable 'archive-tar' feature!");
    }
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
    #[test]
    fn detect_tar_gz() {
        assert_eq!(
            ArchiveKind::Tar(Some(Compression::Gz)),
            detect_archive(&PathBuf::from("Something.tar.gz")).unwrap()
        );
    }
    // `.tar.gz` with the tar container but no gzip codec must error, not fall through to an opaque
    // failure inside the tar reader.
    #[cfg(all(feature = "archive-tar", not(feature = "compression-tar-gz")))]
    #[test]
    fn detect_tar_gz_without_compression_errors() {
        assert!(matches!(
            detect_archive(&PathBuf::from("Something.tar.gz")),
            Err(Error::CompressionNotEnabled(_))
        ));
    }

    #[cfg(feature = "compression-tar-xz")]
    #[test]
    fn detect_plain_xz() {
        assert_eq!(
            ArchiveKind::Plain(Some(Compression::Xz)),
            detect_archive(&PathBuf::from("Something.exe.xz")).unwrap()
        );
    }

    // Without the xz feature, a plain `.xz` asset must be rejected with `CompressionNotEnabled`
    // rather than silently installed as still-compressed bytes (the original #143 footgun).
    #[cfg(not(feature = "compression-tar-xz"))]
    #[test]
    fn detect_plain_xz_without_feature_errors() {
        assert!(matches!(
            detect_archive(&PathBuf::from("Something.exe.xz")),
            Err(Error::CompressionNotEnabled(_))
        ));
    }

    #[cfg(all(feature = "archive-tar", feature = "compression-tar-xz"))]
    #[test]
    fn detect_tar_xz() {
        // Both the `.tar.xz` double extension and the `.txz` short form resolve to a gzip-free tar.
        assert_eq!(
            ArchiveKind::Tar(Some(Compression::Xz)),
            detect_archive(&PathBuf::from("Something.tar.xz")).unwrap()
        );
        assert_eq!(
            ArchiveKind::Tar(Some(Compression::Xz)),
            detect_archive(&PathBuf::from("Something.txz")).unwrap()
        );
    }

    // `.tar.xz` / `.txz` with the tar container but no xz codec must error, not fall through.
    #[cfg(all(feature = "archive-tar", not(feature = "compression-tar-xz")))]
    #[test]
    fn detect_tar_xz_without_compression_errors() {
        assert!(matches!(
            detect_archive(&PathBuf::from("Something.tar.xz")),
            Err(Error::CompressionNotEnabled(_))
        ));
        assert!(matches!(
            detect_archive(&PathBuf::from("Something.txz")),
            Err(Error::CompressionNotEnabled(_))
        ));
    }

    #[cfg(not(feature = "archive-tar"))]
    #[test]
    #[ignore]
    fn detect_plain_tar() {
        println!("WARNING: Please enable 'archive-tar' feature!");
    }
    #[cfg(feature = "archive-tar")]
    #[test]
    fn detect_plain_tar() {
        assert_eq!(
            ArchiveKind::Tar(None),
            detect_archive(&PathBuf::from("Something.tar")).unwrap()
        );
    }

    #[cfg(not(feature = "archive-zip"))]
    #[test]
    #[ignore]
    fn detect_zip() {
        println!("WARNING: Please enable 'archive-zip' feature!");
    }
    #[cfg(feature = "archive-zip")]
    #[test]
    fn detect_zip() {
        assert_eq!(
            ArchiveKind::Zip,
            detect_archive(&PathBuf::from("Something.zip")).unwrap()
        );
    }

    #[allow(dead_code)]
    fn cmp_content<T: AsRef<Path>>(path: T, s: &str) {
        let mut content = String::new();
        let mut f = File::open(&path).unwrap();
        f.read_to_string(&mut content).unwrap();
        assert!(s == content);
    }

    #[cfg(not(feature = "compression-tar-gz"))]
    #[test]
    #[ignore]
    fn unpack_plain_gzip() {
        println!("WARNING: Please enable 'compression-tar-gz' feature!");
    }
    #[cfg(feature = "compression-tar-gz")]
    #[test]
    fn unpack_plain_gzip() {
        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_unpack_plain_gzip_src")
            .tempdir()
            .expect("tempdir fail");
        let fp = tmp_dir.path().with_file_name("temp.gz");
        let mut tmp_file = File::create(&fp).expect("temp file create fail");
        let mut e = GzEncoder::new(&mut tmp_file, flate2::Compression::default());
        e.write_all(b"This is a test!").expect("gz encode fail");
        e.finish().expect("gz finish fail");

        let out_tmp = tempfile::Builder::new()
            .prefix("self_update_unpack_plain_gzip_outdir")
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();
        Extract::from_source(&fp)
            .extract_into(out_path)
            .expect("extract fail");
        let out_file = out_path.join("temp");
        assert!(out_file.exists());
        cmp_content(out_file, "This is a test!");
    }

    #[cfg(not(feature = "compression-tar-gz"))]
    #[test]
    #[ignore]
    fn unpack_plain_gzip_double_ext() {
        println!("WARNING: Please enable 'compression-tar-gz' feature!");
    }
    #[cfg(feature = "compression-tar-gz")]
    #[test]
    fn unpack_plain_gzip_double_ext() {
        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_unpack_plain_gzip_double_ext_src")
            .tempdir()
            .expect("tempdir fail");
        let fp = tmp_dir.path().with_file_name("temp.txt.gz");
        let mut tmp_file = File::create(&fp).expect("temp file create fail");
        let mut e = GzEncoder::new(&mut tmp_file, flate2::Compression::default());
        e.write_all(b"This is a test!").expect("gz encode fail");
        e.finish().expect("gz finish fail");

        let out_tmp = tempfile::Builder::new()
            .prefix("self_update_unpack_plain_gzip_double_ext_outdir")
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();
        Extract::from_source(&fp)
            .extract_into(out_path)
            .expect("extract fail");
        let out_file = out_path.join("temp.txt");
        assert!(out_file.exists());
        cmp_content(out_file, "This is a test!");
    }

    #[cfg(not(all(feature = "archive-tar", feature = "compression-tar-gz")))]
    #[test]
    #[ignore]
    fn unpack_tar_gzip() {
        println!("WARNING: Please enable 'archive-tar compression-tar-gz' features!");
    }
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
    #[test]
    fn unpack_tar_gzip() {
        test_extract_into(
            "self_update_unpack_tar_gzip_src",
            "archive.tar.gz",
            ArchiveKind::Tar(Some(Compression::Gz)),
        );
    }

    #[cfg(not(feature = "compression-tar-gz"))]
    #[test]
    #[ignore]
    fn unpack_file_plain_gzip() {
        println!("WARNING: Please enable 'compression-tar-gz' feature!");
    }
    #[cfg(feature = "compression-tar-gz")]
    #[test]
    fn unpack_file_plain_gzip() {
        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_unpack_file_plain_gzip_src")
            .tempdir()
            .expect("tempdir fail");
        let fp = tmp_dir.path().with_file_name("temp.gz");
        let mut tmp_file = File::create(&fp).expect("temp file create fail");
        let mut e = GzEncoder::new(&mut tmp_file, flate2::Compression::default());
        e.write_all(b"This is a test!").expect("gz encode fail");
        e.finish().expect("gz finish fail");

        let out_tmp = tempfile::Builder::new()
            .prefix("self_update_unpack_file_plain_gzip_outdir")
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();
        Extract::from_source(&fp)
            .extract_file(out_path, "renamed_file")
            .expect("extract fail");
        let out_file = out_path.join("renamed_file");
        assert!(out_file.exists());
        cmp_content(out_file, "This is a test!");
    }

    #[cfg(not(all(feature = "archive-tar", feature = "compression-tar-gz")))]
    #[test]
    #[ignore]
    fn unpack_file_tar_gzip() {
        println!("WARNING: Please enable 'archive-tar compression-tar-gz' features!");
    }
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
    #[test]
    fn unpack_file_tar_gzip() {
        test_extract_file(
            "self_update_unpack_file_tar_gzip_src",
            "archive.tar.gz",
            ArchiveKind::Tar(Some(Compression::Gz)),
        );
    }

    // --- xz (#143) round-trips, mirroring the gzip coverage above -----------------------------

    // A plain single-file `.xz` decodes to the file with the `.xz` extension stripped.
    #[cfg(feature = "compression-tar-xz")]
    #[test]
    fn unpack_plain_xz() {
        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_unpack_plain_xz_src")
            .tempdir()
            .expect("tempdir fail");
        let fp = tmp_dir.path().with_file_name("temp.xz");
        {
            let mut tmp_file = File::create(&fp).expect("temp file create fail");
            lzma_rs::xz_compress(&mut &b"This is a test!"[..], &mut tmp_file)
                .expect("xz encode fail");
        }

        let out_tmp = tempfile::Builder::new()
            .prefix("self_update_unpack_plain_xz_outdir")
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();
        Extract::from_source(&fp)
            .extract_into(out_path)
            .expect("extract fail");
        let out_file = out_path.join("temp");
        assert!(out_file.exists());
        cmp_content(out_file, "This is a test!");
    }

    // A plain `.xz` extracted via `extract_file` is written under the requested name.
    #[cfg(feature = "compression-tar-xz")]
    #[test]
    fn unpack_file_plain_xz() {
        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_unpack_file_plain_xz_src")
            .tempdir()
            .expect("tempdir fail");
        let fp = tmp_dir.path().with_file_name("temp.xz");
        {
            let mut tmp_file = File::create(&fp).expect("temp file create fail");
            lzma_rs::xz_compress(&mut &b"This is a test!"[..], &mut tmp_file)
                .expect("xz encode fail");
        }

        let out_tmp = tempfile::Builder::new()
            .prefix("self_update_unpack_file_plain_xz_outdir")
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();
        Extract::from_source(&fp)
            .extract_file(out_path, "renamed_file")
            .expect("extract fail");
        let out_file = out_path.join("renamed_file");
        assert!(out_file.exists());
        cmp_content(out_file, "This is a test!");
    }

    // A `.tar.xz` unpacks its full tree, exercising the streamed tar-over-xz path end to end.
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-xz"))]
    #[test]
    fn unpack_tar_xz() {
        test_extract_into(
            "self_update_unpack_tar_xz_src",
            "archive.tar.xz",
            ArchiveKind::Tar(Some(Compression::Xz)),
        );
    }

    // A single member of a `.tar.xz` is extractable by path.
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-xz"))]
    #[test]
    fn unpack_file_tar_xz() {
        test_extract_file(
            "self_update_unpack_file_tar_xz_src",
            "archive.tar.xz",
            ArchiveKind::Tar(Some(Compression::Xz)),
        );
    }

    #[cfg(not(feature = "archive-zip"))]
    #[test]
    #[ignore]
    fn unpack_zip() {
        println!("WARNING: Please enable 'archive-zip' feature!");
    }
    #[cfg(feature = "archive-zip")]
    #[test]
    fn unpack_zip() {
        test_extract_into(
            "self_update_unpack_zip_src",
            "archive.zip",
            ArchiveKind::Zip,
        );
    }

    #[cfg(not(feature = "archive-zip"))]
    #[test]
    #[ignore]
    fn unpack_zip_file() {
        println!("WARNING: Please enable 'archive-zip' feature!");
    }
    #[cfg(feature = "archive-zip")]
    #[test]
    fn unpack_zip_file() {
        test_extract_file(
            "self_update_unpack_zip_src",
            "archive.zip",
            ArchiveKind::Zip,
        );
    }

    fn test_extract_into(tmpfile_prefix: &str, src_archive_path: &str, archive_kind: ArchiveKind) {
        let tmp_dir = tempfile::Builder::new()
            .prefix(tmpfile_prefix)
            .tempdir()
            .expect("Failed to create temp dir");

        let tmp_path = tmp_dir.path();
        let archive_file_path = tmp_path.join(src_archive_path);
        let archive_file = File::create(&archive_file_path).expect("Failed to create archive file");

        build_test_archive(archive_file, &archive_file_path, archive_kind);

        let out_tmp = tempfile::Builder::new()
            .prefix(&format!("{}_outdir", tmpfile_prefix))
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();

        Extract::from_source(&archive_file_path)
            .extract_into(out_path)
            .expect("extract fail");

        let out_file = out_path.join("temp.txt");
        assert!(out_file.exists());
        cmp_content(&out_file, "This is a test!");

        let out_file = out_path.join("inner_archive/temp2.txt");
        assert!(out_file.exists());
        cmp_content(&out_file, "This is a second test!");
    }

    fn test_extract_file(tmpfile_prefix: &str, src_archive_path: &str, archive_kind: ArchiveKind) {
        let tmp_dir = tempfile::Builder::new()
            .prefix(tmpfile_prefix)
            .tempdir()
            .expect("Failed to create temp dir");

        let tmp_path = tmp_dir.path();
        let archive_file_path = tmp_path.join(src_archive_path);
        let archive_file = File::create(&archive_file_path).expect("Failed to create archive file");

        build_test_archive(archive_file, &archive_file_path, archive_kind);

        let out_tmp = tempfile::Builder::new()
            .prefix(&format!("{}_outdir", tmpfile_prefix))
            .tempdir()
            .expect("tempdir fail");
        let out_path = out_tmp.path();

        Extract::from_source(&archive_file_path)
            .extract_file(out_path, "temp.txt")
            .expect("extract fail");
        let out_file = out_path.join("temp.txt");
        assert!(out_file.exists());
        cmp_content(&out_file, "This is a test!");

        Extract::from_source(&archive_file_path)
            .extract_file(out_path, "inner_archive/temp2.txt")
            .expect("extract fail");
        let out_file = out_path.join("inner_archive/temp2.txt");
        assert!(out_file.exists());
        cmp_content(&out_file, "This is a second test!");
    }

    // A zip whose entry name escapes the output dir (`../escape.txt`) must be rejected, and nothing
    // may be written outside `into_dir`. Guards against zip-slip.
    #[cfg(feature = "archive-zip")]
    #[test]
    fn extract_into_rejects_zip_slip() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("evil.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("../escape.txt", options).expect("start");
            zip.write_all(b"pwned").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let out_dir = out_tmp.path().join("into");
        fs::create_dir_all(&out_dir).expect("mkdir");

        let res = Extract::from_source(&archive_path).extract_into(&out_dir);
        assert!(res.is_err(), "a zip-slip entry must be rejected");
        assert!(
            !out_tmp.path().join("escape.txt").exists(),
            "nothing must be written outside the extraction dir"
        );
    }

    // A tar built as `tar -czf a.tar.gz -C dir .` names its entries `./f1.txt`, which is what GNU
    // tar produces for the most common "archive this directory" invocation. `bin_path_in_archive`
    // is written the way a user reads the file name ("f1.txt"), so the lookup must see through the
    // leading `./` rather than failing with "Could not find the required path in the archive".
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
    #[test]
    fn extract_file_finds_a_dot_slash_prefixed_tar_entry() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("dot.tar.gz");
        {
            let mut ar = tar::Builder::new(vec![]);
            let mut header = tar::Header::new_gnu();
            // Write the name into the raw GNU header: `set_path` / `append_data` normalize a
            // leading `./` away, which would make this test vacuous. GNU tar keeps it.
            {
                let gnu = header.as_gnu_mut().expect("gnu header");
                let raw = b"./f1.txt";
                gnu.name[..raw.len()].copy_from_slice(raw);
            }
            header.set_size(5);
            header.set_mode(0o644);
            header.set_cksum();
            ar.append(&header, &b"hello"[..]).expect("append");
            let bytes = ar.into_inner().expect("finish tar");
            let mut out = File::create(&archive_path).expect("create archive");
            let mut e = GzEncoder::new(&mut out, flate2::Compression::default());
            e.write_all(&bytes).expect("gz write");
            e.finish().expect("gz finish");
        }
        // Guard against a vacuous test: confirm the archive really stores the `./`-prefixed name
        // (a writer that silently normalized it away would make the lookup below trivial).
        {
            let f = File::open(&archive_path).expect("open archive");
            let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(f));
            let names: Vec<String> = ar
                .entries()
                .expect("entries")
                .map(|e| {
                    e.expect("entry")
                        .path()
                        .expect("path")
                        .display()
                        .to_string()
                })
                .collect();
            assert_eq!(names, vec!["./f1.txt".to_string()], "stored entry name");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_file(out_tmp.path(), "f1.txt")
            .expect("a `./`-prefixed entry must be found by its plain name");
        assert_eq!(
            fs::read(out_tmp.path().join("f1.txt")).expect("read extracted"),
            b"hello"
        );
    }

    // Zip sibling of `extract_file_finds_a_dot_slash_prefixed_tar_entry`: some zip writers store
    // entries with a `./` prefix too, and the by-name lookup is an exact string match.
    #[cfg(feature = "archive-zip")]
    #[test]
    fn extract_file_finds_a_dot_slash_prefixed_zip_entry() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("dot.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("./f1.txt", options).expect("start");
            zip.write_all(b"hello").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_file(out_tmp.path(), "f1.txt")
            .expect("a `./`-prefixed zip entry must be found by its plain name");
        assert_eq!(
            fs::read(out_tmp.path().join("f1.txt")).expect("read extracted"),
            b"hello"
        );
    }

    // The tolerance runs both ways: a caller who writes the path as `./f1.txt` (copying it out of
    // `tar tzf` output) must find an entry stored as plain `f1.txt`.
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
    #[test]
    fn extract_file_accepts_a_dot_slash_prefixed_request() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("plain.tar.gz");
        {
            let mut ar = tar::Builder::new(vec![]);
            let mut header = tar::Header::new_gnu();
            header.set_size(5);
            header.set_mode(0o644);
            header.set_cksum();
            ar.append_data(&mut header, "f1.txt", &b"hello"[..])
                .expect("append");
            let bytes = ar.into_inner().expect("finish tar");
            let mut out = File::create(&archive_path).expect("create archive");
            let mut e = GzEncoder::new(&mut out, flate2::Compression::default());
            e.write_all(&bytes).expect("gz write");
            e.finish().expect("gz finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_file(out_tmp.path(), "./f1.txt")
            .expect("a `./`-prefixed request must find the plainly-named entry");
        assert_eq!(
            fs::read(out_tmp.path().join("f1.txt")).expect("read extracted"),
            b"hello"
        );
    }

    // Only a LEADING `./` is ignored. Interior components are still compared exactly, so the
    // tolerance cannot start matching a same-named file in a subdirectory (which would extract the
    // wrong binary, silently).
    #[test]
    fn archive_path_matching_ignores_only_a_leading_dot_slash() {
        use std::path::Path;
        assert!(super::archive_path_matches(
            Path::new("./f1.txt"),
            Path::new("f1.txt")
        ));
        assert!(super::archive_path_matches(
            Path::new("f1.txt"),
            Path::new("./f1.txt")
        ));
        assert!(super::archive_path_matches(
            Path::new("./sub/f1.txt"),
            Path::new("sub/f1.txt")
        ));
        assert!(
            !super::archive_path_matches(Path::new("sub/f1.txt"), Path::new("f1.txt")),
            "a file in a subdirectory must not satisfy a top-level request"
        );
        assert!(
            !super::archive_path_matches(Path::new("./other.txt"), Path::new("f1.txt")),
            "different names must not match"
        );
    }

    // A zip carrying a nested tree must be restored recursively, including the case where the
    // archive has no explicit directory entries at all (only deep file names), which is what
    // several zip writers produce.
    #[cfg(feature = "archive-zip")]
    #[test]
    fn extract_into_restores_a_nested_zip_tree_without_dir_entries() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("nested.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // No `add_directory` calls: the parents exist only as path components of these names.
            zip.start_file("top/mid/deep/file.txt", options)
                .expect("start");
            zip.write_all(b"deep").expect("write");
            zip.start_file("top/other.txt", options).expect("start");
            zip.write_all(b"other").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");
        assert_eq!(
            fs::read(out_tmp.path().join("top/mid/deep/file.txt")).expect("read deep"),
            b"deep"
        );
        assert_eq!(
            fs::read(out_tmp.path().join("top/other.txt")).expect("read shallow"),
            b"other"
        );
    }

    // A zip entry carrying an executable unix mode must extract with that mode preserved, so a
    // binary installed from a zip to a custom path stays runnable.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_preserves_zip_unix_mode() {
        use std::os::unix::fs::PermissionsExt;
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("app.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored)
                .unix_permissions(0o755);
            zip.start_file("app", options).expect("start");
            zip.write_all(b"#!/bin/sh\n").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");
        let mode = fs::metadata(out_tmp.path().join("app"))
            .expect("stat")
            .permissions()
            .mode();
        assert!(
            mode & 0o111 != 0,
            "the executable bit must be preserved, got mode {:o}",
            mode
        );
    }

    // A zip entry that is a relative symlink (target inside the tree) must be restored as a real
    // symlink, not written out as a regular file containing the target string. The file it points
    // at must be readable through the link. Guards the `.app` framework-symlink regression.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_restores_relative_zip_symlink() {
        use std::os::unix::fs::FileTypeExt as _;
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("links.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // A real file, and a sibling symlink pointing at it by relative path.
            zip.start_file("dir/real.txt", options).expect("start");
            zip.write_all(b"payload").expect("write");
            zip.add_symlink("dir/link.txt", "real.txt", options)
                .expect("add_symlink");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");

        let link_path = out_tmp.path().join("dir/link.txt");
        let meta = fs::symlink_metadata(&link_path).expect("lstat link");
        assert!(
            meta.file_type().is_symlink(),
            "the entry must be restored as a symlink, not a regular file"
        );
        // Sanity: it must not be some other special file type either.
        assert!(!meta.file_type().is_fifo());
        // The link target must be the stored relative path, and reading through it yields the file.
        let target = fs::read_link(&link_path).expect("readlink");
        assert_eq!(target, Path::new("real.txt"));
        let via_link = fs::read_to_string(&link_path).expect("read through link");
        assert_eq!(via_link, "payload");
    }

    // A zip symlink whose target is absolute must be rejected (it would escape the extraction root),
    // and no symlink or file may be left at the entry path.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_rejects_absolute_zip_symlink() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("abs.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.add_symlink("evil", "/etc/passwd", options)
                .expect("add_symlink");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let res = Extract::from_source(&archive_path).extract_into(out_tmp.path());
        assert!(res.is_err(), "an absolute-target symlink must be rejected");
        assert!(
            fs::symlink_metadata(out_tmp.path().join("evil")).is_err(),
            "no link/file may be left behind for a rejected symlink entry"
        );
    }

    // A zip symlink whose relative target climbs above the extraction root with `..` must be
    // rejected, matching the entry-name zip-slip defense.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_rejects_escaping_zip_symlink() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("escape.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // `add_symlink` preserves the raw target string (unlike `add_symlink_from_path`, which
            // would normalize the `..` away), so the escaping target reaches the extractor intact.
            zip.add_symlink("dir/escape", "../../outside", options)
                .expect("add_symlink");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let res = Extract::from_source(&archive_path).extract_into(out_tmp.path());
        assert!(
            res.is_err(),
            "a `..`-escaping symlink target must be rejected"
        );
        assert!(
            fs::symlink_metadata(out_tmp.path().join("dir/escape")).is_err(),
            "no link/file may be left behind for a rejected symlink entry"
        );
    }

    // A `..` target that stays within the root after resolving against the link's parent dir must
    // be allowed (the lexical check must not over-reject legitimate relative links).
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_allows_in_bounds_dotdot_zip_symlink() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("inbounds.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("top.txt", options).expect("start");
            zip.write_all(b"top-payload").expect("write");
            // Link at `dir/up`; target `../top.txt` resolves to `top.txt` inside the root.
            zip.add_symlink("dir/up", "../top.txt", options)
                .expect("add_symlink");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");
        let link_path = out_tmp.path().join("dir/up");
        let meta = fs::symlink_metadata(&link_path).expect("lstat link");
        assert!(meta.file_type().is_symlink(), "must be a symlink");
        let via_link = fs::read_to_string(&link_path).expect("read through link");
        assert_eq!(via_link, "top-payload");
    }

    // extract_file must not write a symlink entry's target string out as the requested file; it
    // errors instead (documented behavior; use extract_into to restore links).
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_file_rejects_zip_symlink_entry() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("single.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.add_symlink("link", "target.txt", options)
                .expect("add_symlink");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let res = Extract::from_source(&archive_path).extract_file(out_tmp.path(), "link");
        assert!(
            res.is_err(),
            "extracting a symlink entry as a file must error"
        );
        assert!(
            fs::symlink_metadata(out_tmp.path().join("link")).is_err(),
            "no file may be written for a rejected symlink entry"
        );
    }

    // --- symlink_target_escapes: lexical edge cases (private fn, adversarial) ---------------
    // These exercise the pure lexical resolver directly so the boundary logic is pinned
    // independently of zip fixture plumbing.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn symlink_target_escapes_lexical_edges() {
        use std::path::Path;
        let esc = symlink_target_escapes;

        // A bare `..` from a top-level link (parent depth 0) climbs above the root -> escapes.
        assert!(
            esc(Path::new(""), Path::new("..")),
            "top-level `..` escapes"
        );
        // `..` from a depth-1 parent resolves exactly to the root -> allowed (boundary, in-bounds).
        assert!(
            !esc(Path::new("dir"), Path::new("..")),
            "`..` back to root is in-bounds"
        );
        // A deep link climbing exactly back to the root then descending stays in-bounds.
        assert!(
            !esc(Path::new("a/b"), Path::new("../../x")),
            "climb exactly to root then descend is in-bounds"
        );
        // One `..` past the root escapes.
        assert!(
            esc(Path::new("a/b"), Path::new("../../..")),
            "climbing one past root escapes"
        );
        // Mixed `./` current-dir components must not be miscounted as depth.
        assert!(
            !esc(Path::new("dir"), Path::new("./real.txt")),
            "`./` component is a no-op, stays in-bounds"
        );
        assert!(
            !esc(Path::new("dir"), Path::new("./../a")),
            "`./` then `..` from depth 1 stays in-bounds"
        );
        // An empty target string has no components -> resolves to the link's own parent, in-bounds.
        assert!(
            !esc(Path::new("dir"), Path::new("")),
            "empty target is in-bounds"
        );
        // Interior `..` that dips and re-descends but never passes the root is in-bounds.
        assert!(
            !esc(Path::new(""), Path::new("a/../b")),
            "dip and re-descend within root is in-bounds"
        );
        // Interior `..` that transiently passes the root escapes even if it would re-descend.
        assert!(
            esc(Path::new(""), Path::new("a/../../b")),
            "transiently passing root escapes"
        );
        // An absolute target always escapes regardless of parent depth.
        assert!(
            esc(Path::new("a/b/c"), Path::new("/etc/passwd")),
            "absolute target escapes"
        );
        assert!(
            esc(Path::new(""), Path::new("/")),
            "bare root target escapes"
        );
    }

    // A symlink chain fully inside the archive (link A -> link B -> real file) must be restored as
    // two real links, readable through the chain. The checks are lexical and per-entry, so an
    // in-tree chain must extract cleanly regardless of order.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_restores_symlink_chain() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("chain.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("real.txt", options).expect("start");
            zip.write_all(b"chain-payload").expect("write");
            // b -> real.txt, a -> b (all siblings at root).
            zip.add_symlink("b", "real.txt", options).expect("b");
            zip.add_symlink("a", "b", options).expect("a");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");
        let a = out_tmp.path().join("a");
        assert!(
            fs::symlink_metadata(&a)
                .expect("lstat a")
                .file_type()
                .is_symlink(),
            "a must be a symlink"
        );
        assert!(
            fs::symlink_metadata(out_tmp.path().join("b"))
                .expect("lstat b")
                .file_type()
                .is_symlink(),
            "b must be a symlink"
        );
        assert_eq!(
            fs::read_to_string(&a).expect("read through chain"),
            "chain-payload"
        );
    }

    // A link entry whose parent directory has no explicit archive entry (and thus no entry ordered
    // before it) must still extract: the loop's `create_dir_all(parent)` must materialize the path.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_symlink_with_implicit_parent_dir() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("implicit.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("target.txt", options).expect("start");
            zip.write_all(b"impl-payload").expect("write");
            // No `nested/` directory entry precedes this link.
            zip.add_symlink("nested/deep/link", "../../target.txt", options)
                .expect("link");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");
        let link = out_tmp.path().join("nested/deep/link");
        assert!(
            fs::symlink_metadata(&link)
                .expect("lstat")
                .file_type()
                .is_symlink(),
            "link must be created under implicitly-created parents"
        );
        assert_eq!(fs::read_to_string(&link).expect("read"), "impl-payload");
    }

    // NOTE on duplicate-path entries: the handoff asked to probe two entries at the same path
    // (regular file then symlink, and symlink then regular file, the latter a possible
    // write-through-link vuln). `zip::ZipWriter` (8.6.0) rejects a second entry at an existing
    // name with `InvalidArchive("Duplicate filename")`, so a duplicate-path fixture cannot be
    // built through the crate's own writer; that code path (the `remove_file` before `symlink`,
    // and `File::create` over a pre-existing link) is only reachable via a hand-forged archive.
    // It is left uncovered here rather than hand-assembling raw zip bytes -- see certification.
    // The stronger, writer-buildable escape is the symlinked-parent bypass below, which needs no
    // duplicate paths.

    // SECURITY: the per-entry lexical `symlink_target_escapes` check alone can be bypassed by
    // first creating a symlinked intermediate directory that aliases to a shallower path. The
    // lexical depth counted for a later link over-estimates the real filesystem depth, so an
    // escaping target would pass the lexical check. The physical-parent verification (canonicalize
    // the entry's parent and require it to equal `canonical_root/<lexical parent>`) is the backstop
    // that rejects any descent through a symlinked ancestor. This pins the rejection.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_rejects_symlink_through_symlinked_parent() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("bypass.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // 1) `d/sl` -> `..`  (link_parent depth 1, `..` -> depth 0, lexically allowed).
            //    Physically aliases `d/sl` to the root.
            zip.add_symlink("d/sl", "..", options).expect("sl");
            // 2) `d/sl/evil` -> `../../x`. Lexically in-bounds, but `d/sl` aliases the root so the
            //    link would land at <root>/evil pointing ABOVE the root. The physical-parent check
            //    rejects it: canonicalize(<root>/d/sl) == <root>, but the expected parent is
            //    <root>/d/sl, so they differ.
            zip.add_symlink("d/sl/evil", "../../x", options)
                .expect("evil");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let res = Extract::from_source(&archive_path).extract_into(out_tmp.path());
        assert!(
            res.is_err(),
            "a symlink descending through a symlinked parent must be rejected"
        );
        // No escaping link may be left behind, at the aliased root location or under `d/sl`.
        assert!(
            fs::symlink_metadata(out_tmp.path().join("evil")).is_err(),
            "no escaping link may be planted at the aliased root path"
        );
        assert!(
            fs::symlink_metadata(out_tmp.path().join("d/sl/evil")).is_err(),
            "no escaping link may be planted under the symlinked parent"
        );
    }

    // A regular-file entry that descends through a symlinked parent must also be rejected: even
    // though the write would land inside the root through the alias (an in-bounds target is all a
    // link can hold), the physical-parent check rejects the descent so nothing is written through
    // an aliased directory.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_rejects_regular_file_through_symlinked_parent() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("filebypass.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // `d/sl` -> `..` aliases to the root; then a regular file under it.
            zip.add_symlink("d/sl", "..", options).expect("sl");
            zip.start_file("d/sl/file.txt", options).expect("start");
            zip.write_all(b"through-alias").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let res = Extract::from_source(&archive_path).extract_into(out_tmp.path());
        assert!(
            res.is_err(),
            "a regular file descending through a symlinked parent must be rejected"
        );
        assert!(
            fs::symlink_metadata(out_tmp.path().join("file.txt")).is_err(),
            "no file may be written at the aliased root path"
        );
    }

    // Positive control: a benign tree whose files legitimately descend through REAL directories
    // (a normal nested layout, plus a symlink to a real in-tree directory used only as a leaf link,
    // never descended through) still extracts fine. The physical-parent check must not over-reject.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_allows_files_through_real_directories() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("benign.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("a/b/c/deep.txt", options).expect("start");
            zip.write_all(b"deep-payload").expect("write");
            zip.start_file("a/b/sibling.txt", options).expect("start");
            zip.write_all(b"sibling-payload").expect("write");
            // A symlink to a real in-tree directory (leaf link, not descended through).
            zip.add_symlink("a/link-to-b", "b", options).expect("link");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_into(out_tmp.path())
            .expect("extract");
        assert_eq!(
            fs::read_to_string(out_tmp.path().join("a/b/c/deep.txt")).expect("read deep"),
            "deep-payload"
        );
        assert_eq!(
            fs::read_to_string(out_tmp.path().join("a/b/sibling.txt")).expect("read sibling"),
            "sibling-payload"
        );
        // The leaf symlink resolves to the real directory and reads the same content through it.
        assert_eq!(
            fs::read_to_string(out_tmp.path().join("a/link-to-b/sibling.txt"))
                .expect("read through link"),
            "sibling-payload"
        );
    }

    // ADVERSARIAL (deeper chain): a symlinked ancestor aliases the root, then a file entry
    // descends TWO real levels below the alias (`a/sl -> ..`, then `a/sl/b/c/deep.txt`). The
    // lexical depth of the entry (a/sl/b/c) over-counts the physical depth (root/b/c), so the
    // per-entry lexical check would pass; the physical-parent equality check must still reject the
    // descent through the symlinked ancestor. Pins that the guard holds across multi-level descents,
    // not just a single level below the symlink.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_rejects_file_deep_below_symlinked_ancestor() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("deepchain.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // `a/sl` -> `..` aliases `a/sl` to the extraction root.
            zip.add_symlink("a/sl", "..", options).expect("sl");
            // Two levels below the alias. Lexically in-bounds (no `..`), physically root/b/c.
            zip.start_file("a/sl/b/c/deep.txt", options).expect("start");
            zip.write_all(b"deep-through-alias").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let res = Extract::from_source(&archive_path).extract_into(out_tmp.path());
        assert!(
            res.is_err(),
            "a file two levels below a symlinked ancestor must be rejected"
        );
        // Nothing may be planted at the aliased root location (root/b/c/deep.txt) either.
        assert!(
            fs::symlink_metadata(out_tmp.path().join("b/c/deep.txt")).is_err(),
            "no file may be written at the aliased (shallower) root path"
        );
        assert!(
            fs::symlink_metadata(out_tmp.path().join("a/sl/b/c/deep.txt")).is_err(),
            "no file may be written below the symlinked ancestor"
        );
    }

    // ADVERSARIAL (symlinked destination): the caller's own `into_dir` may legitimately contain a
    // symlink component (e.g. `/tmp/link-to-real`). `canonical_root` captures its resolved
    // (symlink-free) form up front, so a benign nested archive must extract without being falsely
    // rejected: every entry's physical parent resolves to `canonical_root/<lexical parent>` by
    // construction. Guards against the equality check tripping on a symlink the CALLER supplied
    // rather than one an archive entry created.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_allows_symlinked_destination() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("benign-nested.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("sub/deep/file.txt", options).expect("start");
            zip.write_all(b"nested-payload").expect("write");
            zip.finish().expect("finish");
        }
        // The destination handed to `extract_into` is itself a symlink to the real output dir.
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let real_dest = out_tmp.path().join("real-dest");
        fs::create_dir(&real_dest).expect("mkdir real dest");
        let link_dest = out_tmp.path().join("link-to-dest");
        std::os::unix::fs::symlink(&real_dest, &link_dest).expect("symlink dest");

        Extract::from_source(&archive_path)
            .extract_into(&link_dest)
            .expect("extraction into a symlinked destination must not be rejected");
        // The file lands under the real destination, reachable through the caller's symlink.
        assert_eq!(
            fs::read_to_string(real_dest.join("sub/deep/file.txt")).expect("read real"),
            "nested-payload"
        );
        assert_eq!(
            fs::read_to_string(link_dest.join("sub/deep/file.txt")).expect("read via link"),
            "nested-payload"
        );
    }

    // ADVERSARIAL (unguarded dir branch): the `is_dir()` branch runs `create_dir_all` WITHOUT the
    // physical-parent check, on the reasoning that a symlinked ancestor only aliases in-bounds (its
    // target was validated by `symlink_target_escapes`), so directories created through it stay in
    // bounds, and any later FILE entry under it is rejected by the parent check. This probes that
    // reasoning with a symlink aliasing a real in-tree sibling directory: the dir entry created
    // through the alias must land in-bounds, nothing may be created outside the root, and a file
    // entry descending through the same alias must be rejected even though it too would land
    // in-bounds (the equality check is strict, not a mere prefix/containment check).
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_into_dir_through_symlink_stays_in_bounds_and_file_rejected() {
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("dirthrough.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            // Real in-tree directory `a/b` (materialized by a file entry).
            zip.start_file("a/b/keep.txt", options).expect("start keep");
            zip.write_all(b"keep").expect("write keep");
            // `a/sl` -> `b`: a symlink aliasing a real sibling directory (in-bounds target).
            zip.add_symlink("a/sl", "b", options).expect("sl");
            // Directory entry descending through the alias. The unguarded dir branch creates it.
            zip.add_directory("a/sl/planted", options)
                .expect("dir entry");
            // A file entry under the alias must be rejected by the physical-parent equality check
            // even though it would land in-bounds (root/a/b/planted/f.txt).
            zip.start_file("a/sl/planted/f.txt", options)
                .expect("start f");
            zip.write_all(b"through-alias-file").expect("write f");
            zip.finish().expect("finish");
        }
        // Extract into a nested dest so we can assert nothing escapes into the parent.
        let out_tmp = tempfile::tempdir().expect("tempdir");
        let dest = out_tmp.path().join("dest");
        let res = Extract::from_source(&archive_path).extract_into(&dest);
        assert!(
            res.is_err(),
            "a file descending through a symlinked directory must be rejected"
        );
        // The file must not exist at the aliased location, the lexical location, or anywhere.
        assert!(
            fs::symlink_metadata(dest.join("a/b/planted/f.txt")).is_err(),
            "no file may be written at the aliased in-bounds path"
        );
        assert!(
            fs::symlink_metadata(dest.join("a/sl/planted/f.txt")).is_err(),
            "no file may be written at the lexical path under the symlink"
        );
        // The dir branch is unguarded, so `planted` was materialized through the alias -- but it
        // must be IN-BOUNDS (root/a/b/planted), never outside the extraction root.
        if let Ok(meta) = fs::symlink_metadata(dest.join("a/b/planted")) {
            assert!(
                meta.file_type().is_dir(),
                "planted, if present, is a real dir"
            );
        }
        // Nothing may have been created outside `dest`: the extraction parent holds only `dest`.
        let mut stray: Vec<String> = fs::read_dir(out_tmp.path())
            .expect("read parent")
            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
            .collect();
        stray.retain(|name| name != "dest");
        assert!(
            stray.is_empty(),
            "nothing may be created outside the extraction root, found: {:?}",
            stray
        );
    }

    // extract_file on a normal executable-mode regular zip entry is unaffected by the symlink
    // rejection: it extracts and preserves the exec bit.
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_file_regular_exec_entry_unaffected() {
        use std::os::unix::fs::PermissionsExt as _;
        let staging = tempfile::tempdir().expect("tempdir");
        let archive_path = staging.path().join("exec.zip");
        {
            let f = File::create(&archive_path).expect("create zip");
            let mut zip = zip::ZipWriter::new(f);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored)
                .unix_permissions(0o755);
            zip.start_file("bin", options).expect("start");
            zip.write_all(b"#!/bin/sh\n").expect("write");
            zip.finish().expect("finish");
        }
        let out_tmp = tempfile::tempdir().expect("tempdir");
        Extract::from_source(&archive_path)
            .extract_file(out_tmp.path(), "bin")
            .expect("extract_file");
        let out = out_tmp.path().join("bin");
        let mode = fs::metadata(&out).expect("stat").permissions().mode();
        assert!(mode & 0o111 != 0, "exec bit preserved, got {:o}", mode);
        assert_eq!(fs::read_to_string(&out).expect("read"), "#!/bin/sh\n");
    }

    fn build_test_archive<T: AsRef<Path>>(
        mut archive_file: fs::File,
        archive_file_path: T,
        archive_kind: ArchiveKind,
    ) {
        let archive_file_path = archive_file_path.as_ref();

        match archive_kind {
            #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
            ArchiveKind::Tar(Some(Compression::Gz)) => {
                let tmp_tar_path = archive_file_path
                    .parent()
                    .expect("Missing archive file path parent")
                    .join("tar_contents");
                let tmp_tar_inner_path = tmp_tar_path.join("inner_archive");
                fs::create_dir_all(&tmp_tar_inner_path).expect("Failed to create temp tar path");

                let fp = tmp_tar_path.join("temp.txt");
                let mut tmp_file = File::create(fp).expect("temp file create fail");
                tmp_file.write_all(b"This is a test!").unwrap();

                let fp = tmp_tar_inner_path.join("temp2.txt");
                let mut tmp_file = File::create(fp).expect("temp file create fail");
                tmp_file.write_all(b"This is a second test!").unwrap();

                let mut ar = tar::Builder::new(vec![]);
                ar.append_dir_all(".", &tmp_tar_path)
                    .expect("tar append dir all fail");
                let tar_writer = ar.into_inner().expect("failed getting tar writer");

                let mut e = GzEncoder::new(&mut archive_file, flate2::Compression::default());
                io::copy(&mut tar_writer.as_slice(), &mut e)
                    .expect("failed writing from tar archive to gz encoder");
                e.finish().expect("gz finish fail");
            }

            #[cfg(all(feature = "archive-tar", feature = "compression-tar-xz"))]
            ArchiveKind::Tar(Some(Compression::Xz)) => {
                let tmp_tar_path = archive_file_path
                    .parent()
                    .expect("Missing archive file path parent")
                    .join("tar_contents_xz");
                let tmp_tar_inner_path = tmp_tar_path.join("inner_archive");
                fs::create_dir_all(&tmp_tar_inner_path).expect("Failed to create temp tar path");

                let fp = tmp_tar_path.join("temp.txt");
                let mut tmp_file = File::create(fp).expect("temp file create fail");
                tmp_file.write_all(b"This is a test!").unwrap();

                let fp = tmp_tar_inner_path.join("temp2.txt");
                let mut tmp_file = File::create(fp).expect("temp file create fail");
                tmp_file.write_all(b"This is a second test!").unwrap();

                let mut ar = tar::Builder::new(vec![]);
                ar.append_dir_all(".", &tmp_tar_path)
                    .expect("tar append dir all fail");
                let tar_writer = ar.into_inner().expect("failed getting tar writer");

                lzma_rs::xz_compress(&mut tar_writer.as_slice(), &mut archive_file)
                    .expect("failed writing from tar archive to xz encoder");
            }

            #[cfg(feature = "archive-zip")]
            ArchiveKind::Zip => {
                let mut zip = zip::ZipWriter::new(archive_file);
                let options = zip::write::SimpleFileOptions::default()
                    .compression_method(zip::CompressionMethod::Stored);
                zip.start_file("temp.txt", options)
                    .expect("failed starting zip file");
                zip.write_all(b"This is a test!")
                    .expect("failed writing to zip");
                zip.start_file("inner_archive/temp2.txt", options)
                    .expect("failed starting second zip file");
                zip.write_all(b"This is a second test!")
                    .expect("failed writing to second zip");
                zip.finish().expect("failed finishing zip");
            }

            _ => {
                unimplemented!("{:?} not handled", archive_kind);
            }
        }
    }

    // --- extractor `Internal { source: None }` variant-routing -----------------------------
    //
    // These pin the invariant-violation sites in `extract_file`/`extract_into` to EXACTLY
    // `Error::Internal` carrying NO source (the genuine-invariant residue, distinct from the
    // JoinError `Internal { source: Some(..) }`).

    // `extract_file` on a Plain source where the *requested* `file_to_extract` has no file name
    // (e.g. `..`) must route to `Error::Internal { source: None }` ("Extractor source has no
    // file-name"), not an Io error. `file_to_extract` is caller-supplied and need not exist, so
    // this is reachable without a real hostless-path file. (~lib.rs:852)
    #[test]
    fn extract_file_plain_no_file_name_routes_to_internal_without_source() {
        use std::error::Error as _;
        let src_dir = tempfile::tempdir().expect("tempdir");
        let src = src_dir.path().join("payload.bin");
        fs::write(&src, b"hello").expect("write source");

        let out_dir = tempfile::tempdir().expect("out tempdir");

        // `..` has no `file_name()`, firing the invariant branch.
        let err = Extract::from_source(&src)
            .archive(ArchiveKind::Plain(None))
            .extract_file(out_dir.path(), "..")
            .expect_err("a file_to_extract with no file name must error");
        match err {
            Error::Internal {
                ref message,
                ref source,
            } => {
                assert!(
                    source.is_none(),
                    "the no-file-name invariant carries no source, got {:?}",
                    source
                );
                assert!(
                    message.contains("file-name"),
                    "message must describe the missing file name, got: {}",
                    message
                );
            }
            other => panic!("expected Error::Internal, got {:?}", other),
        }
        // Defensive: confirm the variant truly chains no source via the trait too.
        let err = Extract::from_source(&src)
            .archive(ArchiveKind::Plain(None))
            .extract_file(out_dir.path(), "..")
            .unwrap_err();
        assert!(err.source().is_none());
    }

    // `extract_file` on a Tar source where the requested path is not present in the archive must
    // route to `Error::Internal { source: None }` ("Could not find the required path in the
    // archive"), naming the missing path. (~lib.rs:873)
    #[cfg(all(feature = "archive-tar", feature = "compression-tar-gz"))]
    #[test]
    fn extract_file_tar_missing_path_routes_to_internal_without_source() {
        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_ws3_tar_missing_src")
            .tempdir()
            .expect("tempdir");
        let archive_file_path = tmp_dir.path().join("archive.tar.gz");
        let archive_file = File::create(&archive_file_path).expect("create archive");
        build_test_archive(
            archive_file,
            &archive_file_path,
            ArchiveKind::Tar(Some(Compression::Gz)),
        );

        let out_tmp = tempfile::tempdir().expect("out tempdir");
        let err = Extract::from_source(&archive_file_path)
            .extract_file(out_tmp.path(), "does/not/exist.txt")
            .expect_err("a path absent from the tar must error");
        match err {
            Error::Internal {
                ref message,
                ref source,
            } => {
                assert!(
                    source.is_none(),
                    "the path-not-found invariant carries no source, got {:?}",
                    source
                );
                assert!(
                    message.contains("Could not find the required path"),
                    "message must describe the missing archive path, got: {}",
                    message
                );
            }
            other => panic!("expected Error::Internal, got {:?}", other),
        }
    }

    // `extract_file` on a Zip source where the requested path is not valid UTF-8 must route to
    // `Error::Internal { source: None }` ("cannot extract file with a non-UTF-8 path"). Reachable
    // on Unix by building an `OsStr` from raw non-UTF-8 bytes. (~lib.rs:903)
    #[cfg(all(feature = "archive-zip", unix))]
    #[test]
    fn extract_file_zip_non_utf8_path_routes_to_internal_without_source() {
        use std::os::unix::ffi::OsStrExt;

        let tmp_dir = tempfile::Builder::new()
            .prefix("self_update_ws3_zip_nonutf8_src")
            .tempdir()
            .expect("tempdir");
        let archive_file_path = tmp_dir.path().join("archive.zip");
        let archive_file = File::create(&archive_file_path).expect("create archive");
        build_test_archive(archive_file, &archive_file_path, ArchiveKind::Zip);

        let out_tmp = tempfile::tempdir().expect("out tempdir");
        // 0xFF is never valid UTF-8.
        let bad = std::ffi::OsStr::from_bytes(b"bad\xFFname");
        let err = Extract::from_source(&archive_file_path)
            .extract_file(out_tmp.path(), bad)
            .expect_err("a non-UTF-8 zip path must error");
        match err {
            Error::Internal {
                ref message,
                ref source,
            } => {
                assert!(
                    source.is_none(),
                    "the non-UTF-8-path invariant carries no source, got {:?}",
                    source
                );
                assert!(
                    message.contains("non-UTF-8 path"),
                    "message must describe the non-UTF-8 path, got: {}",
                    message
                );
            }
            other => panic!("expected Error::Internal, got {:?}", other),
        }
    }
}