servo-net 0.1.0-rc1

A component of the servo web-engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::collections::HashSet;
use std::iter::FromIterator;
use std::sync::Arc as StdArc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use async_recursion::async_recursion;
use crossbeam_channel::Sender;
use devtools_traits::{
    ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest,
    HttpResponse as DevtoolsHttpResponse, NetworkEvent, SecurityInfoUpdate,
};
use embedder_traits::{AuthenticationResponse, GenericEmbedderProxy};
use futures::{TryFutureExt, TryStreamExt, future};
use headers::authorization::Basic;
use headers::{
    AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowMethods,
    AccessControlMaxAge, AccessControlRequestMethod, Authorization, CacheControl, ContentLength,
    HeaderMapExt, IfModifiedSince, LastModified, Pragma, Referer, StrictTransportSecurity,
    UserAgent,
};
use http::header::{
    self, ACCEPT, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_REQUEST_HEADERS, AUTHORIZATION,
    CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LOCATION, CONTENT_TYPE, HeaderValue, RANGE,
    WWW_AUTHENTICATE,
};
use http::{HeaderMap, Method, Request as HyperRequest, StatusCode};
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use hyper::Response as HyperResponse;
use hyper::body::{Bytes, Frame};
use hyper::ext::ReasonPhrase;
use hyper::header::{HeaderName, TRANSFER_ENCODING};
use hyper_serde::Serde;
use ipc_channel::IpcError;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use log::{debug, error, info, log_enabled, warn};
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use net_traits::fetch::headers::get_value_from_header_list;
use net_traits::http_status::HttpStatus;
use net_traits::policy_container::RequestPolicyContainer;
use net_traits::pub_domains::{is_same_site, reg_suffix};
use net_traits::request::Origin::Origin as SpecificOrigin;
use net_traits::request::{
    BodyChunkRequest, BodyChunkResponse, CacheMode, CredentialsMode, Destination, Initiator,
    Origin, RedirectMode, Referrer, Request, RequestBuilder, RequestMode, ResponseTainting,
    ServiceWorkersMode, TraversableForUserPrompts, get_cors_unsafe_header_names,
    is_cors_non_wildcard_request_header_name, is_cors_safelisted_method,
    is_cors_safelisted_request_header,
};
use net_traits::response::{
    CacheState, HttpsState, RedirectTaint, Response, ResponseBody, ResponseType,
};
use net_traits::{
    CookieSource, DOCUMENT_ACCEPT_HEADER_VALUE, DebugVec, FetchMetadata, NetworkError,
    RedirectEndValue, RedirectStartValue, ReferrerPolicy, ResourceAttribute, ResourceFetchTiming,
    ResourceTimeValue, TlsSecurityInfo, TlsSecurityState,
};
use parking_lot::{Mutex, RwLock};
use profile_traits::mem::{Report, ReportKind};
use profile_traits::path;
use rustc_hash::FxHashMap;
use servo_arc::Arc;
use servo_base::cross_process_instant::CrossProcessInstant;
use servo_base::generic_channel::GenericSharedMemory;
use servo_base::id::{BrowsingContextId, HistoryStateId, PipelineId};
use servo_url::{ImmutableOrigin, ServoUrl};
use tokio::sync::mpsc::{
    Receiver as TokioReceiver, Sender as TokioSender, UnboundedReceiver, UnboundedSender, channel,
    unbounded_channel,
};
use tokio_stream::wrappers::ReceiverStream;

use crate::async_runtime::spawn_task;
use crate::connector::{
    CertificateErrorOverrideManager, ServoClient, TlsHandshakeInfo, create_tls_config,
};
use crate::cookie::ServoCookie;
use crate::cookie_storage::CookieStorage;
use crate::decoder::Decoder;
use crate::embedder::NetToEmbedderMsg;
use crate::fetch::cors_cache::CorsCache;
use crate::fetch::fetch_params::FetchParams;
use crate::fetch::headers::{SecFetchDest, SecFetchMode, SecFetchSite, SecFetchUser};
use crate::fetch::methods::{Data, DoneChannel, FetchContext, Target, main_fetch};
use crate::hsts::HstsList;
use crate::http_cache::{
    CacheKey, CachedResourcesOrGuard, HttpCache, construct_response, invalidate, refresh,
};
use crate::resource_thread::{AuthCache, AuthCacheEntry};
use crate::websocket_loader::start_websocket;

/// The various states an entry of the HttpCache can be in.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HttpCacheEntryState {
    /// The entry is fully up-to-date,
    /// there are no pending concurrent stores,
    /// and it is ready to construct cached responses.
    ReadyToConstruct,
    /// The entry is pending a number of concurrent stores.
    PendingStore(usize),
}

pub struct HttpState {
    pub hsts_list: RwLock<HstsList>,
    pub cookie_jar: RwLock<CookieStorage>,
    pub http_cache: HttpCache,
    pub auth_cache: RwLock<AuthCache>,
    pub history_states: RwLock<FxHashMap<HistoryStateId, Vec<u8>>>,
    pub client: ServoClient,
    pub override_manager: CertificateErrorOverrideManager,
    pub embedder_proxy: GenericEmbedderProxy<NetToEmbedderMsg>,
}

impl HttpState {
    pub(crate) fn memory_reports(&self, suffix: &str, ops: &mut MallocSizeOfOps) -> Vec<Report> {
        vec![
            Report {
                path: path!["memory-cache", suffix],
                kind: ReportKind::ExplicitJemallocHeapSize,
                size: self.http_cache.size_of(ops),
            },
            Report {
                path: path!["hsts-list", suffix],
                kind: ReportKind::ExplicitJemallocHeapSize,
                size: self.hsts_list.read().size_of(ops),
            },
        ]
    }

    async fn request_authentication(
        &self,
        request: &Request,
        response: &Response,
    ) -> Option<AuthenticationResponse> {
        // We do not make an authentication request for non-WebView associated HTTP requests.
        let webview_id = request.target_webview_id?;
        let for_proxy = response.status == StatusCode::PROXY_AUTHENTICATION_REQUIRED;

        // If this is not actually a navigation request return None.
        if request.mode != RequestMode::Navigate {
            return None;
        }

        let (sender, receiver) = tokio::sync::oneshot::channel();
        self.embedder_proxy
            .send(NetToEmbedderMsg::RequestAuthentication(
                webview_id,
                request.url(),
                for_proxy,
                sender,
            ));
        receiver.await.ok()?
    }
}

/// Step 11 of <https://fetch.spec.whatwg.org/#concept-fetch>.
pub(crate) fn set_default_accept(request: &mut Request) {
    // Step 11. If request’s header list does not contain `Accept`, then:
    if request.headers.contains_key(header::ACCEPT) {
        return;
    }

    // Step 11.2. If request’s initiator is "prefetch", then set value to the document `Accept` header value.
    let value = if request.initiator == Initiator::Prefetch {
        DOCUMENT_ACCEPT_HEADER_VALUE
    } else {
        // Step 11.3. Otherwise, the user agent should set value to the first matching statement,
        // if any, switching on request’s destination:
        match request.destination {
            Destination::Document | Destination::Frame | Destination::IFrame => {
                DOCUMENT_ACCEPT_HEADER_VALUE
            },
            Destination::Image => {
                HeaderValue::from_static("image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5")
            },
            Destination::Json => HeaderValue::from_static("application/json,*/*;q=0.5"),
            Destination::Style => HeaderValue::from_static("text/css,*/*;q=0.1"),
            // Step 11.1. Let value be `*/*`.
            _ => HeaderValue::from_static("*/*"),
        }
    };

    // Step 11.4. Append (`Accept`, value) to request’s header list.
    request.headers.insert(header::ACCEPT, value);
}

fn set_default_accept_encoding(headers: &mut HeaderMap) {
    if headers.contains_key(header::ACCEPT_ENCODING) {
        return;
    }

    // TODO(eijebong): Change this once typed headers are done
    headers.insert(
        header::ACCEPT_ENCODING,
        HeaderValue::from_static("gzip, deflate, br, zstd"),
    );
}

/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-state-no-referrer-when-downgrade>
fn no_referrer_when_downgrade(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
    // Step 1
    if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
        return None;
    }
    // Step 2
    strip_url_for_use_as_referrer(referrer_url, false)
}

/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin>
fn strict_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
    // Step 1
    if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
        return None;
    }
    // Step 2
    strip_url_for_use_as_referrer(referrer_url, true)
}

/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin>
fn strict_origin_when_cross_origin(
    referrer_url: ServoUrl,
    current_url: ServoUrl,
) -> Option<ServoUrl> {
    // Step 1
    if referrer_url.origin() == current_url.origin() {
        return strip_url_for_use_as_referrer(referrer_url, false);
    }
    // Step 2
    if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
        return None;
    }
    // Step 3
    strip_url_for_use_as_referrer(referrer_url, true)
}

/// <https://html.spec.whatwg.org/multipage/#schemelessly-same-site>
fn is_schemelessy_same_site(site_a: &ImmutableOrigin, site_b: &ImmutableOrigin) -> bool {
    // Step 1
    if !site_a.is_tuple() && !site_b.is_tuple() && site_a == site_b {
        true
    } else if site_a.is_tuple() && site_b.is_tuple() {
        // Step 2.1
        let host_a = site_a.host().map(|h| h.to_string()).unwrap_or_default();
        let host_b = site_b.host().map(|h| h.to_string()).unwrap_or_default();

        let host_a_reg = reg_suffix(&host_a);
        let host_b_reg = reg_suffix(&host_b);

        // Step 2.2-2.3
        (site_a.host() == site_b.host() && host_a_reg.is_empty()) ||
            (host_a_reg == host_b_reg && !host_a_reg.is_empty())
    } else {
        // Step 3
        false
    }
}

/// <https://w3c.github.io/webappsec-referrer-policy/#strip-url>
fn strip_url_for_use_as_referrer(mut url: ServoUrl, origin_only: bool) -> Option<ServoUrl> {
    const MAX_REFERRER_URL_LENGTH: usize = 4096;
    // Step 2
    if url.is_local_scheme() {
        return None;
    }
    // Step 3-6
    {
        let url = url.as_mut_url();
        let _ = url.set_username("");
        let _ = url.set_password(None);
        url.set_fragment(None);
        // Note: The result of serializing referrer url should not be
        // greater than 4096 as specified in Step 6 of
        // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
        if origin_only || url.as_str().len() > MAX_REFERRER_URL_LENGTH {
            url.set_path("");
            url.set_query(None);
        }
    }
    // Step 7
    Some(url)
}

/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-same-origin>
fn same_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
    // Step 1
    if referrer_url.origin() == current_url.origin() {
        return strip_url_for_use_as_referrer(referrer_url, false);
    }
    // Step 2
    None
}

/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-origin-when-cross-origin>
fn origin_when_cross_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
    // Step 1
    if referrer_url.origin() == current_url.origin() {
        return strip_url_for_use_as_referrer(referrer_url, false);
    }
    // Step 2
    strip_url_for_use_as_referrer(referrer_url, true)
}

/// <https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer>
pub fn determine_requests_referrer(
    referrer_policy: ReferrerPolicy,
    referrer_source: ServoUrl,
    current_url: ServoUrl,
) -> Option<ServoUrl> {
    match referrer_policy {
        ReferrerPolicy::EmptyString | ReferrerPolicy::NoReferrer => None,
        ReferrerPolicy::Origin => strip_url_for_use_as_referrer(referrer_source, true),
        ReferrerPolicy::UnsafeUrl => strip_url_for_use_as_referrer(referrer_source, false),
        ReferrerPolicy::StrictOrigin => strict_origin(referrer_source, current_url),
        ReferrerPolicy::StrictOriginWhenCrossOrigin => {
            strict_origin_when_cross_origin(referrer_source, current_url)
        },
        ReferrerPolicy::SameOrigin => same_origin(referrer_source, current_url),
        ReferrerPolicy::OriginWhenCrossOrigin => {
            origin_when_cross_origin(referrer_source, current_url)
        },
        ReferrerPolicy::NoReferrerWhenDowngrade => {
            no_referrer_when_downgrade(referrer_source, current_url)
        },
    }
}

