Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "ServiceWorkerContainer.h"
8
9
#include "nsContentPolicyUtils.h"
10
#include "nsContentSecurityManager.h"
11
#include "nsContentUtils.h"
12
#include "mozilla/dom/Document.h"
13
#include "nsIServiceWorkerManager.h"
14
#include "nsIScriptError.h"
15
#include "nsThreadUtils.h"
16
#include "nsIURL.h"
17
#include "nsNetUtil.h"
18
#include "nsPIDOMWindow.h"
19
#include "mozilla/Services.h"
20
#include "mozilla/StaticPrefs_dom.h"
21
22
#include "nsCycleCollectionParticipant.h"
23
#include "nsServiceManagerUtils.h"
24
#include "mozilla/BasePrincipal.h"
25
#include "mozilla/LoadInfo.h"
26
#include "mozilla/StorageAccess.h"
27
#include "mozilla/dom/ClientIPCTypes.h"
28
#include "mozilla/dom/DOMMozPromiseRequestHolder.h"
29
#include "mozilla/dom/MessageEvent.h"
30
#include "mozilla/dom/MessageEventBinding.h"
31
#include "mozilla/dom/Navigator.h"
32
#include "mozilla/dom/Promise.h"
33
#include "mozilla/dom/ServiceWorker.h"
34
#include "mozilla/dom/ServiceWorkerContainerBinding.h"
35
#include "mozilla/dom/ServiceWorkerManager.h"
36
#include "mozilla/dom/ipc/StructuredCloneData.h"
37
38
#include "RemoteServiceWorkerContainerImpl.h"
39
#include "ServiceWorker.h"
40
#include "ServiceWorkerContainerImpl.h"
41
#include "ServiceWorkerRegistration.h"
42
#include "ServiceWorkerUtils.h"
43
44
// This is defined to something else on Windows
45
#ifdef DispatchMessage
46
# undef DispatchMessage
47
#endif
48
49
namespace mozilla {
50
namespace dom {
51
52
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ServiceWorkerContainer)
53
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
54
55
NS_IMPL_ADDREF_INHERITED(ServiceWorkerContainer, DOMEventTargetHelper)
56
NS_IMPL_RELEASE_INHERITED(ServiceWorkerContainer, DOMEventTargetHelper)
57
58
NS_IMPL_CYCLE_COLLECTION_INHERITED(ServiceWorkerContainer, DOMEventTargetHelper,
59
mControllerWorker, mReadyPromise)
60
61
namespace {
62
63
bool IsInPrivateBrowsing(JSContext* const aCx) {
64
if (const nsCOMPtr<nsIGlobalObject> global = xpc::CurrentNativeGlobal(aCx)) {
65
if (const nsCOMPtr<nsIPrincipal> principal = global->PrincipalOrNull()) {
66
return principal->GetPrivateBrowsingId() > 0;
67
}
68
}
69
return false;
70
}
71
72
bool IsServiceWorkersTestingEnabledInWindow(JSObject* const aGlobal) {
73
if (const nsCOMPtr<nsPIDOMWindowInner> innerWindow =
74
Navigator::GetWindowFromGlobal(aGlobal)) {
75
if (const nsCOMPtr<nsPIDOMWindowOuter> outerWindow =
76
innerWindow->GetOuterWindow()) {
77
return outerWindow->GetServiceWorkersTestingEnabled();
78
}
79
}
80
return false;
81
}
82
83
} // namespace
84
85
/* static */
86
bool ServiceWorkerContainer::IsEnabled(JSContext* aCx, JSObject* aGlobal) {
87
MOZ_ASSERT(NS_IsMainThread());
88
89
JS::Rooted<JSObject*> global(aCx, aGlobal);
90
91
if (!StaticPrefs::dom_serviceWorkers_enabled()) {
92
return false;
93
}
94
95
if (IsInPrivateBrowsing(aCx)) {
96
return false;
97
}
98
99
if (IsSecureContextOrObjectIsFromSecureContext(aCx, global)) {
100
return true;
101
}
102
103
const bool isTestingEnabledInWindow =
104
IsServiceWorkersTestingEnabledInWindow(global);
105
const bool isTestingEnabledByPref =
106
StaticPrefs::dom_serviceWorkers_testing_enabled();
107
const bool isTestingEnabled =
108
isTestingEnabledByPref || isTestingEnabledInWindow;
109
110
return isTestingEnabled;
111
}
112
113
// static
114
already_AddRefed<ServiceWorkerContainer> ServiceWorkerContainer::Create(
115
nsIGlobalObject* aGlobal) {
116
RefPtr<Inner> inner;
117
if (ServiceWorkerParentInterceptEnabled()) {
118
inner = new RemoteServiceWorkerContainerImpl();
119
} else {
120
inner = new ServiceWorkerContainerImpl();
121
}
122
NS_ENSURE_TRUE(inner, nullptr);
123
124
RefPtr<ServiceWorkerContainer> ref =
125
new ServiceWorkerContainer(aGlobal, inner.forget());
126
return ref.forget();
127
}
128
129
ServiceWorkerContainer::ServiceWorkerContainer(
130
nsIGlobalObject* aGlobal,
131
already_AddRefed<ServiceWorkerContainer::Inner> aInner)
132
: DOMEventTargetHelper(aGlobal), mInner(aInner) {
133
mInner->AddContainer(this);
134
Maybe<ServiceWorkerDescriptor> controller = aGlobal->GetController();
135
if (controller.isSome()) {
136
mControllerWorker = aGlobal->GetOrCreateServiceWorker(controller.ref());
137
}
138
}
139
140
ServiceWorkerContainer::~ServiceWorkerContainer() {
141
mInner->RemoveContainer(this);
142
}
143
144
void ServiceWorkerContainer::DisconnectFromOwner() {
145
mControllerWorker = nullptr;
146
mReadyPromise = nullptr;
147
DOMEventTargetHelper::DisconnectFromOwner();
148
}
149
150
void ServiceWorkerContainer::ControllerChanged(ErrorResult& aRv) {
151
nsCOMPtr<nsIGlobalObject> go = GetParentObject();
152
if (!go) {
153
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
154
return;
155
}
156
mControllerWorker = go->GetOrCreateServiceWorker(go->GetController().ref());
157
aRv = DispatchTrustedEvent(NS_LITERAL_STRING("controllerchange"));
158
}
159
160
using mozilla::dom::ipc::StructuredCloneData;
161
162
// A ReceivedMessage represents a message sent via
163
// Client.postMessage(). It is used as used both for queuing of
164
// incoming messages and as an interface to DispatchMessage().
165
struct MOZ_HEAP_CLASS ServiceWorkerContainer::ReceivedMessage {
166
explicit ReceivedMessage(const ClientPostMessageArgs& aArgs)
167
: mServiceWorker(aArgs.serviceWorker()) {
168
mClonedData.CopyFromClonedMessageDataForBackgroundChild(aArgs.clonedData());
169
}
170
171
ServiceWorkerDescriptor mServiceWorker;
172
StructuredCloneData mClonedData;
173
174
NS_INLINE_DECL_REFCOUNTING(ReceivedMessage)
175
176
private:
177
~ReceivedMessage() = default;
178
};
179
180
void ServiceWorkerContainer::ReceiveMessage(
181
const ClientPostMessageArgs& aArgs) {
182
RefPtr<ReceivedMessage> message = new ReceivedMessage(aArgs);
183
if (mMessagesStarted) {
184
EnqueueReceivedMessageDispatch(message.forget());
185
} else {
186
mPendingMessages.AppendElement(message.forget());
187
}
188
}
189
190
JSObject* ServiceWorkerContainer::WrapObject(
191
JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
192
return ServiceWorkerContainer_Binding::Wrap(aCx, this, aGivenProto);
193
}
194
195
namespace {
196
197
already_AddRefed<nsIURI> GetBaseURIFromGlobal(nsIGlobalObject* aGlobal,
198
ErrorResult& aRv) {
199
// It would be nice not to require a window here, but right
200
// now we don't have a great way to get the base URL just
201
// from the nsIGlobalObject.
202
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(aGlobal);
203
if (!window) {
204
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
205
return nullptr;
206
}
207
208
Document* doc = window->GetExtantDoc();
209
if (!doc) {
210
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
211
return nullptr;
212
}
213
214
nsCOMPtr<nsIURI> baseURI = doc->GetDocBaseURI();
215
if (!baseURI) {
216
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
217
return nullptr;
218
}
219
220
return baseURI.forget();
221
}
222
223
} // anonymous namespace
224
225
already_AddRefed<Promise> ServiceWorkerContainer::Register(
226
const nsAString& aScriptURL, const RegistrationOptions& aOptions,
227
ErrorResult& aRv) {
228
// Note, we can't use GetGlobalIfValid() from the start here. If we
229
// hit a storage failure we want to log a message with the final
230
// scope string we put together below.
231
nsIGlobalObject* global = GetParentObject();
232
if (!global) {
233
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
234
return nullptr;
235
}
236
237
Maybe<ClientInfo> clientInfo = global->GetClientInfo();
238
if (clientInfo.isNothing()) {
239
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
240
return nullptr;
241
}
242
243
nsCOMPtr<nsIURI> baseURI = GetBaseURIFromGlobal(global, aRv);
244
if (aRv.Failed()) {
245
return nullptr;
246
}
247
248
nsresult rv;
249
nsCOMPtr<nsIURI> scriptURI;
250
rv = NS_NewURI(getter_AddRefs(scriptURI), aScriptURL, nullptr, baseURI);
251
if (NS_WARN_IF(NS_FAILED(rv))) {
252
aRv.ThrowTypeError<MSG_INVALID_URL>(aScriptURL);
253
return nullptr;
254
}
255
256
// In ServiceWorkerContainer.register() the scope argument is parsed against
257
// different base URLs depending on whether it was passed or not.
258
nsCOMPtr<nsIURI> scopeURI;
259
260
// Step 4. If none passed, parse against script's URL
261
if (!aOptions.mScope.WasPassed()) {
262
NS_NAMED_LITERAL_STRING(defaultScope, "./");
263
rv = NS_NewURI(getter_AddRefs(scopeURI), defaultScope, nullptr, scriptURI);
264
if (NS_WARN_IF(NS_FAILED(rv))) {
265
nsAutoCString spec;
266
scriptURI->GetSpec(spec);
267
NS_ConvertUTF8toUTF16 wSpec(spec);
268
aRv.ThrowTypeError<MSG_INVALID_SCOPE>(defaultScope, wSpec);
269
return nullptr;
270
}
271
} else {
272
// Step 5. Parse against entry settings object's base URL.
273
rv = NS_NewURI(getter_AddRefs(scopeURI), aOptions.mScope.Value(), nullptr,
274
baseURI);
275
if (NS_WARN_IF(NS_FAILED(rv))) {
276
nsIURI* uri = baseURI ? baseURI : scriptURI;
277
nsAutoCString spec;
278
uri->GetSpec(spec);
279
NS_ConvertUTF8toUTF16 wSpec(spec);
280
aRv.ThrowTypeError<MSG_INVALID_SCOPE>(aOptions.mScope.Value(), wSpec);
281
return nullptr;
282
}
283
}
284
285
// Strip the any ref from both the script and scope URLs.
286
nsCOMPtr<nsIURI> cloneWithoutRef;
287
aRv = NS_GetURIWithoutRef(scriptURI, getter_AddRefs(cloneWithoutRef));
288
if (aRv.Failed()) {
289
return nullptr;
290
}
291
scriptURI = cloneWithoutRef.forget();
292
293
aRv = NS_GetURIWithoutRef(scopeURI, getter_AddRefs(cloneWithoutRef));
294
if (aRv.Failed()) {
295
return nullptr;
296
}
297
scopeURI = cloneWithoutRef.forget();
298
299
aRv = ServiceWorkerScopeAndScriptAreValid(clientInfo.ref(), scopeURI,
300
scriptURI);
301
if (aRv.Failed()) {
302
return nullptr;
303
}
304
305
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(global);
306
if (!window) {
307
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
308
return nullptr;
309
}
310
311
Document* doc = window->GetExtantDoc();
312
if (!doc) {
313
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
314
return nullptr;
315
}
316
317
// The next section of code executes an NS_CheckContentLoadPolicy()
318
// check. This is necessary to enforce the CSP of the calling client.
319
// Currently this requires an Document. Once bug 965637 lands we
320
// should try to move this into ServiceWorkerScopeAndScriptAreValid()
321
// using the ClientInfo instead of doing a window-specific check here.
322
// See bug 1455077 for further investigation.
323
nsCOMPtr<nsILoadInfo> secCheckLoadInfo = new mozilla::net::LoadInfo(
324
doc->NodePrincipal(), // loading principal
325
doc->NodePrincipal(), // triggering principal
326
doc, // loading node
327
nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK,
328
nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER);
329
330
// Check content policy.
331
int16_t decision = nsIContentPolicy::ACCEPT;
332
rv = NS_CheckContentLoadPolicy(scriptURI, secCheckLoadInfo,
333
NS_LITERAL_CSTRING("application/javascript"),
334
&decision);
335
if (NS_FAILED(rv)) {
336
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
337
return nullptr;
338
}
339
if (NS_WARN_IF(decision != nsIContentPolicy::ACCEPT)) {
340
aRv.Throw(NS_ERROR_CONTENT_BLOCKED);
341
return nullptr;
342
}
343
344
// Get the string representation for both the script and scope since
345
// we sanitized them above.
346
nsCString cleanedScopeURL;
347
aRv = scopeURI->GetSpec(cleanedScopeURL);
348
if (aRv.Failed()) {
349
return nullptr;
350
}
351
352
nsCString cleanedScriptURL;
353
aRv = scriptURI->GetSpec(cleanedScriptURL);
354
if (aRv.Failed()) {
355
return nullptr;
356
}
357
358
// Verify that the global is valid and has permission to store
359
// data. We perform this late so that we can report the final
360
// scope URL in any error message.
361
Unused << GetGlobalIfValid(aRv, [&](Document* aDoc) {
362
AutoTArray<nsString, 1> param;
363
CopyUTF8toUTF16(cleanedScopeURL, *param.AppendElement());
364
nsContentUtils::ReportToConsole(nsIScriptError::errorFlag,
365
NS_LITERAL_CSTRING("Service Workers"), aDoc,
366
nsContentUtils::eDOM_PROPERTIES,
367
"ServiceWorkerRegisterStorageError", param);
368
});
369
370
window->NoteCalledRegisterForServiceWorkerScope(cleanedScopeURL);
371
372
RefPtr<Promise> outer =
373
Promise::Create(global, aRv, Promise::ePropagateUserInteraction);
374
if (aRv.Failed()) {
375
return nullptr;
376
}
377
378
RefPtr<ServiceWorkerContainer> self = this;
379
380
mInner->Register(
381
clientInfo.ref(), cleanedScopeURL, cleanedScriptURL,
382
aOptions.mUpdateViaCache,
383
[self, outer](const ServiceWorkerRegistrationDescriptor& aDesc) {
384
ErrorResult rv;
385
nsIGlobalObject* global = self->GetGlobalIfValid(rv);
386
if (rv.Failed()) {
387
outer->MaybeReject(rv);
388
return;
389
}
390
RefPtr<ServiceWorkerRegistration> reg =
391
global->GetOrCreateServiceWorkerRegistration(aDesc);
392
outer->MaybeResolve(reg);
393
},
394
[outer](ErrorResult& aRv) { outer->MaybeReject(aRv); });
395
396
return outer.forget();
397
}
398
399
already_AddRefed<ServiceWorker> ServiceWorkerContainer::GetController() {
400
RefPtr<ServiceWorker> ref = mControllerWorker;
401
return ref.forget();
402
}
403
404
already_AddRefed<Promise> ServiceWorkerContainer::GetRegistrations(
405
ErrorResult& aRv) {
406
nsIGlobalObject* global = GetGlobalIfValid(aRv, [](Document* aDoc) {
407
nsContentUtils::ReportToConsole(nsIScriptError::errorFlag,
408
NS_LITERAL_CSTRING("Service Workers"), aDoc,
409
nsContentUtils::eDOM_PROPERTIES,
410
"ServiceWorkerGetRegistrationStorageError");
411
});
412
if (aRv.Failed()) {
413
return nullptr;
414
}
415
416
Maybe<ClientInfo> clientInfo = global->GetClientInfo();
417
if (clientInfo.isNothing()) {
418
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
419
return nullptr;
420
}
421
422
RefPtr<Promise> outer =
423
Promise::Create(global, aRv, Promise::ePropagateUserInteraction);
424
if (aRv.Failed()) {
425
return nullptr;
426
}
427
428
RefPtr<ServiceWorkerContainer> self = this;
429
430
mInner->GetRegistrations(
431
clientInfo.ref(),
432
[self,
433
outer](const nsTArray<ServiceWorkerRegistrationDescriptor>& aDescList) {
434
ErrorResult rv;
435
nsIGlobalObject* global = self->GetGlobalIfValid(rv);
436
if (rv.Failed()) {
437
outer->MaybeReject(rv);
438
return;
439
}
440
nsTArray<RefPtr<ServiceWorkerRegistration>> regList;
441
for (auto& desc : aDescList) {
442
RefPtr<ServiceWorkerRegistration> reg =
443
global->GetOrCreateServiceWorkerRegistration(desc);
444
if (reg) {
445
regList.AppendElement(std::move(reg));
446
}
447
}
448
outer->MaybeResolve(regList);
449
},
450
[self, outer](ErrorResult& aRv) { outer->MaybeReject(aRv); });
451
452
return outer.forget();
453
}
454
455
void ServiceWorkerContainer::StartMessages() {
456
while (!mPendingMessages.IsEmpty()) {
457
EnqueueReceivedMessageDispatch(mPendingMessages.ElementAt(0));
458
mPendingMessages.RemoveElementAt(0);
459
}
460
mMessagesStarted = true;
461
}
462
463
already_AddRefed<Promise> ServiceWorkerContainer::GetRegistration(
464
const nsAString& aURL, ErrorResult& aRv) {
465
nsIGlobalObject* global = GetGlobalIfValid(aRv, [](Document* aDoc) {
466
nsContentUtils::ReportToConsole(nsIScriptError::errorFlag,
467
NS_LITERAL_CSTRING("Service Workers"), aDoc,
468
nsContentUtils::eDOM_PROPERTIES,
469
"ServiceWorkerGetRegistrationStorageError");
470
});
471
if (aRv.Failed()) {
472
return nullptr;
473
}
474
475
Maybe<ClientInfo> clientInfo = global->GetClientInfo();
476
if (clientInfo.isNothing()) {
477
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
478
return nullptr;
479
}
480
481
nsCOMPtr<nsIURI> baseURI = GetBaseURIFromGlobal(global, aRv);
482
if (aRv.Failed()) {
483
return nullptr;
484
}
485
486
nsCOMPtr<nsIURI> uri;
487
aRv = NS_NewURI(getter_AddRefs(uri), aURL, nullptr, baseURI);
488
if (aRv.Failed()) {
489
return nullptr;
490
}
491
492
nsCString spec;
493
aRv = uri->GetSpec(spec);
494
if (aRv.Failed()) {
495
return nullptr;
496
}
497
498
RefPtr<Promise> outer =
499
Promise::Create(global, aRv, Promise::ePropagateUserInteraction);
500
if (aRv.Failed()) {
501
return nullptr;
502
}
503
504
RefPtr<ServiceWorkerContainer> self = this;
505
506
mInner->GetRegistration(
507
clientInfo.ref(), spec,
508
[self, outer](const ServiceWorkerRegistrationDescriptor& aDescriptor) {
509
ErrorResult rv;
510
nsIGlobalObject* global = self->GetGlobalIfValid(rv);
511
if (rv.Failed()) {
512
outer->MaybeReject(rv);
513
return;
514
}
515
RefPtr<ServiceWorkerRegistration> reg =
516
global->GetOrCreateServiceWorkerRegistration(aDescriptor);
517
outer->MaybeResolve(reg);
518
},
519
[self, outer](ErrorResult& aRv) {
520
if (!aRv.Failed()) {
521
Unused << self->GetGlobalIfValid(aRv);
522
if (!aRv.Failed()) {
523
outer->MaybeResolveWithUndefined();
524
return;
525
}
526
}
527
outer->MaybeReject(aRv);
528
});
529
530
return outer.forget();
531
}
532
533
Promise* ServiceWorkerContainer::GetReady(ErrorResult& aRv) {
534
if (mReadyPromise) {
535
return mReadyPromise;
536
}
537
538
nsIGlobalObject* global = GetGlobalIfValid(aRv);
539
if (aRv.Failed()) {
540
return nullptr;
541
}
542
MOZ_DIAGNOSTIC_ASSERT(global);
543
544
Maybe<ClientInfo> clientInfo(global->GetClientInfo());
545
if (clientInfo.isNothing()) {
546
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
547
return nullptr;
548
}
549
550
mReadyPromise =
551
Promise::Create(global, aRv, Promise::ePropagateUserInteraction);
552
if (aRv.Failed()) {
553
return nullptr;
554
}
555
556
RefPtr<ServiceWorkerContainer> self = this;
557
RefPtr<Promise> outer = mReadyPromise;
558
559
mInner->GetReady(
560
clientInfo.ref(),
561
[self, outer](const ServiceWorkerRegistrationDescriptor& aDescriptor) {
562
ErrorResult rv;
563
nsIGlobalObject* global = self->GetGlobalIfValid(rv);
564
if (rv.Failed()) {
565
outer->MaybeReject(rv);
566
return;
567
}
568
RefPtr<ServiceWorkerRegistration> reg =
569
global->GetOrCreateServiceWorkerRegistration(aDescriptor);
570
NS_ENSURE_TRUE_VOID(reg);
571
572
// Don't resolve the ready promise until the registration has
573
// reached the right version. This ensures that the active
574
// worker property is set correctly on the registration.
575
reg->WhenVersionReached(
576
aDescriptor.Version(),
577
[outer, reg](bool aResult) { outer->MaybeResolve(reg); });
578
},
579
[self, outer](ErrorResult& aRv) { outer->MaybeReject(aRv); });
580
581
return mReadyPromise;
582
}
583
584
// Testing only.
585
void ServiceWorkerContainer::GetScopeForUrl(const nsAString& aUrl,
586
nsString& aScope,
587
ErrorResult& aRv) {
588
nsCOMPtr<nsIServiceWorkerManager> swm =
589
mozilla::services::GetServiceWorkerManager();
590
if (!swm) {
591
aRv.Throw(NS_ERROR_FAILURE);
592
return;
593
}
594
595
nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
596
if (NS_WARN_IF(!window)) {
597
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
598
return;
599
}
600
601
nsCOMPtr<Document> doc = window->GetExtantDoc();
602
if (NS_WARN_IF(!doc)) {
603
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
604
return;
605
}
606
607
aRv = swm->GetScopeForUrl(doc->NodePrincipal(), aUrl, aScope);
608
}
609
610
nsIGlobalObject* ServiceWorkerContainer::GetGlobalIfValid(
611
ErrorResult& aRv,
612
const std::function<void(Document*)>&& aStorageFailureCB) const {
613
// For now we require a window since ServiceWorkerContainer is
614
// not exposed on worker globals yet. The main thing we need
615
// to fix here to support that is the storage access check via
616
// the nsIGlobalObject.
617
nsPIDOMWindowInner* window = GetOwner();
618
if (NS_WARN_IF(!window)) {
619
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
620
return nullptr;
621
}
622
623
nsCOMPtr<Document> doc = window->GetExtantDoc();
624
if (NS_WARN_IF(!doc)) {
625
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
626
return nullptr;
627
}
628
629
// Don't allow a service worker to access service worker registrations
630
// from a window with storage disabled. If these windows can access
631
// the registration it increases the chance they can bypass the storage
632
// block via postMessage(), etc.
633
auto storageAllowed = StorageAllowedForWindow(window);
634
if (NS_WARN_IF(storageAllowed != StorageAccess::eAllow)) {
635
if (aStorageFailureCB) {
636
aStorageFailureCB(doc);
637
}
638
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
639
return nullptr;
640
}
641
642
// Don't allow service workers when the document is chrome.
643
if (NS_WARN_IF(doc->NodePrincipal()->IsSystemPrincipal())) {
644
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
645
return nullptr;
646
}
647
648
return window->AsGlobal();
649
}
650
651
void ServiceWorkerContainer::EnqueueReceivedMessageDispatch(
652
RefPtr<ReceivedMessage> aMessage) {
653
if (nsPIDOMWindowInner* const window = GetOwner()) {
654
if (auto* const target = window->EventTargetFor(TaskCategory::Other)) {
655
target->Dispatch(NewRunnableMethod<RefPtr<ReceivedMessage>>(
656
"ServiceWorkerContainer::DispatchMessage", this,
657
&ServiceWorkerContainer::DispatchMessage, std::move(aMessage)));
658
}
659
}
660
}
661
662
template <typename F>
663
void ServiceWorkerContainer::RunWithJSContext(F&& aCallable) {
664
nsCOMPtr<nsIGlobalObject> globalObject;
665
if (nsPIDOMWindowInner* const window = GetOwner()) {
666
globalObject = do_QueryInterface(window);
667
}
668
669
// If AutoJSAPI::Init() fails then either global is nullptr or not
670
// in a usable state.
671
AutoJSAPI jsapi;
672
if (!jsapi.Init(globalObject)) {
673
return;
674
}
675
676
aCallable(jsapi.cx(), globalObject);
677
}
678
679
void ServiceWorkerContainer::DispatchMessage(RefPtr<ReceivedMessage> aMessage) {
680
MOZ_ASSERT(NS_IsMainThread());
681
682
// When dispatching a message, either DOMContentLoaded has already
683
// been fired, or someone called startMessages() or set onmessage.
684
// Either way, a global object is supposed to be present. If it's
685
// not, we'd fail to initialize the JS API and exit.
686
RunWithJSContext([this, message = std::move(aMessage)](
687
JSContext* const aCx, nsIGlobalObject* const aGlobal) {
688
ErrorResult result;
689
bool deserializationFailed = false;
690
RootedDictionary<MessageEventInit> init(aCx);
691
if (!FillInMessageEventInit(aCx, aGlobal, *message, init, result)) {
692
deserializationFailed = result.ErrorCodeIs(NS_ERROR_DOM_DATA_CLONE_ERR);
693
MOZ_ASSERT_IF(deserializationFailed, init.mData.isNull());
694
MOZ_ASSERT_IF(deserializationFailed, init.mPorts.IsEmpty());
695
MOZ_ASSERT_IF(deserializationFailed, !init.mOrigin.IsEmpty());
696
MOZ_ASSERT_IF(deserializationFailed, !init.mSource.IsNull());
697
698
if (!deserializationFailed && result.MaybeSetPendingException(aCx)) {
699
return;
700
}
701
}
702
703
RefPtr<MessageEvent> event = MessageEvent::Constructor(
704
this,
705
deserializationFailed ? NS_LITERAL_STRING("messageerror")
706
: NS_LITERAL_STRING("message"),
707
init);
708
event->SetTrusted(true);
709
710
result = NS_OK;
711
DispatchEvent(*event, result);
712
if (result.Failed()) {
713
result.SuppressException();
714
}
715
});
716
}
717
718
namespace {
719
720
nsresult FillInOriginNoSuffix(const ServiceWorkerDescriptor& aServiceWorker,
721
nsString& aOrigin) {
722
using mozilla::ipc::PrincipalInfoToPrincipal;
723
724
nsresult rv;
725
726
nsCOMPtr<nsIPrincipal> principal =
727
PrincipalInfoToPrincipal(aServiceWorker.PrincipalInfo(), &rv);
728
if (NS_FAILED(rv) || !principal) {
729
return rv;
730
}
731
732
nsAutoCString originUTF8;
733
rv = principal->GetOriginNoSuffix(originUTF8);
734
if (NS_FAILED(rv)) {
735
return rv;
736
}
737
738
CopyUTF8toUTF16(originUTF8, aOrigin);
739
return NS_OK;
740
}
741
742
already_AddRefed<ServiceWorker> GetOrCreateServiceWorkerWithoutWarnings(
743
nsIGlobalObject* const aGlobal,
744
const ServiceWorkerDescriptor& aDescriptor) {
745
// In child-intercept mode we have to verify that the registration
746
// exists in the current process. This exact check is also performed
747
// (indirectly) in nsIGlobalObject::GetOrCreateServiceWorker, but it
748
// also emits a warning when the registration is not present. To
749
// to avoid having too many warnings, we do a precheck here.
750
if (!ServiceWorkerParentInterceptEnabled()) {
751
const RefPtr<ServiceWorkerManager> serviceWorkerManager =
752
ServiceWorkerManager::GetInstance();
753
if (!serviceWorkerManager) {
754
return nullptr;
755
}
756
757
const RefPtr<ServiceWorkerRegistrationInfo> registration =
758
serviceWorkerManager->GetRegistration(aDescriptor.PrincipalInfo(),
759
aDescriptor.Scope());
760
if (!registration) {
761
return nullptr;
762
}
763
}
764
765
return aGlobal->GetOrCreateServiceWorker(aDescriptor).forget();
766
}
767
768
} // namespace
769
770
bool ServiceWorkerContainer::FillInMessageEventInit(
771
JSContext* const aCx, nsIGlobalObject* const aGlobal,
772
ReceivedMessage& aMessage, MessageEventInit& aInit, ErrorResult& aRv) {
773
// Determining the source and origin should preceed attempting deserialization
774
// because on a "messageerror" event (i.e. when deserialization fails), the
775
// dispatched message needs to contain such an origin and source, per spec:
776
//
777
// "If this throws an exception, catch it, fire an event named messageerror
778
// at destination, using MessageEvent, with the origin attribute initialized
779
// to origin and the source attribute initialized to source, and then abort
780
// these steps." - 6.4 of postMessage
782
const RefPtr<ServiceWorker> serviceWorkerInstance =
783
GetOrCreateServiceWorkerWithoutWarnings(aGlobal, aMessage.mServiceWorker);
784
if (serviceWorkerInstance) {
785
aInit.mSource.SetValue().SetAsServiceWorker() = serviceWorkerInstance;
786
}
787
788
const nsresult rv =
789
FillInOriginNoSuffix(aMessage.mServiceWorker, aInit.mOrigin);
790
if (NS_FAILED(rv)) {
791
return false;
792
}
793
794
JS::Rooted<JS::Value> messageData(aCx);
795
aMessage.mClonedData.Read(aCx, &messageData, aRv);
796
if (aRv.Failed()) {
797
return false;
798
}
799
800
aInit.mData = messageData;
801
802
if (!aMessage.mClonedData.TakeTransferredPortsAsSequence(aInit.mPorts)) {
803
xpc::Throw(aCx, NS_ERROR_OUT_OF_MEMORY);
804
return false;
805
}
806
807
return true;
808
}
809
810
} // namespace dom
811
} // namespace mozilla