mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

use base64::Engine;
use base64::prelude::BASE64_STANDARD;
use eyre::{Report, Result, WrapErr, bail, ensure, eyre};
use regex::Regex;
use reqwest::StatusCode;
use reqwest::header::{
    ACCEPT_ENCODING, AUTHORIZATION, CONTENT_RANGE, CONTENT_TYPE, COOKIE, DATE, ETAG, HeaderMap,
    HeaderName, HeaderValue, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, LAST_MODIFIED,
    PROXY_AUTHORIZATION, RANGE,
};
use reqwest::{ClientBuilder, IntoUrl, Method, Response, ResponseBuilderExt};
use serde::{Deserialize, Serialize};
use std::sync::LazyLock as Lazy;
use tokio::io::AsyncWriteExt;
use tokio::sync::OnceCell;
use url::Url;

use crate::file::display_path;
use crate::netrc;
use crate::progress::SingleReport;
use crate::redactions::redact_url_userinfo;
use crate::time::format_duration;
use crate::{env, file};
use mise_settings::Settings;

mod cas;

pub static HTTP: Lazy<Client> = Lazy::new(|| {
    Client::new_shared(
        crate::network::http_timeout(&Settings::get()),
        ClientKind::Http,
    )
});

/// HTTP client for streaming request bodies that can take longer than
/// `http_timeout` to transmit.
///
/// It keeps HTTP's connection timeout and redirect policy but omits reqwest's
/// read timeout. Reqwest starts that timer before a streaming request body has
/// finished sending, so applying it here would abort a healthy slow upload
/// before the server can send its response.
pub static HTTP_UPLOAD: Lazy<Client> = Lazy::new(|| {
    Client::new_shared_without_read_timeout(
        crate::network::http_timeout(&Settings::get()),
        ClientKind::Http,
    )
});

pub static HTTP_FETCH: Lazy<Client> = Lazy::new(|| {
    Client::new_shared(
        crate::network::configured_fetch_remote_versions_timeout(&Settings::get()),
        ClientKind::Fetch,
    )
});

/// Follows HTTPS-to-HTTP redirects, which [`HTTP`] refuses. Private so the only
/// way to use it is [`download_file_checksum_pinned`], which rejects the bytes
/// unless they match a checksum the caller already holds; the transport then
/// adds nothing to the integrity of the result. Mirror redirectors need this:
/// `ftpmirror.gnu.org`, the URL of every GNU formula, sends some regions to
/// plain-HTTP mirrors. Unix-only, like its one caller, brew source builds.
#[cfg(unix)]
static HTTP_CHECKSUM_PINNED: Lazy<Client> = Lazy::new(|| {
    Client::new_shared_with(
        crate::network::http_timeout(&Settings::get()),
        ClientKind::Http,
        Downgrade::FollowChecksumPinned,
    )
});

/// In-memory cache for HTTP text responses, useful for requests that are repeated
/// during a single operation (e.g., fetching SHASUMS256.txt for multiple platforms).
/// Each URL gets its own OnceCell to ensure concurrent requests for the same URL
/// wait for the first fetch to complete rather than all fetching simultaneously.
type CachedResult = Arc<OnceCell<Result<String, CachedFailure>>>;
static HTTP_CACHE: Lazy<Mutex<HashMap<String, CachedResult>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));
/// Origins that returned a hard connection failure during a prefer-offline
/// process. Keep the original error text so a short-circuited request remains
/// actionable rather than hiding the reason the circuit opened.
static UNAVAILABLE_HTTP_HOSTS: Lazy<Mutex<HashMap<String, String>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));
type RetryStateHandle = Arc<Mutex<RetryState>>;

/// A failed [`HttpClient::get_text_cached`] request, kept as text so every
/// caller of the URL can share it, along with whether it ever reached the
/// server so [`is_unreachable`] still recognizes it.
#[derive(Clone, Debug)]
struct CachedFailure {
    message: String,
    unreachable: bool,
}

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

impl std::error::Error for CachedFailure {}

#[derive(Debug)]
struct UnavailableHttpHost {
    origin: String,
    cause: String,
}

impl std::fmt::Display for UnavailableHttpHost {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "HTTP host {} is unavailable after an earlier connection failure: {}",
            self.origin, self.cause
        )
    }
}

impl std::error::Error for UnavailableHttpHost {}

struct RetryState {
    headers: HeaderMap,
    use_netrc: bool,
    netrc_replacement_only: bool,
}

fn new_retry_state(headers: &HeaderMap, netrc_replacement_only: bool) -> RetryStateHandle {
    Arc::new(Mutex::new(RetryState {
        headers: headers.clone(),
        use_netrc: true,
        netrc_replacement_only,
    }))
}

/// `headers` with the credentials an earlier attempt settled on: a refreshed
/// token, or none once a token was rejected. Only Authorization is taken from the
/// saved state, which also holds that attempt's own Range and conditional headers.
fn with_saved_authorization(headers: &HeaderMap, retry_state: &RetryStateHandle) -> HeaderMap {
    let mut headers = headers.clone();
    match retry_state.lock().unwrap().headers.get(AUTHORIZATION) {
        Some(value) => {
            headers.insert(AUTHORIZATION, value.clone());
        }
        None => {
            headers.remove(AUTHORIZATION);
        }
    }
    headers
}

/// The headers and send options for the next attempt, which an earlier attempt
/// may have changed (a refreshed token, netrc turned off).
fn attempt_options(
    retry_state: &RetryStateHandle,
    error_for_status: bool,
) -> (HeaderMap, SendOnceOptions) {
    let (headers, use_netrc, netrc_replacement_only) = {
        let state = retry_state.lock().unwrap();
        (
            state.headers.clone(),
            state.use_netrc,
            state.netrc_replacement_only,
        )
    };
    let mut options = SendOnceOptions::new(Some(retry_state.clone()), use_netrc);
    options.netrc_replacement_only = netrc_replacement_only;
    let options = if error_for_status {
        options
    } else {
        options.allow_error_status()
    };
    (headers, options)
}

/// The parts of a request that stay fixed across retry attempts.
struct RetryableRequest<'a> {
    method: Method,
    url: Url,
    headers: &'a HeaderMap,
    verb_label: &'a str,
    retries: i64,
    error_for_status: bool,
}

#[derive(Clone)]
struct SendOnceOptions {
    use_netrc: bool,
    /// Apply netrc only when a URL replacement moved the request to another host.
    netrc_replacement_only: bool,
    retry_github_oauth_401: bool,
    error_for_status: bool,
    allow_range_not_satisfiable: bool,
    retry_state: Option<RetryStateHandle>,
}

impl SendOnceOptions {
    fn check_response(&self, response: Response) -> Result<Response> {
        if self.error_for_status
            && !(self.allow_range_not_satisfiable
                && response.status() == StatusCode::RANGE_NOT_SATISFIABLE)
            && let Err(err) = response.error_for_status_ref().map_err(redact_error_url)
        {
            return Err(match retry_after(&response) {
                Some(wait) => {
                    let message = err.to_string();
                    Report::new(err).wrap_err(RetryAfter { wait, message })
                }
                None => err.into(),
            });
        }
        Ok(response)
    }

    fn new(retry_state: Option<RetryStateHandle>, use_netrc: bool) -> Self {
        Self {
            use_netrc,
            netrc_replacement_only: false,
            retry_github_oauth_401: true,
            error_for_status: true,
            allow_range_not_satisfiable: false,
            retry_state,
        }
    }

    fn allow_error_status(mut self) -> Self {
        self.error_for_status = false;
        self
    }

    fn allow_range_not_satisfiable(mut self) -> Self {
        self.allow_range_not_satisfiable = true;
        self
    }

    fn recursive_retry(&self) -> Self {
        Self {
            use_netrc: false,
            netrc_replacement_only: false,
            retry_github_oauth_401: false,
            error_for_status: self.error_for_status,
            allow_range_not_satisfiable: self.allow_range_not_satisfiable,
            retry_state: self.retry_state.clone(),
        }
    }
}

const PARTIAL_DOWNLOAD_STATE_VERSION: u8 = 3;
const PARTIAL_DOWNLOAD_MAX_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
enum DownloadValidator {
    Etag(String),
    LastModified {
        value: String,
        response_date: String,
    },
}

impl DownloadValidator {
    fn as_header_value(&self) -> &str {
        match self {
            Self::Etag(value) | Self::LastModified { value, .. } => value,
        }
    }

    fn matches(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Etag(a), Self::Etag(b)) => a == b,
            (Self::LastModified { value: a, .. }, Self::LastModified { value: b, .. }) => a == b,
            _ => false,
        }
    }

    fn is_valid(&self) -> bool {
        match self {
            Self::Etag(value) => !value.is_empty() && !value.starts_with("W/"),
            Self::LastModified {
                value,
                response_date,
            } => is_strong_last_modified(value, response_date),
        }
    }
}

/// Whether a download may use the store. With `locked` or `paranoid` only a
/// pinned one may: the checksum is checked after the download, so a store that
/// was restored or shared can't change what gets installed, while an unpinned
/// download has nothing to check a kept file against.
fn cache_allowed(pin: Option<&str>) -> bool {
    let settings = Settings::get();
    settings.download_cache
        && (pin.is_some() || !(settings.locked || settings.paranoid.provenance()))
}

/// How a download may use the store of finished downloads.
#[derive(Clone, Copy)]
struct CacheMode<'a> {
    /// The checksum the tool pinned, as `algo:hex`.
    pin: Option<&'a str>,
    enabled: bool,
}

/// How a download was satisfied.
struct Fetched {
    metadata: DownloadFileMetadata,
    /// A stored file answered the request, so nothing was written to the
    /// destination.
    stored: Option<PathBuf>,
    /// The validator that came with a complete response, for keeping it.
    validator: Option<DownloadValidator>,
    request_hash: String,
    /// The URL requested, which a kept file is pinned under.
    url: String,
}

/// How long a download may take and how much it may write.
#[derive(Clone)]
struct DownloadLimits {
    /// For every attempt and backoff delay together.
    time: Duration,
    /// More fails the download. `None` for files that are streamed to disk
    /// and never read into memory whole.
    bytes: Option<u64>,
    /// Whether netrc may still be sent, shared by every attempt and restart of
    /// the download so a login the server rejected is not sent again.
    netrc: RetryStateHandle,
}

impl DownloadLimits {
    fn new(bytes: Option<u64>, headers: &HeaderMap) -> Self {
        Self {
            time: crate::network::http_download_timeout(&Settings::get()),
            bytes,
            netrc: new_retry_state(headers, false),
        }
    }
}

/// What every attempt is told, and what an attempt learned beyond the bytes it
/// wrote.
#[derive(Default)]
struct AttemptOutcome {
    /// The most bytes the download may write.
    max_bytes: Option<u64>,
    /// The validator of the stored copy, sent so the server can confirm it.
    cond: Option<DownloadValidator>,
    /// The server confirmed the stored copy is current; nothing was written.
    not_modified: std::sync::atomic::AtomicBool,
    /// The validator that came with a complete response, for keeping it.
    validator: Mutex<Option<DownloadValidator>>,
    /// Whether netrc may still be sent; see [`DownloadLimits::netrc`].
    netrc: Option<RetryStateHandle>,
}

#[derive(Debug)]
struct DownloadSizeMismatch {
    expected: u64,
    actual: u64,
}

impl std::fmt::Display for DownloadSizeMismatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "downloaded file size mismatch: expected {} bytes, got {}",
            self.expected, self.actual
        )
    }
}

impl std::error::Error for DownloadSizeMismatch {}

/// A GitHub 403 that is really a rate limit.
///
/// GitHub answers an exhausted rate limit with 403, not 429, so without this
/// marker such a response is indistinguishable from a deterministic "you may
/// not do that" and [`is_transient`] declines to retry it — even though
/// `http_retries` documents 429 as retryable. Carrying the whole message means
/// the marker changes classification without changing what the user reads.
#[derive(Debug)]
struct GithubRateLimited(String);

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

impl std::error::Error for GithubRateLimited {}

/// Longest `Retry-After` the retry loop will wait out. Past this, retrying
/// within the backoff schedule only adds requests to a limiter that is still
/// blocking us, so the 429 is returned for the caller to fall back on.
const MAX_RETRY_AFTER: Duration = Duration::from_secs(30);

/// A 429 that told us how long to wait. Wraps the status error, so
/// [`error_code`] still sees the 429, and carries the message so what the user
/// reads is unchanged apart from the wait.
#[derive(Debug)]
struct RetryAfter {
    wait: Duration,
    message: String,
}

impl std::fmt::Display for RetryAfter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} (retry-after: {}s)",
            self.message,
            self.wait.as_secs()
        )
    }
}

/// How long to sleep before retrying: the scheduled backoff, or the wait the
/// server asked for if that is longer.
fn retry_delay(backoff: Duration, err: &Report) -> Duration {
    err.downcast_ref::<RetryAfter>()
        .map_or(backoff, |retry_after| backoff.max(retry_after.wait))
}

