File: http_network_transaction.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2499 lines) | stat: -rw-r--r-- 93,543 bytes parent folder | download | duplicates (3)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/http_network_transaction.h"

#include <deque>
#include <queue>
#include <set>
#include <utility>
#include <vector>

#include "base/base64url.h"
#include "base/compiler_specific.h"
#include "base/feature_list.h"
#include "base/format_macros.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/values.h"
#include "build/build_config.h"
#include "net/base/address_family.h"
#include "net/base/auth.h"
#include "net/base/features.h"
#include "net/base/host_port_pair.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/load_timing_info.h"
#include "net/base/load_timing_internal_info.h"
#include "net/base/net_errors.h"
#include "net/base/proxy_chain.h"
#include "net/base/proxy_server.h"
#include "net/base/transport_info.h"
#include "net/base/upload_data_stream.h"
#include "net/base/url_util.h"
#include "net/cert/cert_status_flags.h"
#include "net/filter/filter_source_stream.h"
#include "net/filter/source_stream_type.h"
#include "net/http/bidirectional_stream_impl.h"
#include "net/http/http_auth.h"
#include "net/http/http_auth_controller.h"
#include "net/http/http_auth_handler.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_basic_stream.h"
#include "net/http/http_chunked_decoder.h"
#include "net/http/http_connection_info.h"
#include "net/http/http_log_util.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_server_properties.h"
#include "net/http/http_status_code.h"
#include "net/http/http_stream.h"
#include "net/http/http_stream_factory.h"
#include "net/http/http_stream_pool.h"
#include "net/http/http_util.h"
#include "net/http/transport_security_state.h"
#include "net/http/url_security_manager.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_util.h"
#include "net/proxy_resolution/proxy_info.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/next_proto.h"
#include "net/socket/transport_client_socket_pool.h"
#include "net/spdy/spdy_http_stream.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/ssl/ssl_info.h"
#include "net/ssl/ssl_private_key.h"
#include "third_party/abseil-cpp/absl/container/flat_hash_map.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/scheme_host_port.h"
#include "url/url_canon.h"

#if BUILDFLAG(ENABLE_REPORTING)
#include "net/network_error_logging/network_error_logging_service.h"
#include "net/reporting/reporting_header_parser.h"
#include "net/reporting/reporting_service.h"
#endif  // BUILDFLAG(ENABLE_REPORTING)

namespace net {

namespace {

// Max number of |retry_attempts| (excluding the initial request) after which
// we give up and show an error page.
const size_t kMaxRetryAttempts = 2;

// Max number of calls to RestartWith* allowed for a single connection. A single
// HttpNetworkTransaction should not signal very many restartable errors, but it
// may occur due to a bug (e.g. https://crbug.com/823387 or
// https://crbug.com/488043) or simply if the server or proxy requests
// authentication repeatedly. Although these calls are often associated with a
// user prompt, in other scenarios (remembered preferences, extensions,
// multi-leg authentication), they may be triggered automatically. To avoid
// looping forever, bound the number of restarts.
const size_t kMaxRestarts = 32;

// Returns true when Early Hints are allowed on the given protocol.
bool EarlyHintsAreAllowedOn(HttpConnectionInfo connection_info) {
  switch (connection_info) {
    case HttpConnectionInfo::kHTTP0_9:
    case HttpConnectionInfo::kHTTP1_0:
      return false;
    case HttpConnectionInfo::kHTTP1_1:
      return base::FeatureList::IsEnabled(features::kEnableEarlyHintsOnHttp11);
    default:
      // Implicitly allow HttpConnectionInfo::kUNKNOWN because this is the
      // default value and ConnectionInfo isn't always set.
      return true;
  }
}

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class WebSocketFallbackResult {
  kSuccessHttp11 = 0,
  kSuccessHttp2,
  kSuccessHttp11AfterFallback,
  kFailure,
  kFailureAfterFallback,
  kMaxValue = kFailureAfterFallback,
};

WebSocketFallbackResult CalculateWebSocketFallbackResult(
    int result,
    bool http_1_1_was_required,
    HttpConnectionInfoCoarse connection_info) {
  if (result == OK) {
    if (connection_info == HttpConnectionInfoCoarse::kHTTP2) {
      return WebSocketFallbackResult::kSuccessHttp2;
    }
    return http_1_1_was_required
               ? WebSocketFallbackResult::kSuccessHttp11AfterFallback
               : WebSocketFallbackResult::kSuccessHttp11;
  }

  return http_1_1_was_required ? WebSocketFallbackResult::kFailureAfterFallback
                               : WebSocketFallbackResult::kFailure;
}

void RecordWebSocketFallbackResult(int result,
                                   bool http_1_1_was_required,
                                   HttpConnectionInfoCoarse connection_info) {
  CHECK_NE(connection_info, HttpConnectionInfoCoarse::kQUIC);

  // `connection_info` could be kOTHER in tests.
  if (connection_info == HttpConnectionInfoCoarse::kOTHER) {
    return;
  }

  base::UmaHistogramEnumeration(
      "Net.WebSocket.FallbackResult",
      CalculateWebSocketFallbackResult(result, http_1_1_was_required,
                                       connection_info));
}

// TODO(https://crbug.com/413557424): Remove DuplicateRequestLogger, calling
// code, feature, and histograms once investigation is complete.

// Tracks all the URLs requested in the last 10 seconds and emit an histogram if
// any of them are repeated.
class DuplicateRequestLogger final {
 public:
  DuplicateRequestLogger() = default;

  DuplicateRequestLogger(const DuplicateRequestLogger&) = delete;
  DuplicateRequestLogger& operator=(const DuplicateRequestLogger&) = delete;

  // Adds `url` to the queue of recent requests. If it was already added within
  // the last 10 seconds, log a histogram.
  void AddAndMaybeLogRequest(const GURL& url, bool is_main_frame_navigation) {
    if (!expiry_timer_.IsRunning()) {
      StartTimer();
    }
    auto now = base::TimeTicks::Now();
    Entry& entry = entry_queue_.emplace(now, url);
    auto [hash_it, was_inserted] =
        entry_map_.try_emplace(entry.url.possibly_invalid_spec(), &entry);
    if (was_inserted) {
      // No existing match was found.
      return;
    }

    // There was a matching URL.
    auto [_, old_entry_ptr] = *hash_it;
    auto elapsed = now - old_entry_ptr->added_time;
    if (elapsed <= kMaximumDetectionInterval) {
      static constexpr std::string_view kBaseHistogramName =
          "Net.NetworkTransaction.DuplicateRequestInterval";
      DVLOG(3) << "Duplicate request for " << url << " after " << elapsed;
      base::UmaHistogramTimes(kBaseHistogramName, elapsed);
      if (is_main_frame_navigation) {
        base::UmaHistogramTimes(
            base::JoinString({kBaseHistogramName, "MainFrame"}, "."), elapsed);
      }
      if (IsGoogleHostWithAlpnH3(url.host_piece())) {
        base::UmaHistogramTimes(
            base::JoinString({kBaseHistogramName, "GoogleHost"}, "."), elapsed);
        if (is_main_frame_navigation) {
          base::UmaHistogramTimes(
              base::JoinString({kBaseHistogramName, "GoogleHost", "MainFrame"},
                               "."),
              elapsed);
        }
      }
    }

    // Replace the entry. It is not sufficient just to assign it, because we
    // need to change which string backs the string_view key.
    entry_map_.erase(hash_it);
    auto [ignored_it, emplace_succeeded] =
        entry_map_.emplace(entry.url.possibly_invalid_spec(), &entry);
    std::ignore = ignored_it;
    CHECK(emplace_succeeded);
  }

 private:
  // The maximum length of time between duplicate requests that will allow
  // them to be logged.
  static constexpr base::TimeDelta kMaximumDetectionInterval =
      base::Seconds(10);

  // The maximum time to wait between adding an entry to the queue and
  // removing it again. By making this larger than kMaximumDetectionPeriod we
  // can enable entries to be cleaned up in batches for greater efficiency.
  static constexpr base::TimeDelta kCleanupInterval =
      kMaximumDetectionInterval * 2;

  struct Entry {
    base::TimeTicks added_time;
    GURL url;
  };

  // Starts `expiry_timer_`, setting up the callback on the first call.
  void StartTimer() {
    if (expiry_timer_.user_task().is_null()) {
      // We need to set the callback on the first call. This use of
      // base::Unretained() is safe because the callback will not be called
      // after `expiry_timer_` is destroyed, and it is owned by this object.
      expiry_timer_.Start(
          FROM_HERE, kCleanupInterval,
          base::BindRepeating(&DuplicateRequestLogger::OnExpiryTimer,
                              base::Unretained(this)));
    } else {
      // Avoid calling Bind() again.
      expiry_timer_.Reset();
    }
  }

  // Cleans up old entries in `entry_queue_` and `entry_map_`.
  void OnExpiryTimer() {
    base::TimeTicks expiry_threshold =
        base::TimeTicks::Now() - kMaximumDetectionInterval;
    while (!entry_queue_.empty() &&
           entry_queue_.front().added_time < expiry_threshold) {
      const Entry& entry = entry_queue_.front();
      auto it = entry_map_.find(entry.url.possibly_invalid_spec());
      CHECK(it != entry_map_.end());
      auto [key, entry_ptr] = *it;
      CHECK(KeyUsesCorrectBackingStore(key, entry_ptr));
      if (entry_ptr == &entry) {
        entry_map_.erase(it);
      }
      entry_queue_.pop();
    }
    if (!entry_queue_.empty()) {
      expiry_timer_.Reset();
    }
  }

  // Keys in `entry_map_` must always be backed by a string owned by the value.
  // This method checks that invariant.
  bool KeyUsesCorrectBackingStore(std::string_view key, Entry* value) {
    return key.data() == value->url.possibly_invalid_spec().data();
  }

  // `entry_queue_` is a std::deque and not a base::circular_deque because it
  // requires pointer stability.
  std::queue<Entry, std::deque<Entry>> entry_queue_;

  // To avoid keeping duplicate strings in memory, the map from URL to Entry
  // uses a string_view key. The keys in `entry_map_` point to memory owned by
  // `entry_queue_`, so Entry objects in `entry_queue_` must always be inserted
  // before `entry_map_` and removed afterwards. The backing storage for the key
  // must always belong to the Entry pointed to by the value.
  absl::flat_hash_map<std::string_view, raw_ptr<Entry>> entry_map_;

