summaryrefslogtreecommitdiff
path: root/chromium/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp
blob: 286a38138ac6fdeab4f7143be9726cbbf7f3276a (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
/*
 *  Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved.
 *  Copyright (C) 2005-2007 Alexey Proskuryakov <ap@webkit.org>
 *  Copyright (C) 2007, 2008 Julien Chaffraix <jchaffraix@webkit.org>
 *  Copyright (C) 2008, 2011 Google Inc. All rights reserved.
 *  Copyright (C) 2012 Intel Corporation
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "core/xmlhttprequest/XMLHttpRequest.h"

#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/UnionTypesCore.h"
#include "core/dom/DOMArrayBuffer.h"
#include "core/dom/DOMArrayBufferView.h"
#include "core/dom/DOMException.h"
#include "core/dom/DOMImplementation.h"
#include "core/dom/DOMTypedArray.h"
#include "core/dom/DocumentInit.h"
#include "core/dom/DocumentParser.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/XMLDocument.h"
#include "core/editing/markup.h"
#include "core/events/Event.h"
#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/FetchInitiatorTypeNames.h"
#include "core/fetch/FetchUtils.h"
#include "core/fetch/ResourceLoaderOptions.h"
#include "core/fileapi/Blob.h"
#include "core/fileapi/File.h"
#include "core/fileapi/FileReaderLoader.h"
#include "core/fileapi/FileReaderLoaderClient.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/html/DOMFormData.h"
#include "core/html/HTMLDocument.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/loader/ThreadableLoader.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
#include "core/streams/Stream.h"
#include "core/streams/UnderlyingSource.h"
#include "core/xmlhttprequest/XMLHttpRequestProgressEvent.h"
#include "core/xmlhttprequest/XMLHttpRequestUpload.h"
#include "platform/Logging.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/SharedBuffer.h"
#include "platform/blob/BlobData.h"
#include "platform/network/HTTPParsers.h"
#include "platform/network/ParsedContentType.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceRequest.h"
#include "public/platform/WebDataConsumerHandle.h"
#include "public/platform/WebURLRequest.h"
#include "wtf/Assertions.h"
#include "wtf/RefCountedLeakCounter.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/CString.h"

namespace blink {

DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, xmlHttpRequestCounter, ("XMLHttpRequest"));

namespace {

// This class protects the wrapper of the associated XMLHttpRequest object
// via hasPendingActivity method which returns true if
// m_eventDispatchRecursionLevel is positive.
class ScopedEventDispatchProtect final {
public:
    explicit ScopedEventDispatchProtect(int* level) : m_level(level)
    {
        ++*m_level;
    }
    ~ScopedEventDispatchProtect()
    {
        ASSERT(*m_level > 0);
        --*m_level;
    }

private:
    int* const m_level;
};

bool isSetCookieHeader(const AtomicString& name)
{
    return equalIgnoringCase(name, "set-cookie") || equalIgnoringCase(name, "set-cookie2");
}

void replaceCharsetInMediaType(String& mediaType, const String& charsetValue)
{
    unsigned pos = 0, len = 0;

    findCharsetInMediaType(mediaType, pos, len);

    if (!len) {
        // When no charset found, do nothing.
        return;
    }

    // Found at least one existing charset, replace all occurrences with new charset.
    while (len) {
        mediaType.replace(pos, len, charsetValue);
        unsigned start = pos + charsetValue.length();
        findCharsetInMediaType(mediaType, pos, len, start);
    }
}

void logConsoleError(ExecutionContext* context, const String& message)
{
    if (!context)
        return;
    // FIXME: It's not good to report the bad usage without indicating what source line it came from.
    // We should pass additional parameters so we can tell the console where the mistake occurred.
    context->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
}

} // namespace

using Result = WebDataConsumerHandle::Result;

// ReadableStreamSource is the underlying source for the response stream of
// XHR. The class has two modes: with and without body stream (passed to the
// constructor as the |body| argument).
// 1) When an instance is constructed with a body stream, it receives data from
// the body stream. The data reading is originated by a |pullSource| call.
// 2) When an instance is constructed without a body stream, it receives data
// from |didReceiveData| function. The associated XHR instance will push data
// via the function.
class XMLHttpRequest::ReadableStreamSource final : public GarbageCollectedFinalized<ReadableStreamSource>, public UnderlyingSource, public WebDataConsumerHandle::Client {
    USING_GARBAGE_COLLECTED_MIXIN(ReadableStreamSource);
public:
    ReadableStreamSource(XMLHttpRequest* owner, PassOwnPtr<WebDataConsumerHandle> body)
        : m_owner(owner)
        , m_body(body)
        , m_needsMore(false)
        , m_hasReadBody(false)
        , m_hasGotDidFinishLoading(false)
    {
        if (m_body) {
            // |m_body| has |this| as a raw pointer, but it is not a problem
            // because |this| owns |m_body|.
            m_body->registerClient(this);
        }
    }
    ~ReadableStreamSource() override { }

    WebDataConsumerHandle* body() { return m_body.get(); }

    // UnderlyingSource
    void pullSource() override
    {
        if (m_body) {
            m_needsMore = true;
            enqueueToStreamFromHandle();
        }
    }

    ScriptPromise cancelSource(ScriptState* scriptState, ScriptValue reason) override
    {
        m_owner->abort();
        return ScriptPromise::cast(scriptState, v8::Undefined(scriptState->isolate()));
    }

    // WebDataConsumerHandle::Client
    void didGetReadable() override
    {
        ASSERT(m_body);
        enqueueToStreamFromHandle();
    }

    void startStream(ReadableStreamImpl<ReadableStreamChunkTypeTraits<DOMArrayBufferView>>* stream)
    {
        m_stream = stream;
        stream->didSourceStart();
    }

    void didReceiveData(const char* data, size_t size)
    {
        m_stream->enqueue(DOMUint8Array::create(DOMArrayBuffer::create(data, size), 0, size));
    }

    void didReceiveFinishLoadingNotification()
    {
        m_hasGotDidFinishLoading = true;
        if (m_body && !m_hasReadBody) {
            // If |this| is receiving data via |m_body| stream and it has not
            // read all data from it yet, we should not close |m_stream|.
        } else {
            // When |this| is receiving data via didReceiveData or
            // |m_hasReadBody| is true, we have read all data and enqueued them
            // to |m_stream|. Hence we close |m_stream| here.
            m_stream->close();
        }
    }

    DEFINE_INLINE_VIRTUAL_TRACE()
    {
        visitor->trace(m_owner);
        visitor->trace(m_stream);
        UnderlyingSource::trace(visitor);
    }

private:
    void enqueueToStreamFromHandle()
    {
        ASSERT(m_body);
        while (m_needsMore) {
            const void* buffer = nullptr;
            size_t size = 0;
            Result result = m_body->beginRead(&buffer, WebDataConsumerHandle::FlagNone, &size);
            if (result == WebDataConsumerHandle::ShouldWait)
                return;
            if (result == WebDataConsumerHandle::Done) {
                m_hasReadBody = true;
                if (m_hasGotDidFinishLoading) {
                    // If we got didFinishLoading, we should close the stream
                    // here. If we didn't, it's possible that the loading
                    // actually failed and didFail will be notified, so we
                    // don't close the stream.
                    m_stream->close();
                }
                m_needsMore = false;
                return;
            }
            if (result != WebDataConsumerHandle::Ok) {
                m_stream->error(DOMException::create(NetworkError));
                m_owner->abort();
                m_needsMore = false;
                return;
            }
            RefPtr<DOMArrayBuffer> arrayBuffer = DOMArrayBuffer::create(size, 1);
            memcpy(arrayBuffer->data(), buffer, size);
            result = m_body->endRead(size);
            if (result != WebDataConsumerHandle::Ok) {
                m_stream->error(DOMException::create(NetworkError));
                m_owner->abort();
                m_needsMore = false;
                return;
            }
            m_needsMore = m_stream->enqueue(DOMUint8Array::create(arrayBuffer.release(), 0, size));
        }
    }

    // This is RawPtr in non-oilpan build to avoid the reference cycle. To
    // avoid use-after free, the associated ReadableStream must be closed
    // or errored when m_owner is gone.
    RawPtrWillBeMember<XMLHttpRequest> m_owner;
    Member<ReadableStreamImpl<ReadableStreamChunkTypeTraits<DOMArrayBufferView>>> m_stream;
    OwnPtr<WebDataConsumerHandle> m_body;
    bool m_needsMore;
    bool m_hasReadBody;
    bool m_hasGotDidFinishLoading;
};

class XMLHttpRequest::BlobLoader final : public GarbageCollectedFinalized<XMLHttpRequest::BlobLoader>, public FileReaderLoaderClient {
public:
    static BlobLoader* create(XMLHttpRequest* xhr, PassRefPtr<BlobDataHandle> handle)
    {
        return new BlobLoader(xhr, handle);
    }

    // FileReaderLoaderClient functions.
    virtual void didStartLoading() override { }
    virtual void didReceiveDataForClient(const char* data, unsigned length) override
    {
        ASSERT(length <= INT_MAX);
        m_xhr->didReceiveData(data, length);
    }
    virtual void didFinishLoading() override
    {
        m_xhr->didFinishLoadingFromBlob();
    }
    virtual void didFail(FileError::ErrorCode error) override
    {
        m_xhr->didFailLoadingFromBlob();
    }

    void cancel()
    {
        m_loader.cancel();
    }

    DEFINE_INLINE_TRACE()
    {
        visitor->trace(m_xhr);
    }

private:
    BlobLoader(XMLHttpRequest* xhr, PassRefPtr<BlobDataHandle> handle)
        : m_xhr(xhr)
        , m_loader(FileReaderLoader::ReadByClient, this)
    {
        m_loader.start(m_xhr->executionContext(), handle);
    }

    RawPtrWillBeMember<XMLHttpRequest> m_xhr;
    FileReaderLoader m_loader;
};

PassRefPtrWillBeRawPtr<XMLHttpRequest> XMLHttpRequest::create(ScriptState* scriptState)
{
    ExecutionContext* context = scriptState->executionContext();
    DOMWrapperWorld& world = scriptState->world();
    RefPtr<SecurityOrigin> securityOrigin = world.isIsolatedWorld() ? world.isolatedWorldSecurityOrigin() : nullptr;
    RefPtrWillBeRawPtr<XMLHttpRequest> xmlHttpRequest = adoptRefWillBeNoop(new XMLHttpRequest(context, securityOrigin));
    xmlHttpRequest->suspendIfNeeded();

    return xmlHttpRequest.release();
}

PassRefPtrWillBeRawPtr<XMLHttpRequest> XMLHttpRequest::create(ExecutionContext* context)
{
    RefPtrWillBeRawPtr<XMLHttpRequest> xmlHttpRequest = adoptRefWillBeNoop(new XMLHttpRequest(context, nullptr));
    xmlHttpRequest->suspendIfNeeded();

    return xmlHttpRequest.release();
}

XMLHttpRequest::XMLHttpRequest(ExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin)
    : ActiveDOMObject(context)
    , m_timeoutMilliseconds(0)
    , m_loaderIdentifier(0)
    , m_state(UNSENT)
    , m_lengthDownloadedToFile(0)
    , m_receivedLength(0)
    , m_exceptionCode(0)
    , m_progressEventThrottle(this)
    , m_responseTypeCode(ResponseTypeDefault)
    , m_securityOrigin(securityOrigin)
    , m_eventDispatchRecursionLevel(0)
    , m_async(true)
    , m_includeCredentials(false)
    , m_parsedResponse(false)
    , m_error(false)
    , m_uploadEventsAllowed(true)
    , m_uploadComplete(false)
    , m_sameOriginRequest(true)
    , m_downloadingToFile(false)
    , m_responseTextOverflow(false)
{
#ifndef NDEBUG
    xmlHttpRequestCounter.increment();
#endif
}

XMLHttpRequest::~XMLHttpRequest()
{
#ifndef NDEBUG
    xmlHttpRequestCounter.decrement();
#endif
}

Document* XMLHttpRequest::document() const
{
    ASSERT(executionContext()->isDocument());
    return toDocument(executionContext());
}

SecurityOrigin* XMLHttpRequest::securityOrigin() const
{
    return m_securityOrigin ? m_securityOrigin.get() : executionContext()->securityOrigin();
}

XMLHttpRequest::State XMLHttpRequest::readyState() const
{
    return m_state;
}

ScriptString XMLHttpRequest::responseText(ExceptionState& exceptionState)
{
    if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeText) {
        exceptionState.throwDOMException(InvalidStateError, "The value is only accessible if the object's 'responseType' is '' or 'text' (was '" + responseType() + "').");
        return ScriptString();
    }
    if (m_error || (m_state != LOADING && m_state != DONE))
        return ScriptString();
    return m_responseText;
}

ScriptString XMLHttpRequest::responseJSONSource()
{
    ASSERT(m_responseTypeCode == ResponseTypeJSON);

    if (m_error || m_state != DONE)
        return ScriptString();
    return m_responseText;
}

void XMLHttpRequest::initResponseDocument()
{
    // The W3C spec requires the final MIME type to be some valid XML type, or text/html.
    // If it is text/html, then the responseType of "document" must have been supplied explicitly.
    bool isHTML = responseIsHTML();
    if ((m_response.isHTTP() && !responseIsXML() && !isHTML)
        || (isHTML && m_responseTypeCode == ResponseTypeDefault)
        || executionContext()->isWorkerGlobalScope()) {
        m_responseDocument = nullptr;
        return;
    }

    DocumentInit init = DocumentInit::fromContext(document()->contextDocument(), m_url);
    if (isHTML)
        m_responseDocument = HTMLDocument::create(init);
    else
        m_responseDocument = XMLDocument::create(init);

    // FIXME: Set Last-Modified.
    m_responseDocument->setSecurityOrigin(securityOrigin());
    m_responseDocument->setContextFeatures(document()->contextFeatures());
    m_responseDocument->setMimeType(finalResponseMIMETypeWithFallback());
}

Document* XMLHttpRequest::responseXML(ExceptionState& exceptionState)
{
    if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeDocument) {
        exceptionState.throwDOMException(InvalidStateError, "The value is only accessible if the object's 'responseType' is '' or 'document' (was '" + responseType() + "').");
        return 0;
    }

    if (m_error || m_state != DONE)
        return 0;

    if (!m_parsedResponse) {
        initResponseDocument();
        if (!m_responseDocument)
            return nullptr;

        m_responseDocument->setContent(m_responseText.flattenToString());
        if (!m_responseDocument->wellFormed())
            m_responseDocument = nullptr;

        m_parsedResponse = true;
    }

    return m_responseDocument.get();
}

Blob* XMLHttpRequest::responseBlob()
{
    ASSERT(m_responseTypeCode == ResponseTypeBlob);

    // We always return null before DONE.
    if (m_error || m_state != DONE)
        return 0;

    if (!m_responseBlob) {
        if (m_downloadingToFile) {
            ASSERT(!m_binaryResponseBuilder);

            // When responseType is set to "blob", we redirect the downloaded
            // data to a file-handle directly in the browser process. We get
            // the file-path from the ResourceResponse directly instead of
            // copying the bytes between the browser and the renderer.
            m_responseBlob = Blob::create(createBlobDataHandleFromResponse());
        } else {
            OwnPtr<BlobData> blobData = BlobData::create();
            size_t size = 0;
            if (m_binaryResponseBuilder && m_binaryResponseBuilder->size()) {
                size = m_binaryResponseBuilder->size();
                blobData->appendBytes(m_binaryResponseBuilder->data(), size);
                blobData->setContentType(finalResponseMIMETypeWithFallback().lower());
                m_binaryResponseBuilder.clear();
            }
            m_responseBlob = Blob::create(BlobDataHandle::create(blobData.release(), size));
        }
    }

    return m_responseBlob.get();
}

DOMArrayBuffer* XMLHttpRequest::responseArrayBuffer()
{
    ASSERT(m_responseTypeCode == ResponseTypeArrayBuffer);

    if (m_error || m_state != DONE)
        return 0;

    if (!m_responseArrayBuffer) {
        if (m_binaryResponseBuilder && m_binaryResponseBuilder->size()) {
            RefPtr<DOMArrayBuffer> buffer = DOMArrayBuffer::createUninitialized(m_binaryResponseBuilder->size(), 1);
            if (!m_binaryResponseBuilder->getAsBytes(buffer->data(), buffer->byteLength())) {
                // m_binaryResponseBuilder failed to allocate an ArrayBuffer.
                // We need to crash the renderer since there's no way defined in
                // the spec to tell this to the user.
                CRASH();
            }
            m_responseArrayBuffer = buffer.release();
            m_binaryResponseBuilder.clear();
        } else {
            m_responseArrayBuffer = DOMArrayBuffer::create(nullptr, 0);
        }
    }

    return m_responseArrayBuffer.get();
}

Stream* XMLHttpRequest::responseLegacyStream()
{
    ASSERT(m_responseTypeCode == ResponseTypeLegacyStream);

    if (m_error || (m_state != LOADING && m_state != DONE))
        return 0;

    return m_responseLegacyStream.get();
}

ReadableStream* XMLHttpRequest::responseStream()
{
    ASSERT(m_responseTypeCode == ResponseTypeStream);
    if (m_error || (m_state != LOADING && m_state != DONE))
        return 0;

    return m_responseStream;
}

void XMLHttpRequest::setTimeout(unsigned timeout, ExceptionState& exceptionState)
{
    // FIXME: Need to trigger or update the timeout Timer here, if needed. http://webkit.org/b/98156
    // XHR2 spec, 4.7.3. "This implies that the timeout attribute can be set while fetching is in progress. If that occurs it will still be measured relative to the start of fetching."
    if (executionContext()->isDocument() && !m_async) {
        exceptionState.throwDOMException(InvalidAccessError, "Timeouts cannot be set for synchronous requests made from a document.");
        return;
    }

    m_timeoutMilliseconds = timeout;

    // From http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute:
    // Note: This implies that the timeout attribute can be set while fetching is in progress. If
    // that occurs it will still be measured relative to the start of fetching.
    //
    // The timeout may be overridden after send.
    if (m_loader)
        m_loader->overrideTimeout(timeout);
}

void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& exceptionState)
{
    if (m_state >= LOADING) {
        exceptionState.throwDOMException(InvalidStateError, "The response type cannot be set if the object's state is LOADING or DONE.");
        return;
    }

    // Newer functionality is not available to synchronous requests in window contexts, as a spec-mandated
    // attempt to discourage synchronous XHR use. responseType is one such piece of functionality.
    if (!m_async && executionContext()->isDocument()) {
        exceptionState.throwDOMException(InvalidAccessError, "The response type cannot be changed for synchronous requests made from a document.");
        return;
    }

    if (responseType == "") {
        m_responseTypeCode = ResponseTypeDefault;
    } else if (responseType == "text") {
        m_responseTypeCode = ResponseTypeText;
    } else if (responseType == "json") {
        m_responseTypeCode = ResponseTypeJSON;
    } else if (responseType == "document") {
        m_responseTypeCode = ResponseTypeDocument;
    } else if (responseType == "blob") {
        m_responseTypeCode = ResponseTypeBlob;
    } else if (responseType == "arraybuffer") {
        m_responseTypeCode = ResponseTypeArrayBuffer;
    } else if (responseType == "legacystream") {
        if (RuntimeEnabledFeatures::experimentalStreamEnabled())
            m_responseTypeCode = ResponseTypeLegacyStream;
        else
            return;
    } else if (responseType == "stream") {
        if (RuntimeEnabledFeatures::experimentalStreamEnabled())
            m_responseTypeCode = ResponseTypeStream;
        else
            return;
    } else {
        ASSERT_NOT_REACHED();
    }
}

String XMLHttpRequest::responseType()
{
    switch (m_responseTypeCode) {
    case ResponseTypeDefault:
        return "";
    case ResponseTypeText:
        return "text";
    case ResponseTypeJSON:
        return "json";
    case ResponseTypeDocument:
        return "document";
    case ResponseTypeBlob:
        return "blob";
    case ResponseTypeArrayBuffer:
        return "arraybuffer";
    case ResponseTypeLegacyStream:
        return "legacystream";
    case ResponseTypeStream:
        return "stream";
    }
    return "";
}

String XMLHttpRequest::responseURL()
{
    KURL responseURL(m_response.url());
    if (!responseURL.isNull())
        responseURL.removeFragmentIdentifier();
    return responseURL.string();
}

XMLHttpRequestUpload* XMLHttpRequest::upload()
{
    if (!m_upload)
        m_upload = XMLHttpRequestUpload::create(this);
    return m_upload.get();
}

void XMLHttpRequest::trackProgress(long long length)
{
    m_receivedLength += length;

    if (m_state != LOADING) {
        changeState(LOADING);
    } else {
        // Dispatch a readystatechange event because many applications use
        // it to track progress although this is not specified.
        //
        // FIXME: Stop dispatching this event for progress tracking.
        dispatchReadyStateChangeEvent();
    }
    if (m_async)
        dispatchProgressEventFromSnapshot(EventTypeNames::progress);
}

void XMLHttpRequest::changeState(State newState)
{
    if (m_state != newState) {
        m_state = newState;
        dispatchReadyStateChangeEvent();
    }
}

void XMLHttpRequest::dispatchReadyStateChangeEvent()
{
    if (!executionContext())
        return;

    if (m_async || (m_state <= OPENED || m_state == DONE)) {
        TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "XHRReadyStateChange", "data", InspectorXhrReadyStateChangeEvent::data(executionContext(), this));
        XMLHttpRequestProgressEventThrottle::DeferredEventAction action = XMLHttpRequestProgressEventThrottle::Ignore;
        if (m_state == DONE) {
            if (m_error)
                action = XMLHttpRequestProgressEventThrottle::Clear;
            else
                action = XMLHttpRequestProgressEventThrottle::Flush;
        }
        m_progressEventThrottle.dispatchReadyStateChangeEvent(Event::create(EventTypeNames::readystatechange), action);
        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());
    }

    if (m_state == DONE && !m_error) {
        TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "XHRLoad", "data", InspectorXhrLoadEvent::data(executionContext(), this));
        dispatchProgressEventFromSnapshot(EventTypeNames::load);
        dispatchProgressEventFromSnapshot(EventTypeNames::loadend);
        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());
    }
}

void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& exceptionState)
{
    if (m_state > OPENED || m_loader) {
        exceptionState.throwDOMException(InvalidStateError,  "The value may only be set if the object's state is UNSENT or OPENED.");
        return;
    }

    // FIXME: According to XMLHttpRequest Level 2 we should throw InvalidAccessError exception here.
    // However for time being only print warning message to warn web developers.
    if (!m_async)
        UseCounter::countDeprecation(executionContext(), UseCounter::SyncXHRWithCredentials);

    m_includeCredentials = value;
}

void XMLHttpRequest::open(const AtomicString& method, const String& url, ExceptionState& exceptionState)
{
    open(method, url, true, exceptionState);
}

void XMLHttpRequest::open(const AtomicString& method, const String& urlString, bool async, ExceptionState& exceptionState)
{
    open(method, executionContext()->completeURL(urlString), async, exceptionState);
}

void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool async, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.utf8().data(), url.elidedString().utf8().data(), async);

    if (!internalAbort())
        return;

    State previousState = m_state;
    m_state = UNSENT;
    m_error = false;
    m_uploadComplete = false;

    if (!isValidHTTPToken(method)) {
        exceptionState.throwDOMException(SyntaxError, "'" + method + "' is not a valid HTTP method.");
        return;
    }

    if (FetchUtils::isForbiddenMethod(method)) {
        exceptionState.throwSecurityError("'" + method + "' HTTP method is unsupported.");
        return;
    }

    if (!ContentSecurityPolicy::shouldBypassMainWorld(executionContext()) && !executionContext()->contentSecurityPolicy()->allowConnectToSource(url)) {
        // We can safely expose the URL to JavaScript, as these checks happen synchronously before redirection. JavaScript receives no new information.
        exceptionState.throwSecurityError("Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
        return;
    }

    if (!async && executionContext()->isDocument()) {
        if (document()->settings() && !document()->settings()->syncXHRInDocumentsEnabled()) {
            exceptionState.throwDOMException(InvalidAccessError, "Synchronous requests are disabled for this page.");
            return;
        }

        // Newer functionality is not available to synchronous requests in window contexts, as a spec-mandated
        // attempt to discourage synchronous XHR use. responseType is one such piece of functionality.
        if (m_responseTypeCode != ResponseTypeDefault) {
            exceptionState.throwDOMException(InvalidAccessError, "Synchronous requests from a document must not set a response type.");
            return;
        }

        // Similarly, timeouts are disabled for synchronous requests as well.
        if (m_timeoutMilliseconds > 0) {
            exceptionState.throwDOMException(InvalidAccessError, "Synchronous requests must not set a timeout.");
            return;
        }

        // Here we just warn that firing sync XHR's may affect responsiveness.
        // Eventually sync xhr will be deprecated and an "InvalidAccessError" exception thrown.
        // Refer : https://xhr.spec.whatwg.org/#sync-warning
        // Use count for XHR synchronous requests on main thread only.
        if (!document()->processingBeforeUnload())
            UseCounter::countDeprecation(executionContext(), UseCounter::XMLHttpRequestSynchronousInNonWorkerOutsideBeforeUnload);
    }

    m_method = FetchUtils::normalizeMethod(method);

    m_url = url;

    m_async = async;

    ASSERT(!m_loader);

    // Check previous state to avoid dispatching readyState event
    // when calling open several times in a row.
    if (previousState != OPENED)
        changeState(OPENED);
    else
        m_state = OPENED;
}

void XMLHttpRequest::open(const AtomicString& method, const String& urlString, bool async, const String& user, ExceptionState& exceptionState)
{
    KURL urlWithCredentials(executionContext()->completeURL(urlString));
    if (!user.isNull())
        urlWithCredentials.setUser(user);

    open(method, urlWithCredentials, async, exceptionState);
}

void XMLHttpRequest::open(const AtomicString& method, const String& urlString, bool async, const String& user, const String& password, ExceptionState& exceptionState)
{
    KURL urlWithCredentials(executionContext()->completeURL(urlString));
    if (!user.isNull())
        urlWithCredentials.setUser(user);
    if (!password.isNull())
        urlWithCredentials.setPass(password);

    open(method, urlWithCredentials, async, exceptionState);
}

bool XMLHttpRequest::initSend(ExceptionState& exceptionState)
{
    if (!executionContext())
        return false;

    if (m_state != OPENED || m_loader) {
        exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED.");
        return false;
    }

    m_error = false;
    return true;
}

void XMLHttpRequest::send(const ArrayBufferOrArrayBufferViewOrBlobOrDocumentOrStringOrFormData& data, ExceptionState& exceptionState)
{
    if (data.isNull()) {
        send(exceptionState);
        return;
    }

    InspectorInstrumentation::willSendXMLHttpRequest(executionContext(), url());
    if (data.isArrayBuffer()) {
        send(data.getAsArrayBuffer().get(), exceptionState);
        return;
    }

    if (data.isArrayBufferView()) {
        send(data.getAsArrayBufferView().get(), exceptionState);
        return;
    }

    if (data.isBlob()) {
        send(data.getAsBlob(), exceptionState);
        return;
    }

    if (data.isDocument()) {
        send(data.getAsDocument().get(), exceptionState);
        return;
    }

    if (data.isFormData()) {
        send(data.getAsFormData(), exceptionState);
        return;
    }

    ASSERT(data.isString());
    send(data.getAsString(), exceptionState);
}

void XMLHttpRequest::send(ExceptionState& exceptionState)
{
    InspectorInstrumentation::willSendXMLHttpRequest(executionContext(), url());
    send(String(), exceptionState);
}

bool XMLHttpRequest::areMethodAndURLValidForSend()
{
    return m_method != "GET" && m_method != "HEAD" && m_url.protocolIsInHTTPFamily();
}

void XMLHttpRequest::send(Document* document, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p send() Document %p", this, document);

    ASSERT(document);

    if (!initSend(exceptionState))
        return;

    RefPtr<FormData> httpBody;

    if (areMethodAndURLValidForSend()) {
        // FIXME: Per https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send the
        // Content-Type header and whether to serialize as HTML or XML should
        // depend on |document->isHTMLDocument()|.
        if (getRequestHeader("Content-Type").isEmpty())
            setRequestHeaderInternal("Content-Type", "application/xml;charset=UTF-8");

        String body = createMarkup(document);

        httpBody = FormData::create(UTF8Encoding().encode(body, WTF::EntitiesForUnencodables));
    }

    createRequest(httpBody.release(), exceptionState);
}

void XMLHttpRequest::send(const String& body, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p send() String '%s'", this, body.utf8().data());

    if (!initSend(exceptionState))
        return;

    RefPtr<FormData> httpBody;

    if (!body.isNull() && areMethodAndURLValidForSend()) {
        String contentType = getRequestHeader("Content-Type");
        if (contentType.isEmpty()) {
            setRequestHeaderInternal("Content-Type", "text/plain;charset=UTF-8");
        } else {
            replaceCharsetInMediaType(contentType, "UTF-8");
            m_requestHeaders.set("Content-Type", AtomicString(contentType));
        }

        httpBody = FormData::create(UTF8Encoding().encode(body, WTF::EntitiesForUnencodables));
    }

    createRequest(httpBody.release(), exceptionState);
}

void XMLHttpRequest::send(Blob* body, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p send() Blob '%s'", this, body->uuid().utf8().data());

    if (!initSend(exceptionState))
        return;

    RefPtr<FormData> httpBody;

    if (areMethodAndURLValidForSend()) {
        if (getRequestHeader("Content-Type").isEmpty()) {
            const String& blobType = body->type();
            if (!blobType.isEmpty() && isValidContentType(blobType)) {
                setRequestHeaderInternal("Content-Type", AtomicString(blobType));
            }
        }

        // FIXME: add support for uploading bundles.
        httpBody = FormData::create();
        if (body->hasBackingFile()) {
            File* file = toFile(body);
            if (!file->path().isEmpty())
                httpBody->appendFile(file->path());
            else if (!file->fileSystemURL().isEmpty())
                httpBody->appendFileSystemURL(file->fileSystemURL());
            else
                ASSERT_NOT_REACHED();
        } else {
            httpBody->appendBlob(body->uuid(), body->blobDataHandle());
        }
    }

    createRequest(httpBody.release(), exceptionState);
}

void XMLHttpRequest::send(DOMFormData* body, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p send() DOMFormData %p", this, body);

    if (!initSend(exceptionState))
        return;

    RefPtr<FormData> httpBody;

    if (areMethodAndURLValidForSend()) {
        httpBody = body->createMultiPartFormData();

        if (getRequestHeader("Content-Type").isEmpty()) {
            AtomicString contentType = AtomicString("multipart/form-data; boundary=", AtomicString::ConstructFromLiteral) + httpBody->boundary().data();
            setRequestHeaderInternal("Content-Type", contentType);
        }
    }

    createRequest(httpBody.release(), exceptionState);
}

void XMLHttpRequest::send(DOMArrayBuffer* body, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p send() ArrayBuffer %p", this, body);

    sendBytesData(body->data(), body->byteLength(), exceptionState);
}

void XMLHttpRequest::send(DOMArrayBufferView* body, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "XMLHttpRequest %p send() ArrayBufferView %p", this, body);

    sendBytesData(body->baseAddress(), body->byteLength(), exceptionState);
}

void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionState& exceptionState)
{
    if (!initSend(exceptionState))
        return;

    RefPtr<FormData> httpBody;

    if (areMethodAndURLValidForSend()) {
        httpBody = FormData::create(data, length);
    }

    createRequest(httpBody.release(), exceptionState);
}

void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionState& exceptionState)
{
    createRequest(formData ? formData->deepCopy() : nullptr, exceptionState);
    m_exceptionCode = exceptionState.code();
}

void XMLHttpRequest::createRequest(PassRefPtr<FormData> httpBody, ExceptionState& exceptionState)
{
    // Only GET request is supported for blob URL.
    if (m_url.protocolIs("blob") && m_method != "GET") {
        exceptionState.throwDOMException(NetworkError, "'GET' is the only method allowed for 'blob:' URLs.");
        return;
    }

    // The presence of upload event listeners forces us to use preflighting because POSTing to an URL that does not
    // permit cross origin requests should look exactly like POSTing to an URL that does not respond at all.
    // Also, only async requests support upload progress events.
    bool uploadEvents = false;
    if (m_async) {
        dispatchProgressEvent(EventTypeNames::loadstart, 0, 0);
        if (httpBody && m_upload) {
            uploadEvents = m_upload->hasEventListeners();
            m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadstart));
        }
    }

    m_sameOriginRequest = securityOrigin()->canRequest(m_url);

    // We also remember whether upload events should be allowed for this request in case the upload listeners are
    // added after the request is started.
    m_uploadEventsAllowed = m_sameOriginRequest || uploadEvents || !FetchUtils::isSimpleRequest(m_method, m_requestHeaders);

    ASSERT(executionContext());
    ExecutionContext& executionContext = *this->executionContext();

    ResourceRequest request(m_url);
    request.setHTTPMethod(m_method);
    request.setRequestContext(WebURLRequest::RequestContextXMLHttpRequest);
    request.setFetchCredentialsMode(m_includeCredentials ? WebURLRequest::FetchCredentialsModeInclude : WebURLRequest::FetchCredentialsModeSameOrigin);

    InspectorInstrumentation::willLoadXHR(&executionContext, this, this, m_method, m_url, m_async, httpBody ? httpBody->deepCopy() : nullptr, m_requestHeaders, m_includeCredentials);

    if (httpBody) {
        ASSERT(m_method != "GET");
        ASSERT(m_method != "HEAD");
        request.setHTTPBody(httpBody);
    }

    if (m_requestHeaders.size() > 0)
        request.addHTTPHeaderFields(m_requestHeaders);

    ThreadableLoaderOptions options;
    options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight;
    options.crossOriginRequestPolicy = UseAccessControl;
    options.initiator = FetchInitiatorTypeNames::xmlhttprequest;
    options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(&executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
    options.timeoutMilliseconds = m_timeoutMilliseconds;

    ResourceLoaderOptions resourceLoaderOptions;
    resourceLoaderOptions.allowCredentials = (m_sameOriginRequest || m_includeCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
    resourceLoaderOptions.credentialsRequested = m_includeCredentials ? ClientRequestedCredentials : ClientDidNotRequestCredentials;
    resourceLoaderOptions.securityOrigin = securityOrigin();

    // When responseType is set to "blob", we redirect the downloaded data to a
    // file-handle directly.
    m_downloadingToFile = responseTypeCode() == ResponseTypeBlob;
    if (m_downloadingToFile) {
        request.setDownloadToFile(true);
        resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData;
    }

    if (responseTypeCode() == ResponseTypeStream) {
        request.setUseStreamOnResponse(true);
        resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData;
    }

    m_exceptionCode = 0;
    m_error = false;

    if (m_async) {
        UseCounter::count(&executionContext, UseCounter::XMLHttpRequestAsynchronous);
        if (m_upload)
            request.setReportUploadProgress(true);

        // ThreadableLoader::create can return null here, for example if we're no longer attached to a page.
        // This is true while running onunload handlers.
        // FIXME: Maybe we need to be able to send XMLHttpRequests from onunload, <http://bugs.webkit.org/show_bug.cgi?id=10904>.
        // FIXME: Maybe create() can return null for other reasons too?
        ASSERT(!m_loader);
        m_loader = ThreadableLoader::create(executionContext, this, request, options, resourceLoaderOptions);
    } else {
        // Use count for XHR synchronous requests.
        UseCounter::count(&executionContext, UseCounter::XMLHttpRequestSynchronous);
        ThreadableLoader::loadResourceSynchronously(executionContext, request, *this, options, resourceLoaderOptions);
    }

    if (!m_exceptionCode && m_error)
        m_exceptionCode = NetworkError;
    if (m_exceptionCode)
        exceptionState.throwDOMException(m_exceptionCode, "Failed to load '" + m_url.elidedString() + "'.");
}

void XMLHttpRequest::abort()
{
    WTF_LOG(Network, "XMLHttpRequest %p abort()", this);

    // internalAbort() clears |m_loader|. Compute |sendFlag| now.
    //
    // |sendFlag| corresponds to "the send() flag" defined in the XHR spec.
    //
    // |sendFlag| is only set when we have an active, asynchronous loader.
    // Don't use it as "the send() flag" when the XHR is in sync mode.
    bool sendFlag = m_loader;

    // internalAbort() clears the response. Save the data needed for
    // dispatching ProgressEvents.
    long long expectedLength = m_response.expectedContentLength();
    long long receivedLength = m_receivedLength;

    if (!internalAbort())
        return;

    // The script never gets any chance to call abort() on a sync XHR between
    // send() call and transition to the DONE state. It's because a sync XHR
    // doesn't dispatch any event between them. So, if |m_async| is false, we
    // can skip the "request error steps" (defined in the XHR spec) without any
    // state check.
    //
    // FIXME: It's possible open() is invoked in internalAbort() and |m_async|
    // becomes true by that. We should implement more reliable treatment for
    // nested method invocations at some point.
    if (m_async) {
        if ((m_state == OPENED && sendFlag) || m_state == HEADERS_RECEIVED || m_state == LOADING) {
            ASSERT(!m_loader);
            handleRequestError(0, EventTypeNames::abort, receivedLength, expectedLength);
        }
    }
    m_state = UNSENT;
}

void XMLHttpRequest::clearVariablesForLoading()
{
    if (m_blobLoader) {
        m_blobLoader->cancel();
        m_blobLoader = nullptr;
    }

    m_decoder.clear();

    if (m_responseDocumentParser) {
        m_responseDocumentParser->removeClient(this);
#if !ENABLE(OILPAN)
        m_responseDocumentParser->detach();
#endif
        m_responseDocumentParser = nullptr;
    }

    m_finalResponseCharset = String();
}

bool XMLHttpRequest::internalAbort()
{
    m_error = true;

    if (m_responseDocumentParser && !m_responseDocumentParser->isStopped())
        m_responseDocumentParser->stopParsing();

    clearVariablesForLoading();

    InspectorInstrumentation::didFailXHRLoading(executionContext(), this, this);

    if (m_responseLegacyStream && m_state != DONE)
        m_responseLegacyStream->abort();

    if (m_responseStream) {
        // When the stream is already closed (including canceled from the
        // user), |error| does nothing.
        // FIXME: Create a more specific error.
        m_responseStream->error(DOMException::create(!m_async && m_exceptionCode ? m_exceptionCode : AbortError, "XMLHttpRequest::abort"));
    }

    clearResponse();
    clearRequest();

    if (!m_loader)
        return true;

    // Cancelling the ThreadableLoader m_loader may result in calling
    // window.onload synchronously. If such an onload handler contains open()
    // call on the same XMLHttpRequest object, reentry happens.
    //
    // If, window.onload contains open() and send(), m_loader will be set to
    // non 0 value. So, we cannot continue the outer open(). In such case,
    // just abort the outer open() by returning false.
    RefPtr<ThreadableLoader> loader = m_loader.release();
    loader->cancel();

    // If abort() called internalAbort() and a nested open() ended up
    // clearing the error flag, but didn't send(), make sure the error
    // flag is still set.
    bool newLoadStarted = m_loader;
    if (!newLoadStarted)
        m_error = true;

    return !newLoadStarted;
}

void XMLHttpRequest::clearResponse()
{
    // FIXME: when we add the support for multi-part XHR, we will have to
    // be careful with this initialization.
    m_receivedLength = 0;

    m_response = ResourceResponse();

    m_responseText.clear();

    m_parsedResponse = false;
    m_responseDocument = nullptr;

    m_responseBlob = nullptr;

    m_downloadingToFile = false;
    m_lengthDownloadedToFile = 0;

    m_responseLegacyStream = nullptr;
    m_responseStream = nullptr;
    m_responseStreamSource = nullptr;

    // These variables may referred by the response accessors. So, we can clear
    // this only when we clear the response holder variables above.
    m_binaryResponseBuilder.clear();
    m_responseArrayBuffer.clear();
}

void XMLHttpRequest::clearRequest()
{
    m_requestHeaders.clear();
}

void XMLHttpRequest::dispatchProgressEvent(const AtomicString& type, long long receivedLength, long long expectedLength)
{
    bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLength;
    unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0;
    unsigned long long total = lengthComputable ? static_cast<unsigned long long>(expectedLength) : 0;

    m_progressEventThrottle.dispatchProgressEvent(type, lengthComputable, loaded, total);

    if (type == EventTypeNames::loadend)
        InspectorInstrumentation::didDispatchXHRLoadendEvent(executionContext(), this);
}

void XMLHttpRequest::dispatchProgressEventFromSnapshot(const AtomicString& type)
{
    dispatchProgressEvent(type, m_receivedLength, m_response.expectedContentLength());
}

void XMLHttpRequest::handleNetworkError()
{
    WTF_LOG(Network, "XMLHttpRequest %p handleNetworkError()", this);

    // Response is cleared next, save needed progress event data.
    long long expectedLength = m_response.expectedContentLength();
    long long receivedLength = m_receivedLength;

    if (!internalAbort())
        return;

    handleRequestError(NetworkError, EventTypeNames::error, receivedLength, expectedLength);
}

void XMLHttpRequest::handleDidCancel()
{
    WTF_LOG(Network, "XMLHttpRequest %p handleDidCancel()", this);

    // Response is cleared next, save needed progress event data.
    long long expectedLength = m_response.expectedContentLength();
    long long receivedLength = m_receivedLength;

    if (!internalAbort())
        return;

    handleRequestError(AbortError, EventTypeNames::abort, receivedLength, expectedLength);
}

void XMLHttpRequest::handleRequestError(ExceptionCode exceptionCode, const AtomicString& type, long long receivedLength, long long expectedLength)
{
    WTF_LOG(Network, "XMLHttpRequest %p handleRequestError()", this);

    // The request error steps for event 'type' and exception 'exceptionCode'.

    if (!m_async && exceptionCode) {
        m_state = DONE;
        m_exceptionCode = exceptionCode;
        return;
    }
    // With m_error set, the state change steps are minimal: any pending
    // progress event is flushed + a readystatechange is dispatched.
    // No new progress events dispatched; as required, that happens at
    // the end here.
    ASSERT(m_error);
    changeState(DONE);

    if (!m_uploadComplete) {
        m_uploadComplete = true;
        if (m_upload && m_uploadEventsAllowed)
            m_upload->handleRequestError(type);
    }

    // Note: The below event dispatch may be called while |hasPendingActivity() == false|,
    // when |handleRequestError| is called after |internalAbort()|.
    // This is safe, however, as |this| will be kept alive from a strong ref |Event::m_target|.
    dispatchProgressEvent(EventTypeNames::progress, receivedLength, expectedLength);
    dispatchProgressEvent(type, receivedLength, expectedLength);
    dispatchProgressEvent(EventTypeNames::loadend, receivedLength, expectedLength);
}

void XMLHttpRequest::overrideMimeType(const AtomicString& mimeType, ExceptionState& exceptionState)
{
    if (m_state == LOADING || m_state == DONE) {
        exceptionState.throwDOMException(InvalidStateError, "MimeType cannot be overridden when the state is LOADING or DONE.");
        return;
    }

    m_mimeTypeOverride = mimeType;
}

void XMLHttpRequest::setRequestHeader(const AtomicString& name, const AtomicString& value, ExceptionState& exceptionState)
{
    if (m_state != OPENED || m_loader) {
        exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED.");
        return;
    }

    if (!isValidHTTPToken(name)) {
        exceptionState.throwDOMException(SyntaxError, "'" + name + "' is not a valid HTTP header field name.");
        return;
    }

    if (!isValidHTTPHeaderValue(value)) {
        exceptionState.throwDOMException(SyntaxError, "'" + value + "' is not a valid HTTP header field value.");
        return;
    }

    // No script (privileged or not) can set unsafe headers.
    if (FetchUtils::isForbiddenHeaderName(name)) {
        logConsoleError(executionContext(), "Refused to set unsafe header \"" + name + "\"");
        return;
    }

    setRequestHeaderInternal(name, value);
}

void XMLHttpRequest::setRequestHeaderInternal(const AtomicString& name, const AtomicString& value)
{
    HTTPHeaderMap::AddResult result = m_requestHeaders.add(name, value);
    if (!result.isNewEntry)
        result.storedValue->value = result.storedValue->value + ", " + value;
}

const AtomicString& XMLHttpRequest::getRequestHeader(const AtomicString& name) const
{
    return m_requestHeaders.get(name);
}

String XMLHttpRequest::getAllResponseHeaders() const
{
    if (m_state < HEADERS_RECEIVED || m_error)
        return "";

    StringBuilder stringBuilder;

    HTTPHeaderSet accessControlExposeHeaderSet;
    parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access-Control-Expose-Headers"), accessControlExposeHeaderSet);
    HTTPHeaderMap::const_iterator end = m_response.httpHeaderFields().end();
    for (HTTPHeaderMap::const_iterator it = m_response.httpHeaderFields().begin(); it!= end; ++it) {
        // Hide Set-Cookie header fields from the XMLHttpRequest client for these reasons:
        //     1) If the client did have access to the fields, then it could read HTTP-only
        //        cookies; those cookies are supposed to be hidden from scripts.
        //     2) There's no known harm in hiding Set-Cookie header fields entirely; we don't
        //        know any widely used technique that requires access to them.
        //     3) Firefox has implemented this policy.
        if (isSetCookieHeader(it->key) && !securityOrigin()->canLoadLocalResources())
            continue;

        if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(it->key) && !accessControlExposeHeaderSet.contains(it->key))
            continue;

        stringBuilder.append(it->key);
        stringBuilder.append(':');
        stringBuilder.append(' ');
        stringBuilder.append(it->value);
        stringBuilder.append('\r');
        stringBuilder.append('\n');
    }

    return stringBuilder.toString();
}

const AtomicString& XMLHttpRequest::getResponseHeader(const AtomicString& name) const
{
    if (m_state < HEADERS_RECEIVED || m_error)
        return nullAtom;

    // See comment in getAllResponseHeaders above.
    if (isSetCookieHeader(name) && !securityOrigin()->canLoadLocalResources()) {
        logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\"");
        return nullAtom;
    }

    HTTPHeaderSet accessControlExposeHeaderSet;
    parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access-Control-Expose-Headers"), accessControlExposeHeaderSet);

    if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(name) && !accessControlExposeHeaderSet.contains(name)) {
        logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\"");
        return nullAtom;
    }
    return m_response.httpHeaderField(name);
}

AtomicString XMLHttpRequest::finalResponseMIMEType() const
{
    AtomicString overriddenType = extractMIMETypeFromMediaType(m_mimeTypeOverride);
    if (!overriddenType.isEmpty())
        return overriddenType;

    if (m_response.isHTTP())
        return extractMIMETypeFromMediaType(m_response.httpHeaderField("Content-Type"));

    return m_response.mimeType();
}

AtomicString XMLHttpRequest::finalResponseMIMETypeWithFallback() const
{
    AtomicString finalType = finalResponseMIMEType();
    if (!finalType.isEmpty())
        return finalType;

    // FIXME: This fallback is not specified in the final MIME type algorithm
    // of the XHR spec. Move this to more appropriate place.
    return AtomicString("text/xml", AtomicString::ConstructFromLiteral);
}

bool XMLHttpRequest::responseIsXML() const
{
    return DOMImplementation::isXMLMIMEType(finalResponseMIMETypeWithFallback());
}

bool XMLHttpRequest::responseIsHTML() const
{
    return equalIgnoringCase(finalResponseMIMEType(), "text/html");
}

int XMLHttpRequest::status() const
{
    if (m_state == UNSENT || m_state == OPENED || m_error)
        return 0;

    if (m_response.httpStatusCode())
        return m_response.httpStatusCode();

    return 0;
}

String XMLHttpRequest::statusText() const
{
    if (m_state == UNSENT || m_state == OPENED || m_error)
        return String();

    if (!m_response.httpStatusText().isNull())
        return m_response.httpStatusText();

    return String();
}

void XMLHttpRequest::didFail(const ResourceError& error)
{
    WTF_LOG(Network, "XMLHttpRequest %p didFail()", this);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    // If we are already in an error state, for instance we called abort(), bail out early.
    if (m_error)
        return;

    if (error.isCancellation()) {
        handleDidCancel();
        // Now the XMLHttpRequest instance may be dead.
        return;
    }

    if (error.isTimeout()) {
        handleDidTimeout();
        // Now the XMLHttpRequest instance may be dead.
        return;
    }

    // Network failures are already reported to Web Inspector by ResourceLoader.
    if (error.domain() == errorDomainBlinkInternal)
        logConsoleError(executionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());

    handleNetworkError();
    // Now the XMLHttpRequest instance may be dead.
}

void XMLHttpRequest::didFailRedirectCheck()
{
    WTF_LOG(Network, "XMLHttpRequest %p didFailRedirectCheck()", this);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    handleNetworkError();
    // Now the XMLHttpRequest instance may be dead.
}

void XMLHttpRequest::didFinishLoading(unsigned long identifier, double)
{
    WTF_LOG(Network, "XMLHttpRequest %p didFinishLoading(%lu)", this, identifier);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    if (m_error)
        return;

    if (m_state < HEADERS_RECEIVED)
        changeState(HEADERS_RECEIVED);

    m_loaderIdentifier = identifier;

    if (m_downloadingToFile && m_responseTypeCode != ResponseTypeBlob && m_lengthDownloadedToFile) {
        ASSERT(m_state == LOADING);
        // In this case, we have sent the request with DownloadToFile true,
        // but the user changed the response type after that. Hence we need to
        // read the response data and provide it to this object.
        m_blobLoader = BlobLoader::create(this, createBlobDataHandleFromResponse());
    } else {
        didFinishLoadingInternal();
    }
}

void XMLHttpRequest::didFinishLoadingInternal()
{
    if (m_responseDocumentParser) {
        // |DocumentParser::finish()| tells the parser that we have reached end of the data.
        // When using |HTMLDocumentParser|, which works asynchronously, we do not have the
        // complete document just after the |DocumentParser::finish()| call.
        // Wait for the parser to call us back in |notifyParserStopped| to progress state.
        m_responseDocumentParser->finish();
        ASSERT(m_responseDocument);
        return;
    }

    if (m_decoder) {
        auto text = m_decoder->flush();
        if (!text.isEmpty() && !m_responseTextOverflow) {
            m_responseText = m_responseText.concatenateWith(text);
            m_responseTextOverflow = m_responseText.isEmpty();
        }
    }

    if (m_responseLegacyStream)
        m_responseLegacyStream->finalize();

    if (m_responseStreamSource)
        m_responseStreamSource->didReceiveFinishLoadingNotification();

    clearVariablesForLoading();
    endLoading();
}

void XMLHttpRequest::didFinishLoadingFromBlob()
{
    WTF_LOG(Network, "XMLHttpRequest %p didFinishLoadingFromBlob", this);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    didFinishLoadingInternal();
}

void XMLHttpRequest::didFailLoadingFromBlob()
{
    WTF_LOG(Network, "XMLHttpRequest %p didFailLoadingFromBlob()", this);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    if (m_error)
        return;
    handleNetworkError();
}

PassRefPtr<BlobDataHandle> XMLHttpRequest::createBlobDataHandleFromResponse()
{
    ASSERT(m_downloadingToFile);
    OwnPtr<BlobData> blobData = BlobData::create();
    String filePath = m_response.downloadedFilePath();
    // If we errored out or got no data, we return an empty handle.
    if (!filePath.isEmpty() && m_lengthDownloadedToFile) {
        blobData->appendFile(filePath);
        // FIXME: finalResponseMIMETypeWithFallback() defaults to
        // text/xml which may be incorrect. Replace it with
        // finalResponseMIMEType() after compatibility investigation.
        blobData->setContentType(finalResponseMIMETypeWithFallback().lower());
    }
    return BlobDataHandle::create(blobData.release(), m_lengthDownloadedToFile);
}

void XMLHttpRequest::notifyParserStopped()
{
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    // This should only be called when response document is parsed asynchronously.
    ASSERT(m_responseDocumentParser);
    ASSERT(!m_responseDocumentParser->isParsing());
    ASSERT(!m_responseLegacyStream);
    ASSERT(!m_responseStream);

    // Do nothing if we are called from |internalAbort()|.
    if (m_error)
        return;

    clearVariablesForLoading();

    m_responseDocument->implicitClose();

    if (!m_responseDocument->wellFormed())
        m_responseDocument = nullptr;

    m_parsedResponse = true;

    endLoading();
}

void XMLHttpRequest::endLoading()
{
    InspectorInstrumentation::didFinishXHRLoading(executionContext(), this, this, m_loaderIdentifier, m_responseText, m_method, m_url);

    if (m_loader)
        m_loader = nullptr;
    m_loaderIdentifier = 0;

    changeState(DONE);

    if (!executionContext()->isDocument() || !document() || !document()->frame() || !document()->frame()->page())
        return;

    if (status() >= 200 && status() < 300)
        document()->frame()->page()->chrome().client().xhrSucceeded(document()->frame());
}

void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
    WTF_LOG(Network, "XMLHttpRequest %p didSendData(%llu, %llu)", this, bytesSent, totalBytesToBeSent);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    if (!m_upload)
        return;

    if (m_uploadEventsAllowed)
        m_upload->dispatchProgressEvent(bytesSent, totalBytesToBeSent);

    if (bytesSent == totalBytesToBeSent && !m_uploadComplete) {
        m_uploadComplete = true;
        if (m_uploadEventsAllowed)
            m_upload->dispatchEventAndLoadEnd(EventTypeNames::load, true, bytesSent, totalBytesToBeSent);
    }
}

void XMLHttpRequest::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
{
    WTF_LOG(Network, "XMLHttpRequest %p didReceiveResponse(%lu)", this, identifier);
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);

    m_response = response;
    if (!m_mimeTypeOverride.isEmpty()) {
        m_response.setHTTPHeaderField("Content-Type", m_mimeTypeOverride);
        m_finalResponseCharset = extractCharsetFromMediaType(m_mimeTypeOverride);
    }

    if (m_finalResponseCharset.isEmpty())
        m_finalResponseCharset = response.textEncodingName();

    if (handle) {
        ASSERT(!m_responseStream);
        ASSERT(!m_responseStreamSource);
        m_responseStreamSource = new ReadableStreamSource(this, handle);
        m_responseStream = new ReadableStreamImpl<ReadableStreamChunkTypeTraits<DOMArrayBufferView>>(m_responseStreamSource);
        m_responseStreamSource->startStream(m_responseStream);

        changeState(HEADERS_RECEIVED);
        if (m_error) {
            // We need to check for |m_error| because |changeState| may trigger
            // readystatechange, and user javascript can cause |abort()|.
            return;
        }
        changeState(LOADING);
    }
}

void XMLHttpRequest::parseDocumentChunk(const char* data, unsigned len)
{
    if (!m_responseDocumentParser) {
        ASSERT(!m_responseDocument);
        initResponseDocument();
        if (!m_responseDocument)
            return;

        m_responseDocumentParser = m_responseDocument->implicitOpen(AllowAsynchronousParsing);
        m_responseDocumentParser->addClient(this);
    }
    ASSERT(m_responseDocumentParser);

    if (m_responseDocumentParser->needsDecoder())
        m_responseDocumentParser->setDecoder(createDecoder());

    m_responseDocumentParser->appendBytes(data, len);
}

PassOwnPtr<TextResourceDecoder> XMLHttpRequest::createDecoder() const
{
    if (m_responseTypeCode == ResponseTypeJSON)
        return TextResourceDecoder::create("application/json", "UTF-8");

    if (!m_finalResponseCharset.isEmpty())
        return TextResourceDecoder::create("text/plain", m_finalResponseCharset);

    // allow TextResourceDecoder to look inside the m_response if it's XML or HTML
    if (responseIsXML()) {
        OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
        // Don't stop on encoding errors, unlike it is done for other kinds
        // of XML resources. This matches the behavior of previous WebKit
        // versions, Firefox and Opera.
        decoder->useLenientXMLDecoding();

        return decoder.release();
    }

    if (responseIsHTML())
        return TextResourceDecoder::create("text/html", "UTF-8");

    return TextResourceDecoder::create("text/plain", "UTF-8");
}

void XMLHttpRequest::didReceiveData(const char* data, unsigned len)
{
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);
    if (m_error)
        return;

    if (m_state < HEADERS_RECEIVED)
        changeState(HEADERS_RECEIVED);

    // We need to check for |m_error| again, because |changeState| may trigger
    // readystatechange, and user javascript can cause |abort()|.
    if (m_error)
        return;

    if (!len)
        return;

    if (m_responseTypeCode == ResponseTypeDocument && responseIsHTML()) {
        parseDocumentChunk(data, len);
    } else if (m_responseTypeCode == ResponseTypeDefault || m_responseTypeCode == ResponseTypeText || m_responseTypeCode == ResponseTypeJSON || m_responseTypeCode == ResponseTypeDocument) {
        if (!m_decoder)
            m_decoder = createDecoder();

        auto text = m_decoder->decode(data, len);
        if (!text.isEmpty() && !m_responseTextOverflow) {
            m_responseText = m_responseText.concatenateWith(text);
            m_responseTextOverflow = m_responseText.isEmpty();
        }
    } else if (m_responseTypeCode == ResponseTypeArrayBuffer || m_responseTypeCode == ResponseTypeBlob) {
        // Buffer binary data.
        if (!m_binaryResponseBuilder)
            m_binaryResponseBuilder = SharedBuffer::create();
        m_binaryResponseBuilder->append(data, len);
    } else if (m_responseTypeCode == ResponseTypeLegacyStream) {
        if (!m_responseLegacyStream)
            m_responseLegacyStream = Stream::create(executionContext(), responseType());
        m_responseLegacyStream->addData(data, len);
    } else if (m_responseTypeCode == ResponseTypeStream) {
        if (!m_responseStream) {
            ASSERT(!m_responseStreamSource);
            m_responseStreamSource = new ReadableStreamSource(this, nullptr);
            m_responseStream = new ReadableStreamImpl<ReadableStreamChunkTypeTraits<DOMArrayBufferView>>(m_responseStreamSource);
            m_responseStreamSource->startStream(m_responseStream);
        }
        m_responseStreamSource->didReceiveData(data, len);
    }

    if (m_blobLoader) {
        // In this case, the data is provided by m_blobLoader. As progress
        // events are already fired, we should return here.
        return;
    }
    trackProgress(len);
}

void XMLHttpRequest::didDownloadData(int dataLength)
{
    ScopedEventDispatchProtect protect(&m_eventDispatchRecursionLevel);
    if (m_error)
        return;

    ASSERT(m_downloadingToFile);

    if (m_state < HEADERS_RECEIVED)
        changeState(HEADERS_RECEIVED);

    if (!dataLength)
        return;

    // readystatechange event handler may do something to put this XHR in error
    // state. We need to check m_error again here.
    if (m_error)
        return;

    m_lengthDownloadedToFile += dataLength;

    trackProgress(dataLength);
}

void XMLHttpRequest::handleDidTimeout()
{
    WTF_LOG(Network, "XMLHttpRequest %p handleDidTimeout()", this);

    // Response is cleared next, save needed progress event data.
    long long expectedLength = m_response.expectedContentLength();
    long long receivedLength = m_receivedLength;

    if (!internalAbort())
        return;

    handleRequestError(TimeoutError, EventTypeNames::timeout, receivedLength, expectedLength);
}

void XMLHttpRequest::suspend()
{
    m_progressEventThrottle.suspend();
}

void XMLHttpRequest::resume()
{
    m_progressEventThrottle.resume();
}

void XMLHttpRequest::stop()
{
    internalAbort();
}

bool XMLHttpRequest::hasPendingActivity() const
{
    // Neither this object nor the JavaScript wrapper should be deleted while
    // a request is in progress because we need to keep the listeners alive,
    // and they are referenced by the JavaScript wrapper.
    // |m_loader| is non-null while request is active and ThreadableLoaderClient
    // callbacks may be called, and |m_responseDocumentParser| is non-null while
    // DocumentParserClient callbacks may be called.
    if (m_loader || m_responseDocumentParser)
        return true;
    if (m_responseStream && m_responseStream->isLocked())
        return true;
    return m_eventDispatchRecursionLevel > 0;
}

void XMLHttpRequest::contextDestroyed()
{
    ASSERT(!m_loader);
    ActiveDOMObject::contextDestroyed();
}

const AtomicString& XMLHttpRequest::interfaceName() const
{
    return EventTargetNames::XMLHttpRequest;
}

ExecutionContext* XMLHttpRequest::executionContext() const
{
    return ActiveDOMObject::executionContext();
}

DEFINE_TRACE(XMLHttpRequest)
{
    visitor->trace(m_responseBlob);
    visitor->trace(m_responseLegacyStream);
    visitor->trace(m_responseStream);
    visitor->trace(m_responseStreamSource);
    visitor->trace(m_responseDocument);
    visitor->trace(m_responseDocumentParser);
    visitor->trace(m_progressEventThrottle);
    visitor->trace(m_upload);
    visitor->trace(m_blobLoader);
    XMLHttpRequestEventTarget::trace(visitor);
    DocumentParserClient::trace(visitor);
    ActiveDOMObject::trace(visitor);
}

} // namespace blink