/// The wait a 429 asked for, in delay-seconds form. An HTTP-date, which no
/// host we talk to sends, is ignored and the normal backoff applies.
fn retry_after(response: &Response) -> Option<Duration> {
    if response.status() != StatusCode::TOO_MANY_REQUESTS {
        return None;
    }
    response
        .headers()
        .get(reqwest::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .map(Duration::from_secs)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct PartialDownloadState {
    version: u8,
    request_hash: String,
    validator: DownloadValidator,
    total_size: Option<u64>,
    effective_filename: Option<String>,
}

/// Safe response metadata exposed to download callers.
///
/// This intentionally contains only the final URL's decoded path basename.
/// Query strings, fragments, credentials, and the complete URL are never
/// persisted in resumable download state.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DownloadFileMetadata {
    pub effective_filename: Option<String>,
}

type SharedDownload =
    std::sync::Arc<tokio::sync::OnceCell<(tempfile::TempDir, DownloadFileMetadata)>>;
static INVOCATION_DOWNLOADS: std::sync::LazyLock<
    std::sync::Mutex<std::collections::HashMap<String, SharedDownload>>,
> = std::sync::LazyLock::new(Default::default);

// Bound retained scratch space, excluding transfers still borrowed by callers.
// Active transfers are bounded by their callers' jobs limit and remain shared.
fn prune_shared_downloads(
    downloads: &mut std::collections::HashMap<String, SharedDownload>,
    max_bytes: u64,
    max_entries: usize,
) {
    let size = |entry: &SharedDownload| {
        entry
            .get()
            .and_then(|(directory, _)| {
                std::fs::metadata(directory.path().join("artifact"))
                    .ok()
                    .map(|m| m.len())
            })
            .unwrap_or(0)
    };
    let mut bytes: u64 = downloads.values().map(size).sum();
    let mut count = downloads.len();
    downloads.retain(|_, entry| {
        if (bytes > max_bytes || count > max_entries) && Arc::strong_count(entry) == 1 {
            bytes = bytes.saturating_sub(size(entry));
            count -= 1;
            false
        } else {
            true
        }
    });
}

/// Own temporary shared artifacts for this command, including cancellation paths.
pub struct InvocationDownloads;

impl Drop for InvocationDownloads {
    fn drop(&mut self) {
        INVOCATION_DOWNLOADS.lock().unwrap().clear();
    }
}

fn download_filename_hint(url: &Url) -> Option<String> {
    let segment = url.path_segments()?.next_back()?;
    let filename = urlencoding::decode(segment).ok()?.into_owned();
    if filename.is_empty()
        || filename == "."
        || filename == ".."
        || filename.ends_with([' ', '.'])
        || filename.chars().any(|c| {
            c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
        })
    {
        None
    } else {
        Some(filename)
    }
}

#[derive(Debug, Clone)]
struct PartialDownload {
    path: PathBuf,
    state_path: PathBuf,
    request_hash: String,
}

/// The prefix `tempfile` builds the download-state name from. Named so the length the hint
/// measures and the length that is actually created cannot drift apart.
const DOWNLOAD_STATE_PREFIX: &str = ".mise-download-state.";

/// Name the operation and the path, and add the platform hint the bare error does not carry.
///
/// Every downloaded file lands through `tempfile`, whose persist does **not** get the
/// extended-length path handling `std::fs` applies — `file::PreparedAtomicWrite::commit` records
/// the measurement: it breaks at a 253-character target while `fs::rename` on the same tree
/// succeeds at 415. So on Windows this is the first thing to fail as a directory approaches
/// `MAX_PATH`, and until now it failed as a bare `os error 3` with nothing naming the cause.
fn io_error(err: std::io::Error, doing: &str, path: &Path) -> eyre::Report {
    // The hint is resolved while `err` is still borrowable, then the error becomes the source and
    // the message the context -- the same order `PreparedAtomicWrite::commit` uses.
    let msg = file::with_io_hint(format!("{doing}: {}", display_path(path)), path, &err);
    eyre::Report::new(err).wrap_err(msg)
}

impl PartialDownload {
    fn new(destination: &Path, request_hash: String) -> Result<Self> {
        let parent = destination.parent().ok_or_else(|| {
            eyre!(
                "download destination has no parent: {}",
                destination.display()
            )
        })?;
        let filename = destination
            .file_name()
            .ok_or_else(|| {
                eyre!(
                    "download destination has no filename: {}",
                    destination.display()
                )
            })?
            .to_string_lossy();
        let partial_name = format!(".{filename}.mise-part");
        Ok(Self {
            path: parent.join(&partial_name),
            state_path: parent.join(format!("{partial_name}.json")),
            request_hash,
        })
    }

    fn load(&self) -> Result<Option<(PartialDownloadState, u64)>> {
        let state_bytes = match std::fs::read(&self.state_path) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                self.remove_partial_if_exists()?;
                return Ok(None);
            }
            Err(err) => return Err(err.into()),
        };
        let state: PartialDownloadState = match serde_json::from_slice(&state_bytes) {
            Ok(state) => state,
            Err(_) => {
                self.clear()?;
                return Ok(None);
            }
        };
        let partial_size = match std::fs::metadata(&self.path) {
            Ok(metadata) => metadata.len(),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                self.remove_state_if_exists()?;
                return Ok(None);
            }
            Err(err) => return Err(err.into()),
        };
        if state.version != PARTIAL_DOWNLOAD_STATE_VERSION
            || state.request_hash != self.request_hash
            || !state.validator.is_valid()
            || partial_size == 0
            || state.total_size.is_some_and(|total| partial_size > total)
        {
            self.clear()?;
            return Ok(None);
        }
        Ok(Some((state, partial_size)))
    }

    fn write_state(&self, state: &PartialDownloadState) -> Result<()> {
        let parent = self.state_path.parent().unwrap();
        // The name `tempfile` is about to generate, not the directory holding it: the hint decides
        // from the length of what it is given, and the generated name is 27 units longer than the
        // directory. Measuring the directory would leave a window where the temp path is over the
        // limit while the directory is under the hint's threshold, and the failure would go back
        // to being unexplained. `XXXXXX` stands in for the six random characters and is the same
        // length, so what is measured is what Windows sees.
        let temp_name = parent.join(format!("{DOWNLOAD_STATE_PREFIX}XXXXXX"));
        let mut temp = tempfile::NamedTempFile::with_prefix_in(DOWNLOAD_STATE_PREFIX, parent)
            .map_err(|err| io_error(err, "failed to create the download state file", &temp_name))?;
        serde_json::to_writer(&mut temp, state)?;
        temp.as_file_mut().sync_all()?;
        temp.persist(&self.state_path).map_err(|err| {
            io_error(
                err.error,
                "failed to write the download state file",
                &self.state_path,
            )
        })?;
        Ok(())
    }

    fn clear(&self) -> Result<()> {
        self.remove_partial_if_exists()?;
        self.remove_state_if_exists()?;
        Ok(())
    }

    fn remove_partial_if_exists(&self) -> Result<()> {
        remove_file_if_exists(&self.path)
    }

    fn remove_state_if_exists(&self) -> Result<()> {
        remove_file_if_exists(&self.state_path)
    }

    fn persist(&self, destination: &Path) -> Result<()> {
        let temp_path = tempfile::TempPath::try_from_path(&self.path)?;
        if let Err(err) = temp_path.persist(destination) {
            let error = err.error;
            let _ = err.path.keep();
            return Err(io_error(
                error,
                "failed to move the downloaded file into place",
                destination,
            ));
        }
        self.remove_state_if_exists()?;
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParsedContentRange {
    Bytes { start: u64, end: u64, total: u64 },
    Unsatisfied { total: u64 },
}

fn remove_file_if_exists(path: &Path) -> Result<()> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(err.into()),
    }
}

/// Removes completed download artifacts while retaining partial download pairs
/// for validation by a later invocation. Explicit backend purges still remove
/// the entire downloads directory.
pub fn cleanup_download_dir(path: &Path) -> Result<()> {
    let entries = match std::fs::read_dir(path) {
        Ok(entries) => entries,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(err) => return Err(err.into()),
    };
    for entry in entries {
        let entry = entry?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        let pair_path = name
            .strip_suffix(".mise-part.json")
            .map(|stem| path.join(format!("{stem}.mise-part")))
            .or_else(|| {
                name.strip_suffix(".mise-part")
                    .map(|_| path.join(format!("{name}.json")))
            });
        if name.starts_with('.')
            && pair_path.is_some_and(|pair_path| {
                pair_path.is_file()
                    && partial_file_is_recent(&entry.path())
                    && partial_file_is_recent(&pair_path)
            })
        {
            continue;
        }
        let path = entry.path();
        if entry.file_type()?.is_dir() {
            file::remove_all(&path)?;
        } else {
            remove_file_if_exists(&path)?;
        }
    }
    if std::fs::read_dir(path)?.next().is_none() {
        std::fs::remove_dir(path)?;
    }
    Ok(())
}

fn partial_file_is_recent(path: &Path) -> bool {
    let Ok(modified) = std::fs::metadata(path).and_then(|metadata| metadata.modified()) else {
        return false;
    };
    SystemTime::now()
        .duration_since(modified)
        .map_or(true, |age| age <= PARTIAL_DOWNLOAD_MAX_AGE)
}

fn update_download_hash(hasher: &mut blake3::Hasher, value: &[u8]) {
    hasher.update(&(value.len() as u64).to_le_bytes());
    hasher.update(value);
}

fn header_digest(headers: &HeaderMap) -> String {
    let mut hasher = blake3::Hasher::new();
    hash_headers(&mut hasher, headers);
    hasher.finalize().to_hex().to_string()
}

fn hash_headers(hasher: &mut blake3::Hasher, headers: &HeaderMap) {
    let mut header_values = headers
        .keys()
        .flat_map(|name| {
            headers
                .get_all(name)
                .iter()
                .map(move |value| (name.as_str().as_bytes(), value.as_bytes()))
        })
        .collect::<Vec<_>>();
    header_values.sort_unstable();
    for (name, value) in header_values {
        update_download_hash(hasher, name);
        update_download_hash(hasher, value);
    }
}

fn download_request_hash(url: &Url, headers: &HeaderMap) -> String {
    let mut hasher = blake3::Hasher::new();
    update_download_hash(&mut hasher, url.as_str().as_bytes());

    hash_headers(&mut hasher, headers);

    if let Some(replacements) = &Settings::get().url_replacements {
        for (pattern, replacement) in replacements {
            update_download_hash(&mut hasher, pattern.as_bytes());
            update_download_hash(&mut hasher, replacement.as_bytes());
        }
    }
    hasher.finalize().to_hex().to_string()
}

fn response_validator(headers: &HeaderMap) -> Option<DownloadValidator> {
    headers
        .get(ETAG)
        .and_then(|value| value.to_str().ok())
        .filter(|value| !value.is_empty() && !value.starts_with("W/"))
        .map(|value| DownloadValidator::Etag(value.to_string()))
        .or_else(|| {
            let value = headers
                .get(LAST_MODIFIED)
                .and_then(|value| value.to_str().ok())
                .filter(|value| !value.is_empty())?;
            let response_date = headers.get(DATE)?.to_str().ok()?;
            is_strong_last_modified(value, response_date).then(|| DownloadValidator::LastModified {
                value: value.to_string(),
                response_date: response_date.to_string(),
            })
        })
}

fn is_strong_last_modified(value: &str, response_date: &str) -> bool {
    let Ok(last_modified) = chrono::DateTime::parse_from_rfc2822(value) else {
        return false;
    };
    let Ok(response_date) = chrono::DateTime::parse_from_rfc2822(response_date) else {
        return false;
    };
    response_date.signed_duration_since(last_modified) >= chrono::Duration::seconds(60)
}

fn parse_content_range(value: &str) -> Option<ParsedContentRange> {
    let value = value.strip_prefix("bytes ")?;
    let (range, total) = value.split_once('/')?;
    let total = total.parse::<u64>().ok()?;
    if range == "*" {
        return Some(ParsedContentRange::Unsatisfied { total });
    }
    let (start, end) = range.split_once('-')?;
    let start = start.parse::<u64>().ok()?;
    let end = end.parse::<u64>().ok()?;
    if start > end || end >= total {
        return None;
    }
    Some(ParsedContentRange::Bytes { start, end, total })
}

/// Download `url` to `path` and verify it against `sha256`, following a
/// redirect from HTTPS to HTTP if a mirror sends one. On a mismatch the file is
/// removed so no caller can pick up unverified bytes.
#[cfg(unix)]
pub async fn download_file_checksum_pinned<U: IntoUrl>(
    url: U,
    path: &Path,
    sha256: &str,
    pr: Option<&dyn SingleReport>,
) -> Result<()> {
    // Pinned, so a download that fails the check below is not kept.
    let pin = format!("sha256:{sha256}");
    HTTP_CHECKSUM_PINNED
        .download_file_pinned(url, path, Some(&pin), pr)
        .await?;
    verify_sha256_or_remove(path, sha256, pr)
}

#[cfg(unix)]
fn verify_sha256_or_remove(path: &Path, sha256: &str, pr: Option<&dyn SingleReport>) -> Result<()> {
    if let Err(err) = crate::hash::ensure_checksum(path, sha256, pr, "sha256") {
        let _ = file::remove_file(path);
        return Err(err);
    }
    Ok(())
}

/// Whether a client may follow a redirect from HTTPS to HTTP.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Downgrade {
    Refuse,
    /// Only for `HTTP_CHECKSUM_PINNED`.
    #[cfg(unix)]
    FollowChecksumPinned,
}

/// Follow redirects as reqwest normally would, but refuse to step down from
/// HTTPS to HTTP part-way through.
///
/// `what` names the request in the error, since the two clients carry very
/// different traffic.
fn https_downgrade_policy(what: &'static str) -> reqwest::redirect::Policy {
    use reqwest::redirect::Policy;

    Policy::custom(move |attempt| {
        if is_https_downgrade(attempt.previous(), attempt.url()) {
            attempt.error(std::io::Error::other(format!(
                "refusing to redirect {what} from HTTPS to HTTP"
            )))
        } else {
            Policy::default().redirect(attempt)
        }
    })
}

pub fn is_https_downgrade(previous: &[Url], next: &Url) -> bool {
    previous
        .last()
        .is_some_and(|url| url.scheme() == "https" && next.scheme() != "https")
}

#[derive(Debug)]
pub struct Client {
    reqwest: Result<reqwest::Client, String>,
    /// Built on first use by [`Client::send_following_redirects`], which follows
    /// redirects itself so it can decide what each hop may carry.
    manual_redirects: std::sync::OnceLock<Result<reqwest::Client, String>>,
    /// The two clients above with every `Content-Encoding` decoder off, built
    /// on first use by [`Client::send_scoped`] for requests that ask for
    /// `identity`: downloads, whose bytes must be the ones the server sent.
    undecoded: std::sync::OnceLock<Result<reqwest::Client, String>>,
    undecoded_manual_redirects: std::sync::OnceLock<Result<reqwest::Client, String>>,
    timeout: Duration,
    /// What `reqwest` was built with, to build `undecoded` the same way.
    read_timeout: Option<Duration>,
    downgrade: Downgrade,
    kind: ClientKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClientKind {
    Http,
    Fetch,
}

impl ClientKind {
    /// Names this client's traffic in the redirect error. Exhaustive, so a new
    /// kind cannot be added without deciding what to call it.
    fn redirect_subject(self) -> &'static str {
        match self {
            Self::Http => "a download",
            Self::Fetch => "a remote version request",
        }
    }
}

impl Client {
    #[doc(hidden)]
    pub fn new(timeout: Duration, kind: ClientKind) -> Result<Self> {
        Ok(Self {
            reqwest: Ok(Self::build(
                timeout,
                kind,
                Downgrade::Refuse,
                Some(timeout),
                true,
            )?),
            manual_redirects: Default::default(),
            undecoded: Default::default(),
            undecoded_manual_redirects: Default::default(),
            timeout,
            read_timeout: Some(timeout),
            downgrade: Downgrade::Refuse,
            kind,
        })
    }

    fn new_shared(timeout: Duration, kind: ClientKind) -> Self {
        Self::new_shared_with(timeout, kind, Downgrade::Refuse)
    }

    fn new_shared_without_read_timeout(timeout: Duration, kind: ClientKind) -> Self {
        Self {
            reqwest: Self::build(timeout, kind, Downgrade::Refuse, None, true)
                .map_err(|err| format!("{err:#}")),
            manual_redirects: Default::default(),
            undecoded: Default::default(),
            undecoded_manual_redirects: Default::default(),
            timeout,
            read_timeout: None,
            downgrade: Downgrade::Refuse,
            kind,
        }
    }

    fn new_shared_with(timeout: Duration, kind: ClientKind, downgrade: Downgrade) -> Self {
        Self {
            reqwest: Self::build(timeout, kind, downgrade, Some(timeout), true)
                .map_err(|err| format!("{err:#}")),
            manual_redirects: Default::default(),
            undecoded: Default::default(),
            undecoded_manual_redirects: Default::default(),
            timeout,
            read_timeout: Some(timeout),
            downgrade,
            kind,
        }
    }

    fn build(
        timeout: Duration,
        kind: ClientKind,
        downgrade: Downgrade,
        read_timeout: Option<Duration>,
        decode: bool,
    ) -> Result<reqwest::Client> {
        // Built through `build_client` so an empty system trust store falls back
        // to bundled roots; it may call this closure twice.
        Ok(mise_tls::build_client(|| {
            let builder = Self::_new_with(decode).connect_timeout(timeout);
            let builder = match read_timeout {
                Some(read_timeout) => builder.read_timeout(read_timeout),
                None => builder,
            };
            // Applied to every kind rather than per match arm, so no client can be
            // added — or edited back — into existence without it. Downloads are
            // checksum-verified where a checksum is known, but not every caller has
            // one, and a silent downgrade is worth refusing on its own. Redirects
            // are otherwise unchanged: the policy defers to the default for
            // anything that is not a downgrade. The one exception is
            // `HTTP_CHECKSUM_PINNED`, whose only caller verifies every byte.
            let policy = match downgrade {
                Downgrade::Refuse => https_downgrade_policy(kind.redirect_subject()),
                #[cfg(unix)]
                Downgrade::FollowChecksumPinned => reqwest::redirect::Policy::default(),
            };
            builder.redirect(policy)
        })?)
    }

    #[doc(hidden)]
    pub fn with_init_error(error: impl Into<String>) -> Self {
        Self {
            reqwest: Err(error.into()),
            manual_redirects: Default::default(),
            undecoded: Default::default(),
            undecoded_manual_redirects: Default::default(),
            timeout: Duration::from_secs(1),
            read_timeout: Some(Duration::from_secs(1)),
            downgrade: Downgrade::Refuse,
            kind: ClientKind::Http,
        }
    }

    /// Underlying reqwest client. Use sparingly — most callers should reach for
    /// the higher-level `get_*`/`json_*`/`post_json_*` helpers instead. This
    /// exists for callers that need request shapes those helpers don't cover
    /// (e.g. form-encoded POST in the GitHub OAuth flow) but still want the
    /// shared timeouts, gzip, and user-agent.
    pub fn reqwest(&self) -> Result<&reqwest::Client> {
        self.reqwest
            .as_ref()
            .map_err(|err| eyre!("Could not initialize the HTTP client: {err}"))
    }

    /// [`Client::reqwest`] with every `Content-Encoding` decoder off.
    fn undecoded(&self) -> Result<&reqwest::Client> {
        // What kept that one from being built would keep this one from it too.
        self.reqwest()?;
        self.undecoded
            .get_or_init(|| {
                Self::build(
                    self.timeout,
                    self.kind,
                    self.downgrade,
                    self.read_timeout,
                    false,
                )
                .map_err(|err| format!("{err:#}"))
            })
            .as_ref()
            .map_err(|err| eyre!("Could not initialize the HTTP client: {err}"))
    }