  // The timer only runs when `entry_queue_` is non-empty.
  base::RetainingOneShotTimer expiry_timer_;
};

// If an identical URL to `url` has been requested in the last 10 seconds,
// record the time passed since it was last seen to the
// "Net.NetworkTransaction.DuplicateRequestInterval" histogram.
void LogIfDuplicateRequest(const GURL& url, bool is_main_frame_navigation) {
  static base::NoDestructor<DuplicateRequestLogger> logger_;
  logger_->AddAndMaybeLogRequest(url, is_main_frame_navigation);
}

// When this feature is enabled, GET requests with identical URLs within 10
// seconds will result in the Net.NetworkTransaction.DuplicateRequestInterval
// histogram being recorded.
BASE_FEATURE(kLogDuplicateRequests,
             "LogDuplicateRequests",
             base::FEATURE_DISABLED_BY_DEFAULT);

}  // namespace

const int HttpNetworkTransaction::kDrainBodyBufferSize;

HttpNetworkTransaction::HttpNetworkTransaction(RequestPriority priority,
                                               HttpNetworkSession* session)
    : io_callback_(base::BindRepeating(&HttpNetworkTransaction::OnIOComplete,
                                       base::Unretained(this))),
      session_(session),
      priority_(priority) {}

HttpNetworkTransaction::~HttpNetworkTransaction() {
#if BUILDFLAG(ENABLE_REPORTING)
  // If no error or success report has been generated yet at this point, then
  // this network transaction was prematurely cancelled.
  GenerateNetworkErrorLoggingReport(ERR_ABORTED);
#endif  // BUILDFLAG(ENABLE_REPORTING)

  if (stream_.get()) {
    // TODO(mbelshe): The stream_ should be able to compute whether or not the
    //                stream should be kept alive.  No reason to compute here
    //                and pass it in.
    if (!stream_->CanReuseConnection() || next_state_ != STATE_NONE ||
        close_connection_on_destruction_) {
      stream_->Close(true /* not reusable */);
    } else if (stream_->IsResponseBodyComplete()) {
      // If the response body is complete, we can just reuse the socket.
      stream_->Close(false /* reusable */);
    } else {
      // Otherwise, we try to drain the response body.
      HttpStream* stream = stream_.release();
      stream->Drain(session_);
    }
  }
  if (request_ && request_->upload_data_stream)
    request_->upload_data_stream->Reset();  // Invalidate pending callbacks.
}

int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
                                  CompletionOnceCallback callback,
                                  const NetLogWithSource& net_log) {
  TRACE_EVENT("net", "HttpNetworkTransaction::Start",
              NetLogWithSourceToFlow(net_log), "url", request_info->url);

  if (session_->power_suspended()) {
    return ERR_NETWORK_IO_SUSPENDED;
  }

  if (request_info->load_flags & LOAD_ONLY_FROM_CACHE) {
    return ERR_CACHE_MISS;
  }

  DCHECK(request_info->traffic_annotation.is_valid());
  DCHECK(request_info->IsConsistent());
  net_log_ = net_log;
  request_ = request_info;
  url_ = request_->url;
  network_anonymization_key_ = request_->network_anonymization_key;
  start_timeticks_ = base::TimeTicks::Now();
#if BUILDFLAG(ENABLE_REPORTING)
  // Store values for later use in NEL report generation.
  request_method_ = request_->method;
  if (std::optional<std::string> header =
          request_->extra_headers.GetHeader(HttpRequestHeaders::kReferer);
      header) {
    request_referrer_.swap(header.value());
  }
  if (std::optional<std::string> header =
          request_->extra_headers.GetHeader(HttpRequestHeaders::kUserAgent);
      header) {
    request_user_agent_.swap(header.value());
  }
  request_reporting_upload_depth_ = request_->reporting_upload_depth;
#endif  // BUILDFLAG(ENABLE_REPORTING)

  if (request_->idempotency == IDEMPOTENT ||
      (request_->idempotency == DEFAULT_IDEMPOTENCY &&
       HttpUtil::IsMethodSafe(request_info->method))) {
    can_send_early_data_ = true;
  }

  if (request_->load_flags & LOAD_PREFETCH) {
    response_.unused_since_prefetch = true;
  }

  if (request_->load_flags & LOAD_RESTRICTED_PREFETCH_FOR_MAIN_FRAME) {
    DCHECK(response_.unused_since_prefetch);
    response_.restricted_prefetch = true;
  }

  next_state_ = STATE_CREATE_STREAM;
  int rv = DoLoop(OK);
  if (rv == ERR_IO_PENDING)
    callback_ = std::move(callback);

  // This always returns ERR_IO_PENDING because DoCreateStream() does, but
  // GenerateNetworkErrorLoggingReportIfError() should be called here if any
  // other Error can be returned.
  DCHECK_EQ(rv, ERR_IO_PENDING);
  return rv;
}

int HttpNetworkTransaction::RestartIgnoringLastError(
    CompletionOnceCallback callback) {
  DCHECK(!stream_.get());
  DCHECK(!stream_request_.get());
  DCHECK_EQ(STATE_NONE, next_state_);

  TRACE_EVENT("net", "HttpNetworkTransaction::RestartIgnoringLastError",
              NetLogWithSourceToFlow(net_log_));

  if (!CheckMaxRestarts())
    return ERR_TOO_MANY_RETRIES;

  next_state_ = STATE_CREATE_STREAM;

  int rv = DoLoop(OK);
  if (rv == ERR_IO_PENDING)
    callback_ = std::move(callback);

  // This always returns ERR_IO_PENDING because DoCreateStream() does, but
  // GenerateNetworkErrorLoggingReportIfError() should be called here if any
  // other Error can be returned.
  DCHECK_EQ(rv, ERR_IO_PENDING);
  return rv;
}

int HttpNetworkTransaction::RestartWithCertificate(
    scoped_refptr<X509Certificate> client_cert,
    scoped_refptr<SSLPrivateKey> client_private_key,
    CompletionOnceCallback callback) {
  // When we receive ERR_SSL_CLIENT_AUTH_CERT_NEEDED, we always tear down
  // existing streams and stream requests to force a new connection.
  DCHECK(!stream_request_.get());
  DCHECK(!stream_.get());
  DCHECK_EQ(STATE_NONE, next_state_);

  TRACE_EVENT("net", "HttpNetworkTransaction::RestartWithCertificate",
              NetLogWithSourceToFlow(net_log_));

  if (!CheckMaxRestarts())
    return ERR_TOO_MANY_RETRIES;

  // Add the credentials to the client auth cache. The next stream request will
  // then pick them up.
  session_->ssl_client_context()->SetClientCertificate(
      response_.cert_request_info->host_and_port, std::move(client_cert),
      std::move(client_private_key));

  if (!response_.cert_request_info->is_proxy)
    configured_client_cert_for_server_ = true;

  // Reset the other member variables.
  // Note: this is necessary only with SSL renegotiation.
  ResetStateForRestart();
  next_state_ = STATE_CREATE_STREAM;
  int rv = DoLoop(OK);
  if (rv == ERR_IO_PENDING)
    callback_ = std::move(callback);

  // This always returns ERR_IO_PENDING because DoCreateStream() does, but
  // GenerateNetworkErrorLoggingReportIfError() should be called here if any
  // other Error can be returned.
  DCHECK_EQ(rv, ERR_IO_PENDING);
  return rv;
}

int HttpNetworkTransaction::RestartWithAuth(const AuthCredentials& credentials,
                                            CompletionOnceCallback callback) {
  TRACE_EVENT("net", "HttpNetworkTransaction::RestartWithAuth",
              NetLogWithSourceToFlow(net_log_));

  if (!CheckMaxRestarts())
    return ERR_TOO_MANY_RETRIES;

  HttpAuth::Target target = pending_auth_target_;
  if (target == HttpAuth::AUTH_NONE) {
    NOTREACHED();
  }
  pending_auth_target_ = HttpAuth::AUTH_NONE;

  auth_controllers_[target]->ResetAuth(credentials);

  DCHECK(callback_.is_null());

  int rv = OK;
  if (target == HttpAuth::AUTH_PROXY && establishing_tunnel_) {
    // In this case, we've gathered credentials for use with proxy
    // authentication of a tunnel.
    DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
    DCHECK(stream_request_ != nullptr);
    auth_controllers_[target] = nullptr;
    ResetStateForRestart();
    rv = stream_request_->RestartTunnelWithProxyAuth();
  } else {
    // In this case, we've gathered credentials for the server or the proxy
    // but it is not during the tunneling phase.
    DCHECK(stream_request_ == nullptr);
    PrepareForAuthRestart(target);
    rv = DoLoop(OK);
    // Note: If an error is encountered while draining the old response body, no
    // Network Error Logging report will be generated, because the error was
    // with the old request, which will already have had a NEL report generated
    // for it due to the auth challenge (so we don't report a second error for
    // that request).
  }

  if (rv == ERR_IO_PENDING)
    callback_ = std::move(callback);
  return rv;
}

void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
  DCHECK(HaveAuth(target));
  DCHECK(!stream_request_.get());

  // Authorization schemes incompatible with HTTP/2 are unsupported for proxies.
  if (target == HttpAuth::AUTH_SERVER &&
      auth_controllers_[target]->NeedsHTTP11()) {
    // SetHTTP11Requited requires URLs be rewritten first, if there are any
    // applicable rules.
    GURL rewritten_url = request_->url;
    session_->params().host_mapping_rules.RewriteUrl(rewritten_url);

    session_->http_server_properties()->SetHTTP11Required(
        url::SchemeHostPort(rewritten_url), network_anonymization_key_);
    stream_->SetHTTP11Required();
  }

  bool keep_alive = false;
  // Even if the server says the connection is keep-alive, we have to be
  // able to find the end of each response in order to reuse the connection.
  if (stream_->CanReuseConnection()) {
    // If the response body hasn't been completely read, we need to drain
    // it first.
    if (!stream_->IsResponseBodyComplete()) {
      next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
      read_buf_ = base::MakeRefCounted<IOBufferWithSize>(
          kDrainBodyBufferSize);  // A bit bucket.
      read_buf_len_ = kDrainBodyBufferSize;
      return;
    }
    keep_alive = true;
  }

  // We don't need to drain the response body, so we act as if we had drained
  // the response body.
  DidDrainBodyForAuthRestart(keep_alive);
}

void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive) {
  DCHECK(!stream_request_.get());

  if (stream_.get()) {
    total_received_bytes_ += stream_->GetTotalReceivedBytes();
    total_sent_bytes_ += stream_->GetTotalSentBytes();
    std::unique_ptr<HttpStream> new_stream;
    if (keep_alive && stream_->CanReuseConnection()) {
      // We should call connection_->set_idle_time(), but this doesn't occur
      // often enough to be worth the trouble.
      stream_->SetConnectionReused();
      new_stream = stream_->RenewStreamForAuth();
    }

    if (!new_stream) {
      // Close the stream and mark it as not_reusable.  Even in the
      // keep_alive case, we've determined that the stream_ is not
      // reusable if new_stream is NULL.
      TRACE_EVENT("net", "HttpNetworkTransaction::DidDrainBodyForAuthRestart",
                  NetLogWithSourceToFlow(net_log_));
      stream_->Close(true);
      next_state_ = STATE_CREATE_STREAM;
    } else {
      // Renewed streams shouldn't carry over sent or received bytes.
      DCHECK_EQ(0, new_stream->GetTotalReceivedBytes());
      DCHECK_EQ(0, new_stream->GetTotalSentBytes());
      next_state_ = STATE_CONNECTED_CALLBACK;
    }
    stream_ = std::move(new_stream);
  }

  // Reset the other member variables.
  ResetStateForAuthRestart();
}

bool HttpNetworkTransaction::IsReadyToRestartForAuth() {
  return pending_auth_target_ != HttpAuth::AUTH_NONE &&
      HaveAuth(pending_auth_target_);
}

int HttpNetworkTransaction::Read(IOBuffer* buf,
                                 int buf_len,
                                 CompletionOnceCallback callback) {
  DCHECK(buf);
  DCHECK_LT(0, buf_len);

  scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
  if (headers_valid_ && headers.get() && stream_request_.get()) {
    // We're trying to read the body of the response but we're still trying
    // to establish an SSL tunnel through an HTTP proxy.  We can't read these
    // bytes when establishing a tunnel because they might be controlled by
    // an active network attacker.  We don't worry about this for HTTP
    // because an active network attacker can already control HTTP sessions.
    // We reach this case when the user cancels a 407 proxy auth prompt.  We
    // also don't worry about this for an HTTPS Proxy, because the
    // communication with the proxy is secure.
    // See http://crbug.com/8473.
    DCHECK(proxy_info_.AnyProxyInChain(
        [](const ProxyServer& s) { return s.is_http_like(); }));
    DCHECK_EQ(headers->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED);
    return ERR_TUNNEL_CONNECTION_FAILED;
  }

  // Are we using SPDY or HTTP?
  next_state_ = STATE_READ_BODY;

  read_buf_ = buf;
  read_buf_len_ = buf_len;

  int rv = DoLoop(OK);
  if (rv == ERR_IO_PENDING)
    callback_ = std::move(callback);
  return rv;
}

