Bug 1880704 - Crop more PDF rendering and wait differently for rendering r=mboldan
[gecko.git] / image / imgRequest.cpp
blob9713d2f33ea18a27f735d761f96fb44dfd280b97
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 "prtime.h" // for PR_Now
37 #include "nsNetUtil.h"
38 #include "nsIProtocolHandler.h"
39 #include "imgIRequest.h"
40 #include "nsProperties.h"
41 #include "nsIURL.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)
56 : mLoader(aLoader),
57 mCacheKey(aCacheKey),
58 mLoadId(nullptr),
59 mFirstProxy(nullptr),
60 mValidator(nullptr),
61 mCORSMode(CORS_NONE),
62 mImageErrorCode(NS_OK),
63 mImageAvailable(false),
64 mIsDeniedCrossSiteCORSRequest(false),
65 mIsCrossSiteNoCORSRequest(false),
66 mShouldReportRenderTimeForLCP(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 nsCOMPtr<nsIEventTarget> eventTarget = GetMainThreadSerialEventTarget();
338 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
339 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
343 void imgRequest::ContinueCancel(nsresult aStatus) {
344 MOZ_ASSERT(NS_IsMainThread());
346 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
347 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
349 RemoveFromCache();
351 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
352 mRequest->CancelWithReason(aStatus, "imgRequest::ContinueCancel"_ns);
356 class imgRequestMainThreadEvict : public Runnable {
357 public:
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();
367 return NS_OK;
370 private:
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()) {
380 ContinueEvict();
381 } else {
382 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
386 // Helper-method used by EvictFromCache()
387 void imgRequest::ContinueEvict() {
388 MOZ_ASSERT(NS_IsMainThread());
390 RemoveFromCache();
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) {
404 MOZ_ASSERT(aURI);
406 LOG_FUNC(gImgLog, "imgRequest::GetURI");
408 if (mURI) {
409 *aURI = mURI;
410 NS_ADDREF(*aURI);
411 return NS_OK;
414 return NS_ERROR_FAILURE;
417 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
418 MOZ_ASSERT(aURI);
420 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
422 if (mFinalURI) {
423 *aURI = mFinalURI;
424 NS_ADDREF(*aURI);
425 return NS_OK;
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.
449 if (mCacheEntry) {
450 mLoader->RemoveFromCache(mCacheEntry);
451 } else {
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))) &&
477 supportscstr) {
478 nsAutoCString cdHeader;
479 supportscstr->GetData(cdHeader);
480 NS_GetFilenameFromDisposition(fileName, cdHeader);
483 if (fileName.IsEmpty()) {
484 nsCOMPtr<nsIURL> imgUrl(do_QueryInterface(mURI));
485 if (imgUrl) {
486 imgUrl->GetFileName(aFileName);
487 NS_UnescapeURL(aFileName);
489 } else {
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);
497 if (p) {
498 p->GetPriority(&priority);
500 return 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) {
512 return;
515 AdjustPriorityInternal(delta);
518 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
519 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
520 if (p) {
521 p->AdjustPriority(aDelta);
525 void imgRequest::BoostPriority(uint32_t aCategory) {
526 if (!StaticPrefs::image_layout_network_priority()) {
527 return;
530 uint32_t newRequestedCategory =
531 (mBoostCategoriesRequested & aCategory) ^ aCategory;
532 if (!newRequestedCategory) {
533 // priority boost for each category can only apply once.
534 return;
537 MOZ_LOG(gImgLog, LogLevel::Debug,
538 ("[this=%p] imgRequest::BoostPriority for category %x", this,
539 newRequestedCategory));
541 int32_t delta = 0;
543 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
544 --delta;
547 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
548 --delta;
551 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
552 --delta;
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",
565 aInCache);
566 MutexAutoLock lock(mMutex);
567 mIsInCache = aInCache;
570 void imgRequest::UpdateCacheEntrySize() {
571 if (!mCacheEntry) {
572 return;
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) {
585 return;
588 RefPtr<imgRequest> req = aCacheEntry->GetRequest();
589 MOZ_ASSERT(req);
590 RefPtr<nsIURI> uri;
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 **/
629 NS_IMETHODIMP
630 imgRequest::OnStartRequest(nsIRequest* aRequest) {
631 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
633 RefPtr<Image> image;
635 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
636 nsresult rv;
637 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
638 mIsDeniedCrossSiteCORSRequest =
639 loadInfo->GetTainting() == LoadTainting::CORS &&
640 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
641 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
644 UpdateShouldReportRenderTimeForLCP();
645 // Figure out if we're multipart.
646 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
648 MutexAutoLock lock(mMutex);
650 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
651 "Stopped being multipart?");
653 mNewPartPending = true;
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<nsISerialEventTarget> 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 NS_IMETHODIMP
843 imgRequest::OnDataFinished(nsresult) { return NS_OK; }
845 /** nsIStreamListener methods **/
847 struct NewPartResult final {
848 explicit NewPartResult(image::Image* aExistingImage)
849 : mImage(aExistingImage),
850 mIsFirstPart(!aExistingImage),
851 mSucceeded(false),
852 mShouldResetCacheEntry(false) {}
854 nsAutoCString mContentType;
855 nsAutoCString mContentDisposition;
856 RefPtr<image::Image> mImage;
857 const bool mIsFirstPart;
858 bool mSucceeded;
859 bool mShouldResetCacheEntry;
862 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
863 nsIInputStream* aInStr, uint32_t aCount,
864 nsIURI* aURI, bool aIsMultipart,
865 image::Image* aExistingImage,
866 ProgressTracker* aProgressTracker,
867 uint64_t aInnerWindowId) {
868 NewPartResult result(aExistingImage);
870 if (aInStr) {
871 mimetype_closure closure;
872 closure.newType = &result.mContentType;
874 // Look at the first few bytes and see if we can tell what the data is from
875 // that since servers tend to lie. :(
876 uint32_t out;
877 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
880 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
881 if (result.mContentType.IsEmpty()) {
882 nsresult rv =
883 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
884 if (NS_FAILED(rv)) {
885 MOZ_LOG(gImgLog, LogLevel::Error,
886 ("imgRequest::PrepareForNewPart -- "
887 "Content type unavailable from the channel\n"));
888 if (!aIsMultipart) {
889 return result;
894 if (chan) {
895 chan->GetContentDispositionHeader(result.mContentDisposition);
898 MOZ_LOG(gImgLog, LogLevel::Debug,
899 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
900 result.mContentType.get()));
902 // XXX If server lied about mimetype and it's SVG, we may need to copy
903 // the data and dispatch back to the main thread, AND tell the channel to
904 // dispatch there in the future.
906 // Create the new image and give it ownership of our ProgressTracker.
907 if (aIsMultipart) {
908 // Create the ProgressTracker and image for this part.
909 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
910 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
911 aRequest, progressTracker, result.mContentType, aURI,
912 /* aIsMultipart = */ true, aInnerWindowId);
914 if (result.mIsFirstPart) {
915 // First part for a multipart channel. Create the MultipartImage wrapper.
916 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
917 aProgressTracker->SetIsMultipart();
918 result.mImage = image::ImageFactory::CreateMultipartImage(
919 partImage, aProgressTracker);
920 } else {
921 // Transition to the new part.
922 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
923 multipartImage->BeginTransitionToPart(partImage);
925 // Reset our cache entry size so it doesn't keep growing without bound.
926 result.mShouldResetCacheEntry = true;
928 } else {
929 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
930 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
932 // Create an image using our progress tracker.
933 result.mImage = image::ImageFactory::CreateImage(
934 aRequest, aProgressTracker, result.mContentType, aURI,
935 /* aIsMultipart = */ false, aInnerWindowId);
938 MOZ_ASSERT(result.mImage);
939 if (!result.mImage->HasError() || aIsMultipart) {
940 // We allow multipart images to fail to initialize (which generally
941 // indicates a bad content type) without cancelling the load, because
942 // subsequent parts might be fine.
943 result.mSucceeded = true;
946 return result;
949 class FinishPreparingForNewPartRunnable final : public Runnable {
950 public:
951 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
952 NewPartResult&& aResult)
953 : Runnable("FinishPreparingForNewPartRunnable"),
954 mImgRequest(aImgRequest),
955 mResult(aResult) {
956 MOZ_ASSERT(aImgRequest);
959 NS_IMETHOD Run() override {
960 mImgRequest->FinishPreparingForNewPart(mResult);
961 return NS_OK;
964 private:
965 RefPtr<imgRequest> mImgRequest;
966 NewPartResult mResult;
969 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
970 MOZ_ASSERT(NS_IsMainThread());
972 mContentType = aResult.mContentType;
974 SetProperties(aResult.mContentType, aResult.mContentDisposition);
976 if (aResult.mIsFirstPart) {
977 // Notify listeners that we have an image.
978 mImageAvailable = true;
979 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
980 progressTracker->OnImageAvailable();
981 MOZ_ASSERT(progressTracker->HasImage());
984 if (aResult.mShouldResetCacheEntry) {
985 ResetCacheEntry();
988 if (IsDecodeRequested()) {
989 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
993 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
995 NS_IMETHODIMP
996 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
997 uint64_t aOffset, uint32_t aCount) {
998 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
1000 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
1002 RefPtr<Image> image;
1003 RefPtr<ProgressTracker> progressTracker;
1004 bool isMultipart = false;
1005 bool newPartPending = false;
1006 uint64_t innerWindowId = 0;
1008 // Retrieve and update our state.
1010 MutexAutoLock lock(mMutex);
1011 image = mImage;
1012 progressTracker = mProgressTracker;
1013 isMultipart = mIsMultiPartChannel;
1014 newPartPending = mNewPartPending;
1015 mNewPartPending = false;
1016 innerWindowId = mInnerWindowId;
1019 // If this is a new part, we need to sniff its content type and create an
1020 // appropriate image.
1021 if (newPartPending) {
1022 NewPartResult result =
1023 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
1024 progressTracker, innerWindowId);
1025 bool succeeded = result.mSucceeded;
1027 if (result.mImage) {
1028 image = result.mImage;
1030 // Update our state to reflect this new part.
1032 MutexAutoLock lock(mMutex);
1033 mImage = image;
1035 mProgressTracker = nullptr;
1038 // We only get an event target if we are not on the main thread, because
1039 // we have to dispatch in that case.
1040 nsCOMPtr<nsIEventTarget> eventTarget;
1041 if (!NS_IsMainThread()) {
1042 eventTarget = GetMainThreadSerialEventTarget();
1043 MOZ_ASSERT(eventTarget);
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 if (nsContentUtils::IsExternalProtocol(mFinalURI)) {
1224 mRedirectCallback->OnRedirectVerifyCallback(NS_ERROR_ABORT);
1225 mRedirectCallback = nullptr;
1226 return NS_OK;
1229 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1230 mRedirectCallback = nullptr;
1231 return NS_OK;
1234 void imgRequest::UpdateShouldReportRenderTimeForLCP() {
1235 if (mTimedChannel) {
1236 bool allRedirectPassTAO = false;
1237 mTimedChannel->GetAllRedirectsPassTimingAllowCheck(&allRedirectPassTAO);
1238 mShouldReportRenderTimeForLCP =
1239 mTimedChannel->TimingAllowCheck(mTriggeringPrincipal) &&
1240 allRedirectPassTAO;