forked from classilla/tenfourfox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServiceWorkerManager.cpp
5096 lines (4249 loc) · 147 KB
/
ServiceWorkerManager.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 "ServiceWorkerManager.h"
#include "mozIApplication.h"
#include "nsIAppsService.h"
#include "nsIConsoleService.h"
#include "nsIDOMEventTarget.h"
#include "nsIDocument.h"
#include "nsIScriptSecurityManager.h"
#include "nsIStreamLoader.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIHttpHeaderVisitor.h"
#include "nsIJARChannel.h"
#include "nsINetworkInterceptController.h"
#include "nsIMutableArray.h"
#include "nsIScriptError.h"
#include "nsISimpleEnumerator.h"
#include "nsITimer.h"
#include "nsIUploadChannel2.h"
#include "nsPIDOMWindow.h"
#include "nsScriptLoader.h"
#include "nsServiceManagerUtils.h"
#include "nsDebug.h"
#include "nsISupportsPrimitives.h"
#include "jsapi.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/LoadContext.h"
#include "mozilla/Telemetry.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/DOMError.h"
#include "mozilla/dom/ErrorEvent.h"
#include "mozilla/dom/Headers.h"
#include "mozilla/dom/indexedDB/IndexedDatabaseManager.h"
#include "mozilla/dom/indexedDB/IDBFactory.h"
#include "mozilla/dom/InternalHeaders.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/NotificationEvent.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/Request.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/unused.h"
#include "mozilla/EnumSet.h"
#include "nsContentPolicyUtils.h"
#include "nsContentSecurityManager.h"
#include "nsContentUtils.h"
#include "nsGlobalWindow.h"
#include "nsNetUtil.h"
#include "nsIURL.h"
#include "nsProxyRelease.h"
#include "nsQueryObject.h"
#include "nsTArray.h"
#include "RuntimeService.h"
#include "ServiceWorker.h"
#include "ServiceWorkerClient.h"
#include "ServiceWorkerContainer.h"
#include "ServiceWorkerManagerChild.h"
#include "ServiceWorkerPrivate.h"
#include "ServiceWorkerRegistrar.h"
#include "ServiceWorkerRegistration.h"
#include "ServiceWorkerScriptCache.h"
#include "ServiceWorkerEvents.h"
#include "SharedWorker.h"
#include "WorkerInlines.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WorkerScope.h"
#ifndef MOZ_SIMPLEPUSH
#include "mozilla/dom/TypedArray.h"
#endif
#ifdef PostMessage
#undef PostMessage
#endif
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::ipc;
BEGIN_WORKERS_NAMESPACE
#define PURGE_DOMAIN_DATA "browser:purge-domain-data"
#define PURGE_SESSION_HISTORY "browser:purge-session-history"
#define CLEAR_ORIGIN_DATA "clear-origin-data"
static_assert(nsIHttpChannelInternal::CORS_MODE_SAME_ORIGIN == static_cast<uint32_t>(RequestMode::Same_origin),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(nsIHttpChannelInternal::CORS_MODE_NO_CORS == static_cast<uint32_t>(RequestMode::No_cors),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(nsIHttpChannelInternal::CORS_MODE_CORS == static_cast<uint32_t>(RequestMode::Cors),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(nsIHttpChannelInternal::REDIRECT_MODE_FOLLOW == static_cast<uint32_t>(RequestRedirect::Follow),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(nsIHttpChannelInternal::REDIRECT_MODE_ERROR == static_cast<uint32_t>(RequestRedirect::Error),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(nsIHttpChannelInternal::REDIRECT_MODE_MANUAL == static_cast<uint32_t>(RequestRedirect::Manual),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(3 == static_cast<uint32_t>(RequestRedirect::EndGuard_),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static StaticRefPtr<ServiceWorkerManager> gInstance;
struct ServiceWorkerManager::RegistrationDataPerPrincipal final
{
// Ordered list of scopes for glob matching.
// Each entry is an absolute URL representing the scope.
// Each value of the hash table is an array of an absolute URLs representing
// the scopes.
//
// An array is used for now since the number of controlled scopes per
// domain is expected to be relatively low. If that assumption was proved
// wrong this should be replaced with a better structure to avoid the
// memmoves associated with inserting stuff in the middle of the array.
nsTArray<nsCString> mOrderedScopes;
// Scope to registration.
// The scope should be a fully qualified valid URL.
nsRefPtrHashtable<nsCStringHashKey, ServiceWorkerRegistrationInfo> mInfos;
// Maps scopes to job queues.
nsClassHashtable<nsCStringHashKey, ServiceWorkerJobQueue> mJobQueues;
// Map scopes to scheduled update timers.
nsInterfaceHashtable<nsCStringHashKey, nsITimer> mUpdateTimers;
};
struct ServiceWorkerManager::PendingOperation final
{
nsCOMPtr<nsIRunnable> mRunnable;
ServiceWorkerJobQueue* mQueue;
RefPtr<ServiceWorkerJob> mJob;
ServiceWorkerRegistrationData mRegistration;
};
class ServiceWorkerJob : public nsISupports
{
friend class ServiceWorkerJobQueue;
public:
NS_DECL_ISUPPORTS
enum Type
{
RegisterJob,
UpdateJob,
InstallJob,
UnregisterJob
};
virtual void Start() = 0;
void
Cancel()
{
mQueue = nullptr;
mCanceled = true;
}
bool
IsRegisterOrInstallJob() const
{
return mJobType == RegisterJob || mJobType == UpdateJob ||
mJobType == InstallJob;
}
protected:
// The queue keeps the jobs alive, so they can hold a rawptr back to the
// queue.
ServiceWorkerJobQueue* mQueue;
Type mJobType;
bool mCanceled;
explicit ServiceWorkerJob(ServiceWorkerJobQueue* aQueue, Type aJobType)
: mQueue(aQueue)
, mJobType(aJobType)
, mCanceled(false)
{}
virtual ~ServiceWorkerJob()
{}
void
Done(nsresult aStatus);
};
class ServiceWorkerJobQueue final
{
friend class ServiceWorkerJob;
struct QueueData final
{
QueueData()
: mPopping(false)
{ }
~QueueData()
{
if (!mJobs.IsEmpty()) {
NS_WARNING("Pending/running jobs still around on shutdown!");
}
}
nsTArray<RefPtr<ServiceWorkerJob>> mJobs;
bool mPopping;
};
const nsCString mOriginAttributesSuffix;
QueueData mRegistrationJobQueue;
QueueData mInstallationJobQueue;
public:
explicit ServiceWorkerJobQueue(const nsACString& aScopeKey)
: mOriginAttributesSuffix(aScopeKey)
{}
~ServiceWorkerJobQueue()
{ }
void
Append(ServiceWorkerJob* aJob)
{
MOZ_ASSERT(aJob);
QueueData& queue = GetQueue(aJob->mJobType);
MOZ_ASSERT(!queue.mJobs.Contains(aJob));
bool wasEmpty = queue.mJobs.IsEmpty();
queue.mJobs.AppendElement(aJob);
if (wasEmpty) {
aJob->Start();
}
}
void
CancelJobs();
private:
void
CancelJobs(QueueData& aQueue);
// Internal helper function used to assign jobs to the correct queue.
QueueData&
GetQueue(ServiceWorkerJob::Type aType)
{
switch (aType) {
case ServiceWorkerJob::Type::RegisterJob:
case ServiceWorkerJob::Type::UpdateJob:
case ServiceWorkerJob::Type::UnregisterJob:
return mRegistrationJobQueue;
case ServiceWorkerJob::Type::InstallJob:
return mInstallationJobQueue;
default:
MOZ_CRASH("Invalid job queue type.");
return mRegistrationJobQueue;
}
}
bool
IsEmpty()
{
return mRegistrationJobQueue.mJobs.IsEmpty() &&
mInstallationJobQueue.mJobs.IsEmpty();
}
void
Pop(QueueData& aQueue)
{
MOZ_ASSERT(!aQueue.mPopping,
"Pop() called recursively, did you write a job which calls Done() synchronously from Start()?");
AutoRestore<bool> savePopping(aQueue.mPopping);
aQueue.mPopping = true;
MOZ_ASSERT(!aQueue.mJobs.IsEmpty());
aQueue.mJobs.RemoveElementAt(0);
if (!aQueue.mJobs.IsEmpty()) {
aQueue.mJobs[0]->Start();
} else if (IsEmpty()) {
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
swm->MaybeRemoveRegistrationInfo(mOriginAttributesSuffix);
}
}
void
Done(ServiceWorkerJob* aJob)
{
MOZ_ASSERT(aJob);
QueueData& queue = GetQueue(aJob->mJobType);
MOZ_ASSERT(!queue.mJobs.IsEmpty());
MOZ_ASSERT(queue.mJobs[0] == aJob);
if (NS_WARN_IF(queue.mJobs[0] != aJob)) {
return;
}
Pop(queue);
}
};
namespace {
nsresult
PopulateRegistrationData(nsIPrincipal* aPrincipal,
const ServiceWorkerRegistrationInfo* aRegistration,
ServiceWorkerRegistrationData& aData)
{
MOZ_ASSERT(aPrincipal);
MOZ_ASSERT(aRegistration);
if (NS_WARN_IF(!BasePrincipal::Cast(aPrincipal)->IsCodebasePrincipal())) {
return NS_ERROR_FAILURE;
}
nsresult rv = PrincipalToPrincipalInfo(aPrincipal, &aData.principal());
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
aData.scope() = aRegistration->mScope;
RefPtr<ServiceWorkerInfo> newest = aRegistration->Newest();
if (NS_WARN_IF(!newest)) {
return NS_ERROR_FAILURE;
}
aData.scriptSpec() = newest->ScriptSpec();
if (aRegistration->mActiveWorker) {
aData.currentWorkerURL() = aRegistration->mActiveWorker->ScriptSpec();
aData.activeCacheName() = aRegistration->mActiveWorker->CacheName();
}
if (aRegistration->mWaitingWorker) {
aData.waitingCacheName() = aRegistration->mWaitingWorker->CacheName();
}
return NS_OK;
}
class TeardownRunnable final : public nsRunnable
{
public:
explicit TeardownRunnable(ServiceWorkerManagerChild* aActor)
: mActor(aActor)
{
MOZ_ASSERT(mActor);
}
NS_IMETHODIMP Run() override
{
MOZ_ASSERT(mActor);
mActor->SendShutdown();
return NS_OK;
}
private:
~TeardownRunnable() {}
RefPtr<ServiceWorkerManagerChild> mActor;
};
} // namespace
NS_IMPL_ISUPPORTS0(ServiceWorkerJob)
void
ServiceWorkerJob::Done(nsresult aStatus)
{
if (NS_WARN_IF(NS_FAILED(aStatus))) {
#ifdef DEBUG
nsAutoCString errorName;
GetErrorName(aStatus, errorName);
#endif
NS_WARNING(nsPrintfCString("ServiceWorkerJob failed with error: %s",
errorName.get()).get());
}
if (mQueue) {
mQueue->Done(this);
}
}
void
ServiceWorkerRegistrationInfo::Clear()
{
if (mInstallingWorker) {
mInstallingWorker->UpdateState(ServiceWorkerState::Redundant);
mInstallingWorker->WorkerPrivate()->NoteDeadServiceWorkerInfo();
mInstallingWorker = nullptr;
// FIXME(nsm): Abort any inflight requests from installing worker.
}
if (mWaitingWorker) {
mWaitingWorker->UpdateState(ServiceWorkerState::Redundant);
nsresult rv = serviceWorkerScriptCache::PurgeCache(mPrincipal,
mWaitingWorker->CacheName());
if (NS_FAILED(rv)) {
NS_WARNING("Failed to purge the waiting cache.");
}
mWaitingWorker->WorkerPrivate()->NoteDeadServiceWorkerInfo();
mWaitingWorker = nullptr;
}
if (mActiveWorker) {
mActiveWorker->UpdateState(ServiceWorkerState::Redundant);
nsresult rv = serviceWorkerScriptCache::PurgeCache(mPrincipal,
mActiveWorker->CacheName());
if (NS_FAILED(rv)) {
NS_WARNING("Failed to purge the active cache.");
}
mActiveWorker->WorkerPrivate()->NoteDeadServiceWorkerInfo();
mActiveWorker = nullptr;
}
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
swm->InvalidateServiceWorkerRegistrationWorker(this,
WhichServiceWorker::INSTALLING_WORKER |
WhichServiceWorker::WAITING_WORKER |
WhichServiceWorker::ACTIVE_WORKER);
}
ServiceWorkerRegistrationInfo::ServiceWorkerRegistrationInfo(const nsACString& aScope,
nsIPrincipal* aPrincipal)
: mControlledDocumentsCounter(0)
, mUpdateState(NoUpdate)
, mLastUpdateCheckTime(0)
, mScope(aScope)
, mPrincipal(aPrincipal)
, mUpdating(false)
, mPendingUninstall(false)
{}
ServiceWorkerRegistrationInfo::~ServiceWorkerRegistrationInfo()
{
if (IsControllingDocuments()) {
NS_WARNING("ServiceWorkerRegistrationInfo is still controlling documents. This can be a bug or a leak in ServiceWorker API or in any other API that takes the document alive.");
}
}
NS_IMPL_ISUPPORTS(ServiceWorkerRegistrationInfo, nsIServiceWorkerRegistrationInfo)
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::GetPrincipal(nsIPrincipal** aPrincipal)
{
AssertIsOnMainThread();
NS_ADDREF(*aPrincipal = mPrincipal);
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::GetScope(nsAString& aScope)
{
AssertIsOnMainThread();
CopyUTF8toUTF16(mScope, aScope);
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::GetScriptSpec(nsAString& aScriptSpec)
{
AssertIsOnMainThread();
RefPtr<ServiceWorkerInfo> newest = Newest();
if (newest) {
CopyUTF8toUTF16(newest->ScriptSpec(), aScriptSpec);
}
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::GetInstallingWorker(nsIServiceWorkerInfo **aResult)
{
AssertIsOnMainThread();
nsCOMPtr<nsIServiceWorkerInfo> info = do_QueryInterface(mInstallingWorker);
info.forget(aResult);
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::GetWaitingWorker(nsIServiceWorkerInfo **aResult)
{
AssertIsOnMainThread();
nsCOMPtr<nsIServiceWorkerInfo> info = do_QueryInterface(mWaitingWorker);
info.forget(aResult);
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::GetActiveWorker(nsIServiceWorkerInfo **aResult)
{
AssertIsOnMainThread();
nsCOMPtr<nsIServiceWorkerInfo> info = do_QueryInterface(mActiveWorker);
info.forget(aResult);
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::AddListener(
nsIServiceWorkerRegistrationInfoListener *aListener)
{
AssertIsOnMainThread();
if (!aListener || mListeners.Contains(aListener)) {
return NS_ERROR_INVALID_ARG;
}
mListeners.AppendElement(aListener);
return NS_OK;
}
NS_IMETHODIMP
ServiceWorkerRegistrationInfo::RemoveListener(
nsIServiceWorkerRegistrationInfoListener *aListener)
{
AssertIsOnMainThread();
if (!aListener || !mListeners.Contains(aListener)) {
return NS_ERROR_INVALID_ARG;
}
mListeners.RemoveElement(aListener);
return NS_OK;
}
already_AddRefed<ServiceWorkerInfo>
ServiceWorkerRegistrationInfo::GetServiceWorkerInfoById(uint64_t aId)
{
RefPtr<ServiceWorkerInfo> serviceWorker;
if (mInstallingWorker && mInstallingWorker->ID() == aId) {
serviceWorker = mInstallingWorker;
} else if (mWaitingWorker && mWaitingWorker->ID() == aId) {
serviceWorker = mWaitingWorker;
} else if (mActiveWorker && mActiveWorker->ID() == aId) {
serviceWorker = mActiveWorker;
}
return serviceWorker.forget();
}
//////////////////////////
// ServiceWorkerManager //
//////////////////////////
NS_IMPL_ADDREF(ServiceWorkerManager)
NS_IMPL_RELEASE(ServiceWorkerManager)
NS_INTERFACE_MAP_BEGIN(ServiceWorkerManager)
NS_INTERFACE_MAP_ENTRY(nsIServiceWorkerManager)
NS_INTERFACE_MAP_ENTRY(nsIIPCBackgroundChildCreateCallback)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIServiceWorkerManager)
NS_INTERFACE_MAP_END
ServiceWorkerManager::ServiceWorkerManager()
: mActor(nullptr)
, mShuttingDown(false)
{
// Register this component to PBackground.
MOZ_ALWAYS_TRUE(BackgroundChild::GetOrCreateForCurrentThread(this));
}
ServiceWorkerManager::~ServiceWorkerManager()
{
// The map will assert if it is not empty when destroyed.
mRegistrationInfos.Clear();
MOZ_ASSERT(!mActor);
}
void
ServiceWorkerManager::Init()
{
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
DebugOnly<nsresult> rv;
rv = obs->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false /* ownsWeak */);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
if (XRE_IsParentProcess()) {
RefPtr<ServiceWorkerRegistrar> swr = ServiceWorkerRegistrar::Get();
MOZ_ASSERT(swr);
nsTArray<ServiceWorkerRegistrationData> data;
swr->GetRegistrations(data);
LoadRegistrations(data);
if (obs) {
DebugOnly<nsresult> rv;
rv = obs->AddObserver(this, PURGE_SESSION_HISTORY, false /* ownsWeak */);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = obs->AddObserver(this, PURGE_DOMAIN_DATA, false /* ownsWeak */);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = obs->AddObserver(this, CLEAR_ORIGIN_DATA, false /* ownsWeak */);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
}
class ContinueLifecycleTask : public nsISupports
{
NS_DECL_ISUPPORTS
protected:
virtual ~ContinueLifecycleTask()
{}
public:
virtual void ContinueAfterWorkerEvent(bool aSuccess) = 0;
};
NS_IMPL_ISUPPORTS0(ContinueLifecycleTask);
class ServiceWorkerInstallJob;
class ContinueInstallTask final : public ContinueLifecycleTask
{
RefPtr<ServiceWorkerInstallJob> mJob;
public:
explicit ContinueInstallTask(ServiceWorkerInstallJob* aJob)
: mJob(aJob)
{}
void ContinueAfterWorkerEvent(bool aSuccess) override;
};
class ContinueActivateTask final : public ContinueLifecycleTask
{
RefPtr<ServiceWorkerRegistrationInfo> mRegistration;
public:
explicit ContinueActivateTask(ServiceWorkerRegistrationInfo* aReg)
: mRegistration(aReg)
{}
void
ContinueAfterWorkerEvent(bool aSuccess) override;
};
class ContinueLifecycleRunnable final : public LifeCycleEventCallback
{
nsMainThreadPtrHandle<ContinueLifecycleTask> mTask;
bool mSuccess;
public:
explicit ContinueLifecycleRunnable(const nsMainThreadPtrHandle<ContinueLifecycleTask>& aTask)
: mTask(aTask)
, mSuccess(false)
{
AssertIsOnMainThread();
}
void
SetResult(bool aResult) override
{
mSuccess = aResult;
}
NS_IMETHOD
Run() override
{
AssertIsOnMainThread();
mTask->ContinueAfterWorkerEvent(mSuccess);
return NS_OK;
}
};
class ServiceWorkerResolveWindowPromiseOnUpdateCallback final : public ServiceWorkerUpdateFinishCallback
{
RefPtr<nsPIDOMWindow> mWindow;
// The promise "returned" by the call to Update up to
// navigator.serviceWorker.register().
RefPtr<Promise> mPromise;
~ServiceWorkerResolveWindowPromiseOnUpdateCallback()
{}
public:
ServiceWorkerResolveWindowPromiseOnUpdateCallback(nsPIDOMWindow* aWindow, Promise* aPromise)
: mWindow(aWindow)
, mPromise(aPromise)
{}
void
UpdateSucceeded(ServiceWorkerRegistrationInfo* aInfo) override
{
RefPtr<ServiceWorkerRegistrationMainThread> swr =
mWindow->GetServiceWorkerRegistration(NS_ConvertUTF8toUTF16(aInfo->mScope));
mPromise->MaybeResolve(swr);
}
void
UpdateFailed(ErrorResult& aStatus) override
{
mPromise->MaybeReject(aStatus);
}
};
class ContinueUpdateRunnable final : public LifeCycleEventCallback
{
nsMainThreadPtrHandle<nsISupports> mJob;
bool mScriptEvaluationResult;
public:
explicit ContinueUpdateRunnable(const nsMainThreadPtrHandle<nsISupports> aJob)
: mJob(aJob)
, mScriptEvaluationResult(false)
{
AssertIsOnMainThread();
}
void
SetResult(bool aResult)
{
mScriptEvaluationResult = aResult;
}
NS_IMETHOD Run();
};
namespace {
/**
* The spec mandates slightly different behaviors for computing the scope
* prefix string in case a Service-Worker-Allowed header is specified versus
* when it's not available.
*
* With the header:
* "Set maxScopeString to "/" concatenated with the strings in maxScope's
* path (including empty strings), separated from each other by "/"."
* Without the header:
* "Set maxScopeString to "/" concatenated with the strings, except the last
* string that denotes the script's file name, in registration's registering
* script url's path (including empty strings), separated from each other by
* "/"."
*
* In simpler terms, if the header is not present, we should only use the
* "directory" part of the pathname, and otherwise the entire pathname should be
* used. ScopeStringPrefixMode allows the caller to specify the desired
* behavior.
*/
enum ScopeStringPrefixMode {
eUseDirectory,
eUsePath
};
nsresult
GetRequiredScopeStringPrefix(nsIURI* aScriptURI, nsACString& aPrefix,
ScopeStringPrefixMode aPrefixMode)
{
nsresult rv = aScriptURI->GetPrePath(aPrefix);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (aPrefixMode == eUseDirectory) {
nsCOMPtr<nsIURL> scriptURL(do_QueryInterface(aScriptURI));
if (NS_WARN_IF(!scriptURL)) {
return NS_ERROR_FAILURE;
}
nsAutoCString dir;
rv = scriptURL->GetDirectory(dir);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
aPrefix.Append(dir);
} else if (aPrefixMode == eUsePath) {
nsAutoCString path;
rv = aScriptURI->GetPath(path);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
aPrefix.Append(path);
} else {
MOZ_ASSERT_UNREACHABLE("Invalid value for aPrefixMode");
}
return NS_OK;
}
class PropagateSoftUpdateRunnable final : public nsRunnable
{
public:
PropagateSoftUpdateRunnable(const PrincipalOriginAttributes& aOriginAttributes,
const nsAString& aScope)
: mOriginAttributes(aOriginAttributes)
, mScope(aScope)
{}
NS_IMETHOD Run() override
{
AssertIsOnMainThread();
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
swm->PropagateSoftUpdate(mOriginAttributes, mScope);
return NS_OK;
}
private:
~PropagateSoftUpdateRunnable()
{}
const PrincipalOriginAttributes mOriginAttributes;
const nsString mScope;
};
class PropagateUnregisterRunnable final : public nsRunnable
{
public:
PropagateUnregisterRunnable(nsIPrincipal* aPrincipal,
nsIServiceWorkerUnregisterCallback* aCallback,
const nsAString& aScope)
: mPrincipal(aPrincipal)
, mCallback(aCallback)
, mScope(aScope)
{
MOZ_ASSERT(aPrincipal);
}
NS_IMETHOD Run() override
{
AssertIsOnMainThread();
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
nsresult rv = swm->PropagateUnregister(mPrincipal, mCallback, mScope);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
private:
~PropagateUnregisterRunnable()
{}
nsCOMPtr<nsIPrincipal> mPrincipal;
nsCOMPtr<nsIServiceWorkerUnregisterCallback> mCallback;
const nsString mScope;
};
class RemoveRunnable final : public nsRunnable
{
public:
explicit RemoveRunnable(const nsACString& aHost)
{}
NS_IMETHOD Run() override
{
AssertIsOnMainThread();
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
swm->Remove(mHost);
return NS_OK;
}
private:
~RemoveRunnable()
{}
const nsCString mHost;
};
class PropagateRemoveRunnable final : public nsRunnable
{
public:
explicit PropagateRemoveRunnable(const nsACString& aHost)
{}
NS_IMETHOD Run() override
{
AssertIsOnMainThread();
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
swm->PropagateRemove(mHost);
return NS_OK;
}
private:
~PropagateRemoveRunnable()
{}
const nsCString mHost;
};
class PropagateRemoveAllRunnable final : public nsRunnable
{
public:
PropagateRemoveAllRunnable()
{}
NS_IMETHOD Run() override
{
AssertIsOnMainThread();
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
swm->PropagateRemoveAll();
return NS_OK;
}
private:
~PropagateRemoveAllRunnable()
{}
};
} // namespace
class ServiceWorkerJobBase : public ServiceWorkerJob
{
public:
ServiceWorkerJobBase(ServiceWorkerJobQueue* aQueue,
ServiceWorkerJob::Type aJobType,
ServiceWorkerUpdateFinishCallback* aCallback)
: ServiceWorkerJobBase(aQueue, aJobType, aCallback, nullptr, nullptr)
{ }
ServiceWorkerJobBase(ServiceWorkerJobQueue* aQueue,
ServiceWorkerJob::Type aJobType,
ServiceWorkerUpdateFinishCallback* aCallback,
ServiceWorkerRegistrationInfo* aRegistration,
ServiceWorkerInfo* aServiceWorkerInfo)
: ServiceWorkerJob(aQueue, aJobType)
, mCallback(aCallback)
, mRegistration(aRegistration)
, mUpdateAndInstallInfo(aServiceWorkerInfo)
{
AssertIsOnMainThread();
}
protected:
RefPtr<ServiceWorkerUpdateFinishCallback> mCallback;
RefPtr<ServiceWorkerRegistrationInfo> mRegistration;
RefPtr<ServiceWorkerInfo> mUpdateAndInstallInfo;
~ServiceWorkerJobBase()
{ }
void
Succeed()
{
AssertIsOnMainThread();
// We don't have a callback for soft updates.
if (mCallback) {
mCallback->UpdateSucceeded(mRegistration);
mCallback = nullptr;
}
}
};
// Base type for jobs that work with a specific service worker script.
class ServiceWorkerScriptJobBase : public ServiceWorkerJobBase
{
protected:
const nsCString mScriptSpec;
ServiceWorkerScriptJobBase(ServiceWorkerJobQueue* aQueue,
ServiceWorkerJob::Type aJobType,
ServiceWorkerUpdateFinishCallback* aCallback,
ServiceWorkerRegistrationInfo* aRegistration,
ServiceWorkerInfo* aServiceWorkerInfo,
const nsACString& aScriptSpec)
: ServiceWorkerJobBase(aQueue, aJobType, aCallback, aRegistration,
aServiceWorkerInfo)
, mScriptSpec(aScriptSpec)
{
}