forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathXMLHttpRequestWorker.cpp
2300 lines (1876 loc) · 64.9 KB
/
XMLHttpRequestWorker.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/. */
#include "XMLHttpRequestWorker.h"
#include "nsIDOMEventListener.h"
#include "GeckoProfiler.h"
#include "jsapi.h" // JS::RootedValueArray
#include "jsfriendapi.h"
#include "js/ArrayBuffer.h" // JS::Is{,Detached}ArrayBufferObject
#include "js/GCPolicyAPI.h"
#include "js/JSON.h"
#include "js/RootingAPI.h" // JS::{Handle,Heap},PersistentRooted
#include "js/TracingAPI.h"
#include "js/Value.h" // JS::{Undefined,}Value
#include "mozilla/ArrayUtils.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/FormData.h"
#include "mozilla/dom/ProgressEvent.h"
#include "mozilla/dom/SerializedStackHolder.h"
#include "mozilla/dom/StreamBlobImpl.h"
#include "mozilla/dom/StructuredCloneHolder.h"
#include "mozilla/dom/URLSearchParams.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/WorkerRef.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/XMLHttpRequestBinding.h"
#include "mozilla/Telemetry.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsJSUtils.h"
#include "nsThreadUtils.h"
#include "XMLHttpRequestMainThread.h"
#include "XMLHttpRequestUpload.h"
#include "mozilla/UniquePtr.h"
extern mozilla::LazyLogModule gXMLHttpRequestLog;
namespace mozilla::dom {
/**
* XMLHttpRequest in workers
*
* XHR in workers is implemented by proxying calls/events/etc between the
* worker thread and an XMLHttpRequest on the main thread. The glue
* object here is the Proxy, which lives on both threads. All other objects
* live on either the main thread (the XMLHttpRequest) or the worker thread
* (the worker and XHR private objects).
*
* The main thread XHR is always operated in async mode, even for sync XHR
* in workers. Calls made on the worker thread are proxied to the main thread
* synchronously (meaning the worker thread is blocked until the call
* returns). Each proxied call spins up a sync queue, which captures any
* synchronously dispatched events and ensures that they run synchronously
* on the worker as well. Asynchronously dispatched events are posted to the
* worker thread to run asynchronously. Some of the XHR state is mirrored on
* the worker thread to avoid needing a cross-thread call on every property
* access.
*
* The XHR private is stored in the private slot of the XHR JSObject on the
* worker thread. It is destroyed when that JSObject is GCd. The private
* roots its JSObject while network activity is in progress. It also
* adds itself as a feature to the worker to give itself a chance to clean up
* if the worker goes away during an XHR call. It is important that the
* rooting and feature registration (collectively called pinning) happens at
* the proper times. If we pin for too long we can cause memory leaks or even
* shutdown hangs. If we don't pin for long enough we introduce a GC hazard.
*
* The XHR is pinned from the time Send is called to roughly the time loadend
* is received. There are some complications involved with Abort and XHR
* reuse. We maintain a counter on the main thread of how many times Send was
* called on this XHR, and we decrement the counter every time we receive a
* loadend event. When the counter reaches zero we dispatch a runnable to the
* worker thread to unpin the XHR. We only decrement the counter if the
* dispatch was successful, because the worker may no longer be accepting
* regular runnables. In the event that we reach Proxy::Teardown and there
* the outstanding Send count is still non-zero, we dispatch a control
* runnable which is guaranteed to run.
*
* NB: Some of this could probably be simplified now that we have the
* inner/outer channel ids.
*/
class Proxy final : public nsIDOMEventListener {
public:
// Read on multiple threads.
WorkerPrivate* mWorkerPrivate;
XMLHttpRequestWorker* mXMLHttpRequestPrivate;
const ClientInfo mClientInfo;
const Maybe<ServiceWorkerDescriptor> mController;
// XHR Params:
bool mMozAnon;
bool mMozSystem;
// Only touched on the main thread.
RefPtr<XMLHttpRequestMainThread> mXHR;
RefPtr<XMLHttpRequestUpload> mXHRUpload;
nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
nsCOMPtr<nsIEventTarget> mSyncEventResponseTarget;
uint32_t mInnerEventStreamId;
uint32_t mInnerChannelId;
uint32_t mOutstandingSendCount;
// Only touched on the worker thread.
uint32_t mOuterEventStreamId;
uint32_t mOuterChannelId;
uint32_t mOpenCount;
uint64_t mLastLoaded;
uint64_t mLastTotal;
uint64_t mLastUploadLoaded;
uint64_t mLastUploadTotal;
nsresult mLastErrorDetailAtLoadend;
bool mIsSyncXHR;
bool mLastLengthComputable;
bool mLastUploadLengthComputable;
bool mSeenLoadStart;
bool mSeenUploadLoadStart;
bool mDispatchPrematureAbortEvent;
bool mDispatchPrematureAbortEventToUpload;
// Only touched on the main thread.
bool mUploadEventListenersAttached;
bool mMainThreadSeenLoadStart;
bool mInOpen;
public:
Proxy(XMLHttpRequestWorker* aXHRPrivate, const ClientInfo& aClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController, bool aMozAnon,
bool aMozSystem)
: mWorkerPrivate(nullptr),
mXMLHttpRequestPrivate(aXHRPrivate),
mClientInfo(aClientInfo),
mController(aController),
mMozAnon(aMozAnon),
mMozSystem(aMozSystem),
mInnerEventStreamId(0),
mInnerChannelId(0),
mOutstandingSendCount(0),
mOuterEventStreamId(0),
mOuterChannelId(0),
mOpenCount(0),
mLastLoaded(0),
mLastTotal(0),
mLastUploadLoaded(0),
mLastUploadTotal(0),
mLastErrorDetailAtLoadend(NS_OK),
mIsSyncXHR(false),
mLastLengthComputable(false),
mLastUploadLengthComputable(false),
mSeenLoadStart(false),
mSeenUploadLoadStart(false),
mDispatchPrematureAbortEvent(false),
mDispatchPrematureAbortEventToUpload(false),
mUploadEventListenersAttached(false),
mMainThreadSeenLoadStart(false),
mInOpen(false) {}
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIDOMEVENTLISTENER
bool Init();
void Teardown(bool aSendUnpin);
bool AddRemoveEventListeners(bool aUpload, bool aAdd);
void Reset() {
AssertIsOnMainThread();
if (mUploadEventListenersAttached) {
AddRemoveEventListeners(true, false);
}
}
already_AddRefed<nsIEventTarget> GetEventTarget() {
AssertIsOnMainThread();
nsCOMPtr<nsIEventTarget> target =
mSyncEventResponseTarget ? mSyncEventResponseTarget : mSyncLoopTarget;
return target.forget();
}
private:
~Proxy() {
MOZ_ASSERT(!mXHR);
MOZ_ASSERT(!mXHRUpload);
MOZ_ASSERT(!mOutstandingSendCount);
}
};
class WorkerThreadProxySyncRunnable : public WorkerMainThreadRunnable {
protected:
RefPtr<Proxy> mProxy;
private:
// mErrorCode is set on the main thread by MainThreadRun and it's used to at
// the end of the Dispatch() to return the error code.
nsresult mErrorCode;
public:
WorkerThreadProxySyncRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy)
: WorkerMainThreadRunnable(aWorkerPrivate, "XHR"_ns),
mProxy(aProxy),
mErrorCode(NS_OK) {
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aProxy);
aWorkerPrivate->AssertIsOnWorkerThread();
}
void Dispatch(WorkerStatus aFailStatus, ErrorResult& aRv) {
WorkerMainThreadRunnable::Dispatch(aFailStatus, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
if (NS_FAILED(mErrorCode)) {
aRv.Throw(mErrorCode);
}
}
protected:
virtual ~WorkerThreadProxySyncRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) = 0;
private:
virtual bool MainThreadRun() override;
};
class SendRunnable final : public WorkerThreadProxySyncRunnable {
RefPtr<BlobImpl> mBlobImpl;
nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
bool mHasUploadListeners;
public:
SendRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
BlobImpl* aBlobImpl)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mBlobImpl(aBlobImpl),
mHasUploadListeners(false) {}
void SetHaveUploadListeners(bool aHasUploadListeners) {
mHasUploadListeners = aHasUploadListeners;
}
void SetSyncLoopTarget(nsIEventTarget* aSyncLoopTarget) {
mSyncLoopTarget = aSyncLoopTarget;
}
private:
~SendRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override;
};
namespace {
enum {
STRING_abort = 0,
STRING_error,
STRING_load,
STRING_loadstart,
STRING_progress,
STRING_timeout,
STRING_loadend,
STRING_readystatechange,
STRING_COUNT,
STRING_LAST_XHR = STRING_readystatechange,
STRING_LAST_EVENTTARGET = STRING_loadend
};
static_assert(STRING_LAST_XHR >= STRING_LAST_EVENTTARGET, "Bad string setup!");
static_assert(STRING_LAST_XHR == STRING_COUNT - 1, "Bad string setup!");
const char* const sEventStrings[] = {
// XMLHttpRequestEventTarget event types, supported by both XHR and Upload.
"abort",
"error",
"load",
"loadstart",
"progress",
"timeout",
"loadend",
// XMLHttpRequest event types, supported only by XHR.
"readystatechange",
};
static_assert(MOZ_ARRAY_LENGTH(sEventStrings) == STRING_COUNT,
"Bad string count!");
class MainThreadProxyRunnable : public MainThreadWorkerSyncRunnable {
protected:
RefPtr<Proxy> mProxy;
MainThreadProxyRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy)
: MainThreadWorkerSyncRunnable(aWorkerPrivate, aProxy->GetEventTarget()),
mProxy(aProxy) {
MOZ_ASSERT(aProxy);
}
virtual ~MainThreadProxyRunnable() = default;
};
class XHRUnpinRunnable final : public MainThreadWorkerControlRunnable {
XMLHttpRequestWorker* mXMLHttpRequestPrivate;
public:
XHRUnpinRunnable(WorkerPrivate* aWorkerPrivate,
XMLHttpRequestWorker* aXHRPrivate)
: MainThreadWorkerControlRunnable(aWorkerPrivate),
mXMLHttpRequestPrivate(aXHRPrivate) {
MOZ_ASSERT(aXHRPrivate);
}
private:
~XHRUnpinRunnable() = default;
bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
if (mXMLHttpRequestPrivate->SendInProgress()) {
mXMLHttpRequestPrivate->Unpin();
}
return true;
}
};
class AsyncTeardownRunnable final : public Runnable {
RefPtr<Proxy> mProxy;
public:
explicit AsyncTeardownRunnable(Proxy* aProxy)
: Runnable("dom::AsyncTeardownRunnable"), mProxy(aProxy) {
MOZ_ASSERT(aProxy);
}
private:
~AsyncTeardownRunnable() = default;
NS_IMETHOD
Run() override {
AssertIsOnMainThread();
// This means the XHR was GC'd, so we can't be pinned, and we don't need to
// try to unpin.
mProxy->Teardown(/* aSendUnpin */ false);
mProxy = nullptr;
return NS_OK;
}
};
class LoadStartDetectionRunnable final : public Runnable,
public nsIDOMEventListener {
WorkerPrivate* mWorkerPrivate;
RefPtr<Proxy> mProxy;
RefPtr<XMLHttpRequest> mXHR;
XMLHttpRequestWorker* mXMLHttpRequestPrivate;
nsString mEventType;
uint32_t mChannelId;
bool mReceivedLoadStart;
class ProxyCompleteRunnable final : public MainThreadProxyRunnable {
XMLHttpRequestWorker* mXMLHttpRequestPrivate;
uint32_t mChannelId;
public:
ProxyCompleteRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
XMLHttpRequestWorker* aXHRPrivate,
uint32_t aChannelId)
: MainThreadProxyRunnable(aWorkerPrivate, aProxy),
mXMLHttpRequestPrivate(aXHRPrivate),
mChannelId(aChannelId) {}
private:
~ProxyCompleteRunnable() = default;
virtual bool WorkerRun(JSContext* aCx,
WorkerPrivate* aWorkerPrivate) override {
if (mChannelId != mProxy->mOuterChannelId) {
// Threads raced, this event is now obsolete.
return true;
}
if (mSyncLoopTarget) {
aWorkerPrivate->StopSyncLoop(mSyncLoopTarget, NS_OK);
}
if (mXMLHttpRequestPrivate->SendInProgress()) {
mXMLHttpRequestPrivate->Unpin();
}
return true;
}
nsresult Cancel() override { return Run(); }
};
public:
LoadStartDetectionRunnable(Proxy* aProxy, XMLHttpRequestWorker* aXHRPrivate)
: Runnable("dom::LoadStartDetectionRunnable"),
mWorkerPrivate(aProxy->mWorkerPrivate),
mProxy(aProxy),
mXHR(aProxy->mXHR),
mXMLHttpRequestPrivate(aXHRPrivate),
mChannelId(mProxy->mInnerChannelId),
mReceivedLoadStart(false) {
AssertIsOnMainThread();
mEventType.AssignASCII(sEventStrings[STRING_loadstart]);
}
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIRUNNABLE
NS_DECL_NSIDOMEVENTLISTENER
bool RegisterAndDispatch() {
AssertIsOnMainThread();
if (NS_FAILED(mXHR->AddEventListener(mEventType, this, false, false))) {
NS_WARNING("Failed to add event listener!");
return false;
}
return NS_SUCCEEDED(mWorkerPrivate->DispatchToMainThread(this));
}
private:
~LoadStartDetectionRunnable() { AssertIsOnMainThread(); }
};
class EventRunnable final : public MainThreadProxyRunnable {
nsString mType;
UniquePtr<XMLHttpRequestWorker::ResponseData> mResponseData;
nsString mResponseURL;
nsCString mStatusText;
uint64_t mLoaded;
uint64_t mTotal;
uint32_t mEventStreamId;
uint32_t mStatus;
uint16_t mReadyState;
bool mUploadEvent;
bool mProgressEvent;
bool mLengthComputable;
nsresult mStatusResult;
nsresult mErrorDetail;
// mScopeObj is used in PreDispatch only. We init it in our constructor, and
// reset() in PreDispatch, to ensure that it's not still linked into the
// runtime once we go off-thread.
JS::PersistentRooted<JSObject*> mScopeObj;
public:
EventRunnable(Proxy* aProxy, bool aUploadEvent, const nsString& aType,
bool aLengthComputable, uint64_t aLoaded, uint64_t aTotal,
JS::Handle<JSObject*> aScopeObj)
: MainThreadProxyRunnable(aProxy->mWorkerPrivate, aProxy),
mType(aType),
mResponseData(new XMLHttpRequestWorker::ResponseData()),
mLoaded(aLoaded),
mTotal(aTotal),
mEventStreamId(aProxy->mInnerEventStreamId),
mStatus(0),
mReadyState(0),
mUploadEvent(aUploadEvent),
mProgressEvent(true),
mLengthComputable(aLengthComputable),
mStatusResult(NS_OK),
mErrorDetail(NS_OK),
mScopeObj(RootingCx(), aScopeObj) {}
EventRunnable(Proxy* aProxy, bool aUploadEvent, const nsString& aType,
JS::Handle<JSObject*> aScopeObj)
: MainThreadProxyRunnable(aProxy->mWorkerPrivate, aProxy),
mType(aType),
mResponseData(new XMLHttpRequestWorker::ResponseData()),
mLoaded(0),
mTotal(0),
mEventStreamId(aProxy->mInnerEventStreamId),
mStatus(0),
mReadyState(0),
mUploadEvent(aUploadEvent),
mProgressEvent(false),
mLengthComputable(0),
mStatusResult(NS_OK),
mErrorDetail(NS_OK),
mScopeObj(RootingCx(), aScopeObj) {}
private:
~EventRunnable() = default;
bool PreDispatch(WorkerPrivate* /* unused */) final;
bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override;
};
class SyncTeardownRunnable final : public WorkerThreadProxySyncRunnable {
public:
SyncTeardownRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy) {}
private:
~SyncTeardownRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->Teardown(/* aSendUnpin */ true);
MOZ_ASSERT(!mProxy->mSyncLoopTarget);
}
};
class SetBackgroundRequestRunnable final
: public WorkerThreadProxySyncRunnable {
bool mValue;
public:
SetBackgroundRequestRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
bool aValue)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), mValue(aValue) {}
private:
~SetBackgroundRequestRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
// XXXedgar, do we intend to ignore the errors?
mProxy->mXHR->SetMozBackgroundRequest(mValue, aRv);
}
};
class SetWithCredentialsRunnable final : public WorkerThreadProxySyncRunnable {
bool mValue;
public:
SetWithCredentialsRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
bool aValue)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), mValue(aValue) {}
private:
~SetWithCredentialsRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->SetWithCredentials(mValue, aRv);
}
};
class SetResponseTypeRunnable final : public WorkerThreadProxySyncRunnable {
XMLHttpRequestResponseType mResponseType;
public:
SetResponseTypeRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
XMLHttpRequestResponseType aResponseType)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mResponseType(aResponseType) {}
XMLHttpRequestResponseType ResponseType() { return mResponseType; }
private:
~SetResponseTypeRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->SetResponseTypeRaw(mResponseType);
mResponseType = mProxy->mXHR->ResponseType();
}
};
class SetTimeoutRunnable final : public WorkerThreadProxySyncRunnable {
uint32_t mTimeout;
public:
SetTimeoutRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
uint32_t aTimeout)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mTimeout(aTimeout) {}
private:
~SetTimeoutRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->SetTimeout(mTimeout, aRv);
}
};
class AbortRunnable final : public WorkerThreadProxySyncRunnable {
public:
AbortRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy) {}
private:
~AbortRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override;
};
class GetAllResponseHeadersRunnable final
: public WorkerThreadProxySyncRunnable {
nsCString& mResponseHeaders;
public:
GetAllResponseHeadersRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
nsCString& aResponseHeaders)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mResponseHeaders(aResponseHeaders) {}
private:
~GetAllResponseHeadersRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->GetAllResponseHeaders(mResponseHeaders, aRv);
}
};
class GetResponseHeaderRunnable final : public WorkerThreadProxySyncRunnable {
const nsCString mHeader;
nsCString& mValue;
public:
GetResponseHeaderRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsACString& aHeader, nsCString& aValue)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mHeader(aHeader),
mValue(aValue) {}
private:
~GetResponseHeaderRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->GetResponseHeader(mHeader, mValue, aRv);
}
};
class OpenRunnable final : public WorkerThreadProxySyncRunnable {
nsCString mMethod;
nsString mURL;
Optional<nsAString> mUser;
nsString mUserStr;
Optional<nsAString> mPassword;
nsString mPasswordStr;
bool mBackgroundRequest;
bool mWithCredentials;
uint32_t mTimeout;
XMLHttpRequestResponseType mResponseType;
const nsString mMimeTypeOverride;
// Remember the worker thread's stack when the XHR was opened, so that it can
// be passed on to the net monitor.
UniquePtr<SerializedStackHolder> mOriginStack;
// Remember the worker thread's stack when the XHR was opened for profiling
// purposes.
UniquePtr<ProfileChunkedBuffer> mSource;
public:
OpenRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsACString& aMethod, const nsAString& aURL,
const Optional<nsAString>& aUser,
const Optional<nsAString>& aPassword, bool aBackgroundRequest,
bool aWithCredentials, uint32_t aTimeout,
XMLHttpRequestResponseType aResponseType,
const nsString& aMimeTypeOverride,
UniquePtr<SerializedStackHolder> aOriginStack,
UniquePtr<ProfileChunkedBuffer> aSource = nullptr)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mMethod(aMethod),
mURL(aURL),
mBackgroundRequest(aBackgroundRequest),
mWithCredentials(aWithCredentials),
mTimeout(aTimeout),
mResponseType(aResponseType),
mMimeTypeOverride(aMimeTypeOverride),
mOriginStack(std::move(aOriginStack)),
mSource(std::move(aSource)) {
if (aUser.WasPassed()) {
mUserStr = aUser.Value();
mUser = &mUserStr;
}
if (aPassword.WasPassed()) {
mPasswordStr = aPassword.Value();
mPassword = &mPasswordStr;
}
}
private:
~OpenRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
WorkerPrivate* oldWorker = mProxy->mWorkerPrivate;
mProxy->mWorkerPrivate = mWorkerPrivate;
MainThreadRunInternal(aRv);
mProxy->mWorkerPrivate = oldWorker;
}
void MainThreadRunInternal(ErrorResult& aRv);
};
class SetRequestHeaderRunnable final : public WorkerThreadProxySyncRunnable {
nsCString mHeader;
nsCString mValue;
public:
SetRequestHeaderRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsACString& aHeader, const nsACString& aValue)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mHeader(aHeader),
mValue(aValue) {}
private:
~SetRequestHeaderRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->SetRequestHeader(mHeader, mValue, aRv);
}
};
class OverrideMimeTypeRunnable final : public WorkerThreadProxySyncRunnable {
nsString mMimeType;
public:
OverrideMimeTypeRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsAString& aMimeType)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mMimeType(aMimeType) {}
private:
~OverrideMimeTypeRunnable() = default;
virtual void RunOnMainThread(ErrorResult& aRv) override {
mProxy->mXHR->OverrideMimeType(mMimeType, aRv);
}
};
class AutoUnpinXHR {
XMLHttpRequestWorker* mXMLHttpRequestPrivate;
public:
explicit AutoUnpinXHR(XMLHttpRequestWorker* aXMLHttpRequestPrivate)
: mXMLHttpRequestPrivate(aXMLHttpRequestPrivate) {
MOZ_ASSERT(aXMLHttpRequestPrivate);
}
~AutoUnpinXHR() {
if (mXMLHttpRequestPrivate) {
mXMLHttpRequestPrivate->Unpin();
}
}
void Clear() { mXMLHttpRequestPrivate = nullptr; }
};
} // namespace
bool Proxy::Init() {
AssertIsOnMainThread();
MOZ_ASSERT(mWorkerPrivate);
if (mXHR) {
return true;
}
nsPIDOMWindowInner* ownerWindow = mWorkerPrivate->GetWindow();
if (ownerWindow && !ownerWindow->IsCurrentInnerWindow()) {
NS_WARNING("Window has navigated, cannot create XHR here.");
return false;
}
mXHR = new XMLHttpRequestMainThread(ownerWindow ? ownerWindow->AsGlobal()
: nullptr);
mXHR->Construct(mWorkerPrivate->GetPrincipal(),
mWorkerPrivate->CookieJarSettings(), true,
mWorkerPrivate->GetBaseURI(), mWorkerPrivate->GetLoadGroup(),
mWorkerPrivate->GetPerformanceStorage(),
mWorkerPrivate->CSPEventListener());
mXHR->SetParameters(mMozAnon, mMozSystem);
mXHR->SetClientInfoAndController(mClientInfo, mController);
ErrorResult rv;
mXHRUpload = mXHR->GetUpload(rv);
if (NS_WARN_IF(rv.Failed())) {
mXHR = nullptr;
return false;
}
if (!AddRemoveEventListeners(false, true)) {
mXHR = nullptr;
mXHRUpload = nullptr;
return false;
}
return true;
}
void Proxy::Teardown(bool aSendUnpin) {
AssertIsOnMainThread();
if (mXHR) {
Reset();
// NB: We are intentionally dropping events coming from xhr.abort on the
// floor.
AddRemoveEventListeners(false, false);
ErrorResult rv;
mXHR->Abort(rv);
if (NS_WARN_IF(rv.Failed())) {
rv.SuppressException();
}
if (mOutstandingSendCount) {
if (aSendUnpin) {
RefPtr<XHRUnpinRunnable> runnable =
new XHRUnpinRunnable(mWorkerPrivate, mXMLHttpRequestPrivate);
MOZ_ALWAYS_TRUE(runnable->Dispatch());
}
if (mSyncLoopTarget) {
// We have an unclosed sync loop. Fix that now.
RefPtr<MainThreadStopSyncLoopRunnable> runnable =
new MainThreadStopSyncLoopRunnable(
mWorkerPrivate, std::move(mSyncLoopTarget), NS_ERROR_FAILURE);
MOZ_ALWAYS_TRUE(runnable->Dispatch());
}
mOutstandingSendCount = 0;
}
mWorkerPrivate = nullptr;
mXHRUpload = nullptr;
mXHR = nullptr;
}
MOZ_ASSERT(!mWorkerPrivate);
MOZ_ASSERT(!mSyncLoopTarget);
// If there are rare edge cases left that violate our invariants
// just ensure that they won't harm us too much.
mWorkerPrivate = nullptr;
mSyncLoopTarget = nullptr;
}
bool Proxy::AddRemoveEventListeners(bool aUpload, bool aAdd) {
AssertIsOnMainThread();
NS_ASSERTION(!aUpload || (mUploadEventListenersAttached && !aAdd) ||
(!mUploadEventListenersAttached && aAdd),
"Messed up logic for upload listeners!");
RefPtr<DOMEventTargetHelper> targetHelper =
aUpload ? static_cast<XMLHttpRequestUpload*>(mXHRUpload.get())
: static_cast<XMLHttpRequestEventTarget*>(mXHR.get());
MOZ_ASSERT(targetHelper, "This should never fail!");
uint32_t lastEventType = aUpload ? STRING_LAST_EVENTTARGET : STRING_LAST_XHR;
nsAutoString eventType;
for (uint32_t index = 0; index <= lastEventType; index++) {
eventType = NS_ConvertASCIItoUTF16(sEventStrings[index]);
if (aAdd) {
if (NS_FAILED(targetHelper->AddEventListener(eventType, this, false))) {
return false;
}
} else {
targetHelper->RemoveEventListener(eventType, this, false);
}
}
if (aUpload) {
mUploadEventListenersAttached = aAdd;
}
return true;
}
NS_IMPL_ISUPPORTS(Proxy, nsIDOMEventListener)
NS_IMETHODIMP
Proxy::HandleEvent(Event* aEvent) {
AssertIsOnMainThread();
if (!mWorkerPrivate || !mXMLHttpRequestPrivate) {
NS_ERROR("Shouldn't get here!");
return NS_OK;
}
nsAutoString type;
aEvent->GetType(type);
bool isUploadTarget = mXHR != aEvent->GetTarget();
ProgressEvent* progressEvent = aEvent->AsProgressEvent();
if (mInOpen && type.EqualsASCII(sEventStrings[STRING_readystatechange])) {
if (mXHR->ReadyState() == 1) {
mInnerEventStreamId++;
}
}
{
AutoJSAPI jsapi;
JSObject* junkScope = xpc::UnprivilegedJunkScope(fallible);
if (!junkScope || !jsapi.Init(junkScope)) {
return NS_ERROR_FAILURE;
}
JSContext* cx = jsapi.cx();
JS::Rooted<JS::Value> value(cx);
if (!GetOrCreateDOMReflectorNoWrap(cx, mXHR, &value)) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JSObject*> scope(cx, &value.toObject());
RefPtr<EventRunnable> runnable;
if (progressEvent) {
if (!mIsSyncXHR || !type.EqualsASCII(sEventStrings[STRING_progress])) {
runnable = new EventRunnable(
this, isUploadTarget, type, progressEvent->LengthComputable(),
progressEvent->Loaded(), progressEvent->Total(), scope);
}
} else {
runnable = new EventRunnable(this, isUploadTarget, type, scope);
}
if (runnable) {
runnable->Dispatch();
}
}
if (!isUploadTarget) {
if (type.EqualsASCII(sEventStrings[STRING_loadstart])) {
mMainThreadSeenLoadStart = true;
} else if (mMainThreadSeenLoadStart &&
type.EqualsASCII(sEventStrings[STRING_loadend])) {
mMainThreadSeenLoadStart = false;
RefPtr<LoadStartDetectionRunnable> runnable =
new LoadStartDetectionRunnable(this, mXMLHttpRequestPrivate);
if (!runnable->RegisterAndDispatch()) {
NS_WARNING("Failed to dispatch LoadStartDetectionRunnable!");
}
}
}
return NS_OK;
}
NS_IMPL_ISUPPORTS_INHERITED(LoadStartDetectionRunnable, Runnable,
nsIDOMEventListener)
NS_IMETHODIMP
LoadStartDetectionRunnable::Run() {
AssertIsOnMainThread();
mXHR->RemoveEventListener(mEventType, this, false);
if (!mReceivedLoadStart) {
if (mProxy->mOutstandingSendCount > 1) {
mProxy->mOutstandingSendCount--;
} else if (mProxy->mOutstandingSendCount == 1) {
mProxy->Reset();
RefPtr<ProxyCompleteRunnable> runnable = new ProxyCompleteRunnable(
mWorkerPrivate, mProxy, mXMLHttpRequestPrivate, mChannelId);
if (runnable->Dispatch()) {
mProxy->mWorkerPrivate = nullptr;
mProxy->mSyncLoopTarget = nullptr;
mProxy->mOutstandingSendCount--;
}
}
}
mProxy = nullptr;
mXHR = nullptr;
mXMLHttpRequestPrivate = nullptr;
return NS_OK;
}
NS_IMETHODIMP
LoadStartDetectionRunnable::HandleEvent(Event* aEvent) {
AssertIsOnMainThread();
#ifdef DEBUG
{
nsAutoString type;
aEvent->GetType(type);
MOZ_ASSERT(type == mEventType);
}
#endif
mReceivedLoadStart = true;
return NS_OK;
}