legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
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
//! Fetching an `image_url` source: HTTPS only by default, from allowed hosts and ports only, never
//! to an address that isn't ordinary public unicast unless the operator allows its range, within a
//! size cap and a time limit, and without ever writing the URL's query string, user or password
//! anywhere.

use std::fmt;
use std::io::Read;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::str::FromStr;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use ureq::config::Config;
use ureq::http::Uri;
use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver};
use ureq::unversioned::transport::NextTimeout;

use super::connect::{self, ConnectFailure, ConnectionCounters, Trace};
use crate::RequestError;

/// The most redirects a fetch follows by default: none. A redirect is then `download_failed`.
pub const DEFAULT_MAX_REDIRECTS: u32 = 0;

/// How long a fetch may take to connect by default, TLS included.
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// How long a whole fetch may take by default: resolving, connecting, redirects and the body.
pub const DEFAULT_FETCH_TIMEOUT: Duration = Duration::from_secs(60);

/// How many times a fetch is tried again by default after a failure at the connect level: once.
pub const DEFAULT_CONNECT_RETRIES: u32 = 1;

/// How long a connection may stay idle and still be reused, by default.
pub const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(60);

/// How many idle connections a [`Fetcher`] keeps for reuse by default, per host and in all, when
/// nothing sizes its pool: a [`Server`](super::Server) sizes it from its bulk job count instead.
pub const DEFAULT_IDLE_CONNECTIONS: usize = 16;

/// The pause before a fetch is tried again after a failure at the connect level.
const CONNECT_RETRY_PAUSE: Duration = Duration::from_millis(200);

/// The `User-Agent` a fetch sends unless the policy gives another: `legit-hasher/` and the
/// version.
pub const DEFAULT_USER_AGENT: &str = concat!("legit-hasher/", env!("CARGO_PKG_VERSION"));

/// Where a fetch may go and how much it may read.
///
/// With no allowed host, which is the default, every URL is refused: a worker fetches nothing
/// until its operator lists the hosts it may fetch from. An allowed host is allowed on one port:
/// the one its entry names, or without one the URL scheme's default port. Whatever the
/// allowlist says, the worker connects only to ordinary public unicast addresses, unless an
/// allowed range ([`FetchPolicy::allow_range`]) holds the address: see
/// [`FetchPolicy::refused_address`].
///
/// ```
/// use legit_hasher::serve::FetchPolicy;
///
/// let policy = FetchPolicy::new()
///     .allow_host("images.example.com")?
///     .allow_host("*.storage.example.com")?
///     .allow_host("cdn.example.com:8443")?;
/// assert!(policy.check_url("https://images.example.com/a.jpg").is_ok());
/// assert!(policy.check_url("https://eu-1.storage.example.com/a.jpg").is_ok());
/// assert!(policy.check_url("https://storage.example.com/a.jpg").is_err());
/// assert!(policy.check_url("https://images.example.com:8443/a.jpg").is_err());
/// assert!(policy.check_url("https://cdn.example.com:8443/a.jpg").is_ok());
/// assert!(policy.check_url("https://cdn.example.com/a.jpg").is_err());
/// # Ok::<(), String>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchPolicy {
    hosts: Vec<HostEntry>,
    ranges: Vec<IpRange>,
    user_agent: String,
    /// Allow plain `http` URLs, for object storage on a private network. Off by default: `https`
    /// only. A URL with a user or password is refused over `http` even so.
    pub allow_http: bool,
    /// The most bytes the returned body may hold; a longer one is `too_large`, refused from its
    /// `Content-Length` or as soon as the bytes read pass it. At most, and by default, the
    /// decoder's input limit. A redirect's own body is never read: its connection is closed.
    pub max_bytes: u64,
    /// The time allowed to connect, TLS included.
    pub connect_timeout: Duration,
    /// The time allowed for the whole fetch: resolving, connecting, every redirect and the body.
    pub timeout: Duration,
    /// The most redirects followed; 0, the default, follows none.
    pub max_redirects: u32,
    /// How many times a request is tried again after a failure at the connect level, 1 by
    /// default; 0 never tries again. Only these are tried again: no address of the host connected
    /// (no route, refused, timed out), an I/O error of any kind came before the request was
    /// written to a connection, or the connection was reset or closed before any byte of the
    /// response arrived. Never a request that got any byte of a response, an HTTP status
    /// among them, and never past [`FetchPolicy::timeout`]. The request is tried again after a
    /// short pause, on a new resolution of the host, checked again.
    pub connect_retries: u32,
    /// How long a connection may stay idle and still be reused, 60 s by default. A worker that
    /// has fetched nothing for this long closes its idle connections.
    pub idle_timeout: Duration,
    /// How many idle connections are kept for reuse, per host and in all. `None`, the default,
    /// is [`DEFAULT_IDLE_CONNECTIONS`] for a [`Fetcher`] on its own, and the bulk job count in a
    /// [`Server`](super::Server), so each job fetching from one host keeps a connection of its
    /// own. An idle connection past the limit is closed, the oldest first.
    pub max_idle_connections: Option<usize>,
}

impl FetchPolicy {
    /// No allowed host, `https` only, the decoder's input limit, the default time limits, no
    /// redirects, one retry at the connect level, the default idle timeout and pool, and the
    /// default `User-Agent`.
    ///
    /// ```
    /// let policy = legit_hasher::serve::FetchPolicy::new();
    /// assert!(!policy.allows_any_host());
    /// assert!(!policy.allow_http);
    /// assert_eq!(policy.max_redirects, 0);
    /// assert_eq!(policy.connect_retries, 1);
    /// assert_eq!(policy.max_idle_connections, None);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            hosts: Vec::new(),
            ranges: Vec::new(),
            user_agent: DEFAULT_USER_AGENT.to_owned(),
            allow_http: false,
            max_bytes: legit_hashes::DECODE_MAX_INPUT as u64,
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            timeout: DEFAULT_FETCH_TIMEOUT,
            max_redirects: DEFAULT_MAX_REDIRECTS,
            connect_retries: DEFAULT_CONNECT_RETRIES,
            idle_timeout: DEFAULT_IDLE_TIMEOUT,
            max_idle_connections: None,
        }
    }

    /// Allow a host on one port. The host is a name such as `images.example.com`, every name
    /// under one such as `*.example.com` (which doesn't match `example.com` itself), an IPv4
    /// address in dotted decimal, or an IPv6 address, in brackets when a port follows. The port,
    /// after a colon, is 1 to 65535; without one, only the default port of the URL's scheme is
    /// allowed (443 for `https`, 80 for `http`). Names are compared without case and without one
    /// final dot; addresses are compared as addresses, so two spellings of one IPv6 address match.
    ///
    /// # Errors
    ///
    /// A message when `pattern` isn't a host and an optional port: empty; holding a scheme, a
    /// path, a user or a space; a name with an empty label, a character other than letters,
    /// digits, `-` and `_`, or a last label that is a number (an address must be written in dotted
    /// decimal); something in brackets that isn't an IPv6 address; an IPv6 address with a zone
    /// such as `%eth0`; or a port that isn't 1 to 65535.
    ///
    /// ```
    /// use legit_hasher::serve::FetchPolicy;
    ///
    /// assert!(FetchPolicy::new().allow_host("images.example.com:8443").is_ok());
    /// assert!(FetchPolicy::new().allow_host("[2001:db8::1]:8443").is_ok());
    /// assert!(FetchPolicy::new().allow_host("https://images.example.com").is_err());
    /// assert!(FetchPolicy::new().allow_host("images.example.com:").is_err());
    /// assert!(FetchPolicy::new().allow_host("images..example.com").is_err());
    /// assert!(FetchPolicy::new().allow_host("[fe80::1%eth0]").is_err());
    /// ```
    pub fn allow_host(mut self, pattern: &str) -> Result<Self, String> {
        self.hosts.push(pattern.parse()?);
        Ok(self)
    }

    /// Allow the hosts listed in a file's text, one a line, each as [`FetchPolicy::allow_host`]
    /// takes it. Blank lines and lines starting with `#` are skipped.
    ///
    /// # Errors
    ///
    /// A message naming the first line that isn't a host.
    ///
    /// ```
    /// use legit_hasher::serve::FetchPolicy;
    ///
    /// let policy = FetchPolicy::new().allow_hosts_from("# storage\nimages.example.com\n\n*.cdn.example.com\n")?;
    /// assert!(policy.check_url("https://a.cdn.example.com/x.png").is_ok());
    /// # Ok::<(), String>(())
    /// ```
    pub fn allow_hosts_from(mut self, text: &str) -> Result<Self, String> {
        for (index, line) in text.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let pattern = line
                .parse()
                .map_err(|message| format!("line {}: {message}", index + 1))?;
            self.hosts.push(pattern);
        }
        Ok(self)
    }

    /// Allow addresses in a range the worker otherwise never connects to, such as `10.0.0.0/8`
    /// for object storage on a private network or `127.0.0.0/8` on the same machine. Ranges are
    /// written as CIDR, or as one address.
    ///
    /// # Errors
    ///
    /// A message when `range` isn't an address or a CIDR range.
    ///
    /// ```
    /// use std::net::Ipv4Addr;
    /// use legit_hasher::serve::FetchPolicy;
    ///
    /// let policy = FetchPolicy::new().allow_range("10.0.0.0/8")?;
    /// assert_eq!(policy.refused_address(Ipv4Addr::new(10, 1, 2, 3).into()), None);
    /// assert!(policy.refused_address("169.254.169.254".parse().unwrap()).is_some());
    /// # Ok::<(), String>(())
    /// ```
    pub fn allow_range(mut self, range: &str) -> Result<Self, String> {
        self.ranges.push(range.parse()?);
        Ok(self)
    }

    /// Send `user_agent` as the `User-Agent` of every fetch, in place of [`DEFAULT_USER_AGENT`].
    /// Some storage refuses or slows clients that don't name themselves.
    ///
    /// # Errors
    ///
    /// A message when `user_agent` is empty or holds anything but printable ASCII: a control
    /// character, a tab or a line break among them.
    ///
    /// ```
    /// use legit_hasher::serve::FetchPolicy;
    ///
    /// let policy = FetchPolicy::new().with_user_agent("photo-indexer/2 (ops@example.com)")?;
    /// assert_eq!(policy.user_agent(), "photo-indexer/2 (ops@example.com)");
    /// assert!(FetchPolicy::new().with_user_agent("a\r\nX-Injected: 1").is_err());
    /// # Ok::<(), String>(())
    /// ```
    pub fn with_user_agent(mut self, user_agent: &str) -> Result<Self, String> {
        if user_agent.is_empty() || !user_agent.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
            return Err("a user agent is one or more printable ASCII characters, with no control character".to_owned());
        }
        user_agent.clone_into(&mut self.user_agent);
        Ok(self)
    }

    /// The `User-Agent` every fetch sends.
    #[must_use]
    pub fn user_agent(&self) -> &str {
        &self.user_agent
    }

    /// Whether any host is allowed: with none, every URL is refused.
    #[must_use]
    pub fn allows_any_host(&self) -> bool {
        !self.hosts.is_empty()
    }

    /// The checks made on a URL before any connection, and again on every redirect: the scheme,
    /// a user or password over plain `http`, the host and the port. The addresses its host
    /// resolves to are checked when it's fetched, not here.
    ///
    /// # Errors
    ///
    /// Why the URL is refused, worded without its query string, user or password.
    pub fn check_url(&self, url: &str) -> Result<(), String> {
        let uri: Uri = url.parse().map_err(|_| "the value isn't an absolute URL".to_owned())?;
        self.check_target(&uri).map_err(|Refusal(message)| message)
    }

    /// Why the worker won't connect to `address`, or `None` when it may.
    ///
    /// Every address that isn't ordinary public unicast is refused unless an allowed range holds
    /// it: loopback, link-local, unspecified and `0.0.0.0/8`, multicast, broadcast, private
    /// (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`), shared (`100.64.0.0/10`), `192.0.0.0/24`,
    /// documentation, benchmarking, 6to4 relay anycast (`192.88.99.0/24`) and reserved IPv4; unique
    /// local, site-local, documentation and discard-only IPv6; and every IPv6 form that carries an
    /// IPv4 address or leads through a translator or a tunnel: IPv4-compatible `::/96`, NAT64
    /// `64:ff9b::/96` and `64:ff9b:1::/48`, 6to4 `2002::/16` and Teredo `2001::/32`, and anything
    /// outside `2000::/3`. An IPv4 address written as IPv6 (`::ffff:a.b.c.d`) is checked as the
    /// IPv4 address. The blocks come from the IANA special-purpose registries, except those the
    /// registries mark globally reachable that are routed like any public address, which are left
    /// reachable: `192.31.196.0/24`, `192.175.48.0/24` and `2620:4f:8000::/48` (AS112) and
    /// `192.52.193.0/24` (AMT).
    ///
    /// The check is on the address, not on how the network routes it: a VPN, a translator prefix
    /// of the network's own or a tunnel can carry an allowed address somewhere private, and is the
    /// operator's to fence at the network's edge too.
    ///
    /// ```
    /// use std::net::Ipv4Addr;
    /// use legit_hasher::serve::FetchPolicy;
    ///
    /// let policy = FetchPolicy::new();
    /// assert_eq!(policy.refused_address("93.184.215.14".parse().unwrap()), None);
    /// assert!(policy.refused_address(Ipv4Addr::new(10, 0, 0, 1).into()).is_some_and(|why| why.contains("private")));
    /// assert!(policy.refused_address("64:ff9b::a00:1".parse().unwrap()).is_some_and(|why| why.contains("NAT64")));
    /// ```
    #[must_use]
    pub fn refused_address(&self, address: IpAddr) -> Option<&'static str> {
        let address = address.to_canonical();
        let why = special(address)?;
        (!self.ranges.iter().any(|range| range.contains(address))).then_some(why)
    }

    /// The scheme, credential, host and port check made before any connection, and again for
    /// every redirect and by the resolver.
    fn check_target(&self, uri: &Uri) -> Result<(), Refusal> {
        let default_port = match uri.scheme_str() {
            Some("https") => 443,
            Some("http") if self.allow_http => 80,
            Some("http") => {
                return Err(Refusal(
                    "plain `http` isn't allowed; this worker fetches `https` URLs only".to_owned(),
                ));
            }
            _ => return Err(Refusal("only `https` URLs are fetched".to_owned())),
        };
        if !self.allows_any_host() {
            return Err(Refusal(
                "this worker fetches no URLs: no host is allowed (`--allow-host`)".to_owned(),
            ));
        }
        let authority = uri
            .authority()
            .ok_or_else(|| Refusal("the URL has no host".to_owned()))?;
        let (credentials, host_and_port) = match authority.as_str().rsplit_once('@') {
            Some((_, rest)) => (true, rest),
            None => (false, authority.as_str()),
        };
        if credentials && default_port == 80 {
            return Err(Refusal(
                "a URL with a user or password isn't fetched over plain `http`, which would send them in the clear"
                    .to_owned(),
            ));
        }
        let (host, port) = split_port(host_and_port).map_err(|message| Refusal(format!("the URL's {message}")))?;
        let host = Host::parse(host).map_err(|message| Refusal(format!("the URL's host {message}")))?;
        let port = match port {
            Some(port) => parse_port(port).map_err(|message| Refusal(format!("the URL's {message}")))?,
            None => default_port,
        };
        let mut host_listed = false;
        for entry in &self.hosts {
            if entry.pattern.matches(&host) {
                host_listed = true;
                if entry.port.unwrap_or(default_port) == port {
                    return Ok(());
                }
            }
        }
        if host_listed {
            return Err(Refusal(format!(
                "port `{port}` of `{host}` isn't allowed: an entry without a port allows only port `{default_port}`; list `{host}:{port}` to allow another"
            )));
        }
        Err(Refusal(format!("the host `{host}` isn't on this worker's allowlist")))
    }

    /// Refuse when any of `addresses`, those `host` resolved to, is one the policy refuses: one
    /// refused address among them refuses the fetch.
    fn check_addresses(&self, host: &str, addresses: impl IntoIterator<Item = SocketAddr>) -> Result<(), Refusal> {
        for address in addresses {
            if let Some(why) = self.refused_address(address.ip()) {
                return Err(Refusal(format!(
                    "the host `{host}` resolves to `{}`, a {why} address this worker doesn't connect to (`--allow-range` allows a range)",
                    address.ip()
                )));
            }
        }
        Ok(())
    }
}

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

