Bug 1690340 - Part 5: Remove the menu separators from the developer tools menu. r...
[gecko.git] / image / imgRequest.cpp
blobf544169caa966508569df6352f295fa51432f6f6
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 "nsIApplicationCache.h"
28 #include "nsIApplicationCacheChannel.h"
29 #include "nsMimeTypes.h"
31 #include "nsIInterfaceRequestorUtils.h"
32 #include "nsISupportsPrimitives.h"
33 #include "nsIScriptSecurityManager.h"
34 #include "nsComponentManagerUtils.h"
35 #include "nsContentUtils.h"
37 #include "plstr.h" // PL_strcasestr(...)
38 #include "prtime.h" // for PR_Now
39 #include "nsNetUtil.h"
40 #include "nsIProtocolHandler.h"
41 #include "imgIRequest.h"
42 #include "nsProperties.h"
44 #include "mozilla/IntegerPrintfMacros.h"
45 #include "mozilla/SizeOfState.h"
47 using namespace mozilla;
48 using namespace mozilla::image;
50 #define LOG_TEST(level) (MOZ_LOG_TEST(gImgLog, (level)))
52 NS_IMPL_ISUPPORTS(imgRequest, nsIStreamListener, nsIRequestObserver,
53 nsIThreadRetargetableStreamListener, nsIChannelEventSink,
54 nsIInterfaceRequestor, nsIAsyncVerifyRedirectCallback)
56 imgRequest::imgRequest(imgLoader* aLoader, const ImageCacheKey& aCacheKey)
57 : mLoader(aLoader),
58 mCacheKey(aCacheKey),
59 mLoadId(nullptr),
60 mFirstProxy(nullptr),
61 mValidator(nullptr),
62 mInnerWindowId(0),
63 mCORSMode(imgIRequest::CORS_NONE),
64 mImageErrorCode(NS_OK),
65 mImageAvailable(false),
66 mIsDeniedCrossSiteCORSRequest(false),
67 mIsCrossSiteNoCORSRequest(false),
68 mMutex("imgRequest"),
69 mProgressTracker(new ProgressTracker()),
70 mIsMultiPartChannel(false),
71 mIsInCache(false),
72 mDecodeRequested(false),
73 mNewPartPending(false),
74 mHadInsecureRedirect(false) {
75 LOG_FUNC(gImgLog, "imgRequest::imgRequest()");
78 imgRequest::~imgRequest() {
79 if (mLoader) {
80 mLoader->RemoveFromUncachedImages(this);
82 if (mURI) {
83 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::~imgRequest()", "keyuri", mURI);
84 } else
85 LOG_FUNC(gImgLog, "imgRequest::~imgRequest()");
88 nsresult imgRequest::Init(nsIURI* aURI, nsIURI* aFinalURI,
89 bool aHadInsecureRedirect, nsIRequest* aRequest,
90 nsIChannel* aChannel, imgCacheEntry* aCacheEntry,
91 mozilla::dom::Document* aLoadingDocument,
92 nsIPrincipal* aTriggeringPrincipal, int32_t aCORSMode,
93 nsIReferrerInfo* aReferrerInfo) {
94 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
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 void imgRequest::CancelAndAbort(nsresult aStatus) {
279 LOG_SCOPE(gImgLog, "imgRequest::CancelAndAbort");
281 Cancel(aStatus);
283 // It's possible for the channel to fail to open after we've set our
284 // notification callbacks. In that case, make sure to break the cycle between
285 // the channel and us, because it won't.
286 if (mChannel) {
287 mChannel->SetNotificationCallbacks(mPrevChannelSink);
288 mPrevChannelSink = nullptr;
292 class imgRequestMainThreadCancel : public Runnable {
293 public:
294 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
295 : Runnable("imgRequestMainThreadCancel"),
296 mImgRequest(aImgRequest),
297 mStatus(aStatus) {
298 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
299 MOZ_ASSERT(aImgRequest);
302 NS_IMETHOD Run() override {
303 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
304 mImgRequest->ContinueCancel(mStatus);
305 return NS_OK;
308 private:
309 RefPtr<imgRequest> mImgRequest;
310 nsresult mStatus;
313 void imgRequest::Cancel(nsresult aStatus) {
314 /* The Cancel() method here should only be called by this class. */
315 LOG_SCOPE(gImgLog, "imgRequest::Cancel");
317 if (NS_IsMainThread()) {
318 ContinueCancel(aStatus);
319 } else {
320 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
321 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
322 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
323 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
327 void imgRequest::ContinueCancel(nsresult aStatus) {
328 MOZ_ASSERT(NS_IsMainThread());
330 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
331 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
333 RemoveFromCache();
335 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
336 mRequest->Cancel(aStatus);
340 class imgRequestMainThreadEvict : public Runnable {
341 public:
342 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
343 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
344 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
345 MOZ_ASSERT(aImgRequest);
348 NS_IMETHOD Run() override {
349 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
350 mImgRequest->ContinueEvict();
351 return NS_OK;
354 private:
355 RefPtr<imgRequest> mImgRequest;
358 // EvictFromCache() is written to allowed to get called from any thread
359 void imgRequest::EvictFromCache() {
360 /* The EvictFromCache() method here should only be called by this class. */
361 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
363 if (NS_IsMainThread()) {
364 ContinueEvict();
365 } else {
366 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
370 // Helper-method used by EvictFromCache()
371 void imgRequest::ContinueEvict() {
372 MOZ_ASSERT(NS_IsMainThread());
374 RemoveFromCache();
377 void imgRequest::StartDecoding() {
378 MutexAutoLock lock(mMutex);
379 mDecodeRequested = true;
382 bool imgRequest::IsDecodeRequested() const {
383 MutexAutoLock lock(mMutex);
384 return mDecodeRequested;
387 nsresult imgRequest::GetURI(nsIURI** aURI) {
388 MOZ_ASSERT(aURI);
390 LOG_FUNC(gImgLog, "imgRequest::GetURI");
392 if (mURI) {
393 *aURI = mURI;
394 NS_ADDREF(*aURI);
395 return NS_OK;
398 return NS_ERROR_FAILURE;
401 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
402 MOZ_ASSERT(aURI);
404 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
406 if (mFinalURI) {
407 *aURI = mFinalURI;
408 NS_ADDREF(*aURI);
409 return NS_OK;
412 return NS_ERROR_FAILURE;
415 bool imgRequest::IsChrome() const { return mURI->SchemeIs("chrome"); }
417 bool imgRequest::IsData() const { return mURI->SchemeIs("data"); }
419 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
421 void imgRequest::RemoveFromCache() {
422 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
424 bool isInCache = false;
427 MutexAutoLock lock(mMutex);
428 isInCache = mIsInCache;
431 if (isInCache && mLoader) {
432 // mCacheEntry is nulled out when we have no more observers.
433 if (mCacheEntry) {
434 mLoader->RemoveFromCache(mCacheEntry);
435 } else {
436 mLoader->RemoveFromCache(mCacheKey);
440 mCacheEntry = nullptr;
443 bool imgRequest::HasConsumers() const {
444 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
445 return progressTracker && progressTracker->ObserverCount() > 0;
448 already_AddRefed<image::Image> imgRequest::GetImage() const {
449 MutexAutoLock lock(mMutex);
450 RefPtr<image::Image> image = mImage;
451 return image.forget();
454 int32_t imgRequest::Priority() const {
455 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
456 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
457 if (p) {
458 p->GetPriority(&priority);
460 return priority;
463 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
464 // only the first proxy is allowed to modify the priority of this image load.
466 // XXX(darin): this is probably not the most optimal algorithm as we may want
467 // to increase the priority of requests that have a lot of proxies. the key
468 // concern though is that image loads remain lower priority than other pieces
469 // of content such as link clicks, CSS, and JS.
471 if (!mFirstProxy || proxy != mFirstProxy) {
472 return;
475 AdjustPriorityInternal(delta);
478 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
479 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
480 if (p) {
481 p->AdjustPriority(aDelta);
485 void imgRequest::BoostPriority(uint32_t aCategory) {
486 if (!StaticPrefs::image_layout_network_priority()) {
487 return;
490 uint32_t newRequestedCategory =
491 (mBoostCategoriesRequested & aCategory) ^ aCategory;
492 if (!newRequestedCategory) {
493 // priority boost for each category can only apply once.
494 return;
497 MOZ_LOG(gImgLog, LogLevel::Debug,
498 ("[this=%p] imgRequest::BoostPriority for category %x", this,
499 newRequestedCategory));
501 int32_t delta = 0;
503 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
504 --delta;
507 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
508 --delta;
511 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
512 --delta;
515 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
516 delta += nsISupportsPriority::PRIORITY_HIGH;
519 AdjustPriorityInternal(delta);
520 mBoostCategoriesRequested |= newRequestedCategory;
523 void imgRequest::SetIsInCache(bool aInCache) {
524 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
525 aInCache);
526 MutexAutoLock lock(mMutex);
527 mIsInCache = aInCache;
530 void imgRequest::UpdateCacheEntrySize() {
531 if (!mCacheEntry) {
532 return;
535 RefPtr<Image> image = GetImage();
536 SizeOfState state(moz_malloc_size_of);
537 size_t size = image->SizeOfSourceWithComputedFallback(state);
538 mCacheEntry->SetDataSize(size);
541 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
542 nsIRequest* aRequest) {
543 /* get the expires info */
544 if (!aCacheEntry || aCacheEntry->GetExpiryTime() != 0) {
545 return;
548 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest);
550 // Expiration time defaults to 0. We set the expiration time on our entry if
551 // it hasn't been set yet.
552 if (!info.mExpirationTime) {
553 // If the channel doesn't support caching, then ensure this expires the
554 // next time it is used.
555 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
558 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
559 // Cache entries default to not needing to validate. We ensure that
560 // multiple calls to this function don't override an earlier decision to
561 // validate by making validation a one-way decision.
562 if (info.mMustRevalidate) {
563 aCacheEntry->SetMustValidate(info.mMustRevalidate);
567 namespace {
569 already_AddRefed<nsIApplicationCache> GetApplicationCache(
570 nsIRequest* aRequest) {
571 nsresult rv;
573 nsCOMPtr<nsIApplicationCacheChannel> appCacheChan =
574 do_QueryInterface(aRequest);
575 if (!appCacheChan) {
576 return nullptr;
579 bool fromAppCache;
580 rv = appCacheChan->GetLoadedFromApplicationCache(&fromAppCache);
581 NS_ENSURE_SUCCESS(rv, nullptr);
583 if (!fromAppCache) {
584 return nullptr;
587 nsCOMPtr<nsIApplicationCache> appCache;
588 rv = appCacheChan->GetApplicationCache(getter_AddRefs(appCache));
589 NS_ENSURE_SUCCESS(rv, nullptr);
591 return appCache.forget();
594 } // namespace
596 bool imgRequest::CacheChanged(nsIRequest* aNewRequest) {
597 nsCOMPtr<nsIApplicationCache> newAppCache = GetApplicationCache(aNewRequest);
599 // Application cache not involved at all or the same app cache involved
600 // in both of the loads (original and new).
601 if (newAppCache == mApplicationCache) {
602 return false;
605 // In a rare case it may happen that two objects still refer
606 // the same application cache version.
607 if (newAppCache && mApplicationCache) {
608 nsresult rv;
610 nsAutoCString oldAppCacheClientId, newAppCacheClientId;
611 rv = mApplicationCache->GetClientID(oldAppCacheClientId);
612 NS_ENSURE_SUCCESS(rv, true);
613 rv = newAppCache->GetClientID(newAppCacheClientId);
614 NS_ENSURE_SUCCESS(rv, true);
616 if (oldAppCacheClientId == newAppCacheClientId) {
617 return false;
621 // When we get here, app caches differ or app cache is involved
622 // just in one of the loads what we also consider as a change
623 // in a loading cache.
624 return true;
627 bool imgRequest::GetMultipart() const {
628 MutexAutoLock lock(mMutex);
629 return mIsMultiPartChannel;
632 bool imgRequest::HadInsecureRedirect() const {
633 MutexAutoLock lock(mMutex);
634 return mHadInsecureRedirect;
637 /** nsIRequestObserver methods **/
639 NS_IMETHODIMP
640 imgRequest::OnStartRequest(nsIRequest* aRequest) {
641 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
643 RefPtr<Image> image;
645 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
646 nsresult rv;
647 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
648 mIsDeniedCrossSiteCORSRequest =
649 loadInfo->GetTainting() == LoadTainting::CORS &&
650 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
651 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
654 // Figure out if we're multipart.
655 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
657 MutexAutoLock lock(mMutex);
659 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
660 "Stopped being multipart?");
662 mNewPartPending = true;
663 image = mImage;
664 mIsMultiPartChannel = bool(multiPartChannel);
667 // If we're not multipart, we shouldn't have an image yet.
668 if (image && !multiPartChannel) {
669 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
670 Cancel(NS_IMAGELIB_ERROR_FAILURE);
671 return NS_ERROR_FAILURE;
675 * If mRequest is null here, then we need to set it so that we'll be able to
676 * cancel it if our Cancel() method is called. Note that this can only
677 * happen for multipart channels. We could simply not null out mRequest for
678 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
679 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
681 if (!mRequest) {
682 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
683 nsCOMPtr<nsIChannel> baseChannel;
684 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
685 mRequest = baseChannel;
688 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
689 if (channel) {
690 /* Get our principal */
691 nsCOMPtr<nsIScriptSecurityManager> secMan =
692 nsContentUtils::GetSecurityManager();
693 if (secMan) {
694 nsresult rv = secMan->GetChannelResultPrincipal(
695 channel, getter_AddRefs(mPrincipal));
696 if (NS_FAILED(rv)) {
697 return rv;
702 SetCacheValidation(mCacheEntry, aRequest);
704 mApplicationCache = GetApplicationCache(aRequest);
706 // Shouldn't we be dead already if this gets hit?
707 // Probably multipart/x-mixed-replace...
708 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
709 if (progressTracker->ObserverCount() == 0) {
710 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
713 // Try to retarget OnDataAvailable to a decode thread. We must process data
714 // URIs synchronously as per the spec however.
715 if (!channel || IsData()) {
716 return NS_OK;
719 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
720 do_QueryInterface(aRequest);
721 if (retargetable) {
722 nsAutoCString mimeType;
723 nsresult rv = channel->GetContentType(mimeType);
724 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
725 // Retarget OnDataAvailable to the DecodePool's IO thread.
726 nsCOMPtr<nsIEventTarget> target =
727 DecodePool::Singleton()->GetIOEventTarget();
728 rv = retargetable->RetargetDeliveryTo(target);
730 MOZ_LOG(gImgLog, LogLevel::Warning,
731 ("[this=%p] imgRequest::OnStartRequest -- "
732 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
733 this, static_cast<uint32_t>(rv),
734 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
737 return NS_OK;
740 NS_IMETHODIMP
741 imgRequest::OnStopRequest(nsIRequest* aRequest, nsresult status) {
742 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
743 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
745 RefPtr<Image> image = GetImage();
747 RefPtr<imgRequest> strongThis = this;
749 if (mIsMultiPartChannel && mNewPartPending) {
750 OnDataAvailable(aRequest, nullptr, 0, 0);
753 // XXXldb What if this is a non-last part of a multipart request?
754 // xxx before we release our reference to mRequest, lets
755 // save the last status that we saw so that the
756 // imgRequestProxy will have access to it.
757 if (mRequest) {
758 mRequest = nullptr; // we no longer need the request
761 // stop holding a ref to the channel, since we don't need it anymore
762 if (mChannel) {
763 mChannel->SetNotificationCallbacks(mPrevChannelSink);
764 mPrevChannelSink = nullptr;
765 mChannel = nullptr;
768 bool lastPart = true;
769 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
770 if (mpchan) {
771 mpchan->GetIsLastPart(&lastPart);
774 bool isPartial = false;
775 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
776 isPartial = true;
777 status = NS_OK; // fake happy face
780 // Tell the image that it has all of the source data. Note that this can
781 // trigger a failure, since the image might be waiting for more non-optional
782 // data and this is the point where we break the news that it's not coming.
783 if (image) {
784 nsresult rv =
785 image->OnImageDataComplete(aRequest, nullptr, status, lastPart);
787 // If we got an error in the OnImageDataComplete() call, we don't want to
788 // proceed as if nothing bad happened. However, we also want to give
789 // precedence to failure status codes from necko, since presumably they're
790 // more meaningful.
791 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
792 status = rv;
796 // If the request went through, update the cache entry size. Otherwise,
797 // cancel the request, which removes us from the cache.
798 if (image && NS_SUCCEEDED(status) && !isPartial) {
799 // We update the cache entry size here because this is where we finish
800 // loading compressed source data, which is part of our size calculus.
801 UpdateCacheEntrySize();
803 } else if (isPartial) {
804 // Remove the partial image from the cache.
805 this->EvictFromCache();
807 } else {
808 mImageErrorCode = status;
810 // if the error isn't "just" a partial transfer
811 // stops animations, removes from cache
812 this->Cancel(status);
815 if (!image) {
816 // We have to fire the OnStopRequest notifications ourselves because there's
817 // no image capable of doing so.
818 Progress progress =
819 LoadCompleteProgress(lastPart, /* aError = */ false, status);
821 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
822 progressTracker->SyncNotifyProgress(progress);
825 mTimedChannel = nullptr;
826 return NS_OK;
829 struct mimetype_closure {
830 nsACString* newType;
833 /* prototype for these defined below */
834 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
835 const char* fromRawSegment,
836 uint32_t toOffset, uint32_t count,
837 uint32_t* writeCount);
839 /** nsThreadRetargetableStreamListener methods **/
840 NS_IMETHODIMP
841 imgRequest::CheckListenerChain() {
842 // TODO Might need more checking here.
843 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
844 return NS_OK;
847 /** nsIStreamListener methods **/
849 struct NewPartResult final {
850 explicit NewPartResult(image::Image* aExistingImage)
851 : mImage(aExistingImage),
852 mIsFirstPart(!aExistingImage),
853 mSucceeded(false),
854 mShouldResetCacheEntry(false) {}
856 nsAutoCString mContentType;
857 nsAutoCString mContentDisposition;
858 RefPtr<image::Image> mImage;
859 const bool mIsFirstPart;
860 bool mSucceeded;
861 bool mShouldResetCacheEntry;
864 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
865 nsIInputStream* aInStr, uint32_t aCount,
866 nsIURI* aURI, bool aIsMultipart,
867 image::Image* aExistingImage,
868 ProgressTracker* aProgressTracker,
869 uint32_t aInnerWindowId) {
870 NewPartResult result(aExistingImage);
872 if (aInStr) {
873 mimetype_closure closure;
874 closure.newType = &result.mContentType;
876 // Look at the first few bytes and see if we can tell what the data is from
877 // that since servers tend to lie. :(
878 uint32_t out;
879 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
882 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
883 if (result.mContentType.IsEmpty()) {
884 nsresult rv =
885 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
886 if (NS_FAILED(rv)) {
887 MOZ_LOG(gImgLog, LogLevel::Error,
888 ("imgRequest::PrepareForNewPart -- "
889 "Content type unavailable from the channel\n"));
890 if (!aIsMultipart) {
891 return result;
896 if (chan) {
897 chan->GetContentDispositionHeader(result.mContentDisposition);
900 MOZ_LOG(gImgLog, LogLevel::Debug,
901 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
902 result.mContentType.get()));
904 // XXX If server lied about mimetype and it's SVG, we may need to copy
905 // the data and dispatch back to the main thread, AND tell the channel to
906 // dispatch there in the future.
908 // Create the new image and give it ownership of our ProgressTracker.
909 if (aIsMultipart) {
910 // Create the ProgressTracker and image for this part.
911 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
912 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
913 aRequest, progressTracker, result.mContentType, aURI,
914 /* aIsMultipart = */ true, aInnerWindowId);
916 if (result.mIsFirstPart) {
917 // First part for a multipart channel. Create the MultipartImage wrapper.
918 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
919 aProgressTracker->SetIsMultipart();
920 result.mImage = image::ImageFactory::CreateMultipartImage(
921 partImage, aProgressTracker);
922 } else {
923 // Transition to the new part.
924 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
925 multipartImage->BeginTransitionToPart(partImage);
927 // Reset our cache entry size so it doesn't keep growing without bound.
928 result.mShouldResetCacheEntry = true;
930 } else {
931 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
932 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
934 // Create an image using our progress tracker.
935 result.mImage = image::ImageFactory::CreateImage(
936 aRequest, aProgressTracker, result.mContentType, aURI,
937 /* aIsMultipart = */ false, aInnerWindowId);
940 MOZ_ASSERT(result.mImage);
941 if (!result.mImage->HasError() || aIsMultipart) {
942 // We allow multipart images to fail to initialize (which generally
943 // indicates a bad content type) without cancelling the load, because
944 // subsequent parts might be fine.
945 result.mSucceeded = true;
948 return result;
951 class FinishPreparingForNewPartRunnable final : public Runnable {
952 public:
953 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
954 NewPartResult&& aResult)
955 : Runnable("FinishPreparingForNewPartRunnable"),
956 mImgRequest(aImgRequest),
957 mResult(aResult) {
958 MOZ_ASSERT(aImgRequest);
961 NS_IMETHOD Run() override {
962 mImgRequest->FinishPreparingForNewPart(mResult);
963 return NS_OK;
966 private:
967 RefPtr<imgRequest> mImgRequest;
968 NewPartResult mResult;
971 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
972 MOZ_ASSERT(NS_IsMainThread());
974 mContentType = aResult.mContentType;
976 SetProperties(aResult.mContentType, aResult.mContentDisposition);
978 if (aResult.mIsFirstPart) {
979 // Notify listeners that we have an image.
980 mImageAvailable = true;
981 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
982 progressTracker->OnImageAvailable();
983 MOZ_ASSERT(progressTracker->HasImage());
986 if (aResult.mShouldResetCacheEntry) {
987 ResetCacheEntry();
990 if (IsDecodeRequested()) {
991 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
995 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
997 NS_IMETHODIMP
998 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
999 uint64_t aOffset, uint32_t aCount) {
1000 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
1002 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
1004 RefPtr<Image> image;
1005 RefPtr<ProgressTracker> progressTracker;
1006 bool isMultipart = false;
1007 bool newPartPending = false;
1009 // Retrieve and update our state.
1011 MutexAutoLock lock(mMutex);
1012 image = mImage;
1013 progressTracker = mProgressTracker;
1014 isMultipart = mIsMultiPartChannel;
1015 newPartPending = mNewPartPending;
1016 mNewPartPending = false;
1019 // If this is a new part, we need to sniff its content type and create an
1020 // appropriate image.
1021 if (newPartPending) {
1022 NewPartResult result =
1023 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
1024 progressTracker, mInnerWindowId);
1025 bool succeeded = result.mSucceeded;
1027 if (result.mImage) {
1028 image = result.mImage;
1029 nsCOMPtr<nsIEventTarget> eventTarget;
1031 // Update our state to reflect this new part.
1033 MutexAutoLock lock(mMutex);
1034 mImage = image;
1036 // We only get an event target if we are not on the main thread, because
1037 // we have to dispatch in that case. If we are on the main thread, but
1038 // on a different scheduler group than ProgressTracker would give us,
1039 // that is okay because nothing in imagelib requires that, just our
1040 // listeners (which have their own checks).
1041 if (!NS_IsMainThread()) {
1042 eventTarget = mProgressTracker->GetEventTarget();
1043 MOZ_ASSERT(eventTarget);
1046 mProgressTracker = nullptr;
1049 // Some property objects are not threadsafe, and we need to send
1050 // OnImageAvailable on the main thread, so finish on the main thread.
1051 if (!eventTarget) {
1052 MOZ_ASSERT(NS_IsMainThread());
1053 FinishPreparingForNewPart(result);
1054 } else {
1055 nsCOMPtr<nsIRunnable> runnable =
1056 new FinishPreparingForNewPartRunnable(this, std::move(result));
1057 eventTarget->Dispatch(CreateMediumHighRunnable(runnable.forget()),
1058 NS_DISPATCH_NORMAL);
1062 if (!succeeded) {
1063 // Something went wrong; probably a content type issue.
1064 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1065 return NS_BINDING_ABORTED;
1069 // Notify the image that it has new data.
1070 if (aInStr) {
1071 nsresult rv =
1072 image->OnImageDataAvailable(aRequest, nullptr, aInStr, aOffset, aCount);
1074 if (NS_FAILED(rv)) {
1075 MOZ_LOG(gImgLog, LogLevel::Warning,
1076 ("[this=%p] imgRequest::OnDataAvailable -- "
1077 "copy to RasterImage failed\n",
1078 this));
1079 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1080 return NS_BINDING_ABORTED;
1084 return NS_OK;
1087 void imgRequest::SetProperties(const nsACString& aContentType,
1088 const nsACString& aContentDisposition) {
1089 /* set our mimetype as a property */
1090 nsCOMPtr<nsISupportsCString> contentType =
1091 do_CreateInstance("@mozilla.org/supports-cstring;1");
1092 if (contentType) {
1093 contentType->SetData(aContentType);
1094 mProperties->Set("type", contentType);
1097 /* set our content disposition as a property */
1098 if (!aContentDisposition.IsEmpty()) {
1099 nsCOMPtr<nsISupportsCString> contentDisposition =
1100 do_CreateInstance("@mozilla.org/supports-cstring;1");
1101 if (contentDisposition) {
1102 contentDisposition->SetData(aContentDisposition);
1103 mProperties->Set("content-disposition", contentDisposition);
1108 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1109 const char* fromRawSegment,
1110 uint32_t toOffset, uint32_t count,
1111 uint32_t* writeCount) {
1112 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1114 NS_ASSERTION(closure, "closure is null!");
1116 if (count > 0) {
1117 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1120 *writeCount = 0;
1121 return NS_ERROR_FAILURE;
1124 /** nsIInterfaceRequestor methods **/
1126 NS_IMETHODIMP
1127 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1128 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1129 return QueryInterface(aIID, aResult);
1132 NS_ASSERTION(
1133 mPrevChannelSink != this,
1134 "Infinite recursion - don't keep track of channel sinks that are us!");
1135 return mPrevChannelSink->GetInterface(aIID, aResult);
1138 /** nsIChannelEventSink methods **/
1139 NS_IMETHODIMP
1140 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1141 nsIChannel* newChannel, uint32_t flags,
1142 nsIAsyncVerifyRedirectCallback* callback) {
1143 NS_ASSERTION(mRequest && mChannel,
1144 "Got a channel redirect after we nulled out mRequest!");
1145 NS_ASSERTION(mChannel == oldChannel,
1146 "Got a channel redirect for an unknown channel!");
1147 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1149 SetCacheValidation(mCacheEntry, oldChannel);
1151 // Prepare for callback
1152 mRedirectCallback = callback;
1153 mNewRedirectChannel = newChannel;
1155 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1156 if (sink) {
1157 nsresult rv =
1158 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1159 if (NS_FAILED(rv)) {
1160 mRedirectCallback = nullptr;
1161 mNewRedirectChannel = nullptr;
1163 return rv;
1166 (void)OnRedirectVerifyCallback(NS_OK);
1167 return NS_OK;
1170 NS_IMETHODIMP
1171 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1172 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1173 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1175 if (NS_FAILED(result)) {
1176 mRedirectCallback->OnRedirectVerifyCallback(result);
1177 mRedirectCallback = nullptr;
1178 mNewRedirectChannel = nullptr;
1179 return NS_OK;
1182 mChannel = mNewRedirectChannel;
1183 mTimedChannel = do_QueryInterface(mChannel);
1184 mNewRedirectChannel = nullptr;
1186 if (LOG_TEST(LogLevel::Debug)) {
1187 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1188 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1191 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1192 // security code, which needs to know whether there is an insecure load at any
1193 // point in the redirect chain.
1194 bool schemeLocal = false;
1195 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1196 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1197 &schemeLocal)) ||
1198 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1199 !schemeLocal)) {
1200 MutexAutoLock lock(mMutex);
1202 // The csp directive upgrade-insecure-requests performs an internal redirect
1203 // to upgrade all requests from http to https before any data is fetched
1204 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1205 // internal redirect.
1206 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1207 bool upgradeInsecureRequests =
1208 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1209 loadInfo->GetBrowserUpgradeInsecureRequests()
1210 : false;
1211 if (!upgradeInsecureRequests) {
1212 mHadInsecureRedirect = true;
1216 // Update the final URI.
1217 mChannel->GetURI(getter_AddRefs(mFinalURI));
1219 if (LOG_TEST(LogLevel::Debug)) {
1220 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1221 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1224 // Make sure we have a protocol that returns data rather than opens an
1225 // external application, e.g. 'mailto:'.
1226 bool doesNotReturnData = false;
1227 nsresult rv = NS_URIChainHasFlags(
1228 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1229 &doesNotReturnData);
1231 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1232 rv = NS_ERROR_ABORT;
1235 if (NS_FAILED(rv)) {
1236 mRedirectCallback->OnRedirectVerifyCallback(rv);
1237 mRedirectCallback = nullptr;
1238 return NS_OK;
1241 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1242 mRedirectCallback = nullptr;
1243 return NS_OK;