void HttpNetworkTransaction::StopCaching() {}

int64_t HttpNetworkTransaction::GetTotalReceivedBytes() const {
  int64_t total_received_bytes = total_received_bytes_;
  if (stream_)
    total_received_bytes += stream_->GetTotalReceivedBytes();
  return total_received_bytes;
}

int64_t HttpNetworkTransaction::GetTotalSentBytes() const {
  int64_t total_sent_bytes = total_sent_bytes_;
  if (stream_)
    total_sent_bytes += stream_->GetTotalSentBytes();
  return total_sent_bytes;
}

int64_t HttpNetworkTransaction::GetReceivedBodyBytes() const {
  return received_body_bytes_;
}

void HttpNetworkTransaction::DoneReading() {}

const HttpResponseInfo* HttpNetworkTransaction::GetResponseInfo() const {
  return &response_;
}

LoadState HttpNetworkTransaction::GetLoadState() const {
  // TODO(wtc): Define a new LoadState value for the
  // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
  switch (next_state_) {
    case STATE_CREATE_STREAM:
      return LOAD_STATE_WAITING_FOR_DELEGATE;
    case STATE_CREATE_STREAM_COMPLETE:
      return stream_request_->GetLoadState();
    case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
    case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
    case STATE_SEND_REQUEST_COMPLETE:
      return LOAD_STATE_SENDING_REQUEST;
    case STATE_READ_HEADERS_COMPLETE:
      return LOAD_STATE_WAITING_FOR_RESPONSE;
    case STATE_READ_BODY_COMPLETE:
      return LOAD_STATE_READING_RESPONSE;
    default:
      return LOAD_STATE_IDLE;
  }
}

bool HttpNetworkTransaction::GetLoadTimingInfo(
    LoadTimingInfo* load_timing_info) const {
  if (!stream_ || !stream_->GetLoadTimingInfo(load_timing_info))
    return false;

  // If `dns_resolution_{start/end}_time_override_` are set, and they are older
  // than `domain_lookup_{start/end}` of the `stream_`, use the overrides.
  // TODO(crbug.com/40812426): Remove this when we launch Happy Eyeballs v3.
  if (!dns_resolution_start_time_override_.is_null() &&
      !dns_resolution_end_time_override_.is_null() &&
      (dns_resolution_start_time_override_ <
       load_timing_info->connect_timing.domain_lookup_start) &&
      (dns_resolution_end_time_override_ <
       load_timing_info->connect_timing.domain_lookup_end)) {
    load_timing_info->connect_timing.domain_lookup_start =
        dns_resolution_start_time_override_;
    load_timing_info->connect_timing.domain_lookup_end =
        dns_resolution_end_time_override_;
  }

  load_timing_info->proxy_resolve_start =
      proxy_info_.proxy_resolve_start_time();
  load_timing_info->proxy_resolve_end = proxy_info_.proxy_resolve_end_time();
  load_timing_info->send_start = send_start_time_;
  load_timing_info->send_end = send_end_time_;
  return true;
}

void HttpNetworkTransaction::PopulateLoadTimingInternalInfo(
    LoadTimingInternalInfo* load_timing_internal_info) const {
  if (!create_stream_start_time_.is_null() &&
      !create_stream_end_time_.is_null()) {
    CHECK_LE(create_stream_start_time_, create_stream_end_time_);
    load_timing_internal_info->create_stream_delay =
        create_stream_end_time_ - create_stream_start_time_;
  }
  if (!connected_callback_start_time_.is_null() &&
      !connected_callback_end_time_.is_null()) {
    CHECK_LE(connected_callback_start_time_, connected_callback_end_time_);
    load_timing_internal_info->connected_callback_delay =
        connected_callback_end_time_ - connected_callback_start_time_;
  }
  if (!initialize_stream_start_time_.is_null() &&
      !initialize_stream_end_time_.is_null()) {
    CHECK_LE(initialize_stream_start_time_, initialize_stream_end_time_);
    load_timing_internal_info->initialize_stream_delay =
        initialize_stream_end_time_ - initialize_stream_start_time_;
  }
}

bool HttpNetworkTransaction::GetRemoteEndpoint(IPEndPoint* endpoint) const {
  if (remote_endpoint_.address().empty())
    return false;

  *endpoint = remote_endpoint_;
  return true;
}

void HttpNetworkTransaction::PopulateNetErrorDetails(
    NetErrorDetails* details) const {
  *details = net_error_details_;
  if (stream_)
    stream_->PopulateNetErrorDetails(details);
}

void HttpNetworkTransaction::SetPriority(RequestPriority priority) {
  priority_ = priority;

  if (stream_request_)
    stream_request_->SetPriority(priority);
  if (stream_)
    stream_->SetPriority(priority);

  // The above call may have resulted in deleting |*this|.
}

void HttpNetworkTransaction::SetWebSocketHandshakeStreamCreateHelper(
    WebSocketHandshakeStreamBase::CreateHelper* create_helper) {
  websocket_handshake_stream_base_create_helper_ = create_helper;
}

void HttpNetworkTransaction::SetConnectedCallback(
    const ConnectedCallback& callback) {
  connected_callback_ = callback;
}

void HttpNetworkTransaction::SetRequestHeadersCallback(
    RequestHeadersCallback callback) {
  DCHECK(!stream_);
  request_headers_callback_ = std::move(callback);
}

void HttpNetworkTransaction::SetEarlyResponseHeadersCallback(
    ResponseHeadersCallback callback) {
  DCHECK(!stream_);
  early_response_headers_callback_ = std::move(callback);
}

void HttpNetworkTransaction::SetResponseHeadersCallback(
    ResponseHeadersCallback callback) {
  DCHECK(!stream_);
  response_headers_callback_ = std::move(callback);
}

void HttpNetworkTransaction::SetModifyRequestHeadersCallback(
    base::RepeatingCallback<void(HttpRequestHeaders*)> callback) {
  modify_headers_callbacks_ = std::move(callback);
}

void HttpNetworkTransaction::SetIsSharedDictionaryReadAllowedCallback(
    base::RepeatingCallback<bool()> callback) {
  // This method should not be called for this class.
  NOTREACHED();
}

void HttpNetworkTransaction::ResumeAfterConnected(int result) {
  DCHECK_EQ(next_state_, STATE_CONNECTED_CALLBACK_COMPLETE);

  connected_callback_end_time_ = base::TimeTicks::Now();
  CHECK(!connected_callback_start_time_.is_null());
  CHECK_LE(connected_callback_start_time_, connected_callback_end_time_);
  base::UmaHistogramTimes(
      "Net.NetworkTransaction.ConnectedCallbackDelay",
      connected_callback_end_time_ - connected_callback_start_time_);

  OnIOComplete(result);
}

void HttpNetworkTransaction::CloseConnectionOnDestruction() {
  close_connection_on_destruction_ = true;
}

bool HttpNetworkTransaction::IsMdlMatchForMetrics() const {
  return proxy_info_.is_mdl_match();
}

void HttpNetworkTransaction::OnStreamReady(const ProxyInfo& used_proxy_info,
                                           std::unique_ptr<HttpStream> stream) {
  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
  DCHECK(stream_request_.get());

  if (stream_) {
    total_received_bytes_ += stream_->GetTotalReceivedBytes();
    total_sent_bytes_ += stream_->GetTotalSentBytes();
  }
  stream_ = std::move(stream);
  stream_->SetRequestHeadersCallback(request_headers_callback_);
  proxy_info_ = used_proxy_info;
  negotiated_protocol_ = stream_request_->negotiated_protocol();
  // TODO(crbug.com/40473589): Remove `was_alpn_negotiated` when we remove
  // chrome.loadTimes API.
  response_.was_alpn_negotiated =
      stream_request_->negotiated_protocol() != NextProto::kProtoUnknown;
  response_.alpn_negotiated_protocol =
      NextProtoToString(stream_request_->negotiated_protocol());
  response_.alternate_protocol_usage =
      stream_request_->alternate_protocol_usage();
  // TODO(crbug.com/40815866): Stop using `was_fetched_via_spdy`.
  response_.was_fetched_via_spdy =
      stream_request_->negotiated_protocol() == NextProto::kProtoHTTP2;
  response_.dns_aliases = stream_->GetDnsAliases();

  dns_resolution_start_time_override_ =
      stream_request_->dns_resolution_start_time_override();
  dns_resolution_end_time_override_ =
      stream_request_->dns_resolution_end_time_override();

  SetProxyInfoInResponse(used_proxy_info, &response_);
  OnIOComplete(OK);
}

void HttpNetworkTransaction::OnBidirectionalStreamImplReady(
    const ProxyInfo& used_proxy_info,
    std::unique_ptr<BidirectionalStreamImpl> stream) {
  NOTREACHED();
}

void HttpNetworkTransaction::OnWebSocketHandshakeStreamReady(
    const ProxyInfo& used_proxy_info,
    std::unique_ptr<WebSocketHandshakeStreamBase> stream) {
  OnStreamReady(used_proxy_info, std::move(stream));
}

void HttpNetworkTransaction::OnStreamFailed(
    int result,
    const NetErrorDetails& net_error_details,
    const ProxyInfo& used_proxy_info,
    ResolveErrorInfo resolve_error_info) {
  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
  DCHECK_NE(OK, result);
  DCHECK(stream_request_.get());
  DCHECK(!stream_.get());
  net_error_details_ = net_error_details;
  proxy_info_ = used_proxy_info;
  SetProxyInfoInResponse(used_proxy_info, &response_);
  response_.resolve_error_info = resolve_error_info;

  OnIOComplete(result);
}

void HttpNetworkTransaction::OnCertificateError(int result,
                                                const SSLInfo& ssl_info) {
  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
  DCHECK_NE(OK, result);
  DCHECK(stream_request_.get());
  DCHECK(!stream_.get());

  response_.ssl_info = ssl_info;
  if (ssl_info.cert) {
    observed_bad_certs_.emplace_back(ssl_info.cert, ssl_info.cert_status);
  }

  // TODO(mbelshe):  For now, we're going to pass the error through, and that
  // will close the stream_request in all cases.  This means that we're always
  // going to restart an entire STATE_CREATE_STREAM, even if the connection is
  // good and the user chooses to ignore the error.  This is not ideal, but not
  // the end of the world either.

  OnIOComplete(result);
}

void HttpNetworkTransaction::OnNeedsProxyAuth(
    const HttpResponseInfo& proxy_response,
    const ProxyInfo& used_proxy_info,
    HttpAuthController* auth_controller) {
  DCHECK(stream_request_.get());
  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);

  establishing_tunnel_ = true;
  response_.headers = proxy_response.headers;
  response_.auth_challenge = proxy_response.auth_challenge;
  response_.did_use_http_auth = proxy_response.did_use_http_auth;
  SetProxyInfoInResponse(used_proxy_info, &response_);

  if (!ContentEncodingsValid()) {
    DoCallback(ERR_CONTENT_DECODING_FAILED);
    return;
  }

  headers_valid_ = true;
  proxy_info_ = used_proxy_info;

  auth_controllers_[HttpAuth::AUTH_PROXY] = auth_controller;
  pending_auth_target_ = HttpAuth::AUTH_PROXY;

  DoCallback(OK);
}

void HttpNetworkTransaction::OnNeedsClientAuth(SSLCertRequestInfo* cert_info) {
  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);

  response_.cert_request_info = cert_info;
  OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
}

void HttpNetworkTransaction::OnQuicBroken() {
  net_error_details_.quic_broken = true;
}

ConnectionAttempts HttpNetworkTransaction::GetConnectionAttempts() const {
  return connection_attempts_;
}

bool HttpNetworkTransaction::IsSecureRequest() const {
  return request_->url.SchemeIsCryptographic();
}

