Files
palemoon27/dom/cache/TypeUtils.cpp
T
roytam1 967126c55b import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1162211 Use sqlite private cache mode in Cache API. r=ehsan (7d91c65569)
- Bug 1220308 Cache API should teardown DOM objects when Worker hits Terminating status. r=baku (a50fd37df1)
- Bug 1144214 - Fix DeleteOrphanedBodyAction so that it doesn't orphan cache files if the action is canceled; r=bkelly (df310a4915)
- Bug 1243849 - Restore support for accessing the Cache API from app://URLs and also for storing requests/responses with app:// URLs within it; r=bkelly (07144da733)
- Bug 1199434 - Fire an event when the print engine encounters an error. r=smaug (e714d1f979)
- Bug 1230092. Make nsIDOMCustomEvent no longer inherit from nsIDOMEvent, so that CustomEvent doesn't end up with multiple inheritance from nsIDOMEvent. r=smaug (cd8e1b5ff5)
- Bug 1177927: Use nsFrameList::GetLength() instead of manual iteration to count pages in nsPrintEngine. r=tn (ddcdde1201)
- Bug 1177927: Use nsFrameList::GetLength() instead of manual iteration to count pages in nsPrintEngine. r=tn (6b8944ab43)
- Bug 1196896 - add CSSLexer.performEOFFixup. r=heycam, r=bz (c5159fc644)
- Bug 1153378 - Move local variable in behind #ifndef MOZILLA_XPCOMRT_API. r=jesup (8e5a9c1c48)
- Bug 1227396: P1. Remove TimestampedMediaByteRange object. r=cpearce (1fae1c62c5)
- Bug 1201404 - Implement minimal gtests to exercise the MPEG4 parser - r=rillian (2a47ebc9e4)
- Bug 1187067 - Added gtests using the bug's test file, running simple checks and many parsing runs to catch parser crashes. r=rillian (71027a9572)
- Bug 1138992: P2. Add gtest. r=kentuckyfriedtakahe (672e0975a1)
- Bug 1200326 - P 1 - Moved test case contents from test source into separate file - r=rillian (e3cdcdd121)
- Bug 1200326 - part 2 - Parse subsets of the input stream - r=rillian (c72577319e)
- Bug 1200326 - p3 - Test case filenames are now in a list, to allow adding more tests - r=rillian (e8a21b4842)
- Bug 1200326 - p4 - Added test case from bug 1200326, with more checks - r=rillian (8befb8260f)
- Bug 1204580 - p1: Added test case files. r=rillian (6573cf686d)
- Bug 1181213 - Added Added mp4 test case to libstagefright gtest - r=rillian (1278f9dc75)
- Bug 1181719 - p1: Added mp4 test case to libstagefright gtest - r=rillian (7ea78da4d9)
- Bug 1181223 - p1: Added mp4 test case to libstagefright gtest - r=rillian (14f0b6c719)
- Bug 1156505 - p1: Added test case file from bug. r=rillian (9d188b3c6a)
- Bug 1181220 - p1: Added mp4 test case to libstagefright gtest - r=rillian (b98029cb8e)
- Bug 1181215 - p1: Added mp4 test case to libstagefright gtest - r=rillian (2c20d374b7)
- Bug 1185230 - p1: Added mp4 test case to libstagefright gtest - r=rillian (e848ebec16)
- Bug 1216748 - p1. Added test case with different 'covr' sizes - r=rillian (1c0097dc85)
- Bug 1224019 - Disable Stagefright subset gtests - r=jya, rs=botond (5ee3e6319c)
- Bug 1227396: P2. Rename some MediaByteRange methods. r=cpearce (3d14aeb56b)
- Bug 1227396: P3. Add IntervalSet::LastInterval method. r=gerald (96b8503a26)
- Bug 1227396: P4. Add IntervalSet::Clear method. r=gerald (460ff0cd8f)
- Bug 1227396: P5. Make Interval::Span ignore empty interval. r=gerald (ba16de0a91)
- Bug 1227396: P6. Replace MediaByteBuffer with Interval<int64_t>. r=cpearce (eed5d5ca5c)
- Bug 1227396: P7. Replace nsTArray<MediaByteRange> with dedicated MediaByteRangeSet object. r=cpearce (ea59b05aea)
- Bug 1188150 - ADTSContainerParser gtest. r=jya (6a4a061647)
- Bug 1227396: P8. Replace MediaByteRange with Interval<int64_t> typedef. r=cpearce (4d3e657b3b)
- Bug 1219047 - Call rust mp4parser with logging. r=kinetik (70abf59813)
- Bug 1220882 - Use LazyLogModule in MP4Metadata. r=kinetik (3443b56be3)
- Bug 1220885 - Add telemetry probe for rust mp4parse success. r=kinetik p=ally (c012bd11bf)
- Bug 1174356 - Add missing MediaData include. r=jya (bfe6182cfe)
- Bug 1227396: P9. Remove unnecessary monitor. r=cpearce (4f156658c4)
- Bug 1227396: P10: Remove stray function definition. r=cpearce (4c1641560c)
- Bug 1227396: P11. Add IntervalSet::operator- operand. r=gerald (b56ceb52f4)
- Bug 1227396: P12. Use MediaByteRangeSet capabilities to filter already processed data. r=cpearce (098d8852d9)
- Bug 1227396: P13. Refactor how MP4 buffered range is calculated. r=cpearce (66711bd76f)
- Bug 1227396: P14. Reduce memory usage of sample index for audio tracks. r=cpearce (e1c36bd791)
- Bug 1197007: Turn off optimization for GMPLoaderImpl::Load. r=cpearce (5df0a365c7)
- Bug 1208892 - Replace the uses of memset to clean up data in GMPLoader::Load with an inline memset; r=cpearce (ce4f3a3a64)
- Bug 1187031: Move back to using USER_LOCKDOWN for the GMP sandbox policy on Windows. r=aklotz (53c39be48d)
- Bug 1214018 - p1: Using vector to pass machine id - r=cpearce (19782ec5b3)
- Bug 1214018 - p2: Import machine_id_mac.cc from Chromium repo - r=cpearce (000d4734ab)
- Bug 1214018 - p3: Modify machine_id_mac for FF build - r=cpearce (41818ddc72)
- Bug 1214018 - p4: Use machine_id_mac in GMPLoader - r=cpearce (4af56e5a6e)
- Bug 1220326 - Wipe stack after Mac node id generation. r=jrmuizel (8c94ddab25)
- Bug 1181718 - Fallible allocation of blank audio data - r=jya (7867407417)
- Bug 1229963 - use UniquePtr<T[]> instead of nsAutoArrayPtr<T> in dom/media/; r=cpearce (796241f002)
- Bug 1229965 - Use MakeUniqueFallible in blank decoder - r=jya (bac70f5c80)
- Bug 1139256 - remove the assertion in AudioStream::GetPositionInFramesUnlocked(). See bug 1139256 comment 4 for the detail. r=kinetik. (6e386c7b00)
- missing bits (1dc7b00da3)
- Bug 1185115: P2. replace all stagefright::Vector with nsTArray. r=kentuckyfriedtakahe (de4e57b4cd)
- Bug 1181223 - p2: Handle wrong saio/saiz size instead of assuming it is correct - r=rillian (59f5afa21f)
- Bug 1138992: P1. Ignore ctts version if we have 0 samples in the table. r=kentuckyfriedtakahe (efb86ce02d)
- Bug 1216845 - Check fallible allocations - r=rillian (fac4210e2a)
- Bug 1229615 - Compare track counts between rust and stagefright. r=rillian (1b7ee2e4a8)
- Bug 1219475 - Fix a comparison warning. r=gerald (2efe7f952d)
- Bug 1181719 - p2: Check numBitsLeft before each getBits - r=rillian (f7bd7039ed)
- Bug 1187067 - Null-check mLastTrack before dereferencing it - r=rillian (e2d99073ff)
- Bug 1181220 - p2: Check if MIME types are valid - r=rillian (c1d1254f6d)
- Bug 1185230 - p2: Store MPEG4Source::mTimescale as uint32_t - r=rillian (21d124ab25)
- Bug 1207909 - p1: Fixed ALOGV statement - r=jya (0aef385b41)
- Bug 1207909 - p2: Fixed a warning (uninitialized 'err') and typo - r=jya (a9c157feda)
- partial remove of hack (59ca36fbd4)
- Bug 1156505 - p2: Null-check sampleTable before use. r=rillian (ab18d1d939)
- Bug 1181215 - p2: Better track verification - r=rillian (d61d5914aa)
- Bug 1210319 - p1. Removed unused code - r=rillian (4c0b33fc59)
- Bug 1210319 - p2. Minor intf clean-up, RIP trex - r=rillian (27aaf6ae80)
- Bug 1229134: Check that memory allocation actually succeeded. r=gerald (b6587bc900)
- Bug 1209388: [mp3] Remove AppleMP3Reader. r=kentuckyfriedtakahe (e81f265901)
- Bug 1198576 - Remove MediaCodecReader. r=bwu (e867950ff4)
- Bug 1191833: P1. Properly check webm mimetype against codec type. r=cpearce (9b27b8064a)
- Bug 1229605: [MSE] Allow webm/audio independently of video. r=kentuckyfriedtakahe (7b79dfaf4c)
- Bug 1229339: Partial revert of commit c15c9f37f. r=cpearce (90fa115b64)
2023-05-04 10:41:24 +08:00