    /// Send `req`, following redirects ourselves when `headers` hold a credential that
    /// reqwest would forward to another host. reqwest only strips `Authorization`,
    /// `Cookie` and `Proxy-Authorization` on a cross-host redirect, so a header such as
    /// `X-Api-Key` would otherwise reach whatever host the server redirects to.
    ///
    /// The response to a request for `Accept-Encoding: identity` is returned as
    /// it was sent. reqwest decodes by the response's `Content-Encoding` alone,
    /// so a server that ignores `identity` could otherwise have a few kilobytes
    /// inflated to gigabytes, with the `Content-Length` that would have bounded
    /// them removed.
    async fn send_scoped(
        &self,
        method: &Method,
        url: &Url,
        headers: &HeaderMap,
        forward: &ForwardRules,
        timeout: Option<Duration>,
    ) -> std::result::Result<Response, SendError> {
        let decode = headers
            .get(ACCEPT_ENCODING)
            .is_none_or(|encoding| encoding != "identity");
        if !has_unscoped_credential(headers) && !forward.applies_to(headers) {
            let client = if decode {
                self.reqwest()
            } else {
                self.undecoded()
            };
            let mut req = client
                .map_err(|err| SendError::Refused(format!("{err:#}")))?
                .request(method.clone(), url.clone());
            if let Some(timeout) = timeout {
                req = req.timeout(timeout);
            }
            return req
                .headers(headers.clone())
                .send()
                .await
                .map_err(Into::into);
        }
        let manual_redirects = if decode {
            &self.manual_redirects
        } else {
            &self.undecoded_manual_redirects
        };
        let client = manual_redirects
            .get_or_init(|| {
                mise_tls::build_client(|| {
                    Self::_new_with(decode)
                        .read_timeout(self.timeout)
                        .connect_timeout(self.timeout)
                        .redirect(reqwest::redirect::Policy::none())
                })
                .map_err(|err| format!("{err:#}"))
            })
            .as_ref()
            .map_err(|err| {
                SendError::Refused(format!("Could not initialize the HTTP client: {err}"))
            })?;
        let mut method = method.clone();
        let mut url = url.clone();
        let mut headers = headers.clone();
        for _ in 0..MAX_MANUAL_REDIRECTS {
            let mut req = client.request(method.clone(), url.clone());
            if let Some(timeout) = timeout {
                req = req.timeout(timeout);
            }
            let resp = req.headers(headers.clone()).send().await?;
            if !resp.status().is_redirection() {
                return Ok(resp);
            }
            let Some(location) = resp
                .headers()
                .get(reqwest::header::LOCATION)
                .and_then(|value| value.to_str().ok())
            else {
                return Ok(resp);
            };
            let Ok(mut next) = url.join(location) else {
                return Ok(resp);
            };
            if is_https_downgrade(std::slice::from_ref(&url), &next) {
                return Err(SendError::Refused(
                    "refusing to redirect a request with credentials from HTTPS to HTTP"
                        .to_string(),
                ));
            }
            // Scheme and port count as a different origin, as they do for reqwest.
            if next.host() != url.host()
                || next.port_or_known_default() != url.port_or_known_default()
                || next.scheme() != url.scheme()
            {
                forward.retain_for(&mut headers, &url, &next);
                // Userinfo carried over from the previous URL is a credential too.
                let _ = next.set_username("");
                let _ = next.set_password(None);
            }
            if matches!(
                resp.status(),
                StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER
            ) && method != Method::HEAD
            {
                method = Method::GET;
            }
            url = next;
        }
        Err(SendError::Refused(format!(
            "too many redirects (more than {MAX_MANUAL_REDIRECTS})"
        )))
    }

    fn _new() -> ClientBuilder {
        Self::_new_with(true)
    }

    /// With `decode`, gzip and zstd responses are inflated transparently.
    /// Without it, no `Content-Encoding` is: brotli and deflate are compiled
    /// in through other dependencies and are on by default once they are.
    fn _new_with(decode: bool) -> ClientBuilder {
        let builder = ClientBuilder::new().user_agent(crate::user_agent::get());
        if decode {
            builder.gzip(true).zstd(true)
        } else {
            builder.no_gzip().no_zstd().no_brotli().no_deflate()
        }
    }

    fn request_timeout(&self) -> Duration {
        match self.kind {
            ClientKind::Fetch if crate::network::bound_remote_version_lookups(&Settings::get()) => {
                self.timeout.min(Duration::from_secs(3))
            }
            _ => self.timeout,
        }
    }

    pub async fn get_bytes<U: IntoUrl>(&self, url: U) -> Result<impl AsRef<[u8]>> {
        self.get_bytes_with_headers(url, HeaderMap::new()).await
    }

    /// [`Client::get_bytes`] with `headers` layered over the host credentials.
    pub async fn get_bytes_with_headers<U: IntoUrl>(
        &self,
        url: U,
        headers: HeaderMap,
    ) -> Result<impl AsRef<[u8]>> {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let url = url.into_url()?;
        let headers = with_host_auth(&url, &headers)?;
        self.send_with_retries(
            RetryableRequest {
                method: Method::GET,
                url,
                headers: &headers,
                verb_label: "GET",
                retries: crate::network::http_retries(&Settings::get()),
                error_for_status: true,
            },
            |resp| async move {
                Ok(buffer_body(resp)
                    .await?
                    .bytes()
                    .await
                    .map_err(redact_error_url)?)
            },
        )
        .await
    }