bool HttpNetworkTransaction::UsingHttpProxyWithoutTunnel() const {
  return proxy_info_.proxy_chain().is_get_to_proxy_allowed() &&
         request_->url.SchemeIs("http");
}

void HttpNetworkTransaction::DoCallback(int rv) {
  DCHECK_NE(rv, ERR_IO_PENDING);
  DCHECK(!callback_.is_null());

#if BUILDFLAG(ENABLE_REPORTING)
  // Just before invoking the caller's completion callback, generate a NEL
  // report about this network request if the result was an error.
  GenerateNetworkErrorLoggingReportIfError(rv);
#endif  // BUILDFLAG(ENABLE_REPORTING)

  // Since Run may result in Read being called, clear user_callback_ up front.
  std::move(callback_).Run(rv);
}

void HttpNetworkTransaction::OnIOComplete(int result) {
  int rv = DoLoop(result);
  if (rv != ERR_IO_PENDING)
    DoCallback(rv);
}

int HttpNetworkTransaction::DoLoop(int result) {
  DCHECK(next_state_ != STATE_NONE);

  int rv = result;
  do {
    State state = next_state_;
    next_state_ = STATE_NONE;
    switch (state) {
      case STATE_CREATE_STREAM:
        DCHECK_EQ(OK, rv);
        rv = DoCreateStream();
        break;
      case STATE_CREATE_STREAM_COMPLETE:
        rv = DoCreateStreamComplete(rv);
        break;
      case STATE_CONNECTED_CALLBACK:
        rv = DoConnectedCallback();
        break;
      case STATE_CONNECTED_CALLBACK_COMPLETE:
        rv = DoConnectedCallbackComplete(rv);
        break;
      case STATE_INIT_STREAM:
        DCHECK_EQ(OK, rv);
        rv = DoInitStream();
        break;
      case STATE_INIT_STREAM_COMPLETE:
        rv = DoInitStreamComplete(rv);
        break;
      case STATE_GENERATE_PROXY_AUTH_TOKEN:
        DCHECK_EQ(OK, rv);
        rv = DoGenerateProxyAuthToken();
        break;
      case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
        rv = DoGenerateProxyAuthTokenComplete(rv);
        break;
      case STATE_GENERATE_SERVER_AUTH_TOKEN:
        DCHECK_EQ(OK, rv);
        rv = DoGenerateServerAuthToken();
        break;
      case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
        rv = DoGenerateServerAuthTokenComplete(rv);
        break;
      case STATE_INIT_REQUEST_BODY:
        DCHECK_EQ(OK, rv);
        rv = DoInitRequestBody();
        break;
      case STATE_INIT_REQUEST_BODY_COMPLETE:
        rv = DoInitRequestBodyComplete(rv);
        break;
      case STATE_BUILD_REQUEST:
        DCHECK_EQ(OK, rv);
        net_log_.BeginEvent(NetLogEventType::HTTP_TRANSACTION_SEND_REQUEST);
        rv = DoBuildRequest();
        break;
      case STATE_BUILD_REQUEST_COMPLETE:
        rv = DoBuildRequestComplete(rv);
        break;
      case STATE_SEND_REQUEST:
        DCHECK_EQ(OK, rv);
        rv = DoSendRequest();
        break;
      case STATE_SEND_REQUEST_COMPLETE:
        rv = DoSendRequestComplete(rv);
        net_log_.EndEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_SEND_REQUEST, rv);
        break;
      case STATE_READ_HEADERS:
        DCHECK_EQ(OK, rv);
        net_log_.BeginEvent(NetLogEventType::HTTP_TRANSACTION_READ_HEADERS);
        rv = DoReadHeaders();
        break;
      case STATE_READ_HEADERS_COMPLETE:
        rv = DoReadHeadersComplete(rv);
        net_log_.EndEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_READ_HEADERS, rv);
        break;
      case STATE_READ_BODY:
        DCHECK_EQ(OK, rv);
        net_log_.BeginEvent(NetLogEventType::HTTP_TRANSACTION_READ_BODY);
        rv = DoReadBody();
        break;
      case STATE_READ_BODY_COMPLETE:
        rv = DoReadBodyComplete(rv);
        net_log_.EndEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_READ_BODY, rv);
        break;
      case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
        DCHECK_EQ(OK, rv);
        net_log_.BeginEvent(
            NetLogEventType::HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
        rv = DoDrainBodyForAuthRestart();
        break;
      case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE:
        rv = DoDrainBodyForAuthRestartComplete(rv);
        net_log_.EndEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART, rv);
        break;
      default:
        NOTREACHED() << "bad state";
    }
  } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);

  return rv;
}

int HttpNetworkTransaction::DoCreateStream() {
  TRACE_EVENT("net", "HttpNetworkTransaction::CreateStream",
              NetLogWithSourceToFlow(net_log_), "retry_attempts",
              retry_attempts_, "num_restarts", num_restarts_);
  response_.network_accessed = true;

  next_state_ = STATE_CREATE_STREAM_COMPLETE;
  // IP based pooling is only disabled on a retry after 421 Misdirected Request
  // is received. Alternative Services are also disabled in this case (though
  // they can also be disabled when retrying after a QUIC error).
  if (!enable_ip_based_pooling_) {
    DCHECK(!enable_alternative_services_);
  }

  create_stream_start_time_ = base::TimeTicks::Now();
  // Reset `create_stream_end_time__` to prevent an inconsistent state in
  // case that `DoCreateStream` is called multiple times.
  create_stream_end_time_ = base::TimeTicks();

  if (ForWebSocketHandshake()) {
    stream_request_ =
        session_->http_stream_factory()->RequestWebSocketHandshakeStream(
            *request_, priority_, /*allowed_bad_certs=*/observed_bad_certs_,
            this, websocket_handshake_stream_base_create_helper_,
            enable_ip_based_pooling_, enable_alternative_services_, net_log_);
  } else {
    stream_request_ = session_->http_stream_factory()->RequestStream(
        *request_, priority_, /*allowed_bad_certs=*/observed_bad_certs_, this,
        enable_ip_based_pooling_, enable_alternative_services_, net_log_);
  }
  DCHECK(stream_request_.get());
  return ERR_IO_PENDING;
}