fn set_request_cookies(
    url: &ServoUrl,
    headers: &mut HeaderMap,
    cookie_jar: &RwLock<CookieStorage>,
) {
    let mut cookie_jar = cookie_jar.write();
    cookie_jar.remove_expired_cookies_for_url(url);
    if let Some(cookie_list) = cookie_jar.cookies_for_url(url, CookieSource::HTTP) {
        headers.insert(
            header::COOKIE,
            HeaderValue::from_bytes(cookie_list.as_bytes()).unwrap(),
        );
    }
}

fn set_cookie_for_url(cookie_jar: &RwLock<CookieStorage>, request: &ServoUrl, cookie_val: &str) {
    let mut cookie_jar = cookie_jar.write();
    let source = CookieSource::HTTP;

    if let Some(cookie) = ServoCookie::from_cookie_string(cookie_val, request, source) {
        cookie_jar.push(cookie, request, source);
    }
}

fn set_cookies_from_headers(
    url: &ServoUrl,
    headers: &HeaderMap,
    cookie_jar: &RwLock<CookieStorage>,
) {
    for cookie in headers.get_all(header::SET_COOKIE) {
        let cookie_bytes = cookie.as_bytes();
        if !ServoCookie::is_valid_name_or_value(cookie_bytes) {
            continue;
        }
        if let Ok(cookie_str) = std::str::from_utf8(cookie_bytes) {
            set_cookie_for_url(cookie_jar, url, cookie_str);
        }
    }
}

fn build_tls_security_info(handshake: &TlsHandshakeInfo, hsts_enabled: bool) -> TlsSecurityInfo {
    // Simplified security state determination:
    // Servo uses rustls, which only supports TLS 1.2+ and secure cipher suites (GCM, ChaCha20-Poly1305).
    // rustls does NOT support TLS 1.0, TLS 1.1, SSL, or weak ciphers (RC4, 3DES, CBC, etc).
    // Therefore, any successful TLS connection is secure by design.
    //
    // We only check for missing handshake information as a defensive measure.

    let state = if handshake.protocol_version.is_none() || handshake.cipher_suite.is_none() {
        // Missing handshake information indicates an incomplete or failed connection
        TlsSecurityState::Insecure
    } else {
        // rustls guarantees TLS 1.2+ with secure ciphers
        TlsSecurityState::Secure
    };

    TlsSecurityInfo {
        state,
        weakness_reasons: Vec::new(), // rustls never negotiates weak crypto
        protocol_version: handshake.protocol_version.clone(),
        cipher_suite: handshake.cipher_suite.clone(),
        kea_group_name: handshake.kea_group_name.clone(),
        signature_scheme_name: handshake.signature_scheme_name.clone(),
        alpn_protocol: handshake.alpn_protocol.clone(),
        certificate_chain_der: handshake.certificate_chain_der.clone(),
        certificate_transparency: None,
        hsts: hsts_enabled,
        hpkp: false,
        used_ech: handshake.used_ech,
        used_delegated_credentials: false,
        used_ocsp: false,
        used_private_dns: false,
    }
}

#[allow(clippy::too_many_arguments)]
fn prepare_devtools_request(
    request_id: String,
    url: ServoUrl,
    method: Method,
    headers: HeaderMap,
    body: Option<Vec<u8>>,
    pipeline_id: PipelineId,
    connect_time: Duration,
    send_time: Duration,
    destination: Destination,
    is_xhr: bool,
    browsing_context_id: BrowsingContextId,
) -> ChromeToDevtoolsControlMsg {
    let started_date_time = SystemTime::now();
    let request = DevtoolsHttpRequest {
        url,
        method,
        headers,
        body: body.map(DebugVec::from),
        pipeline_id,
        started_date_time,
        time_stamp: started_date_time
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64,
        connect_time,
        send_time,
        destination,
        is_xhr,
        browsing_context_id,
    };
    let net_event = NetworkEvent::HttpRequestUpdate(request);

    ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event)
}

pub fn send_request_to_devtools(
    msg: ChromeToDevtoolsControlMsg,
    devtools_chan: &Sender<DevtoolsControlMsg>,
) {
    if matches!(msg, ChromeToDevtoolsControlMsg::NetworkEvent(_, ref network_event) if !network_event.forward_to_devtools())
    {
        return;
    }
    if let Err(e) = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)) {
        error!("DevTools send failed: {e}");
    }
}

pub fn send_response_to_devtools(
    request: &Request,
    context: &FetchContext,
    response: &Response,
    body_data: Option<Vec<u8>>,
) {
    let meta = match response.metadata() {
        Ok(FetchMetadata::Unfiltered(m)) => m,
        Ok(FetchMetadata::Filtered { unsafe_, .. }) => unsafe_,
        Err(_) => {
            log::warn!("No metadata available, skipping devtools response.");
            return;
        },
    };
    send_response_values_to_devtools(
        meta.headers.map(Serde::into_inner),
        meta.status,
        body_data,
        response.cache_state,
        request,
        context.devtools_chan.clone(),
    );
}

#[allow(clippy::too_many_arguments)]
pub fn send_response_values_to_devtools(
    headers: Option<HeaderMap>,
    status: HttpStatus,
    body: Option<Vec<u8>>,
    cache_state: CacheState,
    request: &Request,
    devtools_chan: Option<Sender<DevtoolsControlMsg>>,
) {
    if let (Some(devtools_chan), Some(pipeline_id), Some(webview_id)) = (
        devtools_chan,
        request.pipeline_id,
        request.target_webview_id,
    ) {
        let browsing_context_id = webview_id.into();
        let from_cache = matches!(cache_state, CacheState::Local | CacheState::Validated);

        let devtoolsresponse = DevtoolsHttpResponse {
            headers,
            status,
            body: body.map(DebugVec::from),
            from_cache,
            pipeline_id,
            browsing_context_id,
        };
        let net_event_response = NetworkEvent::HttpResponse(devtoolsresponse);

        let msg =
            ChromeToDevtoolsControlMsg::NetworkEvent(request.id.0.to_string(), net_event_response);

        let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg));
    }
}

pub fn send_security_info_to_devtools(
    request: &Request,
    context: &FetchContext,
    response: &Response,
) {
    let meta = match response.metadata() {
        Ok(FetchMetadata::Unfiltered(m)) => m,
        Ok(FetchMetadata::Filtered { unsafe_, .. }) => unsafe_,
        Err(_) => {
            log::warn!("No metadata available, skipping devtools security info.");
            return;
        },
    };

    if let (Some(devtools_chan), Some(security_info), Some(webview_id)) = (
        context.devtools_chan.clone(),
        meta.tls_security_info,
        request.target_webview_id,
    ) {
        let update = NetworkEvent::SecurityInfo(SecurityInfoUpdate {
            browsing_context_id: webview_id.into(),
            security_info: Some(security_info),
        });

        let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request.id.0.to_string(), update);

        let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg));
    }
}

pub fn send_early_httprequest_to_devtools(request: &Request, context: &FetchContext) {
    // Do not forward data requests to devtools
    if request.url().scheme() == "data" {
        return;
    }
    if let (Some(devtools_chan), Some(browsing_context_id), Some(pipeline_id)) = (
        context.devtools_chan.as_ref(),
        request.target_webview_id.map(|id| id.into()),
        request.pipeline_id,
    ) {
        // Build the partial DevtoolsHttpRequest
        let devtools_request = DevtoolsHttpRequest {
            url: request.current_url(),
            method: request.method.clone(),
            headers: request.headers.clone(),
            body: None,
            pipeline_id,
            started_date_time: SystemTime::now(),
            time_stamp: 0,
            connect_time: Duration::from_millis(0),
            send_time: Duration::from_millis(0),
            destination: request.destination,
            is_xhr: false,
            browsing_context_id,
        };

        let msg = ChromeToDevtoolsControlMsg::NetworkEvent(
            request.id.0.to_string(),
            NetworkEvent::HttpRequest(devtools_request),
        );

        send_request_to_devtools(msg, devtools_chan);
    }
}

fn auth_from_cache(
    auth_cache: &RwLock<AuthCache>,
    origin: &ImmutableOrigin,
) -> Option<Authorization<Basic>> {
    if let Some(auth_entry) = auth_cache.read().entries.get(&origin.ascii_serialization()) {
        let user_name = &auth_entry.user_name;
        let password = &auth_entry.password;
        Some(Authorization::basic(user_name, password))
    } else {
        None
    }
}

/// Messages from the IPC route to the fetch worker,
/// used to fill the body with bytes coming-in over IPC.
enum BodyChunk {
    /// A chunk of bytes.
    Chunk(GenericSharedMemory),
    /// Body is done.
    Done,
}

/// The stream side of the body passed to hyper.
enum BodyStream {
    /// A receiver that can be used in Body::wrap_stream,
    /// for streaming the request over the network.
    Chunked(TokioReceiver<Result<Frame<Bytes>, hyper::Error>>),
    /// A body whose bytes are buffered
    /// and sent in one chunk over the network.
    Buffered(UnboundedReceiver<BodyChunk>),
}

/// The sink side of the body passed to hyper,
/// used to enqueue chunks.
enum BodySink {
    /// A Tokio sender used to feed chunks to the network stream.
    Chunked(TokioSender<Result<Frame<Bytes>, hyper::Error>>),
    /// A Crossbeam sender used to send chunks to the fetch worker,
    /// where they will be buffered
    /// in order to ensure they are not streamed them over the network.
    Buffered(UnboundedSender<BodyChunk>),
}

impl BodySink {
    fn transmit_bytes(&self, bytes: GenericSharedMemory) {
        match self {
            BodySink::Chunked(sender) => {
                let sender = sender.clone();
                spawn_task(async move {
                    let _ = sender
                        .send(Ok(Frame::data(Bytes::copy_from_slice(&bytes))))
                        .await;
                });
            },
            BodySink::Buffered(sender) => {
                let _ = sender.send(BodyChunk::Chunk(bytes));
            },
        }
    }

    fn close(&self) {
        match self {
            BodySink::Chunked(_) => { /* no need to close sender */ },
            BodySink::Buffered(sender) => {
                let _ = sender.send(BodyChunk::Done);
            },
        }
    }
}

fn request_body_stream_closed_error(action: &str) -> NetworkError {
    NetworkError::Crash(format!(
        "Request body stream has already been closed while trying to {action}."
    ))
}

fn log_request_body_stream_closed(action: &str, error: Option<&IpcError>) {
    match error {
        Some(error) => {
            error!("Request body stream has already been closed while trying to {action}: {error}")
        },
        None => error!("Request body stream has already been closed while trying to {action}."),
    }
}

fn log_fetch_terminated_send_failure(terminated_with_error: bool, context: &str) {
    warn!(
        "Failed to notify request-body stream termination state ({terminated_with_error}) while {context} because the receiver was already dropped."
    );
}

