Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ServiceWorkerManager.h"
#include <algorithm>
#include "nsCOMPtr.h"
#include "nsIEffectiveTLDService.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsINamed.h"
#include "nsINetworkInterceptController.h"
#include "nsIMutableArray.h"
#include "nsIPrincipal.h"
#include "nsITimer.h"
#include "nsIUploadChannel2.h"
#include "nsServiceManagerUtils.h"
#include "nsDebug.h"
#include "nsIPermissionManager.h"
#include "nsXULAppAPI.h"
#include "jsapi.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/LoadContext.h"
#include "mozilla/Result.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/Telemetry.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/ClientHandle.h"
#include "mozilla/dom/ClientManager.h"
#include "mozilla/dom/ClientSource.h"
#include "mozilla/dom/ConsoleUtils.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ErrorEvent.h"
#include "mozilla/dom/Headers.h"
#include "mozilla/dom/InternalHeaders.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/NotificationEvent.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/Request.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/dom/SharedWorker.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/dom/ScriptLoader.h"
#include "mozilla/PermissionManager.h"
#include "mozilla/Unused.h"
#include "mozilla/EnumSet.h"
#include "nsContentUtils.h"
#include "nsNetUtil.h"
#include "nsProxyRelease.h"
#include "nsQueryObject.h"
#include "nsTArray.h"
#include "ServiceWorker.h"
#include "ServiceWorkerContainer.h"
#include "ServiceWorkerInfo.h"
#include "ServiceWorkerJobQueue.h"
#include "ServiceWorkerManagerChild.h"
#include "ServiceWorkerPrivate.h"
#include "ServiceWorkerRegisterJob.h"
#include "ServiceWorkerRegistrar.h"
#include "ServiceWorkerRegistration.h"
#include "ServiceWorkerScriptCache.h"
#include "ServiceWorkerShutdownBlocker.h"
#include "ServiceWorkerEvents.h"
#include "ServiceWorkerUnregisterJob.h"
#include "ServiceWorkerUpdateJob.h"
#include "ServiceWorkerUpdaterChild.h"
#include "ServiceWorkerUtils.h"
#ifdef PostMessage
# undef PostMessage
#endif
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::ipc;
namespace mozilla {
namespace dom {
static_assert(
nsIHttpChannelInternal::CORS_MODE_SAME_ORIGIN ==
static_cast<uint32_t>(RequestMode::Same_origin),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(
nsIHttpChannelInternal::CORS_MODE_NO_CORS ==
static_cast<uint32_t>(RequestMode::No_cors),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(
nsIHttpChannelInternal::CORS_MODE_CORS ==
static_cast<uint32_t>(RequestMode::Cors),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(
nsIHttpChannelInternal::CORS_MODE_NAVIGATE ==
static_cast<uint32_t>(RequestMode::Navigate),
"RequestMode enumeration value should match Necko CORS mode value.");
static_assert(
nsIHttpChannelInternal::REDIRECT_MODE_FOLLOW ==
static_cast<uint32_t>(RequestRedirect::Follow),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(
nsIHttpChannelInternal::REDIRECT_MODE_ERROR ==
static_cast<uint32_t>(RequestRedirect::Error),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(
nsIHttpChannelInternal::REDIRECT_MODE_MANUAL ==
static_cast<uint32_t>(RequestRedirect::Manual),
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(
3 == RequestRedirectValues::Count,
"RequestRedirect enumeration value should make Necko Redirect mode value.");
static_assert(
nsIHttpChannelInternal::FETCH_CACHE_MODE_DEFAULT ==
static_cast<uint32_t>(RequestCache::Default),
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(
nsIHttpChannelInternal::FETCH_CACHE_MODE_NO_STORE ==
static_cast<uint32_t>(RequestCache::No_store),
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(
nsIHttpChannelInternal::FETCH_CACHE_MODE_RELOAD ==
static_cast<uint32_t>(RequestCache::Reload),
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(
nsIHttpChannelInternal::FETCH_CACHE_MODE_NO_CACHE ==
static_cast<uint32_t>(RequestCache::No_cache),
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(
nsIHttpChannelInternal::FETCH_CACHE_MODE_FORCE_CACHE ==
static_cast<uint32_t>(RequestCache::Force_cache),
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(
nsIHttpChannelInternal::FETCH_CACHE_MODE_ONLY_IF_CACHED ==
static_cast<uint32_t>(RequestCache::Only_if_cached),
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(
6 == RequestCacheValues::Count,
"RequestCache enumeration value should match Necko Cache mode value.");
static_assert(static_cast<uint16_t>(ServiceWorkerUpdateViaCache::Imports) ==
nsIServiceWorkerRegistrationInfo::UPDATE_VIA_CACHE_IMPORTS,
"nsIServiceWorkerRegistrationInfo::UPDATE_VIA_CACHE_*"
" should match ServiceWorkerUpdateViaCache enumeration.");
static_assert(static_cast<uint16_t>(ServiceWorkerUpdateViaCache::All) ==
nsIServiceWorkerRegistrationInfo::UPDATE_VIA_CACHE_ALL,
"nsIServiceWorkerRegistrationInfo::UPDATE_VIA_CACHE_*"
" should match ServiceWorkerUpdateViaCache enumeration.");
static_assert(static_cast<uint16_t>(ServiceWorkerUpdateViaCache::None) ==
nsIServiceWorkerRegistrationInfo::UPDATE_VIA_CACHE_NONE,
"nsIServiceWorkerRegistrationInfo::UPDATE_VIA_CACHE_*"
" should match ServiceWorkerUpdateViaCache enumeration.");
static StaticRefPtr<ServiceWorkerManager> gInstance;
namespace {
nsresult PopulateRegistrationData(
nsIPrincipal* aPrincipal,
const ServiceWorkerRegistrationInfo* aRegistration,
ServiceWorkerRegistrationData& aData) {
MOZ_ASSERT(aPrincipal);
MOZ_ASSERT(aRegistration);
if (NS_WARN_IF(!BasePrincipal::Cast(aPrincipal)->IsContentPrincipal())) {
return NS_ERROR_FAILURE;
}
nsresult rv = PrincipalToPrincipalInfo(aPrincipal, &aData.principal());
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
aData.scope() = aRegistration->Scope();
// TODO: When bug 1426401 is implemented we will need to handle more
// than just the active worker here.
RefPtr<ServiceWorkerInfo> active = aRegistration->GetActive();
MOZ_ASSERT(active);
if (NS_WARN_IF(!active)) {
return NS_ERROR_FAILURE;
}
aData.currentWorkerURL() = active->ScriptSpec();
aData.cacheName() = active->CacheName();
aData.currentWorkerHandlesFetch() = active->HandlesFetch();
aData.currentWorkerInstalledTime() = active->GetInstalledTime();
aData.currentWorkerActivatedTime() = active->GetActivatedTime();
aData.updateViaCache() =
static_cast<uint32_t>(aRegistration->GetUpdateViaCache());
aData.lastUpdateTime() = aRegistration->GetLastUpdateTime();
MOZ_ASSERT(ServiceWorkerRegistrationDataIsValid(aData));
return NS_OK;
}
class TeardownRunnable final : public Runnable {
public:
explicit TeardownRunnable(ServiceWorkerManagerChild* aActor)
: Runnable("dom::ServiceWorkerManager::TeardownRunnable"),
mActor(aActor) {
MOZ_ASSERT(mActor);
}
NS_IMETHOD Run() override {
MOZ_ASSERT(mActor);
mActor->SendShutdown();
return NS_OK;
}
private:
~TeardownRunnable() = default;
RefPtr<ServiceWorkerManagerChild> mActor;
};
bool ServiceWorkersAreCrossProcess() {
return ServiceWorkerParentInterceptEnabled() && XRE_IsE10sParentProcess();
}
const char* GetStartShutdownTopic() {
if (ServiceWorkersAreCrossProcess()) {
return "profile-change-teardown";
}
return NS_XPCOM_SHUTDOWN_OBSERVER_ID;
}
constexpr char kFinishShutdownTopic[] = "profile-before-change-qm";
already_AddRefed<nsIAsyncShutdownClient> GetAsyncShutdownBarrier() {
AssertIsOnMainThread();
if (!ServiceWorkersAreCrossProcess()) {
return nullptr;
}
nsCOMPtr<nsIAsyncShutdownService> svc = services::GetAsyncShutdownService();
MOZ_ASSERT(svc);
nsCOMPtr<nsIAsyncShutdownClient> barrier;
DebugOnly<nsresult> rv =
svc->GetProfileChangeTeardown(getter_AddRefs(barrier));
MOZ_ASSERT(NS_SUCCEEDED(rv));
return barrier.forget();
}
Result<nsCOMPtr<nsIPrincipal>, nsresult> ScopeToPrincipal(
nsIURI* aScopeURI, const OriginAttributes& aOriginAttributes) {
MOZ_ASSERT(aScopeURI);
nsCOMPtr<nsIPrincipal> principal =
BasePrincipal::CreateContentPrincipal(aScopeURI, aOriginAttributes);
if (NS_WARN_IF(!principal)) {
return Err(NS_ERROR_FAILURE);
}
return principal;
}
Result<nsCOMPtr<nsIPrincipal>, nsresult> ScopeToPrincipal(
const nsACString& aScope, const OriginAttributes& aOriginAttributes) {
MOZ_ASSERT(nsContentUtils::IsAbsoluteURL(aScope));
nsCOMPtr<nsIURI> scopeURI;
MOZ_TRY(NS_NewURI(getter_AddRefs(scopeURI), aScope));
return ScopeToPrincipal(scopeURI, aOriginAttributes);
}
} // namespace
struct ServiceWorkerManager::RegistrationDataPerPrincipal final {
// Implements a container of keys for the "scope to registration map":
//
// where each key is an absolute URL.
//
// The properties of this map that the spec uses are
// 1) insertion,
// 2) removal,
// 3) iteration of scopes in FIFO order (excluding removed scopes),
// 4) and finding, for a given path, the maximal length scope which is a
// prefix of the path.
//
// Additionally, because this is a container of keys for a map, there
// shouldn't be duplicate scopes.
//
// The current implementation uses a dynamic array as the underlying
// container, which is not optimal for unbounded container sizes (all
// supported operations are in linear time) but may be superior for small
// container sizes.
//
// If this is proven to be too slow, the underlying storage should be replaced
// with a linked list of scopes in combination with an ordered map that maps
// scopes to linked list elements/iterators. This would reduce all of the
// above operations besides iteration (necessarily linear) to logarithmic
// time.
class ScopeContainer final : private nsTArray<nsCString> {
using Base = nsTArray<nsCString>;
public:
using Base::Contains;
using Base::IsEmpty;
using Base::Length;
// No using-declaration to avoid importing the non-const overload.
decltype(auto) operator[](Base::index_type aIndex) const {
return Base::operator[](aIndex);
}
void InsertScope(const nsACString& aScope) {
MOZ_DIAGNOSTIC_ASSERT(nsContentUtils::IsAbsoluteURL(aScope));
if (Contains(aScope)) {
return;
}
AppendElement(aScope);
}
void RemoveScope(const nsACString& aScope) {
MOZ_ALWAYS_TRUE(RemoveElement(aScope));
}
// Implements most of "Match Service Worker Registration":
Maybe<nsCString> MatchScope(const nsACString& aClientUrl) const {
Maybe<nsCString> match;
for (const nsCString& scope : *this) {
if (StringBeginsWith(aClientUrl, scope)) {
if (!match || scope.Length() > match->Length()) {
match = Some(scope);
}
}
}
// Step 7.2:
// "Assert: matchingScope’s origin and clientURL’s origin are same
// origin."
MOZ_DIAGNOSTIC_ASSERT_IF(match, IsSameOrigin(*match, aClientUrl));
return match;
}
private:
bool IsSameOrigin(const nsACString& aMatchingScope,
const nsACString& aClientUrl) const {
auto parseResult = ScopeToPrincipal(aMatchingScope, OriginAttributes());
if (NS_WARN_IF(parseResult.isErr())) {
return false;
}
auto scopePrincipal = parseResult.unwrap();
parseResult = ScopeToPrincipal(aClientUrl, OriginAttributes());
if (NS_WARN_IF(parseResult.isErr())) {
return false;
}
auto clientPrincipal = parseResult.unwrap();
bool equals = false;
if (NS_WARN_IF(
NS_FAILED(scopePrincipal->Equals(clientPrincipal, &equals)))) {
return false;
}
return equals;
}
};
ScopeContainer mScopeContainer;
// Scope to registration.
// The scope should be a fully qualified valid URL.
nsRefPtrHashtable<nsCStringHashKey, ServiceWorkerRegistrationInfo> mInfos;
// Maps scopes to job queues.
nsRefPtrHashtable<nsCStringHashKey, ServiceWorkerJobQueue> mJobQueues;
// Map scopes to scheduled update timers.
nsInterfaceHashtable<nsCStringHashKey, nsITimer> mUpdateTimers;
};
//////////////////////////
// ServiceWorkerManager //
//////////////////////////
NS_IMPL_ADDREF(ServiceWorkerManager)
NS_IMPL_RELEASE(ServiceWorkerManager)
NS_INTERFACE_MAP_BEGIN(ServiceWorkerManager)
NS_INTERFACE_MAP_ENTRY(nsIServiceWorkerManager)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIServiceWorkerManager)
NS_INTERFACE_MAP_END
ServiceWorkerManager::ServiceWorkerManager()
: mActor(nullptr), mShuttingDown(false) {}
ServiceWorkerManager::~ServiceWorkerManager() {
// The map will assert if it is not empty when destroyed.
mRegistrationInfos.Clear();
if (!ServiceWorkersAreCrossProcess()) {
MOZ_ASSERT(!mActor);
}
// This can happen if the browser is started up in ProfileManager mode, in
// which case XPCOM will startup and shutdown, but there won't be any
// profile-* topic notifications. The shutdown blocker expects to be in a
// NotAcceptingPromises state when it's destroyed, and this transition
// normally happens in the "profile-change-teardown" notification callback
// (which won't be called in ProfileManager mode).
if (!mShuttingDown && mShutdownBlocker) {
mShutdownBlocker->StopAcceptingPromises();
}
}
void ServiceWorkerManager::BlockShutdownOn(GenericNonExclusivePromise* aPromise,
uint32_t aShutdownStateId) {
AssertIsOnMainThread();
// This may be called when in non-e10s mode with parent-intercept enabled.
if (!ServiceWorkersAreCrossProcess()) {
return;
}
MOZ_ASSERT(mShutdownBlocker);
MOZ_ASSERT(aPromise);
mShutdownBlocker->WaitOnPromise(aPromise, aShutdownStateId);
}
void ServiceWorkerManager::Init(ServiceWorkerRegistrar* aRegistrar) {
nsCOMPtr<nsIAsyncShutdownClient> shutdownBarrier = GetAsyncShutdownBarrier();
if (shutdownBarrier) {
mShutdownBlocker =
ServiceWorkerShutdownBlocker::CreateAndRegisterOn(shutdownBarrier);
MOZ_ASSERT(mShutdownBlocker);
}
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
DebugOnly<nsresult> rv;
rv = obs->AddObserver(this, GetStartShutdownTopic(), false /* ownsWeak */);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
if (XRE_IsParentProcess()) {
MOZ_DIAGNOSTIC_ASSERT(aRegistrar);
nsTArray<ServiceWorkerRegistrationData> data;
aRegistrar->GetRegistrations(data);
LoadRegistrations(data);
}
PBackgroundChild* actorChild = BackgroundChild::GetOrCreateForCurrentThread();
if (NS_WARN_IF(!actorChild)) {
MaybeStartShutdown();
return;
}
PServiceWorkerManagerChild* actor =
actorChild->SendPServiceWorkerManagerConstructor();
if (!actor) {
MaybeStartShutdown();
return;
}
mActor = static_cast<ServiceWorkerManagerChild*>(actor);
}
RefPtr<GenericErrorResultPromise> ServiceWorkerManager::StartControllingClient(
const ClientInfo& aClientInfo,
ServiceWorkerRegistrationInfo* aRegistrationInfo,
bool aControlClientHandle) {
MOZ_DIAGNOSTIC_ASSERT(aRegistrationInfo->GetActive());
RefPtr<GenericErrorResultPromise> promise;
RefPtr<ServiceWorkerManager> self(this);
const ServiceWorkerDescriptor& active =
aRegistrationInfo->GetActive()->Descriptor();
auto entry = mControlledClients.LookupForAdd(aClientInfo.Id());
if (entry) {
RefPtr<ServiceWorkerRegistrationInfo> old =
std::move(entry.Data()->mRegistrationInfo);
if (aControlClientHandle) {
promise = entry.Data()->mClientHandle->Control(active);
} else {
promise = GenericErrorResultPromise::CreateAndResolve(false, __func__);
}
entry.Data()->mRegistrationInfo = aRegistrationInfo;
if (old != aRegistrationInfo) {
StopControllingRegistration(old);
aRegistrationInfo->StartControllingClient();
}
Telemetry::Accumulate(Telemetry::SERVICE_WORKER_CONTROLLED_DOCUMENTS, 1);
// Always check to see if we failed to actually control the client. In
// that case removed the client from our list of controlled clients.
return promise->Then(
GetMainThreadSerialEventTarget(), __func__,
[](bool) {
// do nothing on success
return GenericErrorResultPromise::CreateAndResolve(true, __func__);
},
[self, aClientInfo](const CopyableErrorResult& aRv) {
// failed to control, forget about this client
self->StopControllingClient(aClientInfo);
return GenericErrorResultPromise::CreateAndReject(aRv, __func__);
});
}
RefPtr<ClientHandle> clientHandle = ClientManager::CreateHandle(
aClientInfo, GetMainThreadSerialEventTarget());
if (aControlClientHandle) {
promise = clientHandle->Control(active);
} else {
promise = GenericErrorResultPromise::CreateAndResolve(false, __func__);
}
aRegistrationInfo->StartControllingClient();
entry.OrInsert([&] {
return new ControlledClientData(clientHandle, aRegistrationInfo);
});
clientHandle->OnDetach()->Then(
GetMainThreadSerialEventTarget(), __func__,
[self, aClientInfo] { self->StopControllingClient(aClientInfo); });
Telemetry::Accumulate(Telemetry::SERVICE_WORKER_CONTROLLED_DOCUMENTS, 1);
// Always check to see if we failed to actually control the client. In
// that case removed the client from our list of controlled clients.
return promise->Then(
GetMainThreadSerialEventTarget(), __func__,
[](bool) {
// do nothing on success
return GenericErrorResultPromise::CreateAndResolve(true, __func__);
},
[self, aClientInfo](const CopyableErrorResult& aRv) {
// failed to control, forget about this client
self->StopControllingClient(aClientInfo);
return GenericErrorResultPromise::CreateAndReject(aRv, __func__);
});
}
void ServiceWorkerManager::StopControllingClient(
const ClientInfo& aClientInfo) {
auto entry = mControlledClients.Lookup(aClientInfo.Id());
if (!entry) {
return;
}
RefPtr<ServiceWorkerRegistrationInfo> reg =
std::move(entry.Data()->mRegistrationInfo);
entry.Remove();
StopControllingRegistration(reg);
}
void ServiceWorkerManager::MaybeStartShutdown() {
MOZ_ASSERT(NS_IsMainThread());
if (mShuttingDown) {
return;
}
mShuttingDown = true;
for (auto& entry : mRegistrationInfos) {
auto& dataPtr = entry.GetData();
for (auto& timerEntry : dataPtr->mUpdateTimers) {
timerEntry.GetData()->Cancel();
}
dataPtr->mUpdateTimers.Clear();
for (auto& queueEntry : dataPtr->mJobQueues) {
queueEntry.GetData()->CancelAll();
}
dataPtr->mJobQueues.Clear();
for (auto& registrationEntry : dataPtr->mInfos) {
registrationEntry.GetData()->ShutdownWorkers();
}
// ServiceWorkerCleanup may try to unregister registrations, so don't clear
// mInfos.
}
for (auto& entry : mControlledClients) {
entry.GetData()->mRegistrationInfo->ShutdownWorkers();
}
for (auto iter = mOrphanedRegistrations.iter(); !iter.done(); iter.next()) {
iter.get()->ShutdownWorkers();
}
if (mShutdownBlocker) {
mShutdownBlocker->StopAcceptingPromises();
}
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->RemoveObserver(this, GetStartShutdownTopic());
if (ServiceWorkersAreCrossProcess()) {
obs->AddObserver(this, kFinishShutdownTopic, false);
return;
}
}
MaybeFinishShutdown();
}
void ServiceWorkerManager::MaybeFinishShutdown() {
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->RemoveObserver(this, kFinishShutdownTopic);
}
if (!mActor) {
return;
}
mActor->ManagerShuttingDown();
RefPtr<TeardownRunnable> runnable = new TeardownRunnable(mActor);
nsresult rv = NS_DispatchToMainThread(runnable);
Unused << NS_WARN_IF(NS_FAILED(rv));
mActor = nullptr;
}
class ServiceWorkerResolveWindowPromiseOnRegisterCallback final
: public ServiceWorkerJob::Callback {
public:
NS_INLINE_DECL_REFCOUNTING(
ServiceWorkerResolveWindowPromiseOnRegisterCallback, override)
virtual void JobFinished(ServiceWorkerJob* aJob,
ErrorResult& aStatus) override {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aJob);
if (aStatus.Failed()) {
mPromiseHolder.Reject(CopyableErrorResult(aStatus), __func__);
return;
}
MOZ_ASSERT(aJob->GetType() == ServiceWorkerJob::Type::Register);
RefPtr<ServiceWorkerRegisterJob> registerJob =
static_cast<ServiceWorkerRegisterJob*>(aJob);
RefPtr<ServiceWorkerRegistrationInfo> reg = registerJob->GetRegistration();
mPromiseHolder.Resolve(reg->Descriptor(), __func__);
}
virtual void JobDiscarded(ErrorResult& aStatus) override {
MOZ_ASSERT(NS_IsMainThread());
mPromiseHolder.Reject(CopyableErrorResult(aStatus), __func__);
}
RefPtr<ServiceWorkerRegistrationPromise> Promise() {
MOZ_ASSERT(NS_IsMainThread());
return mPromiseHolder.Ensure(__func__);
}
private:
~ServiceWorkerResolveWindowPromiseOnRegisterCallback() = default;
MozPromiseHolder<ServiceWorkerRegistrationPromise> mPromiseHolder;
};
namespace {
class PropagateSoftUpdateRunnable final : public Runnable {
public:
PropagateSoftUpdateRunnable(const OriginAttributes& aOriginAttributes,
const nsAString& aScope)
: Runnable("dom::ServiceWorkerManager::PropagateSoftUpdateRunnable"),
mOriginAttributes(aOriginAttributes),
mScope(aScope) {}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (swm) {
swm->PropagateSoftUpdate(mOriginAttributes, mScope);
}
return NS_OK;
}
private:
~PropagateSoftUpdateRunnable() = default;
const OriginAttributes mOriginAttributes;
const nsString mScope;
};
class PromiseResolverCallback final : public ServiceWorkerUpdateFinishCallback {
public:
PromiseResolverCallback(ServiceWorkerUpdateFinishCallback* aCallback,
GenericPromise::Private* aPromise)
: mCallback(aCallback), mPromise(aPromise) {
MOZ_DIAGNOSTIC_ASSERT(mPromise);
}
void UpdateSucceeded(ServiceWorkerRegistrationInfo* aInfo) override {
MOZ_DIAGNOSTIC_ASSERT(mPromise);
if (mCallback) {
mCallback->UpdateSucceeded(aInfo);
}
MaybeResolve();
}
void UpdateFailed(ErrorResult& aStatus) override {
MOZ_DIAGNOSTIC_ASSERT(mPromise);
if (mCallback) {
mCallback->UpdateFailed(aStatus);
}
MaybeResolve();
}
private:
~PromiseResolverCallback() { MaybeResolve(); }
void MaybeResolve() {
if (mPromise) {
mPromise->Resolve(true, __func__);
mPromise = nullptr;
}
}
RefPtr<ServiceWorkerUpdateFinishCallback> mCallback;
RefPtr<GenericPromise::Private> mPromise;
};
// This runnable is used for 2 different tasks:
// - to postpone the SoftUpdate() until the IPC SWM actor is created
// (aInternalMethod == false)
// - to call the 'real' SoftUpdate when the ServiceWorkerUpdaterChild is
// notified by the parent (aInternalMethod == true)
class SoftUpdateRunnable final : public CancelableRunnable {
public:
SoftUpdateRunnable(const OriginAttributes& aOriginAttributes,
const nsACString& aScope, bool aInternalMethod,
GenericPromise::Private* aPromise)
: CancelableRunnable("dom::ServiceWorkerManager::SoftUpdateRunnable"),
mAttrs(aOriginAttributes),
mScope(aScope),
mInternalMethod(aInternalMethod),
mPromise(aPromise) {}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
return NS_ERROR_FAILURE;
}
if (mInternalMethod) {
RefPtr<PromiseResolverCallback> callback =
new PromiseResolverCallback(nullptr, mPromise);
mPromise = nullptr;
swm->SoftUpdateInternal(mAttrs, mScope, callback);
} else {
swm->SoftUpdate(mAttrs, mScope);
}
return NS_OK;
}
nsresult Cancel() override {
mPromise = nullptr;
return NS_OK;
}
private:
~SoftUpdateRunnable() {
if (mPromise) {
mPromise->Resolve(true, __func__);
}
}
const OriginAttributes mAttrs;
const nsCString mScope;
bool mInternalMethod;
RefPtr<GenericPromise::Private> mPromise;
};
// This runnable is used for 2 different tasks:
// - to call the 'real' Update when the ServiceWorkerUpdaterChild is
// notified by the parent (aType == eSuccess)
// - an error must be propagated (aType == eFailure)
class UpdateRunnable final : public CancelableRunnable {
public:
enum Type {
eSuccess,
eFailure,
};
UpdateRunnable(nsIPrincipal* aPrincipal, const nsACString& aScope,
nsCString aNewestWorkerScriptUrl,
ServiceWorkerUpdateFinishCallback* aCallback, Type aType,
GenericPromise::Private* aPromise)
: CancelableRunnable("dom::ServiceWorkerManager::UpdateRunnable"),
mPrincipal(aPrincipal),
mScope(aScope),
mNewestWorkerScriptUrl(std::move(aNewestWorkerScriptUrl)),
mCallback(aCallback),
mType(aType),
mPromise(aPromise) {
MOZ_ASSERT_IF(mType == eSuccess, !mNewestWorkerScriptUrl.IsEmpty());
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(mPromise);
RefPtr<PromiseResolverCallback> callback =
new PromiseResolverCallback(mCallback, mPromise);
mPromise = nullptr;
if (mType == eSuccess) {
swm->UpdateInternal(mPrincipal, mScope, std::move(mNewestWorkerScriptUrl),
callback);
return NS_OK;
}
ErrorResult error(NS_ERROR_DOM_ABORT_ERR);
callback->UpdateFailed(error);
return NS_OK;
}
nsresult Cancel() override {
mPromise = nullptr;
return NS_OK;
}
private:
~UpdateRunnable() {
if (mPromise) {
mPromise->Resolve(true, __func__);
}
}
nsCOMPtr<nsIPrincipal> mPrincipal;
const nsCString mScope;
nsCString mNewestWorkerScriptUrl;
RefPtr<ServiceWorkerUpdateFinishCallback> mCallback;
Type mType;
RefPtr<GenericPromise::Private> mPromise;
};
class ResolvePromiseRunnable final : public CancelableRunnable {
public:
explicit ResolvePromiseRunnable(GenericPromise::Private* aPromise)
: CancelableRunnable("dom::ServiceWorkerManager::ResolvePromiseRunnable"),
mPromise(aPromise) {}
NS_IMETHOD
Run() override {
MaybeResolve();
return NS_OK;
}
nsresult Cancel() override {
mPromise = nullptr;
return NS_OK;
}
private:
~ResolvePromiseRunnable() { MaybeResolve(); }
void MaybeResolve() {
if (mPromise) {
mPromise->Resolve(true, __func__);
mPromise = nullptr;
}
}
RefPtr<GenericPromise::Private> mPromise;
};
} // namespace
NS_IMETHODIMP
ServiceWorkerManager::RegisterForTest(nsIPrincipal* aPrincipal,
const nsAString& aScopeURL,
const nsAString& aScriptURL,
JSContext* aCx,
mozilla::dom::Promise** aPromise) {
nsIGlobalObject* global = xpc::CurrentNativeGlobal(aCx);
if (NS_WARN_IF(!global)) {
return NS_ERROR_FAILURE;
}
ErrorResult erv;
RefPtr<Promise> outer = Promise::Create(global, erv);
if (NS_WARN_IF(erv.Failed())) {
return erv.StealNSResult();
}
if (!StaticPrefs::dom_serviceWorkers_testing_enabled()) {
outer->MaybeRejectWithAbortError(
"registerForTest only allowed when dom.serviceWorkers.testing.enabled "
"is true");
return NS_OK;
}
if (aPrincipal == nullptr) {
outer->MaybeRejectWithAbortError("Missing principal");
return NS_OK;
}
if (aScriptURL.IsEmpty()) {
outer->MaybeRejectWithAbortError("Missing script url");
return NS_OK;
}
if (aScopeURL.IsEmpty()) {
outer->MaybeRejectWithAbortError("Missing scope url");
return NS_OK;
}
// The ClientType isn't really used here, but ClientType::Window
// is the least bad choice since this is happening on the main thread.
Maybe<ClientInfo> clientInfo =
dom::ClientManager::CreateInfo(ClientType::Window, aPrincipal);
if (!clientInfo.isSome()) {
outer->MaybeRejectWithUnknownError("Error creating clientInfo");
return NS_OK;
}
auto scope = NS_ConvertUTF16toUTF8(aScopeURL);
auto scriptURL = NS_ConvertUTF16toUTF8(aScriptURL);
auto regPromise = Register(clientInfo.ref(), scope, scriptURL,
dom::ServiceWorkerUpdateViaCache::Imports);
const RefPtr<ServiceWorkerManager> self(this);
const nsCOMPtr<nsIPrincipal> principal(aPrincipal);
regPromise->Then(
GetMainThreadSerialEventTarget(), __func__,
[self, outer, principal,
scope](const ServiceWorkerRegistrationDescriptor& regDesc) {
RefPtr<ServiceWorkerRegistrationInfo> registration =
self->GetRegistration(principal, NS_ConvertUTF16toUTF8(scope));
if (registration) {
outer->MaybeResolve(registration);
} else {
outer->MaybeRejectWithUnknownError(
"Failed to retrieve ServiceWorkerRegistrationInfo");
}
},
[outer](const mozilla::CopyableErrorResult& err) {
CopyableErrorResult result(err);
outer->MaybeReject(std::move(result));
});
outer.forget(aPromise);
return NS_OK;
}
RefPtr<ServiceWorkerRegistrationPromise> ServiceWorkerManager::Register(
const ClientInfo& aClientInfo, const nsACString& aScopeURL,
const nsACString& aScriptURL, ServiceWorkerUpdateViaCache aUpdateViaCache) {
nsCOMPtr<nsIURI> scopeURI;
nsresult rv = NS_NewURI(getter_AddRefs(scopeURI), aScopeURL);
if (NS_FAILED(rv)) {
// Odd, since it was serialiazed from an nsIURI.
CopyableErrorResult err;
err.ThrowInvalidStateError("Scope URL cannot be parsed");
return ServiceWorkerRegistrationPromise::CreateAndReject(err, __func__);
}
nsCOMPtr<nsIURI> scriptURI;
rv = NS_NewURI(getter_AddRefs(scriptURI), aScriptURL);
if (NS_FAILED(rv)) {
// Odd, since it was serialiazed from an nsIURI.
CopyableErrorResult err;
err.ThrowInvalidStateError("Script URL cannot be parsed");
return ServiceWorkerRegistrationPromise::CreateAndReject(err, __func__);
}
IgnoredErrorResult err;
ServiceWorkerScopeAndScriptAreValid(aClientInfo, scopeURI, scriptURI, err);
if (err.Failed()) {
return ServiceWorkerRegistrationPromise::CreateAndReject(
CopyableErrorResult(std::move(err)), __func__);
}
// If the previous validation step passed then we must have a principal.
auto principalOrErr = aClientInfo.GetPrincipal();
if (NS_WARN_IF(principalOrErr.isErr())) {
return ServiceWorkerRegistrationPromise::CreateAndReject(
CopyableErrorResult(principalOrErr.unwrapErr()), __func__);
}
nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
nsAutoCString scopeKey;
rv = PrincipalToScopeKey(principal, scopeKey);
if (NS_WARN_IF(NS_FAILED(rv))) {
return ServiceWorkerRegistrationPromise::CreateAndReject(
CopyableErrorResult(rv), __func__);
}
RefPtr<ServiceWorkerJobQueue> queue =
GetOrCreateJobQueue(scopeKey, aScopeURL);
RefPtr<ServiceWorkerResolveWindowPromiseOnRegisterCallback> cb =
new ServiceWorkerResolveWindowPromiseOnRegisterCallback();
RefPtr<ServiceWorkerRegisterJob> job = new ServiceWorkerRegisterJob(
principal, aScopeURL, aScriptURL,
static_cast<ServiceWorkerUpdateViaCache>(aUpdateViaCache));
job->AppendResultCallback(cb);
queue->ScheduleJob(job);
MOZ_ASSERT(NS_IsMainThread());
Telemetry::Accumulate(Telemetry::SERVICE_WORKER_REGISTRATIONS, 1);
return cb->Promise();
}
/*
* Implements the async aspects of the getRegistrations algorithm.
*/
class GetRegistrationsRunnable final : public Runnable {
const ClientInfo mClientInfo;
RefPtr<ServiceWorkerRegistrationListPromise::Private> mPromise;
public:
explicit GetRegistrationsRunnable(const ClientInfo& aClientInfo)
: Runnable("dom::ServiceWorkerManager::GetRegistrationsRunnable"),
mClientInfo(aClientInfo),
mPromise(new ServiceWorkerRegistrationListPromise::Private(__func__)) {}
RefPtr<ServiceWorkerRegistrationListPromise> Promise() const {
return mPromise;
}
NS_IMETHOD
Run() override {
auto scopeExit = MakeScopeExit(
[&] { mPromise->Reject(NS_ERROR_DOM_INVALID_STATE_ERR, __func__); });
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
return NS_OK;
}
auto principalOrErr = mClientInfo.GetPrincipal();
if (NS_WARN_IF(principalOrErr.isErr())) {
return NS_OK;
}
nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
nsTArray<ServiceWorkerRegistrationDescriptor> array;
if (NS_WARN_IF(!BasePrincipal::Cast(principal)->IsContentPrincipal())) {
return NS_OK;
}
nsAutoCString scopeKey;
nsresult rv = swm->PrincipalToScopeKey(principal, scopeKey);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
ServiceWorkerManager::RegistrationDataPerPrincipal* data;
if (!swm->mRegistrationInfos.Get(scopeKey, &data)) {
scopeExit.release();
mPromise->Resolve(array, __func__);
return NS_OK;
}
for (uint32_t i = 0; i < data->mScopeContainer.Length(); ++i) {
RefPtr<ServiceWorkerRegistrationInfo> info =
data->mInfos.GetWeak(data->mScopeContainer[i]);
NS_ConvertUTF8toUTF16 scope(data->mScopeContainer[i]);
nsCOMPtr<nsIURI> scopeURI;
nsresult rv = NS_NewURI(getter_AddRefs(scopeURI), scope);
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
// Unfortunately we don't seem to have an obvious window id here; in
// particular ClientInfo does not have one, and neither do service worker
// registrations, as far as I can tell.
rv = principal->CheckMayLoadWithReporting(
scopeURI, false /* allowIfInheritsPrincipal */,
0 /* innerWindowID */);
if (NS_WARN_IF(NS_FAILED(rv))) {
continue;
}
array.AppendElement(info->Descriptor());
}
scopeExit.release();
mPromise->Resolve(array, __func__);
return NS_OK;
}
};
RefPtr<ServiceWorkerRegistrationListPromise>
ServiceWorkerManager::GetRegistrations(const ClientInfo& aClientInfo) const {
RefPtr<GetRegistrationsRunnable> runnable =
new GetRegistrationsRunnable(aClientInfo);
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(runnable));
return runnable->Promise();
;
}
/*
* Implements the async aspects of the getRegistration algorithm.
*/
class GetRegistrationRunnable final : public Runnable {
const ClientInfo mClientInfo;
RefPtr<ServiceWorkerRegistrationPromise::Private> mPromise;
nsCString mURL;
public:
GetRegistrationRunnable(const ClientInfo& aClientInfo, const nsACString& aURL)
: Runnable("dom::ServiceWorkerManager::GetRegistrationRunnable"),
mClientInfo(aClientInfo),
mPromise(new ServiceWorkerRegistrationPromise::Private(__func__)),
mURL(aURL) {}
RefPtr<ServiceWorkerRegistrationPromise> Promise() const { return mPromise; }
NS_IMETHOD
Run() override {
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
mPromise->Reject(NS_ERROR_DOM_INVALID_STATE_ERR, __func__);
return NS_OK;
}
auto principalOrErr = mClientInfo.GetPrincipal();
if (NS_WARN_IF(principalOrErr.isErr())) {
mPromise->Reject(NS_ERROR_DOM_INVALID_STATE_ERR, __func__);
return NS_OK;
}
nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), mURL);
if (NS_WARN_IF(NS_FAILED(rv))) {
mPromise->Reject(rv, __func__);
return NS_OK;
}
// Unfortunately we don't seem to have an obvious window id here; in
// particular ClientInfo does not have one, and neither do service worker
// registrations, as far as I can tell.
rv = principal->CheckMayLoadWithReporting(
uri, false /* allowIfInheritsPrincipal */, 0 /* innerWindowID */);
if (NS_FAILED(rv)) {
mPromise->Reject(NS_ERROR_DOM_SECURITY_ERR, __func__);
return NS_OK;
}
RefPtr<ServiceWorkerRegistrationInfo> registration =
swm->GetServiceWorkerRegistrationInfo(principal, uri);
if (!registration) {
// Reject with NS_OK means "not found".
mPromise->Reject(NS_OK, __func__);
return NS_OK;
}
mPromise->Resolve(registration->Descriptor(), __func__);
return NS_OK;
}
};
RefPtr<ServiceWorkerRegistrationPromise> ServiceWorkerManager::GetRegistration(
const ClientInfo& aClientInfo, const nsACString& aURL) const {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<GetRegistrationRunnable> runnable =
new GetRegistrationRunnable(aClientInfo, aURL);
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(runnable));
return runnable->Promise();
}
NS_IMETHODIMP
ServiceWorkerManager::SendPushEvent(const nsACString& aOriginAttributes,
const nsACString& aScope,
const nsTArray<uint8_t>& aDataBytes,
uint8_t optional_argc) {
if (optional_argc == 1) {
// This does one copy here (while constructing the Maybe) and another when
// we end up copying into the SendPushEventRunnable. We could fix that to
// only do one copy by making things between here and there take
// Maybe<nsTArray<uint8_t>>&&, but then we'd need to copy before we know
// whether we really need to in PushMessageDispatcher::NotifyWorkers. Since
// in practice this only affects JS callers that pass data, and we don't
// have any right now, let's not worry about it.
return SendPushEvent(aOriginAttributes, aScope, EmptyString(),
Some(aDataBytes.Clone()));
}
MOZ_ASSERT(optional_argc == 0);
return SendPushEvent(aOriginAttributes, aScope, EmptyString(), Nothing());
}
nsresult ServiceWorkerManager::SendPushEvent(
const nsACString& aOriginAttributes, const nsACString& aScope,
const nsAString& aMessageId, const Maybe<nsTArray<uint8_t>>& aData) {
OriginAttributes attrs;
if (!attrs.PopulateFromSuffix(aOriginAttributes)) {
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsIPrincipal> principal;
MOZ_TRY_VAR(principal, ScopeToPrincipal(aScope, attrs));
// The registration handling a push notification must have an exact scope
// match. This will try to find an exact match, unlike how fetch may find the
// registration with the longest scope that's a prefix of the fetched URL.
RefPtr<ServiceWorkerRegistrationInfo> registration =
GetRegistration(principal, aScope);
if (NS_WARN_IF(!registration)) {
return NS_ERROR_FAILURE;
}
MOZ_DIAGNOSTIC_ASSERT(registration->Scope().Equals(aScope));
ServiceWorkerInfo* serviceWorker = registration->GetActive();
if (NS_WARN_IF(!serviceWorker)) {
return NS_ERROR_FAILURE;
}
return serviceWorker->WorkerPrivate()->SendPushEvent(aMessageId, aData,
registration);
}
NS_IMETHODIMP
ServiceWorkerManager::SendPushSubscriptionChangeEvent(
const nsACString& aOriginAttributes, const nsACString& aScope) {
OriginAttributes attrs;
if (!attrs.PopulateFromSuffix(aOriginAttributes)) {
return NS_ERROR_INVALID_ARG;
}
ServiceWorkerInfo* info = GetActiveWorkerInfoForScope(attrs, aScope);
if (!info) {
return NS_ERROR_FAILURE;
}
return info->WorkerPrivate()->SendPushSubscriptionChangeEvent();
}
nsresult ServiceWorkerManager::SendNotificationEvent(
const nsAString& aEventName, const nsACString& aOriginSuffix,
const nsACString& aScope, 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) {
OriginAttributes attrs;
if (!attrs.PopulateFromSuffix(aOriginSuffix)) {
return NS_ERROR_INVALID_ARG;
}
ServiceWorkerInfo* info = GetActiveWorkerInfoForScope(attrs, aScope);
if (!info) {
return NS_ERROR_FAILURE;
}
ServiceWorkerPrivate* workerPrivate = info->WorkerPrivate();
return workerPrivate->SendNotificationEvent(
aEventName, aID, aTitle, aDir, aLang, aBody, aTag, aIcon, aData,
aBehavior, NS_ConvertUTF8toUTF16(aScope));
}
NS_IMETHODIMP
ServiceWorkerManager::SendNotificationClickEvent(
const nsACString& aOriginSuffix, const nsACString& aScope,
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) {
return SendNotificationEvent(nsLiteralString(NOTIFICATION_CLICK_EVENT_NAME),
aOriginSuffix, aScope, aID, aTitle, aDir, aLang,
aBody, aTag, aIcon, aData, aBehavior);
}
NS_IMETHODIMP
ServiceWorkerManager::SendNotificationCloseEvent(
const nsACString& aOriginSuffix, const nsACString& aScope,
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) {
return SendNotificationEvent(nsLiteralString(NOTIFICATION_CLOSE_EVENT_NAME),
aOriginSuffix, aScope, aID, aTitle, aDir, aLang,
aBody, aTag, aIcon, aData, aBehavior);
}
RefPtr<ServiceWorkerRegistrationPromise> ServiceWorkerManager::WhenReady(
const ClientInfo& aClientInfo) {
AssertIsOnMainThread();
for (auto& prd : mPendingReadyList) {
if (prd->mClientHandle->Info().Id() == aClientInfo.Id() &&
prd->mClientHandle->Info().PrincipalInfo() ==
aClientInfo.PrincipalInfo()) {
return prd->mPromise;
}
}
RefPtr<ServiceWorkerRegistrationInfo> reg =
GetServiceWorkerRegistrationInfo(aClientInfo);
if (reg && reg->GetActive()) {
return ServiceWorkerRegistrationPromise::CreateAndResolve(reg->Descriptor(),
__func__);
}
nsCOMPtr<nsISerialEventTarget> target = GetMainThreadSerialEventTarget();
RefPtr<ClientHandle> handle =
ClientManager::CreateHandle(aClientInfo, target);
mPendingReadyList.AppendElement(MakeUnique<PendingReadyData>(handle));
RefPtr<ServiceWorkerManager> self(this);
handle->OnDetach()->Then(target, __func__,
[self = std::move(self), aClientInfo] {
self->RemovePendingReadyPromise(aClientInfo);
});
return mPendingReadyList.LastElement()->mPromise;
}
void ServiceWorkerManager::CheckPendingReadyPromises() {
nsTArray<UniquePtr<PendingReadyData>> pendingReadyList;
mPendingReadyList.SwapElements(pendingReadyList);
for (uint32_t i = 0; i < pendingReadyList.Length(); ++i) {
UniquePtr<PendingReadyData> prd(std::move(pendingReadyList[i]));
RefPtr<ServiceWorkerRegistrationInfo> reg =
GetServiceWorkerRegistrationInfo(prd->mClientHandle->Info());
if (reg && reg->GetActive()) {
prd->mPromise->Resolve(reg->Descriptor(), __func__);
} else {
mPendingReadyList.AppendElement(std::move(prd));
}
}
}
void ServiceWorkerManager::RemovePendingReadyPromise(
const ClientInfo& aClientInfo) {
nsTArray<UniquePtr<PendingReadyData>> pendingReadyList;
mPendingReadyList.SwapElements(pendingReadyList);
for (uint32_t i = 0; i < pendingReadyList.Length(); ++i) {
UniquePtr<PendingReadyData> prd(std::move(pendingReadyList[i]));
if (prd->mClientHandle->Info().Id() == aClientInfo.Id() &&
prd->mClientHandle->Info().PrincipalInfo() ==
aClientInfo.PrincipalInfo()) {
prd->mPromise->Reject(NS_ERROR_DOM_ABORT_ERR, __func__);
} else {
mPendingReadyList.AppendElement(std::move(prd));
}
}
}
void ServiceWorkerManager::NoteInheritedController(
const ClientInfo& aClientInfo, const ServiceWorkerDescriptor& aController) {
MOZ_ASSERT(NS_IsMainThread());
auto principalOrErr = PrincipalInfoToPrincipal(aController.PrincipalInfo());
if (NS_WARN_IF(principalOrErr.isErr())) {
return;
}
nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
nsCOMPtr<nsIURI> scope;
nsresult rv = NS_NewURI(getter_AddRefs(scope), aController.Scope());
NS_ENSURE_SUCCESS_VOID(rv);
RefPtr<ServiceWorkerRegistrationInfo> registration =
GetServiceWorkerRegistrationInfo(principal, scope);
NS_ENSURE_TRUE_VOID(registration);
NS_ENSURE_TRUE_VOID(registration->GetActive());
StartControllingClient(aClientInfo, registration,
false /* aControlClientHandle */);
}
ServiceWorkerInfo* ServiceWorkerManager::GetActiveWorkerInfoForScope(
const OriginAttributes& aOriginAttributes, const nsACString& aScope) {
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIURI> scopeURI;
nsresult rv = NS_NewURI(getter_AddRefs(scopeURI), aScope);
if (NS_FAILED(rv)) {
return nullptr;
}
auto result = ScopeToPrincipal(scopeURI, aOriginAttributes);
if (NS_WARN_IF(result.isErr())) {
return nullptr;
}
auto principal = result.unwrap();
RefPtr<ServiceWorkerRegistrationInfo> registration =
GetServiceWorkerRegistrationInfo(principal, scopeURI);
if (!registration) {
return nullptr;
}
return registration->GetActive();
}
namespace {
class UnregisterJobCallback final : public ServiceWorkerJob::Callback {
nsCOMPtr<nsIServiceWorkerUnregisterCallback> mCallback;
~UnregisterJobCallback() { MOZ_ASSERT(!mCallback); }
public:
explicit UnregisterJobCallback(nsIServiceWorkerUnregisterCallback* aCallback)
: mCallback(aCallback) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mCallback);
}
void JobFinished(ServiceWorkerJob* aJob, ErrorResult& aStatus) override {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aJob);
MOZ_ASSERT(mCallback);
auto scopeExit = MakeScopeExit([&]() { mCallback = nullptr; });
if (aStatus.Failed()) {
mCallback->UnregisterFailed();
return;
}
MOZ_ASSERT(aJob->GetType() == ServiceWorkerJob::Type::Unregister);
RefPtr<ServiceWorkerUnregisterJob> unregisterJob =
static_cast<ServiceWorkerUnregisterJob*>(aJob);
mCallback->UnregisterSucceeded(unregisterJob->GetResult());
}
void JobDiscarded(ErrorResult&) override {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mCallback);
mCallback->UnregisterFailed();
mCallback = nullptr;
}
NS_INLINE_DECL_REFCOUNTING(UnregisterJobCallback, override)
};
} // anonymous namespace
NS_IMETHODIMP
ServiceWorkerManager::Unregister(nsIPrincipal* aPrincipal,
nsIServiceWorkerUnregisterCallback* aCallback,
const nsAString& aScope) {
MOZ_ASSERT(NS_IsMainThread());
if (!aPrincipal) {
return NS_ERROR_FAILURE;
}
nsresult rv;
// This is not accessible by content, and callers should always ensure scope is
// a correct URI, so this is wrapped in DEBUG
#ifdef DEBUG
nsCOMPtr<nsIURI> scopeURI;
rv = NS_NewURI(getter_AddRefs(scopeURI), aScope);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NS_ERROR_DOM_SECURITY_ERR;
}
#endif
nsAutoCString scopeKey;
rv = PrincipalToScopeKey(aPrincipal, scopeKey);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
NS_ConvertUTF16toUTF8 scope(aScope);
RefPtr<ServiceWorkerJobQueue> queue = GetOrCreateJobQueue(scopeKey, scope);
RefPtr<ServiceWorkerUnregisterJob> job = new ServiceWorkerUnregisterJob(
aPrincipal, scope, true /* send to parent */);
if (aCallback) {
RefPtr<UnregisterJobCallback> cb = new UnregisterJobCallback(aCallback);
job->AppendResultCallback(cb);
}
queue->ScheduleJob(job);
return NS_OK;
}
nsresult ServiceWorkerManager::NotifyUnregister(nsIPrincipal* aPrincipal,
const nsAString& aScope) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aPrincipal);
nsresult rv;
// This is not accessible by content, and callers should always ensure scope is
// a correct URI, so this is wrapped in DEBUG
#ifdef DEBUG
nsCOMPtr<nsIURI> scopeURI;
rv = NS_NewURI(getter_AddRefs(scopeURI), aScope);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
#endif
nsAutoCString scopeKey;
rv = PrincipalToScopeKey(aPrincipal, scopeKey);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
NS_ConvertUTF16toUTF8 scope(aScope);
RefPtr<ServiceWorkerJobQueue> queue = GetOrCreateJobQueue(scopeKey, scope);
RefPtr<ServiceWorkerUnregisterJob> job = new ServiceWorkerUnregisterJob(
aPrincipal, scope, false /* send to parent */);
queue->ScheduleJob(job);
return NS_OK;
}
void ServiceWorkerManager::WorkerIsIdle(ServiceWorkerInfo* aWorker) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(aWorker);
RefPtr<ServiceWorkerRegistrationInfo> reg =
GetRegistration(aWorker->Principal(), aWorker->Scope());
if (!reg) {
return;
}
if (reg->GetActive() != aWorker) {
return;
}
reg->TryToActivateAsync();
}
already_AddRefed<ServiceWorkerJobQueue>
ServiceWorkerManager::GetOrCreateJobQueue(const nsACString& aKey,
const nsACString& aScope) {
MOZ_ASSERT(!aKey.IsEmpty());
ServiceWorkerManager::RegistrationDataPerPrincipal* data;
// XXX we could use LookupForAdd here to avoid a hashtable lookup, except that
// leads to a false positive assertion, see bug 1370674 comment 7.
if (!mRegistrationInfos.Get(aKey, &data)) {
data = new RegistrationDataPerPrincipal();
mRegistrationInfos.Put(aKey, data);
}
RefPtr<ServiceWorkerJobQueue> queue =
data->mJobQueues.LookupForAdd(aScope).OrInsert(
[]() { return new ServiceWorkerJobQueue(); });
return queue.forget();
}
/* static */
already_AddRefed<ServiceWorkerManager> ServiceWorkerManager::GetInstance() {
// Note: We don't simply check gInstance for null-ness here, since otherwise
// this can resurrect the ServiceWorkerManager pretty late during shutdown.
static bool firstTime = true;
if (firstTime) {
RefPtr<ServiceWorkerRegistrar> swr;
// Don't create the ServiceWorkerManager until the ServiceWorkerRegistrar is
// initialized.
if (XRE_IsParentProcess()) {
swr = ServiceWorkerRegistrar::Get();
if (!swr) {
return nullptr;
}
}
firstTime = false;
MOZ_ASSERT(NS_IsMainThread());
gInstance = new ServiceWorkerManager();
gInstance->Init(swr);
ClearOnShutdown(&gInstance);
}
RefPtr<ServiceWorkerManager> copy = gInstance.get();
return copy.forget();
}
void ServiceWorkerManager::FinishFetch(
ServiceWorkerRegistrationInfo* aRegistration) {}
void ServiceWorkerManager::ReportToAllClients(
const nsCString& aScope, const nsString& aMessage,
const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags) {
ConsoleUtils::ReportForServiceWorkerScope(
NS_ConvertUTF8toUTF16(aScope), aMessage, aFilename, aLineNumber,
aColumnNumber, ConsoleUtils::eError);
}
/* static */
void ServiceWorkerManager::LocalizeAndReportToAllClients(
const nsCString& aScope, const char* aStringKey,
const nsTArray<nsString>& aParamArray, uint32_t aFlags,
const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber) {
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
return;
}
nsresult rv;
nsAutoString message;
rv = nsContentUtils::FormatLocalizedString(nsContentUtils::eDOM_PROPERTIES,
aStringKey, aParamArray, message);
if (NS_SUCCEEDED(rv)) {
swm->ReportToAllClients(aScope, message, aFilename, aLine, aLineNumber,
aColumnNumber, aFlags);
} else {
NS_WARNING("Failed to format and therefore report localized error.");
}
}
void ServiceWorkerManager::HandleError(
JSContext* aCx, nsIPrincipal* aPrincipal, const nsCString& aScope,
const nsString& aWorkerURL, const nsString& aMessage,
const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags, JSExnType aExnType) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aPrincipal);
nsAutoCString scopeKey;
nsresult rv = PrincipalToScopeKey(aPrincipal, scopeKey);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
ServiceWorkerManager::RegistrationDataPerPrincipal* data;
if (NS_WARN_IF(!mRegistrationInfos.Get(scopeKey, &data))) {
return;
}
// Always report any uncaught exceptions or errors to the console of
// each client.
ReportToAllClients(aScope, aMessage, aFilename, aLine, aLineNumber,
aColumnNumber, aFlags);
}
void ServiceWorkerManager::LoadRegistration(
const ServiceWorkerRegistrationData& aRegistration) {
MOZ_ASSERT(NS_IsMainThread());
auto principalOrErr = PrincipalInfoToPrincipal(aRegistration.principal());
if (NS_WARN_IF(principalOrErr.isErr())) {
return;
}
nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
RefPtr<ServiceWorkerRegistrationInfo> registration =
GetRegistration(principal, aRegistration.scope());
if (!registration) {
registration =
CreateNewRegistration(aRegistration.scope(), principal,
static_cast<ServiceWorkerUpdateViaCache>(
aRegistration.updateViaCache()));
} else {
// If active worker script matches our expectations for a "current worker",
// then we are done. Since scripts with the same URL might have different
// contents such as updated scripts or scripts with different LoadFlags, we
// use the CacheName to judje whether the two scripts are identical, where
// the CacheName is an UUID generated when a new script is found.
if (registration->GetActive() &&
registration->GetActive()->CacheName() == aRegistration.cacheName()) {
// No needs for updates.
return;
}
}
registration->SetLastUpdateTime(aRegistration.lastUpdateTime());
nsLoadFlags importsLoadFlags = nsIChannel::LOAD_BYPASS_SERVICE_WORKER;
if (aRegistration.updateViaCache() !=
static_cast<uint16_t>(ServiceWorkerUpdateViaCache::None)) {
importsLoadFlags |= nsIRequest::VALIDATE_ALWAYS;
}
const nsCString& currentWorkerURL = aRegistration.currentWorkerURL();
if (!currentWorkerURL.IsEmpty()) {
registration->SetActive(new ServiceWorkerInfo(
registration->Principal(), registration->Scope(), registration->Id(),
registration->Version(), currentWorkerURL, aRegistration.cacheName(),
importsLoadFlags));
registration->GetActive()->SetHandlesFetch(
aRegistration.currentWorkerHandlesFetch());
registration->GetActive()->SetInstalledTime(
aRegistration.currentWorkerInstalledTime());
registration->GetActive()->SetActivatedTime(
aRegistration.currentWorkerActivatedTime());
}
}
void ServiceWorkerManager::LoadRegistrations(
const nsTArray<ServiceWorkerRegistrationData>& aRegistrations) {
MOZ_ASSERT(NS_IsMainThread());
for (uint32_t i = 0, len = aRegistrations.Length(); i < len; ++i) {
LoadRegistration(aRegistrations[i]);
}
}
void ServiceWorkerManager::StoreRegistration(
nsIPrincipal* aPrincipal, ServiceWorkerRegistrationInfo* aRegistration) {
MOZ_ASSERT(aPrincipal);
MOZ_ASSERT(aRegistration);
if (mShuttingDown) {
return;
}
ServiceWorkerRegistrationData data;
nsresult rv = PopulateRegistrationData(aPrincipal, aRegistration, data);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
PrincipalInfo principalInfo;
if (NS_WARN_IF(
NS_FAILED(PrincipalToPrincipalInfo(aPrincipal, &principalInfo)))) {
return;
}
mActor->SendRegister(data);
}
already_AddRefed<ServiceWorkerRegistrationInfo>
ServiceWorkerManager::GetServiceWorkerRegistrationInfo(
const ClientInfo& aClientInfo) const {
auto principalOrErr = aClientInfo.GetPrincipal();
if (NS_WARN_IF(principalOrErr.isErr())) {
return nullptr;
}
nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aClientInfo.URL());
NS_ENSURE_SUCCESS(rv, nullptr);
return GetServiceWorkerRegistrationInfo(principal, uri);
}
already_AddRefed<ServiceWorkerRegistrationInfo>
ServiceWorkerManager::GetServiceWorkerRegistrationInfo(nsIPrincipal* aPrincipal,
nsIURI* aURI) const {
MOZ_ASSERT(aPrincipal);
MOZ_ASSERT(aURI);
nsAutoCString scopeKey;