/// The blocks of the IANA IPv4 and IPv6 special-purpose address registries the worker refuses,
/// and the rest of the address space that isn't global unicast, each with the reason a refusal
/// gives. The first block holding an address names it.
///
/// Left reachable, because the registries mark them globally reachable and they're routed like
/// any public address, with nothing private behind them: `192.31.196.0/24` and `192.175.48.0/24`
/// (AS112 DNS), `192.52.193.0/24` (AMT) and `2620:4f:8000::/48` (AS112 DNS). The globally
/// reachable entries inside a refused block are refused with it, since none serves images and one
/// rule for the block is easier to check: `192.0.0.9/32` and `192.0.0.10/32` inside
/// `192.0.0.0/24`; the anycast addresses, AMT, AS112, ORCHIDv2 and DRIP entries inside
/// `2001::/23`; and `5f00::/16` (segment routing), which is outside `2000::/3`. An operator who
/// needs one opens it with `--allow-range`.
const SPECIAL_V4: [(Ipv4Addr, u8, &str); 16] = [
    (
        Ipv4Addr::new(0, 0, 0, 0),
        8,
        "unspecified (\"this network\", 0.0.0.0/8)",
    ),
    (Ipv4Addr::new(10, 0, 0, 0), 8, "private (10.0.0.0/8)"),
    (Ipv4Addr::new(100, 64, 0, 0), 10, "shared address space (100.64.0.0/10)"),
    (Ipv4Addr::new(127, 0, 0, 0), 8, "loopback (127.0.0.0/8)"),
    (Ipv4Addr::new(169, 254, 0, 0), 16, "link-local (169.254.0.0/16)"),
    (Ipv4Addr::new(172, 16, 0, 0), 12, "private (172.16.0.0/12)"),
    (
        Ipv4Addr::new(192, 0, 0, 0),
        24,
        "IETF protocol assignments (192.0.0.0/24)",
    ),
    (Ipv4Addr::new(192, 0, 2, 0), 24, "documentation (192.0.2.0/24)"),
    (Ipv4Addr::new(192, 88, 99, 0), 24, "6to4 relay anycast (192.88.99.0/24)"),
    (Ipv4Addr::new(192, 168, 0, 0), 16, "private (192.168.0.0/16)"),
    (Ipv4Addr::new(198, 18, 0, 0), 15, "benchmarking (198.18.0.0/15)"),
    (Ipv4Addr::new(198, 51, 100, 0), 24, "documentation (198.51.100.0/24)"),
    (Ipv4Addr::new(203, 0, 113, 0), 24, "documentation (203.0.113.0/24)"),
    (Ipv4Addr::new(224, 0, 0, 0), 4, "multicast (224.0.0.0/4)"),
    (Ipv4Addr::new(255, 255, 255, 255), 32, "broadcast (255.255.255.255)"),
    (Ipv4Addr::new(240, 0, 0, 0), 4, "reserved (240.0.0.0/4)"),
];

/// The IPv6 blocks, as [`SPECIAL_V4`]. After them, anything outside `2000::/3` is refused.
const SPECIAL_V6: [(Ipv6Addr, u8, &str); 16] = [
    (Ipv6Addr::UNSPECIFIED, 128, "unspecified (::)"),
    (Ipv6Addr::LOCALHOST, 128, "loopback (::1)"),
    (Ipv6Addr::UNSPECIFIED, 96, "IPv4-compatible (::/96)"),
    (
        Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 0, 0),
        96,
        "NAT64 (64:ff9b::/96)",
    ),
    (
        Ipv6Addr::new(0x64, 0xff9b, 1, 0, 0, 0, 0, 0),
        48,
        "local-use NAT64 (64:ff9b:1::/48)",
    ),
    (Ipv6Addr::new(0x100, 0, 0, 0, 0, 0, 0, 0), 64, "discard-only (100::/64)"),
    (
        Ipv6Addr::new(0x2001, 0, 0, 0, 0, 0, 0, 0),
        32,
        "Teredo tunnel (2001::/32)",
    ),
    (
        Ipv6Addr::new(0x2001, 0, 0, 0, 0, 0, 0, 0),
        23,
        "IETF protocol assignments (2001::/23)",
    ),
    (
        Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0),
        32,
        "documentation (2001:db8::/32)",
    ),
    (
        Ipv6Addr::new(0x2002, 0, 0, 0, 0, 0, 0, 0),
        16,
        "6to4 tunnel (2002::/16)",
    ),
    (
        Ipv6Addr::new(0x3fff, 0, 0, 0, 0, 0, 0, 0),
        20,
        "documentation (3fff::/20)",
    ),
    (
        Ipv6Addr::new(0x5f00, 0, 0, 0, 0, 0, 0, 0),
        16,
        "segment routing (5f00::/16)",
    ),
    (Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 0), 7, "unique local (fc00::/7)"),
    (Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0), 10, "link-local (fe80::/10)"),
    (Ipv6Addr::new(0xfec0, 0, 0, 0, 0, 0, 0, 0), 10, "site-local (fec0::/10)"),
    (Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0), 8, "multicast (ff00::/8)"),
];

/// The kind of address `address` is, when it's one the worker refuses by default. `address` is
/// canonical: an IPv4-mapped address has become its IPv4 address.
fn special(address: IpAddr) -> Option<&'static str> {
    match address {
        IpAddr::V4(v4) => SPECIAL_V4
            .iter()
            .find(|(network, prefix, _)| prefix_matches(network.to_bits().into(), v4.to_bits().into(), *prefix, 32))
            .map(|(_, _, why)| *why),
        IpAddr::V6(v6) => SPECIAL_V6
            .iter()
            .find(|(network, prefix, _)| prefix_matches(network.to_bits(), v6.to_bits(), *prefix, 128))
            .map(|(_, _, why)| *why)
            .or_else(|| {
                // Global unicast is `2000::/3`; the rest of the space is reserved or special...
                (v6.segments()[0] & 0xe000 != 0x2000).then_some("not global unicast (outside 2000::/3)")
            }),
    }
}

/// A host as a URL or an allowlist entry gives it, read once: a lower-case name without its final
/// dot, or an address.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Host {
    Name(String),
    Address(IpAddr),
}

impl Host {
    /// Read a host: an IPv6 address in brackets (or bare, in an allowlist entry), an IPv4 address
    /// in dotted decimal, or a name.
    fn parse(text: &str) -> Result<Self, String> {
        let bracketed = text.strip_prefix('[').map(|inner| inner.strip_suffix(']'));
        let address = match bracketed {
            Some(None) => return Err(format!("`{text}` opens a bracket it doesn't close")),
            Some(Some(inner)) => Some(inner),
            None if text.contains(':') => Some(text),
            None => None,
        };
        if let Some(address) = address {
            if address.contains('%') {
                return Err(format!(
                    "`{text}` is an IPv6 address with a zone, which this worker doesn't fetch from"
                ));
            }
            return address
                .parse::<Ipv6Addr>()
                .map(|address| Self::Address(IpAddr::V6(address)))
                .map_err(|_| format!("`{text}` isn't an IPv6 address"));
        }
        if let Ok(address) = text.parse::<Ipv4Addr>() {
            return Ok(Self::Address(IpAddr::V4(address)));
        }
        valid_name(text).map(Self::Name)
    }
}

