Files
palemoon27/dom/workers/ServiceWorkerPrivate.cpp
T
roytam1 cbf860dd80 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1207790 - Fix sandbox build for older Linux distributions. r=gdestuynder (33726f14d6)
- Bug 1157864 - chromium sandbox: Fix compilation for systems without <sys/cdefs.h>. r=jld (19789c8f28)
- Bug 1181704 - Import chromium SafeSPrintf. r=bobowen (c8f2f34098)
- Bug 1196403 - Apply crbug/522201 to support Windows 10 build 10525. r=bobowen (ee9862b408)
- Bug 1200336: Apply fix for Chromium issue 482784 for sandbox bug when built with VS2015. r=tabraldes (7f4cf9640b)
- Bug 1150765 - Add sandbox rules to allow hardware rendering of OpenGL on Mac. r=smichaud (e23a3d3e89)
- Bug 1153809 - Loosen Mac content process sandbox rules for NVidia and Intel HD 3000 graphics hardware. r=areinald (9a3a1fa6ea)
- Bug 1229804: Use the correct string length in Windows sandbox logging. r=tabraldes (6a8cb035ed)
- Bug 1181704 - Use chromium SafeSPrintf for sandbox logging. r=gdestuynder r=glandium (cff9ae432b)
- crash reporter (009341774b)
- Bug 1168555 - Work around Nuwa not always being single-threaded when a normal content process is. r=kang (b858b1fd62)
- Bug 1199413 - Fix MOZ_DISABLE_GMP_SANDBOX so it disables all the sandboxing. r=kang (49125e07be)
- Bug 1176085 - Fix second/nanosecond confusion in Linux sandbox start error case. r=kang (701181c7d2)
- Bug 1199481 - Complain more when entering sandboxing code as root. r=kang (baf7b24675)
- Bug 1215303 - Part 1 - add permissive mode r=jld (e8237859ac)
- Bug 1215303 - Part 2 - automatically enable broker when in permissive mode r=jld (9636c8a956)
- Bug 1222500 - Handle unexpected thread creation better on desktop Linux. r=gdestuynder (58e2f81f96)
- Bug 1131227 - Make the about:certerror Unknown Issuer string mention missing intermediates and unimported roots. r=keeler (29ae92e655)
- Bug 443811 - Use long date format for cert date output. r=keeler (50a31e099c)
- namespace (10ccb72736)
- Bug 1225682 - Don't use nsAuto{,C}String as class member variables in security/manager/. r=keeler (24d10b66f6)
- Bug 1110935 - Part 1 - Assert we're on the main thread on public methods. r=keeler (b9b2b52bf2)
- Bug 1110935 - Part 2 - Remove ReentrantMonitor and ReentrantMonitorAutoEnter uses. r=keeler (3fee4d4653)
- Bug 1110935 - Part 3 - Remove now unnecessary temp variables. r=keeler (f81461993a)
- Bug 1168635 - Add an XPCOM interface to allow RC4. r=keeler (dac5f75e75)
- Bug 1136301 - Null check for mCert->slot added in destructorSafeDestroyNSSReference & MarkForPermDeletion. Formatting update in MarkForPermDeletion. r=keeler (daaaf2db22)
- Bug 1168048 - Avoid potential null-pointer dereferencing in nsNSSCertificateDB r=keeler (c511046073)
- Bug 1224121 - change getRelativeRuleLine to return 0 for line-less rules; r=heycam (7cef25806d)
- Bug 1216234 - add inIDOMUtils.getCSSPseudoElementNames; r=heycam,pbrosset (1c94ca86b4)
- Bug 1146114 - Make assertion checking additional leading in ruby frame non-crash. r=dholbert (326d82db79)
- Bug 1052924 followup - Move the XXX comment to the right field. DONTBUILD (481cb50d0d)
- Bug 1136521 - Don't try to use the ascent when placing a frame whose block-direction doesn't match the line's. r=smontagu (eb01f6aa1a)
- Bug 1138353 - Correct the directionality of vertical-align dimensions in cases where line- and flow-relative coordinate directions differ. r=smontagu (6e51f4be05)
- Bug 1133945 - Fix behavior of vertical-align with a specified length, relative to dominant centered baseline in vertical mode. r=smontagu (a2e611f978)
- Bug 1146117 - Downgrade the assertion in FindNearestRubyBaseAncestor to warning. r=dbaron (db29a321f4)
- Bug 1191185 - Simplify nsHypotheticalBox, eliminating obsolete/redundant fields, and rename to nsHypotheticalPosition. r=dholbert (3741b6aa49)
- Bug 1227099 - [css-grid] Grid container block-size should include a grid-row-gap between each row. r=dholbert (35eed9d00b)
- Bug 1225368 - [css-grid] Make CollectGrowable() deal with frozen tracks; i.e. subtract their base size but don't collect them since they aren't growable. r=dholbert (073964a857)
- Bug 1224634 - [css-grid] Make grid items shrink-wrap when reflowing them, unless they have justify-self:stretch. r=dholbert (070c2cf6a9)
- Bug 1176793 part 1 - [css-grid] Implement margin:auto for grid items. r=dholbert (ff89b80fc2)
- Bug 1176793 part 2 - [css-grid] Reftests for margin:auto on grid items. (fe9367e7ca)
- Bug 1229999 - [css-grid] Clamp auto-placed lines to where kMaxLine is in the translated grid. r=dholbert (576d9a8384)
- Bug 1151243 part 1 - Replace three bool params for nsAbsoluteContainingBlock::Reflow with a flag param (idempotent patch). r=dholbert (7303bb9468)
- Bug 978212 - [css-grid] Resolved value of grid-template-{columns,rows} in px units. r=mat (fe4b886917)
- Bug 1151243 part 2 - [css-grid] Add a eIsGridContainerCB flag for nsAbsoluteContainingBlock::Reflow to trigger Grid specific code (rather than checking GetType()). r=dholbert (2f5f857b16)
- Bug 1215099 part 1 - [css-grid] Backout bug 1206703. r=dholbert (b6af6389ce)
- Bug 1123299 - Allow <input type=number> to be displayed in vertical writing mode; but keep the spinner arrows arranged as for horizontal writing mode. r=dholbert (2a2e17ce76)
- (no bug) Fix typo in grid style-struct comment: s/grid-columns-rows/grid-template-rows/. No review, DONTBUILD (f362946aed)
- fix namespace (70ec283c08)
- Bug 1224251 patch 1 - Add reftests. r=mattwoodrow (4f5eed4d0c)
- Bug 1224251 patch 2 - Add nsChangeHint_UpdateUsesOpacity to say when opacity changes between 1 and non-1. r=xidorn (0cec051688)
- Bug 1224251 patch 3 - Return nsChangeHint_UpdateUsesOpacity when opacity changes between 1 and non-1. r=xidorn (acf5f3514c)
- Bug 1224251 patch 4 - Convert UpdateOpacityLayer to RepaintFrame when changing opacity between 1 and non-1 on table parts. r=mattwoodrow (3101e06481)
- Tweak a couple of comments; no bug. (DONTBUILD) (6b7d8486ad)
- Bug 1219534 - Remove unused nsStyleContext::SetStyle##name_ methods. r=dholbert (4c032b5914)
- (no bug) Fix typo in nsStyleContext.h (s/currenlty/currently/). Comment-only, DONTBUILD (3864f8194b)
- Bug 1208901 - Fix a typo in nsStyleClipPath::nsStyleClipPath; r=heycam (df5c3b59a6)
- Bug 1227766 patch 3 - Make will-change cause creation of a containing block for fixed and absolutely positioned elements when needed. r=dholbert (09c59e07f1)
- Bug 1229278 - Fix dynamic changes to text-emphasis-style. r=dbaron (ab0c450f14)
- Bug 1159729 - Reftest to check that text decoration is properly offset when needed. r=smontagu (b93bb0ca41)
- Bug 196292 - Make table inside align=left reset alignment just like for align=center and align=right. r=bz (3b45a62477)
- Bug 1227917 - Update |disp| after we've (potentially) cloned the Display struct so that subsequent tests of 'display' use the new value. r=jfkthame (d3216e7aad)
- Bug 1155766 - Fix a bad assertion r=dbaron (d6744220f4)
- Bug 1167589 - Mark the members of CSSParsingEnvironment as MOZ_UNSAFE_REF. r=dbaron (ebb9729549)
- Bug 1228542 - Resetting AuthorStyleSheets. r=bz (31b27e491d)
- Use nsContentUtils::GenerateUUIDInPlace() in nsIDocument::GenerateDocumentId(), no bug (642138ebac)
- Bug 1226443 P2 Make service worker fetch and functional events used scheduled timer updates. r=ehsan (a4fc5a9275)
- Bug 1227015 P1 Create ServiceWorkerScriptJobBase as parent class to register and install jobs. r=ehsan (214dda4e7d)
- Bug 1226443 P1 Add a timer based mechanism for firing service worker updates. r=ehsan (f2a9eae9d2)
- Bug 1229052 - Add a telemetry histogram to gather data on the number of top-level pages with scroll-linked positioning effects. r=vladan (6844bfaa2b)
- Bug 1229052 - Log a warning when we detect a scroll-linked effect based on the scroll event. r=roc (da8dd5cff2)
- bug 1215657 - make AccessibleWrap::get_accFocus work with proxied accessibles (02bfa582d6)
- Bug 1227285 part 1 - Add a nsHTMLReflowState ctor flag to request shrink-wrap behavior. r=dholbert (da92253664)
- Bug 1227285 part 2 - [css-grid] Request shrink-wrap behavior when doing a measuring reflow to figure out a grid item's block-size. r=dholbert (6bfcf381fe)
- Bug 1227285 part 3 - [css-grid] Reftests for testing minmax(min-content,max-content) track sizing with grid item with %-sized descendants. (61b769d0d2)
- No bug - [css-grid] Add a small fuzz factor to make this reftest pass on Windows. r=me (3c51c91220)
- Bug 1173689: allow column sets in an orthogonal writing mode to their container to expand in the container's block direction, r=roc (88aa32efd9)
- Bug 1209994. Take block-wrapper path only for blocks that are wrappers. r=bz (ecb4ae8d7e)
- Bug 1191109 - Clean up use of writing-modes in GetHypotheticalBoxContainer, eliminating a redundant ConvertTo call. r=dholbert (f58d0d63c4)
- Bug 1183439 - Update the wording of a few assertions to reflect logical-coordinate conversion. r=dholbert (8aacb0f89d)
- Bug 1233276 - Make css::Declaration::List more useful again, given that it degraded a bit in bug 978833 (/ bug 1221436). r=heycam (1efda568e7)
- Bug 1167665 - Mark css::Loader::mDocument as MOZ_NON_OWNING_REF. r=dbaron (f4d4f4ed1d)
- Bug 621596 - Don't assert when a percentage base value overflows to become negative, when getting the computed style of a property that rejects negative values. r=bzbarsky (6076ce7cb6)
- Bug 622314 - Add crashtest. (f1d64b943c)
- Bug 1230613 - Long-press to trigger text selection should vibrate, r=snorp (f35f37336e)
- Bug 1230582 - Always show caret even if input is empty on Fennec. f=capella, r=roc (6cf1258232)
- Bug 1183085 - Correct argument name for BuildContainerLayerFor; r=roc (0fd119efd1)
- Bug 1183085 - Correct a typo in FrameLayerBuilder.h; r=roc (1fb9a583ed)
- Comment typo fix; no bug. (DONTBUILD) (27d7270052)
- Bug 1211858 - Add a hint for the Restyle label when the id is unavailable. r=roc,benwa (8eb99a4b45)
- bug 1218596 - remove nsPSMInitPanic and other unnecessary things from nsNSSComponent r=Cykesiopka r=jcj (a986e73f0b)
- bug 1220223 - don't load PKCS11 modules in safe mode r=mgoodwin r=bsmedberg (5e071955b0)
- Bug 921907 - Enable OCSP must-staple. r=keeler (448661431f)
- Bug 1215795 - Fix documentation in nsIWeakCryptoOverride.idl. r=keeler IGNORE IDL (3cf051737c)
- bug 1222179 - remove unnecessary observation topics in nsNSSComponent r=Cykesiopka (2eaa16d860)
- bug 986956 - only ever initialize NSS once per process r=Cykesiopka r=mgoodwin (efdec10cbb)
- Bug 1224875 - Enable TLS extended master secret. r=keeler (8f56d54ec1)
- Bug 1145893 - Shutdown nsNSSComponent background threads during xpcom-shutdown. r=keeler, a=me (5d513b930d)
- namespace (bf40a8f575)
- Bug 1224951 - Part 1: Fix nsPresContext::SizeOfExcludingThis() size calculation. r=dholbert (530a54e15d)
- Bug 1227666 - Insure that cached plugin geometry configuration cached in ShadowLayerForwarder gets cleared when we reflow and new content has no plugins. r=roc (a44fbce70e)
- Bug 1140625 - Part 1: Add recursive call in GetFrameForNodeOffset. r=roc (0b7535cf7b)
- Bug 1140625 - Recursive call GetFrameForNodeOffset if text node has no frame. r=roc (9198ab6a20)
- Bug 1140625 - Part 3: Fix a bug in bug414526 so we can reopen the test. r=roc (cbe0d3577d)
- Bug 1140625 - Part 4: Fix scroll_selection_into_view test to make its function remain. r=roc (97ca749e63)
2023-07-11 15:00:13 +08:00

