Files
palemoon27/dom/fetch/Fetch.cpp
T
roytam1 ff0033e97d import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1231975 - Part 3: Break a reference cycle between PendingResolution and DNSRequestChild. r=drno (ecf45de535)
- Bug 1231975 - Part 4: Add some logging and simplification in TestNrSocket. r=drno (fa811f7743)
- Bug 1231975 - Part 5: Fix an intermittent failure caused by the NAT simulator erroneously canceling NR_ASYNC_WAIT_READ. r=drno (e436a8cc75)
- var-let (d228288673)
- Bug 1256022 - dom/network slow GC on mochitest fix r=dragana (e0dffd5033)
- Bug 1231130 - added mHadLocalInstance to constructor.r=jaas (c4f6d0c530)
- Bug 1121290: Use "%ls" instead of "%s" in _snwprintf_s format string# r=bsmedberg (e0434aca5a)
- Bug 1206952 - Rename MagicRequest to ByteRangeRequest. r=sicking (6780309aa2)
- Bug 1206952 - Convert PluginStreamListener to use channel->AsyncOpen2(). r=sicking (8f41f3e148)
- Bug 1262335 - Part 2. Remove Android GB/HC defines from OMX. r=snorp (e5b7435d92)
- Bug 956899 - Add a std::condition_variable work-alike; r=froydnj (98076c707e)
- Bug 1254123 - Handle OOM more gracefully in js::ErrorToException. (r=Waldo) (f9a2ef18d1)
- Bug 1255128 - Standard argument coercion in new ArrayBuffer(length). r=nbp. Thanks to snowmantw for tests. (06e5cedd80)
- Bug 1251919 - Nuke Debugger wrappers on failure. (r=shu) (64bc41b1f1)
- Bug 1254190 - Propagate failure of matchAllDebuggeeGlobals() in Debugger. (r=shu) (927bf01ec5)
- Bug 1254172 - Make UnboxedLayout::makeNativeGroup robust to unknownProperties on unboxed type. (r=jandem) (398a6b3aa7)
- Bug 1268213 - BlobImplFile::GetTypeRunnable can be a WorkerMainThreadRunnable, r=khuey (30e4ff4b75)
- Bug 1250523 - Wait for the markup-view to be loaded in browser_markup_load_01.js; r=gl (acf9e9d88b)
- Bug 1230325 - markup-view: skip keyboard shortcuts if any modifier;r=pbrosset (ab974dfac7)
- Bug 1155465 - part1: layout-view: use content-type CSS_VALUE for editors;r=miker (d21e70b811)
- Bug 1155465 - part2: inplace-editor: disable increment on up/down for PLAIN_TEXT;r=miker (5d72e05f63)
- Bug 1241126 - ruleview property: open editor for prop. name on click on ":";r=gl (4889010c34)
- Bug 1128340 - Allow renaming with non-ASCII characters in WebIDE. r=jryans (f9844e3afb)
- Bug 1039482 - Properly position and style the file name edit field in the projecteditor. r=bgrins (4c29b80958)
- Bug 1268231 - Get rid of StopSyncLoopRunnable, r=khuey (29b0a0ed4f)
- Bug 1267904 - Add telemetry for WorkerMainThreadRunnable, r=khuey (970d39bcce)
- Bug 1261317 - part1: inplace-editor: small refactor of keypress event handler;r=pbro (5261bca85a)
- Bug 1261317 - part2: prevent autocomplete on arrow keys in multiline editor;r=pbro (859738623a)
- Bug 1246677 - 1 - Make waitForSuccess work with async functions; r=miker (3927347635)
- Bug 1227810 - split browser_ruleview_authored.js into three tests; r=pbrosset (f6e4760908)
- Bug 1246677 - 2 - Stop using CPOWs in simulateColorPickerChange; r=miker (69a31024cf)
- Bug 1246677 - 3 - Remove all usages of getNode in ruleview tests; r=tromey (2f25bec099)
- Bug 1240813 - Fixed the unhandled promise rejections in browser_rules_colorpicker-* tests; r=ochameau (bd534ec71b)
- Bug 1217328 - let filter editor work on invalid values. r=pbrosset (91602cac94)
- Bug 1225236 - Removed the 360 value limit for the hue-rotate field in the CSS filter popup. r=pbro (9bceb9947d)
- Bug 1223076 - make FilterWidget handle "unset", "initial", and "inherit". r=pbrosset (6542d5cc99)
- Bug 1221156 - make FilterWidget try to preserve URL quoting; r=pbrosset (3e1105c3d5)
- Bug 1226543 - fix URL quoting in CSSFilterEditorWidget.getValueAt. r=pbrosset (1770cc279a)
- Bug 1241527 - 1 - Fix some unhandled rejected promises in colorpicker, cubicbezier and cssfilter ruleview tests; r=gl (059df355be)
- Bug 1241527 - 2 - Use ruleview-changed event to avoid pending requests when browser_rules_search-filter* tests end; r=gl (407d5866b0)
- Bug 1241527 - 3 - Fix typo in hideTooltipAndWaitForRuleviewChanged; r=gl (964270c8c3)
- Bug 1241527 - 4 - Use ruleview-changed event to avoid pending requests in browser_rules_multiple* tests; r=gl (2947abf296)
- Bug 1241527 - 5 - Use ruleview-changed event to fix remaining pending requests in tests; r=gl (5391857e12)
- Bug 1246677 - 4 - Stop using content.getComputedStyle in ruleview tests; r=miker (f61cd8d5aa)
- Bug 1237885 - fix add-rules_01 intermittent by splitting in two tests;r=gl (45e4de6012)
- Bug 1166956 - add valid unit when incrementing CSS value "0";r=tromey (40ca31b909)
- Bug 1241155 - correctly use indexOf in browser_rules_user-agent-styles.js; r=bgrins (0966d23f7e)
- Bug 1229911 - recognize DevToolsUtils.defineLazyGetter and defineLazyModuleGetter. r=miker (876e4b9f3b)
- Bug 1230093 - Make the import-headjs-globals rule store variables correctly; r=Mossop (be3ddcb7fb)
- Bug 1229224: Support more forms of defining globals and make anywhere we import scripts use them too. r=miker (c9a243fcae)
- Bug 1231963 - handle top-level "this.mumble" assignments in eslint; r=mikeratcliffe (be07835449)
- Bug 1224289 - add eslint rule to reject Cu.importGlobalProperties; r=mikeratcliffe (eac54ddcce)
- Bug 1241544 - add documentation for this-top-level-scope eslint rule; r=mikeratcliffe (9d832af29d)
- Bug 1239426 - handle arrow functions in getASTSource; r=mikeratcliffe (889b5ff89c)
- Bug 1242584 - Remove dead code in import-headjs-globals. r=tromey (e7b07c59b3)
- Bug 1229224: Support more forms of defining globals and make anywhere we import scripts use them too. r=miker (cf4a3d4d48)
- Bug 1242584 - import-globals-from should carry over to tests. r=tromey (f1f7d7269a)
- Bug 1224735 - only emit one error per possible CPOW use; r=miker,Ms2ger (621dba76e1)
- Bug 1245916: Unify eslint global discovery rules. r=pbrosset (e80d38e097)
- Bug 1246677 - 7 - Clean remaining ruleview and tests eslint warnings; r=jdescottes (9415147b5b)
- Bug 1246677 - 5 - Get rid of 'content' in ruleview test files; r=jdescottes (d868fde632)
- Bug 1209295 - Ensure browser_rules_add-property-cancel_02.js waits for the correct change notification. r=pbrosset (4099437554)
- Bug 1240778 - Fixed the unhandled promise rejection in browser_rules_add-property_01.js; r=ochameau (838bd1f99c)
- Bug 1246677 - 8 - Use addProperty and remove code duplication; r=gl (2c33059028)
- Bug 1246677 - 9 - Get rid of all remaining _applyingModifications usage in tests; r=ochameau (a9bc3b2495)
- Bug 1143742 - part1: multiline inplace editor: cleanup existing tests;r=gl (2bc96e58d3)
- Bug 1243695 - ensure caret is visible in ruleview prop editor;r=miker (3353a5a77c)
- Bug 1143742 - part2: multiline inplace-editor should support a maxWidth option;r=gl (98809c04cb)
- Bug 1178462 - Cancel inplace editor autocomplete on window blur;r=gl (c4af4c03d2)
- Bug 1261827 - inplace-editor: copyTextStyles should not copy line-height property;r=pbro (1fc8d7d432)
- Bug 1069829 - 1 - Remove a usage of domUtils.cssPropertyIsValid in inplace-editor; r=tromey (7898eed84b)
- Bug 1143742 - part3: multiline inplace-editor autocomplete behavior;r=gl (53b369dccb)
- Bug 1143742 - part4: add textarea to valid targets when copying;r=gl (84af495716)
- Bug 1143742 - part5: fix eslint error in inspector ruleview test;r=bustage (d7a53a6217)
- Bug 1249888 - try/catch SourceMapConsumer to avoid empty rule-view when source map is invalid; r=gl (c78a7a6ac7)
- Bug 1255787 - Do not assume sourceMap appears only in external stylesheets; r=gl (7c69e1e559)
- Bug 1029459 - remove output-parser iteration limit. r=pbrosset (f2438a8642)
- Bug 1250835 - Display swatch for angles in the rules panel. r=miker (87721e80f2)
- Bug 1259777 - Remove unnecessary DOMUtils lazy load in css-angle.js . r=pbro (e199a014d5)
- Bug 1259559 - Units cycling with shift+click persists value in Style editor. r=miker (b7074813e9)
- Bug 1245996 - inspector: fix xul scrollbars stealing focus;r=pbro (bcb19ffa83)
- Bug 1180349 - Increase the timeout for browser_markupview_links_01.js (b67cd0d2be)
- Bug 1253935 - Remove all CPOW usages in styleeditor tests and use ContentTask instead of custom frame-script; r=ochameau (485308e7b1)
- Bug 1257246: Update devtools for eslint 2. r=pbro (c04f7f3046)
- Bug 1264968 part 2 - Allow persisting attributes of xul:window if its owner document is not root. r=enndeakin (ca8182b534)
- Bug 1244948 - silence the 'loaded script twice' warning. r=bz (fa571b837c)
2024-08-30 20:58:51 +08:00