569 lines
16 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 "mozilla/dom/cache/TypeUtils.h"
#include "mozilla/unused.h"
#include "mozilla/dom/CacheBinding.h"
#include "mozilla/dom/InternalRequest.h"
#include "mozilla/dom/Request.h"
#include "mozilla/dom/Response.h"
#include "mozilla/dom/cache/CachePushStreamChild.h"
#include "mozilla/dom/cache/CacheTypes.h"
#include "mozilla/dom/cache/ReadStream.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/PFileDescriptorSetChild.h"
#include "mozilla/ipc/InputStreamUtils.h"
#include "nsCOMPtr.h"
#include "nsIAsyncInputStream.h"
#include "nsIAsyncOutputStream.h"
#include "nsIIPCSerializableInputStream.h"
#include "nsQueryObject.h"
#include "nsPromiseFlatString.h"
#include "nsStreamUtils.h"
#include "nsString.h"
#include "nsURLParsers.h"
#include "nsCRT.h"
#include "nsHttp.h"
namespace mozilla {
namespace dom {
namespace cache {
using mozilla::ipc::BackgroundChild;
using mozilla::ipc::FileDescriptor;
using mozilla::ipc::PBackgroundChild;
using mozilla::ipc::PFileDescriptorSetChild;
namespace {
static bool
HasVaryStar(mozilla::dom::InternalHeaders* aHeaders)
{
nsAutoTArray<nsCString, 16> varyHeaders;
ErrorResult rv;
aHeaders->GetAll(NS_LITERAL_CSTRING("vary"), varyHeaders, rv);
MOZ_ALWAYS_TRUE(!rv.Failed());
for (uint32_t i = 0; i < varyHeaders.Length(); ++i) {
nsAutoCString varyValue(varyHeaders[i]);
char* rawBuffer = varyValue.BeginWriting();
char* token = nsCRT::strtok(rawBuffer, NS_HTTP_HEADER_SEPS, &rawBuffer);
for (; token;
token = nsCRT::strtok(rawBuffer, NS_HTTP_HEADER_SEPS, &rawBuffer)) {
nsDependentCString header(token);
if (header.EqualsLiteral("*")) {
return true;
}
}
}
return false;
}
void
SerializeNormalStream(nsIInputStream* aStream, CacheReadStream& aReadStreamOut)
{
nsAutoTArray<FileDescriptor, 4> fds;
SerializeInputStream(aStream, aReadStreamOut.params(), fds);
PFileDescriptorSetChild* fdSet = nullptr;
if (!fds.IsEmpty()) {
// We should not be serializing until we have an actor ready
PBackgroundChild* manager = BackgroundChild::GetForCurrentThread();
MOZ_ASSERT(manager);
fdSet = manager->SendPFileDescriptorSetConstructor(fds[0]);
for (uint32_t i = 1; i < fds.Length(); ++i) {
Unused << fdSet->SendAddFileDescriptor(fds[i]);
}
}
if (fdSet) {
aReadStreamOut.fds() = fdSet;
} else {
aReadStreamOut.fds() = void_t();
}
}
void
ToHeadersEntryList(nsTArray<HeadersEntry>& aOut, InternalHeaders* aHeaders)
{
MOZ_ASSERT(aHeaders);
nsAutoTArray<InternalHeaders::Entry, 16> entryList;
aHeaders->GetEntries(entryList);
for (uint32_t i = 0; i < entryList.Length(); ++i) {
InternalHeaders::Entry& entry = entryList[i];
aOut.AppendElement(HeadersEntry(entry.mName, entry.mValue));
}
}
} // namespace
already_AddRefed<InternalRequest>
TypeUtils::ToInternalRequest(const RequestOrUSVString& aIn,
BodyAction aBodyAction, ErrorResult& aRv)
{
if (aIn.IsRequest()) {
Request& request = aIn.GetAsRequest();
// Check and set bodyUsed flag immediately because its on Request
// instead of InternalRequest.
CheckAndSetBodyUsed(&request, aBodyAction, aRv);
if (aRv.Failed()) { return nullptr; }
return request.GetInternalRequest();
}
return ToInternalRequest(aIn.GetAsUSVString(), aRv);
}
already_AddRefed<InternalRequest>
TypeUtils::ToInternalRequest(const OwningRequestOrUSVString& aIn,
BodyAction aBodyAction, ErrorResult& aRv)
{
if (aIn.IsRequest()) {
RefPtr<Request> request = aIn.GetAsRequest().get();
// Check and set bodyUsed flag immediately because its on Request
// instead of InternalRequest.
CheckAndSetBodyUsed(request, aBodyAction, aRv);
if (aRv.Failed()) { return nullptr; }
return request->GetInternalRequest();
}
return ToInternalRequest(aIn.GetAsUSVString(), aRv);
}
void
TypeUtils::ToCacheRequest(CacheRequest& aOut, InternalRequest* aIn,
BodyAction aBodyAction, SchemeAction aSchemeAction,
ErrorResult& aRv)
{
MOZ_ASSERT(aIn);
aIn->GetMethod(aOut.method());
nsAutoCString url;
aIn->GetURL(url);
bool schemeValid;
ProcessURL(url, &schemeValid, &aOut.urlWithoutQuery(), &aOut.urlQuery(), aRv);
if (aRv.Failed()) {
return;
}
if (!schemeValid) {
if (aSchemeAction == TypeErrorOnInvalidScheme) {
NS_ConvertUTF8toUTF16 urlUTF16(url);
aRv.ThrowTypeError<MSG_INVALID_URL_SCHEME>(NS_LITERAL_STRING("Request"),
urlUTF16);
return;
}
}
aIn->GetReferrer(aOut.referrer());
RefPtr<InternalHeaders> headers = aIn->Headers();
MOZ_ASSERT(headers);
ToHeadersEntryList(aOut.headers(), headers);
aOut.headersGuard() = headers->Guard();
aOut.mode() = aIn->Mode();
aOut.credentials() = aIn->GetCredentialsMode();
aOut.contentPolicyType() = aIn->ContentPolicyType();
aOut.requestCache() = aIn->GetCacheMode();
aOut.requestRedirect() = aIn->GetRedirectMode();
if (aBodyAction == IgnoreBody) {
aOut.body() = void_t();
return;
}
// BodyUsed flag is checked and set previously in ToInternalRequest()
nsCOMPtr<nsIInputStream> stream;
aIn->GetBody(getter_AddRefs(stream));
SerializeCacheStream(stream, &aOut.body(), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
}
void
TypeUtils::ToCacheResponseWithoutBody(CacheResponse& aOut,
InternalResponse& aIn, ErrorResult& aRv)
{
aOut.type() = aIn.Type();
aIn.GetUnfilteredUrl(aOut.url());
if (aOut.url() != EmptyCString()) {
// Pass all Response URL schemes through... The spec only requires we take
// action on invalid schemes for Request objects.
ProcessURL(aOut.url(), nullptr, nullptr, nullptr, aRv);
if (aRv.Failed()) {
return;
}
}
aOut.status() = aIn.GetUnfilteredStatus();
aOut.statusText() = aIn.GetUnfilteredStatusText();
RefPtr<InternalHeaders> headers = aIn.UnfilteredHeaders();
MOZ_ASSERT(headers);
if (HasVaryStar(headers)) {
aRv.ThrowTypeError<MSG_RESPONSE_HAS_VARY_STAR>();
return;
}
ToHeadersEntryList(aOut.headers(), headers);
aOut.headersGuard() = headers->Guard();
aOut.channelInfo() = aIn.GetChannelInfo().AsIPCChannelInfo();
if (aIn.GetPrincipalInfo()) {
aOut.principalInfo() = *aIn.GetPrincipalInfo();
} else {
aOut.principalInfo() = void_t();
}
}
void
TypeUtils::ToCacheResponse(CacheResponse& aOut, Response& aIn, ErrorResult& aRv)
{
if (aIn.BodyUsed()) {
aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
return;
}
RefPtr<InternalResponse> ir = aIn.GetInternalResponse();
ToCacheResponseWithoutBody(aOut, *ir, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
nsCOMPtr<nsIInputStream> stream;
ir->GetUnfilteredBody(getter_AddRefs(stream));
if (stream) {
aIn.SetBodyUsed();
}
SerializeCacheStream(stream, &aOut.body(), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
}
// static
void
TypeUtils::ToCacheQueryParams(CacheQueryParams& aOut,
const CacheQueryOptions& aIn)
{
aOut.ignoreSearch() = aIn.mIgnoreSearch;
aOut.ignoreMethod() = aIn.mIgnoreMethod;
aOut.ignoreVary() = aIn.mIgnoreVary;
aOut.cacheNameSet() = aIn.mCacheName.WasPassed();
if (aOut.cacheNameSet()) {
aOut.cacheName() = aIn.mCacheName.Value();
} else {
aOut.cacheName() = NS_LITERAL_STRING("");
}
}
already_AddRefed<Response>
TypeUtils::ToResponse(const CacheResponse& aIn)
{
if (aIn.type() == ResponseType::Error) {
RefPtr<InternalResponse> error = InternalResponse::NetworkError();
RefPtr<Response> r = new Response(GetGlobalObject(), error);
return r.forget();
}
RefPtr<InternalResponse> ir = new InternalResponse(aIn.status(),
aIn.statusText());
ir->SetUrl(aIn.url());
RefPtr<InternalHeaders> internalHeaders =
ToInternalHeaders(aIn.headers(), aIn.headersGuard());
ErrorResult result;
ir->Headers()->SetGuard(aIn.headersGuard(), result);
MOZ_ASSERT(!result.Failed());
ir->Headers()->Fill(*internalHeaders, result);
MOZ_ASSERT(!result.Failed());
ir->InitChannelInfo(aIn.channelInfo());
if (aIn.principalInfo().type() == mozilla::ipc::OptionalPrincipalInfo::TPrincipalInfo) {
UniquePtr<mozilla::ipc::PrincipalInfo> info(new mozilla::ipc::PrincipalInfo(aIn.principalInfo().get_PrincipalInfo()));
ir->SetPrincipalInfo(Move(info));
}
nsCOMPtr<nsIInputStream> stream = ReadStream::Create(aIn.body());
ir->SetBody(stream);
switch (aIn.type())
{
case ResponseType::Basic:
ir = ir->BasicResponse();
break;
case ResponseType::Cors:
ir = ir->CORSResponse();
break;
case ResponseType::Default:
break;
case ResponseType::Opaque:
ir = ir->OpaqueResponse();
break;
case ResponseType::Opaqueredirect:
ir = ir->OpaqueRedirectResponse();
break;
default:
MOZ_CRASH("Unexpected ResponseType!");
}
MOZ_ASSERT(ir);
RefPtr<Response> ref = new Response(GetGlobalObject(), ir);
return ref.forget();
}
already_AddRefed<InternalRequest>
TypeUtils::ToInternalRequest(const CacheRequest& aIn)
{
RefPtr<InternalRequest> internalRequest = new InternalRequest();
internalRequest->SetMethod(aIn.method());
nsAutoCString url(aIn.urlWithoutQuery());
url.Append(aIn.urlQuery());
internalRequest->SetURL(url);
internalRequest->SetReferrer(aIn.referrer());
internalRequest->SetMode(aIn.mode());
internalRequest->SetCredentialsMode(aIn.credentials());
internalRequest->SetContentPolicyType(aIn.contentPolicyType());
internalRequest->SetCacheMode(aIn.requestCache());
internalRequest->SetRedirectMode(aIn.requestRedirect());
RefPtr<InternalHeaders> internalHeaders =
ToInternalHeaders(aIn.headers(), aIn.headersGuard());
ErrorResult result;
// Be careful to fill the headers before setting the guard in order to
// correctly re-create the original headers.
internalRequest->Headers()->Fill(*internalHeaders, result);
MOZ_ASSERT(!result.Failed());
internalRequest->Headers()->SetGuard(aIn.headersGuard(), result);
MOZ_ASSERT(!result.Failed());
nsCOMPtr<nsIInputStream> stream = ReadStream::Create(aIn.body());
internalRequest->SetBody(stream);
return internalRequest.forget();
}
already_AddRefed<Request>
TypeUtils::ToRequest(const CacheRequest& aIn)
{
RefPtr<InternalRequest> internalRequest = ToInternalRequest(aIn);
RefPtr<Request> request = new Request(GetGlobalObject(), internalRequest);
return request.forget();
}
// static
already_AddRefed<InternalHeaders>
TypeUtils::ToInternalHeaders(const nsTArray<HeadersEntry>& aHeadersEntryList,
HeadersGuardEnum aGuard)
{
nsTArray<InternalHeaders::Entry> entryList(aHeadersEntryList.Length());
for (uint32_t i = 0; i < aHeadersEntryList.Length(); ++i) {
const HeadersEntry& headersEntry = aHeadersEntryList[i];
entryList.AppendElement(InternalHeaders::Entry(headersEntry.name(),
headersEntry.value()));
}
RefPtr<InternalHeaders> ref = new InternalHeaders(Move(entryList), aGuard);
return ref.forget();
}
// Utility function to remove the fragment from a URL, check its scheme, and optionally
// provide a URL without the query. We're not using nsIURL or URL to do this because
// they require going to the main thread.
// static
void
TypeUtils::ProcessURL(nsACString& aUrl, bool* aSchemeValidOut,
nsACString* aUrlWithoutQueryOut,nsACString* aUrlQueryOut,
ErrorResult& aRv)
{
const nsAFlatCString& flatURL = PromiseFlatCString(aUrl);
const char* url = flatURL.get();
// off the main thread URL parsing using nsStdURLParser.
nsCOMPtr<nsIURLParser> urlParser = new nsStdURLParser();
uint32_t pathPos;
int32_t pathLen;
uint32_t schemePos;
int32_t schemeLen;
aRv = urlParser->ParseURL(url, flatURL.Length(), &schemePos, &schemeLen,
nullptr, nullptr, // ignore authority
&pathPos, &pathLen);
if (NS_WARN_IF(aRv.Failed())) { return; }
if (aSchemeValidOut) {
nsAutoCString scheme(Substring(flatURL, schemePos, schemeLen));
*aSchemeValidOut = scheme.LowerCaseEqualsLiteral("http") ||
scheme.LowerCaseEqualsLiteral("https") ||
scheme.LowerCaseEqualsLiteral("app");
}
uint32_t queryPos;
int32_t queryLen;
aRv = urlParser->ParsePath(url + pathPos, flatURL.Length() - pathPos,
nullptr, nullptr, // ignore filepath
&queryPos, &queryLen,
nullptr, nullptr);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
if (!aUrlWithoutQueryOut) {
return;
}
MOZ_ASSERT(aUrlQueryOut);
if (queryLen < 0) {
*aUrlWithoutQueryOut = aUrl;
*aUrlQueryOut = EmptyCString();
return;
}
// ParsePath gives us query position relative to the start of the path
queryPos += pathPos;
*aUrlWithoutQueryOut = Substring(aUrl, 0, queryPos - 1);
*aUrlQueryOut = Substring(aUrl, queryPos - 1, queryLen + 1);
}
void
TypeUtils::CheckAndSetBodyUsed(Request* aRequest, BodyAction aBodyAction,
ErrorResult& aRv)
{
MOZ_ASSERT(aRequest);
if (aBodyAction == IgnoreBody) {
return;
}
if (aRequest->BodyUsed()) {
aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
return;
}
nsCOMPtr<nsIInputStream> stream;
aRequest->GetBody(getter_AddRefs(stream));
if (stream) {
aRequest->SetBodyUsed();
}
}
already_AddRefed<InternalRequest>
TypeUtils::ToInternalRequest(const nsAString& aIn, ErrorResult& aRv)
{
RequestOrUSVString requestOrString;
requestOrString.SetAsUSVString().Rebind(aIn.Data(), aIn.Length());
// Re-create a GlobalObject stack object so we can use webidl Constructors.
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.Init(GetGlobalObject()))) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
JSContext* cx = jsapi.cx();
GlobalObject global(cx, GetGlobalObject()->GetGlobalJSObject());
MOZ_ASSERT(!global.Failed());
RefPtr<Request> request = Request::Constructor(global, requestOrString,
RequestInit(), aRv);
if (NS_WARN_IF(aRv.Failed())) { return nullptr; }
return request->GetInternalRequest();
}
void
TypeUtils::SerializeCacheStream(nsIInputStream* aStream,
CacheReadStreamOrVoid* aStreamOut,
ErrorResult& aRv)
{
*aStreamOut = void_t();
if (!aStream) {
return;
}
// Option 1: Send a cache-specific ReadStream if we can.
RefPtr<ReadStream> controlled = do_QueryObject(aStream);
if (controlled) {
controlled->Serialize(aStreamOut);
return;
}
CacheReadStream readStream;
readStream.controlChild() = nullptr;
readStream.controlParent() = nullptr;
readStream.pushStreamChild() = nullptr;
readStream.pushStreamParent() = nullptr;
// Option 2: Do normal stream serialization if its supported.
nsCOMPtr<nsIIPCSerializableInputStream> serial = do_QueryInterface(aStream);
if (serial) {
SerializeNormalStream(aStream, readStream);
// Option 3: As a last resort push data across manually. Should only be
// needed for nsPipe input stream. Only works for async,
// non-blocking streams.
} else {
SerializePushStream(aStream, readStream, aRv);
if (NS_WARN_IF(aRv.Failed())) { return; }
}
*aStreamOut = readStream;
}
void
TypeUtils::SerializePushStream(nsIInputStream* aStream,
CacheReadStream& aReadStreamOut,
ErrorResult& aRv)
{
nsCOMPtr<nsIAsyncInputStream> asyncStream = do_QueryInterface(aStream);
if (NS_WARN_IF(!asyncStream)) {
aRv = NS_ERROR_FAILURE;
return;
}
bool nonBlocking = false;
aRv = asyncStream->IsNonBlocking(&nonBlocking);
if (NS_WARN_IF(aRv.Failed())) { return; }
if (NS_WARN_IF(!nonBlocking)) {
aRv = NS_ERROR_FAILURE;
return;
}
aReadStreamOut.pushStreamChild() = CreatePushStream(asyncStream);
MOZ_ASSERT(aReadStreamOut.pushStreamChild());
aReadStreamOut.params() = void_t();
aReadStreamOut.fds() = void_t();
// CachePushStreamChild::Start() must be called after sending the stream
// across to the parent side.
}
} // namespace cache
} // namespace dom
} // namespace mozilla