#[allow(clippy::too_many_arguments)]
async fn obtain_response(
    client: &ServoClient,
    url: &ServoUrl,
    method: &Method,
    request_headers: &mut HeaderMap,
    body: Option<StdArc<Mutex<Option<IpcSender<BodyChunkRequest>>>>>,
    source_is_null: bool,
    pipeline_id: &Option<PipelineId>,
    request_id: Option<&str>,
    destination: Destination,
    is_xhr: bool,
    context: &FetchContext,
    fetch_terminated: UnboundedSender<bool>,
    browsing_context_id: Option<BrowsingContextId>,
) -> Result<(HyperResponse<Decoder>, Option<ChromeToDevtoolsControlMsg>), NetworkError> {
    {
        let mut headers = request_headers.clone();

        let devtools_bytes = StdArc::new(Mutex::new(vec![]));

        // https://url.spec.whatwg.org/#percent-encoded-bytes
        let encoded_url = url
            .clone()
            .into_url()
            .as_ref()
            .replace('|', "%7C")
            .replace('{', "%7B")
            .replace('}', "%7D");

        let request = if let Some(chunk_requester) = body {
            let (sink, stream) = if source_is_null {
                // Step 4.2 of https://fetch.spec.whatwg.org/#concept-http-network-fetch
                // TODO: this should not be set for HTTP/2(currently not supported?).
                headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));

                let (sender, receiver) = channel(1);
                (BodySink::Chunked(sender), BodyStream::Chunked(receiver))
            } else {
                // Note: Hyper seems to already buffer bytes when the request appears not stream-able,
                // see https://github.com/hyperium/hyper/issues/2232#issuecomment-644322104
                //
                // However since this doesn't appear documented, and we're using an ancient version,
                // for now we buffer manually to ensure we don't stream requests
                // to servers that might not know how to handle them.
                let (sender, receiver) = unbounded_channel();
                (BodySink::Buffered(sender), BodyStream::Buffered(receiver))
            };

            let (body_chan, body_port) = ipc::channel().unwrap();

            {
                let mut lock = chunk_requester.lock();
                if let Some(chunk_requester) = lock.as_mut() {
                    if let Err(error) = chunk_requester.send(BodyChunkRequest::Connect(body_chan)) {
                        log_request_body_stream_closed(
                            "connect to the request body stream",
                            Some(&error),
                        );
                        return Err(request_body_stream_closed_error(
                            "connect to the request body stream",
                        ));
                    }

                    // https://fetch.spec.whatwg.org/#concept-request-transmit-body
                    // Request the first chunk, corresponding to Step 3 and 4.
                    if let Err(error) = chunk_requester.send(BodyChunkRequest::Chunk) {
                        log_request_body_stream_closed(
                            "request the first request body chunk",
                            Some(&error),
                        );
                        return Err(request_body_stream_closed_error(
                            "request the first request body chunk",
                        ));
                    }
                } else {
                    log_request_body_stream_closed("connect to the request body stream", None);
                    return Err(request_body_stream_closed_error(
                        "connect to the request body stream",
                    ));
                }
            }

            let devtools_bytes = devtools_bytes.clone();
            let chunk_requester2 = chunk_requester.clone();

            ROUTER.add_typed_route(
                body_port,
                Box::new(move |message| {
                    info!("Received message");
                    let bytes = match message.unwrap() {
                        BodyChunkResponse::Chunk(bytes) => bytes,
                        BodyChunkResponse::Done => {
                            // Step 3, abort these parallel steps.
                            if fetch_terminated.send(false).is_err() {
                                log_fetch_terminated_send_failure(
                                    false,
                                    "handling request body completion",
                                );
                            }
                            sink.close();

                            return;
                        },
                        BodyChunkResponse::Error => {
                            // Step 4 and/or 5.
                            // TODO: differentiate between the two steps,
                            // where step 5 requires setting an `aborted` flag on the fetch.
                            if fetch_terminated.send(true).is_err() {
                                log_fetch_terminated_send_failure(
                                    true,
                                    "handling request body stream error",
                                );
                            }
                            sink.close();

                            return;
                        },
                    };

                    devtools_bytes.lock().extend_from_slice(&bytes);

                    // Step 5.1.2.2, transmit chunk over the network,
                    // currently implemented by sending the bytes to the fetch worker.
                    sink.transmit_bytes(bytes);

                    // Step 5.1.2.3
                    // Request the next chunk.
                    let mut chunk_requester2 = chunk_requester2.lock();
                    if let Some(chunk_requester2) = chunk_requester2.as_mut() {
                        if let Err(error) = chunk_requester2.send(BodyChunkRequest::Chunk) {
                            log_request_body_stream_closed(
                                "request the next request body chunk",
                                Some(&error),
                            );
                            if fetch_terminated.send(true).is_err() {
                                log_fetch_terminated_send_failure(
                                    true,
                                    "handling failure to request the next request body chunk",
                                );
                            }
                            sink.close();
                        }
                    } else {
                        log_request_body_stream_closed("request the next request body chunk", None);
                        if fetch_terminated.send(true).is_err() {
                            log_fetch_terminated_send_failure(
                                true,
                                "handling a closed request body stream while requesting the next chunk",
                            );
                        }
                        sink.close();
                    }
                }),
            );

            let body = match stream {
                BodyStream::Chunked(receiver) => {
                    let stream = ReceiverStream::new(receiver);
                    BoxBody::new(http_body_util::StreamBody::new(stream))
                },
                BodyStream::Buffered(mut receiver) => {
                    // Accumulate bytes received over IPC into a vector.
                    let mut body = vec![];
                    loop {
                        match receiver.recv().await {
                            Some(BodyChunk::Chunk(bytes)) => {
                                body.extend_from_slice(&bytes);
                            },
                            Some(BodyChunk::Done) => break,
                            None => warn!("Failed to read all chunks from request body."),
                        }
                    }
                    Full::new(body.into()).map_err(|_| unreachable!()).boxed()
                },
            };
            HyperRequest::builder()
                .method(method)
                .uri(encoded_url)
                .body(body)
        } else {
            HyperRequest::builder()
                .method(method)
                .uri(encoded_url)
                .body(
                    http_body_util::Empty::new()
                        .map_err(|_| unreachable!())
                        .boxed(),
                )
        };

        context
            .timing
            .lock()
            .set_attribute(ResourceAttribute::DomainLookupStart);

        // TODO(#21261) connect_start: set if a persistent connection is *not* used and the last non-redirected
        // fetch passes the timing allow check
        let connect_start = CrossProcessInstant::now();
        context
            .timing
            .lock()
            .set_attribute(ResourceAttribute::ConnectStart(connect_start));

        // TODO: We currently don't know when the handhhake before the connection is done
        // so our best bet would be to set `secure_connection_start` here when we are currently
        // fetching on a HTTPS url.
        if url.scheme() == "https" {
            context
                .timing
                .lock()
                .set_attribute(ResourceAttribute::SecureConnectionStart);
        }

        let mut request = match request {
            Ok(request) => request,
            Err(error) => return Err(NetworkError::HttpError(error.to_string())),
        };
        *request.headers_mut() = headers.clone();

        let connect_end = CrossProcessInstant::now();
        context
            .timing
            .lock()
            .set_attribute(ResourceAttribute::ConnectEnd(connect_end));

        let request_id = request_id.map(|v| v.to_owned());
        let pipeline_id = *pipeline_id;
        let closure_url = url.clone();
        let method = method.clone();
        let send_start = CrossProcessInstant::now();

        let host = request.uri().host().unwrap_or("").to_owned();
        let override_manager = context.state.override_manager.clone();
        let headers = headers.clone();
        let is_secure_scheme = url.is_secure_scheme();

        client
            .request(request)
            .and_then(move |res| {
                let send_end = CrossProcessInstant::now();

                // TODO(#21271) response_start: immediately after receiving first byte of response

                let msg = if let Some(request_id) = request_id {
                    if let Some(pipeline_id) = pipeline_id {
                        if let Some(browsing_context_id) = browsing_context_id {
                            Some(prepare_devtools_request(
                                request_id,
                                closure_url,
                                method.clone(),
                                headers,
                                Some(devtools_bytes.lock().clone()),
                                pipeline_id,
                                (connect_end - connect_start).unsigned_abs(),
                                (send_end - send_start).unsigned_abs(),
                                destination,
                                is_xhr,
                                browsing_context_id,
                            ))
                        } else {
                            debug!("Not notifying devtools (no browsing_context_id)");
                            None
                        }
                        // TODO: ^This is not right, connect_start is taken before contructing the
                        // request and connect_end at the end of it. send_start is takend before the
                        // connection too. I'm not sure it's currently possible to get the time at the
                        // point between the connection and the start of a request.
                    } else {
                        debug!("Not notifying devtools (no pipeline_id)");
                        None
                    }
                } else {
                    debug!("Not notifying devtools (no request_id)");
                    None
                };

                future::ready(Ok((
                    Decoder::detect(res.map(|r| r.boxed()), is_secure_scheme),
                    msg,
                )))
            })
            .map_err(move |error| {
                warn!("network error: {error:?}");
                NetworkError::from_hyper_error(
                    &error,
                    override_manager.remove_certificate_failing_verification(host.as_str()),
                )
            })
            .await
    }
}

/// [HTTP fetch](https://fetch.spec.whatwg.org#http-fetch)
#[async_recursion]
#[allow(clippy::too_many_arguments)]
pub async fn http_fetch(
    fetch_params: &mut FetchParams,
    cache: &mut CorsCache,
    cors_flag: bool,
    cors_preflight_flag: bool,
    authentication_fetch_flag: bool,
    target: Target<'async_recursion>,
    done_chan: &mut DoneChannel,
    context: &FetchContext,
) -> Response {
    // This is a new async fetch, reset the channel we are waiting on
    *done_chan = None;
    // Step 1 Let request be fetchParams’s request.
    let request = &mut fetch_params.request;

    // Step 2
    // Let response and internalResponse be null.
    let mut response: Option<Response> = None;

    // Step 3
    if request.service_workers_mode == ServiceWorkersMode::All {
        // TODO: Substep 1
        // Set response to the result of invoking handle fetch for request.

        // Substep 2
        if let Some(ref res) = response {
            // Subsubstep 1
            // TODO: transmit body for request

            // Subsubstep 2
            // nothing to do, since actual_response is a function on response

            // Subsubstep 3
            if (res.response_type == ResponseType::Opaque && request.mode != RequestMode::NoCors) ||
                (res.response_type == ResponseType::OpaqueRedirect &&
                    request.redirect_mode != RedirectMode::Manual) ||
                (res.url_list.len() > 1 && request.redirect_mode != RedirectMode::Follow) ||
                res.is_network_error()
            {
                return Response::network_error(NetworkError::ConnectionFailure);
            }

            // Subsubstep 4
            // TODO: set response's CSP list on actual_response
        }
    }

    // Step 4
    if response.is_none() {
        // Substep 1
        if cors_preflight_flag {
            let method_cache_match = cache.match_method(request, request.method.clone());

            let method_mismatch = !method_cache_match &&
                (!is_cors_safelisted_method(&request.method) || request.use_cors_preflight);
            let header_mismatch = request.headers.iter().any(|(name, value)| {
                !cache.match_header(request, name) &&
                    !is_cors_safelisted_request_header(&name, &value)
            });

            // Sub-substep 1
            if method_mismatch || header_mismatch {
                let preflight_result = cors_preflight_fetch(request, cache, context).await;
                // Sub-substep 2
                if let Some(e) = preflight_result.get_network_error() {
                    return Response::network_error(e.clone());
                }
            }
        }

        // Substep 2
        if request.redirect_mode == RedirectMode::Follow {
            request.service_workers_mode = ServiceWorkersMode::None;
        }

        // Generally, we use a persistent connection, so we will also set other PerformanceResourceTiming
        //   attributes to this as well (domain_lookup_start, domain_lookup_end, connect_start, connect_end,
        //   secure_connection_start)
        context
            .timing
            .lock()
            .set_attribute(ResourceAttribute::RequestStart);

        let mut fetch_result = http_network_or_cache_fetch(
            fetch_params,
            authentication_fetch_flag,
            cors_flag,
            done_chan,
            context,
        )
        .await;

        // Substep 4
        if cors_flag && cors_check(&fetch_params.request, &fetch_result).is_err() {
            return Response::network_error(NetworkError::CorsGeneral);
        }

        fetch_result.return_internal = false;
        response = Some(fetch_result);
    }

    let request = &mut fetch_params.request;

    // response is guaranteed to be something by now
    let mut response = response.unwrap();

    // TODO: Step 5: cross-origin resource policy check

    // Step 6. If internalResponse’s status is a redirect status:
    if response
        .actual_response()
        .status
        .try_code()
        .is_some_and(is_redirect_status)
    {
        // Step 6.1. If internalResponse’s status is not 303, request’s body is non-null,
        // and the connection uses HTTP/2, then user agents may, and are even encouraged to,
        // transmit an RST_STREAM frame.
        if response.actual_response().status != StatusCode::SEE_OTHER {
            // TODO: send RST_STREAM frame
        }

        // Step 6.2. Switch on request’s redirect mode:
        response = match request.redirect_mode {
            // Step 6.2."error".1. Set response to a network error.
            RedirectMode::Error => Response::network_error(NetworkError::RedirectError),
            RedirectMode::Manual => {
                // Step 6.2."manual".1. If request’s mode is "navigate", then set fetchParams’s controller’s
                // next manual redirect steps to run HTTP-redirect fetch given fetchParams and response.
                if request.mode == RequestMode::Navigate {
                    // TODO: We don't implement Fetch controller. Instead, we update the location url
                    // of the response here and don't call `http_redirect_fetch`. That's get called later.
                    // Once we have a fetch controller here, we should update the code as specced.
                    let location_url =
                        location_url_for_response(&response, request.current_url().fragment());
                    response.actual_response_mut().location_url = location_url;
                    response
                } else {
                    // Step 6.2."manual".2. Otherwise, set response to an opaque-redirect filtered response whose internal response is internalResponse.
                    response.to_filtered(ResponseType::OpaqueRedirect)
                }
            },
            RedirectMode::Follow => {
                // set back to default
                response.return_internal = true;
                http_redirect_fetch(
                    fetch_params,
                    cache,
                    response,
                    cors_flag,
                    target,
                    done_chan,
                    context,
                )
                .await
            },
        };
    }

    // set back to default
    response.return_internal = true;
    context
        .timing
        .lock()
        .set_attribute(ResourceAttribute::RedirectCount(
            fetch_params.request.redirect_count as u16,
        ));

    response.resource_timing = Arc::clone(&context.timing);

    // Step 6
    response
}