int HttpNetworkTransaction::DoCreateStreamComplete(int result) {
  CHECK(stream_request_);
  TRACE_EVENT(
      "net", "HttpNetworkTransaction::CreateStreamComplete",
      NetLogWithSourceToFlow(net_log_), "result", result, "negotiated_protocol",
      stream_request_->completed() ? stream_request_->negotiated_protocol()
                                   : NextProto::kProtoUnknown);
  RecordStreamRequestResult(result);
  CopyConnectionAttemptsFromStreamRequest();
  if (result == OK) {
    create_stream_end_time_ = base::TimeTicks::Now();
    next_state_ = STATE_CONNECTED_CALLBACK;
    DCHECK(stream_.get());
    CHECK(!create_stream_start_time_.is_null());
    CHECK_LE(create_stream_start_time_, create_stream_end_time_);
    base::UmaHistogramTimes(
        base::StrCat(
            {"Net.NetworkTransaction.Create",
             (ForWebSocketHandshake() ? "WebSocketStreamTime."
                                      : "HttpStreamTime."),
             (IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ""),
             NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
        create_stream_end_time_ - create_stream_start_time_);
    if (!reset_connection_and_request_for_resend_start_time_.is_null()) {
      base::UmaHistogramTimes(
          "Net.NetworkTransaction.ResetConnectionAndResendRequestTime",
          base::TimeTicks::Now() -
              reset_connection_and_request_for_resend_start_time_);
    }
  } else if (result == ERR_HTTP_1_1_REQUIRED ||
             result == ERR_PROXY_HTTP_1_1_REQUIRED) {
    return HandleHttp11Required(result);
  } else {
    // Handle possible client certificate errors that may have occurred if the
    // stream used SSL for one or more of the layers.
    result = HandleSSLClientAuthError(result);
  }

  // At this point we are done with the stream_request_.
  stream_request_.reset();
  return result;
}

int HttpNetworkTransaction::DoConnectedCallback() {
  TRACE_EVENT("net", "HttpNetworkTransaction::ConnectedCallback",
              NetLogWithSourceToFlow(net_log_));
  // Register the HttpRequestInfo object on the stream here so that it's
  // available when invoking the `connected_callback_`, as
  // HttpStream::GetAcceptChViaAlps() needs the HttpRequestInfo to retrieve
  // the ACCEPT_CH frame payload.
  stream_->RegisterRequest(request_);
  next_state_ = STATE_CONNECTED_CALLBACK_COMPLETE;

  int result = stream_->GetRemoteEndpoint(&remote_endpoint_);
  if (result != OK) {
    // `GetRemoteEndpoint()` fails when the underlying socket is not connected
    // anymore, even though the peer's address is known. This can happen when
    // we picked a socket from socket pools while it was still connected, but
    // the remote side closes it before we get a chance to send our request.
    // See if we should retry the request based on the error code we got.
    return HandleIOError(result);
  }

  if (connected_callback_.is_null()) {
    return OK;
  }

  // Fire off notification that we have successfully connected.
  TransportType type = TransportType::kDirect;
  if (!proxy_info_.is_direct()) {
    type = TransportType::kProxied;
  }

  bool is_issued_by_known_root = false;
  if (IsSecureRequest()) {
    SSLInfo ssl_info;
    CHECK(stream_);
    stream_->GetSSLInfo(&ssl_info);
    is_issued_by_known_root = ssl_info.is_issued_by_known_root;
  }

  connected_callback_start_time_ = base::TimeTicks::Now();
  // Reset `connected_callback_end_time_` to prevent an inconsistent state in
  // case that `DoConnectedCallback` is called multiple times.
  connected_callback_end_time_ = base::TimeTicks();

  return connected_callback_.Run(
      TransportInfo(type, remote_endpoint_,
                    std::string{stream_->GetAcceptChViaAlps()},
                    is_issued_by_known_root,
                    NextProtoFromString(response_.alpn_negotiated_protocol)),
      base::BindOnce(&HttpNetworkTransaction::ResumeAfterConnected,
                     base::Unretained(this)));
}

int HttpNetworkTransaction::DoConnectedCallbackComplete(int result) {
  TRACE_EVENT("net", "HttpNetworkTransaction::ConnectedCallbackComplete",
              NetLogWithSourceToFlow(net_log_), "result", result);
  if (result != OK) {
    if (stream_) {
      stream_->Close(/*not_reusable=*/false);
    }

    // Stop the state machine here if the call failed.
    return result;
  }

  next_state_ = STATE_INIT_STREAM;
  return OK;
}

int HttpNetworkTransaction::DoInitStream() {
  DCHECK(stream_.get());
  TRACE_EVENT("net", "HttpNetworkTransaction::InitStream",
              NetLogWithSourceToFlow(net_log_));
  next_state_ = STATE_INIT_STREAM_COMPLETE;

  initialize_stream_start_time_ = base::TimeTicks::Now();
  int rv = stream_->InitializeStream(can_send_early_data_, priority_, net_log_,
                                     io_callback_);

  // TODO(crbug.com/359404121): Remove this histogram after the investigation
  // completes.
  bool blocked = rv == ERR_IO_PENDING;
  if (blocked) {
    blocked_initialize_stream_start_time_ = initialize_stream_start_time_;
  }
  base::UmaHistogramBoolean(
      base::StrCat(
          {"Net.NetworkTransaction.InitializeStreamBlocked",
           IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ".",
           NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
      blocked);
  return rv;
}

int HttpNetworkTransaction::DoInitStreamComplete(int result) {
  TRACE_EVENT("net", "HttpNetworkTransaction::InitStreamComplete",
              NetLogWithSourceToFlow(net_log_), "result", result);
  initialize_stream_end_time_ = base::TimeTicks::Now();

  // TODO(crbug.com/359404121): Remove this histogram after the investigation
  // completes.
  if (!blocked_initialize_stream_start_time_.is_null()) {
    base::UmaHistogramTimes(
        base::StrCat(
            {"Net.NetworkTransaction.InitializeStreamBlockTime",
             IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ".",
             NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
        initialize_stream_end_time_ - blocked_initialize_stream_start_time_);
  }

  if (result != OK) {
    if (result < 0) {
      result = HandleIOError(result);
    }

    // The stream initialization failed, so this stream will never be useful.
    if (stream_) {
      total_received_bytes_ += stream_->GetTotalReceivedBytes();
      total_sent_bytes_ += stream_->GetTotalSentBytes();
    }
    CacheNetErrorDetailsAndResetStream();

    return result;
  }

  next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
  return result;
}

int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
  next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
  if (!ShouldApplyProxyAuth())
    return OK;
  HttpAuth::Target target = HttpAuth::AUTH_PROXY;
  if (!auth_controllers_[target].get())
    auth_controllers_[target] = base::MakeRefCounted<HttpAuthController>(
        target, AuthURL(target), request_->network_anonymization_key,
        session_->http_auth_cache(), session_->http_auth_handler_factory(),
        session_->host_resolver());
  int rv = auth_controllers_[target]->MaybeGenerateAuthToken(
      request_, io_callback_, net_log_);
  // TODO(crbug.com/359404121): Remove this histogram after the investigation
  // completes.
  const bool blocked = rv == ERR_IO_PENDING;
  if (blocked) {
    blocked_generate_proxy_auth_token_start_time_ = base::TimeTicks::Now();
  }
  base::UmaHistogramBoolean(
      base::StrCat(
          {"Net.NetworkTransaction.GenerateProxyAuthTokenBlocked",
           IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ".",
           NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
      blocked);
  return rv;
}

int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv) {
  DCHECK_NE(ERR_IO_PENDING, rv);
  // TODO(crbug.com/359404121): Remove this histogram after the investigation
  // completes.
  if (!blocked_generate_proxy_auth_token_start_time_.is_null()) {
    base::UmaHistogramTimes(
        base::StrCat(
            {"Net.NetworkTransaction.GenerateProxyAuthTokenBlockTime",
             IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ".",
             NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
        base::TimeTicks::Now() - blocked_generate_proxy_auth_token_start_time_);
  }
  if (rv == OK)
    next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN;
  return rv;
}

int HttpNetworkTransaction::DoGenerateServerAuthToken() {
  next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE;
  HttpAuth::Target target = HttpAuth::AUTH_SERVER;
  if (!auth_controllers_[target].get()) {
    auth_controllers_[target] = base::MakeRefCounted<HttpAuthController>(
        target, AuthURL(target), request_->network_anonymization_key,
        session_->http_auth_cache(), session_->http_auth_handler_factory(),
        session_->host_resolver());
    if (request_->load_flags & LOAD_DO_NOT_USE_EMBEDDED_IDENTITY)
      auth_controllers_[target]->DisableEmbeddedIdentity();
  }
  if (!ShouldApplyServerAuth())
    return OK;
  int rv = auth_controllers_[target]->MaybeGenerateAuthToken(
      request_, io_callback_, net_log_);
  // TODO(crbug.com/359404121): Remove this histogram after the investigation
  // completes.
  const bool blocked = rv == ERR_IO_PENDING;
  if (blocked) {
    blocked_generate_server_auth_token_start_time_ = base::TimeTicks::Now();
  }
  base::UmaHistogramBoolean(
      base::StrCat(
          {"Net.NetworkTransaction.GenerateServerAuthTokenBlocked",
           IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ".",
           NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
      blocked);
  return rv;
}

int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv) {
  DCHECK_NE(ERR_IO_PENDING, rv);
  // TODO(crbug.com/359404121): Remove this histogram after the investigation
  // completes.
  if (!blocked_generate_server_auth_token_start_time_.is_null()) {
    base::UmaHistogramTimes(
        base::StrCat(
            {"Net.NetworkTransaction.GenerateServerAuthTokenBlockTime",
             IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : ".",
             NegotiatedProtocolToHistogramSuffix(negotiated_protocol_)}),
        base::TimeTicks::Now() -
            blocked_generate_server_auth_token_start_time_);
  }
  if (rv == OK)
    next_state_ = STATE_INIT_REQUEST_BODY;
  return rv;
}

int HttpNetworkTransaction::BuildRequestHeaders(
    bool using_http_proxy_without_tunnel) {
  request_headers_.SetHeader(HttpRequestHeaders::kHost,
                             GetHostAndOptionalPort(request_->url));

  // For compat with HTTP/1.0 servers and proxies:
  if (using_http_proxy_without_tunnel) {
    request_headers_.SetHeader(HttpRequestHeaders::kProxyConnection,
                               "keep-alive");
  } else {
    request_headers_.SetHeader(HttpRequestHeaders::kConnection, "keep-alive");
  }

  // Add a content length header?
  if (request_->upload_data_stream) {
    if (request_->upload_data_stream->is_chunked()) {
      request_headers_.SetHeader(
          HttpRequestHeaders::kTransferEncoding, "chunked");
    } else {
      request_headers_.SetHeader(
          HttpRequestHeaders::kContentLength,
          base::NumberToString(request_->upload_data_stream->size()));
    }
  } else if (request_->method == "POST" || request_->method == "PUT") {
    // An empty POST/PUT request still needs a content length.  As for HEAD,
    // IE and Safari also add a content length header.  Presumably it is to
    // support sending a HEAD request to an URL that only expects to be sent a
    // POST or some other method that normally would have a message body.
    // Firefox (40.0) does not send the header, and RFC 7230 & 7231
    // specify that it should not be sent due to undefined behavior.
    request_headers_.SetHeader(HttpRequestHeaders::kContentLength, "0");
  }

  // Honor load flags that impact proxy caches.
  if (request_->load_flags & LOAD_BYPASS_CACHE) {
    request_headers_.SetHeader(HttpRequestHeaders::kPragma, "no-cache");
    request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "no-cache");
  } else if (request_->load_flags & LOAD_VALIDATE_CACHE) {
    request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "max-age=0");
  }

  if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY))
    auth_controllers_[HttpAuth::AUTH_PROXY]->AddAuthorizationHeader(
        &request_headers_);
  if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER))
    auth_controllers_[HttpAuth::AUTH_SERVER]->AddAuthorizationHeader(
        &request_headers_);

  bool is_proxied_request =
      proxy_info_.is_for_ip_protection() && !proxy_info_.is_direct();
  if (features::kIpPrivacyAddHeaderToProxiedRequests.Get() &&
      is_proxied_request) {
    request_headers_.SetHeader("IP-Protection", "1");
  }

  if (bool is_prt_eligible =
          features::kEnableProbabilisticRevealTokensForNonProxiedRequests
              .Get() ||
          is_proxied_request;
      features::kProbabilisticRevealTokensAddHeaderToProxiedRequests.Get() &&
      is_prt_eligible) {
    if (std::optional<std::string> maybe_prt_header_value =
            proxy_info_.prt_header_value();
        maybe_prt_header_value.has_value()) {
      request_headers_.SetHeader("Sec-Probabilistic-Reveal-Token",
                                 std::move(maybe_prt_header_value.value()));
    }
  }

  request_headers_.MergeFrom(request_->extra_headers);

  if (modify_headers_callbacks_) {
    modify_headers_callbacks_.Run(&request_headers_);
  }

  response_.did_use_http_auth =
      request_headers_.HasHeader(HttpRequestHeaders::kAuthorization) ||
      request_headers_.HasHeader(HttpRequestHeaders::kProxyAuthorization);
  return OK;
}

int HttpNetworkTransaction::DoInitRequestBody() {
  TRACE_EVENT("net", "HttpNetworkTransaction::InitRequestBody",
              NetLogWithSourceToFlow(net_log_));
  next_state_ = STATE_INIT_REQUEST_BODY_COMPLETE;
  int rv = OK;
  if (request_->upload_data_stream)
    rv = request_->upload_data_stream->Init(
        base::BindOnce(&HttpNetworkTransaction::OnIOComplete,
                       base::Unretained(this)),
        net_log_);
  return rv;
}

int HttpNetworkTransaction::DoInitRequestBodyComplete(int result) {
  TRACE_EVENT("net", "HttpNetworkTransaction::InitRequestBodyComplete",
              NetLogWithSourceToFlow(net_log_), "result", result);
  if (result == OK)
    next_state_ = STATE_BUILD_REQUEST;
  return result;
}

int HttpNetworkTransaction::DoBuildRequest() {
  TRACE_EVENT("net", "HttpNetworkTransaction::BuildRequest",
              NetLogWithSourceToFlow(net_log_));
  next_state_ = STATE_BUILD_REQUEST_COMPLETE;
  headers_valid_ = false;

  // This is constructed lazily (instead of within our Start method), so that
  // we have proxy info available.
  if (request_headers_.IsEmpty()) {
    bool using_http_proxy_without_tunnel = UsingHttpProxyWithoutTunnel();
    return BuildRequestHeaders(using_http_proxy_without_tunnel);
  }

  return OK;
}

int HttpNetworkTransaction::DoBuildRequestComplete(int result) {
  TRACE_EVENT("net", "HttpNetworkTransaction::BuildRequestComplete",
              NetLogWithSourceToFlow(net_log_), "result", result);
  if (result == OK) {
    next_state_ = STATE_SEND_REQUEST;
  }
  return result;
}

int HttpNetworkTransaction::DoSendRequest() {
  TRACE_EVENT("net", "HttpNetworkTransaction::SendRequest",
              NetLogWithSourceToFlow(net_log_));
  send_start_time_ = base::TimeTicks::Now();
  next_state_ = STATE_SEND_REQUEST_COMPLETE;

  if (base::FeatureList::IsEnabled(kLogDuplicateRequests) &&
      request_->method == "GET") {
    LogIfDuplicateRequest(request_->url, request_->is_main_frame_navigation);
  }

  stream_->SetRequestIdempotency(request_->idempotency);
  return stream_->SendRequest(request_headers_, &response_, io_callback_);
}

int HttpNetworkTransaction::DoSendRequestComplete(int result) {
  TRACE_EVENT("net", "HttpNetworkTransaction::SendRequestComplete",
              NetLogWithSourceToFlow(net_log_), "result", result);
  send_end_time_ = base::TimeTicks::Now();

  if (result == ERR_HTTP_1_1_REQUIRED ||
      result == ERR_PROXY_HTTP_1_1_REQUIRED) {
    return HandleHttp11Required(result);
  }

  if (result < 0)
    return HandleIOError(result);
  next_state_ = STATE_READ_HEADERS;
  return OK;
}

int HttpNetworkTransaction::DoReadHeaders() {
  TRACE_EVENT("net", "HttpNetworkTransaction::ReadHeaders",
              NetLogWithSourceToFlow(net_log_));
  next_state_ = STATE_READ_HEADERS_COMPLETE;
  return stream_->ReadResponseHeaders(io_callback_);
}

int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
  TRACE_EVENT("net", "HttpNetworkTransaction::ReadHeadersComplete",
              NetLogWithSourceToFlow(net_log_), "result", result,
              "response_code",
              response_.headers ? response_.headers->response_code() : -1);
  // We can get a ERR_SSL_CLIENT_AUTH_CERT_NEEDED here due to SSL renegotiation.
  // Server certificate errors are impossible. Rather than reverify the new
  // server certificate, BoringSSL forbids server certificates from changing.
  DCHECK(!IsCertificateError(result));
  if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
    DCHECK(stream_.get());
    DCHECK(IsSecureRequest());
    // Should only reach this code when there's a certificate request.
    CHECK(response_.cert_request_info);

    total_received_bytes_ += stream_->GetTotalReceivedBytes();
    total_sent_bytes_ += stream_->GetTotalSentBytes();
    stream_->Close(true);
    CacheNetErrorDetailsAndResetStream();
  }

  if (result == ERR_HTTP_1_1_REQUIRED ||
      result == ERR_PROXY_HTTP_1_1_REQUIRED) {
    return HandleHttp11Required(result);
  }

  // ERR_CONNECTION_CLOSED is treated differently at this point; if partial
  // response headers were received, we do the best we can to make sense of it
  // and send it back up the stack.
  //
  // TODO(davidben): Consider moving this to HttpBasicStream, It's a little
  // bizarre for SPDY. Assuming this logic is useful at all.
  // TODO(davidben): Bubble the error code up so we do not cache?
  if (result == ERR_CONNECTION_CLOSED && response_.headers.get())
    result = OK;

  if (ForWebSocketHandshake()) {
    RecordWebSocketFallbackResult(
        result, http_1_1_was_required_,
        HttpConnectionInfoToCoarse(response_.connection_info));
  }

  if (result < 0)
    return HandleIOError(result);

  DCHECK(response_.headers.get());

  // Check for a 103 Early Hints response.
  if (response_.headers->response_code() == HTTP_EARLY_HINTS) {
    NetLogResponseHeaders(
        net_log_,
        NetLogEventType::HTTP_TRANSACTION_READ_EARLY_HINTS_RESPONSE_HEADERS,
        response_.headers.get());

    // Early Hints does not make sense for a WebSocket handshake.
    if (ForWebSocketHandshake()) {
      return ERR_FAILED;
    }

    // TODO(crbug.com/40496584): Validate headers?  "Content-Encoding" etc
    // should not appear since informational responses can't contain content.
    // https://www.rfc-editor.org/rfc/rfc9110#name-informational-1xx

    if (EarlyHintsAreAllowedOn(response_.connection_info) &&
        early_response_headers_callback_) {
      // Process Alt-Svc headers so that QUIC session can be set up sooner
      ProcessAltSvcHeader();

      early_response_headers_callback_.Run(std::move(response_.headers));
    }

    // Reset response headers for the final response.
    response_.headers =
        base::MakeRefCounted<HttpResponseHeaders>(std::string());
    next_state_ = STATE_READ_HEADERS;
    return OK;
  }

  if (!ContentEncodingsValid())
    return ERR_CONTENT_DECODING_FAILED;

  // On a 408 response from the server ("Request Timeout") on a stale socket,
  // retry the request for HTTP/1.1 but not HTTP/2 or QUIC because those
  // multiplex requests and have no need for 408.
  if (response_.headers->response_code() == HTTP_REQUEST_TIMEOUT &&
      HttpConnectionInfoToCoarse(response_.connection_info) ==
          HttpConnectionInfoCoarse::kHTTP1 &&
      stream_->IsConnectionReused()) {
#if BUILDFLAG(ENABLE_REPORTING)
    GenerateNetworkErrorLoggingReport(OK);
#endif  // BUILDFLAG(ENABLE_REPORTING)
    net_log_.AddEventWithNetErrorCode(
        NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR,
        response_.headers->response_code());
    // This will close the socket - it would be weird to try and reuse it, even
    // if the server doesn't actually close it.
    ResetConnectionAndRequestForResend(RetryReason::kHttpRequestTimeout);
    return OK;
  }

  NetLogResponseHeaders(net_log_,
                        NetLogEventType::HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
                        response_.headers.get());
  if (response_headers_callback_)
    response_headers_callback_.Run(response_.headers);

  if (response_.headers->GetHttpVersion() < HttpVersion(1, 0)) {
    // HTTP/0.9 doesn't support the PUT method, so lack of response headers
    // indicates a buggy server.  See:
    // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
    if (request_->method == "PUT")
      return ERR_METHOD_NOT_SUPPORTED;
  }

  if (can_send_early_data_ &&
      response_.headers->response_code() == HTTP_TOO_EARLY) {
    return HandleIOError(ERR_EARLY_DATA_REJECTED);
  }

  // Check for an intermediate 100 Continue response.  An origin server is
  // allowed to send this response even if we didn't ask for it, so we just
  // need to skip over it.
  // We treat any other 1xx in this same way unless:
  //  * The response is 103, which is already handled above
  //  * This is a WebSocket request, in which case we pass it on up.
  if (response_.headers->response_code() / 100 == 1 &&
      !ForWebSocketHandshake()) {
    response_.headers =
        base::MakeRefCounted<HttpResponseHeaders>(std::string());
    next_state_ = STATE_READ_HEADERS;
    return OK;
  }

  const bool has_body_with_null_source =
      request_->upload_data_stream &&
      request_->upload_data_stream->has_null_source();
  if (response_.headers->response_code() == 421 &&
      (enable_ip_based_pooling_ || enable_alternative_services_) &&
      !has_body_with_null_source) {
#if BUILDFLAG(ENABLE_REPORTING)
    GenerateNetworkErrorLoggingReport(OK);
#endif  // BUILDFLAG(ENABLE_REPORTING)
    // Retry the request with both IP based pooling and Alternative Services
    // disabled.
    enable_ip_based_pooling_ = false;
    enable_alternative_services_ = false;
    net_log_.AddEvent(
        NetLogEventType::HTTP_TRANSACTION_RESTART_MISDIRECTED_REQUEST);
    ResetConnectionAndRequestForResend(RetryReason::kHttpMisdirectedRequest);
    return OK;
  }

  ProcessAltSvcHeader();

  int rv = HandleAuthChallenge();
  if (rv != OK)
    return rv;

#if BUILDFLAG(ENABLE_REPORTING)
  // Note: This just handles the legacy Report-To header, which is still
  // required for NEL. The newer Reporting-Endpoints header is processed in
  // network::PopulateParsedHeaders().
  ProcessReportToHeader();

  // Note: Unless there is a pre-existing NEL policy for this origin, any NEL
  // reports generated before the NEL header is processed here will just be
  // dropped by the NetworkErrorLoggingService.
  ProcessNetworkErrorLoggingHeader();

  // Generate NEL report here if we have to report an HTTP error (4xx or 5xx
  // code), or if the response body will not be read, or on a redirect.
  // Note: This will report a success for a redirect even if an error is
  // encountered later while draining the body.
  int response_code = response_.headers->response_code();
  if ((response_code >= 400 && response_code < 600) ||
      response_code == HTTP_NO_CONTENT || response_code == HTTP_RESET_CONTENT ||
      response_code == HTTP_NOT_MODIFIED || request_->method == "HEAD" ||
      response_.headers->GetContentLength() == 0 ||
      response_.headers->IsRedirect(nullptr /* location */)) {
    GenerateNetworkErrorLoggingReport(OK);
  }
#endif  // BUILDFLAG(ENABLE_REPORTING)

  headers_valid_ = true;

  // We have reached the end of Start state machine, set the RequestInfo to
  // null.
  // RequestInfo is a member of the HttpTransaction's consumer and is useful
  // only until the final response headers are received. Clearing it will ensure
  // that HttpRequestInfo is only used up until final response headers are
  // received. Clearing is allowed so that the transaction can be disassociated
  // from its creating consumer in cases where it is shared for writing to the
  // cache. It is also safe to set it to null at this point since
  // upload_data_stream is also not used in the Read state machine.
  if (pending_auth_target_ == HttpAuth::AUTH_NONE)
    request_ = nullptr;

  return OK;
}

int HttpNetworkTransaction::DoReadBody() {
  TRACE_EVENT("net", "HttpNetworkTransaction::ReadBody",
              NetLogWithSourceToFlow(net_log_));
  DCHECK(read_buf_.get());
  DCHECK_GT(read_buf_len_, 0);
  DCHECK(stream_ != nullptr);

  next_state_ = STATE_READ_BODY_COMPLETE;
  return stream_->ReadResponseBody(
      read_buf_.get(), read_buf_len_, io_callback_);
}

int HttpNetworkTransaction::DoReadBodyComplete(int result) {
  // We are done with the Read call.
  bool done = false;
  if (result <= 0) {
    DCHECK_NE(ERR_IO_PENDING, result);
    done = true;
  } else {
    received_body_bytes_ += result;
  }

  TRACE_EVENT("net", "HttpNetworkTransaction::ReadBodyComplete",
              NetLogWithSourceToFlow(net_log_), "result", result,
              "received_body_bytes", received_body_bytes_);

  // Clean up connection if we are done.
  if (done) {
    // Note: Just because IsResponseBodyComplete is true, we're not
    // necessarily "done".  We're only "done" when it is the last
    // read on this HttpNetworkTransaction, which will be signified
    // by a zero-length read.
    // TODO(mbelshe): The keep-alive property is really a property of
    //    the stream.  No need to compute it here just to pass back
    //    to the stream's Close function.
    bool keep_alive =
        stream_->IsResponseBodyComplete() && stream_->CanReuseConnection();

    stream_->Close(!keep_alive);
    // Note: we don't reset the stream here.  We've closed it, but we still
    // need it around so that callers can call methods such as
    // GetUploadProgress() and have them be meaningful.
    // TODO(mbelshe): This means we closed the stream here, and we close it
    // again in ~HttpNetworkTransaction.  Clean that up.

    // The next Read call will return 0 (EOF).

    // This transaction was successful. If it had been retried because of an
    // error with an alternative service, mark that alternative service broken.
    if (!enable_alternative_services_ &&
        retried_alternative_service_.protocol != NextProto::kProtoUnknown) {
      HistogramBrokenAlternateProtocolLocation(
          BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_NETWORK_TRANSACTION);
      session_->http_server_properties()->MarkAlternativeServiceBroken(
          retried_alternative_service_, network_anonymization_key_);
    }

#if BUILDFLAG(ENABLE_REPORTING)
    GenerateNetworkErrorLoggingReport(result);
#endif  // BUILDFLAG(ENABLE_REPORTING)
  }

  // Clear these to avoid leaving around old state.
  read_buf_ = nullptr;
  read_buf_len_ = 0;

  return result;
}

int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
  // This method differs from DoReadBody only in the next_state_.  So we just
  // call DoReadBody and override the next_state_.  Perhaps there is a more
  // elegant way for these two methods to share code.
  int rv = DoReadBody();
  DCHECK(next_state_ == STATE_READ_BODY_COMPLETE);
  next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE;
  return rv;
}