1149 lines
31 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/BodyUtil.h"
#include "mozilla/dom/EncodingUtils.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/FetchDriver.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/FormData.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 "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WorkerScope.h"
#include "Workers.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 Runnable
{
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);
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;
}
// Double check that we have chrome privileges if the Request's content
// policy type has been overridden. Note, we must do this before
// entering the global below. Otherwise the IsCallerChrome() will
// always fail.
MOZ_ASSERT_IF(aInput.IsRequest() &&
aInput.GetAsRequest().IsContentPolicyTypeOverridden(),
nsContentUtils::IsCallerChrome());
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<nsPIDOMWindowInner> 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_SUCCEEDS(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();
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);
if (!r->Dispatch()) {
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);
if (!r->Dispatch()) {
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(FormData& 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_NewCStringInputStream(aStream, NS_ConvertUTF16toUTF8(serialized));
}
} // 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()) {
FormData& 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()) {
FormData& 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);
if (!r->Dispatch()) {
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) {
RefPtr<ContinueConsumeBodyRunnable<Derived>> r =
new ContinueConsumeBodyRunnable<Derived>(mFetchBody,
aStatus,
aResultLength,
nonconstResult);
if (!r->Dispatch()) {
// XXXcatalinb: The worker is shutting down, the pump will be canceled
// by FetchBodyFeature::Notify.
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 Runnable
{
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,
NS_LITERAL_CSTRING("Fetch :: Cancel Pump"))
, 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;
bool mWasNotified;
public:
explicit FetchBodyFeature(FetchBody<Derived>* aBody)
: mBody(aBody)
, mWasNotified(false)
{ }
~FetchBodyFeature()
{ }
bool Notify(workers::Status aStatus) override
{
MOZ_ASSERT(aStatus > workers::Running);
if (!mWasNotified) {
mWasNotified = true;
mBody->ContinueConsumeBody(NS_BINDING_ABORTED, 0, nullptr);
}
return true;
}
};
template <class Derived>
FetchBody<Derived>::FetchBody()
: mFeature(nullptr)
, mBodyUsed(false)
#ifdef DEBUG
, mReadDone(false)
#endif
{
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(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(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);
#ifdef DEBUG
mReadDone = true;
#endif
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);
ErrorResult rv;
r->Dispatch(rv);
if (rv.Failed()) {
NS_WARNING("Could not dispatch CancelPumpRunnable. Nothing we can do here");
// None of our callers are callled directly from JS, so there is no
// point in trying to propagate this failure out of here. And
// localPromise is already rejected. Just suppress the failure.
rv.SuppressException();
}
}
}
}
// 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);
BodyUtil::ConsumeArrayBuffer(cx, &arrayBuffer, aResultLength, aResult,
error);
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 = BodyUtil::ConsumeBlob(
DerivedClass()->GetParentObject(), NS_ConvertUTF8toUTF16(mMimeType),
aResultLength, aResult, error);
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<dom::FormData> fd = BodyUtil::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(BodyUtil::ConsumeText(aResultLength, aResult, decoded))) {
if (mConsumeType == CONSUME_TEXT) {
localPromise->MaybeResolve(decoded);
} else {
JS::Rooted<JS::Value> json(cx);
BodyUtil::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()) {
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