impl fmt::Display for Host {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Name(name) => f.write_str(name),
            Self::Address(IpAddr::V6(address)) => write!(f, "[{address}]"),
            Self::Address(address) => write!(f, "{address}"),
        }
    }
}

/// A name, lower-cased and without one final dot, when every label is 1 to 63 of letters, digits,
/// `-` and `_` and the last isn't a number. A last label of digits, or of `0x` and hex digits, is
/// how a resolver reads the short, decimal, octal and hex spellings of an IPv4 address (`127.1`,
/// `2130706433`, `0x7f.1`), which an allowlist and a URL must write in dotted decimal.
fn valid_name(text: &str) -> Result<String, String> {
    let name = text.strip_suffix('.').unwrap_or(text).to_ascii_lowercase();
    let labels_valid = !name.is_empty()
        && name.len() <= 253
        && name.split('.').all(|label| {
            (1..=63).contains(&label.len())
                && label
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
        });
    if !labels_valid {
        return Err(format!(
            "`{text}` isn't a host name: labels of letters, digits, `-` and `_`, none empty"
        ));
    }
    let last = name.rsplit('.').next().unwrap_or_default();
    let numeric = last.bytes().all(|byte| byte.is_ascii_digit())
        || last
            .strip_prefix("0x")
            .is_some_and(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit()));
    if numeric {
        return Err(format!(
            "`{text}` reads as a number, not a name: write an IPv4 address as four decimal parts, such as `192.0.2.1`"
        ));
    }
    Ok(name)
}

/// Split `host:port` into the host, brackets kept, and the port's text when a colon is there. A
/// bare IPv6 address, with more than one colon and no brackets, has no port.
fn split_port(text: &str) -> Result<(&str, Option<&str>), String> {
    if text.starts_with('[') {
        let end = text
            .find(']')
            .ok_or_else(|| format!("host `{text}` opens a bracket it doesn't close"))?;
        let (host, rest) = text.split_at(end + 1);
        return match rest.strip_prefix(':') {
            Some(port) => Ok((host, Some(port))),
            None if rest.is_empty() => Ok((host, None)),
            None => Err(format!("host `{text}` has `{rest}` after its address")),
        };
    }
    if text.matches(':').count() > 1 {
        return Ok((text, None));
    }
    Ok(match text.split_once(':') {
        Some((host, port)) => (host, Some(port)),
        None => (text, None),
    })
}

/// A port: 1 to 65535, written in decimal digits. Never absent when a colon was written.
fn parse_port(text: &str) -> Result<u16, String> {
    text.parse::<u16>()
        .ok()
        .filter(|port| *port > 0 && text.bytes().all(|byte| byte.is_ascii_digit()))
        .ok_or_else(|| format!("port `{text}` isn't a port from 1 to 65535"))
}

/// One allowlist entry: a host pattern and the port it's allowed on, `None` for the scheme's
/// default.
#[derive(Debug, Clone, PartialEq, Eq)]
struct HostEntry {
    pattern: HostPattern,
    port: Option<u16>,
}

/// The host part of an allowlist entry.
#[derive(Debug, Clone, PartialEq, Eq)]
enum HostPattern {
    /// This host only.
    Exact(Host),
    /// Every name ending in this suffix, which starts with a dot.
    Under(String),
}

impl HostPattern {
    fn matches(&self, host: &Host) -> bool {
        match (self, host) {
            (Self::Exact(Host::Address(entry)), Host::Address(address)) => {
                entry.to_canonical() == address.to_canonical()
            }
            (Self::Exact(entry), host) => entry == host,
            (Self::Under(suffix), Host::Name(name)) => name.len() > suffix.len() && name.ends_with(suffix.as_str()),
            (Self::Under(_), Host::Address(_)) => false,
        }
    }
}

impl FromStr for HostEntry {
    type Err = String;

    fn from_str(text: &str) -> Result<Self, String> {
        let entry = text.trim();
        let invalid = |why: String| {
            format!(
                "`{entry}` isn't a host: {why}. Give a name such as `images.example.com` or `*.example.com`, or an address, and optionally `:port`, without a scheme, user or path"
            )
        };
        if entry.is_empty() {
            return Err(invalid("it's empty".to_owned()));
        }
        if let Some(found) = entry
            .chars()
            .find(|c| c.is_whitespace() || matches!(c, '/' | '@' | '?' | '#'))
        {
            return Err(invalid(format!("it holds `{found}`")));
        }
        let (host, port) = split_port(entry).map_err(invalid)?;
        let port = port.map(parse_port).transpose().map_err(invalid)?;
        let pattern = match host.strip_prefix("*.") {
            Some(under) => HostPattern::Under(format!(".{}", valid_name(under).map_err(invalid)?)),
            None => HostPattern::Exact(Host::parse(host).map_err(invalid)?),
        };
        Ok(Self { pattern, port })
    }
}

/// A range of addresses: a network and the length of its prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct IpRange {
    network: IpAddr,
    prefix: u8,
}

impl IpRange {
    fn contains(self, address: IpAddr) -> bool {
        match (self.network, address) {
            (IpAddr::V4(network), IpAddr::V4(address)) => prefix_matches(
                u128::from(network.to_bits()),
                u128::from(address.to_bits()),
                self.prefix,
                32,
            ),
            (IpAddr::V6(network), IpAddr::V6(address)) => {
                prefix_matches(network.to_bits(), address.to_bits(), self.prefix, 128)
            }
            _ => false,
        }
    }
}

/// Whether the first `prefix` of `width` bits of `a` and `b` agree.
fn prefix_matches(a: u128, b: u128, prefix: u8, width: u8) -> bool {
    let shift = u32::from(width - prefix);
    a.checked_shr(shift).unwrap_or(0) == b.checked_shr(shift).unwrap_or(0)
}

impl FromStr for IpRange {
    type Err = String;

    fn from_str(range: &str) -> Result<Self, String> {
        let invalid = || format!("`{range}` isn't an address or a CIDR range such as `10.0.0.0/8`");
        let (address, prefix) = match range.trim().split_once('/') {
            Some((address, prefix)) => (address, Some(prefix)),
            None => (range.trim(), None),
        };
        let network = address.parse::<IpAddr>().map_err(|_| invalid())?.to_canonical();
        let width = if network.is_ipv4() { 32 } else { 128 };
        let prefix = match prefix {
            Some(prefix) => prefix
                .parse::<u8>()
                .ok()
                .filter(|prefix| *prefix <= width)
                .ok_or_else(invalid)?,
            None => width,
        };
        Ok(Self { network, prefix })
    }
}

/// Why a fetch failed, with the code its result carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchError {
    /// The code: `download_failed`, `url_expired`, `host_not_allowed`, `too_large`, or
    /// `invalid_request` for a value that isn't a URL.
    pub code: RequestError,
    /// What went wrong, for a person. It names the URL without its query string, user or
    /// password.
    pub message: String,
}

impl FetchError {
    fn new(code: RequestError, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

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

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

/// A refusal by the policy, carried through the HTTP client as its error.
#[derive(Debug)]
struct Refusal(String);

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

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

/// The resolver every connection goes through: it checks the URL against the policy, resolves
/// the name, and refuses when any address of those the resolver returns is one the policy
/// refuses. The client connects only to the addresses it returns, so a name can't resolve to one
/// address when checked and another when connected. `ureq`'s resolver keeps at most 16 addresses
/// of a longer answer: those are the addresses checked, and the only ones connected to.
///
/// Every request goes through it, one on a pooled connection included: `ureq` resolves the host
/// before it looks for an idle connection, so a request whose host now resolves to a refused
/// address is refused even while a connection opened earlier to an allowed one is idle.
#[derive(Debug, Clone)]
struct CheckedResolver {
    policy: Arc<FetchPolicy>,
    inner: Arc<dyn Resolver>,
}

impl Resolver for CheckedResolver {
    fn resolve(&self, uri: &Uri, config: &Config, timeout: NextTimeout) -> Result<ResolvedSocketAddrs, ureq::Error> {
        let refuse = |refusal: Refusal| ureq::Error::Other(Box::new(refusal));
        self.policy.check_target(uri).map_err(refuse)?;
        let addresses = self.inner.resolve(uri, config, timeout)?;
        let host = uri.host().map(|host| host.to_ascii_lowercase()).unwrap_or_default();
        self.policy
            .check_addresses(&host, addresses.iter().copied())
            .map_err(refuse)?;
        Ok(addresses)
    }
}

/// A URL as it may be written in a message or a log line: its scheme, host, port and path, with
/// no user, password, query string or fragment, any of which may be a credential.
///
/// ```
/// use legit_hasher::serve::redact;
///
/// assert_eq!(
///     redact("https://user:secret@images.example.com:8443/a/b.jpg?X-Amz-Signature=abc#top"),
///     "https://images.example.com:8443/a/b.jpg"
/// );
/// assert_eq!(redact("not a url ?token=abc"), "(not a URL)");
/// ```
#[must_use]
pub fn redact(url: &str) -> String {
    url.parse::<Uri>()
        .map_or_else(|_| "(not a URL)".to_owned(), |uri| redacted(&uri))
}

/// The host of a URL, lower-cased, for a log line: no scheme, port, path, query, user or password.
/// `(not a URL)` when it isn't one.
#[must_use]
pub(crate) fn url_host(url: &str) -> String {
    url.parse::<Uri>()
        .ok()
        .and_then(|uri| uri.host().map(str::to_ascii_lowercase))
        .unwrap_or_else(|| "(not a URL)".to_owned())
}

fn redacted(uri: &Uri) -> String {
    let scheme = uri.scheme_str().unwrap_or("");
    let host = uri.host().unwrap_or("");
    match uri.port_u16() {
        Some(port) => format!("{scheme}://{host}:{port}{}", uri.path()),
        None => format!("{scheme}://{host}{}", uri.path()),
    }
}

/// The URL a redirect's `Location` leads to from `base`: absolute, or relative to `base` as
/// RFC 3986 resolves it, without a fragment. `None` when it isn't a URL with a host.
fn redirect_target(base: &Uri, location: &str) -> Option<Uri> {
    let location = location.split('#').next().unwrap_or_default();
    let scheme = base.scheme_str()?;
    let authority = base.authority()?.as_str();
    let has_scheme = location.split_once(':').is_some_and(|(scheme, _)| {
        scheme.starts_with(|c: char| c.is_ascii_alphabetic())
            && scheme
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    });
    let text = if has_scheme {
        location.to_owned()
    } else if let Some(rest) = location.strip_prefix("//") {
        format!("{scheme}://{rest}")
    } else if location.starts_with('/') {
        format!("{scheme}://{authority}{}", without_dot_segments(location))
    } else if location.starts_with('?') {
        format!("{scheme}://{authority}{}{location}", base.path())
    } else if location.is_empty() {
        return None;
    } else {
        let path = base.path();
        let directory = &path[..=path.rfind('/')?];
        format!(
            "{scheme}://{authority}{}",
            without_dot_segments(&format!("{directory}{location}"))
        )
    };
    let uri: Uri = text.parse().ok()?;
    (uri.scheme().is_some() && uri.authority().is_some()).then_some(uri)
}

/// An absolute path and query with its `.` and `..` segments removed, as RFC 3986 section 5.2.4
/// removes them.
fn without_dot_segments(target: &str) -> String {
    let (path, query) = match target.split_once('?') {
        Some((path, query)) => (path, Some(query)),
        None => (target, None),
    };
    let mut kept: Vec<&str> = Vec::new();
    let segments: Vec<&str> = path.split('/').skip(1).collect();
    for segment in &segments {
        match *segment {
            "." => {}
            ".." => {
                kept.pop();
            }
            segment => kept.push(segment),
        }
    }
    let mut resolved = format!("/{}", kept.join("/"));
    if matches!(segments.last(), Some(&("." | ".."))) && !resolved.ends_with('/') {
        resolved.push('/');
    }
    if let Some(query) = query {
        resolved.push('?');
        resolved.push_str(query);
    }
    resolved
}

/// The bytes a fetch read, and how long it took.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fetched {
    /// The body.
    pub bytes: Vec<u8>,
    /// From the start of the fetch to its last byte.
    pub elapsed: Duration,
}

/// A blocking HTTP client held to a [`FetchPolicy`]. Cheap to share between threads: it holds one
/// pool of connections.
///
/// It sends no credential the URL doesn't carry: no proxy (the environment's proxy settings are
/// ignored), and a URL's user and password go only to its own host, over `https`. It follows
/// redirects itself, up to [`FetchPolicy::max_redirects`], checking each one as it checks the
/// first URL, and closes a redirect's connection without reading its body. The HTTP client's own
/// `log` records, which name whole URLs, are never written by `serve`: see
/// [`subscriber`](super::subscriber).
///
/// It reuses connections. A connection whose response was read to its end goes back to the pool,
/// and a later request for the same scheme, host and port, user and password included, takes it
/// rather than open another; up to [`FetchPolicy::max_idle_connections`] wait there, each for up
/// to [`FetchPolicy::idle_timeout`]. Every request passes the same checks first, on a pooled
/// connection too: the URL's scheme, user, host and port, and the addresses its host resolves to
/// now. A pooled connection keeps the address it was opened to, which was checked then: a change
/// of the host's DNS records is seen at the next new connection, not at once. A connection carries
/// nothing from one request to the next but its socket and its TLS session: no header, no cookie,
/// no credential. A redirect's connection is always closed, with a body or none. Any other
/// response whose body isn't read to its end, a refused status or a body over the cap, closes its
/// connection; a refused status with no body, such as a `403` or `500` with `Content-Length: 0`,
/// goes back to the client's pool before the fetcher sees it, and its connection may be reused.
///
/// It opens a connection to the addresses its resolver returned and the policy checked, each in
/// turn until one connects, within [`FetchPolicy::connect_timeout`] as a whole, and tries a
/// request again after a failure at the connect level as [`FetchPolicy::connect_retries`] says.
///
/// Built as this crate's own manifest builds `ureq`, with only its `rustls` feature, the client
/// keeps no cookies and asks for no compression. A program that turns on `ureq`'s `cookies`
/// feature anywhere in its build changes that for this client too: `ureq` then keeps the cookies a
/// server sets and sends them on later fetches of the same `Fetcher`, across tasks, and has no
/// setting to turn that off. With `ureq`'s `gzip` or `brotli` feature a compressed body is
/// decompressed, and the cap holds the decompressed bytes.
pub struct Fetcher {
    policy: Arc<FetchPolicy>,
    config: Config,
    resolver: CheckedResolver,
    counters: Arc<ConnectionCounters>,
    /// The client, with its pool. Replaced by a new one, which closes every idle connection, when
    /// the fetcher has been idle for the idle timeout.
    agent: Mutex<ureq::Agent>,
    activity: Mutex<Activity>,
}

/// Whether a fetcher is in use, for [`Fetcher::close_idle`].
#[derive(Debug)]
struct Activity {
    in_flight: usize,
    last: Instant,
    /// No connection has been opened since the pool was last emptied.
    closed: bool,
}

/// Counts the fetch in flight until it's dropped.
struct InFlight<'a>(&'a Fetcher);

