Bug 1492664 - update funsize scripts to use TASKCLUSTER_ROOT_URL; r=sfraser
[gecko.git] / image / imgRequest.cpp
blob376656d712f7f882ae7f7785e653f1bf258b908d
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 "nsIDocument.h"
22 #include "nsIThreadRetargetableRequest.h"
23 #include "nsIInputStream.h"
24 #include "nsIMultiPartChannel.h"
25 #include "nsIHttpChannel.h"
26 #include "nsIApplicationCache.h"
27 #include "nsIApplicationCacheChannel.h"
28 #include "nsMimeTypes.h"
30 #include "nsIInterfaceRequestorUtils.h"
31 #include "nsISupportsPrimitives.h"
32 #include "nsIScriptSecurityManager.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(imgIRequest::CORS_NONE),
62 mReferrerPolicy(mozilla::net::RP_Unset),
63 mImageErrorCode(NS_OK),
64 mMutex("imgRequest"),
65 mProgressTracker(new ProgressTracker()),
66 mIsMultiPartChannel(false),
67 mIsInCache(false),
68 mDecodeRequested(false),
69 mNewPartPending(false),
70 mHadInsecureRedirect(false) {
71 LOG_FUNC(gImgLog, "imgRequest::imgRequest()");
74 imgRequest::~imgRequest() {
75 if (mLoader) {
76 mLoader->RemoveFromUncachedImages(this);
78 if (mURI) {
79 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::~imgRequest()", "keyuri", mURI);
80 } else
81 LOG_FUNC(gImgLog, "imgRequest::~imgRequest()");
84 nsresult imgRequest::Init(nsIURI* aURI, nsIURI* aFinalURI,
85 bool aHadInsecureRedirect, nsIRequest* aRequest,
86 nsIChannel* aChannel, imgCacheEntry* aCacheEntry,
87 nsISupports* aCX, nsIPrincipal* aTriggeringPrincipal,
88 int32_t aCORSMode, ReferrerPolicy aReferrerPolicy) {
89 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
91 LOG_FUNC(gImgLog, "imgRequest::Init");
93 MOZ_ASSERT(!mImage, "Multiple calls to init");
94 MOZ_ASSERT(aURI, "No uri");
95 MOZ_ASSERT(aFinalURI, "No final uri");
96 MOZ_ASSERT(aRequest, "No request");
97 MOZ_ASSERT(aChannel, "No channel");
99 mProperties = new nsProperties();
100 mURI = aURI;
101 mFinalURI = aFinalURI;
102 mRequest = aRequest;
103 mChannel = aChannel;
104 mTimedChannel = do_QueryInterface(mChannel);
105 mTriggeringPrincipal = aTriggeringPrincipal;
106 mCORSMode = aCORSMode;
107 mReferrerPolicy = aReferrerPolicy;
109 // If the original URI and the final URI are different, check whether the
110 // original URI is secure. We deliberately don't take the final URI into
111 // account, as it needs to be handled using more complicated rules than
112 // earlier elements of the redirect chain.
113 if (aURI != aFinalURI) {
114 bool isHttps = false;
115 bool isChrome = false;
116 bool schemeLocal = false;
117 if (NS_FAILED(aURI->SchemeIs("https", &isHttps)) ||
118 NS_FAILED(aURI->SchemeIs("chrome", &isChrome)) ||
119 NS_FAILED(NS_URIChainHasFlags(
120 aURI, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &schemeLocal)) ||
121 (!isHttps && !isChrome && !schemeLocal)) {
122 mHadInsecureRedirect = true;
126 // imgCacheValidator may have handled redirects before we were created, so we
127 // allow the caller to let us know if any redirects were insecure.
128 mHadInsecureRedirect = mHadInsecureRedirect || aHadInsecureRedirect;
130 mChannel->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink));
132 NS_ASSERTION(mPrevChannelSink != this,
133 "Initializing with a channel that already calls back to us!");
135 mChannel->SetNotificationCallbacks(this);
137 mCacheEntry = aCacheEntry;
138 mCacheEntry->UpdateLoadTime();
140 SetLoadId(aCX);
142 // Grab the inner window ID of the loading document, if possible.
143 nsCOMPtr<nsIDocument> doc = do_QueryInterface(aCX);
144 if (doc) {
145 mInnerWindowId = doc->InnerWindowID();
148 return NS_OK;
151 void imgRequest::ClearLoader() { mLoader = nullptr; }
153 already_AddRefed<ProgressTracker> imgRequest::GetProgressTracker() const {
154 MutexAutoLock lock(mMutex);
156 if (mImage) {
157 MOZ_ASSERT(!mProgressTracker,
158 "Should have given mProgressTracker to mImage");
159 return mImage->GetProgressTracker();
161 MOZ_ASSERT(mProgressTracker,
162 "Should have mProgressTracker until we create mImage");
163 RefPtr<ProgressTracker> progressTracker = mProgressTracker;
164 MOZ_ASSERT(progressTracker);
165 return progressTracker.forget();
168 void imgRequest::SetCacheEntry(imgCacheEntry* entry) { mCacheEntry = entry; }
170 bool imgRequest::HasCacheEntry() const { return mCacheEntry != nullptr; }
172 void imgRequest::ResetCacheEntry() {
173 if (HasCacheEntry()) {
174 mCacheEntry->SetDataSize(0);
178 void imgRequest::AddProxy(imgRequestProxy* proxy) {
179 MOZ_ASSERT(proxy, "null imgRequestProxy passed in");
180 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::AddProxy", "proxy", proxy);
182 if (!mFirstProxy) {
183 // Save a raw pointer to the first proxy we see, for use in the network
184 // priority logic.
185 mFirstProxy = proxy;
188 // If we're empty before adding, we have to tell the loader we now have
189 // proxies.
190 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
191 if (progressTracker->ObserverCount() == 0) {
192 MOZ_ASSERT(mURI, "Trying to SetHasProxies without key uri.");
193 if (mLoader) {
194 mLoader->SetHasProxies(this);
198 progressTracker->AddObserver(proxy);
201 nsresult imgRequest::RemoveProxy(imgRequestProxy* proxy, nsresult aStatus) {
202 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy", "proxy", proxy);
204 // This will remove our animation consumers, so after removing
205 // this proxy, we don't end up without proxies with observers, but still
206 // have animation consumers.
207 proxy->ClearAnimationConsumers();
209 // Let the status tracker do its thing before we potentially call Cancel()
210 // below, because Cancel() may result in OnStopRequest being called back
211 // before Cancel() returns, leaving the image in a different state then the
212 // one it was in at this point.
213 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
214 if (!progressTracker->RemoveObserver(proxy)) {
215 return NS_OK;
218 if (progressTracker->ObserverCount() == 0) {
219 // If we have no observers, there's nothing holding us alive. If we haven't
220 // been cancelled and thus removed from the cache, tell the image loader so
221 // we can be evicted from the cache.
222 if (mCacheEntry) {
223 MOZ_ASSERT(mURI, "Removing last observer without key uri.");
225 if (mLoader) {
226 mLoader->SetHasNoProxies(this, mCacheEntry);
228 } else {
229 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy no cache entry",
230 "uri", mURI);
233 /* If |aStatus| is a failure code, then cancel the load if it is still in
234 progress. Otherwise, let the load continue, keeping 'this' in the cache
235 with no observers. This way, if a proxy is destroyed without calling
236 cancel on it, it won't leak and won't leave a bad pointer in the observer
237 list.
239 if (!(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE) &&
240 NS_FAILED(aStatus)) {
241 LOG_MSG(gImgLog, "imgRequest::RemoveProxy",
242 "load in progress. canceling");
244 this->Cancel(NS_BINDING_ABORTED);
247 /* break the cycle from the cache entry. */
248 mCacheEntry = nullptr;
251 return NS_OK;
254 void imgRequest::CancelAndAbort(nsresult aStatus) {
255 LOG_SCOPE(gImgLog, "imgRequest::CancelAndAbort");
257 Cancel(aStatus);
259 // It's possible for the channel to fail to open after we've set our
260 // notification callbacks. In that case, make sure to break the cycle between
261 // the channel and us, because it won't.
262 if (mChannel) {
263 mChannel->SetNotificationCallbacks(mPrevChannelSink);
264 mPrevChannelSink = nullptr;
268 class imgRequestMainThreadCancel : public Runnable {
269 public:
270 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
271 : Runnable("imgRequestMainThreadCancel"),
272 mImgRequest(aImgRequest),
273 mStatus(aStatus) {
274 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
275 MOZ_ASSERT(aImgRequest);
278 NS_IMETHOD Run() override {
279 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
280 mImgRequest->ContinueCancel(mStatus);
281 return NS_OK;
284 private:
285 RefPtr<imgRequest> mImgRequest;
286 nsresult mStatus;
289 void imgRequest::Cancel(nsresult aStatus) {
290 /* The Cancel() method here should only be called by this class. */
291 LOG_SCOPE(gImgLog, "imgRequest::Cancel");
293 if (NS_IsMainThread()) {
294 ContinueCancel(aStatus);
295 } else {
296 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
297 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
298 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
299 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
303 void imgRequest::ContinueCancel(nsresult aStatus) {
304 MOZ_ASSERT(NS_IsMainThread());
306 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
307 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
309 RemoveFromCache();
311 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
312 mRequest->Cancel(aStatus);
316 class imgRequestMainThreadEvict : public Runnable {
317 public:
318 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
319 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
320 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
321 MOZ_ASSERT(aImgRequest);
324 NS_IMETHOD Run() override {
325 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
326 mImgRequest->ContinueEvict();
327 return NS_OK;
330 private:
331 RefPtr<imgRequest> mImgRequest;
334 // EvictFromCache() is written to allowed to get called from any thread
335 void imgRequest::EvictFromCache() {
336 /* The EvictFromCache() method here should only be called by this class. */
337 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
339 if (NS_IsMainThread()) {
340 ContinueEvict();
341 } else {
342 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
346 // Helper-method used by EvictFromCache()
347 void imgRequest::ContinueEvict() {
348 MOZ_ASSERT(NS_IsMainThread());
350 RemoveFromCache();
353 void imgRequest::StartDecoding() {
354 MutexAutoLock lock(mMutex);
355 mDecodeRequested = true;
358 bool imgRequest::IsDecodeRequested() const {
359 MutexAutoLock lock(mMutex);
360 return mDecodeRequested;
363 nsresult imgRequest::GetURI(nsIURI** aURI) {
364 MOZ_ASSERT(aURI);
366 LOG_FUNC(gImgLog, "imgRequest::GetURI");
368 if (mURI) {
369 *aURI = mURI;
370 NS_ADDREF(*aURI);
371 return NS_OK;
374 return NS_ERROR_FAILURE;
377 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
378 MOZ_ASSERT(aURI);
380 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
382 if (mFinalURI) {
383 *aURI = mFinalURI;
384 NS_ADDREF(*aURI);
385 return NS_OK;
388 return NS_ERROR_FAILURE;
391 bool imgRequest::IsScheme(const char* aScheme) const {
392 MOZ_ASSERT(aScheme);
393 bool isScheme = false;
394 if (NS_WARN_IF(NS_FAILED(mURI->SchemeIs(aScheme, &isScheme)))) {
395 return false;
397 return isScheme;
400 bool imgRequest::IsChrome() const { return IsScheme("chrome"); }
402 bool imgRequest::IsData() const { return IsScheme("data"); }
404 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
406 void imgRequest::RemoveFromCache() {
407 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
409 bool isInCache = false;
412 MutexAutoLock lock(mMutex);
413 isInCache = mIsInCache;
416 if (isInCache && mLoader) {
417 // mCacheEntry is nulled out when we have no more observers.
418 if (mCacheEntry) {
419 mLoader->RemoveFromCache(mCacheEntry);
420 } else {
421 mLoader->RemoveFromCache(mCacheKey);
425 mCacheEntry = nullptr;
428 bool imgRequest::HasConsumers() const {
429 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
430 return progressTracker && progressTracker->ObserverCount() > 0;
433 already_AddRefed<image::Image> imgRequest::GetImage() const {
434 MutexAutoLock lock(mMutex);
435 RefPtr<image::Image> image = mImage;
436 return image.forget();
439 int32_t imgRequest::Priority() const {
440 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
441 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
442 if (p) {
443 p->GetPriority(&priority);
445 return priority;
448 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
449 // only the first proxy is allowed to modify the priority of this image load.
451 // XXX(darin): this is probably not the most optimal algorithm as we may want
452 // to increase the priority of requests that have a lot of proxies. the key
453 // concern though is that image loads remain lower priority than other pieces
454 // of content such as link clicks, CSS, and JS.
456 if (!mFirstProxy || proxy != mFirstProxy) {
457 return;
460 AdjustPriorityInternal(delta);
463 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
464 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
465 if (p) {
466 p->AdjustPriority(aDelta);
470 void imgRequest::BoostPriority(uint32_t aCategory) {
471 if (!gfxPrefs::ImageLayoutNetworkPriority()) {
472 return;
475 uint32_t newRequestedCategory =
476 (mBoostCategoriesRequested & aCategory) ^ aCategory;
477 if (!newRequestedCategory) {
478 // priority boost for each category can only apply once.
479 return;
482 MOZ_LOG(gImgLog, LogLevel::Debug,
483 ("[this=%p] imgRequest::BoostPriority for category %x", this,
484 newRequestedCategory));
486 int32_t delta = 0;
488 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
489 --delta;
492 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
493 --delta;
496 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
497 delta += nsISupportsPriority::PRIORITY_HIGH;
500 AdjustPriorityInternal(delta);
501 mBoostCategoriesRequested |= newRequestedCategory;
504 void imgRequest::SetIsInCache(bool aInCache) {
505 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
506 aInCache);
507 MutexAutoLock lock(mMutex);
508 mIsInCache = aInCache;
511 void imgRequest::UpdateCacheEntrySize() {
512 if (!mCacheEntry) {
513 return;
516 RefPtr<Image> image = GetImage();
517 SizeOfState state(moz_malloc_size_of);
518 size_t size = image->SizeOfSourceWithComputedFallback(state);
519 mCacheEntry->SetDataSize(size);
522 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
523 nsIRequest* aRequest) {
524 /* get the expires info */
525 if (aCacheEntry) {
526 // Expiration time defaults to 0. We set the expiration time on our
527 // entry if it hasn't been set yet.
528 if (aCacheEntry->GetExpiryTime() == 0) {
529 uint32_t expiration = 0;
530 nsCOMPtr<nsICacheInfoChannel> cacheChannel(do_QueryInterface(aRequest));
531 if (cacheChannel) {
532 /* get the expiration time from the caching channel's token */
533 cacheChannel->GetCacheTokenExpirationTime(&expiration);
535 if (expiration == 0) {
536 // If the channel doesn't support caching, then ensure this expires the
537 // next time it is used.
538 expiration = imgCacheEntry::SecondsFromPRTime(PR_Now()) - 1;
540 aCacheEntry->SetExpiryTime(expiration);
543 // Determine whether the cache entry must be revalidated when we try to use
544 // it. Currently, only HTTP specifies this information...
545 nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
546 if (httpChannel) {
547 bool bMustRevalidate = false;
549 Unused << httpChannel->IsNoStoreResponse(&bMustRevalidate);
551 if (!bMustRevalidate) {
552 Unused << httpChannel->IsNoCacheResponse(&bMustRevalidate);
555 if (!bMustRevalidate) {
556 nsAutoCString cacheHeader;
558 Unused << httpChannel->GetResponseHeader(
559 NS_LITERAL_CSTRING("Cache-Control"), cacheHeader);
560 if (PL_strcasestr(cacheHeader.get(), "must-revalidate")) {
561 bMustRevalidate = true;
565 // Cache entries default to not needing to validate. We ensure that
566 // multiple calls to this function don't override an earlier decision to
567 // validate by making validation a one-way decision.
568 if (bMustRevalidate) {
569 aCacheEntry->SetMustValidate(bMustRevalidate);
575 namespace {
577 already_AddRefed<nsIApplicationCache> GetApplicationCache(
578 nsIRequest* aRequest) {
579 nsresult rv;
581 nsCOMPtr<nsIApplicationCacheChannel> appCacheChan =
582 do_QueryInterface(aRequest);
583 if (!appCacheChan) {
584 return nullptr;
587 bool fromAppCache;
588 rv = appCacheChan->GetLoadedFromApplicationCache(&fromAppCache);
589 NS_ENSURE_SUCCESS(rv, nullptr);
591 if (!fromAppCache) {
592 return nullptr;
595 nsCOMPtr<nsIApplicationCache> appCache;
596 rv = appCacheChan->GetApplicationCache(getter_AddRefs(appCache));
597 NS_ENSURE_SUCCESS(rv, nullptr);
599 return appCache.forget();
602 } // namespace
604 bool imgRequest::CacheChanged(nsIRequest* aNewRequest) {
605 nsCOMPtr<nsIApplicationCache> newAppCache = GetApplicationCache(aNewRequest);
607 // Application cache not involved at all or the same app cache involved
608 // in both of the loads (original and new).
609 if (newAppCache == mApplicationCache) {
610 return false;
613 // In a rare case it may happen that two objects still refer
614 // the same application cache version.
615 if (newAppCache && mApplicationCache) {
616 nsresult rv;
618 nsAutoCString oldAppCacheClientId, newAppCacheClientId;
619 rv = mApplicationCache->GetClientID(oldAppCacheClientId);
620 NS_ENSURE_SUCCESS(rv, true);
621 rv = newAppCache->GetClientID(newAppCacheClientId);
622 NS_ENSURE_SUCCESS(rv, true);
624 if (oldAppCacheClientId == newAppCacheClientId) {
625 return false;
629 // When we get here, app caches differ or app cache is involved
630 // just in one of the loads what we also consider as a change
631 // in a loading cache.
632 return true;
635 bool imgRequest::GetMultipart() const {
636 MutexAutoLock lock(mMutex);
637 return mIsMultiPartChannel;
640 bool imgRequest::HadInsecureRedirect() const {
641 MutexAutoLock lock(mMutex);
642 return mHadInsecureRedirect;
645 /** nsIRequestObserver methods **/
647 NS_IMETHODIMP
648 imgRequest::OnStartRequest(nsIRequest* aRequest, nsISupports* ctxt) {
649 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
651 RefPtr<Image> image;
653 // Figure out if we're multipart.
654 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
655 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
656 "Stopped being multipart?");
658 MutexAutoLock lock(mMutex);
659 mNewPartPending = true;
660 image = mImage;
661 mIsMultiPartChannel = bool(multiPartChannel);
664 // If we're not multipart, we shouldn't have an image yet.
665 if (image && !multiPartChannel) {
666 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
667 Cancel(NS_IMAGELIB_ERROR_FAILURE);
668 return NS_ERROR_FAILURE;
672 * If mRequest is null here, then we need to set it so that we'll be able to
673 * cancel it if our Cancel() method is called. Note that this can only
674 * happen for multipart channels. We could simply not null out mRequest for
675 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
676 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
678 if (!mRequest) {
679 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
680 nsCOMPtr<nsIChannel> baseChannel;
681 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
682 mRequest = baseChannel;
685 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
686 if (channel) {
687 /* Get our principal */
688 nsCOMPtr<nsIScriptSecurityManager> secMan =
689 nsContentUtils::GetSecurityManager();
690 if (secMan) {
691 nsresult rv = secMan->GetChannelResultPrincipal(
692 channel, getter_AddRefs(mPrincipal));
693 if (NS_FAILED(rv)) {
694 return rv;
699 SetCacheValidation(mCacheEntry, aRequest);
701 mApplicationCache = GetApplicationCache(aRequest);
703 // Shouldn't we be dead already if this gets hit?
704 // Probably multipart/x-mixed-replace...
705 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
706 if (progressTracker->ObserverCount() == 0) {
707 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
710 // Try to retarget OnDataAvailable to a decode thread. We must process data
711 // URIs synchronously as per the spec however.
712 if (!channel || IsData()) {
713 return NS_OK;
716 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
717 do_QueryInterface(aRequest);
718 if (retargetable) {
719 nsAutoCString mimeType;
720 nsresult rv = channel->GetContentType(mimeType);
721 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
722 // Retarget OnDataAvailable to the DecodePool's IO thread.
723 nsCOMPtr<nsIEventTarget> target =
724 DecodePool::Singleton()->GetIOEventTarget();
725 rv = retargetable->RetargetDeliveryTo(target);
727 MOZ_LOG(gImgLog, LogLevel::Warning,
728 ("[this=%p] imgRequest::OnStartRequest -- "
729 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
730 this, static_cast<uint32_t>(rv),
731 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
734 return NS_OK;
737 NS_IMETHODIMP
738 imgRequest::OnStopRequest(nsIRequest* aRequest, nsISupports* ctxt,
739 nsresult status) {
740 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
741 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
743 RefPtr<Image> image = GetImage();
745 RefPtr<imgRequest> strongThis = this;
747 if (mIsMultiPartChannel && mNewPartPending) {
748 OnDataAvailable(aRequest, ctxt, nullptr, 0, 0);
751 // XXXldb What if this is a non-last part of a multipart request?
752 // xxx before we release our reference to mRequest, lets
753 // save the last status that we saw so that the
754 // imgRequestProxy will have access to it.
755 if (mRequest) {
756 mRequest = nullptr; // we no longer need the request
759 // stop holding a ref to the channel, since we don't need it anymore
760 if (mChannel) {
761 mChannel->SetNotificationCallbacks(mPrevChannelSink);
762 mPrevChannelSink = nullptr;
763 mChannel = nullptr;
766 bool lastPart = true;
767 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
768 if (mpchan) {
769 mpchan->GetIsLastPart(&lastPart);
772 bool isPartial = false;
773 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
774 isPartial = true;
775 status = NS_OK; // fake happy face
778 // Tell the image that it has all of the source data. Note that this can
779 // trigger a failure, since the image might be waiting for more non-optional
780 // data and this is the point where we break the news that it's not coming.
781 if (image) {
782 nsresult rv = image->OnImageDataComplete(aRequest, ctxt, status, lastPart);
784 // If we got an error in the OnImageDataComplete() call, we don't want to
785 // proceed as if nothing bad happened. However, we also want to give
786 // precedence to failure status codes from necko, since presumably they're
787 // more meaningful.
788 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
789 status = rv;
793 // If the request went through, update the cache entry size. Otherwise,
794 // cancel the request, which removes us from the cache.
795 if (image && NS_SUCCEEDED(status) && !isPartial) {
796 // We update the cache entry size here because this is where we finish
797 // loading compressed source data, which is part of our size calculus.
798 UpdateCacheEntrySize();
800 } else if (isPartial) {
801 // Remove the partial image from the cache.
802 this->EvictFromCache();
804 } else {
805 mImageErrorCode = status;
807 // if the error isn't "just" a partial transfer
808 // stops animations, removes from cache
809 this->Cancel(status);
812 if (!image) {
813 // We have to fire the OnStopRequest notifications ourselves because there's
814 // no image capable of doing so.
815 Progress progress =
816 LoadCompleteProgress(lastPart, /* aError = */ false, status);
818 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
819 progressTracker->SyncNotifyProgress(progress);
822 mTimedChannel = nullptr;
823 return NS_OK;
826 struct mimetype_closure {
827 nsACString* newType;
830 /* prototype for these defined below */
831 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
832 const char* fromRawSegment,
833 uint32_t toOffset, uint32_t count,
834 uint32_t* writeCount);
836 /** nsThreadRetargetableStreamListener methods **/
837 NS_IMETHODIMP
838 imgRequest::CheckListenerChain() {
839 // TODO Might need more checking here.
840 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
841 return NS_OK;
844 /** nsIStreamListener methods **/
846 struct NewPartResult final {
847 explicit NewPartResult(image::Image* aExistingImage)
848 : mImage(aExistingImage),
849 mIsFirstPart(!aExistingImage),
850 mSucceeded(false),
851 mShouldResetCacheEntry(false) {}
853 nsAutoCString mContentType;
854 nsAutoCString mContentDisposition;
855 RefPtr<image::Image> mImage;
856 const bool mIsFirstPart;
857 bool mSucceeded;
858 bool mShouldResetCacheEntry;
861 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
862 nsIInputStream* aInStr, uint32_t aCount,
863 nsIURI* aURI, bool aIsMultipart,
864 image::Image* aExistingImage,
865 ProgressTracker* aProgressTracker,
866 uint32_t aInnerWindowId) {
867 NewPartResult result(aExistingImage);
869 if (aInStr) {
870 mimetype_closure closure;
871 closure.newType = &result.mContentType;
873 // Look at the first few bytes and see if we can tell what the data is from
874 // that since servers tend to lie. :(
875 uint32_t out;
876 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
879 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
880 if (result.mContentType.IsEmpty()) {
881 nsresult rv =
882 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
883 if (NS_FAILED(rv)) {
884 MOZ_LOG(gImgLog, LogLevel::Error,
885 ("imgRequest::PrepareForNewPart -- "
886 "Content type unavailable from the channel\n"));
887 if (!aIsMultipart) {
888 return result;
893 if (chan) {
894 chan->GetContentDispositionHeader(result.mContentDisposition);
897 MOZ_LOG(gImgLog, LogLevel::Debug,
898 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
899 result.mContentType.get()));
901 // XXX If server lied about mimetype and it's SVG, we may need to copy
902 // the data and dispatch back to the main thread, AND tell the channel to
903 // dispatch there in the future.
905 // Create the new image and give it ownership of our ProgressTracker.
906 if (aIsMultipart) {
907 // Create the ProgressTracker and image for this part.
908 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
909 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
910 aRequest, progressTracker, result.mContentType, aURI,
911 /* aIsMultipart = */ true, aInnerWindowId);
913 if (result.mIsFirstPart) {
914 // First part for a multipart channel. Create the MultipartImage wrapper.
915 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
916 aProgressTracker->SetIsMultipart();
917 result.mImage = image::ImageFactory::CreateMultipartImage(
918 partImage, aProgressTracker);
919 } else {
920 // Transition to the new part.
921 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
922 multipartImage->BeginTransitionToPart(partImage);
924 // Reset our cache entry size so it doesn't keep growing without bound.
925 result.mShouldResetCacheEntry = true;
927 } else {
928 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
929 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
931 // Create an image using our progress tracker.
932 result.mImage = image::ImageFactory::CreateImage(
933 aRequest, aProgressTracker, result.mContentType, aURI,
934 /* aIsMultipart = */ false, aInnerWindowId);
937 MOZ_ASSERT(result.mImage);
938 if (!result.mImage->HasError() || aIsMultipart) {
939 // We allow multipart images to fail to initialize (which generally
940 // indicates a bad content type) without cancelling the load, because
941 // subsequent parts might be fine.
942 result.mSucceeded = true;
945 return result;
948 class FinishPreparingForNewPartRunnable final : public Runnable {
949 public:
950 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
951 NewPartResult&& aResult)
952 : Runnable("FinishPreparingForNewPartRunnable"),
953 mImgRequest(aImgRequest),
954 mResult(aResult) {
955 MOZ_ASSERT(aImgRequest);
958 NS_IMETHOD Run() override {
959 mImgRequest->FinishPreparingForNewPart(mResult);
960 return NS_OK;
963 private:
964 RefPtr<imgRequest> mImgRequest;
965 NewPartResult mResult;
968 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
969 MOZ_ASSERT(NS_IsMainThread());
971 mContentType = aResult.mContentType;
973 SetProperties(aResult.mContentType, aResult.mContentDisposition);
975 if (aResult.mIsFirstPart) {
976 // Notify listeners that we have an image.
977 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
978 progressTracker->OnImageAvailable();
979 MOZ_ASSERT(progressTracker->HasImage());
982 if (aResult.mShouldResetCacheEntry) {
983 ResetCacheEntry();
986 if (IsDecodeRequested()) {
987 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
991 NS_IMETHODIMP
992 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsISupports* aContext,
993 nsIInputStream* aInStr, uint64_t aOffset,
994 uint32_t aCount) {
995 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
997 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
999 RefPtr<Image> image;
1000 RefPtr<ProgressTracker> progressTracker;
1001 bool isMultipart = false;
1002 bool newPartPending = false;
1004 // Retrieve and update our state.
1006 MutexAutoLock lock(mMutex);
1007 image = mImage;
1008 progressTracker = mProgressTracker;
1009 isMultipart = mIsMultiPartChannel;
1010 newPartPending = mNewPartPending;
1011 mNewPartPending = false;
1014 // If this is a new part, we need to sniff its content type and create an
1015 // appropriate image.
1016 if (newPartPending) {
1017 NewPartResult result =
1018 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
1019 progressTracker, mInnerWindowId);
1020 bool succeeded = result.mSucceeded;
1022 if (result.mImage) {
1023 image = result.mImage;
1024 nsCOMPtr<nsIEventTarget> eventTarget;
1026 // Update our state to reflect this new part.
1028 MutexAutoLock lock(mMutex);
1029 mImage = image;
1031 // We only get an event target if we are not on the main thread, because
1032 // we have to dispatch in that case. If we are on the main thread, but
1033 // on a different scheduler group than ProgressTracker would give us,
1034 // that is okay because nothing in imagelib requires that, just our
1035 // listeners (which have their own checks).
1036 if (!NS_IsMainThread()) {
1037 eventTarget = mProgressTracker->GetEventTarget();
1038 MOZ_ASSERT(eventTarget);
1041 mProgressTracker = nullptr;
1044 // Some property objects are not threadsafe, and we need to send
1045 // OnImageAvailable on the main thread, so finish on the main thread.
1046 if (!eventTarget) {
1047 MOZ_ASSERT(NS_IsMainThread());
1048 FinishPreparingForNewPart(result);
1049 } else {
1050 nsCOMPtr<nsIRunnable> runnable =
1051 new FinishPreparingForNewPartRunnable(this, std::move(result));
1052 eventTarget->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
1056 if (!succeeded) {
1057 // Something went wrong; probably a content type issue.
1058 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1059 return NS_BINDING_ABORTED;
1063 // Notify the image that it has new data.
1064 if (aInStr) {
1065 nsresult rv = image->OnImageDataAvailable(aRequest, aContext, aInStr,
1066 aOffset, aCount);
1068 if (NS_FAILED(rv)) {
1069 MOZ_LOG(gImgLog, LogLevel::Warning,
1070 ("[this=%p] imgRequest::OnDataAvailable -- "
1071 "copy to RasterImage failed\n",
1072 this));
1073 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1074 return NS_BINDING_ABORTED;
1078 return NS_OK;
1081 void imgRequest::SetProperties(const nsACString& aContentType,
1082 const nsACString& aContentDisposition) {
1083 /* set our mimetype as a property */
1084 nsCOMPtr<nsISupportsCString> contentType =
1085 do_CreateInstance("@mozilla.org/supports-cstring;1");
1086 if (contentType) {
1087 contentType->SetData(aContentType);
1088 mProperties->Set("type", contentType);
1091 /* set our content disposition as a property */
1092 if (!aContentDisposition.IsEmpty()) {
1093 nsCOMPtr<nsISupportsCString> contentDisposition =
1094 do_CreateInstance("@mozilla.org/supports-cstring;1");
1095 if (contentDisposition) {
1096 contentDisposition->SetData(aContentDisposition);
1097 mProperties->Set("content-disposition", contentDisposition);
1102 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1103 const char* fromRawSegment,
1104 uint32_t toOffset, uint32_t count,
1105 uint32_t* writeCount) {
1106 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1108 NS_ASSERTION(closure, "closure is null!");
1110 if (count > 0) {
1111 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1114 *writeCount = 0;
1115 return NS_ERROR_FAILURE;
1118 /** nsIInterfaceRequestor methods **/
1120 NS_IMETHODIMP
1121 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1122 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1123 return QueryInterface(aIID, aResult);
1126 NS_ASSERTION(
1127 mPrevChannelSink != this,
1128 "Infinite recursion - don't keep track of channel sinks that are us!");
1129 return mPrevChannelSink->GetInterface(aIID, aResult);
1132 /** nsIChannelEventSink methods **/
1133 NS_IMETHODIMP
1134 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1135 nsIChannel* newChannel, uint32_t flags,
1136 nsIAsyncVerifyRedirectCallback* callback) {
1137 NS_ASSERTION(mRequest && mChannel,
1138 "Got a channel redirect after we nulled out mRequest!");
1139 NS_ASSERTION(mChannel == oldChannel,
1140 "Got a channel redirect for an unknown channel!");
1141 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1143 SetCacheValidation(mCacheEntry, oldChannel);
1145 // Prepare for callback
1146 mRedirectCallback = callback;
1147 mNewRedirectChannel = newChannel;
1149 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1150 if (sink) {
1151 nsresult rv =
1152 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1153 if (NS_FAILED(rv)) {
1154 mRedirectCallback = nullptr;
1155 mNewRedirectChannel = nullptr;
1157 return rv;
1160 (void)OnRedirectVerifyCallback(NS_OK);
1161 return NS_OK;
1164 NS_IMETHODIMP
1165 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1166 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1167 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1169 if (NS_FAILED(result)) {
1170 mRedirectCallback->OnRedirectVerifyCallback(result);
1171 mRedirectCallback = nullptr;
1172 mNewRedirectChannel = nullptr;
1173 return NS_OK;
1176 mChannel = mNewRedirectChannel;
1177 mTimedChannel = do_QueryInterface(mChannel);
1178 mNewRedirectChannel = nullptr;
1180 if (LOG_TEST(LogLevel::Debug)) {
1181 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1182 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1185 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1186 // security code, which needs to know whether there is an insecure load at any
1187 // point in the redirect chain.
1188 bool isHttps = false;
1189 bool isChrome = false;
1190 bool schemeLocal = false;
1191 if (NS_FAILED(mFinalURI->SchemeIs("https", &isHttps)) ||
1192 NS_FAILED(mFinalURI->SchemeIs("chrome", &isChrome)) ||
1193 NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1194 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1195 &schemeLocal)) ||
1196 (!isHttps && !isChrome && !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->GetLoadInfo();
1204 bool upgradeInsecureRequests =
1205 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1206 loadInfo->GetBrowserUpgradeInsecureRequests()
1207 : false;
1208 if (!upgradeInsecureRequests) {
1209 mHadInsecureRedirect = true;
1213 // Update the final URI.
1214 mChannel->GetURI(getter_AddRefs(mFinalURI));
1216 if (LOG_TEST(LogLevel::Debug)) {
1217 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1218 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1221 // Make sure we have a protocol that returns data rather than opens an
1222 // external application, e.g. 'mailto:'.
1223 bool doesNotReturnData = false;
1224 nsresult rv = NS_URIChainHasFlags(
1225 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1226 &doesNotReturnData);
1228 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1229 rv = NS_ERROR_ABORT;
1232 if (NS_FAILED(rv)) {
1233 mRedirectCallback->OnRedirectVerifyCallback(rv);
1234 mRedirectCallback = nullptr;
1235 return NS_OK;
1238 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1239 mRedirectCallback = nullptr;
1240 return NS_OK;