mirror of
https://github.com/roytam1/palemoon27.git
synced 2026-05-26 14:18:48 +00:00
8a0a002cf2
- Bug 1148708: Add missing 'override' annotations in DocAccessibleChild.h. rs=ehsan (d606358545)
- Bug 1210408 - make nsMaiInterfaceAction work with proxies, r=tbsaunde (f7c819c6ae)
- Bug 1210407 - teach nsMaiInterfaceTable to use proxies, r=tbsaunde (4ca4f10b5f)
- bug 1185157 make sure we don't send an event to a destroyed ipc document r=billm (23acf53f75)
- bug 1214864 - make SetCarretOffset() async r=davidb (e3079e9b2d)
- missing of Bug 1139972 - IPC Proxy for charAt, r=tbsaunde (e9593ed752)
- bug 1191598 - Pass MOZ_CURRENT_PROJECT in environment when running post-build automation steps for universal mac builds. r=gps (fc342c6ced)
- Bug 1164596 - Add mach android-emulator command; r=ahal (afeb9b27d1)
- Bug 1223149 - Add basic usage documentation for mach build; r=glandium (bfb802d175)
- Bug 1182301 - Improve 'mach build' notifications. r=gps (2c65a122d1)
- Bug 1184696 - Add clobber targets to |mach clobber|; Ability to clobber compiled python files, r=gps (35d8be292e)
- Bug 1117958 - Allow any debugging options to the run or gtest mach subcommands to automatically enable debugging. r=gps (32f986af4b)
- Bug 1180081 - Properly rebuild gtest/libxul before running gtests. r=gps (80db9a3d49)
- Bug 1171647, part 1 - Define a new function to convert the mode to a string. r=njn (61ad16f5ba)
- Bug 1171647, part 2 - Remove redundant assertion for dark matter mode. r=njn (b5ac9519f3)
- Bug 1058178, part 1 - Implement DMD heap scanning mode. r=njn (60e1079536)
- Bug 1058178, part 2 - Implement address clamping analysis for DMD scan logs. r=njn (45c0326b93)
- Bug 1102388 - Fix DMD static constructor ordering dependency. r=mccr8 (59b87897a1)
- Bug 1128705 - Don't redefine PAGE_SIZE in DMD if it's already defined. r=erahm (49216348ee)
- Bug 1179042 - Add a script for analyzing memory blocks using a heap scan DMD log. r=njn DONTBUILD (1c08d2d66e)
- Bug 1207245 - part 6 - rename nsRefPtr<T> to RefPtr<T>; r=ehsan; a=Tomcat (1c999d139b)
- Bug 1158772 - fix non-idiomatic memset call in nsDeque.cpp; r=erahm (de6b555245)
- Bug 1199400 - Part 1: Use CheckedInt when growing nsDeque capacity. r=froydnj (dfdf6814a3)
- Bug 1199400 - Part 0: Remove unused nsDequeIterator. r=froydnj (38d69d7f47)
- Bug 1199400 - Part 2: Add tests for possible nsDeque corner cases. r=froydnj (931baff195)
- Bug 1201997 - Part 1 - Converted compiled test to gtest for nsDeque class. Added tests to test untested methods. r=froydn (e893916651)
- Bug 1201997 - Part 2 - Removing unused methods from the nsDeque class. r=froydn (41595a90ac)
- Bug 1201997 - Part 3 - Make internally used methods private. r=froydn (8cd3afd96f)
- Bug 1201997 - Part 4 - Change size and offset variables to size_t.r=froydn (73eabc8d60)
- Bug 1215140 P1 Add an nsIConsoleReportCollector interface to support navigation channel logging. r=bz (8a41535e2b)
- Bug 1215140 P2 Make HttpBaseChannel implement nsIConsoleReportCollector. r=bz (75fca301f2)
- Bug 1197679 - If nsUnknownDecoder is involved in e10s DivertToParent can break. r=jduell (5d94a12504)
- Bug 1178991 - smartptr for http converter r=hurley (8e7fbc8443)
- bug 366559 - patch 2, fix nsHTTPCompressConv indentation r=bagder (ba762da587)
- bug 366559 - patch 3, fix nsHTTPCompressConv bracing style r=bagder (54195ab451)
- bits of bug 366559 - patch 7, content-encoding brotli for http (f0b4051022)
- Bug 1205112 - Make PushEvent.data nullable. r=mt,smaug (775db32856)
- Bug 1193414 - SharedWorkers thread should be kept alive also when the SharedWorker object is CCed, r=khuey (b77ea8125c)
- Bug 1206520: Add about:config prefs to enable throwing on asm.js validation failures; r=bz (c42126665d)
- Bug 1193414 - Telemetry for SharedWorker spawning. r=bkelly (77984b7bcc)
- Bug 1205676 - Enable WPT service-worker/unregister-then-register-new-script.https.html in e10s, r=nsm (ec24939cf6)
- Bug 1193133 - Throw when calling postMessage from a Service Worker dom object with no global. r=bkelly (526dcacfab)
- Bug 1181871 P1 Only enforce Cache Context shared data destruction on target thread after init. r=ehsan (cdbf3ed3a8)
- Bug 1181871 P2 Fix ServiceWorkerManager usage of stack-based ErrorResult. r=ehsan (c449195d90)
- minor cleanup and missing bit of 1198230 (02f459db05)
- Bug 1143717 - Implement the ServiceWorkerMessageEvent interface. r=baku (027b3465f2)
- fix misspatch (708eee4e84)
- Bug 1188545 - Disentangle service workers from shared workers and refactor event dispatching code into a separate class. r=nsm,mrbkap (fb5b5341c9)
- Bug 1205228 - Change PackagedAppVerifier to notify the verification result asynchronously. r=valentin. (9edda0fa00)
- Bug 1178518 - Packaged App Utils. r=valentin (f60f3b7a93)
- Bug 1213150 - Part 1: Add a nsContentUtils::IsNonSubresourceRequest helper; r=jdm (b509cc3cc9)
- Bug 1213150 - Part 2: Rework ShouldPrepareForIntercept() in terms of subresource requests; r=jdm (2e92fe8780)
- Bug 1213150 - Part 3: Remove nsIInterceptedChannel.isNavigation; r=jdm (becf1cc12f)
- Bug 1213150 follow-up: fix build bustage (8d73d6ca73)
- Bug 1198394 - Part 1: Allow interception of HSTS upgraded connections in non-e10s mode; r=mcmanus (f504c5be08)
- Bug 1198394 - Part 2: Add a test for interception of HSTS upgraded connections; r=jdm (054e984eef)
- Bug 1187011 - Don't allow response body with null body status. r=bkelly (b1860741d1)
- missing bit of 1140788 (29d319712e)
- Bug 1213436 - Reject core dumps with node IDs that don't fit in an IEEE 754 double; r=sfink (3c1f6fdda0)
- Bug 1211006 - Add Debugger.Source.prototype.canonicalId; r=ejpbruel (eef7b79fce)
- Bug 1199218 - Implement JS::ubi::Node::size for js::LazyScript referents; r=sfink (098a48d240)
- Bug 1220031 - Add JS::ubi::Node::scriptFilename; r=sfink (6b824ae680)
- Bug 1143575. Remove unused MediaQueue::Empty. r=cpearce (de737f3433)
- Bug 1209933 - Make sure all parent runtime pointers are the topmost parent, r=billm. (fe824d967d)
- Bug 1197012 - Fix ThrowTypeError in Notification. r=mccr8 (0b1a097526)
- Bug 1197893 - Check the number of arguments for ThrowTypeError() and ThrowRangeError() at compile time. r=peterv (d98c7d78a0)
- Bug 1142083 - Add test for IDN Unicode domain redirect. r=mcmanus (0c8961fe17)
- Bug 1187159 - Add mochitest for loading packaged apps (iframe+fetch+mozapp) r=jduell (ce90ea561b)
- Bug 1186290 - Notify TabParent to switch process when loading a signed package. r=honzab, r=kanru. (c58a14554a)
- fix (15e2df75eb)
- Bug 1206124 P1 Fix "same-origin" CORS credentials in FetchDriver. r=ehsan (fae1bb6ab3)
- Bug 1206124 P2 Test fetch() with credentials and redirects. r=ehsan (ffc6254112)
- Bug 1211751: Remove nsIChannelEventSink-forwarding from EventSource and FetchDriver. It's never needed. r=smaug (adafe5737a)
- Bug 1212433 Fail fetch() calls that require preflight and also redirect. r=sicking a=abillings (c0d6742b9e)
- Bug 1193128 - Fix base64 decoding when fetching data URIs. r=baku (80bafa291a)
- Bug 1195167 part 1: Let necko handle all protocols. r=bkelly (bb932b0ada)
- Bug 1195167 part 2: Remove redundant aCORSFlag argument and instead use mCORSFlagEverSet. r=bkelly (beadafcad0)
- Bug 1195167 part 3: Remove more scheme-specific handling from FetchDriver. r=bkelly (d00b38db9e)
- Bug 1195167 part 4: Remove FetchDriver::BasicFetch since it is empty. r=bkelly (c5ed097267)
- Bug 1210413 P2 Test CORS credentials on cross-origin redirects. r=sicking a=dveditz (b4eeb8aac0)
- Bug 1210413 P1 Propagate new channel load flags from child to parent on redirect. r=jduell a=dveditz (8b329af4fa)
- Bug 1195167 part 5: Make FetchDriver use AsyncOpen2. r=bkelly (cc217c4cc1)
- Bug 1195167 part 6: Some code simplification since necko handles fetch recursion. r=bkelly (f3b6da2262)
- Bug 1195167: Followup to fix test which I forgot to change (81e7439a2e)
- Bug 1215746: Remove RequestMode::Cors_with_forced_preflight. r=bkelly (0336e812b6)
- Bug 1211000: Move CORS preflight logic from nsCORSListenerProxy to nsCORSPreflightListener. r=ehsan (bf2f71cf22)
- missing bit of Bug 1211443 - Drop scheduled update if decoder initialization isn't done yet. r=jya (f6bc074e33)
- Bug 1182571: Fix nsILoadInfo->GetContentPolicyType API to be less ambigious. Audit and fix all users of it. r=ckerschb (5af6fa7442)
- fix (e40c8e7625)
- Bug 1173811 - Part 1: Propagate the response URL to intercepted channels when necessary (non-e10s). r=mayhemer,bkelly (26f4f13c28)
- Bug 1173811 - Part 2: Propagate the response URL to intercepted channels when necessary (e10s). r=mayhemer,bkelly (a603fe1df2)
- Bug 1154309 - Add New Resource Timing Fields r=bz,hurley (1d14eb6bef)
- Bug 1175685 - add OriginAttribute to LoadInfo. r=jonas, r=ckerschb, r=michal (a5d18bb637)
- Bug 1175685 - add OriginAttribute to LoadInfo. r=jonas, r=ckerschb, r=michal (fb07d2c8aa)
- Bug 1212904 P1 Add a LoadTainting enumeration. r=jduell (a1db8a3e99)
- Bug 1212904 P2 Add LoadTainting information to nsILoadInfo. r=jduell (2482e5e334)
- Bug 1221151 - use [infallible] in nsILoadInfo.idl instead of manual %{C++ blocks; r=jduell (aae73129b6)
- Bug 1045891 - CSP 2 child-src implementation r=ckerschb (792920aeb9)
- Bug 1219931 - CSP: Don't allow removing a policy (r=sicking) (9daaab4186)
- Bug 1208661 - Dump client-side layer textures. r=BenWa (1f2d17d515)
1535 lines
42 KiB
C++
1535 lines
42 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 "Fetch.h"
|
|
|
|
#include "nsIDocument.h"
|
|
#include "nsIGlobalObject.h"
|
|
#include "nsIStreamLoader.h"
|
|
#include "nsIThreadRetargetableRequest.h"
|
|
#include "nsIUnicodeDecoder.h"
|
|
#include "nsIUnicodeEncoder.h"
|
|
|
|
#include "nsCharSeparatedTokenizer.h"
|
|
#include "nsDOMString.h"
|
|
#include "nsNetUtil.h"
|
|
#include "nsReadableUtils.h"
|
|
#include "nsStreamUtils.h"
|
|
#include "nsStringStream.h"
|
|
|
|
#include "mozilla/ErrorResult.h"
|
|
#include "mozilla/dom/EncodingUtils.h"
|
|
#include "mozilla/dom/Exceptions.h"
|
|
#include "mozilla/dom/FetchDriver.h"
|
|
#include "mozilla/dom/File.h"
|
|
#include "mozilla/dom/Headers.h"
|
|
#include "mozilla/dom/Promise.h"
|
|
#include "mozilla/dom/PromiseWorkerProxy.h"
|
|
#include "mozilla/dom/Request.h"
|
|
#include "mozilla/dom/Response.h"
|
|
#include "mozilla/dom/ScriptSettings.h"
|
|
#include "mozilla/dom/URLSearchParams.h"
|
|
#include "mozilla/Telemetry.h"
|
|
|
|
#include "InternalRequest.h"
|
|
#include "InternalResponse.h"
|
|
|
|
#include "nsFormData.h"
|
|
#include "WorkerPrivate.h"
|
|
#include "WorkerRunnable.h"
|
|
#include "WorkerScope.h"
|
|
#include "Workers.h"
|
|
#include "FetchUtil.h"
|
|
|
|
namespace mozilla {
|
|
namespace dom {
|
|
|
|
using namespace workers;
|
|
|
|
class WorkerFetchResolver final : public FetchDriverObserver
|
|
{
|
|
friend class MainThreadFetchRunnable;
|
|
friend class WorkerFetchResponseEndRunnable;
|
|
friend class WorkerFetchResponseRunnable;
|
|
|
|
RefPtr<PromiseWorkerProxy> mPromiseProxy;
|
|
public:
|
|
// Returns null if worker is shutting down.
|
|
static already_AddRefed<WorkerFetchResolver>
|
|
Create(workers::WorkerPrivate* aWorkerPrivate, Promise* aPromise)
|
|
{
|
|
MOZ_ASSERT(aWorkerPrivate);
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
RefPtr<PromiseWorkerProxy> proxy = PromiseWorkerProxy::Create(aWorkerPrivate, aPromise);
|
|
if (!proxy) {
|
|
return nullptr;
|
|
}
|
|
|
|
RefPtr<WorkerFetchResolver> r = new WorkerFetchResolver(proxy);
|
|
return r.forget();
|
|
}
|
|
|
|
void
|
|
OnResponseAvailableInternal(InternalResponse* aResponse) override;
|
|
|
|
void
|
|
OnResponseEnd() override;
|
|
|
|
private:
|
|
explicit WorkerFetchResolver(PromiseWorkerProxy* aProxy)
|
|
: mPromiseProxy(aProxy)
|
|
{
|
|
MOZ_ASSERT(!NS_IsMainThread());
|
|
MOZ_ASSERT(mPromiseProxy);
|
|
}
|
|
|
|
~WorkerFetchResolver()
|
|
{}
|
|
};
|
|
|
|
class MainThreadFetchResolver final : public FetchDriverObserver
|
|
{
|
|
RefPtr<Promise> mPromise;
|
|
RefPtr<Response> mResponse;
|
|
|
|
NS_DECL_OWNINGTHREAD
|
|
public:
|
|
explicit MainThreadFetchResolver(Promise* aPromise);
|
|
|
|
void
|
|
OnResponseAvailableInternal(InternalResponse* aResponse) override;
|
|
|
|
private:
|
|
~MainThreadFetchResolver();
|
|
};
|
|
|
|
class MainThreadFetchRunnable : public nsRunnable
|
|
{
|
|
RefPtr<WorkerFetchResolver> mResolver;
|
|
RefPtr<InternalRequest> mRequest;
|
|
|
|
public:
|
|
MainThreadFetchRunnable(WorkerFetchResolver* aResolver,
|
|
InternalRequest* aRequest)
|
|
: mResolver(aResolver)
|
|
, mRequest(aRequest)
|
|
{
|
|
MOZ_ASSERT(mResolver);
|
|
}
|
|
|
|
NS_IMETHODIMP
|
|
Run()
|
|
{
|
|
AssertIsOnMainThread();
|
|
RefPtr<PromiseWorkerProxy> proxy = mResolver->mPromiseProxy;
|
|
MutexAutoLock lock(proxy->Lock());
|
|
if (proxy->CleanedUp()) {
|
|
NS_WARNING("Aborting Fetch because worker already shut down");
|
|
return NS_OK;
|
|
}
|
|
|
|
nsCOMPtr<nsIPrincipal> principal = proxy->GetWorkerPrivate()->GetPrincipal();
|
|
MOZ_ASSERT(principal);
|
|
nsCOMPtr<nsILoadGroup> loadGroup = proxy->GetWorkerPrivate()->GetLoadGroup();
|
|
MOZ_ASSERT(loadGroup);
|
|
RefPtr<FetchDriver> fetch = new FetchDriver(mRequest, principal, loadGroup);
|
|
nsIDocument* doc = proxy->GetWorkerPrivate()->GetDocument();
|
|
if (doc) {
|
|
fetch->SetDocument(doc);
|
|
}
|
|
|
|
nsresult rv = fetch->Fetch(mResolver);
|
|
// Right now we only support async fetch, which should never directly fail.
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
return NS_OK;
|
|
}
|
|
};
|
|
|
|
already_AddRefed<Promise>
|
|
FetchRequest(nsIGlobalObject* aGlobal, const RequestOrUSVString& aInput,
|
|
const RequestInit& aInit, ErrorResult& aRv)
|
|
{
|
|
RefPtr<Promise> p = Promise::Create(aGlobal, aRv);
|
|
if (NS_WARN_IF(aRv.Failed())) {
|
|
return nullptr;
|
|
}
|
|
|
|
AutoJSAPI jsapi;
|
|
jsapi.Init(aGlobal);
|
|
JSContext* cx = jsapi.cx();
|
|
|
|
JS::Rooted<JSObject*> jsGlobal(cx, aGlobal->GetGlobalJSObject());
|
|
GlobalObject global(cx, jsGlobal);
|
|
|
|
RefPtr<Request> request = Request::Constructor(global, aInput, aInit, aRv);
|
|
if (NS_WARN_IF(aRv.Failed())) {
|
|
return nullptr;
|
|
}
|
|
|
|
RefPtr<InternalRequest> r = request->GetInternalRequest();
|
|
|
|
if (NS_IsMainThread()) {
|
|
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal);
|
|
nsCOMPtr<nsIDocument> doc;
|
|
nsCOMPtr<nsILoadGroup> loadGroup;
|
|
nsIPrincipal* principal;
|
|
if (window) {
|
|
doc = window->GetExtantDoc();
|
|
if (!doc) {
|
|
aRv.Throw(NS_ERROR_FAILURE);
|
|
return nullptr;
|
|
}
|
|
principal = doc->NodePrincipal();
|
|
loadGroup = doc->GetDocumentLoadGroup();
|
|
} else {
|
|
principal = aGlobal->PrincipalOrNull();
|
|
if (NS_WARN_IF(!principal)) {
|
|
aRv.Throw(NS_ERROR_FAILURE);
|
|
return nullptr;
|
|
}
|
|
nsresult rv = NS_NewLoadGroup(getter_AddRefs(loadGroup), principal);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
aRv.Throw(rv);
|
|
return nullptr;
|
|
}
|
|
}
|
|
|
|
Telemetry::Accumulate(Telemetry::FETCH_IS_MAINTHREAD, 1);
|
|
|
|
RefPtr<MainThreadFetchResolver> resolver = new MainThreadFetchResolver(p);
|
|
RefPtr<FetchDriver> fetch = new FetchDriver(r, principal, loadGroup);
|
|
fetch->SetDocument(doc);
|
|
aRv = fetch->Fetch(resolver);
|
|
if (NS_WARN_IF(aRv.Failed())) {
|
|
return nullptr;
|
|
}
|
|
} else {
|
|
WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
|
|
MOZ_ASSERT(worker);
|
|
|
|
Telemetry::Accumulate(Telemetry::FETCH_IS_MAINTHREAD, 0);
|
|
|
|
if (worker->IsServiceWorker()) {
|
|
r->SetSkipServiceWorker();
|
|
}
|
|
|
|
RefPtr<WorkerFetchResolver> resolver = WorkerFetchResolver::Create(worker, p);
|
|
if (!resolver) {
|
|
NS_WARNING("Could not add WorkerFetchResolver feature to worker");
|
|
aRv.Throw(NS_ERROR_DOM_ABORT_ERR);
|
|
return nullptr;
|
|
}
|
|
|
|
RefPtr<MainThreadFetchRunnable> run = new MainThreadFetchRunnable(resolver, r);
|
|
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(NS_DispatchToMainThread(run)));
|
|
}
|
|
|
|
return p.forget();
|
|
}
|
|
|
|
MainThreadFetchResolver::MainThreadFetchResolver(Promise* aPromise)
|
|
: mPromise(aPromise)
|
|
{
|
|
}
|
|
|
|
void
|
|
MainThreadFetchResolver::OnResponseAvailableInternal(InternalResponse* aResponse)
|
|
{
|
|
NS_ASSERT_OWNINGTHREAD(MainThreadFetchResolver);
|
|
AssertIsOnMainThread();
|
|
|
|
if (aResponse->Type() != ResponseType::Error) {
|
|
nsCOMPtr<nsIGlobalObject> go = mPromise->GetParentObject();
|
|
mResponse = new Response(go, aResponse);
|
|
mPromise->MaybeResolve(mResponse);
|
|
} else {
|
|
ErrorResult result;
|
|
result.ThrowTypeError<MSG_FETCH_FAILED>();
|
|
mPromise->MaybeReject(result);
|
|
}
|
|
}
|
|
|
|
MainThreadFetchResolver::~MainThreadFetchResolver()
|
|
{
|
|
NS_ASSERT_OWNINGTHREAD(MainThreadFetchResolver);
|
|
}
|
|
|
|
class WorkerFetchResponseRunnable final : public WorkerRunnable
|
|
{
|
|
RefPtr<WorkerFetchResolver> mResolver;
|
|
// Passed from main thread to worker thread after being initialized.
|
|
RefPtr<InternalResponse> mInternalResponse;
|
|
public:
|
|
WorkerFetchResponseRunnable(WorkerPrivate* aWorkerPrivate,
|
|
WorkerFetchResolver* aResolver,
|
|
InternalResponse* aResponse)
|
|
: WorkerRunnable(aWorkerPrivate, WorkerThreadModifyBusyCount)
|
|
, mResolver(aResolver)
|
|
, mInternalResponse(aResponse)
|
|
{
|
|
}
|
|
|
|
bool
|
|
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
|
|
{
|
|
MOZ_ASSERT(aWorkerPrivate);
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
RefPtr<Promise> promise = mResolver->mPromiseProxy->WorkerPromise();
|
|
|
|
if (mInternalResponse->Type() != ResponseType::Error) {
|
|
RefPtr<nsIGlobalObject> global = aWorkerPrivate->GlobalScope();
|
|
RefPtr<Response> response = new Response(global, mInternalResponse);
|
|
promise->MaybeResolve(response);
|
|
} else {
|
|
ErrorResult result;
|
|
result.ThrowTypeError<MSG_FETCH_FAILED>();
|
|
promise->MaybeReject(result);
|
|
}
|
|
return true;
|
|
}
|
|
};
|
|
|
|
class WorkerFetchResponseEndRunnable final : public WorkerRunnable
|
|
{
|
|
RefPtr<WorkerFetchResolver> mResolver;
|
|
public:
|
|
WorkerFetchResponseEndRunnable(WorkerPrivate* aWorkerPrivate,
|
|
WorkerFetchResolver* aResolver)
|
|
: WorkerRunnable(aWorkerPrivate, WorkerThreadModifyBusyCount)
|
|
, mResolver(aResolver)
|
|
{
|
|
}
|
|
|
|
bool
|
|
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
|
|
{
|
|
MOZ_ASSERT(aWorkerPrivate);
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
mResolver->mPromiseProxy->CleanUp(aCx);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
void
|
|
WorkerFetchResolver::OnResponseAvailableInternal(InternalResponse* aResponse)
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
MutexAutoLock lock(mPromiseProxy->Lock());
|
|
if (mPromiseProxy->CleanedUp()) {
|
|
return;
|
|
}
|
|
|
|
RefPtr<WorkerFetchResponseRunnable> r =
|
|
new WorkerFetchResponseRunnable(mPromiseProxy->GetWorkerPrivate(), this,
|
|
aResponse);
|
|
|
|
AutoJSAPI jsapi;
|
|
jsapi.Init();
|
|
if (!r->Dispatch(jsapi.cx())) {
|
|
NS_WARNING("Could not dispatch fetch response");
|
|
}
|
|
}
|
|
|
|
void
|
|
WorkerFetchResolver::OnResponseEnd()
|
|
{
|
|
AssertIsOnMainThread();
|
|
MutexAutoLock lock(mPromiseProxy->Lock());
|
|
if (mPromiseProxy->CleanedUp()) {
|
|
return;
|
|
}
|
|
|
|
RefPtr<WorkerFetchResponseEndRunnable> r =
|
|
new WorkerFetchResponseEndRunnable(mPromiseProxy->GetWorkerPrivate(), this);
|
|
|
|
AutoJSAPI jsapi;
|
|
jsapi.Init();
|
|
if (!r->Dispatch(jsapi.cx())) {
|
|
NS_WARNING("Could not dispatch fetch response end");
|
|
}
|
|
}
|
|
|
|
namespace {
|
|
nsresult
|
|
ExtractFromArrayBuffer(const ArrayBuffer& aBuffer,
|
|
nsIInputStream** aStream)
|
|
{
|
|
aBuffer.ComputeLengthAndData();
|
|
//XXXnsm reinterpret_cast<> is used in DOMParser, should be ok.
|
|
return NS_NewByteInputStream(aStream,
|
|
reinterpret_cast<char*>(aBuffer.Data()),
|
|
aBuffer.Length(), NS_ASSIGNMENT_COPY);
|
|
}
|
|
|
|
nsresult
|
|
ExtractFromArrayBufferView(const ArrayBufferView& aBuffer,
|
|
nsIInputStream** aStream)
|
|
{
|
|
aBuffer.ComputeLengthAndData();
|
|
//XXXnsm reinterpret_cast<> is used in DOMParser, should be ok.
|
|
return NS_NewByteInputStream(aStream,
|
|
reinterpret_cast<char*>(aBuffer.Data()),
|
|
aBuffer.Length(), NS_ASSIGNMENT_COPY);
|
|
}
|
|
|
|
nsresult
|
|
ExtractFromBlob(const Blob& aBlob, nsIInputStream** aStream,
|
|
nsCString& aContentType)
|
|
{
|
|
RefPtr<BlobImpl> impl = aBlob.Impl();
|
|
ErrorResult rv;
|
|
impl->GetInternalStream(aStream, rv);
|
|
if (NS_WARN_IF(rv.Failed())) {
|
|
return rv.StealNSResult();
|
|
}
|
|
|
|
nsAutoString type;
|
|
impl->GetType(type);
|
|
aContentType = NS_ConvertUTF16toUTF8(type);
|
|
return NS_OK;
|
|
}
|
|
|
|
nsresult
|
|
ExtractFromFormData(nsFormData& aFormData, nsIInputStream** aStream,
|
|
nsCString& aContentType)
|
|
{
|
|
uint64_t unusedContentLength;
|
|
nsAutoCString unusedCharset;
|
|
return aFormData.GetSendInfo(aStream, &unusedContentLength,
|
|
aContentType, unusedCharset);
|
|
}
|
|
|
|
nsresult
|
|
ExtractFromUSVString(const nsString& aStr,
|
|
nsIInputStream** aStream,
|
|
nsCString& aContentType)
|
|
{
|
|
nsCOMPtr<nsIUnicodeEncoder> encoder = EncodingUtils::EncoderForEncoding("UTF-8");
|
|
if (!encoder) {
|
|
return NS_ERROR_OUT_OF_MEMORY;
|
|
}
|
|
|
|
int32_t destBufferLen;
|
|
nsresult rv = encoder->GetMaxLength(aStr.get(), aStr.Length(), &destBufferLen);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
nsCString encoded;
|
|
if (!encoded.SetCapacity(destBufferLen, fallible)) {
|
|
return NS_ERROR_OUT_OF_MEMORY;
|
|
}
|
|
|
|
char* destBuffer = encoded.BeginWriting();
|
|
int32_t srcLen = (int32_t) aStr.Length();
|
|
int32_t outLen = destBufferLen;
|
|
rv = encoder->Convert(aStr.get(), &srcLen, destBuffer, &outLen);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
MOZ_ASSERT(outLen <= destBufferLen);
|
|
encoded.SetLength(outLen);
|
|
|
|
aContentType = NS_LITERAL_CSTRING("text/plain;charset=UTF-8");
|
|
|
|
return NS_NewCStringInputStream(aStream, encoded);
|
|
}
|
|
|
|
nsresult
|
|
ExtractFromURLSearchParams(const URLSearchParams& aParams,
|
|
nsIInputStream** aStream,
|
|
nsCString& aContentType)
|
|
{
|
|
nsAutoString serialized;
|
|
aParams.Stringify(serialized);
|
|
aContentType = NS_LITERAL_CSTRING("application/x-www-form-urlencoded;charset=UTF-8");
|
|
return NS_NewStringInputStream(aStream, serialized);
|
|
}
|
|
|
|
class MOZ_STACK_CLASS FillFormIterator final
|
|
: public URLSearchParams::ForEachIterator
|
|
{
|
|
public:
|
|
explicit FillFormIterator(nsFormData* aFormData)
|
|
: mFormData(aFormData)
|
|
{
|
|
MOZ_ASSERT(aFormData);
|
|
}
|
|
|
|
bool URLParamsIterator(const nsString& aName,
|
|
const nsString& aValue) override
|
|
{
|
|
mFormData->Append(aName, aValue);
|
|
return true;
|
|
}
|
|
|
|
private:
|
|
nsFormData* mFormData;
|
|
};
|
|
|
|
/**
|
|
* A simple multipart/form-data parser as defined in RFC 2388 and RFC 2046.
|
|
* This does not respect any encoding specified per entry, using UTF-8
|
|
* throughout. This is as the Fetch spec states in the consume body algorithm.
|
|
* Borrows some things from Necko's nsMultiMixedConv, but is simpler since
|
|
* unlike Necko we do not have to deal with receiving incomplete chunks of data.
|
|
*
|
|
* This parser will fail the entire parse on any invalid entry, so it will
|
|
* never return a partially filled FormData.
|
|
* The content-disposition header is used to figure out the name and filename
|
|
* entries. The inclusion of the filename parameter decides if the entry is
|
|
* inserted into the nsFormData as a string or a File.
|
|
*
|
|
* File blobs are copies of the underlying data string since we cannot adopt
|
|
* char* chunks embedded within the larger body without significant effort.
|
|
* FIXME(nsm): Bug 1127552 - We should add telemetry to calls to formData() and
|
|
* friends to figure out if Fetch ends up copying big blobs to see if this is
|
|
* worth optimizing.
|
|
*/
|
|
class MOZ_STACK_CLASS FormDataParser
|
|
{
|
|
private:
|
|
RefPtr<nsFormData> mFormData;
|
|
nsCString mMimeType;
|
|
nsCString mData;
|
|
|
|
// Entry state, reset in START_PART.
|
|
nsCString mName;
|
|
nsCString mFilename;
|
|
nsCString mContentType;
|
|
|
|
enum
|
|
{
|
|
START_PART,
|
|
PARSE_HEADER,
|
|
PARSE_BODY,
|
|
} mState;
|
|
|
|
nsIGlobalObject* mParentObject;
|
|
|
|
// Reads over a boundary and sets start to the position after the end of the
|
|
// boundary. Returns false if no boundary is found immediately.
|
|
bool
|
|
PushOverBoundary(const nsACString& aBoundaryString,
|
|
nsACString::const_iterator& aStart,
|
|
nsACString::const_iterator& aEnd)
|
|
{
|
|
// We copy the end iterator to keep the original pointing to the real end
|
|
// of the string.
|
|
nsACString::const_iterator end(aEnd);
|
|
const char* beginning = aStart.get();
|
|
if (FindInReadable(aBoundaryString, aStart, end)) {
|
|
// We either should find the body immediately, or after 2 chars with the
|
|
// 2 chars being '-', everything else is failure.
|
|
if ((aStart.get() - beginning) == 0) {
|
|
aStart.advance(aBoundaryString.Length());
|
|
return true;
|
|
}
|
|
|
|
if ((aStart.get() - beginning) == 2) {
|
|
if (*(--aStart) == '-' && *(--aStart) == '-') {
|
|
aStart.advance(aBoundaryString.Length() + 2);
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// Reads over a CRLF and positions start after it.
|
|
bool
|
|
PushOverLine(nsACString::const_iterator& aStart)
|
|
{
|
|
if (*aStart == nsCRT::CR && (aStart.size_forward() > 1) && *(++aStart) == nsCRT::LF) {
|
|
++aStart; // advance to after CRLF
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
bool
|
|
FindCRLF(nsACString::const_iterator& aStart,
|
|
nsACString::const_iterator& aEnd)
|
|
{
|
|
nsACString::const_iterator end(aEnd);
|
|
return FindInReadable(NS_LITERAL_CSTRING("\r\n"), aStart, end);
|
|
}
|
|
|
|
bool
|
|
ParseHeader(nsACString::const_iterator& aStart,
|
|
nsACString::const_iterator& aEnd,
|
|
bool* aWasEmptyHeader)
|
|
{
|
|
MOZ_ASSERT(aWasEmptyHeader);
|
|
// Set it to a valid value here so we don't forget later.
|
|
*aWasEmptyHeader = false;
|
|
|
|
const char* beginning = aStart.get();
|
|
nsACString::const_iterator end(aEnd);
|
|
if (!FindCRLF(aStart, end)) {
|
|
return false;
|
|
}
|
|
|
|
if (aStart.get() == beginning) {
|
|
*aWasEmptyHeader = true;
|
|
return true;
|
|
}
|
|
|
|
nsAutoCString header(beginning, aStart.get() - beginning);
|
|
|
|
nsACString::const_iterator headerStart, headerEnd;
|
|
header.BeginReading(headerStart);
|
|
header.EndReading(headerEnd);
|
|
if (!FindCharInReadable(':', headerStart, headerEnd)) {
|
|
return false;
|
|
}
|
|
|
|
nsAutoCString headerName(StringHead(header, headerStart.size_backward()));
|
|
headerName.CompressWhitespace();
|
|
if (!NS_IsValidHTTPToken(headerName)) {
|
|
return false;
|
|
}
|
|
|
|
nsAutoCString headerValue(Substring(++headerStart, headerEnd));
|
|
if (!NS_IsReasonableHTTPHeaderValue(headerValue)) {
|
|
return false;
|
|
}
|
|
headerValue.CompressWhitespace();
|
|
|
|
if (headerName.LowerCaseEqualsLiteral("content-disposition")) {
|
|
nsCCharSeparatedTokenizer tokenizer(headerValue, ';');
|
|
bool seenFormData = false;
|
|
while (tokenizer.hasMoreTokens()) {
|
|
const nsDependentCSubstring& token = tokenizer.nextToken();
|
|
if (token.IsEmpty()) {
|
|
continue;
|
|
}
|
|
|
|
if (token.EqualsLiteral("form-data")) {
|
|
seenFormData = true;
|
|
continue;
|
|
}
|
|
|
|
if (seenFormData &&
|
|
StringBeginsWith(token, NS_LITERAL_CSTRING("name="))) {
|
|
mName = StringTail(token, token.Length() - 5);
|
|
mName.Trim(" \"");
|
|
continue;
|
|
}
|
|
|
|
if (seenFormData &&
|
|
StringBeginsWith(token, NS_LITERAL_CSTRING("filename="))) {
|
|
mFilename = StringTail(token, token.Length() - 9);
|
|
mFilename.Trim(" \"");
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (mName.IsVoid()) {
|
|
// Could not parse a valid entry name.
|
|
return false;
|
|
}
|
|
} else if (headerName.LowerCaseEqualsLiteral("content-type")) {
|
|
mContentType = headerValue;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
// The end of a body is marked by a CRLF followed by the boundary. So the
|
|
// CRLF is part of the boundary and not the body, but any prior CRLFs are
|
|
// part of the body. This will position the iterator at the beginning of the
|
|
// boundary (after the CRLF).
|
|
bool
|
|
ParseBody(const nsACString& aBoundaryString,
|
|
nsACString::const_iterator& aStart,
|
|
nsACString::const_iterator& aEnd)
|
|
{
|
|
const char* beginning = aStart.get();
|
|
|
|
// Find the boundary marking the end of the body.
|
|
nsACString::const_iterator end(aEnd);
|
|
if (!FindInReadable(aBoundaryString, aStart, end)) {
|
|
return false;
|
|
}
|
|
|
|
// We found a boundary, strip the just prior CRLF, and consider
|
|
// everything else the body section.
|
|
if (aStart.get() - beginning < 2) {
|
|
// Only the first entry can have a boundary right at the beginning. Even
|
|
// an empty body will have a CRLF before the boundary. So this is
|
|
// a failure.
|
|
return false;
|
|
}
|
|
|
|
// Check that there is a CRLF right before the boundary.
|
|
aStart.advance(-2);
|
|
|
|
// Skip optional hyphens.
|
|
if (*aStart == '-' && *(aStart.get()+1) == '-') {
|
|
if (aStart.get() - beginning < 2) {
|
|
return false;
|
|
}
|
|
|
|
aStart.advance(-2);
|
|
}
|
|
|
|
if (*aStart != nsCRT::CR || *(aStart.get()+1) != nsCRT::LF) {
|
|
return false;
|
|
}
|
|
|
|
nsAutoCString body(beginning, aStart.get() - beginning);
|
|
|
|
// Restore iterator to after the \r\n as we promised.
|
|
// We do not need to handle the extra hyphens case since our boundary
|
|
// parser in PushOverBoundary()
|
|
aStart.advance(2);
|
|
|
|
if (!mFormData) {
|
|
mFormData = new nsFormData();
|
|
}
|
|
|
|
NS_ConvertUTF8toUTF16 name(mName);
|
|
|
|
if (mFilename.IsVoid()) {
|
|
mFormData->Append(name, NS_ConvertUTF8toUTF16(body));
|
|
} else {
|
|
// Unfortunately we've to copy the data first since all our strings are
|
|
// going to free it. We also need fallible alloc, so we can't just use
|
|
// ToNewCString().
|
|
char* copy = static_cast<char*>(NS_Alloc(body.Length()));
|
|
if (!copy) {
|
|
NS_WARNING("Failed to copy File entry body.");
|
|
return false;
|
|
}
|
|
nsCString::const_iterator bodyIter, bodyEnd;
|
|
body.BeginReading(bodyIter);
|
|
body.EndReading(bodyEnd);
|
|
char *p = copy;
|
|
while (bodyIter != bodyEnd) {
|
|
*p++ = *bodyIter++;
|
|
}
|
|
p = nullptr;
|
|
|
|
RefPtr<Blob> file =
|
|
File::CreateMemoryFile(mParentObject,
|
|
reinterpret_cast<void *>(copy), body.Length(),
|
|
NS_ConvertUTF8toUTF16(mFilename),
|
|
NS_ConvertUTF8toUTF16(mContentType), /* aLastModifiedDate */ 0);
|
|
Optional<nsAString> dummy;
|
|
mFormData->Append(name, *file, dummy);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public:
|
|
FormDataParser(const nsACString& aMimeType, const nsACString& aData, nsIGlobalObject* aParent)
|
|
: mMimeType(aMimeType), mData(aData), mState(START_PART), mParentObject(aParent)
|
|
{
|
|
}
|
|
|
|
bool
|
|
Parse()
|
|
{
|
|
// Determine boundary from mimetype.
|
|
const char* boundaryId = nullptr;
|
|
boundaryId = strstr(mMimeType.BeginWriting(), "boundary");
|
|
if (!boundaryId) {
|
|
return false;
|
|
}
|
|
|
|
boundaryId = strchr(boundaryId, '=');
|
|
if (!boundaryId) {
|
|
return false;
|
|
}
|
|
|
|
// Skip over '='.
|
|
boundaryId++;
|
|
|
|
char *attrib = (char *) strchr(boundaryId, ';');
|
|
if (attrib) *attrib = '\0';
|
|
|
|
nsAutoCString boundaryString(boundaryId);
|
|
if (attrib) *attrib = ';';
|
|
|
|
boundaryString.Trim(" \"");
|
|
|
|
if (boundaryString.Length() == 0) {
|
|
return false;
|
|
}
|
|
|
|
nsACString::const_iterator start, end;
|
|
mData.BeginReading(start);
|
|
// This should ALWAYS point to the end of data.
|
|
// Helpers make copies.
|
|
mData.EndReading(end);
|
|
|
|
while (start != end) {
|
|
switch(mState) {
|
|
case START_PART:
|
|
mName.SetIsVoid(true);
|
|
mFilename.SetIsVoid(true);
|
|
mContentType = NS_LITERAL_CSTRING("text/plain");
|
|
|
|
// MUST start with boundary.
|
|
if (!PushOverBoundary(boundaryString, start, end)) {
|
|
return false;
|
|
}
|
|
|
|
if (start != end && *start == '-') {
|
|
// End of data.
|
|
if (!mFormData) {
|
|
mFormData = new nsFormData();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (!PushOverLine(start)) {
|
|
return false;
|
|
}
|
|
mState = PARSE_HEADER;
|
|
break;
|
|
|
|
case PARSE_HEADER:
|
|
bool emptyHeader;
|
|
if (!ParseHeader(start, end, &emptyHeader)) {
|
|
return false;
|
|
}
|
|
|
|
if (!PushOverLine(start)) {
|
|
return false;
|
|
}
|
|
|
|
mState = emptyHeader ? PARSE_BODY : PARSE_HEADER;
|
|
break;
|
|
|
|
case PARSE_BODY:
|
|
if (mName.IsVoid()) {
|
|
NS_WARNING("No content-disposition header with a valid name was "
|
|
"found. Failing at body parse.");
|
|
return false;
|
|
}
|
|
|
|
if (!ParseBody(boundaryString, start, end)) {
|
|
return false;
|
|
}
|
|
|
|
mState = START_PART;
|
|
break;
|
|
|
|
default:
|
|
MOZ_CRASH("Invalid case");
|
|
}
|
|
}
|
|
|
|
NS_NOTREACHED("Should never reach here.");
|
|
return false;
|
|
}
|
|
|
|
already_AddRefed<nsFormData> FormData()
|
|
{
|
|
return mFormData.forget();
|
|
}
|
|
};
|
|
} // namespace
|
|
|
|
nsresult
|
|
ExtractByteStreamFromBody(const OwningArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams& aBodyInit,
|
|
nsIInputStream** aStream,
|
|
nsCString& aContentType)
|
|
{
|
|
MOZ_ASSERT(aStream);
|
|
|
|
if (aBodyInit.IsArrayBuffer()) {
|
|
const ArrayBuffer& buf = aBodyInit.GetAsArrayBuffer();
|
|
return ExtractFromArrayBuffer(buf, aStream);
|
|
} else if (aBodyInit.IsArrayBufferView()) {
|
|
const ArrayBufferView& buf = aBodyInit.GetAsArrayBufferView();
|
|
return ExtractFromArrayBufferView(buf, aStream);
|
|
} else if (aBodyInit.IsBlob()) {
|
|
const Blob& blob = aBodyInit.GetAsBlob();
|
|
return ExtractFromBlob(blob, aStream, aContentType);
|
|
} else if (aBodyInit.IsFormData()) {
|
|
nsFormData& form = aBodyInit.GetAsFormData();
|
|
return ExtractFromFormData(form, aStream, aContentType);
|
|
} else if (aBodyInit.IsUSVString()) {
|
|
nsAutoString str;
|
|
str.Assign(aBodyInit.GetAsUSVString());
|
|
return ExtractFromUSVString(str, aStream, aContentType);
|
|
} else if (aBodyInit.IsURLSearchParams()) {
|
|
URLSearchParams& params = aBodyInit.GetAsURLSearchParams();
|
|
return ExtractFromURLSearchParams(params, aStream, aContentType);
|
|
}
|
|
|
|
NS_NOTREACHED("Should never reach here");
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
nsresult
|
|
ExtractByteStreamFromBody(const ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams& aBodyInit,
|
|
nsIInputStream** aStream,
|
|
nsCString& aContentType)
|
|
{
|
|
MOZ_ASSERT(aStream);
|
|
|
|
if (aBodyInit.IsArrayBuffer()) {
|
|
const ArrayBuffer& buf = aBodyInit.GetAsArrayBuffer();
|
|
return ExtractFromArrayBuffer(buf, aStream);
|
|
} else if (aBodyInit.IsArrayBufferView()) {
|
|
const ArrayBufferView& buf = aBodyInit.GetAsArrayBufferView();
|
|
return ExtractFromArrayBufferView(buf, aStream);
|
|
} else if (aBodyInit.IsBlob()) {
|
|
const Blob& blob = aBodyInit.GetAsBlob();
|
|
return ExtractFromBlob(blob, aStream, aContentType);
|
|
} else if (aBodyInit.IsFormData()) {
|
|
nsFormData& form = aBodyInit.GetAsFormData();
|
|
return ExtractFromFormData(form, aStream, aContentType);
|
|
} else if (aBodyInit.IsUSVString()) {
|
|
nsAutoString str;
|
|
str.Assign(aBodyInit.GetAsUSVString());
|
|
return ExtractFromUSVString(str, aStream, aContentType);
|
|
} else if (aBodyInit.IsURLSearchParams()) {
|
|
URLSearchParams& params = aBodyInit.GetAsURLSearchParams();
|
|
return ExtractFromURLSearchParams(params, aStream, aContentType);
|
|
}
|
|
|
|
NS_NOTREACHED("Should never reach here");
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
namespace {
|
|
/*
|
|
* Called on successfully reading the complete stream.
|
|
*/
|
|
template <class Derived>
|
|
class ContinueConsumeBodyRunnable final : public WorkerRunnable
|
|
{
|
|
// This has been addrefed before this runnable is dispatched,
|
|
// released in WorkerRun().
|
|
FetchBody<Derived>* mFetchBody;
|
|
nsresult mStatus;
|
|
uint32_t mLength;
|
|
uint8_t* mResult;
|
|
|
|
public:
|
|
ContinueConsumeBodyRunnable(FetchBody<Derived>* aFetchBody, nsresult aStatus,
|
|
uint32_t aLength, uint8_t* aResult)
|
|
: WorkerRunnable(aFetchBody->mWorkerPrivate, WorkerThreadModifyBusyCount)
|
|
, mFetchBody(aFetchBody)
|
|
, mStatus(aStatus)
|
|
, mLength(aLength)
|
|
, mResult(aResult)
|
|
{
|
|
MOZ_ASSERT(NS_IsMainThread());
|
|
}
|
|
|
|
bool
|
|
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
|
|
{
|
|
mFetchBody->ContinueConsumeBody(mStatus, mLength, mResult);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
// OnStreamComplete always adopts the buffer, utility class to release it in
|
|
// a couple of places.
|
|
class MOZ_STACK_CLASS AutoFreeBuffer final {
|
|
uint8_t* mBuffer;
|
|
|
|
public:
|
|
explicit AutoFreeBuffer(uint8_t* aBuffer)
|
|
: mBuffer(aBuffer)
|
|
{}
|
|
|
|
~AutoFreeBuffer()
|
|
{
|
|
moz_free(mBuffer);
|
|
}
|
|
|
|
void
|
|
Reset()
|
|
{
|
|
mBuffer= nullptr;
|
|
}
|
|
};
|
|
|
|
template <class Derived>
|
|
class FailConsumeBodyWorkerRunnable : public MainThreadWorkerControlRunnable
|
|
{
|
|
FetchBody<Derived>* mBody;
|
|
public:
|
|
explicit FailConsumeBodyWorkerRunnable(FetchBody<Derived>* aBody)
|
|
: MainThreadWorkerControlRunnable(aBody->mWorkerPrivate)
|
|
, mBody(aBody)
|
|
{
|
|
AssertIsOnMainThread();
|
|
}
|
|
|
|
bool
|
|
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
|
|
{
|
|
mBody->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
/*
|
|
* In case of failure to create a stream pump or dispatch stream completion to
|
|
* worker, ensure we cleanup properly. Thread agnostic.
|
|
*/
|
|
template <class Derived>
|
|
class MOZ_STACK_CLASS AutoFailConsumeBody final
|
|
{
|
|
FetchBody<Derived>* mBody;
|
|
public:
|
|
explicit AutoFailConsumeBody(FetchBody<Derived>* aBody)
|
|
: mBody(aBody)
|
|
{ }
|
|
|
|
~AutoFailConsumeBody()
|
|
{
|
|
AssertIsOnMainThread();
|
|
if (mBody) {
|
|
if (mBody->mWorkerPrivate) {
|
|
RefPtr<FailConsumeBodyWorkerRunnable<Derived>> r =
|
|
new FailConsumeBodyWorkerRunnable<Derived>(mBody);
|
|
AutoSafeJSContext cx;
|
|
if (!r->Dispatch(cx)) {
|
|
MOZ_CRASH("We are going to leak");
|
|
}
|
|
} else {
|
|
mBody->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr);
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
DontFail()
|
|
{
|
|
mBody = nullptr;
|
|
}
|
|
};
|
|
|
|
template <class Derived>
|
|
class ConsumeBodyDoneObserver : public nsIStreamLoaderObserver
|
|
{
|
|
FetchBody<Derived>* mFetchBody;
|
|
|
|
public:
|
|
NS_DECL_THREADSAFE_ISUPPORTS
|
|
|
|
explicit ConsumeBodyDoneObserver(FetchBody<Derived>* aFetchBody)
|
|
: mFetchBody(aFetchBody)
|
|
{ }
|
|
|
|
NS_IMETHOD
|
|
OnStreamComplete(nsIStreamLoader* aLoader,
|
|
nsISupports* aCtxt,
|
|
nsresult aStatus,
|
|
uint32_t aResultLength,
|
|
const uint8_t* aResult) override
|
|
{
|
|
MOZ_ASSERT(NS_IsMainThread());
|
|
|
|
// If the binding requested cancel, we don't need to call
|
|
// ContinueConsumeBody, since that is the originator.
|
|
if (aStatus == NS_BINDING_ABORTED) {
|
|
return NS_OK;
|
|
}
|
|
|
|
uint8_t* nonconstResult = const_cast<uint8_t*>(aResult);
|
|
if (mFetchBody->mWorkerPrivate) {
|
|
// This way if the runnable dispatch fails, the body is still released.
|
|
AutoFailConsumeBody<Derived> autoFail(mFetchBody);
|
|
RefPtr<ContinueConsumeBodyRunnable<Derived>> r =
|
|
new ContinueConsumeBodyRunnable<Derived>(mFetchBody,
|
|
aStatus,
|
|
aResultLength,
|
|
nonconstResult);
|
|
AutoSafeJSContext cx;
|
|
if (r->Dispatch(cx)) {
|
|
autoFail.DontFail();
|
|
} else {
|
|
NS_WARNING("Could not dispatch ConsumeBodyRunnable");
|
|
// Return failure so that aResult is freed.
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
} else {
|
|
mFetchBody->ContinueConsumeBody(aStatus, aResultLength, nonconstResult);
|
|
}
|
|
|
|
// FetchBody is responsible for data.
|
|
return NS_SUCCESS_ADOPTED_DATA;
|
|
}
|
|
|
|
private:
|
|
virtual ~ConsumeBodyDoneObserver()
|
|
{ }
|
|
};
|
|
|
|
template <class Derived>
|
|
NS_IMPL_ADDREF(ConsumeBodyDoneObserver<Derived>)
|
|
template <class Derived>
|
|
NS_IMPL_RELEASE(ConsumeBodyDoneObserver<Derived>)
|
|
template <class Derived>
|
|
NS_INTERFACE_MAP_BEGIN(ConsumeBodyDoneObserver<Derived>)
|
|
NS_INTERFACE_MAP_ENTRY(nsIStreamLoaderObserver)
|
|
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamLoaderObserver)
|
|
NS_INTERFACE_MAP_END
|
|
|
|
template <class Derived>
|
|
class BeginConsumeBodyRunnable final : public nsRunnable
|
|
{
|
|
FetchBody<Derived>* mFetchBody;
|
|
public:
|
|
explicit BeginConsumeBodyRunnable(FetchBody<Derived>* aBody)
|
|
: mFetchBody(aBody)
|
|
{ }
|
|
|
|
NS_IMETHOD
|
|
Run() override
|
|
{
|
|
mFetchBody->BeginConsumeBodyMainThread();
|
|
return NS_OK;
|
|
}
|
|
};
|
|
|
|
template <class Derived>
|
|
class CancelPumpRunnable final : public WorkerMainThreadRunnable
|
|
{
|
|
FetchBody<Derived>* mBody;
|
|
public:
|
|
explicit CancelPumpRunnable(FetchBody<Derived>* aBody)
|
|
: WorkerMainThreadRunnable(aBody->mWorkerPrivate)
|
|
, mBody(aBody)
|
|
{ }
|
|
|
|
bool
|
|
MainThreadRun() override
|
|
{
|
|
mBody->CancelPump();
|
|
return true;
|
|
}
|
|
};
|
|
} // namespace
|
|
|
|
template <class Derived>
|
|
class FetchBodyFeature final : public workers::WorkerFeature
|
|
{
|
|
// This is addrefed before the feature is created, and is released in ContinueConsumeBody()
|
|
// so we can hold a rawptr.
|
|
FetchBody<Derived>* mBody;
|
|
|
|
public:
|
|
explicit FetchBodyFeature(FetchBody<Derived>* aBody)
|
|
: mBody(aBody)
|
|
{ }
|
|
|
|
~FetchBodyFeature()
|
|
{ }
|
|
|
|
bool Notify(JSContext* aCx, workers::Status aStatus) override
|
|
{
|
|
MOZ_ASSERT(aStatus > workers::Running);
|
|
mBody->ContinueConsumeBody(NS_BINDING_ABORTED, 0, nullptr);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
template <class Derived>
|
|
FetchBody<Derived>::FetchBody()
|
|
: mFeature(nullptr)
|
|
, mBodyUsed(false)
|
|
, mReadDone(false)
|
|
{
|
|
if (!NS_IsMainThread()) {
|
|
mWorkerPrivate = GetCurrentThreadWorkerPrivate();
|
|
MOZ_ASSERT(mWorkerPrivate);
|
|
} else {
|
|
mWorkerPrivate = nullptr;
|
|
}
|
|
}
|
|
|
|
template
|
|
FetchBody<Request>::FetchBody();
|
|
|
|
template
|
|
FetchBody<Response>::FetchBody();
|
|
|
|
template <class Derived>
|
|
FetchBody<Derived>::~FetchBody()
|
|
{
|
|
}
|
|
|
|
// Returns true if addref succeeded.
|
|
// Always succeeds on main thread.
|
|
// May fail on worker if RegisterFeature() fails. In that case, it will release
|
|
// the object before returning false.
|
|
template <class Derived>
|
|
bool
|
|
FetchBody<Derived>::AddRefObject()
|
|
{
|
|
AssertIsOnTargetThread();
|
|
DerivedClass()->AddRef();
|
|
|
|
if (mWorkerPrivate && !mFeature) {
|
|
if (!RegisterFeature()) {
|
|
ReleaseObject();
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
template <class Derived>
|
|
void
|
|
FetchBody<Derived>::ReleaseObject()
|
|
{
|
|
AssertIsOnTargetThread();
|
|
|
|
if (mWorkerPrivate && mFeature) {
|
|
UnregisterFeature();
|
|
}
|
|
|
|
DerivedClass()->Release();
|
|
}
|
|
|
|
template <class Derived>
|
|
bool
|
|
FetchBody<Derived>::RegisterFeature()
|
|
{
|
|
MOZ_ASSERT(mWorkerPrivate);
|
|
mWorkerPrivate->AssertIsOnWorkerThread();
|
|
MOZ_ASSERT(!mFeature);
|
|
mFeature = new FetchBodyFeature<Derived>(this);
|
|
|
|
if (!mWorkerPrivate->AddFeature(mWorkerPrivate->GetJSContext(), mFeature)) {
|
|
NS_WARNING("Failed to add feature");
|
|
mFeature = nullptr;
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
template <class Derived>
|
|
void
|
|
FetchBody<Derived>::UnregisterFeature()
|
|
{
|
|
MOZ_ASSERT(mWorkerPrivate);
|
|
mWorkerPrivate->AssertIsOnWorkerThread();
|
|
MOZ_ASSERT(mFeature);
|
|
|
|
mWorkerPrivate->RemoveFeature(mWorkerPrivate->GetJSContext(), mFeature);
|
|
mFeature = nullptr;
|
|
}
|
|
|
|
template <class Derived>
|
|
void
|
|
FetchBody<Derived>::CancelPump()
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(mConsumeBodyPump);
|
|
mConsumeBodyPump->Cancel(NS_BINDING_ABORTED);
|
|
}
|
|
|
|
// Return value is used by ConsumeBody to bubble the error code up to WebIDL so
|
|
// mConsumePromise doesn't have to be rejected on early exit.
|
|
template <class Derived>
|
|
nsresult
|
|
FetchBody<Derived>::BeginConsumeBody()
|
|
{
|
|
AssertIsOnTargetThread();
|
|
MOZ_ASSERT(!mFeature);
|
|
MOZ_ASSERT(mConsumePromise);
|
|
|
|
// The FetchBody is not thread-safe refcounted. We addref it here and release
|
|
// it once the stream read is finished.
|
|
if (!AddRefObject()) {
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
nsCOMPtr<nsIRunnable> r = new BeginConsumeBodyRunnable<Derived>(this);
|
|
nsresult rv = NS_DispatchToMainThread(r);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
ReleaseObject();
|
|
return rv;
|
|
}
|
|
return NS_OK;
|
|
}
|
|
|
|
/*
|
|
* BeginConsumeBodyMainThread() will automatically reject the consume promise
|
|
* and clean up on any failures, so there is no need for callers to do so,
|
|
* reflected in a lack of error return code.
|
|
*/
|
|
template <class Derived>
|
|
void
|
|
FetchBody<Derived>::BeginConsumeBodyMainThread()
|
|
{
|
|
AssertIsOnMainThread();
|
|
AutoFailConsumeBody<Derived> autoReject(DerivedClass());
|
|
nsresult rv;
|
|
nsCOMPtr<nsIInputStream> stream;
|
|
DerivedClass()->GetBody(getter_AddRefs(stream));
|
|
if (!stream) {
|
|
rv = NS_NewCStringInputStream(getter_AddRefs(stream), EmptyCString());
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
nsCOMPtr<nsIInputStreamPump> pump;
|
|
rv = NS_NewInputStreamPump(getter_AddRefs(pump),
|
|
stream);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return;
|
|
}
|
|
|
|
RefPtr<ConsumeBodyDoneObserver<Derived>> p = new ConsumeBodyDoneObserver<Derived>(this);
|
|
nsCOMPtr<nsIStreamLoader> loader;
|
|
rv = NS_NewStreamLoader(getter_AddRefs(loader), p);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return;
|
|
}
|
|
|
|
rv = pump->AsyncRead(loader, nullptr);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return;
|
|
}
|
|
|
|
// Now that everything succeeded, we can assign the pump to a pointer that
|
|
// stays alive for the lifetime of the FetchBody.
|
|
mConsumeBodyPump = new nsMainThreadPtrHolder<nsIInputStreamPump>(pump);
|
|
// It is ok for retargeting to fail and reads to happen on the main thread.
|
|
autoReject.DontFail();
|
|
|
|
// Try to retarget, otherwise fall back to main thread.
|
|
nsCOMPtr<nsIThreadRetargetableRequest> rr = do_QueryInterface(pump);
|
|
if (rr) {
|
|
nsCOMPtr<nsIEventTarget> sts = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
|
|
rv = rr->RetargetDeliveryTo(sts);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
NS_WARNING("Retargeting failed");
|
|
}
|
|
}
|
|
}
|
|
|
|
template <class Derived>
|
|
void
|
|
FetchBody<Derived>::ContinueConsumeBody(nsresult aStatus, uint32_t aResultLength, uint8_t* aResult)
|
|
{
|
|
AssertIsOnTargetThread();
|
|
// Just a precaution to ensure ContinueConsumeBody is not called out of
|
|
// sync with a body read.
|
|
MOZ_ASSERT(mBodyUsed);
|
|
MOZ_ASSERT(!mReadDone);
|
|
MOZ_ASSERT_IF(mWorkerPrivate, mFeature);
|
|
mReadDone = true;
|
|
|
|
AutoFreeBuffer autoFree(aResult);
|
|
|
|
MOZ_ASSERT(mConsumePromise);
|
|
RefPtr<Promise> localPromise = mConsumePromise.forget();
|
|
|
|
RefPtr<Derived> kungfuDeathGrip = DerivedClass();
|
|
ReleaseObject();
|
|
|
|
if (NS_WARN_IF(NS_FAILED(aStatus))) {
|
|
localPromise->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
|
|
|
|
// If binding aborted, cancel the pump. We can't assert mConsumeBodyPump.
|
|
// In the (admittedly rare) situation that BeginConsumeBodyMainThread()
|
|
// context switches out, and the worker thread gets canceled before the
|
|
// pump is setup, mConsumeBodyPump will be null.
|
|
// We've to use the !! form since non-main thread pointer access on
|
|
// a nsMainThreadPtrHandle is not permitted.
|
|
if (aStatus == NS_BINDING_ABORTED && !!mConsumeBodyPump) {
|
|
if (NS_IsMainThread()) {
|
|
CancelPump();
|
|
} else {
|
|
MOZ_ASSERT(mWorkerPrivate);
|
|
// In case of worker thread, we block the worker while the request is
|
|
// canceled on the main thread. This ensures that OnStreamComplete has
|
|
// a valid FetchBody around to call CancelPump and we don't release the
|
|
// FetchBody on the main thread.
|
|
RefPtr<CancelPumpRunnable<Derived>> r =
|
|
new CancelPumpRunnable<Derived>(this);
|
|
if (!r->Dispatch(mWorkerPrivate->GetJSContext())) {
|
|
NS_WARNING("Could not dispatch CancelPumpRunnable. Nothing we can do here");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Release the pump and then early exit if there was an error.
|
|
// Uses NS_ProxyRelease internally, so this is safe.
|
|
mConsumeBodyPump = nullptr;
|
|
|
|
// Don't warn here since we warned above.
|
|
if (NS_FAILED(aStatus)) {
|
|
return;
|
|
}
|
|
|
|
// Finish successfully consuming body according to type.
|
|
MOZ_ASSERT(aResult);
|
|
|
|
AutoJSAPI jsapi;
|
|
jsapi.Init(DerivedClass()->GetParentObject());
|
|
JSContext* cx = jsapi.cx();
|
|
|
|
ErrorResult error;
|
|
|
|
switch (mConsumeType) {
|
|
case CONSUME_ARRAYBUFFER: {
|
|
JS::Rooted<JSObject*> arrayBuffer(cx);
|
|
FetchUtil::ConsumeArrayBuffer(cx, &arrayBuffer, aResultLength, aResult,
|
|
error);
|
|
|
|
error.WouldReportJSException();
|
|
if (!error.Failed()) {
|
|
JS::Rooted<JS::Value> val(cx);
|
|
val.setObjectOrNull(arrayBuffer);
|
|
|
|
localPromise->MaybeResolve(cx, val);
|
|
// ArrayBuffer takes over ownership.
|
|
autoFree.Reset();
|
|
}
|
|
break;
|
|
}
|
|
case CONSUME_BLOB: {
|
|
RefPtr<dom::Blob> blob = FetchUtil::ConsumeBlob(
|
|
DerivedClass()->GetParentObject(), NS_ConvertUTF8toUTF16(mMimeType),
|
|
aResultLength, aResult, error);
|
|
error.WouldReportJSException();
|
|
if (!error.Failed()) {
|
|
localPromise->MaybeResolve(blob);
|
|
// File takes over ownership.
|
|
autoFree.Reset();
|
|
}
|
|
break;
|
|
}
|
|
case CONSUME_FORMDATA: {
|
|
nsCString data;
|
|
data.Adopt(reinterpret_cast<char*>(aResult), aResultLength);
|
|
autoFree.Reset();
|
|
|
|
RefPtr<nsFormData> fd = FetchUtil::ConsumeFormData(
|
|
DerivedClass()->GetParentObject(),
|
|
mMimeType, data, error);
|
|
if (!error.Failed()) {
|
|
localPromise->MaybeResolve(fd);
|
|
}
|
|
break;
|
|
}
|
|
case CONSUME_TEXT:
|
|
// fall through handles early exit.
|
|
case CONSUME_JSON: {
|
|
nsString decoded;
|
|
if (NS_SUCCEEDED(FetchUtil::ConsumeText(aResultLength, aResult, decoded))) {
|
|
if (mConsumeType == CONSUME_TEXT) {
|
|
localPromise->MaybeResolve(decoded);
|
|
} else {
|
|
JS::Rooted<JS::Value> json(cx);
|
|
FetchUtil::ConsumeJson(cx, &json, decoded, error);
|
|
if (!error.Failed()) {
|
|
localPromise->MaybeResolve(cx, json);
|
|
}
|
|
}
|
|
};
|
|
break;
|
|
}
|
|
default:
|
|
NS_NOTREACHED("Unexpected consume body type");
|
|
}
|
|
|
|
error.WouldReportJSException();
|
|
if (error.Failed()) {
|
|
if (error.IsJSException()) {
|
|
JS::Rooted<JS::Value> exn(cx);
|
|
error.StealJSException(cx, &exn);
|
|
localPromise->MaybeReject(cx, exn);
|
|
} else {
|
|
localPromise->MaybeReject(error);
|
|
}
|
|
}
|
|
}
|
|
|
|
template <class Derived>
|
|
already_AddRefed<Promise>
|
|
FetchBody<Derived>::ConsumeBody(ConsumeType aType, ErrorResult& aRv)
|
|
{
|
|
mConsumeType = aType;
|
|
if (BodyUsed()) {
|
|
aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
|
|
return nullptr;
|
|
}
|
|
|
|
SetBodyUsed();
|
|
|
|
mConsumePromise = Promise::Create(DerivedClass()->GetParentObject(), aRv);
|
|
if (aRv.Failed()) {
|
|
return nullptr;
|
|
}
|
|
|
|
aRv = BeginConsumeBody();
|
|
if (NS_WARN_IF(aRv.Failed())) {
|
|
mConsumePromise = nullptr;
|
|
return nullptr;
|
|
}
|
|
|
|
RefPtr<Promise> promise = mConsumePromise;
|
|
return promise.forget();
|
|
}
|
|
|
|
template
|
|
already_AddRefed<Promise>
|
|
FetchBody<Request>::ConsumeBody(ConsumeType aType, ErrorResult& aRv);
|
|
|
|
template
|
|
already_AddRefed<Promise>
|
|
FetchBody<Response>::ConsumeBody(ConsumeType aType, ErrorResult& aRv);
|
|
|
|
template <class Derived>
|
|
void
|
|
FetchBody<Derived>::SetMimeType()
|
|
{
|
|
// Extract mime type.
|
|
ErrorResult result;
|
|
nsTArray<nsCString> contentTypeValues;
|
|
MOZ_ASSERT(DerivedClass()->GetInternalHeaders());
|
|
DerivedClass()->GetInternalHeaders()->GetAll(NS_LITERAL_CSTRING("Content-Type"),
|
|
contentTypeValues, result);
|
|
MOZ_ALWAYS_TRUE(!result.Failed());
|
|
|
|
// HTTP ABNF states Content-Type may have only one value.
|
|
// This is from the "parse a header value" of the fetch spec.
|
|
if (contentTypeValues.Length() == 1) {
|
|
mMimeType = contentTypeValues[0];
|
|
ToLowerCase(mMimeType);
|
|
}
|
|
}
|
|
|
|
template
|
|
void
|
|
FetchBody<Request>::SetMimeType();
|
|
|
|
template
|
|
void
|
|
FetchBody<Response>::SetMimeType();
|
|
|
|
} // namespace dom
|
|
} // namespace mozilla
|