// Convenience struct that implements Drop, for setting redirectEnd on function return
struct RedirectEndTimer(Option<Arc<Mutex<ResourceFetchTiming>>>);

impl RedirectEndTimer {
    fn neuter(&mut self) {
        self.0 = None;
    }
}

impl Drop for RedirectEndTimer {
    fn drop(&mut self) {
        let RedirectEndTimer(resource_fetch_timing_opt) = self;

        resource_fetch_timing_opt.as_ref().map_or((), |t| {
            t.lock()
                .set_attribute(ResourceAttribute::RedirectEnd(RedirectEndValue::Zero));
        })
    }
}

/// <https://fetch.spec.whatwg.org/#request-body-header-name>
static REQUEST_BODY_HEADER_NAMES: &[HeaderName] = &[
    CONTENT_ENCODING,
    CONTENT_LANGUAGE,
    CONTENT_LOCATION,
    CONTENT_TYPE,
];

/// <https://fetch.spec.whatwg.org/#concept-response-location-url>
fn location_url_for_response(
    response: &Response,
    request_fragment: Option<&str>,
) -> Option<Result<ServoUrl, String>> {
    // Step 1. If response’s status is not a redirect status, then return null.
    assert!(
        response
            .actual_response()
            .status
            .try_code()
            .is_some_and(is_redirect_status)
    );
    // Step 2. Let location be the result of extracting header list values given `Location` and response’s header list.
    let mut location = response
        .actual_response()
        .headers
        .get(header::LOCATION)
        .and_then(|header_value| {
            HeaderValue::to_str(header_value)
                .map(|location_string| {
                    // Step 3. If location is a header value, then set location to the result of parsing location with response’s URL.
                    ServoUrl::parse_with_base(response.actual_response().url(), location_string)
                        .map_err(|error| error.to_string())
                })
                .ok()
        });

    // Step 4. If location is a URL whose fragment is null, then set location’s fragment to requestFragment.
    if let Some(Ok(ref mut location)) = location {
        if location.fragment().is_none() {
            location.set_fragment(request_fragment);
        }
    }
    // Step 5. Return location.
    location
}

/// [HTTP redirect fetch](https://fetch.spec.whatwg.org#http-redirect-fetch)
#[async_recursion]
pub async fn http_redirect_fetch(
    fetch_params: &mut FetchParams,
    cache: &mut CorsCache,
    mut response: Response,
    cors_flag: bool,
    target: Target<'async_recursion>,
    done_chan: &mut DoneChannel,
    context: &FetchContext,
) -> Response {
    let mut redirect_end_timer = RedirectEndTimer(Some(context.timing.clone()));

    // Step 1. Let request be fetchParams’s request.
    let request = &mut fetch_params.request;

    // Step 2. Let internalResponse be response, if response is not a filtered response; otherwise response’s internal response.
    assert!(response.return_internal);

    // Step 3. Let locationURL be internalResponse’s location URL given request’s current URL’s fragment.
    let location_url = location_url_for_response(&response, request.current_url().fragment());
    response.actual_response_mut().location_url = location_url.clone();

    let location_url = match location_url {
        // Step 4. If locationURL is null, then return response.
        None => return response,
        // Step 5. If locationURL is failure, then return a network error.
        Some(Err(err)) => {
            return Response::network_error(NetworkError::ResourceLoadError(
                "Location URL parse failure: ".to_owned() + &err,
            ));
        },
        // Step 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network error.
        Some(Ok(url)) if !matches!(url.scheme(), "http" | "https") => {
            return Response::network_error(NetworkError::UnsupportedScheme);
        },
        Some(Ok(url)) => url,
    };

    // Step 1 of https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-fetchstart
    // TODO: check origin and timing allow check
    context
        .timing
        .lock()
        .set_attribute(ResourceAttribute::RedirectStart(
            RedirectStartValue::FetchStart,
        ));

    context
        .timing
        .lock()
        .set_attribute(ResourceAttribute::FetchStart);

    // start_time should equal redirect_start if nonzero; else fetch_start
    context
        .timing
        .lock()
        .set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));

    context
        .timing
        .lock()
        .set_attribute(ResourceAttribute::StartTime(
            ResourceTimeValue::RedirectStart,
        )); // updates start_time only if redirect_start is nonzero (implying TAO)

    // Step 7: If request’s redirect count is 20, then return a network error.
    if request.redirect_count >= 20 {
        return Response::network_error(NetworkError::TooManyRedirects);
    }

    // Step 8: Increase request’s redirect count by 1.
    request.redirect_count += 1;

    // Step 9. If request’s mode is "cors", locationURL includes credentials,
    // and request’s origin is not same origin with locationURL’s origin, then return a network error.
    let same_origin = match request.origin {
        Origin::Origin(ref origin) => *origin == location_url.origin(),
        Origin::Client => panic!(
            "Request origin should not be client for {}",
            request.current_url()
        ),
    };

    let has_credentials = has_credentials(&location_url);

    if request.mode == RequestMode::CorsMode && !same_origin && has_credentials {
        return Response::network_error(NetworkError::CorsCredentials);
    }

    if cors_flag && location_url.origin() != request.current_url().origin() {
        request.origin = Origin::Origin(ImmutableOrigin::new_opaque());
    }

    // Step 10. If request’s response tainting is "cors" and locationURL includes credentials, then return a network error.
    if cors_flag && has_credentials {
        return Response::network_error(NetworkError::CorsCredentials);
    }

    // Step 11: If internalResponse’s status is not 303, request’s body is non-null, and request’s
    // body’s source is null, then return a network error.
    if response.actual_response().status != StatusCode::SEE_OTHER &&
        request.body.as_ref().is_some_and(|b| b.source_is_null())
    {
        return Response::network_error(NetworkError::ConnectionFailure);
    }

    // Step 12. If one of the following is true
    if response
        .actual_response()
        .status
        .try_code()
        .is_some_and(|code| {
            // internalResponse’s status is 301 or 302 and request’s method is `POST`
            ((code == StatusCode::MOVED_PERMANENTLY || code == StatusCode::FOUND) &&
                request.method == Method::POST) ||
                // internalResponse’s status is 303 and request’s method is not `GET` or `HEAD`
                (code == StatusCode::SEE_OTHER &&
                    request.method != Method::HEAD &&
                    request.method != Method::GET)
        })
    {
        // Step 12.1. Set request’s method to `GET` and request’s body to null.
        request.method = Method::GET;
        request.body = None;
        // Step 12.2. For each headerName of request-body-header name, delete headerName from request’s header list.
        for name in REQUEST_BODY_HEADER_NAMES {
            request.headers.remove(name);
        }
    }

    // Step 13: If request’s current URL’s origin is not same origin with locationURL’s origin, then
    // for each headerName of CORS non-wildcard request-header name, delete headerName from
    // request’s header list.
    if location_url.origin() != request.current_url().origin() {
        // This list currently only contains the AUTHORIZATION header
        // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
        request.headers.remove(AUTHORIZATION);
    }

    // Step 14: If request’s body is non-null, then set request’s body to the body of the result of
    // safely extracting request’s body’s source.
    if let Some(body) = request.body.as_mut() {
        body.extract_source();
    }

    // Steps 15-17 relate to timing, which is not implemented 1:1 with the spec.

    // Step 18: Append locationURL to request’s URL list.
    request.url_list.push(location_url);

    // Step 19: Invoke set request’s referrer policy on redirect on request and internalResponse.
    set_requests_referrer_policy_on_redirect(request, response.actual_response());

    // Step 20: Let recursive be true.
    // Step 21: If request’s redirect mode is "manual", then...
    let recursive_flag = request.redirect_mode != RedirectMode::Manual;

    // Step 22: Return the result of running main fetch given fetchParams and recursive.
    let fetch_response = main_fetch(
        fetch_params,
        cache,
        recursive_flag,
        target,
        done_chan,
        context,
    )
    .await;

    // TODO: timing allow check
    context
        .timing
        .lock()
        .set_attribute(ResourceAttribute::RedirectEnd(
            RedirectEndValue::ResponseEnd,
        ));
    redirect_end_timer.neuter();

    fetch_response
}

