Bug 1796551 [wpt PR 36570] - WebKit export of https://bugs.webkit.org/show_bug.cgi...
[gecko.git] / image / imgRequest.cpp
blob39daf2e5308f2e073d3c5cc16671104c63e2c939
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"
15 #include "Image.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"
34 #include "nsEscape.h"
36 #include "plstr.h" // PL_strcasestr(...)
37 #include "prtime.h" // for PR_Now
38 #include "nsNetUtil.h"
39 #include "nsIProtocolHandler.h"
40 #include "imgIRequest.h"
41 #include "nsProperties.h"
42 #include "nsIURL.h"
44 #include "mozilla/IntegerPrintfMacros.h"
45 #include "mozilla/SizeOfState.h"
47 using namespace mozilla;
48 using namespace mozilla::image;
50 #define LOG_TEST(level) (MOZ_LOG_TEST(gImgLog, (level)))
52 NS_IMPL_ISUPPORTS(imgRequest, nsIStreamListener, nsIRequestObserver,
53 nsIThreadRetargetableStreamListener, nsIChannelEventSink,
54 nsIInterfaceRequestor, nsIAsyncVerifyRedirectCallback)
56 imgRequest::imgRequest(imgLoader* aLoader, const ImageCacheKey& aCacheKey)
57 : mLoader(aLoader),
58 mCacheKey(aCacheKey),
59 mLoadId(nullptr),
60 mFirstProxy(nullptr),
61 mValidator(nullptr),
62 mCORSMode(CORS_NONE),
63 mImageErrorCode(NS_OK),
64 mImageAvailable(false),
65 mIsDeniedCrossSiteCORSRequest(false),
66 mIsCrossSiteNoCORSRequest(false),
67 mMutex("imgRequest"),
68 mProgressTracker(new ProgressTracker()),
69 mIsMultiPartChannel(false),
70 mIsInCache(false),
71 mDecodeRequested(false),
72 mNewPartPending(false),
73 mHadInsecureRedirect(false),
74 mInnerWindowId(0) {
75 LOG_FUNC(gImgLog, "imgRequest::imgRequest()");
78 imgRequest::~imgRequest() {
79 if (mLoader) {
80 mLoader->RemoveFromUncachedImages(this);
82 if (mURI) {
83 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::~imgRequest()", "keyuri", mURI);
84 } else
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
96 // mainthread
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();
107 mURI = aURI;
108 mFinalURI = aFinalURI;
109 mRequest = aRequest;
110 mChannel = aChannel;
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") &&
125 !schemeLocal)) {
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();
151 return NS_OK;
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
161 // cache entries.
162 void* key = (void*)aDoc;
163 uint64_t innerWindowID = aDoc ? aDoc->InnerWindowID() : 0;
164 if (LoadId() == key && InnerWindowID() == innerWindowID) {
165 return true;
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);
174 return false;
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);
187 if (mImage) {
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);
213 if (!mFirstProxy) {
214 // Save a raw pointer to the first proxy we see, for use in the network
215 // priority logic.
216 mFirstProxy = proxy;
219 // If we're empty before adding, we have to tell the loader we now have
220 // proxies.
221 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
222 if (progressTracker->ObserverCount() == 0) {
223 MOZ_ASSERT(mURI, "Trying to SetHasProxies without key uri.");
224 if (mLoader) {
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)) {
246 return NS_OK;
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.
253 if (mCacheEntry) {
254 MOZ_ASSERT(mURI, "Removing last observer without key uri.");
256 if (mLoader) {
257 mLoader->SetHasNoProxies(this, mCacheEntry);
259 } else {
260 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy no cache entry",
261 "uri", mURI);
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
268 list.
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;
282 return NS_OK;
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");
298 Cancel(aStatus);
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.
303 if (mChannel) {
304 mChannel->SetNotificationCallbacks(mPrevChannelSink);
305 mPrevChannelSink = nullptr;
309 class imgRequestMainThreadCancel : public Runnable {
310 public:
311 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
312 : Runnable("imgRequestMainThreadCancel"),
313 mImgRequest(aImgRequest),
314 mStatus(aStatus) {
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);
322 return NS_OK;
325 private:
326 RefPtr<imgRequest> mImgRequest;
327 nsresult mStatus;
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);
336 } else {
337 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
338 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
339 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
340 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
344 void imgRequest::ContinueCancel(nsresult aStatus) {
345 MOZ_ASSERT(NS_IsMainThread());
347 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
348 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
350 RemoveFromCache();
352 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
353 mRequest->CancelWithReason(aStatus, "imgRequest::ContinueCancel"_ns);
357 class imgRequestMainThreadEvict : public Runnable {
358 public:
359 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
360 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
361 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
362 MOZ_ASSERT(aImgRequest);
365 NS_IMETHOD Run() override {
366 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
367 mImgRequest->ContinueEvict();
368 return NS_OK;
371 private:
372 RefPtr<imgRequest> mImgRequest;
375 // EvictFromCache() is written to allowed to get called from any thread
376 void imgRequest::EvictFromCache() {
377 /* The EvictFromCache() method here should only be called by this class. */
378 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
380 if (NS_IsMainThread()) {
381 ContinueEvict();
382 } else {
383 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
387 // Helper-method used by EvictFromCache()
388 void imgRequest::ContinueEvict() {
389 MOZ_ASSERT(NS_IsMainThread());
391 RemoveFromCache();
394 void imgRequest::StartDecoding() {
395 MutexAutoLock lock(mMutex);
396 mDecodeRequested = true;
399 bool imgRequest::IsDecodeRequested() const {
400 MutexAutoLock lock(mMutex);
401 return mDecodeRequested;
404 nsresult imgRequest::GetURI(nsIURI** aURI) {
405 MOZ_ASSERT(aURI);
407 LOG_FUNC(gImgLog, "imgRequest::GetURI");
409 if (mURI) {
410 *aURI = mURI;
411 NS_ADDREF(*aURI);
412 return NS_OK;
415 return NS_ERROR_FAILURE;
418 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
419 MOZ_ASSERT(aURI);
421 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
423 if (mFinalURI) {
424 *aURI = mFinalURI;
425 NS_ADDREF(*aURI);
426 return NS_OK;
429 return NS_ERROR_FAILURE;
432 bool imgRequest::IsChrome() const { return mURI->SchemeIs("chrome"); }
434 bool imgRequest::IsData() const { return mURI->SchemeIs("data"); }
436 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
438 void imgRequest::RemoveFromCache() {
439 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
441 bool isInCache = false;
444 MutexAutoLock lock(mMutex);
445 isInCache = mIsInCache;
448 if (isInCache && mLoader) {
449 // mCacheEntry is nulled out when we have no more observers.
450 if (mCacheEntry) {
451 mLoader->RemoveFromCache(mCacheEntry);
452 } else {
453 mLoader->RemoveFromCache(mCacheKey);
457 mCacheEntry = nullptr;
460 bool imgRequest::HasConsumers() const {
461 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
462 return progressTracker && progressTracker->ObserverCount() > 0;
465 already_AddRefed<image::Image> imgRequest::GetImage() const {
466 MutexAutoLock lock(mMutex);
467 RefPtr<image::Image> image = mImage;
468 return image.forget();
471 void imgRequest::GetFileName(nsACString& aFileName) {
472 nsAutoString fileName;
474 nsCOMPtr<nsISupportsCString> supportscstr;
475 if (NS_SUCCEEDED(mProperties->Get("content-disposition",
476 NS_GET_IID(nsISupportsCString),
477 getter_AddRefs(supportscstr))) &&
478 supportscstr) {
479 nsAutoCString cdHeader;
480 supportscstr->GetData(cdHeader);
481 NS_GetFilenameFromDisposition(fileName, cdHeader);
484 if (fileName.IsEmpty()) {
485 nsCOMPtr<nsIURL> imgUrl(do_QueryInterface(mURI));
486 if (imgUrl) {
487 imgUrl->GetFileName(aFileName);
488 NS_UnescapeURL(aFileName);
490 } else {
491 aFileName = NS_ConvertUTF16toUTF8(fileName);
495 int32_t imgRequest::Priority() const {
496 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
497 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
498 if (p) {
499 p->GetPriority(&priority);
501 return priority;
504 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
505 // only the first proxy is allowed to modify the priority of this image load.
507 // XXX(darin): this is probably not the most optimal algorithm as we may want
508 // to increase the priority of requests that have a lot of proxies. the key
509 // concern though is that image loads remain lower priority than other pieces
510 // of content such as link clicks, CSS, and JS.
512 if (!mFirstProxy || proxy != mFirstProxy) {
513 return;
516 AdjustPriorityInternal(delta);
519 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
520 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
521 if (p) {
522 p->AdjustPriority(aDelta);
526 void imgRequest::BoostPriority(uint32_t aCategory) {
527 if (!StaticPrefs::image_layout_network_priority()) {
528 return;
531 uint32_t newRequestedCategory =
532 (mBoostCategoriesRequested & aCategory) ^ aCategory;
533 if (!newRequestedCategory) {
534 // priority boost for each category can only apply once.
535 return;
538 MOZ_LOG(gImgLog, LogLevel::Debug,
539 ("[this=%p] imgRequest::BoostPriority for category %x", this,
540 newRequestedCategory));
542 int32_t delta = 0;
544 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
545 --delta;
548 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
549 --delta;
552 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
553 --delta;
556 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
557 delta += nsISupportsPriority::PRIORITY_HIGH;
560 AdjustPriorityInternal(delta);
561 mBoostCategoriesRequested |= newRequestedCategory;
564 void imgRequest::SetIsInCache(bool aInCache) {
565 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
566 aInCache);
567 MutexAutoLock lock(mMutex);
568 mIsInCache = aInCache;
571 void imgRequest::UpdateCacheEntrySize() {
572 if (!mCacheEntry) {
573 return;
576 RefPtr<Image> image = GetImage();
577 SizeOfState state(moz_malloc_size_of);
578 size_t size = image->SizeOfSourceWithComputedFallback(state);
579 mCacheEntry->SetDataSize(size);
582 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
583 nsIRequest* aRequest) {
584 /* get the expires info */
585 if (!aCacheEntry || aCacheEntry->GetExpiryTime() != 0) {
586 return;
589 RefPtr<imgRequest> req = aCacheEntry->GetRequest();
590 MOZ_ASSERT(req);
591 RefPtr<nsIURI> uri;
592 req->GetURI(getter_AddRefs(uri));
593 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
594 // get here in such cases sometimes (like for some redirects, see
595 // docshell/test/chrome/test_bug89419.xhtml).
597 // We have the original URI in the cache key though, probably we should be
598 // using that instead of relying on Init() getting called.
599 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest, uri);
601 // Expiration time defaults to 0. We set the expiration time on our entry if
602 // it hasn't been set yet.
603 if (!info.mExpirationTime) {
604 // If the channel doesn't support caching, then ensure this expires the
605 // next time it is used.
606 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
609 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
610 // Cache entries default to not needing to validate. We ensure that
611 // multiple calls to this function don't override an earlier decision to
612 // validate by making validation a one-way decision.
613 if (info.mMustRevalidate) {
614 aCacheEntry->SetMustValidate(info.mMustRevalidate);
618 bool imgRequest::GetMultipart() const {
619 MutexAutoLock lock(mMutex);
620 return mIsMultiPartChannel;
623 bool imgRequest::HadInsecureRedirect() const {
624 MutexAutoLock lock(mMutex);
625 return mHadInsecureRedirect;
628 /** nsIRequestObserver methods **/
630 NS_IMETHODIMP
631 imgRequest::OnStartRequest(nsIRequest* aRequest) {
632 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
634 RefPtr<Image> image;
636 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
637 nsresult rv;
638 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
639 mIsDeniedCrossSiteCORSRequest =
640 loadInfo->GetTainting() == LoadTainting::CORS &&
641 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
642 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
645 // 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;
654 image = mImage;
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
672 if (!mRequest) {
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));
680 if (channel) {
681 /* Get our principal */
682 nsCOMPtr<nsIScriptSecurityManager> secMan =
683 nsContentUtils::GetSecurityManager();
684 if (secMan) {
685 nsresult rv = secMan->GetChannelResultPrincipal(
686 channel, getter_AddRefs(mPrincipal));
687 if (NS_FAILED(rv)) {
688 return rv;
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()) {
705 return NS_OK;
708 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
709 do_QueryInterface(aRequest);
710 if (retargetable) {
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"));
726 return NS_OK;
729 NS_IMETHODIMP
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 bool isMultipart = false;
739 bool newPartPending = false;
741 MutexAutoLock lock(mMutex);
742 isMultipart = mIsMultiPartChannel;
743 newPartPending = mNewPartPending;
745 if (isMultipart && newPartPending) {
746 OnDataAvailable(aRequest, nullptr, 0, 0);
749 // XXXldb What if this is a non-last part of a multipart request?
750 // xxx before we release our reference to mRequest, lets
751 // save the last status that we saw so that the
752 // imgRequestProxy will have access to it.
753 if (mRequest) {
754 mRequest = nullptr; // we no longer need the request
757 // stop holding a ref to the channel, since we don't need it anymore
758 if (mChannel) {
759 mChannel->SetNotificationCallbacks(mPrevChannelSink);
760 mPrevChannelSink = nullptr;
761 mChannel = nullptr;
764 bool lastPart = true;
765 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
766 if (mpchan) {
767 mpchan->GetIsLastPart(&lastPart);
770 bool isPartial = false;
771 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
772 isPartial = true;
773 status = NS_OK; // fake happy face
776 // Tell the image that it has all of the source data. Note that this can
777 // trigger a failure, since the image might be waiting for more non-optional
778 // data and this is the point where we break the news that it's not coming.
779 if (image) {
780 nsresult rv = image->OnImageDataComplete(aRequest, status, lastPart);
782 // If we got an error in the OnImageDataComplete() call, we don't want to
783 // proceed as if nothing bad happened. However, we also want to give
784 // precedence to failure status codes from necko, since presumably they're
785 // more meaningful.
786 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
787 status = rv;
791 // If the request went through, update the cache entry size. Otherwise,
792 // cancel the request, which removes us from the cache.
793 if (image && NS_SUCCEEDED(status) && !isPartial) {
794 // We update the cache entry size here because this is where we finish
795 // loading compressed source data, which is part of our size calculus.
796 UpdateCacheEntrySize();
798 } else if (isPartial) {
799 // Remove the partial image from the cache.
800 this->EvictFromCache();
802 } else {
803 mImageErrorCode = status;
805 // if the error isn't "just" a partial transfer
806 // stops animations, removes from cache
807 this->Cancel(status);
810 if (!image) {
811 // We have to fire the OnStopRequest notifications ourselves because there's
812 // no image capable of doing so.
813 Progress progress =
814 LoadCompleteProgress(lastPart, /* aError = */ false, status);
816 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
817 progressTracker->SyncNotifyProgress(progress);
820 mTimedChannel = nullptr;
821 return NS_OK;
824 struct mimetype_closure {
825 nsACString* newType;
828 /* prototype for these defined below */
829 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
830 const char* fromRawSegment,
831 uint32_t toOffset, uint32_t count,
832 uint32_t* writeCount);
834 /** nsThreadRetargetableStreamListener methods **/
835 NS_IMETHODIMP
836 imgRequest::CheckListenerChain() {
837 // TODO Might need more checking here.
838 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
839 return NS_OK;
842 /** nsIStreamListener methods **/
844 struct NewPartResult final {
845 explicit NewPartResult(image::Image* aExistingImage)
846 : mImage(aExistingImage),
847 mIsFirstPart(!aExistingImage),
848 mSucceeded(false),
849 mShouldResetCacheEntry(false) {}
851 nsAutoCString mContentType;
852 nsAutoCString mContentDisposition;
853 RefPtr<image::Image> mImage;
854 const bool mIsFirstPart;
855 bool mSucceeded;
856 bool mShouldResetCacheEntry;
859 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
860 nsIInputStream* aInStr, uint32_t aCount,
861 nsIURI* aURI, bool aIsMultipart,
862 image::Image* aExistingImage,
863 ProgressTracker* aProgressTracker,
864 uint64_t aInnerWindowId) {
865 NewPartResult result(aExistingImage);
867 if (aInStr) {
868 mimetype_closure closure;
869 closure.newType = &result.mContentType;
871 // Look at the first few bytes and see if we can tell what the data is from
872 // that since servers tend to lie. :(
873 uint32_t out;
874 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
877 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
878 if (result.mContentType.IsEmpty()) {
879 nsresult rv =
880 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
881 if (NS_FAILED(rv)) {
882 MOZ_LOG(gImgLog, LogLevel::Error,
883 ("imgRequest::PrepareForNewPart -- "
884 "Content type unavailable from the channel\n"));
885 if (!aIsMultipart) {
886 return result;
891 if (chan) {
892 chan->GetContentDispositionHeader(result.mContentDisposition);
895 MOZ_LOG(gImgLog, LogLevel::Debug,
896 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
897 result.mContentType.get()));
899 // XXX If server lied about mimetype and it's SVG, we may need to copy
900 // the data and dispatch back to the main thread, AND tell the channel to
901 // dispatch there in the future.
903 // Create the new image and give it ownership of our ProgressTracker.
904 if (aIsMultipart) {
905 // Create the ProgressTracker and image for this part.
906 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
907 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
908 aRequest, progressTracker, result.mContentType, aURI,
909 /* aIsMultipart = */ true, aInnerWindowId);
911 if (result.mIsFirstPart) {
912 // First part for a multipart channel. Create the MultipartImage wrapper.
913 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
914 aProgressTracker->SetIsMultipart();
915 result.mImage = image::ImageFactory::CreateMultipartImage(
916 partImage, aProgressTracker);
917 } else {
918 // Transition to the new part.
919 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
920 multipartImage->BeginTransitionToPart(partImage);
922 // Reset our cache entry size so it doesn't keep growing without bound.
923 result.mShouldResetCacheEntry = true;
925 } else {
926 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
927 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
929 // Create an image using our progress tracker.
930 result.mImage = image::ImageFactory::CreateImage(
931 aRequest, aProgressTracker, result.mContentType, aURI,
932 /* aIsMultipart = */ false, aInnerWindowId);
935 MOZ_ASSERT(result.mImage);
936 if (!result.mImage->HasError() || aIsMultipart) {
937 // We allow multipart images to fail to initialize (which generally
938 // indicates a bad content type) without cancelling the load, because
939 // subsequent parts might be fine.
940 result.mSucceeded = true;
943 return result;
946 class FinishPreparingForNewPartRunnable final : public Runnable {
947 public:
948 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
949 NewPartResult&& aResult)
950 : Runnable("FinishPreparingForNewPartRunnable"),
951 mImgRequest(aImgRequest),
952 mResult(aResult) {
953 MOZ_ASSERT(aImgRequest);
956 NS_IMETHOD Run() override {
957 mImgRequest->FinishPreparingForNewPart(mResult);
958 return NS_OK;
961 private:
962 RefPtr<imgRequest> mImgRequest;
963 NewPartResult mResult;
966 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
967 MOZ_ASSERT(NS_IsMainThread());
969 mContentType = aResult.mContentType;
971 SetProperties(aResult.mContentType, aResult.mContentDisposition);
973 if (aResult.mIsFirstPart) {
974 // Notify listeners that we have an image.
975 mImageAvailable = true;
976 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
977 progressTracker->OnImageAvailable();
978 MOZ_ASSERT(progressTracker->HasImage());
981 if (aResult.mShouldResetCacheEntry) {
982 ResetCacheEntry();
985 if (IsDecodeRequested()) {
986 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
990 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
992 NS_IMETHODIMP
993 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
994 uint64_t aOffset, uint32_t aCount) {
995 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
997 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
999 RefPtr<Image> image;
1000 RefPtr<ProgressTracker> progressTracker;
1001 bool isMultipart = false;
1002 bool newPartPending = false;
1003 uint64_t innerWindowId = 0;
1005 // Retrieve and update our state.
1007 MutexAutoLock lock(mMutex);
1008 image = mImage;
1009 progressTracker = mProgressTracker;
1010 isMultipart = mIsMultiPartChannel;
1011 newPartPending = mNewPartPending;
1012 mNewPartPending = false;
1013 innerWindowId = mInnerWindowId;
1016 // If this is a new part, we need to sniff its content type and create an
1017 // appropriate image.
1018 if (newPartPending) {
1019 NewPartResult result =
1020 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
1021 progressTracker, innerWindowId);
1022 bool succeeded = result.mSucceeded;
1024 if (result.mImage) {
1025 image = result.mImage;
1026 nsCOMPtr<nsIEventTarget> eventTarget;
1028 // Update our state to reflect this new part.
1030 MutexAutoLock lock(mMutex);
1031 mImage = image;
1033 // We only get an event target if we are not on the main thread, because
1034 // we have to dispatch in that case. If we are on the main thread, but
1035 // on a different scheduler group than ProgressTracker would give us,
1036 // that is okay because nothing in imagelib requires that, just our
1037 // listeners (which have their own checks).
1038 if (!NS_IsMainThread()) {
1039 eventTarget = mProgressTracker->GetEventTarget();
1040 MOZ_ASSERT(eventTarget);
1043 mProgressTracker = nullptr;
1046 // Some property objects are not threadsafe, and we need to send
1047 // OnImageAvailable on the main thread, so finish on the main thread.
1048 if (!eventTarget) {
1049 MOZ_ASSERT(NS_IsMainThread());
1050 FinishPreparingForNewPart(result);
1051 } else {
1052 nsCOMPtr<nsIRunnable> runnable =
1053 new FinishPreparingForNewPartRunnable(this, std::move(result));
1054 eventTarget->Dispatch(CreateRenderBlockingRunnable(runnable.forget()),
1055 NS_DISPATCH_NORMAL);
1059 if (!succeeded) {
1060 // Something went wrong; probably a content type issue.
1061 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1062 return NS_BINDING_ABORTED;
1066 // Notify the image that it has new data.
1067 if (aInStr) {
1068 nsresult rv =
1069 image->OnImageDataAvailable(aRequest, aInStr, aOffset, aCount);
1071 if (NS_FAILED(rv)) {
1072 MOZ_LOG(gImgLog, LogLevel::Warning,
1073 ("[this=%p] imgRequest::OnDataAvailable -- "
1074 "copy to RasterImage failed\n",
1075 this));
1076 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1077 return NS_BINDING_ABORTED;
1081 return NS_OK;
1084 void imgRequest::SetProperties(const nsACString& aContentType,
1085 const nsACString& aContentDisposition) {
1086 /* set our mimetype as a property */
1087 nsCOMPtr<nsISupportsCString> contentType =
1088 do_CreateInstance("@mozilla.org/supports-cstring;1");
1089 if (contentType) {
1090 contentType->SetData(aContentType);
1091 mProperties->Set("type", contentType);
1094 /* set our content disposition as a property */
1095 if (!aContentDisposition.IsEmpty()) {
1096 nsCOMPtr<nsISupportsCString> contentDisposition =
1097 do_CreateInstance("@mozilla.org/supports-cstring;1");
1098 if (contentDisposition) {
1099 contentDisposition->SetData(aContentDisposition);
1100 mProperties->Set("content-disposition", contentDisposition);
1105 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1106 const char* fromRawSegment,
1107 uint32_t toOffset, uint32_t count,
1108 uint32_t* writeCount) {
1109 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1111 NS_ASSERTION(closure, "closure is null!");
1113 if (count > 0) {
1114 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1117 *writeCount = 0;
1118 return NS_ERROR_FAILURE;
1121 /** nsIInterfaceRequestor methods **/
1123 NS_IMETHODIMP
1124 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1125 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1126 return QueryInterface(aIID, aResult);
1129 NS_ASSERTION(
1130 mPrevChannelSink != this,
1131 "Infinite recursion - don't keep track of channel sinks that are us!");
1132 return mPrevChannelSink->GetInterface(aIID, aResult);
1135 /** nsIChannelEventSink methods **/
1136 NS_IMETHODIMP
1137 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1138 nsIChannel* newChannel, uint32_t flags,
1139 nsIAsyncVerifyRedirectCallback* callback) {
1140 NS_ASSERTION(mRequest && mChannel,
1141 "Got a channel redirect after we nulled out mRequest!");
1142 NS_ASSERTION(mChannel == oldChannel,
1143 "Got a channel redirect for an unknown channel!");
1144 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1146 SetCacheValidation(mCacheEntry, oldChannel);
1148 // Prepare for callback
1149 mRedirectCallback = callback;
1150 mNewRedirectChannel = newChannel;
1152 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1153 if (sink) {
1154 nsresult rv =
1155 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1156 if (NS_FAILED(rv)) {
1157 mRedirectCallback = nullptr;
1158 mNewRedirectChannel = nullptr;
1160 return rv;
1163 (void)OnRedirectVerifyCallback(NS_OK);
1164 return NS_OK;
1167 NS_IMETHODIMP
1168 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1169 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1170 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1172 if (NS_FAILED(result)) {
1173 mRedirectCallback->OnRedirectVerifyCallback(result);
1174 mRedirectCallback = nullptr;
1175 mNewRedirectChannel = nullptr;
1176 return NS_OK;
1179 mChannel = mNewRedirectChannel;
1180 mTimedChannel = do_QueryInterface(mChannel);
1181 mNewRedirectChannel = nullptr;
1183 if (LOG_TEST(LogLevel::Debug)) {
1184 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1185 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1188 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1189 // security code, which needs to know whether there is an insecure load at any
1190 // point in the redirect chain.
1191 bool schemeLocal = false;
1192 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1193 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1194 &schemeLocal)) ||
1195 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1196 !schemeLocal)) {
1197 MutexAutoLock lock(mMutex);
1199 // The csp directive upgrade-insecure-requests performs an internal redirect
1200 // to upgrade all requests from http to https before any data is fetched
1201 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1202 // internal redirect.
1203 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1204 bool upgradeInsecureRequests =
1205 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1206 loadInfo->GetBrowserUpgradeInsecureRequests()
1207 : false;
1208 if (!upgradeInsecureRequests) {
1209 mHadInsecureRedirect = true;
1213 // Update the final URI.
1214 mChannel->GetURI(getter_AddRefs(mFinalURI));
1216 if (LOG_TEST(LogLevel::Debug)) {
1217 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1218 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1221 // Make sure we have a protocol that returns data rather than opens an
1222 // external application, e.g. 'mailto:'.
1223 bool doesNotReturnData = false;
1224 nsresult rv = NS_URIChainHasFlags(
1225 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1226 &doesNotReturnData);
1228 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1229 rv = NS_ERROR_ABORT;
1232 if (NS_FAILED(rv)) {
1233 mRedirectCallback->OnRedirectVerifyCallback(rv);
1234 mRedirectCallback = nullptr;
1235 return NS_OK;
1238 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1239 mRedirectCallback = nullptr;
1240 return NS_OK;