summaryrefslogtreecommitdiffstats
path: root/netwerk/base/nsSocketTransport2.cpp
blob: e029c8e6bd35e34cfb3e0c4a281ee64383703534 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=4 sw=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsSocketTransport2.h"

#include "mozilla/Attributes.h"
#include "mozilla/SyncRunnable.h"
#include "mozilla/Telemetry.h"
#include "nsIOService.h"
#include "nsStreamUtils.h"
#include "nsNetSegmentUtils.h"
#include "nsNetAddr.h"
#include "nsTransportUtils.h"
#include "nsProxyInfo.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsCOMPtr.h"
#include "plstr.h"
#include "prerr.h"
#include "IOActivityMonitor.h"
#include "NSSErrorsService.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/net/NeckoChild.h"
#include "nsThreadUtils.h"
#include "nsSocketProviderService.h"
#include "nsISocketProvider.h"
#include "nsISSLSocketControl.h"
#include "nsIPipe.h"
#include "nsIClassInfoImpl.h"
#include "nsURLHelper.h"
#include "nsIDNSService.h"
#include "nsIDNSRecord.h"
#include "nsIDNSByTypeRecord.h"
#include "nsICancelable.h"
#include "NetworkDataCountLayer.h"
#include "QuicSocketControl.h"
#include "TCPFastOpenLayer.h"
#include <algorithm>
#include "sslexp.h"
#include "mozilla/net/SSLTokensCache.h"
#include "mozilla/StaticPrefs_network.h"

#include "nsPrintfCString.h"
#include "xpcpublic.h"

#if defined(FUZZING)
#  include "FuzzyLayer.h"
#  include "FuzzySecurityInfo.h"
#  include "mozilla/StaticPrefs_fuzzing.h"
#endif

#if defined(XP_WIN)
#  include "ShutdownLayer.h"
#endif

/* Following inclusions required for keepalive config not supported by NSPR. */
#include "private/pprio.h"
#if defined(XP_WIN)
#  include <winsock2.h>
#  include <mstcpip.h>
#elif defined(XP_UNIX)
#  include <errno.h>
#  include <netinet/tcp.h>
#endif
/* End keepalive config inclusions. */

#define SUCCESSFUL_CONNECTING_TO_IPV4_ADDRESS 0
#define UNSUCCESSFUL_CONNECTING_TO_IPV4_ADDRESS 1
#define SUCCESSFUL_CONNECTING_TO_IPV6_ADDRESS 2
#define UNSUCCESSFUL_CONNECTING_TO_IPV6_ADDRESS 3

//-----------------------------------------------------------------------------

static NS_DEFINE_CID(kDNSServiceCID, NS_DNSSERVICE_CID);

//-----------------------------------------------------------------------------

namespace mozilla {
namespace net {

class nsSocketEvent : public Runnable {
 public:
  nsSocketEvent(nsSocketTransport* transport, uint32_t type,
                nsresult status = NS_OK, nsISupports* param = nullptr)
      : Runnable("net::nsSocketEvent"),
        mTransport(transport),
        mType(type),
        mStatus(status),
        mParam(param) {}

  NS_IMETHOD Run() override {
    mTransport->OnSocketEvent(mType, mStatus, mParam);
    return NS_OK;
  }

 private:
  RefPtr<nsSocketTransport> mTransport;