/// [HTTP network or cache fetch](https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch)
#[async_recursion]
async fn http_network_or_cache_fetch(
    fetch_params: &mut FetchParams,
    authentication_fetch_flag: bool,
    cors_flag: bool,
    done_chan: &mut DoneChannel,
    context: &FetchContext,
) -> Response {
    // Step 2. Let httpFetchParams be null.
    let http_fetch_params: &mut FetchParams;
    let mut fetch_params_copy: FetchParams;

    // Step 3. Let httpRequest be null. (See step 8 for initialization)

    // Step 4. Let response be null.
    let mut response: Option<Response> = None;

    // Step 7. Let the revalidatingFlag be unset.
    let mut revalidating_flag = false;

    // TODO(#33616): Step 8. Run these steps, but abort when fetchParams is canceled:
    // Step 8.1. If request’s traversable for user prompts is "no-traversable"
    // and request’s redirect mode is "error", then set httpFetchParams to fetchParams and httpRequest to request.
    let http_request = if fetch_params.request.traversable_for_user_prompts ==
        TraversableForUserPrompts::NoTraversable &&
        fetch_params.request.redirect_mode == RedirectMode::Error
    {
        http_fetch_params = fetch_params;
        &mut http_fetch_params.request
    }
    // Step 8.2 Otherwise:
    else {
        // Step 8.2.1 - 8.2.3: Set httpRequest to a clone of request
        // and Set httpFetchParams to a copy of fetchParams.
        fetch_params_copy =
            std::mem::replace(fetch_params, FetchParams::new(fetch_params.request.clone()));
        http_fetch_params = &mut fetch_params_copy;

        &mut http_fetch_params.request
    };

    // Step 8.3: Let includeCredentials be true if one of:
    let include_credentials = match http_request.credentials_mode {
        // request’s credentials mode is "include"
        CredentialsMode::Include => true,
        // request’s credentials mode is "same-origin" and request’s response tainting is "basic"
        CredentialsMode::CredentialsSameOrigin
            if http_request.response_tainting == ResponseTainting::Basic =>
        {
            true
        },
        _ => false,
    };

    // Step 8.4: If Cross-Origin-Embedder-Policy allows credentials with request returns false, then
    // set includeCredentials to false.
    // TODO(#33616): Requires request's client object

    // Step 8.5 Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null;
    // otherwise null.
    let content_length = http_request
        .body
        .as_ref()
        .and_then(|body| body.len().map(|size| size as u64));

    // Step 8.6 Let contentLengthHeaderValue be null.
    let mut content_length_header_value = None;

    // Step 8.7 If httpRequest’s body is null and httpRequest’s method is `POST` or `PUT`,
    // then set contentLengthHeaderValue to `0`.
    if http_request.body.is_none() && matches!(http_request.method, Method::POST | Method::PUT) {
        content_length_header_value = Some(0);
    }

    // Step 8.8 If contentLength is non-null, then set contentLengthHeaderValue to contentLength,
    // serialized and isomorphic encoded.
    // NOTE: The header will later be serialized using HeaderMap::typed_insert
    if let Some(content_length) = content_length {
        content_length_header_value = Some(content_length);
    };

    // Step 8.9 If contentLengthHeaderValue is non-null, then append (`Content-Length`, contentLengthHeaderValue)
    // to httpRequest’s header list.
    if let Some(content_length_header_value) = content_length_header_value {
        http_request
            .headers
            .typed_insert(ContentLength(content_length_header_value));
    }

    // Step 8.10 If contentLength is non-null and httpRequest’s keepalive is true, then:
    if http_request.keep_alive {
        if let Some(content_length) = content_length {
            // Step 8.10.1. Let inflightKeepaliveBytes be 0.
            // Step 8.10.2. Let group be httpRequest’s client’s fetch group.
            // Step 8.10.3. Let inflightRecords be the set of fetch records
            // in group whose request’s keepalive is true and done flag is unset.
            let in_flight_keep_alive_bytes: u64 = context
                .in_flight_keep_alive_records
                .lock()
                .get(
                    &http_request
                        .pipeline_id
                        .expect("Must always set a pipeline ID for keep-alive requests"),
                )
                .map(|records| {
                    // Step 8.10.4. For each fetchRecord of inflightRecords:
                    // Step 8.10.4.1. Let inflightRequest be fetchRecord’s request.
                    // Step 8.10.4.2. Increment inflightKeepaliveBytes by inflightRequest’s body’s length.
                    records
                        .iter()
                        .map(|record| {
                            if record.request_id == http_request.id {
                                // Don't double count for this request. We have already added it in
                                // `fetch::methods::fetch_with_cors_cache`
                                0
                            } else {
                                record.keep_alive_body_length
                            }
                        })
                        .sum()
                })
                .unwrap_or_default();
            // Step 8.10.5. If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.
            if content_length + in_flight_keep_alive_bytes > 64 * 1024 {
                return Response::network_error(NetworkError::TooManyInFlightKeepAliveRequests);
            }
        }
    }

    // Step 8.11: If httpRequest’s referrer is a URL, then:
    match http_request.referrer {
        Referrer::ReferrerUrl(ref http_request_referrer) |
        Referrer::Client(ref http_request_referrer) => {
            // Step 8.11.1: Let referrerValue be httpRequest’s referrer, serialized and isomorphic
            // encoded.
            if let Ok(referer) = http_request_referrer.as_str().parse::<Referer>() {
                // Step 8.11.2: Append (`Referer`, referrerValue) to httpRequest’s header list.
                http_request.headers.typed_insert(referer);
            } else {
                // This error should only happen in cases where hyper and rust-url disagree
                // about how to parse a referer.
                // https://github.com/servo/servo/issues/24175
                error!("Failed to parse {} as referrer", http_request_referrer);
            }
        },
        _ => {},
    };

    // Step 8.12 Append a request `Origin` header for httpRequest.
    append_a_request_origin_header(http_request);

    // Step 8.13 Append the Fetch metadata headers for httpRequest.
    append_the_fetch_metadata_headers(http_request);

    // Step 8.14: If httpRequest’s initiator is "prefetch", then set a structured field value given
    // (`Sec-Purpose`, the token "prefetch") in httpRequest’s header list.
    if http_request.initiator == Initiator::Prefetch {
        if let Ok(value) = HeaderValue::from_str("prefetch") {
            http_request.headers.insert("Sec-Purpose", value);
        }
    }

    // Step 8.15: If httpRequest’s header list does not contain `User-Agent`, then user agents
    // should append (`User-Agent`, default `User-Agent` value) to httpRequest’s header list.
    if !http_request.headers.contains_key(header::USER_AGENT) {
        http_request
            .headers
            .typed_insert::<UserAgent>(context.user_agent.parse().unwrap());
    }

    // Steps 8.16 to 8.18
    match http_request.cache_mode {
        // Step 8.16: If httpRequest’s cache mode is "default" and httpRequest’s header list
        // contains `If-Modified-Since`, `If-None-Match`, `If-Unmodified-Since`, `If-Match`, or
        // `If-Range`, then set httpRequest’s cache mode to "no-store".
        CacheMode::Default if is_no_store_cache(&http_request.headers) => {
            http_request.cache_mode = CacheMode::NoStore;
        },

        // Note that the following steps (8.17 and 8.18) are being considered for removal:
        // https://github.com/whatwg/fetch/issues/722#issuecomment-1420264615

        // Step 8.17: If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache
        // cache-control header modification flag is unset, and httpRequest’s header list does not
        // contain `Cache-Control`, then append (`Cache-Control`, `max-age=0`) to httpRequest’s
        // header list.
        // TODO: Implement request's prevent no-cache cache-control header modification flag
        // https://fetch.spec.whatwg.org/#no-cache-prevent-cache-control
        CacheMode::NoCache if !http_request.headers.contains_key(header::CACHE_CONTROL) => {
            http_request
                .headers
                .typed_insert(CacheControl::new().with_max_age(Duration::from_secs(0)));
        },

        // Step 8.18: If httpRequest’s cache mode is "no-store" or "reload", then:
        CacheMode::Reload | CacheMode::NoStore => {
            // Step 8.18.1: If httpRequest’s header list does not contain `Pragma`, then append
            // (`Pragma`, `no-cache`) to httpRequest’s header list.
            if !http_request.headers.contains_key(header::PRAGMA) {
                http_request.headers.typed_insert(Pragma::no_cache());
            }

            // Step 8.18.2: If httpRequest’s header list does not contain `Cache-Control`, then
            // append (`Cache-Control`, `no-cache`) to httpRequest’s header list.
            if !http_request.headers.contains_key(header::CACHE_CONTROL) {
                http_request
                    .headers
                    .typed_insert(CacheControl::new().with_no_cache());
            }
        },

        _ => {},
    }

    // Step 8.19: If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`,
    // `identity`) to httpRequest’s header list.
    if http_request.headers.contains_key(header::RANGE) {
        if let Ok(value) = HeaderValue::from_str("identity") {
            http_request.headers.insert("Accept-Encoding", value);
        }
    }

    // Step 8.20: Modify httpRequest’s header list per HTTP. Do not append a given header if
    // httpRequest’s header list contains that header’s name.
    // `Accept`, `Accept-Charset`, and `Accept-Language` must not be included at this point.
    http_request.headers.remove(header::HOST);
    // unlike http_loader, we should not set the accept header here
    set_default_accept_encoding(&mut http_request.headers);

    let current_url = http_request.current_url();

    // Step 8.21: If includeCredentials is true, then:
    // TODO some of this step can't be implemented yet
    if include_credentials {
        // Substep 1
        // TODO http://mxr.mozilla.org/servo/source/components/net/http_loader.rs#504
        // XXXManishearth http_loader has block_cookies: support content blocking here too
        set_request_cookies(
            &current_url,
            &mut http_request.headers,
            &context.state.cookie_jar,
        );
        // Substep 2
        if !http_request.headers.contains_key(header::AUTHORIZATION) {
            // Substep 3
            let mut authorization_value = None;

            // Substep 4
            if let Some(basic) = auth_from_cache(&context.state.auth_cache, &current_url.origin()) {
                if !http_request.use_url_credentials || !has_credentials(&current_url) {
                    authorization_value = Some(basic);
                }
            }

            // Substep 5
            if authentication_fetch_flag &&
                authorization_value.is_none() &&
                has_credentials(&current_url)
            {
                authorization_value = Some(Authorization::basic(
                    current_url.username(),
                    current_url.password().unwrap_or(""),
                ));
            }

            // Substep 6
            if let Some(basic) = authorization_value {
                http_request.headers.typed_insert(basic);
            }
        }
    }

    // TODO(#33616) Step 8.22 If there’s a proxy-authentication entry, use it as appropriate.
    let should_wait = {
        // Enter critical section on cache entry.
        let mut cache_guard = block_for_cache_ready(
            context,
            http_request,
            done_chan,
            &mut revalidating_flag,
            &mut response,
        )
        .await;

        // TODO(#33616): Step 9. If aborted, then return the appropriate network error for fetchParams.

        // Step 10. If response is null, then:
        if response.is_none() {
            // Step 10.1 If httpRequest’s cache mode is "only-if-cached", then return a network error.
            if http_request.cache_mode == CacheMode::OnlyIfCached {
                // Exit critical section of cache entry.
                return Response::network_error(NetworkError::CacheError);
            }

            // Step 10.2 Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams,
            // includeCredentials, and isNewConnectionFetch.
            drop(cache_guard);
            let forward_response =
                http_network_fetch(http_fetch_params, include_credentials, done_chan, context)
                    .await;

            let http_request = &mut http_fetch_params.request;
            let request_key = CacheKey::new(http_request);
            cache_guard = context
                .state
                .http_cache
                .get_or_guard(request_key.clone())
                .await;
            // Step 10.3 If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399,
            // inclusive, invalidate appropriate stored responses in httpCache, as per the
            // "Invalidating Stored Responses" chapter of HTTP Caching, and set storedResponse to null.
            if forward_response.status.in_range(200..=399) && !http_request.method.is_safe() {
                if let Some(guard) = cache_guard.try_as_mut() {
                    invalidate(http_request, &forward_response, guard).await;
                }
                context
                    .state
                    .http_cache
                    .invalidate_related_urls(http_request, &forward_response, &request_key)
                    .await;
            }

            // Step 10.4 If the revalidatingFlag is set and forwardResponse’s status is 304, then:
            if revalidating_flag && forward_response.status == StatusCode::NOT_MODIFIED {
                // Ensure done_chan is None,
                // since the network response will be replaced by the revalidated stored one.
                *done_chan = None;
                if let Some(guard) = cache_guard.try_as_mut() {
                    response = refresh(http_request, forward_response.clone(), done_chan, guard);
                }

                if let Some(response) = &mut response {
                    response.cache_state = CacheState::Validated;
                }
            }

            // Step 10.5 If response is null, then:
            if response.is_none() {
                // Step 10.5.1 Set response to forwardResponse.
                let forward_response = response.insert(forward_response);

                // Per https://httpwg.org/specs/rfc9111.html#response.cacheability we must not cache responses
                // if the No-Store directive is present
                if http_request.cache_mode != CacheMode::NoStore {
                    // Step 10.5.2 Store httpRequest and forwardResponse in httpCache, as per the
                    //             "Storing Responses in Caches" chapter of HTTP Caching.
                    cache_guard.insert(http_request, forward_response);
                }
            }
            false
        } else {
            true
        }
    }; // Exit Critical Section on cache entry

    if should_wait {
        // If the cache constructed a response, and that is still receiving from the network,
        // we must wait for it to finish in case it is still receiving from the network.
        // Note: this means only the fetch from which the original network response originated
        // will be able to stream it; all others receive a cached response in one chunk.
        wait_for_inflight_requests(done_chan, &mut response).await;
    }

    let http_request = &mut http_fetch_params.request;
    let mut response = response.unwrap();

    // FIXME: The spec doesn't tell us to do this *here*, but if we don't do it then
    // tests fail. Where should we do it instead? See also #33615
    if http_request.response_tainting != ResponseTainting::CorsTainting &&
        cross_origin_resource_policy_check(http_request, &response) ==
            CrossOriginResourcePolicy::Blocked
    {
        return Response::network_error(NetworkError::CorsGeneral);
    }

    // TODO(#33616): Step 11. Set response’s URL list to a clone of httpRequest’s URL list.

    // Step 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.
    if http_request.headers.contains_key(RANGE) {
        response.range_requested = true;
    }

    // TODO(#33616): Step 13 Set response’s request-includes-credentials to includeCredentials.

    // Step 14. If response’s status is 401, httpRequest’s response tainting is not "cors",
    // includeCredentials is true, and request’s window is an environment settings object, then:
    // TODO(#33616): Figure out what to do with request window objects
    // NOTE: Requiring a WWW-Authenticate header here is ad-hoc, but seems to match what other browsers are
    // doing. See Step 14.1.
    if response.status.try_code() == Some(StatusCode::UNAUTHORIZED) &&
        !cors_flag &&
        include_credentials &&
        response.headers.contains_key(WWW_AUTHENTICATE)
    {
        // TODO: Step 14.1 Spec says requires testing on multiple WWW-Authenticate headers

        let request = &mut fetch_params.request;

        // Step 14.2 If request’s body is non-null, then:
        if request.body.is_some() {
            // TODO Implement body source
        }

        // Step 14.3 If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
        if !request.use_url_credentials || authentication_fetch_flag {
            let Some(credentials) = context
                .state
                .request_authentication(request, &response)
                .await
            else {
                return response;
            };

            if let Err(err) = request
                .current_url_mut()
                .set_username(&credentials.username)
            {
                error!("error setting username for url: {:?}", err);
                return response;
            };

            if let Err(err) = request
                .current_url_mut()
                .set_password(Some(&credentials.password))
            {
                error!("error setting password for url: {:?}", err);
                return response;
            };
        }

        // Make sure this is set to None,
        // since we're about to start a new `http_network_or_cache_fetch`.
        *done_chan = None;

        // Step 14.4 Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.
        response = http_network_or_cache_fetch(
            fetch_params,
            true, /* authentication flag */
            cors_flag,
            done_chan,
            context,
        )
        .await;
    }

    // Step 15. If response’s status is 407, then:
    if response.status == StatusCode::PROXY_AUTHENTICATION_REQUIRED {
        let request = &mut fetch_params.request;
        // Step 15.1 If request’s traversable for user prompts is "no-traversable", then return a network error.

        if request.traversable_for_user_prompts == TraversableForUserPrompts::NoTraversable {
            return Response::network_error(NetworkError::ResourceLoadError(
                "Can't find Window object".into(),
            ));
        }

        // (Step 15.2 does not exist, requires testing on Proxy-Authenticate headers)

        // TODO(#33616): Step 15.3 If fetchParams is canceled, then return
        // the appropriate network error for fetchParams.

        // Step 15.4 Prompt the end user as appropriate in request’s window
        // window and store the result as a proxy-authentication entry.
        let Some(credentials) = context
            .state
            .request_authentication(request, &response)
            .await
        else {
            return response;
        };

        // Store the credentials as a proxy-authentication entry.
        let entry = AuthCacheEntry {
            user_name: credentials.username,
            password: credentials.password,
        };
        {
            let mut auth_cache = context.state.auth_cache.write();
            let key = request.current_url().origin().ascii_serialization();
            auth_cache.entries.insert(key, entry);
        }

        // Make sure this is set to None,
        // since we're about to start a new `http_network_or_cache_fetch`.
        *done_chan = None;

        // Step 15.5 Set response to the result of running HTTP-network-or-cache fetch given fetchParams.
        response = http_network_or_cache_fetch(
            fetch_params,
            false, /* authentication flag */
            cors_flag,
            done_chan,
            context,
        )
        .await;
    }

    // TODO(#33616): Step 16. If all of the following are true:
    // * response’s status is 421
    // * isNewConnectionFetch is false
    // * request’s body is null, or request’s body is non-null and request’s body’s source is non-null
    // then: [..]

    // Step 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given realm.
    if authentication_fetch_flag {
        // TODO(#33616)
    }

    // Step 18. Return response.
    response
}
/// If the cache is not ready to construct a response, wait.
///
/// The cache is not ready if a previous fetch checked the cache, found nothing,
/// and moved on to a network fetch, and hasn't updated the cache yet with a pending resource.
///
/// Note that this is a different workflow from the one involving `wait_for_cached_response`.
/// That one happens when a fetch gets a cache hit, and the resource is pending completion from the network.
///
async fn block_for_cache_ready<'a>(
    context: &'a FetchContext,
    http_request: &mut Request,
    done_chan: &mut DoneChannel,
    revalidating_flag: &mut bool,
    response: &mut Option<Response>,
) -> CachedResourcesOrGuard<'a> {
    let entry_key = CacheKey::new(http_request);
    let guard_result = context.state.http_cache.get_or_guard(entry_key).await;

    match guard_result {
        CachedResourcesOrGuard::Guard(_) => {
            *done_chan = None;
        },
        CachedResourcesOrGuard::Value(ref cached_resources) => {
            // TODO(#33616): Step 8.23 Set httpCache to the result of determining the
            // HTTP cache partition, given httpRequest.
            // Step 8.25.1 Set storedResponse to the result of selecting a response from the httpCache,
            //              possibly needing validation, as per the "Constructing Responses from Caches"
            //              chapter of HTTP Caching, if any.
            let stored_response = construct_response(http_request, done_chan, cached_resources);
            // Step 8.25.2 If storedResponse is non-null, then:
            if let Some(response_from_cache) = stored_response {
                let response_headers = response_from_cache.response.headers.clone();
                // Substep 1, 2, 3, 4
                let (cached_response, needs_revalidation) =
                    match (http_request.cache_mode, &http_request.mode) {
                        (CacheMode::ForceCache, _) => (Some(response_from_cache.response), false),
                        (CacheMode::OnlyIfCached, &RequestMode::SameOrigin) => {
                            (Some(response_from_cache.response), false)
                        },
                        (CacheMode::OnlyIfCached, _) |
                        (CacheMode::NoStore, _) |
                        (CacheMode::Reload, _) => (None, false),
                        (_, _) => (
                            Some(response_from_cache.response),
                            response_from_cache.needs_validation,
                        ),
                    };

                if needs_revalidation {
                    *revalidating_flag = true;
                    // Substep 5
                    if let Some(http_date) = response_headers.typed_get::<LastModified>() {
                        let http_date: SystemTime = http_date.into();
                        http_request
                            .headers
                            .typed_insert(IfModifiedSince::from(http_date));
                    }
                    if let Some(entity_tag) = response_headers.get(header::ETAG) {
                        http_request
                            .headers
                            .insert(header::IF_NONE_MATCH, entity_tag.clone());
                    }
                } else {
                    // Substep 6
                    *response = cached_response;
                    if let Some(response) = response {
                        response.cache_state = CacheState::Local;
                    }
                }
                if response.is_none() {
                    // Ensure the done chan is not set if we're not using the cached response,
                    // as the cache might have set it to Some if it constructed a pending response.
                    *done_chan = None;
                }
            }
        },
    }
    guard_result
}

