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 "ServiceWorkerEvents.h"
8
9
#include <utility>
10
11
#include "nsAutoPtr.h"
12
#include "nsContentUtils.h"
13
#include "nsIConsoleReportCollector.h"
14
#include "nsINetworkInterceptController.h"
15
#include "nsIScriptError.h"
16
#include "mozilla/Encoding.h"
17
#include "nsContentPolicyUtils.h"
18
#include "nsContentUtils.h"
19
#include "nsComponentManagerUtils.h"
20
#include "nsServiceManagerUtils.h"
21
#include "nsStreamUtils.h"
22
#include "nsNetCID.h"
23
#include "nsNetUtil.h"
24
#include "nsSerializationHelper.h"
25
#include "nsQueryObject.h"
26
#include "ServiceWorker.h"
27
#include "ServiceWorkerManager.h"
28
29
#include "mozilla/ErrorResult.h"
30
#include "mozilla/LoadInfo.h"
31
#include "mozilla/Move.h"
32
#include "mozilla/Preferences.h"
33
#include "mozilla/dom/BodyUtil.h"
34
#include "mozilla/dom/Client.h"
35
#include "mozilla/dom/EventBinding.h"
36
#include "mozilla/dom/FetchEventBinding.h"
37
#include "mozilla/dom/MessagePort.h"
38
#include "mozilla/dom/PromiseNativeHandler.h"
39
#include "mozilla/dom/PushEventBinding.h"
40
#include "mozilla/dom/PushMessageDataBinding.h"
41
#include "mozilla/dom/PushUtil.h"
42
#include "mozilla/dom/Request.h"
43
#include "mozilla/dom/ServiceWorkerOp.h"
44
#include "mozilla/dom/TypedArray.h"
45
#include "mozilla/dom/Response.h"
46
#include "mozilla/dom/WorkerScope.h"
47
#include "mozilla/dom/WorkerPrivate.h"
48
#include "mozilla/net/NeckoChannelParams.h"
49
50
#include "js/Conversions.h"
51
#include "js/TypeDecls.h"
52
#include "xpcpublic.h"
53
54
using namespace mozilla;
55
using namespace mozilla::dom;
56
57
namespace {
58
59
void AsyncLog(nsIInterceptedChannel* aInterceptedChannel,
60
const nsACString& aRespondWithScriptSpec,
61
uint32_t aRespondWithLineNumber,
62
uint32_t aRespondWithColumnNumber, const nsACString& aMessageName,
63
const nsTArray<nsString>& aParams) {
64
MOZ_ASSERT(aInterceptedChannel);
65
nsCOMPtr<nsIConsoleReportCollector> reporter =
66
aInterceptedChannel->GetConsoleReportCollector();
67
if (reporter) {
68
reporter->AddConsoleReport(
69
nsIScriptError::errorFlag,
70
NS_LITERAL_CSTRING("Service Worker Interception"),
71
nsContentUtils::eDOM_PROPERTIES, aRespondWithScriptSpec,
72
aRespondWithLineNumber, aRespondWithColumnNumber, aMessageName,
73
aParams);
74
}
75
}
76
77
template <typename... Params>
78
void AsyncLog(nsIInterceptedChannel* aInterceptedChannel,
79
const nsACString& aRespondWithScriptSpec,
80
uint32_t aRespondWithLineNumber,
81
uint32_t aRespondWithColumnNumber,
82
// We have to list one explicit string so that calls with an
83
// nsTArray of params won't end up in here.
84
const nsACString& aMessageName, const nsAString& aFirstParam,
85
Params&&... aParams) {
86
nsTArray<nsString> paramsList(sizeof...(Params) + 1);
87
StringArrayAppender::Append(paramsList, sizeof...(Params) + 1, aFirstParam,
88
std::forward<Params>(aParams)...);
89
AsyncLog(aInterceptedChannel, aRespondWithScriptSpec, aRespondWithLineNumber,
90
aRespondWithColumnNumber, aMessageName, paramsList);
91
}
92
93
} // anonymous namespace
94
95
namespace mozilla {
96
namespace dom {
97
98
CancelChannelRunnable::CancelChannelRunnable(
99
nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
100
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
101
nsresult aStatus)
102
: Runnable("dom::CancelChannelRunnable"),
103
mChannel(aChannel),
104
mRegistration(aRegistration),
105
mStatus(aStatus) {}
106
107
NS_IMETHODIMP
108
CancelChannelRunnable::Run() {
109
MOZ_ASSERT(NS_IsMainThread());
110
111
// TODO: When bug 1204254 is implemented, this time marker should be moved to
112
// the point where the body of the network request is complete.
113
mChannel->SetHandleFetchEventEnd(TimeStamp::Now());
114
mChannel->SaveTimeStamps();
115
116
mChannel->CancelInterception(mStatus);
117
mRegistration->MaybeScheduleUpdate();
118
return NS_OK;
119
}
120
121
FetchEvent::FetchEvent(EventTarget* aOwner)
122
: ExtendableEvent(aOwner),
123
mPreventDefaultLineNumber(0),
124
mPreventDefaultColumnNumber(0),
125
mIsReload(false),
126
mWaitToRespond(false) {}
127
128
FetchEvent::~FetchEvent() {}
129
130
void FetchEvent::PostInit(
131
nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
132
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
133
const nsACString& aScriptSpec) {
134
mChannel = aChannel;
135
mRegistration = aRegistration;
136
mScriptSpec.Assign(aScriptSpec);
137
}
138
139
void FetchEvent::PostInit(const nsACString& aScriptSpec,
140
RefPtr<FetchEventOp> aRespondWithHandler) {
141
MOZ_ASSERT(aRespondWithHandler);
142
143
mScriptSpec.Assign(aScriptSpec);
144
mRespondWithHandler = std::move(aRespondWithHandler);
145
}
146
147
/*static*/
148
already_AddRefed<FetchEvent> FetchEvent::Constructor(
149
const GlobalObject& aGlobal, const nsAString& aType,
150
const FetchEventInit& aOptions) {
151
RefPtr<EventTarget> owner = do_QueryObject(aGlobal.GetAsSupports());
152
MOZ_ASSERT(owner);
153
RefPtr<FetchEvent> e = new FetchEvent(owner);
154
bool trusted = e->Init(owner);
155
e->InitEvent(aType, aOptions.mBubbles, aOptions.mCancelable);
156
e->SetTrusted(trusted);
157
e->SetComposed(aOptions.mComposed);
158
e->mRequest = aOptions.mRequest;
159
e->mClientId = aOptions.mClientId;
160
e->mResultingClientId = aOptions.mResultingClientId;
161
e->mIsReload = aOptions.mIsReload;
162
return e.forget();
163
}
164
165
namespace {
166
167
struct RespondWithClosure {
168
nsMainThreadPtrHandle<nsIInterceptedChannel> mInterceptedChannel;
169
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> mRegistration;
170
const nsString mRequestURL;
171
const nsCString mRespondWithScriptSpec;
172
const uint32_t mRespondWithLineNumber;
173
const uint32_t mRespondWithColumnNumber;
174
175
RespondWithClosure(
176
nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
177
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
178
const nsAString& aRequestURL, const nsACString& aRespondWithScriptSpec,
179
uint32_t aRespondWithLineNumber, uint32_t aRespondWithColumnNumber)
180
: mInterceptedChannel(aChannel),
181
mRegistration(aRegistration),
182
mRequestURL(aRequestURL),
183
mRespondWithScriptSpec(aRespondWithScriptSpec),
184
mRespondWithLineNumber(aRespondWithLineNumber),
185
mRespondWithColumnNumber(aRespondWithColumnNumber) {}
186
};
187
188
class FinishResponse final : public Runnable {
189
nsMainThreadPtrHandle<nsIInterceptedChannel> mChannel;
190
191
public:
192
explicit FinishResponse(
193
nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel)
194
: Runnable("dom::FinishResponse"), mChannel(aChannel) {}
195
196
NS_IMETHOD
197
Run() override {
198
MOZ_ASSERT(NS_IsMainThread());
199
200
nsresult rv = mChannel->FinishSynthesizedResponse();
201
if (NS_WARN_IF(NS_FAILED(rv))) {
202
mChannel->CancelInterception(NS_ERROR_INTERCEPTION_FAILED);
203
return NS_OK;
204
}
205
206
TimeStamp timeStamp = TimeStamp::Now();
207
mChannel->SetHandleFetchEventEnd(timeStamp);
208
mChannel->SetFinishSynthesizedResponseEnd(timeStamp);
209
mChannel->SaveTimeStamps();
210
211
return rv;
212
}
213
};
214
215
class BodyCopyHandle final : public nsIInterceptedBodyCallback {
216
UniquePtr<RespondWithClosure> mClosure;
217
218
~BodyCopyHandle() {}
219
220
public:
221
NS_DECL_THREADSAFE_ISUPPORTS
222
223
explicit BodyCopyHandle(UniquePtr<RespondWithClosure>&& aClosure)
224
: mClosure(std::move(aClosure)) {}
225
226
NS_IMETHOD
227
BodyComplete(nsresult aRv) override {
228
MOZ_ASSERT(NS_IsMainThread());
229
230
nsCOMPtr<nsIRunnable> event;
231
if (NS_WARN_IF(NS_FAILED(aRv))) {
232
AsyncLog(mClosure->mInterceptedChannel, mClosure->mRespondWithScriptSpec,
233
mClosure->mRespondWithLineNumber,
234
mClosure->mRespondWithColumnNumber,
235
NS_LITERAL_CSTRING("InterceptionFailedWithURL"),
236
mClosure->mRequestURL);
237
event = new CancelChannelRunnable(mClosure->mInterceptedChannel,
238
mClosure->mRegistration,
239
NS_ERROR_INTERCEPTION_FAILED);
240
} else {
241
event = new FinishResponse(mClosure->mInterceptedChannel);
242
}
243
244
mClosure.reset();
245
246
event->Run();
247
248
return NS_OK;
249
}
250
};
251
252
NS_IMPL_ISUPPORTS(BodyCopyHandle, nsIInterceptedBodyCallback)
253
254
class StartResponse final : public Runnable {
255
nsMainThreadPtrHandle<nsIInterceptedChannel> mChannel;
256
RefPtr<InternalResponse> mInternalResponse;
257
ChannelInfo mWorkerChannelInfo;
258
const nsCString mScriptSpec;
259
const nsCString mResponseURLSpec;
260
UniquePtr<RespondWithClosure> mClosure;
261
262
public:
263
StartResponse(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
264
InternalResponse* aInternalResponse,
265
const ChannelInfo& aWorkerChannelInfo,
266
const nsACString& aScriptSpec,
267
const nsACString& aResponseURLSpec,
268
UniquePtr<RespondWithClosure>&& aClosure)
269
: Runnable("dom::StartResponse"),
270
mChannel(aChannel),
271
mInternalResponse(aInternalResponse),
272
mWorkerChannelInfo(aWorkerChannelInfo),
273
mScriptSpec(aScriptSpec),
274
mResponseURLSpec(aResponseURLSpec),
275
mClosure(std::move(aClosure)) {}
276
277
NS_IMETHOD
278
Run() override {
279
MOZ_ASSERT(NS_IsMainThread());
280
281
nsCOMPtr<nsIChannel> underlyingChannel;
282
nsresult rv = mChannel->GetChannel(getter_AddRefs(underlyingChannel));
283
NS_ENSURE_SUCCESS(rv, rv);
284
NS_ENSURE_TRUE(underlyingChannel, NS_ERROR_UNEXPECTED);
285
nsCOMPtr<nsILoadInfo> loadInfo = underlyingChannel->LoadInfo();
286
287
if (!CSPPermitsResponse(loadInfo)) {
288
mChannel->CancelInterception(NS_ERROR_CONTENT_BLOCKED);
289
return NS_OK;
290
}
291
292
ChannelInfo channelInfo;
293
if (mInternalResponse->GetChannelInfo().IsInitialized()) {
294
channelInfo = mInternalResponse->GetChannelInfo();
295
} else {
296
// We are dealing with a synthesized response here, so fall back to the
297
// channel info for the worker script.
298
channelInfo = mWorkerChannelInfo;
299
}
300
rv = mChannel->SetChannelInfo(&channelInfo);
301
if (NS_WARN_IF(NS_FAILED(rv))) {
302
mChannel->CancelInterception(NS_ERROR_INTERCEPTION_FAILED);
303
return NS_OK;
304
}
305
306
rv = mChannel->SynthesizeStatus(
307
mInternalResponse->GetUnfilteredStatus(),
308
mInternalResponse->GetUnfilteredStatusText());
309
if (NS_WARN_IF(NS_FAILED(rv))) {
310
mChannel->CancelInterception(NS_ERROR_INTERCEPTION_FAILED);
311
return NS_OK;
312
}
313
314
AutoTArray<InternalHeaders::Entry, 5> entries;
315
mInternalResponse->UnfilteredHeaders()->GetEntries(entries);
316
for (uint32_t i = 0; i < entries.Length(); ++i) {
317
mChannel->SynthesizeHeader(entries[i].mName, entries[i].mValue);
318
}
319
320
auto castLoadInfo = static_cast<mozilla::net::LoadInfo*>(loadInfo.get());
321
castLoadInfo->SynthesizeServiceWorkerTainting(
322
mInternalResponse->GetTainting());
323
324
// Get the preferred alternative data type of outter channel
325
nsAutoCString preferredAltDataType(EmptyCString());
326
nsCOMPtr<nsICacheInfoChannel> outerChannel =
327
do_QueryInterface(underlyingChannel);
328
if (outerChannel &&
329
!outerChannel->PreferredAlternativeDataTypes().IsEmpty()) {
330
// TODO: handle multiple types properly.
331
preferredAltDataType.Assign(
332
outerChannel->PreferredAlternativeDataTypes()[0].type());
333
}
334
335
// Get the alternative data type saved in the InternalResponse
336
nsAutoCString altDataType;
337
nsCOMPtr<nsICacheInfoChannel> cacheInfoChannel =
338
mInternalResponse->TakeCacheInfoChannel().get();
339
if (cacheInfoChannel) {
340
cacheInfoChannel->GetAlternativeDataType(altDataType);
341
}
342
343
nsCOMPtr<nsIInputStream> body;
344
if (preferredAltDataType.Equals(altDataType)) {
345
body = mInternalResponse->TakeAlternativeBody();
346
}
347
if (!body) {
348
mInternalResponse->GetUnfilteredBody(getter_AddRefs(body));
349
} else {
350
Telemetry::ScalarAdd(Telemetry::ScalarID::SW_ALTERNATIVE_BODY_USED_COUNT,
351
1);
352
}
353
354
RefPtr<BodyCopyHandle> copyHandle;
355
copyHandle = new BodyCopyHandle(std::move(mClosure));
356
357
rv = mChannel->StartSynthesizedResponse(body, copyHandle, cacheInfoChannel,
358
mResponseURLSpec,
359
mInternalResponse->IsRedirected());
360
if (NS_WARN_IF(NS_FAILED(rv))) {
361
mChannel->CancelInterception(NS_ERROR_INTERCEPTION_FAILED);
362
return NS_OK;
363
}
364
365
nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
366
if (obsService) {
367
obsService->NotifyObservers(
368
underlyingChannel, "service-worker-synthesized-response", nullptr);
369
}
370
371
return rv;
372
}
373
374
bool CSPPermitsResponse(nsILoadInfo* aLoadInfo) {
375
MOZ_ASSERT(NS_IsMainThread());
376
MOZ_ASSERT(aLoadInfo);
377
nsresult rv;
378
nsCOMPtr<nsIURI> uri;
379
nsCString url = mInternalResponse->GetUnfilteredURL();
380
if (url.IsEmpty()) {
381
// Synthetic response. The buck stops at the worker script.
382
url = mScriptSpec;
383
}
384
rv = NS_NewURI(getter_AddRefs(uri), url);
385
NS_ENSURE_SUCCESS(rv, false);
386
int16_t decision = nsIContentPolicy::ACCEPT;
387
rv = NS_CheckContentLoadPolicy(uri, aLoadInfo, EmptyCString(), &decision);
388
NS_ENSURE_SUCCESS(rv, false);
389
return decision == nsIContentPolicy::ACCEPT;
390
}
391
};
392
393
class RespondWithHandler final : public PromiseNativeHandler {
394
nsMainThreadPtrHandle<nsIInterceptedChannel> mInterceptedChannel;
395
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> mRegistration;
396
const RequestMode mRequestMode;
397
const RequestRedirect mRequestRedirectMode;
398
#ifdef DEBUG
399
const bool mIsClientRequest;
400
#endif
401
const nsCString mScriptSpec;
402
const nsString mRequestURL;
403
const nsCString mRequestFragment;
404
const nsCString mRespondWithScriptSpec;
405
const uint32_t mRespondWithLineNumber;
406
const uint32_t mRespondWithColumnNumber;
407
bool mRequestWasHandled;
408
409
public:
410
NS_DECL_ISUPPORTS
411
412
RespondWithHandler(
413
nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
414
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
415
RequestMode aRequestMode, bool aIsClientRequest,
416
RequestRedirect aRedirectMode, const nsACString& aScriptSpec,
417
const nsAString& aRequestURL, const nsACString& aRequestFragment,
418
const nsACString& aRespondWithScriptSpec, uint32_t aRespondWithLineNumber,
419
uint32_t aRespondWithColumnNumber)
420
: mInterceptedChannel(aChannel),
421
mRegistration(aRegistration),
422
mRequestMode(aRequestMode),
423
mRequestRedirectMode(aRedirectMode)
424
#ifdef DEBUG
425
,
426
mIsClientRequest(aIsClientRequest)
427
#endif
428
,
429
mScriptSpec(aScriptSpec),
430
mRequestURL(aRequestURL),
431
mRequestFragment(aRequestFragment),
432
mRespondWithScriptSpec(aRespondWithScriptSpec),
433
mRespondWithLineNumber(aRespondWithLineNumber),
434
mRespondWithColumnNumber(aRespondWithColumnNumber),
435
mRequestWasHandled(false) {
436
}
437
438
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
439
440
void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
441
442
void CancelRequest(nsresult aStatus);
443
444
void AsyncLog(const nsACString& aMessageName,
445
const nsTArray<nsString>& aParams) {
446
::AsyncLog(mInterceptedChannel, mRespondWithScriptSpec,
447
mRespondWithLineNumber, mRespondWithColumnNumber, aMessageName,
448
aParams);
449
}
450
451
void AsyncLog(const nsACString& aSourceSpec, uint32_t aLine, uint32_t aColumn,
452
const nsACString& aMessageName,
453
const nsTArray<nsString>& aParams) {
454
::AsyncLog(mInterceptedChannel, aSourceSpec, aLine, aColumn, aMessageName,
455
aParams);
456
}
457
458
private:
459
~RespondWithHandler() {
460
if (!mRequestWasHandled) {
461
::AsyncLog(mInterceptedChannel, mRespondWithScriptSpec,
462
mRespondWithLineNumber, mRespondWithColumnNumber,
463
NS_LITERAL_CSTRING("InterceptionFailedWithURL"), mRequestURL);
464
CancelRequest(NS_ERROR_INTERCEPTION_FAILED);
465
}
466
}
467
};
468
469
class MOZ_STACK_CLASS AutoCancel {
470
RefPtr<RespondWithHandler> mOwner;
471
nsCString mSourceSpec;
472
uint32_t mLine;
473
uint32_t mColumn;
474
nsCString mMessageName;
475
nsTArray<nsString> mParams;
476
477
public:
478
AutoCancel(RespondWithHandler* aOwner, const nsString& aRequestURL)
479
: mOwner(aOwner),
480
mLine(0),
481
mColumn(0),
482
mMessageName(NS_LITERAL_CSTRING("InterceptionFailedWithURL")) {
483
mParams.AppendElement(aRequestURL);
484
}
485
486
~AutoCancel() {
487
if (mOwner) {
488
if (mSourceSpec.IsEmpty()) {
489
mOwner->AsyncLog(mMessageName, mParams);
490
} else {
491
mOwner->AsyncLog(mSourceSpec, mLine, mColumn, mMessageName, mParams);
492
}
493
mOwner->CancelRequest(NS_ERROR_INTERCEPTION_FAILED);
494
}
495
}
496
497
// This function steals the error message from a ErrorResult.
498
void SetCancelErrorResult(JSContext* aCx, ErrorResult& aRv) {
499
MOZ_DIAGNOSTIC_ASSERT(aRv.Failed());
500
MOZ_DIAGNOSTIC_ASSERT(!JS_IsExceptionPending(aCx));
501
502
// Storing the error as exception in the JSContext.
503
if (!aRv.MaybeSetPendingException(aCx)) {
504
return;
505
}
506
507
MOZ_ASSERT(!aRv.Failed());
508
509
// Let's take the pending exception.
510
JS::Rooted<JS::Value> exn(aCx);
511
if (!JS_GetPendingException(aCx, &exn)) {
512
return;
513
}
514
515
JS_ClearPendingException(aCx);
516
517
// Converting the exception in a js::ErrorReport.
518
js::ErrorReport report(aCx);
519
if (!report.init(aCx, exn, js::ErrorReport::WithSideEffects)) {
520
JS_ClearPendingException(aCx);
521
return;
522
}
523
524
MOZ_ASSERT(mOwner);
525
MOZ_ASSERT(mMessageName.EqualsLiteral("InterceptionFailedWithURL"));
526
MOZ_ASSERT(mParams.Length() == 1);
527
528
// Let's store the error message here.
529
mMessageName.Assign(report.toStringResult().c_str());
530
mParams.Clear();
531
}
532
533
template <typename... Params>
534
void SetCancelMessage(const nsACString& aMessageName, Params&&... aParams) {
535
MOZ_ASSERT(mOwner);
536
MOZ_ASSERT(mMessageName.EqualsLiteral("InterceptionFailedWithURL"));
537
MOZ_ASSERT(mParams.Length() == 1);
538
mMessageName = aMessageName;
539
mParams.Clear();
540
StringArrayAppender::Append(mParams, sizeof...(Params),
541
std::forward<Params>(aParams)...);
542
}
543
544
template <typename... Params>
545
void SetCancelMessageAndLocation(const nsACString& aSourceSpec,
546
uint32_t aLine, uint32_t aColumn,
547
const nsACString& aMessageName,
548
Params&&... aParams) {
549
MOZ_ASSERT(mOwner);
550
MOZ_ASSERT(mMessageName.EqualsLiteral("InterceptionFailedWithURL"));
551
MOZ_ASSERT(mParams.Length() == 1);
552
553
mSourceSpec = aSourceSpec;
554
mLine = aLine;
555
mColumn = aColumn;
556
557
mMessageName = aMessageName;
558
mParams.Clear();
559
StringArrayAppender::Append(mParams, sizeof...(Params),
560
std::forward<Params>(aParams)...);
561
}
562
563
void Reset() { mOwner = nullptr; }
564
};
565
566
NS_IMPL_ISUPPORTS0(RespondWithHandler)
567
568
void RespondWithHandler::ResolvedCallback(JSContext* aCx,
569
JS::Handle<JS::Value> aValue) {
570
AutoCancel autoCancel(this, mRequestURL);
571
mInterceptedChannel->SetFinishResponseStart(TimeStamp::Now());
572
573
if (!aValue.isObject()) {
574
NS_WARNING(
575
"FetchEvent::RespondWith was passed a promise resolved to a non-Object "
576
"value");
577
578
nsCString sourceSpec;
579
uint32_t line = 0;
580
uint32_t column = 0;
581
nsString valueString;
582
nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column,
583
valueString);
584
585
autoCancel.SetCancelMessageAndLocation(
586
sourceSpec, line, column,
587
NS_LITERAL_CSTRING("InterceptedNonResponseWithURL"), mRequestURL,
588
valueString);
589
return;
590
}
591
592
RefPtr<Response> response;
593
nsresult rv = UNWRAP_OBJECT(Response, &aValue.toObject(), response);
594
if (NS_FAILED(rv)) {
595
nsCString sourceSpec;
596
uint32_t line = 0;
597
uint32_t column = 0;
598
nsString valueString;
599
nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column,
600
valueString);
601
602
autoCancel.SetCancelMessageAndLocation(
603
sourceSpec, line, column,
604
NS_LITERAL_CSTRING("InterceptedNonResponseWithURL"), mRequestURL,
605
valueString);
606
return;
607
}
608
609
WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
610
MOZ_ASSERT(worker);
611
worker->AssertIsOnWorkerThread();
612
613
// Section "HTTP Fetch", step 3.3:
614
// If one of the following conditions is true, return a network error:
615
// * response's type is "error".
616
// * request's mode is not "no-cors" and response's type is "opaque".
617
// * request's redirect mode is not "manual" and response's type is
618
// "opaqueredirect".
619
// * request's redirect mode is not "follow" and response's url list
620
// has more than one item.
621
622
if (response->Type() == ResponseType::Error) {
623
autoCancel.SetCancelMessage(
624
NS_LITERAL_CSTRING("InterceptedErrorResponseWithURL"), mRequestURL);
625
return;
626
}
627
628
MOZ_ASSERT_IF(mIsClientRequest, mRequestMode == RequestMode::Same_origin ||
629
mRequestMode == RequestMode::Navigate);
630
631
if (response->Type() == ResponseType::Opaque &&
632
mRequestMode != RequestMode::No_cors) {
633
NS_ConvertASCIItoUTF16 modeString(
634
RequestModeValues::GetString(mRequestMode));
635
636
autoCancel.SetCancelMessage(
637
NS_LITERAL_CSTRING("BadOpaqueInterceptionRequestModeWithURL"),
638
mRequestURL, modeString);
639
return;
640
}
641
642
if (mRequestRedirectMode != RequestRedirect::Manual &&
643
response->Type() == ResponseType::Opaqueredirect) {
644
autoCancel.SetCancelMessage(
645
NS_LITERAL_CSTRING("BadOpaqueRedirectInterceptionWithURL"),
646
mRequestURL);
647
return;
648
}
649
650
if (mRequestRedirectMode != RequestRedirect::Follow &&
651
response->Redirected()) {
652
autoCancel.SetCancelMessage(
653
NS_LITERAL_CSTRING("BadRedirectModeInterceptionWithURL"), mRequestURL);
654
return;
655
}
656
657
{
658
ErrorResult error;
659
bool bodyUsed = response->GetBodyUsed(error);
660
error.WouldReportJSException();
661
if (NS_WARN_IF(error.Failed())) {
662
autoCancel.SetCancelErrorResult(aCx, error);
663
return;
664
}
665
if (NS_WARN_IF(bodyUsed)) {
666
autoCancel.SetCancelMessage(
667
NS_LITERAL_CSTRING("InterceptedUsedResponseWithURL"), mRequestURL);
668
return;
669
}
670
}
671
672
RefPtr<InternalResponse> ir = response->GetInternalResponse();
673
if (NS_WARN_IF(!ir)) {
674
return;
675
}
676
677
// An extra safety check to make sure our invariant that opaque and cors
678
// responses always have a URL does not break.
679
if (NS_WARN_IF((response->Type() == ResponseType::Opaque ||
680
response->Type() == ResponseType::Cors) &&
681
ir->GetUnfilteredURL().IsEmpty())) {
682
MOZ_DIAGNOSTIC_ASSERT(false, "Cors or opaque Response without a URL");
683
return;
684
}
685
686
Telemetry::ScalarAdd(Telemetry::ScalarID::SW_SYNTHESIZED_RES_COUNT, 1);
687
688
if (mRequestMode == RequestMode::Same_origin &&
689
response->Type() == ResponseType::Cors) {
690
Telemetry::ScalarAdd(Telemetry::ScalarID::SW_CORS_RES_FOR_SO_REQ_COUNT, 1);
691
692
// XXXtt: Will have a pref to enable the quirk response in bug 1419684.
693
// The variadic template provided by StringArrayAppender requires exactly
694
// an nsString.
695
NS_ConvertUTF8toUTF16 responseURL(ir->GetUnfilteredURL());
696
autoCancel.SetCancelMessage(
697
NS_LITERAL_CSTRING("CorsResponseForSameOriginRequest"), mRequestURL,
698
responseURL);
699
return;
700
}
701
702
// Propagate the URL to the content if the request mode is not "navigate".
703
// Note that, we only reflect the final URL if the response.redirected is
704
// false. We propagate all the URLs if the response.redirected is true.
705
nsCString responseURL;
706
if (mRequestMode != RequestMode::Navigate) {
707
responseURL = ir->GetUnfilteredURL();
708
709
// Similar to how we apply the request fragment to redirects automatically
710
// we also want to apply it automatically when propagating the response
711
// URL from a service worker interception. Currently response.url strips
712
// the fragment, so this will never conflict with an existing fragment
713
// on the response. In the future we will have to check for a response
714
// fragment and avoid overriding in that case.
715
if (!mRequestFragment.IsEmpty() && !responseURL.IsEmpty()) {
716
MOZ_ASSERT(!responseURL.Contains('#'));
717
responseURL.Append(NS_LITERAL_CSTRING("#"));
718
responseURL.Append(mRequestFragment);
719
}
720
}
721
722
UniquePtr<RespondWithClosure> closure(new RespondWithClosure(
723
mInterceptedChannel, mRegistration, mRequestURL, mRespondWithScriptSpec,
724
mRespondWithLineNumber, mRespondWithColumnNumber));
725
726
nsCOMPtr<nsIRunnable> startRunnable =
727
new StartResponse(mInterceptedChannel, ir, worker->GetChannelInfo(),
728
mScriptSpec, responseURL, std::move(closure));
729
730
nsCOMPtr<nsIInputStream> body;
731
ir->GetUnfilteredBody(getter_AddRefs(body));
732
// Errors and redirects may not have a body.
733
if (body) {
734
ErrorResult error;
735
response->SetBodyUsed(aCx, error);
736
error.WouldReportJSException();
737
if (NS_WARN_IF(error.Failed())) {
738
autoCancel.SetCancelErrorResult(aCx, error);
739
return;
740
}
741
}
742
743
MOZ_ALWAYS_SUCCEEDS(worker->DispatchToMainThread(startRunnable.forget()));
744
745
MOZ_ASSERT(!closure);
746
autoCancel.Reset();
747
mRequestWasHandled = true;
748
}
749
750
void RespondWithHandler::RejectedCallback(JSContext* aCx,
751
JS::Handle<JS::Value> aValue) {
752
nsCString sourceSpec = mRespondWithScriptSpec;
753
uint32_t line = mRespondWithLineNumber;
754
uint32_t column = mRespondWithColumnNumber;
755
nsString valueString;
756
757
mInterceptedChannel->SetFinishResponseStart(TimeStamp::Now());
758
759
nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column,
760
valueString);
761
762
::AsyncLog(mInterceptedChannel, sourceSpec, line, column,
763
NS_LITERAL_CSTRING("InterceptionRejectedResponseWithURL"),
764
mRequestURL, valueString);
765
766
CancelRequest(NS_ERROR_INTERCEPTION_FAILED);
767
}
768
769
void RespondWithHandler::CancelRequest(nsresult aStatus) {
770
nsCOMPtr<nsIRunnable> runnable =
771
new CancelChannelRunnable(mInterceptedChannel, mRegistration, aStatus);
772
// Note, this may run off the worker thread during worker termination.
773
WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
774
if (worker) {
775
MOZ_ALWAYS_SUCCEEDS(worker->DispatchToMainThread(runnable.forget()));
776
} else {
777
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(runnable.forget()));
778
}
779
mRequestWasHandled = true;
780
}
781
782
} // namespace
783
784
void FetchEvent::RespondWith(JSContext* aCx, Promise& aArg, ErrorResult& aRv) {
785
if (EventPhase() == Event_Binding::NONE || mWaitToRespond) {
786
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
787
return;
788
}
789
790
// Record where respondWith() was called in the script so we can include the
791
// information in any error reporting. We should be guaranteed not to get
792
// a file:// string here because service workers require http/https.
793
nsCString spec;
794
uint32_t line = 0;
795
uint32_t column = 0;
796
nsJSUtils::GetCallingLocation(aCx, spec, &line, &column);
797
798
RefPtr<InternalRequest> ir = mRequest->GetInternalRequest();
799
800
nsAutoCString requestURL;
801
ir->GetURL(requestURL);
802
803
StopImmediatePropagation();
804
mWaitToRespond = true;
805
806
if (mChannel) {
807
RefPtr<RespondWithHandler> handler = new RespondWithHandler(
808
mChannel, mRegistration, mRequest->Mode(), ir->IsClientRequest(),
809
mRequest->Redirect(), mScriptSpec, NS_ConvertUTF8toUTF16(requestURL),
810
ir->GetFragment(), spec, line, column);
811
812
aArg.AppendNativeHandler(handler);
813
} else {
814
MOZ_ASSERT(mRespondWithHandler);
815
816
mRespondWithHandler->RespondWithCalledAt(spec, line, column);
817
aArg.AppendNativeHandler(mRespondWithHandler);
818
mRespondWithHandler = nullptr;
819
}
820
821
if (!WaitOnPromise(aArg)) {
822
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
823
}
824
}
825
826
void FetchEvent::PreventDefault(JSContext* aCx, CallerType aCallerType) {
827
MOZ_ASSERT(aCx);
828
MOZ_ASSERT(aCallerType != CallerType::System,
829
"Since when do we support system-principal service workers?");
830
831
if (mPreventDefaultScriptSpec.IsEmpty()) {
832
// Note when the FetchEvent might have been canceled by script, but don't
833
// actually log the location until we are sure it matters. This is
834
// determined in ServiceWorkerPrivate.cpp. We only remember the first
835
// call to preventDefault() as its the most likely to have actually canceled
836
// the event.
837
nsJSUtils::GetCallingLocation(aCx, mPreventDefaultScriptSpec,
838
&mPreventDefaultLineNumber,
839
&mPreventDefaultColumnNumber);
840
}
841
842
Event::PreventDefault(aCx, aCallerType);
843
}
844
845
void FetchEvent::ReportCanceled() {
846
MOZ_ASSERT(!mPreventDefaultScriptSpec.IsEmpty());
847
848
RefPtr<InternalRequest> ir = mRequest->GetInternalRequest();
849
nsAutoCString url;
850
ir->GetURL(url);
851
852
// The variadic template provided by StringArrayAppender requires exactly
853
// an nsString.
854
NS_ConvertUTF8toUTF16 requestURL(url);
855
// nsString requestURL;
856
// CopyUTF8toUTF16(url, requestURL);
857
858
if (mChannel) {
859
::AsyncLog(mChannel.get(), mPreventDefaultScriptSpec,
860
mPreventDefaultLineNumber, mPreventDefaultColumnNumber,
861
NS_LITERAL_CSTRING("InterceptionCanceledWithURL"), requestURL);
862
} else {
863
mRespondWithHandler->ReportCanceled(mPreventDefaultScriptSpec,
864
mPreventDefaultLineNumber,
865
mPreventDefaultColumnNumber);
866
mRespondWithHandler = nullptr;
867
}
868
}
869
870
namespace {
871
872
class WaitUntilHandler final : public PromiseNativeHandler {
873
WorkerPrivate* mWorkerPrivate;
874
const nsCString mScope;
875
nsString mSourceSpec;
876
uint32_t mLine;
877
uint32_t mColumn;
878
nsString mRejectValue;
879
880
~WaitUntilHandler() {}
881
882
public:
883
NS_DECL_THREADSAFE_ISUPPORTS
884
885
WaitUntilHandler(WorkerPrivate* aWorkerPrivate, JSContext* aCx)
886
: mWorkerPrivate(aWorkerPrivate),
887
mScope(mWorkerPrivate->ServiceWorkerScope()),
888
mLine(0),
889
mColumn(0) {
890
mWorkerPrivate->AssertIsOnWorkerThread();
891
892
// Save the location of the waitUntil() call itself as a fallback
893
// in case the rejection value does not contain any location info.
894
nsJSUtils::GetCallingLocation(aCx, mSourceSpec, &mLine, &mColumn);
895
}
896
897
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
898
// do nothing, we are only here to report errors
899
}
900
901
void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
902
mWorkerPrivate->AssertIsOnWorkerThread();
903
904
nsString spec;
905
uint32_t line = 0;
906
uint32_t column = 0;
907
nsContentUtils::ExtractErrorValues(aCx, aValue, spec, &line, &column,
908
mRejectValue);
909
910
// only use the extracted location if we found one
911
if (!spec.IsEmpty()) {
912
mSourceSpec = spec;
913
mLine = line;
914
mColumn = column;
915
}
916
917
MOZ_ALWAYS_SUCCEEDS(mWorkerPrivate->DispatchToMainThread(
918
NewRunnableMethod("WaitUntilHandler::ReportOnMainThread", this,
919
&WaitUntilHandler::ReportOnMainThread)));
920
}
921
922
void ReportOnMainThread() {
923
MOZ_ASSERT(NS_IsMainThread());
924
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
925
if (!swm) {
926
// browser shutdown
927
return;
928
}
929
930
// TODO: Make the error message a localized string. (bug 1222720)
931
nsString message;
932
message.AppendLiteral(
933
"Service worker event waitUntil() was passed a "
934
"promise that rejected with '");
935
message.Append(mRejectValue);
936
message.AppendLiteral("'.");
937
938
// Note, there is a corner case where this won't report to the window
939
// that triggered the error. Consider a navigation fetch event that
940
// rejects waitUntil() without holding respondWith() open. In this case
941
// there is no controlling document yet, the window did call .register()
942
// because there is no documeny yet, and the navigation is no longer
943
// being intercepted.
944
945
swm->ReportToAllClients(mScope, message, mSourceSpec, EmptyString(), mLine,
946
mColumn, nsIScriptError::errorFlag);
947
}
948
};
949
950
NS_IMPL_ISUPPORTS0(WaitUntilHandler)
951
952
} // anonymous namespace
953
954
NS_IMPL_ADDREF_INHERITED(FetchEvent, ExtendableEvent)
955
NS_IMPL_RELEASE_INHERITED(FetchEvent, ExtendableEvent)
956
957
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(FetchEvent)
958
NS_INTERFACE_MAP_END_INHERITING(ExtendableEvent)
959
960
NS_IMPL_CYCLE_COLLECTION_INHERITED(FetchEvent, ExtendableEvent, mRequest)
961
962
ExtendableEvent::ExtendableEvent(EventTarget* aOwner)
963
: Event(aOwner, nullptr, nullptr) {}
964
965
bool ExtendableEvent::WaitOnPromise(Promise& aPromise) {
966
if (!mExtensionsHandler) {
967
return false;
968
}
969
return mExtensionsHandler->WaitOnPromise(aPromise);
970
}
971
972
void ExtendableEvent::SetKeepAliveHandler(
973
ExtensionsHandler* aExtensionsHandler) {
974
MOZ_ASSERT(!mExtensionsHandler);
975
WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
976
MOZ_ASSERT(worker);
977
worker->AssertIsOnWorkerThread();
978
mExtensionsHandler = aExtensionsHandler;
979
}
980
981
void ExtendableEvent::WaitUntil(JSContext* aCx, Promise& aPromise,
982
ErrorResult& aRv) {
983
MOZ_ASSERT(!NS_IsMainThread());
984
985
if (!WaitOnPromise(aPromise)) {
986
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
987
return;
988
}
989
990
// Append our handler to each waitUntil promise separately so we
991
// can record the location in script where waitUntil was called.
992
RefPtr<WaitUntilHandler> handler =
993
new WaitUntilHandler(GetCurrentThreadWorkerPrivate(), aCx);
994
aPromise.AppendNativeHandler(handler);
995
}
996
997
NS_IMPL_ADDREF_INHERITED(ExtendableEvent, Event)
998
NS_IMPL_RELEASE_INHERITED(ExtendableEvent, Event)
999
1000
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ExtendableEvent)
1001
NS_INTERFACE_MAP_END_INHERITING(Event)
1002
1003
namespace {
1004
nsresult ExtractBytesFromUSVString(const nsAString& aStr,
1005
nsTArray<uint8_t>& aBytes) {
1006
MOZ_ASSERT(aBytes.IsEmpty());
1007
auto encoder = UTF_8_ENCODING->NewEncoder();
1008
CheckedInt<size_t> needed =
1009
encoder->MaxBufferLengthFromUTF16WithoutReplacement(aStr.Length());
1010
if (NS_WARN_IF(!needed.isValid() ||
1011
!aBytes.SetLength(needed.value(), fallible))) {
1012
return NS_ERROR_OUT_OF_MEMORY;
1013
}
1014
uint32_t result;
1015
size_t read;
1016
size_t written;
1017
Tie(result, read, written) =
1018
encoder->EncodeFromUTF16WithoutReplacement(aStr, aBytes, true);
1019
MOZ_ASSERT(result == kInputEmpty);
1020
MOZ_ASSERT(read == aStr.Length());
1021
aBytes.TruncateLength(written);
1022
return NS_OK;
1023
}
1024
1025
nsresult ExtractBytesFromData(
1026
const OwningArrayBufferViewOrArrayBufferOrUSVString& aDataInit,
1027
nsTArray<uint8_t>& aBytes) {
1028
if (aDataInit.IsArrayBufferView()) {
1029
const ArrayBufferView& view = aDataInit.GetAsArrayBufferView();
1030
if (NS_WARN_IF(!PushUtil::CopyArrayBufferViewToArray(view, aBytes))) {
1031
return NS_ERROR_OUT_OF_MEMORY;
1032
}
1033
return NS_OK;
1034
}
1035
if (aDataInit.IsArrayBuffer()) {
1036
const ArrayBuffer& buffer = aDataInit.GetAsArrayBuffer();
1037
if (NS_WARN_IF(!PushUtil::CopyArrayBufferToArray(buffer, aBytes))) {
1038
return NS_ERROR_OUT_OF_MEMORY;
1039
}
1040
return NS_OK;
1041
}
1042
if (aDataInit.IsUSVString()) {
1043
return ExtractBytesFromUSVString(aDataInit.GetAsUSVString(), aBytes);
1044
}
1045
MOZ_ASSERT_UNREACHABLE("Unexpected push message data");
1046
return NS_ERROR_FAILURE;
1047
}
1048
} // namespace
1049
1050
PushMessageData::PushMessageData(nsIGlobalObject* aOwner,
1051
nsTArray<uint8_t>&& aBytes)
1052
: mOwner(aOwner), mBytes(std::move(aBytes)) {}
1053
1054
PushMessageData::~PushMessageData() {}
1055
1056
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(PushMessageData, mOwner)
1057
1058
NS_IMPL_CYCLE_COLLECTING_ADDREF(PushMessageData)
1059
NS_IMPL_CYCLE_COLLECTING_RELEASE(PushMessageData)
1060
1061
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PushMessageData)
1062
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
1063
NS_INTERFACE_MAP_ENTRY(nsISupports)
1064
NS_INTERFACE_MAP_END
1065
1066
JSObject* PushMessageData::WrapObject(JSContext* aCx,
1067
JS::Handle<JSObject*> aGivenProto) {
1068
return mozilla::dom::PushMessageData_Binding::Wrap(aCx, this, aGivenProto);
1069
}
1070
1071
void PushMessageData::Json(JSContext* cx, JS::MutableHandle<JS::Value> aRetval,
1072
ErrorResult& aRv) {
1073
if (NS_FAILED(EnsureDecodedText())) {
1074
aRv.Throw(NS_ERROR_DOM_UNKNOWN_ERR);
1075
return;
1076
}
1077
BodyUtil::ConsumeJson(cx, aRetval, mDecodedText, aRv);
1078
}
1079
1080
void PushMessageData::Text(nsAString& aData) {
1081
if (NS_SUCCEEDED(EnsureDecodedText())) {
1082
aData = mDecodedText;
1083
}
1084
}
1085
1086
void PushMessageData::ArrayBuffer(JSContext* cx,
1087
JS::MutableHandle<JSObject*> aRetval,
1088
ErrorResult& aRv) {
1089
uint8_t* data = GetContentsCopy();
1090
if (data) {
1091
BodyUtil::ConsumeArrayBuffer(cx, aRetval, mBytes.Length(), data, aRv);
1092
}
1093
}
1094
1095
already_AddRefed<mozilla::dom::Blob> PushMessageData::Blob(ErrorResult& aRv) {
1096
uint8_t* data = GetContentsCopy();
1097
if (data) {
1098
RefPtr<mozilla::dom::Blob> blob = BodyUtil::ConsumeBlob(
1099
mOwner, EmptyString(), mBytes.Length(), data, aRv);
1100
if (blob) {
1101
return blob.forget();
1102
}
1103
}
1104
return nullptr;
1105
}
1106
1107
nsresult PushMessageData::EnsureDecodedText() {
1108
if (mBytes.IsEmpty() || !mDecodedText.IsEmpty()) {
1109
return NS_OK;
1110
}
1111
nsresult rv = BodyUtil::ConsumeText(
1112
mBytes.Length(), reinterpret_cast<uint8_t*>(mBytes.Elements()),
1113
mDecodedText);
1114
if (NS_WARN_IF(NS_FAILED(rv))) {
1115
mDecodedText.Truncate();
1116
return rv;
1117
}
1118
return NS_OK;
1119
}
1120
1121
uint8_t* PushMessageData::GetContentsCopy() {
1122
uint32_t length = mBytes.Length();
1123
void* data = malloc(length);
1124
if (!data) {
1125
return nullptr;
1126
}
1127
memcpy(data, mBytes.Elements(), length);
1128
return reinterpret_cast<uint8_t*>(data);
1129
}
1130
1131
PushEvent::PushEvent(EventTarget* aOwner) : ExtendableEvent(aOwner) {}
1132
1133
already_AddRefed<PushEvent> PushEvent::Constructor(
1134
mozilla::dom::EventTarget* aOwner, const nsAString& aType,
1135
const PushEventInit& aOptions, ErrorResult& aRv) {
1136
RefPtr<PushEvent> e = new PushEvent(aOwner);
1137
bool trusted = e->Init(aOwner);
1138
e->InitEvent(aType, aOptions.mBubbles, aOptions.mCancelable);
1139
e->SetTrusted(trusted);
1140
e->SetComposed(aOptions.mComposed);
1141
if (aOptions.mData.WasPassed()) {
1142
nsTArray<uint8_t> bytes;
1143
nsresult rv = ExtractBytesFromData(aOptions.mData.Value(), bytes);
1144
if (NS_FAILED(rv)) {
1145
aRv.Throw(rv);
1146
return nullptr;
1147
}
1148
e->mData = new PushMessageData(aOwner->GetOwnerGlobal(), std::move(bytes));
1149
}
1150
return e.forget();
1151
}
1152
1153
NS_IMPL_ADDREF_INHERITED(PushEvent, ExtendableEvent)
1154
NS_IMPL_RELEASE_INHERITED(PushEvent, ExtendableEvent)
1155
1156
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PushEvent)
1157
NS_INTERFACE_MAP_END_INHERITING(ExtendableEvent)
1158
1159
NS_IMPL_CYCLE_COLLECTION_INHERITED(PushEvent, ExtendableEvent, mData)
1160
1161
JSObject* PushEvent::WrapObjectInternal(JSContext* aCx,
1162
JS::Handle<JSObject*> aGivenProto) {
1163
return mozilla::dom::PushEvent_Binding::Wrap(aCx, this, aGivenProto);
1164
}
1165
1166
ExtendableMessageEvent::ExtendableMessageEvent(EventTarget* aOwner)
1167
: ExtendableEvent(aOwner), mData(JS::UndefinedValue()) {
1168
mozilla::HoldJSObjects(this);
1169
}
1170
1171
ExtendableMessageEvent::~ExtendableMessageEvent() {
1172
mData.setUndefined();
1173
DropJSObjects(this);
1174
}
1175
1176
void ExtendableMessageEvent::GetData(JSContext* aCx,
1177
JS::MutableHandle<JS::Value> aData,
1178
ErrorResult& aRv) {
1179
aData.set(mData);
1180
if (!JS_WrapValue(aCx, aData)) {
1181
aRv.Throw(NS_ERROR_FAILURE);
1182
}
1183
}
1184
1185
void ExtendableMessageEvent::GetSource(
1186
Nullable<OwningClientOrServiceWorkerOrMessagePort>& aValue) const {
1187
if (mClient) {
1188
aValue.SetValue().SetAsClient() = mClient;
1189
} else if (mServiceWorker) {
1190
aValue.SetValue().SetAsServiceWorker() = mServiceWorker;
1191
} else if (mMessagePort) {
1192
aValue.SetValue().SetAsMessagePort() = mMessagePort;
1193
} else {
1194
// nullptr source is possible for manually constructed event
1195
aValue.SetNull();
1196
}
1197
}
1198
1199
/* static */
1200
already_AddRefed<ExtendableMessageEvent> ExtendableMessageEvent::Constructor(
1201
const GlobalObject& aGlobal, const nsAString& aType,
1202
const ExtendableMessageEventInit& aOptions) {
1203
nsCOMPtr<EventTarget> t = do_QueryInterface(aGlobal.GetAsSupports());
1204
return Constructor(t, aType, aOptions);
1205
}
1206
1207
/* static */
1208
already_AddRefed<ExtendableMessageEvent> ExtendableMessageEvent::Constructor(
1209
mozilla::dom::EventTarget* aEventTarget, const nsAString& aType,
1210
const ExtendableMessageEventInit& aOptions) {
1211
RefPtr<ExtendableMessageEvent> event =
1212
new ExtendableMessageEvent(aEventTarget);
1213
1214
event->InitEvent(aType, aOptions.mBubbles, aOptions.mCancelable);
1215
bool trusted = event->Init(aEventTarget);
1216
event->SetTrusted(trusted);
1217
1218
event->mData = aOptions.mData;
1219
event->mOrigin = aOptions.mOrigin;
1220
event->mLastEventId = aOptions.mLastEventId;
1221
1222
if (!aOptions.mSource.IsNull()) {
1223
if (aOptions.mSource.Value().IsClient()) {
1224
event->mClient = aOptions.mSource.Value().GetAsClient();
1225
} else if (aOptions.mSource.Value().IsServiceWorker()) {
1226
event->mServiceWorker = aOptions.mSource.Value().GetAsServiceWorker();
1227
} else if (aOptions.mSource.Value().IsMessagePort()) {
1228
event->mMessagePort = aOptions.mSource.Value().GetAsMessagePort();
1229
}
1230
}
1231
1232
event->mPorts.AppendElements(aOptions.mPorts);
1233
return event.forget();
1234
}
1235
1236
void ExtendableMessageEvent::GetPorts(nsTArray<RefPtr<MessagePort>>& aPorts) {
1237
aPorts = mPorts;
1238
}
1239
1240
NS_IMPL_CYCLE_COLLECTION_CLASS(ExtendableMessageEvent)
1241
1242
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(ExtendableMessageEvent, Event)
1243
tmp->mData.setUndefined();
1244
NS_IMPL_CYCLE_COLLECTION_UNLINK(mClient)
1245
NS_IMPL_CYCLE_COLLECTION_UNLINK(mServiceWorker)
1246
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMessagePort)
1247
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPorts)
1248
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
1249
1250
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(ExtendableMessageEvent, Event)
1251
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mClient)
1252
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mServiceWorker)
1253
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMessagePort)
1254
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPorts)
1255
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
1256
1257
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(ExtendableMessageEvent, Event)
1258
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mData)
1259
NS_IMPL_CYCLE_COLLECTION_TRACE_END
1260
1261
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ExtendableMessageEvent)
1262
NS_INTERFACE_MAP_END_INHERITING(Event)
1263
1264
NS_IMPL_ADDREF_INHERITED(ExtendableMessageEvent, Event)
1265
NS_IMPL_RELEASE_INHERITED(ExtendableMessageEvent, Event)
1266
1267
} // namespace dom
1268
} // namespace mozilla