1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
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 "imgRequest.h"
8 #include "ImageLogging.h"
10 #include "imgLoader.h"
11 #include "imgRequestProxy.h"
12 #include "DecodePool.h"
13 #include "ProgressTracker.h"
14 #include "ImageFactory.h"
16 #include "MultipartImage.h"
17 #include "RasterImage.h"
19 #include "nsIChannel.h"
20 #include "nsICacheInfoChannel.h"
21 #include "nsIClassOfService.h"
22 #include "mozilla/dom/Document.h"
23 #include "nsIThreadRetargetableRequest.h"
24 #include "nsIInputStream.h"
25 #include "nsIMultiPartChannel.h"
26 #include "nsIHttpChannel.h"
27 #include "nsMimeTypes.h"
29 #include "nsIInterfaceRequestorUtils.h"
30 #include "nsISupportsPrimitives.h"
31 #include "nsIScriptSecurityManager.h"
32 #include "nsComponentManagerUtils.h"
33 #include "nsContentUtils.h"
36 #include "prtime.h" // for PR_Now
37 #include "nsNetUtil.h"
38 #include "nsIProtocolHandler.h"
39 #include "imgIRequest.h"
40 #include "nsProperties.h"
43 #include "mozilla/IntegerPrintfMacros.h"
44 #include "mozilla/SizeOfState.h"
46 using namespace mozilla
;
47 using namespace mozilla::image
;
49 #define LOG_TEST(level) (MOZ_LOG_TEST(gImgLog, (level)))
51 NS_IMPL_ISUPPORTS(imgRequest
, nsIStreamListener
, nsIRequestObserver
,
52 nsIThreadRetargetableStreamListener
, nsIChannelEventSink
,
53 nsIInterfaceRequestor
, nsIAsyncVerifyRedirectCallback
)
55 imgRequest::imgRequest(imgLoader
* aLoader
, const ImageCacheKey
& aCacheKey
)
62 mImageErrorCode(NS_OK
),
63 mImageAvailable(false),
64 mIsDeniedCrossSiteCORSRequest(false),
65 mIsCrossSiteNoCORSRequest(false),
66 mShouldReportRenderTimeForLCP(false),
68 mProgressTracker(new ProgressTracker()),
69 mIsMultiPartChannel(false),
71 mDecodeRequested(false),
72 mNewPartPending(false),
73 mHadInsecureRedirect(false),
75 LOG_FUNC(gImgLog
, "imgRequest::imgRequest()");
78 imgRequest::~imgRequest() {
80 mLoader
->RemoveFromUncachedImages(this);
83 LOG_FUNC_WITH_PARAM(gImgLog
, "imgRequest::~imgRequest()", "keyuri", mURI
);
85 LOG_FUNC(gImgLog
, "imgRequest::~imgRequest()");
88 nsresult
imgRequest::Init(
89 nsIURI
* aURI
, nsIURI
* aFinalURI
, bool aHadInsecureRedirect
,
90 nsIRequest
* aRequest
, nsIChannel
* aChannel
, imgCacheEntry
* aCacheEntry
,
91 mozilla::dom::Document
* aLoadingDocument
,
92 nsIPrincipal
* aTriggeringPrincipal
, mozilla::CORSMode aCORSMode
,
93 nsIReferrerInfo
* aReferrerInfo
) MOZ_NO_THREAD_SAFETY_ANALYSIS
{
94 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
95 // Init() can only be called once, and that's before it can be used off
98 LOG_FUNC(gImgLog
, "imgRequest::Init");
100 MOZ_ASSERT(!mImage
, "Multiple calls to init");
101 MOZ_ASSERT(aURI
, "No uri");
102 MOZ_ASSERT(aFinalURI
, "No final uri");
103 MOZ_ASSERT(aRequest
, "No request");
104 MOZ_ASSERT(aChannel
, "No channel");
106 mProperties
= new nsProperties();
108 mFinalURI
= aFinalURI
;
111 mTimedChannel
= do_QueryInterface(mChannel
);
112 mTriggeringPrincipal
= aTriggeringPrincipal
;
113 mCORSMode
= aCORSMode
;
114 mReferrerInfo
= aReferrerInfo
;
116 // If the original URI and the final URI are different, check whether the
117 // original URI is secure. We deliberately don't take the final URI into
118 // account, as it needs to be handled using more complicated rules than
119 // earlier elements of the redirect chain.
120 if (aURI
!= aFinalURI
) {
121 bool schemeLocal
= false;
122 if (NS_FAILED(NS_URIChainHasFlags(
123 aURI
, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
, &schemeLocal
)) ||
124 (!aURI
->SchemeIs("https") && !aURI
->SchemeIs("chrome") &&
126 mHadInsecureRedirect
= true;
130 // imgCacheValidator may have handled redirects before we were created, so we
131 // allow the caller to let us know if any redirects were insecure.
132 mHadInsecureRedirect
= mHadInsecureRedirect
|| aHadInsecureRedirect
;
134 mChannel
->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink
));
136 NS_ASSERTION(mPrevChannelSink
!= this,
137 "Initializing with a channel that already calls back to us!");
139 mChannel
->SetNotificationCallbacks(this);
141 mCacheEntry
= aCacheEntry
;
142 mCacheEntry
->UpdateLoadTime();
144 SetLoadId(aLoadingDocument
);
146 // Grab the inner window ID of the loading document, if possible.
147 if (aLoadingDocument
) {
148 mInnerWindowId
= aLoadingDocument
->InnerWindowID();
154 bool imgRequest::CanReuseWithoutValidation(dom::Document
* aDoc
) const {
155 // If the request's loadId is the same as the aLoadingDocument, then it is ok
156 // to use this one because it has already been validated for this context.
157 // XXX: nullptr seems to be a 'special' key value that indicates that NO
158 // validation is required.
159 // XXX: we also check the window ID because the loadID() can return a reused
160 // pointer of a document. This can still happen for non-document image
162 void* key
= (void*)aDoc
;
163 uint64_t innerWindowID
= aDoc
? aDoc
->InnerWindowID() : 0;
164 if (LoadId() == key
&& InnerWindowID() == innerWindowID
) {
168 // As a special-case, if this is a print preview document, also validate on
169 // the original document. This allows to print uncacheable images.
170 if (dom::Document
* original
= aDoc
? aDoc
->GetOriginalDocument() : nullptr) {
171 return CanReuseWithoutValidation(original
);
177 void imgRequest::ClearLoader() { mLoader
= nullptr; }
179 already_AddRefed
<nsIPrincipal
> imgRequest::GetTriggeringPrincipal() const {
180 nsCOMPtr
<nsIPrincipal
> principal
= mTriggeringPrincipal
;
181 return principal
.forget();
184 already_AddRefed
<ProgressTracker
> imgRequest::GetProgressTracker() const {
185 MutexAutoLock
lock(mMutex
);
188 MOZ_ASSERT(!mProgressTracker
,
189 "Should have given mProgressTracker to mImage");
190 return mImage
->GetProgressTracker();
192 MOZ_ASSERT(mProgressTracker
,
193 "Should have mProgressTracker until we create mImage");
194 RefPtr
<ProgressTracker
> progressTracker
= mProgressTracker
;
195 MOZ_ASSERT(progressTracker
);
196 return progressTracker
.forget();
199 void imgRequest::SetCacheEntry(imgCacheEntry
* entry
) { mCacheEntry
= entry
; }
201 bool imgRequest::HasCacheEntry() const { return mCacheEntry
!= nullptr; }
203 void imgRequest::ResetCacheEntry() {
204 if (HasCacheEntry()) {
205 mCacheEntry
->SetDataSize(0);
209 void imgRequest::AddProxy(imgRequestProxy
* proxy
) {
210 MOZ_ASSERT(proxy
, "null imgRequestProxy passed in");
211 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::AddProxy", "proxy", proxy
);
214 // Save a raw pointer to the first proxy we see, for use in the network
219 // If we're empty before adding, we have to tell the loader we now have
221 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
222 if (progressTracker
->ObserverCount() == 0) {
223 MOZ_ASSERT(mURI
, "Trying to SetHasProxies without key uri.");
225 mLoader
->SetHasProxies(this);
229 progressTracker
->AddObserver(proxy
);
232 nsresult
imgRequest::RemoveProxy(imgRequestProxy
* proxy
, nsresult aStatus
) {
233 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::RemoveProxy", "proxy", proxy
);
235 // This will remove our animation consumers, so after removing
236 // this proxy, we don't end up without proxies with observers, but still
237 // have animation consumers.
238 proxy
->ClearAnimationConsumers();
240 // Let the status tracker do its thing before we potentially call Cancel()
241 // below, because Cancel() may result in OnStopRequest being called back
242 // before Cancel() returns, leaving the image in a different state then the
243 // one it was in at this point.
244 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
245 if (!progressTracker
->RemoveObserver(proxy
)) {
249 if (progressTracker
->ObserverCount() == 0) {
250 // If we have no observers, there's nothing holding us alive. If we haven't
251 // been cancelled and thus removed from the cache, tell the image loader so
252 // we can be evicted from the cache.
254 MOZ_ASSERT(mURI
, "Removing last observer without key uri.");
257 mLoader
->SetHasNoProxies(this, mCacheEntry
);
260 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::RemoveProxy no cache entry",
264 /* If |aStatus| is a failure code, then cancel the load if it is still in
265 progress. Otherwise, let the load continue, keeping 'this' in the cache
266 with no observers. This way, if a proxy is destroyed without calling
267 cancel on it, it won't leak and won't leave a bad pointer in the observer
270 if (!(progressTracker
->GetProgress() & FLAG_LAST_PART_COMPLETE
) &&
271 NS_FAILED(aStatus
)) {
272 LOG_MSG(gImgLog
, "imgRequest::RemoveProxy",
273 "load in progress. canceling");
275 this->Cancel(NS_BINDING_ABORTED
);
278 /* break the cycle from the cache entry. */
279 mCacheEntry
= nullptr;
285 uint64_t imgRequest::InnerWindowID() const {
286 MutexAutoLock
lock(mMutex
);
287 return mInnerWindowId
;
290 void imgRequest::SetInnerWindowID(uint64_t aInnerWindowId
) {
291 MutexAutoLock
lock(mMutex
);
292 mInnerWindowId
= aInnerWindowId
;
295 void imgRequest::CancelAndAbort(nsresult aStatus
) {
296 LOG_SCOPE(gImgLog
, "imgRequest::CancelAndAbort");
300 // It's possible for the channel to fail to open after we've set our
301 // notification callbacks. In that case, make sure to break the cycle between
302 // the channel and us, because it won't.
304 mChannel
->SetNotificationCallbacks(mPrevChannelSink
);
305 mPrevChannelSink
= nullptr;
309 class imgRequestMainThreadCancel
: public Runnable
{
311 imgRequestMainThreadCancel(imgRequest
* aImgRequest
, nsresult aStatus
)
312 : Runnable("imgRequestMainThreadCancel"),
313 mImgRequest(aImgRequest
),
315 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
316 MOZ_ASSERT(aImgRequest
);
319 NS_IMETHOD
Run() override
{
320 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
321 mImgRequest
->ContinueCancel(mStatus
);
326 RefPtr
<imgRequest
> mImgRequest
;
330 void imgRequest::Cancel(nsresult aStatus
) {
331 /* The Cancel() method here should only be called by this class. */
332 LOG_SCOPE(gImgLog
, "imgRequest::Cancel");
334 if (NS_IsMainThread()) {
335 ContinueCancel(aStatus
);
337 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
338 nsCOMPtr
<nsIEventTarget
> eventTarget
= progressTracker
->GetEventTarget();
339 nsCOMPtr
<nsIRunnable
> ev
= new imgRequestMainThreadCancel(this, aStatus
);
340 eventTarget
->Dispatch(ev
.forget(), NS_DISPATCH_NORMAL
);
344 void imgRequest::ContinueCancel(nsresult aStatus
) {
345 MOZ_ASSERT(NS_IsMainThread());
347 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
348 progressTracker
->SyncNotifyProgress(FLAG_HAS_ERROR
);
352 if (mRequest
&& !(progressTracker
->GetProgress() & FLAG_LAST_PART_COMPLETE
)) {
353 mRequest
->CancelWithReason(aStatus
, "imgRequest::ContinueCancel"_ns
);
357 class imgRequestMainThreadEvict
: public Runnable
{
359 explicit imgRequestMainThreadEvict(imgRequest
* aImgRequest
)
360 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest
) {
361 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
362 MOZ_ASSERT(aImgRequest
);
365 NS_IMETHOD
Run() override
{
366 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
367 mImgRequest
->ContinueEvict();
372 RefPtr
<imgRequest
> mImgRequest
;
375 // EvictFromCache() is written to allowed to get called from any thread
376 void imgRequest::EvictFromCache() {
377 /* The EvictFromCache() method here should only be called by this class. */
378 LOG_SCOPE(gImgLog
, "imgRequest::EvictFromCache");
380 if (NS_IsMainThread()) {
383 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
387 // Helper-method used by EvictFromCache()
388 void imgRequest::ContinueEvict() {
389 MOZ_ASSERT(NS_IsMainThread());
394 void imgRequest::StartDecoding() {
395 MutexAutoLock
lock(mMutex
);
396 mDecodeRequested
= true;
399 bool imgRequest::IsDecodeRequested() const {
400 MutexAutoLock
lock(mMutex
);
401 return mDecodeRequested
;
404 nsresult
imgRequest::GetURI(nsIURI
** aURI
) {
407 LOG_FUNC(gImgLog
, "imgRequest::GetURI");
415 return NS_ERROR_FAILURE
;
418 nsresult
imgRequest::GetFinalURI(nsIURI
** aURI
) {
421 LOG_FUNC(gImgLog
, "imgRequest::GetFinalURI");
429 return NS_ERROR_FAILURE
;
432 bool imgRequest::IsChrome() const { return mURI
->SchemeIs("chrome"); }
434 bool imgRequest::IsData() const { return mURI
->SchemeIs("data"); }
436 nsresult
imgRequest::GetImageErrorCode() { return mImageErrorCode
; }
438 void imgRequest::RemoveFromCache() {
439 LOG_SCOPE(gImgLog
, "imgRequest::RemoveFromCache");
441 bool isInCache
= false;
444 MutexAutoLock
lock(mMutex
);
445 isInCache
= mIsInCache
;
448 if (isInCache
&& mLoader
) {
449 // mCacheEntry is nulled out when we have no more observers.
451 mLoader
->RemoveFromCache(mCacheEntry
);
453 mLoader
->RemoveFromCache(mCacheKey
);
457 mCacheEntry
= nullptr;
460 bool imgRequest::HasConsumers() const {
461 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
462 return progressTracker
&& progressTracker
->ObserverCount() > 0;
465 already_AddRefed
<image::Image
> imgRequest::GetImage() const {
466 MutexAutoLock
lock(mMutex
);
467 RefPtr
<image::Image
> image
= mImage
;
468 return image
.forget();
471 void imgRequest::GetFileName(nsACString
& aFileName
) {
472 nsAutoString fileName
;
474 nsCOMPtr
<nsISupportsCString
> supportscstr
;
475 if (NS_SUCCEEDED(mProperties
->Get("content-disposition",
476 NS_GET_IID(nsISupportsCString
),
477 getter_AddRefs(supportscstr
))) &&
479 nsAutoCString cdHeader
;
480 supportscstr
->GetData(cdHeader
);
481 NS_GetFilenameFromDisposition(fileName
, cdHeader
);
484 if (fileName
.IsEmpty()) {
485 nsCOMPtr
<nsIURL
> imgUrl(do_QueryInterface(mURI
));
487 imgUrl
->GetFileName(aFileName
);
488 NS_UnescapeURL(aFileName
);
491 aFileName
= NS_ConvertUTF16toUTF8(fileName
);
495 int32_t imgRequest::Priority() const {
496 int32_t priority
= nsISupportsPriority::PRIORITY_NORMAL
;
497 nsCOMPtr
<nsISupportsPriority
> p
= do_QueryInterface(mRequest
);
499 p
->GetPriority(&priority
);
504 void imgRequest::AdjustPriority(imgRequestProxy
* proxy
, int32_t delta
) {
505 // only the first proxy is allowed to modify the priority of this image load.
507 // XXX(darin): this is probably not the most optimal algorithm as we may want
508 // to increase the priority of requests that have a lot of proxies. the key
509 // concern though is that image loads remain lower priority than other pieces
510 // of content such as link clicks, CSS, and JS.
512 if (!mFirstProxy
|| proxy
!= mFirstProxy
) {
516 AdjustPriorityInternal(delta
);
519 void imgRequest::AdjustPriorityInternal(int32_t aDelta
) {
520 nsCOMPtr
<nsISupportsPriority
> p
= do_QueryInterface(mChannel
);
522 p
->AdjustPriority(aDelta
);
526 void imgRequest::BoostPriority(uint32_t aCategory
) {
527 if (!StaticPrefs::image_layout_network_priority()) {
531 uint32_t newRequestedCategory
=
532 (mBoostCategoriesRequested
& aCategory
) ^ aCategory
;
533 if (!newRequestedCategory
) {
534 // priority boost for each category can only apply once.
538 MOZ_LOG(gImgLog
, LogLevel::Debug
,
539 ("[this=%p] imgRequest::BoostPriority for category %x", this,
540 newRequestedCategory
));
544 if (newRequestedCategory
& imgIRequest::CATEGORY_FRAME_INIT
) {
548 if (newRequestedCategory
& imgIRequest::CATEGORY_FRAME_STYLE
) {
552 if (newRequestedCategory
& imgIRequest::CATEGORY_SIZE_QUERY
) {
556 if (newRequestedCategory
& imgIRequest::CATEGORY_DISPLAY
) {
557 delta
+= nsISupportsPriority::PRIORITY_HIGH
;
560 AdjustPriorityInternal(delta
);
561 mBoostCategoriesRequested
|= newRequestedCategory
;
564 void imgRequest::SetIsInCache(bool aInCache
) {
565 LOG_FUNC_WITH_PARAM(gImgLog
, "imgRequest::SetIsCacheable", "aInCache",
567 MutexAutoLock
lock(mMutex
);
568 mIsInCache
= aInCache
;
571 void imgRequest::UpdateCacheEntrySize() {
576 RefPtr
<Image
> image
= GetImage();
577 SizeOfState
state(moz_malloc_size_of
);
578 size_t size
= image
->SizeOfSourceWithComputedFallback(state
);
579 mCacheEntry
->SetDataSize(size
);
582 void imgRequest::SetCacheValidation(imgCacheEntry
* aCacheEntry
,
583 nsIRequest
* aRequest
) {
584 /* get the expires info */
585 if (!aCacheEntry
|| aCacheEntry
->GetExpiryTime() != 0) {
589 RefPtr
<imgRequest
> req
= aCacheEntry
->GetRequest();
592 req
->GetURI(getter_AddRefs(uri
));
593 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
594 // get here in such cases sometimes (like for some redirects, see
595 // docshell/test/chrome/test_bug89419.xhtml).
597 // We have the original URI in the cache key though, probably we should be
598 // using that instead of relying on Init() getting called.
599 auto info
= nsContentUtils::GetSubresourceCacheValidationInfo(aRequest
, uri
);
601 // Expiration time defaults to 0. We set the expiration time on our entry if
602 // it hasn't been set yet.
603 if (!info
.mExpirationTime
) {
604 // If the channel doesn't support caching, then ensure this expires the
605 // next time it is used.
606 info
.mExpirationTime
.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
609 aCacheEntry
->SetExpiryTime(*info
.mExpirationTime
);
610 // Cache entries default to not needing to validate. We ensure that
611 // multiple calls to this function don't override an earlier decision to
612 // validate by making validation a one-way decision.
613 if (info
.mMustRevalidate
) {
614 aCacheEntry
->SetMustValidate(info
.mMustRevalidate
);
618 bool imgRequest::GetMultipart() const {
619 MutexAutoLock
lock(mMutex
);
620 return mIsMultiPartChannel
;
623 bool imgRequest::HadInsecureRedirect() const {
624 MutexAutoLock
lock(mMutex
);
625 return mHadInsecureRedirect
;
628 /** nsIRequestObserver methods **/
631 imgRequest::OnStartRequest(nsIRequest
* aRequest
) {
632 LOG_SCOPE(gImgLog
, "imgRequest::OnStartRequest");
636 if (nsCOMPtr
<nsIHttpChannel
> httpChannel
= do_QueryInterface(aRequest
)) {
638 nsCOMPtr
<nsILoadInfo
> loadInfo
= httpChannel
->LoadInfo();
639 mIsDeniedCrossSiteCORSRequest
=
640 loadInfo
->GetTainting() == LoadTainting::CORS
&&
641 (NS_FAILED(httpChannel
->GetStatus(&rv
)) || NS_FAILED(rv
));
642 mIsCrossSiteNoCORSRequest
= loadInfo
->GetTainting() == LoadTainting::Opaque
;
645 UpdateShouldReportRenderTimeForLCP();
646 // Figure out if we're multipart.
647 nsCOMPtr
<nsIMultiPartChannel
> multiPartChannel
= do_QueryInterface(aRequest
);
649 MutexAutoLock
lock(mMutex
);
651 MOZ_ASSERT(multiPartChannel
|| !mIsMultiPartChannel
,
652 "Stopped being multipart?");
654 mNewPartPending
= true;
656 mIsMultiPartChannel
= bool(multiPartChannel
);
659 // If we're not multipart, we shouldn't have an image yet.
660 if (image
&& !multiPartChannel
) {
661 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
662 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
663 return NS_ERROR_FAILURE
;
667 * If mRequest is null here, then we need to set it so that we'll be able to
668 * cancel it if our Cancel() method is called. Note that this can only
669 * happen for multipart channels. We could simply not null out mRequest for
670 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
671 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
674 MOZ_ASSERT(multiPartChannel
, "Should have mRequest unless we're multipart");
675 nsCOMPtr
<nsIChannel
> baseChannel
;
676 multiPartChannel
->GetBaseChannel(getter_AddRefs(baseChannel
));
677 mRequest
= baseChannel
;
680 nsCOMPtr
<nsIChannel
> channel(do_QueryInterface(aRequest
));
682 /* Get our principal */
683 nsCOMPtr
<nsIScriptSecurityManager
> secMan
=
684 nsContentUtils::GetSecurityManager();
686 nsresult rv
= secMan
->GetChannelResultPrincipal(
687 channel
, getter_AddRefs(mPrincipal
));
694 SetCacheValidation(mCacheEntry
, aRequest
);
696 // Shouldn't we be dead already if this gets hit?
697 // Probably multipart/x-mixed-replace...
698 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
699 if (progressTracker
->ObserverCount() == 0) {
700 this->Cancel(NS_IMAGELIB_ERROR_FAILURE
);
703 // Try to retarget OnDataAvailable to a decode thread. We must process data
704 // URIs synchronously as per the spec however.
705 if (!channel
|| IsData()) {
709 nsCOMPtr
<nsIThreadRetargetableRequest
> retargetable
=
710 do_QueryInterface(aRequest
);
712 nsAutoCString mimeType
;
713 nsresult rv
= channel
->GetContentType(mimeType
);
714 if (NS_SUCCEEDED(rv
) && !mimeType
.EqualsLiteral(IMAGE_SVG_XML
)) {
715 // Retarget OnDataAvailable to the DecodePool's IO thread.
716 nsCOMPtr
<nsISerialEventTarget
> target
=
717 DecodePool::Singleton()->GetIOEventTarget();
718 rv
= retargetable
->RetargetDeliveryTo(target
);
720 MOZ_LOG(gImgLog
, LogLevel::Warning
,
721 ("[this=%p] imgRequest::OnStartRequest -- "
722 "RetargetDeliveryTo rv %" PRIu32
"=%s\n",
723 this, static_cast<uint32_t>(rv
),
724 NS_SUCCEEDED(rv
) ? "succeeded" : "failed"));
731 imgRequest::OnStopRequest(nsIRequest
* aRequest
, nsresult status
) {
732 LOG_FUNC(gImgLog
, "imgRequest::OnStopRequest");
733 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
735 RefPtr
<Image
> image
= GetImage();
737 RefPtr
<imgRequest
> strongThis
= this;
739 bool isMultipart
= false;
740 bool newPartPending
= false;
742 MutexAutoLock
lock(mMutex
);
743 isMultipart
= mIsMultiPartChannel
;
744 newPartPending
= mNewPartPending
;
746 if (isMultipart
&& newPartPending
) {
747 OnDataAvailable(aRequest
, nullptr, 0, 0);
750 // XXXldb What if this is a non-last part of a multipart request?
751 // xxx before we release our reference to mRequest, lets
752 // save the last status that we saw so that the
753 // imgRequestProxy will have access to it.
755 mRequest
= nullptr; // we no longer need the request
758 // stop holding a ref to the channel, since we don't need it anymore
760 mChannel
->SetNotificationCallbacks(mPrevChannelSink
);
761 mPrevChannelSink
= nullptr;
765 bool lastPart
= true;
766 nsCOMPtr
<nsIMultiPartChannel
> mpchan(do_QueryInterface(aRequest
));
768 mpchan
->GetIsLastPart(&lastPart
);
771 bool isPartial
= false;
772 if (image
&& (status
== NS_ERROR_NET_PARTIAL_TRANSFER
)) {
774 status
= NS_OK
; // fake happy face
777 // Tell the image that it has all of the source data. Note that this can
778 // trigger a failure, since the image might be waiting for more non-optional
779 // data and this is the point where we break the news that it's not coming.
781 nsresult rv
= image
->OnImageDataComplete(aRequest
, status
, lastPart
);
783 // If we got an error in the OnImageDataComplete() call, we don't want to
784 // proceed as if nothing bad happened. However, we also want to give
785 // precedence to failure status codes from necko, since presumably they're
787 if (NS_FAILED(rv
) && NS_SUCCEEDED(status
)) {
792 // If the request went through, update the cache entry size. Otherwise,
793 // cancel the request, which removes us from the cache.
794 if (image
&& NS_SUCCEEDED(status
) && !isPartial
) {
795 // We update the cache entry size here because this is where we finish
796 // loading compressed source data, which is part of our size calculus.
797 UpdateCacheEntrySize();
799 } else if (isPartial
) {
800 // Remove the partial image from the cache.
801 this->EvictFromCache();
804 mImageErrorCode
= status
;
806 // if the error isn't "just" a partial transfer
807 // stops animations, removes from cache
808 this->Cancel(status
);
812 // We have to fire the OnStopRequest notifications ourselves because there's
813 // no image capable of doing so.
815 LoadCompleteProgress(lastPart
, /* aError = */ false, status
);
817 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
818 progressTracker
->SyncNotifyProgress(progress
);
821 mTimedChannel
= nullptr;
825 struct mimetype_closure
{
829 /* prototype for these defined below */
830 static nsresult
sniff_mimetype_callback(nsIInputStream
* in
, void* closure
,
831 const char* fromRawSegment
,
832 uint32_t toOffset
, uint32_t count
,
833 uint32_t* writeCount
);
835 /** nsThreadRetargetableStreamListener methods **/
837 imgRequest::CheckListenerChain() {
838 // TODO Might need more checking here.
839 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
844 imgRequest::OnDataFinished(nsresult
) { return NS_OK
; }
846 /** nsIStreamListener methods **/
848 struct NewPartResult final
{
849 explicit NewPartResult(image::Image
* aExistingImage
)
850 : mImage(aExistingImage
),
851 mIsFirstPart(!aExistingImage
),
853 mShouldResetCacheEntry(false) {}
855 nsAutoCString mContentType
;
856 nsAutoCString mContentDisposition
;
857 RefPtr
<image::Image
> mImage
;
858 const bool mIsFirstPart
;
860 bool mShouldResetCacheEntry
;
863 static NewPartResult
PrepareForNewPart(nsIRequest
* aRequest
,
864 nsIInputStream
* aInStr
, uint32_t aCount
,
865 nsIURI
* aURI
, bool aIsMultipart
,
866 image::Image
* aExistingImage
,
867 ProgressTracker
* aProgressTracker
,
868 uint64_t aInnerWindowId
) {
869 NewPartResult
result(aExistingImage
);
872 mimetype_closure closure
;
873 closure
.newType
= &result
.mContentType
;
875 // Look at the first few bytes and see if we can tell what the data is from
876 // that since servers tend to lie. :(
878 aInStr
->ReadSegments(sniff_mimetype_callback
, &closure
, aCount
, &out
);
881 nsCOMPtr
<nsIChannel
> chan(do_QueryInterface(aRequest
));
882 if (result
.mContentType
.IsEmpty()) {
884 chan
? chan
->GetContentType(result
.mContentType
) : NS_ERROR_FAILURE
;
886 MOZ_LOG(gImgLog
, LogLevel::Error
,
887 ("imgRequest::PrepareForNewPart -- "
888 "Content type unavailable from the channel\n"));
896 chan
->GetContentDispositionHeader(result
.mContentDisposition
);
899 MOZ_LOG(gImgLog
, LogLevel::Debug
,
900 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
901 result
.mContentType
.get()));
903 // XXX If server lied about mimetype and it's SVG, we may need to copy
904 // the data and dispatch back to the main thread, AND tell the channel to
905 // dispatch there in the future.
907 // Create the new image and give it ownership of our ProgressTracker.
909 // Create the ProgressTracker and image for this part.
910 RefPtr
<ProgressTracker
> progressTracker
= new ProgressTracker();
911 RefPtr
<image::Image
> partImage
= image::ImageFactory::CreateImage(
912 aRequest
, progressTracker
, result
.mContentType
, aURI
,
913 /* aIsMultipart = */ true, aInnerWindowId
);
915 if (result
.mIsFirstPart
) {
916 // First part for a multipart channel. Create the MultipartImage wrapper.
917 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
918 aProgressTracker
->SetIsMultipart();
919 result
.mImage
= image::ImageFactory::CreateMultipartImage(
920 partImage
, aProgressTracker
);
922 // Transition to the new part.
923 auto multipartImage
= static_cast<MultipartImage
*>(aExistingImage
);
924 multipartImage
->BeginTransitionToPart(partImage
);
926 // Reset our cache entry size so it doesn't keep growing without bound.
927 result
.mShouldResetCacheEntry
= true;
930 MOZ_ASSERT(!aExistingImage
, "New part for non-multipart channel?");
931 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
933 // Create an image using our progress tracker.
934 result
.mImage
= image::ImageFactory::CreateImage(
935 aRequest
, aProgressTracker
, result
.mContentType
, aURI
,
936 /* aIsMultipart = */ false, aInnerWindowId
);
939 MOZ_ASSERT(result
.mImage
);
940 if (!result
.mImage
->HasError() || aIsMultipart
) {
941 // We allow multipart images to fail to initialize (which generally
942 // indicates a bad content type) without cancelling the load, because
943 // subsequent parts might be fine.
944 result
.mSucceeded
= true;
950 class FinishPreparingForNewPartRunnable final
: public Runnable
{
952 FinishPreparingForNewPartRunnable(imgRequest
* aImgRequest
,
953 NewPartResult
&& aResult
)
954 : Runnable("FinishPreparingForNewPartRunnable"),
955 mImgRequest(aImgRequest
),
957 MOZ_ASSERT(aImgRequest
);
960 NS_IMETHOD
Run() override
{
961 mImgRequest
->FinishPreparingForNewPart(mResult
);
966 RefPtr
<imgRequest
> mImgRequest
;
967 NewPartResult mResult
;
970 void imgRequest::FinishPreparingForNewPart(const NewPartResult
& aResult
) {
971 MOZ_ASSERT(NS_IsMainThread());
973 mContentType
= aResult
.mContentType
;
975 SetProperties(aResult
.mContentType
, aResult
.mContentDisposition
);
977 if (aResult
.mIsFirstPart
) {
978 // Notify listeners that we have an image.
979 mImageAvailable
= true;
980 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
981 progressTracker
->OnImageAvailable();
982 MOZ_ASSERT(progressTracker
->HasImage());
985 if (aResult
.mShouldResetCacheEntry
) {
989 if (IsDecodeRequested()) {
990 aResult
.mImage
->StartDecoding(imgIContainer::FLAG_NONE
);
994 bool imgRequest::ImageAvailable() const { return mImageAvailable
; }
997 imgRequest::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
998 uint64_t aOffset
, uint32_t aCount
) {
999 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::OnDataAvailable", "count", aCount
);
1001 NS_ASSERTION(aRequest
, "imgRequest::OnDataAvailable -- no request!");
1003 RefPtr
<Image
> image
;
1004 RefPtr
<ProgressTracker
> progressTracker
;
1005 bool isMultipart
= false;
1006 bool newPartPending
= false;
1007 uint64_t innerWindowId
= 0;
1009 // Retrieve and update our state.
1011 MutexAutoLock
lock(mMutex
);
1013 progressTracker
= mProgressTracker
;
1014 isMultipart
= mIsMultiPartChannel
;
1015 newPartPending
= mNewPartPending
;
1016 mNewPartPending
= false;
1017 innerWindowId
= mInnerWindowId
;
1020 // If this is a new part, we need to sniff its content type and create an
1021 // appropriate image.
1022 if (newPartPending
) {
1023 NewPartResult result
=
1024 PrepareForNewPart(aRequest
, aInStr
, aCount
, mURI
, isMultipart
, image
,
1025 progressTracker
, innerWindowId
);
1026 bool succeeded
= result
.mSucceeded
;
1028 if (result
.mImage
) {
1029 image
= result
.mImage
;
1030 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1032 // Update our state to reflect this new part.
1034 MutexAutoLock
lock(mMutex
);
1037 // We only get an event target if we are not on the main thread, because
1038 // we have to dispatch in that case. If we are on the main thread, but
1039 // on a different scheduler group than ProgressTracker would give us,
1040 // that is okay because nothing in imagelib requires that, just our
1041 // listeners (which have their own checks).
1042 if (!NS_IsMainThread()) {
1043 eventTarget
= mProgressTracker
->GetEventTarget();
1044 MOZ_ASSERT(eventTarget
);
1047 mProgressTracker
= nullptr;
1050 // Some property objects are not threadsafe, and we need to send
1051 // OnImageAvailable on the main thread, so finish on the main thread.
1053 MOZ_ASSERT(NS_IsMainThread());
1054 FinishPreparingForNewPart(result
);
1056 nsCOMPtr
<nsIRunnable
> runnable
=
1057 new FinishPreparingForNewPartRunnable(this, std::move(result
));
1058 eventTarget
->Dispatch(CreateRenderBlockingRunnable(runnable
.forget()),
1059 NS_DISPATCH_NORMAL
);
1064 // Something went wrong; probably a content type issue.
1065 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
1066 return NS_BINDING_ABORTED
;
1070 // Notify the image that it has new data.
1073 image
->OnImageDataAvailable(aRequest
, aInStr
, aOffset
, aCount
);
1075 if (NS_FAILED(rv
)) {
1076 MOZ_LOG(gImgLog
, LogLevel::Warning
,
1077 ("[this=%p] imgRequest::OnDataAvailable -- "
1078 "copy to RasterImage failed\n",
1080 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
1081 return NS_BINDING_ABORTED
;
1088 void imgRequest::SetProperties(const nsACString
& aContentType
,
1089 const nsACString
& aContentDisposition
) {
1090 /* set our mimetype as a property */
1091 nsCOMPtr
<nsISupportsCString
> contentType
=
1092 do_CreateInstance("@mozilla.org/supports-cstring;1");
1094 contentType
->SetData(aContentType
);
1095 mProperties
->Set("type", contentType
);
1098 /* set our content disposition as a property */
1099 if (!aContentDisposition
.IsEmpty()) {
1100 nsCOMPtr
<nsISupportsCString
> contentDisposition
=
1101 do_CreateInstance("@mozilla.org/supports-cstring;1");
1102 if (contentDisposition
) {
1103 contentDisposition
->SetData(aContentDisposition
);
1104 mProperties
->Set("content-disposition", contentDisposition
);
1109 static nsresult
sniff_mimetype_callback(nsIInputStream
* in
, void* data
,
1110 const char* fromRawSegment
,
1111 uint32_t toOffset
, uint32_t count
,
1112 uint32_t* writeCount
) {
1113 mimetype_closure
* closure
= static_cast<mimetype_closure
*>(data
);
1115 NS_ASSERTION(closure
, "closure is null!");
1118 imgLoader::GetMimeTypeFromContent(fromRawSegment
, count
, *closure
->newType
);
1122 return NS_ERROR_FAILURE
;
1125 /** nsIInterfaceRequestor methods **/
1128 imgRequest::GetInterface(const nsIID
& aIID
, void** aResult
) {
1129 if (!mPrevChannelSink
|| aIID
.Equals(NS_GET_IID(nsIChannelEventSink
))) {
1130 return QueryInterface(aIID
, aResult
);
1134 mPrevChannelSink
!= this,
1135 "Infinite recursion - don't keep track of channel sinks that are us!");
1136 return mPrevChannelSink
->GetInterface(aIID
, aResult
);
1139 /** nsIChannelEventSink methods **/
1141 imgRequest::AsyncOnChannelRedirect(nsIChannel
* oldChannel
,
1142 nsIChannel
* newChannel
, uint32_t flags
,
1143 nsIAsyncVerifyRedirectCallback
* callback
) {
1144 NS_ASSERTION(mRequest
&& mChannel
,
1145 "Got a channel redirect after we nulled out mRequest!");
1146 NS_ASSERTION(mChannel
== oldChannel
,
1147 "Got a channel redirect for an unknown channel!");
1148 NS_ASSERTION(newChannel
, "Got a redirect to a NULL channel!");
1150 SetCacheValidation(mCacheEntry
, oldChannel
);
1152 // Prepare for callback
1153 mRedirectCallback
= callback
;
1154 mNewRedirectChannel
= newChannel
;
1156 nsCOMPtr
<nsIChannelEventSink
> sink(do_GetInterface(mPrevChannelSink
));
1159 sink
->AsyncOnChannelRedirect(oldChannel
, newChannel
, flags
, this);
1160 if (NS_FAILED(rv
)) {
1161 mRedirectCallback
= nullptr;
1162 mNewRedirectChannel
= nullptr;
1167 (void)OnRedirectVerifyCallback(NS_OK
);
1172 imgRequest::OnRedirectVerifyCallback(nsresult result
) {
1173 NS_ASSERTION(mRedirectCallback
, "mRedirectCallback not set in callback");
1174 NS_ASSERTION(mNewRedirectChannel
, "mNewRedirectChannel not set in callback");
1176 if (NS_FAILED(result
)) {
1177 mRedirectCallback
->OnRedirectVerifyCallback(result
);
1178 mRedirectCallback
= nullptr;
1179 mNewRedirectChannel
= nullptr;
1183 mChannel
= mNewRedirectChannel
;
1184 mTimedChannel
= do_QueryInterface(mChannel
);
1185 mNewRedirectChannel
= nullptr;
1187 if (LOG_TEST(LogLevel::Debug
)) {
1188 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::OnChannelRedirect", "old",
1189 mFinalURI
? mFinalURI
->GetSpecOrDefault().get() : "");
1192 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1193 // security code, which needs to know whether there is an insecure load at any
1194 // point in the redirect chain.
1195 bool schemeLocal
= false;
1196 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI
,
1197 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
,
1199 (!mFinalURI
->SchemeIs("https") && !mFinalURI
->SchemeIs("chrome") &&
1201 MutexAutoLock
lock(mMutex
);
1203 // The csp directive upgrade-insecure-requests performs an internal redirect
1204 // to upgrade all requests from http to https before any data is fetched
1205 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1206 // internal redirect.
1207 nsCOMPtr
<nsILoadInfo
> loadInfo
= mChannel
->LoadInfo();
1208 bool upgradeInsecureRequests
=
1209 loadInfo
? loadInfo
->GetUpgradeInsecureRequests() ||
1210 loadInfo
->GetBrowserUpgradeInsecureRequests()
1212 if (!upgradeInsecureRequests
) {
1213 mHadInsecureRedirect
= true;
1217 // Update the final URI.
1218 mChannel
->GetURI(getter_AddRefs(mFinalURI
));
1220 if (LOG_TEST(LogLevel::Debug
)) {
1221 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::OnChannelRedirect", "new",
1222 mFinalURI
? mFinalURI
->GetSpecOrDefault().get() : "");
1225 // Make sure we have a protocol that returns data rather than opens an
1226 // external application, e.g. 'mailto:'.
1227 if (nsContentUtils::IsExternalProtocol(mFinalURI
)) {
1228 mRedirectCallback
->OnRedirectVerifyCallback(NS_ERROR_ABORT
);
1229 mRedirectCallback
= nullptr;
1233 mRedirectCallback
->OnRedirectVerifyCallback(NS_OK
);
1234 mRedirectCallback
= nullptr;
1238 void imgRequest::UpdateShouldReportRenderTimeForLCP() {
1239 if (mTimedChannel
) {
1240 bool allRedirectPassTAO
= false;
1241 mTimedChannel
->GetAllRedirectsPassTimingAllowCheck(&allRedirectPassTAO
);
1242 mShouldReportRenderTimeForLCP
=
1243 mTimedChannel
->TimingAllowCheck(mTriggeringPrincipal
) &&