impl Drop for InFlight<'_> {
    fn drop(&mut self) {
        let mut activity = self.0.activity();
        activity.in_flight = activity.in_flight.saturating_sub(1);
        activity.last = Instant::now();
    }
}

/// What the attempts of one request at the connect level found, for the message of a final
/// failure.
#[derive(Debug, Default)]
struct Attempts {
    /// Requests tried, the first included.
    tried: u32,
    /// Connects tried, over every attempt.
    connects: usize,
    /// The most addresses one resolution held.
    addresses: usize,
    /// Why connects failed, each reason once, in the order first seen.
    reasons: Vec<std::io::ErrorKind>,
}

impl Attempts {
    fn record(&mut self, failure: &ConnectFailure) {
        self.connects += failure.failed.len();
        self.addresses = self.addresses.max(failure.addresses);
        for reason in &failure.failed {
            if !self.reasons.contains(reason) {
                self.reasons.push(*reason);
            }
        }
    }
}

impl Fetcher {
    /// A client for `policy`. The body cap is held to the decoder's input limit.
    #[must_use]
    pub fn new(policy: FetchPolicy) -> Self {
        Self::with_resolver(policy, DefaultResolver::default())
    }

    /// A client for `policy` that resolves names with `resolver`, which the tests replace.
    fn with_resolver(mut policy: FetchPolicy, resolver: impl Resolver) -> Self {
        policy.max_bytes = policy.max_bytes.min(legit_hashes::DECODE_MAX_INPUT as u64);
        let idle = policy.max_idle_connections.unwrap_or(DEFAULT_IDLE_CONNECTIONS);
        let policy = Arc::new(policy);
        let config = Config::builder()
            .https_only(!policy.allow_http)
            .proxy(None)
            .http_status_as_error(false)
            .max_redirects(0)
            .max_redirects_will_error(false)
            .timeout_connect(Some(policy.connect_timeout))
            .timeout_global(Some(policy.timeout))
            .max_idle_connections(idle)
            .max_idle_connections_per_host(idle)
            .max_idle_age(policy.idle_timeout)
            .user_agent(policy.user_agent())
            .build();
        let resolver = CheckedResolver {
            policy: Arc::clone(&policy),
            inner: Arc::new(resolver),
        };
        let counters = Arc::new(ConnectionCounters::default());
        let agent = new_agent(&config, &resolver, &counters);
        Self {
            policy,
            config,
            resolver,
            counters,
            agent: Mutex::new(agent),
            activity: Mutex::new(Activity {
                in_flight: 0,
                last: Instant::now(),
                closed: true,
            }),
        }
    }

    /// The policy the client holds to.
    #[must_use]
    pub fn policy(&self) -> &FetchPolicy {
        &self.policy
    }

    /// Close every idle connection when no fetch has run for [`FetchPolicy::idle_timeout`], and
    /// say whether it did. Idle connections past the timeout are never reused, but their sockets
    /// stay open until the next fetch unless this is called: a [`Server`](super::Server) calls it
    /// every second; a program with a fetcher of its own calls it on a timer of its own.
    ///
    /// ```
    /// use legit_hasher::serve::{FetchPolicy, Fetcher};
    ///
    /// let fetcher = Fetcher::new(FetchPolicy::new());
    /// assert!(!fetcher.close_idle(), "nothing was ever opened");
    /// ```
    pub fn close_idle(&self) -> bool {
        let mut activity = self.activity();
        if activity.closed || activity.in_flight > 0 || activity.last.elapsed() < self.policy.idle_timeout {
            return false;
        }
        let fresh = new_agent(&self.config, &self.resolver, &self.counters);
        // The old client drops here, and with it its pool and every idle connection in it...
        drop(std::mem::replace(
            &mut *self.agent.lock().unwrap_or_else(PoisonError::into_inner),
            fresh,
        ));
        activity.closed = true;
        true
    }

    /// Connections opened, requests written to a connection reused, and requests tried again
    /// after a failure at the connect level, since the fetcher was made.
    pub(crate) fn connection_counts(&self) -> (u64, u64, u64) {
        self.counters.load()
    }

    fn activity(&self) -> MutexGuard<'_, Activity> {
        self.activity.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Count a fetch in flight, and take the client it uses.
    fn begin(&self) -> (InFlight<'_>, ureq::Agent) {
        let mut activity = self.activity();
        activity.in_flight += 1;
        activity.closed = false;
        let agent = self.agent.lock().unwrap_or_else(PoisonError::into_inner).clone();
        (InFlight(self), agent)
    }