// TODO(wtc): This method and the DoReadBodyComplete method are almost
// the same.  Figure out a good way for these two methods to share code.
int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
  // keep_alive defaults to true because the very reason we're draining the
  // response body is to reuse the connection for auth restart.
  bool done = false, keep_alive = true;
  if (result < 0) {
    // Error or closed connection while reading the socket.
    // Note: No Network Error Logging report is generated here because a report
    // will have already been generated for the original request due to the auth
    // challenge, so a second report is not generated for the same request here.
    done = true;
    keep_alive = false;
  } else if (stream_->IsResponseBodyComplete()) {
    done = true;
  }

  if (done) {
    DidDrainBodyForAuthRestart(keep_alive);
  } else {
    // Keep draining.
    next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
  }

  return OK;
}

#if BUILDFLAG(ENABLE_REPORTING)
void HttpNetworkTransaction::ProcessReportToHeader() {
  std::optional<std::string> value =
      response_.headers->GetNormalizedHeader("Report-To");
  if (!value) {
    return;
  }

  ReportingService* reporting_service = session_->reporting_service();
  if (!reporting_service)
    return;

  // Only accept Report-To headers on HTTPS connections that have no
  // certificate errors.
  if (!response_.ssl_info.is_valid())
    return;
  if (IsCertStatusError(response_.ssl_info.cert_status))
    return;

  reporting_service->ProcessReportToHeader(url::Origin::Create(url_),
                                           network_anonymization_key_, *value);
}

