/* -*- 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 mPromiseProxy; public: // Returns null if worker is shutting down. static already_AddRefed Create(workers::WorkerPrivate* aWorkerPrivate, Promise* aPromise) { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); RefPtr proxy = PromiseWorkerProxy::Create(aWorkerPrivate, aPromise); if (!proxy) { return nullptr; } RefPtr 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 mPromise; RefPtr mResponse; NS_DECL_OWNINGTHREAD public: explicit MainThreadFetchResolver(Promise* aPromise); void OnResponseAvailableInternal(InternalResponse* aResponse) override; private: ~MainThreadFetchResolver(); }; class MainThreadFetchRunnable : public Runnable { RefPtr mResolver; RefPtr mRequest; public: MainThreadFetchRunnable(WorkerFetchResolver* aResolver, InternalRequest* aRequest) : mResolver(aResolver) , mRequest(aRequest) { MOZ_ASSERT(mResolver); } NS_IMETHODIMP Run() { AssertIsOnMainThread(); RefPtr proxy = mResolver->mPromiseProxy; MutexAutoLock lock(proxy->Lock()); if (proxy->CleanedUp()) { NS_WARNING("Aborting Fetch because worker already shut down"); return NS_OK; } nsCOMPtr principal = proxy->GetWorkerPrivate()->GetPrincipal(); MOZ_ASSERT(principal); nsCOMPtr loadGroup = proxy->GetWorkerPrivate()->GetLoadGroup(); MOZ_ASSERT(loadGroup); RefPtr 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 FetchRequest(nsIGlobalObject* aGlobal, const RequestOrUSVString& aInput, const RequestInit& aInit, ErrorResult& aRv) { RefPtr 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 jsGlobal(cx, aGlobal->GetGlobalJSObject()); GlobalObject global(cx, jsGlobal); RefPtr request = Request::Constructor(global, aInput, aInit, aRv); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } RefPtr r = request->GetInternalRequest(); if (NS_IsMainThread()) { nsCOMPtr window = do_QueryInterface(aGlobal); nsCOMPtr doc; nsCOMPtr 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 resolver = new MainThreadFetchResolver(p); RefPtr 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 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 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 go = mPromise->GetParentObject(); mResponse = new Response(go, aResponse); mPromise->MaybeResolve(mResponse); } else { ErrorResult result; result.ThrowTypeError(); mPromise->MaybeReject(result); } } MainThreadFetchResolver::~MainThreadFetchResolver() { NS_ASSERT_OWNINGTHREAD(MainThreadFetchResolver); } class WorkerFetchResponseRunnable final : public WorkerRunnable { RefPtr mResolver; // Passed from main thread to worker thread after being initialized. RefPtr mInternalResponse; public: WorkerFetchResponseRunnable(WorkerPrivate* aWorkerPrivate, WorkerFetchResolver* aResolver, InternalResponse* aResponse) : WorkerRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount) , mResolver(aResolver) , mInternalResponse(aResponse) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); RefPtr promise = mResolver->mPromiseProxy->WorkerPromise(); if (mInternalResponse->Type() != ResponseType::Error) { RefPtr global = aWorkerPrivate->GlobalScope(); RefPtr response = new Response(global, mInternalResponse); promise->MaybeResolve(response); } else { ErrorResult result; result.ThrowTypeError(); promise->MaybeReject(result); } return true; } bool PreDispatch(WorkerPrivate* aWorkerPrivate) override { // Don't call default PreDispatch() since it incorrectly asserts we are // dispatching from the parent worker thread. We always dispatch from // the main thread. AssertIsOnMainThread(); return true; } void PostDispatch(WorkerPrivate* aWorkerPrivate, bool aDispatchResult) override { // Don't call default PostDispatch() since it incorrectly asserts we are // dispatching from the parent worker thread. We always dispatch from // the main thread. AssertIsOnMainThread(); } }; class WorkerFetchResponseEndBase { RefPtr mPromiseProxy; public: explicit WorkerFetchResponseEndBase(PromiseWorkerProxy* aPromiseProxy) : mPromiseProxy(aPromiseProxy) { MOZ_ASSERT(mPromiseProxy); } void WorkerRunInternal(WorkerPrivate* aWorkerPrivate) { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); mPromiseProxy->CleanUp(); } }; class WorkerFetchResponseEndRunnable final : public WorkerRunnable , public WorkerFetchResponseEndBase { public: explicit WorkerFetchResponseEndRunnable(PromiseWorkerProxy* aPromiseProxy) : WorkerRunnable(aPromiseProxy->GetWorkerPrivate(), WorkerThreadUnchangedBusyCount) , WorkerFetchResponseEndBase(aPromiseProxy) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override { WorkerRunInternal(aWorkerPrivate); return true; } nsresult Cancel() override { // Execute Run anyway to make sure we cleanup our promise proxy to avoid // leaking the worker thread Run(); return WorkerRunnable::Cancel(); } bool PreDispatch(WorkerPrivate* aWorkerPrivate) override { // Don't call default PreDispatch() since it incorrectly asserts we are // dispatching from the parent worker thread. We always dispatch from // the main thread. AssertIsOnMainThread(); return true; } void PostDispatch(WorkerPrivate* aWorkerPrivate, bool aDispatchResult) override { // Don't call default PostDispatch() since it incorrectly asserts we are // dispatching from the parent worker thread. We always dispatch from // the main thread. AssertIsOnMainThread(); } }; class WorkerFetchResponseEndControlRunnable final : public MainThreadWorkerControlRunnable , public WorkerFetchResponseEndBase { public: explicit WorkerFetchResponseEndControlRunnable(PromiseWorkerProxy* aPromiseProxy) : MainThreadWorkerControlRunnable(aPromiseProxy->GetWorkerPrivate()) , WorkerFetchResponseEndBase(aPromiseProxy) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override { WorkerRunInternal(aWorkerPrivate); return true; } // Control runnable cancel already calls Run(). }; void WorkerFetchResolver::OnResponseAvailableInternal(InternalResponse* aResponse) { AssertIsOnMainThread(); MutexAutoLock lock(mPromiseProxy->Lock()); if (mPromiseProxy->CleanedUp()) { return; } RefPtr 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 r = new WorkerFetchResponseEndRunnable(mPromiseProxy); if (!r->Dispatch()) { RefPtr cr = new WorkerFetchResponseEndControlRunnable(mPromiseProxy); // This can fail if the worker thread is canceled or killed causing // the PromiseWorkerProxy to give up its WorkerFeature immediately, // allowing the worker thread to become Dead. if (!cr->Dispatch()) { NS_WARNING("Failed to dispatch WorkerFetchResponseEndControlRunnable"); } } } 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(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(aBuffer.Data()), aBuffer.Length(), NS_ASSIGNMENT_COPY); } nsresult ExtractFromBlob(const Blob& aBlob, nsIInputStream** aStream, nsCString& aContentType) { RefPtr 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 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 ContinueConsumeBodyRunnable final : public WorkerRunnable { // This has been addrefed before this runnable is dispatched, // released in WorkerRun(). FetchBody* mFetchBody; nsresult mStatus; uint32_t mLength; uint8_t* mResult; public: ContinueConsumeBodyRunnable(FetchBody* aFetchBody, nsresult aStatus, uint32_t aLength, uint8_t* aResult) : WorkerRunnable(aFetchBody->mWorkerPrivate, WorkerThreadUnchangedBusyCount) , 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; } bool PreDispatch(WorkerPrivate* aWorkerPrivate) override { // Don't call default PreDispatch() since it incorrectly asserts we are // dispatching from the parent worker thread. We always dispatch from // the main thread. AssertIsOnMainThread(); return true; } void PostDispatch(WorkerPrivate* aWorkerPrivate, bool aDispatchResult) override { // Don't call default PostDispatch() since it incorrectly asserts we are // dispatching from the parent worker thread. We always dispatch from // the main thread. AssertIsOnMainThread(); } }; // 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() { free(mBuffer); } void Reset() { mBuffer= nullptr; } }; template class FailConsumeBodyWorkerRunnable : public MainThreadWorkerControlRunnable { FetchBody* mBody; public: explicit FailConsumeBodyWorkerRunnable(FetchBody* 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 MOZ_STACK_CLASS AutoFailConsumeBody final { FetchBody* mBody; public: explicit AutoFailConsumeBody(FetchBody* aBody) : mBody(aBody) { } ~AutoFailConsumeBody() { AssertIsOnMainThread(); if (mBody) { if (mBody->mWorkerPrivate) { RefPtr> r = new FailConsumeBodyWorkerRunnable(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 ConsumeBodyDoneObserver : public nsIStreamLoaderObserver { FetchBody* mFetchBody; public: NS_DECL_THREADSAFE_ISUPPORTS explicit ConsumeBodyDoneObserver(FetchBody* 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(aResult); if (mFetchBody->mWorkerPrivate) { RefPtr> r = new ContinueConsumeBodyRunnable(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 NS_IMPL_ADDREF(ConsumeBodyDoneObserver) template NS_IMPL_RELEASE(ConsumeBodyDoneObserver) template NS_INTERFACE_MAP_BEGIN(ConsumeBodyDoneObserver) NS_INTERFACE_MAP_ENTRY(nsIStreamLoaderObserver) NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamLoaderObserver) NS_INTERFACE_MAP_END template class BeginConsumeBodyRunnable final : public Runnable { FetchBody* mFetchBody; public: explicit BeginConsumeBodyRunnable(FetchBody* aBody) : mFetchBody(aBody) { } NS_IMETHOD Run() override { mFetchBody->BeginConsumeBodyMainThread(); return NS_OK; } }; template class CancelPumpRunnable final : public WorkerMainThreadRunnable { FetchBody* mBody; public: explicit CancelPumpRunnable(FetchBody* aBody) : WorkerMainThreadRunnable(aBody->mWorkerPrivate, NS_LITERAL_CSTRING("Fetch :: Cancel Pump")) , mBody(aBody) { } bool MainThreadRun() override { mBody->CancelPump(); return true; } }; } // namespace template 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* mBody; bool mWasNotified; public: explicit FetchBodyFeature(FetchBody* 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 FetchBody::FetchBody() : mFeature(nullptr) , mBodyUsed(false) #ifdef DEBUG , mReadDone(false) #endif { if (!NS_IsMainThread()) { mWorkerPrivate = GetCurrentThreadWorkerPrivate(); MOZ_ASSERT(mWorkerPrivate); } else { mWorkerPrivate = nullptr; } } template FetchBody::FetchBody(); template FetchBody::FetchBody(); template FetchBody::~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 bool FetchBody::AddRefObject() { AssertIsOnTargetThread(); DerivedClass()->AddRef(); if (mWorkerPrivate && !mFeature) { if (!RegisterFeature()) { ReleaseObject(); return false; } } return true; } template void FetchBody::ReleaseObject() { AssertIsOnTargetThread(); if (mWorkerPrivate && mFeature) { UnregisterFeature(); } DerivedClass()->Release(); } template bool FetchBody::RegisterFeature() { MOZ_ASSERT(mWorkerPrivate); mWorkerPrivate->AssertIsOnWorkerThread(); MOZ_ASSERT(!mFeature); mFeature = new FetchBodyFeature(this); if (!mWorkerPrivate->AddFeature(mFeature)) { NS_WARNING("Failed to add feature"); mFeature = nullptr; return false; } return true; } template void FetchBody::UnregisterFeature() { MOZ_ASSERT(mWorkerPrivate); mWorkerPrivate->AssertIsOnWorkerThread(); MOZ_ASSERT(mFeature); mWorkerPrivate->RemoveFeature(mFeature); mFeature = nullptr; } template void FetchBody::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 nsresult FetchBody::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 r = new BeginConsumeBodyRunnable(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 void FetchBody::BeginConsumeBodyMainThread() { AssertIsOnMainThread(); AutoFailConsumeBody autoReject(DerivedClass()); nsresult rv; nsCOMPtr stream; DerivedClass()->GetBody(getter_AddRefs(stream)); if (!stream) { rv = NS_NewCStringInputStream(getter_AddRefs(stream), EmptyCString()); if (NS_WARN_IF(NS_FAILED(rv))) { return; } } nsCOMPtr pump; rv = NS_NewInputStreamPump(getter_AddRefs(pump), stream); if (NS_WARN_IF(NS_FAILED(rv))) { return; } RefPtr> p = new ConsumeBodyDoneObserver(this); nsCOMPtr 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(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 rr = do_QueryInterface(pump); if (rr) { nsCOMPtr sts = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); rv = rr->RetargetDeliveryTo(sts); if (NS_WARN_IF(NS_FAILED(rv))) { NS_WARNING("Retargeting failed"); } } } template void FetchBody::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 localPromise = mConsumePromise.forget(); RefPtr 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> r = new CancelPumpRunnable(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 arrayBuffer(cx); BodyUtil::ConsumeArrayBuffer(cx, &arrayBuffer, aResultLength, aResult, error); if (!error.Failed()) { JS::Rooted val(cx); val.setObjectOrNull(arrayBuffer); localPromise->MaybeResolve(cx, val); // ArrayBuffer takes over ownership. autoFree.Reset(); } break; } case CONSUME_BLOB: { RefPtr 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(aResult), aResultLength); autoFree.Reset(); RefPtr 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 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 already_AddRefed FetchBody::ConsumeBody(ConsumeType aType, ErrorResult& aRv) { mConsumeType = aType; if (BodyUsed()) { aRv.ThrowTypeError(); 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 = mConsumePromise; return promise.forget(); } template already_AddRefed FetchBody::ConsumeBody(ConsumeType aType, ErrorResult& aRv); template already_AddRefed FetchBody::ConsumeBody(ConsumeType aType, ErrorResult& aRv); template void FetchBody::SetMimeType() { // Extract mime type. ErrorResult result; nsTArray 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::SetMimeType(); template void FetchBody::SetMimeType(); } // namespace dom } // namespace mozilla