    pub async fn get_async<U: IntoUrl>(&self, url: U) -> Result<Response> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.get_async_with_headers(url, &headers).await
    }

    pub async fn get_async_with_headers<U: IntoUrl>(
        &self,
        url: U,
        headers: &HeaderMap,
    ) -> Result<Response> {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let url = url.into_url()?;
        let resp = self
            .send_with_https_fallback(Method::GET, url, headers, "GET")
            .await?;
        resp.error_for_status_ref().map_err(redact_error_url)?;
        Ok(resp)
    }

    pub async fn get_async_with_headers_allow_error_status<U: IntoUrl>(
        &self,
        url: U,
        headers: &HeaderMap,
    ) -> Result<Response> {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let url = url.into_url()?;
        self.send_with_https_fallback_allow_error_status(Method::GET, url, headers, "GET")
            .await
    }

    pub async fn head<U: IntoUrl>(&self, url: U) -> Result<Response> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.head_async_with_headers(url, &headers).await
    }

    /// HEAD without `.netrc` credentials for the requested host (netrc for a
    /// URL-replacement host still applies). For reachability probes where a
    /// credentialed request changes the answer: github.com redirects an
    /// authenticated release download to a presigned URL that rejects HEAD.
    ///
    /// `max_retries` caps the retry budget below `http_retries`, so a probe
    /// with somewhere else to go can give up quickly.
    pub async fn head_without_netrc<U: IntoUrl>(
        &self,
        url: U,
        max_retries: i64,
    ) -> Result<Response> {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        let retry_state = new_retry_state(&headers, true);
        let resp = retry_async_with_retries(
            "HEAD",
            &url,
            crate::network::http_retries(&Settings::get()).min(max_retries),
            || async {
                let (headers, options) = attempt_options(&retry_state, true);
                self.send_once_with_https_fallback_with_retry_headers(
                    Method::HEAD,
                    url.clone(),
                    &headers,
                    "HEAD",
                    options,
                )
                .await
            },
        )
        .await?;
        resp.error_for_status_ref().map_err(redact_error_url)?;
        Ok(resp)
    }

    pub async fn head_async_with_headers<U: IntoUrl>(
        &self,
        url: U,
        headers: &HeaderMap,
    ) -> Result<Response> {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let url = url.into_url()?;
        let resp = self
            .send_with_https_fallback(Method::HEAD, url, headers, "HEAD")
            .await?;
        resp.error_for_status_ref().map_err(redact_error_url)?;
        Ok(resp)
    }

    pub async fn get_text<U: IntoUrl>(&self, url: U) -> Result<String> {
        self.get_text_request(url).send().await
    }

    pub fn get_text_request<U: IntoUrl>(&self, url: U) -> TextRequest<'_> {
        // Defer surfacing an invalid URL to `send()` (which returns `Result`) so a
        // bad URL is reported as an error instead of panicking here. See #3547.
        TextRequest {
            client: self,
            url: url.into_url().map_err(|e| e.to_string()),
            extra_headers: HeaderMap::new(),
            retries: crate::network::http_retries(&Settings::get()),
            allow_html: false,
        }
    }

    /// Like get_text but caches results in memory for the duration of the process.
    /// Useful when the same URL will be requested multiple times (e.g., SHASUMS256.txt
    /// when locking multiple platforms). Concurrent requests for the same URL will
    /// wait for the first fetch to complete.
    pub async fn get_text_cached<U: IntoUrl>(&self, url: U) -> Result<String> {
        self.get_text_cached_with_headers(url, &HeaderMap::new())
            .await
    }

    /// [`Self::get_text_cached`] with extra request headers. The cache is keyed by URL
    /// alone, so every caller of one URL within a process must send the same headers.
    pub async fn get_text_cached_with_headers<U: IntoUrl>(
        &self,
        url: U,
        headers: &HeaderMap,
    ) -> Result<String> {
        let url = url.into_url()?;
        // Responses can depend on the credentials (a token may select a repository), so
        // they are part of the key, as a digest so the values are never kept in memory
        // as plain text.
        let key = if headers.is_empty() {
            url.to_string()
        } else {
            format!("{url}\n{}", header_digest(headers))
        };

        // Get or create the OnceCell for this URL
        let cell = {
            let mut cache = HTTP_CACHE.lock().unwrap();
            cache.entry(key).or_default().clone()
        };

        // Initialize the cell if needed - concurrent callers will wait
        let result = cell
            .get_or_init(|| {
                let url = url.clone();
                async move {
                    match self.get_text_request(url).headers(headers).send().await {
                        Ok(text) => Ok(text),
                        Err(err) => Err(CachedFailure {
                            message: err.to_string(),
                            unreachable: is_unreachable(&err),
                        }),
                    }
                }
            })
            .await;

        match result {
            Ok(text) => Ok(text.clone()),
            Err(err) => Err(err.clone().into()),
        }
    }

    pub async fn get_html<U: IntoUrl>(&self, url: U) -> Result<String> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.get_html_with_headers(url, &headers).await
    }

    pub async fn get_html_with_headers<U: IntoUrl>(
        &self,
        url: U,
        headers: &HeaderMap,
    ) -> Result<String> {
        let url = url.into_url()?;
        let resp = self.get_async_with_headers(url.clone(), headers).await?;
        let is_html = resp
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|content_type| content_type.to_str().ok())
            .is_some_and(|content_type| {
                let media_type = content_type
                    .split_once(';')
                    .map_or(content_type, |(media_type, _)| media_type)
                    .trim()
                    .to_ascii_lowercase();
                // `+html` covers PEP 691 (`application/vnd.pypi.simple.v1+html`)
                media_type == "text/html" || media_type.ends_with("+html")
            });
        if !is_html {
            bail!("Got non-HTML text from {}", log_url(&url));
        }
        let read = async {
            Ok(buffer_body(resp)
                .await?
                .text()
                .await
                .map_err(redact_error_url)?)
        };
        read_body_within(
            crate::network::http_download_timeout(&Settings::get()),
            &url,
            read,
        )
        .await
    }

    pub async fn json_headers<T, U: IntoUrl>(&self, url: U) -> Result<(T, HeaderMap)>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.json_headers_with_headers(url, &headers).await
    }

    pub async fn json_headers_with_headers<T, U: IntoUrl>(
        &self,
        url: U,
        headers: &HeaderMap,
    ) -> Result<(T, HeaderMap)>
    where
        T: serde::de::DeserializeOwned,
    {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let url = url.into_url()?;
        self.send_with_retries(
            RetryableRequest {
                method: Method::GET,
                url,
                headers,
                verb_label: "GET",
                retries: crate::network::http_retries(&Settings::get()),
                error_for_status: true,
            },
            |resp| async move {
                let headers = resp.headers().clone();
                Ok((
                    buffer_body(resp)
                        .await?
                        .json()
                        .await
                        .map_err(redact_error_url)?,
                    headers,
                ))
            },
        )
        .await
    }

    pub async fn json<T, U: IntoUrl>(&self, url: U) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        self.json_headers(url).await.map(|(json, _)| json)
    }

    /// Like json but caches raw JSON text in memory for the duration of the process.
    /// Useful when the same URL will be requested multiple times (e.g., zig index.json
    /// when locking multiple platforms). Concurrent requests for the same URL will
    /// wait for the first fetch to complete.
    pub async fn json_cached<T, U: IntoUrl>(&self, url: U) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let text = self.get_text_cached(url).await?;
        Ok(serde_json::from_str(&text)?)
    }

    pub async fn json_with_headers<T, U: IntoUrl>(&self, url: U, headers: &HeaderMap) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        self.json_headers_with_headers(url, headers)
            .await
            .map(|(json, _)| json)
    }

    pub async fn download_file<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        pr: Option<&dyn SingleReport>,
    ) -> Result<()> {
        self.download_file_with_metadata(url, path, pr)
            .await
            .map(|_| ())
    }

    /// [`Client::download_file`] for a file mise then reads whole into memory,
    /// such as a remote task file. The server decides how much it sends, so the
    /// download fails once more than `max_bytes` have arrived, instead of
    /// filling the disk and then memory.
    pub async fn download_file_limited<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        max_bytes: u64,
        pr: Option<&dyn SingleReport>,
    ) -> Result<()> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.download_file_with_pin_limited(url.clone(), path, &headers, None, pr, Some(max_bytes))
            .await?;
        ensure_download_within(path, &url, max_bytes)
    }

    pub async fn download_file_with_metadata<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        pr: Option<&dyn SingleReport>,
    ) -> Result<DownloadFileMetadata> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.download_file_with_headers_metadata(url, path, &headers, pr)
            .await
    }

    pub async fn download_file_with_headers<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        headers: &HeaderMap,
        pr: Option<&dyn SingleReport>,
    ) -> Result<()> {
        self.download_file_with_headers_metadata(url, path, headers, pr)
            .await
            .map(|_| ())
    }

    pub async fn download_file_with_headers_metadata<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        headers: &HeaderMap,
        pr: Option<&dyn SingleReport>,
    ) -> Result<DownloadFileMetadata> {
        self.download_file_with_pin(url, path, headers, None, pr)
            .await
    }

    /// Like [`Client::download_file`], for a tool that pinned `pin`
    /// (`algo:hex`). A download kept earlier under that checksum is used
    /// without a request once it hashes to the pin again. The caller still
    /// verifies the result.
    pub async fn download_file_pinned<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
    ) -> Result<DownloadFileMetadata> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.download_file_with_pin(url, path, &headers, pin, pr)
            .await
    }

    pub async fn download_file_with_pin<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        headers: &HeaderMap,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
    ) -> Result<DownloadFileMetadata> {
        self.download_file_with_pin_limited(url, path, headers, pin, pr, None)
            .await
    }

    async fn download_file_with_pin_limited<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        headers: &HeaderMap,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
        max_bytes: Option<u64>,
    ) -> Result<DownloadFileMetadata> {
        let url = url.into_url()?;
        if Settings::get().generate_lockfiles() {
            let key = format!(
                "{:p}:{}:{max_bytes:?}",
                self,
                download_request_hash(&url, headers)
            );
            let shared = INVOCATION_DOWNLOADS
                .lock()
                .unwrap()
                .entry(key)
                .or_default()
                .clone();
            let (directory, metadata) = shared
                .get_or_try_init(|| async {
                    // Not TEMP: a download under a deep TEMP passes MAX_PATH on Windows,
                    // and a lockfile must not depend on where TEMP points.
                    let scratch = crate::dirs::CACHE.join("invocation-downloads");
                    file::create_dir_all(&scratch)?;
                    let directory = tempfile::tempdir_in(&scratch)?;
                    let metadata = self
                        .download_file_with_headers_timeout(
                            url.clone(),
                            &directory.path().join("artifact"),
                            headers,
                            pin,
                            pr,
                            DownloadLimits::new(max_bytes, headers),
                        )
                        .await?;
                    Ok::<_, eyre::Report>((directory, metadata))
                })
                .await?;
            if let Some(parent) = path.parent() {
                file::create_dir_all(parent)?;
            }
            let partial = PartialDownload::new(path, download_request_hash(&url, headers))?;
            let lock_path = partial.path.clone();
            let _download_lock = tokio::task::spawn_blocking(move || {
                crate::lock_file::LockFile::new(&lock_path).lock()
            })
            .await??;
            partial.clear()?;
            file::copy(directory.path().join("artifact"), &partial.path)?;
            partial.persist(path)?;
            let metadata = metadata.clone();
            drop(shared);
            prune_shared_downloads(
                &mut INVOCATION_DOWNLOADS.lock().unwrap(),
                512 * 1024 * 1024,
                64,
            );
            return Ok(metadata);
        }
        self.download_file_with_headers_timeout(
            url,
            path,
            headers,
            pin,
            pr,
            DownloadLimits::new(max_bytes, headers),
        )
        .await
    }

    async fn download_file_with_headers_timeout<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        headers: &HeaderMap,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
        limits: DownloadLimits,
    ) -> Result<DownloadFileMetadata> {
        let use_cache = cache_allowed(pin);
        let cache = CacheMode {
            pin,
            enabled: use_cache,
        };
        let fetched = self
            .download_file_inner(url, path, headers, cache, pr, limits)
            .await?;
        if let Some(blob) = fetched.stored {
            let dest = path.to_path_buf();
            tokio::task::spawn_blocking(move || cas::place(&blob, &dest, false)).await??;
            return Ok(fetched.metadata);
        }
        if use_cache {
            // Best effort: a download that can't be kept is still a download.
            let path = path.to_path_buf();
            let pin = pin.map(str::to_string);
            let effective_filename = fetched.metadata.effective_filename.clone();
            let kept = tokio::task::spawn_blocking(move || {
                cas::store(
                    &path,
                    cas::Keep {
                        request_hash: &fetched.request_hash,
                        url: &fetched.url,
                        pin: pin.as_deref(),
                        validator: fetched.validator.as_ref(),
                        effective_filename,
                    },
                )
            })
            .await;
            if let Ok(Err(err)) | Err(err) = kept.map_err(Report::from) {
                debug!("could not keep the download: {err:#}");
            }
        }
        Ok(fetched.metadata)
    }

    /// [`Client::download_file_linked`] with the automatic host credentials, for
    /// callers that send no headers of their own.
    pub async fn download_file_stored<U: IntoUrl>(
        &self,
        url: U,
        dest: &Path,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
    ) -> Result<DownloadFileMetadata> {
        let url = url.into_url()?;
        let headers = host_auth_headers(&url)?;
        self.download_file_linked(url, dest, &headers, pin, pr)
            .await
    }

    /// Like [`Client::download_file_pinned`], but the download is kept in the
    /// store first and `dest` is a link to it where the filesystem allows one,
    /// so the bytes exist once. Across devices, or without a store, it is a
    /// copy. For callers that only read the file: a change through the link
    /// would change the stored file, which is hashed again before it is reused.
    pub async fn download_file_linked<U: IntoUrl>(
        &self,
        url: U,
        dest: &Path,
        headers: &HeaderMap,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
    ) -> Result<DownloadFileMetadata> {
        self.download_file_linked_limited(url, dest, headers, pin, pr, None)
            .await
    }

    /// [`Client::download_file_linked`] that fails once more than `max_bytes`
    /// have arrived, for a file mise then reads whole into memory.
    pub async fn download_file_linked_limited<U: IntoUrl>(
        &self,
        url: U,
        dest: &Path,
        headers: &HeaderMap,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
        max_bytes: Option<u64>,
    ) -> Result<DownloadFileMetadata> {
        let url = url.into_url()?;
        let metadata = self
            .download_file_linked_inner(url.clone(), dest, headers, pin, pr, max_bytes)
            .await?;
        if let Some(max_bytes) = max_bytes {
            ensure_download_within(dest, &url, max_bytes)?;
        }
        Ok(metadata)
    }

    async fn download_file_linked_inner(
        &self,
        url: Url,
        dest: &Path,
        headers: &HeaderMap,
        pin: Option<&str>,
        pr: Option<&dyn SingleReport>,
        max_bytes: Option<u64>,
    ) -> Result<DownloadFileMetadata> {
        let name = dest
            .file_name()
            .ok_or_else(|| eyre!("download destination has no filename: {}", dest.display()))?
            .to_string_lossy()
            .to_string();
        let request_hash = download_request_hash(&url, headers);
        let staging = (cache_allowed(pin) && !Settings::get().generate_lockfiles())
            .then(|| cas::staging_path(&request_hash, &name))
            .flatten();
        let Some(staging) = staging else {
            return self
                .download_file_with_pin_limited(url, dest, headers, pin, pr, max_bytes)
                .await;
        };
        let cache = CacheMode { pin, enabled: true };
        let fetched = self
            .download_file_inner(
                url,
                &staging,
                headers,
                cache,
                pr,
                DownloadLimits::new(max_bytes, headers),
            )
            .await?;
        let blob = match fetched.stored {
            Some(blob) => Some(blob),
            None => {
                let staged = staging.clone();
                let pin = pin.map(str::to_string);
                let effective_filename = fetched.metadata.effective_filename.clone();
                let validator = fetched.validator.clone();
                let hash = fetched.request_hash.clone();
                let fetched_url = fetched.url.clone();
                tokio::task::spawn_blocking(move || {
                    cas::ingest(
                        &staged,
                        cas::Keep {
                            request_hash: &hash,
                            url: &fetched_url,
                            pin: pin.as_deref(),
                            validator: validator.as_ref(),
                            effective_filename,
                        },
                    )
                })
                .await??
            }
        };
        let dest = dest.to_path_buf();
        // With nothing to index it by (no validator, no pin), or a pin it
        // doesn't match, the staged file is the download itself.
        let (source, link) = match &blob {
            Some(blob) => (blob.clone(), true),
            None => (staging.clone(), false),
        };
        tokio::task::spawn_blocking(move || cas::place(&source, &dest, link)).await??;
        if blob.is_none() {
            let _ = file::remove_file(&staging);
        }
        Ok(fetched.metadata)
    }

    /// With `use_cache`, a download kept under `pin` is reused outright, and one
    /// kept for the same request is offered to the server for revalidation and
    /// reused on `304 Not Modified`.
    async fn download_file_inner<U: IntoUrl>(
        &self,
        url: U,
        path: &Path,
        headers: &HeaderMap,
        cache: CacheMode<'_>,
        pr: Option<&dyn SingleReport>,
        limits: DownloadLimits,
    ) -> Result<Fetched> {
        let total_timeout = limits.time;
        let CacheMode {
            pin,
            enabled: use_cache,
        } = cache;
        let started = Instant::now();
        let url = url.into_url()?;
        let request_hash = download_request_hash(&url, headers);
        // A pinned download kept earlier needs no request, so this comes before
        // the offline check.
        if use_cache && let Some(hit) = pin.and_then(|pin| cas::lookup_pin(pin, url.as_str())) {
            let effective_filename = hit.effective_filename.clone();
            if let Some(blob) = tokio::task::spawn_blocking(move || hit.verified()).await? {
                return Ok(Fetched {
                    metadata: DownloadFileMetadata { effective_filename },
                    stored: Some(blob),
                    validator: None,
                    request_hash,
                    url: url.to_string(),
                });
            }
        }
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        debug!(
            "GET Downloading {} to {}",
            log_url(&url),
            display_path(path)
        );
        let parent = path.parent().unwrap();
        file::create_dir_all(parent)?;
        let partial = PartialDownload::new(path, download_request_hash(&url, headers))?;
        // Backends may already hold a lock for the destination while they
        // download it (for example rustup-init). Lock the downloader-owned
        // partial path instead so concurrent transfers are serialized without
        // recursively acquiring the caller's destination lock.
        let lock_path = partial.path.clone();
        let _download_lock =
            tokio::task::spawn_blocking(move || crate::lock_file::LockFile::new(&lock_path).lock())
                .await??;
        let attempt = Arc::new(AtomicUsize::new(0));
        let progress = Arc::new(DownloadProgress::default());
        let cached = if use_cache {
            cas::lookup_url(&request_hash, pin)
        } else {
            None
        };
        let outcome = Arc::new(AttemptOutcome {
            max_bytes: limits.bytes,
            netrc: Some(limits.netrc.clone()),
            cond: cached.as_ref().map(|c| c.validator.clone()),
            ..Default::default()
        });

        // Retry the whole transfer, resuming a validated partial response when
        // possible. send_once_with_https_fallback_allow_416 (not
        // send_with_https_fallback) is used inside to avoid retry-on-retry.
        let download = retry_async("GET", &url, || {
            let attempt = attempt.clone();
            let progress = progress.clone();
            let request_url = url.clone();
            let partial = partial.clone();
            let outcome = outcome.clone();
            async move {
                attempt.fetch_add(1, Ordering::Relaxed);
                progress.start_attempt();
                // Boxed: inlined, this future nests deeply enough to overflow
                // the compiler's layout query depth in some callers.
                Box::pin(self.download_file_attempt(
                    request_url,
                    headers,
                    &partial,
                    pr,
                    &progress,
                    &outcome,
                ))
                .await
            }
        });

        // Warn (once) when the transfer crawls, instead of silently waiting out
        // the whole budget: a throttled host that trickles bytes never trips the
        // per-read `http_timeout`, and shims queued behind this install's lock
        // would otherwise wait with no hint of why.
        let download = async {
            tokio::select! {
                result = download => result,
                never = warn_when_download_is_slow(&url, &progress) => match never {},
            }
        };

        let metadata = match tokio::time::timeout(total_timeout, download).await {
            Ok(result) => result?,
            Err(_) => {
                // A timeout cancels the transfer future before its normal cleanup
                // runs. Loading the sidecar removes an unvalidated partial while
                // preserving a resumable one.
                if let Err(err) = partial.load() {
                    debug!("failed to validate partial download after timeout: {err:#}");
                }
                bail!(
                    "HTTP download timed out after {} for {} (attempt {}, {} bytes received; change with `http_download_timeout` or env `MISE_HTTP_DOWNLOAD_TIMEOUT`)",
                    format_duration(total_timeout),
                    log_url(&url),
                    attempt.load(Ordering::Relaxed),
                    progress.attempt.load(Ordering::Relaxed),
                )
            }
        };

        // Complete the atomic rename after the cancellable transfer budget. A
        // blocking task cannot be cancelled once it starts, so keeping it out
        // of `timeout` prevents us from returning an error while it can still
        // install the destination in the background.
        let path = path.to_path_buf();
        if outcome.not_modified.load(Ordering::Relaxed)
            && let Some(cached) = cached
        {
            let effective_filename = cached.effective_filename();
            let hit = cached.into_hit();
            if let Some(blob) = tokio::task::spawn_blocking(move || hit.verified()).await? {
                return Ok(Fetched {
                    metadata: DownloadFileMetadata { effective_filename },
                    stored: Some(blob),
                    validator: None,
                    request_hash,
                    url: url.to_string(),
                });
            }
            // The stored file no longer matches what was recorded: fetch it again.
            drop(_download_lock);
            let cache = CacheMode {
                pin,
                enabled: false,
            };
            // What is left of the budget, not a fresh one.
            let remaining = total_timeout
                .checked_sub(started.elapsed())
                .filter(|left| !left.is_zero())
                .ok_or_else(|| {
                    eyre!(
                        "HTTP download timed out after {} for {}",
                        format_duration(total_timeout),
                        log_url(&url)
                    )
                })?;
            let limits = DownloadLimits {
                time: remaining,
                ..limits
            };
            return Box::pin(self.download_file_inner(url, &path, headers, cache, pr, limits))
                .await;
        }
        let persist_path = path.clone();
        tokio::task::spawn_blocking(move || partial.persist(&persist_path)).await??;
        let validator = outcome.validator.lock().unwrap().take();
        Ok(Fetched {
            metadata,
            stored: None,
            validator,
            request_hash,
            url: url.to_string(),
        })
    }

    async fn download_file_attempt(
        &self,
        url: Url,
        headers: &HeaderMap,
        partial: &PartialDownload,
        pr: Option<&dyn SingleReport>,
        progress: &DownloadProgress,
        outcome: &AttemptOutcome,
    ) -> Result<DownloadFileMetadata> {
        let max_bytes = outcome.max_bytes;
        let too_large = |max: u64| {
            eyre!(
                "download from {} is larger than {}",
                log_url(&url),
                bytesize::ByteSize::b(max).display().iec()
            )
        };
        let mut restarted_without_resume = false;
        loop {
            let resume = if restarted_without_resume {
                None
            } else {
                partial.load()?
            };
            if let Some((state, partial_size)) = &resume
                && state.total_size == Some(*partial_size)
            {
                if let Some(pr) = pr {
                    pr.set_length(*partial_size);
                    pr.set_position(*partial_size);
                }
                return Ok(DownloadFileMetadata {
                    effective_filename: state.effective_filename.clone(),
                });
            }

            let offset = resume.as_ref().map(|(_, size)| *size).unwrap_or(0);
            let netrc_state = outcome.netrc.as_ref().expect("download sets netrc state");
            let mut request_headers = with_saved_authorization(headers, netrc_state);
            request_headers.insert(ACCEPT_ENCODING, HeaderValue::from_static("identity"));
            let mut conditional = false;
            if resume.is_none()
                && let Some(cond) = &outcome.cond
            {
                conditional = true;
                match cond {
                    DownloadValidator::Etag(value) => {
                        request_headers.insert(IF_NONE_MATCH, HeaderValue::from_str(value)?);
                    }
                    DownloadValidator::LastModified { value, .. } => {
                        request_headers.insert(IF_MODIFIED_SINCE, HeaderValue::from_str(value)?);
                    }
                }
            }
            if let Some((state, _)) = &resume {
                request_headers.insert(RANGE, HeaderValue::from_str(&format!("bytes={offset}-"))?);
                request_headers.insert(
                    IF_RANGE,
                    HeaderValue::from_str(state.validator.as_header_value())?,
                );
            }

            let mut resp = self
                .send_once_with_https_fallback_allow_416(
                    Method::GET,
                    url.clone(),
                    &request_headers,
                    "GET",
                    netrc_state,
                )
                .await?;
            let response_filename = download_filename_hint(resp.url());
            // A relayed response comes from the local adapter (`localhost`);
            // the upstream GitHub host is the one actually sending the bytes.
            #[cfg(unix)]
            let served_by = if github_relay_socket(&url).is_some() {
                &url
            } else {
                resp.url()
            };
            #[cfg(not(unix))]
            let served_by = resp.url();
            progress.served_by(served_by);

            if conditional && resp.status() == StatusCode::NOT_MODIFIED {
                outcome.not_modified.store(true, Ordering::Relaxed);
                return Ok(DownloadFileMetadata::default());
            }
            *outcome.validator.lock().unwrap() = (resp.status() != StatusCode::PARTIAL_CONTENT)
                .then(|| response_validator(resp.headers()))
                .flatten();

            if resp.status() == StatusCode::RANGE_NOT_SATISFIABLE {
                if let Some(ParsedContentRange::Unsatisfied { total }) = resp
                    .headers()
                    .get(CONTENT_RANGE)
                    .and_then(|value| value.to_str().ok())
                    .and_then(parse_content_range)
                {
                    debug!("range request at offset {offset} was unsatisfied for {total} bytes");
                }
                partial.clear()?;
                if offset > 0 && !restarted_without_resume {
                    restarted_without_resume = true;
                    continue;
                }
                resp.error_for_status_ref().map_err(redact_error_url)?;
            }

            let (write_offset, total_size, validator, resumable, effective_filename) =
                if resp.status() == StatusCode::PARTIAL_CONTENT {
                    let Some((state, _)) = resume else {
                        partial.clear()?;
                        if !restarted_without_resume {
                            restarted_without_resume = true;
                            continue;
                        }
                        bail!("server returned partial content without a resumable request");
                    };
                    let content_range = resp
                        .headers()
                        .get(CONTENT_RANGE)
                        .and_then(|value| value.to_str().ok())
                        .and_then(parse_content_range);
                    let Some(ParsedContentRange::Bytes { start, end, total }) = content_range
                    else {
                        partial.clear()?;
                        if restarted_without_resume {
                            bail!("server returned an invalid Content-Range response");
                        }
                        restarted_without_resume = true;
                        continue;
                    };
                    let validator = response_validator(resp.headers());
                    let response_length_matches = resp
                        .content_length()
                        .is_none_or(|length| length == end - start + 1);
                    if start != offset
                        || end + 1 != total
                        || !response_length_matches
                        || state.total_size.is_some_and(|expected| expected != total)
                        || validator
                            .as_ref()
                            .is_some_and(|value| !value.matches(&state.validator))
                    {
                        partial.clear()?;
                        if restarted_without_resume {
                            bail!("server returned inconsistent partial content");
                        }
                        restarted_without_resume = true;
                        continue;
                    }
                    // Keep the filename associated with the bytes already on disk.
                    // A redirect target may change between requests even when the
                    // server accepts the validator and Range header. Replacing the
                    // stored hint could make the completed bytes use a different
                    // archive format than the response that started the partial.
                    let effective_filename = state.effective_filename;
                    let validator = validator.unwrap_or(state.validator);
                    (
                        offset,
                        Some(total),
                        Some(validator),
                        true,
                        effective_filename,
                    )
                } else {
                    partial.clear()?;
                    let total_size = resp.content_length();
                    let validator = response_validator(resp.headers());
                    let resumable = total_size.is_some() && validator.is_some();
                    (
                        0,
                        total_size,
                        validator.filter(|_| resumable),
                        resumable,
                        response_filename,
                    )
                };

            if let Some(max) = max_bytes
                && total_size.is_some_and(|total| total > max)
            {
                partial.clear()?;
                return Err(too_large(max));
            }

            let state = validator.map(|validator| PartialDownloadState {
                version: PARTIAL_DOWNLOAD_STATE_VERSION,
                request_hash: partial.request_hash.clone(),
                validator,
                total_size,
                effective_filename: effective_filename.clone(),
            });
            if let Some(state) = &state {
                partial.write_state(state)?;
            } else {
                partial.remove_state_if_exists()?;
            }

            if let Some(pr) = pr {
                if let Some(total_size) = total_size {
                    pr.set_length(total_size);
                }
                pr.set_position(write_offset);
            }
            let mut file = tokio::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .append(write_offset > 0)
                .truncate(write_offset == 0)
                .open(&partial.path)
                .await?;
            let mut over_limit = false;
            let transfer = async {
                let mut written = write_offset;
                while let Some(chunk) = resp.chunk().await.map_err(redact_error_url)? {
                    if crate::cancel::is_cancelled() {
                        bail!("download cancelled by user");
                    }
                    written += chunk.len() as u64;
                    if let Some(max) = max_bytes
                        && written > max
                    {
                        over_limit = true;
                        return Err(too_large(max));
                    }
                    file.write_all(&chunk).await?;
                    progress
                        .attempt
                        .fetch_add(chunk.len() as u64, Ordering::Relaxed);
                    if let Some(pr) = pr {
                        pr.inc(chunk.len() as u64);
                    }
                }
                Ok::<_, Report>(())
            }
            .await;
            // Outside the transfer, so it also runs when the transfer failed.
            // `tokio::fs::File` buffers writes and dropping one does not flush,
            // so a transfer that dies part way through was leaving the bytes it
            // had already received unwritten — the resume then asked for a range
            // starting before them and downloaded them again. Whether any of it
            // survived depended on when the background flush happened to land.
            let persisted = async {
                file.shutdown().await?;
                file.sync_all().await?;
                Ok::<_, Report>(())
            }
            .await;
            // Before `clear()`: flushing into a file that has just been removed
            // would recreate it.
            if transfer.is_err()
                && (!resumable || over_limit)
                && let Err(err) = partial.clear()
            {
                debug!("failed to remove unvalidated partial download: {err:#}");
            }
            transfer?;
            persisted?;

            if let Some(total_size) = total_size {
                let actual_size = tokio::fs::metadata(&partial.path).await?.len();
                if actual_size != total_size {
                    return Err(DownloadSizeMismatch {
                        expected: total_size,
                        actual: actual_size,
                    }
                    .into());
                }
            }
            return Ok(DownloadFileMetadata { effective_filename });
        }
    }

    async fn send_with_https_fallback(
        &self,
        method: Method,
        url: Url,
        headers: &HeaderMap,
        verb_label: &str,
    ) -> Result<Response> {
        self.send_with_https_fallback_with_retries(
            method,
            url,
            headers,
            verb_label,
            crate::network::http_retries(&Settings::get()),
            true,
        )
        .await
    }

    async fn send_with_https_fallback_allow_error_status(
        &self,
        method: Method,
        url: Url,
        headers: &HeaderMap,
        verb_label: &str,
    ) -> Result<Response> {
        self.send_with_https_fallback_with_retries(
            method,
            url,
            headers,
            verb_label,
            crate::network::http_retries(&Settings::get()),
            false,
        )
        .await
    }

    async fn send_with_https_fallback_with_retries(
        &self,
        method: Method,
        url: Url,
        headers: &HeaderMap,
        verb_label: &str,
        retries: i64,
        error_for_status: bool,
    ) -> Result<Response> {
        let retry_state = new_retry_state(headers, false);
        retry_async_with_retries(verb_label, &url, retries, || async {
            let (headers, options) = attempt_options(&retry_state, error_for_status);
            self.send_once_with_https_fallback_with_retry_headers(
                method.clone(),
                url.clone(),
                &headers,
                verb_label,
                options,
            )
            .await
        })
        .await
    }

    /// Send with retries, turning the response into `T` inside the retried unit.
    /// reqwest resolves a request once the headers arrive, so reading the body
    /// after the retry loop leaves a mid-body connection drop unretried.
    /// Reading the body is bounded by `http_download_timeout`, as a file
    /// download is.
    async fn send_with_retries<T, F, Fut>(&self, req: RetryableRequest<'_>, read: F) -> Result<T>
    where
        F: Fn(Response) -> Fut,
        Fut: std::future::Future<Output = Result<T>>,
    {
        self.send_with_retries_body_timeout(
            req,
            read,
            crate::network::http_download_timeout(&Settings::get()),
        )
        .await
    }

    async fn send_with_retries_body_timeout<T, F, Fut>(
        &self,
        req: RetryableRequest<'_>,
        read: F,
        body_timeout: Duration,
    ) -> Result<T>
    where
        F: Fn(Response) -> Fut,
        Fut: std::future::Future<Output = Result<T>>,
    {
        let retry_state = new_retry_state(req.headers, false);
        retry_async_with_retries(req.verb_label, &req.url, req.retries, || async {
            let (headers, options) = attempt_options(&retry_state, req.error_for_status);
            let resp = self
                .send_once_with_https_fallback_with_retry_headers(
                    req.method.clone(),
                    req.url.clone(),
                    &headers,
                    req.verb_label,
                    options,
                )
                .await?;
            read_body_within(body_timeout, &req.url, read(resp)).await
        })
        .await
    }

    /// One attempt with http→https fallback, no retry. Used as the inner step
    /// for both `send_with_https_fallback` (which adds retry) and
    /// `download_file_with_headers` (which has its own outer retry covering the
    /// chunk stream). Splitting this out avoids retry × retry blowup.
    /// The fallback only fires on connection-level errors (corporate proxy
    /// blocking plain http), not on HTTP status errors — falling back to https
    /// after the server already returned a 4xx/5xx makes no sense.
    async fn send_once_with_https_fallback_allow_416(
        &self,
        method: Method,
        url: Url,
        headers: &HeaderMap,
        verb_label: &str,
        netrc_state: &RetryStateHandle,
    ) -> Result<Response> {
        let use_netrc = netrc_state.lock().unwrap().use_netrc;
        self.send_once_with_https_fallback_with_retry_headers(
            method,
            url,
            headers,
            verb_label,
            SendOnceOptions::new(Some(netrc_state.clone()), use_netrc)
                .allow_range_not_satisfiable(),
        )
        .await
    }

    async fn send_once_with_https_fallback_with_retry_headers(
        &self,
        method: Method,
        url: Url,
        headers: &HeaderMap,
        verb_label: &str,
        options: SendOnceOptions,
    ) -> Result<Response> {
        match self
            .send_once_with_retry_headers(
                method.clone(),
                url.clone(),
                headers,
                verb_label,
                options.clone(),
            )
            .await
        {
            Ok(resp) => Ok(resp),
            Err(err) if url.scheme() == "http" && is_unreachable(&err) => {
                let mut url = url;
                url.set_scheme("https").unwrap();
                self.send_once_with_retry_headers(method, url, headers, verb_label, options)
                    .await
            }
            Err(err) => Err(err),
        }
    }

    async fn send_once_with_retry_headers(
        &self,
        method: Method,
        url: Url,
        headers: &HeaderMap,
        verb_label: &str,
        options: SendOnceOptions,
    ) -> Result<Response> {
        self.send_once_inner(method, url, headers, verb_label, options)
            .await
    }

    async fn send_once_inner(
        &self,
        method: Method,
        mut url: Url,
        headers: &HeaderMap,
        verb_label: &str,
        options: SendOnceOptions,
    ) -> Result<Response> {
        let original_url = url.clone();
        let (headers, forward_rules) = split_forward_rules(headers);
        let headers = &headers;
        crate::resolve_progress::fetching(&url);
        #[cfg(unix)]
        if let Some(socket) = github_relay_socket(&url) {
            let response = crate::github_relay::unix::request(
                std::path::Path::new(&socket),
                method,
                &url,
                headers,
            )
            .await?;
            // This path returns before the GitHub 403 handling below, so without
            // this a relayed rate limit stays a bare status error that
            // `is_transient` calls deterministic and never retries. The relay
            // authenticates upstream itself, so report auth from the headers we
            // sent rather than claiming a token we do not hold. If the adapter
            // does not forward the rate-limit headers this simply does not
            // match, leaving the previous behaviour.
            if options.error_for_status
                && is_github_forbidden(&url, &response)
                && is_github_rate_limited(&response)
            {
                let status_error = response
                    .error_for_status_ref()
                    .expect_err("403 response should be an error");
                let status_error = redact_error_url(status_error);
                let used_github_token = headers.contains_key(AUTHORIZATION);
                let rate_limit = github_rate_limit_summary(&response);
                let body = read_bounded_error_body(response, self.timeout).await;
                return Err(github_forbidden_report(
                    status_error,
                    used_github_token,
                    rate_limit,
                    true,
                    &body,
                ));
            }
            return options.check_response(response);
        }
        apply_url_replacements(&mut url);
        crate::resolve_progress::fetching(&url);
        let host_key = http_host_key(&url);
        if crate::network::prefer_offline(&Settings::get())
            && let Some(host) = &host_key
            && let Some(cause) = UNAVAILABLE_HTTP_HOSTS.lock().unwrap().get(host).cloned()
        {
            return Err(UnavailableHttpHost {
                origin: host.clone(),
                cause,
            }
            .into());
        }
        debug!("{} {}", verb_label, log_url(&url));

        // Apply netrc credentials after URL replacement.
        //
        // netrc is treated as a *fallback*, mirroring curl's behavior: an
        // explicit Authorization header (e.g. the forge token resolved by
        // `host_auth_headers` from GITHUB_TOKEN/gh/github_tokens.toml) wins
        // over netrc. The one exception is when a URL replacement actually
        // redirected the request to a different URL — in that case the
        // pre-existing credentials were built for the *original* host and are
        // removed before netrc credentials scoped to the new host are applied.
        // This preserves the #7164 use case
        // (replace a public URL with a private mirror authenticated via
        // netrc) without clobbering forge tokens on un-redirected requests.
        let mut final_headers = headers.clone();
        clear_cross_host_credentials(&mut final_headers, &original_url, &mut url);
        // Refuse the downgrade for credentials that survive host scoping: a same-host
        // rewrite keeps the original Authorization, and userinfo written into the rule
        // itself is sent as-is. This runs before netrc because netrc credentials are
        // scoped to the *replacement* host by the user, who already gets them sent to a
        // plain `http://` URL with no rewrite involved — a rewrite must not be stricter
        // than the direct request, or an http mirror fronting an https origin (#7164)
        // becomes unusable.
        ensure_secure_replacement_credentials(&original_url, &url, &final_headers)?;
        // Set when netrc alone supplied the Authorization header for this host.
        let mut netrc_fallback_used = false;
        if options.use_netrc
            && !(options.netrc_replacement_only && url.host() == original_url.host())
        {
            let before = final_headers.get(AUTHORIZATION).cloned();
            final_headers =
                apply_netrc_credentials(final_headers, &original_url, &url, netrc_headers(&url));
            netrc_fallback_used = url.host() == original_url.host()
                && final_headers.get(AUTHORIZATION) != before.as_ref();
        }

        let request_timeout = self.request_timeout();
        let timeout = matches!(self.kind, ClientKind::Fetch).then_some(request_timeout);
        let resp = match self
            .send_scoped(&method, &url, &final_headers, &forward_rules, timeout)
            .await
        {
            Ok(resp) => resp,
            Err(SendError::Refused(message)) => return Err(eyre!(message)),
            Err(SendError::Reqwest(err)) => {
                let err = err.without_url();
                if crate::network::prefer_offline(&Settings::get())
                    && is_hard_connection_failure(&err)
                    && let Some(host) = host_key
                {
                    UNAVAILABLE_HTTP_HOSTS
                        .lock()
                        .unwrap()
                        .insert(host, err.to_string());
                }
                if err.is_timeout() {
                    let (setting, env_var) = match self.kind {
                        ClientKind::Http => ("http_timeout", "MISE_HTTP_TIMEOUT"),
                        ClientKind::Fetch => (
                            "fetch_remote_versions_timeout",
                            "MISE_FETCH_REMOTE_VERSIONS_TIMEOUT",
                        ),
                    };
                    let hint = format!(
                        "HTTP timed out after {} for {} (change with `{}` or env `{}`).",
                        format_duration(request_timeout),
                        log_url(&url),
                        setting,
                        env_var
                    );
                    // wrap_err preserves the underlying reqwest::Error in the chain so
                    // is_transient() can still classify this as a retryable timeout.
                    return Err(Report::new(err).wrap_err(hint));
                }
                return Err(err.into());
            }
        };
        if *env::MISE_LOG_HTTP {
            eprintln!("{} {} {}", verb_label, log_url(&url), resp.status());
        }
        debug!("{} {} {}", verb_label, log_url(&url), resp.status());
        display_github_rate_limit(&resp);
        if options.retry_github_oauth_401
            && let Some(stale_access_token) =
                stale_github_oauth_unauthorized_token(&original_url, &final_headers, &resp)
            && let Some(host) = original_url.host_str()
        {
            match crate::github::oauth::refresh_cached_token_for_host(host, &stale_access_token)
                .await
            {
                Ok(Some(token)) => {
                    let mut headers = headers.clone();
                    if let Ok(value) = HeaderValue::from_str(format!("Bearer {token}").as_str()) {
                        crate::github::remember_token_source(
                            host,
                            &token,
                            crate::github::TokenSource::GithubOauth,
                        );
                        headers.insert(AUTHORIZATION, value);
                        forward_rules.attach_to(&mut headers);
                        if let Some(retry_state) = &options.retry_state {
                            *retry_state.lock().unwrap() = RetryState {
                                headers: headers.clone(),
                                use_netrc: false,
                                netrc_replacement_only: false,
                            };
                        }
                        debug!(
                            "{} {} retrying with refreshed GitHub OAuth token after 401",
                            verb_label,
                            log_url(&url)
                        );
                        return Box::pin(self.send_once_inner(
                            method,
                            original_url,
                            &headers,
                            verb_label,
                            options.recursive_retry(),
                        ))
                        .await;
                    } else {
                        debug!(
                            "refreshed GitHub OAuth token contains invalid header bytes; skipping retry"
                        );
                    }
                }
                Ok(None) => {}
                Err(err) => {
                    crate::github::oauth::log_refresh_error(&err);
                }
            }
        }
        // A stale netrc login earns a 401 even from hosts that serve the resource
        // anonymously (a public GitLab release asset). netrc is only a fallback, so
        // retry once without it rather than fail. Callers that read the status
        // themselves (`allow_error_status`) keep the 401, and a response from
        // another origin after a redirect never saw the netrc header.
        if netrc_fallback_used
            && options.error_for_status
            && resp.status() == StatusCode::UNAUTHORIZED
            && resp.url().origin() == url.origin()
        {
            let mut headers = headers.clone();
            forward_rules.attach_to(&mut headers);
            debug!(
                "{} {} retrying without netrc credentials after 401",
                verb_label,
                log_url(&url)
            );
            // Later attempts of an outer retry loop must not resend the rejected login.
            if let Some(retry_state) = &options.retry_state {
                *retry_state.lock().unwrap() = RetryState {
                    headers: headers.clone(),
                    use_netrc: false,
                    netrc_replacement_only: false,
                };
            }
            return Box::pin(self.send_once_inner(
                method,
                original_url,
                &headers,
                verb_label,
                options.recursive_retry(),
            ))
            .await;
        }
        // raw.githubusercontent.com answers a token it does not accept (expired,
        // revoked) with a 404 rather than a 401, even for a public repository, so
        // the file looks missing. Retry once without the token: a public file
        // then arrives, and a private one is the same 404 as before. Callers that
        // read the status themselves get the retried response too, so a rejected
        // token cannot make a file they probe for look absent.
        if let Some(token) = raw_content_token_to_drop(&url, resp.status(), &final_headers) {
            let token_source = url
                .host_str()
                .and_then(|host| crate::github::token_source_for_token(host, token));
            let mut headers = final_headers.clone();
            headers.remove(AUTHORIZATION);
            forward_rules.attach_to(&mut headers);
            if let Some(retry_state) = &options.retry_state {
                *retry_state.lock().unwrap() = RetryState {
                    headers: headers.clone(),
                    use_netrc: false,
                    netrc_replacement_only: false,
                };
            }
            debug!(
                "{} {} retrying without GitHub auth after 404",
                verb_label,
                log_url(&url)
            );
            let retried = Box::pin(self.send_once_inner(
                method,
                original_url,
                &headers,
                verb_label,
                options.recursive_retry(),
            ))
            .await?;
            if retried.status().is_success() {
                warn_once!("{}", rejected_raw_token_warning(token_source.as_ref()));
            }
            return Ok(retried);
        }
        if options.error_for_status && is_github_unauthorized(&url, &resp) {
            // A static invalid/expired token (env var, gh CLI, ...) produces a 401
            // that the OAuth-refresh path above cannot recover. Surface a clear
            // error naming the token source instead of a bare status error. See #7218.
            let status_error = resp
                .error_for_status_ref()
                .expect_err("401 response should be an error");
            let status_error = redact_error_url(status_error);
            let used_github_token = final_headers.contains_key(AUTHORIZATION);
            // Use the source captured when this exact token was added to the request.
            // A netrc/caller-provided header must not be blamed on an unrelated token.
            let token_source = final_headers
                .get(AUTHORIZATION)
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.strip_prefix("Bearer "))
                .zip(original_url.host_str())
                .and_then(|(token, host)| crate::github::token_source_for_token(host, token));
            let body = read_bounded_error_body(resp, self.timeout).await;
            return Err(github_unauthorized_report(
                status_error,
                used_github_token,
                token_source.as_ref(),
                &body,
            ));
        }
        if options.error_for_status && is_github_forbidden(&url, &resp) {
            let status = resp.status();
            let status_error = resp
                .error_for_status_ref()
                .expect_err("403 response should be an error");
            let status_error = redact_error_url(status_error);
            let used_github_token = final_headers.contains_key(AUTHORIZATION);
            let rate_limit = github_rate_limit_summary(&resp);
            let rate_limited = is_github_rate_limited(&resp);
            let body = read_bounded_error_body(resp, self.timeout).await;
            // Retry without auth when the response mentions IP allow lists: GitHub App
            // installation tokens (`ghs_*`) get 403 on public API resources for orgs with IP
            // allow lists; stripping auth avoids that path.
            // https://github.com/orgs/community/discussions/191185
            // https://github.com/jdx/mise/discussions/9119
            // Kept to api.github.com: stripping Authorization and re-sending is
            // a response to that specific GitHub.com behaviour, not something
            // to start doing against an enterprise host.
            if used_github_token
                && url.host_str() == Some("api.github.com")
                && body.contains("IP allow list")
            {
                let mut headers = final_headers;
                headers.remove(AUTHORIZATION);
                forward_rules.attach_to(&mut headers);
                debug!(
                    "{} {} retrying without GitHub auth after {}",
                    verb_label,
                    log_url(&url),
                    status
                );
                return Box::pin(self.send_once_inner(
                    method,
                    original_url,
                    &headers,
                    verb_label,
                    options.recursive_retry(),
                ))
                .await;
            }
            return Err(github_forbidden_report(
                status_error,
                used_github_token,
                rate_limit,
                rate_limited,
                &body,
            ));
        }
        options.check_response(resp)
    }
}

