summaryrefslogtreecommitdiff
path: root/dom/xhr/XMLHttpRequestMainThread.cpp
blob: d99747e2b7e86bad59bc47485626a50972abc7f5 (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
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "XMLHttpRequestMainThread.h"

#include <algorithm>
#ifndef XP_WIN
#include <unistd.h>
#endif
#include "mozilla/ArrayUtils.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/dom/BlobSet.h"
#include "mozilla/dom/DOMString.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/FetchUtil.h"
#include "mozilla/dom/FormData.h"
#include "mozilla/dom/MutableBlobStorage.h"
#include "mozilla/dom/XMLDocument.h"
#include "mozilla/dom/URLSearchParams.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/LoadContext.h"
#include "mozilla/MemoryReporting.h"
#include "nsIDOMDocument.h"
#include "mozilla/dom/ProgressEvent.h"
#include "nsIJARChannel.h"
#include "nsIJARURI.h"
#include "nsLayoutCID.h"
#include "nsReadableUtils.h"

#include "nsIURI.h"
#include "nsILoadGroup.h"
#include "nsNetUtil.h"
#include "nsStringStream.h"
#include "nsIAuthPrompt.h"
#include "nsIAuthPrompt2.h"
#include "nsIOutputStream.h"
#include "nsISupportsPrimitives.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsStreamUtils.h"
#include "nsThreadUtils.h"
#include "nsIUploadChannel.h"
#include "nsIUploadChannel2.h"
#include "nsIDOMSerializer.h"
#include "nsXPCOM.h"
#include "nsIDOMEventListener.h"
#include "nsIScriptSecurityManager.h"
#include "nsIVariant.h"
#include "nsVariant.h"
#include "nsIScriptError.h"
#include "nsIStreamConverterService.h"
#include "nsICachingChannel.h"
#include "nsContentUtils.h"
#include "nsCycleCollectionParticipant.h"
#include "nsError.h"
#include "nsIHTMLDocument.h"
#include "nsIStorageStream.h"
#include "nsIPromptFactory.h"
#include "nsIWindowWatcher.h"
#include "nsIConsoleService.h"
#include "nsIContentSecurityPolicy.h"
#include "nsAsyncRedirectVerifyHelper.h"
#include "nsStringBuffer.h"
#include "nsIFileChannel.h"
#include "jsfriendapi.h"
#include "GeckoProfiler.h"
#include "mozilla/dom/EncodingUtils.h"
#include "nsIUnicodeDecoder.h"
#include "mozilla/dom/XMLHttpRequestBinding.h"
#include "mozilla/Attributes.h"
#include "MultipartBlobImpl.h"
#include "nsIPermissionManager.h"
#include "nsMimeTypes.h"
#include "nsIHttpChannelInternal.h"
#include "nsIClassOfService.h"
#include "nsCharSeparatedTokenizer.h"
#include "nsStreamListenerWrapper.h"
#include "xpcjsid.h"
#include "nsITimedChannel.h"
#include "nsWrapperCacheInlines.h"
#include "nsZipArchive.h"
#include "mozilla/Preferences.h"
#include "private/pprio.h"
#include "XMLHttpRequestUpload.h"
#include "nsHostObjectProtocolHandler.h"

using namespace mozilla::net;

namespace mozilla {
namespace dom {

// Maximum size that we'll grow an ArrayBuffer instead of doubling,
// once doubling reaches this threshold
const uint32_t XML_HTTP_REQUEST_ARRAYBUFFER_MAX_GROWTH = 32*1024*1024;
// start at 32k to avoid lots of doubling right at the start
const uint32_t XML_HTTP_REQUEST_ARRAYBUFFER_MIN_SIZE = 32*1024;
// the maximum Content-Length that we'll preallocate.  1GB.  Must fit
// in an int32_t!
const int32_t XML_HTTP_REQUEST_MAX_CONTENT_LENGTH_PREALLOCATE = 1*1024*1024*1024LL;

namespace {
  const nsLiteralString ProgressEventTypeStrings[] = {
    NS_LITERAL_STRING("loadstart"),
    NS_LITERAL_STRING("progress"),
    NS_LITERAL_STRING("error"),
    NS_LITERAL_STRING("abort"),
    NS_LITERAL_STRING("timeout"),
    NS_LITERAL_STRING("load"),
    NS_LITERAL_STRING("loadend")
  };
  static_assert(MOZ_ARRAY_LENGTH(ProgressEventTypeStrings) ==
                  size_t(XMLHttpRequestMainThread::ProgressEventType::ENUM_MAX),
                "Mismatched lengths for ProgressEventTypeStrings and ProgressEventType enums");

  const nsString kLiteralString_readystatechange = NS_LITERAL_STRING("readystatechange");
  const nsString kLiteralString_xmlhttprequest = NS_LITERAL_STRING("xmlhttprequest");
  const nsString kLiteralString_DOMContentLoaded = NS_LITERAL_STRING("DOMContentLoaded");
}

// CIDs
#define NS_BADCERTHANDLER_CONTRACTID \
  "@mozilla.org/content/xmlhttprequest-bad-cert-handler;1"

#define NS_PROGRESS_EVENT_INTERVAL 50
#define MAX_SYNC_TIMEOUT_WHEN_UNLOADING 10000 /* 10 secs */

NS_IMPL_ISUPPORTS(nsXHRParseEndListener, nsIDOMEventListener)

class nsResumeTimeoutsEvent : public Runnable
{
public:
  explicit nsResumeTimeoutsEvent(nsPIDOMWindowInner* aWindow) : mWindow(aWindow) {}

  NS_IMETHOD Run() override
  {
    mWindow->Resume();
    return NS_OK;
  }

private:
  nsCOMPtr<nsPIDOMWindowInner> mWindow;
};


// This helper function adds the given load flags to the request's existing
// load flags.
static void AddLoadFlags(nsIRequest *request, nsLoadFlags newFlags)
{
  nsLoadFlags flags;
  request->GetLoadFlags(&flags);
  flags |= newFlags;
  request->SetLoadFlags(flags);
}

/////////////////////////////////////////////
//
//
/////////////////////////////////////////////

bool
XMLHttpRequestMainThread::sDontWarnAboutSyncXHR = false;

XMLHttpRequestMainThread::XMLHttpRequestMainThread()
  : mResponseBodyDecodedPos(0),
    mResponseType(XMLHttpRequestResponseType::_empty),
    mRequestObserver(nullptr),
    mState(State::unsent),
    mFlagSynchronous(false), mFlagAborted(false), mFlagParseBody(false),
    mFlagSyncLooping(false), mFlagBackgroundRequest(false),
    mFlagHadUploadListenersOnSend(false), mFlagACwithCredentials(false),
    mFlagTimedOut(false), mFlagDeleted(false), mFlagSend(false),
    mUploadTransferred(0), mUploadTotal(0), mUploadComplete(true),
    mProgressSinceLastProgressEvent(false),
    mRequestSentTime(0), mTimeoutMilliseconds(0),
    mErrorLoad(false), mErrorParsingXML(false),
    mWaitingForOnStopRequest(false),
    mProgressTimerIsActive(false),
    mIsHtml(false),
    mWarnAboutSyncHtml(false),
    mLoadTotal(-1),
    mIsSystem(false),
    mIsAnon(false),
    mFirstStartRequestSeen(false),
    mInLoadProgressEvent(false),
    mResultJSON(JS::UndefinedValue()),
    mResultArrayBuffer(nullptr),
    mIsMappedArrayBuffer(false),
    mXPCOMifier(nullptr)
{
  mozilla::HoldJSObjects(this);
}

XMLHttpRequestMainThread::~XMLHttpRequestMainThread()
{
  mFlagDeleted = true;

  if ((mState == State::opened && mFlagSend) ||
      mState == State::loading) {
    Abort();
  }

  MOZ_ASSERT(!mFlagSyncLooping, "we rather crash than hang");
  mFlagSyncLooping = false;

  mResultJSON.setUndefined();
  mResultArrayBuffer = nullptr;
  mozilla::DropJSObjects(this);
}

/**
 * This Init method is called from the factory constructor.
 */
nsresult
XMLHttpRequestMainThread::Init()
{
  nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
  nsCOMPtr<nsIPrincipal> subjectPrincipal;
  if (secMan) {
    secMan->GetSystemPrincipal(getter_AddRefs(subjectPrincipal));
  }
  NS_ENSURE_STATE(subjectPrincipal);

  // Instead of grabbing some random global from the context stack,
  // let's use the default one (junk scope) for now.
  // We should move away from this Init...
  Construct(subjectPrincipal, xpc::NativeGlobal(xpc::PrivilegedJunkScope()));
  return NS_OK;
}

/**
 * This Init method should only be called by C++ consumers.
 */
NS_IMETHODIMP
XMLHttpRequestMainThread::Init(nsIPrincipal* aPrincipal,
                               nsIGlobalObject* aGlobalObject,
                               nsIURI* aBaseURI,
                               nsILoadGroup* aLoadGroup)
{
  NS_ENSURE_ARG_POINTER(aPrincipal);
  Construct(aPrincipal, aGlobalObject, aBaseURI, aLoadGroup);
  return NS_OK;
}

void
XMLHttpRequestMainThread::InitParameters(bool aAnon, bool aSystem)
{
  if (!aAnon && !aSystem) {
    return;
  }

  // Check for permissions.
  // Chrome is always allowed access, so do the permission check only
  // for non-chrome pages.
  if (!IsSystemXHR() && aSystem) {
    nsIGlobalObject* global = GetOwnerGlobal();
    if (NS_WARN_IF(!global)) {
      SetParameters(aAnon, false);
      return;
    }

    nsIPrincipal* principal = global->PrincipalOrNull();
    if (NS_WARN_IF(!principal)) {
      SetParameters(aAnon, false);
      return;
    }

    nsCOMPtr<nsIPermissionManager> permMgr =
      services::GetPermissionManager();
    if (NS_WARN_IF(!permMgr)) {
      SetParameters(aAnon, false);
      return;
    }

    uint32_t permission;
    nsresult rv =
      permMgr->TestPermissionFromPrincipal(principal, "systemXHR", &permission);
    if (NS_FAILED(rv) || permission != nsIPermissionManager::ALLOW_ACTION) {
      SetParameters(aAnon, false);
      return;
    }
  }

  SetParameters(aAnon, aSystem);
}

void
XMLHttpRequestMainThread::ResetResponse()
{
  mResponseXML = nullptr;
  mResponseBody.Truncate();
  TruncateResponseText();
  mResponseBlob = nullptr;
  mDOMBlob = nullptr;
  mBlobStorage = nullptr;
  mBlobSet = nullptr;
  mResultArrayBuffer = nullptr;
  mArrayBufferBuilder.reset();
  mResultJSON.setUndefined();
  mDataAvailable = 0;
  mLoadTransferred = 0;
  mResponseBodyDecodedPos = 0;
}

void
XMLHttpRequestMainThread::SetRequestObserver(nsIRequestObserver* aObserver)
{
  mRequestObserver = aObserver;
}

  NS_IMPL_CYCLE_COLLECTION_CLASS(XMLHttpRequestMainThread)

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(XMLHttpRequestMainThread,
                                                  XMLHttpRequestEventTarget)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContext)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChannel)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResponseXML)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mXMLParserStreamListener)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResponseBlob)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDOMBlob)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNotificationCallbacks)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChannelEventSink)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mProgressEventSink)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mUpload)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(XMLHttpRequestMainThread,
                                                XMLHttpRequestEventTarget)
  tmp->mResultArrayBuffer = nullptr;
  tmp->mArrayBufferBuilder.reset();
  tmp->mResultJSON.setUndefined();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mContext)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mChannel)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mResponseXML)

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mXMLParserStreamListener)

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mResponseBlob)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mDOMBlob)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mNotificationCallbacks)

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mChannelEventSink)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mProgressEventSink)

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mUpload)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(XMLHttpRequestMainThread,
                                               XMLHttpRequestEventTarget)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mResultArrayBuffer)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mResultJSON)
NS_IMPL_CYCLE_COLLECTION_TRACE_END

bool
XMLHttpRequestMainThread::IsCertainlyAliveForCC() const
{
  return mWaitingForOnStopRequest;
}

// QueryInterface implementation for XMLHttpRequestMainThread
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(XMLHttpRequestMainThread)
  NS_INTERFACE_MAP_ENTRY(nsIXMLHttpRequest)
  NS_INTERFACE_MAP_ENTRY(nsIJSXMLHttpRequest)
  NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
  NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
  NS_INTERFACE_MAP_ENTRY(nsIChannelEventSink)
  NS_INTERFACE_MAP_ENTRY(nsIProgressEventSink)
  NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
  NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
  NS_INTERFACE_MAP_ENTRY(nsISizeOfEventTarget)
NS_INTERFACE_MAP_END_INHERITING(XMLHttpRequestEventTarget)

NS_IMPL_ADDREF_INHERITED(XMLHttpRequestMainThread, XMLHttpRequestEventTarget)
NS_IMPL_RELEASE_INHERITED(XMLHttpRequestMainThread, XMLHttpRequestEventTarget)

NS_IMPL_EVENT_HANDLER(XMLHttpRequestMainThread, readystatechange)

void
XMLHttpRequestMainThread::DisconnectFromOwner()
{
  XMLHttpRequestEventTarget::DisconnectFromOwner();
  Abort();
}

size_t
XMLHttpRequestMainThread::SizeOfEventTargetIncludingThis(
  MallocSizeOf aMallocSizeOf) const
{
  size_t n = aMallocSizeOf(this);
  n += mResponseBody.SizeOfExcludingThisIfUnshared(aMallocSizeOf);

  // Why is this safe?  Because no-one else will report this string.  The
  // other possible sharers of this string are as follows.
  //
  // - The JS engine could hold copies if the JS code holds references, e.g.
  //   |var text = XHR.responseText|.  However, those references will be via JS
  //   external strings, for which the JS memory reporter does *not* report the
  //   chars.
  //
  // - Binary extensions, but they're *extremely* unlikely to do any memory
  //   reporting.
  //
  n += mResponseText.SizeOfThis(aMallocSizeOf);

  return n;

  // Measurement of the following members may be added later if DMD finds it is
  // worthwhile:
  // - lots
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetChannel(nsIChannel **aChannel)
{
  NS_ENSURE_ARG_POINTER(aChannel);
  NS_IF_ADDREF(*aChannel = mChannel);

  return NS_OK;
}

static void LogMessage(const char* aWarning, nsPIDOMWindowInner* aWindow,
                       const char16_t** aParams=nullptr, uint32_t aParamCount=0)
{
  nsCOMPtr<nsIDocument> doc;
  if (aWindow) {
    doc = aWindow->GetExtantDoc();
  }
  nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
                                  NS_LITERAL_CSTRING("DOM"), doc,
                                  nsContentUtils::eDOM_PROPERTIES,
                                  aWarning, aParams, aParamCount);
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetResponseXML(nsIDOMDocument **aResponseXML)
{
  ErrorResult rv;
  nsIDocument* responseXML = GetResponseXML(rv);
  if (rv.Failed()) {
    return rv.StealNSResult();
  }

  if (!responseXML) {
    *aResponseXML = nullptr;
    return NS_OK;
  }

  return CallQueryInterface(responseXML, aResponseXML);
}

nsIDocument*
XMLHttpRequestMainThread::GetResponseXML(ErrorResult& aRv)
{
  if (mResponseType != XMLHttpRequestResponseType::_empty &&
      mResponseType != XMLHttpRequestResponseType::Document) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSEXML);
    return nullptr;
  }
  if (mWarnAboutSyncHtml) {
    mWarnAboutSyncHtml = false;
    LogMessage("HTMLSyncXHRWarning", GetOwner());
  }
  if (mState != State::done) {
    return nullptr;
  }
  return mResponseXML;
}

/*
 * This piece copied from XMLDocument, we try to get the charset
 * from HTTP headers.
 */
nsresult
XMLHttpRequestMainThread::DetectCharset()
{
  mResponseCharset.Truncate();
  mDecoder = nullptr;

  if (mResponseType != XMLHttpRequestResponseType::_empty &&
      mResponseType != XMLHttpRequestResponseType::Text &&
      mResponseType != XMLHttpRequestResponseType::Json &&
      mResponseType != XMLHttpRequestResponseType::Moz_chunked_text) {
    return NS_OK;
  }

  nsAutoCString charsetVal;
  bool ok = mChannel &&
            NS_SUCCEEDED(mChannel->GetContentCharset(charsetVal)) &&
            EncodingUtils::FindEncodingForLabel(charsetVal, mResponseCharset);
  if (!ok || mResponseCharset.IsEmpty()) {
    // MS documentation states UTF-8 is default for responseText
    mResponseCharset.AssignLiteral("UTF-8");
  }

  if (mResponseType == XMLHttpRequestResponseType::Json &&
      !mResponseCharset.EqualsLiteral("UTF-8")) {
    // The XHR spec says only UTF-8 is supported for responseType == "json"
    LogMessage("JSONCharsetWarning", GetOwner());
    mResponseCharset.AssignLiteral("UTF-8");
  }

  mDecoder = EncodingUtils::DecoderForEncoding(mResponseCharset);

  return NS_OK;
}

