Bug 1758813 [wpt PR 33142] - Implement RP sign out, a=testonly
[gecko.git] / image / imgRequest.cpp
blobe63533618fe8dea1fe292c622166af452deabeea
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"
35 #include "plstr.h" // PL_strcasestr(...)
36 #include "prtime.h" // for PR_Now
37 #include "nsNetUtil.h"
38 #include "nsIProtocolHandler.h"
39 #include "imgIRequest.h"
40 #include "nsProperties.h"
42 #include "mozilla/IntegerPrintfMacros.h"
43 #include "mozilla/SizeOfState.h"
45 using namespace mozilla;
46 using namespace mozilla::image;
48 #define LOG_TEST(level) (MOZ_LOG_TEST(gImgLog, (level)))
50 NS_IMPL_ISUPPORTS(imgRequest, nsIStreamListener, nsIRequestObserver,
51 nsIThreadRetargetableStreamListener, nsIChannelEventSink,
52 nsIInterfaceRequestor, nsIAsyncVerifyRedirectCallback)
54 imgRequest::imgRequest(imgLoader* aLoader, const ImageCacheKey& aCacheKey)
55 : mLoader(aLoader),
56 mCacheKey(aCacheKey),
57 mLoadId(nullptr),
58 mFirstProxy(nullptr),
59 mValidator(nullptr),
60 mCORSMode(CORS_NONE),
61 mImageErrorCode(NS_OK),
62 mImageAvailable(false),
63 mIsDeniedCrossSiteCORSRequest(false),
64 mIsCrossSiteNoCORSRequest(false),
65 mMutex("imgRequest"),
66 mProgressTracker(new ProgressTracker()),
67 mIsMultiPartChannel(false),
68 mIsInCache(false),
69 mDecodeRequested(false),
70 mNewPartPending(false),
71 mHadInsecureRedirect(false),
72 mInnerWindowId(0) {
73 LOG_FUNC(gImgLog, "imgRequest::imgRequest()");
76 imgRequest::~imgRequest() {
77 if (mLoader) {
78 mLoader->RemoveFromUncachedImages(this);
80 if (mURI) {
81 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::~imgRequest()", "keyuri", mURI);
82 } else
83 LOG_FUNC(gImgLog, "imgRequest::~imgRequest()");
86 nsresult imgRequest::Init(
87 nsIURI* aURI, nsIURI* aFinalURI, bool aHadInsecureRedirect,
88 nsIRequest* aRequest, nsIChannel* aChannel, imgCacheEntry* aCacheEntry,
89 mozilla::dom::Document* aLoadingDocument,
90 nsIPrincipal* aTriggeringPrincipal, mozilla::CORSMode aCORSMode,
91 nsIReferrerInfo* aReferrerInfo) NO_THREAD_SAFETY_ANALYSIS {
92 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
93 // Init() can only be called once, and that's before it can be used off
94 // mainthread
96 LOG_FUNC(gImgLog, "imgRequest::Init");
98 MOZ_ASSERT(!mImage, "Multiple calls to init");
99 MOZ_ASSERT(aURI, "No uri");
100 MOZ_ASSERT(aFinalURI, "No final uri");
101 MOZ_ASSERT(aRequest, "No request");
102 MOZ_ASSERT(aChannel, "No channel");
104 mProperties = new nsProperties();
105 mURI = aURI;
106 mFinalURI = aFinalURI;
107 mRequest = aRequest;
108 mChannel = aChannel;
109 mTimedChannel = do_QueryInterface(mChannel);
110 mTriggeringPrincipal = aTriggeringPrincipal;
111 mCORSMode = aCORSMode;
112 mReferrerInfo = aReferrerInfo;
114 // If the original URI and the final URI are different, check whether the
115 // original URI is secure. We deliberately don't take the final URI into
116 // account, as it needs to be handled using more complicated rules than
117 // earlier elements of the redirect chain.
118 if (aURI != aFinalURI) {
119 bool schemeLocal = false;
120 if (NS_FAILED(NS_URIChainHasFlags(
121 aURI, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &schemeLocal)) ||
122 (!aURI->SchemeIs("https") && !aURI->SchemeIs("chrome") &&
123 !schemeLocal)) {
124 mHadInsecureRedirect = true;
128 // imgCacheValidator may have handled redirects before we were created, so we
129 // allow the caller to let us know if any redirects were insecure.
130 mHadInsecureRedirect = mHadInsecureRedirect || aHadInsecureRedirect;
132 mChannel->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink));
134 NS_ASSERTION(mPrevChannelSink != this,
135 "Initializing with a channel that already calls back to us!");
137 mChannel->SetNotificationCallbacks(this);
139 mCacheEntry = aCacheEntry;
140 mCacheEntry->UpdateLoadTime();
142 SetLoadId(aLoadingDocument);
144 // Grab the inner window ID of the loading document, if possible.
145 if (aLoadingDocument) {
146 mInnerWindowId = aLoadingDocument->InnerWindowID();
149 return NS_OK;
152 bool imgRequest::CanReuseWithoutValidation(dom::Document* aDoc) const {
153 // If the request's loadId is the same as the aLoadingDocument, then it is ok
154 // to use this one because it has already been validated for this context.
155 // XXX: nullptr seems to be a 'special' key value that indicates that NO
156 // validation is required.
157 // XXX: we also check the window ID because the loadID() can return a reused
158 // pointer of a document. This can still happen for non-document image
159 // cache entries.
160 void* key = (void*)aDoc;
161 uint64_t innerWindowID = aDoc ? aDoc->InnerWindowID() : 0;
162 if (LoadId() == key && InnerWindowID() == innerWindowID) {
163 return true;
166 // As a special-case, if this is a print preview document, also validate on
167 // the original document. This allows to print uncacheable images.
168 if (dom::Document* original = aDoc ? aDoc->GetOriginalDocument() : nullptr) {
169 return CanReuseWithoutValidation(original);
172 return false;
175 void imgRequest::ClearLoader() { mLoader = nullptr; }
177 already_AddRefed<ProgressTracker> imgRequest::GetProgressTracker() const {
178 MutexAutoLock lock(mMutex);
180 if (mImage) {
181 MOZ_ASSERT(!mProgressTracker,
182 "Should have given mProgressTracker to mImage");
183 return mImage->GetProgressTracker();
185 MOZ_ASSERT(mProgressTracker,
186 "Should have mProgressTracker until we create mImage");
187 RefPtr<ProgressTracker> progressTracker = mProgressTracker;
188 MOZ_ASSERT(progressTracker);
189 return progressTracker.forget();
192 void imgRequest::SetCacheEntry(imgCacheEntry* entry) { mCacheEntry = entry; }
194 bool imgRequest::HasCacheEntry() const { return mCacheEntry != nullptr; }
196 void imgRequest::ResetCacheEntry() {
197 if (HasCacheEntry()) {
198 mCacheEntry->SetDataSize(0);
202 void imgRequest::AddProxy(imgRequestProxy* proxy) {
203 MOZ_ASSERT(proxy, "null imgRequestProxy passed in");
204 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::AddProxy", "proxy", proxy);
206 if (!mFirstProxy) {
207 // Save a raw pointer to the first proxy we see, for use in the network
208 // priority logic.
209 mFirstProxy = proxy;
212 // If we're empty before adding, we have to tell the loader we now have
213 // proxies.
214 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
215 if (progressTracker->ObserverCount() == 0) {
216 MOZ_ASSERT(mURI, "Trying to SetHasProxies without key uri.");
217 if (mLoader) {
218 mLoader->SetHasProxies(this);
222 progressTracker->AddObserver(proxy);
225 nsresult imgRequest::RemoveProxy(imgRequestProxy* proxy, nsresult aStatus) {
226 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy", "proxy", proxy);
228 // This will remove our animation consumers, so after removing
229 // this proxy, we don't end up without proxies with observers, but still
230 // have animation consumers.
231 proxy->ClearAnimationConsumers();
233 // Let the status tracker do its thing before we potentially call Cancel()
234 // below, because Cancel() may result in OnStopRequest being called back
235 // before Cancel() returns, leaving the image in a different state then the
236 // one it was in at this point.
237 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
238 if (!progressTracker->RemoveObserver(proxy)) {
239 return NS_OK;
242 if (progressTracker->ObserverCount() == 0) {
243 // If we have no observers, there's nothing holding us alive. If we haven't
244 // been cancelled and thus removed from the cache, tell the image loader so
245 // we can be evicted from the cache.
246 if (mCacheEntry) {
247 MOZ_ASSERT(mURI, "Removing last observer without key uri.");
249 if (mLoader) {
250 mLoader->SetHasNoProxies(this, mCacheEntry);
252 } else {
253 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy no cache entry",
254 "uri", mURI);
257 /* If |aStatus| is a failure code, then cancel the load if it is still in
258 progress. Otherwise, let the load continue, keeping 'this' in the cache
259 with no observers. This way, if a proxy is destroyed without calling
260 cancel on it, it won't leak and won't leave a bad pointer in the observer
261 list.
263 if (!(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE) &&
264 NS_FAILED(aStatus)) {
265 LOG_MSG(gImgLog, "imgRequest::RemoveProxy",
266 "load in progress. canceling");
268 this->Cancel(NS_BINDING_ABORTED);
271 /* break the cycle from the cache entry. */
272 mCacheEntry = nullptr;
275 return NS_OK;
278 uint64_t imgRequest::InnerWindowID() const {
279 MutexAutoLock lock(mMutex);
280 return mInnerWindowId;
283 void imgRequest::SetInnerWindowID(uint64_t aInnerWindowId) {
284 MutexAutoLock lock(mMutex);
285 mInnerWindowId = aInnerWindowId;
288 void imgRequest::CancelAndAbort(nsresult aStatus) {
289 LOG_SCOPE(gImgLog, "imgRequest::CancelAndAbort");
291 Cancel(aStatus);
293 // It's possible for the channel to fail to open after we've set our
294 // notification callbacks. In that case, make sure to break the cycle between
295 // the channel and us, because it won't.
296 if (mChannel) {
297 mChannel->SetNotificationCallbacks(mPrevChannelSink);
298 mPrevChannelSink = nullptr;
302 class imgRequestMainThreadCancel : public Runnable {
303 public:
304 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
305 : Runnable("imgRequestMainThreadCancel"),
306 mImgRequest(aImgRequest),
307 mStatus(aStatus) {
308 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
309 MOZ_ASSERT(aImgRequest);
312 NS_IMETHOD Run() override {
313 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
314 mImgRequest->ContinueCancel(mStatus);
315 return NS_OK;
318 private:
319 RefPtr<imgRequest> mImgRequest;
320 nsresult mStatus;
323 void imgRequest::Cancel(nsresult aStatus) {
324 /* The Cancel() method here should only be called by this class. */
325 LOG_SCOPE(gImgLog, "imgRequest::Cancel");
327 if (NS_IsMainThread()) {
328 ContinueCancel(aStatus);
329 } else {
330 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
331 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
332 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
333 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
337 void imgRequest::ContinueCancel(nsresult aStatus) {
338 MOZ_ASSERT(NS_IsMainThread());
340 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
341 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
343 RemoveFromCache();
345 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
346 mRequest->Cancel(aStatus);
350 class imgRequestMainThreadEvict : public Runnable {
351 public:
352 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
353 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
354 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
355 MOZ_ASSERT(aImgRequest);
358 NS_IMETHOD Run() override {
359 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
360 mImgRequest->ContinueEvict();
361 return NS_OK;
364 private:
365 RefPtr<imgRequest> mImgRequest;
368 // EvictFromCache() is written to allowed to get called from any thread
369 void imgRequest::EvictFromCache() {
370 /* The EvictFromCache() method here should only be called by this class. */
371 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
373 if (NS_IsMainThread()) {
374 ContinueEvict();
375 } else {
376 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
380 // Helper-method used by EvictFromCache()
381 void imgRequest::ContinueEvict() {
382 MOZ_ASSERT(NS_IsMainThread());
384 RemoveFromCache();
387 void imgRequest::StartDecoding() {
388 MutexAutoLock lock(mMutex);
389 mDecodeRequested = true;
392 bool imgRequest::IsDecodeRequested() const {
393 MutexAutoLock lock(mMutex);
394 return mDecodeRequested;
397 nsresult imgRequest::GetURI(nsIURI** aURI) {
398 MOZ_ASSERT(aURI);
400 LOG_FUNC(gImgLog, "imgRequest::GetURI");
402 if (mURI) {
403 *aURI = mURI;
404 NS_ADDREF(*aURI);
405 return NS_OK;
408 return NS_ERROR_FAILURE;
411 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
412 MOZ_ASSERT(aURI);
414 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
416 if (mFinalURI) {
417 *aURI = mFinalURI;
418 NS_ADDREF(*aURI);
419 return NS_OK;
422 return NS_ERROR_FAILURE;
425 bool imgRequest::IsChrome() const { return mURI->SchemeIs("chrome"); }
427 bool imgRequest::IsData() const { return mURI->SchemeIs("data"); }
429 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
431 void imgRequest::RemoveFromCache() {
432 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
434 bool isInCache = false;
437 MutexAutoLock lock(mMutex);
438 isInCache = mIsInCache;
441 if (isInCache && mLoader) {
442 // mCacheEntry is nulled out when we have no more observers.
443 if (mCacheEntry) {
444 mLoader->RemoveFromCache(mCacheEntry);
445 } else {
446 mLoader->RemoveFromCache(mCacheKey);
450 mCacheEntry = nullptr;
453 bool imgRequest::HasConsumers() const {
454 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
455 return progressTracker && progressTracker->ObserverCount() > 0;
458 already_AddRefed<image::Image> imgRequest::GetImage() const {
459 MutexAutoLock lock(mMutex);
460 RefPtr<image::Image> image = mImage;
461 return image.forget();
464 int32_t imgRequest::Priority() const {
465 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
466 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
467 if (p) {
468 p->GetPriority(&priority);
470 return priority;
473 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
474 // only the first proxy is allowed to modify the priority of this image load.
476 // XXX(darin): this is probably not the most optimal algorithm as we may want
477 // to increase the priority of requests that have a lot of proxies. the key
478 // concern though is that image loads remain lower priority than other pieces
479 // of content such as link clicks, CSS, and JS.
481 if (!mFirstProxy || proxy != mFirstProxy) {
482 return;
485 AdjustPriorityInternal(delta);
488 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
489 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
490 if (p) {
491 p->AdjustPriority(aDelta);
495 void imgRequest::BoostPriority(uint32_t aCategory) {
496 if (!StaticPrefs::image_layout_network_priority()) {
497 return;
500 uint32_t newRequestedCategory =
501 (mBoostCategoriesRequested & aCategory) ^ aCategory;
502 if (!newRequestedCategory) {
503 // priority boost for each category can only apply once.
504 return;
507 MOZ_LOG(gImgLog, LogLevel::Debug,
508 ("[this=%p] imgRequest::BoostPriority for category %x", this,
509 newRequestedCategory));
511 int32_t delta = 0;
513 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
514 --delta;
517 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
518 --delta;
521 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
522 --delta;
525 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
526 delta += nsISupportsPriority::PRIORITY_HIGH;
529 AdjustPriorityInternal(delta);
530 mBoostCategoriesRequested |= newRequestedCategory;
533 void imgRequest::SetIsInCache(bool aInCache) {
534 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
535 aInCache);
536 MutexAutoLock lock(mMutex);
537 mIsInCache = aInCache;
540 void imgRequest::UpdateCacheEntrySize() {
541 if (!mCacheEntry) {
542 return;
545 RefPtr<Image> image = GetImage();
546 SizeOfState state(moz_malloc_size_of);
547 size_t size = image->SizeOfSourceWithComputedFallback(state);
548 mCacheEntry->SetDataSize(size);
551 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
552 nsIRequest* aRequest) {
553 /* get the expires info */
554 if (!aCacheEntry || aCacheEntry->GetExpiryTime() != 0) {
555 return;
558 RefPtr<imgRequest> req = aCacheEntry->GetRequest();
559 MOZ_ASSERT(req);
560 RefPtr<nsIURI> uri;
561 req->GetURI(getter_AddRefs(uri));
562 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
563 // get here in such cases sometimes (like for some redirects, see
564 // docshell/test/chrome/test_bug89419.xhtml).
566 // We have the original URI in the cache key though, probably we should be
567 // using that instead of relying on Init() getting called.
568 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest, uri);
570 // Expiration time defaults to 0. We set the expiration time on our entry if
571 // it hasn't been set yet.
572 if (!info.mExpirationTime) {
573 // If the channel doesn't support caching, then ensure this expires the
574 // next time it is used.
575 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
578 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
579 // Cache entries default to not needing to validate. We ensure that
580 // multiple calls to this function don't override an earlier decision to
581 // validate by making validation a one-way decision.
582 if (info.mMustRevalidate) {
583 aCacheEntry->SetMustValidate(info.mMustRevalidate);
587 bool imgRequest::GetMultipart() const {
588 MutexAutoLock lock(mMutex);
589 return mIsMultiPartChannel;
592 bool imgRequest::HadInsecureRedirect() const {
593 MutexAutoLock lock(mMutex);
594 return mHadInsecureRedirect;
597 /** nsIRequestObserver methods **/
599 NS_IMETHODIMP
600 imgRequest::OnStartRequest(nsIRequest* aRequest) {
601 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
603 RefPtr<Image> image;
605 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
606 nsresult rv;
607 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
608 mIsDeniedCrossSiteCORSRequest =
609 loadInfo->GetTainting() == LoadTainting::CORS &&
610 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
611 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
614 // Figure out if we're multipart.
615 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
617 MutexAutoLock lock(mMutex);
619 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
620 "Stopped being multipart?");
622 mNewPartPending = true;
623 image = mImage;
624 mIsMultiPartChannel = bool(multiPartChannel);
627 // If we're not multipart, we shouldn't have an image yet.
628 if (image && !multiPartChannel) {
629 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
630 Cancel(NS_IMAGELIB_ERROR_FAILURE);
631 return NS_ERROR_FAILURE;
635 * If mRequest is null here, then we need to set it so that we'll be able to
636 * cancel it if our Cancel() method is called. Note that this can only
637 * happen for multipart channels. We could simply not null out mRequest for
638 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
639 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
641 if (!mRequest) {
642 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
643 nsCOMPtr<nsIChannel> baseChannel;
644 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
645 mRequest = baseChannel;
648 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
649 if (channel) {
650 /* Get our principal */
651 nsCOMPtr<nsIScriptSecurityManager> secMan =
652 nsContentUtils::GetSecurityManager();
653 if (secMan) {
654 nsresult rv = secMan->GetChannelResultPrincipal(
655 channel, getter_AddRefs(mPrincipal));
656 if (NS_FAILED(rv)) {
657 return rv;
662 SetCacheValidation(mCacheEntry, aRequest);
664 // Shouldn't we be dead already if this gets hit?
665 // Probably multipart/x-mixed-replace...
666 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
667 if (progressTracker->ObserverCount() == 0) {
668 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
671 // Try to retarget OnDataAvailable to a decode thread. We must process data
672 // URIs synchronously as per the spec however.
673 if (!channel || IsData()) {
674 return NS_OK;
677 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
678 do_QueryInterface(aRequest);
679 if (retargetable) {
680 nsAutoCString mimeType;
681 nsresult rv = channel->GetContentType(mimeType);
682 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
683 // Retarget OnDataAvailable to the DecodePool's IO thread.
684 nsCOMPtr<nsIEventTarget> target =
685 DecodePool::Singleton()->GetIOEventTarget();
686 rv = retargetable->RetargetDeliveryTo(target);
688 MOZ_LOG(gImgLog, LogLevel::Warning,
689 ("[this=%p] imgRequest::OnStartRequest -- "
690 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
691 this, static_cast<uint32_t>(rv),
692 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
695 return NS_OK;
698 NS_IMETHODIMP
699 imgRequest::OnStopRequest(nsIRequest* aRequest, nsresult status) {
700 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
701 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
703 RefPtr<Image> image = GetImage();
705 RefPtr<imgRequest> strongThis = this;
707 bool isMultipart = false;
708 bool newPartPending = false;
710 MutexAutoLock lock(mMutex);
711 isMultipart = mIsMultiPartChannel;
712 newPartPending = mNewPartPending;
714 if (isMultipart && newPartPending) {
715 OnDataAvailable(aRequest, nullptr, 0, 0);
718 // XXXldb What if this is a non-last part of a multipart request?
719 // xxx before we release our reference to mRequest, lets
720 // save the last status that we saw so that the
721 // imgRequestProxy will have access to it.
722 if (mRequest) {
723 mRequest = nullptr; // we no longer need the request
726 // stop holding a ref to the channel, since we don't need it anymore
727 if (mChannel) {
728 mChannel->SetNotificationCallbacks(mPrevChannelSink);
729 mPrevChannelSink = nullptr;
730 mChannel = nullptr;
733 bool lastPart = true;
734 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
735 if (mpchan) {
736 mpchan->GetIsLastPart(&lastPart);
739 bool isPartial = false;
740 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
741 isPartial = true;
742 status = NS_OK; // fake happy face
745 // Tell the image that it has all of the source data. Note that this can
746 // trigger a failure, since the image might be waiting for more non-optional
747 // data and this is the point where we break the news that it's not coming.
748 if (image) {
749 nsresult rv = image->OnImageDataComplete(aRequest, status, lastPart);
751 // If we got an error in the OnImageDataComplete() call, we don't want to
752 // proceed as if nothing bad happened. However, we also want to give
753 // precedence to failure status codes from necko, since presumably they're
754 // more meaningful.
755 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
756 status = rv;
760 // If the request went through, update the cache entry size. Otherwise,
761 // cancel the request, which removes us from the cache.
762 if (image && NS_SUCCEEDED(status) && !isPartial) {
763 // We update the cache entry size here because this is where we finish
764 // loading compressed source data, which is part of our size calculus.
765 UpdateCacheEntrySize();
767 } else if (isPartial) {
768 // Remove the partial image from the cache.
769 this->EvictFromCache();
771 } else {
772 mImageErrorCode = status;
774 // if the error isn't "just" a partial transfer
775 // stops animations, removes from cache
776 this->Cancel(status);
779 if (!image) {
780 // We have to fire the OnStopRequest notifications ourselves because there's
781 // no image capable of doing so.
782 Progress progress =
783 LoadCompleteProgress(lastPart, /* aError = */ false, status);
785 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
786 progressTracker->SyncNotifyProgress(progress);
789 mTimedChannel = nullptr;
790 return NS_OK;
793 struct mimetype_closure {
794 nsACString* newType;
797 /* prototype for these defined below */
798 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
799 const char* fromRawSegment,
800 uint32_t toOffset, uint32_t count,
801 uint32_t* writeCount);
803 /** nsThreadRetargetableStreamListener methods **/
804 NS_IMETHODIMP
805 imgRequest::CheckListenerChain() {
806 // TODO Might need more checking here.
807 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
808 return NS_OK;
811 /** nsIStreamListener methods **/
813 struct NewPartResult final {
814 explicit NewPartResult(image::Image* aExistingImage)
815 : mImage(aExistingImage),
816 mIsFirstPart(!aExistingImage),
817 mSucceeded(false),
818 mShouldResetCacheEntry(false) {}
820 nsAutoCString mContentType;
821 nsAutoCString mContentDisposition;
822 RefPtr<image::Image> mImage;
823 const bool mIsFirstPart;
824 bool mSucceeded;
825 bool mShouldResetCacheEntry;
828 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
829 nsIInputStream* aInStr, uint32_t aCount,
830 nsIURI* aURI, bool aIsMultipart,
831 image::Image* aExistingImage,
832 ProgressTracker* aProgressTracker,
833 uint64_t aInnerWindowId) {
834 NewPartResult result(aExistingImage);
836 if (aInStr) {
837 mimetype_closure closure;
838 closure.newType = &result.mContentType;
840 // Look at the first few bytes and see if we can tell what the data is from
841 // that since servers tend to lie. :(
842 uint32_t out;
843 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
846 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
847 if (result.mContentType.IsEmpty()) {
848 nsresult rv =
849 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
850 if (NS_FAILED(rv)) {
851 MOZ_LOG(gImgLog, LogLevel::Error,
852 ("imgRequest::PrepareForNewPart -- "
853 "Content type unavailable from the channel\n"));
854 if (!aIsMultipart) {
855 return result;
860 if (chan) {
861 chan->GetContentDispositionHeader(result.mContentDisposition);
864 MOZ_LOG(gImgLog, LogLevel::Debug,
865 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
866 result.mContentType.get()));
868 // XXX If server lied about mimetype and it's SVG, we may need to copy
869 // the data and dispatch back to the main thread, AND tell the channel to
870 // dispatch there in the future.
872 // Create the new image and give it ownership of our ProgressTracker.
873 if (aIsMultipart) {
874 // Create the ProgressTracker and image for this part.
875 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
876 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
877 aRequest, progressTracker, result.mContentType, aURI,
878 /* aIsMultipart = */ true, aInnerWindowId);
880 if (result.mIsFirstPart) {
881 // First part for a multipart channel. Create the MultipartImage wrapper.
882 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
883 aProgressTracker->SetIsMultipart();
884 result.mImage = image::ImageFactory::CreateMultipartImage(
885 partImage, aProgressTracker);
886 } else {
887 // Transition to the new part.
888 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
889 multipartImage->BeginTransitionToPart(partImage);
891 // Reset our cache entry size so it doesn't keep growing without bound.
892 result.mShouldResetCacheEntry = true;
894 } else {
895 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
896 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
898 // Create an image using our progress tracker.
899 result.mImage = image::ImageFactory::CreateImage(
900 aRequest, aProgressTracker, result.mContentType, aURI,
901 /* aIsMultipart = */ false, aInnerWindowId);
904 MOZ_ASSERT(result.mImage);
905 if (!result.mImage->HasError() || aIsMultipart) {
906 // We allow multipart images to fail to initialize (which generally
907 // indicates a bad content type) without cancelling the load, because
908 // subsequent parts might be fine.
909 result.mSucceeded = true;
912 return result;
915 class FinishPreparingForNewPartRunnable final : public Runnable {
916 public:
917 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
918 NewPartResult&& aResult)
919 : Runnable("FinishPreparingForNewPartRunnable"),
920 mImgRequest(aImgRequest),
921 mResult(aResult) {
922 MOZ_ASSERT(aImgRequest);
925 NS_IMETHOD Run() override {
926 mImgRequest->FinishPreparingForNewPart(mResult);
927 return NS_OK;
930 private:
931 RefPtr<imgRequest> mImgRequest;
932 NewPartResult mResult;
935 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
936 MOZ_ASSERT(NS_IsMainThread());
938 mContentType = aResult.mContentType;
940 SetProperties(aResult.mContentType, aResult.mContentDisposition);
942 if (aResult.mIsFirstPart) {
943 // Notify listeners that we have an image.
944 mImageAvailable = true;
945 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
946 progressTracker->OnImageAvailable();
947 MOZ_ASSERT(progressTracker->HasImage());
950 if (aResult.mShouldResetCacheEntry) {
951 ResetCacheEntry();
954 if (IsDecodeRequested()) {
955 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
959 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
961 NS_IMETHODIMP
962 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
963 uint64_t aOffset, uint32_t aCount) {
964 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
966 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
968 RefPtr<Image> image;
969 RefPtr<ProgressTracker> progressTracker;
970 bool isMultipart = false;
971 bool newPartPending = false;
972 uint64_t innerWindowId = 0;
974 // Retrieve and update our state.
976 MutexAutoLock lock(mMutex);
977 image = mImage;
978 progressTracker = mProgressTracker;
979 isMultipart = mIsMultiPartChannel;
980 newPartPending = mNewPartPending;
981 mNewPartPending = false;
982 innerWindowId = mInnerWindowId;
985 // If this is a new part, we need to sniff its content type and create an
986 // appropriate image.
987 if (newPartPending) {
988 NewPartResult result =
989 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
990 progressTracker, innerWindowId);
991 bool succeeded = result.mSucceeded;
993 if (result.mImage) {
994 image = result.mImage;
995 nsCOMPtr<nsIEventTarget> eventTarget;
997 // Update our state to reflect this new part.
999 MutexAutoLock lock(mMutex);
1000 mImage = image;
1002 // We only get an event target if we are not on the main thread, because
1003 // we have to dispatch in that case. If we are on the main thread, but
1004 // on a different scheduler group than ProgressTracker would give us,
1005 // that is okay because nothing in imagelib requires that, just our
1006 // listeners (which have their own checks).
1007 if (!NS_IsMainThread()) {
1008 eventTarget = mProgressTracker->GetEventTarget();
1009 MOZ_ASSERT(eventTarget);
1012 mProgressTracker = nullptr;
1015 // Some property objects are not threadsafe, and we need to send
1016 // OnImageAvailable on the main thread, so finish on the main thread.
1017 if (!eventTarget) {
1018 MOZ_ASSERT(NS_IsMainThread());
1019 FinishPreparingForNewPart(result);
1020 } else {
1021 nsCOMPtr<nsIRunnable> runnable =
1022 new FinishPreparingForNewPartRunnable(this, std::move(result));
1023 eventTarget->Dispatch(CreateRenderBlockingRunnable(runnable.forget()),
1024 NS_DISPATCH_NORMAL);
1028 if (!succeeded) {
1029 // Something went wrong; probably a content type issue.
1030 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1031 return NS_BINDING_ABORTED;
1035 // Notify the image that it has new data.
1036 if (aInStr) {
1037 nsresult rv =
1038 image->OnImageDataAvailable(aRequest, aInStr, aOffset, aCount);
1040 if (NS_FAILED(rv)) {
1041 MOZ_LOG(gImgLog, LogLevel::Warning,
1042 ("[this=%p] imgRequest::OnDataAvailable -- "
1043 "copy to RasterImage failed\n",
1044 this));
1045 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1046 return NS_BINDING_ABORTED;
1050 return NS_OK;
1053 void imgRequest::SetProperties(const nsACString& aContentType,
1054 const nsACString& aContentDisposition) {
1055 /* set our mimetype as a property */
1056 nsCOMPtr<nsISupportsCString> contentType =
1057 do_CreateInstance("@mozilla.org/supports-cstring;1");
1058 if (contentType) {
1059 contentType->SetData(aContentType);
1060 mProperties->Set("type", contentType);
1063 /* set our content disposition as a property */
1064 if (!aContentDisposition.IsEmpty()) {
1065 nsCOMPtr<nsISupportsCString> contentDisposition =
1066 do_CreateInstance("@mozilla.org/supports-cstring;1");
1067 if (contentDisposition) {
1068 contentDisposition->SetData(aContentDisposition);
1069 mProperties->Set("content-disposition", contentDisposition);
1074 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1075 const char* fromRawSegment,
1076 uint32_t toOffset, uint32_t count,
1077 uint32_t* writeCount) {
1078 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1080 NS_ASSERTION(closure, "closure is null!");
1082 if (count > 0) {
1083 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1086 *writeCount = 0;
1087 return NS_ERROR_FAILURE;
1090 /** nsIInterfaceRequestor methods **/
1092 NS_IMETHODIMP
1093 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1094 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1095 return QueryInterface(aIID, aResult);
1098 NS_ASSERTION(
1099 mPrevChannelSink != this,
1100 "Infinite recursion - don't keep track of channel sinks that are us!");
1101 return mPrevChannelSink->GetInterface(aIID, aResult);
1104 /** nsIChannelEventSink methods **/
1105 NS_IMETHODIMP
1106 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1107 nsIChannel* newChannel, uint32_t flags,
1108 nsIAsyncVerifyRedirectCallback* callback) {
1109 NS_ASSERTION(mRequest && mChannel,
1110 "Got a channel redirect after we nulled out mRequest!");
1111 NS_ASSERTION(mChannel == oldChannel,
1112 "Got a channel redirect for an unknown channel!");
1113 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1115 SetCacheValidation(mCacheEntry, oldChannel);
1117 // Prepare for callback
1118 mRedirectCallback = callback;
1119 mNewRedirectChannel = newChannel;
1121 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1122 if (sink) {
1123 nsresult rv =
1124 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1125 if (NS_FAILED(rv)) {
1126 mRedirectCallback = nullptr;
1127 mNewRedirectChannel = nullptr;
1129 return rv;
1132 (void)OnRedirectVerifyCallback(NS_OK);
1133 return NS_OK;
1136 NS_IMETHODIMP
1137 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1138 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1139 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1141 if (NS_FAILED(result)) {
1142 mRedirectCallback->OnRedirectVerifyCallback(result);
1143 mRedirectCallback = nullptr;
1144 mNewRedirectChannel = nullptr;
1145 return NS_OK;
1148 mChannel = mNewRedirectChannel;
1149 mTimedChannel = do_QueryInterface(mChannel);
1150 mNewRedirectChannel = nullptr;
1152 if (LOG_TEST(LogLevel::Debug)) {
1153 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1154 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1157 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1158 // security code, which needs to know whether there is an insecure load at any
1159 // point in the redirect chain.
1160 bool schemeLocal = false;
1161 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1162 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1163 &schemeLocal)) ||
1164 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1165 !schemeLocal)) {
1166 MutexAutoLock lock(mMutex);
1168 // The csp directive upgrade-insecure-requests performs an internal redirect
1169 // to upgrade all requests from http to https before any data is fetched
1170 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1171 // internal redirect.
1172 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1173 bool upgradeInsecureRequests =
1174 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1175 loadInfo->GetBrowserUpgradeInsecureRequests()
1176 : false;
1177 if (!upgradeInsecureRequests) {
1178 mHadInsecureRedirect = true;
1182 // Update the final URI.
1183 mChannel->GetURI(getter_AddRefs(mFinalURI));
1185 if (LOG_TEST(LogLevel::Debug)) {
1186 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1187 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1190 // Make sure we have a protocol that returns data rather than opens an
1191 // external application, e.g. 'mailto:'.
1192 bool doesNotReturnData = false;
1193 nsresult rv = NS_URIChainHasFlags(
1194 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1195 &doesNotReturnData);
1197 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1198 rv = NS_ERROR_ABORT;
1201 if (NS_FAILED(rv)) {
1202 mRedirectCallback->OnRedirectVerifyCallback(rv);
1203 mRedirectCallback = nullptr;
1204 return NS_OK;
1207 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1208 mRedirectCallback = nullptr;
1209 return NS_OK;