pub struct TextRequest<'a> {
    client: &'a Client,
    // Parsed lazily by `get_text_request`; an invalid URL surfaces as an error in
    // `send()` rather than a panic. See #3547.
    url: Result<Url, String>,
    extra_headers: HeaderMap,
    retries: i64,
    allow_html: bool,
}

impl TextRequest<'_> {
    pub fn headers(mut self, headers: &HeaderMap) -> Self {
        self.extra_headers.extend(headers.clone());
        self
    }

    pub fn retries(mut self, retries: i64) -> Self {
        self.retries = retries;
        self
    }

    /// Accept an HTML body instead of rejecting it, for callers that parse
    /// arbitrary content such as directory listings.
    pub fn allow_html(mut self) -> Self {
        self.allow_html = true;
        self
    }

    pub async fn send(mut self) -> Result<String> {
        ensure!(
            !crate::network::offline(&Settings::get()),
            "offline mode is enabled"
        );
        let mut url = self.url.clone().map_err(|e| eyre!(e))?;
        // Merge GitHub headers with any extra headers provided
        let mut headers = host_auth_headers(&url)?;
        headers.extend(self.extra_headers.clone());
        let text = self
            .client
            .send_with_retries(
                RetryableRequest {
                    method: Method::GET,
                    url: url.clone(),
                    headers: &headers,
                    verb_label: "GET",
                    retries: self.retries,
                    error_for_status: true,
                },
                |resp| async move {
                    Ok(buffer_body(resp)
                        .await?
                        .text()
                        .await
                        .map_err(redact_error_url)?)
                },
            )
            .await?;
        if !self.allow_html && text.starts_with("<!DOCTYPE html>") {
            if url.scheme() == "http" {
                // try with https since http may be blocked
                url.set_scheme("https").unwrap();
                self.url = Ok(url);
                return Box::pin(self.send()).await;
            }
            bail!("Got HTML instead of text from {}", log_url(&url));
        }
        Ok(text)
    }
}

