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"
17 #include "nsServiceManagerUtils.h"
19 namespace mozilla::css
{
21 StreamLoader::StreamLoader(SheetLoadData
& aSheetLoadData
)
22 : mSheetLoadData(&aSheetLoadData
), mStatus(NS_OK
) {}
24 StreamLoader::~StreamLoader() {
26 MOZ_RELEASE_ASSERT(mOnStopRequestCalled
|| mChannelOpenFailed
);
30 NS_IMPL_ISUPPORTS(StreamLoader
, nsIStreamListener
,
31 nsIThreadRetargetableStreamListener
)
33 /* nsIRequestObserver implementation */
35 StreamLoader::OnStartRequest(nsIRequest
* aRequest
) {
37 mSheetLoadData
->NotifyStart(aRequest
);
39 // It's kinda bad to let Web content send a number that results
40 // in a potentially large allocation directly, but efficiency of
41 // compression bombs is so great that it doesn't make much sense
42 // to require a site to send one before going ahead and allocating.
43 if (nsCOMPtr
<nsIChannel
> channel
= do_QueryInterface(aRequest
)) {
45 nsresult rv
= channel
->GetContentLength(&length
);
46 if (NS_SUCCEEDED(rv
) && length
> 0) {
47 CheckedInt
<nsACString::size_type
> checkedLength(length
);
48 if (!checkedLength
.isValid()) {
49 return (mStatus
= NS_ERROR_OUT_OF_MEMORY
);
51 if (!mBytes
.SetCapacity(checkedLength
.value(), fallible
)) {
52 return (mStatus
= NS_ERROR_OUT_OF_MEMORY
);
56 if (nsCOMPtr
<nsIThreadRetargetableRequest
> rr
= do_QueryInterface(aRequest
)) {
57 nsCOMPtr
<nsIEventTarget
> sts
=
58 do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID
);
60 TaskQueue::Create(sts
.forget(), "css::StreamLoader Delivery Queue");
61 rr
->RetargetDeliveryTo(queue
);
64 mSheetLoadData
->mExpirationTime
= [&] {
65 auto info
= nsContentUtils::GetSubresourceCacheValidationInfo(
66 aRequest
, mSheetLoadData
->mURI
);
68 // For now, we never cache entries that we have to revalidate, or whose
69 // channel don't support caching.
70 if (info
.mMustRevalidate
|| !info
.mExpirationTime
) {
71 return nsContentUtils::SecondsFromPRTime(PR_Now()) - 1;
73 return *info
.mExpirationTime
;
80 StreamLoader::CheckListenerChain() { return NS_OK
; }
83 StreamLoader::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
85 MOZ_RELEASE_ASSERT(!mOnStopRequestCalled
);
86 mOnStopRequestCalled
= true;
89 nsresult rv
= mStatus
;
93 // Hold the nsStringBuffer for the bytes from the stack to ensure release
94 // no matter which return branch is taken.
95 nsCString bytes
= std::move(mBytes
);
97 nsCOMPtr
<nsIChannel
> channel
= do_QueryInterface(aRequest
);
99 if (NS_FAILED(mStatus
)) {
100 mSheetLoadData
->VerifySheetReadyToParse(mStatus
, ""_ns
, ""_ns
, channel
);
104 rv
= mSheetLoadData
->VerifySheetReadyToParse(aStatus
, mBOMBytes
, bytes
,
106 if (rv
!= NS_OK_PARSE_SHEET
) {
110 // BOM detection generally happens during the write callback, but that won't
111 // have happened if fewer than three bytes were received.
112 if (mEncodingFromBOM
.isNothing()) {
114 MOZ_ASSERT(mEncodingFromBOM
.isSome());
117 // The BOM handling has happened, but we still may not have an encoding if
118 // there was no BOM. Ensure we have one.
119 const Encoding
* encoding
= mEncodingFromBOM
.value();
122 encoding
= mSheetLoadData
->DetermineNonBOMEncoding(bytes
, channel
);
124 mSheetLoadData
->mEncoding
= encoding
;
126 size_t validated
= 0;
127 if (encoding
== UTF_8_ENCODING
) {
128 validated
= Encoding::UTF8ValidUpTo(bytes
);
131 if (validated
== bytes
.Length()) {
132 // Either this is UTF-8 and all valid, or it's not UTF-8 but is an empty
133 // string. This assumes that an empty string in any encoding decodes to
134 // empty string, which seems like a plausible assumption.
135 utf8String
= std::move(bytes
);
137 rv
= encoding
->DecodeWithoutBOMHandling(bytes
, utf8String
, validated
);
138 NS_ENSURE_SUCCESS(rv
, rv
);
140 } // run destructor for `bytes`
142 // For reasons I don't understand, factoring the below lines into
143 // a method on SheetLoadData resulted in a linker error. Hence,
144 // accessing fields of mSheetLoadData from here.
145 mSheetLoadData
->mLoader
->ParseSheet(utf8String
, *mSheetLoadData
,
146 Loader::AllowAsyncParse::Yes
);
151 /* nsIStreamListener implementation */
153 StreamLoader::OnDataAvailable(nsIRequest
*, nsIInputStream
* aInputStream
,
154 uint64_t, uint32_t aCount
) {
155 if (NS_FAILED(mStatus
)) {
159 return aInputStream
->ReadSegments(WriteSegmentFun
, this, aCount
, &dummy
);
163 StreamLoader::OnDataFinished(nsresult aStatus
) { return NS_OK
; }
165 void StreamLoader::HandleBOM() {
166 MOZ_ASSERT(mEncodingFromBOM
.isNothing());
167 MOZ_ASSERT(mBytes
.IsEmpty());
169 auto [encoding
, bomLength
] = Encoding::ForBOM(mBOMBytes
);
170 mEncodingFromBOM
.emplace(encoding
); // Null means no BOM.
172 // BOMs are three bytes at most, but may be fewer. Copy over anything
173 // that wasn't part of the BOM to mBytes. Note that we need to track
174 // any BOM bytes as well for SRI handling.
175 mBytes
.Append(Substring(mBOMBytes
, bomLength
));
176 mBOMBytes
.Truncate(bomLength
);
179 nsresult
StreamLoader::WriteSegmentFun(nsIInputStream
*, void* aClosure
,
180 const char* aSegment
, uint32_t,
181 uint32_t aCount
, uint32_t* aWriteCount
) {
183 StreamLoader
* self
= static_cast<StreamLoader
*>(aClosure
);
184 if (NS_FAILED(self
->mStatus
)) {
185 return self
->mStatus
;
188 // If we haven't done BOM detection yet, divert bytes into the special buffer.
189 if (self
->mEncodingFromBOM
.isNothing()) {
190 size_t bytesToCopy
= std::min
<size_t>(3 - self
->mBOMBytes
.Length(), aCount
);
191 self
->mBOMBytes
.Append(aSegment
, bytesToCopy
);
192 aSegment
+= bytesToCopy
;
193 *aWriteCount
+= bytesToCopy
;
194 aCount
-= bytesToCopy
;
196 if (self
->mBOMBytes
.Length() == 3) {
203 if (!self
->mBytes
.Append(aSegment
, aCount
, fallible
)) {
204 self
->mBytes
.Truncate();
205 return (self
->mStatus
= NS_ERROR_OUT_OF_MEMORY
);
208 *aWriteCount
+= aCount
;
212 } // namespace mozilla::css