nsresult
XMLHttpRequestMainThread::AppendToResponseText(const char * aSrcBuffer,
                                               uint32_t aSrcBufferLen)
{
  NS_ENSURE_STATE(mDecoder);

  int32_t destBufferLen;
  nsresult rv = mDecoder->GetMaxLength(aSrcBuffer, aSrcBufferLen,
                                       &destBufferLen);
  NS_ENSURE_SUCCESS(rv, rv);

  CheckedInt32 size = mResponseText.Length();
  size += destBufferLen;
  if (!size.isValid()) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  XMLHttpRequestStringWriterHelper helper(mResponseText);

  if (!helper.AddCapacity(destBufferLen)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // This code here is basically a copy of a similar thing in
  // nsScanner::Append(const char* aBuffer, uint32_t aLen).
  int32_t srclen = (int32_t)aSrcBufferLen;
  int32_t destlen = (int32_t)destBufferLen;
  rv = mDecoder->Convert(aSrcBuffer,
                         &srclen,
                         helper.EndOfExistingData(),
                         &destlen);
  MOZ_ASSERT(NS_SUCCEEDED(rv));
  MOZ_ASSERT(destlen <= destBufferLen);

  helper.AddLength(destlen);
  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetResponseText(nsAString& aResponseText)
{
  ErrorResult rv;
  DOMString str;
  GetResponseText(str, rv);
  if (NS_WARN_IF(rv.Failed())) {
    return rv.StealNSResult();
  }

  str.ToString(aResponseText);
  return NS_OK;
}

void
XMLHttpRequestMainThread::GetResponseText(DOMString& aResponseText,
                                          ErrorResult& aRv)
{
  XMLHttpRequestStringSnapshot snapshot;
  GetResponseText(snapshot, aRv);
  if (aRv.Failed()) {
    return;
  }

  if (!snapshot.GetAsString(aResponseText)) {
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }
}

void
XMLHttpRequestMainThread::GetResponseText(XMLHttpRequestStringSnapshot& aSnapshot,
                                          ErrorResult& aRv)
{
  aSnapshot.Reset();

  if (mResponseType != XMLHttpRequestResponseType::_empty &&
      mResponseType != XMLHttpRequestResponseType::Text &&
      mResponseType != XMLHttpRequestResponseType::Moz_chunked_text) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSETEXT);
    return;
  }

  if (mResponseType == XMLHttpRequestResponseType::Moz_chunked_text &&
      !mInLoadProgressEvent) {
    aSnapshot.SetVoid();
    return;
  }

  if (mState != State::loading && mState != State::done) {
    return;
  }

  // We only decode text lazily if we're also parsing to a doc.
  // Also, if we've decoded all current data already, then no need to decode
  // more.
  if ((!mResponseXML && !mErrorParsingXML) ||
      mResponseBodyDecodedPos == mResponseBody.Length()) {
    mResponseText.CreateSnapshot(aSnapshot);
    return;
  }

  MatchCharsetAndDecoderToResponseDocument();

  NS_ASSERTION(mResponseBodyDecodedPos < mResponseBody.Length(),
               "Unexpected mResponseBodyDecodedPos");
  aRv = AppendToResponseText(mResponseBody.get() + mResponseBodyDecodedPos,
                             mResponseBody.Length() - mResponseBodyDecodedPos);
  if (aRv.Failed()) {
    return;
  }

  mResponseBodyDecodedPos = mResponseBody.Length();

  if (mState == State::done) {
    // Free memory buffer which we no longer need
    mResponseBody.Truncate();
    mResponseBodyDecodedPos = 0;
  }

  mResponseText.CreateSnapshot(aSnapshot);
}

nsresult
XMLHttpRequestMainThread::CreateResponseParsedJSON(JSContext* aCx)
{
  if (!aCx) {
    return NS_ERROR_FAILURE;
  }

  nsAutoString string;
  if (!mResponseText.GetAsString(string)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // The Unicode converter has already zapped the BOM if there was one
  JS::Rooted<JS::Value> value(aCx);
  if (!JS_ParseJSON(aCx, string.BeginReading(), string.Length(), &value)) {
    return NS_ERROR_FAILURE;
  }

  mResultJSON = value;
  return NS_OK;
}

void
XMLHttpRequestMainThread::CreatePartialBlob(ErrorResult& aRv)
{
  if (mDOMBlob) {
    // Use progress info to determine whether load is complete, but use
    // mDataAvailable to ensure a slice is created based on the uncompressed
    // data count.
    if (mState == State::done) {
      mResponseBlob = mDOMBlob;
    } else {
      mResponseBlob = mDOMBlob->CreateSlice(0, mDataAvailable,
                                            EmptyString(), aRv);
    }
    return;
  }

  // mBlobSet can be null if the request has been canceled
  if (!mBlobSet) {
    return;
  }

  nsAutoCString contentType;
  if (mState == State::done) {
    mChannel->GetContentType(contentType);
  }

  nsTArray<RefPtr<BlobImpl>> subImpls(mBlobSet->GetBlobImpls());
  RefPtr<BlobImpl> blobImpl =
    MultipartBlobImpl::Create(Move(subImpls),
                              NS_ConvertASCIItoUTF16(contentType),
                              aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  mResponseBlob = Blob::Create(GetOwner(), blobImpl);
}

NS_IMETHODIMP XMLHttpRequestMainThread::GetResponseType(nsAString& aResponseType)
{
  MOZ_ASSERT(mResponseType < XMLHttpRequestResponseType::EndGuard_);
  const EnumEntry& entry =
    XMLHttpRequestResponseTypeValues::strings[static_cast<uint32_t>(mResponseType)];
  aResponseType.AssignASCII(entry.value, entry.length);
  return NS_OK;
}

NS_IMETHODIMP XMLHttpRequestMainThread::SetResponseType(const nsAString& aResponseType)
{
  uint32_t i = 0;
  for (const EnumEntry* entry = XMLHttpRequestResponseTypeValues::strings;
       entry->value; ++entry, ++i) {
    if (aResponseType.EqualsASCII(entry->value, entry->length)) {
      ErrorResult rv;
      SetResponseType(static_cast<XMLHttpRequestResponseType>(i), rv);
      return rv.StealNSResult();
    }
  }

  return NS_OK;
}

void
XMLHttpRequestMainThread::SetResponseType(XMLHttpRequestResponseType aResponseType,
                                          ErrorResult& aRv)
{
  if (mState == State::loading || mState == State::done) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_LOADING_OR_DONE);
    return;
  }

  // sync request is not allowed setting responseType in window context
  if (HasOrHasHadOwner() && mState != State::unsent && mFlagSynchronous) {
    LogMessage("ResponseTypeSyncXHRWarning", GetOwner());
    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_XHR_TIMEOUT_AND_RESPONSETYPE_UNSUPPORTED_FOR_SYNC);
    return;
  }

  if (mFlagSynchronous &&
      (aResponseType == XMLHttpRequestResponseType::Moz_chunked_text ||
       aResponseType == XMLHttpRequestResponseType::Moz_chunked_arraybuffer)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_CHUNKED_RESPONSETYPES_UNSUPPORTED_FOR_SYNC);
    return;
  }

  // Set the responseType attribute's value to the given value.
  mResponseType = aResponseType;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetResponse(JSContext *aCx, JS::MutableHandle<JS::Value> aResult)
{
  ErrorResult rv;
  GetResponse(aCx, aResult, rv);
  return rv.StealNSResult();
}

void
XMLHttpRequestMainThread::GetResponse(JSContext* aCx,
                                      JS::MutableHandle<JS::Value> aResponse,
                                      ErrorResult& aRv)
{
  switch (mResponseType) {
  case XMLHttpRequestResponseType::_empty:
  case XMLHttpRequestResponseType::Text:
  case XMLHttpRequestResponseType::Moz_chunked_text:
  {
    DOMString str;
    GetResponseText(str, aRv);
    if (aRv.Failed()) {
      return;
    }
    if (!xpc::StringToJsval(aCx, str, aResponse)) {
      aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    }
    return;
  }

  case XMLHttpRequestResponseType::Arraybuffer:
  case XMLHttpRequestResponseType::Moz_chunked_arraybuffer:
  {
    if (!(mResponseType == XMLHttpRequestResponseType::Arraybuffer &&
          mState == State::done) &&
        !(mResponseType == XMLHttpRequestResponseType::Moz_chunked_arraybuffer &&
          mInLoadProgressEvent)) {
      aResponse.setNull();
      return;
    }

    if (!mResultArrayBuffer) {
      mResultArrayBuffer = mArrayBufferBuilder.getArrayBuffer(aCx);
      if (!mResultArrayBuffer) {
        aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
        return;
      }
    }
    aResponse.setObject(*mResultArrayBuffer);
    return;
  }
  case XMLHttpRequestResponseType::Blob:
  case XMLHttpRequestResponseType::Moz_blob:
  {
    if (mState != State::done) {
      if (mResponseType != XMLHttpRequestResponseType::Moz_blob) {
        aResponse.setNull();
        return;
      }

      if (!mResponseBlob) {
        CreatePartialBlob(aRv);
      }
    }

    if (!mResponseBlob) {
      aResponse.setNull();
      return;
    }

    GetOrCreateDOMReflector(aCx, mResponseBlob, aResponse);
    return;
  }
  case XMLHttpRequestResponseType::Document:
  {
    if (!mResponseXML || mState != State::done) {
      aResponse.setNull();
      return;
    }

    aRv = nsContentUtils::WrapNative(aCx, mResponseXML, aResponse);
    return;
  }
  case XMLHttpRequestResponseType::Json:
  {
    if (mState != State::done) {
      aResponse.setNull();
      return;
    }

    if (mResultJSON.isUndefined()) {
      aRv = CreateResponseParsedJSON(aCx);
      TruncateResponseText();
      if (aRv.Failed()) {
        // Per spec, errors aren't propagated. null is returned instead.
        aRv = NS_OK;
        // It would be nice to log the error to the console. That's hard to
        // do without calling window.onerror as a side effect, though.
        JS_ClearPendingException(aCx);
        mResultJSON.setNull();
      }
    }
    aResponse.set(mResultJSON);
    return;
  }
  default:
    NS_ERROR("Should not happen");
  }

  aResponse.setNull();
}

bool
XMLHttpRequestMainThread::IsCrossSiteCORSRequest() const
{
  if (!mChannel) {
    return false;
  }

  nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
  MOZ_ASSERT(loadInfo);

  return loadInfo->GetTainting() == LoadTainting::CORS;
}

bool
XMLHttpRequestMainThread::IsDeniedCrossSiteCORSRequest()
{
  if (IsCrossSiteCORSRequest()) {
    nsresult rv;
    mChannel->GetStatus(&rv);
    if (NS_FAILED(rv)) {
      return true;
    }
  }
  return false;
}

