generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathXMLHttpRequestMainThread.cpp
4456 lines (3771 loc) · 139 KB
/
XMLHttpRequestMainThread.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
/*
* Modifications Copyright SAP SE. 2019-2021. All rights reserved.
*/
#include "XMLHttpRequestMainThread.h"
#include <algorithm>
#ifndef XP_WIN
# include <unistd.h>
#endif
#include "mozilla/ArrayUtils.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/Components.h"
#include "mozilla/dom/AutoSuppressEventHandlingAndSuspend.h"
#include "mozilla/dom/BlobBinding.h"
#include "mozilla/dom/BlobURLProtocolHandler.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/DOMString.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/FileBinding.h"
#include "mozilla/dom/FileCreatorHelper.h"
#include "mozilla/dom/FetchUtil.h"
#include "mozilla/dom/FormData.h"
#include "mozilla/dom/quota/QuotaCommon.h"
#include "mozilla/dom/MutableBlobStorage.h"
#include "mozilla/dom/XMLDocument.h"
#include "mozilla/dom/URLSearchParams.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/ReferrerInfo.h"
#include "mozilla/dom/WorkerError.h"
#include "mozilla/Encoding.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/LoadContext.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/net/ContentRange.h"
#include "mozilla/PreloaderBase.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/dom/ProgressEvent.h"
#include "nsDataChannel.h"
#include "nsIBaseChannel.h"
#include "nsIJARChannel.h"
#include "nsIJARURI.h"
#include "nsReadableUtils.h"
#include "nsSandboxFlags.h"
#include "nsTaintingUtils.h"
#include "nsIURI.h"
#include "nsIURIMutator.h"
#include "nsILoadGroup.h"
#include "nsNetUtil.h"
#include "nsStringStream.h"
#include "nsIAuthPrompt.h"
#include "nsIAuthPrompt2.h"
#include "nsIClassOfService.h"
#include "nsIHttpChannel.h"
#include "nsISupportsPriority.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsStreamUtils.h"
#include "nsThreadUtils.h"
#include "nsIUploadChannel.h"
#include "nsIUploadChannel2.h"
#include "nsXPCOM.h"
#include "nsIDOMEventListener.h"
#include "nsVariant.h"
#include "nsIScriptError.h"
#include "nsICachingChannel.h"
#include "nsICookieJarSettings.h"
#include "nsContentUtils.h"
#include "nsCycleCollectionParticipant.h"
#include "nsError.h"
#include "nsIPromptFactory.h"
#include "nsIWindowWatcher.h"
#include "nsIConsoleService.h"
#include "nsAsyncRedirectVerifyHelper.h"
#include "nsStringBuffer.h"
#include "nsIFileChannel.h"
#include "mozilla/Telemetry.h"
#include "js/ArrayBuffer.h" // JS::{Create,Release}MappedArrayBufferContents,New{,Mapped}ArrayBufferWithContents
#include "js/JSON.h" // JS_ParseJSON
#include "js/MemoryFunctions.h"
#include "js/RootingAPI.h" // JS::{{,Mutable}Handle,Rooted}
#include "js/Value.h" // JS::{,Undefined}Value
#include "jsapi.h" // JS_ClearPendingException
#include "GeckoProfiler.h"
#include "mozilla/dom/XMLHttpRequestBinding.h"
#include "mozilla/Attributes.h"
#include "MultipartBlobImpl.h"
#include "nsIPermissionManager.h"
#include "nsMimeTypes.h"
#include "nsIHttpChannelInternal.h"
#include "nsCharSeparatedTokenizer.h"
#include "nsStreamListenerWrapper.h"
#include "nsITimedChannel.h"
#include "nsWrapperCacheInlines.h"
#include "nsZipArchive.h"
#include "mozilla/Preferences.h"
#include "private/pprio.h"
#include "XMLHttpRequestUpload.h"
// Undefine the macro of CreateFile to avoid FileCreatorHelper#CreateFile being
// replaced by FileCreatorHelper#CreateFileW.
#ifdef CreateFile
# undef CreateFile
#endif
extern mozilla::LazyLogModule gXMLHttpRequestLog;
using namespace mozilla::net;
namespace mozilla::dom {
using EventType = XMLHttpRequest::EventType;
using Events = XMLHttpRequest::Events;
// 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 nsString kLiteralString_readystatechange = u"readystatechange"_ns;
const nsString kLiteralString_xmlhttprequest = u"xmlhttprequest"_ns;
const nsString kLiteralString_DOMContentLoaded = u"DOMContentLoaded"_ns;
const nsCString kLiteralString_charset = "charset"_ns;
const nsCString kLiteralString_UTF_8 = "UTF-8"_ns;
} // namespace
#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)
: Runnable("dom::nsResumeTimeoutsEvent"), 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);
}
// We are in a sync event loop.
#define NOT_CALLABLE_IN_SYNC_SEND_RV \
if (mFlagSyncLooping || mEventDispatchingSuspended) { \
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT); \
return; \
}
/////////////////////////////////////////////
//
//
/////////////////////////////////////////////
#ifdef DEBUG
// In debug mode, annotate WorkerRefs with the name of the function being
// invoked for increased scrutability. Save the previous value on the stack.
namespace {
struct DebugWorkerRefs {
Mutex& mMutex;
RefPtr<ThreadSafeWorkerRef> mTSWorkerRef;
nsCString mPrev;
DebugWorkerRefs(XMLHttpRequestMainThread& aXHR, const std::string& aStatus)
: mMutex(aXHR.mTSWorkerRefMutex) {
MutexAutoLock lock(mMutex);
mTSWorkerRef = aXHR.mTSWorkerRef;
if (!mTSWorkerRef) {
return;
}
MOZ_ASSERT(mTSWorkerRef->Private());
nsCString status(aStatus.c_str());
mPrev = GET_WORKERREF_DEBUG_STATUS(mTSWorkerRef->Ref());
SET_WORKERREF_DEBUG_STATUS(mTSWorkerRef->Ref(), status);
}
~DebugWorkerRefs() {
MutexAutoLock lock(mMutex);
if (!mTSWorkerRef) {
return;
}
MOZ_ASSERT(mTSWorkerRef->Private());
SET_WORKERREF_DEBUG_STATUS(mTSWorkerRef->Ref(), mPrev);
mTSWorkerRef = nullptr;
}
};
} // namespace
# define STREAM_STRING(stuff) \
(((const std::ostringstream&)(std::ostringstream() << stuff)) \
.str()) // NOLINT
# define DEBUG_WORKERREFS \
DebugWorkerRefs MOZ_UNIQUE_VAR(debugWR__)(*this, __func__)
# define DEBUG_WORKERREFS1(x) \
DebugWorkerRefs MOZ_UNIQUE_VAR(debugWR__)( \
*this, STREAM_STRING(__func__ << ": " << x)) // NOLINT
#else
# define DEBUG_WORKERREFS void()
# define DEBUG_WORKERREFS1(x) void()
#endif // DEBUG
bool XMLHttpRequestMainThread::sDontWarnAboutSyncXHR = false;
XMLHttpRequestMainThread::XMLHttpRequestMainThread(
nsIGlobalObject* aGlobalObject)
: XMLHttpRequest(aGlobalObject),
#ifdef DEBUG
mTSWorkerRefMutex("Debug WorkerRefs"),
#endif
mResponseBodyDecodedPos(0),
mResponseType(XMLHttpRequestResponseType::_empty),
mState(XMLHttpRequest_Binding::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(ErrorType::eOK),
mErrorLoadDetail(NS_OK),
mErrorParsingXML(false),
mWaitingForOnStopRequest(false),
mProgressTimerIsActive(false),
mIsHtml(false),
mWarnAboutSyncHtml(false),
mLoadTotal(-1),
mLoadTransferred(0),
mIsSystem(false),
mIsAnon(false),
mResultJSON(JS::UndefinedValue()),
mArrayBufferBuilder(new ArrayBufferBuilder()),
mResultArrayBuffer(nullptr),
mIsMappedArrayBuffer(false),
mXPCOMifier(nullptr),
mEventDispatchingSuspended(false),
mEofDecoded(false),
mDelayedDoneNotifier(nullptr) {
DEBUG_WORKERREFS;
mozilla::HoldJSObjects(this);
}
XMLHttpRequestMainThread::~XMLHttpRequestMainThread() {
DEBUG_WORKERREFS;
MOZ_ASSERT(
!mDelayedDoneNotifier,
"How can we have mDelayedDoneNotifier, which owns us, in destructor?");
mFlagDeleted = true;
if ((mState == XMLHttpRequest_Binding::OPENED && mFlagSend) ||
mState == XMLHttpRequest_Binding::LOADING) {
Abort();
}
if (mParseEndListener) {
mParseEndListener->SetIsStale();
mParseEndListener = nullptr;
}
MOZ_ASSERT(!mFlagSyncLooping, "we rather crash than hang");
mFlagSyncLooping = false;
mozilla::DropJSObjects(this);
}
void XMLHttpRequestMainThread::Construct(
nsIPrincipal* aPrincipal, nsICookieJarSettings* aCookieJarSettings,
bool aForWorker, nsIURI* aBaseURI /* = nullptr */,
nsILoadGroup* aLoadGroup /* = nullptr */,
PerformanceStorage* aPerformanceStorage /* = nullptr */,
nsICSPEventListener* aCSPEventListener /* = nullptr */) {
DEBUG_WORKERREFS;
MOZ_ASSERT(aPrincipal);
mPrincipal = aPrincipal;
mBaseURI = aBaseURI;
mLoadGroup = aLoadGroup;
mCookieJarSettings = aCookieJarSettings;
mForWorker = aForWorker;
mPerformanceStorage = aPerformanceStorage;
mCSPEventListener = aCSPEventListener;
}
void XMLHttpRequestMainThread::InitParameters(bool aAnon, bool aSystem) {
DEBUG_WORKERREFS;
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 =
components::PermissionManager::Service();
if (NS_WARN_IF(!permMgr)) {
SetParameters(aAnon, false);
return;
}
uint32_t permission;
nsresult rv = permMgr->TestPermissionFromPrincipal(
principal, "systemXHR"_ns, &permission);
if (NS_FAILED(rv) || permission != nsIPermissionManager::ALLOW_ACTION) {
SetParameters(aAnon, false);
return;
}
}
SetParameters(aAnon, aSystem);
}
void XMLHttpRequestMainThread::SetClientInfoAndController(
const ClientInfo& aClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController) {
mClientInfo.emplace(aClientInfo);
mController = aController;
}
void XMLHttpRequestMainThread::ResetResponse() {
mResponseXML = nullptr;
mResponseBody.Truncate();
TruncateResponseText();
mResponseBlobImpl = nullptr;
mResponseBlob = nullptr;
mBlobStorage = nullptr;
mResultArrayBuffer = nullptr;
mArrayBufferBuilder = new ArrayBufferBuilder();
mResultJSON.setUndefined();
mLoadTransferred = 0;
mResponseBodyDecodedPos = 0;
mEofDecoded = false;
}
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(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 = nullptr;
tmp->mResultJSON.setUndefined();
tmp->mResponseBlobImpl = nullptr;
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(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(XMLHttpRequestMainThread)
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(nsITimerCallback)
NS_INTERFACE_MAP_ENTRY(nsINamed)
NS_INTERFACE_MAP_ENTRY(nsISizeOfEventTarget)
NS_INTERFACE_MAP_END_INHERITING(XMLHttpRequestEventTarget)
NS_IMPL_ADDREF_INHERITED(XMLHttpRequestMainThread, XMLHttpRequestEventTarget)
NS_IMPL_RELEASE_INHERITED(XMLHttpRequestMainThread, XMLHttpRequestEventTarget)
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
}
static void LogMessage(
const char* aWarning, nsPIDOMWindowInner* aWindow,
const nsTArray<nsString>& aParams = nsTArray<nsString>()) {
nsCOMPtr<Document> doc;
if (aWindow) {
doc = aWindow->GetExtantDoc();
}
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, doc,
nsContentUtils::eDOM_PROPERTIES, aWarning,
aParams);
}
Document* XMLHttpRequestMainThread::GetResponseXML(ErrorResult& aRv) {
if (mResponseType != XMLHttpRequestResponseType::_empty &&
mResponseType != XMLHttpRequestResponseType::Document) {
aRv.ThrowInvalidStateError(
"responseXML is only available if responseType is '' or 'document'.");
return nullptr;
}
if (mWarnAboutSyncHtml) {
mWarnAboutSyncHtml = false;
LogMessage("HTMLSyncXHRWarning", GetOwner());
}
if (mState != XMLHttpRequest_Binding::DONE) {
return nullptr;
}
return mResponseXML;
}
/*
* This piece copied from XMLDocument, we try to get the charset
* from HTTP headers.
*/
nsresult XMLHttpRequestMainThread::DetectCharset() {
DEBUG_WORKERREFS;
mDecoder = nullptr;
if (mResponseType != XMLHttpRequestResponseType::_empty &&
mResponseType != XMLHttpRequestResponseType::Text &&
mResponseType != XMLHttpRequestResponseType::Json) {
return NS_OK;
}
nsAutoCString charsetVal;
const Encoding* encoding;
bool ok = mChannel && NS_SUCCEEDED(mChannel->GetContentCharset(charsetVal)) &&
(encoding = Encoding::ForLabel(charsetVal));
if (!ok) {
// MS documentation states UTF-8 is default for responseText
encoding = UTF_8_ENCODING;
}
if (mResponseType == XMLHttpRequestResponseType::Json &&
encoding != UTF_8_ENCODING) {
// The XHR spec says only UTF-8 is supported for responseType == "json"
LogMessage("JSONCharsetWarning", GetOwner());
encoding = UTF_8_ENCODING;
}
// Only sniff the BOM for non-JSON responseTypes
if (mResponseType == XMLHttpRequestResponseType::Json) {
mDecoder = encoding->NewDecoderWithBOMRemoval();
} else {
mDecoder = encoding->NewDecoder();
}
return NS_OK;
}
nsresult XMLHttpRequestMainThread::AppendToResponseText(
Span<const uint8_t> aBuffer, const StringTaint& aTaint, bool aLast) {
// Call this with an empty buffer to send the decoder the signal
// that we have hit the end of the stream.
NS_ENSURE_STATE(mDecoder);
CheckedInt<size_t> destBufferLen =
mDecoder->MaxUTF16BufferLength(aBuffer.Length());
{ // scope for holding the mutex that protects mResponseText
XMLHttpRequestStringWriterHelper helper(mResponseText);
uint32_t len = helper.Length();
destBufferLen += len;
if (!destBufferLen.isValid() || destBufferLen.value() > UINT32_MAX) {
return NS_ERROR_OUT_OF_MEMORY;
}
auto handleOrErr = helper.BulkWrite(destBufferLen.value());
if (handleOrErr.isErr()) {
return handleOrErr.unwrapErr();
}
auto handle = handleOrErr.unwrap();
uint32_t result;
size_t read;
size_t written;
std::tie(result, read, written, std::ignore) =
mDecoder->DecodeToUTF16(aBuffer, handle.AsSpan().From(len), aLast);
MOZ_ASSERT(result == kInputEmpty);
MOZ_ASSERT(read == aBuffer.Length());
len += written;
MOZ_ASSERT(len <= destBufferLen.value());
handle.Finish(len, false);
// TaintFox: propagate taint. TODO(samuel) deal with encoding
helper.AppendTaintAt(len, aTaint);
} // release mutex
if (aLast) {
// Drop the finished decoder to avoid calling into a decoder
// that has finished.
mDecoder = nullptr;
mEofDecoded = true;
}
return NS_OK;
}
void XMLHttpRequestMainThread::GetResponseText(DOMString& aResponseText,
ErrorResult& aRv) {
MOZ_DIAGNOSTIC_ASSERT(!mForWorker);
XMLHttpRequestStringSnapshot snapshot;
GetResponseText(snapshot, aRv);
if (aRv.Failed()) {
return;
}
if (!snapshot.GetAsString(aResponseText)) {
aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
return;
}
// Taintfox: XMLHttpRequest.response source
nsTArray<nsString> args;
nsAutoString url;
if (mRequestURL) {
nsCString cUrl = mRequestURL->GetSpecOrDefault();
url = NS_ConvertUTF8toUTF16(cUrl);
}
args.AppendElement(url);
nsAutoCString requestHeaders;
mAuthorRequestHeaders.GetAll(requestHeaders);
args.AppendElement(NS_ConvertUTF8toUTF16(requestHeaders));
nsAutoCString responseHeaders;
GetAllResponseHeaders(responseHeaders, aRv);
args.AppendElement(NS_ConvertUTF8toUTF16(responseHeaders));
MarkTaintSource(aResponseText, "XMLHttpRequest.response", args);
}
void XMLHttpRequestMainThread::GetResponseText(
XMLHttpRequestStringSnapshot& aSnapshot, ErrorResult& aRv) {
aSnapshot.Reset();
if (mResponseType != XMLHttpRequestResponseType::_empty &&
mResponseType != XMLHttpRequestResponseType::Text) {
aRv.ThrowInvalidStateError(
"responseText is only available if responseType is '' or 'text'.");
return;
}
if (mState != XMLHttpRequest_Binding::LOADING &&
mState != XMLHttpRequest_Binding::DONE) {
return;
}
// Main Fetch step 18 requires to ignore body for head/connect methods.
if (mRequestMethod.EqualsLiteral("HEAD") ||
mRequestMethod.EqualsLiteral("CONNECT")) {
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() &&
(mState != XMLHttpRequest_Binding::DONE || mEofDecoded))) {
mResponseText.CreateSnapshot(aSnapshot);
return;
}
MatchCharsetAndDecoderToResponseDocument();
MOZ_ASSERT(mResponseBodyDecodedPos < mResponseBody.Length() ||
mState == XMLHttpRequest_Binding::DONE,
"Unexpected mResponseBodyDecodedPos");
Span<const uint8_t> span = mResponseBody;
aRv = AppendToResponseText(span.From(mResponseBodyDecodedPos),
mResponseBody.Taint().subtaint(mResponseBodyDecodedPos, -1),
mState == XMLHttpRequest_Binding::DONE);
if (aRv.Failed()) {
return;
}
mResponseBodyDecodedPos = mResponseBody.Length();
if (mEofDecoded) {
// 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;
nsresult rv = GetResponseTextForJSON(string);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// 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::SetResponseType(
XMLHttpRequestResponseType aResponseType, ErrorResult& aRv) {
NOT_CALLABLE_IN_SYNC_SEND_RV
if (mState == XMLHttpRequest_Binding::LOADING ||
mState == XMLHttpRequest_Binding::DONE) {
aRv.ThrowInvalidStateError(
"Cannot set 'responseType' property on XMLHttpRequest after 'send()' "
"(when its state is LOADING or DONE).");
return;
}
// sync request is not allowed setting responseType in window context
if (HasOrHasHadOwner() && mState != XMLHttpRequest_Binding::UNSENT &&
mFlagSynchronous) {
LogMessage("ResponseTypeSyncXHRWarning", GetOwner());
aRv.ThrowInvalidAccessError(
"synchronous XMLHttpRequests do not support timeout and responseType");
return;
}
// Set the responseType attribute's value to the given value.
SetResponseTypeRaw(aResponseType);
}
void XMLHttpRequestMainThread::GetResponse(
JSContext* aCx, JS::MutableHandle<JS::Value> aResponse, ErrorResult& aRv) {
MOZ_DIAGNOSTIC_ASSERT(!mForWorker);
switch (mResponseType) {
case XMLHttpRequestResponseType::_empty:
case XMLHttpRequestResponseType::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: {
if (mState != XMLHttpRequest_Binding::DONE) {
aResponse.setNull();
return;
}
if (!mResultArrayBuffer) {
mResultArrayBuffer = mArrayBufferBuilder->TakeArrayBuffer(aCx);
if (!mResultArrayBuffer) {
aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
return;
}
}
aResponse.setObject(*mResultArrayBuffer);
return;
}
case XMLHttpRequestResponseType::Blob: {
if (mState != XMLHttpRequest_Binding::DONE) {
aResponse.setNull();
return;
}
if (!mResponseBlobImpl) {
aResponse.setNull();
return;
}
if (!mResponseBlob) {
mResponseBlob = Blob::Create(GetOwnerGlobal(), mResponseBlobImpl);
}
if (!GetOrCreateDOMReflector(aCx, mResponseBlob, aResponse)) {
aResponse.setNull();
}
return;
}
case XMLHttpRequestResponseType::Document: {
if (!mResponseXML || mState != XMLHttpRequest_Binding::DONE) {
aResponse.setNull();
return;
}
aRv =
nsContentUtils::WrapNative(aCx, ToSupports(mResponseXML), aResponse);
return;
}
case XMLHttpRequestResponseType::Json: {
if (mState != XMLHttpRequest_Binding::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();
}
already_AddRefed<BlobImpl> XMLHttpRequestMainThread::GetResponseBlobImpl() {
MOZ_DIAGNOSTIC_ASSERT(mForWorker);
MOZ_DIAGNOSTIC_ASSERT(mResponseType == XMLHttpRequestResponseType::Blob);
if (mState != XMLHttpRequest_Binding::DONE) {
return nullptr;
}
RefPtr<BlobImpl> blobImpl = mResponseBlobImpl;
return blobImpl.forget();
}
already_AddRefed<ArrayBufferBuilder>
XMLHttpRequestMainThread::GetResponseArrayBufferBuilder() {
MOZ_DIAGNOSTIC_ASSERT(mForWorker);
MOZ_DIAGNOSTIC_ASSERT(mResponseType ==
XMLHttpRequestResponseType::Arraybuffer);
if (mState != XMLHttpRequest_Binding::DONE) {
return nullptr;
}
RefPtr<ArrayBufferBuilder> builder = mArrayBufferBuilder;
return builder.forget();
}
nsresult XMLHttpRequestMainThread::GetResponseTextForJSON(nsAString& aString) {
if (mState != XMLHttpRequest_Binding::DONE) {
aString.SetIsVoid(true);
return NS_OK;
}
if (!mResponseText.GetAsString(aString)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
bool XMLHttpRequestMainThread::IsCrossSiteCORSRequest() const {
if (!mChannel) {
return false;
}
nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
return loadInfo->GetTainting() == LoadTainting::CORS;
}
bool XMLHttpRequestMainThread::IsDeniedCrossSiteCORSRequest() {
if (IsCrossSiteCORSRequest()) {
nsresult rv;
mChannel->GetStatus(&rv);
if (NS_FAILED(rv)) {
return true;
}
}
return false;
}
bool XMLHttpRequestMainThread::BadContentRangeRequested() {
if (!mChannel) {
return false;
}
// Only nsIBaseChannel supports this
nsCOMPtr<nsIBaseChannel> baseChan = do_QueryInterface(mChannel);
if (!baseChan) {
return false;
}
// A bad range was requested if the channel has no content range
// despite the request specifying a range header.
return !baseChan->ContentRange() && mAuthorRequestHeaders.Has("range");
}
RefPtr<mozilla::net::ContentRange>
XMLHttpRequestMainThread::GetRequestedContentRange() const {
MOZ_ASSERT(mChannel);
nsCOMPtr<nsIBaseChannel> baseChan = do_QueryInterface(mChannel);
if (!baseChan) {
return nullptr;
}
return baseChan->ContentRange();
}
void XMLHttpRequestMainThread::GetContentRangeHeader(nsACString& out) const {
if (!IsBlobURI(mRequestURL)) {
out.SetIsVoid(true);
return;
}
RefPtr<mozilla::net::ContentRange> range = GetRequestedContentRange();
if (range) {
range->AsHeader(out);
} else {
out.SetIsVoid(true);
}
}
void XMLHttpRequestMainThread::GetResponseURL(nsAString& aUrl) {
aUrl.Truncate();
if ((mState == XMLHttpRequest_Binding::UNSENT ||
mState == XMLHttpRequest_Binding::OPENED) ||
!mChannel) {
return;
}
// Make sure we don't leak responseURL information from denied cross-site
// requests.
if (IsDeniedCrossSiteCORSRequest()) {
return;
}
nsCOMPtr<nsIURI> responseUrl;
if (NS_FAILED(NS_GetFinalChannelURI(mChannel, getter_AddRefs(responseUrl)))) {
return;
}
nsAutoCString temp;
responseUrl->GetSpecIgnoringRef(temp);
CopyUTF8toUTF16(temp, aUrl);
}
uint32_t XMLHttpRequestMainThread::GetStatus(ErrorResult& aRv) {
// Make sure we don't leak status information from denied cross-site
// requests.
if (IsDeniedCrossSiteCORSRequest()) {
return 0;
}
if (mState == XMLHttpRequest_Binding::UNSENT ||
mState == XMLHttpRequest_Binding::OPENED) {
return 0;
}
if (mErrorLoad != ErrorType::eOK) {
// 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/206 response, since our load was successful
return GetRequestedContentRange() ? 206 : 200;