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 nsCOMPtr
<nsIEventTarget
> eventTarget
= GetMainThreadSerialEventTarget();
338 nsCOMPtr
<nsIRunnable
> ev
= new imgRequestMainThreadCancel(this, aStatus
);
339 eventTarget
->Dispatch(ev
.forget(), NS_DISPATCH_NORMAL
);
343 void imgRequest::ContinueCancel(nsresult aStatus
) {
344 MOZ_ASSERT(NS_IsMainThread());
346 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
347 progressTracker
->SyncNotifyProgress(FLAG_HAS_ERROR
);
351 if (mRequest
&& !(progressTracker
->GetProgress() & FLAG_LAST_PART_COMPLETE
)) {
352 mRequest
->CancelWithReason(aStatus
, "imgRequest::ContinueCancel"_ns
);
356 class imgRequestMainThreadEvict
: public Runnable
{
358 explicit imgRequestMainThreadEvict(imgRequest
* aImgRequest
)
359 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest
) {
360 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
361 MOZ_ASSERT(aImgRequest
);
364 NS_IMETHOD
Run() override
{
365 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
366 mImgRequest
->ContinueEvict();
371 RefPtr
<imgRequest
> mImgRequest
;
374 // EvictFromCache() is written to allowed to get called from any thread
375 void imgRequest::EvictFromCache() {
376 /* The EvictFromCache() method here should only be called by this class. */
377 LOG_SCOPE(gImgLog
, "imgRequest::EvictFromCache");
379 if (NS_IsMainThread()) {
382 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
386 // Helper-method used by EvictFromCache()
387 void imgRequest::ContinueEvict() {
388 MOZ_ASSERT(NS_IsMainThread());
393 void imgRequest::StartDecoding() {
394 MutexAutoLock
lock(mMutex
);
395 mDecodeRequested
= true;
398 bool imgRequest::IsDecodeRequested() const {
399 MutexAutoLock
lock(mMutex
);
400 return mDecodeRequested
;
403 nsresult
imgRequest::GetURI(nsIURI
** aURI
) {
406 LOG_FUNC(gImgLog
, "imgRequest::GetURI");
414 return NS_ERROR_FAILURE
;
417 nsresult
imgRequest::GetFinalURI(nsIURI
** aURI
) {
420 LOG_FUNC(gImgLog
, "imgRequest::GetFinalURI");
428 return NS_ERROR_FAILURE
;
431 bool imgRequest::IsChrome() const { return mURI
->SchemeIs("chrome"); }
433 bool imgRequest::IsData() const { return mURI
->SchemeIs("data"); }
435 nsresult
imgRequest::GetImageErrorCode() { return mImageErrorCode
; }
437 void imgRequest::RemoveFromCache() {
438 LOG_SCOPE(gImgLog
, "imgRequest::RemoveFromCache");
440 bool isInCache
= false;
443 MutexAutoLock
lock(mMutex
);
444 isInCache
= mIsInCache
;
447 if (isInCache
&& mLoader
) {
448 // mCacheEntry is nulled out when we have no more observers.
450 mLoader
->RemoveFromCache(mCacheEntry
);
452 mLoader
->RemoveFromCache(mCacheKey
);
456 mCacheEntry
= nullptr;
459 bool imgRequest::HasConsumers() const {
460 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
461 return progressTracker
&& progressTracker
->ObserverCount() > 0;
464 already_AddRefed
<image::Image
> imgRequest::GetImage() const {
465 MutexAutoLock
lock(mMutex
);
466 RefPtr
<image::Image
> image
= mImage
;
467 return image
.forget();
470 void imgRequest::GetFileName(nsACString
& aFileName
) {
471 nsAutoString fileName
;
473 nsCOMPtr
<nsISupportsCString
> supportscstr
;
474 if (NS_SUCCEEDED(mProperties
->Get("content-disposition",
475 NS_GET_IID(nsISupportsCString
),
476 getter_AddRefs(supportscstr
))) &&
478 nsAutoCString cdHeader
;
479 supportscstr
->GetData(cdHeader
);
480 NS_GetFilenameFromDisposition(fileName
, cdHeader
);
483 if (fileName
.IsEmpty()) {
484 nsCOMPtr
<nsIURL
> imgUrl(do_QueryInterface(mURI
));
486 imgUrl
->GetFileName(aFileName
);
487 NS_UnescapeURL(aFileName
);
490 aFileName
= NS_ConvertUTF16toUTF8(fileName
);
494 int32_t imgRequest::Priority() const {
495 int32_t priority
= nsISupportsPriority::PRIORITY_NORMAL
;
496 nsCOMPtr
<nsISupportsPriority
> p
= do_QueryInterface(mRequest
);
498 p
->GetPriority(&priority
);
503 void imgRequest::AdjustPriority(imgRequestProxy
* proxy
, int32_t delta
) {
504 // only the first proxy is allowed to modify the priority of this image load.
506 // XXX(darin): this is probably not the most optimal algorithm as we may want
507 // to increase the priority of requests that have a lot of proxies. the key
508 // concern though is that image loads remain lower priority than other pieces
509 // of content such as link clicks, CSS, and JS.
511 if (!mFirstProxy
|| proxy
!= mFirstProxy
) {
515 AdjustPriorityInternal(delta
);
518 void imgRequest::AdjustPriorityInternal(int32_t aDelta
) {
519 nsCOMPtr
<nsISupportsPriority
> p
= do_QueryInterface(mChannel
);
521 p
->AdjustPriority(aDelta
);
525 void imgRequest::BoostPriority(uint32_t aCategory
) {
526 if (!StaticPrefs::image_layout_network_priority()) {
530 uint32_t newRequestedCategory
=
531 (mBoostCategoriesRequested
& aCategory
) ^ aCategory
;
532 if (!newRequestedCategory
) {
533 // priority boost for each category can only apply once.
537 MOZ_LOG(gImgLog
, LogLevel::Debug
,
538 ("[this=%p] imgRequest::BoostPriority for category %x", this,
539 newRequestedCategory
));
543 if (newRequestedCategory
& imgIRequest::CATEGORY_FRAME_INIT
) {
547 if (newRequestedCategory
& imgIRequest::CATEGORY_FRAME_STYLE
) {
551 if (newRequestedCategory
& imgIRequest::CATEGORY_SIZE_QUERY
) {
555 if (newRequestedCategory
& imgIRequest::CATEGORY_DISPLAY
) {
556 delta
+= nsISupportsPriority::PRIORITY_HIGH
;
559 AdjustPriorityInternal(delta
);
560 mBoostCategoriesRequested
|= newRequestedCategory
;
563 void imgRequest::SetIsInCache(bool aInCache
) {
564 LOG_FUNC_WITH_PARAM(gImgLog
, "imgRequest::SetIsCacheable", "aInCache",
566 MutexAutoLock
lock(mMutex
);
567 mIsInCache
= aInCache
;
570 void imgRequest::UpdateCacheEntrySize() {
575 RefPtr
<Image
> image
= GetImage();
576 SizeOfState
state(moz_malloc_size_of
);
577 size_t size
= image
->SizeOfSourceWithComputedFallback(state
);
578 mCacheEntry
->SetDataSize(size
);
581 void imgRequest::SetCacheValidation(imgCacheEntry
* aCacheEntry
,
582 nsIRequest
* aRequest
) {
583 /* get the expires info */
584 if (!aCacheEntry
|| aCacheEntry
->GetExpiryTime() != 0) {
588 RefPtr
<imgRequest
> req
= aCacheEntry
->GetRequest();
591 req
->GetURI(getter_AddRefs(uri
));
592 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
593 // get here in such cases sometimes (like for some redirects, see
594 // docshell/test/chrome/test_bug89419.xhtml).
596 // We have the original URI in the cache key though, probably we should be
597 // using that instead of relying on Init() getting called.
598 auto info
= nsContentUtils::GetSubresourceCacheValidationInfo(aRequest
, uri
);
600 // Expiration time defaults to 0. We set the expiration time on our entry if
601 // it hasn't been set yet.
602 if (!info
.mExpirationTime
) {
603 // If the channel doesn't support caching, then ensure this expires the
604 // next time it is used.
605 info
.mExpirationTime
.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
608 aCacheEntry
->SetExpiryTime(*info
.mExpirationTime
);
609 // Cache entries default to not needing to validate. We ensure that
610 // multiple calls to this function don't override an earlier decision to
611 // validate by making validation a one-way decision.
612 if (info
.mMustRevalidate
) {
613 aCacheEntry
->SetMustValidate(info
.mMustRevalidate
);
617 bool imgRequest::GetMultipart() const {
618 MutexAutoLock
lock(mMutex
);
619 return mIsMultiPartChannel
;
622 bool imgRequest::HadInsecureRedirect() const {
623 MutexAutoLock
lock(mMutex
);
624 return mHadInsecureRedirect
;
627 /** nsIRequestObserver methods **/
630 imgRequest::OnStartRequest(nsIRequest
* aRequest
) {
631 LOG_SCOPE(gImgLog
, "imgRequest::OnStartRequest");
635 if (nsCOMPtr
<nsIHttpChannel
> httpChannel
= do_QueryInterface(aRequest
)) {
637 nsCOMPtr
<nsILoadInfo
> loadInfo
= httpChannel
->LoadInfo();
638 mIsDeniedCrossSiteCORSRequest
=
639 loadInfo
->GetTainting() == LoadTainting::CORS
&&
640 (NS_FAILED(httpChannel
->GetStatus(&rv
)) || NS_FAILED(rv
));
641 mIsCrossSiteNoCORSRequest
= loadInfo
->GetTainting() == LoadTainting::Opaque
;
644 UpdateShouldReportRenderTimeForLCP();
645 // Figure out if we're multipart.
646 nsCOMPtr
<nsIMultiPartChannel
> multiPartChannel
= do_QueryInterface(aRequest
);
648 MutexAutoLock
lock(mMutex
);
650 MOZ_ASSERT(multiPartChannel
|| !mIsMultiPartChannel
,
651 "Stopped being multipart?");
653 mNewPartPending
= true;
655 mIsMultiPartChannel
= bool(multiPartChannel
);
658 // If we're not multipart, we shouldn't have an image yet.
659 if (image
&& !multiPartChannel
) {
660 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
661 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
662 return NS_ERROR_FAILURE
;
666 * If mRequest is null here, then we need to set it so that we'll be able to
667 * cancel it if our Cancel() method is called. Note that this can only
668 * happen for multipart channels. We could simply not null out mRequest for
669 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
670 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
673 MOZ_ASSERT(multiPartChannel
, "Should have mRequest unless we're multipart");
674 nsCOMPtr
<nsIChannel
> baseChannel
;
675 multiPartChannel
->GetBaseChannel(getter_AddRefs(baseChannel
));
676 mRequest
= baseChannel
;
679 nsCOMPtr
<nsIChannel
> channel(do_QueryInterface(aRequest
));
681 /* Get our principal */
682 nsCOMPtr
<nsIScriptSecurityManager
> secMan
=
683 nsContentUtils::GetSecurityManager();
685 nsresult rv
= secMan
->GetChannelResultPrincipal(
686 channel
, getter_AddRefs(mPrincipal
));
693 SetCacheValidation(mCacheEntry
, aRequest
);
695 // Shouldn't we be dead already if this gets hit?
696 // Probably multipart/x-mixed-replace...
697 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
698 if (progressTracker
->ObserverCount() == 0) {
699 this->Cancel(NS_IMAGELIB_ERROR_FAILURE
);
702 // Try to retarget OnDataAvailable to a decode thread. We must process data
703 // URIs synchronously as per the spec however.
704 if (!channel
|| IsData()) {
708 nsCOMPtr
<nsIThreadRetargetableRequest
> retargetable
=
709 do_QueryInterface(aRequest
);
711 nsAutoCString mimeType
;
712 nsresult rv
= channel
->GetContentType(mimeType
);
713 if (NS_SUCCEEDED(rv
) && !mimeType
.EqualsLiteral(IMAGE_SVG_XML
)) {
714 mOffMainThreadData
= true;
715 // Retarget OnDataAvailable to the DecodePool's IO thread.
716 nsCOMPtr
<nsISerialEventTarget
> target
=
717 DecodePool::Singleton()->GetIOEventTarget();
718 rv
= retargetable
->RetargetDeliveryTo(target
);
719 MOZ_LOG(gImgLog
, LogLevel::Warning
,
720 ("[this=%p] imgRequest::OnStartRequest -- "
721 "RetargetDeliveryTo rv %" PRIu32
"=%s\n",
722 this, static_cast<uint32_t>(rv
),
723 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 return mOffMainThreadData
? NS_OK
: NS_ERROR_NO_INTERFACE
;
842 imgRequest::OnDataFinished(nsresult
) { return NS_OK
; }
844 /** nsIStreamListener methods **/
846 struct NewPartResult final
{
847 explicit NewPartResult(image::Image
* aExistingImage
)
848 : mImage(aExistingImage
),
849 mIsFirstPart(!aExistingImage
),
851 mShouldResetCacheEntry(false) {}
853 nsAutoCString mContentType
;
854 nsAutoCString mContentDisposition
;
855 RefPtr
<image::Image
> mImage
;
856 const bool mIsFirstPart
;
858 bool mShouldResetCacheEntry
;
861 static NewPartResult
PrepareForNewPart(nsIRequest
* aRequest
,
862 nsIInputStream
* aInStr
, uint32_t aCount
,
863 nsIURI
* aURI
, bool aIsMultipart
,
864 image::Image
* aExistingImage
,
865 ProgressTracker
* aProgressTracker
,
866 uint64_t aInnerWindowId
) {
867 NewPartResult
result(aExistingImage
);
870 mimetype_closure closure
;
871 closure
.newType
= &result
.mContentType
;
873 // Look at the first few bytes and see if we can tell what the data is from
874 // that since servers tend to lie. :(
876 aInStr
->ReadSegments(sniff_mimetype_callback
, &closure
, aCount
, &out
);
879 nsCOMPtr
<nsIChannel
> chan(do_QueryInterface(aRequest
));
880 if (result
.mContentType
.IsEmpty()) {
882 chan
? chan
->GetContentType(result
.mContentType
) : NS_ERROR_FAILURE
;
884 MOZ_LOG(gImgLog
, LogLevel::Error
,
885 ("imgRequest::PrepareForNewPart -- "
886 "Content type unavailable from the channel\n"));
894 chan
->GetContentDispositionHeader(result
.mContentDisposition
);
897 MOZ_LOG(gImgLog
, LogLevel::Debug
,
898 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
899 result
.mContentType
.get()));
901 // XXX If server lied about mimetype and it's SVG, we may need to copy
902 // the data and dispatch back to the main thread, AND tell the channel to
903 // dispatch there in the future.
905 // Create the new image and give it ownership of our ProgressTracker.
907 // Create the ProgressTracker and image for this part.
908 RefPtr
<ProgressTracker
> progressTracker
= new ProgressTracker();
909 RefPtr
<image::Image
> partImage
= image::ImageFactory::CreateImage(
910 aRequest
, progressTracker
, result
.mContentType
, aURI
,
911 /* aIsMultipart = */ true, aInnerWindowId
);
913 if (result
.mIsFirstPart
) {
914 // First part for a multipart channel. Create the MultipartImage wrapper.
915 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
916 aProgressTracker
->SetIsMultipart();
917 result
.mImage
= image::ImageFactory::CreateMultipartImage(
918 partImage
, aProgressTracker
);
920 // Transition to the new part.
921 auto multipartImage
= static_cast<MultipartImage
*>(aExistingImage
);
922 multipartImage
->BeginTransitionToPart(partImage
);
924 // Reset our cache entry size so it doesn't keep growing without bound.
925 result
.mShouldResetCacheEntry
= true;
928 MOZ_ASSERT(!aExistingImage
, "New part for non-multipart channel?");
929 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
931 // Create an image using our progress tracker.
932 result
.mImage
= image::ImageFactory::CreateImage(
933 aRequest
, aProgressTracker
, result
.mContentType
, aURI
,
934 /* aIsMultipart = */ false, aInnerWindowId
);
937 MOZ_ASSERT(result
.mImage
);
938 if (!result
.mImage
->HasError() || aIsMultipart
) {
939 // We allow multipart images to fail to initialize (which generally
940 // indicates a bad content type) without cancelling the load, because
941 // subsequent parts might be fine.
942 result
.mSucceeded
= true;
948 class FinishPreparingForNewPartRunnable final
: public Runnable
{
950 FinishPreparingForNewPartRunnable(imgRequest
* aImgRequest
,
951 NewPartResult
&& aResult
)
952 : Runnable("FinishPreparingForNewPartRunnable"),
953 mImgRequest(aImgRequest
),
955 MOZ_ASSERT(aImgRequest
);
958 NS_IMETHOD
Run() override
{
959 mImgRequest
->FinishPreparingForNewPart(mResult
);
964 RefPtr
<imgRequest
> mImgRequest
;
965 NewPartResult mResult
;
968 void imgRequest::FinishPreparingForNewPart(const NewPartResult
& aResult
) {
969 MOZ_ASSERT(NS_IsMainThread());
971 mContentType
= aResult
.mContentType
;
973 SetProperties(aResult
.mContentType
, aResult
.mContentDisposition
);
975 if (aResult
.mIsFirstPart
) {
976 // Notify listeners that we have an image.
977 mImageAvailable
= true;
978 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
979 progressTracker
->OnImageAvailable();
980 MOZ_ASSERT(progressTracker
->HasImage());
983 if (aResult
.mShouldResetCacheEntry
) {
987 if (IsDecodeRequested()) {
988 aResult
.mImage
->StartDecoding(imgIContainer::FLAG_NONE
);
992 bool imgRequest::ImageAvailable() const { return mImageAvailable
; }
995 imgRequest::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
996 uint64_t aOffset
, uint32_t aCount
) {
997 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::OnDataAvailable", "count", aCount
);
999 NS_ASSERTION(aRequest
, "imgRequest::OnDataAvailable -- no request!");
1001 RefPtr
<Image
> image
;
1002 RefPtr
<ProgressTracker
> progressTracker
;
1003 bool isMultipart
= false;
1004 bool newPartPending
= false;
1005 uint64_t innerWindowId
= 0;
1007 // Retrieve and update our state.
1009 MutexAutoLock
lock(mMutex
);
1011 progressTracker
= mProgressTracker
;
1012 isMultipart
= mIsMultiPartChannel
;
1013 newPartPending
= mNewPartPending
;
1014 mNewPartPending
= false;
1015 innerWindowId
= mInnerWindowId
;
1018 // If this is a new part, we need to sniff its content type and create an
1019 // appropriate image.
1020 if (newPartPending
) {
1021 NewPartResult result
=
1022 PrepareForNewPart(aRequest
, aInStr
, aCount
, mURI
, isMultipart
, image
,
1023 progressTracker
, innerWindowId
);
1024 bool succeeded
= result
.mSucceeded
;
1026 if (result
.mImage
) {
1027 image
= result
.mImage
;
1029 // Update our state to reflect this new part.
1031 MutexAutoLock
lock(mMutex
);
1034 mProgressTracker
= nullptr;
1037 // We only get an event target if we are not on the main thread, because
1038 // we have to dispatch in that case.
1039 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1040 if (!NS_IsMainThread()) {
1041 eventTarget
= GetMainThreadSerialEventTarget();
1042 MOZ_ASSERT(eventTarget
);
1045 // Some property objects are not threadsafe, and we need to send
1046 // OnImageAvailable on the main thread, so finish on the main thread.
1048 MOZ_ASSERT(NS_IsMainThread());
1049 FinishPreparingForNewPart(result
);
1051 nsCOMPtr
<nsIRunnable
> runnable
=
1052 new FinishPreparingForNewPartRunnable(this, std::move(result
));
1053 eventTarget
->Dispatch(CreateRenderBlockingRunnable(runnable
.forget()),
1054 NS_DISPATCH_NORMAL
);
1059 // Something went wrong; probably a content type issue.
1060 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
1061 return NS_BINDING_ABORTED
;
1065 // Notify the image that it has new data.
1068 image
->OnImageDataAvailable(aRequest
, aInStr
, aOffset
, aCount
);
1070 if (NS_FAILED(rv
)) {
1071 MOZ_LOG(gImgLog
, LogLevel::Warning
,
1072 ("[this=%p] imgRequest::OnDataAvailable -- "
1073 "copy to RasterImage failed\n",
1075 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
1076 return NS_BINDING_ABORTED
;
1083 void imgRequest::SetProperties(const nsACString
& aContentType
,
1084 const nsACString
& aContentDisposition
) {
1085 /* set our mimetype as a property */
1086 nsCOMPtr
<nsISupportsCString
> contentType
=
1087 do_CreateInstance("@mozilla.org/supports-cstring;1");
1089 contentType
->SetData(aContentType
);
1090 mProperties
->Set("type", contentType
);
1093 /* set our content disposition as a property */
1094 if (!aContentDisposition
.IsEmpty()) {
1095 nsCOMPtr
<nsISupportsCString
> contentDisposition
=
1096 do_CreateInstance("@mozilla.org/supports-cstring;1");
1097 if (contentDisposition
) {
1098 contentDisposition
->SetData(aContentDisposition
);
1099 mProperties
->Set("content-disposition", contentDisposition
);
1104 static nsresult
sniff_mimetype_callback(nsIInputStream
* in
, void* data
,
1105 const char* fromRawSegment
,
1106 uint32_t toOffset
, uint32_t count
,
1107 uint32_t* writeCount
) {
1108 mimetype_closure
* closure
= static_cast<mimetype_closure
*>(data
);
1110 NS_ASSERTION(closure
, "closure is null!");
1113 imgLoader::GetMimeTypeFromContent(fromRawSegment
, count
, *closure
->newType
);
1117 return NS_ERROR_FAILURE
;
1120 /** nsIInterfaceRequestor methods **/
1123 imgRequest::GetInterface(const nsIID
& aIID
, void** aResult
) {
1124 if (!mPrevChannelSink
|| aIID
.Equals(NS_GET_IID(nsIChannelEventSink
))) {
1125 return QueryInterface(aIID
, aResult
);
1129 mPrevChannelSink
!= this,
1130 "Infinite recursion - don't keep track of channel sinks that are us!");
1131 return mPrevChannelSink
->GetInterface(aIID
, aResult
);
1134 /** nsIChannelEventSink methods **/
1136 imgRequest::AsyncOnChannelRedirect(nsIChannel
* oldChannel
,
1137 nsIChannel
* newChannel
, uint32_t flags
,
1138 nsIAsyncVerifyRedirectCallback
* callback
) {
1139 NS_ASSERTION(mRequest
&& mChannel
,
1140 "Got a channel redirect after we nulled out mRequest!");
1141 NS_ASSERTION(mChannel
== oldChannel
,
1142 "Got a channel redirect for an unknown channel!");
1143 NS_ASSERTION(newChannel
, "Got a redirect to a NULL channel!");
1145 SetCacheValidation(mCacheEntry
, oldChannel
);
1147 // Prepare for callback
1148 mRedirectCallback
= callback
;
1149 mNewRedirectChannel
= newChannel
;
1151 nsCOMPtr
<nsIChannelEventSink
> sink(do_GetInterface(mPrevChannelSink
));
1154 sink
->AsyncOnChannelRedirect(oldChannel
, newChannel
, flags
, this);
1155 if (NS_FAILED(rv
)) {
1156 mRedirectCallback
= nullptr;
1157 mNewRedirectChannel
= nullptr;
1162 (void)OnRedirectVerifyCallback(NS_OK
);
1167 imgRequest::OnRedirectVerifyCallback(nsresult result
) {
1168 NS_ASSERTION(mRedirectCallback
, "mRedirectCallback not set in callback");
1169 NS_ASSERTION(mNewRedirectChannel
, "mNewRedirectChannel not set in callback");
1171 if (NS_FAILED(result
)) {
1172 mRedirectCallback
->OnRedirectVerifyCallback(result
);
1173 mRedirectCallback
= nullptr;
1174 mNewRedirectChannel
= nullptr;
1178 mChannel
= mNewRedirectChannel
;
1179 mTimedChannel
= do_QueryInterface(mChannel
);
1180 mNewRedirectChannel
= nullptr;
1182 if (LOG_TEST(LogLevel::Debug
)) {
1183 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::OnChannelRedirect", "old",
1184 mFinalURI
? mFinalURI
->GetSpecOrDefault().get() : "");
1187 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1188 // security code, which needs to know whether there is an insecure load at any
1189 // point in the redirect chain.
1190 bool schemeLocal
= false;
1191 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI
,
1192 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
,
1194 (!mFinalURI
->SchemeIs("https") && !mFinalURI
->SchemeIs("chrome") &&
1196 MutexAutoLock
lock(mMutex
);
1198 // The csp directive upgrade-insecure-requests performs an internal redirect
1199 // to upgrade all requests from http to https before any data is fetched
1200 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1201 // internal redirect.
1202 nsCOMPtr
<nsILoadInfo
> loadInfo
= mChannel
->LoadInfo();
1203 bool upgradeInsecureRequests
=
1204 loadInfo
? loadInfo
->GetUpgradeInsecureRequests() ||
1205 loadInfo
->GetBrowserUpgradeInsecureRequests()
1207 if (!upgradeInsecureRequests
) {
1208 mHadInsecureRedirect
= true;
1212 // Update the final URI.
1213 mChannel
->GetURI(getter_AddRefs(mFinalURI
));
1215 if (LOG_TEST(LogLevel::Debug
)) {
1216 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::OnChannelRedirect", "new",
1217 mFinalURI
? mFinalURI
->GetSpecOrDefault().get() : "");
1220 // Make sure we have a protocol that returns data rather than opens an
1221 // external application, e.g. 'mailto:'.
1222 if (nsContentUtils::IsExternalProtocol(mFinalURI
)) {
1223 mRedirectCallback
->OnRedirectVerifyCallback(NS_ERROR_ABORT
);
1224 mRedirectCallback
= nullptr;
1228 mRedirectCallback
->OnRedirectVerifyCallback(NS_OK
);
1229 mRedirectCallback
= nullptr;
1233 void imgRequest::UpdateShouldReportRenderTimeForLCP() {
1234 if (mTimedChannel
) {
1235 bool allRedirectPassTAO
= false;
1236 mTimedChannel
->GetAllRedirectsPassTimingAllowCheck(&allRedirectPassTAO
);
1237 mShouldReportRenderTimeForLCP
=
1238 mTimedChannel
->TimingAllowCheck(mTriggeringPrincipal
) &&