Files
palemoon27/dom/fetch/Request.cpp
T
roytam1 bc8ce42355 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1226200: Don't assume a TCPSocket has only one managee (and rename LoneManagedOrNull) r=jdm (aa2d0fcc14)
- Bug 1227300, Part 1 - Add an alert notification component. r=MattN,wchen (37758ce9ff)
- Bug 1230700. Make Notification::ShowInternal explicitly suppress the exception from GetPermissionInternal. r=smaug (9e288cf5ae)
- Bug 1225336 - Add telemetry about web notification display/messages. r=wchen,kitcambridge p=vladan# Please enter the commit message for your changes. Lines starting (b2e481691a)
- Bug 1219030 - Collect notification management telemetry. r=wchen,MattN; p=ally (c0ba425b4e)
- Bug 1212611 - Use system notification for website notifications in Android. r=mfinkle (84985bcf01)
- Bug 1227300, Part 2 - Implement showAlert. r=MattN,wchen (33eedc7e91)
- Bug 1214305 - Part 0: Ensure site security service is initialized before trying to use DataStorage via IPC. (8bd73f43b0)
- Bug 1137681 - Make user agent docshell overrides affect network requests. r=jduell (e8dabb8338)
- Bug 1233245 - Propagate the interception information in the non-e10s case for all HTTP redirects, not just the internal ones; r=jdm (6922fddcf8)
- Bug 1226444 - Use helper function to identify preloads. r=sicking (d110669f73)
- Bug 1214305 - Part 1: Refactor the logic for querying whether a connection should go through a secure upgrade into NS_ShouldSecureUpgrade; r=mcmanus (2d04c78290)
- Bug 1137681 - Per-tab user agent emulation. r=bz (4ff70db690)
- Bug 1227300, Part 3 - Implement showAlert for the OS X alerts backend. r=mstange (5eb05d0728)
- Bug 1227300, Part 4 - Implement showAlert for the libnotify alerts backend. r=karlt (0942fa2764)
- Bug 1227300, Part 5 - Implement showAlert for the B2G alerts backend. r=mhenretty (e39581aea5)
- Bug 1227300, Part 6 - Use showAlert to display web notifications. r=wchen (ab79eaa0c8)
- domBug 1227300, Part 7 - Update test interfaces. a=testonly (387cb62772)
- Bug 1214305 - Part 3: Add a nsIInterceptedChannel.secureUpgradedChannelURI helper; r=jdm (811d25bd58)
- Bug 1214305 - Part 4: Use the secure upgraded channel URI in ServiceWorkerManager::PrepareFetchEvent; r=jdm (0c44bf527c)
- Bug 1214305 - Part 5: Use the secure upgraded channel URI in FetchEventRunnable::Init; r=jdm (a30f239261)
- Bug 1214305 - Part 6: Use a non-IPC redirect for synthesized upgraded responses to ensure the response URL is correctly propagated; r=mcmanus (8ba8a5728c)
- Bug 1214305 - Part 7: Decide in the child process whether an intercepted channel should go through a secure upgrade; r=mcmanus (93e27decae)
- Bug 1198397 - Add a test for interception of requests upgraded through the CSP upgrade-insecure-requests directive; r=jdm (21eb14eb34)
- Bug 1214305 - Part 8: Enable secure upgrade service worker tests on e10s; r=jdm (c14f5fb504)
- Bug 1214305 - Part 10: Clean up global DataStorage references in the child process; r=keeler (ef0b52d049)
- Bug 1224771 - Close all web notifications when the originating tab is closed. r=wchen (da295b4ba7)
- Bug 1214305 - Part 2: Refactor the logic for obtaining the secure upgraded URI into HttpBaseChannel; r=mcmanus (3346078285)
- Bug 1237151 (part 1) - Remove ignored qualifiers in dom/media/gmp/. r=cpearce. (18134820a6)
- Bug 1237151 (part 2) - Remove ignored qualifiers in WebRTC-relate code. r=jesup. (effe5bd694)
- Bug 1118820 part 1 (style system part) - [css-grid] Implement the 'auto-fill' and 'auto-fit' keywords in the repeat() function. r=dholbert (5db1a577db)
- Bug 1118820 part 2a - [css-grid] Add a LineNameMap class that lets us lookup line names with a dynamic number of 'repeat(auto-fill/auto-fit)' tracks taken into account. r=dholbert (3ecf4b53f0)
- Bug 1118820 part 2b - [css-grid] Move the static functions FindLine/RFindLine/FindNamedLine into the LineNameMap class (idempotent patch). r=dholbert (efb12c594b)
- Bug 1118820 part 2c+2d - [css-grid] Modify the LineNameMap::FindLine/RFindLine/FindNamedLine methods to take line names associated with 'repeat(auto-fill/auto-fit)' tracks into account. Instantiate and pass around a LineNameMap object instead of an array of line name arrays. r=dholbert (a3db750297)
- Bug 1118820 part 3a - [css-grid] Modify TrackSizingFunctions to take a dynamic number of 'repeat(auto-fill/auto-fit)' tracks taking into account. r=dholbert (9aa6033332)
- Bug 1118820 part 3b - [css-grid] Implement the CalculateRepeatFillCount method that calculates the number of 'repeat(auto-fill/auto-fit)' tracks to use for the given sizes. r=dholbert (cf75fab8a8)
- Bug 1118820 part 4 - [css-grid] Provide the sizes to use for CalculateRepeatFillCount. r=dholbert (8184c00dba)
- Bug 1118820 part 5 - [css-grid] Remove any empty 'repeat(auto-fit)' tracks at the end of its range and adjust affected grid area line numbers accordingly. r=dholbert (c02ba6a6e3)
- Bug 1229165 - [css-grid] Reftests for min/max-width/height properties on the grid container. (725097f878)
- Bug 1229999 - [css-grid] Reftest. (51b5bc9535)
- Bug 1237151 (part 3) - Remove ignored qualifiers in all remaining code. r=froydnj. (69917ebbad)
- more bits of  Bug 1178892 - Split the profiler into Core & Gecko files (41bb127b9c)
- Bug 1199841 - Restructure private browsing to remember status after OnStopRequest r=jdm (16c2c1044d)
- Bug 1233845 - Report an interception error and cancel the HTTP channel when encountering a known topcrash situation. r=ehsan (5d08075110)
- Bug 664163 - Fix Get(Local|Remote)(Address|Port) in HttpChannelChild. r=jduell (cbf70af4e8)
- Bug 1229177 - Show the tracking protection shield for fetch and XHR requests. r=jduell (5833b3e872)
- Bug 1220678 Don't crash when DivertToParent() is called on an intercepted channel. r=jdm (5d7ff6ecc8)
- Bug 1220681 P1 Make HttpChannelChild::DivertToParent() work with synthetic responses. r=jdm (67715703ef)
- Bug 1169819 Add browser chrome test to validate SW force refresh. r=ehsan (c0b6b3e874)
- Bug 1220681 P2 Test synthetic responses that trigger downloads. r=ehsan (c701f3ddb1)
- Bug 1220681 P3 Delay diversion on parent side until response head has been synthesized. r=jdm (7c697aacee)
- Bug 1220681 P4 Automatically suspend the parent channel after synthesizing the response for diverison. r=jdm (27f31bcb35)
- Bug 1220681 P5 Don't double suspend parent channel during synthesized divert to parent. r=jdm (62081d4b56)
- Bug 1220681 P6 Use clients.claim() in browser_download.js to avoid worker unregister race. r=jdm (c8de291727)
- Bug 1240161 - Remove "only-if-cached" from RequestCache; r=bkelly (283486f584)
- Bug 1184550 - Add a mochitest for the Request constructor that tests that the body is set to used after being fetched and then fails on the second fetch with the same Request. r=bkelly (db4a967203)
- Bug 1205495 - Correctly use the requests's body and redirect mode in reroute.js; r=nsm (a36a96624a)
- Bug 1189656 - Fix fetch-request-fallback test paths. r=bkelly (366c884179)
- Bug 1219085 - Import the fetch-request-redirect.https.html test from Blink; r=jdm (bf6b484d82)
- Bug 1209081 - Part 1: Implement the "navigate" value for RequestMode; r=bkelly (a22f19d94b)
- Bug 1209081 - Part 2: Upgrade the saved Requests in the DOM Cache to reflect the "navigate" RequestMode if they represent navigation content policy types; r=bkelly (60d1da23bb)
- Bug 1219469 - Part 1: Revert the error reporting added in bug 1233845; r=jdm (dcc022b9d3)
- Bug 1219469 - Part 2: Make HttpChannelParentListener be the controller; r=jdm,jduell (9c5f0dfbe0)
- Bug 1229369 - Intercept redirected network fetches that have their request mode set to manual; r=jdm (fb21d86ed2)
2023-07-25 10:32:23 +08:00