  uint32_t mType;
  nsresult mStatus;
  nsCOMPtr<nsISupports> mParam;
};

//-----------------------------------------------------------------------------

//#define TEST_CONNECT_ERRORS
#ifdef TEST_CONNECT_ERRORS
#  include <stdlib.h>
static PRErrorCode RandomizeConnectError(PRErrorCode code) {
  //
  // To test out these errors, load http://www.yahoo.com/.  It should load
  // correctly despite the random occurrence of these errors.
  //
  int n = rand();
  if (n > RAND_MAX / 2) {
    struct {
      PRErrorCode err_code;
      const char* err_name;
    } errors[] = {
        //
        // These errors should be recoverable provided there is another
        // IP address in mDNSRecord.
        //
        {PR_CONNECT_REFUSED_ERROR, "PR_CONNECT_REFUSED_ERROR"},
        {PR_CONNECT_TIMEOUT_ERROR, "PR_CONNECT_TIMEOUT_ERROR"},
        //
        // This error will cause this socket transport to error out;
        // however, if the consumer is HTTP, then the HTTP transaction
        // should be restarted when this error occurs.
        //
        {PR_CONNECT_RESET_ERROR, "PR_CONNECT_RESET_ERROR"},
    };
    n = n % (sizeof(errors) / sizeof(errors[0]));
    code = errors[n].err_code;
    SOCKET_LOG(("simulating NSPR error %d [%s]\n", code, errors[n].err_name));
  }
  return code;
}
#endif

//-----------------------------------------------------------------------------

nsresult ErrorAccordingToNSPR(PRErrorCode errorCode) {
  nsresult rv = NS_ERROR_FAILURE;
  switch (errorCode) {
    case PR_WOULD_BLOCK_ERROR:
      rv = NS_BASE_STREAM_WOULD_BLOCK;
      break;
    case PR_CONNECT_ABORTED_ERROR:
    case PR_CONNECT_RESET_ERROR:
      rv = NS_ERROR_NET_RESET;
      break;
    case PR_END_OF_FILE_ERROR:  // XXX document this correlation
      rv = NS_ERROR_NET_INTERRUPT;
      break;
    case PR_CONNECT_REFUSED_ERROR:
    // We lump the following NSPR codes in with PR_CONNECT_REFUSED_ERROR. We
    // could get better diagnostics by adding distinct XPCOM error codes for
    // each of these, but there are a lot of places in Gecko that check
    // specifically for NS_ERROR_CONNECTION_REFUSED, all of which would need to
    // be checked.
    case PR_NETWORK_UNREACHABLE_ERROR:
    case PR_HOST_UNREACHABLE_ERROR:
    case PR_ADDRESS_NOT_AVAILABLE_ERROR:
    // Treat EACCES as a soft error since (at least on Linux) connect() returns
    // EACCES when an IPv6 connection is blocked by a firewall. See bug 270784.
    case PR_NO_ACCESS_RIGHTS_ERROR:
      rv = NS_ERROR_CONNECTION_REFUSED;
      break;
    case PR_ADDRESS_NOT_SUPPORTED_ERROR:
      rv = NS_ERROR_SOCKET_ADDRESS_NOT_SUPPORTED;
      break;
    case PR_IO_TIMEOUT_ERROR:
    case PR_CONNECT_TIMEOUT_ERROR:
      rv = NS_ERROR_NET_TIMEOUT;
      break;
    case PR_OUT_OF_MEMORY_ERROR:
    // These really indicate that the descriptor table filled up, or that the
    // kernel ran out of network buffers - but nobody really cares which part of
    // the system ran out of memory.
    case PR_PROC_DESC_TABLE_FULL_ERROR:
    case PR_SYS_DESC_TABLE_FULL_ERROR:
    case PR_INSUFFICIENT_RESOURCES_ERROR:
      rv = NS_ERROR_OUT_OF_MEMORY;
      break;
    case PR_ADDRESS_IN_USE_ERROR:
      rv = NS_ERROR_SOCKET_ADDRESS_IN_USE;
      break;
    // These filename-related errors can arise when using Unix-domain sockets.
    case PR_FILE_NOT_FOUND_ERROR:
      rv = NS_ERROR_FILE_NOT_FOUND;
      break;
    case PR_IS_DIRECTORY_ERROR:
      rv = NS_ERROR_FILE_IS_DIRECTORY;
      break;
    case PR_LOOP_ERROR:
      rv = NS_ERROR_FILE_UNRESOLVABLE_SYMLINK;
      break;
    case PR_NAME_TOO_LONG_ERROR:
      rv = NS_ERROR_FILE_NAME_TOO_LONG;
      break;
    case PR_NO_DEVICE_SPACE_ERROR:
      rv = NS_ERROR_FILE_NO_DEVICE_SPACE;
      break;
    case PR_NOT_DIRECTORY_ERROR:
      rv = NS_ERROR_FILE_NOT_DIRECTORY;
      break;
    case PR_READ_ONLY_FILESYSTEM_ERROR:
      rv = NS_ERROR_FILE_READ_ONLY;
      break;
    case PR_BAD_ADDRESS_ERROR:
      rv = NS_ERROR_UNKNOWN_HOST;
      break;
    default:
      if (psm::IsNSSErrorCode(errorCode)) {
        rv = psm::GetXPCOMFromNSSError(errorCode);
      }
      break;

      // NSPR's socket code can return these, but they're not worth breaking out
      // into their own error codes, distinct from NS_ERROR_FAILURE:
      //
      // PR_BAD_DESCRIPTOR_ERROR
      // PR_INVALID_ARGUMENT_ERROR
      // PR_NOT_SOCKET_ERROR
      // PR_NOT_TCP_SOCKET_ERROR
      //   These would indicate a bug internal to the component.
      //
      // PR_PROTOCOL_NOT_SUPPORTED_ERROR
      //   This means that we can't use the given "protocol" (like
      //   IPPROTO_TCP or IPPROTO_UDP) with a socket of the given type. As
      //   above, this indicates an internal bug.
      //
      // PR_IS_CONNECTED_ERROR
      //   This indicates that we've applied a system call like 'bind' or
      //   'connect' to a socket that is already connected. The socket
      //   components manage each file descriptor's state, and in some cases
      //   handle this error result internally. We shouldn't be returning
      //   this to our callers.
      //
      // PR_IO_ERROR
      //   This is so vague that NS_ERROR_FAILURE is just as good.
  }
  SOCKET_LOG(("ErrorAccordingToNSPR [in=%d out=%" PRIx32 "]\n", errorCode,
              static_cast<uint32_t>(rv)));
  return rv;
}

//-----------------------------------------------------------------------------
// socket input stream impl
//-----------------------------------------------------------------------------

nsSocketInputStream::nsSocketInputStream(nsSocketTransport* trans)
    : mTransport(trans),
      mReaderRefCnt(0),
      mCondition(NS_OK),
      mCallbackFlags(0),
      mByteCount(0) {}

// called on the socket transport thread...
//
//   condition : failure code if socket has been closed
//
void nsSocketInputStream::OnSocketReady(nsresult condition) {
  SOCKET_LOG(("nsSocketInputStream::OnSocketReady [this=%p cond=%" PRIx32 "]\n",
              this, static_cast<uint32_t>(condition)));

  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  nsCOMPtr<nsIInputStreamCallback> callback;
  {
    MutexAutoLock lock(mTransport->mLock);

    // update condition, but be careful not to erase an already
    // existing error condition.
    if (NS_SUCCEEDED(mCondition)) mCondition = condition;

    // ignore event if only waiting for closure and not closed.
    if (NS_FAILED(mCondition) || !(mCallbackFlags & WAIT_CLOSURE_ONLY)) {
      callback = std::move(mCallback);
      mCallbackFlags = 0;
    }
  }

  if (callback) callback->OnInputStreamReady(this);
}

NS_IMPL_QUERY_INTERFACE(nsSocketInputStream, nsIInputStream,
                        nsIAsyncInputStream)

NS_IMETHODIMP_(MozExternalRefCountType)
nsSocketInputStream::AddRef() {
  ++mReaderRefCnt;
  return mTransport->AddRef();
}

NS_IMETHODIMP_(MozExternalRefCountType)
nsSocketInputStream::Release() {
  if (--mReaderRefCnt == 0) Close();
  return mTransport->Release();
}

NS_IMETHODIMP
nsSocketInputStream::Close() { return CloseWithStatus(NS_BASE_STREAM_CLOSED); }

NS_IMETHODIMP
nsSocketInputStream::Available(uint64_t* avail) {
  SOCKET_LOG(("nsSocketInputStream::Available [this=%p]\n", this));

  *avail = 0;

  PRFileDesc* fd;
  {
    MutexAutoLock lock(mTransport->mLock);

    if (NS_FAILED(mCondition)) return mCondition;

    fd = mTransport->GetFD_Locked();
    if (!fd) return NS_OK;
  }

  // cannot hold lock while calling NSPR.  (worried about the fact that PSM
  // synchronously proxies notifications over to the UI thread, which could
  // mistakenly try to re-enter this code.)
  int32_t n = PR_Available(fd);

  // PSM does not implement PR_Available() so do a best approximation of it
  // with MSG_PEEK
  if ((n == -1) && (PR_GetError() == PR_NOT_IMPLEMENTED_ERROR)) {
    char c;

    n = PR_Recv(fd, &c, 1, PR_MSG_PEEK, 0);
    SOCKET_LOG(
        ("nsSocketInputStream::Available [this=%p] "
         "using PEEK backup n=%d]\n",
         this, n));
  }

  nsresult rv;
  {
    MutexAutoLock lock(mTransport->mLock);

    mTransport->ReleaseFD_Locked(fd);

    if (n >= 0)
      *avail = n;
    else {
      PRErrorCode code = PR_GetError();
      if (code == PR_WOULD_BLOCK_ERROR) return NS_OK;
      mCondition = ErrorAccordingToNSPR(code);
    }
    rv = mCondition;
  }
  if (NS_FAILED(rv)) mTransport->OnInputClosed(rv);
  return rv;
}

NS_IMETHODIMP
nsSocketInputStream::Read(char* buf, uint32_t count, uint32_t* countRead) {
  SOCKET_LOG(("nsSocketInputStream::Read [this=%p count=%u]\n", this, count));

  *countRead = 0;

  PRFileDesc* fd = nullptr;
  {
    MutexAutoLock lock(mTransport->mLock);

    if (NS_FAILED(mCondition))
      return (mCondition == NS_BASE_STREAM_CLOSED) ? NS_OK : mCondition;

    fd = mTransport->GetFD_Locked();
    if (!fd) return NS_BASE_STREAM_WOULD_BLOCK;
  }

  SOCKET_LOG(("  calling PR_Read [count=%u]\n", count));

  // cannot hold lock while calling NSPR.  (worried about the fact that PSM
  // synchronously proxies notifications over to the UI thread, which could
  // mistakenly try to re-enter this code.)
  int32_t n = PR_Read(fd, buf, count);

  SOCKET_LOG(("  PR_Read returned [n=%d]\n", n));

  nsresult rv = NS_OK;
  {
    MutexAutoLock lock(mTransport->mLock);

#ifdef ENABLE_SOCKET_TRACING
    if (n > 0) mTransport->TraceInBuf(buf, n);
#endif

    mTransport->ReleaseFD_Locked(fd);

    if (n > 0)
      mByteCount += (*countRead = n);
    else if (n < 0) {
      PRErrorCode code = PR_GetError();
      if (code == PR_WOULD_BLOCK_ERROR) return NS_BASE_STREAM_WOULD_BLOCK;
      mCondition = ErrorAccordingToNSPR(code);
    }
    rv = mCondition;
  }
  if (NS_FAILED(rv)) mTransport->OnInputClosed(rv);

  // only send this notification if we have indeed read some data.
  // see bug 196827 for an example of why this is important.
  if (n > 0) mTransport->SendStatus(NS_NET_STATUS_RECEIVING_FROM);
  return rv;
}

NS_IMETHODIMP
nsSocketInputStream::ReadSegments(nsWriteSegmentFun writer, void* closure,
                                  uint32_t count, uint32_t* countRead) {
  // socket stream is unbuffered
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsSocketInputStream::IsNonBlocking(bool* nonblocking) {
  *nonblocking = true;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketInputStream::CloseWithStatus(nsresult reason) {
  SOCKET_LOG(("nsSocketInputStream::CloseWithStatus [this=%p reason=%" PRIx32
              "]\n",
              this, static_cast<uint32_t>(reason)));

  // may be called from any thread

  nsresult rv;
  {
    MutexAutoLock lock(mTransport->mLock);

    if (NS_SUCCEEDED(mCondition))
      rv = mCondition = reason;
    else
      rv = NS_OK;
  }
  if (NS_FAILED(rv)) mTransport->OnInputClosed(rv);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketInputStream::AsyncWait(nsIInputStreamCallback* callback, uint32_t flags,
                               uint32_t amount, nsIEventTarget* target) {
  SOCKET_LOG(("nsSocketInputStream::AsyncWait [this=%p]\n", this));

  bool hasError = false;
  {
    MutexAutoLock lock(mTransport->mLock);

    if (callback && target) {
      //
      // build event proxy
      //
      mCallback = NS_NewInputStreamReadyEvent("nsSocketInputStream::AsyncWait",
                                              callback, target);
    } else
      mCallback = callback;
    mCallbackFlags = flags;

    hasError = NS_FAILED(mCondition);
  }  // unlock mTransport->mLock

  if (hasError) {
    // OnSocketEvent will call OnInputStreamReady with an error code after
    // going through the event loop. We do this because most socket callers
    // do not expect AsyncWait() to synchronously execute the OnInputStreamReady
    // callback.
    mTransport->PostEvent(nsSocketTransport::MSG_INPUT_PENDING);
  } else {
    mTransport->OnInputPending();
  }

  return NS_OK;
}

//-----------------------------------------------------------------------------
// socket output stream impl
//-----------------------------------------------------------------------------

nsSocketOutputStream::nsSocketOutputStream(nsSocketTransport* trans)
    : mTransport(trans),
      mWriterRefCnt(0),
      mCondition(NS_OK),
      mCallbackFlags(0),
      mByteCount(0) {}

// called on the socket transport thread...
//
//   condition : failure code if socket has been closed
//
void nsSocketOutputStream::OnSocketReady(nsresult condition) {
  SOCKET_LOG(("nsSocketOutputStream::OnSocketReady [this=%p cond=%" PRIx32
              "]\n",
              this, static_cast<uint32_t>(condition)));

  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  nsCOMPtr<nsIOutputStreamCallback> callback;
  {
    MutexAutoLock lock(mTransport->mLock);

    // update condition, but be careful not to erase an already
    // existing error condition.
    if (NS_SUCCEEDED(mCondition)) mCondition = condition;

    // ignore event if only waiting for closure and not closed.
    if (NS_FAILED(mCondition) || !(mCallbackFlags & WAIT_CLOSURE_ONLY)) {
      callback = std::move(mCallback);
      mCallbackFlags = 0;
    }
  }

  if (callback) callback->OnOutputStreamReady(this);
}

NS_IMPL_QUERY_INTERFACE(nsSocketOutputStream, nsIOutputStream,
                        nsIAsyncOutputStream)

NS_IMETHODIMP_(MozExternalRefCountType)
nsSocketOutputStream::AddRef() {
  ++mWriterRefCnt;
  return mTransport->AddRef();
}

NS_IMETHODIMP_(MozExternalRefCountType)
nsSocketOutputStream::Release() {
  if (--mWriterRefCnt == 0) Close();
  return mTransport->Release();
}

NS_IMETHODIMP
nsSocketOutputStream::Close() { return CloseWithStatus(NS_BASE_STREAM_CLOSED); }

NS_IMETHODIMP
nsSocketOutputStream::Flush() { return NS_OK; }

NS_IMETHODIMP
nsSocketOutputStream::Write(const char* buf, uint32_t count,
                            uint32_t* countWritten) {
  SOCKET_LOG(("nsSocketOutputStream::Write [this=%p count=%u]\n", this, count));

  *countWritten = 0;

  // A write of 0 bytes can be used to force the initial SSL handshake, so do
  // not reject that.

  PRFileDesc* fd = nullptr;
  bool fastOpenInProgress;
  {
    MutexAutoLock lock(mTransport->mLock);

    if (NS_FAILED(mCondition)) return mCondition;

    fd = mTransport->GetFD_LockedAlsoDuringFastOpen();
    if (!fd) return NS_BASE_STREAM_WOULD_BLOCK;

    fastOpenInProgress = mTransport->FastOpenInProgress();
  }

  if (fastOpenInProgress) {
    // If we are in the fast open phase, we should not write more data
    // than TCPFastOpenLayer can accept. If we write more data, this data
    // will be buffered in tls and we want to avoid that.
    uint32_t availableSpace = TCPFastOpenGetBufferSizeLeft(fd);
    count = (count > availableSpace) ? availableSpace : count;
    if (!count) {
      {
        MutexAutoLock lock(mTransport->mLock);
        mTransport->ReleaseFD_Locked(fd);
      }
      return NS_BASE_STREAM_WOULD_BLOCK;
    }
  }

  SOCKET_LOG(("  calling PR_Write [count=%u]\n", count));

  // cannot hold lock while calling NSPR.  (worried about the fact that PSM
  // synchronously proxies notifications over to the UI thread, which could
  // mistakenly try to re-enter this code.)
  int32_t n = PR_Write(fd, buf, count);

  SOCKET_LOG(("  PR_Write returned [n=%d]\n", n));

  nsresult rv = NS_OK;
  {
    MutexAutoLock lock(mTransport->mLock);

#ifdef ENABLE_SOCKET_TRACING
    if (n > 0) mTransport->TraceOutBuf(buf, n);
#endif

    mTransport->ReleaseFD_Locked(fd);

    if (n > 0)
      mByteCount += (*countWritten = n);
    else if (n < 0) {
      PRErrorCode code = PR_GetError();
      if (code == PR_WOULD_BLOCK_ERROR) return NS_BASE_STREAM_WOULD_BLOCK;
      mCondition = ErrorAccordingToNSPR(code);
    }
    rv = mCondition;
  }
  if (NS_FAILED(rv)) mTransport->OnOutputClosed(rv);

  // only send this notification if we have indeed written some data.
  // see bug 196827 for an example of why this is important.
  // During a fast open we are actually not sending data, the data will be
  // only buffered in the TCPFastOpenLayer. Therefore we will call
  // SendStatus(NS_NET_STATUS_SENDING_TO) when we really send data (i.e. when
  // TCPFastOpenFinish is called.
  if ((n > 0) && !fastOpenInProgress) {
    mTransport->SendStatus(NS_NET_STATUS_SENDING_TO);
  }

  return rv;
}

NS_IMETHODIMP
nsSocketOutputStream::WriteSegments(nsReadSegmentFun reader, void* closure,
                                    uint32_t count, uint32_t* countRead) {
  // socket stream is unbuffered
  return NS_ERROR_NOT_IMPLEMENTED;
}

nsresult nsSocketOutputStream::WriteFromSegments(
    nsIInputStream* input, void* closure, const char* fromSegment,
    uint32_t offset, uint32_t count, uint32_t* countRead) {
  nsSocketOutputStream* self = (nsSocketOutputStream*)closure;
  return self->Write(fromSegment, count, countRead);
}

NS_IMETHODIMP
nsSocketOutputStream::WriteFrom(nsIInputStream* stream, uint32_t count,
                                uint32_t* countRead) {
  return stream->ReadSegments(WriteFromSegments, this, count, countRead);
}

NS_IMETHODIMP
nsSocketOutputStream::IsNonBlocking(bool* nonblocking) {
  *nonblocking = true;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketOutputStream::CloseWithStatus(nsresult reason) {
  SOCKET_LOG(("nsSocketOutputStream::CloseWithStatus [this=%p reason=%" PRIx32
              "]\n",
              this, static_cast<uint32_t>(reason)));

  // may be called from any thread

  nsresult rv;
  {
    MutexAutoLock lock(mTransport->mLock);

    if (NS_SUCCEEDED(mCondition))
      rv = mCondition = reason;
    else
      rv = NS_OK;
  }
  if (NS_FAILED(rv)) mTransport->OnOutputClosed(rv);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketOutputStream::AsyncWait(nsIOutputStreamCallback* callback,
                                uint32_t flags, uint32_t amount,
                                nsIEventTarget* target) {
  SOCKET_LOG(("nsSocketOutputStream::AsyncWait [this=%p]\n", this));

  {
    MutexAutoLock lock(mTransport->mLock);

    if (callback && target) {
      //
      // build event proxy
      //
      mCallback = NS_NewOutputStreamReadyEvent(callback, target);
    } else
      mCallback = callback;

    mCallbackFlags = flags;
  }
  mTransport->OnOutputPending();
  return NS_OK;
}

//-----------------------------------------------------------------------------
// socket transport impl
//-----------------------------------------------------------------------------

nsSocketTransport::nsSocketTransport()
    : mPort(0),
      mProxyPort(0),
      mOriginPort(0),
      mProxyTransparent(false),
      mProxyTransparentResolvesHost(false),
      mHttpsProxy(false),
      mConnectionFlags(0),
      mResetFamilyPreference(false),
      mTlsFlags(0),
      mReuseAddrPort(false),
      mState(STATE_CLOSED),
      mAttached(false),
      mInputClosed(true),
      mOutputClosed(true),
      mResolving(false),
      mEchConfigUsed(false),
      mResolvedByTRR(false),
      mNetAddrIsSet(false),
      mSelfAddrIsSet(false),
      mLock("nsSocketTransport.mLock"),
      mFD(this),
      mFDref(0),
      mFDconnected(false),
      mFDFastOpenInProgress(false),
      mSocketTransportService(gSocketTransportService),
      mInput(this),
      mOutput(this),
      mLingerPolarity(false),
      mLingerTimeout(0),
      mQoSBits(0x00),
      mKeepaliveEnabled(false),
      mKeepaliveIdleTimeS(-1),
      mKeepaliveRetryIntervalS(-1),
      mKeepaliveProbeCount(-1),
      mFastOpenCallback(nullptr),
      mFastOpenLayerHasBufferedData(false),
      mFastOpenStatus(TFO_NOT_SET),
      mFirstRetryError(NS_OK),
      mDoNotRetryToConnect(false),
      mUsingQuic(false) {
  this->mNetAddr.raw.family = 0;
  this->mNetAddr.inet = {};
  this->mSelfAddr.raw.family = 0;
  this->mSelfAddr.inet = {};
  SOCKET_LOG(("creating nsSocketTransport @%p\n", this));

  mTimeouts[TIMEOUT_CONNECT] = UINT16_MAX;     // no timeout
  mTimeouts[TIMEOUT_READ_WRITE] = UINT16_MAX;  // no timeout
}

nsSocketTransport::~nsSocketTransport() {
  SOCKET_LOG(("destroying nsSocketTransport @%p\n", this));
}

nsresult nsSocketTransport::Init(const nsTArray<nsCString>& types,
                                 const nsACString& host, uint16_t port,
                                 const nsACString& hostRoute,
                                 uint16_t portRoute,
                                 nsIProxyInfo* givenProxyInfo) {
  nsCOMPtr<nsProxyInfo> proxyInfo;
  if (givenProxyInfo) {
    proxyInfo = do_QueryInterface(givenProxyInfo);
    NS_ENSURE_ARG(proxyInfo);
  }

  // init socket type info

  mOriginHost = host;
  mOriginPort = port;
  if (!hostRoute.IsEmpty()) {
    mHost = hostRoute;
    mPort = portRoute;
  } else {
    mHost = host;
    mPort = port;
  }

  // A subtle check we don't enter this method more than once for the socket
  // transport lifetime.  Disable on TSan builds to prevent race checking, we
  // don't want an atomic here for perf reasons!
#ifndef MOZ_TSAN
  MOZ_ASSERT(!mPortRemappingApplied);
#endif  // !MOZ_TSAN

  if (proxyInfo) {
    mHttpsProxy = proxyInfo->IsHTTPS();
  }

  const char* proxyType = nullptr;
  mProxyInfo = proxyInfo;
  if (proxyInfo) {
    mProxyPort = proxyInfo->Port();
    mProxyHost = proxyInfo->Host();
    // grab proxy type (looking for "socks" for example)
    proxyType = proxyInfo->Type();
    if (proxyType && (proxyInfo->IsHTTP() || proxyInfo->IsHTTPS() ||
                      proxyInfo->IsDirect() || !strcmp(proxyType, "unknown"))) {
      proxyType = nullptr;
    }
  }

  SOCKET_LOG1(
      ("nsSocketTransport::Init [this=%p host=%s:%hu origin=%s:%d "
       "proxy=%s:%hu]\n",
       this, mHost.get(), mPort, mOriginHost.get(), mOriginPort,
       mProxyHost.get(), mProxyPort));

  // include proxy type as a socket type if proxy type is not "http"
  uint32_t typeCount = types.Length() + (proxyType != nullptr);
  if (!typeCount) return NS_OK;

  // if we have socket types, then the socket provider service had
  // better exist!
  nsresult rv;
  nsCOMPtr<nsISocketProviderService> spserv =
      nsSocketProviderService::GetOrCreate();

  if (!mTypes.SetCapacity(typeCount, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // now verify that each socket type has a registered socket provider.
  for (uint32_t i = 0, type = 0; i < typeCount; ++i) {
    // store socket types
    if (i == 0 && proxyType)
      mTypes.AppendElement(proxyType);
    else
      mTypes.AppendElement(types[type++]);

    // quic does not have a socketProvider.
    if (!mTypes[i].EqualsLiteral("quic")) {
      nsCOMPtr<nsISocketProvider> provider;
      rv = spserv->GetSocketProvider(mTypes[i].get(), getter_AddRefs(provider));
      if (NS_FAILED(rv)) {
        NS_WARNING("no registered socket provider");
        return rv;
      }
    }

    // note if socket type corresponds to a transparent proxy
    // XXX don't hardcode SOCKS here (use proxy info's flags instead).
    if (mTypes[i].EqualsLiteral("socks") || mTypes[i].EqualsLiteral("socks4")) {
      mProxyTransparent = true;

      if (proxyInfo->Flags() & nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST) {
        // we want the SOCKS layer to send the hostname
        // and port to the proxy and let it do the DNS.
        mProxyTransparentResolvesHost = true;
      }
    }
  }

  return NS_OK;
}

#if defined(XP_UNIX)
nsresult nsSocketTransport::InitWithFilename(const char* filename) {
  return InitWithName(filename, strlen(filename));
}

nsresult nsSocketTransport::InitWithName(const char* name, size_t length) {
  if (length > sizeof(mNetAddr.local.path) - 1) {
    return NS_ERROR_FILE_NAME_TOO_LONG;
  }

  if (!name[0] && length > 1) {
    // name is abstract address name that is supported on Linux only
#  if defined(XP_LINUX)
    mHost.Assign(name + 1, length - 1);
#  else
    return NS_ERROR_SOCKET_ADDRESS_NOT_SUPPORTED;
#  endif
  } else {
    // The name isn't abstract socket address.  So this is Unix domain
    // socket that has file path.
    mHost.Assign(name, length);
  }
  mPort = 0;

  mNetAddr.local.family = AF_LOCAL;
  memcpy(mNetAddr.local.path, name, length);
  mNetAddr.local.path[length] = '\0';
  mNetAddrIsSet = true;

  return NS_OK;
}
#endif

nsresult nsSocketTransport::InitWithConnectedSocket(PRFileDesc* fd,
                                                    const NetAddr* addr) {
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
  NS_ASSERTION(!mFD.IsInitialized(), "already initialized");

  char buf[kNetAddrMaxCStrBufSize];
  addr->ToStringBuffer(buf, sizeof(buf));
  mHost.Assign(buf);

  uint16_t port;
  if (addr->raw.family == AF_INET)
    port = addr->inet.port;
  else if (addr->raw.family == AF_INET6)
    port = addr->inet6.port;
  else
    port = 0;
  mPort = ntohs(port);

  memcpy(&mNetAddr, addr, sizeof(NetAddr));

  mPollFlags = (PR_POLL_READ | PR_POLL_WRITE | PR_POLL_EXCEPT);
  mState = STATE_TRANSFERRING;
  SetSocketName(fd);
  mNetAddrIsSet = true;

  {
    MutexAutoLock lock(mLock);

    mFD = fd;
    mFDref = 1;
    mFDconnected = true;
    mPollTimeout = mTimeouts[TIMEOUT_READ_WRITE];
  }

  // make sure new socket is non-blocking
  PRSocketOptionData opt;
  opt.option = PR_SockOpt_Nonblocking;
  opt.value.non_blocking = true;
  PR_SetSocketOption(fd, &opt);

  SOCKET_LOG(
      ("nsSocketTransport::InitWithConnectedSocket [this=%p addr=%s:%hu]\n",
       this, mHost.get(), mPort));

  // jump to InitiateSocket to get ourselves attached to the STS poll list.
  return PostEvent(MSG_RETRY_INIT_SOCKET);
}

nsresult nsSocketTransport::InitWithConnectedSocket(PRFileDesc* aFD,
                                                    const NetAddr* aAddr,
                                                    nsISupports* aSecInfo) {
  mSecInfo = aSecInfo;
  return InitWithConnectedSocket(aFD, aAddr);
}

nsresult nsSocketTransport::PostEvent(uint32_t type, nsresult status,
                                      nsISupports* param) {
  SOCKET_LOG(("nsSocketTransport::PostEvent [this=%p type=%u status=%" PRIx32
              " param=%p]\n",
              this, type, static_cast<uint32_t>(status), param));

  nsCOMPtr<nsIRunnable> event = new nsSocketEvent(this, type, status, param);
  if (!event) return NS_ERROR_OUT_OF_MEMORY;

  return mSocketTransportService->Dispatch(event, NS_DISPATCH_NORMAL);
}

void nsSocketTransport::SendStatus(nsresult status) {
  SOCKET_LOG1(("nsSocketTransport::SendStatus [this=%p status=%" PRIx32 "]\n",
               this, static_cast<uint32_t>(status)));

  nsCOMPtr<nsITransportEventSink> sink;
  uint64_t progress;
  {
    MutexAutoLock lock(mLock);
    sink = mEventSink;
    switch (status) {
      case NS_NET_STATUS_SENDING_TO:
        progress = mOutput.ByteCount();
        // If Fast Open is used, we buffer some data in TCPFastOpenLayer,
        // This data can  be only tls data or application data as well.
        // socketTransport should send status only if it really has sent
        // application data. socketTransport cannot query transaction for
        // that info but it can know if transaction has send data if
        // mOutput.ByteCount() is > 0.
        if (progress == 0) {
          return;
        }
        break;
      case NS_NET_STATUS_RECEIVING_FROM:
        progress = mInput.ByteCount();
        break;
      default:
        progress = 0;
        break;
    }
  }
  if (sink) {
    sink->OnTransportStatus(this, status, progress, -1);
  }
}

nsresult nsSocketTransport::ResolveHost() {
  SOCKET_LOG((
      "nsSocketTransport::ResolveHost [this=%p %s:%d%s] "
      "mProxyTransparentResolvesHost=%d\n",
      this, SocketHost().get(), SocketPort(),
      mConnectionFlags & nsSocketTransport::BYPASS_CACHE ? " bypass cache" : "",
      mProxyTransparentResolvesHost));

  nsresult rv;

  if (!mProxyHost.IsEmpty()) {
    if (!mProxyTransparent || mProxyTransparentResolvesHost) {
#if defined(XP_UNIX)
      MOZ_ASSERT(!mNetAddrIsSet || mNetAddr.raw.family != AF_LOCAL,
                 "Unix domain sockets can't be used with proxies");
#endif
      // When not resolving mHost locally, we still want to ensure that
      // it only contains valid characters.  See bug 304904 for details.
      // Sometimes the end host is not yet known and mHost is *
      if (!net_IsValidHostName(mHost) && !mHost.EqualsLiteral("*")) {
        SOCKET_LOG(("  invalid hostname %s\n", mHost.get()));
        return NS_ERROR_UNKNOWN_HOST;
      }
    }
    if (mProxyTransparentResolvesHost) {
      // Name resolution is done on the server side.  Just pretend
      // client resolution is complete, this will get picked up later.
      // since we don't need to do DNS now, we bypass the resolving
      // step by initializing mNetAddr to an empty address, but we
      // must keep the port. The SOCKS IO layer will use the hostname
      // we send it when it's created, rather than the empty address
      // we send with the connect call.
      mState = STATE_RESOLVING;
      mNetAddr.raw.family = AF_INET;
      mNetAddr.inet.port = htons(SocketPort());
      mNetAddr.inet.ip = htonl(INADDR_ANY);
      return PostEvent(MSG_DNS_LOOKUP_COMPLETE, NS_OK, nullptr);
    }
  }

  nsCOMPtr<nsIDNSService> dns = nullptr;
  auto initTask = [&dns]() { dns = do_GetService(kDNSServiceCID); };
  if (!NS_IsMainThread()) {
    // Forward to the main thread synchronously.
    RefPtr<nsIThread> mainThread = do_GetMainThread();
    if (!mainThread) {
      return NS_ERROR_FAILURE;
    }

    SyncRunnable::DispatchToThread(
        mainThread,
        new SyncRunnable(NS_NewRunnableFunction(
            "nsSocketTransport::ResolveHost->GetDNSService", initTask)));
  } else {
    initTask();
  }
  if (!dns) {
    return NS_ERROR_FAILURE;
  }

  mResolving = true;

  uint32_t dnsFlags = 0;
  if (mConnectionFlags & nsSocketTransport::BYPASS_CACHE)
    dnsFlags = nsIDNSService::RESOLVE_BYPASS_CACHE;
  if (mConnectionFlags & nsSocketTransport::REFRESH_CACHE)
    dnsFlags = nsIDNSService::RESOLVE_REFRESH_CACHE;
  if (mConnectionFlags & nsSocketTransport::DISABLE_IPV6)
    dnsFlags |= nsIDNSService::RESOLVE_DISABLE_IPV6;
  if (mConnectionFlags & nsSocketTransport::DISABLE_IPV4)
    dnsFlags |= nsIDNSService::RESOLVE_DISABLE_IPV4;
  if (mConnectionFlags & nsSocketTransport::DISABLE_TRR)
    dnsFlags |= nsIDNSService::RESOLVE_DISABLE_TRR;

  if (mConnectionFlags & nsSocketTransport::USE_IP_HINT_ADDRESS) {
    dnsFlags |= nsIDNSService::RESOLVE_IP_HINT;
  }

  dnsFlags |= nsIDNSService::GetFlagsFromTRRMode(
      nsISocketTransport::GetTRRModeFromFlags(mConnectionFlags));

  // When we get here, we are not resolving using any configured proxy likely
  // because of individual proxy setting on the request or because the host is
  // excluded from proxying.  Hence, force resolution despite global proxy-DNS
  // configuration.
  dnsFlags |= nsIDNSService::RESOLVE_IGNORE_SOCKS_DNS;

  NS_ASSERTION(!(dnsFlags & nsIDNSService::RESOLVE_DISABLE_IPV6) ||
                   !(dnsFlags & nsIDNSService::RESOLVE_DISABLE_IPV4),
               "Setting both RESOLVE_DISABLE_IPV6 and RESOLVE_DISABLE_IPV4");

  SendStatus(NS_NET_STATUS_RESOLVING_HOST);

  if (!SocketHost().Equals(mOriginHost)) {
    SOCKET_LOG(("nsSocketTransport %p origin %s doing dns for %s\n", this,
                mOriginHost.get(), SocketHost().get()));
  }
  rv =
      dns->AsyncResolveNative(SocketHost(), nsIDNSService::RESOLVE_TYPE_DEFAULT,
                              dnsFlags, nullptr, this, mSocketTransportService,
                              mOriginAttributes, getter_AddRefs(mDNSRequest));

  if (NS_SUCCEEDED(rv)) {
    SOCKET_LOG(("  advancing to STATE_RESOLVING\n"));
    mState = STATE_RESOLVING;
  }
  return rv;
}

nsresult nsSocketTransport::BuildSocket(PRFileDesc*& fd, bool& proxyTransparent,
                                        bool& usingSSL) {
  SOCKET_LOG(("nsSocketTransport::BuildSocket [this=%p]\n", this));

  nsresult rv = NS_OK;

  proxyTransparent = false;
  usingSSL = false;

  if (mTypes.IsEmpty()) {
    fd = PR_OpenTCPSocket(mNetAddr.raw.family);
    if (!fd) {
      SOCKET_LOG(("  error creating TCP nspr socket [rv=%" PRIx32 "]\n",
                  static_cast<uint32_t>(rv)));
      return NS_ERROR_OUT_OF_MEMORY;
    }
    return NS_OK;
  }

#if defined(XP_UNIX)
  MOZ_ASSERT(!mNetAddrIsSet || mNetAddr.raw.family != AF_LOCAL,
             "Unix domain sockets can't be used with socket types");
#endif

  fd = nullptr;

  uint32_t controlFlags = 0;
  if (mProxyTransparentResolvesHost)
    controlFlags |= nsISocketProvider::PROXY_RESOLVES_HOST;

  if (mConnectionFlags & nsISocketTransport::ANONYMOUS_CONNECT)
    controlFlags |= nsISocketProvider::ANONYMOUS_CONNECT;

  if (mConnectionFlags & nsISocketTransport::NO_PERMANENT_STORAGE)
    controlFlags |= nsISocketProvider::NO_PERMANENT_STORAGE;

  if (mConnectionFlags & nsISocketTransport::BE_CONSERVATIVE)
    controlFlags |= nsISocketProvider::BE_CONSERVATIVE;

  // by setting host to mOriginHost, instead of mHost we send the
  // SocketProvider (e.g. PSM) the origin hostname but can still do DNS
  // on an explicit alternate service host name
  const char* host = mOriginHost.get();
  int32_t port = (int32_t)mOriginPort;

  if (mTypes[0].EqualsLiteral("quic")) {
    fd = PR_OpenUDPSocket(mNetAddr.raw.family);
    if (!fd) {
      SOCKET_LOG(("  error creating UDP nspr socket [rv=%" PRIx32 "]\n",
                  static_cast<uint32_t>(rv)));
      return NS_ERROR_OUT_OF_MEMORY;
    }

    mUsingQuic = true;
    // Create security control and info object for quic.
    RefPtr<QuicSocketControl> quicCtrl = new QuicSocketControl(controlFlags);
    quicCtrl->SetHostName(mHttpsProxy ? mProxyHost.get() : host);
    quicCtrl->SetPort(mHttpsProxy ? mProxyPort : port);
    nsCOMPtr<nsISupports> secinfo;
    quicCtrl->QueryInterface(NS_GET_IID(nsISupports), (void**)(&secinfo));

    // remember security info and give notification callbacks to PSM...
    nsCOMPtr<nsIInterfaceRequestor> callbacks;
    {
      MutexAutoLock lock(mLock);
      mSecInfo = secinfo;
      callbacks = mCallbacks;
      SOCKET_LOG(
          ("  [secinfo=%p callbacks=%p]\n", mSecInfo.get(), mCallbacks.get()));
    }
    // don't call into PSM while holding mLock!!
    quicCtrl->SetNotificationCallbacks(callbacks);

    return NS_OK;
  }

  nsCOMPtr<nsISocketProviderService> spserv =
      nsSocketProviderService::GetOrCreate();
  nsCOMPtr<nsIProxyInfo> proxyInfo = mProxyInfo;

  uint32_t i;
  for (i = 0; i < mTypes.Length(); ++i) {
    nsCOMPtr<nsISocketProvider> provider;

    SOCKET_LOG(("  pushing io layer [%u:%s]\n", i, mTypes[i].get()));

    rv = spserv->GetSocketProvider(mTypes[i].get(), getter_AddRefs(provider));
    if (NS_FAILED(rv)) break;

    nsCOMPtr<nsISupports> secinfo;
    if (i == 0) {
      // if this is the first type, we'll want the
      // service to allocate a new socket

      // Most layers _ESPECIALLY_ PSM want the origin name here as they
      // will use it for secure checks, etc.. and any connection management
      // differences between the origin name and the routed name can be
      // taken care of via DNS. However, SOCKS is a special case as there is
      // no DNS. in the case of SOCKS and PSM the PSM is a separate layer
      // and receives the origin name.
      const char* socketProviderHost = host;
      int32_t socketProviderPort = port;
      if (mProxyTransparentResolvesHost &&
          (mTypes[0].EqualsLiteral("socks") ||
           mTypes[0].EqualsLiteral("socks4"))) {
        SOCKET_LOG(("SOCKS %d Host/Route override: %s:%d -> %s:%d\n",
                    mHttpsProxy, socketProviderHost, socketProviderPort,
                    mHost.get(), mPort));
        socketProviderHost = mHost.get();
        socketProviderPort = mPort;
      }

      // when https proxying we want to just connect to the proxy as if
      // it were the end host (i.e. expect the proxy's cert)

      rv = provider->NewSocket(
          mNetAddr.raw.family,
          mHttpsProxy ? mProxyHost.get() : socketProviderHost,
          mHttpsProxy ? mProxyPort : socketProviderPort, proxyInfo,
          mOriginAttributes, controlFlags, mTlsFlags, &fd,
          getter_AddRefs(secinfo));

      if (NS_SUCCEEDED(rv) && !fd) {
        MOZ_ASSERT_UNREACHABLE(
            "NewSocket succeeded but failed to "
            "create a PRFileDesc");
        rv = NS_ERROR_UNEXPECTED;
      }
    } else {
      // the socket has already been allocated,
      // so we just want the service to add itself
      // to the stack (such as pushing an io layer)
      rv = provider->AddToSocket(mNetAddr.raw.family, host, port, proxyInfo,
                                 mOriginAttributes, controlFlags, mTlsFlags, fd,
                                 getter_AddRefs(secinfo));
    }

    // controlFlags = 0; not used below this point...
    if (NS_FAILED(rv)) break;

    // if the service was ssl or starttls, we want to hold onto the socket
    // info
    bool isSSL = mTypes[i].EqualsLiteral("ssl");
    if (isSSL || mTypes[i].EqualsLiteral("starttls")) {
      // remember security info and give notification callbacks to PSM...
      nsCOMPtr<nsIInterfaceRequestor> callbacks;
      {
        MutexAutoLock lock(mLock);
        mSecInfo = secinfo;
        callbacks = mCallbacks;
        SOCKET_LOG(("  [secinfo=%p callbacks=%p]\n", mSecInfo.get(),
                    mCallbacks.get()));
      }
      // don't call into PSM while holding mLock!!
      nsCOMPtr<nsISSLSocketControl> secCtrl(do_QueryInterface(secinfo));
      if (secCtrl) secCtrl->SetNotificationCallbacks(callbacks);
      // remember if socket type is SSL so we can ProxyStartSSL if need be.
      usingSSL = isSSL;
    } else if (mTypes[i].EqualsLiteral("socks") ||
               mTypes[i].EqualsLiteral("socks4")) {
      // since socks is transparent, any layers above
      // it do not have to worry about proxy stuff
      proxyInfo = nullptr;
      proxyTransparent = true;
    }
  }

  if (NS_FAILED(rv)) {
    SOCKET_LOG(("  error pushing io layer [%u:%s rv=%" PRIx32 "]\n", i,
                mTypes[i].get(), static_cast<uint32_t>(rv)));
    if (fd) {
      CloseSocket(
          fd, mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase());
    }
  }
  return rv;
}

nsresult nsSocketTransport::InitiateSocket() {
  SOCKET_LOG(("nsSocketTransport::InitiateSocket [this=%p]\n", this));

  nsresult rv;
  bool isLocal;
  IsLocal(&isLocal);

  if (gIOService->IsNetTearingDown()) {
    return NS_ERROR_ABORT;
  }
  if (gIOService->IsOffline()) {
    if (!isLocal) return NS_ERROR_OFFLINE;
  } else if (!isLocal) {
#ifdef DEBUG
    // all IP networking has to be done from the parent
    if (NS_SUCCEEDED(mCondition) && ((mNetAddr.raw.family == AF_INET) ||
                                     (mNetAddr.raw.family == AF_INET6))) {
      MOZ_ASSERT(!IsNeckoChild());
    }
#endif

    if (NS_SUCCEEDED(mCondition) && xpc::AreNonLocalConnectionsDisabled() &&
        !(mNetAddr.IsIPAddrAny() || mNetAddr.IsIPAddrLocal() ||
          mNetAddr.IsIPAddrShared())) {
      nsAutoCString ipaddr;
      RefPtr<nsNetAddr> netaddr = new nsNetAddr(&mNetAddr);
      netaddr->GetAddress(ipaddr);
      fprintf_stderr(
          stderr,
          "FATAL ERROR: Non-local network connections are disabled and a "
          "connection "
          "attempt to %s (%s) was made.\nYou should only access hostnames "
          "available via the test networking proxy (if running mochitests) "
          "or from a test-specific httpd.js server (if running xpcshell "
          "tests). "
          "Browser services should be disabled or redirected to a local "
          "server.\n",
          mHost.get(), ipaddr.get());
      MOZ_CRASH("Attempting to connect to non-local address!");
    }
  }

  // Hosts/Proxy Hosts that are Local IP Literals should not be speculatively
  // connected - Bug 853423.
  if (mConnectionFlags & nsISocketTransport::DISABLE_RFC1918 &&
      mNetAddr.IsIPAddrLocal()) {
    if (SOCKET_LOG_ENABLED()) {
      nsAutoCString netAddrCString;
      netAddrCString.SetLength(kIPv6CStrBufSize);
      if (!mNetAddr.ToStringBuffer(netAddrCString.BeginWriting(),
                                   kIPv6CStrBufSize))
        netAddrCString = "<IP-to-string failed>"_ns;
      SOCKET_LOG(
          ("nsSocketTransport::InitiateSocket skipping "
           "speculative connection for host [%s:%d] proxy "
           "[%s:%d] with Local IP address [%s]",
           mHost.get(), mPort, mProxyHost.get(), mProxyPort,
           netAddrCString.get()));
    }
    mCondition = NS_ERROR_CONNECTION_REFUSED;
    OnSocketDetached(nullptr);
    return mCondition;
  }

  //
  // find out if it is going to be ok to attach another socket to the STS.
  // if not then we have to wait for the STS to tell us that it is ok.
  // the notification is asynchronous, which means that when we could be
  // in a race to call AttachSocket once notified.  for this reason, when
  // we get notified, we just re-enter this function.  as a result, we are
  // sure to ask again before calling AttachSocket.  in this way we deal
  // with the race condition.  though it isn't the most elegant solution,
  // it is far simpler than trying to build a system that would guarantee
  // FIFO ordering (which wouldn't even be that valuable IMO).  see bug
  // 194402 for more info.
  //
  if (!mSocketTransportService->CanAttachSocket()) {
    nsCOMPtr<nsIRunnable> event =
        new nsSocketEvent(this, MSG_RETRY_INIT_SOCKET);
    if (!event) return NS_ERROR_OUT_OF_MEMORY;
    return mSocketTransportService->NotifyWhenCanAttachSocket(event);
  }

  //
  // if we already have a connected socket, then just attach and return.
  //
  if (mFD.IsInitialized()) {
    rv = mSocketTransportService->AttachSocket(mFD, this);
    if (NS_SUCCEEDED(rv)) mAttached = true;
    return rv;
  }

  //
  // create new socket fd, push io layers, etc.
  //
  PRFileDesc* fd;
  bool proxyTransparent;
  bool usingSSL;

  rv = BuildSocket(fd, proxyTransparent, usingSSL);
  if (NS_FAILED(rv)) {
    SOCKET_LOG(
        ("  BuildSocket failed [rv=%" PRIx32 "]\n", static_cast<uint32_t>(rv)));
    return rv;
  }

  // create proxy via IOActivityMonitor
  IOActivityMonitor::MonitorSocket(fd);

#ifdef FUZZING
  if (StaticPrefs::fuzzing_necko_enabled()) {
    rv = AttachFuzzyIOLayer(fd);
    if (NS_FAILED(rv)) {
      SOCKET_LOG(("Failed to attach fuzzing IOLayer [rv=%" PRIx32 "].\n",
                  static_cast<uint32_t>(rv)));
      return rv;
    }
    SOCKET_LOG(("Successfully attached fuzzing IOLayer.\n"));

    if (usingSSL) {
      mSecInfo = static_cast<nsISupports*>(
          static_cast<nsISSLSocketControl*>(new FuzzySecurityInfo()));
    }
  }
#endif

  PRStatus status;

  // Make the socket non-blocking...
  PRSocketOptionData opt;
  opt.option = PR_SockOpt_Nonblocking;
  opt.value.non_blocking = true;
  status = PR_SetSocketOption(fd, &opt);
  NS_ASSERTION(status == PR_SUCCESS, "unable to make socket non-blocking");

  if (mUsingQuic) {
    opt.option = PR_SockOpt_RecvBufferSize;
    opt.value.recv_buffer_size =
        StaticPrefs::network_http_http3_recvBufferSize();
    status = PR_SetSocketOption(fd, &opt);
    if (status != PR_SUCCESS) {
      SOCKET_LOG(("  Couldn't set recv buffer size"));
    }
  }

  if (!mUsingQuic) {
    if (mReuseAddrPort) {
      SOCKET_LOG(("  Setting port/addr reuse socket options\n"));

      // Set ReuseAddr for TCP sockets to enable having several
      // sockets bound to same local IP and port
      PRSocketOptionData opt_reuseaddr;
      opt_reuseaddr.option = PR_SockOpt_Reuseaddr;
      opt_reuseaddr.value.reuse_addr = PR_TRUE;
      status = PR_SetSocketOption(fd, &opt_reuseaddr);
      if (status != PR_SUCCESS) {
        SOCKET_LOG(("  Couldn't set reuse addr socket option: %d\n", status));
      }

      // And also set ReusePort for platforms supporting this socket option
      PRSocketOptionData opt_reuseport;
      opt_reuseport.option = PR_SockOpt_Reuseport;
      opt_reuseport.value.reuse_port = PR_TRUE;
      status = PR_SetSocketOption(fd, &opt_reuseport);
      if (status != PR_SUCCESS &&
          PR_GetError() != PR_OPERATION_NOT_SUPPORTED_ERROR) {
        SOCKET_LOG(("  Couldn't set reuse port socket option: %d\n", status));
      }
    }

    // disable the nagle algorithm - if we rely on it to coalesce writes into
    // full packets the final packet of a multi segment POST/PUT or pipeline
    // sequence is delayed a full rtt
    opt.option = PR_SockOpt_NoDelay;
    opt.value.no_delay = true;
    PR_SetSocketOption(fd, &opt);

    // if the network.tcp.sendbuffer preference is set, use it to size SO_SNDBUF
    // The Windows default of 8KB is too small and as of vista sp1, autotuning
    // only applies to receive window
    int32_t sndBufferSize;
    mSocketTransportService->GetSendBufferSize(&sndBufferSize);
    if (sndBufferSize > 0) {
      opt.option = PR_SockOpt_SendBufferSize;
      opt.value.send_buffer_size = sndBufferSize;
      PR_SetSocketOption(fd, &opt);
    }

    if (mQoSBits) {
      opt.option = PR_SockOpt_IpTypeOfService;
      opt.value.tos = mQoSBits;
      PR_SetSocketOption(fd, &opt);
    }

#if defined(XP_WIN)
    // The linger is turned off by default. This is not a hard close, but
    // closesocket should return immediately and operating system tries to send
    // remaining data for certain, implementation specific, amount of time.
    // https://msdn.microsoft.com/en-us/library/ms739165.aspx
    //
    // Turn the linger option on an set the interval to 0. This will cause hard
    // close of the socket.
    opt.option = PR_SockOpt_Linger;
    opt.value.linger.polarity = 1;
    opt.value.linger.linger = 0;
    PR_SetSocketOption(fd, &opt);
#endif
  }

  // inform socket transport about this newly created socket...
  rv = mSocketTransportService->AttachSocket(fd, this);
  if (NS_FAILED(rv)) {
    CloseSocket(fd,
                mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase());
    return rv;
  }
  mAttached = true;

  // assign mFD so that we can properly handle OnSocketDetached before we've
  // established a connection.
  {
    MutexAutoLock lock(mLock);
    mFD = fd;
    mFDref = 1;
    mFDconnected = false;
    mPollTimeout = mTimeouts[TIMEOUT_CONNECT];
  }

  SOCKET_LOG(("  advancing to STATE_CONNECTING\n"));
  mState = STATE_CONNECTING;
  SendStatus(NS_NET_STATUS_CONNECTING_TO);

  if (SOCKET_LOG_ENABLED()) {
    char buf[kNetAddrMaxCStrBufSize];
    mNetAddr.ToStringBuffer(buf, sizeof(buf));
    SOCKET_LOG(("  trying address: %s\n", buf));
  }

  //
  // Initiate the connect() to the host...
  //
  PRNetAddr prAddr;
  memset(&prAddr, 0, sizeof(prAddr));
  {
    if (mBindAddr) {
      MutexAutoLock lock(mLock);
      NetAddrToPRNetAddr(mBindAddr.get(), &prAddr);
      status = PR_Bind(fd, &prAddr);
      if (status != PR_SUCCESS) {
        return NS_ERROR_FAILURE;
      }
      mBindAddr = nullptr;
    }
  }

  NetAddrToPRNetAddr(&mNetAddr, &prAddr);

#ifdef XP_WIN
  // Find the real tcp socket and set non-blocking once again!
  // Bug 1158189.
  PRFileDesc* bottom = PR_GetIdentitiesLayer(fd, PR_NSPR_IO_LAYER);
  if (bottom) {
    PROsfd osfd = PR_FileDesc2NativeHandle(bottom);
    u_long nonblocking = 1;
    if (ioctlsocket(osfd, FIONBIO, &nonblocking) != 0) {
      NS_WARNING("Socket could not be set non-blocking!");
      return NS_ERROR_FAILURE;
    }
  }
#endif

  nsCOMPtr<nsISSLSocketControl> secCtrl = do_QueryInterface(mSecInfo);
  if (secCtrl) {
    if (!mEchConfig.IsEmpty() &&
        !(mConnectionFlags & (DONT_TRY_ECH | BE_CONSERVATIVE))) {
      SOCKET_LOG(("nsSocketTransport::InitiateSocket set echconfig."));
      rv = secCtrl->SetEchConfig(mEchConfig);
      if (NS_FAILED(rv)) {
        return rv;
      }
      mEchConfigUsed = true;
    }
  }

  if (mUsingQuic) {
    //
    // we pretend that we are connected!
    //
    if (PR_Connect(fd, &prAddr, NS_SOCKET_CONNECT_TIMEOUT) == PR_SUCCESS) {
      OnSocketConnected();
      return NS_OK;
    }
    PRErrorCode code = PR_GetError();
    return ErrorAccordingToNSPR(code);
  }

  // We use PRIntervalTime here because we need
  // nsIOService::LastOfflineStateChange time and
  // nsIOService::LastConectivityChange time to be atomic.
  PRIntervalTime connectStarted = 0;
  if (gSocketTransportService->IsTelemetryEnabledAndNotSleepPhase()) {
    connectStarted = PR_IntervalNow();
  }

  bool tfo = false;
  if (!mProxyTransparent && mFastOpenCallback &&
      mFastOpenCallback->FastOpenEnabled()) {
    if (NS_SUCCEEDED(AttachTCPFastOpenIOLayer(fd))) {
      tfo = true;
      SOCKET_LOG(
          ("nsSocketTransport::InitiateSocket TCP Fast Open "
           "started [this=%p]\n",
           this));
    }
  }

  if (Telemetry::CanRecordPrereleaseData() ||
      Telemetry::CanRecordReleaseData()) {
    if (NS_FAILED(AttachNetworkDataCountLayer(fd))) {
      SOCKET_LOG(
          ("nsSocketTransport::InitiateSocket "
           "AttachNetworkDataCountLayer failed [this=%p]\n",
           this));
    }
  }

  bool connectCalled = true;  // This is only needed for telemetry.
  status = PR_Connect(fd, &prAddr, NS_SOCKET_CONNECT_TIMEOUT);
  PRErrorCode code = PR_GetError();
  if (status == PR_SUCCESS) {
    PR_SetFDInheritable(fd, false);
  }
  if ((status == PR_SUCCESS) && tfo) {
    {
      MutexAutoLock lock(mLock);
      mFDFastOpenInProgress = true;
    }
    SOCKET_LOG(("Using TCP Fast Open."));
    rv = mFastOpenCallback->StartFastOpen();
    if (NS_FAILED(rv)) {
      if (NS_SUCCEEDED(mCondition)) {
        mCondition = rv;
      }
      mFastOpenCallback = nullptr;
      MutexAutoLock lock(mLock);
      mFDFastOpenInProgress = false;
      return rv;
    }
    status = PR_FAILURE;
    connectCalled = false;
    bool fastOpenNotSupported = false;
    TCPFastOpenFinish(fd, code, fastOpenNotSupported, mFastOpenStatus);

    // If we have sent data, trigger a socket status event.
    if (mFastOpenStatus == TFO_DATA_SENT) {
      SendStatus(NS_NET_STATUS_SENDING_TO);
    }

    // If we have still some data buffered this data must be flush before
    // mOutput.OnSocketReady(NS_OK) is called in
    // nsSocketTransport::OnSocketReady, partially to keep socket status
    // event in order.
    mFastOpenLayerHasBufferedData = TCPFastOpenGetCurrentBufferSize(fd);

    MOZ_ASSERT((mFastOpenStatus == TFO_NOT_TRIED) ||
               (mFastOpenStatus == TFO_DISABLED) ||
               (mFastOpenStatus == TFO_DATA_SENT) ||
               (mFastOpenStatus == TFO_TRIED));
    mFastOpenCallback->SetFastOpenStatus(mFastOpenStatus);
    SOCKET_LOG(
        ("called StartFastOpen - code=%d; fastOpen is %s "
         "supported.\n",
         code, fastOpenNotSupported ? "not" : ""));
    SOCKET_LOG(("TFO status %d\n", mFastOpenStatus));

    if (fastOpenNotSupported) {
      // When TCP_FastOpen is turned off on the local host
      // SendTo will return PR_NOT_TCP_SOCKET_ERROR. This is only
      // on Linux.
      // If a windows version does not support Fast Open, the return value
      // will be PR_NOT_IMPLEMENTED_ERROR. This is only for windows 10
      // versions older than version 1607, because we do not have subverion
      // to check, we need to call PR_SendTo to check if it is supported.
      mFastOpenCallback->FastOpenNotSupported();
      // FastOpenNotSupported will set Fast Open as not supported globally.
      // For this connection we will pretend that we still use fast open,
      // because of the fallback mechanism in case we need to restart the
      // attached transaction.
      connectCalled = true;
    }
  } else {
    mFastOpenCallback = nullptr;
  }

  if (gSocketTransportService->IsTelemetryEnabledAndNotSleepPhase() &&
      connectStarted && connectCalled) {
    SendPRBlockingTelemetry(
        connectStarted, Telemetry::PRCONNECT_BLOCKING_TIME_NORMAL,
        Telemetry::PRCONNECT_BLOCKING_TIME_SHUTDOWN,
        Telemetry::PRCONNECT_BLOCKING_TIME_CONNECTIVITY_CHANGE,
        Telemetry::PRCONNECT_BLOCKING_TIME_LINK_CHANGE,
        Telemetry::PRCONNECT_BLOCKING_TIME_OFFLINE);
  }

  if (status == PR_SUCCESS) {
    //
    // we are connected!
    //
    OnSocketConnected();
  } else {
#if defined(TEST_CONNECT_ERRORS)
    code = RandomizeConnectError(code);
#endif
    //
    // If the PR_Connect(...) would block, then poll for a connection.
    //
    if ((PR_WOULD_BLOCK_ERROR == code) || (PR_IN_PROGRESS_ERROR == code))
      mPollFlags = (PR_POLL_EXCEPT | PR_POLL_WRITE);
    //
    // If the socket is already connected, then return success...
    //
    else if (PR_IS_CONNECTED_ERROR == code) {
      //
      // we are connected!
      //
      OnSocketConnected();

      if (mSecInfo && !mProxyHost.IsEmpty() && proxyTransparent && usingSSL) {
        // if the connection phase is finished, and the ssl layer has
        // been pushed, and we were proxying (transparently; ie. nothing
        // has to happen in the protocol layer above us), it's time for
        // the ssl to start doing it's thing.
        nsCOMPtr<nsISSLSocketControl> secCtrl = do_QueryInterface(mSecInfo);
        if (secCtrl) {
          SOCKET_LOG(("  calling ProxyStartSSL()\n"));
          secCtrl->ProxyStartSSL();
        }
        // XXX what if we were forced to poll on the socket for a successful
        // connection... wouldn't we need to call ProxyStartSSL after a call
        // to PR_ConnectContinue indicates that we are connected?
        //
        // XXX this appears to be what the old socket transport did.  why
        // isn't this broken?
      }
    }
    //
    // A SOCKS request was rejected; get the actual error code from
    // the OS error
    //
    else if (PR_UNKNOWN_ERROR == code && mProxyTransparent &&
             !mProxyHost.IsEmpty()) {
      code = PR_GetOSError();
      rv = ErrorAccordingToNSPR(code);
    }
    //
    // The connection was refused...
    //
    else {
      if (gSocketTransportService->IsTelemetryEnabledAndNotSleepPhase() &&
          connectStarted && connectCalled) {
        SendPRBlockingTelemetry(
            connectStarted, Telemetry::PRCONNECT_FAIL_BLOCKING_TIME_NORMAL,
            Telemetry::PRCONNECT_FAIL_BLOCKING_TIME_SHUTDOWN,
            Telemetry::PRCONNECT_FAIL_BLOCKING_TIME_CONNECTIVITY_CHANGE,
            Telemetry::PRCONNECT_FAIL_BLOCKING_TIME_LINK_CHANGE,
            Telemetry::PRCONNECT_FAIL_BLOCKING_TIME_OFFLINE);
      }

      rv = ErrorAccordingToNSPR(code);
      if ((rv == NS_ERROR_CONNECTION_REFUSED) && !mProxyHost.IsEmpty())
        rv = NS_ERROR_PROXY_CONNECTION_REFUSED;
    }
  }
  return rv;
}

bool nsSocketTransport::RecoverFromError() {
  NS_ASSERTION(NS_FAILED(mCondition), "there should be something wrong");

  SOCKET_LOG(
      ("nsSocketTransport::RecoverFromError [this=%p state=%x cond=%" PRIx32
       "]\n",
       this, mState, static_cast<uint32_t>(mCondition)));

  if (mDoNotRetryToConnect) {
    SOCKET_LOG(
        ("nsSocketTransport::RecoverFromError do not retry because "
         "mDoNotRetryToConnect is set [this=%p]\n",
         this));
    return false;
  }

#if defined(XP_UNIX)
  // Unix domain connections don't have multiple addresses to try,
  // so the recovery techniques here don't apply.
  if (mNetAddrIsSet && mNetAddr.raw.family == AF_LOCAL) return false;
#endif

  if ((mConnectionFlags & nsSocketTransport::USE_IP_HINT_ADDRESS) &&
      mCondition == NS_ERROR_UNKNOWN_HOST &&
      (mState == MSG_DNS_LOOKUP_COMPLETE || mState == MSG_ENSURE_CONNECT)) {
    SOCKET_LOG(("  try again without USE_IP_HINT_ADDRESS"));
    mConnectionFlags &= ~nsSocketTransport::USE_IP_HINT_ADDRESS;
    mState = STATE_CLOSED;
    return NS_SUCCEEDED(PostEvent(MSG_ENSURE_CONNECT, NS_OK));
  }

  // can only recover from errors in these states
  if (mState != STATE_RESOLVING && mState != STATE_CONNECTING) {
    SOCKET_LOG(("  not in a recoverable state"));
    return false;
  }

  nsresult rv;

  // OK to check this outside mLock
  NS_ASSERTION(!mFDconnected, "socket should not be connected");

  // all connection failures need to be reported to DNS so that the next
  // time we will use a different address if available.
  // Skip conditions that can be cause by TCP Fast Open.
  if ((!mFDFastOpenInProgress ||
       ((mCondition != NS_ERROR_CONNECTION_REFUSED) &&
        (mCondition != NS_ERROR_NET_TIMEOUT) &&
        (mCondition != NS_BASE_STREAM_CLOSED) &&
        (mCondition != NS_ERROR_PROXY_CONNECTION_REFUSED))) &&
      mState == STATE_CONNECTING && mDNSRecord) {
    mDNSRecord->ReportUnusable(SocketPort());
  }

#if defined(_WIN64) && defined(WIN95)
  // can only recover from these errors
  if (mCondition != NS_ERROR_CONNECTION_REFUSED &&
      mCondition != NS_ERROR_PROXY_CONNECTION_REFUSED &&
      mCondition != NS_ERROR_NET_TIMEOUT &&
      mCondition != NS_ERROR_UNKNOWN_HOST &&
      mCondition != NS_ERROR_UNKNOWN_PROXY_HOST &&
      !(mFDFastOpenInProgress && (mCondition == NS_ERROR_FAILURE))) {
    SOCKET_LOG(("  not a recoverable error %" PRIx32,
                static_cast<uint32_t>(mCondition)));
    return false;
  }
#else
  if (mCondition != NS_ERROR_CONNECTION_REFUSED &&
      mCondition != NS_ERROR_PROXY_CONNECTION_REFUSED &&
      mCondition != NS_ERROR_NET_TIMEOUT &&
      mCondition != NS_ERROR_UNKNOWN_HOST &&
      mCondition != NS_ERROR_UNKNOWN_PROXY_HOST) {
    SOCKET_LOG(("  not a recoverable error %" PRIx32,
                static_cast<uint32_t>(mCondition)));
    return false;
  }
#endif

  bool tryAgain = false;
  if (mFDFastOpenInProgress &&
      ((mCondition == NS_ERROR_CONNECTION_REFUSED) ||
       (mCondition == NS_ERROR_NET_TIMEOUT) ||
#if defined(_WIN64) && defined(WIN95)
       // On Windows PR_ContinueConnect can return NS_ERROR_FAILURE.
       // This will be fixed in bug 1386719 and this is just a temporary
       // work around.
       (mCondition == NS_ERROR_FAILURE) ||
#endif
       (mCondition == NS_ERROR_PROXY_CONNECTION_REFUSED))) {
    // TCP Fast Open can be blocked by middle boxes so we will retry
    // without it.
    tryAgain = true;
    // If we cancel the connection because backup socket was successfully
    // connected, mFDFastOpenInProgress will be true but mFastOpenCallback
    // will be nullptr.
    if (mFastOpenCallback) {
      mFastOpenCallback->SetFastOpenConnected(mCondition, true);
    }
    mFastOpenCallback = nullptr;

  } else {
    // This is only needed for telemetry.
    if (NS_SUCCEEDED(mFirstRetryError)) {
      mFirstRetryError = mCondition;
    }
    if ((mState == STATE_CONNECTING) && mDNSRecord) {
      if (mNetAddr.raw.family == AF_INET) {
        if (mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase()) {
          Telemetry::Accumulate(Telemetry::IPV4_AND_IPV6_ADDRESS_CONNECTIVITY,
                                UNSUCCESSFUL_CONNECTING_TO_IPV4_ADDRESS);
        }
      } else if (mNetAddr.raw.family == AF_INET6) {
        if (mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase()) {
          Telemetry::Accumulate(Telemetry::IPV4_AND_IPV6_ADDRESS_CONNECTIVITY,
                                UNSUCCESSFUL_CONNECTING_TO_IPV6_ADDRESS);
        }
      }
    }

    if (mConnectionFlags & RETRY_WITH_DIFFERENT_IP_FAMILY &&
        mCondition == NS_ERROR_UNKNOWN_HOST && mState == STATE_RESOLVING &&
        !mProxyTransparentResolvesHost) {
      SOCKET_LOG(("  trying lookup again with opposite ip family\n"));
      mConnectionFlags ^= (DISABLE_IPV6 | DISABLE_IPV4);
      mConnectionFlags &= ~RETRY_WITH_DIFFERENT_IP_FAMILY;
      // This will tell the consuming half-open to reset preference on the
      // connection entry
      mResetFamilyPreference = true;
      tryAgain = true;
    }

    // try next ip address only if past the resolver stage...
    if (mState == STATE_CONNECTING && mDNSRecord) {
      nsresult rv = mDNSRecord->GetNextAddr(SocketPort(), &mNetAddr);
      mDNSRecord->IsTRR(&mResolvedByTRR);
      if (NS_SUCCEEDED(rv)) {
        SOCKET_LOG(("  trying again with next ip address\n"));
        tryAgain = true;
      } else if (mConnectionFlags & RETRY_WITH_DIFFERENT_IP_FAMILY) {
        SOCKET_LOG(("  failed to connect, trying with opposite ip family\n"));
        // Drop state to closed.  This will trigger new round of DNS
        // resolving bellow.
        mState = STATE_CLOSED;
        mConnectionFlags ^= (DISABLE_IPV6 | DISABLE_IPV4);
        mConnectionFlags &= ~RETRY_WITH_DIFFERENT_IP_FAMILY;
        // This will tell the consuming half-open to reset preference on the
        // connection entry
        mResetFamilyPreference = true;
        tryAgain = true;
      } else if (!(mConnectionFlags & DISABLE_TRR)) {
        bool trrEnabled;
        mDNSRecord->IsTRR(&trrEnabled);

        // Bug 1648147 - If the server responded with `0.0.0.0` or `::` then we
        // should intentionally not fallback to regular DNS.
        if (!StaticPrefs::network_trr_fallback_on_zero_response() &&
            ((mNetAddr.raw.family == AF_INET && mNetAddr.inet.ip == 0) ||
             (mNetAddr.raw.family == AF_INET6 &&
              mNetAddr.inet6.ip.u64[0] == 0 &&
              mNetAddr.inet6.ip.u64[1] == 0))) {
          SOCKET_LOG(("  TRR returned 0.0.0.0 and there are no other IPs"));
        } else if (trrEnabled) {
          uint32_t trrMode = 0;
          mDNSRecord->GetEffectiveTRRMode(&trrMode);
          // If current trr mode is trr only, we should not retry.
          if (trrMode != 3) {
            // Drop state to closed.  This will trigger a new round of
            // DNS resolving. Bypass the cache this time since the
            // cached data came from TRR and failed already!
            SOCKET_LOG(("  failed to connect with TRR enabled, try w/o\n"));
            mState = STATE_CLOSED;
            mConnectionFlags |= DISABLE_TRR | BYPASS_CACHE | REFRESH_CACHE;
            tryAgain = true;
          }
        }
      }
    }
  }

  // prepare to try again.
  if (tryAgain) {
    uint32_t msg;

    if (mState == STATE_CONNECTING) {
      mState = STATE_RESOLVING;
      msg = MSG_DNS_LOOKUP_COMPLETE;
    } else {
      mState = STATE_CLOSED;
      msg = MSG_ENSURE_CONNECT;
    }

    rv = PostEvent(msg, NS_OK);
    if (NS_FAILED(rv)) tryAgain = false;
  }

  return tryAgain;
}

// called on the socket thread only
void nsSocketTransport::OnMsgInputClosed(nsresult reason) {
  SOCKET_LOG(("nsSocketTransport::OnMsgInputClosed [this=%p reason=%" PRIx32
              "]\n",
              this, static_cast<uint32_t>(reason)));

  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  mInputClosed = true;
  // check if event should affect entire transport
  if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED))
    mCondition = reason;  // XXX except if NS_FAILED(mCondition), right??
  else if (mOutputClosed)
    mCondition =
        NS_BASE_STREAM_CLOSED;  // XXX except if NS_FAILED(mCondition), right??
  else {
    if (mState == STATE_TRANSFERRING) mPollFlags &= ~PR_POLL_READ;
    mInput.OnSocketReady(reason);
  }
}

// called on the socket thread only
void nsSocketTransport::OnMsgOutputClosed(nsresult reason) {
  SOCKET_LOG(("nsSocketTransport::OnMsgOutputClosed [this=%p reason=%" PRIx32
              "]\n",
              this, static_cast<uint32_t>(reason)));

  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  mOutputClosed = true;
  // check if event should affect entire transport
  if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED))
    mCondition = reason;  // XXX except if NS_FAILED(mCondition), right??
  else if (mInputClosed)
    mCondition =
        NS_BASE_STREAM_CLOSED;  // XXX except if NS_FAILED(mCondition), right??
  else {
    if (mState == STATE_TRANSFERRING) mPollFlags &= ~PR_POLL_WRITE;
    mOutput.OnSocketReady(reason);
  }
}

void nsSocketTransport::OnSocketConnected() {
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
  SOCKET_LOG(("  advancing to STATE_TRANSFERRING\n"));

  mPollFlags = (PR_POLL_READ | PR_POLL_WRITE | PR_POLL_EXCEPT);
  mState = STATE_TRANSFERRING;

  // Set the m*AddrIsSet flags only when state has reached TRANSFERRING
  // because we need to make sure its value does not change due to failover
  mNetAddrIsSet = true;

  if (mFDFastOpenInProgress && mFastOpenCallback) {
    // mFastOpenCallback can be null when for example h2 is negotiated on
    // another connection to the same host and all connections are
    // abandoned.
    mFastOpenCallback->SetFastOpenConnected(NS_OK, false);
  }
  mFastOpenCallback = nullptr;

  // assign mFD (must do this within the transport lock), but take care not
  // to trample over mFDref if mFD is already set.
  {
    MutexAutoLock lock(mLock);
    NS_ASSERTION(mFD.IsInitialized(), "no socket");
    NS_ASSERTION(mFDref == 1, "wrong socket ref count");
    SetSocketName(mFD);
    mFDconnected = true;
    mFDFastOpenInProgress = false;
    mPollTimeout = mTimeouts[TIMEOUT_READ_WRITE];
  }

  // Ensure keepalive is configured correctly if previously enabled.
  if (mKeepaliveEnabled) {
    nsresult rv = SetKeepaliveEnabledInternal(true);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      SOCKET_LOG(("  SetKeepaliveEnabledInternal failed rv[0x%" PRIx32 "]",
                  static_cast<uint32_t>(rv)));
    }
  }

  SendStatus(NS_NET_STATUS_CONNECTED_TO);
}

void nsSocketTransport::SetSocketName(PRFileDesc* fd) {
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
  if (mSelfAddrIsSet) {
    return;
  }

  PRNetAddr prAddr;
  memset(&prAddr, 0, sizeof(prAddr));
  if (PR_GetSockName(fd, &prAddr) == PR_SUCCESS) {
    PRNetAddrToNetAddr(&prAddr, &mSelfAddr);
    mSelfAddrIsSet = true;
  }
}

PRFileDesc* nsSocketTransport::GetFD_Locked() {
  mLock.AssertCurrentThreadOwns();

  // mFD is not available to the streams while disconnected.
  if (!mFDconnected) return nullptr;

  if (mFD.IsInitialized()) mFDref++;

  return mFD;
}

PRFileDesc* nsSocketTransport::GetFD_LockedAlsoDuringFastOpen() {
  mLock.AssertCurrentThreadOwns();

  // mFD is not available to the streams while disconnected.
  if (!mFDconnected && !mFDFastOpenInProgress) {
    return nullptr;
  }

  if (mFD.IsInitialized()) {
    mFDref++;
  }

  return mFD;
}

bool nsSocketTransport::FastOpenInProgress() {
  mLock.AssertCurrentThreadOwns();
  return mFDFastOpenInProgress;
}

class ThunkPRClose : public Runnable {
 public:
  explicit ThunkPRClose(PRFileDesc* fd)
      : Runnable("net::ThunkPRClose"), mFD(fd) {}

  NS_IMETHOD Run() override {
    nsSocketTransport::CloseSocket(
        mFD, gSocketTransportService->IsTelemetryEnabledAndNotSleepPhase());
    return NS_OK;
  }

 private:
  PRFileDesc* mFD;
};

void STS_PRCloseOnSocketTransport(PRFileDesc* fd, bool lingerPolarity,
                                  int16_t lingerTimeout) {
  if (gSocketTransportService) {
    // Can't PR_Close() a socket off STS thread. Thunk it to STS to die
    gSocketTransportService->Dispatch(new ThunkPRClose(fd), NS_DISPATCH_NORMAL);
  } else {
    // something horrible has happened
    NS_ASSERTION(gSocketTransportService, "No STS service");
  }
}

void nsSocketTransport::ReleaseFD_Locked(PRFileDesc* fd) {
  mLock.AssertCurrentThreadOwns();

  NS_ASSERTION(mFD == fd, "wrong fd");

  if (--mFDref == 0) {
    if (gIOService->IsNetTearingDown() &&
        ((PR_IntervalNow() - gIOService->NetTearingDownStarted()) >
         gSocketTransportService->MaxTimeForPrClosePref())) {
      // If shutdown last to long, let the socket leak and do not close it.
      SOCKET_LOG(("Intentional leak"));
    } else {
      if (mLingerPolarity || mLingerTimeout) {
        PRSocketOptionData socket_linger;
        socket_linger.option = PR_SockOpt_Linger;
        socket_linger.value.linger.polarity = mLingerPolarity;
        socket_linger.value.linger.linger = mLingerTimeout;
        PR_SetSocketOption(mFD, &socket_linger);
      }
      if (OnSocketThread()) {
        SOCKET_LOG(("nsSocketTransport: calling PR_Close [this=%p]\n", this));
        CloseSocket(
            mFD, mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase());
      } else {
        // Can't PR_Close() a socket off STS thread. Thunk it to STS to die
        STS_PRCloseOnSocketTransport(mFD, mLingerPolarity, mLingerTimeout);
      }
    }
    mFD = nullptr;
  }
}

//-----------------------------------------------------------------------------
// socket event handler impl

void nsSocketTransport::OnSocketEvent(uint32_t type, nsresult status,
                                      nsISupports* param) {
  SOCKET_LOG(
      ("nsSocketTransport::OnSocketEvent [this=%p type=%u status=%" PRIx32
       " param=%p]\n",
       this, type, static_cast<uint32_t>(status), param));

  if (NS_FAILED(mCondition)) {
    // block event since we're apparently already dead.
    SOCKET_LOG(("  blocking event [condition=%" PRIx32 "]\n",
                static_cast<uint32_t>(mCondition)));
    //
    // notify input/output streams in case either has a pending notify.
    //
    mInput.OnSocketReady(mCondition);
    mOutput.OnSocketReady(mCondition);
    return;
  }

  switch (type) {
    case MSG_ENSURE_CONNECT:
      SOCKET_LOG(("  MSG_ENSURE_CONNECT\n"));

      // Apply port remapping here so that we do it on the socket thread and
      // before we process the resolved DNS name or create the socket the first
      // time.
      if (!mPortRemappingApplied) {
        mPortRemappingApplied = true;

        mSocketTransportService->ApplyPortRemap(&mPort);
        mSocketTransportService->ApplyPortRemap(&mOriginPort);
      }

      //
      // ensure that we have created a socket, attached it, and have a
      // connection.
      //
      if (mState == STATE_CLOSED) {
        // Unix domain sockets are ready to connect; mNetAddr is all we
        // need. Internet address families require a DNS lookup (or possibly
        // several) before we can connect.
#if defined(XP_UNIX)
        if (mNetAddrIsSet && mNetAddr.raw.family == AF_LOCAL)
          mCondition = InitiateSocket();
        else
#endif
          mCondition = ResolveHost();

      } else {
        SOCKET_LOG(("  ignoring redundant event\n"));
      }
      break;

    case MSG_DNS_LOOKUP_COMPLETE:
      if (mDNSRequest) {  // only send this if we actually resolved anything
        SendStatus(NS_NET_STATUS_RESOLVED_HOST);
      }

      SOCKET_LOG(("  MSG_DNS_LOOKUP_COMPLETE\n"));
      mDNSRequest = nullptr;

      if (mDNSRecord) {
        mDNSRecord->GetNextAddr(SocketPort(), &mNetAddr);
        mDNSRecord->IsTRR(&mResolvedByTRR);
      }
      // status contains DNS lookup status
      if (NS_FAILED(status)) {
        // When using a HTTP proxy, NS_ERROR_UNKNOWN_HOST means the HTTP
        // proxy host is not found, so we fixup the error code.
        // For SOCKS proxies (mProxyTransparent == true), the socket
        // transport resolves the real host here, so there's no fixup
        // (see bug 226943).
        if ((status == NS_ERROR_UNKNOWN_HOST) && !mProxyTransparent &&
            !mProxyHost.IsEmpty())
          mCondition = NS_ERROR_UNKNOWN_PROXY_HOST;
        else
          mCondition = status;
      } else if (mState == STATE_RESOLVING) {
        mCondition = InitiateSocket();
      }
      break;

    case MSG_RETRY_INIT_SOCKET:
      mCondition = InitiateSocket();
      break;

    case MSG_INPUT_CLOSED:
      SOCKET_LOG(("  MSG_INPUT_CLOSED\n"));
      OnMsgInputClosed(status);
      break;

    case MSG_INPUT_PENDING:
      SOCKET_LOG(("  MSG_INPUT_PENDING\n"));
      OnMsgInputPending();
      break;

    case MSG_OUTPUT_CLOSED:
      SOCKET_LOG(("  MSG_OUTPUT_CLOSED\n"));
      OnMsgOutputClosed(status);
      break;

    case MSG_OUTPUT_PENDING:
      SOCKET_LOG(("  MSG_OUTPUT_PENDING\n"));
      OnMsgOutputPending();
      break;
    case MSG_TIMEOUT_CHANGED:
      SOCKET_LOG(("  MSG_TIMEOUT_CHANGED\n"));
      {
        MutexAutoLock lock(mLock);
        mPollTimeout =
            mTimeouts[(mState == STATE_TRANSFERRING) ? TIMEOUT_READ_WRITE
                                                     : TIMEOUT_CONNECT];
      }
      break;
    default:
      SOCKET_LOG(("  unhandled event!\n"));
  }

  if (NS_FAILED(mCondition)) {
    SOCKET_LOG(("  after event [this=%p cond=%" PRIx32 "]\n", this,
                static_cast<uint32_t>(mCondition)));
    if (!mAttached)  // need to process this error ourselves...
      OnSocketDetached(nullptr);
  } else if (mPollFlags == PR_POLL_EXCEPT)
    mPollFlags = 0;  // make idle
}

//-----------------------------------------------------------------------------
// socket handler impl

void nsSocketTransport::OnSocketReady(PRFileDesc* fd, int16_t outFlags) {
  SOCKET_LOG1(("nsSocketTransport::OnSocketReady [this=%p outFlags=%hd]\n",
               this, outFlags));

  if (outFlags == -1) {
    SOCKET_LOG(("socket timeout expired\n"));
    mCondition = NS_ERROR_NET_TIMEOUT;
    return;
  }

  if ((mState == STATE_TRANSFERRING) && mFastOpenLayerHasBufferedData) {
    // We have some data buffered in TCPFastOpenLayer. We will flush them
    // first. We need to do this first before calling OnSocketReady below
    // so that the socket status events are kept in the correct order.
    mFastOpenLayerHasBufferedData = TCPFastOpenFlushBuffer(fd);
    if (mFastOpenLayerHasBufferedData) {
      return;
    }
    SendStatus(NS_NET_STATUS_SENDING_TO);

    // If we are done sending the buffered data continue with the normal
    // path.
    // In case of an error, TCPFastOpenFlushBuffer will return false and
    // the normal code path will pick up the error.
    mFastOpenLayerHasBufferedData = false;
  }

  if (mState == STATE_TRANSFERRING) {
    // if waiting to write and socket is writable or hit an exception.
    if ((mPollFlags & PR_POLL_WRITE) && (outFlags & ~PR_POLL_READ)) {
      // assume that we won't need to poll any longer (the stream will
      // request that we poll again if it is still pending).
      mPollFlags &= ~PR_POLL_WRITE;
      mOutput.OnSocketReady(NS_OK);
    }
    // if waiting to read and socket is readable or hit an exception.
    if ((mPollFlags & PR_POLL_READ) && (outFlags & ~PR_POLL_WRITE)) {
      // assume that we won't need to poll any longer (the stream will
      // request that we poll again if it is still pending).
      mPollFlags &= ~PR_POLL_READ;
      mInput.OnSocketReady(NS_OK);
    }
    // Update poll timeout in case it was changed
    {
      MutexAutoLock lock(mLock);
      mPollTimeout = mTimeouts[TIMEOUT_READ_WRITE];
    }
  } else if ((mState == STATE_CONNECTING) && !gIOService->IsNetTearingDown()) {
    // We do not need to do PR_ConnectContinue when we are already
    // shutting down.

    // We use PRIntervalTime here because we need
    // nsIOService::LastOfflineStateChange time and
    // nsIOService::LastConectivityChange time to be atomic.
    PRIntervalTime connectStarted = 0;
    if (gSocketTransportService->IsTelemetryEnabledAndNotSleepPhase()) {
      connectStarted = PR_IntervalNow();
    }

    PRStatus status = PR_ConnectContinue(fd, outFlags);

#if defined(_WIN64) && defined(WIN95)
#  ifndef TCP_FASTOPEN
#    define TCP_FASTOPEN 15
#  endif

    if (mFDFastOpenInProgress && mFastOpenCallback &&
        (mFastOpenStatus == TFO_DATA_SENT)) {
      PROsfd osfd = PR_FileDesc2NativeHandle(fd);
      BOOL option = 0;
      int len = sizeof(option);
      PRInt32 rv = getsockopt((SOCKET)osfd, IPPROTO_TCP, TCP_FASTOPEN,
                              (char*)&option, &len);
      if (!rv && !option) {
        // On error, I will let the normal necko paths pickup the error.
        mFastOpenCallback->SetFastOpenStatus(TFO_DATA_COOKIE_NOT_ACCEPTED);
      }
    }
#endif

    if (gSocketTransportService->IsTelemetryEnabledAndNotSleepPhase() &&
        connectStarted) {
      SendPRBlockingTelemetry(
          connectStarted, Telemetry::PRCONNECTCONTINUE_BLOCKING_TIME_NORMAL,
          Telemetry::PRCONNECTCONTINUE_BLOCKING_TIME_SHUTDOWN,
          Telemetry::PRCONNECTCONTINUE_BLOCKING_TIME_CONNECTIVITY_CHANGE,
          Telemetry::PRCONNECTCONTINUE_BLOCKING_TIME_LINK_CHANGE,
          Telemetry::PRCONNECTCONTINUE_BLOCKING_TIME_OFFLINE);
    }

    if (status == PR_SUCCESS) {
      //
      // we are connected!
      //
      OnSocketConnected();

      if (mNetAddr.raw.family == AF_INET) {
        if (mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase()) {
          Telemetry::Accumulate(Telemetry::IPV4_AND_IPV6_ADDRESS_CONNECTIVITY,
                                SUCCESSFUL_CONNECTING_TO_IPV4_ADDRESS);
        }
      } else if (mNetAddr.raw.family == AF_INET6) {
        if (mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase()) {
          Telemetry::Accumulate(Telemetry::IPV4_AND_IPV6_ADDRESS_CONNECTIVITY,
                                SUCCESSFUL_CONNECTING_TO_IPV6_ADDRESS);
        }
      }
    } else {
      PRErrorCode code = PR_GetError();
#if defined(TEST_CONNECT_ERRORS)
      code = RandomizeConnectError(code);
#endif
      //
      // If the connect is still not ready, then continue polling...
      //
      if ((PR_WOULD_BLOCK_ERROR == code) || (PR_IN_PROGRESS_ERROR == code)) {
        // Set up the select flags for connect...
        mPollFlags = (PR_POLL_EXCEPT | PR_POLL_WRITE);
        // Update poll timeout in case it was changed
        {
          MutexAutoLock lock(mLock);
          mPollTimeout = mTimeouts[TIMEOUT_CONNECT];
        }
      }
      //
      // The SOCKS proxy rejected our request. Find out why.
      //
      else if (PR_UNKNOWN_ERROR == code && mProxyTransparent &&
               !mProxyHost.IsEmpty()) {
        code = PR_GetOSError();
        mCondition = ErrorAccordingToNSPR(code);
      } else {
        //
        // else, the connection failed...
        //
        mCondition = ErrorAccordingToNSPR(code);
        if ((mCondition == NS_ERROR_CONNECTION_REFUSED) &&
            !mProxyHost.IsEmpty())
          mCondition = NS_ERROR_PROXY_CONNECTION_REFUSED;
        SOCKET_LOG(("  connection failed! [reason=%" PRIx32 "]\n",
                    static_cast<uint32_t>(mCondition)));
      }
    }
  } else if ((mState == STATE_CONNECTING) && gIOService->IsNetTearingDown()) {
    // We do not need to do PR_ConnectContinue when we are already
    // shutting down.
    SOCKET_LOG(
        ("We are in shutdown so skip PR_ConnectContinue and set "
         "and error.\n"));
    mCondition = NS_ERROR_ABORT;
  } else {
    NS_ERROR("unexpected socket state");
    mCondition = NS_ERROR_UNEXPECTED;
  }

  if (mPollFlags == PR_POLL_EXCEPT) mPollFlags = 0;  // make idle
}

// called on the socket thread only
void nsSocketTransport::OnSocketDetached(PRFileDesc* fd) {
  SOCKET_LOG(("nsSocketTransport::OnSocketDetached [this=%p cond=%" PRIx32
              "]\n",
              this, static_cast<uint32_t>(mCondition)));

  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  mAttached = false;

  // if we didn't initiate this detach, then be sure to pass an error
  // condition up to our consumers.  (e.g., STS is shutting down.)
  if (NS_SUCCEEDED(mCondition)) {
    if (gIOService->IsOffline()) {
      mCondition = NS_ERROR_OFFLINE;
    } else {
      mCondition = NS_ERROR_ABORT;
    }
  }

  mFastOpenLayerHasBufferedData = false;

  // If we are not shutting down try again.
  if (!gIOService->IsNetTearingDown() && RecoverFromError())
    mCondition = NS_OK;
  else {
    mState = STATE_CLOSED;

    // The error can happened before we start fast open. In that case do not
    // call mFastOpenCallback->SetFastOpenConnected; If error happends during
    // fast open, inform the halfOpenSocket.
    // If we cancel the connection because backup socket was successfully
    // connected, mFDFastOpenInProgress will be true but mFastOpenCallback
    // will be nullptr.
    if (mFDFastOpenInProgress && mFastOpenCallback) {
      mFastOpenCallback->SetFastOpenConnected(mCondition, false);
    }
    mFastOpenCallback = nullptr;

    // make sure there isn't any pending DNS request
    if (mDNSRequest) {
      mDNSRequest->Cancel(NS_ERROR_ABORT);
      mDNSRequest = nullptr;
    }

    //
    // notify input/output streams
    //
    mInput.OnSocketReady(mCondition);
    mOutput.OnSocketReady(mCondition);
  }

  // If FastOpen has been used (mFDFastOpenInProgress==true),
  // mFastOpenCallback must be nullptr now. We decided to recover from
  // error like NET_TIMEOUT, CONNECTION_REFUSED or we have called
  // SetFastOpenConnected(mCondition) in this function a couple of lines
  // above.
  // If FastOpen has not been used (mFDFastOpenInProgress==false) it can be
  // that mFastOpenCallback is no null, this is the case when we recover from
  // errors like UKNOWN_HOST in which case socket was not been connected yet
  // and mFastOpenCallback-StartFastOpen was not be called yet (but we can
  // still call it in the next try).
  MOZ_ASSERT(!(mFDFastOpenInProgress && mFastOpenCallback));

  // break any potential reference cycle between the security info object
  // and ourselves by resetting its notification callbacks object.  see
  // bug 285991 for details.
  nsCOMPtr<nsISSLSocketControl> secCtrl = do_QueryInterface(mSecInfo);
  if (secCtrl) secCtrl->SetNotificationCallbacks(nullptr);

  // finally, release our reference to the socket (must do this within
  // the transport lock) possibly closing the socket. Also release our
  // listeners to break potential refcount cycles.

  // We should be careful not to release mEventSink and mCallbacks while
  // we're locked, because releasing it might require acquiring the lock
  // again, so we just null out mEventSink and mCallbacks while we're
  // holding the lock, and let the stack based objects' destuctors take
  // care of destroying it if needed.
  nsCOMPtr<nsIInterfaceRequestor> ourCallbacks;
  nsCOMPtr<nsITransportEventSink> ourEventSink;
  {
    MutexAutoLock lock(mLock);
    if (mFD.IsInitialized()) {
      ReleaseFD_Locked(mFD);
      // flag mFD as unusable; this prevents other consumers from
      // acquiring a reference to mFD.
      mFDconnected = false;
      mFDFastOpenInProgress = false;
    }

    // We must release mCallbacks and mEventSink to avoid memory leak
    // but only when RecoverFromError() above failed. Otherwise we lose
    // link with UI and security callbacks on next connection attempt
    // round. That would lead e.g. to a broken certificate exception page.
    if (NS_FAILED(mCondition)) {
      mCallbacks.swap(ourCallbacks);
      mEventSink.swap(ourEventSink);
    }
  }
}

void nsSocketTransport::IsLocal(bool* aIsLocal) {
  {
    MutexAutoLock lock(mLock);

#if defined(XP_UNIX)
    // Unix-domain sockets are always local.
    if (mNetAddr.raw.family == PR_AF_LOCAL) {
      *aIsLocal = true;
      return;
    }
#endif

    *aIsLocal = mNetAddr.IsLoopbackAddr();
  }
}

//-----------------------------------------------------------------------------
// xpcom api

NS_IMPL_ISUPPORTS(nsSocketTransport, nsISocketTransport, nsITransport,
                  nsIDNSListener, nsIClassInfo, nsIInterfaceRequestor)
NS_IMPL_CI_INTERFACE_GETTER(nsSocketTransport, nsISocketTransport, nsITransport,
                            nsIDNSListener, nsIInterfaceRequestor)

NS_IMETHODIMP
nsSocketTransport::OpenInputStream(uint32_t flags, uint32_t segsize,
                                   uint32_t segcount, nsIInputStream** result) {
  SOCKET_LOG(
      ("nsSocketTransport::OpenInputStream [this=%p flags=%x]\n", this, flags));

  NS_ENSURE_TRUE(!mInput.IsReferenced(), NS_ERROR_UNEXPECTED);

  nsresult rv;
  nsCOMPtr<nsIAsyncInputStream> pipeIn;

  if (!(flags & OPEN_UNBUFFERED) || (flags & OPEN_BLOCKING)) {
    // XXX if the caller wants blocking, then the caller also gets buffered!
    // bool openBuffered = !(flags & OPEN_UNBUFFERED);
    bool openBlocking = (flags & OPEN_BLOCKING);

    net_ResolveSegmentParams(segsize, segcount);

    // create a pipe
    nsCOMPtr<nsIAsyncOutputStream> pipeOut;
    rv = NS_NewPipe2(getter_AddRefs(pipeIn), getter_AddRefs(pipeOut),
                     !openBlocking, true, segsize, segcount);
    if (NS_FAILED(rv)) return rv;

    // async copy from socket to pipe
    rv = NS_AsyncCopy(&mInput, pipeOut, mSocketTransportService,
                      NS_ASYNCCOPY_VIA_WRITESEGMENTS, segsize);
    if (NS_FAILED(rv)) return rv;

    *result = pipeIn;
  } else
    *result = &mInput;

  // flag input stream as open
  mInputClosed = false;

  rv = PostEvent(MSG_ENSURE_CONNECT);
  if (NS_FAILED(rv)) return rv;

  NS_ADDREF(*result);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::OpenOutputStream(uint32_t flags, uint32_t segsize,
                                    uint32_t segcount,
                                    nsIOutputStream** result) {
  SOCKET_LOG(("nsSocketTransport::OpenOutputStream [this=%p flags=%x]\n", this,
              flags));

  NS_ENSURE_TRUE(!mOutput.IsReferenced(), NS_ERROR_UNEXPECTED);

  nsresult rv;
  nsCOMPtr<nsIAsyncOutputStream> pipeOut;
  if (!(flags & OPEN_UNBUFFERED) || (flags & OPEN_BLOCKING)) {
    // XXX if the caller wants blocking, then the caller also gets buffered!
    // bool openBuffered = !(flags & OPEN_UNBUFFERED);
    bool openBlocking = (flags & OPEN_BLOCKING);

    net_ResolveSegmentParams(segsize, segcount);

    // create a pipe
    nsCOMPtr<nsIAsyncInputStream> pipeIn;
    rv = NS_NewPipe2(getter_AddRefs(pipeIn), getter_AddRefs(pipeOut), true,
                     !openBlocking, segsize, segcount);
    if (NS_FAILED(rv)) return rv;

    // async copy from socket to pipe
    rv = NS_AsyncCopy(pipeIn, &mOutput, mSocketTransportService,
                      NS_ASYNCCOPY_VIA_READSEGMENTS, segsize);
    if (NS_FAILED(rv)) return rv;

    *result = pipeOut;
  } else
    *result = &mOutput;

  // flag output stream as open
  mOutputClosed = false;

  rv = PostEvent(MSG_ENSURE_CONNECT);
  if (NS_FAILED(rv)) return rv;

  NS_ADDREF(*result);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::Close(nsresult reason) {
  SOCKET_LOG(("nsSocketTransport::Close %p reason=%" PRIx32, this,
              static_cast<uint32_t>(reason)));

  if (NS_SUCCEEDED(reason)) reason = NS_BASE_STREAM_CLOSED;

  mDoNotRetryToConnect = true;

  if (mFDFastOpenInProgress && mFastOpenCallback) {
    mFastOpenCallback->SetFastOpenConnected(reason, false);
  }
  mFastOpenCallback = nullptr;

  mInput.CloseWithStatus(reason);
  mOutput.CloseWithStatus(reason);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetSecurityInfo(nsISupports** secinfo) {
  MutexAutoLock lock(mLock);
  NS_IF_ADDREF(*secinfo = mSecInfo);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetSecurityCallbacks(nsIInterfaceRequestor** callbacks) {
  MutexAutoLock lock(mLock);
  NS_IF_ADDREF(*callbacks = mCallbacks);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetSecurityCallbacks(nsIInterfaceRequestor* callbacks) {
  nsCOMPtr<nsIInterfaceRequestor> threadsafeCallbacks;
  NS_NewNotificationCallbacksAggregation(callbacks, nullptr,
                                         GetCurrentEventTarget(),
                                         getter_AddRefs(threadsafeCallbacks));

  nsCOMPtr<nsISupports> secinfo;
  {
    MutexAutoLock lock(mLock);
    mCallbacks = threadsafeCallbacks;
    SOCKET_LOG(("Reset callbacks for secinfo=%p callbacks=%p\n", mSecInfo.get(),
                mCallbacks.get()));

    secinfo = mSecInfo;
  }

  // don't call into PSM while holding mLock!!
  nsCOMPtr<nsISSLSocketControl> secCtrl(do_QueryInterface(secinfo));
  if (secCtrl) secCtrl->SetNotificationCallbacks(threadsafeCallbacks);

  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetEventSink(nsITransportEventSink* sink,
                                nsIEventTarget* target) {
  nsCOMPtr<nsITransportEventSink> temp;
  if (target) {
    nsresult rv =
        net_NewTransportEventSinkProxy(getter_AddRefs(temp), sink, target);
    if (NS_FAILED(rv)) return rv;
    sink = temp.get();
  }

  MutexAutoLock lock(mLock);
  mEventSink = sink;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::IsAlive(bool* result) {
  *result = false;

  // During Fast Open we need to return true here.
  if (mFDFastOpenInProgress) {
    *result = true;
    return NS_OK;
  }

  nsresult conditionWhileLocked = NS_OK;
  PRFileDescAutoLock fd(this, false, &conditionWhileLocked);
  if (NS_FAILED(conditionWhileLocked) || !fd.IsInitialized()) {
    return NS_OK;
  }

  // XXX do some idle-time based checks??

  char c;
  int32_t rval = PR_Recv(fd, &c, 1, PR_MSG_PEEK, 0);

  if ((rval > 0) || (rval < 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR))
    *result = true;

  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetHost(nsACString& host) {
  host = SocketHost();
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetPort(int32_t* port) {
  *port = (int32_t)SocketPort();
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetScriptableOriginAttributes(
    JSContext* aCx, JS::MutableHandle<JS::Value> aOriginAttributes) {
  if (NS_WARN_IF(!ToJSValue(aCx, mOriginAttributes, aOriginAttributes))) {
    return NS_ERROR_FAILURE;
  }
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetScriptableOriginAttributes(
    JSContext* aCx, JS::Handle<JS::Value> aOriginAttributes) {
  MutexAutoLock lock(mLock);
  NS_ENSURE_FALSE(mFD.IsInitialized(), NS_ERROR_FAILURE);

  OriginAttributes attrs;
  if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
    return NS_ERROR_INVALID_ARG;
  }

  mOriginAttributes = attrs;
  return NS_OK;
}

nsresult nsSocketTransport::GetOriginAttributes(
    OriginAttributes* aOriginAttributes) {
  NS_ENSURE_ARG(aOriginAttributes);
  *aOriginAttributes = mOriginAttributes;
  return NS_OK;
}

nsresult nsSocketTransport::SetOriginAttributes(
    const OriginAttributes& aOriginAttributes) {
  MutexAutoLock lock(mLock);
  NS_ENSURE_FALSE(mFD.IsInitialized(), NS_ERROR_FAILURE);

  mOriginAttributes = aOriginAttributes;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetPeerAddr(NetAddr* addr) {
  // once we are in the connected state, mNetAddr will not change.
  // so if we can verify that we are in the connected state, then
  // we can freely access mNetAddr from any thread without being
  // inside a critical section.

  if (!mNetAddrIsSet) {
    SOCKET_LOG(
        ("nsSocketTransport::GetPeerAddr [this=%p state=%d] "
         "NOT_AVAILABLE because not yet connected.",
         this, mState));
    return NS_ERROR_NOT_AVAILABLE;
  }

  memcpy(addr, &mNetAddr, sizeof(NetAddr));
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetSelfAddr(NetAddr* addr) {
  // once we are in the connected state, mSelfAddr will not change.
  // so if we can verify that we are in the connected state, then
  // we can freely access mSelfAddr from any thread without being
  // inside a critical section.

  if (!mSelfAddrIsSet) {
    SOCKET_LOG(
        ("nsSocketTransport::GetSelfAddr [this=%p state=%d] "
         "NOT_AVAILABLE because not yet connected.",
         this, mState));
    return NS_ERROR_NOT_AVAILABLE;
  }

  memcpy(addr, &mSelfAddr, sizeof(NetAddr));
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::Bind(NetAddr* aLocalAddr) {
  NS_ENSURE_ARG(aLocalAddr);

  MutexAutoLock lock(mLock);
  if (mAttached) {
    return NS_ERROR_FAILURE;
  }

  mBindAddr = MakeUnique<NetAddr>();
  memcpy(mBindAddr.get(), aLocalAddr, sizeof(NetAddr));

  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetScriptablePeerAddr(nsINetAddr** addr) {
  NetAddr rawAddr;

  nsresult rv;
  rv = GetPeerAddr(&rawAddr);
  if (NS_FAILED(rv)) return rv;

  RefPtr<nsNetAddr> netaddr = new nsNetAddr(&rawAddr);
  netaddr.forget(addr);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetScriptableSelfAddr(nsINetAddr** addr) {
  NetAddr rawAddr;

  nsresult rv;
  rv = GetSelfAddr(&rawAddr);
  if (NS_FAILED(rv)) return rv;

  RefPtr<nsNetAddr> netaddr = new nsNetAddr(&rawAddr);
  netaddr.forget(addr);

  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetTimeout(uint32_t type, uint32_t* value) {
  NS_ENSURE_ARG_MAX(type, nsISocketTransport::TIMEOUT_READ_WRITE);
  MutexAutoLock lock(mLock);
  *value = (uint32_t)mTimeouts[type];
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetTimeout(uint32_t type, uint32_t value) {
  NS_ENSURE_ARG_MAX(type, nsISocketTransport::TIMEOUT_READ_WRITE);

  SOCKET_LOG(("nsSocketTransport::SetTimeout %p type=%u, value=%u", this, type,
              value));

  // truncate overly large timeout values.
  {
    MutexAutoLock lock(mLock);
    mTimeouts[type] = (uint16_t)std::min<uint32_t>(value, UINT16_MAX);
  }
  PostEvent(MSG_TIMEOUT_CHANGED);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetReuseAddrPort(bool reuseAddrPort) {
  mReuseAddrPort = reuseAddrPort;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetLinger(bool aPolarity, int16_t aTimeout) {
  MutexAutoLock lock(mLock);

  mLingerPolarity = aPolarity;
  mLingerTimeout = aTimeout;

  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetQoSBits(uint8_t aQoSBits) {
  // Don't do any checking here of bits.  Why?  Because as of RFC-4594
  // several different Class Selector and Assured Forwarding values
  // have been defined, but that isn't to say more won't be added later.
  // In that case, any checking would be an impediment to interoperating
  // with newer QoS definitions.

  mQoSBits = aQoSBits;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetQoSBits(uint8_t* aQoSBits) {
  *aQoSBits = mQoSBits;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetRecvBufferSize(uint32_t* aSize) {
  PRFileDescAutoLock fd(this, false);
  if (!fd.IsInitialized()) return NS_ERROR_NOT_CONNECTED;

  nsresult rv = NS_OK;
  PRSocketOptionData opt;
  opt.option = PR_SockOpt_RecvBufferSize;
  if (PR_GetSocketOption(fd, &opt) == PR_SUCCESS)
    *aSize = opt.value.recv_buffer_size;
  else
    rv = NS_ERROR_FAILURE;

  return rv;
}

NS_IMETHODIMP
nsSocketTransport::GetSendBufferSize(uint32_t* aSize) {
  PRFileDescAutoLock fd(this, false);
  if (!fd.IsInitialized()) return NS_ERROR_NOT_CONNECTED;

  nsresult rv = NS_OK;
  PRSocketOptionData opt;
  opt.option = PR_SockOpt_SendBufferSize;
  if (PR_GetSocketOption(fd, &opt) == PR_SUCCESS)
    *aSize = opt.value.send_buffer_size;
  else
    rv = NS_ERROR_FAILURE;

  return rv;
}

NS_IMETHODIMP
nsSocketTransport::SetRecvBufferSize(uint32_t aSize) {
  PRFileDescAutoLock fd(this, false);
  if (!fd.IsInitialized()) return NS_ERROR_NOT_CONNECTED;

  nsresult rv = NS_OK;
  PRSocketOptionData opt;
  opt.option = PR_SockOpt_RecvBufferSize;
  opt.value.recv_buffer_size = aSize;
  if (PR_SetSocketOption(fd, &opt) != PR_SUCCESS) rv = NS_ERROR_FAILURE;

  return rv;
}

NS_IMETHODIMP
nsSocketTransport::SetSendBufferSize(uint32_t aSize) {
  PRFileDescAutoLock fd(this, false);
  if (!fd.IsInitialized()) return NS_ERROR_NOT_CONNECTED;

  nsresult rv = NS_OK;
  PRSocketOptionData opt;
  opt.option = PR_SockOpt_SendBufferSize;
  opt.value.send_buffer_size = aSize;
  if (PR_SetSocketOption(fd, &opt) != PR_SUCCESS) rv = NS_ERROR_FAILURE;

  return rv;
}

NS_IMETHODIMP
nsSocketTransport::OnLookupComplete(nsICancelable* request, nsIDNSRecord* rec,
                                    nsresult status) {
  SOCKET_LOG(("nsSocketTransport::OnLookupComplete: this=%p status %" PRIx32
              ".",
              this, static_cast<uint32_t>(status)));

  if (NS_SUCCEEDED(status)) {
    mDNSRecord = do_QueryInterface(rec);
    MOZ_ASSERT(mDNSRecord);
  }

  // flag host lookup complete for the benefit of the ResolveHost method.
  mResolving = false;
  nsresult rv = PostEvent(MSG_DNS_LOOKUP_COMPLETE, status, nullptr);

  // if posting a message fails, then we should assume that the socket
  // transport has been shutdown.  this should never happen!  if it does
  // it means that the socket transport service was shutdown before the
  // DNS service.
  if (NS_FAILED(rv)) {
    NS_WARNING("unable to post DNS lookup complete message");
  }

  return NS_OK;
}

// nsIInterfaceRequestor
NS_IMETHODIMP
nsSocketTransport::GetInterface(const nsIID& iid, void** result) {
  if (iid.Equals(NS_GET_IID(nsIDNSRecord)) ||
      iid.Equals(NS_GET_IID(nsIDNSAddrRecord))) {
    return mDNSRecord ? mDNSRecord->QueryInterface(iid, result)
                      : NS_ERROR_NO_INTERFACE;
  }
  return this->QueryInterface(iid, result);
}

NS_IMETHODIMP
nsSocketTransport::GetInterfaces(nsTArray<nsIID>& array) {
  return NS_CI_INTERFACE_GETTER_NAME(nsSocketTransport)(array);
}

NS_IMETHODIMP
nsSocketTransport::GetScriptableHelper(nsIXPCScriptable** _retval) {
  *_retval = nullptr;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetContractID(nsACString& aContractID) {
  aContractID.SetIsVoid(true);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetClassDescription(nsACString& aClassDescription) {
  aClassDescription.SetIsVoid(true);
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetClassID(nsCID** aClassID) {
  *aClassID = nullptr;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetFlags(uint32_t* aFlags) {
  *aFlags = nsIClassInfo::THREADSAFE;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetClassIDNoAlloc(nsCID* aClassIDNoAlloc) {
  return NS_ERROR_NOT_AVAILABLE;
}

NS_IMETHODIMP
nsSocketTransport::GetConnectionFlags(uint32_t* value) {
  *value = mConnectionFlags;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetConnectionFlags(uint32_t value) {
  SOCKET_LOG(
      ("nsSocketTransport::SetConnectionFlags %p flags=%u", this, value));

  mConnectionFlags = value;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetIsPrivate(bool aIsPrivate) {
  mIsPrivate = aIsPrivate;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetTlsFlags(uint32_t* value) {
  *value = mTlsFlags;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetTlsFlags(uint32_t value) {
  mTlsFlags = value;
  return NS_OK;
}

void nsSocketTransport::OnKeepaliveEnabledPrefChange(bool aEnabled) {
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  // The global pref toggles keepalive as a system feature; it only affects
  // an individual socket if keepalive has been specifically enabled for it.
  // So, ensure keepalive is configured correctly if previously enabled.
  if (mKeepaliveEnabled) {
    nsresult rv = SetKeepaliveEnabledInternal(aEnabled);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      SOCKET_LOG(("  SetKeepaliveEnabledInternal [%s] failed rv[0x%" PRIx32 "]",
                  aEnabled ? "enable" : "disable", static_cast<uint32_t>(rv)));
    }
  }
}

nsresult nsSocketTransport::SetKeepaliveEnabledInternal(bool aEnable) {
  MOZ_ASSERT(mKeepaliveIdleTimeS > 0 && mKeepaliveIdleTimeS <= kMaxTCPKeepIdle);
  MOZ_ASSERT(mKeepaliveRetryIntervalS > 0 &&
             mKeepaliveRetryIntervalS <= kMaxTCPKeepIntvl);
  MOZ_ASSERT(mKeepaliveProbeCount > 0 &&
             mKeepaliveProbeCount <= kMaxTCPKeepCount);

  PRFileDescAutoLock fd(this, true);
  if (NS_WARN_IF(!fd.IsInitialized())) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Only enable if keepalives are globally enabled, but ensure other
  // options are set correctly on the fd.
  bool enable = aEnable && mSocketTransportService->IsKeepaliveEnabled();
  nsresult rv =
      fd.SetKeepaliveVals(enable, mKeepaliveIdleTimeS, mKeepaliveRetryIntervalS,
                          mKeepaliveProbeCount);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    SOCKET_LOG(("  SetKeepaliveVals failed rv[0x%" PRIx32 "]",
                static_cast<uint32_t>(rv)));
    return rv;
  }
  rv = fd.SetKeepaliveEnabled(enable);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    SOCKET_LOG(("  SetKeepaliveEnabled failed rv[0x%" PRIx32 "]",
                static_cast<uint32_t>(rv)));
    return rv;
  }
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetKeepaliveEnabled(bool* aResult) {
  MOZ_ASSERT(aResult);

  *aResult = mKeepaliveEnabled;
  return NS_OK;
}

nsresult nsSocketTransport::EnsureKeepaliveValsAreInitialized() {
  nsresult rv = NS_OK;
  int32_t val = -1;
  if (mKeepaliveIdleTimeS == -1) {
    rv = mSocketTransportService->GetKeepaliveIdleTime(&val);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    mKeepaliveIdleTimeS = val;
  }
  if (mKeepaliveRetryIntervalS == -1) {
    rv = mSocketTransportService->GetKeepaliveRetryInterval(&val);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    mKeepaliveRetryIntervalS = val;
  }
  if (mKeepaliveProbeCount == -1) {
    rv = mSocketTransportService->GetKeepaliveProbeCount(&val);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    mKeepaliveProbeCount = val;
  }
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetKeepaliveEnabled(bool aEnable) {
#if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  if (aEnable == mKeepaliveEnabled) {
    SOCKET_LOG(("nsSocketTransport::SetKeepaliveEnabled [%p] already %s.", this,
                aEnable ? "enabled" : "disabled"));
    return NS_OK;
  }

  nsresult rv = NS_OK;
  if (aEnable) {
    rv = EnsureKeepaliveValsAreInitialized();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      SOCKET_LOG(
          ("  SetKeepaliveEnabled [%p] "
           "error [0x%" PRIx32 "] initializing keepalive vals",
           this, static_cast<uint32_t>(rv)));
      return rv;
    }
  }
  SOCKET_LOG(
      ("nsSocketTransport::SetKeepaliveEnabled [%p] "
       "%s, idle time[%ds] retry interval[%ds] packet count[%d]: "
       "globally %s.",
       this, aEnable ? "enabled" : "disabled", mKeepaliveIdleTimeS,
       mKeepaliveRetryIntervalS, mKeepaliveProbeCount,
       mSocketTransportService->IsKeepaliveEnabled() ? "enabled" : "disabled"));

  // Set mKeepaliveEnabled here so that state is maintained; it is possible
  // that we're in between fds, e.g. the 1st IP address failed, so we're about
  // to retry on a 2nd from the DNS record.
  mKeepaliveEnabled = aEnable;

  rv = SetKeepaliveEnabledInternal(aEnable);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    SOCKET_LOG(("  SetKeepaliveEnabledInternal failed rv[0x%" PRIx32 "]",
                static_cast<uint32_t>(rv)));
    return rv;
  }

  return NS_OK;
#else /* !(defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)) */
  SOCKET_LOG(("nsSocketTransport::SetKeepaliveEnabled unsupported platform"));
  return NS_ERROR_NOT_IMPLEMENTED;
#endif
}

NS_IMETHODIMP
nsSocketTransport::SetKeepaliveVals(int32_t aIdleTime, int32_t aRetryInterval) {
#if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
  if (NS_WARN_IF(aIdleTime <= 0 || kMaxTCPKeepIdle < aIdleTime)) {
    return NS_ERROR_INVALID_ARG;
  }
  if (NS_WARN_IF(aRetryInterval <= 0 || kMaxTCPKeepIntvl < aRetryInterval)) {
    return NS_ERROR_INVALID_ARG;
  }

  if (aIdleTime == mKeepaliveIdleTimeS &&
      aRetryInterval == mKeepaliveRetryIntervalS) {
    SOCKET_LOG(
        ("nsSocketTransport::SetKeepaliveVals [%p] idle time "
         "already %ds and retry interval already %ds.",
         this, mKeepaliveIdleTimeS, mKeepaliveRetryIntervalS));
    return NS_OK;
  }
  mKeepaliveIdleTimeS = aIdleTime;
  mKeepaliveRetryIntervalS = aRetryInterval;

  nsresult rv = NS_OK;
  if (mKeepaliveProbeCount == -1) {
    int32_t val = -1;
    nsresult rv = mSocketTransportService->GetKeepaliveProbeCount(&val);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    mKeepaliveProbeCount = val;
  }

  SOCKET_LOG(
      ("nsSocketTransport::SetKeepaliveVals [%p] "
       "keepalive %s, idle time[%ds] retry interval[%ds] "
       "packet count[%d]",
       this, mKeepaliveEnabled ? "enabled" : "disabled", mKeepaliveIdleTimeS,
       mKeepaliveRetryIntervalS, mKeepaliveProbeCount));

  PRFileDescAutoLock fd(this, true);
  if (NS_WARN_IF(!fd.IsInitialized())) {
    return NS_ERROR_NULL_POINTER;
  }

  rv = fd.SetKeepaliveVals(mKeepaliveEnabled, mKeepaliveIdleTimeS,
                           mKeepaliveRetryIntervalS, mKeepaliveProbeCount);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  return NS_OK;
#else
  SOCKET_LOG(("nsSocketTransport::SetKeepaliveVals unsupported platform"));
  return NS_ERROR_NOT_IMPLEMENTED;
#endif
}

#ifdef ENABLE_SOCKET_TRACING

#  include <stdio.h>
#  include <ctype.h>
#  include "prenv.h"

static void DumpBytesToFile(const char* path, const char* header,
                            const char* buf, int32_t n) {
  FILE* fp = fopen(path, "a");

  fprintf(fp, "\n%s [%d bytes]\n", header, n);

  const unsigned char* p;
  while (n) {
    p = (const unsigned char*)buf;

    int32_t i, row_max = std::min(16, n);

    for (i = 0; i < row_max; ++i) fprintf(fp, "%02x  ", *p++);
    for (i = row_max; i < 16; ++i) fprintf(fp, "    ");

    p = (const unsigned char*)buf;
    for (i = 0; i < row_max; ++i, ++p) {
      if (isprint(*p))
        fprintf(fp, "%c", *p);
      else
        fprintf(fp, ".");
    }

    fprintf(fp, "\n");
    buf += row_max;
    n -= row_max;
  }

  fprintf(fp, "\n");
  fclose(fp);
}

void nsSocketTransport::TraceInBuf(const char* buf, int32_t n) {
  char* val = PR_GetEnv("NECKO_SOCKET_TRACE_LOG");
  if (!val || !*val) return;

  nsAutoCString header;
  header.AssignLiteral("Reading from: ");
  header.Append(mHost);
  header.Append(':');
  header.AppendInt(mPort);

  DumpBytesToFile(val, header.get(), buf, n);
}

void nsSocketTransport::TraceOutBuf(const char* buf, int32_t n) {
  char* val = PR_GetEnv("NECKO_SOCKET_TRACE_LOG");
  if (!val || !*val) return;

  nsAutoCString header;
  header.AssignLiteral("Writing to: ");
  header.Append(mHost);
  header.Append(':');
  header.AppendInt(mPort);

  DumpBytesToFile(val, header.get(), buf, n);
}

#endif

static void LogNSPRError(const char* aPrefix, const void* aObjPtr) {
#if defined(DEBUG)
  PRErrorCode errCode = PR_GetError();
  int errLen = PR_GetErrorTextLength();
  nsAutoCString errStr;
  if (errLen > 0) {
    errStr.SetLength(errLen);
    PR_GetErrorText(errStr.BeginWriting());
  }
  NS_WARNING(
      nsPrintfCString("%s [%p] NSPR error[0x%x] %s.",
                      aPrefix ? aPrefix : "nsSocketTransport", aObjPtr, errCode,
                      errLen > 0 ? errStr.BeginReading() : "<no error text>")
          .get());
#endif
}

nsresult nsSocketTransport::PRFileDescAutoLock::SetKeepaliveEnabled(
    bool aEnable) {
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
  MOZ_ASSERT(!(aEnable && !gSocketTransportService->IsKeepaliveEnabled()),
             "Cannot enable keepalive if global pref is disabled!");
  if (aEnable && !gSocketTransportService->IsKeepaliveEnabled()) {
    return NS_ERROR_ILLEGAL_VALUE;
  }

  PRSocketOptionData opt;

  opt.option = PR_SockOpt_Keepalive;
  opt.value.keep_alive = aEnable;
  PRStatus status = PR_SetSocketOption(mFd, &opt);
  if (NS_WARN_IF(status != PR_SUCCESS)) {
    LogNSPRError("nsSocketTransport::PRFileDescAutoLock::SetKeepaliveEnabled",
                 mSocketTransport);
    return ErrorAccordingToNSPR(PR_GetError());
  }
  return NS_OK;
}

static void LogOSError(const char* aPrefix, const void* aObjPtr) {
#if defined(DEBUG)
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

#  ifdef XP_WIN
  DWORD errCode = WSAGetLastError();
  LPVOID errMessage;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL, errCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPTSTR)&errMessage, 0, NULL);
#  else
  int errCode = errno;
  char* errMessage = strerror(errno);
#  endif
  NS_WARNING(nsPrintfCString("%s [%p] OS error[0x%x] %s",
                             aPrefix ? aPrefix : "nsSocketTransport", aObjPtr,
                             errCode,
                             errMessage ? errMessage : "<no error text>")
                 .get());
#  ifdef XP_WIN
  LocalFree(errMessage);
#  endif
#endif
}

/* XXX PR_SetSockOpt does not support setting keepalive values, so native
 * handles and platform specific apis (setsockopt, WSAIOCtl) are used in this
 * file. Requires inclusion of NSPR private/pprio.h, and platform headers.
 */

nsresult nsSocketTransport::PRFileDescAutoLock::SetKeepaliveVals(
    bool aEnabled, int aIdleTime, int aRetryInterval, int aProbeCount) {
#if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
  if (NS_WARN_IF(aIdleTime <= 0 || kMaxTCPKeepIdle < aIdleTime)) {
    return NS_ERROR_INVALID_ARG;
  }
  if (NS_WARN_IF(aRetryInterval <= 0 || kMaxTCPKeepIntvl < aRetryInterval)) {
    return NS_ERROR_INVALID_ARG;
  }
  if (NS_WARN_IF(aProbeCount <= 0 || kMaxTCPKeepCount < aProbeCount)) {
    return NS_ERROR_INVALID_ARG;
  }

  PROsfd sock = PR_FileDesc2NativeHandle(mFd);
  if (NS_WARN_IF(sock == -1)) {
    LogNSPRError("nsSocketTransport::PRFileDescAutoLock::SetKeepaliveVals",
                 mSocketTransport);
    return ErrorAccordingToNSPR(PR_GetError());
  }
#endif

#if defined(XP_WIN)
  // Windows allows idle time and retry interval to be set; NOT ping count.
  struct tcp_keepalive keepalive_vals = {(u_long)aEnabled,
                                         // Windows uses msec.
                                         (u_long)(aIdleTime * 1000UL),
                                         (u_long)(aRetryInterval * 1000UL)};
  DWORD bytes_returned;
  int err =
      WSAIoctl(sock, SIO_KEEPALIVE_VALS, &keepalive_vals,
               sizeof(keepalive_vals), NULL, 0, &bytes_returned, NULL, NULL);
  if (NS_WARN_IF(err)) {
    LogOSError("nsSocketTransport WSAIoctl failed", mSocketTransport);
    return NS_ERROR_UNEXPECTED;
  }
  return NS_OK;

#elif defined(XP_DARWIN)
  // Darwin uses sec; only supports idle time being set.
  int err = setsockopt(sock, IPPROTO_TCP, TCP_KEEPALIVE, &aIdleTime,
                       sizeof(aIdleTime));
  if (NS_WARN_IF(err)) {
    LogOSError("nsSocketTransport Failed setting TCP_KEEPALIVE",
               mSocketTransport);
    return NS_ERROR_UNEXPECTED;
  }
  return NS_OK;

#elif defined(XP_UNIX)
  // Not all *nix OSes support the following setsockopt() options
  // ... but we assume they are supported in the Android kernel;
  // build errors will tell us if they are not.
#  if defined(ANDROID) || defined(TCP_KEEPIDLE)
  // Idle time until first keepalive probe; interval between ack'd probes;
  // seconds.
  int err = setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &aIdleTime,
                       sizeof(aIdleTime));
  if (NS_WARN_IF(err)) {
    LogOSError("nsSocketTransport Failed setting TCP_KEEPIDLE",
               mSocketTransport);
    return NS_ERROR_UNEXPECTED;
  }

#  endif
#  if defined(ANDROID) || defined(TCP_KEEPINTVL)
  // Interval between unack'd keepalive probes; seconds.
  err = setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &aRetryInterval,
                   sizeof(aRetryInterval));
  if (NS_WARN_IF(err)) {
    LogOSError("nsSocketTransport Failed setting TCP_KEEPINTVL",
               mSocketTransport);
    return NS_ERROR_UNEXPECTED;
  }

#  endif
#  if defined(ANDROID) || defined(TCP_KEEPCNT)
  // Number of unack'd keepalive probes before connection times out.
  err = setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &aProbeCount,
                   sizeof(aProbeCount));
  if (NS_WARN_IF(err)) {
    LogOSError("nsSocketTransport Failed setting TCP_KEEPCNT",
               mSocketTransport);
    return NS_ERROR_UNEXPECTED;
  }

#  endif
  return NS_OK;
#else
  MOZ_ASSERT(false,
             "nsSocketTransport::PRFileDescAutoLock::SetKeepaliveVals "
             "called on unsupported platform!");
  return NS_ERROR_UNEXPECTED;
#endif
}

void nsSocketTransport::CloseSocket(PRFileDesc* aFd, bool aTelemetryEnabled) {
#if defined(XP_WIN)
  AttachShutdownLayer(aFd);
#endif

  // We use PRIntervalTime here because we need
  // nsIOService::LastOfflineStateChange time and
  // nsIOService::LastConectivityChange time to be atomic.
  PRIntervalTime closeStarted;
  if (aTelemetryEnabled) {
    closeStarted = PR_IntervalNow();
  }

  PR_Close(aFd);

  if (aTelemetryEnabled) {
    SendPRBlockingTelemetry(
        closeStarted, Telemetry::PRCLOSE_TCP_BLOCKING_TIME_NORMAL,
        Telemetry::PRCLOSE_TCP_BLOCKING_TIME_SHUTDOWN,
        Telemetry::PRCLOSE_TCP_BLOCKING_TIME_CONNECTIVITY_CHANGE,
        Telemetry::PRCLOSE_TCP_BLOCKING_TIME_LINK_CHANGE,
        Telemetry::PRCLOSE_TCP_BLOCKING_TIME_OFFLINE);
  }
}

void nsSocketTransport::SendPRBlockingTelemetry(
    PRIntervalTime aStart, Telemetry::HistogramID aIDNormal,
    Telemetry::HistogramID aIDShutdown,
    Telemetry::HistogramID aIDConnectivityChange,
    Telemetry::HistogramID aIDLinkChange, Telemetry::HistogramID aIDOffline) {
  PRIntervalTime now = PR_IntervalNow();
  if (gIOService->IsNetTearingDown()) {
    Telemetry::Accumulate(aIDShutdown, PR_IntervalToMilliseconds(now - aStart));

  } else if (PR_IntervalToSeconds(now - gIOService->LastConnectivityChange()) <
             60) {
    Telemetry::Accumulate(aIDConnectivityChange,
                          PR_IntervalToMilliseconds(now - aStart));
  } else if (PR_IntervalToSeconds(now - gIOService->LastNetworkLinkChange()) <
             60) {
    Telemetry::Accumulate(aIDLinkChange,
                          PR_IntervalToMilliseconds(now - aStart));

  } else if (PR_IntervalToSeconds(now - gIOService->LastOfflineStateChange()) <
             60) {
    Telemetry::Accumulate(aIDOffline, PR_IntervalToMilliseconds(now - aStart));
  } else {
    Telemetry::Accumulate(aIDNormal, PR_IntervalToMilliseconds(now - aStart));
  }
}

NS_IMETHODIMP
nsSocketTransport::SetFastOpenCallback(TCPFastOpen* aFastOpen) {
  mFastOpenCallback = aFastOpen;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetFirstRetryError(nsresult* aFirstRetryError) {
  *aFirstRetryError = mFirstRetryError;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetResetIPFamilyPreference(bool* aReset) {
  *aReset = mResetFamilyPreference;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::GetEchConfigUsed(bool* aEchConfigUsed) {
  *aEchConfigUsed = mEchConfigUsed;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::SetEchConfig(const nsACString& aEchConfig) {
  mEchConfig = aEchConfig;
  return NS_OK;
}

NS_IMETHODIMP
nsSocketTransport::ResolvedByTRR(bool* aResolvedByTRR) {
  *aResolvedByTRR = mResolvedByTRR;
  return NS_OK;
}

}  // namespace net
}  // namespace mozilla