/// Wait for a cached response from channel.
/// Happens when a fetch gets a cache hit, and the resource is pending completion from the network.
async fn wait_for_inflight_requests(done_chan: &mut DoneChannel, response: &mut Option<Response>) {
    if let Some(ref mut ch) = *done_chan {
        // The cache constructed a response with a body of ResponseBody::Receiving.
        // We wait for the response in the cache to "finish",
        // with a body of either Done or Cancelled.
        assert!(response.is_some());

        loop {
            match ch.1.recv().await {
                Some(Data::Payload(_)) => {},
                Some(Data::Done) => break, // Return the full response as if it was initially cached as such.
                Some(Data::Cancelled) => {
                    // The response was cancelled while the fetch was ongoing.
                    break;
                },
                _ => panic!("HTTP cache should always send Done or Cancelled"),
            }
        }
    }
    // Set done_chan back to None, it's cache-related usefulness ends here.
    *done_chan = None;
}

/// <https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check>
///
/// This is obtained from [cross_origin_resource_policy_check]
#[derive(PartialEq)]
enum CrossOriginResourcePolicy {
    Allowed,
    Blocked,
}

// TODO(#33615): Judging from the name, this appears to be https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check,
//       but the steps aren't even close to the spec. Perhaps this needs to be rewritten?
fn cross_origin_resource_policy_check(
    request: &Request,
    response: &Response,
) -> CrossOriginResourcePolicy {
    // Step 1
    if request.mode != RequestMode::NoCors {
        return CrossOriginResourcePolicy::Allowed;
    }

    // Step 2
    let current_url_origin = request.current_url().origin();
    let same_origin = if let Origin::Origin(ref origin) = request.origin {
        *origin == request.current_url().origin()
    } else {
        false
    };

    if same_origin {
        return CrossOriginResourcePolicy::Allowed;
    }

    // Step 3
    let policy = response
        .headers
        .get(HeaderName::from_static("cross-origin-resource-policy"))
        .map(|h| h.to_str().unwrap_or(""))
        .unwrap_or("");

    // Step 4
    if policy == "same-origin" {
        return CrossOriginResourcePolicy::Blocked;
    }

    // Step 5
    if let Origin::Origin(ref request_origin) = request.origin {
        let schemeless_same_origin = is_schemelessy_same_site(request_origin, &current_url_origin);
        if schemeless_same_origin &&
            (request_origin.scheme() == Some("https") ||
                response.https_state == HttpsState::None)
        {
            return CrossOriginResourcePolicy::Allowed;
        }
    };

    // Step 6
    if policy == "same-site" {
        return CrossOriginResourcePolicy::Blocked;
    }

    CrossOriginResourcePolicy::Allowed
}

// Convenience struct that implements Done, for setting responseEnd on function return
struct ResponseEndTimer(Option<Arc<Mutex<ResourceFetchTiming>>>);

impl ResponseEndTimer {
    fn neuter(&mut self) {
        self.0 = None;
    }
}

impl Drop for ResponseEndTimer {
    fn drop(&mut self) {
        let ResponseEndTimer(resource_fetch_timing_opt) = self;

        resource_fetch_timing_opt.as_ref().map_or((), |t| {
            t.lock().set_attribute(ResourceAttribute::ResponseEnd);
        })
    }
}