void HttpNetworkTransaction::ProcessNetworkErrorLoggingHeader() {
  std::optional<std::string> value = response_.headers->GetNormalizedHeader(
      NetworkErrorLoggingService::kHeaderName);
  if (!value) {
    return;
  }

  NetworkErrorLoggingService* network_error_logging_service =
      session_->network_error_logging_service();
  if (!network_error_logging_service)
    return;

  // Don't accept NEL headers received via a proxy, because the IP address of
  // the destination server is not known.
  if (response_.WasFetchedViaProxy()) {
    return;
  }

  // Only accept NEL headers on HTTPS connections that have no certificate
  // errors.
  if (!response_.ssl_info.is_valid() ||
      IsCertStatusError(response_.ssl_info.cert_status)) {
    return;
  }

  if (remote_endpoint_.address().empty())
    return;

  network_error_logging_service->OnHeader(network_anonymization_key_,
                                          url::Origin::Create(url_),
                                          remote_endpoint_.address(), *value);
}

void HttpNetworkTransaction::GenerateNetworkErrorLoggingReportIfError(int rv) {
  if (rv < 0 && rv != ERR_IO_PENDING)
    GenerateNetworkErrorLoggingReport(rv);
}

void HttpNetworkTransaction::GenerateNetworkErrorLoggingReport(int rv) {
  // |rv| should be a valid Error
  DCHECK_NE(rv, ERR_IO_PENDING);
  DCHECK_LE(rv, 0);

  if (network_error_logging_report_generated_)
    return;
  network_error_logging_report_generated_ = true;

  NetworkErrorLoggingService* service =
      session_->network_error_logging_service();
  if (!service)
    return;

  // Don't report on proxy auth challenges.
  if (response_.headers && response_.headers->response_code() ==
                               HTTP_PROXY_AUTHENTICATION_REQUIRED) {
    return;
  }

  // Don't generate NEL reports if we are behind a proxy, to avoid leaking
  // internal network details.
  if (response_.WasFetchedViaProxy()) {
    return;
  }

  // Ignore errors from non-HTTPS origins.
  if (!url_.SchemeIsCryptographic())
    return;

  NetworkErrorLoggingService::RequestDetails details;

  details.network_anonymization_key = network_anonymization_key_;
  details.uri = url_;
  if (!request_referrer_.empty())
    details.referrer = GURL(request_referrer_);
  details.user_agent = request_user_agent_;
  if (!remote_endpoint_.address().empty()) {
    details.server_ip = remote_endpoint_.address();
  } else if (!connection_attempts_.empty()) {
    // When we failed to connect to the server, `remote_endpoint_` is not set.
    // In such case, we use the last endpoint address of `connection_attempts_`
    // for the NEL report. This address information is important for the
    // downgrade step to protect against port scan attack.
    // https://www.w3.org/TR/network-error-logging/#generate-a-network-error-report
    details.server_ip = connection_attempts_.back().endpoint.address();
  } else {
    details.server_ip = IPAddress();
  }
  // HttpResponseHeaders::response_code() returns 0 if response code couldn't
  // be parsed, which is also how NEL represents the same.
  if (response_.headers) {
    details.status_code = response_.headers->response_code();
  } else {
    details.status_code = 0;
  }
  // If we got response headers, assume that the connection used HTTP/1.1
  // unless ALPN negotiation tells us otherwise (handled below).
  if (response_.was_alpn_negotiated) {
    details.protocol = response_.alpn_negotiated_protocol;
  } else {
    details.protocol = "http/1.1";
  }
  details.method = request_method_;
  details.elapsed_time = base::TimeTicks::Now() - start_timeticks_;
  details.type = static_cast<Error>(rv);
  details.reporting_upload_depth = request_reporting_upload_depth_;

  service->OnRequest(std::move(details));
}
#endif  // BUILDFLAG(ENABLE_REPORTING)

int HttpNetworkTransaction::HandleHttp11Required(int error) {
  DCHECK(error == ERR_HTTP_1_1_REQUIRED ||
         error == ERR_PROXY_HTTP_1_1_REQUIRED);

  http_1_1_was_required_ = true;

  // HttpServerProperties should have been updated, so when the request is sent
  // again, it will automatically use HTTP/1.1.
  ResetConnectionAndRequestForResend(RetryReason::kHttp11Required);
  return OK;
}