/// Matches what [`is_github_unauthorized`] accepts, so a GitHub Enterprise
/// Server host gets the same 403 report and rate-limit classification as
/// api.github.com rather than a bare status error.
fn is_github_forbidden(url: &Url, resp: &Response) -> bool {
    resp.status() == StatusCode::FORBIDDEN && crate::github::is_github_api_url(url)
}

fn is_github_unauthorized(url: &Url, resp: &Response) -> bool {
    resp.status() == StatusCode::UNAUTHORIZED && crate::github::is_github_api_url(url)
}

/// Fails, removing `path`, when a download capped at `max_bytes` came out
/// larger. The transfer enforces the cap as bytes arrive, but a download can
/// also be satisfied without a transfer: a stored copy the server says is
/// still current, a pinned copy, or a partial download that was already
/// complete, any of which an uncapped download of the same URL may have left.
fn ensure_download_within(path: &Path, url: &Url, max_bytes: u64) -> Result<()> {
    if std::fs::metadata(path)?.len() > max_bytes {
        let _ = std::fs::remove_file(path);
        bail!(
            "download from {} is larger than {}",
            log_url(url),
            bytesize::ByteSize::b(max_bytes).display().iec()
        );
    }
    Ok(())
}

/// Awaits `read`, which reads a response body, for at most `timeout`. Only
/// `Fetch` requests carry a total request timeout; on the `Http` client the
/// idle `read_timeout` restarts whenever a byte arrives, so a body that
/// trickles in needs its own deadline. The error is not a reqwest timeout, so
/// it is not retried.
async fn read_body_within<T>(
    timeout: Duration,
    url: &Url,
    read: impl std::future::Future<Output = Result<T>>,
) -> Result<T> {
    match tokio::time::timeout(timeout, read).await {
        Ok(result) => result,
        Err(_) => Err(BodyTimedOut {
            timeout,
            url: log_url(url).into_owned(),
        }
        .into()),
    }
}

/// A response body that did not finish arriving within `http_download_timeout`.
/// A caller that falls back when a host is unavailable can treat it as that.
#[derive(Debug, thiserror::Error)]
#[error(
    "HTTP response body timed out after {} for {url} (change with `http_download_timeout` or env `MISE_HTTP_DOWNLOAD_TIMEOUT`)",
    format_duration(*timeout)
)]
pub struct BodyTimedOut {
    timeout: Duration,
    url: String,
}

/// Most decoded bytes a successful response may hold in memory when mise parses
/// it rather than saving it to a file. The client inflates gzip and zstd
/// transparently, so neither `Content-Length` nor the bytes on the wire bound
/// what `json()`, `text()` or `bytes()` collect: a 1 MiB gzip reply can inflate
/// to 1 GiB. The largest documents read this way, Homebrew's formula list and
/// GitHub release pages, are a few tens of MiB. Downloads stream to disk and
/// are not affected; a caller that parses something larger passes its own
/// limit to [`buffer_body_with_limit`].
/// Lower in tests, which have to send more than this to reach it.
pub const MAX_BODY_BYTES: usize = if cfg!(test) {
    1024 * 1024
} else {
    128 * 1024 * 1024
};

/// [`buffer_body_with_limit`] with [`MAX_BODY_BYTES`].
pub async fn buffer_body(resp: Response) -> Result<Response> {
    buffer_body_with_limit(resp, MAX_BODY_BYTES).await
}

/// Reads the decoded body chunk by chunk, failing once it passes `limit`, and
/// returns the response with the body buffered, ready for `json()`, `text()`
/// or `bytes()`. Those collect whatever the server sends, so call this first.
/// The read is also bounded by `http_download_timeout`. Neither failure is a
/// transport error, so neither is retried.
pub async fn buffer_body_with_limit(mut resp: Response, limit: usize) -> Result<Response> {
    let too_large = |url: &Url| {
        eyre!(
            "response body from {} is larger than {}",
            log_url(url),
            bytesize::ByteSize::b(limit as u64).display().iec()
        )
    };
    if resp
        .content_length()
        .is_some_and(|length| length > limit as u64)
    {
        return Err(too_large(resp.url()));
    }
    // Bounded in time as well as size: a caller may hold a response from a
    // client with only an idle read timeout, which a body that trickles in a
    // byte at a time never trips.
    let url = resp.url().clone();
    let read = async {
        let mut bytes = Vec::new();
        while let Some(chunk) = resp.chunk().await.map_err(redact_error_url)? {
            if bytes.len() + chunk.len() > limit {
                return Err(too_large(resp.url()));
            }
            bytes.extend_from_slice(&chunk);
        }
        Ok(bytes)
    };
    let bytes = read_body_within(
        crate::network::http_download_timeout(&Settings::get()),
        &url,
        read,
    )
    .await?;
    let mut buffered = ::http::Response::builder()
        .status(resp.status())
        .version(resp.version())
        .url(resp.url().clone())
        .body(bytes)?;
    *buffered.headers_mut() = std::mem::take(resp.headers_mut());
    Ok(buffered.into())
}

/// Maximum body bytes buffered when building a GitHub error report, so an
/// oversized or slow-trickling error response can't exhaust memory. The overall
/// request timeout bounds the time; this bounds the memory.
const MAX_ERROR_BODY_BYTES: usize = 64 * 1024;

/// Reads at most [`MAX_ERROR_BODY_BYTES`] of the response body for use in an
/// error message, streaming chunk-by-chunk instead of buffering the whole body,
/// and abandoning the read after `deadline` so a slowly-trickling response can't
/// block indefinitely (the `Http` client has no overall request timeout, only an
/// idle `read_timeout`). On timeout the partial body is dropped and "" returned.
pub async fn read_bounded_error_body(resp: Response, deadline: Duration) -> String {
    let read = async move {
        let mut resp = resp;
        let mut bytes = Vec::new();
        while let Ok(Some(chunk)) = resp.chunk().await {
            let remaining = MAX_ERROR_BODY_BYTES.saturating_sub(bytes.len());
            if remaining == 0 {
                break;
            }
            bytes.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
        }
        String::from_utf8_lossy(&bytes).to_string()
    };
    tokio::time::timeout(deadline, read)
        .await
        .unwrap_or_default()
}

/// The GitHub token a raw.githubusercontent.com request should be retried
/// without: the one it carried when the answer was a 404. Any scheme, unlike
/// `is_github_raw_content_url`, whose https rule keeps a token off cleartext:
/// dropping a token can never leak one.
fn raw_content_token_to_drop<'a>(
    url: &Url,
    status: StatusCode,
    headers: &'a HeaderMap,
) -> Option<&'a str> {
    if status != StatusCode::NOT_FOUND || url.host_str() != Some("raw.githubusercontent.com") {
        return None;
    }
    headers
        .get(AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
}

/// What to tell the user when raw.githubusercontent.com served a file only once
/// mise stopped sending their GitHub token: the token is not being accepted, and
/// the requests that need it (private repositories, the API) will fail too.
fn rejected_raw_token_warning(token_source: Option<&crate::github::TokenSource>) -> String {
    let source = match token_source {
        Some(crate::github::TokenSource::EnvVar(var)) => format!("token in `{var}`"),
        Some(source) => format!("token from {source}"),
        None => "configured GitHub token".to_string(),
    };
    format!(
        "GitHub did not accept the {source}: raw.githubusercontent.com answered 404 until mise \
         retried without it. Check that it is valid and not expired with `mise token github` — \
         see https://mise.jdx.dev/dev-tools/github-tokens.html"
    )
}

fn github_unauthorized_report(
    status_error: reqwest::Error,
    used_github_token: bool,
    token_source: Option<&crate::github::TokenSource>,
    body: &str,
) -> Report {
    // Only report a token when one was actually sent: the process may have a
    // GitHub token env var set that wasn't applied to this request.
    let auth = if !used_github_token {
        "no".to_string()
    } else {
        token_source
            .map(|source| format!("yes (token from {source})"))
            .unwrap_or_else(|| "yes".to_string())
    };
    let body = format_response_body(body);
    let hint = if used_github_token {
        let source = match token_source {
            Some(crate::github::TokenSource::EnvVar(var)) => format!("token in `{var}`"),
            Some(source) => format!("token from {source}"),
            None => "configured GitHub token".to_string(),
        };
        format!(
            "\nhint: the {source} was rejected by GitHub (401 Unauthorized). Verify it is a \
             valid, non-expired token for this host with the required scopes — see \
             https://mise.jdx.dev/dev-tools/github-tokens.html"
        )
    } else {
        String::new()
    };
    eyre!("{status_error}\ngithub auth: {auth}\ngithub response: {body}{hint}")
}

fn github_forbidden_report(
    status_error: reqwest::Error,
    used_github_token: bool,
    rate_limit: Option<String>,
    rate_limited: bool,
    body: &str,
) -> Report {
    let token_status = if used_github_token { "yes" } else { "no" };
    let rate_limit = rate_limit
        .map(|summary| format!("\ngithub rate limit: {summary}"))
        .unwrap_or_default();
    let body = format_response_body(body);
    let message =
        format!("{status_error}\ngithub auth: {token_status}{rate_limit}\ngithub response: {body}");
    if rate_limited {
        return GithubRateLimited(message).into();
    }
    eyre!("{message}")
}

/// Whether a GitHub 403 is a rate limit rather than a refusal.
///
/// `x-ratelimit-remaining: 0` covers the primary limit; `retry-after` covers
/// the secondary limits, which can arrive with quota still on the clock. Mirrors
/// what [`display_github_rate_limit`] reports so the two cannot disagree.
fn is_github_rate_limited(resp: &Response) -> bool {
    let headers = resp.headers();
    let exhausted = headers
        .get("x-ratelimit-remaining")
        .and_then(|h| h.to_str().ok())
        .is_some_and(|remaining| remaining == "0");
    exhausted || headers.contains_key("retry-after")
}

