Files
palemoon27/dom/workers/ServiceWorkerEvents.cpp
T
roytam1 2b0b985a18 import changes from `dev' branch of rmottola/Arctic-Fox:
- pointer style (4cb5b536b)
- Bug 1186696. Event handlers on JS-implemented webidl interfaces should have the same behavior as other event handlers: accept all values, convert non-objects to null. r=smaug (f61a308fb)
- Bug 983301 part 1. Handle JS-to-native conversion for Promise values via calling Promise::Resolve on whatever value was passed in (except if the type is nullable and the passed-in value is null or undefined). r=peterv (4aaf04c66)
- Bug 983301 part 2. Change Promise to not be distinguishable from any other type. r=peterv (0f463a834)
- Bug 1157848 - Fix leak in OwningNonNull constructor from already_AddRefed; r=bz (a2a0aaa7a)
- Bug 983301 Add a test for FetchEvent.respondWith(5). r=bz (5de2ea7d5)
- Bug 1166932 - Part 1: Copy the editor observers array before iterating over it; r=roc (db74b264d)
- Bug 1166932 - Part 2: Make sure that nsTextInputListener doesn't try to perform edit actions if it has been disconnected from the editor object; r=roc (7143bc782)
- Bug 1190823 - Move OwningNonNull.h to xpcom/base/; r=froydnj (77c373751)
- Bug 1163044 - Forward NS_MOUSE_ENTER_WIDGET into content process. r=smaug (46fcb7720)
- Bug 1182358 - RequestSyncService.jsm should use AlarmService instead nsITimer, r=nsm (d0eb0bcd4)
- Bug 1142609 - Fix PEP 8 E111/E113 warnings in dom/bindings's Python code. r=peterv (56bc4b865)
- Bug 1142609 - Fix PEP 8 E121 warnings in dom/bindings's Python code. r=peterv (93f8021f6)
- Bug 1142609 - Fix flake8's E122 warnings in dom/bindings's Python code. r=peterv (32f4cb3a2)
- Bug 1142609 - Fix PEP 8 E126 warnings in dom/bindings's Python code. r=peterv (fd7710f34)
- Bug 1142609 - Fix PEP 8 E124 warnings in dom/bindings's Python code. r=peterv (20d26ce01)
- Bug 1142609 - Fix PEP 8 E125 warnings in dom/bindings's Python code. r=peterv (817ae2eb6)
- Bug 1142609 - Fix PEP 8 E127 warnings in dom/bindings's Python code. r=peterv (031b0026f)
- Bug 1142609 - Fix PEP 8 E128 warnings in dom/bindings's Python code. r=peterv (ec4ab550e)
- Bug 1142609 - Fix PEP 8 E2xx warnings in dom/bindings's Python code. r=peterv (0a65500d3)
- Bug 1157588. Produce a better error message when someone tries to pass a mixin as an argument. r=peterv (33d91a9b0)
- Bug 1142609 - Fix PEP 8 E3xx warnings in dom/bindings's Python code. r=peterv (0cd9b0613)
- Bug 1176236. Make typed array arguments work for constructors of JS-implemented interfaces. r=peterv (31e3d3c82)
- Bug 1162956 part 1. Move forwardDeclareForType to be a method on ForwardDeclarationBuilder. r=peterv (8f5f3ff49)
- Bug 1162956 part 2. Forward-declare things as needed in example codegen. Also, use js/TypeDecls.h for the JSContext declaration and include BindingDeclarations.h so we get things like Optional (which are a pain to forward-declare). r=peterv (9192d061b)
- Bug 1166443. Example codegen should output the right signature for Wrap() when the object is not wrappercached. r=peterv (12ca80503)
- Bug 1177869. Fix example codegen to output the correct return type for WrapObject in the non-wrappercached case. r=peterv (0c44da02c)
- Bug 1025395. Output a #error instead of a nonexistent macro for the CC bits of example codegen, to make it clearer to people using it what they should do with CC. r=peterv (75dce91d4)
- Bug 1173913. Indicate what webidl generated files were generated from, if they were generated for a particular webidl file. r=peterv (aaa86dbe8)
- Bug 1165182 - Stop LE scans when Bluetooth adapter is disconnected from its owner. r=joliu (6a3dbc1ae)
- Bug 1176898 - Remove redundant DisconnectFromOwner of BluetoothDiscoveryHandle. r=btian (7ddae05ad)
- Bug 1156716: Build GATT HAL helpers in Bluetooth v1, r=joliu (0572f1af1)
- Bug 1163499 - Part 1: Revise BluetoothGattInterface and result handler for daemon support. r=tzimmermann (e40f7703f)
- Bug 1163499 - Part 2: Add helpers for Bluetooth daemon GATT client support. r=tzimmermann (9c52b9b0b)
- Bug 1163499 - Part 3: Add GATT module for Bluetooth daemon. r=tzimmermann (730394aac)
- Bug 1163499 - Part 4: Add GATT and GATT client interfaces for Bluetooth daemon. r=tzimmermann (7aefc1c20)
- Bug 1163499 - Part 5: Support GATT profile when using Bluetooth daemon. r=tzimmermann (4e71b4901)
- Bug 1148506: Remove unused variable 'bool result' from code generated by getDeleterBody(), in Codegen.py. r=jorendorff (aa31f486d)
- Bug 1170971 - Part 1: Fix BluetoothGattReadParam unpacking in daemon backend. r=tzimmermann (78e8facce)
- Bug 1142609 - Fix PEP 8 E5xx warnings in dom/bindings's Python code. r=peterv (08f5edc45)
- Bug 1142609 - Fix PEP 8 E7xx warnings in dom/bindings's Python code. r=peterv (7fc970bff)
- Bug 1170971 - Part 2: Fix BluetoothGattAdvData unpacking in daemon backend. r=tzimmermann (4285509b2)
- Bug 603201 - Enable primitive receivers in [[Set]]. r=jorendorff (726d46b63)
- Bug 1174717 - Passing fallible when calling AppendElement method for Sequence types in bluetooth2. r=shuang (557d92545)
- pointer style (8f7275cf4)
- Bug 1192297 - Rephrase Proxy static methods to make it clearer that the handler->hasPrototype() case is the weird case. r=Waldo. (2e68353c3)
- Bug 1105045 - Outerize the receiver passed to proxy hooks. r=efaust. (c00a1db2f)
- Bug 603201 - Change GetProperty receiver argument to Value in JS. r=efaust (f5a87f31b)
- Bug 603201 - Change GetProperty receiver argument to Value in the browser. r=smaug (0b871d846)
- Bug 1175173 - Don't box primitive this values in {Object, Array}.prototype.toLocaleString. r=till (11a66b2b6)
- Bug 1179141 - Remove macro |BT_API2_LOGR|, r=joliu (792fbcde8)
- Bug 1161991: Gatt server neutral-backend interface; r=jocelyn (f093551c3)
2021-11-11 10:04:26 +08:00

467 lines
12 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 "ServiceWorkerEvents.h"
#include "ServiceWorkerClient.h"
#include "nsIHttpChannelInternal.h"
#include "nsINetworkInterceptController.h"
#include "nsIOutputStream.h"
#include "nsContentUtils.h"
#include "nsComponentManagerUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsNetCID.h"
#include "nsSerializationHelper.h"
#include "nsQueryObject.h"
#include "mozilla/Preferences.h"
#include "mozilla/dom/FetchEventBinding.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/Request.h"
#include "mozilla/dom/Response.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/workers/bindings/ServiceWorker.h"
#include "WorkerPrivate.h"
using namespace mozilla::dom;
BEGIN_WORKERS_NAMESPACE
FetchEvent::FetchEvent(EventTarget* aOwner)
: Event(aOwner, nullptr, nullptr)
, mIsReload(false)
, mWaitToRespond(false)
{
}
FetchEvent::~FetchEvent()
{
}
void
FetchEvent::PostInit(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
nsMainThreadPtrHandle<ServiceWorker>& aServiceWorker,
nsAutoPtr<ServiceWorkerClientInfo>& aClientInfo)
{
mChannel = aChannel;
mServiceWorker = aServiceWorker;
mClientInfo = aClientInfo;
}
/*static*/ already_AddRefed<FetchEvent>
FetchEvent::Constructor(const GlobalObject& aGlobal,
const nsAString& aType,
const FetchEventInit& aOptions,
ErrorResult& aRv)
{
nsRefPtr<EventTarget> owner = do_QueryObject(aGlobal.GetAsSupports());
MOZ_ASSERT(owner);
nsRefPtr<FetchEvent> e = new FetchEvent(owner);
bool trusted = e->Init(owner);
e->InitEvent(aType, aOptions.mBubbles, aOptions.mCancelable);
e->SetTrusted(trusted);
e->mRequest = aOptions.mRequest.WasPassed() ?
&aOptions.mRequest.Value() : nullptr;
e->mIsReload = aOptions.mIsReload.WasPassed() ?
aOptions.mIsReload.Value() : false;
e->mClient = aOptions.mClient.WasPassed() ?
&aOptions.mClient.Value() : nullptr;
return e.forget();
}
namespace {
class CancelChannelRunnable final : public nsRunnable
{
nsMainThreadPtrHandle<nsIInterceptedChannel> mChannel;
const nsresult mStatus;
public:
CancelChannelRunnable(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
nsresult aStatus)
: mChannel(aChannel)
, mStatus(aStatus)
{
}
NS_IMETHOD Run()
{
MOZ_ASSERT(NS_IsMainThread());
nsresult rv = mChannel->Cancel(mStatus);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
};
class FinishResponse final : public nsRunnable
{
nsMainThreadPtrHandle<nsIInterceptedChannel> mChannel;
nsRefPtr<InternalResponse> mInternalResponse;
ChannelInfo mWorkerChannelInfo;
public:
FinishResponse(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
InternalResponse* aInternalResponse,
const ChannelInfo& aWorkerChannelInfo)
: mChannel(aChannel)
, mInternalResponse(aInternalResponse)
, mWorkerChannelInfo(aWorkerChannelInfo)
{
}
NS_IMETHOD
Run()
{
AssertIsOnMainThread();
ChannelInfo channelInfo;
if (mInternalResponse->GetChannelInfo().IsInitialized()) {
channelInfo = mInternalResponse->GetChannelInfo();
} else {
// We are dealing with a synthesized response here, so fall back to the
// channel info for the worker script.
channelInfo = mWorkerChannelInfo;
}
nsresult rv = mChannel->SetChannelInfo(&channelInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mChannel->SynthesizeStatus(mInternalResponse->GetStatus(), mInternalResponse->GetStatusText());
nsAutoTArray<InternalHeaders::Entry, 5> entries;
mInternalResponse->UnfilteredHeaders()->GetEntries(entries);
for (uint32_t i = 0; i < entries.Length(); ++i) {
mChannel->SynthesizeHeader(entries[i].mName, entries[i].mValue);
}
rv = mChannel->FinishSynthesizedResponse();
NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Failed to finish synthesized response");
return rv;
}
};
class RespondWithHandler final : public PromiseNativeHandler
{
nsMainThreadPtrHandle<nsIInterceptedChannel> mInterceptedChannel;
nsMainThreadPtrHandle<ServiceWorker> mServiceWorker;
RequestMode mRequestMode;
bool mIsClientRequest;
public:
NS_DECL_ISUPPORTS
RespondWithHandler(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
nsMainThreadPtrHandle<ServiceWorker>& aServiceWorker,
RequestMode aRequestMode, bool aIsClientRequest)
: mInterceptedChannel(aChannel)
, mServiceWorker(aServiceWorker)
, mRequestMode(aRequestMode)
, mIsClientRequest(aIsClientRequest)
{
}
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
void CancelRequest(nsresult aStatus);
private:
~RespondWithHandler() {}
};
struct RespondWithClosure
{
nsMainThreadPtrHandle<nsIInterceptedChannel> mInterceptedChannel;
nsRefPtr<InternalResponse> mInternalResponse;
ChannelInfo mWorkerChannelInfo;
RespondWithClosure(nsMainThreadPtrHandle<nsIInterceptedChannel>& aChannel,
InternalResponse* aInternalResponse,
const ChannelInfo& aWorkerChannelInfo)
: mInterceptedChannel(aChannel)
, mInternalResponse(aInternalResponse)
, mWorkerChannelInfo(aWorkerChannelInfo)
{
}
};
void RespondWithCopyComplete(void* aClosure, nsresult aStatus)
{
nsAutoPtr<RespondWithClosure> data(static_cast<RespondWithClosure*>(aClosure));
nsCOMPtr<nsIRunnable> event;
if (NS_SUCCEEDED(aStatus)) {
event = new FinishResponse(data->mInterceptedChannel,
data->mInternalResponse,
data->mWorkerChannelInfo);
} else {
event = new CancelChannelRunnable(data->mInterceptedChannel,
NS_ERROR_INTERCEPTION_FAILED);
}
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(NS_DispatchToMainThread(event)));
}
class MOZ_STACK_CLASS AutoCancel
{
nsRefPtr<RespondWithHandler> mOwner;
nsresult mStatus;
public:
explicit AutoCancel(RespondWithHandler* aOwner)
: mOwner(aOwner)
, mStatus(NS_ERROR_INTERCEPTION_FAILED)
{
}
~AutoCancel()
{
if (mOwner) {
mOwner->CancelRequest(mStatus);
}
}
void SetCancelStatus(nsresult aStatus)
{
MOZ_ASSERT(NS_FAILED(aStatus));
mStatus = aStatus;
}
void Reset()
{
mOwner = nullptr;
}
};
NS_IMPL_ISUPPORTS0(RespondWithHandler)
void
RespondWithHandler::ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue)
{
AutoCancel autoCancel(this);
if (!aValue.isObject()) {
return;
}
nsRefPtr<Response> response;
nsresult rv = UNWRAP_OBJECT(Response, &aValue.toObject(), response);
if (NS_FAILED(rv)) {
return;
}
WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(worker);
worker->AssertIsOnWorkerThread();
// Allow opaque response interception to be disabled until we can ensure the
// security implications are not a complete disaster.
if (response->Type() == ResponseType::Opaque &&
!worker->OpaqueInterceptionEnabled()) {
autoCancel.SetCancelStatus(NS_ERROR_OPAQUE_INTERCEPTION_DISABLED);
return;
}
// Section 4.2, step 2.2:
// If one of the following conditions is true, return a network error:
// * response's type is "error".
// * request's mode is not "no-cors" and response's type is "opaque".
// * request is a client request and response's type is neither "basic"
// nor "default".
if (response->Type() == ResponseType::Error) {
autoCancel.SetCancelStatus(NS_ERROR_INTERCEPTED_ERROR_RESPONSE);
return;
}
if (response->Type() == ResponseType::Opaque && mRequestMode != RequestMode::No_cors) {
autoCancel.SetCancelStatus(NS_ERROR_BAD_OPAQUE_INTERCEPTION_REQUEST_MODE);
return;
}
if (mIsClientRequest && response->Type() != ResponseType::Basic &&
response->Type() != ResponseType::Default) {
autoCancel.SetCancelStatus(NS_ERROR_CLIENT_REQUEST_OPAQUE_INTERCEPTION);
return;
}
if (NS_WARN_IF(response->BodyUsed())) {
autoCancel.SetCancelStatus(NS_ERROR_INTERCEPTED_USED_RESPONSE);
return;
}
nsRefPtr<InternalResponse> ir = response->GetInternalResponse();
if (NS_WARN_IF(!ir)) {
return;
}
nsAutoPtr<RespondWithClosure> closure(
new RespondWithClosure(mInterceptedChannel, ir, worker->GetChannelInfo()));
nsCOMPtr<nsIInputStream> body;
ir->GetInternalBody(getter_AddRefs(body));
// Errors and redirects may not have a body.
if (body) {
response->SetBodyUsed();
nsCOMPtr<nsIOutputStream> responseBody;
rv = mInterceptedChannel->GetResponseBody(getter_AddRefs(responseBody));
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsCOMPtr<nsIEventTarget> stsThread = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
if (NS_WARN_IF(!stsThread)) {
return;
}
// XXXnsm, Fix for Bug 1141332 means that if we decide to make this
// streaming at some point, we'll need a different solution to that bug.
rv = NS_AsyncCopy(body, responseBody, stsThread, NS_ASYNCCOPY_VIA_READSEGMENTS, 4096,
RespondWithCopyComplete, closure.forget());
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
} else {
RespondWithCopyComplete(closure.forget(), NS_OK);
}
MOZ_ASSERT(!closure);
autoCancel.Reset();
}
void
RespondWithHandler::RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue)
{
CancelRequest(NS_ERROR_INTERCEPTION_FAILED);
}
void
RespondWithHandler::CancelRequest(nsresult aStatus)
{
nsCOMPtr<nsIRunnable> runnable =
new CancelChannelRunnable(mInterceptedChannel, aStatus);
NS_DispatchToMainThread(runnable);
}
} // namespace
void
FetchEvent::RespondWith(Promise& aArg, ErrorResult& aRv)
{
if (mWaitToRespond) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
nsRefPtr<InternalRequest> ir = mRequest->GetInternalRequest();
mWaitToRespond = true;
nsRefPtr<RespondWithHandler> handler =
new RespondWithHandler(mChannel, mServiceWorker, mRequest->Mode(),
ir->IsClientRequest());
aArg.AppendNativeHandler(handler);
}
already_AddRefed<ServiceWorkerClient>
FetchEvent::GetClient()
{
if (!mClient) {
if (!mClientInfo) {
return nullptr;
}
mClient = new ServiceWorkerClient(GetParentObject(), *mClientInfo);
}
nsRefPtr<ServiceWorkerClient> client = mClient;
return client.forget();
}
NS_IMPL_ADDREF_INHERITED(FetchEvent, Event)
NS_IMPL_RELEASE_INHERITED(FetchEvent, Event)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(FetchEvent)
NS_INTERFACE_MAP_END_INHERITING(Event)
NS_IMPL_CYCLE_COLLECTION_INHERITED(FetchEvent, Event, mRequest, mClient)
ExtendableEvent::ExtendableEvent(EventTarget* aOwner)
: Event(aOwner, nullptr, nullptr)
{
}
void
ExtendableEvent::WaitUntil(Promise& aPromise)
{
MOZ_ASSERT(!NS_IsMainThread());
// Only first caller counts.
if (EventPhase() == AT_TARGET && !mPromise) {
mPromise = &aPromise;
}
}
NS_IMPL_ADDREF_INHERITED(ExtendableEvent, Event)
NS_IMPL_RELEASE_INHERITED(ExtendableEvent, Event)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(ExtendableEvent)
NS_INTERFACE_MAP_END_INHERITING(Event)
NS_IMPL_CYCLE_COLLECTION_INHERITED(ExtendableEvent, Event, mPromise)
#ifndef MOZ_SIMPLEPUSH
PushMessageData::PushMessageData(const nsAString& aData)
: mData(aData)
{
}
PushMessageData::~PushMessageData()
{
}
NS_IMPL_ISUPPORTS0(PushMessageData);
void
PushMessageData::Json(JSContext* cx, JS::MutableHandle<JSObject*> aRetval)
{
//todo bug 1149195. Don't be lazy.
NS_ABORT();
}
void
PushMessageData::Text(nsAString& aData)
{
aData = mData;
}
void
PushMessageData::ArrayBuffer(JSContext* cx, JS::MutableHandle<JSObject*> aRetval)
{
//todo bug 1149195. Don't be lazy.
NS_ABORT();
}
mozilla::dom::Blob*
PushMessageData::Blob()
{
//todo bug 1149195. Don't be lazy.
NS_ABORT();
return nullptr;
}
PushEvent::PushEvent(EventTarget* aOwner)
: ExtendableEvent(aOwner)
{
}
NS_INTERFACE_MAP_BEGIN(PushEvent)
NS_INTERFACE_MAP_END_INHERITING(ExtendableEvent)
NS_IMPL_ADDREF_INHERITED(PushEvent, ExtendableEvent)
NS_IMPL_RELEASE_INHERITED(PushEvent, ExtendableEvent)
#endif /* ! MOZ_SIMPLEPUSH */
END_WORKERS_NAMESPACE