Bug 1708422: part 9) Declare `mozInlineSpellChecker::ShouldSpellCheckNode` `static...
[gecko.git] / image / imgRequest.cpp
blob53095511c5a5dd25d22a79ebec6a8fb2b3f35cdb
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 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest);
549 // Expiration time defaults to 0. We set the expiration time on our entry if
550 // it hasn't been set yet.
551 if (!info.mExpirationTime) {
552 // If the channel doesn't support caching, then ensure this expires the
553 // next time it is used.
554 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
557 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
558 // Cache entries default to not needing to validate. We ensure that
559 // multiple calls to this function don't override an earlier decision to
560 // validate by making validation a one-way decision.
561 if (info.mMustRevalidate) {
562 aCacheEntry->SetMustValidate(info.mMustRevalidate);
566 bool imgRequest::GetMultipart() const {
567 MutexAutoLock lock(mMutex);
568 return mIsMultiPartChannel;
571 bool imgRequest::HadInsecureRedirect() const {
572 MutexAutoLock lock(mMutex);
573 return mHadInsecureRedirect;
576 /** nsIRequestObserver methods **/
578 NS_IMETHODIMP
579 imgRequest::OnStartRequest(nsIRequest* aRequest) {
580 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
582 RefPtr<Image> image;
584 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
585 nsresult rv;
586 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
587 mIsDeniedCrossSiteCORSRequest =
588 loadInfo->GetTainting() == LoadTainting::CORS &&
589 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
590 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
593 // Figure out if we're multipart.
594 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
596 MutexAutoLock lock(mMutex);
598 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
599 "Stopped being multipart?");
601 mNewPartPending = true;
602 image = mImage;
603 mIsMultiPartChannel = bool(multiPartChannel);
606 // If we're not multipart, we shouldn't have an image yet.
607 if (image && !multiPartChannel) {
608 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
609 Cancel(NS_IMAGELIB_ERROR_FAILURE);
610 return NS_ERROR_FAILURE;
614 * If mRequest is null here, then we need to set it so that we'll be able to
615 * cancel it if our Cancel() method is called. Note that this can only
616 * happen for multipart channels. We could simply not null out mRequest for
617 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
618 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
620 if (!mRequest) {
621 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
622 nsCOMPtr<nsIChannel> baseChannel;
623 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
624 mRequest = baseChannel;
627 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
628 if (channel) {
629 /* Get our principal */
630 nsCOMPtr<nsIScriptSecurityManager> secMan =
631 nsContentUtils::GetSecurityManager();
632 if (secMan) {
633 nsresult rv = secMan->GetChannelResultPrincipal(
634 channel, getter_AddRefs(mPrincipal));
635 if (NS_FAILED(rv)) {
636 return rv;
641 SetCacheValidation(mCacheEntry, aRequest);
643 // Shouldn't we be dead already if this gets hit?
644 // Probably multipart/x-mixed-replace...
645 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
646 if (progressTracker->ObserverCount() == 0) {
647 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
650 // Try to retarget OnDataAvailable to a decode thread. We must process data
651 // URIs synchronously as per the spec however.
652 if (!channel || IsData()) {
653 return NS_OK;
656 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
657 do_QueryInterface(aRequest);
658 if (retargetable) {
659 nsAutoCString mimeType;
660 nsresult rv = channel->GetContentType(mimeType);
661 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
662 // Retarget OnDataAvailable to the DecodePool's IO thread.
663 nsCOMPtr<nsIEventTarget> target =
664 DecodePool::Singleton()->GetIOEventTarget();
665 rv = retargetable->RetargetDeliveryTo(target);
667 MOZ_LOG(gImgLog, LogLevel::Warning,
668 ("[this=%p] imgRequest::OnStartRequest -- "
669 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
670 this, static_cast<uint32_t>(rv),
671 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
674 return NS_OK;
677 NS_IMETHODIMP
678 imgRequest::OnStopRequest(nsIRequest* aRequest, nsresult status) {
679 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
680 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
682 RefPtr<Image> image = GetImage();
684 RefPtr<imgRequest> strongThis = this;
686 if (mIsMultiPartChannel && mNewPartPending) {
687 OnDataAvailable(aRequest, nullptr, 0, 0);
690 // XXXldb What if this is a non-last part of a multipart request?
691 // xxx before we release our reference to mRequest, lets
692 // save the last status that we saw so that the
693 // imgRequestProxy will have access to it.
694 if (mRequest) {
695 mRequest = nullptr; // we no longer need the request
698 // stop holding a ref to the channel, since we don't need it anymore
699 if (mChannel) {
700 mChannel->SetNotificationCallbacks(mPrevChannelSink);
701 mPrevChannelSink = nullptr;
702 mChannel = nullptr;
705 bool lastPart = true;
706 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
707 if (mpchan) {
708 mpchan->GetIsLastPart(&lastPart);
711 bool isPartial = false;
712 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
713 isPartial = true;
714 status = NS_OK; // fake happy face
717 // Tell the image that it has all of the source data. Note that this can
718 // trigger a failure, since the image might be waiting for more non-optional
719 // data and this is the point where we break the news that it's not coming.
720 if (image) {
721 nsresult rv =
722 image->OnImageDataComplete(aRequest, nullptr, status, lastPart);
724 // If we got an error in the OnImageDataComplete() call, we don't want to
725 // proceed as if nothing bad happened. However, we also want to give
726 // precedence to failure status codes from necko, since presumably they're
727 // more meaningful.
728 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
729 status = rv;
733 // If the request went through, update the cache entry size. Otherwise,
734 // cancel the request, which removes us from the cache.
735 if (image && NS_SUCCEEDED(status) && !isPartial) {
736 // We update the cache entry size here because this is where we finish
737 // loading compressed source data, which is part of our size calculus.
738 UpdateCacheEntrySize();
740 } else if (isPartial) {
741 // Remove the partial image from the cache.
742 this->EvictFromCache();
744 } else {
745 mImageErrorCode = status;
747 // if the error isn't "just" a partial transfer
748 // stops animations, removes from cache
749 this->Cancel(status);
752 if (!image) {
753 // We have to fire the OnStopRequest notifications ourselves because there's
754 // no image capable of doing so.
755 Progress progress =
756 LoadCompleteProgress(lastPart, /* aError = */ false, status);
758 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
759 progressTracker->SyncNotifyProgress(progress);
762 mTimedChannel = nullptr;
763 return NS_OK;
766 struct mimetype_closure {
767 nsACString* newType;
770 /* prototype for these defined below */
771 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
772 const char* fromRawSegment,
773 uint32_t toOffset, uint32_t count,
774 uint32_t* writeCount);
776 /** nsThreadRetargetableStreamListener methods **/
777 NS_IMETHODIMP
778 imgRequest::CheckListenerChain() {
779 // TODO Might need more checking here.
780 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
781 return NS_OK;
784 /** nsIStreamListener methods **/
786 struct NewPartResult final {
787 explicit NewPartResult(image::Image* aExistingImage)
788 : mImage(aExistingImage),
789 mIsFirstPart(!aExistingImage),
790 mSucceeded(false),
791 mShouldResetCacheEntry(false) {}
793 nsAutoCString mContentType;
794 nsAutoCString mContentDisposition;
795 RefPtr<image::Image> mImage;
796 const bool mIsFirstPart;
797 bool mSucceeded;
798 bool mShouldResetCacheEntry;
801 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
802 nsIInputStream* aInStr, uint32_t aCount,
803 nsIURI* aURI, bool aIsMultipart,
804 image::Image* aExistingImage,
805 ProgressTracker* aProgressTracker,
806 uint32_t aInnerWindowId) {
807 NewPartResult result(aExistingImage);
809 if (aInStr) {
810 mimetype_closure closure;
811 closure.newType = &result.mContentType;
813 // Look at the first few bytes and see if we can tell what the data is from
814 // that since servers tend to lie. :(
815 uint32_t out;
816 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
819 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
820 if (result.mContentType.IsEmpty()) {
821 nsresult rv =
822 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
823 if (NS_FAILED(rv)) {
824 MOZ_LOG(gImgLog, LogLevel::Error,
825 ("imgRequest::PrepareForNewPart -- "
826 "Content type unavailable from the channel\n"));
827 if (!aIsMultipart) {
828 return result;
833 if (chan) {
834 chan->GetContentDispositionHeader(result.mContentDisposition);
837 MOZ_LOG(gImgLog, LogLevel::Debug,
838 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
839 result.mContentType.get()));
841 // XXX If server lied about mimetype and it's SVG, we may need to copy
842 // the data and dispatch back to the main thread, AND tell the channel to
843 // dispatch there in the future.
845 // Create the new image and give it ownership of our ProgressTracker.
846 if (aIsMultipart) {
847 // Create the ProgressTracker and image for this part.
848 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
849 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
850 aRequest, progressTracker, result.mContentType, aURI,
851 /* aIsMultipart = */ true, aInnerWindowId);
853 if (result.mIsFirstPart) {
854 // First part for a multipart channel. Create the MultipartImage wrapper.
855 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
856 aProgressTracker->SetIsMultipart();
857 result.mImage = image::ImageFactory::CreateMultipartImage(
858 partImage, aProgressTracker);
859 } else {
860 // Transition to the new part.
861 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
862 multipartImage->BeginTransitionToPart(partImage);
864 // Reset our cache entry size so it doesn't keep growing without bound.
865 result.mShouldResetCacheEntry = true;
867 } else {
868 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
869 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
871 // Create an image using our progress tracker.
872 result.mImage = image::ImageFactory::CreateImage(
873 aRequest, aProgressTracker, result.mContentType, aURI,
874 /* aIsMultipart = */ false, aInnerWindowId);
877 MOZ_ASSERT(result.mImage);
878 if (!result.mImage->HasError() || aIsMultipart) {
879 // We allow multipart images to fail to initialize (which generally
880 // indicates a bad content type) without cancelling the load, because
881 // subsequent parts might be fine.
882 result.mSucceeded = true;
885 return result;
888 class FinishPreparingForNewPartRunnable final : public Runnable {
889 public:
890 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
891 NewPartResult&& aResult)
892 : Runnable("FinishPreparingForNewPartRunnable"),
893 mImgRequest(aImgRequest),
894 mResult(aResult) {
895 MOZ_ASSERT(aImgRequest);
898 NS_IMETHOD Run() override {
899 mImgRequest->FinishPreparingForNewPart(mResult);
900 return NS_OK;
903 private:
904 RefPtr<imgRequest> mImgRequest;
905 NewPartResult mResult;
908 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
909 MOZ_ASSERT(NS_IsMainThread());
911 mContentType = aResult.mContentType;
913 SetProperties(aResult.mContentType, aResult.mContentDisposition);
915 if (aResult.mIsFirstPart) {
916 // Notify listeners that we have an image.
917 mImageAvailable = true;
918 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
919 progressTracker->OnImageAvailable();
920 MOZ_ASSERT(progressTracker->HasImage());
923 if (aResult.mShouldResetCacheEntry) {
924 ResetCacheEntry();
927 if (IsDecodeRequested()) {
928 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
932 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
934 NS_IMETHODIMP
935 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
936 uint64_t aOffset, uint32_t aCount) {
937 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
939 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
941 RefPtr<Image> image;
942 RefPtr<ProgressTracker> progressTracker;
943 bool isMultipart = false;
944 bool newPartPending = false;
946 // Retrieve and update our state.
948 MutexAutoLock lock(mMutex);
949 image = mImage;
950 progressTracker = mProgressTracker;
951 isMultipart = mIsMultiPartChannel;
952 newPartPending = mNewPartPending;
953 mNewPartPending = false;
956 // If this is a new part, we need to sniff its content type and create an
957 // appropriate image.
958 if (newPartPending) {
959 NewPartResult result =
960 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
961 progressTracker, mInnerWindowId);
962 bool succeeded = result.mSucceeded;
964 if (result.mImage) {
965 image = result.mImage;
966 nsCOMPtr<nsIEventTarget> eventTarget;
968 // Update our state to reflect this new part.
970 MutexAutoLock lock(mMutex);
971 mImage = image;
973 // We only get an event target if we are not on the main thread, because
974 // we have to dispatch in that case. If we are on the main thread, but
975 // on a different scheduler group than ProgressTracker would give us,
976 // that is okay because nothing in imagelib requires that, just our
977 // listeners (which have their own checks).
978 if (!NS_IsMainThread()) {
979 eventTarget = mProgressTracker->GetEventTarget();
980 MOZ_ASSERT(eventTarget);
983 mProgressTracker = nullptr;
986 // Some property objects are not threadsafe, and we need to send
987 // OnImageAvailable on the main thread, so finish on the main thread.
988 if (!eventTarget) {
989 MOZ_ASSERT(NS_IsMainThread());
990 FinishPreparingForNewPart(result);
991 } else {
992 nsCOMPtr<nsIRunnable> runnable =
993 new FinishPreparingForNewPartRunnable(this, std::move(result));
994 eventTarget->Dispatch(CreateMediumHighRunnable(runnable.forget()),
995 NS_DISPATCH_NORMAL);
999 if (!succeeded) {
1000 // Something went wrong; probably a content type issue.
1001 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1002 return NS_BINDING_ABORTED;
1006 // Notify the image that it has new data.
1007 if (aInStr) {
1008 nsresult rv =
1009 image->OnImageDataAvailable(aRequest, nullptr, aInStr, aOffset, aCount);
1011 if (NS_FAILED(rv)) {
1012 MOZ_LOG(gImgLog, LogLevel::Warning,
1013 ("[this=%p] imgRequest::OnDataAvailable -- "
1014 "copy to RasterImage failed\n",
1015 this));
1016 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1017 return NS_BINDING_ABORTED;
1021 return NS_OK;
1024 void imgRequest::SetProperties(const nsACString& aContentType,
1025 const nsACString& aContentDisposition) {
1026 /* set our mimetype as a property */
1027 nsCOMPtr<nsISupportsCString> contentType =
1028 do_CreateInstance("@mozilla.org/supports-cstring;1");
1029 if (contentType) {
1030 contentType->SetData(aContentType);
1031 mProperties->Set("type", contentType);
1034 /* set our content disposition as a property */
1035 if (!aContentDisposition.IsEmpty()) {
1036 nsCOMPtr<nsISupportsCString> contentDisposition =
1037 do_CreateInstance("@mozilla.org/supports-cstring;1");
1038 if (contentDisposition) {
1039 contentDisposition->SetData(aContentDisposition);
1040 mProperties->Set("content-disposition", contentDisposition);
1045 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1046 const char* fromRawSegment,
1047 uint32_t toOffset, uint32_t count,
1048 uint32_t* writeCount) {
1049 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1051 NS_ASSERTION(closure, "closure is null!");
1053 if (count > 0) {
1054 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1057 *writeCount = 0;
1058 return NS_ERROR_FAILURE;
1061 /** nsIInterfaceRequestor methods **/
1063 NS_IMETHODIMP
1064 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1065 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1066 return QueryInterface(aIID, aResult);
1069 NS_ASSERTION(
1070 mPrevChannelSink != this,
1071 "Infinite recursion - don't keep track of channel sinks that are us!");
1072 return mPrevChannelSink->GetInterface(aIID, aResult);
1075 /** nsIChannelEventSink methods **/
1076 NS_IMETHODIMP
1077 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1078 nsIChannel* newChannel, uint32_t flags,
1079 nsIAsyncVerifyRedirectCallback* callback) {
1080 NS_ASSERTION(mRequest && mChannel,
1081 "Got a channel redirect after we nulled out mRequest!");
1082 NS_ASSERTION(mChannel == oldChannel,
1083 "Got a channel redirect for an unknown channel!");
1084 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1086 SetCacheValidation(mCacheEntry, oldChannel);
1088 // Prepare for callback
1089 mRedirectCallback = callback;
1090 mNewRedirectChannel = newChannel;
1092 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1093 if (sink) {
1094 nsresult rv =
1095 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1096 if (NS_FAILED(rv)) {
1097 mRedirectCallback = nullptr;
1098 mNewRedirectChannel = nullptr;
1100 return rv;
1103 (void)OnRedirectVerifyCallback(NS_OK);
1104 return NS_OK;
1107 NS_IMETHODIMP
1108 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1109 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1110 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1112 if (NS_FAILED(result)) {
1113 mRedirectCallback->OnRedirectVerifyCallback(result);
1114 mRedirectCallback = nullptr;
1115 mNewRedirectChannel = nullptr;
1116 return NS_OK;
1119 mChannel = mNewRedirectChannel;
1120 mTimedChannel = do_QueryInterface(mChannel);
1121 mNewRedirectChannel = nullptr;
1123 if (LOG_TEST(LogLevel::Debug)) {
1124 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1125 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1128 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1129 // security code, which needs to know whether there is an insecure load at any
1130 // point in the redirect chain.
1131 bool schemeLocal = false;
1132 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1133 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1134 &schemeLocal)) ||
1135 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1136 !schemeLocal)) {
1137 MutexAutoLock lock(mMutex);
1139 // The csp directive upgrade-insecure-requests performs an internal redirect
1140 // to upgrade all requests from http to https before any data is fetched
1141 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1142 // internal redirect.
1143 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1144 bool upgradeInsecureRequests =
1145 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1146 loadInfo->GetBrowserUpgradeInsecureRequests()
1147 : false;
1148 if (!upgradeInsecureRequests) {
1149 mHadInsecureRedirect = true;
1153 // Update the final URI.
1154 mChannel->GetURI(getter_AddRefs(mFinalURI));
1156 if (LOG_TEST(LogLevel::Debug)) {
1157 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1158 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1161 // Make sure we have a protocol that returns data rather than opens an
1162 // external application, e.g. 'mailto:'.
1163 bool doesNotReturnData = false;
1164 nsresult rv = NS_URIChainHasFlags(
1165 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1166 &doesNotReturnData);
1168 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1169 rv = NS_ERROR_ABORT;
1172 if (NS_FAILED(rv)) {
1173 mRedirectCallback->OnRedirectVerifyCallback(rv);
1174 mRedirectCallback = nullptr;
1175 return NS_OK;
1178 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1179 mRedirectCallback = nullptr;
1180 return NS_OK;