forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScriptLoader.cpp
2496 lines (2024 loc) · 81.9 KB
/
ScriptLoader.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 "ScriptLoader.h"
#include <algorithm>
#include <type_traits>
#include "nsIChannel.h"
#include "nsIContentPolicy.h"
#include "nsIContentSecurityPolicy.h"
#include "nsICookieJarSettings.h"
#include "nsIDocShell.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIInputStreamPump.h"
#include "nsIIOService.h"
#include "nsIOService.h"
#include "nsIPrincipal.h"
#include "nsIProtocolHandler.h"
#include "nsIScriptError.h"
#include "nsIScriptSecurityManager.h"
#include "nsIStreamLoader.h"
#include "nsIStreamListenerTee.h"
#include "nsIThreadRetargetableRequest.h"
#include "nsIURI.h"
#include "nsIXPConnect.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/CompilationAndEvaluation.h"
#include "js/Exception.h"
#include "js/SourceText.h"
#include "nsError.h"
#include "nsComponentManagerUtils.h"
#include "nsContentPolicyUtils.h"
#include "nsContentUtils.h"
#include "nsDocShellCID.h"
#include "nsJSEnvironment.h"
#include "nsNetUtil.h"
#include "nsIPipe.h"
#include "nsIOutputStream.h"
#include "nsPrintfCString.h"
#include "nsString.h"
#include "nsStreamUtils.h"
#include "nsTArray.h"
#include "nsThreadUtils.h"
#include "nsXPCOM.h"
#include "xpcpublic.h"
#include "mozilla/ArrayAlgorithm.h"
#include "mozilla/Assertions.h"
#include "mozilla/LoadContext.h"
#include "mozilla/Maybe.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/dom/BlobURLProtocolHandler.h"
#include "mozilla/dom/CacheBinding.h"
#include "mozilla/dom/cache/CacheTypes.h"
#include "mozilla/dom/cache/Cache.h"
#include "mozilla/dom/cache/CacheStorage.h"
#include "mozilla/dom/ChannelInfo.h"
#include "mozilla/dom/ClientChannelHelper.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/InternalResponse.h"
#include "mozilla/dom/nsCSPService.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "mozilla/dom/PerformanceStorage.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/Response.h"
#include "mozilla/dom/ScriptLoader.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SerializedStackHolder.h"
#include "mozilla/dom/SRILogHelper.h"
#include "mozilla/dom/SerializedStackHolder.h"
#include "mozilla/dom/ServiceWorkerBinding.h"
#include "mozilla/dom/ServiceWorkerManager.h"
#include "mozilla/Result.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/UniquePtr.h"
#include "Principal.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WorkerScope.h"
#define MAX_CONCURRENT_SCRIPTS 1000
using mozilla::dom::cache::Cache;
using mozilla::dom::cache::CacheStorage;
using mozilla::ipc::PrincipalInfo;
namespace mozilla {
namespace dom {
namespace {
nsIURI* GetBaseURI(bool aIsMainScript, WorkerPrivate* aWorkerPrivate) {
MOZ_ASSERT(aWorkerPrivate);
nsIURI* baseURI;
WorkerPrivate* parentWorker = aWorkerPrivate->GetParent();
if (aIsMainScript) {
if (parentWorker) {
baseURI = parentWorker->GetBaseURI();
NS_ASSERTION(baseURI, "Should have been set already!");
} else {
// May be null.
baseURI = aWorkerPrivate->GetBaseURI();
}
} else {
baseURI = aWorkerPrivate->GetBaseURI();
NS_ASSERTION(baseURI, "Should have been set already!");
}
return baseURI;
}
nsresult ConstructURI(const nsAString& aScriptURL, nsIURI* baseURI,
Document* parentDoc, bool aDefaultURIEncoding,
nsIURI** aResult) {
nsresult rv;
if (aDefaultURIEncoding) {
rv = NS_NewURI(aResult, aScriptURL, nullptr, baseURI);
} else {
rv = nsContentUtils::NewURIWithDocumentCharset(aResult, aScriptURL,
parentDoc, baseURI);
}
if (NS_FAILED(rv)) {
return NS_ERROR_DOM_SYNTAX_ERR;
}
return NS_OK;
}
nsresult ChannelFromScriptURL(
nsIPrincipal* principal, Document* parentDoc, WorkerPrivate* aWorkerPrivate,
nsILoadGroup* loadGroup, nsIIOService* ios,
nsIScriptSecurityManager* secMan, nsIURI* aScriptURL,
const Maybe<ClientInfo>& aClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController, bool aIsMainScript,
WorkerScriptType aWorkerScriptType,
nsContentPolicyType aMainScriptContentPolicyType, nsLoadFlags aLoadFlags,
nsICookieJarSettings* aCookieJarSettings, nsIReferrerInfo* aReferrerInfo,
nsIChannel** aChannel) {
AssertIsOnMainThread();
nsresult rv;
nsCOMPtr<nsIURI> uri = aScriptURL;
// If we have the document, use it. Unfortunately, for dedicated workers
// 'parentDoc' ends up being the parent document, which is not the document
// that we want to use. So make sure to avoid using 'parentDoc' in that
// situation.
if (parentDoc && parentDoc->NodePrincipal() != principal) {
parentDoc = nullptr;
}
uint32_t secFlags =
aIsMainScript ? nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
: nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT;
bool inheritAttrs = nsContentUtils::ChannelShouldInheritPrincipal(
principal, uri, true /* aInheritForAboutBlank */,
false /* aForceInherit */);
bool isData = uri->SchemeIs("data");
if (inheritAttrs && !isData) {
secFlags |= nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
}
if (aWorkerScriptType == DebuggerScript) {
// A DebuggerScript needs to be a local resource like chrome: or resource:
bool isUIResource = false;
rv = NS_URIChainHasFlags(uri, nsIProtocolHandler::URI_IS_UI_RESOURCE,
&isUIResource);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (!isUIResource) {
return NS_ERROR_DOM_SECURITY_ERR;
}
secFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
}
// Note: this is for backwards compatibility and goes against spec.
// We should find a better solution.
if (aIsMainScript && isData) {
secFlags = nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL;
}
nsContentPolicyType contentPolicyType =
aIsMainScript ? aMainScriptContentPolicyType
: nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS;
// The main service worker script should never be loaded over the network
// in this path. It should always be offlined by ServiceWorkerScriptCache.
// We assert here since this error should also be caught by the runtime
// check in CacheScriptLoader.
//
// Note, if we ever allow service worker scripts to be loaded from network
// here we need to configure the channel properly. For example, it must
// not allow redirects.
MOZ_DIAGNOSTIC_ASSERT(contentPolicyType !=
nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER);
nsCOMPtr<nsIChannel> channel;
if (parentDoc) {
rv = NS_NewChannel(getter_AddRefs(channel), uri, parentDoc, secFlags,
contentPolicyType,
nullptr, // aPerformanceStorage
loadGroup,
nullptr, // aCallbacks
aLoadFlags, ios);
NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_SECURITY_ERR);
} else {
// We must have a loadGroup with a load context for the principal to
// traverse the channel correctly.
MOZ_ASSERT(loadGroup);
MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(loadGroup, principal));
RefPtr<PerformanceStorage> performanceStorage;
nsCOMPtr<nsICSPEventListener> cspEventListener;
if (aWorkerPrivate && !aIsMainScript) {
performanceStorage = aWorkerPrivate->GetPerformanceStorage();
cspEventListener = aWorkerPrivate->CSPEventListener();
}
if (aClientInfo.isSome()) {
rv = NS_NewChannel(getter_AddRefs(channel), uri, principal,
aClientInfo.ref(), aController, secFlags,
contentPolicyType, aCookieJarSettings,
performanceStorage, loadGroup, nullptr, // aCallbacks
aLoadFlags, ios);
} else {
rv = NS_NewChannel(getter_AddRefs(channel), uri, principal, secFlags,
contentPolicyType, aCookieJarSettings,
performanceStorage, loadGroup, nullptr, // aCallbacks
aLoadFlags, ios);
}
NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_SECURITY_ERR);
if (cspEventListener) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
rv = loadInfo->SetCspEventListener(cspEventListener);
NS_ENSURE_SUCCESS(rv, rv);
}
}
if (aReferrerInfo) {
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel);
if (httpChannel) {
rv = httpChannel->SetReferrerInfo(aReferrerInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
}
channel.forget(aChannel);
return rv;
}
struct ScriptLoadInfo {
ScriptLoadInfo() {
MOZ_ASSERT(mScriptIsUTF8 == false, "set by member initializer");
MOZ_ASSERT(mScriptLength == 0, "set by member initializer");
mScript.mUTF16 = nullptr;
}
~ScriptLoadInfo() {
if (void* data = mScriptIsUTF8 ? static_cast<void*>(mScript.mUTF8)
: static_cast<void*>(mScript.mUTF16)) {
js_free(data);
}
}
nsString mURL;
// This full URL string is populated only if this object is used in a
// ServiceWorker.
nsString mFullURL;
// This promise is set only when the script is for a ServiceWorker but
// it's not in the cache yet. The promise is resolved when the full body is
// stored into the cache. mCachePromise will be set to nullptr after
// resolution.
RefPtr<Promise> mCachePromise;
// The reader stream the cache entry should be filled from, for those cases
// when we're going to have an mCachePromise.
nsCOMPtr<nsIInputStream> mCacheReadStream;
nsCOMPtr<nsIChannel> mChannel;
Maybe<ClientInfo> mReservedClientInfo;
nsresult mLoadResult = NS_ERROR_NOT_INITIALIZED;
// If |mScriptIsUTF8|, then |mUTF8| is active, otherwise |mUTF16| is active.
union {
char16_t* mUTF16;
Utf8Unit* mUTF8;
} mScript;
size_t mScriptLength = 0; // in code units
bool mScriptIsUTF8 = false;
bool ScriptTextIsNull() const {
return mScriptIsUTF8 ? mScript.mUTF8 == nullptr : mScript.mUTF16 == nullptr;
}
void InitUTF8Script() {
MOZ_ASSERT(ScriptTextIsNull());
MOZ_ASSERT(mScriptLength == 0);
mScriptIsUTF8 = true;
mScript.mUTF8 = nullptr;
mScriptLength = 0;
}
void InitUTF16Script() {
MOZ_ASSERT(ScriptTextIsNull());
MOZ_ASSERT(mScriptLength == 0);
mScriptIsUTF8 = false;
mScript.mUTF16 = nullptr;
mScriptLength = 0;
}
bool mLoadingFinished = false;
bool mExecutionScheduled = false;
bool mExecutionResult = false;
Maybe<nsString> mSourceMapURL;
enum CacheStatus {
// By default a normal script is just loaded from the network. But for
// ServiceWorkers, we have to check if the cache contains the script and
// load it from the cache.
Uncached,
WritingToCache,
ReadingFromCache,
// This script has been loaded from the ServiceWorker cache.
Cached,
// This script must be stored in the ServiceWorker cache.
ToBeCached,
// Something went wrong or the worker went away.
Cancel
};
CacheStatus mCacheStatus = Uncached;
nsLoadFlags mLoadFlags = nsIRequest::LOAD_NORMAL;
Maybe<bool> mMutedErrorFlag;
bool Finished() const {
return mLoadingFinished && !mCachePromise && !mChannel;
}
};
class ScriptLoaderRunnable;
class ScriptExecutorRunnable final : public MainThreadWorkerSyncRunnable {
ScriptLoaderRunnable& mScriptLoader;
const bool mIsWorkerScript;
const Span<ScriptLoadInfo> mLoadInfosAlreadyExecuted, mLoadInfosToExecute;
public:
ScriptExecutorRunnable(ScriptLoaderRunnable& aScriptLoader,
nsIEventTarget* aSyncLoopTarget, bool aIsWorkerScript,
Span<ScriptLoadInfo> aLoadInfosAlreadyExecuted,
Span<ScriptLoadInfo> aLoadInfosToExecute);
private:
~ScriptExecutorRunnable() = default;
virtual bool IsDebuggerRunnable() const override;
virtual bool PreRun(WorkerPrivate* aWorkerPrivate) override;
virtual bool WorkerRun(JSContext* aCx,
WorkerPrivate* aWorkerPrivate) override;
virtual void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
bool aRunResult) override;
nsresult Cancel() override;
void ShutdownScriptLoader(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
bool aResult, bool aMutedError);
void LogExceptionToConsole(JSContext* aCx, WorkerPrivate* WorkerPrivate);
bool AllScriptsExecutable() const;
};
class CacheScriptLoader;
class CacheCreator final : public PromiseNativeHandler {
public:
NS_DECL_ISUPPORTS
explicit CacheCreator(WorkerPrivate* aWorkerPrivate)
: mCacheName(aWorkerPrivate->ServiceWorkerCacheName()),
mOriginAttributes(aWorkerPrivate->GetOriginAttributes()) {
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
AssertIsOnMainThread();
}
void AddLoader(MovingNotNull<RefPtr<CacheScriptLoader>> aLoader) {
AssertIsOnMainThread();
MOZ_ASSERT(!mCacheStorage);
mLoaders.AppendElement(std::move(aLoader));
}
virtual void ResolvedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue) override;
virtual void RejectedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue) override;
// Try to load from cache with aPrincipal used for cache access.
nsresult Load(nsIPrincipal* aPrincipal);
Cache* Cache_() const {
AssertIsOnMainThread();
MOZ_ASSERT(mCache);
return mCache;
}
nsIGlobalObject* Global() const {
AssertIsOnMainThread();
MOZ_ASSERT(mSandboxGlobalObject);
return mSandboxGlobalObject;
}
void DeleteCache();
private:
~CacheCreator() = default;
nsresult CreateCacheStorage(nsIPrincipal* aPrincipal);
void FailLoaders(nsresult aRv);
RefPtr<Cache> mCache;
RefPtr<CacheStorage> mCacheStorage;
nsCOMPtr<nsIGlobalObject> mSandboxGlobalObject;
nsTArray<NotNull<RefPtr<CacheScriptLoader>>> mLoaders;
nsString mCacheName;
OriginAttributes mOriginAttributes;
};
NS_IMPL_ISUPPORTS0(CacheCreator)
class CacheScriptLoader final : public PromiseNativeHandler,
public nsIStreamLoaderObserver {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMLOADEROBSERVER
CacheScriptLoader(WorkerPrivate* aWorkerPrivate, ScriptLoadInfo& aLoadInfo,
bool aIsWorkerScript, ScriptLoaderRunnable* aRunnable)
: mLoadInfo(aLoadInfo),
mRunnable(aRunnable),
mIsWorkerScript(aIsWorkerScript),
mFailed(false),
mState(aWorkerPrivate->GetServiceWorkerDescriptor().State()) {
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
mMainThreadEventTarget = aWorkerPrivate->MainThreadEventTarget();
MOZ_ASSERT(mMainThreadEventTarget);
mBaseURI = GetBaseURI(mIsWorkerScript, aWorkerPrivate);
AssertIsOnMainThread();
}
void Fail(nsresult aRv);
void Load(Cache* aCache);
virtual void ResolvedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue) override;
virtual void RejectedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue) override;
private:
~CacheScriptLoader() { AssertIsOnMainThread(); }
ScriptLoadInfo& mLoadInfo;
const RefPtr<ScriptLoaderRunnable> mRunnable;
const bool mIsWorkerScript;
bool mFailed;
const ServiceWorkerState mState;
nsCOMPtr<nsIInputStreamPump> mPump;
nsCOMPtr<nsIURI> mBaseURI;
mozilla::dom::ChannelInfo mChannelInfo;
UniquePtr<PrincipalInfo> mPrincipalInfo;
nsCString mCSPHeaderValue;
nsCString mCSPReportOnlyHeaderValue;
nsCString mReferrerPolicyHeaderValue;
nsCOMPtr<nsIEventTarget> mMainThreadEventTarget;
};
NS_IMPL_ISUPPORTS(CacheScriptLoader, nsIStreamLoaderObserver)
class CachePromiseHandler final : public PromiseNativeHandler {
public:
NS_DECL_ISUPPORTS
CachePromiseHandler(ScriptLoaderRunnable* aRunnable,
ScriptLoadInfo& aLoadInfo)
: mRunnable(aRunnable), mLoadInfo(aLoadInfo) {
AssertIsOnMainThread();
MOZ_ASSERT(mRunnable);
}
virtual void ResolvedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue) override;
virtual void RejectedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue) override;
private:
~CachePromiseHandler() { AssertIsOnMainThread(); }
RefPtr<ScriptLoaderRunnable> mRunnable;
ScriptLoadInfo& mLoadInfo;
};
NS_IMPL_ISUPPORTS0(CachePromiseHandler)
class LoaderListener final : public nsIStreamLoaderObserver,
public nsIRequestObserver {
public:
NS_DECL_ISUPPORTS
LoaderListener(ScriptLoaderRunnable* aRunnable, ScriptLoadInfo& aLoadInfo)
: mRunnable(aRunnable), mLoadInfo(aLoadInfo) {
MOZ_ASSERT(mRunnable);
}
NS_IMETHOD
OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
nsresult aStatus, uint32_t aStringLen,
const uint8_t* aString) override;
NS_IMETHOD
OnStartRequest(nsIRequest* aRequest) override;
NS_IMETHOD
OnStopRequest(nsIRequest* aRequest, nsresult aStatusCode) override {
// Nothing to do here!
return NS_OK;
}
private:
~LoaderListener() = default;
RefPtr<ScriptLoaderRunnable> mRunnable;
ScriptLoadInfo& mLoadInfo;
};
NS_IMPL_ISUPPORTS(LoaderListener, nsIStreamLoaderObserver, nsIRequestObserver)
class ScriptResponseHeaderProcessor final : public nsIRequestObserver {
public:
NS_DECL_ISUPPORTS
ScriptResponseHeaderProcessor(WorkerPrivate* aWorkerPrivate,
bool aIsMainScript)
: mWorkerPrivate(aWorkerPrivate), mIsMainScript(aIsMainScript) {
AssertIsOnMainThread();
}
NS_IMETHOD OnStartRequest(nsIRequest* aRequest) override {
if (!StaticPrefs::browser_tabs_remote_useCrossOriginEmbedderPolicy()) {
return NS_OK;
}
nsresult rv = ProcessCrossOriginEmbedderPolicyHeader(aRequest);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRequest->Cancel(rv);
}
return rv;
}
NS_IMETHOD OnStopRequest(nsIRequest* aRequest,
nsresult aStatusCode) override {
return NS_OK;
}
static nsresult ProcessCrossOriginEmbedderPolicyHeader(
WorkerPrivate* aWorkerPrivate,
nsILoadInfo::CrossOriginEmbedderPolicy aPolicy, bool aIsMainScript) {
MOZ_ASSERT(aWorkerPrivate);
if (aIsMainScript) {
MOZ_TRY(aWorkerPrivate->SetEmbedderPolicy(aPolicy));
} else {
// NOTE: Spec doesn't mention non-main scripts must match COEP header with
// the main script, but it must pass CORP checking.
// see: wpt window-simple-success.https.html, the worker import script
// test-incrementer.js without coep header.
Unused << NS_WARN_IF(!aWorkerPrivate->MatchEmbedderPolicy(aPolicy));
}
return NS_OK;
}
private:
~ScriptResponseHeaderProcessor() = default;
nsresult ProcessCrossOriginEmbedderPolicyHeader(nsIRequest* aRequest) {
nsCOMPtr<nsIHttpChannelInternal> httpChannel = do_QueryInterface(aRequest);
// NOTE: the spec doesn't say what to do with non-HTTP workers.
// See: https://github.com/whatwg/html/issues/4916
if (!httpChannel) {
if (mIsMainScript) {
mWorkerPrivate->InheritOwnerEmbedderPolicyOrNull(aRequest);
}
return NS_OK;
}
nsILoadInfo::CrossOriginEmbedderPolicy coep;
MOZ_TRY(httpChannel->GetResponseEmbedderPolicy(&coep));
return ProcessCrossOriginEmbedderPolicyHeader(mWorkerPrivate, coep,
mIsMainScript);
}
WorkerPrivate* const mWorkerPrivate;
const bool mIsMainScript;
};
NS_IMPL_ISUPPORTS(ScriptResponseHeaderProcessor, nsIRequestObserver);
class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed {
friend class ScriptExecutorRunnable;
friend class CachePromiseHandler;
friend class CacheScriptLoader;
friend class LoaderListener;
WorkerPrivate* const mWorkerPrivate;
UniquePtr<SerializedStackHolder> mOriginStack;
nsString mOriginStackJSON;
nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
nsTArrayView<ScriptLoadInfo> mLoadInfos;
RefPtr<CacheCreator> mCacheCreator;
Maybe<ClientInfo> mClientInfo;
Maybe<ServiceWorkerDescriptor> mController;
const bool mIsMainScript;
WorkerScriptType mWorkerScriptType;
bool mCanceledMainThread;
ErrorResult& mRv;
public:
NS_DECL_THREADSAFE_ISUPPORTS
ScriptLoaderRunnable(WorkerPrivate* aWorkerPrivate,
UniquePtr<SerializedStackHolder> aOriginStack,
nsIEventTarget* aSyncLoopTarget,
nsTArray<ScriptLoadInfo> aLoadInfos,
const Maybe<ClientInfo>& aClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController,
bool aIsMainScript, WorkerScriptType aWorkerScriptType,
ErrorResult& aRv)
: mWorkerPrivate(aWorkerPrivate),
mOriginStack(std::move(aOriginStack)),
mSyncLoopTarget(aSyncLoopTarget),
mLoadInfos(std::move(aLoadInfos)),
mClientInfo(aClientInfo),
mController(aController),
mIsMainScript(aIsMainScript),
mWorkerScriptType(aWorkerScriptType),
mCanceledMainThread(false),
mRv(aRv) {
aWorkerPrivate->AssertIsOnWorkerThread();
MOZ_ASSERT(aSyncLoopTarget);
MOZ_ASSERT_IF(aIsMainScript, mLoadInfos.Length() == 1);
}
void CancelMainThreadWithBindingAborted() {
CancelMainThread(NS_BINDING_ABORTED);
}
private:
~ScriptLoaderRunnable() = default;
NS_IMETHOD
Run() override {
AssertIsOnMainThread();
nsresult rv = RunInternal();
if (NS_WARN_IF(NS_FAILED(rv))) {
CancelMainThread(rv);
}
return NS_OK;
}
NS_IMETHOD
GetName(nsACString& aName) override {
aName.AssignLiteral("ScriptLoaderRunnable");
return NS_OK;
}
void LoadingFinished(ScriptLoadInfo& aLoadInfo, nsresult aRv) {
AssertIsOnMainThread();
aLoadInfo.mLoadResult = aRv;
MOZ_ASSERT(!aLoadInfo.mLoadingFinished);
aLoadInfo.mLoadingFinished = true;
if (IsMainWorkerScript() && NS_SUCCEEDED(aRv)) {
MOZ_DIAGNOSTIC_ASSERT(mWorkerPrivate->PrincipalURIMatchesScriptURL());
}
MaybeExecuteFinishedScripts(aLoadInfo);
}
void MaybeExecuteFinishedScripts(const ScriptLoadInfo& aLoadInfo) {
AssertIsOnMainThread();
// We execute the last step if we don't have a pending operation with the
// cache and the loading is completed.
if (aLoadInfo.Finished()) {
ExecuteFinishedScripts();
}
}
nsresult OnStreamComplete(nsIStreamLoader* aLoader, ScriptLoadInfo& aLoadInfo,
nsresult aStatus, uint32_t aStringLen,
const uint8_t* aString) {
AssertIsOnMainThread();
nsresult rv = OnStreamCompleteInternal(aLoader, aStatus, aStringLen,
aString, aLoadInfo);
LoadingFinished(aLoadInfo, rv);
return NS_OK;
}
nsresult OnStartRequest(nsIRequest* aRequest, ScriptLoadInfo& aLoadInfo) {
nsresult rv = OnStartRequestInternal(aRequest, aLoadInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRequest->Cancel(rv);
}
return rv;
}
nsresult OnStartRequestInternal(nsIRequest* aRequest,
ScriptLoadInfo& aLoadInfo) {
AssertIsOnMainThread();
// If one load info cancels or hits an error, it can race with the start
// callback coming from another load info.
if (mCanceledMainThread || !mCacheCreator) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
// Checking the MIME type is only required for ServiceWorkers'
// importScripts, per step 10 of
// https://w3c.github.io/ServiceWorker/#importscripts
//
// "Extract a MIME type from the response’s header list. If this MIME type
// (ignoring parameters) is not a JavaScript MIME type, return a network
// error."
if (mWorkerPrivate->IsServiceWorker()) {
nsAutoCString mimeType;
channel->GetContentType(mimeType);
if (!nsContentUtils::IsJavascriptMIMEType(
NS_ConvertUTF8toUTF16(mimeType))) {
const nsCString& scope =
mWorkerPrivate->GetServiceWorkerRegistrationDescriptor().Scope();
ServiceWorkerManager::LocalizeAndReportToAllClients(
scope, "ServiceWorkerRegisterMimeTypeError2",
nsTArray<nsString>{NS_ConvertUTF8toUTF16(scope),
NS_ConvertUTF8toUTF16(mimeType),
aLoadInfo.mURL});
return NS_ERROR_DOM_NETWORK_ERR;
}
}
// Note that importScripts() can redirect. In theory the main
// script could also encounter an internal redirect, but currently
// the assert does not allow that.
MOZ_ASSERT_IF(mIsMainScript, channel == aLoadInfo.mChannel);
aLoadInfo.mChannel = channel;
// We synthesize the result code, but its never exposed to content.
RefPtr<mozilla::dom::InternalResponse> ir =
new mozilla::dom::InternalResponse(200, "OK"_ns);
ir->SetBody(aLoadInfo.mCacheReadStream,
InternalResponse::UNKNOWN_BODY_SIZE);
// Drop our reference to the stream now that we've passed it along, so it
// doesn't hang around once the cache is done with it and keep data alive.
aLoadInfo.mCacheReadStream = nullptr;
// Set the channel info of the channel on the response so that it's
// saved in the cache.
ir->InitChannelInfo(channel);
// Save the principal of the channel since its URI encodes the script URI
// rather than the ServiceWorkerRegistrationInfo URI.
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
NS_ASSERTION(ssm, "Should never be null!");
nsCOMPtr<nsIPrincipal> channelPrincipal;
MOZ_TRY(ssm->GetChannelResultPrincipal(channel,
getter_AddRefs(channelPrincipal)));
UniquePtr<PrincipalInfo> principalInfo(new PrincipalInfo());
MOZ_TRY(PrincipalToPrincipalInfo(channelPrincipal, principalInfo.get()));
ir->SetPrincipalInfo(std::move(principalInfo));
ir->Headers()->FillResponseHeaders(aLoadInfo.mChannel);
RefPtr<mozilla::dom::Response> response =
new mozilla::dom::Response(mCacheCreator->Global(), ir, nullptr);
mozilla::dom::RequestOrUSVString request;
MOZ_ASSERT(!aLoadInfo.mFullURL.IsEmpty());
request.SetAsUSVString().ShareOrDependUpon(aLoadInfo.mFullURL);
// This JSContext will not end up executing JS code because here there are
// no ReadableStreams involved.
AutoJSAPI jsapi;
jsapi.Init();
ErrorResult error;
RefPtr<Promise> cachePromise =
mCacheCreator->Cache_()->Put(jsapi.cx(), request, *response, error);
error.WouldReportJSException();
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
RefPtr<CachePromiseHandler> promiseHandler =
new CachePromiseHandler(this, aLoadInfo);
cachePromise->AppendNativeHandler(promiseHandler);
aLoadInfo.mCachePromise.swap(cachePromise);
aLoadInfo.mCacheStatus = ScriptLoadInfo::WritingToCache;
return NS_OK;
}
bool IsMainWorkerScript() const {
return mIsMainScript && mWorkerScriptType == WorkerScript;
}
bool IsDebuggerScript() const { return mWorkerScriptType == DebuggerScript; }
void CancelMainThread(nsresult aCancelResult) {
AssertIsOnMainThread();
if (mCanceledMainThread) {
return;
}
mCanceledMainThread = true;
if (mCacheCreator) {
MOZ_ASSERT(mWorkerPrivate->IsServiceWorker());
DeleteCache();
}
// Cancel all the channels that were already opened.
for (ScriptLoadInfo& loadInfo : mLoadInfos) {
// If promise or channel is non-null, their failures will lead to
// LoadingFinished being called.
bool callLoadingFinished = true;
if (loadInfo.mCachePromise) {
MOZ_ASSERT(mWorkerPrivate->IsServiceWorker());
loadInfo.mCachePromise->MaybeReject(aCancelResult);
loadInfo.mCachePromise = nullptr;
callLoadingFinished = false;
}
if (loadInfo.mChannel) {
if (NS_SUCCEEDED(loadInfo.mChannel->Cancel(aCancelResult))) {
callLoadingFinished = false;
} else {
NS_WARNING("Failed to cancel channel!");
}
}
if (callLoadingFinished && !loadInfo.Finished()) {
LoadingFinished(loadInfo, aCancelResult);
}
}
ExecuteFinishedScripts();
}
void DeleteCache() {
AssertIsOnMainThread();
if (!mCacheCreator) {
return;
}
mCacheCreator->DeleteCache();
mCacheCreator = nullptr;
}
nsresult RunInternal() {
AssertIsOnMainThread();
if (IsMainWorkerScript()) {
mWorkerPrivate->SetLoadingWorkerScript(true);
}
// Convert the origin stack to JSON (which must be done on the main
// thread) explicitly, so that we can use the stack to notify the net
// monitor about every script we load.
if (mOriginStack) {
ConvertSerializedStackToJSON(std::move(mOriginStack), mOriginStackJSON);
}
if (!mWorkerPrivate->IsServiceWorker() || IsDebuggerScript()) {
for (ScriptLoadInfo& loadInfo : mLoadInfos) {
nsresult rv = LoadScript(loadInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
LoadingFinished(loadInfo, rv);
return rv;
}
}
return NS_OK;
}
MOZ_ASSERT(!mCacheCreator);
mCacheCreator = new CacheCreator(mWorkerPrivate);
for (ScriptLoadInfo& loadInfo : mLoadInfos) {
mCacheCreator->AddLoader(MakeNotNull<RefPtr<CacheScriptLoader>>(
mWorkerPrivate, loadInfo, IsMainWorkerScript(), this));
}
// The worker may have a null principal on first load, but in that case its
// parent definitely will have one.
nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
if (!principal) {
WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
MOZ_ASSERT(parentWorker, "Must have a parent!");
principal = parentWorker->GetPrincipal();
}
nsresult rv = mCacheCreator->Load(principal);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult LoadScript(ScriptLoadInfo& aLoadInfo) {
AssertIsOnMainThread();
MOZ_ASSERT_IF(IsMainWorkerScript(), mWorkerScriptType != DebuggerScript);
WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
// For JavaScript debugging, the devtools server must run on the same
// thread as the debuggee, indicating the worker uses content principal.
// However, in Bug 863246, web content will no longer be able to load
// resource:// URIs by default, so we need system principal to load
// debugger scripts.
nsIPrincipal* principal = (mWorkerScriptType == DebuggerScript)
? nsContentUtils::GetSystemPrincipal()
: mWorkerPrivate->GetPrincipal();