Bug 1839315: part 4) Link from `SheetLoadData::mWasAlternate` to spec. r=emilio DONTBUILD
[gecko.git] / layout / style / StreamLoader.cpp
blob51965fcf1263023c26cbf53d0534c3986cdc1405
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/css/StreamLoader.h"
9 #include "mozilla/Encoding.h"
10 #include "mozilla/TaskQueue.h"
11 #include "nsContentUtils.h"
12 #include "nsIChannel.h"
13 #include "nsIInputStream.h"
14 #include "nsIThreadRetargetableRequest.h"
15 #include "nsIStreamTransportService.h"
16 #include "nsNetCID.h"
17 #include "nsServiceManagerUtils.h"
19 #include <limits>
21 namespace mozilla::css {
23 StreamLoader::StreamLoader(SheetLoadData& aSheetLoadData)
24 : mSheetLoadData(&aSheetLoadData), mStatus(NS_OK) {}
26 StreamLoader::~StreamLoader() {
27 #ifdef NIGHTLY_BUILD
28 MOZ_RELEASE_ASSERT(mOnStopRequestCalled || mChannelOpenFailed);
29 #endif
32 NS_IMPL_ISUPPORTS(StreamLoader, nsIStreamListener,
33 nsIThreadRetargetableStreamListener)
35 /* nsIRequestObserver implementation */
36 NS_IMETHODIMP
37 StreamLoader::OnStartRequest(nsIRequest* aRequest) {
38 MOZ_ASSERT(aRequest);
39 mSheetLoadData->NotifyStart(aRequest);
41 // It's kinda bad to let Web content send a number that results
42 // in a potentially large allocation directly, but efficiency of
43 // compression bombs is so great that it doesn't make much sense
44 // to require a site to send one before going ahead and allocating.
45 if (nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest)) {
46 int64_t length;
47 nsresult rv = channel->GetContentLength(&length);
48 if (NS_SUCCEEDED(rv) && length > 0) {
49 CheckedInt<nsACString::size_type> checkedLength(length);
50 if (!checkedLength.isValid()) {
51 return (mStatus = NS_ERROR_OUT_OF_MEMORY);
53 if (!mBytes.SetCapacity(checkedLength.value(), fallible)) {
54 return (mStatus = NS_ERROR_OUT_OF_MEMORY);
58 if (nsCOMPtr<nsIThreadRetargetableRequest> rr = do_QueryInterface(aRequest)) {
59 nsCOMPtr<nsIEventTarget> sts =
60 do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
61 RefPtr queue =
62 TaskQueue::Create(sts.forget(), "css::StreamLoader Delivery Queue");
63 rr->RetargetDeliveryTo(queue);
66 mSheetLoadData->mExpirationTime = [&] {
67 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(
68 aRequest, mSheetLoadData->mURI);
70 // For now, we never cache entries that we have to revalidate, or whose
71 // channel don't support caching.
72 if (info.mMustRevalidate || !info.mExpirationTime) {
73 return nsContentUtils::SecondsFromPRTime(PR_Now()) - 1;
75 return *info.mExpirationTime;
76 }();
78 return NS_OK;
81 NS_IMETHODIMP
82 StreamLoader::CheckListenerChain() { return NS_OK; }
84 NS_IMETHODIMP
85 StreamLoader::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
86 #ifdef NIGHTLY_BUILD
87 MOZ_RELEASE_ASSERT(!mOnStopRequestCalled);
88 mOnStopRequestCalled = true;
89 #endif
91 nsresult rv = mStatus;
92 // Decoded data
93 nsCString utf8String;
95 // Hold the nsStringBuffer for the bytes from the stack to ensure release
96 // no matter which return branch is taken.
97 nsCString bytes = std::move(mBytes);
99 nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
101 if (NS_FAILED(mStatus)) {
102 mSheetLoadData->VerifySheetReadyToParse(mStatus, ""_ns, ""_ns, channel);
103 return mStatus;
106 rv = mSheetLoadData->VerifySheetReadyToParse(aStatus, mBOMBytes, bytes,
107 channel);
108 if (rv != NS_OK_PARSE_SHEET) {
109 return rv;
112 // BOM detection generally happens during the write callback, but that won't
113 // have happened if fewer than three bytes were received.
114 if (mEncodingFromBOM.isNothing()) {
115 HandleBOM();
116 MOZ_ASSERT(mEncodingFromBOM.isSome());
119 // The BOM handling has happened, but we still may not have an encoding if
120 // there was no BOM. Ensure we have one.
121 const Encoding* encoding = mEncodingFromBOM.value();
122 if (!encoding) {
123 // No BOM
124 encoding = mSheetLoadData->DetermineNonBOMEncoding(bytes, channel);
126 mSheetLoadData->mEncoding = encoding;
128 size_t validated = 0;
129 if (encoding == UTF_8_ENCODING) {
130 validated = Encoding::UTF8ValidUpTo(bytes);
133 if (validated == bytes.Length()) {
134 // Either this is UTF-8 and all valid, or it's not UTF-8 but is an empty
135 // string. This assumes that an empty string in any encoding decodes to
136 // empty string, which seems like a plausible assumption.
137 utf8String = std::move(bytes);
138 } else {
139 rv = encoding->DecodeWithoutBOMHandling(bytes, utf8String, validated);
140 NS_ENSURE_SUCCESS(rv, rv);
142 } // run destructor for `bytes`
144 // For reasons I don't understand, factoring the below lines into
145 // a method on SheetLoadData resulted in a linker error. Hence,
146 // accessing fields of mSheetLoadData from here.
147 mSheetLoadData->mLoader->ParseSheet(utf8String, *mSheetLoadData,
148 Loader::AllowAsyncParse::Yes);
150 return NS_OK;
153 /* nsIStreamListener implementation */
154 NS_IMETHODIMP
155 StreamLoader::OnDataAvailable(nsIRequest*, nsIInputStream* aInputStream,
156 uint64_t, uint32_t aCount) {
157 if (NS_FAILED(mStatus)) {
158 return mStatus;
160 uint32_t dummy;
161 return aInputStream->ReadSegments(WriteSegmentFun, this, aCount, &dummy);
164 void StreamLoader::HandleBOM() {
165 MOZ_ASSERT(mEncodingFromBOM.isNothing());
166 MOZ_ASSERT(mBytes.IsEmpty());
168 auto [encoding, bomLength] = Encoding::ForBOM(mBOMBytes);
169 mEncodingFromBOM.emplace(encoding); // Null means no BOM.
171 // BOMs are three bytes at most, but may be fewer. Copy over anything
172 // that wasn't part of the BOM to mBytes. Note that we need to track
173 // any BOM bytes as well for SRI handling.
174 mBytes.Append(Substring(mBOMBytes, bomLength));
175 mBOMBytes.Truncate(bomLength);
178 nsresult StreamLoader::WriteSegmentFun(nsIInputStream*, void* aClosure,
179 const char* aSegment, uint32_t,
180 uint32_t aCount, uint32_t* aWriteCount) {
181 *aWriteCount = 0;
182 StreamLoader* self = static_cast<StreamLoader*>(aClosure);
183 if (NS_FAILED(self->mStatus)) {
184 return self->mStatus;
187 // If we haven't done BOM detection yet, divert bytes into the special buffer.
188 if (self->mEncodingFromBOM.isNothing()) {
189 size_t bytesToCopy = std::min<size_t>(3 - self->mBOMBytes.Length(), aCount);
190 self->mBOMBytes.Append(aSegment, bytesToCopy);
191 aSegment += bytesToCopy;
192 *aWriteCount += bytesToCopy;
193 aCount -= bytesToCopy;
195 if (self->mBOMBytes.Length() == 3) {
196 self->HandleBOM();
197 } else {
198 return NS_OK;
202 if (!self->mBytes.Append(aSegment, aCount, fallible)) {
203 self->mBytes.Truncate();
204 return (self->mStatus = NS_ERROR_OUT_OF_MEMORY);
207 *aWriteCount += aCount;
208 return NS_OK;
211 } // namespace mozilla::css