fn format_response_body(body: &str) -> String {
    const MAX_BODY_CHARS: usize = 4096;
    if body.trim().is_empty() {
        return "<empty>".to_string();
    }

    let mut chars = body.chars();
    let mut formatted: String = chars.by_ref().take(MAX_BODY_CHARS).collect();
    if chars.next().is_some() {
        formatted.push_str("\n<truncated>");
    }
    formatted
}

fn github_rate_limit_summary(resp: &Response) -> Option<String> {
    let headers = resp.headers();
    let limit = headers
        .get("x-ratelimit-limit")
        .and_then(|h| h.to_str().ok());
    let remaining = headers
        .get("x-ratelimit-remaining")
        .and_then(|h| h.to_str().ok());
    let resource = headers
        .get("x-ratelimit-resource")
        .and_then(|h| h.to_str().ok());
    let reset = headers
        .get("x-ratelimit-reset")
        .and_then(|h| h.to_str().ok());

    if limit.is_none() && remaining.is_none() && resource.is_none() && reset.is_none() {
        return None;
    }

    Some(format!(
        "{}/{}{}{}",
        remaining.unwrap_or("?"),
        limit.unwrap_or("?"),
        resource
            .map(|resource| format!(" ({resource})"))
            .unwrap_or_default(),
        reset
            .map(|reset| format!(", resets at {reset}"))
            .unwrap_or_default()
    ))
}

fn stale_github_oauth_unauthorized_token(
    url: &Url,
    headers: &HeaderMap,
    resp: &Response,
) -> Option<String> {
    if resp.status() != StatusCode::UNAUTHORIZED || !crate::github::is_github_api_url(url) {
        return None;
    }
    let host = url.host_str()?;
    let token = crate::github::oauth::cached_access_token_for_host(host)?;
    let header_token = headers
        .get(AUTHORIZATION)
        .and_then(|header| header.to_str().ok())
        .and_then(|header| header.strip_prefix("Bearer "))?;
    if header_token == token {
        Some(header_token.to_string())
    } else {
        None
    }
}

pub fn error_code(e: &Report) -> Option<u16> {
    // The real status first: a message can mention 404 without being one, such
    // as a 429 whose `Retry-After` is 404 seconds.
    if let Some(status) = e
        .downcast_ref::<reqwest::Error>()
        .and_then(reqwest::Error::status)
    {
        return Some(status.as_u16());
    }
    if e.to_string().contains("404") {
        // TODO: not this when I can figure out how to use eyre properly
        return Some(404);
    }
    None
}

/// The automatic host credentials for `url` (a forge token, say) with `headers` layered
/// on top, so a configured header replaces the one of the same name and every other
/// automatic header is kept. Every request that takes caller headers sends this.
pub fn with_host_auth(url: &Url, headers: &HeaderMap) -> Result<HeaderMap> {
    let mut merged = host_auth_headers(url)?;
    merged.extend(headers.clone());
    Ok(merged)
}

pub fn host_auth_headers(url: &Url) -> Result<HeaderMap> {
    // raw.githubusercontent.com is not an API host, but a private repository's
    // files are a 404 without the token, so it is routed here too. `get_headers`
    // decides what each host actually gets.
    if crate::github::is_github_api_url(url) || crate::github::is_github_raw_content_url(url) {
        return crate::github::get_headers(url.as_str(), crate::github::API_URL);
    }

    // A generic URL does not carry the configured GitHub Enterprise, GitLab or
    // Forgejo API origin, so it cannot establish a safe trust boundary for those
    // tokens. Their backend-specific callers must pass the request and API URLs
    // directly to the corresponding `get_headers` function.
    Ok(HeaderMap::new())
}

/// Decide whether netrc credentials should be applied to a request.
///
/// netrc is a *fallback*: an explicit Authorization header (e.g. a forge
/// token resolved from GITHUB_TOKEN/gh/github_tokens.toml) takes precedence
/// over netrc, matching curl's behavior. The exception is a URL replacement
/// that redirected the request to a *different host*: the existing auth
/// header was built for the original host and is likely wrong for the
/// replacement target, so netrc (which is itself scoped to the new host) is
/// allowed to override it. A same-host rewrite (e.g. a path-only replacement)
/// keeps the existing auth, since the forge token is still valid for that host.
fn netrc_should_apply(host_changed: bool, has_existing_auth: bool) -> bool {
    host_changed || !has_existing_auth
}

const MAX_MANUAL_REDIRECTS: usize = 10;

enum SendError {
    Reqwest(reqwest::Error),
    /// A refusal that is not a transport failure, so it is neither retried nor
    /// classified as a timeout.
    Refused(String),
}

impl From<reqwest::Error> for SendError {
    fn from(err: reqwest::Error) -> Self {
        Self::Reqwest(err)
    }
}

/// A credential header that reqwest does not remove on a cross-host redirect.
fn has_unscoped_credential(headers: &HeaderMap) -> bool {
    headers.iter().any(|(name, value)| {
        is_credential_header(name, value)
            && name != AUTHORIZATION
            && name != COOKIE
            && name != PROXY_AUTHORIZATION
    })
}

/// Prefix of the internal headers that carry [`ForwardRules`] alongside the real ones, so
/// they travel through every retry and cache key without a parallel argument. They are
/// removed before a request is built and are never sent.
const FORWARD_RULE_PREFIX: &str = "x-mise-forward-";

/// Whether `name` is reserved for forwarding rules and cannot be used as a request header.
pub fn is_reserved_header_name(name: &str) -> bool {
    name.to_ascii_lowercase().starts_with(FORWARD_RULE_PREFIX)
}

/// Whether `pattern` is a host an allowlist may contain: an exact hostname, or `*.` followed
/// by a suffix for its subdomains. A bare `*` is refused so the list cannot mean "everywhere".
pub fn is_valid_forward_host(pattern: &str) -> bool {
    let host = pattern.strip_prefix("*.").unwrap_or(pattern);
    !host.is_empty()
        && !host.contains('*')
        && host
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
        && !host.starts_with('.')
        && !host.ends_with('.')
}

/// Encode "`name` may follow a redirect to these hosts" as an internal header.
pub fn forward_rule_header(
    name: &HeaderName,
    hosts: &[String],
) -> Result<(HeaderName, HeaderValue)> {
    for host in hosts {
        ensure!(is_valid_forward_host(host), "invalid forward host `{host}`");
    }
    Ok((
        HeaderName::from_bytes(format!("{FORWARD_RULE_PREFIX}{}", name.as_str()).as_bytes())?,
        HeaderValue::from_str(&hosts.join(","))?,
    ))
}

/// Which hosts each request header may be forwarded to after a cross-host redirect.
/// Everything not listed is dropped, so the default is to forward nothing.
#[derive(Debug, Default)]
struct ForwardRules(HashMap<HeaderName, Vec<String>>);

impl ForwardRules {
    /// Re-encode the rules onto `headers`, for a request that is sent again after
    /// [`split_forward_rules`] took them off.
    fn attach_to(&self, headers: &mut HeaderMap) {
        for (name, hosts) in &self.0 {
            if let Ok((rule_name, rule_value)) = forward_rule_header(name, hosts) {
                headers.insert(rule_name, rule_value);
            }
        }
    }

    fn applies_to(&self, headers: &HeaderMap) -> bool {
        self.0.keys().any(|name| headers.contains_key(name))
    }

    /// Cross-origin hop to `next`: drop every credential header that is not allowed to
    /// reach `next`. A header dropped here stays dropped for the rest of the chain.
    fn retain_for(&self, headers: &mut HeaderMap, previous: &Url, next: &Url) {
        let host = next.host_str().unwrap_or_default();
        // Forwarding is for secrets, so it never steps down to plain HTTP. A chain that
        // is already plain HTTP, because the user wrote an `http://` URL, stays allowed.
        let secure = next.scheme() == "https" || previous.scheme() == "http";
        let dropped = headers
            .iter()
            .filter(|(name, value)| is_credential_header(name, value))
            .filter(|(name, _)| {
                !(secure
                    && self
                        .0
                        .get(*name)
                        .is_some_and(|patterns| host_matches_any(patterns, host)))
            })
            .map(|(name, _)| name.clone())
            .collect::<Vec<_>>();
        for name in dropped {
            headers.remove(name);
        }
    }
}

fn host_matches_any(patterns: &[String], host: &str) -> bool {
    // DNS names are case-insensitive, and so are both sides of the comparison.
    let host = host.to_ascii_lowercase();
    patterns.iter().any(|pattern| {
        let pattern = pattern.to_ascii_lowercase();
        match pattern.strip_prefix("*.") {
            Some(suffix) => host
                .strip_suffix(suffix)
                .is_some_and(|rest| rest.ends_with('.') && rest.len() > 1),
            None => pattern == host,
        }
    })
}

/// Separate the real request headers from the internal forwarding rules.
fn split_forward_rules(headers: &HeaderMap) -> (HeaderMap, ForwardRules) {
    let mut real = HeaderMap::new();
    let mut rules = HashMap::new();
    for (name, value) in headers {
        if let Some(target) = name.as_str().strip_prefix(FORWARD_RULE_PREFIX) {
            if let (Ok(target), Ok(value)) =
                (HeaderName::from_bytes(target.as_bytes()), value.to_str())
            {
                rules.insert(
                    target,
                    value.split(',').map(str::to_string).collect::<Vec<_>>(),
                );
            }
        } else {
            real.append(name.clone(), value.clone());
        }
    }
    (real, ForwardRules(rules))
}

fn is_credential_header(name: &HeaderName, value: &HeaderValue) -> bool {
    if value.is_sensitive()
        || name == AUTHORIZATION
        || name == PROXY_AUTHORIZATION
        || name == COOKIE
    {
        return true;
    }
    let name = name.as_str();
    name == "api-key"
        || name == "x-api-key"
        || name.ends_with("-api-key")
        || name.contains("token")
        || name.contains("secret")
        || name.contains("credential")
}

/// Drop credentials scoped to the original host before contacting a replacement host.
pub fn clear_cross_host_credentials(headers: &mut HeaderMap, original_url: &Url, url: &mut Url) {
    if url.host() == original_url.host() {
        return;
    }
    let credential_headers = headers
        .iter()
        .filter(|(name, value)| is_credential_header(name, value))
        .map(|(name, _)| name.clone())
        .collect::<Vec<_>>();
    for name in credential_headers {
        headers.remove(name);
    }
    let inherited_userinfo = (!original_url.username().is_empty()
        || original_url.password().is_some())
        && url.username() == original_url.username()
        && url.password() == original_url.password();
    if inherited_userinfo {
        url.set_password(None)
            .expect("HTTP URLs support clearing passwords");
        url.set_username("")
            .expect("HTTP URLs support clearing usernames");
    }
}

/// Merge `netrc` credentials into `final_headers`, honoring the fallback
/// policy in [`netrc_should_apply`]. `original_url` is the URL before any
/// `apply_url_replacements` rewrite and `url` is the (possibly rewritten)
/// URL actually being requested; a change of *host* means the request was
/// redirected to a different server, which lets netrc supply replacement-host
/// authentication after original-host credentials have been removed. Netrc
/// values are `insert`ed so only one Authorization value is present.
fn apply_netrc_credentials(
    mut final_headers: HeaderMap,
    original_url: &Url,
    url: &Url,
    netrc: HeaderMap,
) -> HeaderMap {
    // Compare host only: netrc lookup and forge-token selection are both
    // host-scoped, so a path/query-only rewrite on the same host must not
    // let netrc clobber a still-valid forge token.
    let host_changed = url.host() != original_url.host();
    let has_auth = final_headers.contains_key(AUTHORIZATION);
    if netrc_should_apply(host_changed, has_auth) {
        for (name, value) in netrc {
            if let Some(name) = name {
                final_headers.insert(name, value);
            }
        }
    }
    final_headers
}

/// Reject credentials when a URL replacement downgrades an HTTPS request to HTTP.
pub fn ensure_secure_replacement_credentials(
    original_url: &Url,
    url: &Url,
    headers: &HeaderMap,
) -> Result<()> {
    let has_credentials = headers
        .iter()
        .any(|(name, value)| is_credential_header(name, value));
    ensure_secure_url_replacement(original_url, url, has_credentials)
}

pub fn ensure_secure_url_replacement(
    original_url: &Url,
    url: &Url,
    has_credentials: bool,
) -> Result<()> {
    let downgraded = original_url.scheme() == "https" && url.scheme() == "http";
    let has_credentials = has_credentials || !url.username().is_empty() || url.password().is_some();
    ensure!(
        !downgraded || !has_credentials,
        "refusing to send credentials over an HTTPS-to-HTTP URL replacement"
    );
    Ok(())
}

/// Get HTTP Basic authentication headers from netrc file for the given URL
pub fn netrc_headers(url: &Url) -> HeaderMap {
    let mut headers = HeaderMap::new();
    // A host that a project `version_list_url` named in safe mode; see
    // `untrusted_hosts`.
    if crate::untrusted_hosts::netrc_denied(url) {
        return headers;
    }
    if let Some(host) = url.host_str()
        && let Some((login, password)) = netrc::get_credentials(host)
    {
        let credentials = BASE64_STANDARD.encode(format!("{login}:{password}"));
        if let Ok(value) = HeaderValue::from_str(&format!("Basic {credentials}")) {
            headers.insert(reqwest::header::AUTHORIZATION, value);
        }
    }
    headers
}

/// Resolve the `rel="next"` target of a `Link` header against the URL it came from.
///
/// Forge APIs are inconsistent about this: an absolute URL is the common case, but a
/// root-relative or relative target is legal and appears from instances behind a proxy.
/// Shared by [`crate::github`] and [`crate::gitlab`] so their pagination loops resolve
/// the next page the same way — the two drifted apart once already (#6318).
pub fn resolve_pagination_url(current: &str, next: &str) -> Result<String> {
    if next.starts_with("http://") || next.starts_with("https://") {
        return Ok(next.to_string());
    }
    let base = url::Url::parse(current)
        .wrap_err_with(|| format!("invalid pagination base URL: {current}"))?;
    if next.starts_with('/') {
        return Ok(format!("{}{next}", base.origin().ascii_serialization()));
    }
    base.join(next)
        .map(|u| u.to_string())
        .wrap_err_with(|| format!("invalid pagination URL: {next}"))
}

/// Apply URL replacements based on settings configuration
/// Supports both simple string replacement and regex patterns (prefixed with "regex:")
/// The GitHub relay socket to send `url` through instead of the network,
/// when mise runs behind a relay adapter.
#[cfg(unix)]
fn github_relay_socket(url: &Url) -> Option<std::ffi::OsString> {
    if matches!(url.host_str(), Some("github.com" | "api.github.com")) {
        std::env::var_os("MISE_GITHUB_RELAY_SOCKET")
    } else {
        None
    }
}

pub fn apply_url_replacements(url: &mut Url) {
    let settings = Settings::get();
    if let Some(replacements) = &settings.url_replacements {
        let url_string = url.to_string();

        for (pattern, replacement) in replacements {
            if let Some(pattern_without_prefix) = pattern.strip_prefix("regex:") {
                // Regex replacement
                if let Ok(regex) = Regex::new(pattern_without_prefix) {
                    let new_url_string = regex.replace(&url_string, replacement.as_str());
                    // Only proceed if the URL actually changed
                    if new_url_string != url_string
                        && let Ok(new_url) = new_url_string.parse()
                    {
                        *url = new_url;
                        trace!(
                            "Replaced URL using regex '{}': {} -> {}",
                            pattern_without_prefix,
                            redact_url_userinfo(&url_string),
                            log_url(url)
                        );
                        return; // Apply only the first matching replacement
                    }
                } else {
                    warn!(
                        "Invalid regex pattern in URL replacement: {}",
                        pattern_without_prefix
                    );
                }
            } else {
                // Simple string replacement
                if url_string.contains(pattern) {
                    let new_url_string = url_string.replace(pattern, replacement);
                    // Only proceed if the URL actually changed
                    if new_url_string != url_string
                        && let Ok(new_url) = new_url_string.parse()
                    {
                        *url = new_url;
                        trace!(
                            "Replaced URL using string replacement '{}': {} -> {}",
                            pattern,
                            redact_url_userinfo(&url_string),
                            log_url(url)
                        );
                        return; // Apply only the first matching replacement
                    }
                }
            }
        }
    }
}