void
XMLHttpRequestMainThread::GetResponseURL(nsAString& aUrl)
{
  aUrl.Truncate();

  uint16_t readyState = ReadyState();
  if ((readyState == UNSENT || readyState == OPENED) || !mChannel) {
    return;
  }

  // Make sure we don't leak responseURL information from denied cross-site
  // requests.
  if (IsDeniedCrossSiteCORSRequest()) {
    return;
  }

  nsCOMPtr<nsIURI> responseUrl;
  mChannel->GetURI(getter_AddRefs(responseUrl));

  if (!responseUrl) {
    return;
  }

  nsAutoCString temp;
  responseUrl->GetSpecIgnoringRef(temp);
  CopyUTF8toUTF16(temp, aUrl);
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetStatus(uint32_t *aStatus)
{
  ErrorResult rv;
  *aStatus = GetStatus(rv);
  return rv.StealNSResult();
}

uint32_t
XMLHttpRequestMainThread::GetStatus(ErrorResult& aRv)
{
  // Make sure we don't leak status information from denied cross-site
  // requests.
  if (IsDeniedCrossSiteCORSRequest()) {
    return 0;
  }

  uint16_t readyState = ReadyState();
  if (readyState == UNSENT || readyState == OPENED) {
    return 0;
  }

  if (mErrorLoad) {
    // Let's simulate the http protocol for jar/app requests:
    nsCOMPtr<nsIJARChannel> jarChannel = GetCurrentJARChannel();
    if (jarChannel) {
      nsresult status;
      mChannel->GetStatus(&status);

      if (status == NS_ERROR_FILE_NOT_FOUND) {
        return 404; // Not Found
      } else {
        return 500; // Internal Error
      }
    }

    return 0;
  }

  nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel();
  if (!httpChannel) {
    // Pretend like we got a 200 response, since our load was successful
    return 200;
  }

  uint32_t status;
  nsresult rv = httpChannel->GetResponseStatus(&status);
  if (NS_FAILED(rv)) {
    status = 0;
  }

  return status;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetStatusText(nsACString& aOut)
{
  ErrorResult rv;
  GetStatusText(aOut, rv);
  return rv.StealNSResult();
}

void
XMLHttpRequestMainThread::GetStatusText(nsACString& aStatusText,
                                        ErrorResult& aRv)
{
  // Return an empty status text on all error loads.
  aStatusText.Truncate();

  // Make sure we don't leak status information from denied cross-site
  // requests.
  if (IsDeniedCrossSiteCORSRequest()) {
    return;
  }

  // Check the current XHR state to see if it is valid to obtain the statusText
  // value.  This check is to prevent the status text for redirects from being
  // available before all the redirects have been followed and HTTP headers have
  // been received.
  uint16_t readyState = ReadyState();
  if (readyState == UNSENT || readyState == OPENED) {
    return;
  }

  if (mErrorLoad) {
    return;
  }

  nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel();
  if (httpChannel) {
    httpChannel->GetResponseStatusText(aStatusText);
  } else {
    aStatusText.AssignLiteral("OK");
  }
}

void
XMLHttpRequestMainThread::CloseRequest()
{
  mWaitingForOnStopRequest = false;
  if (mChannel) {
    mChannel->Cancel(NS_BINDING_ABORTED);
  }
  if (mTimeoutTimer) {
    mTimeoutTimer->Cancel();
  }
}

void
XMLHttpRequestMainThread::CloseRequestWithError(const ProgressEventType aType)
{
  CloseRequest();

  ResetResponse();

  // If we're in the destructor, don't risk dispatching an event.
  if (mFlagDeleted) {
    mFlagSyncLooping = false;
    return;
  }

  if (mState != State::unsent &&
      !(mState == State::opened && !mFlagSend) &&
      mState != State::done) {
    ChangeState(State::done, true);

    if (!mFlagSyncLooping) {
      if (mUpload && !mUploadComplete) {
        mUploadComplete = true;
        DispatchProgressEvent(mUpload, aType, 0, -1);
      }
      DispatchProgressEvent(this, aType, 0, -1);
    }
  }

  // The ChangeState call above calls onreadystatechange handlers which
  // if they load a new url will cause XMLHttpRequestMainThread::Open to clear
  // the abort state bit. If this occurs we're not uninitialized (bug 361773).
  if (mFlagAborted) {
    ChangeState(State::unsent, false);  // IE seems to do it
  }

  mFlagSyncLooping = false;
}

void
XMLHttpRequestMainThread::RequestErrorSteps(const ProgressEventType aEventType,
                                            const nsresult aOptionalException,
                                            ErrorResult& aRv)
{
  // Step 1
  mState = State::done;

  StopProgressEventTimer();

  // Step 2
  mFlagSend = false;

  // Step 3
  ResetResponse();

  // If we're in the destructor, don't risk dispatching an event.
  if (mFlagDeleted) {
    mFlagSyncLooping = false;
    return;
  }

  // Step 4
  if (mFlagSynchronous && NS_FAILED(aOptionalException)) {
    aRv.Throw(aOptionalException);
    return;
  }

  // Step 5
  FireReadystatechangeEvent();

  // Step 6
  if (mUpload && !mUploadComplete) {

    // Step 6-1
    mUploadComplete = true;

    // Step 6-2
    if (mFlagHadUploadListenersOnSend) {

      // Steps 6-3, 6-4 (loadend is fired for us)
      DispatchProgressEvent(mUpload, aEventType, 0, -1);
    }
  }

  // Steps 7 and 8 (loadend is fired for us)
  DispatchProgressEvent(this, aEventType, 0, -1);
}

void
XMLHttpRequestMainThread::Abort(ErrorResult& aRv)
{
  mFlagAborted = true;

  // Step 1
  CloseRequest();

  // Step 2
  if ((mState == State::opened && mFlagSend) ||
       mState == State::headers_received ||
       mState == State::loading) {
    RequestErrorSteps(ProgressEventType::abort, NS_OK, aRv);
  }

  // Step 3
  if (mState == State::done) {
    ChangeState(State::unsent, false); // no ReadystateChange event
  }

  mFlagSyncLooping = false;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::SlowAbort()
{
  Abort();
  return NS_OK;
}

/*Method that checks if it is safe to expose a header value to the client.
It is used to check what headers are exposed for CORS requests.*/
bool
XMLHttpRequestMainThread::IsSafeHeader(const nsACString& aHeader,
                                       NotNull<nsIHttpChannel*> aHttpChannel) const
{
  // See bug #380418. Hide "Set-Cookie" headers from non-chrome scripts.
  if (!IsSystemXHR() && nsContentUtils::IsForbiddenResponseHeader(aHeader)) {
    NS_WARNING("blocked access to response header");
    return false;
  }
  // if this is not a CORS call all headers are safe
  if (!IsCrossSiteCORSRequest()) {
    return true;
  }
  // Check for dangerous headers
  // Make sure we don't leak header information from denied cross-site
  // requests.
  if (mChannel) {
    nsresult status;
    mChannel->GetStatus(&status);
    if (NS_FAILED(status)) {
      return false;
    }
  }
  const char* kCrossOriginSafeHeaders[] = {
    "cache-control", "content-language", "content-type", "expires",
    "last-modified", "pragma"
  };
  for (uint32_t i = 0; i < ArrayLength(kCrossOriginSafeHeaders); ++i) {
    if (aHeader.LowerCaseEqualsASCII(kCrossOriginSafeHeaders[i])) {
      return true;
    }
  }
  nsAutoCString headerVal;
  // The "Access-Control-Expose-Headers" header contains a comma separated
  // list of method names.
  aHttpChannel->
      GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Expose-Headers"),
                        headerVal);
  nsCCharSeparatedTokenizer exposeTokens(headerVal, ',');
  bool isSafe = false;
  while (exposeTokens.hasMoreTokens()) {
    const nsDependentCSubstring& token = exposeTokens.nextToken();
    if (token.IsEmpty()) {
      continue;
    }
    if (!NS_IsValidHTTPToken(token)) {
      return false;
    }
    if (token.EqualsLiteral("*") && !mFlagACwithCredentials) {
      isSafe = true;
    } else if (aHeader.Equals(token, nsCaseInsensitiveCStringComparator())) {
      isSafe = true;
    }
  }
  return isSafe;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetAllResponseHeaders(nsACString& aOut)
{
  ErrorResult rv;
  GetAllResponseHeaders(aOut, rv);
  return rv.StealNSResult();
}

void
XMLHttpRequestMainThread::GetAllResponseHeaders(nsACString& aResponseHeaders,
                                                ErrorResult& aRv)
{
  aResponseHeaders.Truncate();

  // If the state is UNSENT or OPENED,
  // return the empty string and terminate these steps.
  if (mState == State::unsent || mState == State::opened) {
    return;
  }

  if (mErrorLoad) {
    return;
  }

  if (nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel()) {
    RefPtr<nsHeaderVisitor> visitor =
      new nsHeaderVisitor(*this, WrapNotNull(httpChannel));
    if (NS_SUCCEEDED(httpChannel->VisitResponseHeaders(visitor))) {
      aResponseHeaders = visitor->Headers();
    }
    return;
  }

  if (!mChannel) {
    return;
  }

  // Even non-http channels supply content type.
  nsAutoCString value;
  if (NS_SUCCEEDED(mChannel->GetContentType(value))) {
    aResponseHeaders.AppendLiteral("Content-Type: ");
    aResponseHeaders.Append(value);
    if (NS_SUCCEEDED(mChannel->GetContentCharset(value)) && !value.IsEmpty()) {
      aResponseHeaders.AppendLiteral(";charset=");
      aResponseHeaders.Append(value);
    }
    aResponseHeaders.AppendLiteral("\r\n");
  }

  // Don't provide Content-Length for data URIs
  nsCOMPtr<nsIURI> uri;
  bool isDataURI;
  if (NS_FAILED(mChannel->GetURI(getter_AddRefs(uri))) ||
      NS_FAILED(uri->SchemeIs("data", &isDataURI)) ||
      !isDataURI) {
    int64_t length;
    if (NS_SUCCEEDED(mChannel->GetContentLength(&length))) {
      aResponseHeaders.AppendLiteral("Content-Length: ");
      aResponseHeaders.AppendInt(length);
      aResponseHeaders.AppendLiteral("\r\n");
    }
  }
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetResponseHeader(const nsACString& aHeader,
                                            nsACString& aResult)
{
  ErrorResult rv;
  GetResponseHeader(aHeader, aResult, rv);
  return rv.StealNSResult();
}

void
XMLHttpRequestMainThread::GetResponseHeader(const nsACString& header,
                                            nsACString& _retval, ErrorResult& aRv)
{
  _retval.SetIsVoid(true);

  nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel();

  if (!httpChannel) {
    // If the state is UNSENT or OPENED,
    // return null and terminate these steps.
    if (mState == State::unsent || mState == State::opened) {
      return;
    }

    // Even non-http channels supply content type and content length.
    // Remember we don't leak header information from denied cross-site
    // requests.
    nsresult status;
    if (!mChannel ||
        NS_FAILED(mChannel->GetStatus(&status)) ||
        NS_FAILED(status)) {
      return;
    }

    // Content Type:
    if (header.LowerCaseEqualsASCII("content-type")) {
      if (NS_FAILED(mChannel->GetContentType(_retval))) {
        // Means no content type
        _retval.SetIsVoid(true);
        return;
      }

      nsCString value;
      if (NS_SUCCEEDED(mChannel->GetContentCharset(value)) &&
          !value.IsEmpty()) {
        _retval.AppendLiteral(";charset=");
        _retval.Append(value);
      }
    }

    // Content Length:
    else if (header.LowerCaseEqualsASCII("content-length")) {
      int64_t length;
      if (NS_SUCCEEDED(mChannel->GetContentLength(&length))) {
        _retval.AppendInt(length);
      }
    }

    return;
  }

  // Check for dangerous headers
  if (!IsSafeHeader(header, WrapNotNull(httpChannel))) {
    return;
  }

  aRv = httpChannel->GetResponseHeader(header, _retval);
  if (aRv.ErrorCodeIs(NS_ERROR_NOT_AVAILABLE)) {
    // Means no header
    _retval.SetIsVoid(true);
    aRv.SuppressException();
  }
}

already_AddRefed<nsILoadGroup>
XMLHttpRequestMainThread::GetLoadGroup() const
{
  if (mFlagBackgroundRequest) {
    return nullptr;
  }

  if (mLoadGroup) {
    nsCOMPtr<nsILoadGroup> ref = mLoadGroup;
    return ref.forget();
  }

  nsIDocument* doc = GetDocumentIfCurrent();
  if (doc) {
    return doc->GetDocumentLoadGroup();
  }

  return nullptr;
}

nsresult
XMLHttpRequestMainThread::FireReadystatechangeEvent()
{
  RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
  event->InitEvent(kLiteralString_readystatechange, false, false);
  // We assume anyone who managed to call CreateReadystatechangeEvent is trusted
  event->SetTrusted(true);
  DispatchDOMEvent(nullptr, event, nullptr, nullptr);
  return NS_OK;
}

void
XMLHttpRequestMainThread::DispatchProgressEvent(DOMEventTargetHelper* aTarget,
                                                const ProgressEventType aType,
                                                int64_t aLoaded, int64_t aTotal)
{
  NS_ASSERTION(aTarget, "null target");

  if (NS_FAILED(CheckInnerWindowCorrectness()) ||
      (!AllowUploadProgress() && aTarget == mUpload)) {
    return;
  }

  // If blocked by CORS, zero-out the stats on progress events
  // and never fire "progress" or "load" events at all.
  if (IsDeniedCrossSiteCORSRequest()) {
    if (aType == ProgressEventType::progress ||
        aType == ProgressEventType::load) {
      return;
    }
    aLoaded = 0;
    aTotal = -1;
  }

  if (aType == ProgressEventType::progress) {
    mInLoadProgressEvent = true;
  }

  ProgressEventInit init;
  init.mBubbles = false;
  init.mCancelable = false;
  init.mLengthComputable = aTotal != -1; // XHR spec step 6.1
  init.mLoaded = aLoaded;
  init.mTotal = (aTotal == -1) ? 0 : aTotal;

  const nsAString& typeString = ProgressEventTypeStrings[(uint8_t)aType];
  RefPtr<ProgressEvent> event =
    ProgressEvent::Constructor(aTarget, typeString, init);
  event->SetTrusted(true);

  aTarget->DispatchDOMEvent(nullptr, event, nullptr, nullptr);

  if (aType == ProgressEventType::progress) {
    mInLoadProgressEvent = false;

    // clear chunked responses after every progress event
    if (mResponseType == XMLHttpRequestResponseType::Moz_chunked_text ||
        mResponseType == XMLHttpRequestResponseType::Moz_chunked_arraybuffer) {
      mResponseBody.Truncate();
      TruncateResponseText();
      mResultArrayBuffer = nullptr;
      mArrayBufferBuilder.reset();
    }
  }

  // If we're sending a load, error, timeout or abort event, then
  // also dispatch the subsequent loadend event.
  if (aType == ProgressEventType::load || aType == ProgressEventType::error ||
      aType == ProgressEventType::timeout || aType == ProgressEventType::abort) {
    DispatchProgressEvent(aTarget, ProgressEventType::loadend, aLoaded, aTotal);
  }
}

already_AddRefed<nsIHttpChannel>
XMLHttpRequestMainThread::GetCurrentHttpChannel()
{
  nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel);
  return httpChannel.forget();
}

already_AddRefed<nsIJARChannel>
XMLHttpRequestMainThread::GetCurrentJARChannel()
{
  nsCOMPtr<nsIJARChannel> appChannel = do_QueryInterface(mChannel);
  return appChannel.forget();
}

bool
XMLHttpRequestMainThread::IsSystemXHR() const
{
  return mIsSystem || nsContentUtils::IsSystemPrincipal(mPrincipal);
}
 
bool
XMLHttpRequestMainThread::InUploadPhase() const
{
  // We're in the upload phase while our state is State::opened.
  return mState == State::opened;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::Open(const nsACString& aMethod, const nsACString& aUrl,
                               bool aAsync, const nsAString& aUsername,
                               const nsAString& aPassword, uint8_t optional_argc)
{
  return Open(aMethod, aUrl, optional_argc > 0 ? aAsync : true,
              aUsername, aPassword);
}

// This case is hit when the async parameter is outright omitted, which
// should set it to true (and the username and password to null).
void
XMLHttpRequestMainThread::Open(const nsACString& aMethod, const nsAString& aUrl,
                               ErrorResult& aRv)
{
  Open(aMethod, aUrl, true, NullString(), NullString(), aRv);
}

// This case is hit when the async parameter is specified, even if the
// JS value was "undefined" (which due to legacy reasons should be
// treated as true, which is how it will already be passed in here).
void
XMLHttpRequestMainThread::Open(const nsACString& aMethod,
                               const nsAString& aUrl,
                               bool aAsync,
                               const nsAString& aUsername,
                               const nsAString& aPassword,
                               ErrorResult& aRv)
{
  nsresult rv = Open(aMethod, NS_ConvertUTF16toUTF8(aUrl), aAsync, aUsername, aPassword);
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
  }
}

nsresult
XMLHttpRequestMainThread::Open(const nsACString& aMethod,
                               const nsACString& aUrl,
                               bool aAsync,
                               const nsAString& aUsername,
                               const nsAString& aPassword) {
  // Gecko-specific
  if (!aAsync && !DontWarnAboutSyncXHR() && GetOwner() &&
      GetOwner()->GetExtantDoc()) {
    GetOwner()->GetExtantDoc()->WarnOnceAbout(nsIDocument::eSyncXMLHttpRequest);
  }

  // Step 1
  nsCOMPtr<nsIDocument> responsibleDocument = GetDocumentIfCurrent();
  if (!responsibleDocument) {
    // This could be because we're no longer current or because we're in some
    // non-window context...
    nsresult rv = CheckInnerWindowCorrectness();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT;
    }
  }
  NS_ENSURE_TRUE(mPrincipal, NS_ERROR_NOT_INITIALIZED);

  // Steps 2-4
  nsAutoCString method;
  nsresult rv = FetchUtil::GetValidRequestMethod(aMethod, method);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Steps 5-6
  nsCOMPtr<nsIURI> baseURI;
  if (mBaseURI) {
    baseURI = mBaseURI;
  } else if (responsibleDocument) {
    baseURI = responsibleDocument->GetBaseURI();
  }
  nsCOMPtr<nsIURI> parsedURL;
  rv = NS_NewURI(getter_AddRefs(parsedURL), aUrl, nullptr, baseURI);
  if (NS_FAILED(rv)) {
    if (rv ==  NS_ERROR_MALFORMED_URI) {
      return NS_ERROR_DOM_MALFORMED_URI;
    }
    return rv;
  }
  if (NS_WARN_IF(NS_FAILED(CheckInnerWindowCorrectness()))) {
    return NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT;
  }

  // Step 7
  // This is already handled by the other Open() method, which passes
  // username and password in as NullStrings.

  // Step 8
  nsAutoCString host;
  parsedURL->GetHost(host);
  if (!host.IsEmpty()) {
    nsAutoCString userpass;
    if (!aUsername.IsVoid()) {
      CopyUTF16toUTF8(aUsername, userpass);
    }
    userpass.AppendLiteral(":");
    if (!aPassword.IsVoid()) {
      AppendUTF16toUTF8(aPassword, userpass);
    }
    parsedURL->SetUserPass(userpass);
  }

  // Step 9
  if (!aAsync && HasOrHasHadOwner() && (mTimeoutMilliseconds ||
       mResponseType != XMLHttpRequestResponseType::_empty)) {
    if (mTimeoutMilliseconds) {
      LogMessage("TimeoutSyncXHRWarning", GetOwner());
    }
    if (mResponseType != XMLHttpRequestResponseType::_empty) {
      LogMessage("ResponseTypeSyncXHRWarning", GetOwner());
    }
    return NS_ERROR_DOM_INVALID_ACCESS_XHR_TIMEOUT_AND_RESPONSETYPE_UNSUPPORTED_FOR_SYNC;
  }

  // Step 10
  CloseRequest();

  // Step 11
  // timeouts are handled without a flag
  mFlagSend = false;
  mRequestMethod.Assign(method);
  mRequestURL = parsedURL;
  mFlagSynchronous = !aAsync;
  mAuthorRequestHeaders.Clear();
  ResetResponse();

  // Gecko-specific
  mFlagHadUploadListenersOnSend = false;
  mFlagAborted = false;
  mFlagTimedOut = false;

  // Per spec we should only create the channel on send(), but we have internal
  // code that relies on the channel being created now, and that code is not
  // always IsSystemXHR(). However, we're not supposed to throw channel-creation
  // errors during open(), so we silently ignore those here.
  CreateChannel();

  // Step 12
  if (mState != State::opened) {
    mState = State::opened;
    FireReadystatechangeEvent();
  }

  return NS_OK;
}

void
XMLHttpRequestMainThread::SetOriginAttributes(const OriginAttributesDictionary& aAttrs)
{
  MOZ_ASSERT((mState == State::opened) && !mFlagSend);

  GenericOriginAttributes attrs(aAttrs);
  NeckoOriginAttributes neckoAttrs;
  neckoAttrs.SetFromGenericAttributes(attrs);

  nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
  MOZ_ASSERT(loadInfo);
  loadInfo->SetOriginAttributes(neckoAttrs);
}

void
XMLHttpRequestMainThread::PopulateNetworkInterfaceId()
{
  if (mNetworkInterfaceId.IsEmpty()) {
    return;
  }
  nsCOMPtr<nsIHttpChannelInternal> channel(do_QueryInterface(mChannel));
  if (!channel) {
    return;
  }
  channel->SetNetworkInterfaceId(mNetworkInterfaceId);
}

/*
 * "Copy" from a stream.
 */
nsresult
XMLHttpRequestMainThread::StreamReaderFunc(nsIInputStream* in,
                                           void* closure,
                                           const char* fromRawSegment,
                                           uint32_t toOffset,
                                           uint32_t count,
                                           uint32_t *writeCount)
{
  XMLHttpRequestMainThread* xmlHttpRequest = static_cast<XMLHttpRequestMainThread*>(closure);
  if (!xmlHttpRequest || !writeCount) {
    NS_WARNING("XMLHttpRequest cannot read from stream: no closure or writeCount");
    return NS_ERROR_FAILURE;
  }

  nsresult rv = NS_OK;

  if (xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Blob) {
    if (!xmlHttpRequest->mDOMBlob) {
      xmlHttpRequest->MaybeCreateBlobStorage();
      rv = xmlHttpRequest->mBlobStorage->Append(fromRawSegment, count);
    }
  } else if (xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Moz_blob) {
    if (!xmlHttpRequest->mDOMBlob) {
      if (!xmlHttpRequest->mBlobSet) {
        xmlHttpRequest->mBlobSet = new BlobSet();
      }
      rv = xmlHttpRequest->mBlobSet->AppendVoidPtr(fromRawSegment, count);
    }
    // Clear the cache so that the blob size is updated.
    xmlHttpRequest->mResponseBlob = nullptr;
  } else if ((xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Arraybuffer &&
              !xmlHttpRequest->mIsMappedArrayBuffer) ||
             xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Moz_chunked_arraybuffer) {
    // get the initial capacity to something reasonable to avoid a bunch of reallocs right
    // at the start
    if (xmlHttpRequest->mArrayBufferBuilder.capacity() == 0)
      xmlHttpRequest->mArrayBufferBuilder.setCapacity(std::max(count, XML_HTTP_REQUEST_ARRAYBUFFER_MIN_SIZE));

    xmlHttpRequest->mArrayBufferBuilder.append(reinterpret_cast<const uint8_t*>(fromRawSegment), count,
                                               XML_HTTP_REQUEST_ARRAYBUFFER_MAX_GROWTH);
  } else if (xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::_empty &&
             xmlHttpRequest->mResponseXML) {
    // Copy for our own use
    if (!xmlHttpRequest->mResponseBody.Append(fromRawSegment, count, fallible)) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
  } else if (xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::_empty ||
             xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Text ||
             xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Json ||
             xmlHttpRequest->mResponseType == XMLHttpRequestResponseType::Moz_chunked_text) {
    NS_ASSERTION(!xmlHttpRequest->mResponseXML,
                 "We shouldn't be parsing a doc here");
    xmlHttpRequest->AppendToResponseText(fromRawSegment, count);
  }

  if (xmlHttpRequest->mFlagParseBody) {
    // Give the same data to the parser.

    // We need to wrap the data in a new lightweight stream and pass that
    // to the parser, because calling ReadSegments() recursively on the same
    // stream is not supported.
    nsCOMPtr<nsIInputStream> copyStream;
    rv = NS_NewByteInputStream(getter_AddRefs(copyStream), fromRawSegment, count);

    if (NS_SUCCEEDED(rv) && xmlHttpRequest->mXMLParserStreamListener) {
      NS_ASSERTION(copyStream, "NS_NewByteInputStream lied");
      nsresult parsingResult = xmlHttpRequest->mXMLParserStreamListener
                                  ->OnDataAvailable(xmlHttpRequest->mChannel,
                                                    xmlHttpRequest->mContext,
                                                    copyStream, toOffset, count);

      // No use to continue parsing if we failed here, but we
      // should still finish reading the stream
      if (NS_FAILED(parsingResult)) {
        xmlHttpRequest->mFlagParseBody = false;
      }
    }
  }

  if (NS_SUCCEEDED(rv)) {
    *writeCount = count;
  } else {
    *writeCount = 0;
  }

  return rv;
}

bool XMLHttpRequestMainThread::CreateDOMBlob(nsIRequest *request)
{
  nsCOMPtr<nsIFile> file;
  nsCOMPtr<nsIFileChannel> fc = do_QueryInterface(request);
  if (fc) {
    fc->GetFile(getter_AddRefs(file));
  }

  if (!file)
    return false;

  nsAutoCString contentType;
  mChannel->GetContentType(contentType);

  mDOMBlob = File::CreateFromFile(GetOwner(), file, EmptyString(),
                                  NS_ConvertASCIItoUTF16(contentType));

  mBlobStorage = nullptr;
  mBlobSet = nullptr;
  NS_ASSERTION(mResponseBody.IsEmpty(), "mResponseBody should be empty");
  return true;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::OnDataAvailable(nsIRequest *request,
                                          nsISupports *ctxt,
                                          nsIInputStream *inStr,
                                          uint64_t sourceOffset,
                                          uint32_t count)
{
  NS_ENSURE_ARG_POINTER(inStr);

  MOZ_ASSERT(mContext.get() == ctxt,"start context different from OnDataAvailable context");

  mProgressSinceLastProgressEvent = true;
  XMLHttpRequestBinding::ClearCachedResponseTextValue(this);

  bool cancelable = false;
  if ((mResponseType == XMLHttpRequestResponseType::Blob ||
       mResponseType == XMLHttpRequestResponseType::Moz_blob) && !mDOMBlob) {
    cancelable = CreateDOMBlob(request);
    // The nsIStreamListener contract mandates us
    // to read from the stream before returning.
  }

  uint32_t totalRead;
  nsresult rv = inStr->ReadSegments(XMLHttpRequestMainThread::StreamReaderFunc,
                                    (void*)this, count, &totalRead);
  NS_ENSURE_SUCCESS(rv, rv);

  if (cancelable) {
    // We don't have to read from the local file for the blob response
    ErrorResult error;
    mDataAvailable = mDOMBlob->GetSize(error);
    if (NS_WARN_IF(error.Failed())) {
      return error.StealNSResult();
    }

    ChangeState(State::loading);
    return request->Cancel(NS_OK);
  }

  mDataAvailable += totalRead;

  // Fire the first progress event/loading state change
  if (mState != State::loading) {
    ChangeState(State::loading);
    if (!mFlagSynchronous) {
      DispatchProgressEvent(this, ProgressEventType::progress,
                            mLoadTransferred, mLoadTotal);
    }
    mProgressSinceLastProgressEvent = false;
  }

  if (!mFlagSynchronous && !mProgressTimerIsActive) {
    StartProgressEventTimer();
  }

  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::OnStartRequest(nsIRequest *request, nsISupports *ctxt)
{
  PROFILER_LABEL("XMLHttpRequestMainThread", "OnStartRequest",
    js::ProfileEntry::Category::NETWORK);

  nsresult rv = NS_OK;
  if (!mFirstStartRequestSeen && mRequestObserver) {
    mFirstStartRequestSeen = true;
    mRequestObserver->OnStartRequest(request, ctxt);
  }

  if (request != mChannel) {
    // Can this still happen?
    return NS_OK;
  }

  // Don't do anything if we have been aborted
  if (mState == State::unsent) {
    return NS_OK;
  }

  /* Apparently, Abort() should set State::unsent.  See bug 361773.
     XHR2 spec says this is correct. */
  if (mFlagAborted) {
    NS_ERROR("Ugh, still getting data on an aborted XMLHttpRequest!");

    return NS_ERROR_UNEXPECTED;
  }

  // Don't do anything if we have timed out.
  if (mFlagTimedOut) {
    return NS_OK;
  }

  nsCOMPtr<nsIChannel> channel(do_QueryInterface(request));
  NS_ENSURE_TRUE(channel, NS_ERROR_UNEXPECTED);

  nsresult status;
  request->GetStatus(&status);
  mErrorLoad = mErrorLoad || NS_FAILED(status);

  // Upload phase is now over. If we were uploading anything,
  // stop the timer and fire any final progress events.
  if (mUpload && !mUploadComplete && !mErrorLoad && !mFlagSynchronous) {
    StopProgressEventTimer();

    mUploadTransferred = mUploadTotal;

    if (mProgressSinceLastProgressEvent) {
      DispatchProgressEvent(mUpload, ProgressEventType::progress,
                            mUploadTransferred, mUploadTotal);
      mProgressSinceLastProgressEvent = false;
    }

    mUploadComplete = true;
    DispatchProgressEvent(mUpload, ProgressEventType::load,
                          mUploadTotal, mUploadTotal);
  }

  mContext = ctxt;
  mFlagParseBody = true;
  ChangeState(State::headers_received);

  ResetResponse();

  if (!mOverrideMimeType.IsEmpty()) {
    channel->SetContentType(NS_ConvertUTF16toUTF8(mOverrideMimeType));
  }

  DetectCharset();

  // Set up arraybuffer
  if (mResponseType == XMLHttpRequestResponseType::Arraybuffer &&
      NS_SUCCEEDED(status)) {
    if (mIsMappedArrayBuffer) {
      nsCOMPtr<nsIJARChannel> jarChannel = do_QueryInterface(channel);
      if (jarChannel) {
        nsCOMPtr<nsIURI> uri;
        rv = channel->GetURI(getter_AddRefs(uri));
        if (NS_SUCCEEDED(rv)) {
          nsAutoCString file;
          nsAutoCString scheme;
          uri->GetScheme(scheme);
          if (scheme.LowerCaseEqualsLiteral("jar")) {
            nsCOMPtr<nsIJARURI> jarURI = do_QueryInterface(uri);
            if (jarURI) {
              jarURI->GetJAREntry(file);
            }
          }
          nsCOMPtr<nsIFile> jarFile;
          jarChannel->GetJarFile(getter_AddRefs(jarFile));
          if (!jarFile) {
            mIsMappedArrayBuffer = false;
          } else {
            rv = mArrayBufferBuilder.mapToFileInPackage(file, jarFile);
            if (NS_WARN_IF(NS_FAILED(rv))) {
              mIsMappedArrayBuffer = false;
            } else {
              channel->SetContentType(NS_LITERAL_CSTRING("application/mem-mapped"));
            }
          }
        }
      }
    }
    // If memory mapping failed, mIsMappedArrayBuffer would be set to false,
    // and we want it fallback to the malloc way.
    if (!mIsMappedArrayBuffer) {
      int64_t contentLength;
      rv = channel->GetContentLength(&contentLength);
      if (NS_SUCCEEDED(rv) &&
          contentLength > 0 &&
          contentLength < XML_HTTP_REQUEST_MAX_CONTENT_LENGTH_PREALLOCATE) {
        mArrayBufferBuilder.setCapacity(static_cast<int32_t>(contentLength));
      }
    }
  }

  // Set up responseXML
  bool parseBody = mResponseType == XMLHttpRequestResponseType::_empty ||
                   mResponseType == XMLHttpRequestResponseType::Document;
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mChannel));
  if (parseBody && httpChannel) {
    nsAutoCString method;
    httpChannel->GetRequestMethod(method);
    parseBody = !method.EqualsLiteral("HEAD");
  }

  mIsHtml = false;
  mWarnAboutSyncHtml = false;
  if (parseBody && NS_SUCCEEDED(status)) {
    // We can gain a huge performance win by not even trying to
    // parse non-XML data. This also protects us from the situation
    // where we have an XML document and sink, but HTML (or other)
    // parser, which can produce unreliable results.
    nsAutoCString type;
    channel->GetContentType(type);

    if ((mResponseType == XMLHttpRequestResponseType::Document) &&
        type.EqualsLiteral("text/html")) {
      // HTML parsing is only supported for responseType == "document" to
      // avoid running the parser and, worse, populating responseXML for
      // legacy users of XHR who use responseType == "" for retrieving the
      // responseText of text/html resources. This legacy case is so common
      // that it's not useful to emit a warning about it.
      if (mFlagSynchronous) {
        // We don't make cool new features available in the bad synchronous
        // mode. The synchronous mode is for legacy only.
        mWarnAboutSyncHtml = true;
        mFlagParseBody = false;
      } else {
        mIsHtml = true;
      }
    } else if (!(type.EqualsLiteral("text/xml") ||
                 type.EqualsLiteral("application/xml") ||
                 type.RFind("+xml", true, -1, 4) != kNotFound)) {
      // Follow https://xhr.spec.whatwg.org/
      // If final MIME type is not null, text/html, text/xml, application/xml,
      // or does not end in +xml, return null.
      mFlagParseBody = false;
    }
  } else {
    // The request failed, so we shouldn't be parsing anyway
    mFlagParseBody = false;
  }

  if (mFlagParseBody) {
    nsCOMPtr<nsIURI> baseURI, docURI;
    rv = mChannel->GetURI(getter_AddRefs(docURI));
    NS_ENSURE_SUCCESS(rv, rv);
    baseURI = docURI;

    nsCOMPtr<nsIDocument> doc = GetDocumentIfCurrent();
    nsCOMPtr<nsIURI> chromeXHRDocURI, chromeXHRDocBaseURI;
    if (doc) {
      chromeXHRDocURI = doc->GetDocumentURI();
      chromeXHRDocBaseURI = doc->GetBaseURI();
    } else {
      // If we're no longer current, just kill the load, though it really should
      // have been killed already.
      if (NS_WARN_IF(NS_FAILED(CheckInnerWindowCorrectness()))) {
        return NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT;
      }
    }

    // Create an empty document from it.
    const nsAString& emptyStr = EmptyString();
    nsCOMPtr<nsIDOMDocument> responseDoc;
    nsIGlobalObject* global = DOMEventTargetHelper::GetParentObject();

    nsCOMPtr<nsIPrincipal> requestingPrincipal;
    rv = nsContentUtils::GetSecurityManager()->
       GetChannelResultPrincipal(channel, getter_AddRefs(requestingPrincipal));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = NS_NewDOMDocument(getter_AddRefs(responseDoc),
                           emptyStr, emptyStr, nullptr, docURI,
                           baseURI, requestingPrincipal, true, global,
                           mIsHtml ? DocumentFlavorHTML :
                                     DocumentFlavorLegacyGuess);
    NS_ENSURE_SUCCESS(rv, rv);
    mResponseXML = do_QueryInterface(responseDoc);
    mResponseXML->SetChromeXHRDocURI(chromeXHRDocURI);
    mResponseXML->SetChromeXHRDocBaseURI(chromeXHRDocBaseURI);

    if (nsContentUtils::IsSystemPrincipal(mPrincipal)) {
      mResponseXML->ForceEnableXULXBL();
    }

    nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
    MOZ_ASSERT(loadInfo);
    bool isCrossSite = loadInfo->GetTainting() != LoadTainting::Basic;

    if (isCrossSite) {
      nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(mResponseXML);
      if (htmlDoc) {
        htmlDoc->DisableCookieAccess();
      }
    }

    nsCOMPtr<nsIStreamListener> listener;
    nsCOMPtr<nsILoadGroup> loadGroup;
    channel->GetLoadGroup(getter_AddRefs(loadGroup));

    // suppress <parsererror> nodes on XML document parse failure, but only
    // for non-privileged code (including Web Extensions). See bug 289714.
    if (!IsSystemXHR()) {
      mResponseXML->SetSuppressParserErrorElement(true);
    }

    rv = mResponseXML->StartDocumentLoad(kLoadAsData, channel, loadGroup,
                                         nullptr, getter_AddRefs(listener),
                                         !isCrossSite);
    NS_ENSURE_SUCCESS(rv, rv);

    // the spec requires the response document.referrer to be the empty string
    mResponseXML->SetReferrer(NS_LITERAL_CSTRING(""));

    mXMLParserStreamListener = listener;
    rv = mXMLParserStreamListener->OnStartRequest(request, ctxt);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Download phase beginning; start the progress event timer if necessary.
  if (NS_SUCCEEDED(rv) && HasListenersFor(nsGkAtoms::onprogress)) {
    StartProgressEventTimer();
  }

  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::OnStopRequest(nsIRequest *request, nsISupports *ctxt, nsresult status)
{
  PROFILER_LABEL("XMLHttpRequestMainThread", "OnStopRequest",
    js::ProfileEntry::Category::NETWORK);

  if (request != mChannel) {
    // Can this still happen?
    return NS_OK;
  }

  mWaitingForOnStopRequest = false;

  if (mRequestObserver) {
    NS_ASSERTION(mFirstStartRequestSeen, "Inconsistent state!");
    mFirstStartRequestSeen = false;
    mRequestObserver->OnStopRequest(request, ctxt, status);
  }

  // suppress parsing failure messages to console for status 204/304 (see bug 884693).
  if (mResponseXML) {
    uint32_t responseStatus;
    if (NS_SUCCEEDED(GetStatus(&responseStatus)) &&
        (responseStatus == 204 || responseStatus == 304)) {
      mResponseXML->SetSuppressParserErrorConsoleMessages(true);
    }
  }

  // make sure to notify the listener if we were aborted
  // XXX in fact, why don't we do the cleanup below in this case??
  // State::unsent is for abort calls.  See OnStartRequest above.
  if (mState == State::unsent || mFlagTimedOut) {
    if (mXMLParserStreamListener)
      (void) mXMLParserStreamListener->OnStopRequest(request, ctxt, status);
    return NS_OK;
  }

  // Is this good enough here?
  if (mXMLParserStreamListener && mFlagParseBody) {
    mXMLParserStreamListener->OnStopRequest(request, ctxt, status);
  }

  mXMLParserStreamListener = nullptr;
  mContext = nullptr;

  bool waitingForBlobCreation = false;

  if (NS_SUCCEEDED(status) &&
      (mResponseType == XMLHttpRequestResponseType::Blob ||
       mResponseType == XMLHttpRequestResponseType::Moz_blob)) {
    ErrorResult rv;
    if (!mDOMBlob) {
      CreateDOMBlob(request);
    }
    if (mDOMBlob) {
      mResponseBlob = mDOMBlob;
      mDOMBlob = nullptr;
    } else {
      // Smaller files may be written in cache map instead of separate files.
      // Also, no-store response cannot be written in persistent cache.
      nsAutoCString contentType;
      mChannel->GetContentType(contentType);

      if (mResponseType == XMLHttpRequestResponseType::Blob) {
        // mBlobStorage can be null if the channel is non-file non-cacheable
        // and if the response length is zero.
        MaybeCreateBlobStorage();
        mBlobStorage->GetBlobWhenReady(GetOwner(), contentType, this);
        waitingForBlobCreation = true;
      } else {
        // mBlobSet can be null if the channel is non-file non-cacheable
        // and if the response length is zero.
        if (!mBlobSet) {
          mBlobSet = new BlobSet();
        }

        nsTArray<RefPtr<BlobImpl>> subImpls(mBlobSet->GetBlobImpls());
        RefPtr<BlobImpl> blobImpl =
          MultipartBlobImpl::Create(Move(subImpls),
                                    NS_ConvertASCIItoUTF16(contentType),
                                    rv);
        mBlobSet = nullptr;

        if (NS_WARN_IF(rv.Failed())) {
          return rv.StealNSResult();
        }

        mResponseBlob = Blob::Create(GetOwner(), blobImpl);
      }
    }

    NS_ASSERTION(mResponseBody.IsEmpty(), "mResponseBody should be empty");
    NS_ASSERTION(mResponseText.IsEmpty(), "mResponseText should be empty");
  } else if (NS_SUCCEEDED(status) &&
             ((mResponseType == XMLHttpRequestResponseType::Arraybuffer &&
               !mIsMappedArrayBuffer) ||
              mResponseType == XMLHttpRequestResponseType::Moz_chunked_arraybuffer)) {
    // set the capacity down to the actual length, to realloc back
    // down to the actual size
    if (!mArrayBufferBuilder.setCapacity(mArrayBufferBuilder.length())) {
      // this should never happen!
      status = NS_ERROR_UNEXPECTED;
    }
  }

  nsCOMPtr<nsIChannel> channel(do_QueryInterface(request));
  NS_ENSURE_TRUE(channel, NS_ERROR_UNEXPECTED);

  channel->SetNotificationCallbacks(nullptr);
  mNotificationCallbacks = nullptr;
  mChannelEventSink = nullptr;
  mProgressEventSink = nullptr;

  mFlagSyncLooping = false;

  // update our charset and decoder to match mResponseXML,
  // before it is possibly nulled out
  MatchCharsetAndDecoderToResponseDocument();

  if (NS_FAILED(status)) {
    // This can happen if the server is unreachable. Other possible
    // reasons are that the user leaves the page or hits the ESC key.

    mErrorLoad = true;
    mResponseXML = nullptr;
  }

  // If we're uninitialized at this point, we encountered an error
  // earlier and listeners have already been notified. Also we do
  // not want to do this if we already completed.
  if (mState == State::unsent || mState == State::done) {
    return NS_OK;
  }

  if (!mResponseXML) {
    mFlagParseBody = false;

    //We postpone the 'done' until the creation of the Blob is completed.
    if (!waitingForBlobCreation) {
      ChangeStateToDone();
    }

    return NS_OK;
  }

  if (mIsHtml) {
    NS_ASSERTION(!mFlagSyncLooping,
      "We weren't supposed to support HTML parsing with XHR!");
    nsCOMPtr<EventTarget> eventTarget = do_QueryInterface(mResponseXML);
    EventListenerManager* manager =
      eventTarget->GetOrCreateListenerManager();
    manager->AddEventListenerByType(new nsXHRParseEndListener(this),
                                    kLiteralString_DOMContentLoaded,
                                    TrustedEventsAtSystemGroupBubble());
    return NS_OK;
  } else {
    mFlagParseBody = false;
  }

  // We might have been sent non-XML data. If that was the case,
  // we should null out the document member. The idea in this
  // check here is that if there is no document element it is not
  // an XML document. We might need a fancier check...
  if (!mResponseXML->GetRootElement()) {
    mErrorParsingXML = true;
    mResponseXML = nullptr;
  }
  ChangeStateToDone();
  return NS_OK;
}

void
XMLHttpRequestMainThread::OnBodyParseEnd()
{
  mFlagParseBody = false;
  ChangeStateToDone();
}

void
XMLHttpRequestMainThread::MatchCharsetAndDecoderToResponseDocument()
{
  if (mResponseXML && mResponseCharset != mResponseXML->GetDocumentCharacterSet()) {
    mResponseCharset = mResponseXML->GetDocumentCharacterSet();
    TruncateResponseText();
    mResponseBodyDecodedPos = 0;
    mDecoder = EncodingUtils::DecoderForEncoding(mResponseCharset);
  }
}

void
XMLHttpRequestMainThread::ChangeStateToDone()
{
  StopProgressEventTimer();

  MOZ_ASSERT(!mFlagParseBody,
             "ChangeStateToDone() called before async HTML parsing is done.");

  mFlagSend = false;

  if (mTimeoutTimer) {
    mTimeoutTimer->Cancel();
  }

  // Per spec, fire the last download progress event, if any,
  // before readystatechange=4/done. (Note that 0-sized responses
  // will have not sent a progress event yet, so one must be sent here).
  if (!mFlagSynchronous &&
      (!mLoadTransferred || mProgressSinceLastProgressEvent)) {
    DispatchProgressEvent(this, ProgressEventType::progress,
                          mLoadTransferred, mLoadTotal);
    mProgressSinceLastProgressEvent = false;
  }

  // Per spec, fire readystatechange=4/done before final error events.
  ChangeState(State::done, true);

  // Per spec, if we failed in the upload phase, fire a final error
  // and loadend events for the upload after readystatechange=4/done.
  if (!mFlagSynchronous && mUpload && !mUploadComplete) {
    DispatchProgressEvent(mUpload, ProgressEventType::error, 0, -1);
  }

  // Per spec, fire download's load/error and loadend events after
  // readystatechange=4/done (and of course all upload events).
  DispatchProgressEvent(this,
                        mErrorLoad ? ProgressEventType::error :
                                     ProgressEventType::load,
                        mErrorLoad ? 0 : mLoadTransferred,
                        mErrorLoad ? -1 : mLoadTotal);

  if (mErrorLoad) {
    // By nulling out channel here we make it so that Send() can test
    // for that and throw. Also calling the various status
    // methods/members will not throw.
    // This matches what IE does.
    mChannel = nullptr;
  }
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<nsIDocument>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  nsCOMPtr<nsIDOMDocument> domdoc(do_QueryInterface(mBody));
  NS_ENSURE_STATE(domdoc);
  aCharset.AssignLiteral("UTF-8");

  nsresult rv;
  nsCOMPtr<nsIStorageStream> storStream;
  rv = NS_NewStorageStream(4096, UINT32_MAX, getter_AddRefs(storStream));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIOutputStream> output;
  rv = storStream->GetOutputStream(0, getter_AddRefs(output));
  NS_ENSURE_SUCCESS(rv, rv);

  if (mBody->IsHTMLDocument()) {
    aContentType.AssignLiteral("text/html");

    nsString serialized;
    if (!nsContentUtils::SerializeNodeToMarkup(mBody, true, serialized)) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    nsAutoCString utf8Serialized;
    if (!AppendUTF16toUTF8(serialized, utf8Serialized, fallible)) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    uint32_t written;
    rv = output->Write(utf8Serialized.get(), utf8Serialized.Length(), &written);
    NS_ENSURE_SUCCESS(rv, rv);

    MOZ_ASSERT(written == utf8Serialized.Length());
  } else {
    aContentType.AssignLiteral("application/xml");

    nsCOMPtr<nsIDOMSerializer> serializer =
      do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Make sure to use the encoding we'll send
    rv = serializer->SerializeToStream(domdoc, output, aCharset);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  output->Close();

  uint32_t length;
  rv = storStream->GetLength(&length);
  NS_ENSURE_SUCCESS(rv, rv);
  *aContentLength = length;

  rv = storStream->NewInputStream(0, aResult);
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<const nsAString>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  aContentType.AssignLiteral("text/plain");
  aCharset.AssignLiteral("UTF-8");

  nsAutoCString converted;
  if (!AppendUTF16toUTF8(*mBody, converted, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  *aContentLength = converted.Length();
  nsresult rv = NS_NewCStringInputStream(aResult, converted);
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<nsIInputStream>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  aContentType.AssignLiteral("text/plain");
  aCharset.Truncate();

  nsresult rv = mBody->Available(aContentLength);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIInputStream> stream(mBody);
  stream.forget(aResult);
  return NS_OK;
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<Blob>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  return mBody->GetSendInfo(aResult, aContentLength, aContentType, aCharset);
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<FormData>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  return mBody->GetSendInfo(aResult, aContentLength, aContentType, aCharset);
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<URLSearchParams>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  return mBody->GetSendInfo(aResult, aContentLength, aContentType, aCharset);
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<nsIXHRSendable>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  return mBody->GetSendInfo(aResult, aContentLength, aContentType, aCharset);
}

static nsresult
GetBufferDataAsStream(const uint8_t* aData, uint32_t aDataLength,
                      nsIInputStream** aResult, uint64_t* aContentLength,
                      nsACString& aContentType, nsACString& aCharset)
{
  aContentType.SetIsVoid(true);
  aCharset.Truncate();

  *aContentLength = aDataLength;
  const char* data = reinterpret_cast<const char*>(aData);

  nsCOMPtr<nsIInputStream> stream;
  nsresult rv = NS_NewByteInputStream(getter_AddRefs(stream), data, aDataLength,
                                      NS_ASSIGNMENT_COPY);
  NS_ENSURE_SUCCESS(rv, rv);

  stream.forget(aResult);

  return NS_OK;
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<const ArrayBuffer>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  mBody->ComputeLengthAndData();
  return GetBufferDataAsStream(mBody->Data(), mBody->Length(),
                               aResult, aContentLength, aContentType, aCharset);
}

template<> nsresult
XMLHttpRequestMainThread::RequestBody<const ArrayBufferView>::GetAsStream(
   nsIInputStream** aResult, uint64_t* aContentLength,
   nsACString& aContentType, nsACString& aCharset) const
{
  mBody->ComputeLengthAndData();
  return GetBufferDataAsStream(mBody->Data(), mBody->Length(),
                               aResult, aContentLength, aContentType, aCharset);
}


nsresult
XMLHttpRequestMainThread::CreateChannel()
{
  // When we are called from JS we can find the load group for the page,
  // and add ourselves to it. This way any pending requests
  // will be automatically aborted if the user leaves the page.
  nsCOMPtr<nsILoadGroup> loadGroup = GetLoadGroup();

  nsSecurityFlags secFlags;
  nsLoadFlags loadFlags = nsIRequest::LOAD_BACKGROUND;
  if (nsContentUtils::IsSystemPrincipal(mPrincipal)) {
    // When chrome is loading we want to make sure to sandbox any potential
    // result document. We also want to allow cross-origin loads.
    secFlags = nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL |
               nsILoadInfo::SEC_SANDBOXED;
  } else if (IsSystemXHR()) {
    // For pages that have appropriate permissions, we want to still allow
    // cross-origin loads, but make sure that the any potential result
    // documents get the same principal as the loader.
    secFlags = nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS |
               nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
    loadFlags |= nsIChannel::LOAD_BYPASS_SERVICE_WORKER;
  } else {
    // Otherwise use CORS. Again, make sure that potential result documents
    // use the same principal as the loader.
    secFlags = nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS |
               nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
  }

  if (mIsAnon) {
    secFlags |= nsILoadInfo::SEC_COOKIES_OMIT;
  }

  // Use the responsibleDocument if we have it, except for dedicated workers
  // where it will be the parent document, which is not the one we want to use.
  nsresult rv;
  nsCOMPtr<nsIDocument> responsibleDocument = GetDocumentIfCurrent();
  if (responsibleDocument && responsibleDocument->NodePrincipal() == mPrincipal) {
    rv = NS_NewChannel(getter_AddRefs(mChannel),
                       mRequestURL,
                       responsibleDocument,
                       secFlags,
                       nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST,
                       loadGroup,
                       nullptr,   // aCallbacks
                       loadFlags);
  } else {
    // Otherwise use the principal.
    rv = NS_NewChannel(getter_AddRefs(mChannel),
                       mRequestURL,
                       mPrincipal,
                       secFlags,
                       nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST,
                       loadGroup,
                       nullptr,   // aCallbacks
                       loadFlags);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mChannel));
  if (httpChannel) {
    rv = httpChannel->SetRequestMethod(mRequestMethod);
    NS_ENSURE_SUCCESS(rv, rv);

    // Set the initiator type
    nsCOMPtr<nsITimedChannel> timedChannel(do_QueryInterface(httpChannel));
    if (timedChannel) {
      timedChannel->SetInitiatorType(NS_LITERAL_STRING("xmlhttprequest"));
    }
  }

  // Using the provided principal as the triggeringPrincipal is fine, since we
  // want to be able to access any of the origins that the principal has access
  // to during the security checks, but we don't want a document to inherit an
  // expanded principal, so in that case we need to select the principal in the
  // expanded principal's whitelist that can load our URL as principalToInherit.
  nsCOMPtr<nsIPrincipal> resultingDocumentPrincipal(mPrincipal);
  nsCOMPtr<nsIExpandedPrincipal> ep = do_QueryInterface(mPrincipal);
  if (ep) {
    nsTArray<nsCOMPtr<nsIPrincipal>>* whitelist = nullptr;
    ep->GetWhiteList(&whitelist);
    if (!whitelist) {
      return NS_ERROR_FAILURE;
    }
    MOZ_ASSERT(!(secFlags & nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS));
    bool dataInherits = (secFlags &
      (nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS |
       nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS)) != 0;
    for (const auto& principal : *whitelist) {
      if (NS_SUCCEEDED(principal->CheckMayLoad(mRequestURL, false, dataInherits))) {
        resultingDocumentPrincipal = principal;
        break;
      }
    }
  }

  nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
  rv = loadInfo->SetPrincipalToInherit(resultingDocumentPrincipal);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult
XMLHttpRequestMainThread::InitiateFetch(nsIInputStream* aUploadStream,
                                        int64_t aUploadLength,
                                        nsACString& aUploadContentType)
{
  nsresult rv;

  // nsIRequest::LOAD_BACKGROUND prevents throbber from becoming active, which
  // in turn keeps STOP button from becoming active.  If the consumer passed in
  // a progress event handler we must load with nsIRequest::LOAD_NORMAL or
  // necko won't generate any progress notifications.
  if (HasListenersFor(nsGkAtoms::onprogress) ||
      (mUpload && mUpload->HasListenersFor(nsGkAtoms::onprogress))) {
    nsLoadFlags loadFlags;
    mChannel->GetLoadFlags(&loadFlags);
    loadFlags &= ~nsIRequest::LOAD_BACKGROUND;
    loadFlags |= nsIRequest::LOAD_NORMAL;
    mChannel->SetLoadFlags(loadFlags);
  }

  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mChannel));
  if (httpChannel) {
    // If the user hasn't overridden the Accept header, set it to */* per spec.
    if (!mAuthorRequestHeaders.Has("accept")) {
      mAuthorRequestHeaders.Set("accept", NS_LITERAL_CSTRING("*/*"));
    }

    mAuthorRequestHeaders.ApplyToChannel(httpChannel);

    if (!IsSystemXHR()) {
      nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
      nsCOMPtr<nsIDocument> doc = owner ? owner->GetExtantDoc() : nullptr;
      nsContentUtils::SetFetchReferrerURIWithPolicy(mPrincipal, doc,
                                                    httpChannel,
                                                    mozilla::net::RP_Default);
    }

    // Some extensions override the http protocol handler and provide their own
    // implementation. The channels returned from that implementation don't
    // always seem to implement the nsIUploadChannel2 interface, presumably
    // because it's a new interface. Eventually we should remove this and simply
    // require that http channels implement the new interface (see bug 529041).
    nsCOMPtr<nsIUploadChannel2> uploadChannel2 = do_QueryInterface(httpChannel);
    if (!uploadChannel2) {
      nsCOMPtr<nsIConsoleService> consoleService =
        do_GetService(NS_CONSOLESERVICE_CONTRACTID);
      if (consoleService) {
        consoleService->LogStringMessage(NS_LITERAL_STRING(
          "Http channel implementation doesn't support nsIUploadChannel2. "
          "An extension has supplied a non-functional http protocol handler. "
          "This will break behavior and in future releases not work at all."
        ).get());
      }
    }

    if (aUploadStream) {
      // If necessary, wrap the stream in a buffered stream so as to guarantee
      // support for our upload when calling ExplicitSetUploadStream.
      nsCOMPtr<nsIInputStream> bufferedStream;
      if (!NS_InputStreamIsBuffered(aUploadStream)) {
        rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedStream),
                                       aUploadStream, 4096);
        NS_ENSURE_SUCCESS(rv, rv);

        aUploadStream = bufferedStream;
      }

      // We want to use a newer version of the upload channel that won't
      // ignore the necessary headers for an empty Content-Type.
      nsCOMPtr<nsIUploadChannel2> uploadChannel2(do_QueryInterface(httpChannel));
      // This assertion will fire if buggy extensions are installed
      NS_ASSERTION(uploadChannel2, "http must support nsIUploadChannel2");
      if (uploadChannel2) {
          uploadChannel2->ExplicitSetUploadStream(aUploadStream,
                                                  aUploadContentType,
                                                  mUploadTotal, mRequestMethod,
                                                  false);
      } else {
        // The http channel doesn't support the new nsIUploadChannel2.
        // Emulate it as best we can using nsIUploadChannel.
        if (aUploadContentType.IsEmpty()) {
          aUploadContentType.AssignLiteral("application/octet-stream");
        }
        nsCOMPtr<nsIUploadChannel> uploadChannel =
          do_QueryInterface(httpChannel);
        uploadChannel->SetUploadStream(aUploadStream, aUploadContentType,
                                       mUploadTotal);
        // Reset the method to its original value
        httpChannel->SetRequestMethod(mRequestMethod);
      }
    }
  }

  // Due to the chrome-only XHR.channel API, we need a hacky way to set the
  // SEC_COOKIES_INCLUDE *after* the channel has been has been created, since
  // .withCredentials can be called after open() is called.
  // Not doing this for privileged system XHRs since those don't use CORS.
  if (!IsSystemXHR() && !mIsAnon && mFlagACwithCredentials) {
    nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
    static_cast<net::LoadInfo*>(loadInfo.get())->SetIncludeCookiesSecFlag();
  }

  // Blocking gets are common enough out of XHR that we should mark
  // the channel slow by default for pipeline purposes
  AddLoadFlags(mChannel, nsIRequest::INHIBIT_PIPELINE);

  // We never let XHR be blocked by head CSS/JS loads to avoid potential
  // deadlock where server generation of CSS/JS requires an XHR signal.
  nsCOMPtr<nsIClassOfService> cos(do_QueryInterface(mChannel));
  if (cos) {
    cos->AddClassFlags(nsIClassOfService::Unblocked);
  }

  // Disable Necko-internal response timeouts.
  nsCOMPtr<nsIHttpChannelInternal>
    internalHttpChannel(do_QueryInterface(mChannel));
  if (internalHttpChannel) {
    internalHttpChannel->SetResponseTimeoutEnabled(false);
  }

  if (!mIsAnon) {
    AddLoadFlags(mChannel, nsIChannel::LOAD_EXPLICIT_CREDENTIALS);
  }

  // Bypass the network cache in cases where it makes no sense:
  // POST responses are always unique, and we provide no API that would
  // allow our consumers to specify a "cache key" to access old POST
  // responses, so they are not worth caching.
  if (mRequestMethod.EqualsLiteral("POST")) {
    AddLoadFlags(mChannel,
                 nsICachingChannel::LOAD_BYPASS_LOCAL_CACHE |
                 nsIRequest::INHIBIT_CACHING);
  } else {
    // When we are sync loading, we need to bypass the local cache when it would
    // otherwise block us waiting for exclusive access to the cache.  If we don't
    // do this, then we could dead lock in some cases (see bug 309424).
    //
    // Also don't block on the cache entry on async if it is busy - favoring parallelism
    // over cache hit rate for xhr. This does not disable the cache everywhere -
    // only in cases where more than one channel for the same URI is accessed
    // simultanously.
    AddLoadFlags(mChannel, nsICachingChannel::LOAD_BYPASS_LOCAL_CACHE_IF_BUSY);
  }

  // Since we expect XML data, set the type hint accordingly
  // if the channel doesn't know any content type.
  // This means that we always try to parse local files as XML
  // ignoring return value, as this is not critical
  nsAutoCString contentType;
  if (NS_FAILED(mChannel->GetContentType(contentType)) ||
      contentType.IsEmpty() ||
      contentType.Equals(UNKNOWN_CONTENT_TYPE)) {
    mChannel->SetContentType(NS_LITERAL_CSTRING("application/xml"));
  }

  // Set up the preflight if needed
  if (!IsSystemXHR()) {
    nsTArray<nsCString> CORSUnsafeHeaders;
    mAuthorRequestHeaders.GetCORSUnsafeHeaders(CORSUnsafeHeaders);
    nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
    loadInfo->SetCorsPreflightInfo(CORSUnsafeHeaders,
                                   mFlagHadUploadListenersOnSend);
  }

  // Hook us up to listen to redirects and the like. Only do this very late
  // since this creates a cycle between the channel and us. This cycle has
  // to be manually broken if anything below fails.
  mChannel->GetNotificationCallbacks(getter_AddRefs(mNotificationCallbacks));
  mChannel->SetNotificationCallbacks(this);

  if (internalHttpChannel) {
    internalHttpChannel->SetBlockAuthPrompt(ShouldBlockAuthPrompt());
  }

  // Because of bug 682305, we can't let listener be the XHR object itself
  // because JS wouldn't be able to use it. So create a listener around 'this'.
  // Make sure to hold a strong reference so that we don't leak the wrapper.
  nsCOMPtr<nsIStreamListener> listener = new net::nsStreamListenerWrapper(this);

  // Start reading from the channel
  rv = mChannel->AsyncOpen2(listener);
  listener = nullptr;
  if (NS_WARN_IF(NS_FAILED(rv))) {
    // Drop our ref to the channel to avoid cycles. Also drop channel's
    // ref to us to be extra safe.
    mChannel->SetNotificationCallbacks(mNotificationCallbacks);
    mChannel = nullptr;

    mErrorLoad = true;

    // Per spec, we throw on sync errors, but not async.
    if (mFlagSynchronous) {
      return NS_ERROR_DOM_NETWORK_ERR;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::Send(nsIVariant* aVariant)
{
  if (!aVariant) {
    return SendInternal(nullptr);
  }

  uint16_t dataType;
  nsresult rv = aVariant->GetDataType(&dataType);
  NS_ENSURE_SUCCESS(rv, rv);

  if (dataType == nsIDataType::VTYPE_INTERFACE ||
      dataType == nsIDataType::VTYPE_INTERFACE_IS) {
    nsCOMPtr<nsISupports> supports;
    nsID *iid;
    rv = aVariant->GetAsInterface(&iid, getter_AddRefs(supports));
    NS_ENSURE_SUCCESS(rv, rv);

    free(iid);

    // document?
    nsCOMPtr<nsIDocument> doc = do_QueryInterface(supports);
    if (doc) {
      RequestBody<nsIDocument> body(doc);
      return SendInternal(&body);
    }

    // nsISupportsString?
    nsCOMPtr<nsISupportsString> wstr = do_QueryInterface(supports);
    if (wstr) {
      nsAutoString string;
      wstr->GetData(string);
      RequestBody<const nsAString> body(&string);
      return SendInternal(&body);
    }

    // nsIInputStream?
    nsCOMPtr<nsIInputStream> stream = do_QueryInterface(supports);
    if (stream) {
      RequestBody<nsIInputStream> body(stream);
      return SendInternal(&body);
    }

    // nsIXHRSendable?
    nsCOMPtr<nsIXHRSendable> sendable = do_QueryInterface(supports);
    if (sendable) {
      RequestBody<nsIXHRSendable> body(sendable);
      return SendInternal(&body);
    }

    // ArrayBuffer?
    JS::RootingContext* rootingCx = RootingCx();
    JS::Rooted<JS::Value> realVal(rootingCx);

    nsresult rv = aVariant->GetAsJSVal(&realVal);
    if (NS_SUCCEEDED(rv) && !realVal.isPrimitive()) {
      JS::Rooted<JSObject*> obj(rootingCx, realVal.toObjectOrNull());
      RootedTypedArray<ArrayBuffer> buf(rootingCx);
      if (buf.Init(obj)) {
        RequestBody<const ArrayBuffer> body(&buf);
        return SendInternal(&body);
      }
    }
  } else if (dataType == nsIDataType::VTYPE_VOID ||
           dataType == nsIDataType::VTYPE_EMPTY) {
    return SendInternal(nullptr);
  }

  char16_t* data = nullptr;
  uint32_t len = 0;
  rv = aVariant->GetAsWStringWithSize(&len, &data);
  NS_ENSURE_SUCCESS(rv, rv);

  nsString string;
  string.Adopt(data, len);

  RequestBody<const nsAString> body(&string);
  return SendInternal(&body);
}

nsresult
XMLHttpRequestMainThread::SendInternal(const RequestBodyBase* aBody)
{
  NS_ENSURE_TRUE(mPrincipal, NS_ERROR_NOT_INITIALIZED);

  // Step 1
  if (mState != State::opened) {
    return NS_ERROR_DOM_INVALID_STATE_XHR_MUST_BE_OPENED;
  }

  // Step 2
  if (mFlagSend) {
    return NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_SENDING;
  }

  nsresult rv = CheckInnerWindowCorrectness();
  if (NS_FAILED(rv)) {
    return NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT;
  }

  // If open() failed to create the channel, then throw a network error
  // as per spec. We really should create the channel here in send(), but
  // we have internal code relying on the channel being created in open().
  if (!mChannel) {
    return NS_ERROR_DOM_NETWORK_ERR;
  }

  // non-GET requests aren't allowed for blob.
  if (IsBlobURI(mRequestURL) && !mRequestMethod.EqualsLiteral("GET")) {
    return NS_ERROR_DOM_NETWORK_ERR;
  }

  PopulateNetworkInterfaceId();

  // XXX We should probably send a warning to the JS console
  //     if there are no event listeners set and we are doing
  //     an asynchronous call.

  mUploadTransferred = 0;
  mUploadTotal = 0;
  // By default we don't have any upload, so mark upload complete.
  mUploadComplete = true;
  mErrorLoad = false;
  mLoadTotal = -1;
  nsCOMPtr<nsIInputStream> uploadStream;
  nsAutoCString uploadContentType;
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mChannel));
  if (aBody && httpChannel &&
      !mRequestMethod.EqualsLiteral("GET") &&
      !mRequestMethod.EqualsLiteral("HEAD")) {

    nsAutoCString charset;
    nsAutoCString defaultContentType;
    uint64_t size_u64;
    rv = aBody->GetAsStream(getter_AddRefs(uploadStream),
                            &size_u64, defaultContentType, charset);
    NS_ENSURE_SUCCESS(rv, rv);

    // make sure it fits within js MAX_SAFE_INTEGER
    mUploadTotal =
      net::InScriptableRange(size_u64) ? static_cast<int64_t>(size_u64) : -1;

    if (uploadStream) {
      // If author set no Content-Type, use the default from GetAsStream().
      mAuthorRequestHeaders.Get("content-type", uploadContentType);
      if (uploadContentType.IsVoid()) {
        uploadContentType = defaultContentType;

        if (!charset.IsEmpty()) {
          // If we are providing the default content type, then we also need to
          // provide a charset declaration.
          uploadContentType.Append(NS_LITERAL_CSTRING(";charset="));
          uploadContentType.Append(charset);
        }
      }

      // We don't want to set a charset for streams.
      if (!charset.IsEmpty()) {
        // Replace all case-insensitive matches of the charset in the
        // content-type with the correct case.
        RequestHeaders::CharsetIterator iter(uploadContentType);
        const nsCaseInsensitiveCStringComparator cmp;
        while (iter.Next()) {
          if (!iter.Equals(charset, cmp)) {
            iter.Replace(charset);
          }
        }
      }

      mUploadComplete = false;
    }
  }

  ResetResponse();

  // Check if we should enable cross-origin upload listeners.
  if (mUpload && mUpload->HasListeners()) {
    mFlagHadUploadListenersOnSend = true;
  }

  mIsMappedArrayBuffer = false;
  if (mResponseType == XMLHttpRequestResponseType::Arraybuffer &&
      Preferences::GetBool("dom.mapped_arraybuffer.enabled", true)) {
    nsCOMPtr<nsIURI> uri;
    nsAutoCString scheme;

    rv = mChannel->GetURI(getter_AddRefs(uri));
    if (NS_SUCCEEDED(rv)) {
      uri->GetScheme(scheme);
      if (scheme.LowerCaseEqualsLiteral("jar")) {
        mIsMappedArrayBuffer = true;
      }
    }
  }

  rv = InitiateFetch(uploadStream, mUploadTotal, uploadContentType);
  NS_ENSURE_SUCCESS(rv, rv);

  // Start our timeout
  mRequestSentTime = PR_Now();
  StartTimeoutTimer();

  mWaitingForOnStopRequest = true;

  // Step 8
  mFlagSend = true;

  // If we're synchronous, spin an event loop here and wait
  if (mFlagSynchronous) {
    mFlagSyncLooping = true;

    nsCOMPtr<nsIDocument> suspendedDoc;
    nsCOMPtr<nsIRunnable> resumeTimeoutRunnable;
    if (GetOwner()) {
      if (nsCOMPtr<nsPIDOMWindowOuter> topWindow = GetOwner()->GetOuterWindow()->GetTop()) {
        if (nsCOMPtr<nsPIDOMWindowInner> topInner = topWindow->GetCurrentInnerWindow()) {
          suspendedDoc = topWindow->GetExtantDoc();
          if (suspendedDoc) {
            suspendedDoc->SuppressEventHandling(nsIDocument::eEvents);
          }
          topInner->Suspend();
          resumeTimeoutRunnable = new nsResumeTimeoutsEvent(topInner);
        }
      }
    }

    StopProgressEventTimer();

    SyncTimeoutType syncTimeoutType = MaybeStartSyncTimeoutTimer();
    if (syncTimeoutType == eErrorOrExpired) {
      Abort();
      rv = NS_ERROR_DOM_NETWORK_ERR;
    }

    if (NS_SUCCEEDED(rv)) {
      nsAutoSyncOperation sync(suspendedDoc);
      nsIThread *thread = NS_GetCurrentThread();
      while (mFlagSyncLooping) {
        if (!NS_ProcessNextEvent(thread)) {
          rv = NS_ERROR_UNEXPECTED;
          break;
        }
      }

      // Time expired... We should throw.
      if (syncTimeoutType == eTimerStarted && !mSyncTimeoutTimer) {
        rv = NS_ERROR_DOM_NETWORK_ERR;
      }

      CancelSyncTimeoutTimer();
    }

    if (suspendedDoc) {
      suspendedDoc->UnsuppressEventHandlingAndFireEvents(nsIDocument::eEvents,
                                                         true);
    }

    if (resumeTimeoutRunnable) {
      NS_DispatchToCurrentThread(resumeTimeoutRunnable);
    }
  } else {
    // Now that we've successfully opened the channel, we can change state.  Note
    // that this needs to come after the AsyncOpen() and rv check, because this
    // can run script that would try to restart this request, and that could end
    // up doing our AsyncOpen on a null channel if the reentered AsyncOpen fails.
    StopProgressEventTimer();

    // Upload phase beginning; start the progress event timer if necessary.
    if (mUpload && mUpload->HasListenersFor(nsGkAtoms::onprogress)) {
      StartProgressEventTimer();
    }
    // Dispatch loadstart events
    DispatchProgressEvent(this, ProgressEventType::loadstart, 0, -1);
    if (mUpload && !mUploadComplete) {
      DispatchProgressEvent(mUpload, ProgressEventType::loadstart,
                            0, mUploadTotal);
    }
  }

  if (!mChannel) {
    // Per spec, silently fail on async request failures; throw for sync.
    if (mFlagSynchronous) {
      return NS_ERROR_DOM_NETWORK_ERR;
    } else {
      // Defer the actual sending of async events just in case listeners
      // are attached after the send() method is called.
      NS_DispatchToCurrentThread(
        NewRunnableMethod<ProgressEventType>(this,
          &XMLHttpRequestMainThread::CloseRequestWithError,
          ProgressEventType::error));
      return NS_OK;
    }
  }

  return rv;
}

// http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader
NS_IMETHODIMP
XMLHttpRequestMainThread::SetRequestHeader(const nsACString& aName,
                                           const nsACString& aValue)
{
  // Step 1
  if (mState != State::opened) {
    return NS_ERROR_DOM_INVALID_STATE_XHR_MUST_BE_OPENED;
  }

  // Step 2
  if (mFlagSend) {
    return NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_SENDING;
  }

  // Step 3
  nsAutoCString value(aValue);
  static const char kHTTPWhitespace[] = "\n\t\r ";
  value.Trim(kHTTPWhitespace);

  // Step 4
  if (!NS_IsValidHTTPToken(aName) || !NS_IsReasonableHTTPHeaderValue(value)) {
    return NS_ERROR_DOM_INVALID_HEADER_NAME;
  }

  // Step 5
  bool isPrivilegedCaller = IsSystemXHR();
  bool isForbiddenHeader = nsContentUtils::IsForbiddenRequestHeader(aName);
  if (!isPrivilegedCaller && isForbiddenHeader) {
    NS_ConvertUTF8toUTF16 name(aName);
    const char16_t* params[] = { name.get() };
    LogMessage("ForbiddenHeaderWarning", GetOwner(), params, ArrayLength(params));
    return NS_OK;
  }

  // Step 6.1
  // Skipping for now, as normalizing the case of header names may not be
  // web-compatible. See bug 1285036.

  // Step 6.2-6.3
  // Gecko-specific: invalid headers can be set by privileged
  //                 callers, but will not merge.
  if (isPrivilegedCaller && isForbiddenHeader) {
    mAuthorRequestHeaders.Set(aName, value);
  } else {
    mAuthorRequestHeaders.MergeOrSet(aName, value);
  }

  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetTimeout(uint32_t *aTimeout)
{
  *aTimeout = Timeout();
  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::SetTimeout(uint32_t aTimeout)
{
  ErrorResult rv;
  SetTimeout(aTimeout, rv);
  return rv.StealNSResult();
}

void
XMLHttpRequestMainThread::SetTimeout(uint32_t aTimeout, ErrorResult& aRv)
{
  if (mFlagSynchronous && mState != State::unsent && HasOrHasHadOwner()) {
    /* Timeout is not supported for synchronous requests with an owning window,
       per XHR2 spec. */
    LogMessage("TimeoutSyncXHRWarning", GetOwner());
    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_XHR_TIMEOUT_AND_RESPONSETYPE_UNSUPPORTED_FOR_SYNC);
    return;
  }

  mTimeoutMilliseconds = aTimeout;
  if (mRequestSentTime) {
    StartTimeoutTimer();
  }
}

void
XMLHttpRequestMainThread::StartTimeoutTimer()
{
  MOZ_ASSERT(mRequestSentTime,
             "StartTimeoutTimer mustn't be called before the request was sent!");
  if (mState == State::done) {
    // do nothing!
    return;
  }

  if (mTimeoutTimer) {
    mTimeoutTimer->Cancel();
  }

  if (!mTimeoutMilliseconds) {
    return;
  }

  if (!mTimeoutTimer) {
    mTimeoutTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
  }
  uint32_t elapsed =
    (uint32_t)((PR_Now() - mRequestSentTime) / PR_USEC_PER_MSEC);
  mTimeoutTimer->InitWithCallback(
    this,
    mTimeoutMilliseconds > elapsed ? mTimeoutMilliseconds - elapsed : 0,
    nsITimer::TYPE_ONE_SHOT
  );
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetReadyState(uint16_t *aState)
{
  *aState = ReadyState();
  return NS_OK;
}

uint16_t
XMLHttpRequestMainThread::ReadyState() const
{
  // Translate some of our internal states for external consumers
  switch(mState) {
    case State::unsent:
      return UNSENT;
    case State::opened:
      return OPENED;
    case State::headers_received:
      return HEADERS_RECEIVED;
    case State::loading:
      return LOADING;
    case State::done:
      return DONE;
    default:
      MOZ_CRASH("Unknown state");
  }
  return 0;
}

void XMLHttpRequestMainThread::OverrideMimeType(const nsAString& aMimeType, ErrorResult& aRv)
{
  if (mState == State::loading || mState == State::done) {
    ResetResponse();
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_LOADING_OR_DONE);
    return;
  }

  mOverrideMimeType = aMimeType;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::SlowOverrideMimeType(const nsAString& aMimeType)
{
  ErrorResult aRv;
  OverrideMimeType(aMimeType, aRv);
  return aRv.StealNSResult();
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetMozBackgroundRequest(bool *_retval)
{
  *_retval = MozBackgroundRequest();
  return NS_OK;
}

bool
XMLHttpRequestMainThread::MozBackgroundRequest() const
{
  return mFlagBackgroundRequest;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::SetMozBackgroundRequest(bool aMozBackgroundRequest)
{
  if (!IsSystemXHR()) {
    return NS_ERROR_DOM_SECURITY_ERR;
  }

  if (mState != State::unsent) {
    // Can't change this while we're in the middle of something.
    return NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_SENDING;
  }

  mFlagBackgroundRequest = aMozBackgroundRequest;

  return NS_OK;
}

void
XMLHttpRequestMainThread::SetMozBackgroundRequest(bool aMozBackgroundRequest,
                                                  ErrorResult& aRv)
{
  // No errors for this webIDL method on main-thread.
  SetMozBackgroundRequest(aMozBackgroundRequest);
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetWithCredentials(bool *_retval)
{
  *_retval = WithCredentials();
  return NS_OK;
}

bool
XMLHttpRequestMainThread::WithCredentials() const
{
  return mFlagACwithCredentials;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::SetWithCredentials(bool aWithCredentials)
{
  ErrorResult rv;
  SetWithCredentials(aWithCredentials, rv);
  return rv.StealNSResult();
}

void
XMLHttpRequestMainThread::SetWithCredentials(bool aWithCredentials, ErrorResult& aRv)
{
  // Return error if we're already processing a request.  Note that we can't use
  // ReadyState() here, because it can't differentiate between "opened" and
  // "sent", so we use mState directly.

  if ((mState != State::unsent && mState != State::opened) ||
      mFlagSend || mIsAnon) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_SENDING);
    return;
  }

  mFlagACwithCredentials = aWithCredentials;
}

nsresult
XMLHttpRequestMainThread::ChangeState(State aState, bool aBroadcast)
{
  mState = aState;
  nsresult rv = NS_OK;

  if (aState != State::headers_received && aState != State::loading) {
    StopProgressEventTimer();
  }


  if (aBroadcast && (!mFlagSynchronous ||
                     aState == State::opened ||
                     aState == State::done)) {
    rv = FireReadystatechangeEvent();
  }

  return rv;
}

/////////////////////////////////////////////////////
// nsIChannelEventSink methods:
//
NS_IMETHODIMP
XMLHttpRequestMainThread::AsyncOnChannelRedirect(nsIChannel *aOldChannel,
                                                 nsIChannel *aNewChannel,
                                                 uint32_t    aFlags,
                                                 nsIAsyncVerifyRedirectCallback *callback)
{
  NS_PRECONDITION(aNewChannel, "Redirect without a channel?");

  // Prepare to receive callback
  mRedirectCallback = callback;
  mNewRedirectChannel = aNewChannel;

  if (mChannelEventSink) {
    nsCOMPtr<nsIAsyncVerifyRedirectCallback> fwd =
      EnsureXPCOMifier();

    nsresult rv = mChannelEventSink->AsyncOnChannelRedirect(aOldChannel,
                                                            aNewChannel,
                                                            aFlags, fwd);
    if (NS_FAILED(rv)) {
        mRedirectCallback = nullptr;
        mNewRedirectChannel = nullptr;
    }
    return rv;
  }
  OnRedirectVerifyCallback(NS_OK);
  return NS_OK;
}

nsresult
XMLHttpRequestMainThread::OnRedirectVerifyCallback(nsresult result)
{
  NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
  NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");

  if (NS_SUCCEEDED(result)) {
    mChannel = mNewRedirectChannel;

    nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mChannel));
    if (httpChannel) {
      // Ensure all original headers are duplicated for the new channel (bug #553888)
      mAuthorRequestHeaders.ApplyToChannel(httpChannel);
    }
  } else {
    mErrorLoad = true;
  }

  mNewRedirectChannel = nullptr;

  mRedirectCallback->OnRedirectVerifyCallback(result);
  mRedirectCallback = nullptr;

  // It's important that we return success here. If we return the result code
  // that we were passed, JavaScript callers who cancel the redirect will wind
  // up throwing an exception in the process.
  return NS_OK;
}

/////////////////////////////////////////////////////
// nsIProgressEventSink methods:
//

NS_IMETHODIMP
XMLHttpRequestMainThread::OnProgress(nsIRequest *aRequest, nsISupports *aContext, int64_t aProgress, int64_t aProgressMax)
{
  // When uploading, OnProgress reports also headers in aProgress and aProgressMax.
  // So, try to remove the headers, if possible.
  bool lengthComputable = (aProgressMax != -1);
  if (InUploadPhase()) {
    int64_t loaded = aProgress;
    if (lengthComputable) {
      int64_t headerSize = aProgressMax - mUploadTotal;
      loaded -= headerSize;
    }
    mUploadTransferred = loaded;
    mProgressSinceLastProgressEvent = true;

    if (!mFlagSynchronous && !mProgressTimerIsActive) {
      StartProgressEventTimer();
    }
  } else {
    mLoadTotal = aProgressMax;
    mLoadTransferred = aProgress;
    // OnDataAvailable() handles mProgressSinceLastProgressEvent
    // for the download phase.
  }

  if (mProgressEventSink) {
    mProgressEventSink->OnProgress(aRequest, aContext, aProgress,
                                   aProgressMax);
  }

  return NS_OK;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::OnStatus(nsIRequest *aRequest, nsISupports *aContext, nsresult aStatus, const char16_t *aStatusArg)
{
  if (mProgressEventSink) {
    mProgressEventSink->OnStatus(aRequest, aContext, aStatus, aStatusArg);
  }

  return NS_OK;
}

bool
XMLHttpRequestMainThread::AllowUploadProgress()
{
  return !IsCrossSiteCORSRequest() ||
         mFlagHadUploadListenersOnSend;
}

/////////////////////////////////////////////////////
// nsIInterfaceRequestor methods:
//
NS_IMETHODIMP
XMLHttpRequestMainThread::GetInterface(const nsIID & aIID, void **aResult)
{
  nsresult rv;

  // Make sure to return ourselves for the channel event sink interface and
  // progress event sink interface, no matter what.  We can forward these to
  // mNotificationCallbacks if it wants to get notifications for them.  But we
  // need to see these notifications for proper functioning.
  if (aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
    mChannelEventSink = do_GetInterface(mNotificationCallbacks);
    *aResult = static_cast<nsIChannelEventSink*>(EnsureXPCOMifier().take());
    return NS_OK;
  } else if (aIID.Equals(NS_GET_IID(nsIProgressEventSink))) {
    mProgressEventSink = do_GetInterface(mNotificationCallbacks);
    *aResult = static_cast<nsIProgressEventSink*>(EnsureXPCOMifier().take());
    return NS_OK;
  }

  // Now give mNotificationCallbacks (if non-null) a chance to return the
  // desired interface.
  if (mNotificationCallbacks) {
    rv = mNotificationCallbacks->GetInterface(aIID, aResult);
    if (NS_SUCCEEDED(rv)) {
      NS_ASSERTION(*aResult, "Lying nsIInterfaceRequestor implementation!");
      return rv;
    }
  }

  if (mFlagBackgroundRequest) {
    nsCOMPtr<nsIInterfaceRequestor> badCertHandler(do_CreateInstance(NS_BADCERTHANDLER_CONTRACTID, &rv));

    // Ignore failure to get component, we may not have all its dependencies
    // available
    if (NS_SUCCEEDED(rv)) {
      rv = badCertHandler->GetInterface(aIID, aResult);
      if (NS_SUCCEEDED(rv))
        return rv;
    }
  }
  else if (aIID.Equals(NS_GET_IID(nsIAuthPrompt)) ||
           aIID.Equals(NS_GET_IID(nsIAuthPrompt2))) {
    nsCOMPtr<nsIPromptFactory> wwatch =
      do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Get the an auth prompter for our window so that the parenting
    // of the dialogs works as it should when using tabs.

    nsCOMPtr<nsPIDOMWindowOuter> window;
    if (GetOwner()) {
      window = GetOwner()->GetOuterWindow();
    }

    return wwatch->GetPrompt(window, aIID,
                             reinterpret_cast<void**>(aResult));
  }
  // Now check for the various XHR non-DOM interfaces, except
  // nsIProgressEventSink and nsIChannelEventSink which we already
  // handled above.
  else if (aIID.Equals(NS_GET_IID(nsIStreamListener))) {
    *aResult = static_cast<nsIStreamListener*>(EnsureXPCOMifier().take());
    return NS_OK;
  }
  else if (aIID.Equals(NS_GET_IID(nsIRequestObserver))) {
    *aResult = static_cast<nsIRequestObserver*>(EnsureXPCOMifier().take());
    return NS_OK;
  }
  else if (aIID.Equals(NS_GET_IID(nsITimerCallback))) {
    *aResult = static_cast<nsITimerCallback*>(EnsureXPCOMifier().take());
    return NS_OK;
  }

  return QueryInterface(aIID, aResult);
}

void
XMLHttpRequestMainThread::GetInterface(JSContext* aCx, nsIJSID* aIID,
                                       JS::MutableHandle<JS::Value> aRetval,
                                       ErrorResult& aRv)
{
  dom::GetInterface(aCx, this, aIID, aRetval, aRv);
}

XMLHttpRequestUpload*
XMLHttpRequestMainThread::GetUpload(ErrorResult& aRv)
{
  if (!mUpload) {
    mUpload = new XMLHttpRequestUpload(this);
  }
  return mUpload;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetUpload(nsIXMLHttpRequestUpload** aUpload)
{
  ErrorResult rv;
  RefPtr<XMLHttpRequestUpload> upload = GetUpload(rv);
  upload.forget(aUpload);
  return rv.StealNSResult();
}

bool
XMLHttpRequestMainThread::MozAnon() const
{
  return mIsAnon;
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetMozAnon(bool* aAnon)
{
  *aAnon = MozAnon();
  return NS_OK;
}

bool
XMLHttpRequestMainThread::MozSystem() const
{
  return IsSystemXHR();
}

NS_IMETHODIMP
XMLHttpRequestMainThread::GetMozSystem(bool* aSystem)
{
  *aSystem = MozSystem();
  return NS_OK;
}

void
XMLHttpRequestMainThread::HandleTimeoutCallback()
{
  if (mState == State::done) {
    NS_NOTREACHED("XMLHttpRequestMainThread::HandleTimeoutCallback with completed request");
    // do nothing!
    return;
  }

  mFlagTimedOut = true;
  CloseRequestWithError(ProgressEventType::timeout);
}

NS_IMETHODIMP
XMLHttpRequestMainThread::Notify(nsITimer* aTimer)
{
  if (mProgressNotifier == aTimer) {
    HandleProgressTimerCallback();
    return NS_OK;
  }

  if (mTimeoutTimer == aTimer) {
    HandleTimeoutCallback();
    return NS_OK;
  }

  if (mSyncTimeoutTimer == aTimer) {
    HandleSyncTimeoutTimer();
    return NS_OK;
  }

  // Just in case some JS user wants to QI to nsITimerCallback and play with us...
  NS_WARNING("Unexpected timer!");
  return NS_ERROR_INVALID_POINTER;
}

void
XMLHttpRequestMainThread::HandleProgressTimerCallback()
{
  // Don't fire the progress event if mLoadTotal is 0, see XHR spec step 6.1
  if (!mLoadTotal && mLoadTransferred) {
    return;
  }

  mProgressTimerIsActive = false;

  if (!mProgressSinceLastProgressEvent || mErrorLoad) {
    return;
  }

  if (InUploadPhase()) {
    if (mUpload && !mUploadComplete) {
      DispatchProgressEvent(mUpload, ProgressEventType::progress,
                            mUploadTransferred, mUploadTotal);
    }
  } else {
    FireReadystatechangeEvent();
    DispatchProgressEvent(this, ProgressEventType::progress,
                          mLoadTransferred, mLoadTotal);
  }

  mProgressSinceLastProgressEvent = false;

  StartProgressEventTimer();
}

void
XMLHttpRequestMainThread::StopProgressEventTimer()
{
  if (mProgressNotifier) {
    mProgressTimerIsActive = false;
    mProgressNotifier->Cancel();
  }
}

void
XMLHttpRequestMainThread::StartProgressEventTimer()
{
  if (!mProgressNotifier) {
    mProgressNotifier = do_CreateInstance(NS_TIMER_CONTRACTID);
  }
  if (mProgressNotifier) {
    mProgressTimerIsActive = true;
    mProgressNotifier->Cancel();
    mProgressNotifier->InitWithCallback(this, NS_PROGRESS_EVENT_INTERVAL,
                                        nsITimer::TYPE_ONE_SHOT);
  }
}

XMLHttpRequestMainThread::SyncTimeoutType
XMLHttpRequestMainThread::MaybeStartSyncTimeoutTimer()
{
  MOZ_ASSERT(mFlagSynchronous);

  nsIDocument* doc = GetDocumentIfCurrent();
  if (!doc || !doc->GetPageUnloadingEventTimeStamp()) {
    return eNoTimerNeeded;
  }

  // If we are in a beforeunload or a unload event, we must force a timeout.
  TimeDuration diff = (TimeStamp::NowLoRes() - doc->GetPageUnloadingEventTimeStamp());
  if (diff.ToMilliseconds() > MAX_SYNC_TIMEOUT_WHEN_UNLOADING) {
    return eErrorOrExpired;
  }

  mSyncTimeoutTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
  if (!mSyncTimeoutTimer) {
    return eErrorOrExpired;
  }

  uint32_t timeout = MAX_SYNC_TIMEOUT_WHEN_UNLOADING - diff.ToMilliseconds();
  nsresult rv = mSyncTimeoutTimer->InitWithCallback(this, timeout,
                                                    nsITimer::TYPE_ONE_SHOT);
  return NS_FAILED(rv) ? eErrorOrExpired : eTimerStarted;
}

void
XMLHttpRequestMainThread::HandleSyncTimeoutTimer()
{
  MOZ_ASSERT(mSyncTimeoutTimer);
  MOZ_ASSERT(mFlagSyncLooping);

  CancelSyncTimeoutTimer();
  Abort();
}

void
XMLHttpRequestMainThread::CancelSyncTimeoutTimer()
{
  if (mSyncTimeoutTimer) {
    mSyncTimeoutTimer->Cancel();
    mSyncTimeoutTimer = nullptr;
  }
}

already_AddRefed<nsXMLHttpRequestXPCOMifier>
XMLHttpRequestMainThread::EnsureXPCOMifier()
{
  if (!mXPCOMifier) {
    mXPCOMifier = new nsXMLHttpRequestXPCOMifier(this);
  }
  RefPtr<nsXMLHttpRequestXPCOMifier> newRef(mXPCOMifier);
  return newRef.forget();
}

bool
XMLHttpRequestMainThread::ShouldBlockAuthPrompt()
{
  // Verify that it's ok to prompt for credentials here, per spec
  // http://xhr.spec.whatwg.org/#the-send%28%29-method

  if (mAuthorRequestHeaders.Has("authorization")) {
    return true;
  }

  nsCOMPtr<nsIURI> uri;
  nsresult rv = mChannel->GetURI(getter_AddRefs(uri));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  // Also skip if a username and/or password is provided in the URI.
  nsCString username;
  rv = uri->GetUsername(username);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  nsCString password;
  rv = uri->GetPassword(password);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  if (!username.IsEmpty() || !password.IsEmpty()) {
    return true;
  }

  return false;
}

void
XMLHttpRequestMainThread::TruncateResponseText()
{
  mResponseText.Truncate();
  XMLHttpRequestBinding::ClearCachedResponseTextValue(this);
}

NS_IMPL_ISUPPORTS(XMLHttpRequestMainThread::nsHeaderVisitor, nsIHttpHeaderVisitor)

NS_IMETHODIMP XMLHttpRequestMainThread::
nsHeaderVisitor::VisitHeader(const nsACString &header, const nsACString &value)
{
  if (mXHR.IsSafeHeader(header, mHttpChannel)) {
    mHeaders.Append(header);
    mHeaders.AppendLiteral(": ");
    mHeaders.Append(value);
    mHeaders.AppendLiteral("\r\n");
  }
  return NS_OK;
}

void
XMLHttpRequestMainThread::MaybeCreateBlobStorage()
{
  MOZ_ASSERT(mResponseType == XMLHttpRequestResponseType::Blob);

  if (mBlobStorage) {
    return;
  }

  MutableBlobStorage::MutableBlobStorageType storageType =
    BasePrincipal::Cast(mPrincipal)->PrivateBrowsingId() == 0
      ? MutableBlobStorage::eCouldBeInTemporaryFile
      : MutableBlobStorage::eOnlyInMemory;

  mBlobStorage = new MutableBlobStorage(storageType);
}

void
XMLHttpRequestMainThread::BlobStoreCompleted(MutableBlobStorage* aBlobStorage,
                                             Blob* aBlob, nsresult aRv)
{
  // Ok, the state is changed...
  if (mBlobStorage != aBlobStorage || NS_FAILED(aRv)) {
    return;
  }

  MOZ_ASSERT(mState != State::done);

  mResponseBlob = aBlob;
  mBlobStorage = nullptr;

  ChangeStateToDone();
}

// nsXMLHttpRequestXPCOMifier implementation
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsXMLHttpRequestXPCOMifier)
  NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
  NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
  NS_INTERFACE_MAP_ENTRY(nsIChannelEventSink)
  NS_INTERFACE_MAP_ENTRY(nsIAsyncVerifyRedirectCallback)
  NS_INTERFACE_MAP_ENTRY(nsIProgressEventSink)
  NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
  NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamListener)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(nsXMLHttpRequestXPCOMifier)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsXMLHttpRequestXPCOMifier)

// Can't NS_IMPL_CYCLE_COLLECTION( because mXHR has ambiguous
// inheritance from nsISupports.
NS_IMPL_CYCLE_COLLECTION_CLASS(nsXMLHttpRequestXPCOMifier)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXMLHttpRequestXPCOMifier)
if (tmp->mXHR) {
  tmp->mXHR->mXPCOMifier = nullptr;
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mXHR)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXMLHttpRequestXPCOMifier)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mXHR)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMETHODIMP
nsXMLHttpRequestXPCOMifier::GetInterface(const nsIID & aIID, void **aResult)
{
  // Return ourselves for the things we implement (except
  // nsIInterfaceRequestor) and the XHR for the rest.
  if (!aIID.Equals(NS_GET_IID(nsIInterfaceRequestor))) {
    nsresult rv = QueryInterface(aIID, aResult);
    if (NS_SUCCEEDED(rv)) {
      return rv;
    }
  }

  return mXHR->GetInterface(aIID, aResult);
}

ArrayBufferBuilder::ArrayBufferBuilder()
  : mDataPtr(nullptr),
    mCapacity(0),
    mLength(0),
    mMapPtr(nullptr)
{
}

ArrayBufferBuilder::~ArrayBufferBuilder()
{
  reset();
}

void
ArrayBufferBuilder::reset()
{
  if (mDataPtr) {
    JS_free(nullptr, mDataPtr);
  }

  if (mMapPtr) {
    JS_ReleaseMappedArrayBufferContents(mMapPtr, mLength);
    mMapPtr = nullptr;
  }

  mDataPtr = nullptr;
  mCapacity = mLength = 0;
}

bool
ArrayBufferBuilder::setCapacity(uint32_t aNewCap)
{
  MOZ_ASSERT(!mMapPtr);

  // To ensure that realloc won't free mDataPtr, use a size of 1
  // instead of 0.
  uint8_t* newdata = (uint8_t *) js_realloc(mDataPtr, aNewCap ? aNewCap : 1);

  if (!newdata) {
    return false;
  }

  if (aNewCap > mCapacity) {
    memset(newdata + mCapacity, 0, aNewCap - mCapacity);
  }

  mDataPtr = newdata;
  mCapacity = aNewCap;
  if (mLength > aNewCap) {
    mLength = aNewCap;
  }

  return true;
}

bool
ArrayBufferBuilder::append(const uint8_t *aNewData, uint32_t aDataLen,
                           uint32_t aMaxGrowth)
{
  MOZ_ASSERT(!mMapPtr);

  CheckedUint32 neededCapacity = mLength;
  neededCapacity += aDataLen;
  if (!neededCapacity.isValid()) {
    return false;
  }
  if (mLength + aDataLen > mCapacity) {
    CheckedUint32 newcap = mCapacity;
    // Double while under aMaxGrowth or if not specified.
    if (!aMaxGrowth || mCapacity < aMaxGrowth) {
      newcap *= 2;
    } else {
      newcap += aMaxGrowth;
    }

    if (!newcap.isValid()) {
      return false;
    }

    // But make sure there's always enough to satisfy our request.
    if (newcap.value() < neededCapacity.value()) {
      newcap = neededCapacity;
    }

    if (!setCapacity(newcap.value())) {
      return false;
    }
  }

  // Assert that the region isn't overlapping so we can memcpy.
  MOZ_ASSERT(!areOverlappingRegions(aNewData, aDataLen, mDataPtr + mLength,
                                    aDataLen));

  memcpy(mDataPtr + mLength, aNewData, aDataLen);
  mLength += aDataLen;

  return true;
}

JSObject*
ArrayBufferBuilder::getArrayBuffer(JSContext* aCx)
{
  if (mMapPtr) {
    JSObject* obj = JS_NewMappedArrayBufferWithContents(aCx, mLength, mMapPtr);
    if (!obj) {
      JS_ReleaseMappedArrayBufferContents(mMapPtr, mLength);
    }
    mMapPtr = nullptr;

    // The memory-mapped contents will be released when the ArrayBuffer becomes
    // detached or is GC'd.
    return obj;
  }

  // we need to check for mLength == 0, because nothing may have been
  // added
  if (mCapacity > mLength || mLength == 0) {
    if (!setCapacity(mLength)) {
      return nullptr;
    }
  }

  JSObject* obj = JS_NewArrayBufferWithContents(aCx, mLength, mDataPtr);
  mLength = mCapacity = 0;
  if (!obj) {
    js_free(mDataPtr);
  }
  mDataPtr = nullptr;
  return obj;
}

nsresult
ArrayBufferBuilder::mapToFileInPackage(const nsCString& aFile,
                                       nsIFile* aJarFile)
{
  nsresult rv;

  // Open Jar file to get related attributes of target file.
  RefPtr<nsZipArchive> zip = new nsZipArchive();
  rv = zip->OpenArchive(aJarFile);
  if (NS_FAILED(rv)) {
    return rv;
  }
  nsZipItem* zipItem = zip->GetItem(aFile.get());
  if (!zipItem) {
    return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST;
  }

  // If file was added to the package as stored(uncompressed), map to the
  // offset of file in zip package.
  if (!zipItem->Compression()) {
    uint32_t offset = zip->GetDataOffset(zipItem);
    uint32_t size = zipItem->RealSize();
    mozilla::AutoFDClose pr_fd;
    rv = aJarFile->OpenNSPRFileDesc(PR_RDONLY, 0, &pr_fd.rwget());
    if (NS_FAILED(rv)) {
      return rv;
    }
    mMapPtr = JS_CreateMappedArrayBufferContents(PR_FileDesc2NativeHandle(pr_fd),
                                                 offset, size);
    if (mMapPtr) {
      mLength = size;
      return NS_OK;
    }
  }
  return NS_ERROR_FAILURE;
}

/* static */ bool
ArrayBufferBuilder::areOverlappingRegions(const uint8_t* aStart1,
                                          uint32_t aLength1,
                                          const uint8_t* aStart2,
                                          uint32_t aLength2)
{
  const uint8_t* end1 = aStart1 + aLength1;
  const uint8_t* end2 = aStart2 + aLength2;

  const uint8_t* max_start = aStart1 > aStart2 ? aStart1 : aStart2;
  const uint8_t* min_end   = end1 < end2 ? end1 : end2;

  return max_start < min_end;
}

RequestHeaders::RequestHeader*
RequestHeaders::Find(const nsACString& aName)
{
  const nsCaseInsensitiveCStringComparator ignoreCase;
  for (RequestHeaders::RequestHeader& header : mHeaders) {
    if (header.mName.Equals(aName, ignoreCase)) {
      return &header;
    }
  }
  return nullptr;
}

bool
RequestHeaders::Has(const char* aName)
{
  return Has(nsDependentCString(aName));
}

bool
RequestHeaders::Has(const nsACString& aName)
{
  return !!Find(aName);
}

void
RequestHeaders::Get(const char* aName, nsACString& aValue)
{
  Get(nsDependentCString(aName), aValue);
}

void
RequestHeaders::Get(const nsACString& aName, nsACString& aValue)
{
  RequestHeader* header = Find(aName);
  if (header) {
    aValue = header->mValue;
  } else {
    aValue.SetIsVoid(true);
  }
}

void
RequestHeaders::Set(const char* aName, const nsACString& aValue)
{
  Set(nsDependentCString(aName), aValue);
}

void
RequestHeaders::Set(const nsACString& aName, const nsACString& aValue)
{
  RequestHeader* header = Find(aName);
  if (header) {
    header->mValue.Assign(aValue);
  } else {
    RequestHeader newHeader = {
      nsCString(aName), nsCString(aValue)
    };
    mHeaders.AppendElement(newHeader);
  }
}

void
RequestHeaders::MergeOrSet(const char* aName, const nsACString& aValue)
{
  MergeOrSet(nsDependentCString(aName), aValue);
}

void
RequestHeaders::MergeOrSet(const nsACString& aName, const nsACString& aValue)
{
  RequestHeader* header = Find(aName);
  if (header) {
    header->mValue.AppendLiteral(", ");
    header->mValue.Append(aValue);
  } else {
    RequestHeader newHeader = {
      nsCString(aName), nsCString(aValue)
    };
    mHeaders.AppendElement(newHeader);
  }
}

void
RequestHeaders::Clear()
{
  mHeaders.Clear();
}

void
RequestHeaders::ApplyToChannel(nsIHttpChannel* aHttpChannel) const
{
  for (const RequestHeader& header : mHeaders) {
    if (header.mValue.IsEmpty()) {
      aHttpChannel->SetEmptyRequestHeader(header.mName);
    } else {
      aHttpChannel->SetRequestHeader(header.mName, header.mValue, false);
    }
  }
}

void
RequestHeaders::GetCORSUnsafeHeaders(nsTArray<nsCString>& aArray) const
{
  static const char *kCrossOriginSafeHeaders[] = {
    "accept", "accept-language", "content-language", "content-type",
    "last-event-id"
  };
  const uint32_t kCrossOriginSafeHeadersLength =
    ArrayLength(kCrossOriginSafeHeaders);
  for (const RequestHeader& header : mHeaders) {
    bool safe = false;
    for (uint32_t i = 0; i < kCrossOriginSafeHeadersLength; ++i) {
      if (header.mName.LowerCaseEqualsASCII(kCrossOriginSafeHeaders[i])) {
        safe = true;
        break;
      }
    }
    if (!safe) {
      aArray.AppendElement(header.mName);
    }
  }
}

RequestHeaders::CharsetIterator::CharsetIterator(nsACString& aSource) :
  mValid(false),
  mCurPos(-1),
  mCurLen(-1),
  mCutoff(aSource.Length()),
  mSource(aSource)
{
}

bool
RequestHeaders::CharsetIterator::Equals(const nsACString& aOther,
                                        const nsCStringComparator& aCmp) const
{
  if (mValid) {
    return Substring(mSource, mCurPos, mCurLen).Equals(aOther, aCmp);
  } else {
    return false;
  }
}

void
RequestHeaders::CharsetIterator::Replace(const nsACString& aReplacement)
{
  if (mValid) {
    mSource.Replace(mCurPos, mCurLen, aReplacement);
    mCurLen = aReplacement.Length();
  }
}

bool
RequestHeaders::CharsetIterator::Next()
{
  int32_t start, end;
  nsAutoCString charset;

  // Look for another charset declaration in the string, limiting the
  // search to only the characters before the parts we've already searched
  // (before mCutoff), so that we don't find the same charset twice.
  NS_ExtractCharsetFromContentType(Substring(mSource, 0, mCutoff),
                                   charset, &mValid, &start, &end);

  if (!mValid) {
    return false;
  }

  // Everything after the = sign is the part of the charset we want.
  mCurPos = mSource.FindChar('=', start) + 1;
  mCurLen = end - mCurPos;

  // Special case: the extracted charset is quoted with single quotes.
  // For the purpose of preserving what was set we want to handle them
  // as delimiters (although they aren't really).
  if (charset.Length() >= 2 &&
      charset.First() == '\'' &&
      charset.Last() == '\'') {
    ++mCurPos;
    mCurLen -= 2;
  }

  mCutoff = start;

  return true;
}

} // dom namespace
} // mozilla namespace