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 "mozilla/dom/Document.h"
22 #include "nsIThreadRetargetableRequest.h"
23 #include "nsIInputStream.h"
24 #include "nsIMultiPartChannel.h"
25 #include "nsIHttpChannel.h"
26 #include "nsIApplicationCache.h"
27 #include "nsIApplicationCacheChannel.h"
28 #include "nsMimeTypes.h"
30 #include "nsIInterfaceRequestorUtils.h"
31 #include "nsISupportsPrimitives.h"
32 #include "nsIScriptSecurityManager.h"
33 #include "nsContentUtils.h"
35 #include "plstr.h" // PL_strcasestr(...)
36 #include "prtime.h" // for PR_Now
37 #include "nsNetUtil.h"
38 #include "nsIProtocolHandler.h"
39 #include "imgIRequest.h"
40 #include "nsProperties.h"
42 #include "mozilla/IntegerPrintfMacros.h"
43 #include "mozilla/SizeOfState.h"
45 using namespace mozilla
;
46 using namespace mozilla::image
;
48 #define LOG_TEST(level) (MOZ_LOG_TEST(gImgLog, (level)))
50 NS_IMPL_ISUPPORTS(imgRequest
, nsIStreamListener
, nsIRequestObserver
,
51 nsIThreadRetargetableStreamListener
, nsIChannelEventSink
,
52 nsIInterfaceRequestor
, nsIAsyncVerifyRedirectCallback
)
54 imgRequest::imgRequest(imgLoader
* aLoader
, const ImageCacheKey
& aCacheKey
)
61 mCORSMode(imgIRequest::CORS_NONE
),
62 mImageErrorCode(NS_OK
),
63 mImageAvailable(false),
65 mProgressTracker(new ProgressTracker()),
66 mIsMultiPartChannel(false),
68 mDecodeRequested(false),
69 mNewPartPending(false),
70 mHadInsecureRedirect(false) {
71 LOG_FUNC(gImgLog
, "imgRequest::imgRequest()");
74 imgRequest::~imgRequest() {
76 mLoader
->RemoveFromUncachedImages(this);
79 LOG_FUNC_WITH_PARAM(gImgLog
, "imgRequest::~imgRequest()", "keyuri", mURI
);
81 LOG_FUNC(gImgLog
, "imgRequest::~imgRequest()");
84 nsresult
imgRequest::Init(nsIURI
* aURI
, nsIURI
* aFinalURI
,
85 bool aHadInsecureRedirect
, nsIRequest
* aRequest
,
86 nsIChannel
* aChannel
, imgCacheEntry
* aCacheEntry
,
87 nsISupports
* aCX
, nsIPrincipal
* aTriggeringPrincipal
,
88 int32_t aCORSMode
, nsIReferrerInfo
* aReferrerInfo
) {
89 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
91 LOG_FUNC(gImgLog
, "imgRequest::Init");
93 MOZ_ASSERT(!mImage
, "Multiple calls to init");
94 MOZ_ASSERT(aURI
, "No uri");
95 MOZ_ASSERT(aFinalURI
, "No final uri");
96 MOZ_ASSERT(aRequest
, "No request");
97 MOZ_ASSERT(aChannel
, "No channel");
99 mProperties
= new nsProperties();
101 mFinalURI
= aFinalURI
;
104 mTimedChannel
= do_QueryInterface(mChannel
);
105 mTriggeringPrincipal
= aTriggeringPrincipal
;
106 mCORSMode
= aCORSMode
;
107 mReferrerInfo
= aReferrerInfo
;
109 // If the original URI and the final URI are different, check whether the
110 // original URI is secure. We deliberately don't take the final URI into
111 // account, as it needs to be handled using more complicated rules than
112 // earlier elements of the redirect chain.
113 if (aURI
!= aFinalURI
) {
114 bool schemeLocal
= false;
115 if (NS_FAILED(NS_URIChainHasFlags(
116 aURI
, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
, &schemeLocal
)) ||
117 (!aURI
->SchemeIs("https") && !aURI
->SchemeIs("chrome") &&
119 mHadInsecureRedirect
= true;
123 // imgCacheValidator may have handled redirects before we were created, so we
124 // allow the caller to let us know if any redirects were insecure.
125 mHadInsecureRedirect
= mHadInsecureRedirect
|| aHadInsecureRedirect
;
127 mChannel
->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink
));
129 NS_ASSERTION(mPrevChannelSink
!= this,
130 "Initializing with a channel that already calls back to us!");
132 mChannel
->SetNotificationCallbacks(this);
134 mCacheEntry
= aCacheEntry
;
135 mCacheEntry
->UpdateLoadTime();
139 // Grab the inner window ID of the loading document, if possible.
140 nsCOMPtr
<dom::Document
> doc
= do_QueryInterface(aCX
);
142 mInnerWindowId
= doc
->InnerWindowID();
148 void imgRequest::ClearLoader() { mLoader
= nullptr; }
150 already_AddRefed
<ProgressTracker
> imgRequest::GetProgressTracker() const {
151 MutexAutoLock
lock(mMutex
);
154 MOZ_ASSERT(!mProgressTracker
,
155 "Should have given mProgressTracker to mImage");
156 return mImage
->GetProgressTracker();
158 MOZ_ASSERT(mProgressTracker
,
159 "Should have mProgressTracker until we create mImage");
160 RefPtr
<ProgressTracker
> progressTracker
= mProgressTracker
;
161 MOZ_ASSERT(progressTracker
);
162 return progressTracker
.forget();
165 void imgRequest::SetCacheEntry(imgCacheEntry
* entry
) { mCacheEntry
= entry
; }
167 bool imgRequest::HasCacheEntry() const { return mCacheEntry
!= nullptr; }
169 void imgRequest::ResetCacheEntry() {
170 if (HasCacheEntry()) {
171 mCacheEntry
->SetDataSize(0);
175 void imgRequest::AddProxy(imgRequestProxy
* proxy
) {
176 MOZ_ASSERT(proxy
, "null imgRequestProxy passed in");
177 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::AddProxy", "proxy", proxy
);
180 // Save a raw pointer to the first proxy we see, for use in the network
185 // If we're empty before adding, we have to tell the loader we now have
187 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
188 if (progressTracker
->ObserverCount() == 0) {
189 MOZ_ASSERT(mURI
, "Trying to SetHasProxies without key uri.");
191 mLoader
->SetHasProxies(this);
195 progressTracker
->AddObserver(proxy
);
198 nsresult
imgRequest::RemoveProxy(imgRequestProxy
* proxy
, nsresult aStatus
) {
199 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::RemoveProxy", "proxy", proxy
);
201 // This will remove our animation consumers, so after removing
202 // this proxy, we don't end up without proxies with observers, but still
203 // have animation consumers.
204 proxy
->ClearAnimationConsumers();
206 // Let the status tracker do its thing before we potentially call Cancel()
207 // below, because Cancel() may result in OnStopRequest being called back
208 // before Cancel() returns, leaving the image in a different state then the
209 // one it was in at this point.
210 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
211 if (!progressTracker
->RemoveObserver(proxy
)) {
215 if (progressTracker
->ObserverCount() == 0) {
216 // If we have no observers, there's nothing holding us alive. If we haven't
217 // been cancelled and thus removed from the cache, tell the image loader so
218 // we can be evicted from the cache.
220 MOZ_ASSERT(mURI
, "Removing last observer without key uri.");
223 mLoader
->SetHasNoProxies(this, mCacheEntry
);
226 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::RemoveProxy no cache entry",
230 /* If |aStatus| is a failure code, then cancel the load if it is still in
231 progress. Otherwise, let the load continue, keeping 'this' in the cache
232 with no observers. This way, if a proxy is destroyed without calling
233 cancel on it, it won't leak and won't leave a bad pointer in the observer
236 if (!(progressTracker
->GetProgress() & FLAG_LAST_PART_COMPLETE
) &&
237 NS_FAILED(aStatus
)) {
238 LOG_MSG(gImgLog
, "imgRequest::RemoveProxy",
239 "load in progress. canceling");
241 this->Cancel(NS_BINDING_ABORTED
);
244 /* break the cycle from the cache entry. */
245 mCacheEntry
= nullptr;
251 void imgRequest::CancelAndAbort(nsresult aStatus
) {
252 LOG_SCOPE(gImgLog
, "imgRequest::CancelAndAbort");
256 // It's possible for the channel to fail to open after we've set our
257 // notification callbacks. In that case, make sure to break the cycle between
258 // the channel and us, because it won't.
260 mChannel
->SetNotificationCallbacks(mPrevChannelSink
);
261 mPrevChannelSink
= nullptr;
265 class imgRequestMainThreadCancel
: public Runnable
{
267 imgRequestMainThreadCancel(imgRequest
* aImgRequest
, nsresult aStatus
)
268 : Runnable("imgRequestMainThreadCancel"),
269 mImgRequest(aImgRequest
),
271 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
272 MOZ_ASSERT(aImgRequest
);
275 NS_IMETHOD
Run() override
{
276 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
277 mImgRequest
->ContinueCancel(mStatus
);
282 RefPtr
<imgRequest
> mImgRequest
;
286 void imgRequest::Cancel(nsresult aStatus
) {
287 /* The Cancel() method here should only be called by this class. */
288 LOG_SCOPE(gImgLog
, "imgRequest::Cancel");
290 if (NS_IsMainThread()) {
291 ContinueCancel(aStatus
);
293 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
294 nsCOMPtr
<nsIEventTarget
> eventTarget
= progressTracker
->GetEventTarget();
295 nsCOMPtr
<nsIRunnable
> ev
= new imgRequestMainThreadCancel(this, aStatus
);
296 eventTarget
->Dispatch(ev
.forget(), NS_DISPATCH_NORMAL
);
300 void imgRequest::ContinueCancel(nsresult aStatus
) {
301 MOZ_ASSERT(NS_IsMainThread());
303 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
304 progressTracker
->SyncNotifyProgress(FLAG_HAS_ERROR
);
308 if (mRequest
&& !(progressTracker
->GetProgress() & FLAG_LAST_PART_COMPLETE
)) {
309 mRequest
->Cancel(aStatus
);
313 class imgRequestMainThreadEvict
: public Runnable
{
315 explicit imgRequestMainThreadEvict(imgRequest
* aImgRequest
)
316 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest
) {
317 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
318 MOZ_ASSERT(aImgRequest
);
321 NS_IMETHOD
Run() override
{
322 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
323 mImgRequest
->ContinueEvict();
328 RefPtr
<imgRequest
> mImgRequest
;
331 // EvictFromCache() is written to allowed to get called from any thread
332 void imgRequest::EvictFromCache() {
333 /* The EvictFromCache() method here should only be called by this class. */
334 LOG_SCOPE(gImgLog
, "imgRequest::EvictFromCache");
336 if (NS_IsMainThread()) {
339 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
343 // Helper-method used by EvictFromCache()
344 void imgRequest::ContinueEvict() {
345 MOZ_ASSERT(NS_IsMainThread());
350 void imgRequest::StartDecoding() {
351 MutexAutoLock
lock(mMutex
);
352 mDecodeRequested
= true;
355 bool imgRequest::IsDecodeRequested() const {
356 MutexAutoLock
lock(mMutex
);
357 return mDecodeRequested
;
360 nsresult
imgRequest::GetURI(nsIURI
** aURI
) {
363 LOG_FUNC(gImgLog
, "imgRequest::GetURI");
371 return NS_ERROR_FAILURE
;
374 nsresult
imgRequest::GetFinalURI(nsIURI
** aURI
) {
377 LOG_FUNC(gImgLog
, "imgRequest::GetFinalURI");
385 return NS_ERROR_FAILURE
;
388 bool imgRequest::IsChrome() const { return mURI
->SchemeIs("chrome"); }
390 bool imgRequest::IsData() const { return mURI
->SchemeIs("data"); }
392 nsresult
imgRequest::GetImageErrorCode() { return mImageErrorCode
; }
394 void imgRequest::RemoveFromCache() {
395 LOG_SCOPE(gImgLog
, "imgRequest::RemoveFromCache");
397 bool isInCache
= false;
400 MutexAutoLock
lock(mMutex
);
401 isInCache
= mIsInCache
;
404 if (isInCache
&& mLoader
) {
405 // mCacheEntry is nulled out when we have no more observers.
407 mLoader
->RemoveFromCache(mCacheEntry
);
409 mLoader
->RemoveFromCache(mCacheKey
);
413 mCacheEntry
= nullptr;
416 bool imgRequest::HasConsumers() const {
417 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
418 return progressTracker
&& progressTracker
->ObserverCount() > 0;
421 already_AddRefed
<image::Image
> imgRequest::GetImage() const {
422 MutexAutoLock
lock(mMutex
);
423 RefPtr
<image::Image
> image
= mImage
;
424 return image
.forget();
427 int32_t imgRequest::Priority() const {
428 int32_t priority
= nsISupportsPriority::PRIORITY_NORMAL
;
429 nsCOMPtr
<nsISupportsPriority
> p
= do_QueryInterface(mRequest
);
431 p
->GetPriority(&priority
);
436 void imgRequest::AdjustPriority(imgRequestProxy
* proxy
, int32_t delta
) {
437 // only the first proxy is allowed to modify the priority of this image load.
439 // XXX(darin): this is probably not the most optimal algorithm as we may want
440 // to increase the priority of requests that have a lot of proxies. the key
441 // concern though is that image loads remain lower priority than other pieces
442 // of content such as link clicks, CSS, and JS.
444 if (!mFirstProxy
|| proxy
!= mFirstProxy
) {
448 AdjustPriorityInternal(delta
);
451 void imgRequest::AdjustPriorityInternal(int32_t aDelta
) {
452 nsCOMPtr
<nsISupportsPriority
> p
= do_QueryInterface(mChannel
);
454 p
->AdjustPriority(aDelta
);
458 void imgRequest::BoostPriority(uint32_t aCategory
) {
459 if (!StaticPrefs::image_layout_network_priority()) {
463 uint32_t newRequestedCategory
=
464 (mBoostCategoriesRequested
& aCategory
) ^ aCategory
;
465 if (!newRequestedCategory
) {
466 // priority boost for each category can only apply once.
470 MOZ_LOG(gImgLog
, LogLevel::Debug
,
471 ("[this=%p] imgRequest::BoostPriority for category %x", this,
472 newRequestedCategory
));
476 if (newRequestedCategory
& imgIRequest::CATEGORY_FRAME_INIT
) {
480 if (newRequestedCategory
& imgIRequest::CATEGORY_FRAME_STYLE
) {
484 if (newRequestedCategory
& imgIRequest::CATEGORY_SIZE_QUERY
) {
488 if (newRequestedCategory
& imgIRequest::CATEGORY_DISPLAY
) {
489 delta
+= nsISupportsPriority::PRIORITY_HIGH
;
492 AdjustPriorityInternal(delta
);
493 mBoostCategoriesRequested
|= newRequestedCategory
;
496 void imgRequest::SetIsInCache(bool aInCache
) {
497 LOG_FUNC_WITH_PARAM(gImgLog
, "imgRequest::SetIsCacheable", "aInCache",
499 MutexAutoLock
lock(mMutex
);
500 mIsInCache
= aInCache
;
503 void imgRequest::UpdateCacheEntrySize() {
508 RefPtr
<Image
> image
= GetImage();
509 SizeOfState
state(moz_malloc_size_of
);
510 size_t size
= image
->SizeOfSourceWithComputedFallback(state
);
511 mCacheEntry
->SetDataSize(size
);
514 void imgRequest::SetCacheValidation(imgCacheEntry
* aCacheEntry
,
515 nsIRequest
* aRequest
) {
516 /* get the expires info */
518 // Expiration time defaults to 0. We set the expiration time on our
519 // entry if it hasn't been set yet.
520 if (aCacheEntry
->GetExpiryTime() == 0) {
521 uint32_t expiration
= 0;
522 nsCOMPtr
<nsICacheInfoChannel
> cacheChannel(do_QueryInterface(aRequest
));
524 /* get the expiration time from the caching channel's token */
525 cacheChannel
->GetCacheTokenExpirationTime(&expiration
);
527 if (expiration
== 0) {
528 // If the channel doesn't support caching, then ensure this expires the
529 // next time it is used.
530 expiration
= imgCacheEntry::SecondsFromPRTime(PR_Now()) - 1;
532 aCacheEntry
->SetExpiryTime(expiration
);
535 // Determine whether the cache entry must be revalidated when we try to use
536 // it. Currently, only HTTP specifies this information...
537 nsCOMPtr
<nsIHttpChannel
> httpChannel(do_QueryInterface(aRequest
));
539 bool bMustRevalidate
= false;
541 Unused
<< httpChannel
->IsNoStoreResponse(&bMustRevalidate
);
543 if (!bMustRevalidate
) {
544 Unused
<< httpChannel
->IsNoCacheResponse(&bMustRevalidate
);
547 if (!bMustRevalidate
) {
548 nsAutoCString cacheHeader
;
550 Unused
<< httpChannel
->GetResponseHeader(
551 NS_LITERAL_CSTRING("Cache-Control"), cacheHeader
);
552 if (PL_strcasestr(cacheHeader
.get(), "must-revalidate")) {
553 bMustRevalidate
= true;
557 // Cache entries default to not needing to validate. We ensure that
558 // multiple calls to this function don't override an earlier decision to
559 // validate by making validation a one-way decision.
560 if (bMustRevalidate
) {
561 aCacheEntry
->SetMustValidate(bMustRevalidate
);
569 already_AddRefed
<nsIApplicationCache
> GetApplicationCache(
570 nsIRequest
* aRequest
) {
573 nsCOMPtr
<nsIApplicationCacheChannel
> appCacheChan
=
574 do_QueryInterface(aRequest
);
580 rv
= appCacheChan
->GetLoadedFromApplicationCache(&fromAppCache
);
581 NS_ENSURE_SUCCESS(rv
, nullptr);
587 nsCOMPtr
<nsIApplicationCache
> appCache
;
588 rv
= appCacheChan
->GetApplicationCache(getter_AddRefs(appCache
));
589 NS_ENSURE_SUCCESS(rv
, nullptr);
591 return appCache
.forget();
596 bool imgRequest::CacheChanged(nsIRequest
* aNewRequest
) {
597 nsCOMPtr
<nsIApplicationCache
> newAppCache
= GetApplicationCache(aNewRequest
);
599 // Application cache not involved at all or the same app cache involved
600 // in both of the loads (original and new).
601 if (newAppCache
== mApplicationCache
) {
605 // In a rare case it may happen that two objects still refer
606 // the same application cache version.
607 if (newAppCache
&& mApplicationCache
) {
610 nsAutoCString oldAppCacheClientId
, newAppCacheClientId
;
611 rv
= mApplicationCache
->GetClientID(oldAppCacheClientId
);
612 NS_ENSURE_SUCCESS(rv
, true);
613 rv
= newAppCache
->GetClientID(newAppCacheClientId
);
614 NS_ENSURE_SUCCESS(rv
, true);
616 if (oldAppCacheClientId
== newAppCacheClientId
) {
621 // When we get here, app caches differ or app cache is involved
622 // just in one of the loads what we also consider as a change
623 // in a loading cache.
627 bool imgRequest::GetMultipart() const {
628 MutexAutoLock
lock(mMutex
);
629 return mIsMultiPartChannel
;
632 bool imgRequest::HadInsecureRedirect() const {
633 MutexAutoLock
lock(mMutex
);
634 return mHadInsecureRedirect
;
637 /** nsIRequestObserver methods **/
640 imgRequest::OnStartRequest(nsIRequest
* aRequest
) {
641 LOG_SCOPE(gImgLog
, "imgRequest::OnStartRequest");
645 // Figure out if we're multipart.
646 nsCOMPtr
<nsIMultiPartChannel
> multiPartChannel
= do_QueryInterface(aRequest
);
647 MOZ_ASSERT(multiPartChannel
|| !mIsMultiPartChannel
,
648 "Stopped being multipart?");
650 MutexAutoLock
lock(mMutex
);
651 mNewPartPending
= true;
653 mIsMultiPartChannel
= bool(multiPartChannel
);
656 // If we're not multipart, we shouldn't have an image yet.
657 if (image
&& !multiPartChannel
) {
658 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
659 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
660 return NS_ERROR_FAILURE
;
664 * If mRequest is null here, then we need to set it so that we'll be able to
665 * cancel it if our Cancel() method is called. Note that this can only
666 * happen for multipart channels. We could simply not null out mRequest for
667 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
668 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
671 MOZ_ASSERT(multiPartChannel
, "Should have mRequest unless we're multipart");
672 nsCOMPtr
<nsIChannel
> baseChannel
;
673 multiPartChannel
->GetBaseChannel(getter_AddRefs(baseChannel
));
674 mRequest
= baseChannel
;
677 nsCOMPtr
<nsIChannel
> channel(do_QueryInterface(aRequest
));
679 /* Get our principal */
680 nsCOMPtr
<nsIScriptSecurityManager
> secMan
=
681 nsContentUtils::GetSecurityManager();
683 nsresult rv
= secMan
->GetChannelResultPrincipal(
684 channel
, getter_AddRefs(mPrincipal
));
691 SetCacheValidation(mCacheEntry
, aRequest
);
693 mApplicationCache
= GetApplicationCache(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 // Retarget OnDataAvailable to the DecodePool's IO thread.
715 nsCOMPtr
<nsIEventTarget
> target
=
716 DecodePool::Singleton()->GetIOEventTarget();
717 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"));
730 imgRequest::OnStopRequest(nsIRequest
* aRequest
, nsresult status
) {
731 LOG_FUNC(gImgLog
, "imgRequest::OnStopRequest");
732 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
734 RefPtr
<Image
> image
= GetImage();
736 RefPtr
<imgRequest
> strongThis
= this;
738 if (mIsMultiPartChannel
&& mNewPartPending
) {
739 OnDataAvailable(aRequest
, nullptr, 0, 0);
742 // XXXldb What if this is a non-last part of a multipart request?
743 // xxx before we release our reference to mRequest, lets
744 // save the last status that we saw so that the
745 // imgRequestProxy will have access to it.
747 mRequest
= nullptr; // we no longer need the request
750 // stop holding a ref to the channel, since we don't need it anymore
752 mChannel
->SetNotificationCallbacks(mPrevChannelSink
);
753 mPrevChannelSink
= nullptr;
757 bool lastPart
= true;
758 nsCOMPtr
<nsIMultiPartChannel
> mpchan(do_QueryInterface(aRequest
));
760 mpchan
->GetIsLastPart(&lastPart
);
763 bool isPartial
= false;
764 if (image
&& (status
== NS_ERROR_NET_PARTIAL_TRANSFER
)) {
766 status
= NS_OK
; // fake happy face
769 // Tell the image that it has all of the source data. Note that this can
770 // trigger a failure, since the image might be waiting for more non-optional
771 // data and this is the point where we break the news that it's not coming.
774 image
->OnImageDataComplete(aRequest
, nullptr, status
, lastPart
);
776 // If we got an error in the OnImageDataComplete() call, we don't want to
777 // proceed as if nothing bad happened. However, we also want to give
778 // precedence to failure status codes from necko, since presumably they're
780 if (NS_FAILED(rv
) && NS_SUCCEEDED(status
)) {
785 // If the request went through, update the cache entry size. Otherwise,
786 // cancel the request, which removes us from the cache.
787 if (image
&& NS_SUCCEEDED(status
) && !isPartial
) {
788 // We update the cache entry size here because this is where we finish
789 // loading compressed source data, which is part of our size calculus.
790 UpdateCacheEntrySize();
792 } else if (isPartial
) {
793 // Remove the partial image from the cache.
794 this->EvictFromCache();
797 mImageErrorCode
= status
;
799 // if the error isn't "just" a partial transfer
800 // stops animations, removes from cache
801 this->Cancel(status
);
805 // We have to fire the OnStopRequest notifications ourselves because there's
806 // no image capable of doing so.
808 LoadCompleteProgress(lastPart
, /* aError = */ false, status
);
810 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
811 progressTracker
->SyncNotifyProgress(progress
);
814 mTimedChannel
= nullptr;
818 struct mimetype_closure
{
822 /* prototype for these defined below */
823 static nsresult
sniff_mimetype_callback(nsIInputStream
* in
, void* closure
,
824 const char* fromRawSegment
,
825 uint32_t toOffset
, uint32_t count
,
826 uint32_t* writeCount
);
828 /** nsThreadRetargetableStreamListener methods **/
830 imgRequest::CheckListenerChain() {
831 // TODO Might need more checking here.
832 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
836 /** nsIStreamListener methods **/
838 struct NewPartResult final
{
839 explicit NewPartResult(image::Image
* aExistingImage
)
840 : mImage(aExistingImage
),
841 mIsFirstPart(!aExistingImage
),
843 mShouldResetCacheEntry(false) {}
845 nsAutoCString mContentType
;
846 nsAutoCString mContentDisposition
;
847 RefPtr
<image::Image
> mImage
;
848 const bool mIsFirstPart
;
850 bool mShouldResetCacheEntry
;
853 static NewPartResult
PrepareForNewPart(nsIRequest
* aRequest
,
854 nsIInputStream
* aInStr
, uint32_t aCount
,
855 nsIURI
* aURI
, bool aIsMultipart
,
856 image::Image
* aExistingImage
,
857 ProgressTracker
* aProgressTracker
,
858 uint32_t aInnerWindowId
) {
859 NewPartResult
result(aExistingImage
);
862 mimetype_closure closure
;
863 closure
.newType
= &result
.mContentType
;
865 // Look at the first few bytes and see if we can tell what the data is from
866 // that since servers tend to lie. :(
868 aInStr
->ReadSegments(sniff_mimetype_callback
, &closure
, aCount
, &out
);
871 nsCOMPtr
<nsIChannel
> chan(do_QueryInterface(aRequest
));
872 if (result
.mContentType
.IsEmpty()) {
874 chan
? chan
->GetContentType(result
.mContentType
) : NS_ERROR_FAILURE
;
876 MOZ_LOG(gImgLog
, LogLevel::Error
,
877 ("imgRequest::PrepareForNewPart -- "
878 "Content type unavailable from the channel\n"));
886 chan
->GetContentDispositionHeader(result
.mContentDisposition
);
889 MOZ_LOG(gImgLog
, LogLevel::Debug
,
890 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
891 result
.mContentType
.get()));
893 // XXX If server lied about mimetype and it's SVG, we may need to copy
894 // the data and dispatch back to the main thread, AND tell the channel to
895 // dispatch there in the future.
897 // Create the new image and give it ownership of our ProgressTracker.
899 // Create the ProgressTracker and image for this part.
900 RefPtr
<ProgressTracker
> progressTracker
= new ProgressTracker();
901 RefPtr
<image::Image
> partImage
= image::ImageFactory::CreateImage(
902 aRequest
, progressTracker
, result
.mContentType
, aURI
,
903 /* aIsMultipart = */ true, aInnerWindowId
);
905 if (result
.mIsFirstPart
) {
906 // First part for a multipart channel. Create the MultipartImage wrapper.
907 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
908 aProgressTracker
->SetIsMultipart();
909 result
.mImage
= image::ImageFactory::CreateMultipartImage(
910 partImage
, aProgressTracker
);
912 // Transition to the new part.
913 auto multipartImage
= static_cast<MultipartImage
*>(aExistingImage
);
914 multipartImage
->BeginTransitionToPart(partImage
);
916 // Reset our cache entry size so it doesn't keep growing without bound.
917 result
.mShouldResetCacheEntry
= true;
920 MOZ_ASSERT(!aExistingImage
, "New part for non-multipart channel?");
921 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
923 // Create an image using our progress tracker.
924 result
.mImage
= image::ImageFactory::CreateImage(
925 aRequest
, aProgressTracker
, result
.mContentType
, aURI
,
926 /* aIsMultipart = */ false, aInnerWindowId
);
929 MOZ_ASSERT(result
.mImage
);
930 if (!result
.mImage
->HasError() || aIsMultipart
) {
931 // We allow multipart images to fail to initialize (which generally
932 // indicates a bad content type) without cancelling the load, because
933 // subsequent parts might be fine.
934 result
.mSucceeded
= true;
940 class FinishPreparingForNewPartRunnable final
: public Runnable
{
942 FinishPreparingForNewPartRunnable(imgRequest
* aImgRequest
,
943 NewPartResult
&& aResult
)
944 : Runnable("FinishPreparingForNewPartRunnable"),
945 mImgRequest(aImgRequest
),
947 MOZ_ASSERT(aImgRequest
);
950 NS_IMETHOD
Run() override
{
951 mImgRequest
->FinishPreparingForNewPart(mResult
);
956 RefPtr
<imgRequest
> mImgRequest
;
957 NewPartResult mResult
;
960 void imgRequest::FinishPreparingForNewPart(const NewPartResult
& aResult
) {
961 MOZ_ASSERT(NS_IsMainThread());
963 mContentType
= aResult
.mContentType
;
965 SetProperties(aResult
.mContentType
, aResult
.mContentDisposition
);
967 if (aResult
.mIsFirstPart
) {
968 // Notify listeners that we have an image.
969 mImageAvailable
= true;
970 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
971 progressTracker
->OnImageAvailable();
972 MOZ_ASSERT(progressTracker
->HasImage());
975 if (aResult
.mShouldResetCacheEntry
) {
979 if (IsDecodeRequested()) {
980 aResult
.mImage
->StartDecoding(imgIContainer::FLAG_NONE
);
984 bool imgRequest::ImageAvailable() const { return mImageAvailable
; }
987 imgRequest::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
988 uint64_t aOffset
, uint32_t aCount
) {
989 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::OnDataAvailable", "count", aCount
);
991 NS_ASSERTION(aRequest
, "imgRequest::OnDataAvailable -- no request!");
994 RefPtr
<ProgressTracker
> progressTracker
;
995 bool isMultipart
= false;
996 bool newPartPending
= false;
998 // Retrieve and update our state.
1000 MutexAutoLock
lock(mMutex
);
1002 progressTracker
= mProgressTracker
;
1003 isMultipart
= mIsMultiPartChannel
;
1004 newPartPending
= mNewPartPending
;
1005 mNewPartPending
= false;
1008 // If this is a new part, we need to sniff its content type and create an
1009 // appropriate image.
1010 if (newPartPending
) {
1011 NewPartResult result
=
1012 PrepareForNewPart(aRequest
, aInStr
, aCount
, mURI
, isMultipart
, image
,
1013 progressTracker
, mInnerWindowId
);
1014 bool succeeded
= result
.mSucceeded
;
1016 if (result
.mImage
) {
1017 image
= result
.mImage
;
1018 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1020 // Update our state to reflect this new part.
1022 MutexAutoLock
lock(mMutex
);
1025 // We only get an event target if we are not on the main thread, because
1026 // we have to dispatch in that case. If we are on the main thread, but
1027 // on a different scheduler group than ProgressTracker would give us,
1028 // that is okay because nothing in imagelib requires that, just our
1029 // listeners (which have their own checks).
1030 if (!NS_IsMainThread()) {
1031 eventTarget
= mProgressTracker
->GetEventTarget();
1032 MOZ_ASSERT(eventTarget
);
1035 mProgressTracker
= nullptr;
1038 // Some property objects are not threadsafe, and we need to send
1039 // OnImageAvailable on the main thread, so finish on the main thread.
1041 MOZ_ASSERT(NS_IsMainThread());
1042 FinishPreparingForNewPart(result
);
1044 nsCOMPtr
<nsIRunnable
> runnable
=
1045 new FinishPreparingForNewPartRunnable(this, std::move(result
));
1046 eventTarget
->Dispatch(CreateMediumHighRunnable(runnable
.forget()),
1047 NS_DISPATCH_NORMAL
);
1052 // Something went wrong; probably a content type issue.
1053 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
1054 return NS_BINDING_ABORTED
;
1058 // Notify the image that it has new data.
1061 image
->OnImageDataAvailable(aRequest
, nullptr, aInStr
, aOffset
, aCount
);
1063 if (NS_FAILED(rv
)) {
1064 MOZ_LOG(gImgLog
, LogLevel::Warning
,
1065 ("[this=%p] imgRequest::OnDataAvailable -- "
1066 "copy to RasterImage failed\n",
1068 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
1069 return NS_BINDING_ABORTED
;
1076 void imgRequest::SetProperties(const nsACString
& aContentType
,
1077 const nsACString
& aContentDisposition
) {
1078 /* set our mimetype as a property */
1079 nsCOMPtr
<nsISupportsCString
> contentType
=
1080 do_CreateInstance("@mozilla.org/supports-cstring;1");
1082 contentType
->SetData(aContentType
);
1083 mProperties
->Set("type", contentType
);
1086 /* set our content disposition as a property */
1087 if (!aContentDisposition
.IsEmpty()) {
1088 nsCOMPtr
<nsISupportsCString
> contentDisposition
=
1089 do_CreateInstance("@mozilla.org/supports-cstring;1");
1090 if (contentDisposition
) {
1091 contentDisposition
->SetData(aContentDisposition
);
1092 mProperties
->Set("content-disposition", contentDisposition
);
1097 static nsresult
sniff_mimetype_callback(nsIInputStream
* in
, void* data
,
1098 const char* fromRawSegment
,
1099 uint32_t toOffset
, uint32_t count
,
1100 uint32_t* writeCount
) {
1101 mimetype_closure
* closure
= static_cast<mimetype_closure
*>(data
);
1103 NS_ASSERTION(closure
, "closure is null!");
1106 imgLoader::GetMimeTypeFromContent(fromRawSegment
, count
, *closure
->newType
);
1110 return NS_ERROR_FAILURE
;
1113 /** nsIInterfaceRequestor methods **/
1116 imgRequest::GetInterface(const nsIID
& aIID
, void** aResult
) {
1117 if (!mPrevChannelSink
|| aIID
.Equals(NS_GET_IID(nsIChannelEventSink
))) {
1118 return QueryInterface(aIID
, aResult
);
1122 mPrevChannelSink
!= this,
1123 "Infinite recursion - don't keep track of channel sinks that are us!");
1124 return mPrevChannelSink
->GetInterface(aIID
, aResult
);
1127 /** nsIChannelEventSink methods **/
1129 imgRequest::AsyncOnChannelRedirect(nsIChannel
* oldChannel
,
1130 nsIChannel
* newChannel
, uint32_t flags
,
1131 nsIAsyncVerifyRedirectCallback
* callback
) {
1132 NS_ASSERTION(mRequest
&& mChannel
,
1133 "Got a channel redirect after we nulled out mRequest!");
1134 NS_ASSERTION(mChannel
== oldChannel
,
1135 "Got a channel redirect for an unknown channel!");
1136 NS_ASSERTION(newChannel
, "Got a redirect to a NULL channel!");
1138 SetCacheValidation(mCacheEntry
, oldChannel
);
1140 // Prepare for callback
1141 mRedirectCallback
= callback
;
1142 mNewRedirectChannel
= newChannel
;
1144 nsCOMPtr
<nsIChannelEventSink
> sink(do_GetInterface(mPrevChannelSink
));
1147 sink
->AsyncOnChannelRedirect(oldChannel
, newChannel
, flags
, this);
1148 if (NS_FAILED(rv
)) {
1149 mRedirectCallback
= nullptr;
1150 mNewRedirectChannel
= nullptr;
1155 (void)OnRedirectVerifyCallback(NS_OK
);
1160 imgRequest::OnRedirectVerifyCallback(nsresult result
) {
1161 NS_ASSERTION(mRedirectCallback
, "mRedirectCallback not set in callback");
1162 NS_ASSERTION(mNewRedirectChannel
, "mNewRedirectChannel not set in callback");
1164 if (NS_FAILED(result
)) {
1165 mRedirectCallback
->OnRedirectVerifyCallback(result
);
1166 mRedirectCallback
= nullptr;
1167 mNewRedirectChannel
= nullptr;
1171 mChannel
= mNewRedirectChannel
;
1172 mTimedChannel
= do_QueryInterface(mChannel
);
1173 mNewRedirectChannel
= nullptr;
1175 if (LOG_TEST(LogLevel::Debug
)) {
1176 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::OnChannelRedirect", "old",
1177 mFinalURI
? mFinalURI
->GetSpecOrDefault().get() : "");
1180 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1181 // security code, which needs to know whether there is an insecure load at any
1182 // point in the redirect chain.
1183 bool schemeLocal
= false;
1184 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI
,
1185 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
,
1187 (!mFinalURI
->SchemeIs("https") && !mFinalURI
->SchemeIs("chrome") &&
1189 MutexAutoLock
lock(mMutex
);
1191 // The csp directive upgrade-insecure-requests performs an internal redirect
1192 // to upgrade all requests from http to https before any data is fetched
1193 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1194 // internal redirect.
1195 nsCOMPtr
<nsILoadInfo
> loadInfo
= mChannel
->LoadInfo();
1196 bool upgradeInsecureRequests
=
1197 loadInfo
? loadInfo
->GetUpgradeInsecureRequests() ||
1198 loadInfo
->GetBrowserUpgradeInsecureRequests()
1200 if (!upgradeInsecureRequests
) {
1201 mHadInsecureRedirect
= true;
1205 // Update the final URI.
1206 mChannel
->GetURI(getter_AddRefs(mFinalURI
));
1208 if (LOG_TEST(LogLevel::Debug
)) {
1209 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::OnChannelRedirect", "new",
1210 mFinalURI
? mFinalURI
->GetSpecOrDefault().get() : "");
1213 // Make sure we have a protocol that returns data rather than opens an
1214 // external application, e.g. 'mailto:'.
1215 bool doesNotReturnData
= false;
1216 nsresult rv
= NS_URIChainHasFlags(
1217 mFinalURI
, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA
,
1218 &doesNotReturnData
);
1220 if (NS_SUCCEEDED(rv
) && doesNotReturnData
) {
1221 rv
= NS_ERROR_ABORT
;
1224 if (NS_FAILED(rv
)) {
1225 mRedirectCallback
->OnRedirectVerifyCallback(rv
);
1226 mRedirectCallback
= nullptr;
1230 mRedirectCallback
->OnRedirectVerifyCallback(NS_OK
);
1231 mRedirectCallback
= nullptr;