Bug 1766413 [wpt PR 33787] - Fix some cases of "ref test" to be "reftest", a=testonly
[gecko.git] / image / imgRequest.cpp
blobfb80d42264f511716f0a05ba6d82f9659c91989e
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"
34 #include "nsEscape.h"
36 #include "plstr.h" // PL_strcasestr(...)
37 #include "prtime.h" // for PR_Now
38 #include "nsNetUtil.h"
39 #include "nsIProtocolHandler.h"
40 #include "imgIRequest.h"
41 #include "nsProperties.h"
42 #include "nsIURL.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 mCORSMode(CORS_NONE),
63 mImageErrorCode(NS_OK),
64 mImageAvailable(false),
65 mIsDeniedCrossSiteCORSRequest(false),
66 mIsCrossSiteNoCORSRequest(false),
67 mMutex("imgRequest"),
68 mProgressTracker(new ProgressTracker()),
69 mIsMultiPartChannel(false),
70 mIsInCache(false),
71 mDecodeRequested(false),
72 mNewPartPending(false),
73 mHadInsecureRedirect(false),
74 mInnerWindowId(0) {
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(
89 nsIURI* aURI, nsIURI* aFinalURI, bool aHadInsecureRedirect,
90 nsIRequest* aRequest, nsIChannel* aChannel, imgCacheEntry* aCacheEntry,
91 mozilla::dom::Document* aLoadingDocument,
92 nsIPrincipal* aTriggeringPrincipal, mozilla::CORSMode aCORSMode,
93 nsIReferrerInfo* aReferrerInfo) NO_THREAD_SAFETY_ANALYSIS {
94 MOZ_ASSERT(NS_IsMainThread(), "Cannot use nsIURI off main thread!");
95 // Init() can only be called once, and that's before it can be used off
96 // mainthread
98 LOG_FUNC(gImgLog, "imgRequest::Init");
100 MOZ_ASSERT(!mImage, "Multiple calls to init");
101 MOZ_ASSERT(aURI, "No uri");
102 MOZ_ASSERT(aFinalURI, "No final uri");
103 MOZ_ASSERT(aRequest, "No request");
104 MOZ_ASSERT(aChannel, "No channel");
106 mProperties = new nsProperties();
107 mURI = aURI;
108 mFinalURI = aFinalURI;
109 mRequest = aRequest;
110 mChannel = aChannel;
111 mTimedChannel = do_QueryInterface(mChannel);
112 mTriggeringPrincipal = aTriggeringPrincipal;
113 mCORSMode = aCORSMode;
114 mReferrerInfo = aReferrerInfo;
116 // If the original URI and the final URI are different, check whether the
117 // original URI is secure. We deliberately don't take the final URI into
118 // account, as it needs to be handled using more complicated rules than
119 // earlier elements of the redirect chain.
120 if (aURI != aFinalURI) {
121 bool schemeLocal = false;
122 if (NS_FAILED(NS_URIChainHasFlags(
123 aURI, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &schemeLocal)) ||
124 (!aURI->SchemeIs("https") && !aURI->SchemeIs("chrome") &&
125 !schemeLocal)) {
126 mHadInsecureRedirect = true;
130 // imgCacheValidator may have handled redirects before we were created, so we
131 // allow the caller to let us know if any redirects were insecure.
132 mHadInsecureRedirect = mHadInsecureRedirect || aHadInsecureRedirect;
134 mChannel->GetNotificationCallbacks(getter_AddRefs(mPrevChannelSink));
136 NS_ASSERTION(mPrevChannelSink != this,
137 "Initializing with a channel that already calls back to us!");
139 mChannel->SetNotificationCallbacks(this);
141 mCacheEntry = aCacheEntry;
142 mCacheEntry->UpdateLoadTime();
144 SetLoadId(aLoadingDocument);
146 // Grab the inner window ID of the loading document, if possible.
147 if (aLoadingDocument) {
148 mInnerWindowId = aLoadingDocument->InnerWindowID();
151 return NS_OK;
154 bool imgRequest::CanReuseWithoutValidation(dom::Document* aDoc) const {
155 // If the request's loadId is the same as the aLoadingDocument, then it is ok
156 // to use this one because it has already been validated for this context.
157 // XXX: nullptr seems to be a 'special' key value that indicates that NO
158 // validation is required.
159 // XXX: we also check the window ID because the loadID() can return a reused
160 // pointer of a document. This can still happen for non-document image
161 // cache entries.
162 void* key = (void*)aDoc;
163 uint64_t innerWindowID = aDoc ? aDoc->InnerWindowID() : 0;
164 if (LoadId() == key && InnerWindowID() == innerWindowID) {
165 return true;
168 // As a special-case, if this is a print preview document, also validate on
169 // the original document. This allows to print uncacheable images.
170 if (dom::Document* original = aDoc ? aDoc->GetOriginalDocument() : nullptr) {
171 return CanReuseWithoutValidation(original);
174 return false;
177 void imgRequest::ClearLoader() { mLoader = nullptr; }
179 already_AddRefed<ProgressTracker> imgRequest::GetProgressTracker() const {
180 MutexAutoLock lock(mMutex);
182 if (mImage) {
183 MOZ_ASSERT(!mProgressTracker,
184 "Should have given mProgressTracker to mImage");
185 return mImage->GetProgressTracker();
187 MOZ_ASSERT(mProgressTracker,
188 "Should have mProgressTracker until we create mImage");
189 RefPtr<ProgressTracker> progressTracker = mProgressTracker;
190 MOZ_ASSERT(progressTracker);
191 return progressTracker.forget();
194 void imgRequest::SetCacheEntry(imgCacheEntry* entry) { mCacheEntry = entry; }
196 bool imgRequest::HasCacheEntry() const { return mCacheEntry != nullptr; }
198 void imgRequest::ResetCacheEntry() {
199 if (HasCacheEntry()) {
200 mCacheEntry->SetDataSize(0);
204 void imgRequest::AddProxy(imgRequestProxy* proxy) {
205 MOZ_ASSERT(proxy, "null imgRequestProxy passed in");
206 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::AddProxy", "proxy", proxy);
208 if (!mFirstProxy) {
209 // Save a raw pointer to the first proxy we see, for use in the network
210 // priority logic.
211 mFirstProxy = proxy;
214 // If we're empty before adding, we have to tell the loader we now have
215 // proxies.
216 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
217 if (progressTracker->ObserverCount() == 0) {
218 MOZ_ASSERT(mURI, "Trying to SetHasProxies without key uri.");
219 if (mLoader) {
220 mLoader->SetHasProxies(this);
224 progressTracker->AddObserver(proxy);
227 nsresult imgRequest::RemoveProxy(imgRequestProxy* proxy, nsresult aStatus) {
228 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy", "proxy", proxy);
230 // This will remove our animation consumers, so after removing
231 // this proxy, we don't end up without proxies with observers, but still
232 // have animation consumers.
233 proxy->ClearAnimationConsumers();
235 // Let the status tracker do its thing before we potentially call Cancel()
236 // below, because Cancel() may result in OnStopRequest being called back
237 // before Cancel() returns, leaving the image in a different state then the
238 // one it was in at this point.
239 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
240 if (!progressTracker->RemoveObserver(proxy)) {
241 return NS_OK;
244 if (progressTracker->ObserverCount() == 0) {
245 // If we have no observers, there's nothing holding us alive. If we haven't
246 // been cancelled and thus removed from the cache, tell the image loader so
247 // we can be evicted from the cache.
248 if (mCacheEntry) {
249 MOZ_ASSERT(mURI, "Removing last observer without key uri.");
251 if (mLoader) {
252 mLoader->SetHasNoProxies(this, mCacheEntry);
254 } else {
255 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::RemoveProxy no cache entry",
256 "uri", mURI);
259 /* If |aStatus| is a failure code, then cancel the load if it is still in
260 progress. Otherwise, let the load continue, keeping 'this' in the cache
261 with no observers. This way, if a proxy is destroyed without calling
262 cancel on it, it won't leak and won't leave a bad pointer in the observer
263 list.
265 if (!(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE) &&
266 NS_FAILED(aStatus)) {
267 LOG_MSG(gImgLog, "imgRequest::RemoveProxy",
268 "load in progress. canceling");
270 this->Cancel(NS_BINDING_ABORTED);
273 /* break the cycle from the cache entry. */
274 mCacheEntry = nullptr;
277 return NS_OK;
280 uint64_t imgRequest::InnerWindowID() const {
281 MutexAutoLock lock(mMutex);
282 return mInnerWindowId;
285 void imgRequest::SetInnerWindowID(uint64_t aInnerWindowId) {
286 MutexAutoLock lock(mMutex);
287 mInnerWindowId = aInnerWindowId;
290 void imgRequest::CancelAndAbort(nsresult aStatus) {
291 LOG_SCOPE(gImgLog, "imgRequest::CancelAndAbort");
293 Cancel(aStatus);
295 // It's possible for the channel to fail to open after we've set our
296 // notification callbacks. In that case, make sure to break the cycle between
297 // the channel and us, because it won't.
298 if (mChannel) {
299 mChannel->SetNotificationCallbacks(mPrevChannelSink);
300 mPrevChannelSink = nullptr;
304 class imgRequestMainThreadCancel : public Runnable {
305 public:
306 imgRequestMainThreadCancel(imgRequest* aImgRequest, nsresult aStatus)
307 : Runnable("imgRequestMainThreadCancel"),
308 mImgRequest(aImgRequest),
309 mStatus(aStatus) {
310 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
311 MOZ_ASSERT(aImgRequest);
314 NS_IMETHOD Run() override {
315 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
316 mImgRequest->ContinueCancel(mStatus);
317 return NS_OK;
320 private:
321 RefPtr<imgRequest> mImgRequest;
322 nsresult mStatus;
325 void imgRequest::Cancel(nsresult aStatus) {
326 /* The Cancel() method here should only be called by this class. */
327 LOG_SCOPE(gImgLog, "imgRequest::Cancel");
329 if (NS_IsMainThread()) {
330 ContinueCancel(aStatus);
331 } else {
332 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
333 nsCOMPtr<nsIEventTarget> eventTarget = progressTracker->GetEventTarget();
334 nsCOMPtr<nsIRunnable> ev = new imgRequestMainThreadCancel(this, aStatus);
335 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
339 void imgRequest::ContinueCancel(nsresult aStatus) {
340 MOZ_ASSERT(NS_IsMainThread());
342 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
343 progressTracker->SyncNotifyProgress(FLAG_HAS_ERROR);
345 RemoveFromCache();
347 if (mRequest && !(progressTracker->GetProgress() & FLAG_LAST_PART_COMPLETE)) {
348 mRequest->Cancel(aStatus);
352 class imgRequestMainThreadEvict : public Runnable {
353 public:
354 explicit imgRequestMainThreadEvict(imgRequest* aImgRequest)
355 : Runnable("imgRequestMainThreadEvict"), mImgRequest(aImgRequest) {
356 MOZ_ASSERT(!NS_IsMainThread(), "Create me off main thread only!");
357 MOZ_ASSERT(aImgRequest);
360 NS_IMETHOD Run() override {
361 MOZ_ASSERT(NS_IsMainThread(), "I should be running on the main thread!");
362 mImgRequest->ContinueEvict();
363 return NS_OK;
366 private:
367 RefPtr<imgRequest> mImgRequest;
370 // EvictFromCache() is written to allowed to get called from any thread
371 void imgRequest::EvictFromCache() {
372 /* The EvictFromCache() method here should only be called by this class. */
373 LOG_SCOPE(gImgLog, "imgRequest::EvictFromCache");
375 if (NS_IsMainThread()) {
376 ContinueEvict();
377 } else {
378 NS_DispatchToMainThread(new imgRequestMainThreadEvict(this));
382 // Helper-method used by EvictFromCache()
383 void imgRequest::ContinueEvict() {
384 MOZ_ASSERT(NS_IsMainThread());
386 RemoveFromCache();
389 void imgRequest::StartDecoding() {
390 MutexAutoLock lock(mMutex);
391 mDecodeRequested = true;
394 bool imgRequest::IsDecodeRequested() const {
395 MutexAutoLock lock(mMutex);
396 return mDecodeRequested;
399 nsresult imgRequest::GetURI(nsIURI** aURI) {
400 MOZ_ASSERT(aURI);
402 LOG_FUNC(gImgLog, "imgRequest::GetURI");
404 if (mURI) {
405 *aURI = mURI;
406 NS_ADDREF(*aURI);
407 return NS_OK;
410 return NS_ERROR_FAILURE;
413 nsresult imgRequest::GetFinalURI(nsIURI** aURI) {
414 MOZ_ASSERT(aURI);
416 LOG_FUNC(gImgLog, "imgRequest::GetFinalURI");
418 if (mFinalURI) {
419 *aURI = mFinalURI;
420 NS_ADDREF(*aURI);
421 return NS_OK;
424 return NS_ERROR_FAILURE;
427 bool imgRequest::IsChrome() const { return mURI->SchemeIs("chrome"); }
429 bool imgRequest::IsData() const { return mURI->SchemeIs("data"); }
431 nsresult imgRequest::GetImageErrorCode() { return mImageErrorCode; }
433 void imgRequest::RemoveFromCache() {
434 LOG_SCOPE(gImgLog, "imgRequest::RemoveFromCache");
436 bool isInCache = false;
439 MutexAutoLock lock(mMutex);
440 isInCache = mIsInCache;
443 if (isInCache && mLoader) {
444 // mCacheEntry is nulled out when we have no more observers.
445 if (mCacheEntry) {
446 mLoader->RemoveFromCache(mCacheEntry);
447 } else {
448 mLoader->RemoveFromCache(mCacheKey);
452 mCacheEntry = nullptr;
455 bool imgRequest::HasConsumers() const {
456 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
457 return progressTracker && progressTracker->ObserverCount() > 0;
460 already_AddRefed<image::Image> imgRequest::GetImage() const {
461 MutexAutoLock lock(mMutex);
462 RefPtr<image::Image> image = mImage;
463 return image.forget();
466 void imgRequest::GetFileName(nsACString& aFileName) {
467 nsAutoString fileName;
469 nsCOMPtr<nsISupportsCString> supportscstr;
470 if (NS_SUCCEEDED(mProperties->Get("content-disposition",
471 NS_GET_IID(nsISupportsCString),
472 getter_AddRefs(supportscstr))) &&
473 supportscstr) {
474 nsAutoCString cdHeader;
475 supportscstr->GetData(cdHeader);
476 NS_GetFilenameFromDisposition(fileName, cdHeader);
479 if (fileName.IsEmpty()) {
480 nsCOMPtr<nsIURL> imgUrl(do_QueryInterface(mURI));
481 if (imgUrl) {
482 imgUrl->GetFileName(aFileName);
483 NS_UnescapeURL(aFileName);
485 } else {
486 aFileName = NS_ConvertUTF16toUTF8(fileName);
490 int32_t imgRequest::Priority() const {
491 int32_t priority = nsISupportsPriority::PRIORITY_NORMAL;
492 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mRequest);
493 if (p) {
494 p->GetPriority(&priority);
496 return priority;
499 void imgRequest::AdjustPriority(imgRequestProxy* proxy, int32_t delta) {
500 // only the first proxy is allowed to modify the priority of this image load.
502 // XXX(darin): this is probably not the most optimal algorithm as we may want
503 // to increase the priority of requests that have a lot of proxies. the key
504 // concern though is that image loads remain lower priority than other pieces
505 // of content such as link clicks, CSS, and JS.
507 if (!mFirstProxy || proxy != mFirstProxy) {
508 return;
511 AdjustPriorityInternal(delta);
514 void imgRequest::AdjustPriorityInternal(int32_t aDelta) {
515 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
516 if (p) {
517 p->AdjustPriority(aDelta);
521 void imgRequest::BoostPriority(uint32_t aCategory) {
522 if (!StaticPrefs::image_layout_network_priority()) {
523 return;
526 uint32_t newRequestedCategory =
527 (mBoostCategoriesRequested & aCategory) ^ aCategory;
528 if (!newRequestedCategory) {
529 // priority boost for each category can only apply once.
530 return;
533 MOZ_LOG(gImgLog, LogLevel::Debug,
534 ("[this=%p] imgRequest::BoostPriority for category %x", this,
535 newRequestedCategory));
537 int32_t delta = 0;
539 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_INIT) {
540 --delta;
543 if (newRequestedCategory & imgIRequest::CATEGORY_FRAME_STYLE) {
544 --delta;
547 if (newRequestedCategory & imgIRequest::CATEGORY_SIZE_QUERY) {
548 --delta;
551 if (newRequestedCategory & imgIRequest::CATEGORY_DISPLAY) {
552 delta += nsISupportsPriority::PRIORITY_HIGH;
555 AdjustPriorityInternal(delta);
556 mBoostCategoriesRequested |= newRequestedCategory;
559 void imgRequest::SetIsInCache(bool aInCache) {
560 LOG_FUNC_WITH_PARAM(gImgLog, "imgRequest::SetIsCacheable", "aInCache",
561 aInCache);
562 MutexAutoLock lock(mMutex);
563 mIsInCache = aInCache;
566 void imgRequest::UpdateCacheEntrySize() {
567 if (!mCacheEntry) {
568 return;
571 RefPtr<Image> image = GetImage();
572 SizeOfState state(moz_malloc_size_of);
573 size_t size = image->SizeOfSourceWithComputedFallback(state);
574 mCacheEntry->SetDataSize(size);
577 void imgRequest::SetCacheValidation(imgCacheEntry* aCacheEntry,
578 nsIRequest* aRequest) {
579 /* get the expires info */
580 if (!aCacheEntry || aCacheEntry->GetExpiryTime() != 0) {
581 return;
584 RefPtr<imgRequest> req = aCacheEntry->GetRequest();
585 MOZ_ASSERT(req);
586 RefPtr<nsIURI> uri;
587 req->GetURI(getter_AddRefs(uri));
588 // TODO(emilio): Seems we should be able to assert `uri` is not null, but we
589 // get here in such cases sometimes (like for some redirects, see
590 // docshell/test/chrome/test_bug89419.xhtml).
592 // We have the original URI in the cache key though, probably we should be
593 // using that instead of relying on Init() getting called.
594 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(aRequest, uri);
596 // Expiration time defaults to 0. We set the expiration time on our entry if
597 // it hasn't been set yet.
598 if (!info.mExpirationTime) {
599 // If the channel doesn't support caching, then ensure this expires the
600 // next time it is used.
601 info.mExpirationTime.emplace(nsContentUtils::SecondsFromPRTime(PR_Now()) -
604 aCacheEntry->SetExpiryTime(*info.mExpirationTime);
605 // Cache entries default to not needing to validate. We ensure that
606 // multiple calls to this function don't override an earlier decision to
607 // validate by making validation a one-way decision.
608 if (info.mMustRevalidate) {
609 aCacheEntry->SetMustValidate(info.mMustRevalidate);
613 bool imgRequest::GetMultipart() const {
614 MutexAutoLock lock(mMutex);
615 return mIsMultiPartChannel;
618 bool imgRequest::HadInsecureRedirect() const {
619 MutexAutoLock lock(mMutex);
620 return mHadInsecureRedirect;
623 /** nsIRequestObserver methods **/
625 NS_IMETHODIMP
626 imgRequest::OnStartRequest(nsIRequest* aRequest) {
627 LOG_SCOPE(gImgLog, "imgRequest::OnStartRequest");
629 RefPtr<Image> image;
631 if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest)) {
632 nsresult rv;
633 nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
634 mIsDeniedCrossSiteCORSRequest =
635 loadInfo->GetTainting() == LoadTainting::CORS &&
636 (NS_FAILED(httpChannel->GetStatus(&rv)) || NS_FAILED(rv));
637 mIsCrossSiteNoCORSRequest = loadInfo->GetTainting() == LoadTainting::Opaque;
640 // Figure out if we're multipart.
641 nsCOMPtr<nsIMultiPartChannel> multiPartChannel = do_QueryInterface(aRequest);
643 MutexAutoLock lock(mMutex);
645 MOZ_ASSERT(multiPartChannel || !mIsMultiPartChannel,
646 "Stopped being multipart?");
648 mNewPartPending = true;
649 image = mImage;
650 mIsMultiPartChannel = bool(multiPartChannel);
653 // If we're not multipart, we shouldn't have an image yet.
654 if (image && !multiPartChannel) {
655 MOZ_ASSERT_UNREACHABLE("Already have an image for a non-multipart request");
656 Cancel(NS_IMAGELIB_ERROR_FAILURE);
657 return NS_ERROR_FAILURE;
661 * If mRequest is null here, then we need to set it so that we'll be able to
662 * cancel it if our Cancel() method is called. Note that this can only
663 * happen for multipart channels. We could simply not null out mRequest for
664 * non-last parts, if GetIsLastPart() were reliable, but it's not. See
665 * https://bugzilla.mozilla.org/show_bug.cgi?id=339610
667 if (!mRequest) {
668 MOZ_ASSERT(multiPartChannel, "Should have mRequest unless we're multipart");
669 nsCOMPtr<nsIChannel> baseChannel;
670 multiPartChannel->GetBaseChannel(getter_AddRefs(baseChannel));
671 mRequest = baseChannel;
674 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
675 if (channel) {
676 /* Get our principal */
677 nsCOMPtr<nsIScriptSecurityManager> secMan =
678 nsContentUtils::GetSecurityManager();
679 if (secMan) {
680 nsresult rv = secMan->GetChannelResultPrincipal(
681 channel, getter_AddRefs(mPrincipal));
682 if (NS_FAILED(rv)) {
683 return rv;
688 SetCacheValidation(mCacheEntry, aRequest);
690 // Shouldn't we be dead already if this gets hit?
691 // Probably multipart/x-mixed-replace...
692 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
693 if (progressTracker->ObserverCount() == 0) {
694 this->Cancel(NS_IMAGELIB_ERROR_FAILURE);
697 // Try to retarget OnDataAvailable to a decode thread. We must process data
698 // URIs synchronously as per the spec however.
699 if (!channel || IsData()) {
700 return NS_OK;
703 nsCOMPtr<nsIThreadRetargetableRequest> retargetable =
704 do_QueryInterface(aRequest);
705 if (retargetable) {
706 nsAutoCString mimeType;
707 nsresult rv = channel->GetContentType(mimeType);
708 if (NS_SUCCEEDED(rv) && !mimeType.EqualsLiteral(IMAGE_SVG_XML)) {
709 // Retarget OnDataAvailable to the DecodePool's IO thread.
710 nsCOMPtr<nsIEventTarget> target =
711 DecodePool::Singleton()->GetIOEventTarget();
712 rv = retargetable->RetargetDeliveryTo(target);
714 MOZ_LOG(gImgLog, LogLevel::Warning,
715 ("[this=%p] imgRequest::OnStartRequest -- "
716 "RetargetDeliveryTo rv %" PRIu32 "=%s\n",
717 this, static_cast<uint32_t>(rv),
718 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
721 return NS_OK;
724 NS_IMETHODIMP
725 imgRequest::OnStopRequest(nsIRequest* aRequest, nsresult status) {
726 LOG_FUNC(gImgLog, "imgRequest::OnStopRequest");
727 MOZ_ASSERT(NS_IsMainThread(), "Can't send notifications off-main-thread");
729 RefPtr<Image> image = GetImage();
731 RefPtr<imgRequest> strongThis = this;
733 bool isMultipart = false;
734 bool newPartPending = false;
736 MutexAutoLock lock(mMutex);
737 isMultipart = mIsMultiPartChannel;
738 newPartPending = mNewPartPending;
740 if (isMultipart && newPartPending) {
741 OnDataAvailable(aRequest, nullptr, 0, 0);
744 // XXXldb What if this is a non-last part of a multipart request?
745 // xxx before we release our reference to mRequest, lets
746 // save the last status that we saw so that the
747 // imgRequestProxy will have access to it.
748 if (mRequest) {
749 mRequest = nullptr; // we no longer need the request
752 // stop holding a ref to the channel, since we don't need it anymore
753 if (mChannel) {
754 mChannel->SetNotificationCallbacks(mPrevChannelSink);
755 mPrevChannelSink = nullptr;
756 mChannel = nullptr;
759 bool lastPart = true;
760 nsCOMPtr<nsIMultiPartChannel> mpchan(do_QueryInterface(aRequest));
761 if (mpchan) {
762 mpchan->GetIsLastPart(&lastPart);
765 bool isPartial = false;
766 if (image && (status == NS_ERROR_NET_PARTIAL_TRANSFER)) {
767 isPartial = true;
768 status = NS_OK; // fake happy face
771 // Tell the image that it has all of the source data. Note that this can
772 // trigger a failure, since the image might be waiting for more non-optional
773 // data and this is the point where we break the news that it's not coming.
774 if (image) {
775 nsresult rv = image->OnImageDataComplete(aRequest, status, lastPart);
777 // If we got an error in the OnImageDataComplete() call, we don't want to
778 // proceed as if nothing bad happened. However, we also want to give
779 // precedence to failure status codes from necko, since presumably they're
780 // more meaningful.
781 if (NS_FAILED(rv) && NS_SUCCEEDED(status)) {
782 status = rv;
786 // If the request went through, update the cache entry size. Otherwise,
787 // cancel the request, which removes us from the cache.
788 if (image && NS_SUCCEEDED(status) && !isPartial) {
789 // We update the cache entry size here because this is where we finish
790 // loading compressed source data, which is part of our size calculus.
791 UpdateCacheEntrySize();
793 } else if (isPartial) {
794 // Remove the partial image from the cache.
795 this->EvictFromCache();
797 } else {
798 mImageErrorCode = status;
800 // if the error isn't "just" a partial transfer
801 // stops animations, removes from cache
802 this->Cancel(status);
805 if (!image) {
806 // We have to fire the OnStopRequest notifications ourselves because there's
807 // no image capable of doing so.
808 Progress progress =
809 LoadCompleteProgress(lastPart, /* aError = */ false, status);
811 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
812 progressTracker->SyncNotifyProgress(progress);
815 mTimedChannel = nullptr;
816 return NS_OK;
819 struct mimetype_closure {
820 nsACString* newType;
823 /* prototype for these defined below */
824 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* closure,
825 const char* fromRawSegment,
826 uint32_t toOffset, uint32_t count,
827 uint32_t* writeCount);
829 /** nsThreadRetargetableStreamListener methods **/
830 NS_IMETHODIMP
831 imgRequest::CheckListenerChain() {
832 // TODO Might need more checking here.
833 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
834 return NS_OK;
837 /** nsIStreamListener methods **/
839 struct NewPartResult final {
840 explicit NewPartResult(image::Image* aExistingImage)
841 : mImage(aExistingImage),
842 mIsFirstPart(!aExistingImage),
843 mSucceeded(false),
844 mShouldResetCacheEntry(false) {}
846 nsAutoCString mContentType;
847 nsAutoCString mContentDisposition;
848 RefPtr<image::Image> mImage;
849 const bool mIsFirstPart;
850 bool mSucceeded;
851 bool mShouldResetCacheEntry;
854 static NewPartResult PrepareForNewPart(nsIRequest* aRequest,
855 nsIInputStream* aInStr, uint32_t aCount,
856 nsIURI* aURI, bool aIsMultipart,
857 image::Image* aExistingImage,
858 ProgressTracker* aProgressTracker,
859 uint64_t aInnerWindowId) {
860 NewPartResult result(aExistingImage);
862 if (aInStr) {
863 mimetype_closure closure;
864 closure.newType = &result.mContentType;
866 // Look at the first few bytes and see if we can tell what the data is from
867 // that since servers tend to lie. :(
868 uint32_t out;
869 aInStr->ReadSegments(sniff_mimetype_callback, &closure, aCount, &out);
872 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
873 if (result.mContentType.IsEmpty()) {
874 nsresult rv =
875 chan ? chan->GetContentType(result.mContentType) : NS_ERROR_FAILURE;
876 if (NS_FAILED(rv)) {
877 MOZ_LOG(gImgLog, LogLevel::Error,
878 ("imgRequest::PrepareForNewPart -- "
879 "Content type unavailable from the channel\n"));
880 if (!aIsMultipart) {
881 return result;
886 if (chan) {
887 chan->GetContentDispositionHeader(result.mContentDisposition);
890 MOZ_LOG(gImgLog, LogLevel::Debug,
891 ("imgRequest::PrepareForNewPart -- Got content type %s\n",
892 result.mContentType.get()));
894 // XXX If server lied about mimetype and it's SVG, we may need to copy
895 // the data and dispatch back to the main thread, AND tell the channel to
896 // dispatch there in the future.
898 // Create the new image and give it ownership of our ProgressTracker.
899 if (aIsMultipart) {
900 // Create the ProgressTracker and image for this part.
901 RefPtr<ProgressTracker> progressTracker = new ProgressTracker();
902 RefPtr<image::Image> partImage = image::ImageFactory::CreateImage(
903 aRequest, progressTracker, result.mContentType, aURI,
904 /* aIsMultipart = */ true, aInnerWindowId);
906 if (result.mIsFirstPart) {
907 // First part for a multipart channel. Create the MultipartImage wrapper.
908 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
909 aProgressTracker->SetIsMultipart();
910 result.mImage = image::ImageFactory::CreateMultipartImage(
911 partImage, aProgressTracker);
912 } else {
913 // Transition to the new part.
914 auto multipartImage = static_cast<MultipartImage*>(aExistingImage);
915 multipartImage->BeginTransitionToPart(partImage);
917 // Reset our cache entry size so it doesn't keep growing without bound.
918 result.mShouldResetCacheEntry = true;
920 } else {
921 MOZ_ASSERT(!aExistingImage, "New part for non-multipart channel?");
922 MOZ_ASSERT(aProgressTracker, "Shouldn't have given away tracker yet");
924 // Create an image using our progress tracker.
925 result.mImage = image::ImageFactory::CreateImage(
926 aRequest, aProgressTracker, result.mContentType, aURI,
927 /* aIsMultipart = */ false, aInnerWindowId);
930 MOZ_ASSERT(result.mImage);
931 if (!result.mImage->HasError() || aIsMultipart) {
932 // We allow multipart images to fail to initialize (which generally
933 // indicates a bad content type) without cancelling the load, because
934 // subsequent parts might be fine.
935 result.mSucceeded = true;
938 return result;
941 class FinishPreparingForNewPartRunnable final : public Runnable {
942 public:
943 FinishPreparingForNewPartRunnable(imgRequest* aImgRequest,
944 NewPartResult&& aResult)
945 : Runnable("FinishPreparingForNewPartRunnable"),
946 mImgRequest(aImgRequest),
947 mResult(aResult) {
948 MOZ_ASSERT(aImgRequest);
951 NS_IMETHOD Run() override {
952 mImgRequest->FinishPreparingForNewPart(mResult);
953 return NS_OK;
956 private:
957 RefPtr<imgRequest> mImgRequest;
958 NewPartResult mResult;
961 void imgRequest::FinishPreparingForNewPart(const NewPartResult& aResult) {
962 MOZ_ASSERT(NS_IsMainThread());
964 mContentType = aResult.mContentType;
966 SetProperties(aResult.mContentType, aResult.mContentDisposition);
968 if (aResult.mIsFirstPart) {
969 // Notify listeners that we have an image.
970 mImageAvailable = true;
971 RefPtr<ProgressTracker> progressTracker = GetProgressTracker();
972 progressTracker->OnImageAvailable();
973 MOZ_ASSERT(progressTracker->HasImage());
976 if (aResult.mShouldResetCacheEntry) {
977 ResetCacheEntry();
980 if (IsDecodeRequested()) {
981 aResult.mImage->StartDecoding(imgIContainer::FLAG_NONE);
985 bool imgRequest::ImageAvailable() const { return mImageAvailable; }
987 NS_IMETHODIMP
988 imgRequest::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
989 uint64_t aOffset, uint32_t aCount) {
990 LOG_SCOPE_WITH_PARAM(gImgLog, "imgRequest::OnDataAvailable", "count", aCount);
992 NS_ASSERTION(aRequest, "imgRequest::OnDataAvailable -- no request!");
994 RefPtr<Image> image;
995 RefPtr<ProgressTracker> progressTracker;
996 bool isMultipart = false;
997 bool newPartPending = false;
998 uint64_t innerWindowId = 0;
1000 // Retrieve and update our state.
1002 MutexAutoLock lock(mMutex);
1003 image = mImage;
1004 progressTracker = mProgressTracker;
1005 isMultipart = mIsMultiPartChannel;
1006 newPartPending = mNewPartPending;
1007 mNewPartPending = false;
1008 innerWindowId = mInnerWindowId;
1011 // If this is a new part, we need to sniff its content type and create an
1012 // appropriate image.
1013 if (newPartPending) {
1014 NewPartResult result =
1015 PrepareForNewPart(aRequest, aInStr, aCount, mURI, isMultipart, image,
1016 progressTracker, innerWindowId);
1017 bool succeeded = result.mSucceeded;
1019 if (result.mImage) {
1020 image = result.mImage;
1021 nsCOMPtr<nsIEventTarget> eventTarget;
1023 // Update our state to reflect this new part.
1025 MutexAutoLock lock(mMutex);
1026 mImage = image;
1028 // We only get an event target if we are not on the main thread, because
1029 // we have to dispatch in that case. If we are on the main thread, but
1030 // on a different scheduler group than ProgressTracker would give us,
1031 // that is okay because nothing in imagelib requires that, just our
1032 // listeners (which have their own checks).
1033 if (!NS_IsMainThread()) {
1034 eventTarget = mProgressTracker->GetEventTarget();
1035 MOZ_ASSERT(eventTarget);
1038 mProgressTracker = nullptr;
1041 // Some property objects are not threadsafe, and we need to send
1042 // OnImageAvailable on the main thread, so finish on the main thread.
1043 if (!eventTarget) {
1044 MOZ_ASSERT(NS_IsMainThread());
1045 FinishPreparingForNewPart(result);
1046 } else {
1047 nsCOMPtr<nsIRunnable> runnable =
1048 new FinishPreparingForNewPartRunnable(this, std::move(result));
1049 eventTarget->Dispatch(CreateRenderBlockingRunnable(runnable.forget()),
1050 NS_DISPATCH_NORMAL);
1054 if (!succeeded) {
1055 // Something went wrong; probably a content type issue.
1056 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1057 return NS_BINDING_ABORTED;
1061 // Notify the image that it has new data.
1062 if (aInStr) {
1063 nsresult rv =
1064 image->OnImageDataAvailable(aRequest, aInStr, aOffset, aCount);
1066 if (NS_FAILED(rv)) {
1067 MOZ_LOG(gImgLog, LogLevel::Warning,
1068 ("[this=%p] imgRequest::OnDataAvailable -- "
1069 "copy to RasterImage failed\n",
1070 this));
1071 Cancel(NS_IMAGELIB_ERROR_FAILURE);
1072 return NS_BINDING_ABORTED;
1076 return NS_OK;
1079 void imgRequest::SetProperties(const nsACString& aContentType,
1080 const nsACString& aContentDisposition) {
1081 /* set our mimetype as a property */
1082 nsCOMPtr<nsISupportsCString> contentType =
1083 do_CreateInstance("@mozilla.org/supports-cstring;1");
1084 if (contentType) {
1085 contentType->SetData(aContentType);
1086 mProperties->Set("type", contentType);
1089 /* set our content disposition as a property */
1090 if (!aContentDisposition.IsEmpty()) {
1091 nsCOMPtr<nsISupportsCString> contentDisposition =
1092 do_CreateInstance("@mozilla.org/supports-cstring;1");
1093 if (contentDisposition) {
1094 contentDisposition->SetData(aContentDisposition);
1095 mProperties->Set("content-disposition", contentDisposition);
1100 static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
1101 const char* fromRawSegment,
1102 uint32_t toOffset, uint32_t count,
1103 uint32_t* writeCount) {
1104 mimetype_closure* closure = static_cast<mimetype_closure*>(data);
1106 NS_ASSERTION(closure, "closure is null!");
1108 if (count > 0) {
1109 imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *closure->newType);
1112 *writeCount = 0;
1113 return NS_ERROR_FAILURE;
1116 /** nsIInterfaceRequestor methods **/
1118 NS_IMETHODIMP
1119 imgRequest::GetInterface(const nsIID& aIID, void** aResult) {
1120 if (!mPrevChannelSink || aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
1121 return QueryInterface(aIID, aResult);
1124 NS_ASSERTION(
1125 mPrevChannelSink != this,
1126 "Infinite recursion - don't keep track of channel sinks that are us!");
1127 return mPrevChannelSink->GetInterface(aIID, aResult);
1130 /** nsIChannelEventSink methods **/
1131 NS_IMETHODIMP
1132 imgRequest::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1133 nsIChannel* newChannel, uint32_t flags,
1134 nsIAsyncVerifyRedirectCallback* callback) {
1135 NS_ASSERTION(mRequest && mChannel,
1136 "Got a channel redirect after we nulled out mRequest!");
1137 NS_ASSERTION(mChannel == oldChannel,
1138 "Got a channel redirect for an unknown channel!");
1139 NS_ASSERTION(newChannel, "Got a redirect to a NULL channel!");
1141 SetCacheValidation(mCacheEntry, oldChannel);
1143 // Prepare for callback
1144 mRedirectCallback = callback;
1145 mNewRedirectChannel = newChannel;
1147 nsCOMPtr<nsIChannelEventSink> sink(do_GetInterface(mPrevChannelSink));
1148 if (sink) {
1149 nsresult rv =
1150 sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
1151 if (NS_FAILED(rv)) {
1152 mRedirectCallback = nullptr;
1153 mNewRedirectChannel = nullptr;
1155 return rv;
1158 (void)OnRedirectVerifyCallback(NS_OK);
1159 return NS_OK;
1162 NS_IMETHODIMP
1163 imgRequest::OnRedirectVerifyCallback(nsresult result) {
1164 NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
1165 NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
1167 if (NS_FAILED(result)) {
1168 mRedirectCallback->OnRedirectVerifyCallback(result);
1169 mRedirectCallback = nullptr;
1170 mNewRedirectChannel = nullptr;
1171 return NS_OK;
1174 mChannel = mNewRedirectChannel;
1175 mTimedChannel = do_QueryInterface(mChannel);
1176 mNewRedirectChannel = nullptr;
1178 if (LOG_TEST(LogLevel::Debug)) {
1179 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "old",
1180 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1183 // If the previous URI is a non-HTTPS URI, record that fact for later use by
1184 // security code, which needs to know whether there is an insecure load at any
1185 // point in the redirect chain.
1186 bool schemeLocal = false;
1187 if (NS_FAILED(NS_URIChainHasFlags(mFinalURI,
1188 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
1189 &schemeLocal)) ||
1190 (!mFinalURI->SchemeIs("https") && !mFinalURI->SchemeIs("chrome") &&
1191 !schemeLocal)) {
1192 MutexAutoLock lock(mMutex);
1194 // The csp directive upgrade-insecure-requests performs an internal redirect
1195 // to upgrade all requests from http to https before any data is fetched
1196 // from the network. Do not pollute mHadInsecureRedirect in case of such an
1197 // internal redirect.
1198 nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
1199 bool upgradeInsecureRequests =
1200 loadInfo ? loadInfo->GetUpgradeInsecureRequests() ||
1201 loadInfo->GetBrowserUpgradeInsecureRequests()
1202 : false;
1203 if (!upgradeInsecureRequests) {
1204 mHadInsecureRedirect = true;
1208 // Update the final URI.
1209 mChannel->GetURI(getter_AddRefs(mFinalURI));
1211 if (LOG_TEST(LogLevel::Debug)) {
1212 LOG_MSG_WITH_PARAM(gImgLog, "imgRequest::OnChannelRedirect", "new",
1213 mFinalURI ? mFinalURI->GetSpecOrDefault().get() : "");
1216 // Make sure we have a protocol that returns data rather than opens an
1217 // external application, e.g. 'mailto:'.
1218 bool doesNotReturnData = false;
1219 nsresult rv = NS_URIChainHasFlags(
1220 mFinalURI, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
1221 &doesNotReturnData);
1223 if (NS_SUCCEEDED(rv) && doesNotReturnData) {
1224 rv = NS_ERROR_ABORT;
1227 if (NS_FAILED(rv)) {
1228 mRedirectCallback->OnRedirectVerifyCallback(rv);
1229 mRedirectCallback = nullptr;
1230 return NS_OK;
1233 mRedirectCallback->OnRedirectVerifyCallback(NS_OK);
1234 mRedirectCallback = nullptr;
1235 return NS_OK;