int HttpNetworkTransaction::HandleSSLClientAuthError(int error) {
  // Client certificate errors may come from either the origin server or the
  // proxy.
  //
  // Origin errors are handled here, while most proxy errors are handled in the
  // HttpStreamFactory and below, while handshaking with the proxy. However, in
  // TLS 1.2 with False Start, or TLS 1.3, client certificate errors are
  // reported immediately after the handshake. The error will then surface out
  // of the first Read() rather than Connect().
  //
  // If the request is tunneled (i.e. the origin is HTTPS), this first Read()
  // occurs while establishing the tunnel and HttpStreamFactory handles the
  // proxy error. However, if the request is not tunneled (i.e. the origin is
  // HTTP), this first Read() happens late and is ultimately surfaced out of
  // DoReadHeadersComplete(). This method will then be responsible for both
  // origin and proxy errors.
  //
  // See https://crbug.com/828965.
  if (error != ERR_SSL_PROTOCOL_ERROR && !IsClientCertificateError(error)) {
    return error;
  }

  bool is_server = !UsingHttpProxyWithoutTunnel();
  HostPortPair host_port_pair;
  // TODO(crbug.com/40284947): Remove check and return error when
  // multi-proxy chain.
  if (is_server) {
    host_port_pair = HostPortPair::FromURL(request_->url);
  } else {
    CHECK(proxy_info_.proxy_chain().is_single_proxy());
    host_port_pair = proxy_info_.proxy_chain().First().host_port_pair();
  }

  // Check that something in the proxy chain or endpoint are using HTTPS.
  if (DCHECK_IS_ON()) {
    bool server_using_tls = IsSecureRequest();
    bool proxy_using_tls = proxy_info_.AnyProxyInChain(
        [](const ProxyServer& s) { return s.is_secure_http_like(); });
    DCHECK(server_using_tls || proxy_using_tls);
  }

  if (session_->ssl_client_context()->ClearClientCertificate(host_port_pair)) {
    // The private key handle may have gone stale due to, e.g., the user
    // unplugging their smartcard. Operating systems do not provide reliable
    // notifications for this, so if the signature failed and the user was
    // not already prompted for certificate on this request, retry to ask
    // the user for a new one.
    //
    // TODO(davidben): There is no corresponding feature for proxy client
    // certificates. Ideally this would live at a lower level, common to both,
    // but |configured_client_cert_for_server_| is not accessible below the
    // socket pools.
    if (is_server && error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED &&
        !configured_client_cert_for_server_ && !HasExceededMaxRetries()) {
      retry_attempts_++;
      net_log_.AddEventWithNetErrorCode(
          NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
      ResetConnectionAndRequestForResend(
          RetryReason::kSslClientAuthSignatureFailed);
      return OK;
    }
  }
  return error;
}

// static
std::optional<HttpNetworkTransaction::RetryReason>
HttpNetworkTransaction::GetRetryReasonForIOError(int error) {
  switch (error) {
    case ERR_CONNECTION_RESET:
      return RetryReason::kConnectionReset;
    case ERR_CONNECTION_CLOSED:
      return RetryReason::kConnectionClosed;
    case ERR_CONNECTION_ABORTED:
      return RetryReason::kConnectionAborted;
    case ERR_SOCKET_NOT_CONNECTED:
      return RetryReason::kSocketNotConnected;
    case ERR_EMPTY_RESPONSE:
      return RetryReason::kEmptyResponse;
    case ERR_EARLY_DATA_REJECTED:
      return RetryReason::kEarlyDataRejected;
    case ERR_WRONG_VERSION_ON_EARLY_DATA:
      return RetryReason::kWrongVersionOnEarlyData;
    case ERR_HTTP2_PING_FAILED:
      return RetryReason::kHttp2PingFailed;
    case ERR_HTTP2_SERVER_REFUSED_STREAM:
      return RetryReason::kHttp2ServerRefusedStream;
    case ERR_QUIC_HANDSHAKE_FAILED:
      return RetryReason::kQuicHandshakeFailed;
    case ERR_QUIC_GOAWAY_REQUEST_CAN_BE_RETRIED:
      return RetryReason::kQuicGoawayRequestCanBeRetried;
    case ERR_QUIC_PROTOCOL_ERROR:
      return RetryReason::kQuicProtocolError;
  }
  return std::nullopt;
}

// This method determines whether it is safe to resend the request after an
// IO error. It should only be called in response to errors received before
// final set of response headers have been successfully parsed, that the
// transaction may need to be retried on.
// It should not be used in other cases, such as a Connect error.
int HttpNetworkTransaction::HandleIOError(int error) {
  // Because the peer may request renegotiation with client authentication at
  // any time, check and handle client authentication errors.
  error = HandleSSLClientAuthError(error);

#if BUILDFLAG(ENABLE_REPORTING)
  GenerateNetworkErrorLoggingReportIfError(error);
#endif  // BUILDFLAG(ENABLE_REPORTING)

  std::optional<HttpNetworkTransaction::RetryReason> retry_reason =
      GetRetryReasonForIOError(error);
  if (!retry_reason) {
    return error;
  }
  switch (*retry_reason) {
    // If we try to reuse a connection that the server is in the process of
    // closing, we may end up successfully writing out our request (or a
    // portion of our request) only to find a connection error when we try to
    // read from (or finish writing to) the socket.
    case RetryReason::kConnectionReset:
    case RetryReason::kConnectionClosed:
    case RetryReason::kConnectionAborted:
    // There can be a race between the socket pool checking checking whether a
    // socket is still connected, receiving the FIN, and sending/reading data
    // on a reused socket.  If we receive the FIN between the connectedness
    // check and writing/reading from the socket, we may first learn the socket
    // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED.  This will most
    // likely happen when trying to retrieve its IP address.
    // See http://crbug.com/105824 for more details.
    case RetryReason::kSocketNotConnected:
    // If a socket is closed on its initial request, HttpStreamParser returns
    // ERR_EMPTY_RESPONSE. This may still be close/reuse race if the socket was
    // preconnected but failed to be used before the server timed it out.
    case RetryReason::kEmptyResponse:
      if (ShouldResendRequest()) {
        net_log_.AddEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
        ResetConnectionAndRequestForResend(*retry_reason);
        error = OK;
      }
      break;
    case RetryReason::kEarlyDataRejected:
    case RetryReason::kWrongVersionOnEarlyData:
      net_log_.AddEventWithNetErrorCode(
          NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
      // Disable early data on a reset.
      can_send_early_data_ = false;
      ResetConnectionAndRequestForResend(*retry_reason);
      error = OK;
      break;
    case RetryReason::kHttp2PingFailed:
    case RetryReason::kHttp2ServerRefusedStream:
    case RetryReason::kQuicHandshakeFailed:
    case RetryReason::kQuicGoawayRequestCanBeRetried:
      if (HasExceededMaxRetries())
        break;
      net_log_.AddEventWithNetErrorCode(
          NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
      retry_attempts_++;
      ResetConnectionAndRequestForResend(*retry_reason);
      error = OK;
      break;
    case RetryReason::kQuicProtocolError:
      if (HasExceededMaxRetries() || GetResponseHeaders() != nullptr ||
          !stream_->GetAlternativeService(&retried_alternative_service_)) {
        // If the response headers have already been received and passed up
        // then the request can not be retried. Also, if there was no
        // alternative service used for this request, then there is no
        // alternative service to be disabled.
        break;
      }

      if (session_->http_server_properties()->IsAlternativeServiceBroken(
              retried_alternative_service_, network_anonymization_key_)) {
        // If the alternative service was marked as broken while the request
        // was in flight, retry the request which will not use the broken
        // alternative service.
        net_log_.AddEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
        retry_attempts_++;
        ResetConnectionAndRequestForResend(*retry_reason);
        error = OK;
      } else if (session_->context()
                     .quic_context->params()
                     ->retry_without_alt_svc_on_quic_errors) {
        // Disable alternative services for this request and retry it. If the
        // retry succeeds, then the alternative service will be marked as
        // broken then.
        enable_alternative_services_ = false;
        net_log_.AddEventWithNetErrorCode(
            NetLogEventType::HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
        retry_attempts_++;
        ResetConnectionAndRequestForResend(*retry_reason);
        error = OK;
      }
      break;

    // The following reasons are not covered here.
    case RetryReason::kHttpRequestTimeout:
    case RetryReason::kHttpMisdirectedRequest:
    case RetryReason::kHttp11Required:
    case RetryReason::kSslClientAuthSignatureFailed:
      NOTREACHED();
  }
  return error;
}

void HttpNetworkTransaction::ResetStateForRestart() {
  ResetStateForAuthRestart();
  if (stream_) {
    total_received_bytes_ += stream_->GetTotalReceivedBytes();
    total_sent_bytes_ += stream_->GetTotalSentBytes();
  }
  CacheNetErrorDetailsAndResetStream();
}

void HttpNetworkTransaction::ResetStateForAuthRestart() {
  send_start_time_ = base::TimeTicks();
  send_end_time_ = base::TimeTicks();

  pending_auth_target_ = HttpAuth::AUTH_NONE;
  read_buf_ = nullptr;
  read_buf_len_ = 0;
  headers_valid_ = false;
  request_headers_.Clear();
  response_ = HttpResponseInfo();
  SetProxyInfoInResponse(proxy_info_, &response_);
  establishing_tunnel_ = false;
  remote_endpoint_ = IPEndPoint();
  net_error_details_.quic_broken = false;
  net_error_details_.quic_connection_error = quic::QUIC_NO_ERROR;
#if BUILDFLAG(ENABLE_REPORTING)
  network_error_logging_report_generated_ = false;
  start_timeticks_ = base::TimeTicks::Now();
#endif  // BUILDFLAG(ENABLE_REPORTING)
}

void HttpNetworkTransaction::CacheNetErrorDetailsAndResetStream() {
  if (stream_)
    stream_->PopulateNetErrorDetails(&net_error_details_);
  stream_.reset();
}

HttpResponseHeaders* HttpNetworkTransaction::GetResponseHeaders() const {
  return response_.headers.get();
}

bool HttpNetworkTransaction::ShouldResendRequest() const {
  bool connection_is_proven = stream_->IsConnectionReused();
  bool has_received_headers = GetResponseHeaders() != nullptr;

  // NOTE: we resend a request only if we reused a keep-alive connection.
  // This automatically prevents an infinite resend loop because we'll run
  // out of the cached keep-alive connections eventually.
  return connection_is_proven && !has_received_headers;
}

bool HttpNetworkTransaction::HasExceededMaxRetries() const {
  return (retry_attempts_ >= kMaxRetryAttempts);
}

bool HttpNetworkTransaction::CheckMaxRestarts() {
  num_restarts_++;
  return num_restarts_ < kMaxRestarts;
}

void HttpNetworkTransaction::ResetConnectionAndRequestForResend(
    RetryReason retry_reason) {
  TRACE_EVENT("net",
              "HttpNetworkTransaction::ResetConnectionAndRequestForResend",
              NetLogWithSourceToFlow(net_log_), "retry_reason", retry_reason);

  reset_connection_and_request_for_resend_start_time_ = base::TimeTicks::Now();

  // TODO:(crbug.com/1495705): Remove this CHECK after fixing the bug.
  CHECK(request_);
  base::UmaHistogramEnumeration(
      IsGoogleHostWithAlpnH3(url_.host_piece())
          ? "Net.NetworkTransactionH3SupportedGoogleHost.RetryReason"
          : "Net.NetworkTransaction.RetryReason",
      retry_reason);

  if (stream_.get()) {
    stream_->Close(true);
    CacheNetErrorDetailsAndResetStream();
  }

  // We need to clear request_headers_ because it contains the real request
  // headers, but we may need to resend the CONNECT request first to recreate
  // the SSL tunnel.
  request_headers_.Clear();
  next_state_ = STATE_CREATE_STREAM;  // Resend the request.

#if BUILDFLAG(ENABLE_REPORTING)
  // Reset for new request.
  network_error_logging_report_generated_ = false;
  start_timeticks_ = base::TimeTicks::Now();
#endif  // BUILDFLAG(ENABLE_REPORTING)

  ResetStateForRestart();
}

bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
  // TODO(crbug.com/40284947): Update to handle multi-proxy chains.
  if (proxy_info_.proxy_chain().is_multi_proxy()) {
    return false;
  }
  return UsingHttpProxyWithoutTunnel();
}

bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
  return request_->privacy_mode == PRIVACY_MODE_DISABLED;
}

int HttpNetworkTransaction::HandleAuthChallenge() {
  scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
  DCHECK(headers.get());

  int status = headers->response_code();
  if (status != HTTP_UNAUTHORIZED &&
      status != HTTP_PROXY_AUTHENTICATION_REQUIRED)
    return OK;
  HttpAuth::Target target = status == HTTP_PROXY_AUTHENTICATION_REQUIRED ?
                            HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
  if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
    return ERR_UNEXPECTED_PROXY_AUTH;

  // This case can trigger when an HTTPS server responds with a "Proxy
  // authentication required" status code through a non-authenticating
  // proxy.
  if (!auth_controllers_[target].get())
    return ERR_UNEXPECTED_PROXY_AUTH;

  int rv = auth_controllers_[target]->HandleAuthChallenge(
      headers, response_.ssl_info, !ShouldApplyServerAuth(), false, net_log_);
  if (auth_controllers_[target]->HaveAuthHandler())
    pending_auth_target_ = target;

  auth_controllers_[target]->TakeAuthInfo(&response_.auth_challenge);

  return rv;
}

bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target) const {
  return auth_controllers_[target].get() &&
      auth_controllers_[target]->HaveAuth();
}

GURL HttpNetworkTransaction::AuthURL(HttpAuth::Target target) const {
  switch (target) {
    case HttpAuth::AUTH_PROXY: {
      // TODO(crbug.com/40284947): Update to handle multi-proxy chain.
      CHECK(proxy_info_.proxy_chain().is_single_proxy());
      if (!proxy_info_.proxy_chain().IsValid() ||
          proxy_info_.proxy_chain().is_direct()) {
        return GURL();  // There is no proxy chain.
      }
      // TODO(crbug.com/40704785): Mapping proxy addresses to
      // URLs is a lossy conversion, shouldn't do this.
      auto& proxy_server = proxy_info_.proxy_chain().First();
      const char* scheme =
          proxy_server.is_secure_http_like() ? "https://" : "http://";
      return GURL(scheme + proxy_server.host_port_pair().ToString());
    }
    case HttpAuth::AUTH_SERVER:
      if (ForWebSocketHandshake()) {
        return ChangeWebSocketSchemeToHttpScheme(request_->url);
      }
      return request_->url;
    default:
     return GURL();
  }
}

bool HttpNetworkTransaction::ForWebSocketHandshake() const {
  return websocket_handshake_stream_base_create_helper_ &&
         request_->url.SchemeIsWSOrWSS();
}

void HttpNetworkTransaction::CopyConnectionAttemptsFromStreamRequest() {
  DCHECK(stream_request_);

  // Since the transaction can restart with auth credentials, it may create a
  // stream more than once. Accumulate all of the connection attempts across
  // those streams by appending them to the vector:
  for (const auto& attempt : stream_request_->connection_attempts())
    connection_attempts_.push_back(attempt);
}

bool HttpNetworkTransaction::ContentEncodingsValid() const {
  HttpResponseHeaders* headers = GetResponseHeaders();
  DCHECK(headers);

  std::set<std::string> allowed_encodings;
  if (!HttpUtil::ParseAcceptEncoding(
          request_headers_.GetHeader(HttpRequestHeaders::kAcceptEncoding)
              .value_or(std::string()),
          &allowed_encodings)) {
    return false;
  }

  std::string content_encoding =
      headers->GetNormalizedHeader("Content-Encoding").value_or(std::string());
  std::set<std::string> used_encodings;
  if (!HttpUtil::ParseContentEncoding(content_encoding, &used_encodings))
    return false;

  // When "Accept-Encoding" is not specified, it is parsed as "*".
  // If "*" encoding is advertised, then any encoding should be "accepted".
  // This does not mean, that it will be successfully decoded.
  if (allowed_encodings.find("*") != allowed_encodings.end())
    return true;

  bool result = true;
  for (auto const& encoding : used_encodings) {
    SourceStreamType source_type =
        FilterSourceStream::ParseEncodingType(encoding);
    // We don't reject encodings we are not aware. They just will not decode.
    if (source_type == SourceStreamType::kUnknown) {
      continue;
    }
    if (allowed_encodings.find(encoding) == allowed_encodings.end()) {
      result = false;
      break;
    }
  }

  // Temporary workaround for http://crbug.com/714514
  if (headers->IsRedirect(nullptr)) {
    return true;
  }

  return result;
}

void HttpNetworkTransaction::RecordStreamRequestResult(int result) {
  // Do not record the elapsed time when this restarted. Restarting usually
  // involves user interaction and we can't predict how long the interaction
  // took time.
  if (num_restarts_ == 0) {
    base::TimeDelta elapsed = base::TimeTicks::Now() - start_timeticks_;
    base::UmaHistogramTimes(
        base::StrCat(
            {"Net.NetworkTransaction.StreamRequestCompleteTime.",
             IsGoogleHostWithAlpnH3(url_.host_piece()) ? "GoogleHost." : "",
             result == OK ? "Success" : "Failure"}),
        elapsed);
  }

  if (result == OK) {
    base::UmaHistogramEnumeration(
        base::StrCat({
            "Net.NetworkTransaction.NegotiatedProtocol",
            IsGoogleHostWithAlpnH3(url_.host_piece()) ? ".GoogleHost" : "",
        }),
        negotiated_protocol_);

    IPEndPoint endpoint;
    int get_endpoint_result = stream_->GetRemoteEndpoint(&endpoint);
    if (get_endpoint_result == OK) {
      base::UmaHistogramEnumeration(
          "Net.NetworkTransaction.StreamAddressFamily", endpoint.GetFamily(),
          static_cast<AddressFamily>(ADDRESS_FAMILY_LAST + 1));
    }
  } else {
    base::UmaHistogramSparse("Net.NetworkTransaction.StreamRequestErrorCode",
                             -result);
  }
}

void HttpNetworkTransaction::ProcessAltSvcHeader() {
  if (IsSecureRequest()) {
    stream_->GetSSLInfo(&response_.ssl_info);
    if (response_.ssl_info.is_valid() &&
        !IsCertStatusError(response_.ssl_info.cert_status)) {
      session_->http_stream_factory()->ProcessAlternativeServices(
          session_, network_anonymization_key_, response_.headers.get(),
          url::SchemeHostPort(request_->url));
    }
  }
}

// static
void HttpNetworkTransaction::SetProxyInfoInResponse(
    const ProxyInfo& proxy_info,
    HttpResponseInfo* response_info) {
  response_info->was_mdl_match = proxy_info.is_mdl_match();
  if (proxy_info.is_empty()) {
    response_info->proxy_chain = ProxyChain();
  } else {
    response_info->proxy_chain = proxy_info.proxy_chain();
  }
}

}  // namespace net