    /// Fetch `url` with `GET` and return its body.
    ///
    /// # Errors
    ///
    /// A [`FetchError`]: `invalid_request` for a value that isn't an absolute URL;
    /// `host_not_allowed` for a scheme, a user or password over plain `http`, a host, a port or a
    /// resolved address the policy refuses, checked before connecting and again on every
    /// redirect; `too_large` for a body over the cap, from its `Content-Length` or while it's
    /// read, never holding more than the cap; `url_expired` for `401` or `403`; and
    /// `download_failed` for any other failure: no such host, no connection, a timeout, a
    /// redirect past [`FetchPolicy::max_redirects`], another status that isn't `2xx`, or a body
    /// cut short. No message holds the URL's query string, user or password, and none names an
    /// address the host resolved to: a failure to connect counts the addresses and attempts
    /// tried.
    pub fn fetch(&self, url: &str) -> Result<Fetched, FetchError> {
        let started = Instant::now();
        let deadline = started + self.policy.timeout;
        let mut uri: Uri = url
            .parse()
            .ok()
            .filter(|uri: &Uri| uri.scheme().is_some() && uri.host().is_some_and(|host| !host.is_empty()))
            .ok_or_else(|| FetchError::new(RequestError::InvalidRequest, "`image_url` isn't an absolute URL"))?;
        let shown = redacted(&uri);
        let (_in_flight, agent) = self.begin();
        let mut retries_left = self.policy.connect_retries;
        let mut redirects = 0;
        let mut response = loop {
            self.policy
                .check_target(&uri)
                .map_err(|Refusal(message)| FetchError::new(RequestError::HostNotAllowed, message))?;
            let response = self.request(&agent, &uri, deadline, &mut retries_left, &shown)?;
            let status = response.status().as_u16();
            if !matches!(status, 301 | 302 | 303 | 307 | 308) {
                break response;
            }
            if redirects >= self.policy.max_redirects {
                let message = match self.policy.max_redirects {
                    0 => format!(
                        "`{shown}` answered `{status}`, a redirect this worker doesn't follow (`--max-redirects` is 0)"
                    ),
                    most => format!("`{shown}` redirected more than {most} times"),
                };
                return Err(FetchError::new(RequestError::DownloadFailed, message));
            }
            let next = response
                .headers()
                .get(ureq::http::header::LOCATION)
                .and_then(|value| value.to_str().ok())
                .and_then(|location| redirect_target(&uri, location))
                .ok_or_else(|| {
                    FetchError::new(
                        RequestError::DownloadFailed,
                        format!("`{shown}` redirected to a URL that couldn't be followed"),
                    )
                })?;
            // Dropped unread: the redirect's body is never read, and its connection is closed...
            drop(response);
            redirects += 1;
            uri = next;
        };
        let status = response.status().as_u16();
        match status {
            200..=299 => {}
            401 | 403 => {
                return Err(FetchError::new(
                    RequestError::UrlExpired,
                    format!(
                        "`{shown}` answered `{status}`: its signature has expired or isn't valid, or, for a URL with no signature, the object is gone or not public"
                    ),
                ));
            }
            _ => {
                return Err(FetchError::new(
                    RequestError::DownloadFailed,
                    format!("`{shown}` answered `{status}`"),
                ));
            }
        }
        let max = self.policy.max_bytes;
        let length = response
            .headers()
            .get(ureq::http::header::CONTENT_LENGTH)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.trim().parse::<u64>().ok());
        if let Some(length) = length
            && length > max
        {
            return Err(too_large(&shown, max));
        }
        let mut bytes = Vec::with_capacity(usize::try_from(length.unwrap_or(0)).unwrap_or(0));
        // Read to its end, the connection goes back to the pool...
        response
            .body_mut()
            .with_config()
            .limit(max)
            .reader()
            .read_to_end(&mut bytes)
            .map_err(|error| self.failure(&ureq::Error::from(error), &shown, &Attempts::default()))?;
        Ok(Fetched {
            bytes,
            elapsed: started.elapsed(),
        })
    }

    /// One request of a fetch, `uri` already checked, tried again after a failure at the connect
    /// level while `retries_left` allows and the deadline leaves time.
    fn request(
        &self,
        agent: &ureq::Agent,
        uri: &Uri,
        deadline: Instant,
        retries_left: &mut u32,
        shown: &str,
    ) -> Result<ureq::http::Response<ureq::Body>, FetchError> {
        let mut attempts = Attempts::default();
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(self.failure(&ureq::Error::Timeout(ureq::Timeout::Global), shown, &attempts));
            }
            attempts.tried += 1;
            // The resolver checks the URL and its addresses again on every attempt...
            let (result, trace) = connect::traced(|| {
                agent
                    .get(uri.clone())
                    .config()
                    .timeout_global(Some(remaining))
                    .build()
                    .call()
            });
            if trace.sent && !trace.connecting {
                self.counters.reused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
            let error = match result {
                Ok(response) => return Ok(response),
                Err(error) => error,
            };
            if let ureq::Error::Other(inner) = &error
                && let Some(failure) = inner.downcast_ref::<ConnectFailure>()
            {
                attempts.record(failure);
            }
            let time_left = deadline.saturating_duration_since(Instant::now()) > CONNECT_RETRY_PAUSE;
            if *retries_left == 0 || !time_left || !connect_level(&error, trace) {
                return Err(self.failure(&error, shown, &attempts));
            }
            *retries_left -= 1;
            self.counters.retries.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            std::thread::sleep(CONNECT_RETRY_PAUSE);
        }
    }

    /// The fetch error for a failure of the client, worded without the client's own messages,
    /// which may hold the URL, and without the addresses the host resolved to.
    fn failure(&self, error: &ureq::Error, shown: &str, attempts: &Attempts) -> FetchError {
        let failed = |message: String| FetchError::new(RequestError::DownloadFailed, message);
        let after = match attempts.tried {
            0 | 1 => String::new(),
            tried => format!(" (after {tried} attempts)"),
        };
        match error {
            ureq::Error::Other(inner) => {
                if let Some(Refusal(message)) = inner.downcast_ref::<Refusal>() {
                    return FetchError::new(RequestError::HostNotAllowed, message.clone());
                }
                if inner.is::<ConnectFailure>() {
                    return failed(connect_failure(shown, attempts, self.policy.connect_timeout));
                }
                failed(format!("couldn't fetch `{shown}`{after}"))
            }
            ureq::Error::RequireHttpsOnly(_) => FetchError::new(
                RequestError::HostNotAllowed,
                format!("`{shown}` led to plain `http`, which this worker doesn't fetch"),
            ),
            ureq::Error::BodyExceedsLimit(_) => too_large(shown, self.policy.max_bytes),
            ureq::Error::Timeout(_) => failed(format!(
                "fetching `{shown}` took longer than allowed ({} s in all, {} s to connect){after}",
                self.policy.timeout.as_secs_f64(),
                self.policy.connect_timeout.as_secs_f64()
            )),
            ureq::Error::HostNotFound => failed(format!("couldn't resolve the host of `{shown}`{after}")),
            ureq::Error::ConnectionFailed => failed(format!("couldn't connect to `{shown}`{after}")),
            ureq::Error::TooManyRedirects | ureq::Error::RedirectFailed | ureq::Error::BadUri(_) => {
                failed(format!("`{shown}` redirected to a URL that couldn't be followed"))
            }
            // The kind alone can read as `uncategorized error`: the system's error number, when
            // there is one, says which, and names no URL or address as the error's text may.
            ureq::Error::Io(io) => {
                let number = io
                    .raw_os_error()
                    .map_or_else(String::new, |number| format!(" (os error {number})"));
                failed(format!("fetching `{shown}` failed: {}{number}{after}", io.kind()))
            }
            ureq::Error::Tls(_) | ureq::Error::Rustls(_) | ureq::Error::TlsRequired | ureq::Error::Pem(_) => {
                failed(format!("the TLS connection to `{shown}` failed{after}"))
            }
            _ => failed(format!(
                "fetching `{shown}` failed: the server's reply couldn't be read{after}"
            )),
        }
    }
}

/// A new client with an empty pool.
fn new_agent(config: &Config, resolver: &CheckedResolver, counters: &Arc<ConnectionCounters>) -> ureq::Agent {
    ureq::Agent::with_parts(
        config.clone(),
        connect::connector(Arc::clone(counters)),
        resolver.clone(),
    )
}

/// Whether a request that failed with `error` failed at the connect level, and may be tried
/// again: no address connected, the connect timed out, an I/O error of any kind came before the
/// request was written to a connection, so no request left the worker, or the connection was
/// reset or closed before any byte of a response arrived.
fn connect_level(error: &ureq::Error, trace: Trace) -> bool {
    use std::io::ErrorKind;
    match error {
        ureq::Error::Other(inner) => inner.is::<ConnectFailure>(),
        ureq::Error::Timeout(ureq::Timeout::Connect) => !trace.received,
        ureq::Error::Io(_) if !trace.sent => true,
        ureq::Error::Io(io) => {
            !trace.received
                && matches!(
                    io.kind(),
                    ErrorKind::ConnectionReset
                        | ErrorKind::ConnectionAborted
                        | ErrorKind::BrokenPipe
                        | ErrorKind::UnexpectedEof
                        | ErrorKind::ConnectionRefused
                        | ErrorKind::NetworkUnreachable
                        | ErrorKind::HostUnreachable
                )
        }
        _ => false,
    }
}

/// The message of a fetch that never connected: how many connects to how many addresses over how
/// many attempts, and why they failed, naming no address.
fn connect_failure(shown: &str, attempts: &Attempts, connect_timeout: Duration) -> String {
    let plural = |count: usize, one: &str, many: &str| {
        if count == 1 {
            format!("1 {one}")
        } else {
            format!("{count} {many}")
        }
    };
    let reasons: Vec<String> = attempts
        .reasons
        .iter()
        .map(|reason| match reason {
            std::io::ErrorKind::TimedOut => format!("timed out ({} s to connect)", connect_timeout.as_secs_f64()),
            reason => reason.to_string(),
        })
        .collect();
    format!(
        "couldn't connect to `{shown}`: {} to {} over {} failed: {}",
        plural(attempts.connects, "connect", "connects"),
        plural(attempts.addresses, "address", "addresses"),
        plural(attempts.tried as usize, "attempt", "attempts"),
        reasons.join(", ")
    )
}

fn too_large(shown: &str, max: u64) -> FetchError {
    FetchError::new(
        RequestError::TooLarge,
        format!("`{shown}` holds more than `{max}` bytes, the most this worker fetches"),
    )
}