1748 lines
52 KiB
C++

/* -*- 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 "ServiceWorkerPrivate.h"
#include "ServiceWorkerManager.h"
#include "nsStreamUtils.h"
#include "nsStringStream.h"
#include "mozilla/dom/FetchUtil.h"
using namespace mozilla;
using namespace mozilla::dom;
BEGIN_WORKERS_NAMESPACE
NS_IMPL_CYCLE_COLLECTING_ADDREF(ServiceWorkerPrivate)
NS_IMPL_CYCLE_COLLECTING_RELEASE(ServiceWorkerPrivate)
NS_IMPL_CYCLE_COLLECTION(ServiceWorkerPrivate, mSupportsArray)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ServiceWorkerPrivate)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
// Tracks the "dom.disable_open_click_delay" preference. Modified on main
// thread, read on worker threads.
// It is updated every time a "notificationclick" event is dispatched. While
// this is done without synchronization, at the worst, the thread will just get
// an older value within which a popup is allowed to be displayed, which will
// still be a valid value since it was set prior to dispatching the runnable.
Atomic<uint32_t> gDOMDisableOpenClickDelay(0);
// Used to keep track of pending waitUntil as well as in-flight extendable events.
// When the last token is released, we attempt to terminate the worker.
class KeepAliveToken final : public nsISupports
{
public:
NS_DECL_ISUPPORTS
explicit KeepAliveToken(ServiceWorkerPrivate* aPrivate)
: mPrivate(aPrivate)
{
AssertIsOnMainThread();
MOZ_ASSERT(aPrivate);
mPrivate->AddToken();
}
private:
~KeepAliveToken()
{
AssertIsOnMainThread();
mPrivate->ReleaseToken();
}
RefPtr<ServiceWorkerPrivate> mPrivate;
};
NS_IMPL_ISUPPORTS0(KeepAliveToken)
ServiceWorkerPrivate::ServiceWorkerPrivate(ServiceWorkerInfo* aInfo)
: mInfo(aInfo)
, mIsPushWorker(false)
, mDebuggerCount(0)
, mTokenCount(0)
{
AssertIsOnMainThread();
MOZ_ASSERT(aInfo);
mIdleWorkerTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
MOZ_ASSERT(mIdleWorkerTimer);
}
ServiceWorkerPrivate::~ServiceWorkerPrivate()
{
MOZ_ASSERT(!mWorkerPrivate);
MOZ_ASSERT(!mTokenCount);
MOZ_ASSERT(!mInfo);
MOZ_ASSERT(mSupportsArray.IsEmpty());
mIdleWorkerTimer->Cancel();
}
nsresult
ServiceWorkerPrivate::SendMessageEvent(JSContext* aCx,
JS::Handle<JS::Value> aMessage,
const Optional<Sequence<JS::Value>>& aTransferable,
UniquePtr<ServiceWorkerClientInfo>&& aClientInfo)
{
ErrorResult rv(SpawnWorkerIfNeeded(MessageEvent, nullptr));
if (NS_WARN_IF(rv.Failed())) {
return rv.StealNSResult();
}
// FIXME(catalinb): Bug 1143717
// Keep the worker alive when dispatching a message event.
mWorkerPrivate->PostMessageToServiceWorker(aCx, aMessage, aTransferable,
Move(aClientInfo), rv);
return rv.StealNSResult();
}
namespace {
class CheckScriptEvaluationWithCallback final : public WorkerRunnable
{
nsMainThreadPtrHandle<KeepAliveToken> mKeepAliveToken;
RefPtr<LifeCycleEventCallback> mCallback;
DebugOnly<bool> mDone;
public:
CheckScriptEvaluationWithCallback(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aKeepAliveToken,
LifeCycleEventCallback* aCallback)
: WorkerRunnable(aWorkerPrivate, WorkerThreadModifyBusyCount)
, mKeepAliveToken(new nsMainThreadPtrHolder<KeepAliveToken>(aKeepAliveToken))
, mCallback(aCallback)
, mDone(false)
{
AssertIsOnMainThread();
}
~CheckScriptEvaluationWithCallback()
{
MOZ_ASSERT(mDone);
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
aWorkerPrivate->AssertIsOnWorkerThread();
Done(aWorkerPrivate->WorkerScriptExecutedSuccessfully());
return true;
}
NS_IMETHOD
Cancel() override
{
Done(false);
return WorkerRunnable::Cancel();
}
private:
void
Done(bool aResult)
{
mDone = true;
mCallback->SetResult(aResult);
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(NS_DispatchToMainThread(mCallback)));
}
};
} // anonymous namespace
nsresult
ServiceWorkerPrivate::CheckScriptEvaluation(LifeCycleEventCallback* aCallback)
{
nsresult rv = SpawnWorkerIfNeeded(LifeCycleEvent, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(mKeepAliveToken);
RefPtr<WorkerRunnable> r = new CheckScriptEvaluationWithCallback(mWorkerPrivate,
mKeepAliveToken,
aCallback);
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
namespace {
// Holds the worker alive until the waitUntil promise is resolved or
// rejected.
class KeepAliveHandler final : public PromiseNativeHandler
{
nsMainThreadPtrHandle<KeepAliveToken> mKeepAliveToken;
virtual ~KeepAliveHandler()
{}
public:
NS_DECL_ISUPPORTS
explicit KeepAliveHandler(const nsMainThreadPtrHandle<KeepAliveToken>& aKeepAliveToken)
: mKeepAliveToken(aKeepAliveToken)
{ }
void
ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
{
#ifdef DEBUG
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(workerPrivate);
workerPrivate->AssertIsOnWorkerThread();
#endif
}
void
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
{
#ifdef DEBUG
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(workerPrivate);
workerPrivate->AssertIsOnWorkerThread();
#endif
}
};
NS_IMPL_ISUPPORTS0(KeepAliveHandler)
class RegistrationUpdateRunnable : public nsRunnable
{
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> mRegistration;
const bool mNeedTimeCheck;
public:
RegistrationUpdateRunnable(nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
bool aNeedTimeCheck)
: mRegistration(aRegistration)
, mNeedTimeCheck(aNeedTimeCheck)
{
}
NS_IMETHOD
Run() override
{
if (mNeedTimeCheck) {
mRegistration->MaybeScheduleTimeCheckAndUpdate();
} else {
mRegistration->MaybeScheduleUpdate();
}
return NS_OK;
}
};
class ExtendableEventWorkerRunnable : public WorkerRunnable
{
protected:
nsMainThreadPtrHandle<KeepAliveToken> mKeepAliveToken;
public:
ExtendableEventWorkerRunnable(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aKeepAliveToken)
: WorkerRunnable(aWorkerPrivate, WorkerThreadModifyBusyCount)
{
AssertIsOnMainThread();
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aKeepAliveToken);
mKeepAliveToken =
new nsMainThreadPtrHolder<KeepAliveToken>(aKeepAliveToken);
}
void
DispatchExtendableEventOnWorkerScope(JSContext* aCx,
WorkerGlobalScope* aWorkerScope,
ExtendableEvent* aEvent,
Promise** aWaitUntilPromise)
{
MOZ_ASSERT(aWorkerScope);
MOZ_ASSERT(aEvent);
nsCOMPtr<nsIGlobalObject> sgo = aWorkerScope;
WidgetEvent* internalEvent = aEvent->GetInternalNSEvent();
ErrorResult result;
result = aWorkerScope->DispatchDOMEvent(nullptr, aEvent, nullptr, nullptr);
if (NS_WARN_IF(result.Failed()) || internalEvent->mFlags.mExceptionHasBeenRisen) {
result.SuppressException();
return;
}
RefPtr<Promise> waitUntilPromise = aEvent->GetPromise();
if (!waitUntilPromise) {
waitUntilPromise =
Promise::Resolve(sgo, aCx, JS::UndefinedHandleValue, result);
if (NS_WARN_IF(result.Failed())) {
result.SuppressException();
return;
}
}
MOZ_ASSERT(waitUntilPromise);
RefPtr<KeepAliveHandler> keepAliveHandler =
new KeepAliveHandler(mKeepAliveToken);
waitUntilPromise->AppendNativeHandler(keepAliveHandler);
if (aWaitUntilPromise) {
waitUntilPromise.forget(aWaitUntilPromise);
}
}
};
// Handle functional event
// 9.9.7 If the time difference in seconds calculated by the current time minus
// registration's last update check time is greater than 86400, invoke Soft Update
// algorithm.
class ExtendableFunctionalEventWorkerRunnable : public ExtendableEventWorkerRunnable
{
protected:
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> mRegistration;
public:
ExtendableFunctionalEventWorkerRunnable(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aKeepAliveToken,
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration)
: ExtendableEventWorkerRunnable(aWorkerPrivate, aKeepAliveToken)
, mRegistration(aRegistration)
{
MOZ_ASSERT(aRegistration);
}
void
PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult)
{
nsCOMPtr<nsIRunnable> runnable =
new RegistrationUpdateRunnable(mRegistration, true /* time check */);
NS_DispatchToMainThread(runnable.forget());
}
};
/*
* Fires 'install' event on the ServiceWorkerGlobalScope. Modifies busy count
* since it fires the event. This is ok since there can't be nested
* ServiceWorkers, so the parent thread -> worker thread requirement for
* runnables is satisfied.
*/
class LifecycleEventWorkerRunnable : public ExtendableEventWorkerRunnable
{
nsString mEventName;
RefPtr<LifeCycleEventCallback> mCallback;
public:
LifecycleEventWorkerRunnable(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aToken,
const nsAString& aEventName,
LifeCycleEventCallback* aCallback)
: ExtendableEventWorkerRunnable(aWorkerPrivate, aToken)
, mEventName(aEventName)
, mCallback(aCallback)
{
AssertIsOnMainThread();
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
MOZ_ASSERT(aWorkerPrivate);
return DispatchLifecycleEvent(aCx, aWorkerPrivate);
}
NS_IMETHOD
Cancel() override
{
mCallback->SetResult(false);
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(NS_DispatchToMainThread(mCallback)));
return WorkerRunnable::Cancel();
}
private:
bool
DispatchLifecycleEvent(JSContext* aCx, WorkerPrivate* aWorkerPrivate);
};
/*
* Used to handle ExtendableEvent::waitUntil() and catch abnormal worker
* termination during the execution of life cycle events. It is responsible
* with advancing the job queue for install/activate tasks.
*/
class LifeCycleEventWatcher final : public PromiseNativeHandler,
public WorkerFeature
{
WorkerPrivate* mWorkerPrivate;
RefPtr<LifeCycleEventCallback> mCallback;
bool mDone;
~LifeCycleEventWatcher()
{
if (mDone) {
return;
}
MOZ_ASSERT(GetCurrentThreadWorkerPrivate() == mWorkerPrivate);
// XXXcatalinb: If all the promises passed to waitUntil go out of scope,
// the resulting Promise.all will be cycle collected and it will drop its
// native handlers (including this object). Instead of waiting for a timeout
// we report the failure now.
JSContext* cx = mWorkerPrivate->GetJSContext();
ReportResult(cx, false);
}
public:
NS_DECL_ISUPPORTS
LifeCycleEventWatcher(WorkerPrivate* aWorkerPrivate,
LifeCycleEventCallback* aCallback)
: mWorkerPrivate(aWorkerPrivate)
, mCallback(aCallback)
, mDone(false)
{
MOZ_ASSERT(aWorkerPrivate);
aWorkerPrivate->AssertIsOnWorkerThread();
}
bool
Init()
{
MOZ_ASSERT(mWorkerPrivate);
mWorkerPrivate->AssertIsOnWorkerThread();
JSContext* cx = mWorkerPrivate->GetJSContext();
// We need to listen for worker termination in case the event handler
// never completes or never resolves the waitUntil promise. There are
// two possible scenarios:
// 1. The keepAlive token expires and the worker is terminated, in which
// case the registration/update promise will be rejected
// 2. A new service worker is registered which will terminate the current
// installing worker.
if (NS_WARN_IF(!mWorkerPrivate->AddFeature(cx, this))) {
NS_WARNING("LifeCycleEventWatcher failed to add feature.");
ReportResult(cx, false);
return false;
}
return true;
}
bool
Notify(JSContext* aCx, Status aStatus) override
{
if (aStatus < Terminating) {
return true;
}
MOZ_ASSERT(GetCurrentThreadWorkerPrivate() == mWorkerPrivate);
ReportResult(aCx, false);
return true;
}
void
ReportResult(JSContext* aCx, bool aResult)
{
mWorkerPrivate->AssertIsOnWorkerThread();
if (mDone) {
return;
}
mDone = true;
mCallback->SetResult(aResult);
nsresult rv = NS_DispatchToMainThread(mCallback);
if (NS_WARN_IF(NS_FAILED(rv))) {
NS_RUNTIMEABORT("Failed to dispatch life cycle event handler.");
}
mWorkerPrivate->RemoveFeature(aCx, this);
}
void
ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
{
MOZ_ASSERT(GetCurrentThreadWorkerPrivate() == mWorkerPrivate);
mWorkerPrivate->AssertIsOnWorkerThread();
ReportResult(aCx, true);
}
void
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
{
MOZ_ASSERT(GetCurrentThreadWorkerPrivate() == mWorkerPrivate);
mWorkerPrivate->AssertIsOnWorkerThread();
ReportResult(aCx, false);
// Note, all WaitUntil() rejections are reported to client consoles
// by the WaitUntilHandler in ServiceWorkerEvents. This ensures that
// errors in non-lifecycle events like FetchEvent and PushEvent are
// reported properly.
}
};
NS_IMPL_ISUPPORTS0(LifeCycleEventWatcher)
bool
LifecycleEventWorkerRunnable::DispatchLifecycleEvent(JSContext* aCx,
WorkerPrivate* aWorkerPrivate)
{
aWorkerPrivate->AssertIsOnWorkerThread();
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
RefPtr<ExtendableEvent> event;
RefPtr<EventTarget> target = aWorkerPrivate->GlobalScope();
if (mEventName.EqualsASCII("install") || mEventName.EqualsASCII("activate")) {
ExtendableEventInit init;
init.mBubbles = false;
init.mCancelable = false;
event = ExtendableEvent::Constructor(target, mEventName, init);
} else {
MOZ_CRASH("Unexpected lifecycle event");
}
event->SetTrusted(true);
// It is important to initialize the watcher before actually dispatching
// the event in order to catch worker termination while the event handler
// is still executing. This can happen with infinite loops, for example.
RefPtr<LifeCycleEventWatcher> watcher =
new LifeCycleEventWatcher(aWorkerPrivate, mCallback);
if (!watcher->Init()) {
return true;
}
RefPtr<Promise> waitUntil;
DispatchExtendableEventOnWorkerScope(aCx, aWorkerPrivate->GlobalScope(),
event, getter_AddRefs(waitUntil));
if (waitUntil) {
waitUntil->AppendNativeHandler(watcher);
} else {
watcher->ReportResult(aCx, false);
}
return true;
}
} // anonymous namespace
nsresult
ServiceWorkerPrivate::SendLifeCycleEvent(const nsAString& aEventType,
LifeCycleEventCallback* aCallback,
nsIRunnable* aLoadFailure)
{
nsresult rv = SpawnWorkerIfNeeded(LifeCycleEvent, aLoadFailure);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(mKeepAliveToken);
RefPtr<WorkerRunnable> r = new LifecycleEventWorkerRunnable(mWorkerPrivate,
mKeepAliveToken,
aEventType,
aCallback);
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
#ifndef MOZ_SIMPLEPUSH
namespace {
class SendPushEventRunnable final : public ExtendableFunctionalEventWorkerRunnable
{
Maybe<nsTArray<uint8_t>> mData;
public:
SendPushEventRunnable(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aKeepAliveToken,
const Maybe<nsTArray<uint8_t>>& aData,
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> aRegistration)
: ExtendableFunctionalEventWorkerRunnable(
aWorkerPrivate, aKeepAliveToken, aRegistration)
, mData(aData)
{
AssertIsOnMainThread();
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
MOZ_ASSERT(aWorkerPrivate);
GlobalObject globalObj(aCx, aWorkerPrivate->GlobalScope()->GetWrapper());
PushEventInit pei;
if (mData) {
const nsTArray<uint8_t>& bytes = mData.ref();
JSObject* data = Uint8Array::Create(aCx, bytes.Length(), bytes.Elements());
if (!data) {
return false;
}
pei.mData.Construct().SetAsArrayBufferView().Init(data);
}
pei.mBubbles = false;
pei.mCancelable = false;
ErrorResult result;
RefPtr<PushEvent> event =
PushEvent::Constructor(globalObj, NS_LITERAL_STRING("push"), pei, result);
if (NS_WARN_IF(result.Failed())) {
result.SuppressException();
return false;
}
event->SetTrusted(true);
DispatchExtendableEventOnWorkerScope(aCx, aWorkerPrivate->GlobalScope(),
event, nullptr);
return true;
}
};
class SendPushSubscriptionChangeEventRunnable final : public ExtendableEventWorkerRunnable
{
public:
explicit SendPushSubscriptionChangeEventRunnable(
WorkerPrivate* aWorkerPrivate, KeepAliveToken* aKeepAliveToken)
: ExtendableEventWorkerRunnable(aWorkerPrivate, aKeepAliveToken)
{
AssertIsOnMainThread();
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
MOZ_ASSERT(aWorkerPrivate);
RefPtr<EventTarget> target = aWorkerPrivate->GlobalScope();
ExtendableEventInit init;
init.mBubbles = false;
init.mCancelable = false;
RefPtr<ExtendableEvent> event =
ExtendableEvent::Constructor(target,
NS_LITERAL_STRING("pushsubscriptionchange"),
init);
event->SetTrusted(true);
DispatchExtendableEventOnWorkerScope(aCx, aWorkerPrivate->GlobalScope(),
event, nullptr);
return true;
}
};
} // anonymous namespace
#endif // !MOZ_SIMPLEPUSH
nsresult
ServiceWorkerPrivate::SendPushEvent(const Maybe<nsTArray<uint8_t>>& aData,
ServiceWorkerRegistrationInfo* aRegistration)
{
#ifdef MOZ_SIMPLEPUSH
return NS_ERROR_NOT_AVAILABLE;
#else
nsresult rv = SpawnWorkerIfNeeded(PushEvent, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(mKeepAliveToken);
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> regInfo(
new nsMainThreadPtrHolder<ServiceWorkerRegistrationInfo>(aRegistration, false));
RefPtr<WorkerRunnable> r = new SendPushEventRunnable(mWorkerPrivate,
mKeepAliveToken,
aData,
regInfo);
if (mInfo->State() == ServiceWorkerState::Activating) {
mPendingFunctionalEvents.AppendElement(r.forget());
return NS_OK;
}
MOZ_ASSERT(mInfo->State() == ServiceWorkerState::Activated);
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
#endif // MOZ_SIMPLEPUSH
}
nsresult
ServiceWorkerPrivate::SendPushSubscriptionChangeEvent()
{
#ifdef MOZ_SIMPLEPUSH
return NS_ERROR_NOT_AVAILABLE;
#else
nsresult rv = SpawnWorkerIfNeeded(PushSubscriptionChangeEvent, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(mKeepAliveToken);
RefPtr<WorkerRunnable> r =
new SendPushSubscriptionChangeEventRunnable(mWorkerPrivate, mKeepAliveToken);
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
#endif // MOZ_SIMPLEPUSH
}
namespace {
static void
DummyNotificationTimerCallback(nsITimer* aTimer, void* aClosure)
{
// Nothing.
}
class AllowWindowInteractionHandler;
class ClearWindowAllowedRunnable final : public WorkerRunnable
{
public:
ClearWindowAllowedRunnable(WorkerPrivate* aWorkerPrivate,
AllowWindowInteractionHandler* aHandler)
: WorkerRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount)
, mHandler(aHandler)
{ }
private:
bool
PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
// WorkerRunnable asserts that the dispatch is from parent thread if
// the busy count modification is WorkerThreadUnchangedBusyCount.
// Since this runnable will be dispatched from the timer thread, we override
// PreDispatch and PostDispatch to skip the check.
return true;
}
void
PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
bool aDispatchResult) override
{
// Silence bad assertions.
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override;
RefPtr<AllowWindowInteractionHandler> mHandler;
};
class AllowWindowInteractionHandler final : public PromiseNativeHandler
{
friend class ClearWindowAllowedRunnable;
nsCOMPtr<nsITimer> mTimer;
~AllowWindowInteractionHandler()
{
}
void
ClearWindowAllowed(WorkerPrivate* aWorkerPrivate)
{
MOZ_ASSERT(aWorkerPrivate);
aWorkerPrivate->AssertIsOnWorkerThread();
if (!mTimer) {
return;
}
// XXXcatalinb: This *might* be executed after the global was unrooted, in
// which case GlobalScope() will return null. Making the check here just
// to be safe.
WorkerGlobalScope* globalScope = aWorkerPrivate->GlobalScope();
if (!globalScope) {
return;
}
globalScope->ConsumeWindowInteraction();
mTimer->Cancel();
mTimer = nullptr;
MOZ_ALWAYS_TRUE(aWorkerPrivate->ModifyBusyCountFromWorker(aWorkerPrivate->GetJSContext(),
false));
}
void
StartClearWindowTimer(WorkerPrivate* aWorkerPrivate)
{
MOZ_ASSERT(aWorkerPrivate);
aWorkerPrivate->AssertIsOnWorkerThread();
MOZ_ASSERT(!mTimer);
nsresult rv;
nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
RefPtr<ClearWindowAllowedRunnable> r =
new ClearWindowAllowedRunnable(aWorkerPrivate, this);
RefPtr<TimerThreadEventTarget> target =
new TimerThreadEventTarget(aWorkerPrivate, r);
rv = timer->SetTarget(target);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
// The important stuff that *has* to be reversed.
if (NS_WARN_IF(!aWorkerPrivate->ModifyBusyCountFromWorker(aWorkerPrivate->GetJSContext(), true))) {
return;
}
aWorkerPrivate->GlobalScope()->AllowWindowInteraction();
timer.swap(mTimer);
// We swap first and then initialize the timer so that even if initializing
// fails, we still clean the busy count and interaction count correctly.
// The timer can't be initialized before modifying the busy count since the
// timer thread could run and call the timeout but the worker may
// already be terminating and modifying the busy count could fail.
rv = mTimer->InitWithFuncCallback(DummyNotificationTimerCallback, nullptr,
gDOMDisableOpenClickDelay,
nsITimer::TYPE_ONE_SHOT);
if (NS_WARN_IF(NS_FAILED(rv))) {
ClearWindowAllowed(aWorkerPrivate);
return;
}
}
public:
NS_DECL_ISUPPORTS
explicit AllowWindowInteractionHandler(WorkerPrivate* aWorkerPrivate)
{
StartClearWindowTimer(aWorkerPrivate);
}
void
ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
{
WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
ClearWindowAllowed(workerPrivate);
}
void
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
{
WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
ClearWindowAllowed(workerPrivate);
}
};
NS_IMPL_ISUPPORTS0(AllowWindowInteractionHandler)
bool
ClearWindowAllowedRunnable::WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate)
{
mHandler->ClearWindowAllowed(aWorkerPrivate);
return true;
}
class SendNotificationClickEventRunnable final : public ExtendableEventWorkerRunnable
{
const nsString mID;
const nsString mTitle;
const nsString mDir;
const nsString mLang;
const nsString mBody;
const nsString mTag;
const nsString mIcon;
const nsString mData;
const nsString mBehavior;
const nsString mScope;
public:
SendNotificationClickEventRunnable(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aKeepAliveToken,
const nsAString& aID,
const nsAString& aTitle,
const nsAString& aDir,
const nsAString& aLang,
const nsAString& aBody,
const nsAString& aTag,
const nsAString& aIcon,
const nsAString& aData,
const nsAString& aBehavior,
const nsAString& aScope)
: ExtendableEventWorkerRunnable(aWorkerPrivate, aKeepAliveToken)
, mID(aID)
, mTitle(aTitle)
, mDir(aDir)
, mLang(aLang)
, mBody(aBody)
, mTag(aTag)
, mIcon(aIcon)
, mData(aData)
, mBehavior(aBehavior)
, mScope(aScope)
{
AssertIsOnMainThread();
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
MOZ_ASSERT(aWorkerPrivate);
RefPtr<EventTarget> target = do_QueryObject(aWorkerPrivate->GlobalScope());
ErrorResult result;
RefPtr<Notification> notification =
Notification::ConstructFromFields(aWorkerPrivate->GlobalScope(), mID,
mTitle, mDir, mLang, mBody, mTag, mIcon,
mData, mScope, result);
if (NS_WARN_IF(result.Failed())) {
return false;
}
NotificationEventInit nei;
nei.mNotification = notification;
nei.mBubbles = false;
nei.mCancelable = false;
RefPtr<NotificationEvent> event =
NotificationEvent::Constructor(target,
NS_LITERAL_STRING("notificationclick"),
nei, result);
if (NS_WARN_IF(result.Failed())) {
return false;
}
event->SetTrusted(true);
RefPtr<Promise> waitUntil;
aWorkerPrivate->GlobalScope()->AllowWindowInteraction();
DispatchExtendableEventOnWorkerScope(aCx, aWorkerPrivate->GlobalScope(),
event, getter_AddRefs(waitUntil));
aWorkerPrivate->GlobalScope()->ConsumeWindowInteraction();
if (waitUntil) {
RefPtr<AllowWindowInteractionHandler> allowWindowInteraction =
new AllowWindowInteractionHandler(aWorkerPrivate);
waitUntil->AppendNativeHandler(allowWindowInteraction);
}
return true;
}
};
} // namespace anonymous
nsresult
ServiceWorkerPrivate::SendNotificationClickEvent(const nsAString& aID,
const nsAString& aTitle,
const nsAString& aDir,
const nsAString& aLang,
const nsAString& aBody,
const nsAString& aTag,
const nsAString& aIcon,
const nsAString& aData,
const nsAString& aBehavior,
const nsAString& aScope)
{
nsresult rv = SpawnWorkerIfNeeded(NotificationClickEvent, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
gDOMDisableOpenClickDelay = Preferences::GetInt("dom.disable_open_click_delay");
RefPtr<WorkerRunnable> r =
new SendNotificationClickEventRunnable(mWorkerPrivate, mKeepAliveToken,
aID, aTitle, aDir, aLang,
aBody, aTag, aIcon, aData,
aBehavior, aScope);
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
namespace {
// Inheriting ExtendableEventWorkerRunnable so that the worker is not terminated
// while handling the fetch event, though that's very unlikely.
class FetchEventRunnable : public ExtendableFunctionalEventWorkerRunnable
, public nsIHttpHeaderVisitor {
nsMainThreadPtrHandle<nsIInterceptedChannel> mInterceptedChannel;
const nsCString mScriptSpec;
nsTArray<nsCString> mHeaderNames;
nsTArray<nsCString> mHeaderValues;
nsCString mSpec;
nsCString mMethod;
nsString mClientId;
bool mIsReload;
DebugOnly<bool> mIsHttpChannel;
RequestMode mRequestMode;
RequestRedirect mRequestRedirect;
RequestCredentials mRequestCredentials;
nsContentPolicyType mContentPolicyType;
nsCOMPtr<nsIInputStream> mUploadStream;
nsCString mReferrer;
public:
FetchEventRunnable(WorkerPrivate* aWorkerPrivate,
KeepAliveToken* aKeepAliveToken,
nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
// CSP checks might require the worker script spec
// later on.
const nsACString& aScriptSpec,
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
const nsAString& aDocumentId,
bool aIsReload)
: ExtendableFunctionalEventWorkerRunnable(
aWorkerPrivate, aKeepAliveToken, aRegistration)
, mInterceptedChannel(aChannel)
, mScriptSpec(aScriptSpec)
, mClientId(aDocumentId)
, mIsReload(aIsReload)
, mIsHttpChannel(false)
, mRequestMode(RequestMode::No_cors)
, mRequestRedirect(RequestRedirect::Follow)
// By default we set it to same-origin since normal HTTP fetches always
// send credentials to same-origin websites unless explicitly forbidden.
, mRequestCredentials(RequestCredentials::Same_origin)
, mContentPolicyType(nsIContentPolicy::TYPE_INVALID)
, mReferrer(kFETCH_CLIENT_REFERRER_STR)
{
MOZ_ASSERT(aWorkerPrivate);
}
NS_DECL_ISUPPORTS_INHERITED
NS_IMETHOD
VisitHeader(const nsACString& aHeader, const nsACString& aValue) override
{
mHeaderNames.AppendElement(aHeader);
mHeaderValues.AppendElement(aValue);
return NS_OK;
}
nsresult
Init()
{
AssertIsOnMainThread();
nsCOMPtr<nsIChannel> channel;
nsresult rv = mInterceptedChannel->GetChannel(getter_AddRefs(channel));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
rv = uri->GetSpec(mSpec);
NS_ENSURE_SUCCESS(rv, rv);
uint32_t loadFlags;
rv = channel->GetLoadFlags(&loadFlags);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsILoadInfo> loadInfo;
rv = channel->GetLoadInfo(getter_AddRefs(loadInfo));
NS_ENSURE_SUCCESS(rv, rv);
mContentPolicyType = loadInfo->InternalContentPolicyType();
nsCOMPtr<nsIURI> referrerURI;
rv = NS_GetReferrerFromChannel(channel, getter_AddRefs(referrerURI));
// We can't bail on failure since certain non-http channels like JAR
// channels are intercepted but don't have referrers.
if (NS_SUCCEEDED(rv) && referrerURI) {
rv = referrerURI->GetSpec(mReferrer);
NS_ENSURE_SUCCESS(rv, rv);
}
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel);
if (httpChannel) {
mIsHttpChannel = true;
rv = httpChannel->GetRequestMethod(mMethod);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIHttpChannelInternal> internalChannel = do_QueryInterface(httpChannel);
NS_ENSURE_TRUE(internalChannel, NS_ERROR_NOT_AVAILABLE);
mRequestMode = InternalRequest::MapChannelToRequestMode(channel);
// This is safe due to static_asserts at top of file.
uint32_t redirectMode;
internalChannel->GetRedirectMode(&redirectMode);
mRequestRedirect = static_cast<RequestRedirect>(redirectMode);
if (loadFlags & nsIRequest::LOAD_ANONYMOUS) {
mRequestCredentials = RequestCredentials::Omit;
} else {
bool includeCrossOrigin;
internalChannel->GetCorsIncludeCredentials(&includeCrossOrigin);
if (includeCrossOrigin) {
mRequestCredentials = RequestCredentials::Include;
}
}
rv = httpChannel->VisitNonDefaultRequestHeaders(this);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIUploadChannel2> uploadChannel = do_QueryInterface(httpChannel);
if (uploadChannel) {
MOZ_ASSERT(!mUploadStream);
bool bodyHasHeaders = false;
rv = uploadChannel->GetUploadStreamHasHeaders(&bodyHasHeaders);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIInputStream> uploadStream;
rv = uploadChannel->CloneUploadStream(getter_AddRefs(uploadStream));
NS_ENSURE_SUCCESS(rv, rv);
if (bodyHasHeaders) {
HandleBodyWithHeaders(uploadStream);
} else {
mUploadStream = uploadStream;
}
}
} else {
nsCOMPtr<nsIJARChannel> jarChannel = do_QueryInterface(channel);
// If it is not an HTTP channel it must be a JAR one.
NS_ENSURE_TRUE(jarChannel, NS_ERROR_NOT_AVAILABLE);
mMethod = "GET";
mRequestMode = InternalRequest::MapChannelToRequestMode(channel);
if (loadFlags & nsIRequest::LOAD_ANONYMOUS) {
mRequestCredentials = RequestCredentials::Omit;
}
}
return NS_OK;
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
MOZ_ASSERT(aWorkerPrivate);
return DispatchFetchEvent(aCx, aWorkerPrivate);
}
NS_IMETHOD
Cancel() override
{
nsCOMPtr<nsIRunnable> runnable = new ResumeRequest(mInterceptedChannel);
if (NS_FAILED(NS_DispatchToMainThread(runnable))) {
NS_WARNING("Failed to resume channel on FetchEventRunnable::Cancel()!\n");
}
WorkerRunnable::Cancel();
return NS_OK;
}
private:
~FetchEventRunnable() {}
class ResumeRequest final : public nsRunnable {
nsMainThreadPtrHandle<nsIInterceptedChannel> mChannel;
public:
explicit ResumeRequest(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel)
: mChannel(aChannel)
{
}
NS_IMETHOD Run()
{
AssertIsOnMainThread();
nsresult rv = mChannel->ResetInterception();
NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Failed to resume intercepted network request");
return rv;
}
};
bool
DispatchFetchEvent(JSContext* aCx, WorkerPrivate* aWorkerPrivate)
{
MOZ_ASSERT(aCx);
MOZ_ASSERT(aWorkerPrivate);
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
GlobalObject globalObj(aCx, aWorkerPrivate->GlobalScope()->GetWrapper());
NS_ConvertUTF8toUTF16 local(mSpec);
RequestOrUSVString requestInfo;
requestInfo.SetAsUSVString().Rebind(local.Data(), local.Length());
RootedDictionary<RequestInit> reqInit(aCx);
reqInit.mMethod.Construct(mMethod);
RefPtr<InternalHeaders> internalHeaders = new InternalHeaders(HeadersGuardEnum::Request);
MOZ_ASSERT(mHeaderNames.Length() == mHeaderValues.Length());
for (uint32_t i = 0; i < mHeaderNames.Length(); i++) {
ErrorResult result;
internalHeaders->Set(mHeaderNames[i], mHeaderValues[i], result);
if (NS_WARN_IF(result.Failed())) {
result.SuppressException();
return false;
}
}
RefPtr<Headers> headers = new Headers(globalObj.GetAsSupports(), internalHeaders);
reqInit.mHeaders.Construct();
reqInit.mHeaders.Value().SetAsHeaders() = headers;
reqInit.mMode.Construct(mRequestMode);
reqInit.mRedirect.Construct(mRequestRedirect);
reqInit.mCredentials.Construct(mRequestCredentials);
ErrorResult result;
RefPtr<Request> request = Request::Constructor(globalObj, requestInfo, reqInit, result);
if (NS_WARN_IF(result.Failed())) {
result.SuppressException();
return false;
}
// For Telemetry, note that this Request object was created by a Fetch event.
RefPtr<InternalRequest> internalReq = request->GetInternalRequest();
MOZ_ASSERT(internalReq);
internalReq->SetCreatedByFetchEvent();
internalReq->SetBody(mUploadStream);
internalReq->SetReferrer(NS_ConvertUTF8toUTF16(mReferrer));
request->SetContentPolicyType(mContentPolicyType);
request->GetInternalHeaders()->SetGuard(HeadersGuardEnum::Immutable, result);
if (NS_WARN_IF(result.Failed())) {
result.SuppressException();
return false;
}
// TODO: remove conditional on http here once app protocol support is
// removed from service worker interception
MOZ_ASSERT_IF(mIsHttpChannel && internalReq->IsNavigationRequest(),
request->Redirect() == RequestRedirect::Manual);
RootedDictionary<FetchEventInit> init(aCx);
init.mRequest.Construct();
init.mRequest.Value() = request;
init.mBubbles = false;
init.mCancelable = true;
init.mClientId = mClientId;
init.mIsReload = mIsReload;
RefPtr<FetchEvent> event =
FetchEvent::Constructor(globalObj, NS_LITERAL_STRING("fetch"), init, result);
if (NS_WARN_IF(result.Failed())) {
result.SuppressException();
return false;
}
event->PostInit(mInterceptedChannel, mScriptSpec);
event->SetTrusted(true);
RefPtr<EventTarget> target = do_QueryObject(aWorkerPrivate->GlobalScope());
nsresult rv2 = target->DispatchDOMEvent(nullptr, event, nullptr, nullptr);
if (NS_WARN_IF(NS_FAILED(rv2)) || !event->WaitToRespond()) {
nsCOMPtr<nsIRunnable> runnable;
if (event->DefaultPrevented(aCx)) {
event->ReportCanceled();
} else if (event->GetInternalNSEvent()->mFlags.mExceptionHasBeenRisen) {
// Exception logged via the WorkerPrivate ErrorReporter
} else {
runnable = new ResumeRequest(mInterceptedChannel);
}
if (!runnable) {
nsCOMPtr<nsIRunnable> updateRunnable =
new RegistrationUpdateRunnable(mRegistration, false /* time check */);
NS_DispatchToMainThread(runnable.forget());
runnable = new CancelChannelRunnable(mInterceptedChannel,
NS_ERROR_INTERCEPTION_FAILED);
}
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(NS_DispatchToMainThread(runnable)));
}
RefPtr<Promise> waitUntilPromise = event->GetPromise();
if (waitUntilPromise) {
RefPtr<KeepAliveHandler> keepAliveHandler =
new KeepAliveHandler(mKeepAliveToken);
waitUntilPromise->AppendNativeHandler(keepAliveHandler);
}
return true;
}
nsresult
HandleBodyWithHeaders(nsIInputStream* aUploadStream)
{
// We are dealing with an nsMIMEInputStream which uses string input streams
// under the hood, so all of the data is available synchronously.
bool nonBlocking = false;
nsresult rv = aUploadStream->IsNonBlocking(&nonBlocking);
NS_ENSURE_SUCCESS(rv, rv);
if (NS_WARN_IF(!nonBlocking)) {
return NS_ERROR_NOT_AVAILABLE;
}
nsAutoCString body;
rv = NS_ConsumeStream(aUploadStream, UINT32_MAX, body);
NS_ENSURE_SUCCESS(rv, rv);
// Extract the headers in the beginning of the buffer
nsAutoCString::const_iterator begin, end;
body.BeginReading(begin);
body.EndReading(end);
const nsAutoCString::const_iterator body_end = end;
nsAutoCString headerName, headerValue;
bool emptyHeader = false;
while (FetchUtil::ExtractHeader(begin, end, headerName,
headerValue, &emptyHeader) &&
!emptyHeader) {
mHeaderNames.AppendElement(headerName);
mHeaderValues.AppendElement(headerValue);
headerName.Truncate();
headerValue.Truncate();
}
// Replace the upload stream with one only containing the body text.
nsCOMPtr<nsIStringInputStream> strStream =
do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Skip past the "\r\n" that separates the headers and the body.
++begin;
++begin;
body.Assign(Substring(begin, body_end));
rv = strStream->SetData(body.BeginReading(), body.Length());
NS_ENSURE_SUCCESS(rv, rv);
mUploadStream = strStream;
return NS_OK;
}
};
NS_IMPL_ISUPPORTS_INHERITED(FetchEventRunnable, WorkerRunnable, nsIHttpHeaderVisitor)
} // anonymous namespace
nsresult
ServiceWorkerPrivate::SendFetchEvent(nsIInterceptedChannel* aChannel,
nsILoadGroup* aLoadGroup,
const nsAString& aDocumentId,
bool aIsReload)
{
AssertIsOnMainThread();
// if the ServiceWorker script fails to load for some reason, just resume
// the original channel.
nsCOMPtr<nsIRunnable> failRunnable =
NS_NewRunnableMethod(aChannel, &nsIInterceptedChannel::ResetInterception);
nsresult rv = SpawnWorkerIfNeeded(FetchEvent, failRunnable, aLoadGroup);
NS_ENSURE_SUCCESS(rv, rv);
nsMainThreadPtrHandle<nsIInterceptedChannel> handle(
new nsMainThreadPtrHolder<nsIInterceptedChannel>(aChannel, false));
if (NS_WARN_IF(!mInfo)) {
return NS_ERROR_FAILURE;
}
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
RefPtr<ServiceWorkerRegistrationInfo> registration =
swm->GetRegistration(mInfo->GetPrincipal(), mInfo->Scope());
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo> regInfo(
new nsMainThreadPtrHolder<ServiceWorkerRegistrationInfo>(registration, false));
RefPtr<FetchEventRunnable> r =
new FetchEventRunnable(mWorkerPrivate, mKeepAliveToken, handle,
mInfo->ScriptSpec(), regInfo,
aDocumentId, aIsReload);
rv = r->Init();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (mInfo->State() == ServiceWorkerState::Activating) {
mPendingFunctionalEvents.AppendElement(r.forget());
return NS_OK;
}
MOZ_ASSERT(mInfo->State() == ServiceWorkerState::Activated);
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
nsresult
ServiceWorkerPrivate::SpawnWorkerIfNeeded(WakeUpReason aWhy,
nsIRunnable* aLoadFailedRunnable,
nsILoadGroup* aLoadGroup)
{
AssertIsOnMainThread();
// XXXcatalinb: We need to have a separate load group that's linked to
// an existing tab child to pass security checks on b2g.
// This should be fixed in bug 1125961, but for now we enforce updating
// the overriden load group when intercepting a fetch.
MOZ_ASSERT_IF(aWhy == FetchEvent, aLoadGroup);
if (mWorkerPrivate) {
mWorkerPrivate->UpdateOverridenLoadGroup(aLoadGroup);
RenewKeepAliveToken(aWhy);
return NS_OK;
}
// Sanity check: mSupportsArray should be empty if we're about to
// spin up a new worker.
MOZ_ASSERT(mSupportsArray.IsEmpty());
if (NS_WARN_IF(!mInfo)) {
NS_WARNING("Trying to wake up a dead service worker.");
return NS_ERROR_FAILURE;
}
// TODO(catalinb): Bug 1192138 - Add telemetry for service worker wake-ups.
// Ensure that the IndexedDatabaseManager is initialized
NS_WARN_IF(!indexedDB::IndexedDatabaseManager::GetOrCreate());
WorkerLoadInfo info;
nsresult rv = NS_NewURI(getter_AddRefs(info.mBaseURI), mInfo->ScriptSpec(),
nullptr, nullptr);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
info.mResolvedScriptURI = info.mBaseURI;
MOZ_ASSERT(!mInfo->CacheName().IsEmpty());
info.mServiceWorkerCacheName = mInfo->CacheName();
info.mServiceWorkerID = mInfo->ID();
info.mLoadGroup = aLoadGroup;
info.mLoadFailedAsyncRunnable = aLoadFailedRunnable;
rv = info.mBaseURI->GetHost(info.mDomain);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
info.mPrincipal = mInfo->GetPrincipal();
nsContentUtils::StorageAccess access =
nsContentUtils::StorageAllowedForPrincipal(info.mPrincipal);
info.mStorageAllowed = access > nsContentUtils::StorageAccess::ePrivateBrowsing;
info.mPrivateBrowsing = false;
nsCOMPtr<nsIContentSecurityPolicy> csp;
rv = info.mPrincipal->GetCsp(getter_AddRefs(csp));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
info.mCSP = csp;
if (info.mCSP) {
rv = info.mCSP->GetAllowsEval(&info.mReportCSPViolations,
&info.mEvalAllowed);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
} else {
info.mEvalAllowed = true;
info.mReportCSPViolations = false;
}
WorkerPrivate::OverrideLoadInfoLoadGroup(info);
AutoJSAPI jsapi;
jsapi.Init();
ErrorResult error;
NS_ConvertUTF8toUTF16 scriptSpec(mInfo->ScriptSpec());
mWorkerPrivate = WorkerPrivate::Constructor(jsapi.cx(),
scriptSpec,
false, WorkerTypeService,
mInfo->Scope(), &info, error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
mIsPushWorker = false;
RenewKeepAliveToken(aWhy);
return NS_OK;
}
void
ServiceWorkerPrivate::StoreISupports(nsISupports* aSupports)
{
AssertIsOnMainThread();
MOZ_ASSERT(mWorkerPrivate);
MOZ_ASSERT(!mSupportsArray.Contains(aSupports));
mSupportsArray.AppendElement(aSupports);
}
void
ServiceWorkerPrivate::RemoveISupports(nsISupports* aSupports)
{
AssertIsOnMainThread();
mSupportsArray.RemoveElement(aSupports);
}
void
ServiceWorkerPrivate::TerminateWorker()
{
AssertIsOnMainThread();
mIdleWorkerTimer->Cancel();
mKeepAliveToken = nullptr;
if (mWorkerPrivate) {
if (Preferences::GetBool("dom.serviceWorkers.testing.enabled")) {
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (os) {
os->NotifyObservers(this, "service-worker-shutdown", nullptr);
}
}
AutoJSAPI jsapi;
jsapi.Init();
NS_WARN_IF(!mWorkerPrivate->Terminate(jsapi.cx()));
mWorkerPrivate = nullptr;
mSupportsArray.Clear();
// Any pending events are never going to fire on this worker. Cancel
// them so that intercepted channels can be reset and other resources
// cleaned up.
nsTArray<RefPtr<WorkerRunnable>> pendingEvents;
mPendingFunctionalEvents.SwapElements(pendingEvents);
for (uint32_t i = 0; i < pendingEvents.Length(); ++i) {
pendingEvents[i]->Cancel();
}
}
}
void
ServiceWorkerPrivate::NoteDeadServiceWorkerInfo()
{
AssertIsOnMainThread();
mInfo = nullptr;
TerminateWorker();
}
void
ServiceWorkerPrivate::NoteStoppedControllingDocuments()
{
AssertIsOnMainThread();
if (mIsPushWorker || mDebuggerCount) {
return;
}
TerminateWorker();
}
void
ServiceWorkerPrivate::Activated()
{
AssertIsOnMainThread();
// If we had to queue up events due to the worker activating, that means
// the worker must be currently running. We should be called synchronously
// when the worker becomes activated.
MOZ_ASSERT_IF(!mPendingFunctionalEvents.IsEmpty(), mWorkerPrivate);
nsTArray<RefPtr<WorkerRunnable>> pendingEvents;
mPendingFunctionalEvents.SwapElements(pendingEvents);
for (uint32_t i = 0; i < pendingEvents.Length(); ++i) {
RefPtr<WorkerRunnable> r = pendingEvents[i].forget();
AutoJSAPI jsapi;
jsapi.Init();
if (NS_WARN_IF(!r->Dispatch(jsapi.cx()))) {
NS_WARNING("Failed to dispatch pending functional event!");
}
}
}
nsresult
ServiceWorkerPrivate::GetDebugger(nsIWorkerDebugger** aResult)
{
AssertIsOnMainThread();
MOZ_ASSERT(aResult);
if (!mDebuggerCount) {
return NS_OK;
}
MOZ_ASSERT(mWorkerPrivate);
nsCOMPtr<nsIWorkerDebugger> debugger = do_QueryInterface(mWorkerPrivate->Debugger());
debugger.forget(aResult);
return NS_OK;
}
nsresult
ServiceWorkerPrivate::AttachDebugger()
{
AssertIsOnMainThread();
// When the first debugger attaches to a worker, we spawn a worker if needed,
// and cancel the idle timeout. The idle timeout should not be reset until
// the last debugger detached from the worker.
if (!mDebuggerCount) {
nsresult rv = SpawnWorkerIfNeeded(AttachEvent, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
mIdleWorkerTimer->Cancel();
}
++mDebuggerCount;
return NS_OK;
}
nsresult
ServiceWorkerPrivate::DetachDebugger()
{
AssertIsOnMainThread();
if (!mDebuggerCount) {
return NS_ERROR_UNEXPECTED;
}
--mDebuggerCount;
// When the last debugger detaches from a worker, we either reset the idle
// timeout, or terminate the worker if there are no more active tokens.
if (!mDebuggerCount) {
if (mTokenCount) {
ResetIdleTimeout();
} else {
TerminateWorker();
}
}
return NS_OK;
}
/* static */ void
ServiceWorkerPrivate::NoteIdleWorkerCallback(nsITimer* aTimer, void* aPrivate)
{
AssertIsOnMainThread();
MOZ_ASSERT(aPrivate);
RefPtr<ServiceWorkerPrivate> swp = static_cast<ServiceWorkerPrivate*>(aPrivate);
MOZ_ASSERT(aTimer == swp->mIdleWorkerTimer, "Invalid timer!");
// Release ServiceWorkerPrivate's token, since the grace period has ended.
swp->mKeepAliveToken = nullptr;
if (swp->mWorkerPrivate) {
// If we still have a workerPrivate at this point it means there are pending
// waitUntil promises. Wait a bit more until we forcibly terminate the
// worker.
uint32_t timeout = Preferences::GetInt("dom.serviceWorkers.idle_extended_timeout");
DebugOnly<nsresult> rv =
swp->mIdleWorkerTimer->InitWithFuncCallback(ServiceWorkerPrivate::TerminateWorkerCallback,
aPrivate,
timeout,
nsITimer::TYPE_ONE_SHOT);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
/* static */ void
ServiceWorkerPrivate::TerminateWorkerCallback(nsITimer* aTimer, void *aPrivate)
{
AssertIsOnMainThread();
MOZ_ASSERT(aPrivate);
RefPtr<ServiceWorkerPrivate> serviceWorkerPrivate =
static_cast<ServiceWorkerPrivate*>(aPrivate);
MOZ_ASSERT(aTimer == serviceWorkerPrivate->mIdleWorkerTimer,
"Invalid timer!");
serviceWorkerPrivate->TerminateWorker();
}
void
ServiceWorkerPrivate::RenewKeepAliveToken(WakeUpReason aWhy)
{
// We should have an active worker if we're renewing the keep alive token.
MOZ_ASSERT(mWorkerPrivate);
if (aWhy == PushEvent || aWhy == PushSubscriptionChangeEvent) {
mIsPushWorker = true;
}
// If there is at least one debugger attached to the worker, the idle worker
// timeout was canceled when the first debugger attached to the worker. It
// should not be reset until the last debugger detaches from the worker.
if (!mDebuggerCount) {
ResetIdleTimeout();
}
if (!mKeepAliveToken) {
mKeepAliveToken = new KeepAliveToken(this);
}
}
void
ServiceWorkerPrivate::ResetIdleTimeout()
{
uint32_t timeout = Preferences::GetInt("dom.serviceWorkers.idle_timeout");
DebugOnly<nsresult> rv =
mIdleWorkerTimer->InitWithFuncCallback(ServiceWorkerPrivate::NoteIdleWorkerCallback,
this, timeout,
nsITimer::TYPE_ONE_SHOT);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
void
ServiceWorkerPrivate::AddToken()
{
AssertIsOnMainThread();
++mTokenCount;
}
void
ServiceWorkerPrivate::ReleaseToken()
{
AssertIsOnMainThread();
MOZ_ASSERT(mTokenCount > 0);
--mTokenCount;
if (!mTokenCount) {
TerminateWorker();
}
}
END_WORKERS_NAMESPACE