455 lines
12 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Request.h"
#include "nsIURI.h"
#include "nsPIDOMWindow.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/Headers.h"
#include "mozilla/dom/Fetch.h"
#include "mozilla/dom/FetchUtil.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/URL.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/workers/bindings/URL.h"
#include "mozilla/unused.h"
#include "WorkerPrivate.h"
namespace mozilla {
namespace dom {
NS_IMPL_CYCLE_COLLECTING_ADDREF(Request)
NS_IMPL_CYCLE_COLLECTING_RELEASE(Request)
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(Request, mOwner, mHeaders)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Request)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
Request::Request(nsIGlobalObject* aOwner, InternalRequest* aRequest)
: FetchBody<Request>()
, mOwner(aOwner)
, mRequest(aRequest)
{
SetMimeType();
}
Request::~Request()
{
}
// static
bool
Request::RequestContextEnabled(JSContext* aCx, JSObject* aObj)
{
if (NS_IsMainThread()) {
return Preferences::GetBool("dom.requestcontext.enabled", false);
}
using namespace workers;
// Otherwise, check the pref via the WorkerPrivate
WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
if (!workerPrivate) {
return false;
}
return workerPrivate->RequestContextEnabled();
}
// static
bool
Request::RequestCacheEnabled(JSContext* aCx, JSObject* aObj)
{
if (NS_IsMainThread()) {
return Preferences::GetBool("dom.requestcache.enabled", false);
}
using namespace workers;
// Otherwise, check the pref via the WorkerPrivate
WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
if (!workerPrivate) {
return false;
}
return workerPrivate->RequestCacheEnabled();
}
already_AddRefed<InternalRequest>
Request::GetInternalRequest()
{
RefPtr<InternalRequest> r = mRequest;
return r.forget();
}
namespace {
void
GetRequestURLFromDocument(nsIDocument* aDocument, const nsAString& aInput,
nsAString& aRequestURL, ErrorResult& aRv)
{
MOZ_ASSERT(aDocument);
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIURI> baseURI = aDocument->GetBaseURI();
nsCOMPtr<nsIURI> resolvedURI;
aRv = NS_NewURI(getter_AddRefs(resolvedURI), aInput, nullptr, baseURI);
if (NS_WARN_IF(aRv.Failed())) {
aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
return;
}
// This fails with URIs with weird protocols, even when they are valid,
// so we ignore the failure
nsAutoCString credentials;
Unused << resolvedURI->GetUserPass(credentials);
if (!credentials.IsEmpty()) {
aRv.ThrowTypeError<MSG_URL_HAS_CREDENTIALS>(aInput);
return;
}
nsCOMPtr<nsIURI> resolvedURIClone;
// We use CloneIgnoringRef to strip away the fragment even if the original URI
// is immutable.
aRv = resolvedURI->CloneIgnoringRef(getter_AddRefs(resolvedURIClone));
if (NS_WARN_IF(aRv.Failed())) {
return;
}
nsAutoCString spec;
aRv = resolvedURIClone->GetSpec(spec);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
CopyUTF8toUTF16(spec, aRequestURL);
}
void
GetRequestURLFromChrome(const nsAString& aInput, nsAString& aRequestURL,
ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIURI> uri;
aRv = NS_NewURI(getter_AddRefs(uri), aInput, nullptr, nullptr);
if (NS_WARN_IF(aRv.Failed())) {
aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
return;
}
// This fails with URIs with weird protocols, even when they are valid,
// so we ignore the failure
nsAutoCString credentials;
Unused << uri->GetUserPass(credentials);
if (!credentials.IsEmpty()) {
aRv.ThrowTypeError<MSG_URL_HAS_CREDENTIALS>(aInput);
return;
}
nsCOMPtr<nsIURI> uriClone;
// We use CloneIgnoringRef to strip away the fragment even if the original URI
// is immutable.
aRv = uri->CloneIgnoringRef(getter_AddRefs(uriClone));
if (NS_WARN_IF(aRv.Failed())) {
return;
}
nsAutoCString spec;
aRv = uriClone->GetSpec(spec);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
CopyUTF8toUTF16(spec, aRequestURL);
}
void
GetRequestURLFromWorker(const GlobalObject& aGlobal, const nsAString& aInput,
nsAString& aRequestURL, ErrorResult& aRv)
{
workers::WorkerPrivate* worker = workers::GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(worker);
worker->AssertIsOnWorkerThread();
NS_ConvertUTF8toUTF16 baseURL(worker->GetLocationInfo().mHref);
RefPtr<workers::URL> url =
workers::URL::Constructor(aGlobal, aInput, baseURL, aRv);
if (NS_WARN_IF(aRv.Failed())) {
aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
return;
}
nsString username;
url->GetUsername(username, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
nsString password;
url->GetPassword(password, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
if (!username.IsEmpty() || !password.IsEmpty()) {
aRv.ThrowTypeError<MSG_URL_HAS_CREDENTIALS>(aInput);
return;
}
url->SetHash(EmptyString(), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
url->Stringify(aRequestURL, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
}
} // namespace
/*static*/ already_AddRefed<Request>
Request::Constructor(const GlobalObject& aGlobal,
const RequestOrUSVString& aInput,
const RequestInit& aInit, ErrorResult& aRv)
{
nsCOMPtr<nsIInputStream> temporaryBody;
RefPtr<InternalRequest> request;
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
if (aInput.IsRequest()) {
RefPtr<Request> inputReq = &aInput.GetAsRequest();
nsCOMPtr<nsIInputStream> body;
inputReq->GetBody(getter_AddRefs(body));
if (body) {
if (inputReq->BodyUsed()) {
aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
return nullptr;
}
temporaryBody = body;
}
request = inputReq->GetInternalRequest();
} else {
request = new InternalRequest();
}
request = request->GetRequestConstructorCopy(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
RequestMode fallbackMode = RequestMode::EndGuard_;
RequestCredentials fallbackCredentials = RequestCredentials::EndGuard_;
RequestCache fallbackCache = RequestCache::EndGuard_;
if (aInput.IsUSVString()) {
nsAutoString input;
input.Assign(aInput.GetAsUSVString());
nsAutoString requestURL;
if (NS_IsMainThread()) {
nsIDocument* doc = GetEntryDocument();
if (doc) {
GetRequestURLFromDocument(doc, input, requestURL, aRv);
} else {
// If we don't have a document, we must assume that this is a full URL.
GetRequestURLFromChrome(input, requestURL, aRv);
}
} else {
GetRequestURLFromWorker(aGlobal, input, requestURL, aRv);
}
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
request->SetURL(NS_ConvertUTF16toUTF8(requestURL));
fallbackMode = RequestMode::Cors;
fallbackCredentials = RequestCredentials::Omit;
fallbackCache = RequestCache::Default;
}
RequestMode mode = aInit.mMode.WasPassed() ? aInit.mMode.Value() : fallbackMode;
RequestCredentials credentials =
aInit.mCredentials.WasPassed() ? aInit.mCredentials.Value()
: fallbackCredentials;
if (mode == RequestMode::Navigate) {
aRv.ThrowTypeError<MSG_INVALID_REQUEST_MODE>(NS_LITERAL_STRING("navigate"));
return nullptr;
}
if (mode != RequestMode::EndGuard_) {
request->ClearCreatedByFetchEvent();
request->SetMode(mode);
}
if (credentials != RequestCredentials::EndGuard_) {
request->ClearCreatedByFetchEvent();
request->SetCredentialsMode(credentials);
}
RequestCache cache = aInit.mCache.WasPassed() ?
aInit.mCache.Value() : fallbackCache;
if (cache != RequestCache::EndGuard_) {
request->ClearCreatedByFetchEvent();
request->SetCacheMode(cache);
}
if (aInit.mRedirect.WasPassed()) {
request->SetRedirectMode(aInit.mRedirect.Value());
}
// Request constructor step 14.
if (aInit.mMethod.WasPassed()) {
nsAutoCString method(aInit.mMethod.Value());
// Step 14.1. Disallow forbidden methods, and anything that is not a HTTP
// token, since HTTP states that Method may be any of the defined values or
// a token (extension method).
nsAutoCString outMethod;
nsresult rv = FetchUtil::GetValidRequestMethod(method, outMethod);
if (NS_FAILED(rv)) {
NS_ConvertUTF8toUTF16 label(method);
aRv.ThrowTypeError<MSG_INVALID_REQUEST_METHOD>(label);
return nullptr;
}
// Step 14.2
request->ClearCreatedByFetchEvent();
request->SetMethod(outMethod);
}
RefPtr<InternalHeaders> requestHeaders = request->Headers();
RefPtr<InternalHeaders> headers;
if (aInit.mHeaders.WasPassed()) {
RefPtr<Headers> h = Headers::Constructor(aGlobal, aInit.mHeaders.Value(), aRv);
if (aRv.Failed()) {
return nullptr;
}
request->ClearCreatedByFetchEvent();
headers = h->GetInternalHeaders();
} else {
headers = new InternalHeaders(*requestHeaders);
}
requestHeaders->Clear();
// From "Let r be a new Request object associated with request and a new
// Headers object whose guard is "request"."
requestHeaders->SetGuard(HeadersGuardEnum::Request, aRv);
MOZ_ASSERT(!aRv.Failed());
if (request->Mode() == RequestMode::No_cors) {
if (!request->HasSimpleMethod()) {
nsAutoCString method;
request->GetMethod(method);
NS_ConvertUTF8toUTF16 label(method);
aRv.ThrowTypeError<MSG_INVALID_REQUEST_METHOD>(label);
return nullptr;
}
requestHeaders->SetGuard(HeadersGuardEnum::Request_no_cors, aRv);
if (aRv.Failed()) {
return nullptr;
}
}
requestHeaders->Fill(*headers, aRv);
if (aRv.Failed()) {
return nullptr;
}
if (aInit.mBody.WasPassed() || temporaryBody) {
// HEAD and GET are not allowed to have a body.
nsAutoCString method;
request->GetMethod(method);
// method is guaranteed to be uppercase due to step 14.2 above.
if (method.EqualsLiteral("HEAD") || method.EqualsLiteral("GET")) {
aRv.ThrowTypeError<MSG_NO_BODY_ALLOWED_FOR_GET_AND_HEAD>();
return nullptr;
}
}
if (aInit.mBody.WasPassed()) {
const OwningArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams& bodyInit = aInit.mBody.Value();
nsCOMPtr<nsIInputStream> stream;
nsAutoCString contentType;
aRv = ExtractByteStreamFromBody(bodyInit,
getter_AddRefs(stream), contentType);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
temporaryBody = stream;
if (!contentType.IsVoid() &&
!requestHeaders->Has(NS_LITERAL_CSTRING("Content-Type"), aRv)) {
requestHeaders->Append(NS_LITERAL_CSTRING("Content-Type"),
contentType, aRv);
}
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
request->ClearCreatedByFetchEvent();
request->SetBody(temporaryBody);
}
RefPtr<Request> domRequest = new Request(global, request);
domRequest->SetMimeType();
if (aInput.IsRequest()) {
RefPtr<Request> inputReq = &aInput.GetAsRequest();
nsCOMPtr<nsIInputStream> body;
inputReq->GetBody(getter_AddRefs(body));
if (body) {
inputReq->SetBody(nullptr);
inputReq->SetBodyUsed();
}
}
return domRequest.forget();
}
already_AddRefed<Request>
Request::Clone(ErrorResult& aRv) const
{
if (BodyUsed()) {
aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
return nullptr;
}
RefPtr<InternalRequest> ir = mRequest->Clone();
if (!ir) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Request> request = new Request(mOwner, ir);
return request.forget();
}
Headers*
Request::Headers_()
{
if (!mHeaders) {
mHeaders = new Headers(mOwner, mRequest->Headers());
}
return mHeaders;
}
} // namespace dom
} // namespace mozilla