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"
21 namespace mozilla::css
{
23 StreamLoader::StreamLoader(SheetLoadData
& aSheetLoadData
)
24 : mSheetLoadData(&aSheetLoadData
), mStatus(NS_OK
) {}
26 StreamLoader::~StreamLoader() {
28 MOZ_RELEASE_ASSERT(mOnStopRequestCalled
|| mChannelOpenFailed
);
32 NS_IMPL_ISUPPORTS(StreamLoader
, nsIStreamListener
,
33 nsIThreadRetargetableStreamListener
)
35 /* nsIRequestObserver implementation */
37 StreamLoader::OnStartRequest(nsIRequest
* 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
)) {
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
);
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
;
82 StreamLoader::CheckListenerChain() { return NS_OK
; }
85 StreamLoader::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
87 MOZ_RELEASE_ASSERT(!mOnStopRequestCalled
);
88 mOnStopRequestCalled
= true;
91 nsresult rv
= mStatus
;
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
);
106 rv
= mSheetLoadData
->VerifySheetReadyToParse(aStatus
, mBOMBytes
, bytes
,
108 if (rv
!= NS_OK_PARSE_SHEET
) {
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()) {
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();
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
);
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
);
153 /* nsIStreamListener implementation */
155 StreamLoader::OnDataAvailable(nsIRequest
*, nsIInputStream
* aInputStream
,
156 uint64_t, uint32_t aCount
) {
157 if (NS_FAILED(mStatus
)) {
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
) {
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) {
202 if (!self
->mBytes
.Append(aSegment
, aCount
, fallible
)) {
203 self
->mBytes
.Truncate();
204 return (self
->mStatus
= NS_ERROR_OUT_OF_MEMORY
);
207 *aWriteCount
+= aCount
;
211 } // namespace mozilla::css