/// [HTTP network fetch](https://fetch.spec.whatwg.org/#http-network-fetch)
async fn http_network_fetch(
    fetch_params: &mut FetchParams,
    credentials_flag: bool,
    done_chan: &mut DoneChannel,
    context: &FetchContext,
) -> Response {
    let mut response_end_timer = ResponseEndTimer(Some(context.timing.clone()));

    // Step 1: Let request be fetchParams’s request.
    let request = &mut fetch_params.request;

    // Step 2
    // TODO be able to create connection using current url's origin and credentials

    // Step 3
    // TODO be able to tell if the connection is a failure

    // Step 4
    // TODO: check whether the connection is HTTP/2

    // Step 5
    let url = request.current_url();
    let request_id = request.id.0.to_string();
    if log_enabled!(log::Level::Info) {
        info!("{:?} request for {}", request.method, url);
        for header in request.headers.iter() {
            debug!(" - {:?}", header);
        }
    }

    // XHR uses the default destination; other kinds of fetches (which haven't been implemented yet)
    // do not. Once we support other kinds of fetches we'll need to be more fine grained here
    // since things like image fetches are classified differently by devtools
    let is_xhr = request.destination == Destination::None;

    // The receiver will receive true if there has been an error streaming the request body.
    let (fetch_terminated_sender, mut fetch_terminated_receiver) = unbounded_channel();

    let body = request.body.as_ref().map(|body| body.clone_stream());

    if body.is_none() {
        // There cannot be an error streaming a non-existent body.
        // However in such a case the channel will remain unused
        // and drop inside `obtain_response`.
        // Send the confirmation now, ensuring the receiver will not dis-connect first.
        let _ = fetch_terminated_sender.send(false);
    }

    let browsing_context_id = request.target_webview_id.map(Into::into);

    let (res, msg) = match &request.mode {
        RequestMode::WebSocket {
            protocols,
            original_url: _,
        } => {
            // https://fetch.spec.whatwg.org/#websocket-opening-handshake

            let (resource_event_sender, dom_action_receiver) = {
                let mut websocket_chan = context.websocket_chan.as_ref().unwrap().lock();
                (
                    websocket_chan.sender.clone(),
                    websocket_chan.receiver.take().unwrap(),
                )
            };

            let mut tls_config = create_tls_config(
                context.ca_certificates.clone(),
                context.ignore_certificate_errors,
                context.state.override_manager.clone(),
            );
            tls_config.alpn_protocols = vec!["http/1.1".to_string().into()];

            let response = match start_websocket(
                context.state.clone(),
                resource_event_sender,
                protocols,
                request,
                tls_config,
                dom_action_receiver,
            )
            .await
            {
                Ok(response) => response,
                Err(error) => {
                    return Response::network_error(NetworkError::WebsocketConnectionFailure(
                        format!("{error:?}"),
                    ));
                },
            };

            let response = response.map(|r| match r {
                Some(body) => Full::from(body).map_err(|_| unreachable!()).boxed(),
                None => http_body_util::Empty::new()
                    .map_err(|_| unreachable!())
                    .boxed(),
            });
            (Decoder::detect(response, url.is_secure_scheme()), None)
        },
        _ => {
            let response_future = obtain_response(
                &context.state.client,
                &url,
                &request.method,
                &mut request.headers,
                body,
                request
                    .body
                    .as_ref()
                    .is_some_and(|body| body.source_is_null()),
                &request.pipeline_id,
                Some(&request_id),
                request.destination,
                is_xhr,
                context,
                fetch_terminated_sender,
                browsing_context_id,
            );

            // This will only get the headers, the body is read later
            let (res, msg) = match response_future.await {
                Ok(wrapped_response) => wrapped_response,
                Err(error) => return Response::network_error(error),
            };
            (res, msg)
        },
    };

    if log_enabled!(log::Level::Info) {
        debug!("{:?} response for {}", res.version(), url);
        for header in res.headers().iter() {
            debug!(" - {:?}", header);
        }
    }

    // Check if there was an error while streaming the request body.
    //
    match fetch_terminated_receiver.recv().await {
        Some(true) => return Response::network_error(NetworkError::ConnectionFailure),
        Some(false) => {},
        _ => warn!("Failed to receive confirmation request was streamed without error."),
    }

    let header_strings: Vec<&str> = res
        .headers()
        .get_all("Timing-Allow-Origin")
        .iter()
        .map(|header_value| header_value.to_str().unwrap_or(""))
        .collect();
    let wildcard_present = header_strings.contains(&"*");
    // The spec: https://www.w3.org/TR/resource-timing-2/#sec-timing-allow-origin
    // says that a header string is either an origin or a wildcard so we can just do a straight
    // check against the document origin
    let req_origin_in_timing_allow = header_strings
        .iter()
        .any(|header_str| match request.origin {
            SpecificOrigin(ref immutable_request_origin) => {
                *header_str == immutable_request_origin.ascii_serialization()
            },
            _ => false,
        });

    let is_same_origin = request.url_list.iter().all(|url| match request.origin {
        SpecificOrigin(ref immutable_request_origin) => url.origin() == *immutable_request_origin,
        _ => false,
    });

    if !(is_same_origin || req_origin_in_timing_allow || wildcard_present) {
        context.timing.lock().mark_timing_check_failed();
    }

    let timing = context.timing.lock().clone();
    let mut response = Response::new(url.clone(), timing);

    if let Some(handshake_info) = res.extensions().get::<TlsHandshakeInfo>() {
        let mut hsts_enabled = url
            .host_str()
            .is_some_and(|host| context.state.hsts_list.read().is_host_secure(host));

        if url.scheme() == "https" {
            if let Some(sts) = res.headers().typed_get::<StrictTransportSecurity>() {
                // max-age > 0 enables HSTS, max-age = 0 disables it (RFC 6797 Section 6.1.1)
                hsts_enabled = sts.max_age().as_secs() > 0;
            }
        }
        response.tls_security_info = Some(build_tls_security_info(handshake_info, hsts_enabled));
    }

    let status_text = res
        .extensions()
        .get::<ReasonPhrase>()
        .map(ReasonPhrase::as_bytes)
        .or_else(|| res.status().canonical_reason().map(str::as_bytes))
        .map(Vec::from)
        .unwrap_or_default();
    response.status = HttpStatus::new(res.status(), status_text);

    info!("got {:?} response for {:?}", res.status(), request.url());
    response.headers = res.headers().clone();
    response.referrer = request.referrer.to_url().cloned();
    response.referrer_policy = request.referrer_policy;

    let res_body = response.body.clone();

    // We're about to spawn a future to be waited on here
    let (done_sender, done_receiver) = unbounded_channel();
    *done_chan = Some((done_sender.clone(), done_receiver));

    let devtools_sender = context.devtools_chan.clone();
    let cancellation_listener = context.cancellation_listener.clone();
    if cancellation_listener.cancelled() {
        return Response::network_error(NetworkError::LoadCancelled);
    }

    *res_body.lock() = ResponseBody::Receiving(vec![]);
    let res_body2 = res_body.clone();

    if let Some(ref sender) = devtools_sender {
        if let Some(m) = msg {
            send_request_to_devtools(m, sender);
        }
    }

    let done_sender2 = done_sender.clone();
    let done_sender3 = done_sender.clone();
    let timing_ptr2 = context.timing.clone();
    let timing_ptr3 = context.timing.clone();
    let devtools_request = request.clone();
    let url1 = devtools_request.url();
    let url2 = url1.clone();

    let status = response.status.clone();
    let headers = response.headers.clone();
    let devtools_chan = context.devtools_chan.clone();

    spawn_task(
        res.into_body()
            .try_fold(res_body, move |res_body, chunk| {
                if cancellation_listener.cancelled() {
                    *res_body.lock() = ResponseBody::Done(vec![]);
                    let _ = done_sender.send(Data::Cancelled);
                    return future::ready(Err(std::io::Error::new(
                        std::io::ErrorKind::Interrupted,
                        "Fetch aborted",
                    )));
                }
                if let ResponseBody::Receiving(ref mut body) = *res_body.lock() {
                    let bytes = chunk;
                    body.extend_from_slice(&bytes);
                    let _ = done_sender.send(Data::Payload(bytes.to_vec()));
                }
                future::ready(Ok(res_body))
            })
            .and_then(move |res_body| {
                debug!("successfully finished response for {:?}", url1);
                let mut body = res_body.lock();
                let completed_body = match *body {
                    ResponseBody::Receiving(ref mut body) => std::mem::take(body),
                    _ => vec![],
                };
                let devtools_response_body = completed_body.clone();
                *body = ResponseBody::Done(completed_body);
                send_response_values_to_devtools(
                    Some(headers),
                    status,
                    Some(devtools_response_body),
                    CacheState::None,
                    &devtools_request,
                    devtools_chan,
                );
                timing_ptr2
                    .lock()
                    .set_attribute(ResourceAttribute::ResponseEnd);
                let _ = done_sender2.send(Data::Done);
                future::ready(Ok(()))
            })
            .map_err(move |error| {
                if let std::io::ErrorKind::InvalidData = error.kind() {
                    debug!("Content decompression error for {:?}", url2);
                    let _ = done_sender3.send(Data::Error(NetworkError::DecompressionError));
                    let mut body = res_body2.lock();

                    *body = ResponseBody::Done(vec![]);
                }
                debug!("finished response for {:?}", url2);
                let mut body = res_body2.lock();
                let completed_body = match *body {
                    ResponseBody::Receiving(ref mut body) => std::mem::take(body),
                    _ => vec![],
                };
                *body = ResponseBody::Done(completed_body);
                timing_ptr3
                    .lock()
                    .set_attribute(ResourceAttribute::ResponseEnd);
                let _ = done_sender3.send(Data::Done);
            }),
    );

    // TODO these substeps aren't possible yet
    // Substep 1

    // Substep 2

    response.https_state = match url.scheme() {
        "https" => HttpsState::Modern,
        _ => HttpsState::None,
    };

    // TODO Read request

    // Step 6-11
    // (needs stream bodies)

    // Step 13
    // TODO this step isn't possible yet (CSP)

    // Step 14, update the cached response, done via the shared response body.

    // TODO this step isn't possible yet
    // Step 15
    if credentials_flag {
        set_cookies_from_headers(&url, &response.headers, &context.state.cookie_jar);
    }
    context
        .state
        .hsts_list
        .write()
        .update_hsts_list_from_response(&url, &response.headers);

    // TODO these steps
    // Step 16
    // Substep 1
    // Substep 2
    // Sub-substep 1
    // Sub-substep 2
    // Sub-substep 3
    // Sub-substep 4
    // Substep 3

    // Step 16

    // Ensure we don't override "responseEnd" on successful return of this function
    response_end_timer.neuter();
    response
}

/// [CORS preflight fetch](https://fetch.spec.whatwg.org#cors-preflight-fetch)
async fn cors_preflight_fetch(
    request: &Request,
    cache: &mut CorsCache,
    context: &FetchContext,
) -> Response {
    // Step 1. Let preflight be a new request whose method is `OPTIONS`, URL list is a clone
    // of request’s URL list, initiator is request’s initiator, destination is request’s destination,
    // origin is request’s origin, referrer is request’s referrer, referrer policy is request’s
    // referrer policy, mode is "cors", and response tainting is "cors".
    let mut preflight = RequestBuilder::new(
        request.target_webview_id,
        request.current_url(),
        request.referrer.clone(),
    )
    .method(Method::OPTIONS)
    .origin(match &request.origin {
        Origin::Client => {
            unreachable!("We shouldn't get Client origin in cors_preflight_fetch.")
        },
        Origin::Origin(origin) => origin.clone(),
    })
    .pipeline_id(request.pipeline_id)
    .initiator(request.initiator)
    .destination(request.destination)
    .referrer_policy(request.referrer_policy)
    .mode(RequestMode::CorsMode)
    .response_tainting(ResponseTainting::CorsTainting)
    .policy_container(match &request.policy_container {
        RequestPolicyContainer::Client => {
            unreachable!("We should have a policy container for request in cors_preflight_fetch")
        },
        RequestPolicyContainer::PolicyContainer(policy_container) => policy_container.clone(),
    })
    .build();

    // Step 2. Append (`Accept`, `*/*`) to preflight’s header list.
    preflight
        .headers
        .insert(ACCEPT, HeaderValue::from_static("*/*"));

    // Step 3. Append (`Access-Control-Request-Method`, request’s method) to preflight’s header list.
    preflight
        .headers
        .typed_insert::<AccessControlRequestMethod>(AccessControlRequestMethod::from(
            request.method.clone(),
        ));

    // Step 4. Let headers be the CORS-unsafe request-header names with request’s header list.
    let headers = get_cors_unsafe_header_names(&request.headers);

    // Step 5 If headers is not empty, then:
    if !headers.is_empty() {
        // 5.1 Let value be the items in headers separated from each other by `,`
        // TODO(36451): replace this with typed_insert when headers fixes headers#207
        preflight.headers.insert(
            ACCESS_CONTROL_REQUEST_HEADERS,
            HeaderValue::from_bytes(itertools::join(headers.iter(), ",").as_bytes())
                .unwrap_or(HeaderValue::from_static("")),
        );
    }

    // Step 6. Let response be the result of running HTTP-network-or-cache fetch given a
    // new fetch params whose request is preflight.
    let mut fetch_params = FetchParams::new(preflight);
    let response =
        http_network_or_cache_fetch(&mut fetch_params, false, false, &mut None, context).await;

    // Step 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
    if cors_check(request, &response).is_ok() && response.status.code().is_success() {
        // Step 7.1 Let methods be the result of extracting header list values given
        // `Access-Control-Allow-Methods` and response’s header list.
        let mut methods = if response
            .headers
            .contains_key(header::ACCESS_CONTROL_ALLOW_METHODS)
        {
            match response.headers.typed_get::<AccessControlAllowMethods>() {
                Some(methods) => methods.iter().collect(),
                // Step 7.3 If either methods or headerNames is failure, return a network error.
                None => {
                    return Response::network_error(NetworkError::CorsAllowMethods);
                },
            }
        } else {
            vec![]
        };

        // Step 7.2 Let headerNames be the result of extracting header list values given
        // `Access-Control-Allow-Headers` and response’s header list.
        let header_names = if response
            .headers
            .contains_key(header::ACCESS_CONTROL_ALLOW_HEADERS)
        {
            match response.headers.typed_get::<AccessControlAllowHeaders>() {
                Some(names) => names.iter().collect(),
                // Step 7.3 If either methods or headerNames is failure, return a network error.
                None => {
                    return Response::network_error(NetworkError::CorsAllowHeaders);
                },
            }
        } else {
            vec![]
        };

        debug!(
            "CORS check: Allowed methods: {:?}, current method: {:?}",
            methods, request.method
        );

        // Step 7.4 If methods is null and request’s use-CORS-preflight flag is set,
        // then set methods to a new list containing request’s method.
        if methods.is_empty() && request.use_cors_preflight {
            methods = vec![request.method.clone()];
        }

        // Step 7.5 If request’s method is not in methods, request’s method is not a CORS-safelisted method,
        // and request’s credentials mode is "include" or methods does not contain `*`, then return a network error.
        if methods
            .iter()
            .all(|method| *method.as_str() != *request.method.as_ref()) &&
            !is_cors_safelisted_method(&request.method) &&
            (request.credentials_mode == CredentialsMode::Include ||
                methods.iter().all(|method| method.as_ref() != "*"))
        {
            return Response::network_error(NetworkError::CorsMethod);
        }

        debug!(
            "CORS check: Allowed headers: {:?}, current headers: {:?}",
            header_names, request.headers
        );

        // Step 7.6 If one of request’s header list’s names is a CORS non-wildcard request-header name
        // and is not a byte-case-insensitive match for an item in headerNames, then return a network error.
        if request.headers.iter().any(|(name, _)| {
            is_cors_non_wildcard_request_header_name(name) &&
                header_names.iter().all(|header_name| header_name != name)
        }) {
            return Response::network_error(NetworkError::CorsAuthorization);
        }

        // Step 7.7 For each unsafeName of the CORS-unsafe request-header names with request’s header list,
        // if unsafeName is not a byte-case-insensitive match for an item in headerNames and request’s credentials
        // mode is "include" or headerNames does not contain `*`, return a network error.
        let unsafe_names = get_cors_unsafe_header_names(&request.headers);
        let header_names_set: HashSet<&HeaderName> = HashSet::from_iter(header_names.iter());
        let header_names_contains_star = header_names
            .iter()
            .any(|header_name| header_name.as_str() == "*");
        for unsafe_name in unsafe_names.iter() {
            if !header_names_set.contains(unsafe_name) &&
                (request.credentials_mode == CredentialsMode::Include ||
                    !header_names_contains_star)
            {
                return Response::network_error(NetworkError::CorsHeaders);
            }
        }

        // Step 7.8 Let max-age be the result of extracting header list values given
        // `Access-Control-Max-Age` and response’s header list.
        let max_age: Option<Duration> = response
            .headers
            .typed_get::<AccessControlMaxAge>()
            .map(|acma| acma.into());

        // Step 7.9 If max-age is failure or null, then set max-age to 5.
        let max_age = max_age.unwrap_or(Duration::from_secs(5));

        // Step 7.10 If max-age is greater than an imposed limit on max-age, then set max-age to the imposed limit.
        // TODO: Need to define what an imposed limit on max-age is

        // Step 7.11 If the user agent does not provide for a cache, then return response.
        // NOTE: This can be ignored, we do have a CORS cache

        // Step 7.12 For each method in methods for which there is a method cache entry match using request,
        // set matching entry’s max-age to max-age.
        // Step 7.13 For each method in methods for which there is no method cache entry match using request,
        // create a new cache entry with request, max-age, method, and null.
        for method in &methods {
            cache.match_method_and_update(request, method.clone(), max_age);
        }

        // Step 7.14 For each headerName in headerNames for which there is a header-name cache entry match using request,
        // set matching entry’s max-age to max-age.
        // Step 7.15 For each headerName in headerNames for which there is no header-name cache entry match using request,
        // create a new cache entry with request, max-age, null, and headerName.
        for header_name in &header_names {
            cache.match_header_and_update(request, header_name, max_age);
        }

        // Step 7.16 Return response.
        return response;
    }

    // Step 8 Return a network error.
    Response::network_error(NetworkError::CorsGeneral)
}

