Bug 1754107: Release the memory allocated by calls to VTSessionCopyProperty. r=media...
[gecko.git] / image / imgRequest.cpp
blob9295391e3c3fc451978fd5e5cd4fab63dce03638
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!");
94 // Init() can only be called once, and that's before it can be used off
95 // mainthread
97 LOG_FUNC(gImgLog, "imgRequest::Init");
99 MOZ_ASSERT(!mImage, "Multiple calls to init");
100 MOZ_ASSERT(aURI, "No uri");
101 MOZ_ASSERT(aFinalURI, "No final uri");
102 MOZ_ASSERT(aRequest, "No request");
103 MOZ_ASSERT(aChannel, "No channel");
105 mProperties = new nsProperties();
106 mURI = aURI;
107 mFinalURI = aFinalURI;
108 mRequest = aRequest;
109 mChannel = aChannel;
110 mTimedChannel = do_QueryInterface(mChannel);
111 mTriggeringPrincipal = aTriggeringPrincipal;
112 mCORSMode = aCORSMode;
113 mReferrerInfo = aReferrerInfo;
115 // If the original URI and the final URI are different, check whether the
116 // original URI is secure. We deliberately don't take the final URI into
117 // account, as it needs to be handled using more complicated rules than
118 // earlier elements of the redirect chain.
119 if (aURI != aFinalURI) {
120 bool schemeLocal = false;
121 if (NS_FAILED(NS_URIChainHasFlags(
122 aURI, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &schemeLocal)) ||
123 (!aURI->SchemeIs("https") && !aURI->SchemeIs("chrome") &&
124 !schemeLocal)) {
125 mHadInsecureRedirect = true;
129 // imgCacheValidator may have handled redirects before we were created, so we
130 // allow the caller to let us know if any redirects were insecure.
131 mHadInsecureRedirect = mHadInsecureRedirect || aHadInsecureRedirect;
133 mChannel->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink));
135 NS_ASSERTION(mPrevChannelSink != this,
136 "Initializing with a channel that already calls back to us!");
138 mChannel->SetNotificationCallbacks(this);
140 mCacheEntry = aCacheEntry;
141 mCacheEntry->UpdateLoadTime();
143 SetLoadId(aLoadingDocument);
145 // Grab the inner window ID of the loading document, if possible.
146 if (aLoadingDocument) {
147 mInnerWindowId = aLoadingDocument->InnerWindowID();
150 return NS_OK;
153 bool imgRequest::CanReuseWithoutValidation(dom::Document* aDoc) const {
154 // If the request's loadId is the same as the aLoadingDocument, then it is ok
155 // to use this one because it has already been validated for this context.
156 // XXX: nullptr seems to be a 'special' key value that indicates that NO
157 // validation is required.
158 // XXX: we also check the window ID because the loadID() can return a reused
159 // pointer of a document. This can still happen for non-document image
160 // cache entries.
161 void* key = (void*)aDoc;
162 uint64_t innerWindowID = aDoc ? aDoc->InnerWindowID() : 0;
163 if (LoadId() == key && InnerWindowID() == innerWindowID) {
164 return true;
167 // As a special-case, if this is a print preview document, also validate on
168 // the original document. This allows to print uncacheable images.
169 if (dom::Document* original = aDoc ? aDoc->GetOriginalDocument() : nullptr) {
170 return CanReuseWithoutValidation(original);
173 return false;
176 void imgRequest::ClearLoader() { mLoader = nullptr; }
178 already_AddRefed<ProgressTracker> imgRequest::GetProgressTracker() const {
179 MutexAutoLock lock(mMutex);
181 if (mImage) {
182 MOZ_ASSERT(!mProgressTracker,
183 "Should have given mProgressTracker to mImage");
184 return mImage->GetProgressTracker();
186 MOZ_ASSERT(mProgressTracker,
187 "Should have mProgressTracker until we create mImage");
188 RefPtr<ProgressTracker> progressTracker = mProgressTracker;
189 MOZ_ASSERT(progressTracker);
190 return progressTracker.forget();
193 void imgRequest::SetCacheEntry(imgCacheEntry* entry) { mCacheEntry = entry; }
195 bool imgRequest::HasCacheEntry() const { return mCacheEntry != nullptr; }
197 void imgRequest::ResetCacheEntry() {
198 if (HasCacheEntry()) {
199 mCacheEntry->SetDataSize(0);
203 void imgRequest::AddProxy(imgRequestProxy* proxy) {
204 MOZ_ASSERT(proxy, "null imgRequestProxy passed in");
205 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::AddProxy", "proxy", proxy);
207 if (!mFirstProxy) {
208 // Save a raw pointer to the first proxy we see, for use in the network
209 // priority logic.
210 mFirstProxy = proxy;
213 // If we're empty before adding, we have to tell the loader we now have
214 // proxies.
215 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
216 if (progressTracker->ObserverCount() == 0) {
217 MOZ_ASSERT(mURI, "Trying to SetHasProxies without key uri.");
218 if (mLoader) {
219 mLoader->SetHasProxies(this);
223 progressTracker->AddObserver(proxy);
226 nsresult imgRequest::RemoveProxy(imgRequestProxy* proxy, nsresult aStatus) {
227 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy", "proxy", proxy);
229 // This will remove our animation consumers, so after removing
230 // this proxy, we don't end up without proxies with observers, but still
231 // have animation consumers.
232 proxy->ClearAnimationConsumers();
234 // Let the status tracker do its thing before we potentially call Cancel()
235 // below, because Cancel() may result in OnStopRequest being called back
236 // before Cancel() returns, leaving the image in a different state then the
237 // one it was in at this point.
238 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
239 if (!progressTracker->RemoveObserver(proxy)) {
240 return NS_OK;
243 if (progressTracker->ObserverCount() == 0) {
244 // If we have no observers, there's nothing holding us alive. If we haven't
245 // been cancelled and thus removed from the cache, tell the image loader so
246 // we can be evicted from the cache.
247 if (mCacheEntry) {
248 MOZ_ASSERT(mURI, "Removing last observer without key uri.");
250 if (mLoader) {
251 mLoader->SetHasNoProxies(this, mCacheEntry);
253 } else {
254 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy no cache entry",
255 "uri", mURI);
258 /* If |aStatus| is a failure code, then cancel the load if it is still in
259 progress. Otherwise, let the load continue, keeping 'this' in the cache
260 with no observers. This way, if a proxy is destroyed without calling
261 cancel on it, it won't leak and won't leave a bad pointer in the observer
262 list.
264 if (!(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE) &&
265 NS_FAILED(aStatus)) {
266 LOG_MSG(gImgLog, "imgRequest::RemoveProxy",
267 "load in progress. canceling");
269 this->Cancel(NS_BINDING_ABORTED);
272 /* break the cycle from the cache entry. */
273 mCacheEntry = nullptr;
276 return NS_OK;
279 void imgRequest::CancelAndAbort(nsresult aStatus) {
280 LOG_SCOPE(gImgLog, "imgRequest::CancelAndAbort");
282 Cancel(aStatus);
284 // It's possible for the channel to fail to open after we've set our
285 // notification callbacks. In that case, make sure to break the cycle between
286 // the channel and us, because it won't.
287 if (mChannel) {
288 mChannel->SetNotificationCallbacks(mPrevChannelSink);
289 mPrevChannelSink = nullptr;
293 class imgRequestMainThreadCancel : public Runnable {
294 public:
295 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
296 : Runnable("imgRequestMainThreadCancel"),
297 mImgRequest(aImgRequest),
298 mStatus(aStatus) {
299 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
300 MOZ_ASSERT(aImgRequest);
303 NS_IMETHOD Run() override {
304 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
305 mImgRequest->ContinueCancel(mStatus);
306 return NS_OK;
309 private:
310 RefPtr<imgRequest> mImgRequest;
311 nsresult mStatus;
314 void imgRequest::Cancel(nsresult aStatus) {
315 /* The Cancel() method here should only be called by this class. */
316 LOG_SCOPE(gImgLog, "imgRequest::Cancel");
318 if (NS_IsMainThread()) {
319 ContinueCancel(aStatus);
320 } else {
321 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
322 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
323 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
324 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
328 void imgRequest::ContinueCancel(nsresult aStatus) {
329 MOZ_ASSERT(NS_IsMainThread());
331 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
332 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
334 RemoveFromCache();
336 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
337 mRequest->Cancel(aStatus);
341 class imgRequestMainThreadEvict : public Runnable {
342 public:
343 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
344 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
345 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
346 MOZ_ASSERT(aImgRequest);
349 NS_IMETHOD Run() override {
350 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
351 mImgRequest->ContinueEvict();
352 return NS_OK;
355 private:
356 RefPtr<imgRequest> mImgRequest;
359 // EvictFromCache() is written to allowed to get called from any thread
360 void imgRequest::EvictFromCache() {
361 /* The EvictFromCache() method here should only be called by this class. */
362 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
364 if (NS_IsMainThread()) {
365 ContinueEvict();
366 } else {
367 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
371 // Helper-method used by EvictFromCache()
372 void imgRequest::ContinueEvict() {
373 MOZ_ASSERT(NS_IsMainThread());
375 RemoveFromCache();
378 void imgRequest::StartDecoding() {
379 MutexAutoLock lock(mMutex);
380 mDecodeRequested = true;
383 bool imgRequest::IsDecodeRequested() const {
384 MutexAutoLock lock(mMutex);
385 return mDecodeRequested;
388 nsresult imgRequest::GetURI(nsIURI** aURI) {
389 MOZ_ASSERT(aURI);
391 LOG_FUNC(gImgLog, "imgRequest::GetURI");
393 if (mURI) {
394 *aURI = mURI;
395 NS_ADDREF(*aURI);
396 return NS_OK;
399 return NS_ERROR_FAILURE;
402 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
403 MOZ_ASSERT(aURI);
405 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
407 if (mFinalURI) {
408 *aURI = mFinalURI;
409 NS_ADDREF(*aURI);
410 return NS_OK;
413 return NS_ERROR_FAILURE;
416 bool imgRequest::IsChrome() const { return mURI->SchemeIs("chrome"); }
418 bool imgRequest::IsData() const { return mURI->SchemeIs("data"); }
420 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
422 void imgRequest::RemoveFromCache() {
423 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
425 bool isInCache = false;
428 MutexAutoLock lock(mMutex);
429 isInCache = mIsInCache;
432 if (isInCache && mLoader) {
433 // mCacheEntry is nulled out when we have no more observers.
434 if (mCacheEntry) {
435 mLoader->RemoveFromCache(mCacheEntry);
436 } else {
437 mLoader->RemoveFromCache(mCacheKey);
441 mCacheEntry = nullptr;
444 bool imgRequest::HasConsumers() const {
445 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
446 return progressTracker && progressTracker->ObserverCount() > 0;
449 already_AddRefed<image::Image> imgRequest::GetImage() const {
450 MutexAutoLock lock(mMutex);
451 RefPtr<image::Image> image = mImage;
452 return image.forget();
455 int32_t imgRequest::Priority() const {
456 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
457 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
458 if (p) {
459 p->GetPriority(&priority);
461 return priority;
464 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
465 // only the first proxy is allowed to modify the priority of this image load.
467 // XXX(darin): this is probably not the most optimal algorithm as we may want
468 // to increase the priority of requests that have a lot of proxies. the key
469 // concern though is that image loads remain lower priority than other pieces
470 // of content such as link clicks, CSS, and JS.
472 if (!mFirstProxy || proxy != mFirstProxy) {
473 return;
476 AdjustPriorityInternal(delta);
479 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
480 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
481 if (p) {
482 p->AdjustPriority(aDelta);
486 void imgRequest::BoostPriority(uint32_t aCategory) {
487 if (!StaticPrefs::image_layout_network_priority()) {
488 return;
491 uint32_t newRequestedCategory =
492 (mBoostCategoriesRequested & aCategory) ^ aCategory;
493 if (!newRequestedCategory) {
494 // priority boost for each category can only apply once.
495 return;
498 MOZ_LOG(gImgLog, LogLevel::Debug,
499 ("[this=%p] imgRequest::BoostPriority for category %x", this,
500 newRequestedCategory));
502 int32_t delta = 0;
504 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
505 --delta;
508 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
509 --delta;
512 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
513 --delta;
516 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
517 delta += nsISupportsPriority::PRIORITY_HIGH;
520 AdjustPriorityInternal(delta);
521 mBoostCategoriesRequested |= newRequestedCategory;
524 void imgRequest::SetIsInCache(bool aInCache) {
525 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
526 aInCache);
527 MutexAutoLock lock(mMutex);
528 mIsInCache = aInCache;
531 void imgRequest::UpdateCacheEntrySize() {
532 if (!mCacheEntry) {
533 return;
536 RefPtr<Image> image = GetImage();
537 SizeOfState state(moz_malloc_size_of);
538 size_t size = image->SizeOfSourceWithComputedFallback(state);
539 mCacheEntry->SetDataSize(size);
542 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
543 nsIRequest* aRequest) {
544 /* get the expires info */
545 if (!aCacheEntry || aCacheEntry->GetExpiryTime() != 0) {
546 return;
549 RefPtr<imgRequest> req = aCacheEntry->GetRequest();
550 MOZ_ASSERT(req);
551 RefPtr<nsIURI> uri;
552 req->GetURI(getter_AddRefs(uri));
553 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
554 // get here in such cases sometimes (like for some redirects, see
555 // docshell/test/chrome/test_bug89419.xhtml).
557 // We have the original URI in the cache key though, probably we should be
558 // using that instead of relying on Init() getting called.
559 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest, uri);
561 // Expiration time defaults to 0. We set the expiration time on our entry if
562 // it hasn't been set yet.
563 if (!info.mExpirationTime) {
564 // If the channel doesn't support caching, then ensure this expires the
565 // next time it is used.
566 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
569 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
570 // Cache entries default to not needing to validate. We ensure that
571 // multiple calls to this function don't override an earlier decision to
572 // validate by making validation a one-way decision.
573 if (info.mMustRevalidate) {
574 aCacheEntry->SetMustValidate(info.mMustRevalidate);
578 bool imgRequest::GetMultipart() const {
579 MutexAutoLock lock(mMutex);
580 return mIsMultiPartChannel;
583 bool imgRequest::HadInsecureRedirect() const {
584 MutexAutoLock lock(mMutex);
585 return mHadInsecureRedirect;
588 /** nsIRequestObserver methods **/
590 NS_IMETHODIMP
591 imgRequest::OnStartRequest(nsIRequest* aRequest) {
592 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
594 RefPtr<Image> image;
596 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
597 nsresult rv;
598 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
599 mIsDeniedCrossSiteCORSRequest =
600 loadInfo->GetTainting() == LoadTainting::CORS &&
601 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
602 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
605 // Figure out if we're multipart.
606 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
608 MutexAutoLock lock(mMutex);
610 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
611 "Stopped being multipart?");
613 mNewPartPending = true;
614 image = mImage;
615 mIsMultiPartChannel = bool(multiPartChannel);
618 // If we're not multipart, we shouldn't have an image yet.
619 if (image && !multiPartChannel) {
620 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
621 Cancel(NS_IMAGELIB_ERROR_FAILURE);
622 return NS_ERROR_FAILURE;
626 * If mRequest is null here, then we need to set it so that we'll be able to
627 * cancel it if our Cancel() method is called. Note that this can only
628 * happen for multipart channels. We could simply not null out mRequest for
629 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
630 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
632 if (!mRequest) {
633 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
634 nsCOMPtr<nsIChannel> baseChannel;
635 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
636 mRequest = baseChannel;
639 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
640 if (channel) {
641 /* Get our principal */
642 nsCOMPtr<nsIScriptSecurityManager> secMan =
643 nsContentUtils::GetSecurityManager();
644 if (secMan) {
645 nsresult rv = secMan->GetChannelResultPrincipal(
646 channel, getter_AddRefs(mPrincipal));
647 if (NS_FAILED(rv)) {
648 return rv;
653 SetCacheValidation(mCacheEntry, aRequest);
655 // Shouldn't we be dead already if this gets hit?
656 // Probably multipart/x-mixed-replace...
657 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
658 if (progressTracker->ObserverCount() == 0) {
659 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
662 // Try to retarget OnDataAvailable to a decode thread. We must process data
663 // URIs synchronously as per the spec however.
664 if (!channel || IsData()) {
665 return NS_OK;
668 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
669 do_QueryInterface(aRequest);
670 if (retargetable) {
671 nsAutoCString mimeType;
672 nsresult rv = channel->GetContentType(mimeType);
673 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
674 // Retarget OnDataAvailable to the DecodePool's IO thread.
675 nsCOMPtr<nsIEventTarget> target =
676 DecodePool::Singleton()->GetIOEventTarget();
677 rv = retargetable->RetargetDeliveryTo(target);
679 MOZ_LOG(gImgLog, LogLevel::Warning,
680 ("[this=%p] imgRequest::OnStartRequest -- "
681 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
682 this, static_cast<uint32_t>(rv),
683 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
686 return NS_OK;
689 NS_IMETHODIMP
690 imgRequest::OnStopRequest(nsIRequest* aRequest, nsresult status) {
691 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
692 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
694 RefPtr<Image> image = GetImage();
696 RefPtr<imgRequest> strongThis = this;
698 bool isMultipart = false;
699 bool newPartPending = false;
701 MutexAutoLock lock(mMutex);
702 isMultipart = mIsMultiPartChannel;
703 newPartPending = mNewPartPending;
705 if (isMultipart && newPartPending) {
706 OnDataAvailable(aRequest, nullptr, 0, 0);
709 // XXXldb What if this is a non-last part of a multipart request?
710 // xxx before we release our reference to mRequest, lets
711 // save the last status that we saw so that the
712 // imgRequestProxy will have access to it.
713 if (mRequest) {
714 mRequest = nullptr; // we no longer need the request
717 // stop holding a ref to the channel, since we don't need it anymore
718 if (mChannel) {
719 mChannel->SetNotificationCallbacks(mPrevChannelSink);
720 mPrevChannelSink = nullptr;
721 mChannel = nullptr;
724 bool lastPart = true;
725 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
726 if (mpchan) {
727 mpchan->GetIsLastPart(&lastPart);
730 bool isPartial = false;
731 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
732 isPartial = true;
733 status = NS_OK; // fake happy face
736 // Tell the image that it has all of the source data. Note that this can
737 // trigger a failure, since the image might be waiting for more non-optional
738 // data and this is the point where we break the news that it's not coming.
739 if (image) {
740 nsresult rv = image->OnImageDataComplete(aRequest, status, lastPart);
742 // If we got an error in the OnImageDataComplete() call, we don't want to
743 // proceed as if nothing bad happened. However, we also want to give
744 // precedence to failure status codes from necko, since presumably they're
745 // more meaningful.
746 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
747 status = rv;
751 // If the request went through, update the cache entry size. Otherwise,
752 // cancel the request, which removes us from the cache.
753 if (image && NS_SUCCEEDED(status) && !isPartial) {
754 // We update the cache entry size here because this is where we finish
755 // loading compressed source data, which is part of our size calculus.
756 UpdateCacheEntrySize();
758 } else if (isPartial) {
759 // Remove the partial image from the cache.
760 this->EvictFromCache();
762 } else {
763 mImageErrorCode = status;
765 // if the error isn't "just" a partial transfer
766 // stops animations, removes from cache
767 this->Cancel(status);
770 if (!image) {
771 // We have to fire the OnStopRequest notifications ourselves because there's
772 // no image capable of doing so.
773 Progress progress =
774 LoadCompleteProgress(lastPart, /* aError = */ false, status);
776 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
777 progressTracker->SyncNotifyProgress(progress);
780 mTimedChannel = nullptr;
781 return NS_OK;
784 struct mimetype_closure {
785 nsACString* newType;
788 /* prototype for these defined below */
789 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
790 const char* fromRawSegment,
791 uint32_t toOffset, uint32_t count,
792 uint32_t* writeCount);
794 /** nsThreadRetargetableStreamListener methods **/
795 NS_IMETHODIMP
796 imgRequest::CheckListenerChain() {
797 // TODO Might need more checking here.
798 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
799 return NS_OK;
802 /** nsIStreamListener methods **/
804 struct NewPartResult final {
805 explicit NewPartResult(image::Image* aExistingImage)
806 : mImage(aExistingImage),
807 mIsFirstPart(!aExistingImage),
808 mSucceeded(false),
809 mShouldResetCacheEntry(false) {}
811 nsAutoCString mContentType;
812 nsAutoCString mContentDisposition;
813 RefPtr<image::Image> mImage;
814 const bool mIsFirstPart;
815 bool mSucceeded;
816 bool mShouldResetCacheEntry;
819 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
820 nsIInputStream* aInStr, uint32_t aCount,
821 nsIURI* aURI, bool aIsMultipart,
822 image::Image* aExistingImage,
823 ProgressTracker* aProgressTracker,
824 uint32_t aInnerWindowId) {
825 NewPartResult result(aExistingImage);
827 if (aInStr) {
828 mimetype_closure closure;
829 closure.newType = &result.mContentType;
831 // Look at the first few bytes and see if we can tell what the data is from
832 // that since servers tend to lie. :(
833 uint32_t out;
834 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
837 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
838 if (result.mContentType.IsEmpty()) {
839 nsresult rv =
840 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
841 if (NS_FAILED(rv)) {
842 MOZ_LOG(gImgLog, LogLevel::Error,
843 ("imgRequest::PrepareForNewPart -- "
844 "Content type unavailable from the channel\n"));
845 if (!aIsMultipart) {
846 return result;
851 if (chan) {
852 chan->GetContentDispositionHeader(result.mContentDisposition);
855 MOZ_LOG(gImgLog, LogLevel::Debug,
856 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
857 result.mContentType.get()));
859 // XXX If server lied about mimetype and it's SVG, we may need to copy
860 // the data and dispatch back to the main thread, AND tell the channel to
861 // dispatch there in the future.
863 // Create the new image and give it ownership of our ProgressTracker.
864 if (aIsMultipart) {
865 // Create the ProgressTracker and image for this part.
866 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
867 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
868 aRequest, progressTracker, result.mContentType, aURI,
869 /* aIsMultipart = */ true, aInnerWindowId);
871 if (result.mIsFirstPart) {
872 // First part for a multipart channel. Create the MultipartImage wrapper.
873 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
874 aProgressTracker->SetIsMultipart();
875 result.mImage = image::ImageFactory::CreateMultipartImage(
876 partImage, aProgressTracker);
877 } else {
878 // Transition to the new part.
879 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
880 multipartImage->BeginTransitionToPart(partImage);
882 // Reset our cache entry size so it doesn't keep growing without bound.
883 result.mShouldResetCacheEntry = true;
885 } else {
886 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
887 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
889 // Create an image using our progress tracker.
890 result.mImage = image::ImageFactory::CreateImage(
891 aRequest, aProgressTracker, result.mContentType, aURI,
892 /* aIsMultipart = */ false, aInnerWindowId);
895 MOZ_ASSERT(result.mImage);
896 if (!result.mImage->HasError() || aIsMultipart) {
897 // We allow multipart images to fail to initialize (which generally
898 // indicates a bad content type) without cancelling the load, because
899 // subsequent parts might be fine.
900 result.mSucceeded = true;
903 return result;
906 class FinishPreparingForNewPartRunnable final : public Runnable {
907 public:
908 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
909 NewPartResult&& aResult)
910 : Runnable("FinishPreparingForNewPartRunnable"),
911 mImgRequest(aImgRequest),
912 mResult(aResult) {
913 MOZ_ASSERT(aImgRequest);
916 NS_IMETHOD Run() override {
917 mImgRequest->FinishPreparingForNewPart(mResult);
918 return NS_OK;
921 private:
922 RefPtr<imgRequest> mImgRequest;
923 NewPartResult mResult;
926 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
927 MOZ_ASSERT(NS_IsMainThread());
929 mContentType = aResult.mContentType;
931 SetProperties(aResult.mContentType, aResult.mContentDisposition);
933 if (aResult.mIsFirstPart) {
934 // Notify listeners that we have an image.
935 mImageAvailable = true;
936 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
937 progressTracker->OnImageAvailable();
938 MOZ_ASSERT(progressTracker->HasImage());
941 if (aResult.mShouldResetCacheEntry) {
942 ResetCacheEntry();
945 if (IsDecodeRequested()) {
946 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
950 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
952 NS_IMETHODIMP
953 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
954 uint64_t aOffset, uint32_t aCount) {
955 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
957 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
959 RefPtr<Image> image;
960 RefPtr<ProgressTracker> progressTracker;
961 bool isMultipart = false;
962 bool newPartPending = false;
964 // Retrieve and update our state.
966 MutexAutoLock lock(mMutex);
967 image = mImage;
968 progressTracker = mProgressTracker;
969 isMultipart = mIsMultiPartChannel;
970 newPartPending = mNewPartPending;
971 mNewPartPending = false;
974 // If this is a new part, we need to sniff its content type and create an
975 // appropriate image.
976 if (newPartPending) {
977 NewPartResult result =
978 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
979 progressTracker, mInnerWindowId);
980 bool succeeded = result.mSucceeded;
982 if (result.mImage) {
983 image = result.mImage;
984 nsCOMPtr<nsIEventTarget> eventTarget;
986 // Update our state to reflect this new part.
988 MutexAutoLock lock(mMutex);
989 mImage = image;
991 // We only get an event target if we are not on the main thread, because
992 // we have to dispatch in that case. If we are on the main thread, but
993 // on a different scheduler group than ProgressTracker would give us,
994 // that is okay because nothing in imagelib requires that, just our
995 // listeners (which have their own checks).
996 if (!NS_IsMainThread()) {
997 eventTarget = mProgressTracker->GetEventTarget();
998 MOZ_ASSERT(eventTarget);
1001 mProgressTracker = nullptr;
1004 // Some property objects are not threadsafe, and we need to send
1005 // OnImageAvailable on the main thread, so finish on the main thread.
1006 if (!eventTarget) {
1007 MOZ_ASSERT(NS_IsMainThread());
1008 FinishPreparingForNewPart(result);
1009 } else {
1010 nsCOMPtr<nsIRunnable> runnable =
1011 new FinishPreparingForNewPartRunnable(this, std::move(result));
1012 eventTarget->Dispatch(CreateRenderBlockingRunnable(runnable.forget()),
1013 NS_DISPATCH_NORMAL);
1017 if (!succeeded) {
1018 // Something went wrong; probably a content type issue.
1019 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1020 return NS_BINDING_ABORTED;
1024 // Notify the image that it has new data.
1025 if (aInStr) {
1026 nsresult rv =
1027 image->OnImageDataAvailable(aRequest, aInStr, aOffset, aCount);
1029 if (NS_FAILED(rv)) {
1030 MOZ_LOG(gImgLog, LogLevel::Warning,
1031 ("[this=%p] imgRequest::OnDataAvailable -- "
1032 "copy to RasterImage failed\n",
1033 this));
1034 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1035 return NS_BINDING_ABORTED;
1039 return NS_OK;
1042 void imgRequest::SetProperties(const nsACString& aContentType,
1043 const nsACString& aContentDisposition) {
1044 /* set our mimetype as a property */
1045 nsCOMPtr<nsISupportsCString> contentType =
1046 do_CreateInstance("@mozilla.org/supports-cstring;1");
1047 if (contentType) {
1048 contentType->SetData(aContentType);
1049 mProperties->Set("type", contentType);
1052 /* set our content disposition as a property */
1053 if (!aContentDisposition.IsEmpty()) {
1054 nsCOMPtr<nsISupportsCString> contentDisposition =
1055 do_CreateInstance("@mozilla.org/supports-cstring;1");
1056 if (contentDisposition) {
1057 contentDisposition->SetData(aContentDisposition);
1058 mProperties->Set("content-disposition", contentDisposition);
1063 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1064 const char* fromRawSegment,
1065 uint32_t toOffset, uint32_t count,
1066 uint32_t* writeCount) {
1067 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1069 NS_ASSERTION(closure, "closure is null!");
1071 if (count > 0) {
1072 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1075 *writeCount = 0;
1076 return NS_ERROR_FAILURE;
1079 /** nsIInterfaceRequestor methods **/
1081 NS_IMETHODIMP
1082 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1083 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1084 return QueryInterface(aIID, aResult);
1087 NS_ASSERTION(
1088 mPrevChannelSink != this,
1089 "Infinite recursion - don't keep track of channel sinks that are us!");
1090 return mPrevChannelSink->GetInterface(aIID, aResult);
1093 /** nsIChannelEventSink methods **/
1094 NS_IMETHODIMP
1095 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1096 nsIChannel* newChannel, uint32_t flags,
1097 nsIAsyncVerifyRedirectCallback* callback) {
1098 NS_ASSERTION(mRequest && mChannel,
1099 "Got a channel redirect after we nulled out mRequest!");
1100 NS_ASSERTION(mChannel == oldChannel,
1101 "Got a channel redirect for an unknown channel!");
1102 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1104 SetCacheValidation(mCacheEntry, oldChannel);
1106 // Prepare for callback
1107 mRedirectCallback = callback;
1108 mNewRedirectChannel = newChannel;
1110 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1111 if (sink) {
1112 nsresult rv =
1113 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1114 if (NS_FAILED(rv)) {
1115 mRedirectCallback = nullptr;
1116 mNewRedirectChannel = nullptr;
1118 return rv;
1121 (void)OnRedirectVerifyCallback(NS_OK);
1122 return NS_OK;
1125 NS_IMETHODIMP
1126 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1127 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1128 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1130 if (NS_FAILED(result)) {
1131 mRedirectCallback->OnRedirectVerifyCallback(result);
1132 mRedirectCallback = nullptr;
1133 mNewRedirectChannel = nullptr;
1134 return NS_OK;
1137 mChannel = mNewRedirectChannel;
1138 mTimedChannel = do_QueryInterface(mChannel);
1139 mNewRedirectChannel = nullptr;
1141 if (LOG_TEST(LogLevel::Debug)) {
1142 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1143 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1146 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1147 // security code, which needs to know whether there is an insecure load at any
1148 // point in the redirect chain.
1149 bool schemeLocal = false;
1150 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1151 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1152 &schemeLocal)) ||
1153 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1154 !schemeLocal)) {
1155 MutexAutoLock lock(mMutex);
1157 // The csp directive upgrade-insecure-requests performs an internal redirect
1158 // to upgrade all requests from http to https before any data is fetched
1159 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1160 // internal redirect.
1161 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1162 bool upgradeInsecureRequests =
1163 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1164 loadInfo->GetBrowserUpgradeInsecureRequests()
1165 : false;
1166 if (!upgradeInsecureRequests) {
1167 mHadInsecureRedirect = true;
1171 // Update the final URI.
1172 mChannel->GetURI(getter_AddRefs(mFinalURI));
1174 if (LOG_TEST(LogLevel::Debug)) {
1175 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1176 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1179 // Make sure we have a protocol that returns data rather than opens an
1180 // external application, e.g. 'mailto:'.
1181 bool doesNotReturnData = false;
1182 nsresult rv = NS_URIChainHasFlags(
1183 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1184 &doesNotReturnData);
1186 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1187 rv = NS_ERROR_ABORT;
1190 if (NS_FAILED(rv)) {
1191 mRedirectCallback->OnRedirectVerifyCallback(rv);
1192 mRedirectCallback = nullptr;
1193 return NS_OK;
1196 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1197 mRedirectCallback = nullptr;
1198 return NS_OK;