impl fmt::Debug for Fetcher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Fetcher")
            .field("policy", &self.policy)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;
    use std::io::Write;
    use std::net::{TcpListener, TcpStream};
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    fn policy(entries: &[&str]) -> FetchPolicy {
        entries
            .iter()
            .try_fold(FetchPolicy::new(), |policy, entry| policy.allow_host(entry))
            .expect("valid entries")
    }

    fn ip(text: &str) -> IpAddr {
        text.parse().expect("an address")
    }

    /// One row per refused IPv4 block and its neighbours on either side: the address, and a word
    /// of the reason it's refused for, or `None` when it's allowed. Written as octets.
    const CLASSIFIED_V4: &[([u8; 4], Option<&str>)] = &[
        // 0.0.0.0/8
        ([0, 0, 0, 0], Some("unspecified")),
        ([0, 255, 255, 255], Some("unspecified")),
        ([1, 0, 0, 0], None),
        // 10.0.0.0/8
        ([9, 255, 255, 255], None),
        ([10, 0, 0, 0], Some("private")),
        ([10, 255, 255, 255], Some("private")),
        ([11, 0, 0, 0], None),
        // 100.64.0.0/10, a cloud metadata address among them
        ([100, 63, 255, 255], None),
        ([100, 64, 0, 0], Some("shared")),
        ([100, 100, 100, 200], Some("shared")),
        ([100, 127, 255, 255], Some("shared")),
        ([100, 128, 0, 0], None),
        // 127.0.0.0/8
        ([126, 255, 255, 255], None),
        ([127, 0, 0, 1], Some("loopback")),
        ([127, 255, 255, 255], Some("loopback")),
        ([128, 0, 0, 0], None),
        // 169.254.0.0/16, the metadata address of most clouds among them
        ([169, 253, 255, 255], None),
        ([169, 254, 0, 0], Some("link-local")),
        ([169, 254, 169, 254], Some("link-local")),
        ([169, 255, 0, 0], None),
        // 172.16.0.0/12
        ([172, 15, 255, 255], None),
        ([172, 16, 0, 0], Some("private")),
        ([172, 31, 255, 255], Some("private")),
        ([172, 32, 0, 0], None),
        // 192.0.0.0/24 and 192.0.2.0/24
        ([191, 255, 255, 255], None),
        ([192, 0, 0, 0], Some("IETF protocol")),
        ([192, 0, 0, 9], Some("IETF protocol")),
        ([192, 0, 0, 255], Some("IETF protocol")),
        ([192, 0, 1, 0], None),
        ([192, 0, 2, 0], Some("documentation")),
        ([192, 0, 2, 255], Some("documentation")),
        ([192, 0, 3, 0], None),
        // Left reachable: AS112
        ([192, 31, 196, 1], None),
        // 192.88.99.0/24
        ([192, 88, 98, 255], None),
        ([192, 88, 99, 1], Some("6to4")),
        ([192, 88, 100, 0], None),
        // 192.168.0.0/16
        ([192, 167, 255, 255], None),
        ([192, 168, 0, 0], Some("private")),
        ([192, 168, 255, 255], Some("private")),
        ([192, 169, 0, 0], None),
        // 198.18.0.0/15
        ([198, 17, 255, 255], None),
        ([198, 18, 0, 0], Some("benchmarking")),
        ([198, 19, 255, 255], Some("benchmarking")),
        ([198, 20, 0, 0], None),
        // 198.51.100.0/24
        ([198, 51, 99, 255], None),
        ([198, 51, 100, 7], Some("documentation")),
        ([198, 51, 101, 0], None),
        // 203.0.113.0/24
        ([203, 0, 112, 255], None),
        ([203, 0, 113, 7], Some("documentation")),
        ([203, 0, 114, 0], None),
        // 224.0.0.0/4, 240.0.0.0/4 and the broadcast address
        ([223, 255, 255, 255], None),
        ([224, 0, 0, 0], Some("multicast")),
        ([239, 255, 255, 255], Some("multicast")),
        ([240, 0, 0, 0], Some("reserved")),
        ([255, 255, 255, 254], Some("reserved")),
        ([255, 255, 255, 255], Some("broadcast")),
        // Ordinary public addresses
        ([8, 8, 8, 8], None),
        ([93, 184, 215, 14], None),
    ];

    /// The same for IPv6, and IPv4 written as IPv6.
    const CLASSIFIED_V6: &[(&str, Option<&str>)] = &[
        // IPv6: the unspecified and loopback addresses, and IPv4-compatible ::/96
        ("::", Some("unspecified")),
        ("::1", Some("loopback")),
        ("::2", Some("IPv4-compatible")),
        ("::7f00:1", Some("IPv4-compatible")),
        ("::808:808", Some("IPv4-compatible")),
        ("::1:0:0:0", Some("outside 2000::/3")),
        // IPv4-mapped, checked as the IPv4 address
        ("::ffff:127.0.0.1", Some("loopback")),
        ("::ffff:a00:1", Some("private")),
        ("::ffff:169.254.169.254", Some("link-local")),
        ("::ffff:8.8.8.8", None),
        // IPv4-translated ::ffff:0:0:0/96
        ("::ffff:0:808:808", Some("outside 2000::/3")),
        // NAT64
        ("64:ff9a:ffff:ffff:ffff:ffff:ffff:ffff", Some("outside 2000::/3")),
        ("64:ff9b::808:808", Some("NAT64")),
        ("64:ff9b::a9fe:a9fe", Some("NAT64")),
        ("64:ff9b:1::1", Some("local-use NAT64")),
        ("64:ff9b:1:ffff:ffff:ffff:ffff:ffff", Some("local-use NAT64")),
        // Discard-only
        ("100::1", Some("discard-only")),
        ("100:0:0:1::1", Some("outside 2000::/3")),
        // 2001::/23: Teredo 2001::/32 and the rest of the protocol assignments
        ("2000:ffff:ffff:ffff:ffff:ffff:ffff:ffff", None),
        ("2001::1", Some("Teredo")),
        ("2001:0:ffff:ffff:ffff:ffff:ffff:ffff", Some("Teredo")),
        ("2001:1::1", Some("IETF protocol")),
        ("2001:1ff:ffff:ffff:ffff:ffff:ffff:ffff", Some("IETF protocol")),
        ("2001:200::", None),
        // Documentation 2001:db8::/32
        ("2001:db7:ffff:ffff:ffff:ffff:ffff:ffff", None),
        ("2001:db8::1", Some("documentation")),
        ("2001:db8:ffff:ffff:ffff:ffff:ffff:ffff", Some("documentation")),
        ("2001:db9::", None),
        // 6to4 2002::/16
        ("2001:ffff:ffff:ffff:ffff:ffff:ffff:ffff", None),
        ("2002::1", Some("6to4")),
        ("2002:c0a8:101::1", Some("6to4")),
        ("2003::", None),
        // Documentation 3fff::/20
        ("3ffe:ffff::", None),
        ("3fff::1", Some("documentation")),
        ("3fff:fff:ffff:ffff:ffff:ffff:ffff:ffff", Some("documentation")),
        ("3fff:1000::", None),
        // Outside 2000::/3
        ("1fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", Some("outside 2000::/3")),
        ("4000::", Some("outside 2000::/3")),
        ("5f00::1", Some("segment routing")),
        // Unique local fc00::/7, the AWS metadata address `fd00:ec2::254` among them
        ("fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", Some("outside 2000::/3")),
        ("fc00::", Some("unique local")),
        ("fd00:ec2::254", Some("unique local")),
        ("fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", Some("unique local")),
        // Link-local, site-local and multicast
        ("fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff", Some("outside 2000::/3")),
        ("fe80::1", Some("link-local")),
        ("febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff", Some("link-local")),
        ("fec0::1", Some("site-local")),
        ("feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", Some("site-local")),
        ("ff02::1", Some("multicast")),
        // Ordinary public IPv6, and an AS112 address left reachable
        ("2606:4700:4700::1111", None),
        ("2a00:1450:4001::1", None),
        ("2620:4f:8000::1", None),
    ];

    #[test]
    fn every_address_that_isnt_ordinary_public_unicast_is_refused_with_its_reason() {
        let policy = FetchPolicy::new();
        let rows = CLASSIFIED_V4
            .iter()
            .map(|(octets, expected)| (IpAddr::from(*octets), expected))
            .chain(CLASSIFIED_V6.iter().map(|(text, expected)| (ip(text), expected)));
        for (address, expected) in rows {
            let refused = policy.refused_address(address);
            match expected {
                Some(word) => assert!(
                    refused.is_some_and(|why| why.contains(word)),
                    "{address}: expected a refusal naming `{word}`, got {refused:?}"
                ),
                None => assert_eq!(refused, None, "{address}"),
            }
        }
    }

    #[test]
    fn an_allowed_range_opens_only_what_it_holds() {
        let policy = FetchPolicy::new()
            .allow_range("127.0.0.0/8")
            .and_then(|policy| policy.allow_range("fe80::/10"))
            .and_then(|policy| policy.allow_range("10.0.0.0/8"))
            .expect("valid ranges");
        for open in [
            ip("127.0.0.1"),
            ip("::ffff:127.0.0.2"),
            ip("fe80::9"),
            IpAddr::from([10, 20, 30, 40]),
            ip("::ffff:a00:1"),
        ] {
            assert_eq!(policy.refused_address(open), None, "{open}");
        }
        for closed in [
            ip("::1"),
            ip("169.254.1.1"),
            IpAddr::from([172, 16, 0, 1]),
            ip("64:ff9b::a00:1"),
            ip("::a00:1"),
        ] {
            assert!(policy.refused_address(closed).is_some(), "{closed}");
        }
    }

    #[test]
    fn ranges_parse_as_cidr_or_one_address() {
        let range: IpRange = "10.0.0.0/8".parse().expect("valid");
        assert!(range.contains(IpAddr::from([10, 255, 0, 1])));
        assert!(!range.contains(ip("11.0.0.1")));
        let one: IpRange = "192.0.2.7".parse().expect("valid");
        assert!(one.contains(ip("192.0.2.7")));
        assert!(!one.contains(ip("192.0.2.8")));
        let all: IpRange = "0.0.0.0/0".parse().expect("valid");
        assert!(all.contains(ip("8.8.8.8")));
        assert!(!all.contains(ip("::1")));
        for bad in ["192.0.2.0/33", "::/129", "192.0.2/24", "x", "192.0.2.0/"] {
            assert!(bad.parse::<IpRange>().is_err(), "{bad}");
        }
    }

    #[test]
    fn hosts_match_exactly_or_under_a_suffix_on_the_default_port() {
        let policy = policy(&["Images.Example.com.", "*.cdn.example.com", "[::1]"]);
        for allowed in [
            "https://images.example.com/a.jpg",
            "https://IMAGES.EXAMPLE.COM./a.jpg",
            "https://images.example.com:443/a.jpg",
            "https://eu.cdn.example.com/a.jpg",
            "https://a.b.cdn.example.com/a.jpg",
            "https://[::1]/a.jpg",
            "https://[0:0:0:0:0:0:0:1]/a.jpg",
        ] {
            assert_eq!(policy.check_url(allowed), Ok(()), "{allowed}");
        }
        for refused in [
            "https://other.images.example.com/a.jpg",
            "https://cdn.example.com/a.jpg",
            "https://evilcdn.example.com/a.jpg",
            "https://images.example.com../a.jpg",
            "https://images..example.com/a.jpg",
            "https://images.example.com:8443/a.jpg",
            "https://images.example.com:80/a.jpg",
            "https://[::2]/a.jpg",
        ] {
            assert!(policy.check_url(refused).is_err(), "{refused}");
        }
    }

    #[test]
    fn an_entry_allows_one_port_and_a_port_must_be_1_to_65535() {
        let policy = policy(&["images.example.com:8443", "[2001:db8::1]:8443", "192.0.2.1:9000"]);
        for allowed in [
            "https://images.example.com:8443/a.jpg",
            "https://[2001:db8::1]:8443/a.jpg",
            "https://[2001:0db8:0000::0001]:8443/a.jpg",
            "https://192.0.2.1:9000/a.jpg",
        ] {
            assert_eq!(policy.check_url(allowed), Ok(()), "{allowed}");
        }
        for refused in [
            "https://images.example.com/a.jpg",
            "https://images.example.com:443/a.jpg",
            "https://images.example.com:8444/a.jpg",
            "https://[2001:db8::1]/a.jpg",
            "https://192.0.2.1/a.jpg",
        ] {
            let message = policy.check_url(refused).expect_err(refused);
            assert!(message.contains("port"), "{refused}: {message}");
        }
        for bad in [
            "images.example.com:",
            "images.example.com:0",
            "images.example.com:65536",
            "images.example.com:+443",
            "images.example.com:44a",
            "[2001:db8::1]:",
            "[2001:db8::1]x",
        ] {
            assert!(FetchPolicy::new().allow_host(bad).is_err(), "{bad}");
        }
        // An empty or out-of-range port in a URL is refused, never read as the default...
        let policy = self::policy(&["images.example.com"]);
        for bad in [
            "https://images.example.com:/a.jpg",
            "https://images.example.com:0/a.jpg",
        ] {
            assert!(policy.check_url(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn entries_are_read_strictly() {
        for bad in [
            "",
            "*.",
            "*",
            "https://x.example.com",
            "x.example.com/a",
            "a b",
            "u@x",
            "x..example.com",
            ".x.example.com",
            "x.example.com..",
            "[x.example.com]",
            "[192.0.2.1]",
            "[2001:db8::1",
            "[fe80::1%eth0]",
            "fe80::1%eth0",
            "[fe80::1%25eth0]",
            "2130706433",
            "127.1",
            "0x7f.1",
            "0177.0.0.1",
            "x.123",
            "*.123",
            "ex%61mple.com",
            "bücher.example",
        ] {
            assert!(FetchPolicy::new().allow_host(bad).is_err(), "{bad:?}");
        }
        for good in [
            "x.example.com",
            "x.example.com.",
            "*.example.com",
            "_service.example.com",
            "192.0.2.1",
            "2001:db8::1",
            "[2001:db8::1]",
            "localhost",
            "xn--bcher-kva.example",
        ] {
            assert!(FetchPolicy::new().allow_host(good).is_ok(), "{good}");
        }
    }

    #[test]
    fn a_url_with_a_spelling_trick_is_refused_before_any_connection() {
        let policy = policy(&["images.example.com", "192.0.2.1"]);
        for refused in [
            "https://[fe80::1%25eth0]/a.jpg",
            "https://2130706433/a.jpg",
            "https://3221225985/a.jpg",
            "https://0xc0.0.2.1/a.jpg",
            "https://0300.0.2.1/a.jpg",
            "https://192.0.513/a.jpg",
            "https://images.example.com%2e/a.jpg",
            "https://[::ffff:c000:201]:8443/a.jpg",
        ] {
            assert!(policy.check_url(refused).is_err(), "{refused}");
        }
        // The same address in IPv4-mapped spelling is the same host...
        assert_eq!(policy.check_url("https://[::ffff:192.0.2.1]/a.jpg"), Ok(()));
    }

    #[test]
    fn a_user_or_password_is_refused_over_plain_http() {
        let mut policy = policy(&["images.example.com"]);
        policy.allow_http = true;
        for refused in [
            "http://user:secret@images.example.com/a.jpg",
            "http://user@images.example.com/a.jpg",
            "http://:secret@images.example.com/a.jpg",
        ] {
            let message = policy.check_url(refused).expect_err(refused);
            assert!(message.contains("in the clear"), "{message}");
            assert!(!message.contains("secret"), "the message names no password");
        }
        assert_eq!(policy.check_url("https://user:secret@images.example.com/a.jpg"), Ok(()));
        assert_eq!(policy.check_url("http://images.example.com/a.jpg"), Ok(()));
    }

    #[test]
    fn a_user_agent_is_printable_ascii() {
        assert_eq!(FetchPolicy::new().user_agent(), DEFAULT_USER_AGENT);
        assert!(DEFAULT_USER_AGENT.starts_with("legit-hasher/"));
        for bad in ["", "a\tb", "a\nb", "a\r\nb", "a\u{7f}", "a\0", "naïve"] {
            assert!(FetchPolicy::new().with_user_agent(bad).is_err(), "{bad:?}");
        }
        assert!(
            FetchPolicy::new()
                .with_user_agent("indexer/1.0 (+https://example.com/bot)")
                .is_ok()
        );
    }

    #[test]
    fn a_redirect_resolves_against_the_url_it_came_from() {
        let base: Uri = "https://u:p@images.example.com/a/b/c.png?sig=1".parse().expect("a URL");
        for (location, expected) in [
            ("https://other.example.com/x.png", "https://other.example.com/x.png"),
            ("HTTP://other.example.com/x.png", "http://other.example.com/x.png"),
            ("//other.example.com/x.png", "https://other.example.com/x.png"),
            ("/x.png?sig=2", "https://u:p@images.example.com/x.png?sig=2"),
            ("d.png", "https://u:p@images.example.com/a/b/d.png"),
            ("../d.png", "https://u:p@images.example.com/a/d.png"),
            ("../../../../d.png", "https://u:p@images.example.com/d.png"),
            ("./", "https://u:p@images.example.com/a/b/"),
            ("?sig=2", "https://u:p@images.example.com/a/b/c.png?sig=2"),
            ("d.png#frag", "https://u:p@images.example.com/a/b/d.png"),
        ] {
            let target = redirect_target(&base, location).map(|uri| uri.to_string());
            assert_eq!(target.as_deref(), Some(expected), "{location}");
        }
        for location in ["", "#frag", "mailto:a@example.com", "https://", "http://[::1"] {
            assert!(redirect_target(&base, location).is_none(), "{location}");
        }
    }

    #[test]
    fn one_refused_address_among_those_resolved_refuses_the_fetch() {
        let policy = FetchPolicy::new().allow_range("127.0.0.0/8").expect("valid");
        let at = |text: &str| SocketAddr::new(ip(text), 443);
        let private = SocketAddr::new(IpAddr::from([10, 0, 0, 1]), 443);
        assert!(
            policy
                .check_addresses("h", [at("127.0.0.1"), at("93.184.215.14")])
                .is_ok()
        );
        for mixed in [
            vec![at("93.184.215.14"), private],
            vec![at("169.254.169.254"), at("93.184.215.14")],
            vec![at("2606:4700:4700::1111"), at("64:ff9b::a9fe:a9fe")],
        ] {
            let Err(Refusal(message)) = policy.check_addresses("h", mixed) else {
                panic!("a mixed answer was allowed");
            };
            assert!(message.contains("resolves to"), "{message}");
        }
        // Every address handed to the check is checked, however many: a refused one after the
        // first 16 still refuses...
        let mut long: Vec<SocketAddr> = (1..=20u8).map(|last| at(&format!("93.184.215.{last}"))).collect();
        long[18] = private;
        assert!(policy.check_addresses("h", long).is_err());
    }

    /// A resolver that answers every name with the same addresses, so no test looks up a name.
    #[derive(Debug)]
    struct Fixed(Vec<IpAddr>);

    impl Resolver for Fixed {
        fn resolve(&self, uri: &Uri, _: &Config, _: NextTimeout) -> Result<ResolvedSocketAddrs, ureq::Error> {
            let port = uri.port_u16().unwrap_or(443);
            let mut addresses = self.empty();
            for address in &self.0 {
                addresses.push(SocketAddr::new(*address, port));
            }
            Ok(addresses)
        }
    }

    #[test]
    fn a_fetch_connects_to_no_address_when_one_resolved_is_refused() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("a port");
        listener.set_nonblocking(true).expect("non-blocking");
        let port = listener.local_addr().expect("an address").port();
        let mut policy = policy(&[&format!("images.example.com:{port}")])
            .allow_range("127.0.0.0/8")
            .expect("valid");
        policy.allow_http = true;
        let url = format!("http://images.example.com:{port}/a.png");
        for answer in [
            vec![ip("127.0.0.1"), IpAddr::from([10, 0, 0, 1])],
            vec![IpAddr::from([10, 0, 0, 1]), ip("127.0.0.1")],
        ] {
            let fetcher = Fetcher::with_resolver(policy.clone(), Fixed(answer));
            let refused = fetcher.fetch(&url).expect_err("a refused address");
            assert_eq!(refused.code, RequestError::HostNotAllowed);
            assert!(refused.message.contains("private (10.0.0.0/8)"), "{}", refused.message);
        }
        assert!(listener.accept().is_err(), "no connection was made");
    }

    #[test]
    fn a_url_is_checked_before_any_connection() {
        let fetcher = Fetcher::new(FetchPolicy::new());
        let refused = fetcher
            .fetch("https://images.example.com/a.jpg?sig=1")
            .expect_err("no host allowed");
        assert_eq!(refused.code, RequestError::HostNotAllowed);
        let fetcher = Fetcher::new(policy(&["images.example.com"]));
        for (url, code) in [
            ("http://images.example.com/a.jpg", RequestError::HostNotAllowed),
            ("ftp://images.example.com/a.jpg", RequestError::HostNotAllowed),
            ("https://other.example.com/a.jpg", RequestError::HostNotAllowed),
            ("https://images.example.com:8443/a.jpg", RequestError::HostNotAllowed),
            ("/a.jpg", RequestError::InvalidRequest),
            ("not a url", RequestError::InvalidRequest),
        ] {
            assert_eq!(fetcher.fetch(url).expect_err(url).code, code, "{url}");
        }
    }
    /// A resolver that gives its answers in turn, the last one again once they run out, and counts
    /// the resolutions asked of it.
    #[derive(Debug)]
    struct Scripted {
        answers: Mutex<VecDeque<Vec<SocketAddr>>>,
        calls: Arc<AtomicUsize>,
    }

    impl Scripted {
        fn new(answers: Vec<Vec<SocketAddr>>) -> (Self, Arc<AtomicUsize>) {
            let calls = Arc::new(AtomicUsize::new(0));
            let resolver = Self {
                answers: Mutex::new(answers.into()),
                calls: Arc::clone(&calls),
            };
            (resolver, calls)
        }
    }

    impl Resolver for Scripted {
        fn resolve(&self, _: &Uri, _: &Config, _: NextTimeout) -> Result<ResolvedSocketAddrs, ureq::Error> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let mut answers = self.answers.lock().expect("answers");
            let answer = if answers.len() > 1 {
                answers.pop_front().unwrap_or_default()
            } else {
                answers.front().cloned().unwrap_or_default()
            };
            let mut addresses = self.empty();
            for address in answer {
                addresses.push(address);
            }
            Ok(addresses)
        }
    }

    /// A plain `http` server on `127.0.0.1` that keeps connections open and counts them. `/ok`
    /// answers `ok`; `/broken` answers `500`; `/hangup` closes before any byte of a reply, and
    /// `/hangup-late` after one.
    struct Server {
        port: u16,
        connections: Arc<AtomicUsize>,
        requests: Arc<Mutex<Vec<(usize, String)>>>,
    }

    impl Server {
        fn start() -> Self {
            let listener = TcpListener::bind("127.0.0.1:0").expect("a port");
            let port = listener.local_addr().expect("an address").port();
            let connections = Arc::new(AtomicUsize::new(0));
            let requests = Arc::new(Mutex::new(Vec::new()));
            let (counted, seen) = (Arc::clone(&connections), Arc::clone(&requests));
            std::thread::spawn(move || {
                for stream in listener.incoming().flatten() {
                    let connection = counted.fetch_add(1, Ordering::SeqCst) + 1;
                    let seen = Arc::clone(&seen);
                    std::thread::spawn(move || serve(stream, connection, &seen));
                }
            });
            Self {
                port,
                connections,
                requests,
            }
        }

        fn connections(&self) -> usize {
            self.connections.load(Ordering::SeqCst)
        }

        fn requests(&self) -> Vec<(usize, String)> {
            self.requests.lock().expect("requests").clone()
        }

        fn at(&self) -> SocketAddr {
            SocketAddr::new(ip("127.0.0.1"), self.port)
        }
    }

    fn serve(mut stream: TcpStream, connection: usize, seen: &Mutex<Vec<(usize, String)>>) {
        loop {
            let mut head = Vec::new();
            let mut byte = [0u8; 1];
            while !head.ends_with(b"\r\n\r\n") {
                match stream.read(&mut byte) {
                    Ok(1) => head.push(byte[0]),
                    _ => return,
                }
            }
            let head = String::from_utf8_lossy(&head).into_owned();
            let target = head.split(' ').nth(1).unwrap_or("/").to_owned();
            seen.lock().expect("requests").push((connection, target.clone()));
            let written = match target.as_str() {
                "/ok" => stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"),
                "/broken" => stream.write_all(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"),
                "/hangup-late" => {
                    let _ = stream.write_all(b"HTTP/1.1 2");
                    return;
                }
                _ => return,
            };
            if written.is_err() {
                return;
            }
        }
    }

    /// A port nothing listens on, so a connect to it is refused.
    fn closed_port() -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").expect("a port");
        listener.local_addr().expect("an address")
    }

    /// `255.255.255.255`: a connect to the broadcast address fails at once, `network
    /// unreachable` on Linux, as an IPv6 address does on a host with no IPv6 route.
    fn unreachable(port: u16) -> SocketAddr {
        SocketAddr::new(IpAddr::from([255, 255, 255, 255]), port)
    }

    /// Fetches from `images.example.com` on `port`, and any name under `example.com`, with
    /// loopback and the broadcast address open, over plain `http`.
    fn open_policy(port: u16) -> FetchPolicy {
        let mut policy = policy(&[&format!("images.example.com:{port}"), &format!("*.example.com:{port}")])
            .allow_range("127.0.0.0/8")
            .and_then(|policy| policy.allow_range("255.255.255.255"))
            .expect("valid");
        policy.allow_http = true;
        policy.timeout = Duration::from_secs(10);
        policy
    }

    #[test]
    fn every_checked_address_is_tried_in_order_until_one_connects() {
        let server = Server::start();
        let answer = vec![unreachable(server.port), closed_port(), server.at()];
        let (resolver, calls) = Scripted::new(vec![answer]);
        let fetcher = Fetcher::with_resolver(open_policy(server.port), resolver);
        let url = format!("http://images.example.com:{}/ok", server.port);
        assert_eq!(fetcher.fetch(&url).expect("the third address connects").bytes, b"ok");
        assert_eq!(calls.load(Ordering::SeqCst), 1, "no retry was needed");
        assert_eq!(fetcher.connection_counts(), (1, 0, 0));
    }

    #[test]
    fn many_fetches_at_once_fall_through_an_unreachable_first_address() {
        // The worker's failing case, reproduced: a host whose name gives an unreachable address
        // first and a good one after, and many fetches at once. Every fetch connects...
        let server = Server::start();
        let (resolver, _) = Scripted::new(vec![vec![unreachable(server.port), server.at()]]);
        let fetcher = Arc::new(Fetcher::with_resolver(open_policy(server.port), resolver));
        let url = format!("http://images.example.com:{}/ok", server.port);
        let threads: Vec<_> = (0..32)
            .map(|_| {
                let (fetcher, url) = (Arc::clone(&fetcher), url.clone());
                std::thread::spawn(move || (0..10).filter(|_| fetcher.fetch(&url).is_err()).count())
            })
            .collect();
        let failed: usize = threads.into_iter().map(|thread| thread.join().expect("ran")).sum();
        assert_eq!(failed, 0);
        assert!(server.connections() <= 34, "{} connections", server.connections());
    }

    #[test]
    fn a_final_connect_failure_counts_addresses_and_attempts_and_names_no_address() {
        let closed = closed_port();
        let answer = vec![closed, unreachable(closed.port())];
        let (resolver, calls) = Scripted::new(vec![answer]);
        let fetcher = Fetcher::with_resolver(open_policy(closed.port()), resolver);
        let refused = fetcher
            .fetch(&format!("http://images.example.com:{}/ok", closed.port()))
            .expect_err("nothing listens");
        assert_eq!(refused.code, RequestError::DownloadFailed);
        // Every address of both resolutions was tried, and each reason is given: before, only
        // the last address's error was, so a refused first address read as `network unreachable`...
        assert!(
            refused
                .message
                .contains("4 connects to 2 addresses over 2 attempts failed: connection refused"),
            "{}",
            refused.message
        );
        assert!(!refused.message.contains("127.0.0.1") && !refused.message.contains("255.255"));
        assert_eq!(calls.load(Ordering::SeqCst), 2, "resolved again for the retry");
        assert_eq!(fetcher.connection_counts(), (0, 0, 1));
    }

    #[test]
    fn a_connect_failure_is_tried_once_more_on_a_new_resolution_checked_again() {
        let server = Server::start();
        let url = format!("http://images.example.com:{}/ok", server.port);
        let (resolver, calls) = Scripted::new(vec![vec![closed_port()], vec![server.at()]]);
        let fetcher = Fetcher::with_resolver(open_policy(server.port), resolver);
        assert_eq!(fetcher.fetch(&url).expect("the retry connects").bytes, b"ok");
        assert_eq!(calls.load(Ordering::SeqCst), 2);
        assert_eq!(fetcher.connection_counts(), (1, 0, 1));

        // Turned off, the first failure is final...
        let mut policy = open_policy(server.port);
        policy.connect_retries = 0;
        let (resolver, calls) = Scripted::new(vec![vec![closed_port()], vec![server.at()]]);
        let refused = Fetcher::with_resolver(policy, resolver)
            .fetch(&url)
            .expect_err("no retry");
        assert!(refused.message.contains("over 1 attempt failed"), "{}", refused.message);
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        // ...and the new resolution is checked as the first was: a refused address refuses it.
        let (resolver, _) = Scripted::new(vec![
            vec![closed_port()],
            vec![SocketAddr::new(IpAddr::from([10, 0, 0, 1]), server.port)],
        ]);
        let refused = Fetcher::with_resolver(open_policy(server.port), resolver)
            .fetch(&url)
            .expect_err("refused on the retry");
        assert_eq!(refused.code, RequestError::HostNotAllowed);
        assert!(refused.message.contains("private (10.0.0.0/8)"), "{}", refused.message);
    }

    #[test]
    fn a_request_is_tried_again_only_when_no_byte_of_a_reply_arrived() {
        let server = Server::start();
        let (resolver, _) = Scripted::new(vec![vec![server.at()]]);
        let fetcher = Fetcher::with_resolver(open_policy(server.port), resolver);
        let at = |target: &str| format!("http://images.example.com:{}{target}", server.port);
        let count = |target: &str| server.requests().iter().filter(|(_, seen)| seen == target).count();

        // Closed before any byte: tried once more, then the failure is final...
        let refused = fetcher.fetch(&at("/hangup")).expect_err("hung up");
        assert_eq!(refused.code, RequestError::DownloadFailed);
        assert!(refused.message.contains("after 2 attempts"), "{}", refused.message);
        assert_eq!(count("/hangup"), 2);
        // ...but never after a byte of the reply, and never for a status.
        assert!(fetcher.fetch(&at("/hangup-late")).is_err());
        assert_eq!(count("/hangup-late"), 1);
        let refused = fetcher.fetch(&at("/broken")).expect_err("500");
        assert!(refused.message.contains("`500`"), "{}", refused.message);
        assert_eq!(count("/broken"), 1);
        assert_eq!(fetcher.connection_counts().2, 1);
    }

    /// `ENOBUFS` on Linux: an error number the standard library gives no category, so its kind
    /// reads `uncategorized error`.
    const UNCATEGORIZED: i32 = 105;

    /// A resolver whose first resolution fails with an I/O error of `UNCATEGORIZED`, before any
    /// connection, and whose later ones answer `then`; it counts the resolutions asked of it.
    #[derive(Debug)]
    struct FailsFirst {
        then: Vec<SocketAddr>,
        calls: Arc<AtomicUsize>,
    }

    impl FailsFirst {
        fn new(then: Vec<SocketAddr>) -> (Self, Arc<AtomicUsize>) {
            let calls = Arc::new(AtomicUsize::new(0));
            let resolver = Self {
                then,
                calls: Arc::clone(&calls),
            };
            (resolver, calls)
        }
    }

    impl Resolver for FailsFirst {
        fn resolve(&self, _: &Uri, _: &Config, _: NextTimeout) -> Result<ResolvedSocketAddrs, ureq::Error> {
            if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
                return Err(ureq::Error::Io(std::io::Error::from_raw_os_error(UNCATEGORIZED)));
            }
            let mut addresses = self.empty();
            for address in &self.then {
                addresses.push(*address);
            }
            Ok(addresses)
        }
    }

    #[test]
    fn an_io_error_of_any_kind_before_anything_is_sent_is_tried_once_more_checked_again() {
        assert_eq!(
            std::io::Error::from_raw_os_error(UNCATEGORIZED).kind().to_string(),
            "uncategorized error"
        );
        let server = Server::start();
        let url = format!("http://images.example.com:{}/ok", server.port);
        let (resolver, calls) = FailsFirst::new(vec![server.at()]);
        let fetcher = Fetcher::with_resolver(open_policy(server.port), resolver);
        assert_eq!(fetcher.fetch(&url).expect("the retry connects").bytes, b"ok");
        assert_eq!(calls.load(Ordering::SeqCst), 2, "resolved again for the retry");
        assert_eq!(fetcher.connection_counts(), (1, 0, 1));

        // The new resolution is checked as the first would have been...
        let (resolver, _) = FailsFirst::new(vec![SocketAddr::new(IpAddr::from([10, 0, 0, 1]), server.port)]);
        let refused = Fetcher::with_resolver(open_policy(server.port), resolver)
            .fetch(&url)
            .expect_err("refused on the retry");
        assert_eq!(refused.code, RequestError::HostNotAllowed);

        // ...and with retries turned off the failure is final, its message giving the number.
        let mut policy = open_policy(server.port);
        policy.connect_retries = 0;
        let (resolver, calls) = FailsFirst::new(vec![server.at()]);
        let failed = Fetcher::with_resolver(policy, resolver)
            .fetch(&url)
            .expect_err("no retry");
        assert_eq!(failed.code, RequestError::DownloadFailed);
        assert!(
            failed.message.ends_with("failed: uncategorized error (os error 105)"),
            "{}",
            failed.message
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert_eq!(server.requests().len(), 1, "only the first fetch wrote a request");
    }

    #[test]
    fn an_io_error_after_the_request_was_written_is_tried_again_only_if_it_is_a_lost_connection() {
        let uncategorized = || ureq::Error::Io(std::io::Error::from_raw_os_error(UNCATEGORIZED));
        let reset = || ureq::Error::Io(std::io::ErrorKind::ConnectionReset.into());
        let before = Trace::default();
        let written = Trace {
            sent: true,
            ..Trace::default()
        };
        let answered = Trace {
            sent: true,
            received: true,
            ..Trace::default()
        };
        assert!(connect_level(&uncategorized(), before));
        assert!(connect_level(&reset(), before));
        // After the request was written, only a lost connection before the reply is retried...
        assert!(!connect_level(&uncategorized(), written));
        assert!(connect_level(&reset(), written));
        // ...and nothing after a byte of the response.
        assert!(!connect_level(&uncategorized(), answered));
        assert!(!connect_level(&reset(), answered));
    }

    #[test]
    fn an_io_failure_names_the_systems_error_number_only_when_there_is_one() {
        let fetcher = Fetcher::new(FetchPolicy::new());
        let shown = "https://images.example.com/a.jpg";
        let message = |error: std::io::Error| {
            fetcher
                .failure(&ureq::Error::Io(error), shown, &Attempts::default())
                .message
        };
        assert_eq!(
            message(std::io::Error::from_raw_os_error(UNCATEGORIZED)),
            format!("fetching `{shown}` failed: uncategorized error (os error 105)")
        );
        assert_eq!(
            message(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "from 203.0.113.7 at https://images.example.com/a.jpg?sig=secret"
            )),
            format!("fetching `{shown}` failed: unexpected end of file")
        );
    }

    #[test]
    fn a_retry_never_runs_past_the_fetchs_deadline() {
        let closed = closed_port();
        let mut policy = open_policy(closed.port());
        policy.timeout = Duration::from_millis(150);
        let (resolver, calls) = Scripted::new(vec![vec![closed]]);
        let started = Instant::now();
        let refused = Fetcher::with_resolver(policy, resolver)
            .fetch(&format!("http://images.example.com:{}/ok", closed.port()))
            .expect_err("nothing listens");
        assert_eq!(refused.code, RequestError::DownloadFailed);
        assert_eq!(calls.load(Ordering::SeqCst), 1, "no time was left for a retry's pause");
        assert!(started.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn a_pooled_connection_serves_only_its_own_host_and_port() {
        let server = Server::start();
        let (resolver, _) = Scripted::new(vec![vec![server.at()]]);
        let fetcher = Fetcher::with_resolver(open_policy(server.port), resolver);
        for host in ["a.example.com", "b.example.com", "a.example.com", "b.example.com"] {
            let url = format!("http://{host}:{}/ok", server.port);
            assert_eq!(fetcher.fetch(&url).expect("fetched").bytes, b"ok");
        }
        // Two names on one server and one address: a connection each, each reused once...
        assert_eq!(server.connections(), 2);
        assert_eq!(fetcher.connection_counts(), (2, 2, 0));
        let by_connection: Vec<usize> = server.requests().iter().map(|(connection, _)| *connection).collect();
        assert_eq!(by_connection, [1, 2, 1, 2]);
    }

    #[test]
    fn every_request_is_checked_before_it_is_written_even_with_a_connection_idle() {
        let server = Server::start();
        let at = server.at();
        let (resolver, calls) = Scripted::new(vec![
            vec![at],
            vec![SocketAddr::new(IpAddr::from([169, 254, 169, 254]), server.port)],
        ]);
        let fetcher = Fetcher::with_resolver(open_policy(server.port), resolver);
        let url = format!("http://images.example.com:{}/ok", server.port);
        fetcher.fetch(&url).expect("fetched");
        // An idle connection to the server waits in the pool. A URL the policy refuses is refused
        // without it: scheme, user over `http`, host and port...
        for refused in [
            format!("ftp://images.example.com:{}/ok", server.port),
            format!("http://user:secret@images.example.com:{}/ok", server.port),
            format!("http://images.example.org:{}/ok", server.port),
            format!("http://images.example.com:{}/ok", closed_port().port()),
        ] {
            let error = fetcher.fetch(&refused).expect_err(&refused);
            assert_eq!(error.code, RequestError::HostNotAllowed, "{refused}: {}", error.message);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 1, "refused before resolving");
        // ...and so is a URL whose host now resolves to a refused address, though the connection
        // opened to the address it resolved to before is still idle.
        let error = fetcher.fetch(&url).expect_err("now link-local");
        assert_eq!(error.code, RequestError::HostNotAllowed);
        assert!(error.message.contains("link-local"), "{}", error.message);
        assert_eq!(server.requests().len(), 1, "nothing more was written");
        assert_eq!(server.connections(), 1);
    }
}