/// [CORS check](https://fetch.spec.whatwg.org#concept-cors-check)
fn cors_check(request: &Request, response: &Response) -> Result<(), ()> {
    // Step 1. Let origin be the result of getting `Access-Control-Allow-Origin` from response’s header list.
    let Some(origins) =
        get_value_from_header_list(ACCESS_CONTROL_ALLOW_ORIGIN.as_str(), &response.headers)
    else {
        // Step 2. If origin is null, then return failure.
        return Err(());
    };
    let origin = origins.into_iter().map(char::from).collect::<String>();

    // Step 3. If request’s credentials mode is not "include" and origin is `*`, then return success.
    if request.credentials_mode != CredentialsMode::Include && origin == "*" {
        return Ok(());
    }

    // Step 4. If the result of byte-serializing a request origin with request is not origin, then return failure.
    if serialize_request_origin(request).to_string() != origin {
        return Err(());
    }

    // Step 5. If request’s credentials mode is not "include", then return success.
    if request.credentials_mode != CredentialsMode::Include {
        return Ok(());
    }

    // Step 6. Let credentials be the result of getting `Access-Control-Allow-Credentials` from response’s header list.
    let credentials = response
        .headers
        .typed_get::<AccessControlAllowCredentials>();

    // Step 7. If credentials is `true`, then return success.
    if credentials.is_some() {
        return Ok(());
    }

    // Step 8. Return failure.
    Err(())
}

fn has_credentials(url: &ServoUrl) -> bool {
    !url.username().is_empty() || url.password().is_some()
}

fn is_no_store_cache(headers: &HeaderMap) -> bool {
    headers.contains_key(header::IF_MODIFIED_SINCE) |
        headers.contains_key(header::IF_NONE_MATCH) |
        headers.contains_key(header::IF_UNMODIFIED_SINCE) |
        headers.contains_key(header::IF_MATCH) |
        headers.contains_key(header::IF_RANGE)
}

/// <https://fetch.spec.whatwg.org/#redirect-status>
fn is_redirect_status(status: StatusCode) -> bool {
    matches!(
        status,
        StatusCode::MOVED_PERMANENTLY |
            StatusCode::FOUND |
            StatusCode::SEE_OTHER |
            StatusCode::TEMPORARY_REDIRECT |
            StatusCode::PERMANENT_REDIRECT
    )
}

/// <https://fetch.spec.whatwg.org/#serializing-a-request-origin>
fn serialize_request_origin(request: &Request) -> headers::Origin {
    // Step 1. Assert: request’s origin is not "client".
    let Origin::Origin(origin) = &request.origin else {
        panic!("origin cannot be \"client\" at this point in time");
    };

    // Step 2. If request’s redirect-taint is not "same-origin", then return "null".
    if request.redirect_taint_for_request() != RedirectTaint::SameOrigin {
        return headers::Origin::NULL;
    }

    // Step 3. Return request’s origin, serialized.
    serialize_origin(origin)
}

/// Step 3 of <https://fetch.spec.whatwg.org/#serializing-a-request-origin>.
pub fn serialize_origin(origin: &ImmutableOrigin) -> headers::Origin {
    match origin {
        ImmutableOrigin::Opaque(_) => headers::Origin::NULL,
        ImmutableOrigin::Tuple(scheme, host, port) => {
            // Note: This must be kept in sync with `Origin::ascii_serialization()`, which does not
            // use the port number when a default port is used.
            let port = match (scheme.as_ref(), port) {
                ("http" | "ws", 80) | ("https" | "wss", 443) | ("ftp", 21) => None,
                _ => Some(*port),
            };

            // TODO: Ensure that hyper/servo don't disagree about valid origin headers
            headers::Origin::try_from_parts(scheme, &host.to_string(), port)
                .unwrap_or(headers::Origin::NULL)
        },
    }
}

/// <https://fetch.spec.whatwg.org/#append-a-request-origin-header>
fn append_a_request_origin_header(request: &mut Request) {
    // Step 1. Assert: request’s origin is not "client".
    let Origin::Origin(request_origin) = &request.origin else {
        panic!("origin cannot be \"client\" at this point in time");
    };

    // Step 2. Let serializedOrigin be the result of byte-serializing a request origin with request.
    let mut serialized_origin = serialize_request_origin(request);

    // Step 3. If request’s response tainting is "cors" or request’s mode is "websocket",
    //         then append (`Origin`, serializedOrigin) to request’s header list.
    if request.response_tainting == ResponseTainting::CorsTainting ||
        matches!(request.mode, RequestMode::WebSocket { .. })
    {
        request.headers.typed_insert(serialized_origin);
    }
    // Step 4. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
    else if !matches!(request.method, Method::GET | Method::HEAD) {
        // Step 4.1 If request’s mode is not "cors", then switch on request’s referrer policy:
        if request.mode != RequestMode::CorsMode {
            match request.referrer_policy {
                ReferrerPolicy::NoReferrer => {
                    // Set serializedOrigin to `null`.
                    serialized_origin = headers::Origin::NULL;
                },
                ReferrerPolicy::NoReferrerWhenDowngrade |
                ReferrerPolicy::StrictOrigin |
                ReferrerPolicy::StrictOriginWhenCrossOrigin => {
                    // If request’s origin is a tuple origin, its scheme is "https", and
                    // request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
                    if let ImmutableOrigin::Tuple(scheme, _, _) = &request_origin {
                        if scheme == "https" && request.current_url().scheme() != "https" {
                            serialized_origin = headers::Origin::NULL;
                        }
                    }
                },
                ReferrerPolicy::SameOrigin => {
                    // If request’s origin is not same origin with request’s current URL’s origin,
                    // then set serializedOrigin to `null`.
                    if *request_origin != request.current_url().origin() {
                        serialized_origin = headers::Origin::NULL;
                    }
                },
                _ => {
                    // Otherwise, do nothing.
                },
            };
        }

        // Step 4.2. Append (`Origin`, serializedOrigin) to request’s header list.
        request.headers.typed_insert(serialized_origin);
    }
}

/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-append-the-fetch-metadata-headers-for-a-request>
fn append_the_fetch_metadata_headers(r: &mut Request) {
    // Step 1. If r’s url is not an potentially trustworthy URL, return.
    if !r.url().is_potentially_trustworthy() {
        return;
    }

    // Step 2. Set the Sec-Fetch-Dest header for r.
    set_the_sec_fetch_dest_header(r);

    // Step 3. Set the Sec-Fetch-Mode header for r.
    set_the_sec_fetch_mode_header(r);

    // Step 4. Set the Sec-Fetch-Site header for r.
    set_the_sec_fetch_site_header(r);

    // Step 5. Set the Sec-Fetch-User header for r.
    set_the_sec_fetch_user_header(r);
}

/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-dest>
fn set_the_sec_fetch_dest_header(r: &mut Request) {
    // Step 1. Assert: r’s url is a potentially trustworthy URL.
    debug_assert!(r.url().is_potentially_trustworthy());

    // Step 2. Let header be a Structured Header whose value is a token.
    // Step 3. If r’s destination is the empty string, set header’s value to the string "empty".
    // Otherwise, set header’s value to r’s destination.
    let header = r.destination;

    // Step 4. Set a structured field value `Sec-Fetch-Dest`/header in r’s header list.
    r.headers.typed_insert(SecFetchDest(header));
}

/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-mode>
fn set_the_sec_fetch_mode_header(r: &mut Request) {
    // Step 1. Assert: r’s url is a potentially trustworthy URL.
    debug_assert!(r.url().is_potentially_trustworthy());

    // Step 2. Let header be a Structured Header whose value is a token.
    // Step 3. Set header’s value to r’s mode.
    let header = &r.mode;

    // Step 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
    r.headers.typed_insert(SecFetchMode::from(header));
}

/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-site>
fn set_the_sec_fetch_site_header(r: &mut Request) {
    // The webappsec spec seems to have a similar issue as
    // https://github.com/whatwg/fetch/issues/1773
    let Origin::Origin(request_origin) = &r.origin else {
        panic!("request origin cannot be \"client\" at this point")
    };

    // Step 1. Assert: r’s url is a potentially trustworthy URL.
    debug_assert!(r.url().is_potentially_trustworthy());

    // Step 2. Let header be a Structured Header whose value is a token.
    // Step 3. Set header’s value to same-origin.
    let mut header = SecFetchSite::SameOrigin;

    // TODO: Step 3. If r is a navigation request that was explicitly caused by a
    // user’s interaction with the user agent, then set header’s value to none.

    // Step 5. If header’s value is not none, then for each url in r’s url list:
    if header != SecFetchSite::None {
        for url in &r.url_list {
            // Step 5.1 If url is same origin with r’s origin, continue.
            if url.origin() == *request_origin {
                continue;
            }

            // Step 5.2 Set header’s value to cross-site.
            header = SecFetchSite::CrossSite;

            // Step 5.3 If r’s origin is not same site with url’s origin, then break.
            if !is_same_site(request_origin, &url.origin()) {
                break;
            }

            // Step 5.4 Set header’s value to same-site.
            header = SecFetchSite::SameSite;
        }
    }

    // Step 6. Set a structured field value `Sec-Fetch-Site`/header in r’s header list.
    r.headers.typed_insert(header);
}

/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-user>
fn set_the_sec_fetch_user_header(r: &mut Request) {
    // Step 1. Assert: r’s url is a potentially trustworthy URL.
    debug_assert!(r.url().is_potentially_trustworthy());

    // Step 2. If r is not a navigation request, or if r’s user-activation is false, return.
    // TODO user activation
    if !r.is_navigation_request() {
        return;
    }

    // Step 3. Let header be a Structured Header whose value is a token.
    // Step 4. Set header’s value to true.
    let header = SecFetchUser;

    // Step 5. Set a structured field value `Sec-Fetch-User`/header in r’s header list.
    r.headers.typed_insert(header);
}

/// <https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect>
fn set_requests_referrer_policy_on_redirect(request: &mut Request, response: &Response) {
    // Step 1: Let policy be the result of executing § 8.1 Parse a referrer policy from a
    // Referrer-Policy header on actualResponse.
    let referrer_policy: ReferrerPolicy = response
        .headers
        .typed_get::<headers::ReferrerPolicy>()
        .into();

    // Step 2: If policy is not the empty string, then set request’s referrer policy to policy.
    if referrer_policy != ReferrerPolicy::EmptyString {
        request.referrer_policy = referrer_policy;
    }
}