Bug 1732043 [wpt PR 30820] - WebKit export of https://bugs.webkit.org/show_bug.cgi...
[gecko.git] / image / imgRequest.cpp
blobc5ae04b26bea4e590a922a0fc8db0b3e993366de
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 mInnerWindowId(0),
61 mCORSMode(CORS_NONE),
62 mImageErrorCode(NS_OK),
63 mImageAvailable(false),
64 mIsDeniedCrossSiteCORSRequest(false),
65 mIsCrossSiteNoCORSRequest(false),
66 mMutex("imgRequest"),
67 mProgressTracker(new ProgressTracker()),
68 mIsMultiPartChannel(false),
69 mIsInCache(false),
70 mDecodeRequested(false),
71 mNewPartPending(false),
72 mHadInsecureRedirect(false) {
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(nsIURI* aURI, nsIURI* aFinalURI,
87 bool aHadInsecureRedirect, nsIRequest* aRequest,
88 nsIChannel* aChannel, imgCacheEntry* aCacheEntry,
89 mozilla::dom::Document* aLoadingDocument,
90 nsIPrincipal* aTriggeringPrincipal,
91 mozilla::CORSMode aCORSMode,
92 nsIReferrerInfo* aReferrerInfo) {
93 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
95 LOG_FUNC(gImgLog, "imgRequest::Init");
97 MOZ_ASSERT(!mImage, "Multiple calls to init");
98 MOZ_ASSERT(aURI, "No uri");
99 MOZ_ASSERT(aFinalURI, "No final uri");
100 MOZ_ASSERT(aRequest, "No request");
101 MOZ_ASSERT(aChannel, "No channel");
103 mProperties = new nsProperties();
104 mURI = aURI;
105 mFinalURI = aFinalURI;
106 mRequest = aRequest;
107 mChannel = aChannel;
108 mTimedChannel = do_QueryInterface(mChannel);
109 mTriggeringPrincipal = aTriggeringPrincipal;
110 mCORSMode = aCORSMode;
111 mReferrerInfo = aReferrerInfo;
113 // If the original URI and the final URI are different, check whether the
114 // original URI is secure. We deliberately don't take the final URI into
115 // account, as it needs to be handled using more complicated rules than
116 // earlier elements of the redirect chain.
117 if (aURI != aFinalURI) {
118 bool schemeLocal = false;
119 if (NS_FAILED(NS_URIChainHasFlags(
120 aURI, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &schemeLocal)) ||
121 (!aURI->SchemeIs("https") && !aURI->SchemeIs("chrome") &&
122 !schemeLocal)) {
123 mHadInsecureRedirect = true;
127 // imgCacheValidator may have handled redirects before we were created, so we
128 // allow the caller to let us know if any redirects were insecure.
129 mHadInsecureRedirect = mHadInsecureRedirect || aHadInsecureRedirect;
131 mChannel->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink));
133 NS_ASSERTION(mPrevChannelSink != this,
134 "Initializing with a channel that already calls back to us!");
136 mChannel->SetNotificationCallbacks(this);
138 mCacheEntry = aCacheEntry;
139 mCacheEntry->UpdateLoadTime();
141 SetLoadId(aLoadingDocument);
143 // Grab the inner window ID of the loading document, if possible.
144 if (aLoadingDocument) {
145 mInnerWindowId = aLoadingDocument->InnerWindowID();
148 return NS_OK;
151 bool imgRequest::CanReuseWithoutValidation(dom::Document* aDoc) const {
152 // If the request's loadId is the same as the aLoadingDocument, then it is ok
153 // to use this one because it has already been validated for this context.
154 // XXX: nullptr seems to be a 'special' key value that indicates that NO
155 // validation is required.
156 // XXX: we also check the window ID because the loadID() can return a reused
157 // pointer of a document. This can still happen for non-document image
158 // cache entries.
159 void* key = (void*)aDoc;
160 uint64_t innerWindowID = aDoc ? aDoc->InnerWindowID() : 0;
161 if (LoadId() == key && InnerWindowID() == innerWindowID) {
162 return true;
165 // As a special-case, if this is a print preview document, also validate on
166 // the original document. This allows to print uncacheable images.
167 if (dom::Document* original = aDoc ? aDoc->GetOriginalDocument() : nullptr) {
168 return CanReuseWithoutValidation(original);
171 return false;
174 void imgRequest::ClearLoader() { mLoader = nullptr; }
176 already_AddRefed<ProgressTracker> imgRequest::GetProgressTracker() const {
177 MutexAutoLock lock(mMutex);
179 if (mImage) {
180 MOZ_ASSERT(!mProgressTracker,
181 "Should have given mProgressTracker to mImage");
182 return mImage->GetProgressTracker();
184 MOZ_ASSERT(mProgressTracker,
185 "Should have mProgressTracker until we create mImage");
186 RefPtr<ProgressTracker> progressTracker = mProgressTracker;
187 MOZ_ASSERT(progressTracker);
188 return progressTracker.forget();
191 void imgRequest::SetCacheEntry(imgCacheEntry* entry) { mCacheEntry = entry; }
193 bool imgRequest::HasCacheEntry() const { return mCacheEntry != nullptr; }
195 void imgRequest::ResetCacheEntry() {
196 if (HasCacheEntry()) {
197 mCacheEntry->SetDataSize(0);
201 void imgRequest::AddProxy(imgRequestProxy* proxy) {
202 MOZ_ASSERT(proxy, "null imgRequestProxy passed in");
203 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::AddProxy", "proxy", proxy);
205 if (!mFirstProxy) {
206 // Save a raw pointer to the first proxy we see, for use in the network
207 // priority logic.
208 mFirstProxy = proxy;
211 // If we're empty before adding, we have to tell the loader we now have
212 // proxies.
213 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
214 if (progressTracker->ObserverCount() == 0) {
215 MOZ_ASSERT(mURI, "Trying to SetHasProxies without key uri.");
216 if (mLoader) {
217 mLoader->SetHasProxies(this);
221 progressTracker->AddObserver(proxy);
224 nsresult imgRequest::RemoveProxy(imgRequestProxy* proxy, nsresult aStatus) {
225 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy", "proxy", proxy);
227 // This will remove our animation consumers, so after removing
228 // this proxy, we don't end up without proxies with observers, but still
229 // have animation consumers.
230 proxy->ClearAnimationConsumers();
232 // Let the status tracker do its thing before we potentially call Cancel()
233 // below, because Cancel() may result in OnStopRequest being called back
234 // before Cancel() returns, leaving the image in a different state then the
235 // one it was in at this point.
236 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
237 if (!progressTracker->RemoveObserver(proxy)) {
238 return NS_OK;
241 if (progressTracker->ObserverCount() == 0) {
242 // If we have no observers, there's nothing holding us alive. If we haven't
243 // been cancelled and thus removed from the cache, tell the image loader so
244 // we can be evicted from the cache.
245 if (mCacheEntry) {
246 MOZ_ASSERT(mURI, "Removing last observer without key uri.");
248 if (mLoader) {
249 mLoader->SetHasNoProxies(this, mCacheEntry);
251 } else {
252 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy no cache entry",
253 "uri", mURI);
256 /* If |aStatus| is a failure code, then cancel the load if it is still in
257 progress. Otherwise, let the load continue, keeping 'this' in the cache
258 with no observers. This way, if a proxy is destroyed without calling
259 cancel on it, it won't leak and won't leave a bad pointer in the observer
260 list.
262 if (!(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE) &&
263 NS_FAILED(aStatus)) {
264 LOG_MSG(gImgLog, "imgRequest::RemoveProxy",
265 "load in progress. canceling");
267 this->Cancel(NS_BINDING_ABORTED);
270 /* break the cycle from the cache entry. */
271 mCacheEntry = nullptr;
274 return NS_OK;
277 void imgRequest::CancelAndAbort(nsresult aStatus) {
278 LOG_SCOPE(gImgLog, "imgRequest::CancelAndAbort");
280 Cancel(aStatus);
282 // It's possible for the channel to fail to open after we've set our
283 // notification callbacks. In that case, make sure to break the cycle between
284 // the channel and us, because it won't.
285 if (mChannel) {
286 mChannel->SetNotificationCallbacks(mPrevChannelSink);
287 mPrevChannelSink = nullptr;
291 class imgRequestMainThreadCancel : public Runnable {
292 public:
293 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
294 : Runnable("imgRequestMainThreadCancel"),
295 mImgRequest(aImgRequest),
296 mStatus(aStatus) {
297 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
298 MOZ_ASSERT(aImgRequest);
301 NS_IMETHOD Run() override {
302 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
303 mImgRequest->ContinueCancel(mStatus);
304 return NS_OK;
307 private:
308 RefPtr<imgRequest> mImgRequest;
309 nsresult mStatus;
312 void imgRequest::Cancel(nsresult aStatus) {
313 /* The Cancel() method here should only be called by this class. */
314 LOG_SCOPE(gImgLog, "imgRequest::Cancel");
316 if (NS_IsMainThread()) {
317 ContinueCancel(aStatus);
318 } else {
319 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
320 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
321 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
322 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
326 void imgRequest::ContinueCancel(nsresult aStatus) {
327 MOZ_ASSERT(NS_IsMainThread());
329 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
330 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
332 RemoveFromCache();
334 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
335 mRequest->Cancel(aStatus);
339 class imgRequestMainThreadEvict : public Runnable {
340 public:
341 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
342 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
343 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
344 MOZ_ASSERT(aImgRequest);
347 NS_IMETHOD Run() override {
348 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
349 mImgRequest->ContinueEvict();
350 return NS_OK;
353 private:
354 RefPtr<imgRequest> mImgRequest;
357 // EvictFromCache() is written to allowed to get called from any thread
358 void imgRequest::EvictFromCache() {
359 /* The EvictFromCache() method here should only be called by this class. */
360 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
362 if (NS_IsMainThread()) {
363 ContinueEvict();
364 } else {
365 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
369 // Helper-method used by EvictFromCache()
370 void imgRequest::ContinueEvict() {
371 MOZ_ASSERT(NS_IsMainThread());
373 RemoveFromCache();
376 void imgRequest::StartDecoding() {
377 MutexAutoLock lock(mMutex);
378 mDecodeRequested = true;
381 bool imgRequest::IsDecodeRequested() const {
382 MutexAutoLock lock(mMutex);
383 return mDecodeRequested;
386 nsresult imgRequest::GetURI(nsIURI** aURI) {
387 MOZ_ASSERT(aURI);
389 LOG_FUNC(gImgLog, "imgRequest::GetURI");
391 if (mURI) {
392 *aURI = mURI;
393 NS_ADDREF(*aURI);
394 return NS_OK;
397 return NS_ERROR_FAILURE;
400 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
401 MOZ_ASSERT(aURI);
403 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
405 if (mFinalURI) {
406 *aURI = mFinalURI;
407 NS_ADDREF(*aURI);
408 return NS_OK;
411 return NS_ERROR_FAILURE;
414 bool imgRequest::IsChrome() const { return mURI->SchemeIs("chrome"); }
416 bool imgRequest::IsData() const { return mURI->SchemeIs("data"); }
418 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
420 void imgRequest::RemoveFromCache() {
421 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
423 bool isInCache = false;
426 MutexAutoLock lock(mMutex);
427 isInCache = mIsInCache;
430 if (isInCache && mLoader) {
431 // mCacheEntry is nulled out when we have no more observers.
432 if (mCacheEntry) {
433 mLoader->RemoveFromCache(mCacheEntry);
434 } else {
435 mLoader->RemoveFromCache(mCacheKey);
439 mCacheEntry = nullptr;
442 bool imgRequest::HasConsumers() const {
443 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
444 return progressTracker && progressTracker->ObserverCount() > 0;
447 already_AddRefed<image::Image> imgRequest::GetImage() const {
448 MutexAutoLock lock(mMutex);
449 RefPtr<image::Image> image = mImage;
450 return image.forget();
453 int32_t imgRequest::Priority() const {
454 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
455 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
456 if (p) {
457 p->GetPriority(&priority);
459 return priority;
462 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
463 // only the first proxy is allowed to modify the priority of this image load.
465 // XXX(darin): this is probably not the most optimal algorithm as we may want
466 // to increase the priority of requests that have a lot of proxies. the key
467 // concern though is that image loads remain lower priority than other pieces
468 // of content such as link clicks, CSS, and JS.
470 if (!mFirstProxy || proxy != mFirstProxy) {
471 return;
474 AdjustPriorityInternal(delta);
477 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
478 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
479 if (p) {
480 p->AdjustPriority(aDelta);
484 void imgRequest::BoostPriority(uint32_t aCategory) {
485 if (!StaticPrefs::image_layout_network_priority()) {
486 return;
489 uint32_t newRequestedCategory =
490 (mBoostCategoriesRequested & aCategory) ^ aCategory;
491 if (!newRequestedCategory) {
492 // priority boost for each category can only apply once.
493 return;
496 MOZ_LOG(gImgLog, LogLevel::Debug,
497 ("[this=%p] imgRequest::BoostPriority for category %x", this,
498 newRequestedCategory));
500 int32_t delta = 0;
502 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
503 --delta;
506 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
507 --delta;
510 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
511 --delta;
514 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
515 delta += nsISupportsPriority::PRIORITY_HIGH;
518 AdjustPriorityInternal(delta);
519 mBoostCategoriesRequested |= newRequestedCategory;
522 void imgRequest::SetIsInCache(bool aInCache) {
523 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
524 aInCache);
525 MutexAutoLock lock(mMutex);
526 mIsInCache = aInCache;
529 void imgRequest::UpdateCacheEntrySize() {
530 if (!mCacheEntry) {
531 return;
534 RefPtr<Image> image = GetImage();
535 SizeOfState state(moz_malloc_size_of);
536 size_t size = image->SizeOfSourceWithComputedFallback(state);
537 mCacheEntry->SetDataSize(size);
540 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
541 nsIRequest* aRequest) {
542 /* get the expires info */
543 if (!aCacheEntry || aCacheEntry->GetExpiryTime() != 0) {
544 return;
547 RefPtr<imgRequest> req = aCacheEntry->GetRequest();
548 MOZ_ASSERT(req);
549 RefPtr<nsIURI> uri;
550 req->GetURI(getter_AddRefs(uri));
551 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
552 // get here in such cases sometimes (like for some redirects, see
553 // docshell/test/chrome/test_bug89419.xhtml).
555 // We have the original URI in the cache key though, probably we should be
556 // using that instead of relying on Init() getting called.
557 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest, uri);
559 // Expiration time defaults to 0. We set the expiration time on our entry if
560 // it hasn't been set yet.
561 if (!info.mExpirationTime) {
562 // If the channel doesn't support caching, then ensure this expires the
563 // next time it is used.
564 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
567 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
568 // Cache entries default to not needing to validate. We ensure that
569 // multiple calls to this function don't override an earlier decision to
570 // validate by making validation a one-way decision.
571 if (info.mMustRevalidate) {
572 aCacheEntry->SetMustValidate(info.mMustRevalidate);
576 bool imgRequest::GetMultipart() const {
577 MutexAutoLock lock(mMutex);
578 return mIsMultiPartChannel;
581 bool imgRequest::HadInsecureRedirect() const {
582 MutexAutoLock lock(mMutex);
583 return mHadInsecureRedirect;
586 /** nsIRequestObserver methods **/
588 NS_IMETHODIMP
589 imgRequest::OnStartRequest(nsIRequest* aRequest) {
590 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
592 RefPtr<Image> image;
594 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
595 nsresult rv;
596 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
597 mIsDeniedCrossSiteCORSRequest =
598 loadInfo->GetTainting() == LoadTainting::CORS &&
599 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
600 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
603 // Figure out if we're multipart.
604 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
606 MutexAutoLock lock(mMutex);
608 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
609 "Stopped being multipart?");
611 mNewPartPending = true;
612 image = mImage;
613 mIsMultiPartChannel = bool(multiPartChannel);
616 // If we're not multipart, we shouldn't have an image yet.
617 if (image && !multiPartChannel) {
618 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
619 Cancel(NS_IMAGELIB_ERROR_FAILURE);
620 return NS_ERROR_FAILURE;
624 * If mRequest is null here, then we need to set it so that we'll be able to
625 * cancel it if our Cancel() method is called. Note that this can only
626 * happen for multipart channels. We could simply not null out mRequest for
627 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
628 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
630 if (!mRequest) {
631 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
632 nsCOMPtr<nsIChannel> baseChannel;
633 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
634 mRequest = baseChannel;
637 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
638 if (channel) {
639 /* Get our principal */
640 nsCOMPtr<nsIScriptSecurityManager> secMan =
641 nsContentUtils::GetSecurityManager();
642 if (secMan) {
643 nsresult rv = secMan->GetChannelResultPrincipal(
644 channel, getter_AddRefs(mPrincipal));
645 if (NS_FAILED(rv)) {
646 return rv;
651 SetCacheValidation(mCacheEntry, aRequest);
653 // Shouldn't we be dead already if this gets hit?
654 // Probably multipart/x-mixed-replace...
655 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
656 if (progressTracker->ObserverCount() == 0) {
657 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
660 // Try to retarget OnDataAvailable to a decode thread. We must process data
661 // URIs synchronously as per the spec however.
662 if (!channel || IsData()) {
663 return NS_OK;
666 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
667 do_QueryInterface(aRequest);
668 if (retargetable) {
669 nsAutoCString mimeType;
670 nsresult rv = channel->GetContentType(mimeType);
671 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
672 // Retarget OnDataAvailable to the DecodePool's IO thread.
673 nsCOMPtr<nsIEventTarget> target =
674 DecodePool::Singleton()->GetIOEventTarget();
675 rv = retargetable->RetargetDeliveryTo(target);
677 MOZ_LOG(gImgLog, LogLevel::Warning,
678 ("[this=%p] imgRequest::OnStartRequest -- "
679 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
680 this, static_cast<uint32_t>(rv),
681 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
684 return NS_OK;
687 NS_IMETHODIMP
688 imgRequest::OnStopRequest(nsIRequest* aRequest, nsresult status) {
689 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
690 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
692 RefPtr<Image> image = GetImage();
694 RefPtr<imgRequest> strongThis = this;
696 if (mIsMultiPartChannel && mNewPartPending) {
697 OnDataAvailable(aRequest, nullptr, 0, 0);
700 // XXXldb What if this is a non-last part of a multipart request?
701 // xxx before we release our reference to mRequest, lets
702 // save the last status that we saw so that the
703 // imgRequestProxy will have access to it.
704 if (mRequest) {
705 mRequest = nullptr; // we no longer need the request
708 // stop holding a ref to the channel, since we don't need it anymore
709 if (mChannel) {
710 mChannel->SetNotificationCallbacks(mPrevChannelSink);
711 mPrevChannelSink = nullptr;
712 mChannel = nullptr;
715 bool lastPart = true;
716 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
717 if (mpchan) {
718 mpchan->GetIsLastPart(&lastPart);
721 bool isPartial = false;
722 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
723 isPartial = true;
724 status = NS_OK; // fake happy face
727 // Tell the image that it has all of the source data. Note that this can
728 // trigger a failure, since the image might be waiting for more non-optional
729 // data and this is the point where we break the news that it's not coming.
730 if (image) {
731 nsresult rv =
732 image->OnImageDataComplete(aRequest, nullptr, status, lastPart);
734 // If we got an error in the OnImageDataComplete() call, we don't want to
735 // proceed as if nothing bad happened. However, we also want to give
736 // precedence to failure status codes from necko, since presumably they're
737 // more meaningful.
738 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
739 status = rv;
743 // If the request went through, update the cache entry size. Otherwise,
744 // cancel the request, which removes us from the cache.
745 if (image && NS_SUCCEEDED(status) && !isPartial) {
746 // We update the cache entry size here because this is where we finish
747 // loading compressed source data, which is part of our size calculus.
748 UpdateCacheEntrySize();
750 } else if (isPartial) {
751 // Remove the partial image from the cache.
752 this->EvictFromCache();
754 } else {
755 mImageErrorCode = status;
757 // if the error isn't "just" a partial transfer
758 // stops animations, removes from cache
759 this->Cancel(status);
762 if (!image) {
763 // We have to fire the OnStopRequest notifications ourselves because there's
764 // no image capable of doing so.
765 Progress progress =
766 LoadCompleteProgress(lastPart, /* aError = */ false, status);
768 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
769 progressTracker->SyncNotifyProgress(progress);
772 mTimedChannel = nullptr;
773 return NS_OK;
776 struct mimetype_closure {
777 nsACString* newType;
780 /* prototype for these defined below */
781 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
782 const char* fromRawSegment,
783 uint32_t toOffset, uint32_t count,
784 uint32_t* writeCount);
786 /** nsThreadRetargetableStreamListener methods **/
787 NS_IMETHODIMP
788 imgRequest::CheckListenerChain() {
789 // TODO Might need more checking here.
790 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
791 return NS_OK;
794 /** nsIStreamListener methods **/
796 struct NewPartResult final {
797 explicit NewPartResult(image::Image* aExistingImage)
798 : mImage(aExistingImage),
799 mIsFirstPart(!aExistingImage),
800 mSucceeded(false),
801 mShouldResetCacheEntry(false) {}
803 nsAutoCString mContentType;
804 nsAutoCString mContentDisposition;
805 RefPtr<image::Image> mImage;
806 const bool mIsFirstPart;
807 bool mSucceeded;
808 bool mShouldResetCacheEntry;
811 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
812 nsIInputStream* aInStr, uint32_t aCount,
813 nsIURI* aURI, bool aIsMultipart,
814 image::Image* aExistingImage,
815 ProgressTracker* aProgressTracker,
816 uint32_t aInnerWindowId) {
817 NewPartResult result(aExistingImage);
819 if (aInStr) {
820 mimetype_closure closure;
821 closure.newType = &result.mContentType;
823 // Look at the first few bytes and see if we can tell what the data is from
824 // that since servers tend to lie. :(
825 uint32_t out;
826 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
829 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
830 if (result.mContentType.IsEmpty()) {
831 nsresult rv =
832 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
833 if (NS_FAILED(rv)) {
834 MOZ_LOG(gImgLog, LogLevel::Error,
835 ("imgRequest::PrepareForNewPart -- "
836 "Content type unavailable from the channel\n"));
837 if (!aIsMultipart) {
838 return result;
843 if (chan) {
844 chan->GetContentDispositionHeader(result.mContentDisposition);
847 MOZ_LOG(gImgLog, LogLevel::Debug,
848 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
849 result.mContentType.get()));
851 // XXX If server lied about mimetype and it's SVG, we may need to copy
852 // the data and dispatch back to the main thread, AND tell the channel to
853 // dispatch there in the future.
855 // Create the new image and give it ownership of our ProgressTracker.
856 if (aIsMultipart) {
857 // Create the ProgressTracker and image for this part.
858 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
859 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
860 aRequest, progressTracker, result.mContentType, aURI,
861 /* aIsMultipart = */ true, aInnerWindowId);
863 if (result.mIsFirstPart) {
864 // First part for a multipart channel. Create the MultipartImage wrapper.
865 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
866 aProgressTracker->SetIsMultipart();
867 result.mImage = image::ImageFactory::CreateMultipartImage(
868 partImage, aProgressTracker);
869 } else {
870 // Transition to the new part.
871 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
872 multipartImage->BeginTransitionToPart(partImage);
874 // Reset our cache entry size so it doesn't keep growing without bound.
875 result.mShouldResetCacheEntry = true;
877 } else {
878 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
879 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
881 // Create an image using our progress tracker.
882 result.mImage = image::ImageFactory::CreateImage(
883 aRequest, aProgressTracker, result.mContentType, aURI,
884 /* aIsMultipart = */ false, aInnerWindowId);
887 MOZ_ASSERT(result.mImage);
888 if (!result.mImage->HasError() || aIsMultipart) {
889 // We allow multipart images to fail to initialize (which generally
890 // indicates a bad content type) without cancelling the load, because
891 // subsequent parts might be fine.
892 result.mSucceeded = true;
895 return result;
898 class FinishPreparingForNewPartRunnable final : public Runnable {
899 public:
900 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
901 NewPartResult&& aResult)
902 : Runnable("FinishPreparingForNewPartRunnable"),
903 mImgRequest(aImgRequest),
904 mResult(aResult) {
905 MOZ_ASSERT(aImgRequest);
908 NS_IMETHOD Run() override {
909 mImgRequest->FinishPreparingForNewPart(mResult);
910 return NS_OK;
913 private:
914 RefPtr<imgRequest> mImgRequest;
915 NewPartResult mResult;
918 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
919 MOZ_ASSERT(NS_IsMainThread());
921 mContentType = aResult.mContentType;
923 SetProperties(aResult.mContentType, aResult.mContentDisposition);
925 if (aResult.mIsFirstPart) {
926 // Notify listeners that we have an image.
927 mImageAvailable = true;
928 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
929 progressTracker->OnImageAvailable();
930 MOZ_ASSERT(progressTracker->HasImage());
933 if (aResult.mShouldResetCacheEntry) {
934 ResetCacheEntry();
937 if (IsDecodeRequested()) {
938 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
942 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
944 NS_IMETHODIMP
945 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
946 uint64_t aOffset, uint32_t aCount) {
947 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
949 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
951 RefPtr<Image> image;
952 RefPtr<ProgressTracker> progressTracker;
953 bool isMultipart = false;
954 bool newPartPending = false;
956 // Retrieve and update our state.
958 MutexAutoLock lock(mMutex);
959 image = mImage;
960 progressTracker = mProgressTracker;
961 isMultipart = mIsMultiPartChannel;
962 newPartPending = mNewPartPending;
963 mNewPartPending = false;
966 // If this is a new part, we need to sniff its content type and create an
967 // appropriate image.
968 if (newPartPending) {
969 NewPartResult result =
970 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
971 progressTracker, mInnerWindowId);
972 bool succeeded = result.mSucceeded;
974 if (result.mImage) {
975 image = result.mImage;
976 nsCOMPtr<nsIEventTarget> eventTarget;
978 // Update our state to reflect this new part.
980 MutexAutoLock lock(mMutex);
981 mImage = image;
983 // We only get an event target if we are not on the main thread, because
984 // we have to dispatch in that case. If we are on the main thread, but
985 // on a different scheduler group than ProgressTracker would give us,
986 // that is okay because nothing in imagelib requires that, just our
987 // listeners (which have their own checks).
988 if (!NS_IsMainThread()) {
989 eventTarget = mProgressTracker->GetEventTarget();
990 MOZ_ASSERT(eventTarget);
993 mProgressTracker = nullptr;
996 // Some property objects are not threadsafe, and we need to send
997 // OnImageAvailable on the main thread, so finish on the main thread.
998 if (!eventTarget) {
999 MOZ_ASSERT(NS_IsMainThread());
1000 FinishPreparingForNewPart(result);
1001 } else {
1002 nsCOMPtr<nsIRunnable> runnable =
1003 new FinishPreparingForNewPartRunnable(this, std::move(result));
1004 eventTarget->Dispatch(CreateMediumHighRunnable(runnable.forget()),
1005 NS_DISPATCH_NORMAL);
1009 if (!succeeded) {
1010 // Something went wrong; probably a content type issue.
1011 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1012 return NS_BINDING_ABORTED;
1016 // Notify the image that it has new data.
1017 if (aInStr) {
1018 nsresult rv =
1019 image->OnImageDataAvailable(aRequest, nullptr, aInStr, aOffset, aCount);
1021 if (NS_FAILED(rv)) {
1022 MOZ_LOG(gImgLog, LogLevel::Warning,
1023 ("[this=%p] imgRequest::OnDataAvailable -- "
1024 "copy to RasterImage failed\n",
1025 this));
1026 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1027 return NS_BINDING_ABORTED;
1031 return NS_OK;
1034 void imgRequest::SetProperties(const nsACString& aContentType,
1035 const nsACString& aContentDisposition) {
1036 /* set our mimetype as a property */
1037 nsCOMPtr<nsISupportsCString> contentType =
1038 do_CreateInstance("@mozilla.org/supports-cstring;1");
1039 if (contentType) {
1040 contentType->SetData(aContentType);
1041 mProperties->Set("type", contentType);
1044 /* set our content disposition as a property */
1045 if (!aContentDisposition.IsEmpty()) {
1046 nsCOMPtr<nsISupportsCString> contentDisposition =
1047 do_CreateInstance("@mozilla.org/supports-cstring;1");
1048 if (contentDisposition) {
1049 contentDisposition->SetData(aContentDisposition);
1050 mProperties->Set("content-disposition", contentDisposition);
1055 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1056 const char* fromRawSegment,
1057 uint32_t toOffset, uint32_t count,
1058 uint32_t* writeCount) {
1059 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1061 NS_ASSERTION(closure, "closure is null!");
1063 if (count > 0) {
1064 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1067 *writeCount = 0;
1068 return NS_ERROR_FAILURE;
1071 /** nsIInterfaceRequestor methods **/
1073 NS_IMETHODIMP
1074 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1075 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1076 return QueryInterface(aIID, aResult);
1079 NS_ASSERTION(
1080 mPrevChannelSink != this,
1081 "Infinite recursion - don't keep track of channel sinks that are us!");
1082 return mPrevChannelSink->GetInterface(aIID, aResult);
1085 /** nsIChannelEventSink methods **/
1086 NS_IMETHODIMP
1087 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1088 nsIChannel* newChannel, uint32_t flags,
1089 nsIAsyncVerifyRedirectCallback* callback) {
1090 NS_ASSERTION(mRequest && mChannel,
1091 "Got a channel redirect after we nulled out mRequest!");
1092 NS_ASSERTION(mChannel == oldChannel,
1093 "Got a channel redirect for an unknown channel!");
1094 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1096 SetCacheValidation(mCacheEntry, oldChannel);
1098 // Prepare for callback
1099 mRedirectCallback = callback;
1100 mNewRedirectChannel = newChannel;
1102 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1103 if (sink) {
1104 nsresult rv =
1105 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1106 if (NS_FAILED(rv)) {
1107 mRedirectCallback = nullptr;
1108 mNewRedirectChannel = nullptr;
1110 return rv;
1113 (void)OnRedirectVerifyCallback(NS_OK);
1114 return NS_OK;
1117 NS_IMETHODIMP
1118 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1119 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1120 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1122 if (NS_FAILED(result)) {
1123 mRedirectCallback->OnRedirectVerifyCallback(result);
1124 mRedirectCallback = nullptr;
1125 mNewRedirectChannel = nullptr;
1126 return NS_OK;
1129 mChannel = mNewRedirectChannel;
1130 mTimedChannel = do_QueryInterface(mChannel);
1131 mNewRedirectChannel = nullptr;
1133 if (LOG_TEST(LogLevel::Debug)) {
1134 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1135 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1138 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1139 // security code, which needs to know whether there is an insecure load at any
1140 // point in the redirect chain.
1141 bool schemeLocal = false;
1142 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1143 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1144 &schemeLocal)) ||
1145 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1146 !schemeLocal)) {
1147 MutexAutoLock lock(mMutex);
1149 // The csp directive upgrade-insecure-requests performs an internal redirect
1150 // to upgrade all requests from http to https before any data is fetched
1151 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1152 // internal redirect.
1153 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1154 bool upgradeInsecureRequests =
1155 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1156 loadInfo->GetBrowserUpgradeInsecureRequests()
1157 : false;
1158 if (!upgradeInsecureRequests) {
1159 mHadInsecureRedirect = true;
1163 // Update the final URI.
1164 mChannel->GetURI(getter_AddRefs(mFinalURI));
1166 if (LOG_TEST(LogLevel::Debug)) {
1167 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1168 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1171 // Make sure we have a protocol that returns data rather than opens an
1172 // external application, e.g. 'mailto:'.
1173 bool doesNotReturnData = false;
1174 nsresult rv = NS_URIChainHasFlags(
1175 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1176 &doesNotReturnData);
1178 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1179 rv = NS_ERROR_ABORT;
1182 if (NS_FAILED(rv)) {
1183 mRedirectCallback->OnRedirectVerifyCallback(rv);
1184 mRedirectCallback = nullptr;
1185 return NS_OK;
1188 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1189 mRedirectCallback = nullptr;
1190 return NS_OK;