/// `url` for a log line or error message, without the credentials it may embed:
/// its userinfo, and the values of its query parameters (see [`redact_query`]).
fn log_url(url: &Url) -> std::borrow::Cow<'_, str> {
    match url.query() {
        Some(query) if redact_query(query) != query => {
            let mut url = url.clone();
            url.set_query(Some(&redact_query(query)));
            redact_url_userinfo(url.as_str()).into_owned().into()
        }
        _ => redact_url_userinfo(url.as_str()),
    }
}

/// A query string with the value of each parameter replaced by `[redacted]`.
///
/// Signed URLs and API keys travel in the query (`?private_token=`,
/// `?X-Amz-Signature=`), and mise cannot tell those from harmless parameters by
/// name. Names are kept, and so are the short numbers of the paging parameters
/// mise sends (`page=2`, `per_page=100`, `limit=100`), which keep paged requests
/// readable; a short number under any other name (`token=123456`) is hidden.
fn redact_query(query: &str) -> String {
    query
        .split('&')
        .map(|pair| {
            let (name, value) = match pair.split_once('=') {
                Some((name, value)) => (Some(name), value),
                None => (None, pair),
            };
            // Only the paging parameters mise sends keep a short number, so a
            // numeric token (`token=123456`) is hidden like any other value.
            let paging = name.is_some_and(|name| matches!(name, "page" | "per_page" | "limit"));
            let harmless = value.is_empty()
                || (paging && value.len() <= 6 && value.bytes().all(|b| b.is_ascii_digit()));
            match (name, harmless) {
                (_, true) => pair.to_string(),
                (Some(name), false) => format!("{name}=[redacted]"),
                (None, false) => "[redacted]".to_string(),
            }
        })
        .collect::<Vec<_>>()
        .join("&")
}

/// `err` with the URL it reports (`for url (...)`, the last hop after
/// redirects) stripped of its credentials, as [`log_url`] shows URLs. The error
/// keeps its kind and status, so retry decisions are unaffected.
fn redact_error_url(mut err: reqwest::Error) -> reqwest::Error {
    if let Some(url) = err.url_mut() {
        let _ = url.set_username("");
        let _ = url.set_password(None);
        if let Some(query) = url.query().map(redact_query) {
            url.set_query(Some(&query));
        }
    }
    err
}

fn display_github_rate_limit(resp: &Response) {
    let status = resp.status().as_u16();
    if status == 403 || status == 429 {
        let remaining = resp
            .headers()
            .get("x-ratelimit-remaining")
            .and_then(|r| r.to_str().ok());
        if remaining.is_some_and(|r| r == "0") {
            if let Some(reset_time) = resp
                .headers()
                .get("x-ratelimit-reset")
                .and_then(|h| h.to_str().ok())
                .and_then(|s| s.parse::<i64>().ok())
                .and_then(|ts| chrono::DateTime::from_timestamp(ts, 0))
            {
                warn!(
                    "GitHub rate limit exceeded. Resets at {}",
                    reset_time.with_timezone(&chrono::Local)
                );
            }
            return;
        }
        // retry-after header is processed only if x-ratelimit-remaining is not 0 or is missing
        if let Some(retry_after) = resp
            .headers()
            .get("retry-after")
            .and_then(|h| h.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok())
        {
            warn!(
                "GitHub rate limit exceeded. Retry after {} seconds",
                retry_after
            );
        }
    }
}

pub fn default_backoff_strategy(retries: i64) -> impl Iterator<Item = Duration> {
    // Hand-rolled schedule (with jitter): ~200ms / ~1s / ~4s / ~15s, then 15s
    // for every retry beyond the schedule. The trailing repeat matters because
    // `MISE_HTTP_RETRIES` can be set arbitrarily high — a fixed-length array
    // would silently cap retries at its length. tokio_retry's ExponentialBackoff
    // ::from_millis is geometric in the base (base, base*base, …) so picking a
    // base that gives nice human-scale delays is awkward; explicit is clearer.
    // Retry tests assert attempts and outcomes, not wall-clock sleeping.
    let schedule = if crate::testing::in_tests() {
        [2u64, 10, 40, 150]
    } else {
        [200u64, 1_000, 4_000, 15_000]
    };
    schedule
        .into_iter()
        .chain(std::iter::repeat(15_000))
        .map(Duration::from_millis)
        .map(equal_jitter)
        .take(retries.max(0) as usize)
}

/// Jitter the duration to a random value in `[d/2, d)` — "equal jitter" per
/// AWS's backoff guidance. Avoids tokio_retry's `jitter` which can return
/// near-zero (its range is `[0, d)`), defeating the point of backoff.
fn equal_jitter(d: Duration) -> Duration {
    let factor = 0.5 + rand::random::<f64>() * 0.5;
    Duration::from_secs_f64(d.as_secs_f64() * factor)
}

/// True if the error is a network-layer connection problem (no status received).
/// Used to decide when http→https fallback makes sense: only when the http
/// attempt never reached the server, not when the server returned a status.
fn is_connection_error(err: &Report) -> bool {
    err.chain().any(|e| {
        let Some(reqwest_err) = e.downcast_ref::<reqwest::Error>() else {
            return false;
        };
        (reqwest_err.is_connect() || reqwest_err.is_timeout()) && reqwest_err.status().is_none()
    })
}

/// True if a request failed without reaching the server: a connection failure,
/// a timeout, or a host already marked unavailable. Unlike [`is_transient`],
/// HTTP statuses and other errors from the server or the caller never match.
pub fn is_unreachable(err: &Report) -> bool {
    is_connection_error(err)
        || is_unavailable_http_host_error(err)
        || err.chain().any(|err| {
            err.downcast_ref::<CachedFailure>()
                .is_some_and(|failure| failure.unreachable)
        })
}

fn http_host_key(url: &Url) -> Option<String> {
    let host = url.host_str()?;
    let port = url.port_or_known_default()?;
    Some(format!("{}://{host}:{port}", url.scheme()))
}

fn is_unavailable_http_host_error(err: &Report) -> bool {
    err.chain()
        .any(|err| err.downcast_ref::<UnavailableHttpHost>().is_some())
}

/// hyper-util exposes DNS failures in the error chain as a `dns error` source,
/// but reqwest intentionally erases the concrete connector type. Match that
/// stable connector error label rather than platform-specific getaddrinfo text.
fn is_dns_error(err: &(dyn std::error::Error + 'static)) -> bool {
    let mut current = Some(err);
    while let Some(source) = current {
        if source.to_string() == "dns error" {
            return true;
        }
        current = source.source();
    }
    false
}

fn is_hard_connection_failure(err: &reqwest::Error) -> bool {
    is_dns_error(err) || (err.is_connect() && !err.is_timeout())
}

fn is_serde_error(err: &(dyn std::error::Error + 'static)) -> bool {
    let mut cur = err.source();
    while let Some(e) = cur {
        if e.is::<serde_json::Error>() {
            return true;
        }
        cur = e.source();
    }
    false
}

/// Classifies an error as transient (should retry) vs permanent.
/// Walks the error chain so wrapped errors (e.g. our timeout hint) still match.
pub fn is_transient(err: &Report) -> bool {
    if is_dns_error(err.as_ref()) {
        return false;
    }
    if err
        .downcast_ref::<RetryAfter>()
        .is_some_and(|r| r.wait > MAX_RETRY_AFTER)
    {
        return false;
    }
    err.chain().any(|e| {
        if e.downcast_ref::<DownloadSizeMismatch>().is_some() {
            return true;
        }
        if e.downcast_ref::<std::io::Error>()
            .is_some_and(|err| err.kind() == std::io::ErrorKind::TimedOut)
        {
            return true;
        }
        // GitHub answers a rate limit with 403, which the status check below
        // treats as deterministic. Classify it with the 429 it means.
        if e.downcast_ref::<GithubRateLimited>().is_some() {
            return true;
        }
        let Some(reqwest_err) = e.downcast_ref::<reqwest::Error>() else {
            return false;
        };
        // Network-layer failures: connect refused, timeout, mid-stream body drop.
        if reqwest_err.is_timeout() || reqwest_err.is_connect() || reqwest_err.is_body() {
            return true;
        }
        // reqwest stamps a failed body read as `Decode`. An HTTP/2 stream reset
        // mid-download arrives as a `Decode` wrapping an `h2::Error` with no
        // nested `Body` error. Deserialization failures (serde) are
        // deterministic, so only transport-level decode failures retry.
        if reqwest_err.is_decode() && !is_serde_error(reqwest_err) {
            return true;
        }
        // Send failures that never produced a response: the connection was
        // established but the request did not complete, so no application logic
        // ran and a retry is safe. This covers HTTP/2 stream errors such as
        // REFUSED_STREAM (which RFC 9113 §8.7 defines as "the request was not
        // processed", i.e. safely retryable) and connections closed before the
        // response started. These are not is_connect(), because connecting
        // succeeded, and they carry no status, so without this they fall through
        // and fail on the first attempt regardless of `http_retries`.
        if reqwest_err.is_request() && reqwest_err.status().is_none() {
            return true;
        }
        // Status errors: 5xx server errors plus 408 (Request Timeout) and
        // 429 (Too Many Requests). Other 4xx are deterministic — don't retry.
        if let Some(status) = reqwest_err.status() {
            let code = status.as_u16();
            return code == 408 || code == 429 || (500..600).contains(&code);
        }
        false
    })
}

/// Retry an async operation on transient errors using `default_backoff_strategy`.
/// Emits a warn! immediately on each transient failure so the user sees flaky
/// infrastructure as it's happening, instead of waiting through the backoff
/// schedule. Successful rescues and final exhaustion don't get extra warnings
/// — the caller surfaces the outcome.
///
/// Uses the configured `http_retries` rather than `network::http_retries`: the
/// prefer-offline zero-retry budget bounds remote-version lookups, but an
/// artifact download that `mise exec`/a shim triggered is an install and must
/// retry like `mise install` does.
pub async fn retry_async<F, Fut, T>(verb_label: &str, url: &Url, f: F) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    retry_async_with_retries(verb_label, url, Settings::get().http_retries, f).await
}

pub async fn retry_async_with_retries<F, Fut, T>(
    verb_label: &str,
    url: &Url,
    retries: i64,
    mut f: F,
) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let mut backoff = default_backoff_strategy(retries);
    let mut attempt: usize = 1;
    loop {
        let started_at = Instant::now();
        match f().await {
            Ok(value) => return Ok(value),
            Err(err) => {
                if !is_transient(&err) {
                    return Err(err);
                }
                let Some(delay) = backoff.next() else {
                    return Err(err);
                };
                let delay = retry_delay(delay, &err);
                warn!(
                    "HTTP {} {} attempt {} failed after {} (transient): {}; retrying in {:?}",
                    verb_label,
                    log_url(url),
                    attempt,
                    format_duration(started_at.elapsed()),
                    err,
                    delay
                );
                crate::resolve_progress::retrying(url, attempt + 1, delay);
                tokio::time::sleep(delay).await;
                attempt += 1;
            }
        }
    }
}

/// Averaged over a full [`SLOW_DOWNLOAD_WINDOW`], throughput below this is
/// reported. At 16 KiB/s the default 30 minute `http_download_timeout` covers
/// under 30 MB, so a typical tool archive would not finish in time.
const SLOW_DOWNLOAD_BYTES_PER_SEC: u64 = 16 * 1024;
const SLOW_DOWNLOAD_WINDOW: Duration = Duration::from_secs(60);
const SLOW_DOWNLOAD_SAMPLE_INTERVAL: Duration = Duration::from_secs(5);

/// Progress of a retried download. `attempt` restarts at zero on each retry
/// (the timeout error reports it per attempt); `total` never goes backwards,
/// which the slow-download watchdog relies on.
#[derive(Default)]
struct DownloadProgress {
    attempt: AtomicU64,
    earlier_attempts: AtomicU64,
    /// Server of the latest response, after `url_replacements` and redirects
    /// (the upstream GitHub host for relayed responses).
    served_by: Mutex<Option<ServedBy>>,
}

/// When a host started serving a download, so throughput can be split
/// exactly between hosts when a retry lands somewhere else.
#[derive(Clone, Debug, PartialEq)]
struct ServedBy {
    host: String,
    since: Instant,
    total_at_start: u64,
}

impl DownloadProgress {
    fn served_by(&self, url: &Url) {
        let Some(host) = url.host_str() else {
            return;
        };
        let mut served_by = self.served_by.lock().unwrap();
        if served_by.as_ref().is_none_or(|s| s.host != host) {
            *served_by = Some(ServedBy {
                host: host.to_string(),
                since: Instant::now(),
                total_at_start: self.total(),
            });
        }
    }

    fn start_attempt(&self) {
        self.earlier_attempts
            .fetch_add(self.attempt.swap(0, Ordering::Relaxed), Ordering::Relaxed);
    }

    fn total(&self) -> u64 {
        self.earlier_attempts.load(Ordering::Relaxed) + self.attempt.load(Ordering::Relaxed)
    }
}

/// Tracks transfer throughput over tumbling windows of a monotonic byte total.
struct SlowDownloadDetector {
    window_start: Instant,
    window_start_total: u64,
}

impl SlowDownloadDetector {
    fn new(now: Instant) -> Self {
        Self {
            window_start: now,
            window_start_total: 0,
        }
    }

    /// Starts a fresh window, discarding what the current one measured.
    fn restart(&mut self, now: Instant, total: u64) {
        self.window_start = now;
        self.window_start_total = total;
    }

    /// Records the bytes received so far across all attempts and, once a full
    /// window has elapsed, returns that window's rate in bytes/sec if it was
    /// too slow.
    fn observe(&mut self, now: Instant, total: u64) -> Option<u64> {
        let elapsed = now.duration_since(self.window_start);
        if elapsed < SLOW_DOWNLOAD_WINDOW {
            return None;
        }
        let bytes = total.saturating_sub(self.window_start_total);
        self.window_start = now;
        self.window_start_total = total;
        let rate = (bytes as f64 / elapsed.as_secs_f64()) as u64;
        (rate < SLOW_DOWNLOAD_BYTES_PER_SEC).then_some(rate)
    }
}

/// Decides, sample by sample, whether a download has been slow and which host
/// to blame. Each host is measured on its own: when a retry lands on another
/// host, the outgoing host's window ends exactly where the new host started.
struct SlowDownloadWatch {
    detector: SlowDownloadDetector,
    host: Option<String>,
}

impl SlowDownloadWatch {
    fn new(now: Instant) -> Self {
        Self {
            detector: SlowDownloadDetector::new(now),
            host: None,
        }
    }

    /// Returns the host to blame (if known) and its rate when a full window
    /// was too slow.
    fn sample(
        &mut self,
        now: Instant,
        total: u64,
        served_by: Option<&ServedBy>,
    ) -> Option<(Option<String>, u64)> {
        if let Some(served) = served_by
            && self.host.as_deref() != Some(served.host.as_str())
        {
            let previous = self.host.replace(served.host.clone());
            let slow = self.detector.observe(served.since, served.total_at_start);
            self.detector.restart(served.since, served.total_at_start);
            if let Some(rate) = slow {
                return Some((previous, rate));
            }
        }
        self.detector
            .observe(now, total)
            .map(|rate| (self.host.clone(), rate))
    }
}

/// Runs alongside a download and never completes. Warns at most once.
///
/// Names only the host: download URLs can carry credentials in their userinfo,
/// query, or path (presigned URLs), and this is a warning, not a debug line.
async fn warn_when_download_is_slow(
    url: &Url,
    progress: &DownloadProgress,
) -> std::convert::Infallible {
    let mut watch = SlowDownloadWatch::new(Instant::now());
    let mut ticks = tokio::time::interval(SLOW_DOWNLOAD_SAMPLE_INTERVAL);
    ticks.tick().await;
    let (host, rate) = loop {
        ticks.tick().await;
        let served_by = progress.served_by.lock().unwrap().clone();
        if let Some(sample) = watch.sample(Instant::now(), progress.total(), served_by.as_ref()) {
            break sample;
        }
    };
    let host = host
        .or_else(|| url.host_str().map(str::to_string))
        .unwrap_or_else(|| "the server".to_string());
    warn!(
        "download from {} is very slow ({}/s over the last minute). \
         mise keeps trying until `http_download_timeout` runs out; \
         if the host is throttling this connection, switching to a mirror may help",
        host,
        bytesize::ByteSize::b(rate).display().iec(),
    );
    std::future::pending().await
}

#[cfg(test)]
mod tests;