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),
67 mProgressTracker(new ProgressTracker()),
68 mIsMultiPartChannel(false),
70 mDecodeRequested(false),
71 mNewPartPending(false),
72 mHadInsecureRedirect(false),
74 LOG_FUNC(gImgLog
, "imgRequest::imgRequest()");
77 imgRequest::~imgRequest() {
79 mLoader
->RemoveFromUncachedImages(this);
82 LOG_FUNC_WITH_PARAM(gImgLog
, "imgRequest::~imgRequest()", "keyuri", mURI
);
84 LOG_FUNC(gImgLog
, "imgRequest::~imgRequest()");
87 nsresult
imgRequest::Init(
88 nsIURI
* aURI
, nsIURI
* aFinalURI
, bool aHadInsecureRedirect
,
89 nsIRequest
* aRequest
, nsIChannel
* aChannel
, imgCacheEntry
* aCacheEntry
,
90 mozilla::dom::Document
* aLoadingDocument
,
91 nsIPrincipal
* aTriggeringPrincipal
, mozilla::CORSMode aCORSMode
,
92 nsIReferrerInfo
* aReferrerInfo
) MOZ_NO_THREAD_SAFETY_ANALYSIS
{
93 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
94 // Init() can only be called once, and that's before it can be used off
97 LOG_FUNC(gImgLog
, "imgRequest::Init");
99 MOZ_ASSERT(!mImage
, "Multiple calls to init");
100 MOZ_ASSERT(aURI
, "No uri");
101 MOZ_ASSERT(aFinalURI
, "No final uri");
102 MOZ_ASSERT(aRequest
, "No request");
103 MOZ_ASSERT(aChannel
, "No channel");
105 mProperties
= new nsProperties();
107 mFinalURI
= aFinalURI
;
110 mTimedChannel
= do_QueryInterface(mChannel
);
111 mTriggeringPrincipal
= aTriggeringPrincipal
;
112 mCORSMode
= aCORSMode
;
113 mReferrerInfo
= aReferrerInfo
;
115 // If the original URI and the final URI are different, check whether the
116 // original URI is secure. We deliberately don't take the final URI into
117 // account, as it needs to be handled using more complicated rules than
118 // earlier elements of the redirect chain.
119 if (aURI
!= aFinalURI
) {
120 bool schemeLocal
= false;
121 if (NS_FAILED(NS_URIChainHasFlags(
122 aURI
, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
, &schemeLocal
)) ||
123 (!aURI
->SchemeIs("https") && !aURI
->SchemeIs("chrome") &&
125 mHadInsecureRedirect
= true;
129 // imgCacheValidator may have handled redirects before we were created, so we
130 // allow the caller to let us know if any redirects were insecure.
131 mHadInsecureRedirect
= mHadInsecureRedirect
|| aHadInsecureRedirect
;
133 mChannel
->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink
));
135 NS_ASSERTION(mPrevChannelSink
!= this,
136 "Initializing with a channel that already calls back to us!");
138 mChannel
->SetNotificationCallbacks(this);
140 mCacheEntry
= aCacheEntry
;
141 mCacheEntry
->UpdateLoadTime();
143 SetLoadId(aLoadingDocument
);
145 // Grab the inner window ID of the loading document, if possible.
146 if (aLoadingDocument
) {
147 mInnerWindowId
= aLoadingDocument
->InnerWindowID();
153 bool imgRequest::CanReuseWithoutValidation(dom::Document
* aDoc
) const {
154 // If the request's loadId is the same as the aLoadingDocument, then it is ok
155 // to use this one because it has already been validated for this context.
156 // XXX: nullptr seems to be a 'special' key value that indicates that NO
157 // validation is required.
158 // XXX: we also check the window ID because the loadID() can return a reused
159 // pointer of a document. This can still happen for non-document image
161 void* key
= (void*)aDoc
;
162 uint64_t innerWindowID
= aDoc
? aDoc
->InnerWindowID() : 0;
163 if (LoadId() == key
&& InnerWindowID() == innerWindowID
) {
167 // As a special-case, if this is a print preview document, also validate on
168 // the original document. This allows to print uncacheable images.
169 if (dom::Document
* original
= aDoc
? aDoc
->GetOriginalDocument() : nullptr) {
170 return CanReuseWithoutValidation(original
);
176 void imgRequest::ClearLoader() { mLoader
= nullptr; }
178 already_AddRefed
<nsIPrincipal
> imgRequest::GetTriggeringPrincipal() const {
179 nsCOMPtr
<nsIPrincipal
> principal
= mTriggeringPrincipal
;
180 return principal
.forget();
183 already_AddRefed
<ProgressTracker
> imgRequest::GetProgressTracker() const {
184 MutexAutoLock
lock(mMutex
);
187 MOZ_ASSERT(!mProgressTracker
,
188 "Should have given mProgressTracker to mImage");
189 return mImage
->GetProgressTracker();
191 MOZ_ASSERT(mProgressTracker
,
192 "Should have mProgressTracker until we create mImage");
193 RefPtr
<ProgressTracker
> progressTracker
= mProgressTracker
;
194 MOZ_ASSERT(progressTracker
);
195 return progressTracker
.forget();
198 void imgRequest::SetCacheEntry(imgCacheEntry
* entry
) { mCacheEntry
= entry
; }
200 bool imgRequest::HasCacheEntry() const { return mCacheEntry
!= nullptr; }
202 void imgRequest::ResetCacheEntry() {
203 if (HasCacheEntry()) {
204 mCacheEntry
->SetDataSize(0);
208 void imgRequest::AddProxy(imgRequestProxy
* proxy
) {
209 MOZ_ASSERT(proxy
, "null imgRequestProxy passed in");
210 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::AddProxy", "proxy", proxy
);
213 // Save a raw pointer to the first proxy we see, for use in the network
218 // If we're empty before adding, we have to tell the loader we now have
220 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
221 if (progressTracker
->ObserverCount() == 0) {
222 MOZ_ASSERT(mURI
, "Trying to SetHasProxies without key uri.");
224 mLoader
->SetHasProxies(this);
228 progressTracker
->AddObserver(proxy
);
231 nsresult
imgRequest::RemoveProxy(imgRequestProxy
* proxy
, nsresult aStatus
) {
232 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::RemoveProxy", "proxy", proxy
);
234 // This will remove our animation consumers, so after removing
235 // this proxy, we don't end up without proxies with observers, but still
236 // have animation consumers.
237 proxy
->ClearAnimationConsumers();
239 // Let the status tracker do its thing before we potentially call Cancel()
240 // below, because Cancel() may result in OnStopRequest being called back
241 // before Cancel() returns, leaving the image in a different state then the
242 // one it was in at this point.
243 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
244 if (!progressTracker
->RemoveObserver(proxy
)) {
248 if (progressTracker
->ObserverCount() == 0) {
249 // If we have no observers, there's nothing holding us alive. If we haven't
250 // been cancelled and thus removed from the cache, tell the image loader so
251 // we can be evicted from the cache.
253 MOZ_ASSERT(mURI
, "Removing last observer without key uri.");
256 mLoader
->SetHasNoProxies(this, mCacheEntry
);
259 LOG_MSG_WITH_PARAM(gImgLog
, "imgRequest::RemoveProxy no cache entry",
263 /* If |aStatus| is a failure code, then cancel the load if it is still in
264 progress. Otherwise, let the load continue, keeping 'this' in the cache
265 with no observers. This way, if a proxy is destroyed without calling
266 cancel on it, it won't leak and won't leave a bad pointer in the observer
269 if (!(progressTracker
->GetProgress() & FLAG_LAST_PART_COMPLETE
) &&
270 NS_FAILED(aStatus
)) {
271 LOG_MSG(gImgLog
, "imgRequest::RemoveProxy",
272 "load in progress. canceling");
274 this->Cancel(NS_BINDING_ABORTED
);
277 /* break the cycle from the cache entry. */
278 mCacheEntry
= nullptr;
284 uint64_t imgRequest::InnerWindowID() const {
285 MutexAutoLock
lock(mMutex
);
286 return mInnerWindowId
;
289 void imgRequest::SetInnerWindowID(uint64_t aInnerWindowId
) {
290 MutexAutoLock
lock(mMutex
);
291 mInnerWindowId
= aInnerWindowId
;
294 void imgRequest::CancelAndAbort(nsresult aStatus
) {
295 LOG_SCOPE(gImgLog
, "imgRequest::CancelAndAbort");
299 // It's possible for the channel to fail to open after we've set our
300 // notification callbacks. In that case, make sure to break the cycle between
301 // the channel and us, because it won't.
303 mChannel
->SetNotificationCallbacks(mPrevChannelSink
);
304 mPrevChannelSink
= nullptr;
308 class imgRequestMainThreadCancel
: public Runnable
{
310 imgRequestMainThreadCancel(imgRequest
* aImgRequest
, nsresult aStatus
)
311 : Runnable("imgRequestMainThreadCancel"),
312 mImgRequest(aImgRequest
),
314 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
315 MOZ_ASSERT(aImgRequest
);
318 NS_IMETHOD
Run() override
{
319 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
320 mImgRequest
->ContinueCancel(mStatus
);
325 RefPtr
<imgRequest
> mImgRequest
;
329 void imgRequest::Cancel(nsresult aStatus
) {
330 /* The Cancel() method here should only be called by this class. */
331 LOG_SCOPE(gImgLog
, "imgRequest::Cancel");
333 if (NS_IsMainThread()) {
334 ContinueCancel(aStatus
);
336 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
337 nsCOMPtr
<nsIEventTarget
> eventTarget
= progressTracker
->GetEventTarget();
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 // Figure out if we're multipart.
645 nsCOMPtr
<nsIMultiPartChannel
> multiPartChannel
= do_QueryInterface(aRequest
);
647 MutexAutoLock
lock(mMutex
);
649 MOZ_ASSERT(multiPartChannel
|| !mIsMultiPartChannel
,
650 "Stopped being multipart?");
652 mNewPartPending
= true;
654 mIsMultiPartChannel
= bool(multiPartChannel
);
657 // If we're not multipart, we shouldn't have an image yet.
658 if (image
&& !multiPartChannel
) {
659 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
660 Cancel(NS_IMAGELIB_ERROR_FAILURE
);
661 return NS_ERROR_FAILURE
;
665 * If mRequest is null here, then we need to set it so that we'll be able to
666 * cancel it if our Cancel() method is called. Note that this can only
667 * happen for multipart channels. We could simply not null out mRequest for
668 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
669 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
672 MOZ_ASSERT(multiPartChannel
, "Should have mRequest unless we're multipart");
673 nsCOMPtr
<nsIChannel
> baseChannel
;
674 multiPartChannel
->GetBaseChannel(getter_AddRefs(baseChannel
));
675 mRequest
= baseChannel
;
678 nsCOMPtr
<nsIChannel
> channel(do_QueryInterface(aRequest
));
680 /* Get our principal */
681 nsCOMPtr
<nsIScriptSecurityManager
> secMan
=
682 nsContentUtils::GetSecurityManager();
684 nsresult rv
= secMan
->GetChannelResultPrincipal(
685 channel
, getter_AddRefs(mPrincipal
));
692 SetCacheValidation(mCacheEntry
, aRequest
);
694 // Shouldn't we be dead already if this gets hit?
695 // Probably multipart/x-mixed-replace...
696 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
697 if (progressTracker
->ObserverCount() == 0) {
698 this->Cancel(NS_IMAGELIB_ERROR_FAILURE
);
701 // Try to retarget OnDataAvailable to a decode thread. We must process data
702 // URIs synchronously as per the spec however.
703 if (!channel
|| IsData()) {
707 nsCOMPtr
<nsIThreadRetargetableRequest
> retargetable
=
708 do_QueryInterface(aRequest
);
710 nsAutoCString mimeType
;
711 nsresult rv
= channel
->GetContentType(mimeType
);
712 if (NS_SUCCEEDED(rv
) && !mimeType
.EqualsLiteral(IMAGE_SVG_XML
)) {
713 // Retarget OnDataAvailable to the DecodePool's IO thread.
714 nsCOMPtr
<nsIEventTarget
> target
=
715 DecodePool::Singleton()->GetIOEventTarget();
716 rv
= retargetable
->RetargetDeliveryTo(target
);
718 MOZ_LOG(gImgLog
, LogLevel::Warning
,
719 ("[this=%p] imgRequest::OnStartRequest -- "
720 "RetargetDeliveryTo rv %" PRIu32
"=%s\n",
721 this, static_cast<uint32_t>(rv
),
722 NS_SUCCEEDED(rv
) ? "succeeded" : "failed"));
729 imgRequest::OnStopRequest(nsIRequest
* aRequest
, nsresult status
) {
730 LOG_FUNC(gImgLog
, "imgRequest::OnStopRequest");
731 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
733 RefPtr
<Image
> image
= GetImage();
735 RefPtr
<imgRequest
> strongThis
= this;
737 bool isMultipart
= false;
738 bool newPartPending
= false;
740 MutexAutoLock
lock(mMutex
);
741 isMultipart
= mIsMultiPartChannel
;
742 newPartPending
= mNewPartPending
;
744 if (isMultipart
&& newPartPending
) {
745 OnDataAvailable(aRequest
, nullptr, 0, 0);
748 // XXXldb What if this is a non-last part of a multipart request?
749 // xxx before we release our reference to mRequest, lets
750 // save the last status that we saw so that the
751 // imgRequestProxy will have access to it.
753 mRequest
= nullptr; // we no longer need the request
756 // stop holding a ref to the channel, since we don't need it anymore
758 mChannel
->SetNotificationCallbacks(mPrevChannelSink
);
759 mPrevChannelSink
= nullptr;
763 bool lastPart
= true;
764 nsCOMPtr
<nsIMultiPartChannel
> mpchan(do_QueryInterface(aRequest
));
766 mpchan
->GetIsLastPart(&lastPart
);
769 bool isPartial
= false;
770 if (image
&& (status
== NS_ERROR_NET_PARTIAL_TRANSFER
)) {
772 status
= NS_OK
; // fake happy face
775 // Tell the image that it has all of the source data. Note that this can
776 // trigger a failure, since the image might be waiting for more non-optional
777 // data and this is the point where we break the news that it's not coming.
779 nsresult rv
= image
->OnImageDataComplete(aRequest
, status
, lastPart
);
781 // If we got an error in the OnImageDataComplete() call, we don't want to
782 // proceed as if nothing bad happened. However, we also want to give
783 // precedence to failure status codes from necko, since presumably they're
785 if (NS_FAILED(rv
) && NS_SUCCEEDED(status
)) {
790 // If the request went through, update the cache entry size. Otherwise,
791 // cancel the request, which removes us from the cache.
792 if (image
&& NS_SUCCEEDED(status
) && !isPartial
) {
793 // We update the cache entry size here because this is where we finish
794 // loading compressed source data, which is part of our size calculus.
795 UpdateCacheEntrySize();
797 } else if (isPartial
) {
798 // Remove the partial image from the cache.
799 this->EvictFromCache();
802 mImageErrorCode
= status
;
804 // if the error isn't "just" a partial transfer
805 // stops animations, removes from cache
806 this->Cancel(status
);
810 // We have to fire the OnStopRequest notifications ourselves because there's
811 // no image capable of doing so.
813 LoadCompleteProgress(lastPart
, /* aError = */ false, status
);
815 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
816 progressTracker
->SyncNotifyProgress(progress
);
819 mTimedChannel
= nullptr;
823 struct mimetype_closure
{
827 /* prototype for these defined below */
828 static nsresult
sniff_mimetype_callback(nsIInputStream
* in
, void* closure
,
829 const char* fromRawSegment
,
830 uint32_t toOffset
, uint32_t count
,
831 uint32_t* writeCount
);
833 /** nsThreadRetargetableStreamListener methods **/
835 imgRequest::CheckListenerChain() {
836 // TODO Might need more checking here.
837 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
841 /** nsIStreamListener methods **/
843 struct NewPartResult final
{
844 explicit NewPartResult(image::Image
* aExistingImage
)
845 : mImage(aExistingImage
),
846 mIsFirstPart(!aExistingImage
),
848 mShouldResetCacheEntry(false) {}
850 nsAutoCString mContentType
;
851 nsAutoCString mContentDisposition
;
852 RefPtr
<image::Image
> mImage
;
853 const bool mIsFirstPart
;
855 bool mShouldResetCacheEntry
;
858 static NewPartResult
PrepareForNewPart(nsIRequest
* aRequest
,
859 nsIInputStream
* aInStr
, uint32_t aCount
,
860 nsIURI
* aURI
, bool aIsMultipart
,
861 image::Image
* aExistingImage
,
862 ProgressTracker
* aProgressTracker
,
863 uint64_t aInnerWindowId
) {
864 NewPartResult
result(aExistingImage
);
867 mimetype_closure closure
;
868 closure
.newType
= &result
.mContentType
;
870 // Look at the first few bytes and see if we can tell what the data is from
871 // that since servers tend to lie. :(
873 aInStr
->ReadSegments(sniff_mimetype_callback
, &closure
, aCount
, &out
);
876 nsCOMPtr
<nsIChannel
> chan(do_QueryInterface(aRequest
));
877 if (result
.mContentType
.IsEmpty()) {
879 chan
? chan
->GetContentType(result
.mContentType
) : NS_ERROR_FAILURE
;
881 MOZ_LOG(gImgLog
, LogLevel::Error
,
882 ("imgRequest::PrepareForNewPart -- "
883 "Content type unavailable from the channel\n"));
891 chan
->GetContentDispositionHeader(result
.mContentDisposition
);
894 MOZ_LOG(gImgLog
, LogLevel::Debug
,
895 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
896 result
.mContentType
.get()));
898 // XXX If server lied about mimetype and it's SVG, we may need to copy
899 // the data and dispatch back to the main thread, AND tell the channel to
900 // dispatch there in the future.
902 // Create the new image and give it ownership of our ProgressTracker.
904 // Create the ProgressTracker and image for this part.
905 RefPtr
<ProgressTracker
> progressTracker
= new ProgressTracker();
906 RefPtr
<image::Image
> partImage
= image::ImageFactory::CreateImage(
907 aRequest
, progressTracker
, result
.mContentType
, aURI
,
908 /* aIsMultipart = */ true, aInnerWindowId
);
910 if (result
.mIsFirstPart
) {
911 // First part for a multipart channel. Create the MultipartImage wrapper.
912 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
913 aProgressTracker
->SetIsMultipart();
914 result
.mImage
= image::ImageFactory::CreateMultipartImage(
915 partImage
, aProgressTracker
);
917 // Transition to the new part.
918 auto multipartImage
= static_cast<MultipartImage
*>(aExistingImage
);
919 multipartImage
->BeginTransitionToPart(partImage
);
921 // Reset our cache entry size so it doesn't keep growing without bound.
922 result
.mShouldResetCacheEntry
= true;
925 MOZ_ASSERT(!aExistingImage
, "New part for non-multipart channel?");
926 MOZ_ASSERT(aProgressTracker
, "Shouldn't have given away tracker yet");
928 // Create an image using our progress tracker.
929 result
.mImage
= image::ImageFactory::CreateImage(
930 aRequest
, aProgressTracker
, result
.mContentType
, aURI
,
931 /* aIsMultipart = */ false, aInnerWindowId
);
934 MOZ_ASSERT(result
.mImage
);
935 if (!result
.mImage
->HasError() || aIsMultipart
) {
936 // We allow multipart images to fail to initialize (which generally
937 // indicates a bad content type) without cancelling the load, because
938 // subsequent parts might be fine.
939 result
.mSucceeded
= true;
945 class FinishPreparingForNewPartRunnable final
: public Runnable
{
947 FinishPreparingForNewPartRunnable(imgRequest
* aImgRequest
,
948 NewPartResult
&& aResult
)
949 : Runnable("FinishPreparingForNewPartRunnable"),
950 mImgRequest(aImgRequest
),
952 MOZ_ASSERT(aImgRequest
);
955 NS_IMETHOD
Run() override
{
956 mImgRequest
->FinishPreparingForNewPart(mResult
);
961 RefPtr
<imgRequest
> mImgRequest
;
962 NewPartResult mResult
;
965 void imgRequest::FinishPreparingForNewPart(const NewPartResult
& aResult
) {
966 MOZ_ASSERT(NS_IsMainThread());
968 mContentType
= aResult
.mContentType
;
970 SetProperties(aResult
.mContentType
, aResult
.mContentDisposition
);
972 if (aResult
.mIsFirstPart
) {
973 // Notify listeners that we have an image.
974 mImageAvailable
= true;
975 RefPtr
<ProgressTracker
> progressTracker
= GetProgressTracker();
976 progressTracker
->OnImageAvailable();
977 MOZ_ASSERT(progressTracker
->HasImage());
980 if (aResult
.mShouldResetCacheEntry
) {
984 if (IsDecodeRequested()) {
985 aResult
.mImage
->StartDecoding(imgIContainer::FLAG_NONE
);
989 bool imgRequest::ImageAvailable() const { return mImageAvailable
; }
992 imgRequest::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
993 uint64_t aOffset
, uint32_t aCount
) {
994 LOG_SCOPE_WITH_PARAM(gImgLog
, "imgRequest::OnDataAvailable", "count", aCount
);
996 NS_ASSERTION(aRequest
, "imgRequest::OnDataAvailable -- no request!");
999 RefPtr
<ProgressTracker
> progressTracker
;
1000 bool isMultipart
= false;
1001 bool newPartPending
= false;
1002 uint64_t innerWindowId
= 0;
1004 // Retrieve and update our state.
1006 MutexAutoLock
lock(mMutex
);
1008 progressTracker
= mProgressTracker
;
1009 isMultipart
= mIsMultiPartChannel
;
1010 newPartPending
= mNewPartPending
;
1011 mNewPartPending
= false;
1012 innerWindowId
= mInnerWindowId
;
1015 // If this is a new part, we need to sniff its content type and create an
1016 // appropriate image.
1017 if (newPartPending
) {
1018 NewPartResult result
=
1019 PrepareForNewPart(aRequest
, aInStr
, aCount
, mURI
, isMultipart
, image
,
1020 progressTracker
, innerWindowId
);
1021 bool succeeded
= result
.mSucceeded
;
1023 if (result
.mImage
) {
1024 image
= result
.mImage
;
1025 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1027 // Update our state to reflect this new part.
1029 MutexAutoLock
lock(mMutex
);
1032 // We only get an event target if we are not on the main thread, because
1033 // we have to dispatch in that case. If we are on the main thread, but
1034 // on a different scheduler group than ProgressTracker would give us,
1035 // that is okay because nothing in imagelib requires that, just our
1036 // listeners (which have their own checks).
1037 if (!NS_IsMainThread()) {
1038 eventTarget
= mProgressTracker
->GetEventTarget();
1039 MOZ_ASSERT(eventTarget
);
1042 mProgressTracker
= nullptr;
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;