Bug 1740824 remove unused support file links r=mjf
[gecko.git] / image / imgLoader.cpp
blob2e4b3615b344b97bc01202deba9a18096e682f8f
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
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 // Undefine windows version of LoadImage because our code uses that name.
8 #include "mozilla/ScopeExit.h"
9 #undef LoadImage
11 #include "imgLoader.h"
13 #include <algorithm>
14 #include <utility>
16 #include "DecoderFactory.h"
17 #include "Image.h"
18 #include "ImageLogging.h"
19 #include "ReferrerInfo.h"
20 #include "imgRequestProxy.h"
21 #include "mozilla/Attributes.h"
22 #include "mozilla/BasePrincipal.h"
23 #include "mozilla/ChaosMode.h"
24 #include "mozilla/ClearOnShutdown.h"
25 #include "mozilla/LoadInfo.h"
26 #include "mozilla/NullPrincipal.h"
27 #include "mozilla/Preferences.h"
28 #include "mozilla/ProfilerLabels.h"
29 #include "mozilla/StaticPrefs_image.h"
30 #include "mozilla/StaticPrefs_network.h"
31 #include "mozilla/StoragePrincipalHelper.h"
32 #include "mozilla/dom/ContentParent.h"
33 #include "mozilla/dom/nsMixedContentBlocker.h"
34 #include "mozilla/image/ImageMemoryReporter.h"
35 #include "mozilla/layers/CompositorManagerChild.h"
36 #include "nsCOMPtr.h"
37 #include "nsCRT.h"
38 #include "nsComponentManagerUtils.h"
39 #include "nsContentPolicyUtils.h"
40 #include "nsContentUtils.h"
41 #include "nsHttpChannel.h"
42 #include "nsIAsyncVerifyRedirectCallback.h"
43 #include "nsICacheInfoChannel.h"
44 #include "nsIChannelEventSink.h"
45 #include "nsIClassOfService.h"
46 #include "nsIEffectiveTLDService.h"
47 #include "nsIFile.h"
48 #include "nsIFileURL.h"
49 #include "nsIHttpChannel.h"
50 #include "nsIInterfaceRequestor.h"
51 #include "nsIInterfaceRequestorUtils.h"
52 #include "nsIMemoryReporter.h"
53 #include "nsINetworkPredictor.h"
54 #include "nsIProgressEventSink.h"
55 #include "nsIProtocolHandler.h"
56 #include "nsImageModule.h"
57 #include "nsMediaSniffer.h"
58 #include "nsMimeTypes.h"
59 #include "nsNetCID.h"
60 #include "nsNetUtil.h"
61 #include "nsProxyRelease.h"
62 #include "nsQueryObject.h"
63 #include "nsReadableUtils.h"
64 #include "nsStreamUtils.h"
65 #include "prtime.h"
67 // we want to explore making the document own the load group
68 // so we can associate the document URI with the load group.
69 // until this point, we have an evil hack:
70 #include "nsIHttpChannelInternal.h"
71 #include "nsILoadGroupChild.h"
72 #include "nsIDocShell.h"
74 using namespace mozilla;
75 using namespace mozilla::dom;
76 using namespace mozilla::image;
77 using namespace mozilla::net;
79 MOZ_DEFINE_MALLOC_SIZE_OF(ImagesMallocSizeOf)
81 class imgMemoryReporter final : public nsIMemoryReporter {
82 ~imgMemoryReporter() = default;
84 public:
85 NS_DECL_ISUPPORTS
87 NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport,
88 nsISupports* aData, bool aAnonymize) override {
89 MOZ_ASSERT(NS_IsMainThread());
91 layers::CompositorManagerChild* manager =
92 mozilla::layers::CompositorManagerChild::GetInstance();
93 if (!manager || !StaticPrefs::image_mem_debug_reporting()) {
94 layers::SharedSurfacesMemoryReport sharedSurfaces;
95 FinishCollectReports(aHandleReport, aData, aAnonymize, sharedSurfaces);
96 return NS_OK;
99 RefPtr<imgMemoryReporter> self(this);
100 nsCOMPtr<nsIHandleReportCallback> handleReport(aHandleReport);
101 nsCOMPtr<nsISupports> data(aData);
102 manager->SendReportSharedSurfacesMemory(
103 [=](layers::SharedSurfacesMemoryReport aReport) {
104 self->FinishCollectReports(handleReport, data, aAnonymize, aReport);
106 [=](mozilla::ipc::ResponseRejectReason&& aReason) {
107 layers::SharedSurfacesMemoryReport sharedSurfaces;
108 self->FinishCollectReports(handleReport, data, aAnonymize,
109 sharedSurfaces);
111 return NS_OK;
114 void FinishCollectReports(
115 nsIHandleReportCallback* aHandleReport, nsISupports* aData,
116 bool aAnonymize, layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
117 nsTArray<ImageMemoryCounter> chrome;
118 nsTArray<ImageMemoryCounter> content;
119 nsTArray<ImageMemoryCounter> uncached;
121 for (uint32_t i = 0; i < mKnownLoaders.Length(); i++) {
122 for (imgCacheEntry* entry : mKnownLoaders[i]->mChromeCache.Values()) {
123 RefPtr<imgRequest> req = entry->GetRequest();
124 RecordCounterForRequest(req, &chrome, !entry->HasNoProxies());
126 for (imgCacheEntry* entry : mKnownLoaders[i]->mCache.Values()) {
127 RefPtr<imgRequest> req = entry->GetRequest();
128 RecordCounterForRequest(req, &content, !entry->HasNoProxies());
130 MutexAutoLock lock(mKnownLoaders[i]->mUncachedImagesMutex);
131 for (RefPtr<imgRequest> req : mKnownLoaders[i]->mUncachedImages) {
132 RecordCounterForRequest(req, &uncached, req->HasConsumers());
136 // Note that we only need to anonymize content image URIs.
138 ReportCounterArray(aHandleReport, aData, chrome, "images/chrome",
139 /* aAnonymize */ false, aSharedSurfaces);
141 ReportCounterArray(aHandleReport, aData, content, "images/content",
142 aAnonymize, aSharedSurfaces);
144 // Uncached images may be content or chrome, so anonymize them.
145 ReportCounterArray(aHandleReport, aData, uncached, "images/uncached",
146 aAnonymize, aSharedSurfaces);
148 // Report any shared surfaces that were not merged with the surface cache.
149 ImageMemoryReporter::ReportSharedSurfaces(aHandleReport, aData,
150 aSharedSurfaces);
152 nsCOMPtr<nsIMemoryReporterManager> imgr =
153 do_GetService("@mozilla.org/memory-reporter-manager;1");
154 if (imgr) {
155 imgr->EndReport();
159 static int64_t ImagesContentUsedUncompressedDistinguishedAmount() {
160 size_t n = 0;
161 for (uint32_t i = 0; i < imgLoader::sMemReporter->mKnownLoaders.Length();
162 i++) {
163 for (imgCacheEntry* entry :
164 imgLoader::sMemReporter->mKnownLoaders[i]->mCache.Values()) {
165 if (entry->HasNoProxies()) {
166 continue;
169 RefPtr<imgRequest> req = entry->GetRequest();
170 RefPtr<image::Image> image = req->GetImage();
171 if (!image) {
172 continue;
175 // Both this and EntryImageSizes measure
176 // images/content/raster/used/decoded memory. This function's
177 // measurement is secondary -- the result doesn't go in the "explicit"
178 // tree -- so we use moz_malloc_size_of instead of ImagesMallocSizeOf to
179 // prevent DMD from seeing it reported twice.
180 SizeOfState state(moz_malloc_size_of);
181 ImageMemoryCounter counter(req, image, state, /* aIsUsed = */ true);
183 n += counter.Values().DecodedHeap();
184 n += counter.Values().DecodedNonHeap();
185 n += counter.Values().DecodedUnknown();
188 return n;
191 void RegisterLoader(imgLoader* aLoader) {
192 mKnownLoaders.AppendElement(aLoader);
195 void UnregisterLoader(imgLoader* aLoader) {
196 mKnownLoaders.RemoveElement(aLoader);
199 private:
200 nsTArray<imgLoader*> mKnownLoaders;
202 struct MemoryTotal {
203 MemoryTotal& operator+=(const ImageMemoryCounter& aImageCounter) {
204 if (aImageCounter.Type() == imgIContainer::TYPE_RASTER) {
205 if (aImageCounter.IsUsed()) {
206 mUsedRasterCounter += aImageCounter.Values();
207 } else {
208 mUnusedRasterCounter += aImageCounter.Values();
210 } else if (aImageCounter.Type() == imgIContainer::TYPE_VECTOR) {
211 if (aImageCounter.IsUsed()) {
212 mUsedVectorCounter += aImageCounter.Values();
213 } else {
214 mUnusedVectorCounter += aImageCounter.Values();
216 } else if (aImageCounter.Type() == imgIContainer::TYPE_REQUEST) {
217 // Nothing to do, we did not get to the point of having an image.
218 } else {
219 MOZ_CRASH("Unexpected image type");
222 return *this;
225 const MemoryCounter& UsedRaster() const { return mUsedRasterCounter; }
226 const MemoryCounter& UnusedRaster() const { return mUnusedRasterCounter; }
227 const MemoryCounter& UsedVector() const { return mUsedVectorCounter; }
228 const MemoryCounter& UnusedVector() const { return mUnusedVectorCounter; }
230 private:
231 MemoryCounter mUsedRasterCounter;
232 MemoryCounter mUnusedRasterCounter;
233 MemoryCounter mUsedVectorCounter;
234 MemoryCounter mUnusedVectorCounter;
237 // Reports all images of a single kind, e.g. all used chrome images.
238 void ReportCounterArray(nsIHandleReportCallback* aHandleReport,
239 nsISupports* aData,
240 nsTArray<ImageMemoryCounter>& aCounterArray,
241 const char* aPathPrefix, bool aAnonymize,
242 layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
243 MemoryTotal summaryTotal;
244 MemoryTotal nonNotableTotal;
246 // Report notable images, and compute total and non-notable aggregate sizes.
247 for (uint32_t i = 0; i < aCounterArray.Length(); i++) {
248 ImageMemoryCounter& counter = aCounterArray[i];
250 if (aAnonymize) {
251 counter.URI().Truncate();
252 counter.URI().AppendPrintf("<anonymized-%u>", i);
253 } else {
254 // The URI could be an extremely long data: URI. Truncate if needed.
255 static const size_t max = 256;
256 if (counter.URI().Length() > max) {
257 counter.URI().Truncate(max);
258 counter.URI().AppendLiteral(" (truncated)");
260 counter.URI().ReplaceChar('/', '\\');
263 summaryTotal += counter;
265 if (counter.IsNotable() || StaticPrefs::image_mem_debug_reporting()) {
266 ReportImage(aHandleReport, aData, aPathPrefix, counter,
267 aSharedSurfaces);
268 } else {
269 ImageMemoryReporter::TrimSharedSurfaces(counter, aSharedSurfaces);
270 nonNotableTotal += counter;
274 // Report non-notable images in aggregate.
275 ReportTotal(aHandleReport, aData, /* aExplicit = */ true, aPathPrefix,
276 "<non-notable images>/", nonNotableTotal);
278 // Report a summary in aggregate, outside of the explicit tree.
279 ReportTotal(aHandleReport, aData, /* aExplicit = */ false, aPathPrefix, "",
280 summaryTotal);
283 static void ReportImage(nsIHandleReportCallback* aHandleReport,
284 nsISupports* aData, const char* aPathPrefix,
285 const ImageMemoryCounter& aCounter,
286 layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
287 nsAutoCString pathPrefix("explicit/"_ns);
288 pathPrefix.Append(aPathPrefix);
290 switch (aCounter.Type()) {
291 case imgIContainer::TYPE_RASTER:
292 pathPrefix.AppendLiteral("/raster/");
293 break;
294 case imgIContainer::TYPE_VECTOR:
295 pathPrefix.AppendLiteral("/vector/");
296 break;
297 case imgIContainer::TYPE_REQUEST:
298 pathPrefix.AppendLiteral("/request/");
299 break;
300 default:
301 pathPrefix.AppendLiteral("/unknown=");
302 pathPrefix.AppendInt(aCounter.Type());
303 pathPrefix.AppendLiteral("/");
304 break;
307 pathPrefix.Append(aCounter.IsUsed() ? "used/" : "unused/");
308 if (aCounter.IsValidating()) {
309 pathPrefix.AppendLiteral("validating/");
311 if (aCounter.HasError()) {
312 pathPrefix.AppendLiteral("err/");
315 pathPrefix.AppendLiteral("progress=");
316 pathPrefix.AppendInt(aCounter.Progress(), 16);
317 pathPrefix.AppendLiteral("/");
319 pathPrefix.AppendLiteral("image(");
320 pathPrefix.AppendInt(aCounter.IntrinsicSize().width);
321 pathPrefix.AppendLiteral("x");
322 pathPrefix.AppendInt(aCounter.IntrinsicSize().height);
323 pathPrefix.AppendLiteral(", ");
325 if (aCounter.URI().IsEmpty()) {
326 pathPrefix.AppendLiteral("<unknown URI>");
327 } else {
328 pathPrefix.Append(aCounter.URI());
331 pathPrefix.AppendLiteral(")/");
333 ReportSurfaces(aHandleReport, aData, pathPrefix, aCounter, aSharedSurfaces);
335 ReportSourceValue(aHandleReport, aData, pathPrefix, aCounter.Values());
338 static void ReportSurfaces(
339 nsIHandleReportCallback* aHandleReport, nsISupports* aData,
340 const nsACString& aPathPrefix, const ImageMemoryCounter& aCounter,
341 layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
342 for (const SurfaceMemoryCounter& counter : aCounter.Surfaces()) {
343 nsAutoCString surfacePathPrefix(aPathPrefix);
344 switch (counter.Type()) {
345 case SurfaceMemoryCounterType::NORMAL:
346 if (counter.IsLocked()) {
347 surfacePathPrefix.AppendLiteral("locked/");
348 } else {
349 surfacePathPrefix.AppendLiteral("unlocked/");
351 if (counter.IsFactor2()) {
352 surfacePathPrefix.AppendLiteral("factor2/");
354 if (counter.CannotSubstitute()) {
355 surfacePathPrefix.AppendLiteral("cannot_substitute/");
357 break;
358 case SurfaceMemoryCounterType::CONTAINER:
359 surfacePathPrefix.AppendLiteral("container/");
360 break;
361 default:
362 MOZ_ASSERT_UNREACHABLE("Unknown counter type");
363 break;
366 surfacePathPrefix.AppendLiteral("types=");
367 surfacePathPrefix.AppendInt(counter.Values().SurfaceTypes(), 16);
368 surfacePathPrefix.AppendLiteral("/surface(");
369 surfacePathPrefix.AppendInt(counter.Key().Size().width);
370 surfacePathPrefix.AppendLiteral("x");
371 surfacePathPrefix.AppendInt(counter.Key().Size().height);
373 if (!counter.IsFinished()) {
374 surfacePathPrefix.AppendLiteral(", incomplete");
377 if (counter.Values().ExternalHandles() > 0) {
378 surfacePathPrefix.AppendLiteral(", handles:");
379 surfacePathPrefix.AppendInt(
380 uint32_t(counter.Values().ExternalHandles()));
383 ImageMemoryReporter::AppendSharedSurfacePrefix(surfacePathPrefix, counter,
384 aSharedSurfaces);
386 PlaybackType playback = counter.Key().Playback();
387 if (playback == PlaybackType::eAnimated) {
388 if (StaticPrefs::image_mem_debug_reporting()) {
389 surfacePathPrefix.AppendPrintf(
390 " (animation %4u)", uint32_t(counter.Values().FrameIndex()));
391 } else {
392 surfacePathPrefix.AppendLiteral(" (animation)");
396 if (counter.Key().Flags() != DefaultSurfaceFlags()) {
397 surfacePathPrefix.AppendLiteral(", flags:");
398 surfacePathPrefix.AppendInt(uint32_t(counter.Key().Flags()),
399 /* aRadix = */ 16);
402 if (counter.Key().Region()) {
403 const ImageIntRegion& region = counter.Key().Region().ref();
404 const gfx::IntRect& rect = region.Rect();
405 surfacePathPrefix.AppendLiteral(", region:[ rect=(");
406 surfacePathPrefix.AppendInt(rect.x);
407 surfacePathPrefix.AppendLiteral(",");
408 surfacePathPrefix.AppendInt(rect.y);
409 surfacePathPrefix.AppendLiteral(") ");
410 surfacePathPrefix.AppendInt(rect.width);
411 surfacePathPrefix.AppendLiteral("x");
412 surfacePathPrefix.AppendInt(rect.height);
413 if (region.IsRestricted()) {
414 const gfx::IntRect& restrict = region.Restriction();
415 if (restrict == rect) {
416 surfacePathPrefix.AppendLiteral(", restrict=rect");
417 } else {
418 surfacePathPrefix.AppendLiteral(", restrict=(");
419 surfacePathPrefix.AppendInt(restrict.x);
420 surfacePathPrefix.AppendLiteral(",");
421 surfacePathPrefix.AppendInt(restrict.y);
422 surfacePathPrefix.AppendLiteral(") ");
423 surfacePathPrefix.AppendInt(restrict.width);
424 surfacePathPrefix.AppendLiteral("x");
425 surfacePathPrefix.AppendInt(restrict.height);
428 if (region.GetExtendMode() != gfx::ExtendMode::CLAMP) {
429 surfacePathPrefix.AppendLiteral(", extendMode=");
430 surfacePathPrefix.AppendInt(int32_t(region.GetExtendMode()));
432 surfacePathPrefix.AppendLiteral("]");
435 if (counter.Key().SVGContext()) {
436 const SVGImageContext& context = counter.Key().SVGContext().ref();
437 surfacePathPrefix.AppendLiteral(", svgContext:[ ");
438 if (context.GetViewportSize()) {
439 const CSSIntSize& size = context.GetViewportSize().ref();
440 surfacePathPrefix.AppendLiteral("viewport=(");
441 surfacePathPrefix.AppendInt(size.width);
442 surfacePathPrefix.AppendLiteral("x");
443 surfacePathPrefix.AppendInt(size.height);
444 surfacePathPrefix.AppendLiteral(") ");
446 if (context.GetPreserveAspectRatio()) {
447 nsAutoString aspect;
448 context.GetPreserveAspectRatio()->ToString(aspect);
449 surfacePathPrefix.AppendLiteral("preserveAspectRatio=(");
450 LossyAppendUTF16toASCII(aspect, surfacePathPrefix);
451 surfacePathPrefix.AppendLiteral(") ");
453 if (context.GetContextPaint()) {
454 const SVGEmbeddingContextPaint* paint = context.GetContextPaint();
455 surfacePathPrefix.AppendLiteral("contextPaint=(");
456 if (paint->GetFill()) {
457 surfacePathPrefix.AppendLiteral(" fill=");
458 surfacePathPrefix.AppendInt(paint->GetFill()->ToABGR(), 16);
460 if (paint->GetFillOpacity() != 1.0) {
461 surfacePathPrefix.AppendLiteral(" fillOpa=");
462 surfacePathPrefix.AppendFloat(paint->GetFillOpacity());
464 if (paint->GetStroke()) {
465 surfacePathPrefix.AppendLiteral(" stroke=");
466 surfacePathPrefix.AppendInt(paint->GetStroke()->ToABGR(), 16);
468 if (paint->GetStrokeOpacity() != 1.0) {
469 surfacePathPrefix.AppendLiteral(" strokeOpa=");
470 surfacePathPrefix.AppendFloat(paint->GetStrokeOpacity());
472 surfacePathPrefix.AppendLiteral(" ) ");
474 surfacePathPrefix.AppendLiteral("]");
477 surfacePathPrefix.AppendLiteral(")/");
479 ReportValues(aHandleReport, aData, surfacePathPrefix, counter.Values());
483 static void ReportTotal(nsIHandleReportCallback* aHandleReport,
484 nsISupports* aData, bool aExplicit,
485 const char* aPathPrefix, const char* aPathInfix,
486 const MemoryTotal& aTotal) {
487 nsAutoCString pathPrefix;
488 if (aExplicit) {
489 pathPrefix.AppendLiteral("explicit/");
491 pathPrefix.Append(aPathPrefix);
493 nsAutoCString rasterUsedPrefix(pathPrefix);
494 rasterUsedPrefix.AppendLiteral("/raster/used/");
495 rasterUsedPrefix.Append(aPathInfix);
496 ReportValues(aHandleReport, aData, rasterUsedPrefix, aTotal.UsedRaster());
498 nsAutoCString rasterUnusedPrefix(pathPrefix);
499 rasterUnusedPrefix.AppendLiteral("/raster/unused/");
500 rasterUnusedPrefix.Append(aPathInfix);
501 ReportValues(aHandleReport, aData, rasterUnusedPrefix,
502 aTotal.UnusedRaster());
504 nsAutoCString vectorUsedPrefix(pathPrefix);
505 vectorUsedPrefix.AppendLiteral("/vector/used/");
506 vectorUsedPrefix.Append(aPathInfix);
507 ReportValues(aHandleReport, aData, vectorUsedPrefix, aTotal.UsedVector());
509 nsAutoCString vectorUnusedPrefix(pathPrefix);
510 vectorUnusedPrefix.AppendLiteral("/vector/unused/");
511 vectorUnusedPrefix.Append(aPathInfix);
512 ReportValues(aHandleReport, aData, vectorUnusedPrefix,
513 aTotal.UnusedVector());
516 static void ReportValues(nsIHandleReportCallback* aHandleReport,
517 nsISupports* aData, const nsACString& aPathPrefix,
518 const MemoryCounter& aCounter) {
519 ReportSourceValue(aHandleReport, aData, aPathPrefix, aCounter);
521 ReportValue(aHandleReport, aData, KIND_HEAP, aPathPrefix, "decoded-heap",
522 "Decoded image data which is stored on the heap.",
523 aCounter.DecodedHeap());
525 ReportValue(aHandleReport, aData, KIND_NONHEAP, aPathPrefix,
526 "decoded-nonheap",
527 "Decoded image data which isn't stored on the heap.",
528 aCounter.DecodedNonHeap());
530 // We don't know for certain whether or not it is on the heap, so let's
531 // just report it as non-heap for reporting purposes.
532 ReportValue(aHandleReport, aData, KIND_NONHEAP, aPathPrefix,
533 "decoded-unknown",
534 "Decoded image data which is unknown to be on the heap or not.",
535 aCounter.DecodedUnknown());
538 static void ReportSourceValue(nsIHandleReportCallback* aHandleReport,
539 nsISupports* aData,
540 const nsACString& aPathPrefix,
541 const MemoryCounter& aCounter) {
542 ReportValue(aHandleReport, aData, KIND_HEAP, aPathPrefix, "source",
543 "Raster image source data and vector image documents.",
544 aCounter.Source());
547 static void ReportValue(nsIHandleReportCallback* aHandleReport,
548 nsISupports* aData, int32_t aKind,
549 const nsACString& aPathPrefix,
550 const char* aPathSuffix, const char* aDescription,
551 size_t aValue) {
552 if (aValue == 0) {
553 return;
556 nsAutoCString desc(aDescription);
557 nsAutoCString path(aPathPrefix);
558 path.Append(aPathSuffix);
560 aHandleReport->Callback(""_ns, path, aKind, UNITS_BYTES, aValue, desc,
561 aData);
564 static void RecordCounterForRequest(imgRequest* aRequest,
565 nsTArray<ImageMemoryCounter>* aArray,
566 bool aIsUsed) {
567 SizeOfState state(ImagesMallocSizeOf);
568 RefPtr<image::Image> image = aRequest->GetImage();
569 if (image) {
570 ImageMemoryCounter counter(aRequest, image, state, aIsUsed);
571 aArray->AppendElement(std::move(counter));
572 } else {
573 // We can at least record some information about the image from the
574 // request, and mark it as not knowing the image type yet.
575 ImageMemoryCounter counter(aRequest, state, aIsUsed);
576 aArray->AppendElement(std::move(counter));
581 NS_IMPL_ISUPPORTS(imgMemoryReporter, nsIMemoryReporter)
583 NS_IMPL_ISUPPORTS(nsProgressNotificationProxy, nsIProgressEventSink,
584 nsIChannelEventSink, nsIInterfaceRequestor)
586 NS_IMETHODIMP
587 nsProgressNotificationProxy::OnProgress(nsIRequest* request, int64_t progress,
588 int64_t progressMax) {
589 nsCOMPtr<nsILoadGroup> loadGroup;
590 request->GetLoadGroup(getter_AddRefs(loadGroup));
592 nsCOMPtr<nsIProgressEventSink> target;
593 NS_QueryNotificationCallbacks(mOriginalCallbacks, loadGroup,
594 NS_GET_IID(nsIProgressEventSink),
595 getter_AddRefs(target));
596 if (!target) {
597 return NS_OK;
599 return target->OnProgress(mImageRequest, progress, progressMax);
602 NS_IMETHODIMP
603 nsProgressNotificationProxy::OnStatus(nsIRequest* request, nsresult status,
604 const char16_t* statusArg) {
605 nsCOMPtr<nsILoadGroup> loadGroup;
606 request->GetLoadGroup(getter_AddRefs(loadGroup));
608 nsCOMPtr<nsIProgressEventSink> target;
609 NS_QueryNotificationCallbacks(mOriginalCallbacks, loadGroup,
610 NS_GET_IID(nsIProgressEventSink),
611 getter_AddRefs(target));
612 if (!target) {
613 return NS_OK;
615 return target->OnStatus(mImageRequest, status, statusArg);
618 NS_IMETHODIMP
619 nsProgressNotificationProxy::AsyncOnChannelRedirect(
620 nsIChannel* oldChannel, nsIChannel* newChannel, uint32_t flags,
621 nsIAsyncVerifyRedirectCallback* cb) {
622 // Tell the original original callbacks about it too
623 nsCOMPtr<nsILoadGroup> loadGroup;
624 newChannel->GetLoadGroup(getter_AddRefs(loadGroup));
625 nsCOMPtr<nsIChannelEventSink> target;
626 NS_QueryNotificationCallbacks(mOriginalCallbacks, loadGroup,
627 NS_GET_IID(nsIChannelEventSink),
628 getter_AddRefs(target));
629 if (!target) {
630 cb->OnRedirectVerifyCallback(NS_OK);
631 return NS_OK;
634 // Delegate to |target| if set, reusing |cb|
635 return target->AsyncOnChannelRedirect(oldChannel, newChannel, flags, cb);
638 NS_IMETHODIMP
639 nsProgressNotificationProxy::GetInterface(const nsIID& iid, void** result) {
640 if (iid.Equals(NS_GET_IID(nsIProgressEventSink))) {
641 *result = static_cast<nsIProgressEventSink*>(this);
642 NS_ADDREF_THIS();
643 return NS_OK;
645 if (iid.Equals(NS_GET_IID(nsIChannelEventSink))) {
646 *result = static_cast<nsIChannelEventSink*>(this);
647 NS_ADDREF_THIS();
648 return NS_OK;
650 if (mOriginalCallbacks) {
651 return mOriginalCallbacks->GetInterface(iid, result);
653 return NS_NOINTERFACE;
656 static void NewRequestAndEntry(bool aForcePrincipalCheckForCacheEntry,
657 imgLoader* aLoader, const ImageCacheKey& aKey,
658 imgRequest** aRequest, imgCacheEntry** aEntry) {
659 RefPtr<imgRequest> request = new imgRequest(aLoader, aKey);
660 RefPtr<imgCacheEntry> entry =
661 new imgCacheEntry(aLoader, request, aForcePrincipalCheckForCacheEntry);
662 aLoader->AddToUncachedImages(request);
663 request.forget(aRequest);
664 entry.forget(aEntry);
667 static bool ShouldRevalidateEntry(imgCacheEntry* aEntry, nsLoadFlags aFlags,
668 bool aHasExpired) {
669 if (aFlags & nsIRequest::LOAD_BYPASS_CACHE) {
670 return false;
672 if (aFlags & nsIRequest::VALIDATE_ALWAYS) {
673 return true;
675 if (aEntry->GetMustValidate()) {
676 return true;
678 if (aHasExpired) {
679 // The cache entry has expired... Determine whether the stale cache
680 // entry can be used without validation...
681 if (aFlags & (nsIRequest::LOAD_FROM_CACHE | nsIRequest::VALIDATE_NEVER |
682 nsIRequest::VALIDATE_ONCE_PER_SESSION)) {
683 // LOAD_FROM_CACHE, VALIDATE_NEVER and VALIDATE_ONCE_PER_SESSION allow
684 // stale cache entries to be used unless they have been explicitly marked
685 // to indicate that revalidation is necessary.
686 return false;
688 // Entry is expired, revalidate.
689 return true;
691 return false;
694 /* Call content policies on cached images that went through a redirect */
695 static bool ShouldLoadCachedImage(imgRequest* aImgRequest,
696 Document* aLoadingDocument,
697 nsIPrincipal* aTriggeringPrincipal,
698 nsContentPolicyType aPolicyType,
699 bool aSendCSPViolationReports) {
700 /* Call content policies on cached images - Bug 1082837
701 * Cached images are keyed off of the first uri in a redirect chain.
702 * Hence content policies don't get a chance to test the intermediate hops
703 * or the final destination. Here we test the final destination using
704 * mFinalURI off of the imgRequest and passing it into content policies.
705 * For Mixed Content Blocker, we do an additional check to determine if any
706 * of the intermediary hops went through an insecure redirect with the
707 * mHadInsecureRedirect flag
709 bool insecureRedirect = aImgRequest->HadInsecureRedirect();
710 nsCOMPtr<nsIURI> contentLocation;
711 aImgRequest->GetFinalURI(getter_AddRefs(contentLocation));
712 nsresult rv;
714 nsCOMPtr<nsIPrincipal> loadingPrincipal =
715 aLoadingDocument ? aLoadingDocument->NodePrincipal()
716 : aTriggeringPrincipal;
717 // If there is no context and also no triggeringPrincipal, then we use a fresh
718 // nullPrincipal as the loadingPrincipal because we can not create a loadinfo
719 // without a valid loadingPrincipal.
720 if (!loadingPrincipal) {
721 loadingPrincipal = NullPrincipal::CreateWithoutOriginAttributes();
724 nsCOMPtr<nsILoadInfo> secCheckLoadInfo = new LoadInfo(
725 loadingPrincipal, aTriggeringPrincipal, aLoadingDocument,
726 nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, aPolicyType);
728 secCheckLoadInfo->SetSendCSPViolationEvents(aSendCSPViolationReports);
730 int16_t decision = nsIContentPolicy::REJECT_REQUEST;
731 rv = NS_CheckContentLoadPolicy(contentLocation, secCheckLoadInfo,
732 ""_ns, // mime guess
733 &decision, nsContentUtils::GetContentPolicy());
734 if (NS_FAILED(rv) || !NS_CP_ACCEPTED(decision)) {
735 return false;
738 // We call all Content Policies above, but we also have to call mcb
739 // individually to check the intermediary redirect hops are secure.
740 if (insecureRedirect) {
741 // Bug 1314356: If the image ended up in the cache upgraded by HSTS and the
742 // page uses upgrade-inscure-requests it had an insecure redirect
743 // (http->https). We need to invalidate the image and reload it because
744 // mixed content blocker only bails if upgrade-insecure-requests is set on
745 // the doc and the resource load is http: which would result in an incorrect
746 // mixed content warning.
747 nsCOMPtr<nsIDocShell> docShell =
748 NS_CP_GetDocShellFromContext(ToSupports(aLoadingDocument));
749 if (docShell) {
750 Document* document = docShell->GetDocument();
751 if (document && document->GetUpgradeInsecureRequests(false)) {
752 return false;
756 if (!aTriggeringPrincipal || !aTriggeringPrincipal->IsSystemPrincipal()) {
757 // reset the decision for mixed content blocker check
758 decision = nsIContentPolicy::REJECT_REQUEST;
759 rv = nsMixedContentBlocker::ShouldLoad(insecureRedirect, contentLocation,
760 secCheckLoadInfo,
761 ""_ns, // mime guess
762 true, // aReportError
763 &decision);
764 if (NS_FAILED(rv) || !NS_CP_ACCEPTED(decision)) {
765 return false;
770 return true;
773 // Returns true if this request is compatible with the given CORS mode on the
774 // given loading principal, and false if the request may not be reused due
775 // to CORS.
776 static bool ValidateCORSMode(imgRequest* aRequest, bool aForcePrincipalCheck,
777 CORSMode aCORSMode,
778 nsIPrincipal* aTriggeringPrincipal) {
779 // If the entry's CORS mode doesn't match, or the CORS mode matches but the
780 // document principal isn't the same, we can't use this request.
781 if (aRequest->GetCORSMode() != aCORSMode) {
782 return false;
785 if (aRequest->GetCORSMode() != CORS_NONE || aForcePrincipalCheck) {
786 nsCOMPtr<nsIPrincipal> otherprincipal = aRequest->GetTriggeringPrincipal();
788 // If we previously had a principal, but we don't now, we can't use this
789 // request.
790 if (otherprincipal && !aTriggeringPrincipal) {
791 return false;
794 if (otherprincipal && aTriggeringPrincipal &&
795 !otherprincipal->Equals(aTriggeringPrincipal)) {
796 return false;
800 return true;
803 static bool ValidateSecurityInfo(imgRequest* aRequest,
804 bool aForcePrincipalCheck, CORSMode aCORSMode,
805 nsIPrincipal* aTriggeringPrincipal,
806 Document* aLoadingDocument,
807 nsContentPolicyType aPolicyType) {
808 if (!ValidateCORSMode(aRequest, aForcePrincipalCheck, aCORSMode,
809 aTriggeringPrincipal)) {
810 return false;
812 // Content Policy Check on Cached Images
813 return ShouldLoadCachedImage(aRequest, aLoadingDocument, aTriggeringPrincipal,
814 aPolicyType,
815 /* aSendCSPViolationReports */ false);
818 static nsresult NewImageChannel(
819 nsIChannel** aResult,
820 // If aForcePrincipalCheckForCacheEntry is true, then we will
821 // force a principal check even when not using CORS before
822 // assuming we have a cache hit on a cache entry that we
823 // create for this channel. This is an out param that should
824 // be set to true if this channel ends up depending on
825 // aTriggeringPrincipal and false otherwise.
826 bool* aForcePrincipalCheckForCacheEntry, nsIURI* aURI,
827 nsIURI* aInitialDocumentURI, CORSMode aCORSMode,
828 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
829 nsLoadFlags aLoadFlags, nsContentPolicyType aPolicyType,
830 nsIPrincipal* aTriggeringPrincipal, nsINode* aRequestingNode,
831 bool aRespectPrivacy) {
832 MOZ_ASSERT(aResult);
834 nsresult rv;
835 nsCOMPtr<nsIHttpChannel> newHttpChannel;
837 nsCOMPtr<nsIInterfaceRequestor> callbacks;
839 if (aLoadGroup) {
840 // Get the notification callbacks from the load group for the new channel.
842 // XXX: This is not exactly correct, because the network request could be
843 // referenced by multiple windows... However, the new channel needs
844 // something. So, using the 'first' notification callbacks is better
845 // than nothing...
847 aLoadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks));
850 // Pass in a nullptr loadgroup because this is the underlying network
851 // request. This request may be referenced by several proxy image requests
852 // (possibly in different documents).
853 // If all of the proxy requests are canceled then this request should be
854 // canceled too.
857 nsSecurityFlags securityFlags =
858 aCORSMode == CORS_NONE
859 ? nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
860 : nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT;
861 if (aCORSMode == CORS_ANONYMOUS) {
862 securityFlags |= nsILoadInfo::SEC_COOKIES_SAME_ORIGIN;
863 } else if (aCORSMode == CORS_USE_CREDENTIALS) {
864 securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
866 securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
868 // Note we are calling NS_NewChannelWithTriggeringPrincipal() here with a
869 // node and a principal. This is for things like background images that are
870 // specified by user stylesheets, where the document is being styled, but
871 // the principal is that of the user stylesheet.
872 if (aRequestingNode && aTriggeringPrincipal) {
873 rv = NS_NewChannelWithTriggeringPrincipal(aResult, aURI, aRequestingNode,
874 aTriggeringPrincipal,
875 securityFlags, aPolicyType,
876 nullptr, // PerformanceStorage
877 nullptr, // loadGroup
878 callbacks, aLoadFlags);
880 if (NS_FAILED(rv)) {
881 return rv;
884 if (aPolicyType == nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON) {
885 // If this is a favicon loading, we will use the originAttributes from the
886 // triggeringPrincipal as the channel's originAttributes. This allows the
887 // favicon loading from XUL will use the correct originAttributes.
889 nsCOMPtr<nsILoadInfo> loadInfo = (*aResult)->LoadInfo();
890 rv = loadInfo->SetOriginAttributes(
891 aTriggeringPrincipal->OriginAttributesRef());
893 } else {
894 // either we are loading something inside a document, in which case
895 // we should always have a requestingNode, or we are loading something
896 // outside a document, in which case the triggeringPrincipal and
897 // triggeringPrincipal should always be the systemPrincipal.
898 // However, there are exceptions: one is Notifications which create a
899 // channel in the parent process in which case we can't get a
900 // requestingNode.
901 rv = NS_NewChannel(aResult, aURI, nsContentUtils::GetSystemPrincipal(),
902 securityFlags, aPolicyType,
903 nullptr, // nsICookieJarSettings
904 nullptr, // PerformanceStorage
905 nullptr, // loadGroup
906 callbacks, aLoadFlags);
908 if (NS_FAILED(rv)) {
909 return rv;
912 // Use the OriginAttributes from the loading principal, if one is available,
913 // and adjust the private browsing ID based on what kind of load the caller
914 // has asked us to perform.
915 OriginAttributes attrs;
916 if (aTriggeringPrincipal) {
917 attrs = aTriggeringPrincipal->OriginAttributesRef();
919 attrs.mPrivateBrowsingId = aRespectPrivacy ? 1 : 0;
921 nsCOMPtr<nsILoadInfo> loadInfo = (*aResult)->LoadInfo();
922 rv = loadInfo->SetOriginAttributes(attrs);
925 if (NS_FAILED(rv)) {
926 return rv;
929 // only inherit if we have a principal
930 *aForcePrincipalCheckForCacheEntry =
931 aTriggeringPrincipal && nsContentUtils::ChannelShouldInheritPrincipal(
932 aTriggeringPrincipal, aURI,
933 /* aInheritForAboutBlank */ false,
934 /* aForceInherit */ false);
936 // Initialize HTTP-specific attributes
937 newHttpChannel = do_QueryInterface(*aResult);
938 if (newHttpChannel) {
939 nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
940 do_QueryInterface(newHttpChannel);
941 NS_ENSURE_TRUE(httpChannelInternal, NS_ERROR_UNEXPECTED);
942 rv = httpChannelInternal->SetDocumentURI(aInitialDocumentURI);
943 MOZ_ASSERT(NS_SUCCEEDED(rv));
944 if (aReferrerInfo) {
945 DebugOnly<nsresult> rv = newHttpChannel->SetReferrerInfo(aReferrerInfo);
946 MOZ_ASSERT(NS_SUCCEEDED(rv));
950 // Image channels are loaded by default with reduced priority.
951 nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(*aResult);
952 if (p) {
953 uint32_t priority = nsISupportsPriority::PRIORITY_LOW;
955 if (aLoadFlags & nsIRequest::LOAD_BACKGROUND) {
956 ++priority; // further reduce priority for background loads
959 p->AdjustPriority(priority);
962 // Create a new loadgroup for this new channel, using the old group as
963 // the parent. The indirection keeps the channel insulated from cancels,
964 // but does allow a way for this revalidation to be associated with at
965 // least one base load group for scheduling/caching purposes.
967 nsCOMPtr<nsILoadGroup> loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
968 nsCOMPtr<nsILoadGroupChild> childLoadGroup = do_QueryInterface(loadGroup);
969 if (childLoadGroup) {
970 childLoadGroup->SetParentLoadGroup(aLoadGroup);
972 (*aResult)->SetLoadGroup(loadGroup);
974 return NS_OK;
977 static uint32_t SecondsFromPRTime(PRTime aTime) {
978 return nsContentUtils::SecondsFromPRTime(aTime);
981 /* static */
982 imgCacheEntry::imgCacheEntry(imgLoader* loader, imgRequest* request,
983 bool forcePrincipalCheck)
984 : mLoader(loader),
985 mRequest(request),
986 mDataSize(0),
987 mTouchedTime(SecondsFromPRTime(PR_Now())),
988 mLoadTime(SecondsFromPRTime(PR_Now())),
989 mExpiryTime(0),
990 mMustValidate(false),
991 // We start off as evicted so we don't try to update the cache.
992 // PutIntoCache will set this to false.
993 mEvicted(true),
994 mHasNoProxies(true),
995 mForcePrincipalCheck(forcePrincipalCheck) {}
997 imgCacheEntry::~imgCacheEntry() {
998 LOG_FUNC(gImgLog, "imgCacheEntry::~imgCacheEntry()");
1001 void imgCacheEntry::Touch(bool updateTime /* = true */) {
1002 LOG_SCOPE(gImgLog, "imgCacheEntry::Touch");
1004 if (updateTime) {
1005 mTouchedTime = SecondsFromPRTime(PR_Now());
1008 UpdateCache();
1011 void imgCacheEntry::UpdateCache(int32_t diff /* = 0 */) {
1012 // Don't update the cache if we've been removed from it or it doesn't care
1013 // about our size or usage.
1014 if (!Evicted() && HasNoProxies()) {
1015 mLoader->CacheEntriesChanged(mRequest->IsChrome(), diff);
1019 void imgCacheEntry::UpdateLoadTime() {
1020 mLoadTime = SecondsFromPRTime(PR_Now());
1023 void imgCacheEntry::SetHasNoProxies(bool hasNoProxies) {
1024 if (MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
1025 if (hasNoProxies) {
1026 LOG_FUNC_WITH_PARAM(gImgLog, "imgCacheEntry::SetHasNoProxies true", "uri",
1027 mRequest->CacheKey().URI());
1028 } else {
1029 LOG_FUNC_WITH_PARAM(gImgLog, "imgCacheEntry::SetHasNoProxies false",
1030 "uri", mRequest->CacheKey().URI());
1034 mHasNoProxies = hasNoProxies;
1037 imgCacheQueue::imgCacheQueue() : mDirty(false), mSize(0) {}
1039 void imgCacheQueue::UpdateSize(int32_t diff) { mSize += diff; }
1041 uint32_t imgCacheQueue::GetSize() const { return mSize; }
1043 void imgCacheQueue::Remove(imgCacheEntry* entry) {
1044 uint64_t index = mQueue.IndexOf(entry);
1045 if (index == queueContainer::NoIndex) {
1046 return;
1049 mSize -= mQueue[index]->GetDataSize();
1051 // If the queue is clean and this is the first entry,
1052 // then we can efficiently remove the entry without
1053 // dirtying the sort order.
1054 if (!IsDirty() && index == 0) {
1055 std::pop_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
1056 mQueue.RemoveLastElement();
1057 return;
1060 // Remove from the middle of the list. This potentially
1061 // breaks the binary heap sort order.
1062 mQueue.RemoveElementAt(index);
1064 // If we only have one entry or the queue is empty, though,
1065 // then the sort order is still effectively good. Simply
1066 // refresh the list to clear the dirty flag.
1067 if (mQueue.Length() <= 1) {
1068 Refresh();
1069 return;
1072 // Otherwise we must mark the queue dirty and potentially
1073 // trigger an expensive sort later.
1074 MarkDirty();
1077 void imgCacheQueue::Push(imgCacheEntry* entry) {
1078 mSize += entry->GetDataSize();
1080 RefPtr<imgCacheEntry> refptr(entry);
1081 mQueue.AppendElement(std::move(refptr));
1082 // If we're not dirty already, then we can efficiently add this to the
1083 // binary heap immediately. This is only O(log n).
1084 if (!IsDirty()) {
1085 std::push_heap(mQueue.begin(), mQueue.end(),
1086 imgLoader::CompareCacheEntries);
1090 already_AddRefed<imgCacheEntry> imgCacheQueue::Pop() {
1091 if (mQueue.IsEmpty()) {
1092 return nullptr;
1094 if (IsDirty()) {
1095 Refresh();
1098 std::pop_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
1099 RefPtr<imgCacheEntry> entry = mQueue.PopLastElement();
1101 mSize -= entry->GetDataSize();
1102 return entry.forget();
1105 void imgCacheQueue::Refresh() {
1106 // Resort the list. This is an O(3 * n) operation and best avoided
1107 // if possible.
1108 std::make_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
1109 mDirty = false;
1112 void imgCacheQueue::MarkDirty() { mDirty = true; }
1114 bool imgCacheQueue::IsDirty() { return mDirty; }
1116 uint32_t imgCacheQueue::GetNumElements() const { return mQueue.Length(); }
1118 bool imgCacheQueue::Contains(imgCacheEntry* aEntry) const {
1119 return mQueue.Contains(aEntry);
1122 imgCacheQueue::iterator imgCacheQueue::begin() { return mQueue.begin(); }
1124 imgCacheQueue::const_iterator imgCacheQueue::begin() const {
1125 return mQueue.begin();
1128 imgCacheQueue::iterator imgCacheQueue::end() { return mQueue.end(); }
1130 imgCacheQueue::const_iterator imgCacheQueue::end() const {
1131 return mQueue.end();
1134 nsresult imgLoader::CreateNewProxyForRequest(
1135 imgRequest* aRequest, nsIURI* aURI, nsILoadGroup* aLoadGroup,
1136 Document* aLoadingDocument, imgINotificationObserver* aObserver,
1137 nsLoadFlags aLoadFlags, imgRequestProxy** _retval) {
1138 LOG_SCOPE_WITH_PARAM(gImgLog, "imgLoader::CreateNewProxyForRequest",
1139 "imgRequest", aRequest);
1141 /* XXX If we move decoding onto separate threads, we should save off the
1142 calling thread here and pass it off to |proxyRequest| so that it call
1143 proxy calls to |aObserver|.
1146 RefPtr<imgRequestProxy> proxyRequest = new imgRequestProxy();
1148 /* It is important to call |SetLoadFlags()| before calling |Init()| because
1149 |Init()| adds the request to the loadgroup.
1151 proxyRequest->SetLoadFlags(aLoadFlags);
1153 // init adds itself to imgRequest's list of observers
1154 nsresult rv = proxyRequest->Init(aRequest, aLoadGroup, aLoadingDocument, aURI,
1155 aObserver);
1156 if (NS_WARN_IF(NS_FAILED(rv))) {
1157 return rv;
1160 proxyRequest.forget(_retval);
1161 return NS_OK;
1164 class imgCacheExpirationTracker final
1165 : public nsExpirationTracker<imgCacheEntry, 3> {
1166 enum { TIMEOUT_SECONDS = 10 };
1168 public:
1169 imgCacheExpirationTracker();
1171 protected:
1172 void NotifyExpired(imgCacheEntry* entry) override;
1175 imgCacheExpirationTracker::imgCacheExpirationTracker()
1176 : nsExpirationTracker<imgCacheEntry, 3>(TIMEOUT_SECONDS * 1000,
1177 "imgCacheExpirationTracker") {}
1179 void imgCacheExpirationTracker::NotifyExpired(imgCacheEntry* entry) {
1180 // Hold on to a reference to this entry, because the expiration tracker
1181 // mechanism doesn't.
1182 RefPtr<imgCacheEntry> kungFuDeathGrip(entry);
1184 if (MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
1185 RefPtr<imgRequest> req = entry->GetRequest();
1186 if (req) {
1187 LOG_FUNC_WITH_PARAM(gImgLog, "imgCacheExpirationTracker::NotifyExpired",
1188 "entry", req->CacheKey().URI());
1192 // We can be called multiple times on the same entry. Don't do work multiple
1193 // times.
1194 if (!entry->Evicted()) {
1195 entry->Loader()->RemoveFromCache(entry);
1198 entry->Loader()->VerifyCacheSizes();
1201 ///////////////////////////////////////////////////////////////////////////////
1202 // imgLoader
1203 ///////////////////////////////////////////////////////////////////////////////
1205 double imgLoader::sCacheTimeWeight;
1206 uint32_t imgLoader::sCacheMaxSize;
1207 imgMemoryReporter* imgLoader::sMemReporter;
1209 NS_IMPL_ISUPPORTS(imgLoader, imgILoader, nsIContentSniffer, imgICache,
1210 nsISupportsWeakReference, nsIObserver)
1212 static imgLoader* gNormalLoader = nullptr;
1213 static imgLoader* gPrivateBrowsingLoader = nullptr;
1215 /* static */
1216 already_AddRefed<imgLoader> imgLoader::CreateImageLoader() {
1217 // In some cases, such as xpctests, XPCOM modules are not automatically
1218 // initialized. We need to make sure that our module is initialized before
1219 // we hand out imgLoader instances and code starts using them.
1220 mozilla::image::EnsureModuleInitialized();
1222 RefPtr<imgLoader> loader = new imgLoader();
1223 loader->Init();
1225 return loader.forget();
1228 imgLoader* imgLoader::NormalLoader() {
1229 if (!gNormalLoader) {
1230 gNormalLoader = CreateImageLoader().take();
1232 return gNormalLoader;
1235 imgLoader* imgLoader::PrivateBrowsingLoader() {
1236 if (!gPrivateBrowsingLoader) {
1237 gPrivateBrowsingLoader = CreateImageLoader().take();
1238 gPrivateBrowsingLoader->RespectPrivacyNotifications();
1240 return gPrivateBrowsingLoader;
1243 imgLoader::imgLoader()
1244 : mUncachedImagesMutex("imgLoader::UncachedImages"),
1245 mRespectPrivacy(false) {
1246 sMemReporter->AddRef();
1247 sMemReporter->RegisterLoader(this);
1250 imgLoader::~imgLoader() {
1251 ClearChromeImageCache();
1252 ClearImageCache();
1254 // If there are any of our imgRequest's left they are in the uncached
1255 // images set, so clear their pointer to us.
1256 MutexAutoLock lock(mUncachedImagesMutex);
1257 for (RefPtr<imgRequest> req : mUncachedImages) {
1258 req->ClearLoader();
1261 sMemReporter->UnregisterLoader(this);
1262 sMemReporter->Release();
1265 void imgLoader::VerifyCacheSizes() {
1266 #ifdef DEBUG
1267 if (!mCacheTracker) {
1268 return;
1271 uint32_t cachesize = mCache.Count() + mChromeCache.Count();
1272 uint32_t queuesize =
1273 mCacheQueue.GetNumElements() + mChromeCacheQueue.GetNumElements();
1274 uint32_t trackersize = 0;
1275 for (nsExpirationTracker<imgCacheEntry, 3>::Iterator it(mCacheTracker.get());
1276 it.Next();) {
1277 trackersize++;
1279 MOZ_ASSERT(queuesize == trackersize, "Queue and tracker sizes out of sync!");
1280 MOZ_ASSERT(queuesize <= cachesize, "Queue has more elements than cache!");
1281 #endif
1284 imgLoader::imgCacheTable& imgLoader::GetCache(bool aForChrome) {
1285 return aForChrome ? mChromeCache : mCache;
1288 imgLoader::imgCacheTable& imgLoader::GetCache(const ImageCacheKey& aKey) {
1289 return GetCache(aKey.IsChrome());
1292 imgCacheQueue& imgLoader::GetCacheQueue(bool aForChrome) {
1293 return aForChrome ? mChromeCacheQueue : mCacheQueue;
1296 imgCacheQueue& imgLoader::GetCacheQueue(const ImageCacheKey& aKey) {
1297 return GetCacheQueue(aKey.IsChrome());
1300 void imgLoader::GlobalInit() {
1301 sCacheTimeWeight = StaticPrefs::image_cache_timeweight_AtStartup() / 1000.0;
1302 int32_t cachesize = StaticPrefs::image_cache_size_AtStartup();
1303 sCacheMaxSize = cachesize > 0 ? cachesize : 0;
1305 sMemReporter = new imgMemoryReporter();
1306 RegisterStrongAsyncMemoryReporter(sMemReporter);
1307 RegisterImagesContentUsedUncompressedDistinguishedAmount(
1308 imgMemoryReporter::ImagesContentUsedUncompressedDistinguishedAmount);
1311 void imgLoader::ShutdownMemoryReporter() {
1312 UnregisterImagesContentUsedUncompressedDistinguishedAmount();
1313 UnregisterStrongMemoryReporter(sMemReporter);
1316 nsresult imgLoader::InitCache() {
1317 nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
1318 if (!os) {
1319 return NS_ERROR_FAILURE;
1322 os->AddObserver(this, "memory-pressure", false);
1323 os->AddObserver(this, "chrome-flush-caches", false);
1324 os->AddObserver(this, "last-pb-context-exited", false);
1325 os->AddObserver(this, "profile-before-change", false);
1326 os->AddObserver(this, "xpcom-shutdown", false);
1328 mCacheTracker = MakeUnique<imgCacheExpirationTracker>();
1330 return NS_OK;
1333 nsresult imgLoader::Init() {
1334 InitCache();
1336 return NS_OK;
1339 NS_IMETHODIMP
1340 imgLoader::RespectPrivacyNotifications() {
1341 mRespectPrivacy = true;
1342 return NS_OK;
1345 NS_IMETHODIMP
1346 imgLoader::Observe(nsISupports* aSubject, const char* aTopic,
1347 const char16_t* aData) {
1348 if (strcmp(aTopic, "memory-pressure") == 0) {
1349 MinimizeCaches();
1350 } else if (strcmp(aTopic, "chrome-flush-caches") == 0) {
1351 MinimizeCaches();
1352 ClearChromeImageCache();
1353 } else if (strcmp(aTopic, "last-pb-context-exited") == 0) {
1354 if (mRespectPrivacy) {
1355 ClearImageCache();
1356 ClearChromeImageCache();
1358 } else if (strcmp(aTopic, "profile-before-change") == 0) {
1359 mCacheTracker = nullptr;
1360 } else if (strcmp(aTopic, "xpcom-shutdown") == 0) {
1361 mCacheTracker = nullptr;
1362 ShutdownMemoryReporter();
1364 } else {
1365 // (Nothing else should bring us here)
1366 MOZ_ASSERT(0, "Invalid topic received");
1369 return NS_OK;
1372 NS_IMETHODIMP
1373 imgLoader::ClearCache(bool chrome) {
1374 if (XRE_IsParentProcess()) {
1375 bool privateLoader = this == gPrivateBrowsingLoader;
1376 for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
1377 Unused << cp->SendClearImageCache(privateLoader, chrome);
1381 if (chrome) {
1382 return ClearChromeImageCache();
1384 return ClearImageCache();
1387 NS_IMETHODIMP
1388 imgLoader::RemoveEntriesFromPrincipalInAllProcesses(nsIPrincipal* aPrincipal) {
1389 if (!XRE_IsParentProcess()) {
1390 return NS_ERROR_NOT_AVAILABLE;
1393 for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
1394 Unused << cp->SendClearImageCacheFromPrincipal(aPrincipal);
1397 imgLoader* loader;
1398 if (aPrincipal->OriginAttributesRef().mPrivateBrowsingId ==
1399 nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID) {
1400 loader = imgLoader::NormalLoader();
1401 } else {
1402 loader = imgLoader::PrivateBrowsingLoader();
1405 return loader->RemoveEntriesInternal(aPrincipal, nullptr);
1408 NS_IMETHODIMP
1409 imgLoader::RemoveEntriesFromBaseDomainInAllProcesses(
1410 const nsACString& aBaseDomain) {
1411 if (!XRE_IsParentProcess()) {
1412 return NS_ERROR_NOT_AVAILABLE;
1415 for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
1416 Unused << cp->SendClearImageCacheFromBaseDomain(nsCString(aBaseDomain));
1419 return RemoveEntriesInternal(nullptr, &aBaseDomain);
1422 nsresult imgLoader::RemoveEntriesInternal(nsIPrincipal* aPrincipal,
1423 const nsACString* aBaseDomain) {
1424 // Can only clear by either principal or base domain.
1425 if ((!aPrincipal && !aBaseDomain) || (aPrincipal && aBaseDomain)) {
1426 return NS_ERROR_INVALID_ARG;
1429 nsAutoString origin;
1430 if (aPrincipal) {
1431 nsresult rv = nsContentUtils::GetUTFOrigin(aPrincipal, origin);
1432 if (NS_WARN_IF(NS_FAILED(rv))) {
1433 return rv;
1437 nsCOMPtr<nsIEffectiveTLDService> tldService;
1438 AutoTArray<RefPtr<imgCacheEntry>, 128> entriesToBeRemoved;
1440 // For base domain we only clear the non-chrome cache.
1441 imgCacheTable& cache =
1442 GetCache(aPrincipal && aPrincipal->IsSystemPrincipal());
1443 for (const auto& entry : cache) {
1444 const auto& key = entry.GetKey();
1446 const bool shouldRemove = [&] {
1447 if (aPrincipal) {
1448 if (key.OriginAttributesRef() !=
1449 BasePrincipal::Cast(aPrincipal)->OriginAttributesRef()) {
1450 return false;
1453 nsAutoString imageOrigin;
1454 nsresult rv = nsContentUtils::GetUTFOrigin(key.URI(), imageOrigin);
1455 if (NS_WARN_IF(NS_FAILED(rv))) {
1456 return false;
1459 return imageOrigin == origin;
1462 if (!aBaseDomain) {
1463 return false;
1465 // Clear by baseDomain.
1466 nsAutoCString host;
1467 nsresult rv = key.URI()->GetHost(host);
1468 if (NS_FAILED(rv) || host.IsEmpty()) {
1469 return false;
1472 if (!tldService) {
1473 tldService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
1475 if (NS_WARN_IF(!tldService)) {
1476 return false;
1479 bool hasRootDomain = false;
1480 rv = tldService->HasRootDomain(host, *aBaseDomain, &hasRootDomain);
1481 if (NS_SUCCEEDED(rv) && hasRootDomain) {
1482 return true;
1485 // If we don't get a direct base domain match, also check for cache of
1486 // third parties partitioned under aBaseDomain.
1488 // The isolation key is either just the base domain, or an origin suffix
1489 // which contains the partitionKey holding the baseDomain.
1491 if (key.IsolationKeyRef().Equals(*aBaseDomain)) {
1492 return true;
1495 // The isolation key does not match the given base domain. It may be an
1496 // origin suffix. Parse it into origin attributes.
1497 OriginAttributes attrs;
1498 if (!attrs.PopulateFromSuffix(key.IsolationKeyRef())) {
1499 // Key is not an origin suffix.
1500 return false;
1503 return StoragePrincipalHelper::PartitionKeyHasBaseDomain(
1504 attrs.mPartitionKey, *aBaseDomain);
1505 }();
1507 if (shouldRemove) {
1508 entriesToBeRemoved.AppendElement(entry.GetData());
1512 for (auto& entry : entriesToBeRemoved) {
1513 if (!RemoveFromCache(entry)) {
1514 NS_WARNING(
1515 "Couldn't remove an entry from the cache in "
1516 "RemoveEntriesInternal()\n");
1520 return NS_OK;
1523 NS_IMETHODIMP
1524 imgLoader::RemoveEntry(nsIURI* aURI, Document* aDoc) {
1525 if (aURI) {
1526 OriginAttributes attrs;
1527 if (aDoc) {
1528 nsCOMPtr<nsIPrincipal> principal = aDoc->NodePrincipal();
1529 if (principal) {
1530 attrs = principal->OriginAttributesRef();
1534 ImageCacheKey key(aURI, attrs, aDoc);
1535 if (RemoveFromCache(key)) {
1536 return NS_OK;
1539 return NS_ERROR_NOT_AVAILABLE;
1542 NS_IMETHODIMP
1543 imgLoader::FindEntryProperties(nsIURI* uri, Document* aDoc,
1544 nsIProperties** _retval) {
1545 *_retval = nullptr;
1547 OriginAttributes attrs;
1548 if (aDoc) {
1549 nsCOMPtr<nsIPrincipal> principal = aDoc->NodePrincipal();
1550 if (principal) {
1551 attrs = principal->OriginAttributesRef();
1555 ImageCacheKey key(uri, attrs, aDoc);
1556 imgCacheTable& cache = GetCache(key);
1558 RefPtr<imgCacheEntry> entry;
1559 if (cache.Get(key, getter_AddRefs(entry)) && entry) {
1560 if (mCacheTracker && entry->HasNoProxies()) {
1561 mCacheTracker->MarkUsed(entry);
1564 RefPtr<imgRequest> request = entry->GetRequest();
1565 if (request) {
1566 nsCOMPtr<nsIProperties> properties = request->Properties();
1567 properties.forget(_retval);
1571 return NS_OK;
1574 NS_IMETHODIMP_(void)
1575 imgLoader::ClearCacheForControlledDocument(Document* aDoc) {
1576 MOZ_ASSERT(aDoc);
1577 AutoTArray<RefPtr<imgCacheEntry>, 128> entriesToBeRemoved;
1578 imgCacheTable& cache = GetCache(false);
1579 for (const auto& entry : cache) {
1580 const auto& key = entry.GetKey();
1581 if (key.ControlledDocument() == aDoc) {
1582 entriesToBeRemoved.AppendElement(entry.GetData());
1585 for (auto& entry : entriesToBeRemoved) {
1586 if (!RemoveFromCache(entry)) {
1587 NS_WARNING(
1588 "Couldn't remove an entry from the cache in "
1589 "ClearCacheForControlledDocument()\n");
1594 void imgLoader::Shutdown() {
1595 NS_IF_RELEASE(gNormalLoader);
1596 gNormalLoader = nullptr;
1597 NS_IF_RELEASE(gPrivateBrowsingLoader);
1598 gPrivateBrowsingLoader = nullptr;
1601 nsresult imgLoader::ClearChromeImageCache() {
1602 return EvictEntries(mChromeCache);
1605 nsresult imgLoader::ClearImageCache() { return EvictEntries(mCache); }
1607 void imgLoader::MinimizeCaches() {
1608 EvictEntries(mCacheQueue);
1609 EvictEntries(mChromeCacheQueue);
1612 bool imgLoader::PutIntoCache(const ImageCacheKey& aKey, imgCacheEntry* entry) {
1613 imgCacheTable& cache = GetCache(aKey);
1615 LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::PutIntoCache", "uri",
1616 aKey.URI());
1618 // Check to see if this request already exists in the cache. If so, we'll
1619 // replace the old version.
1620 RefPtr<imgCacheEntry> tmpCacheEntry;
1621 if (cache.Get(aKey, getter_AddRefs(tmpCacheEntry)) && tmpCacheEntry) {
1622 MOZ_LOG(
1623 gImgLog, LogLevel::Debug,
1624 ("[this=%p] imgLoader::PutIntoCache -- Element already in the cache",
1625 nullptr));
1626 RefPtr<imgRequest> tmpRequest = tmpCacheEntry->GetRequest();
1628 // If it already exists, and we're putting the same key into the cache, we
1629 // should remove the old version.
1630 MOZ_LOG(gImgLog, LogLevel::Debug,
1631 ("[this=%p] imgLoader::PutIntoCache -- Replacing cached element",
1632 nullptr));
1634 RemoveFromCache(aKey);
1635 } else {
1636 MOZ_LOG(gImgLog, LogLevel::Debug,
1637 ("[this=%p] imgLoader::PutIntoCache --"
1638 " Element NOT already in the cache",
1639 nullptr));
1642 cache.InsertOrUpdate(aKey, RefPtr{entry});
1644 // We can be called to resurrect an evicted entry.
1645 if (entry->Evicted()) {
1646 entry->SetEvicted(false);
1649 // If we're resurrecting an entry with no proxies, put it back in the
1650 // tracker and queue.
1651 if (entry->HasNoProxies()) {
1652 nsresult addrv = NS_OK;
1654 if (mCacheTracker) {
1655 addrv = mCacheTracker->AddObject(entry);
1658 if (NS_SUCCEEDED(addrv)) {
1659 imgCacheQueue& queue = GetCacheQueue(aKey);
1660 queue.Push(entry);
1664 RefPtr<imgRequest> request = entry->GetRequest();
1665 request->SetIsInCache(true);
1666 RemoveFromUncachedImages(request);
1668 return true;
1671 bool imgLoader::SetHasNoProxies(imgRequest* aRequest, imgCacheEntry* aEntry) {
1672 LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::SetHasNoProxies", "uri",
1673 aRequest->CacheKey().URI());
1675 aEntry->SetHasNoProxies(true);
1677 if (aEntry->Evicted()) {
1678 return false;
1681 imgCacheQueue& queue = GetCacheQueue(aRequest->IsChrome());
1683 nsresult addrv = NS_OK;
1685 if (mCacheTracker) {
1686 addrv = mCacheTracker->AddObject(aEntry);
1689 if (NS_SUCCEEDED(addrv)) {
1690 queue.Push(aEntry);
1693 imgCacheTable& cache = GetCache(aRequest->IsChrome());
1694 CheckCacheLimits(cache, queue);
1696 return true;
1699 bool imgLoader::SetHasProxies(imgRequest* aRequest) {
1700 VerifyCacheSizes();
1702 const ImageCacheKey& key = aRequest->CacheKey();
1703 imgCacheTable& cache = GetCache(key);
1705 LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::SetHasProxies", "uri",
1706 key.URI());
1708 RefPtr<imgCacheEntry> entry;
1709 if (cache.Get(key, getter_AddRefs(entry)) && entry) {
1710 // Make sure the cache entry is for the right request
1711 RefPtr<imgRequest> entryRequest = entry->GetRequest();
1712 if (entryRequest == aRequest && entry->HasNoProxies()) {
1713 imgCacheQueue& queue = GetCacheQueue(key);
1714 queue.Remove(entry);
1716 if (mCacheTracker) {
1717 mCacheTracker->RemoveObject(entry);
1720 entry->SetHasNoProxies(false);
1722 return true;
1726 return false;
1729 void imgLoader::CacheEntriesChanged(bool aForChrome,
1730 int32_t aSizeDiff /* = 0 */) {
1731 imgCacheQueue& queue = GetCacheQueue(aForChrome);
1732 // We only need to dirty the queue if there is any sorting
1733 // taking place. Empty or single-entry lists can't become
1734 // dirty.
1735 if (queue.GetNumElements() > 1) {
1736 queue.MarkDirty();
1738 queue.UpdateSize(aSizeDiff);
1741 void imgLoader::CheckCacheLimits(imgCacheTable& cache, imgCacheQueue& queue) {
1742 if (queue.GetNumElements() == 0) {
1743 NS_ASSERTION(queue.GetSize() == 0,
1744 "imgLoader::CheckCacheLimits -- incorrect cache size");
1747 // Remove entries from the cache until we're back at our desired max size.
1748 while (queue.GetSize() > sCacheMaxSize) {
1749 // Remove the first entry in the queue.
1750 RefPtr<imgCacheEntry> entry(queue.Pop());
1752 NS_ASSERTION(entry, "imgLoader::CheckCacheLimits -- NULL entry pointer");
1754 if (MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
1755 RefPtr<imgRequest> req = entry->GetRequest();
1756 if (req) {
1757 LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::CheckCacheLimits",
1758 "entry", req->CacheKey().URI());
1762 if (entry) {
1763 // We just popped this entry from the queue, so pass AlreadyRemoved
1764 // to avoid searching the queue again in RemoveFromCache.
1765 RemoveFromCache(entry, QueueState::AlreadyRemoved);
1770 bool imgLoader::ValidateRequestWithNewChannel(
1771 imgRequest* request, nsIURI* aURI, nsIURI* aInitialDocumentURI,
1772 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
1773 imgINotificationObserver* aObserver, Document* aLoadingDocument,
1774 uint64_t aInnerWindowId, nsLoadFlags aLoadFlags,
1775 nsContentPolicyType aLoadPolicyType, imgRequestProxy** aProxyRequest,
1776 nsIPrincipal* aTriggeringPrincipal, CORSMode aCORSMode, bool aLinkPreload,
1777 bool* aNewChannelCreated) {
1778 // now we need to insert a new channel request object in between the real
1779 // request and the proxy that basically delays loading the image until it
1780 // gets a 304 or figures out that this needs to be a new request
1782 nsresult rv;
1784 // If we're currently in the middle of validating this request, just hand
1785 // back a proxy to it; the required work will be done for us.
1786 if (imgCacheValidator* validator = request->GetValidator()) {
1787 rv = CreateNewProxyForRequest(request, aURI, aLoadGroup, aLoadingDocument,
1788 aObserver, aLoadFlags, aProxyRequest);
1789 if (NS_FAILED(rv)) {
1790 return false;
1793 if (*aProxyRequest) {
1794 imgRequestProxy* proxy = static_cast<imgRequestProxy*>(*aProxyRequest);
1796 // We will send notifications from imgCacheValidator::OnStartRequest().
1797 // In the mean time, we must defer notifications because we are added to
1798 // the imgRequest's proxy list, and we can get extra notifications
1799 // resulting from methods such as StartDecoding(). See bug 579122.
1800 proxy->MarkValidating();
1802 if (aLinkPreload) {
1803 MOZ_ASSERT(aLoadingDocument);
1804 proxy->PrioritizeAsPreload();
1805 auto preloadKey = PreloadHashKey::CreateAsImage(
1806 aURI, aTriggeringPrincipal, aCORSMode);
1807 proxy->NotifyOpen(preloadKey, aLoadingDocument, true);
1810 // Attach the proxy without notifying
1811 validator->AddProxy(proxy);
1814 return true;
1816 // We will rely on Necko to cache this request when it's possible, and to
1817 // tell imgCacheValidator::OnStartRequest whether the request came from its
1818 // cache.
1819 nsCOMPtr<nsIChannel> newChannel;
1820 bool forcePrincipalCheck;
1821 rv = NewImageChannel(getter_AddRefs(newChannel), &forcePrincipalCheck, aURI,
1822 aInitialDocumentURI, aCORSMode, aReferrerInfo,
1823 aLoadGroup, aLoadFlags, aLoadPolicyType,
1824 aTriggeringPrincipal, aLoadingDocument, mRespectPrivacy);
1825 if (NS_FAILED(rv)) {
1826 return false;
1829 if (aNewChannelCreated) {
1830 *aNewChannelCreated = true;
1833 RefPtr<imgRequestProxy> req;
1834 rv = CreateNewProxyForRequest(request, aURI, aLoadGroup, aLoadingDocument,
1835 aObserver, aLoadFlags, getter_AddRefs(req));
1836 if (NS_FAILED(rv)) {
1837 return false;
1840 // Make sure that OnStatus/OnProgress calls have the right request set...
1841 RefPtr<nsProgressNotificationProxy> progressproxy =
1842 new nsProgressNotificationProxy(newChannel, req);
1843 if (!progressproxy) {
1844 return false;
1847 RefPtr<imgCacheValidator> hvc =
1848 new imgCacheValidator(progressproxy, this, request, aLoadingDocument,
1849 aInnerWindowId, forcePrincipalCheck);
1851 // Casting needed here to get past multiple inheritance.
1852 nsCOMPtr<nsIStreamListener> listener =
1853 do_QueryInterface(static_cast<nsIThreadRetargetableStreamListener*>(hvc));
1854 NS_ENSURE_TRUE(listener, false);
1856 // We must set the notification callbacks before setting up the
1857 // CORS listener, because that's also interested inthe
1858 // notification callbacks.
1859 newChannel->SetNotificationCallbacks(hvc);
1861 request->SetValidator(hvc);
1863 // We will send notifications from imgCacheValidator::OnStartRequest().
1864 // In the mean time, we must defer notifications because we are added to
1865 // the imgRequest's proxy list, and we can get extra notifications
1866 // resulting from methods such as StartDecoding(). See bug 579122.
1867 req->MarkValidating();
1869 if (aLinkPreload) {
1870 MOZ_ASSERT(aLoadingDocument);
1871 req->PrioritizeAsPreload();
1872 auto preloadKey =
1873 PreloadHashKey::CreateAsImage(aURI, aTriggeringPrincipal, aCORSMode);
1874 req->NotifyOpen(preloadKey, aLoadingDocument, true);
1877 // Add the proxy without notifying
1878 hvc->AddProxy(req);
1880 mozilla::net::PredictorLearn(aURI, aInitialDocumentURI,
1881 nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE,
1882 aLoadGroup);
1883 rv = newChannel->AsyncOpen(listener);
1884 if (NS_WARN_IF(NS_FAILED(rv))) {
1885 req->CancelAndForgetObserver(rv);
1886 // This will notify any current or future <link preload> tags. Pass the
1887 // non-open channel so that we can read loadinfo and referrer info of that
1888 // channel.
1889 req->NotifyStart(newChannel);
1890 // Use the non-channel overload of this method to force the notification to
1891 // happen. The preload request has not been assigned a channel.
1892 req->NotifyStop(rv);
1893 return false;
1896 req.forget(aProxyRequest);
1897 return true;
1900 void imgLoader::NotifyObserversForCachedImage(
1901 imgCacheEntry* aEntry, imgRequest* request, nsIURI* aURI,
1902 nsIReferrerInfo* aReferrerInfo, Document* aLoadingDocument,
1903 nsIPrincipal* aTriggeringPrincipal, CORSMode aCORSMode) {
1904 nsCOMPtr<nsIChannel> newChannel;
1905 bool forcePrincipalCheck;
1906 nsresult rv =
1907 NewImageChannel(getter_AddRefs(newChannel), &forcePrincipalCheck, aURI,
1908 nullptr, aCORSMode, aReferrerInfo, nullptr, 0,
1909 nsIContentPolicy::TYPE_INTERNAL_IMAGE,
1910 aTriggeringPrincipal, aLoadingDocument, mRespectPrivacy);
1911 if (NS_FAILED(rv)) {
1912 return;
1915 RefPtr<HttpBaseChannel> httpBaseChannel = do_QueryObject(newChannel);
1916 if (httpBaseChannel) {
1917 httpBaseChannel->SetDummyChannelForImageCache();
1918 newChannel->SetContentType(nsDependentCString(request->GetMimeType()));
1919 RefPtr<mozilla::image::Image> image = request->GetImage();
1920 if (image) {
1921 newChannel->SetContentLength(aEntry->GetDataSize());
1923 nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
1924 obsService->NotifyObservers(newChannel, "http-on-image-cache-response",
1925 nullptr);
1929 bool imgLoader::ValidateEntry(
1930 imgCacheEntry* aEntry, nsIURI* aURI, nsIURI* aInitialDocumentURI,
1931 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
1932 imgINotificationObserver* aObserver, Document* aLoadingDocument,
1933 nsLoadFlags aLoadFlags, nsContentPolicyType aLoadPolicyType,
1934 bool aCanMakeNewChannel, bool* aNewChannelCreated,
1935 imgRequestProxy** aProxyRequest, nsIPrincipal* aTriggeringPrincipal,
1936 CORSMode aCORSMode, bool aLinkPreload) {
1937 LOG_SCOPE(gImgLog, "imgLoader::ValidateEntry");
1939 // If the expiration time is zero, then the request has not gotten far enough
1940 // to know when it will expire, or we know it will never expire (see
1941 // nsContentUtils::GetSubresourceCacheValidationInfo).
1942 uint32_t expiryTime = aEntry->GetExpiryTime();
1943 bool hasExpired = expiryTime && expiryTime <= SecondsFromPRTime(PR_Now());
1945 nsresult rv;
1947 // Special treatment for file URLs - aEntry has expired if file has changed
1948 nsCOMPtr<nsIFileURL> fileUrl(do_QueryInterface(aURI));
1949 if (fileUrl) {
1950 uint32_t lastModTime = aEntry->GetLoadTime();
1952 nsCOMPtr<nsIFile> theFile;
1953 rv = fileUrl->GetFile(getter_AddRefs(theFile));
1954 if (NS_SUCCEEDED(rv)) {
1955 PRTime fileLastMod;
1956 rv = theFile->GetLastModifiedTime(&fileLastMod);
1957 if (NS_SUCCEEDED(rv)) {
1958 // nsIFile uses millisec, NSPR usec
1959 fileLastMod *= 1000;
1960 hasExpired = SecondsFromPRTime((PRTime)fileLastMod) > lastModTime;
1965 RefPtr<imgRequest> request(aEntry->GetRequest());
1967 if (!request) {
1968 return false;
1971 if (!ValidateSecurityInfo(request, aEntry->ForcePrincipalCheck(), aCORSMode,
1972 aTriggeringPrincipal, aLoadingDocument,
1973 aLoadPolicyType)) {
1974 return false;
1977 // data URIs are immutable and by their nature can't leak data, so we can
1978 // just return true in that case. Doing so would mean that shift-reload
1979 // doesn't reload data URI documents/images though (which is handy for
1980 // debugging during gecko development) so we make an exception in that case.
1981 nsAutoCString scheme;
1982 aURI->GetScheme(scheme);
1983 if (scheme.EqualsLiteral("data") &&
1984 !(aLoadFlags & nsIRequest::LOAD_BYPASS_CACHE)) {
1985 return true;
1988 bool validateRequest = false;
1990 if (!request->CanReuseWithoutValidation(aLoadingDocument)) {
1991 // If we would need to revalidate this entry, but we're being told to
1992 // bypass the cache, we don't allow this entry to be used.
1993 if (aLoadFlags & nsIRequest::LOAD_BYPASS_CACHE) {
1994 return false;
1997 if (MOZ_UNLIKELY(ChaosMode::isActive(ChaosFeature::ImageCache))) {
1998 if (ChaosMode::randomUint32LessThan(4) < 1) {
1999 return false;
2003 // Determine whether the cache aEntry must be revalidated...
2004 validateRequest = ShouldRevalidateEntry(aEntry, aLoadFlags, hasExpired);
2006 MOZ_LOG(gImgLog, LogLevel::Debug,
2007 ("imgLoader::ValidateEntry validating cache entry. "
2008 "validateRequest = %d",
2009 validateRequest));
2010 } else if (!aLoadingDocument && MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
2011 MOZ_LOG(gImgLog, LogLevel::Debug,
2012 ("imgLoader::ValidateEntry BYPASSING cache validation for %s "
2013 "because of NULL loading document",
2014 aURI->GetSpecOrDefault().get()));
2017 // If the original request is still transferring don't kick off a validation
2018 // network request because it is a bit silly to issue a validation request if
2019 // the original request hasn't even finished yet. So just return true
2020 // indicating the caller can create a new proxy for the request and use it as
2021 // is.
2022 // This is an optimization but it's also required for correctness. If we don't
2023 // do this then when firing the load complete notification for the original
2024 // request that can unblock load for the document and then spin the event loop
2025 // (see the stack in bug 1641682) which then the OnStartRequest for the
2026 // validation request can fire which can call UpdateProxies and can sync
2027 // notify on the progress tracker about all existing state, which includes
2028 // load complete, so we fire a second load complete notification for the
2029 // image.
2030 // In addition, we want to validate if the original request encountered
2031 // an error for two reasons. The first being if the error was a network error
2032 // then trying to re-fetch the image might succeed. The second is more
2033 // complicated. We decide if we should fire the load or error event for img
2034 // elements depending on if the image has error in its status at the time when
2035 // the load complete notification is received, and we set error status on an
2036 // image if it encounters a network error or a decode error with no real way
2037 // to tell them apart. So if we load an image that will produce a decode error
2038 // the first time we will usually fire the load event, and then decode enough
2039 // to encounter the decode error and set the error status on the image. The
2040 // next time we reference the image in the same document the load complete
2041 // notification is replayed and this time the error status from the decode is
2042 // already present so we fire the error event instead of the load event. This
2043 // is a bug (bug 1645576) that we should fix. In order to avoid that bug in
2044 // some cases (specifically the cases when we hit this code and try to
2045 // validate the request) we make sure to validate. This avoids the bug because
2046 // when the load complete notification arrives the proxy is marked as
2047 // validating so it lies about its status and returns nothing.
2048 bool requestComplete = false;
2049 RefPtr<ProgressTracker> tracker;
2050 RefPtr<mozilla::image::Image> image = request->GetImage();
2051 if (image) {
2052 tracker = image->GetProgressTracker();
2053 } else {
2054 tracker = request->GetProgressTracker();
2056 if (tracker) {
2057 if (tracker->GetProgress() & (FLAG_LOAD_COMPLETE | FLAG_HAS_ERROR)) {
2058 requestComplete = true;
2061 if (!requestComplete) {
2062 return true;
2065 if (validateRequest && aCanMakeNewChannel) {
2066 LOG_SCOPE(gImgLog, "imgLoader::ValidateRequest |cache hit| must validate");
2068 uint64_t innerWindowID =
2069 aLoadingDocument ? aLoadingDocument->InnerWindowID() : 0;
2070 return ValidateRequestWithNewChannel(
2071 request, aURI, aInitialDocumentURI, aReferrerInfo, aLoadGroup,
2072 aObserver, aLoadingDocument, innerWindowID, aLoadFlags, aLoadPolicyType,
2073 aProxyRequest, aTriggeringPrincipal, aCORSMode, aLinkPreload,
2074 aNewChannelCreated);
2077 if (!validateRequest) {
2078 NotifyObserversForCachedImage(aEntry, request, aURI, aReferrerInfo,
2079 aLoadingDocument, aTriggeringPrincipal,
2080 aCORSMode);
2083 return !validateRequest;
2086 bool imgLoader::RemoveFromCache(const ImageCacheKey& aKey) {
2087 LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::RemoveFromCache", "uri",
2088 aKey.URI());
2090 imgCacheTable& cache = GetCache(aKey);
2091 imgCacheQueue& queue = GetCacheQueue(aKey);
2093 RefPtr<imgCacheEntry> entry;
2094 cache.Remove(aKey, getter_AddRefs(entry));
2095 if (entry) {
2096 MOZ_ASSERT(!entry->Evicted(), "Evicting an already-evicted cache entry!");
2098 // Entries with no proxies are in the tracker.
2099 if (entry->HasNoProxies()) {
2100 if (mCacheTracker) {
2101 mCacheTracker->RemoveObject(entry);
2103 queue.Remove(entry);
2106 entry->SetEvicted(true);
2108 RefPtr<imgRequest> request = entry->GetRequest();
2109 request->SetIsInCache(false);
2110 AddToUncachedImages(request);
2112 return true;
2114 return false;
2117 bool imgLoader::RemoveFromCache(imgCacheEntry* entry, QueueState aQueueState) {
2118 LOG_STATIC_FUNC(gImgLog, "imgLoader::RemoveFromCache entry");
2120 RefPtr<imgRequest> request = entry->GetRequest();
2121 if (request) {
2122 const ImageCacheKey& key = request->CacheKey();
2123 imgCacheTable& cache = GetCache(key);
2124 imgCacheQueue& queue = GetCacheQueue(key);
2126 LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::RemoveFromCache",
2127 "entry's uri", key.URI());
2129 cache.Remove(key);
2131 if (entry->HasNoProxies()) {
2132 LOG_STATIC_FUNC(gImgLog,
2133 "imgLoader::RemoveFromCache removing from tracker");
2134 if (mCacheTracker) {
2135 mCacheTracker->RemoveObject(entry);
2137 // Only search the queue to remove the entry if its possible it might
2138 // be in the queue. If we know its not in the queue this would be
2139 // wasted work.
2140 MOZ_ASSERT_IF(aQueueState == QueueState::AlreadyRemoved,
2141 !queue.Contains(entry));
2142 if (aQueueState == QueueState::MaybeExists) {
2143 queue.Remove(entry);
2147 entry->SetEvicted(true);
2148 request->SetIsInCache(false);
2149 AddToUncachedImages(request);
2151 return true;
2154 return false;
2157 nsresult imgLoader::EvictEntries(imgCacheTable& aCacheToClear) {
2158 LOG_STATIC_FUNC(gImgLog, "imgLoader::EvictEntries table");
2160 // We have to make a temporary, since RemoveFromCache removes the element
2161 // from the queue, invalidating iterators.
2162 const auto entries =
2163 ToTArray<nsTArray<RefPtr<imgCacheEntry>>>(aCacheToClear.Values());
2164 for (const auto& entry : entries) {
2165 if (!RemoveFromCache(entry)) {
2166 return NS_ERROR_FAILURE;
2170 MOZ_ASSERT(aCacheToClear.Count() == 0);
2172 return NS_OK;
2175 nsresult imgLoader::EvictEntries(imgCacheQueue& aQueueToClear) {
2176 LOG_STATIC_FUNC(gImgLog, "imgLoader::EvictEntries queue");
2178 // We have to make a temporary, since RemoveFromCache removes the element
2179 // from the queue, invalidating iterators.
2180 nsTArray<RefPtr<imgCacheEntry>> entries(aQueueToClear.GetNumElements());
2181 for (auto i = aQueueToClear.begin(); i != aQueueToClear.end(); ++i) {
2182 entries.AppendElement(*i);
2185 // Iterate in reverse order to minimize array copying.
2186 for (auto& entry : entries) {
2187 if (!RemoveFromCache(entry)) {
2188 return NS_ERROR_FAILURE;
2192 MOZ_ASSERT(aQueueToClear.GetNumElements() == 0);
2194 return NS_OK;
2197 void imgLoader::AddToUncachedImages(imgRequest* aRequest) {
2198 MutexAutoLock lock(mUncachedImagesMutex);
2199 mUncachedImages.Insert(aRequest);
2202 void imgLoader::RemoveFromUncachedImages(imgRequest* aRequest) {
2203 MutexAutoLock lock(mUncachedImagesMutex);
2204 mUncachedImages.Remove(aRequest);
2207 #define LOAD_FLAGS_CACHE_MASK \
2208 (nsIRequest::LOAD_BYPASS_CACHE | nsIRequest::LOAD_FROM_CACHE)
2210 #define LOAD_FLAGS_VALIDATE_MASK \
2211 (nsIRequest::VALIDATE_ALWAYS | nsIRequest::VALIDATE_NEVER | \
2212 nsIRequest::VALIDATE_ONCE_PER_SESSION)
2214 NS_IMETHODIMP
2215 imgLoader::LoadImageXPCOM(
2216 nsIURI* aURI, nsIURI* aInitialDocumentURI, nsIReferrerInfo* aReferrerInfo,
2217 nsIPrincipal* aTriggeringPrincipal, nsILoadGroup* aLoadGroup,
2218 imgINotificationObserver* aObserver, Document* aLoadingDocument,
2219 nsLoadFlags aLoadFlags, nsISupports* aCacheKey,
2220 nsContentPolicyType aContentPolicyType, imgIRequest** _retval) {
2221 // Optional parameter, so defaults to 0 (== TYPE_INVALID)
2222 if (!aContentPolicyType) {
2223 aContentPolicyType = nsIContentPolicy::TYPE_INTERNAL_IMAGE;
2225 imgRequestProxy* proxy;
2226 nsresult rv = LoadImage(
2227 aURI, aInitialDocumentURI, aReferrerInfo, aTriggeringPrincipal, 0,
2228 aLoadGroup, aObserver, aLoadingDocument, aLoadingDocument, aLoadFlags,
2229 aCacheKey, aContentPolicyType, u""_ns,
2230 /* aUseUrgentStartForChannel */ false, /* aListPreload */ false, &proxy);
2231 *_retval = proxy;
2232 return rv;
2235 static void MakeRequestStaticIfNeeded(
2236 Document* aLoadingDocument, imgRequestProxy** aProxyAboutToGetReturned) {
2237 if (!aLoadingDocument || !aLoadingDocument->IsStaticDocument()) {
2238 return;
2241 if (!*aProxyAboutToGetReturned) {
2242 return;
2245 RefPtr<imgRequestProxy> proxy = dont_AddRef(*aProxyAboutToGetReturned);
2246 *aProxyAboutToGetReturned = nullptr;
2248 RefPtr<imgRequestProxy> staticProxy =
2249 proxy->GetStaticRequest(aLoadingDocument);
2250 if (staticProxy != proxy) {
2251 proxy->CancelAndForgetObserver(NS_BINDING_ABORTED);
2252 proxy = std::move(staticProxy);
2254 proxy.forget(aProxyAboutToGetReturned);
2257 bool imgLoader::IsImageAvailable(nsIURI* aURI,
2258 nsIPrincipal* aTriggeringPrincipal,
2259 CORSMode aCORSMode, Document* aDocument) {
2260 ImageCacheKey key(aURI, aTriggeringPrincipal->OriginAttributesRef(),
2261 aDocument);
2262 RefPtr<imgCacheEntry> entry;
2263 imgCacheTable& cache = GetCache(key);
2264 if (!cache.Get(key, getter_AddRefs(entry)) || !entry) {
2265 return false;
2267 RefPtr<imgRequest> request = entry->GetRequest();
2268 if (!request) {
2269 return false;
2271 return ValidateCORSMode(request, false, aCORSMode, aTriggeringPrincipal);
2274 nsresult imgLoader::LoadImage(
2275 nsIURI* aURI, nsIURI* aInitialDocumentURI, nsIReferrerInfo* aReferrerInfo,
2276 nsIPrincipal* aTriggeringPrincipal, uint64_t aRequestContextID,
2277 nsILoadGroup* aLoadGroup, imgINotificationObserver* aObserver,
2278 nsINode* aContext, Document* aLoadingDocument, nsLoadFlags aLoadFlags,
2279 nsISupports* aCacheKey, nsContentPolicyType aContentPolicyType,
2280 const nsAString& initiatorType, bool aUseUrgentStartForChannel,
2281 bool aLinkPreload, imgRequestProxy** _retval) {
2282 VerifyCacheSizes();
2284 NS_ASSERTION(aURI, "imgLoader::LoadImage -- NULL URI pointer");
2286 if (!aURI) {
2287 return NS_ERROR_NULL_POINTER;
2290 auto makeStaticIfNeeded = mozilla::MakeScopeExit(
2291 [&] { MakeRequestStaticIfNeeded(aLoadingDocument, _retval); });
2293 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING("imgLoader::LoadImage", NETWORK,
2294 aURI->GetSpecOrDefault());
2296 LOG_SCOPE_WITH_PARAM(gImgLog, "imgLoader::LoadImage", "aURI", aURI);
2298 *_retval = nullptr;
2300 RefPtr<imgRequest> request;
2302 nsresult rv;
2303 nsLoadFlags requestFlags = nsIRequest::LOAD_NORMAL;
2305 #ifdef DEBUG
2306 bool isPrivate = false;
2308 if (aLoadingDocument) {
2309 isPrivate = nsContentUtils::IsInPrivateBrowsing(aLoadingDocument);
2310 } else if (aLoadGroup) {
2311 isPrivate = nsContentUtils::IsInPrivateBrowsing(aLoadGroup);
2313 MOZ_ASSERT(isPrivate == mRespectPrivacy);
2315 if (aLoadingDocument) {
2316 // The given load group should match that of the document if given. If
2317 // that isn't the case, then we need to add more plumbing to ensure we
2318 // block the document as well.
2319 nsCOMPtr<nsILoadGroup> docLoadGroup =
2320 aLoadingDocument->GetDocumentLoadGroup();
2321 MOZ_ASSERT(docLoadGroup == aLoadGroup);
2323 #endif
2325 // Get the default load flags from the loadgroup (if possible)...
2326 if (aLoadGroup) {
2327 aLoadGroup->GetLoadFlags(&requestFlags);
2330 // Merge the default load flags with those passed in via aLoadFlags.
2331 // Currently, *only* the caching, validation and background load flags
2332 // are merged...
2334 // The flags in aLoadFlags take precedence over the default flags!
2336 if (aLoadFlags & LOAD_FLAGS_CACHE_MASK) {
2337 // Override the default caching flags...
2338 requestFlags = (requestFlags & ~LOAD_FLAGS_CACHE_MASK) |
2339 (aLoadFlags & LOAD_FLAGS_CACHE_MASK);
2341 if (aLoadFlags & LOAD_FLAGS_VALIDATE_MASK) {
2342 // Override the default validation flags...
2343 requestFlags = (requestFlags & ~LOAD_FLAGS_VALIDATE_MASK) |
2344 (aLoadFlags & LOAD_FLAGS_VALIDATE_MASK);
2346 if (aLoadFlags & nsIRequest::LOAD_BACKGROUND) {
2347 // Propagate background loading...
2348 requestFlags |= nsIRequest::LOAD_BACKGROUND;
2350 if (aLoadFlags & nsIRequest::LOAD_RECORD_START_REQUEST_DELAY) {
2351 requestFlags |= nsIRequest::LOAD_RECORD_START_REQUEST_DELAY;
2354 if (aLinkPreload) {
2355 // Set background loading if it is <link rel=preload>
2356 requestFlags |= nsIRequest::LOAD_BACKGROUND;
2359 CORSMode corsmode = CORS_NONE;
2360 if (aLoadFlags & imgILoader::LOAD_CORS_ANONYMOUS) {
2361 corsmode = CORS_ANONYMOUS;
2362 } else if (aLoadFlags & imgILoader::LOAD_CORS_USE_CREDENTIALS) {
2363 corsmode = CORS_USE_CREDENTIALS;
2366 // Look in the preloaded images of loading document first.
2367 if (StaticPrefs::network_preload() && !aLinkPreload && aLoadingDocument) {
2368 auto key =
2369 PreloadHashKey::CreateAsImage(aURI, aTriggeringPrincipal, corsmode);
2370 if (RefPtr<PreloaderBase> preload =
2371 aLoadingDocument->Preloads().LookupPreload(key)) {
2372 RefPtr<imgRequestProxy> proxy = do_QueryObject(preload);
2373 MOZ_ASSERT(proxy);
2375 MOZ_LOG(gImgLog, LogLevel::Debug,
2376 ("[this=%p] imgLoader::LoadImage -- preloaded [proxy=%p]"
2377 " [document=%p]\n",
2378 this, proxy.get(), aLoadingDocument));
2380 // Removing the preload for this image to be in parity with Chromium. Any
2381 // following regular image request will be reloaded using the regular
2382 // path: image cache, http cache, network. Any following `<link
2383 // rel=preload as=image>` will start a new image preload that can be
2384 // satisfied from http cache or network.
2386 // There is a spec discussion for "preload cache", see
2387 // https://github.com/w3c/preload/issues/97. And it is also not clear how
2388 // preload image interacts with list of available images, see
2389 // https://github.com/whatwg/html/issues/4474.
2390 proxy->RemoveSelf(aLoadingDocument);
2391 proxy->NotifyUsage();
2393 imgRequest* request = proxy->GetOwner();
2394 nsresult rv =
2395 CreateNewProxyForRequest(request, aURI, aLoadGroup, aLoadingDocument,
2396 aObserver, requestFlags, _retval);
2397 NS_ENSURE_SUCCESS(rv, rv);
2399 imgRequestProxy* newProxy = *_retval;
2400 if (imgCacheValidator* validator = request->GetValidator()) {
2401 newProxy->MarkValidating();
2402 // Attach the proxy without notifying and this will add us to the load
2403 // group.
2404 validator->AddProxy(newProxy);
2405 } else {
2406 // It's OK to add here even if the request is done. If it is, it'll send
2407 // a OnStopRequest()and the proxy will be removed from the loadgroup in
2408 // imgRequestProxy::OnLoadComplete.
2409 newProxy->AddToLoadGroup();
2410 newProxy->NotifyListener();
2413 return NS_OK;
2417 RefPtr<imgCacheEntry> entry;
2419 // Look in the cache for our URI, and then validate it.
2420 // XXX For now ignore aCacheKey. We will need it in the future
2421 // for correctly dealing with image load requests that are a result
2422 // of post data.
2423 OriginAttributes attrs;
2424 if (aTriggeringPrincipal) {
2425 attrs = aTriggeringPrincipal->OriginAttributesRef();
2427 ImageCacheKey key(aURI, attrs, aLoadingDocument);
2428 imgCacheTable& cache = GetCache(key);
2430 if (cache.Get(key, getter_AddRefs(entry)) && entry) {
2431 bool newChannelCreated = false;
2432 if (ValidateEntry(entry, aURI, aInitialDocumentURI, aReferrerInfo,
2433 aLoadGroup, aObserver, aLoadingDocument, requestFlags,
2434 aContentPolicyType, true, &newChannelCreated, _retval,
2435 aTriggeringPrincipal, corsmode, aLinkPreload)) {
2436 request = entry->GetRequest();
2438 // If this entry has no proxies, its request has no reference to the
2439 // entry.
2440 if (entry->HasNoProxies()) {
2441 LOG_FUNC_WITH_PARAM(gImgLog,
2442 "imgLoader::LoadImage() adding proxyless entry",
2443 "uri", key.URI());
2444 MOZ_ASSERT(!request->HasCacheEntry(),
2445 "Proxyless entry's request has cache entry!");
2446 request->SetCacheEntry(entry);
2448 if (mCacheTracker && entry->GetExpirationState()->IsTracked()) {
2449 mCacheTracker->MarkUsed(entry);
2453 entry->Touch();
2455 if (!newChannelCreated) {
2456 // This is ugly but it's needed to report CSP violations. We have 3
2457 // scenarios:
2458 // - we don't have cache. We are not in this if() stmt. A new channel is
2459 // created and that triggers the CSP checks.
2460 // - We have a cache entry and this is blocked by CSP directives.
2461 DebugOnly<bool> shouldLoad = ShouldLoadCachedImage(
2462 request, aLoadingDocument, aTriggeringPrincipal, aContentPolicyType,
2463 /* aSendCSPViolationReports */ true);
2464 MOZ_ASSERT(shouldLoad);
2466 } else {
2467 // We can't use this entry. We'll try to load it off the network, and if
2468 // successful, overwrite the old entry in the cache with a new one.
2469 entry = nullptr;
2473 // Keep the channel in this scope, so we can adjust its notificationCallbacks
2474 // later when we create the proxy.
2475 nsCOMPtr<nsIChannel> newChannel;
2476 // If we didn't get a cache hit, we need to load from the network.
2477 if (!request) {
2478 LOG_SCOPE(gImgLog, "imgLoader::LoadImage |cache miss|");
2480 bool forcePrincipalCheck;
2481 rv = NewImageChannel(getter_AddRefs(newChannel), &forcePrincipalCheck, aURI,
2482 aInitialDocumentURI, corsmode, aReferrerInfo,
2483 aLoadGroup, requestFlags, aContentPolicyType,
2484 aTriggeringPrincipal, aContext, mRespectPrivacy);
2485 if (NS_FAILED(rv)) {
2486 return NS_ERROR_FAILURE;
2489 MOZ_ASSERT(NS_UsePrivateBrowsing(newChannel) == mRespectPrivacy);
2491 NewRequestAndEntry(forcePrincipalCheck, this, key, getter_AddRefs(request),
2492 getter_AddRefs(entry));
2494 MOZ_LOG(gImgLog, LogLevel::Debug,
2495 ("[this=%p] imgLoader::LoadImage -- Created new imgRequest"
2496 " [request=%p]\n",
2497 this, request.get()));
2499 nsCOMPtr<nsIClassOfService> cos(do_QueryInterface(newChannel));
2500 if (cos) {
2501 if (aUseUrgentStartForChannel && !aLinkPreload) {
2502 cos->AddClassFlags(nsIClassOfService::UrgentStart);
2505 if (StaticPrefs::network_http_tailing_enabled() &&
2506 aContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON) {
2507 cos->AddClassFlags(nsIClassOfService::Throttleable |
2508 nsIClassOfService::Tail);
2509 nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(newChannel));
2510 if (httpChannel) {
2511 Unused << httpChannel->SetRequestContextID(aRequestContextID);
2516 nsCOMPtr<nsILoadGroup> channelLoadGroup;
2517 newChannel->GetLoadGroup(getter_AddRefs(channelLoadGroup));
2518 rv = request->Init(aURI, aURI, /* aHadInsecureRedirect = */ false,
2519 channelLoadGroup, newChannel, entry, aLoadingDocument,
2520 aTriggeringPrincipal, corsmode, aReferrerInfo);
2521 if (NS_FAILED(rv)) {
2522 return NS_ERROR_FAILURE;
2525 // Add the initiator type for this image load
2526 nsCOMPtr<nsITimedChannel> timedChannel = do_QueryInterface(newChannel);
2527 if (timedChannel) {
2528 timedChannel->SetInitiatorType(initiatorType);
2531 // create the proxy listener
2532 nsCOMPtr<nsIStreamListener> listener = new ProxyListener(request.get());
2534 MOZ_LOG(gImgLog, LogLevel::Debug,
2535 ("[this=%p] imgLoader::LoadImage -- Calling channel->AsyncOpen()\n",
2536 this));
2538 mozilla::net::PredictorLearn(aURI, aInitialDocumentURI,
2539 nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE,
2540 aLoadGroup);
2542 nsresult openRes = newChannel->AsyncOpen(listener);
2544 if (NS_FAILED(openRes)) {
2545 MOZ_LOG(
2546 gImgLog, LogLevel::Debug,
2547 ("[this=%p] imgLoader::LoadImage -- AsyncOpen() failed: 0x%" PRIx32
2548 "\n",
2549 this, static_cast<uint32_t>(openRes)));
2550 request->CancelAndAbort(openRes);
2551 return openRes;
2554 // Try to add the new request into the cache.
2555 PutIntoCache(key, entry);
2556 } else {
2557 LOG_MSG_WITH_PARAM(gImgLog, "imgLoader::LoadImage |cache hit|", "request",
2558 request);
2561 // If we didn't get a proxy when validating the cache entry, we need to
2562 // create one.
2563 if (!*_retval) {
2564 // ValidateEntry() has three return values: "Is valid," "might be valid --
2565 // validating over network", and "not valid." If we don't have a _retval,
2566 // we know ValidateEntry is not validating over the network, so it's safe
2567 // to SetLoadId here because we know this request is valid for this context.
2569 // Note, however, that this doesn't guarantee the behaviour we want (one
2570 // URL maps to the same image on a page) if we load the same image in a
2571 // different tab (see bug 528003), because its load id will get re-set, and
2572 // that'll cause us to validate over the network.
2573 request->SetLoadId(aLoadingDocument);
2575 LOG_MSG(gImgLog, "imgLoader::LoadImage", "creating proxy request.");
2576 rv = CreateNewProxyForRequest(request, aURI, aLoadGroup, aLoadingDocument,
2577 aObserver, requestFlags, _retval);
2578 if (NS_FAILED(rv)) {
2579 return rv;
2582 imgRequestProxy* proxy = *_retval;
2584 // Make sure that OnStatus/OnProgress calls have the right request set, if
2585 // we did create a channel here.
2586 if (newChannel) {
2587 nsCOMPtr<nsIInterfaceRequestor> requestor(
2588 new nsProgressNotificationProxy(newChannel, proxy));
2589 if (!requestor) {
2590 return NS_ERROR_OUT_OF_MEMORY;
2592 newChannel->SetNotificationCallbacks(requestor);
2595 if (aLinkPreload) {
2596 MOZ_ASSERT(aLoadingDocument);
2597 proxy->PrioritizeAsPreload();
2598 auto preloadKey =
2599 PreloadHashKey::CreateAsImage(aURI, aTriggeringPrincipal, corsmode);
2600 proxy->NotifyOpen(preloadKey, aLoadingDocument, true);
2603 // Note that it's OK to add here even if the request is done. If it is,
2604 // it'll send a OnStopRequest() to the proxy in imgRequestProxy::Notify and
2605 // the proxy will be removed from the loadgroup.
2606 proxy->AddToLoadGroup();
2608 // If we're loading off the network, explicitly don't notify our proxy,
2609 // because necko (or things called from necko, such as imgCacheValidator)
2610 // are going to call our notifications asynchronously, and we can't make it
2611 // further asynchronous because observers might rely on imagelib completing
2612 // its work between the channel's OnStartRequest and OnStopRequest.
2613 if (!newChannel) {
2614 proxy->NotifyListener();
2617 return rv;
2620 NS_ASSERTION(*_retval, "imgLoader::LoadImage -- no return value");
2622 return NS_OK;
2625 NS_IMETHODIMP
2626 imgLoader::LoadImageWithChannelXPCOM(nsIChannel* channel,
2627 imgINotificationObserver* aObserver,
2628 Document* aLoadingDocument,
2629 nsIStreamListener** listener,
2630 imgIRequest** _retval) {
2631 nsresult result;
2632 imgRequestProxy* proxy;
2633 result = LoadImageWithChannel(channel, aObserver, aLoadingDocument, listener,
2634 &proxy);
2635 *_retval = proxy;
2636 return result;
2639 nsresult imgLoader::LoadImageWithChannel(nsIChannel* channel,
2640 imgINotificationObserver* aObserver,
2641 Document* aLoadingDocument,
2642 nsIStreamListener** listener,
2643 imgRequestProxy** _retval) {
2644 NS_ASSERTION(channel,
2645 "imgLoader::LoadImageWithChannel -- NULL channel pointer");
2647 MOZ_ASSERT(NS_UsePrivateBrowsing(channel) == mRespectPrivacy);
2649 auto makeStaticIfNeeded = mozilla::MakeScopeExit(
2650 [&] { MakeRequestStaticIfNeeded(aLoadingDocument, _retval); });
2652 LOG_SCOPE(gImgLog, "imgLoader::LoadImageWithChannel");
2653 RefPtr<imgRequest> request;
2655 nsCOMPtr<nsIURI> uri;
2656 channel->GetURI(getter_AddRefs(uri));
2658 NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE);
2659 nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
2661 OriginAttributes attrs = loadInfo->GetOriginAttributes();
2663 ImageCacheKey key(uri, attrs, aLoadingDocument);
2665 nsLoadFlags requestFlags = nsIRequest::LOAD_NORMAL;
2666 channel->GetLoadFlags(&requestFlags);
2668 RefPtr<imgCacheEntry> entry;
2670 if (requestFlags & nsIRequest::LOAD_BYPASS_CACHE) {
2671 RemoveFromCache(key);
2672 } else {
2673 // Look in the cache for our URI, and then validate it.
2674 // XXX For now ignore aCacheKey. We will need it in the future
2675 // for correctly dealing with image load requests that are a result
2676 // of post data.
2677 imgCacheTable& cache = GetCache(key);
2678 if (cache.Get(key, getter_AddRefs(entry)) && entry) {
2679 // We don't want to kick off another network load. So we ask
2680 // ValidateEntry to only do validation without creating a new proxy. If
2681 // it says that the entry isn't valid any more, we'll only use the entry
2682 // we're getting if the channel is loading from the cache anyways.
2684 // XXX -- should this be changed? it's pretty much verbatim from the old
2685 // code, but seems nonsensical.
2687 // Since aCanMakeNewChannel == false, we don't need to pass content policy
2688 // type/principal/etc
2690 nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
2691 // if there is a loadInfo, use the right contentType, otherwise
2692 // default to the internal image type
2693 nsContentPolicyType policyType = loadInfo->InternalContentPolicyType();
2695 if (ValidateEntry(entry, uri, nullptr, nullptr, nullptr, aObserver,
2696 aLoadingDocument, requestFlags, policyType, false,
2697 nullptr, nullptr, nullptr, CORS_NONE, false)) {
2698 request = entry->GetRequest();
2699 } else {
2700 nsCOMPtr<nsICacheInfoChannel> cacheChan(do_QueryInterface(channel));
2701 bool bUseCacheCopy;
2703 if (cacheChan) {
2704 cacheChan->IsFromCache(&bUseCacheCopy);
2705 } else {
2706 bUseCacheCopy = false;
2709 if (!bUseCacheCopy) {
2710 entry = nullptr;
2711 } else {
2712 request = entry->GetRequest();
2716 if (request && entry) {
2717 // If this entry has no proxies, its request has no reference to
2718 // the entry.
2719 if (entry->HasNoProxies()) {
2720 LOG_FUNC_WITH_PARAM(
2721 gImgLog,
2722 "imgLoader::LoadImageWithChannel() adding proxyless entry", "uri",
2723 key.URI());
2724 MOZ_ASSERT(!request->HasCacheEntry(),
2725 "Proxyless entry's request has cache entry!");
2726 request->SetCacheEntry(entry);
2728 if (mCacheTracker && entry->GetExpirationState()->IsTracked()) {
2729 mCacheTracker->MarkUsed(entry);
2736 nsCOMPtr<nsILoadGroup> loadGroup;
2737 channel->GetLoadGroup(getter_AddRefs(loadGroup));
2739 #ifdef DEBUG
2740 if (aLoadingDocument) {
2741 // The load group of the channel should always match that of the
2742 // document if given. If that isn't the case, then we need to add more
2743 // plumbing to ensure we block the document as well.
2744 nsCOMPtr<nsILoadGroup> docLoadGroup =
2745 aLoadingDocument->GetDocumentLoadGroup();
2746 MOZ_ASSERT(docLoadGroup == loadGroup);
2748 #endif
2750 // Filter out any load flags not from nsIRequest
2751 requestFlags &= nsIRequest::LOAD_REQUESTMASK;
2753 nsresult rv = NS_OK;
2754 if (request) {
2755 // we have this in our cache already.. cancel the current (document) load
2757 // this should fire an OnStopRequest
2758 channel->Cancel(NS_ERROR_PARSED_DATA_CACHED);
2760 *listener = nullptr; // give them back a null nsIStreamListener
2762 rv = CreateNewProxyForRequest(request, uri, loadGroup, aLoadingDocument,
2763 aObserver, requestFlags, _retval);
2764 static_cast<imgRequestProxy*>(*_retval)->NotifyListener();
2765 } else {
2766 // We use originalURI here to fulfil the imgIRequest contract on GetURI.
2767 nsCOMPtr<nsIURI> originalURI;
2768 channel->GetOriginalURI(getter_AddRefs(originalURI));
2770 // XXX(seth): We should be able to just use |key| here, except that |key| is
2771 // constructed above with the *current URI* and not the *original URI*. I'm
2772 // pretty sure this is a bug, and it's preventing us from ever getting a
2773 // cache hit in LoadImageWithChannel when redirects are involved.
2774 ImageCacheKey originalURIKey(originalURI, attrs, aLoadingDocument);
2776 // Default to doing a principal check because we don't know who
2777 // started that load and whether their principal ended up being
2778 // inherited on the channel.
2779 NewRequestAndEntry(/* aForcePrincipalCheckForCacheEntry = */ true, this,
2780 originalURIKey, getter_AddRefs(request),
2781 getter_AddRefs(entry));
2783 // No principal specified here, because we're not passed one.
2784 // In LoadImageWithChannel, the redirects that may have been
2785 // associated with this load would have gone through necko.
2786 // We only have the final URI in ImageLib and hence don't know
2787 // if the request went through insecure redirects. But if it did,
2788 // the necko cache should have handled that (since all necko cache hits
2789 // including the redirects will go through content policy). Hence, we
2790 // can set aHadInsecureRedirect to false here.
2791 rv = request->Init(originalURI, uri, /* aHadInsecureRedirect = */ false,
2792 channel, channel, entry, aLoadingDocument, nullptr,
2793 CORS_NONE, nullptr);
2794 NS_ENSURE_SUCCESS(rv, rv);
2796 RefPtr<ProxyListener> pl =
2797 new ProxyListener(static_cast<nsIStreamListener*>(request.get()));
2798 pl.forget(listener);
2800 // Try to add the new request into the cache.
2801 PutIntoCache(originalURIKey, entry);
2803 rv = CreateNewProxyForRequest(request, originalURI, loadGroup,
2804 aLoadingDocument, aObserver, requestFlags,
2805 _retval);
2807 // Explicitly don't notify our proxy, because we're loading off the
2808 // network, and necko (or things called from necko, such as
2809 // imgCacheValidator) are going to call our notifications asynchronously,
2810 // and we can't make it further asynchronous because observers might rely
2811 // on imagelib completing its work between the channel's OnStartRequest and
2812 // OnStopRequest.
2815 if (NS_FAILED(rv)) {
2816 return rv;
2819 (*_retval)->AddToLoadGroup();
2820 return rv;
2823 bool imgLoader::SupportImageWithMimeType(const nsACString& aMimeType,
2824 AcceptedMimeTypes aAccept
2825 /* = AcceptedMimeTypes::IMAGES */) {
2826 nsAutoCString mimeType(aMimeType);
2827 ToLowerCase(mimeType);
2829 if (aAccept == AcceptedMimeTypes::IMAGES_AND_DOCUMENTS &&
2830 mimeType.EqualsLiteral("image/svg+xml")) {
2831 return true;
2834 DecoderType type = DecoderFactory::GetDecoderType(mimeType.get());
2835 return type != DecoderType::UNKNOWN;
2838 NS_IMETHODIMP
2839 imgLoader::GetMIMETypeFromContent(nsIRequest* aRequest,
2840 const uint8_t* aContents, uint32_t aLength,
2841 nsACString& aContentType) {
2842 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
2843 if (channel) {
2844 nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
2845 if (loadInfo->GetSkipContentSniffing()) {
2846 return NS_ERROR_NOT_AVAILABLE;
2850 nsresult rv =
2851 GetMimeTypeFromContent((const char*)aContents, aLength, aContentType);
2852 if (NS_SUCCEEDED(rv) && channel && XRE_IsParentProcess()) {
2853 if (RefPtr<mozilla::net::nsHttpChannel> httpChannel =
2854 do_QueryObject(channel)) {
2855 // If the image type pattern matching algorithm given bytes does not
2856 // return undefined, then disable the further check and allow the
2857 // response.
2858 httpChannel->DisableIsOpaqueResponseAllowedAfterSniffCheck(
2859 mozilla::net::nsHttpChannel::SnifferType::Image);
2863 return rv;
2866 /* static */
2867 nsresult imgLoader::GetMimeTypeFromContent(const char* aContents,
2868 uint32_t aLength,
2869 nsACString& aContentType) {
2870 nsAutoCString detected;
2872 /* Is it a GIF? */
2873 if (aLength >= 6 &&
2874 (!strncmp(aContents, "GIF87a", 6) || !strncmp(aContents, "GIF89a", 6))) {
2875 aContentType.AssignLiteral(IMAGE_GIF);
2877 /* or a PNG? */
2878 } else if (aLength >= 8 && ((unsigned char)aContents[0] == 0x89 &&
2879 (unsigned char)aContents[1] == 0x50 &&
2880 (unsigned char)aContents[2] == 0x4E &&
2881 (unsigned char)aContents[3] == 0x47 &&
2882 (unsigned char)aContents[4] == 0x0D &&
2883 (unsigned char)aContents[5] == 0x0A &&
2884 (unsigned char)aContents[6] == 0x1A &&
2885 (unsigned char)aContents[7] == 0x0A)) {
2886 aContentType.AssignLiteral(IMAGE_PNG);
2888 /* maybe a JPEG (JFIF)? */
2889 /* JFIF files start with SOI APP0 but older files can start with SOI DQT
2890 * so we test for SOI followed by any marker, i.e. FF D8 FF
2891 * this will also work for SPIFF JPEG files if they appear in the future.
2893 * (JFIF is 0XFF 0XD8 0XFF 0XE0 <skip 2> 0X4A 0X46 0X49 0X46 0X00)
2895 } else if (aLength >= 3 && ((unsigned char)aContents[0]) == 0xFF &&
2896 ((unsigned char)aContents[1]) == 0xD8 &&
2897 ((unsigned char)aContents[2]) == 0xFF) {
2898 aContentType.AssignLiteral(IMAGE_JPEG);
2900 /* or how about ART? */
2901 /* ART begins with JG (4A 47). Major version offset 2.
2902 * Minor version offset 3. Offset 4 must be nullptr.
2904 } else if (aLength >= 5 && ((unsigned char)aContents[0]) == 0x4a &&
2905 ((unsigned char)aContents[1]) == 0x47 &&
2906 ((unsigned char)aContents[4]) == 0x00) {
2907 aContentType.AssignLiteral(IMAGE_ART);
2909 } else if (aLength >= 2 && !strncmp(aContents, "BM", 2)) {
2910 aContentType.AssignLiteral(IMAGE_BMP);
2912 // ICOs always begin with a 2-byte 0 followed by a 2-byte 1.
2913 // CURs begin with 2-byte 0 followed by 2-byte 2.
2914 } else if (aLength >= 4 && (!memcmp(aContents, "\000\000\001\000", 4) ||
2915 !memcmp(aContents, "\000\000\002\000", 4))) {
2916 aContentType.AssignLiteral(IMAGE_ICO);
2918 // WebPs always begin with RIFF, a 32-bit length, and WEBP.
2919 } else if (aLength >= 12 && !memcmp(aContents, "RIFF", 4) &&
2920 !memcmp(aContents + 8, "WEBP", 4)) {
2921 aContentType.AssignLiteral(IMAGE_WEBP);
2923 } else if (MatchesMP4(reinterpret_cast<const uint8_t*>(aContents), aLength,
2924 detected) &&
2925 detected.Equals(IMAGE_AVIF)) {
2926 aContentType.AssignLiteral(IMAGE_AVIF);
2927 } else if ((aLength >= 2 && !memcmp(aContents, "\xFF\x0A", 2)) ||
2928 (aLength >= 12 &&
2929 !memcmp(aContents, "\x00\x00\x00\x0CJXL \x0D\x0A\x87\x0A", 12))) {
2930 // Each version is for containerless and containerful files respectively.
2931 aContentType.AssignLiteral(IMAGE_JXL);
2932 } else {
2933 /* none of the above? I give up */
2934 return NS_ERROR_NOT_AVAILABLE;
2937 return NS_OK;
2941 * proxy stream listener class used to handle multipart/x-mixed-replace
2944 #include "nsIRequest.h"
2945 #include "nsIStreamConverterService.h"
2947 NS_IMPL_ISUPPORTS(ProxyListener, nsIStreamListener,
2948 nsIThreadRetargetableStreamListener, nsIRequestObserver)
2950 ProxyListener::ProxyListener(nsIStreamListener* dest) : mDestListener(dest) {
2951 /* member initializers and constructor code */
2954 ProxyListener::~ProxyListener() { /* destructor code */
2957 /** nsIRequestObserver methods **/
2959 NS_IMETHODIMP
2960 ProxyListener::OnStartRequest(nsIRequest* aRequest) {
2961 if (!mDestListener) {
2962 return NS_ERROR_FAILURE;
2965 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
2966 if (channel) {
2967 // We need to set the initiator type for the image load
2968 nsCOMPtr<nsITimedChannel> timedChannel = do_QueryInterface(channel);
2969 if (timedChannel) {
2970 nsAutoString type;
2971 timedChannel->GetInitiatorType(type);
2972 if (type.IsEmpty()) {
2973 timedChannel->SetInitiatorType(u"img"_ns);
2977 nsAutoCString contentType;
2978 nsresult rv = channel->GetContentType(contentType);
2980 if (!contentType.IsEmpty()) {
2981 /* If multipart/x-mixed-replace content, we'll insert a MIME decoder
2982 in the pipeline to handle the content and pass it along to our
2983 original listener.
2985 if ("multipart/x-mixed-replace"_ns.Equals(contentType)) {
2986 nsCOMPtr<nsIStreamConverterService> convServ(
2987 do_GetService("@mozilla.org/streamConverters;1", &rv));
2988 if (NS_SUCCEEDED(rv)) {
2989 nsCOMPtr<nsIStreamListener> toListener(mDestListener);
2990 nsCOMPtr<nsIStreamListener> fromListener;
2992 rv = convServ->AsyncConvertData("multipart/x-mixed-replace", "*/*",
2993 toListener, nullptr,
2994 getter_AddRefs(fromListener));
2995 if (NS_SUCCEEDED(rv)) {
2996 mDestListener = fromListener;
3003 return mDestListener->OnStartRequest(aRequest);
3006 NS_IMETHODIMP
3007 ProxyListener::OnStopRequest(nsIRequest* aRequest, nsresult status) {
3008 if (!mDestListener) {
3009 return NS_ERROR_FAILURE;
3012 return mDestListener->OnStopRequest(aRequest, status);
3015 /** nsIStreamListener methods **/
3017 NS_IMETHODIMP
3018 ProxyListener::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* inStr,
3019 uint64_t sourceOffset, uint32_t count) {
3020 if (!mDestListener) {
3021 return NS_ERROR_FAILURE;
3024 return mDestListener->OnDataAvailable(aRequest, inStr, sourceOffset, count);
3027 /** nsThreadRetargetableStreamListener methods **/
3028 NS_IMETHODIMP
3029 ProxyListener::CheckListenerChain() {
3030 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
3031 nsresult rv = NS_OK;
3032 nsCOMPtr<nsIThreadRetargetableStreamListener> retargetableListener =
3033 do_QueryInterface(mDestListener, &rv);
3034 if (retargetableListener) {
3035 rv = retargetableListener->CheckListenerChain();
3037 MOZ_LOG(
3038 gImgLog, LogLevel::Debug,
3039 ("ProxyListener::CheckListenerChain %s [this=%p listener=%p rv=%" PRIx32
3040 "]",
3041 (NS_SUCCEEDED(rv) ? "success" : "failure"), this,
3042 (nsIStreamListener*)mDestListener, static_cast<uint32_t>(rv)));
3043 return rv;
3047 * http validate class. check a channel for a 304
3050 NS_IMPL_ISUPPORTS(imgCacheValidator, nsIStreamListener, nsIRequestObserver,
3051 nsIThreadRetargetableStreamListener, nsIChannelEventSink,
3052 nsIInterfaceRequestor, nsIAsyncVerifyRedirectCallback)
3054 imgCacheValidator::imgCacheValidator(nsProgressNotificationProxy* progress,
3055 imgLoader* loader, imgRequest* request,
3056 Document* aDocument,
3057 uint64_t aInnerWindowId,
3058 bool forcePrincipalCheckForCacheEntry)
3059 : mProgressProxy(progress),
3060 mRequest(request),
3061 mDocument(aDocument),
3062 mInnerWindowId(aInnerWindowId),
3063 mImgLoader(loader),
3064 mHadInsecureRedirect(false) {
3065 NewRequestAndEntry(forcePrincipalCheckForCacheEntry, loader,
3066 mRequest->CacheKey(), getter_AddRefs(mNewRequest),
3067 getter_AddRefs(mNewEntry));
3070 imgCacheValidator::~imgCacheValidator() {
3071 if (mRequest) {
3072 // If something went wrong, and we never unblocked the requests waiting on
3073 // validation, now is our last chance. We will cancel the new request and
3074 // switch the waiting proxies to it.
3075 UpdateProxies(/* aCancelRequest */ true, /* aSyncNotify */ false);
3079 void imgCacheValidator::AddProxy(imgRequestProxy* aProxy) {
3080 // aProxy needs to be in the loadgroup since we're validating from
3081 // the network.
3082 aProxy->AddToLoadGroup();
3084 mProxies.AppendElement(aProxy);
3087 void imgCacheValidator::RemoveProxy(imgRequestProxy* aProxy) {
3088 mProxies.RemoveElement(aProxy);
3091 void imgCacheValidator::UpdateProxies(bool aCancelRequest, bool aSyncNotify) {
3092 MOZ_ASSERT(mRequest);
3094 // Clear the validator before updating the proxies. The notifications may
3095 // clone an existing request, and its state could be inconsistent.
3096 mRequest->SetValidator(nullptr);
3097 mRequest = nullptr;
3099 // If an error occurred, we will want to cancel the new request, and make the
3100 // validating proxies point to it. Any proxies still bound to the original
3101 // request which are not validating should remain untouched.
3102 if (aCancelRequest) {
3103 MOZ_ASSERT(mNewRequest);
3104 mNewRequest->CancelAndAbort(NS_BINDING_ABORTED);
3107 // We have finished validating the request, so we can safely take ownership
3108 // of the proxy list. imgRequestProxy::SyncNotifyListener can mutate the list
3109 // if imgRequestProxy::CancelAndForgetObserver is called by its owner. Note
3110 // that any potential notifications should still be suppressed in
3111 // imgRequestProxy::ChangeOwner because we haven't cleared the validating
3112 // flag yet, and thus they will remain deferred.
3113 AutoTArray<RefPtr<imgRequestProxy>, 4> proxies(std::move(mProxies));
3115 for (auto& proxy : proxies) {
3116 // First update the state of all proxies before notifying any of them
3117 // to ensure a consistent state (e.g. in case the notification causes
3118 // other proxies to be touched indirectly.)
3119 MOZ_ASSERT(proxy->IsValidating());
3120 MOZ_ASSERT(proxy->NotificationsDeferred(),
3121 "Proxies waiting on cache validation should be "
3122 "deferring notifications!");
3123 if (mNewRequest) {
3124 proxy->ChangeOwner(mNewRequest);
3126 proxy->ClearValidating();
3129 mNewRequest = nullptr;
3130 mNewEntry = nullptr;
3132 for (auto& proxy : proxies) {
3133 if (aSyncNotify) {
3134 // Notify synchronously, because the caller knows we are already in an
3135 // asynchronously-called function (e.g. OnStartRequest).
3136 proxy->SyncNotifyListener();
3137 } else {
3138 // Notify asynchronously, because the caller does not know our current
3139 // call state (e.g. ~imgCacheValidator).
3140 proxy->NotifyListener();
3145 /** nsIRequestObserver methods **/
3147 NS_IMETHODIMP
3148 imgCacheValidator::OnStartRequest(nsIRequest* aRequest) {
3149 // We may be holding on to a document, so ensure that it's released.
3150 RefPtr<Document> document = mDocument.forget();
3152 // If for some reason we don't still have an existing request (probably
3153 // because OnStartRequest got delivered more than once), just bail.
3154 if (!mRequest) {
3155 MOZ_ASSERT_UNREACHABLE("OnStartRequest delivered more than once?");
3156 aRequest->Cancel(NS_BINDING_ABORTED);
3157 return NS_ERROR_FAILURE;
3160 // If this request is coming from cache and has the same URI as our
3161 // imgRequest, the request all our proxies are pointing at is valid, and all
3162 // we have to do is tell them to notify their listeners.
3163 nsCOMPtr<nsICacheInfoChannel> cacheChan(do_QueryInterface(aRequest));
3164 nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
3165 if (cacheChan && channel) {
3166 bool isFromCache = false;
3167 cacheChan->IsFromCache(&isFromCache);
3169 nsCOMPtr<nsIURI> channelURI;
3170 channel->GetURI(getter_AddRefs(channelURI));
3172 nsCOMPtr<nsIURI> finalURI;
3173 mRequest->GetFinalURI(getter_AddRefs(finalURI));
3175 bool sameURI = false;
3176 if (channelURI && finalURI) {
3177 channelURI->Equals(finalURI, &sameURI);
3180 if (isFromCache && sameURI) {
3181 // We don't need to load this any more.
3182 aRequest->Cancel(NS_BINDING_ABORTED);
3183 mNewRequest = nullptr;
3185 // Clear the validator before updating the proxies. The notifications may
3186 // clone an existing request, and its state could be inconsistent.
3187 mRequest->SetLoadId(document);
3188 mRequest->SetInnerWindowID(mInnerWindowId);
3189 UpdateProxies(/* aCancelRequest */ false, /* aSyncNotify */ true);
3190 return NS_OK;
3194 // We can't load out of cache. We have to create a whole new request for the
3195 // data that's coming in off the channel.
3196 nsCOMPtr<nsIURI> uri;
3197 mRequest->GetURI(getter_AddRefs(uri));
3199 LOG_MSG_WITH_PARAM(gImgLog,
3200 "imgCacheValidator::OnStartRequest creating new request",
3201 "uri", uri);
3203 CORSMode corsmode = mRequest->GetCORSMode();
3204 nsCOMPtr<nsIReferrerInfo> referrerInfo = mRequest->GetReferrerInfo();
3205 nsCOMPtr<nsIPrincipal> triggeringPrincipal =
3206 mRequest->GetTriggeringPrincipal();
3208 // Doom the old request's cache entry
3209 mRequest->RemoveFromCache();
3211 // We use originalURI here to fulfil the imgIRequest contract on GetURI.
3212 nsCOMPtr<nsIURI> originalURI;
3213 channel->GetOriginalURI(getter_AddRefs(originalURI));
3214 nsresult rv = mNewRequest->Init(originalURI, uri, mHadInsecureRedirect,
3215 aRequest, channel, mNewEntry, document,
3216 triggeringPrincipal, corsmode, referrerInfo);
3217 if (NS_FAILED(rv)) {
3218 UpdateProxies(/* aCancelRequest */ true, /* aSyncNotify */ true);
3219 return rv;
3222 mDestListener = new ProxyListener(mNewRequest);
3224 // Try to add the new request into the cache. Note that the entry must be in
3225 // the cache before the proxies' ownership changes, because adding a proxy
3226 // changes the caching behaviour for imgRequests.
3227 mImgLoader->PutIntoCache(mNewRequest->CacheKey(), mNewEntry);
3228 UpdateProxies(/* aCancelRequest */ false, /* aSyncNotify */ true);
3229 return mDestListener->OnStartRequest(aRequest);
3232 NS_IMETHODIMP
3233 imgCacheValidator::OnStopRequest(nsIRequest* aRequest, nsresult status) {
3234 // Be sure we've released the document that we may have been holding on to.
3235 mDocument = nullptr;
3237 if (!mDestListener) {
3238 return NS_OK;
3241 return mDestListener->OnStopRequest(aRequest, status);
3244 /** nsIStreamListener methods **/
3246 NS_IMETHODIMP
3247 imgCacheValidator::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* inStr,
3248 uint64_t sourceOffset, uint32_t count) {
3249 if (!mDestListener) {
3250 // XXX see bug 113959
3251 uint32_t _retval;
3252 inStr->ReadSegments(NS_DiscardSegment, nullptr, count, &_retval);
3253 return NS_OK;
3256 return mDestListener->OnDataAvailable(aRequest, inStr, sourceOffset, count);
3259 /** nsIThreadRetargetableStreamListener methods **/
3261 NS_IMETHODIMP
3262 imgCacheValidator::CheckListenerChain() {
3263 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
3264 nsresult rv = NS_OK;
3265 nsCOMPtr<nsIThreadRetargetableStreamListener> retargetableListener =
3266 do_QueryInterface(mDestListener, &rv);
3267 if (retargetableListener) {
3268 rv = retargetableListener->CheckListenerChain();
3270 MOZ_LOG(
3271 gImgLog, LogLevel::Debug,
3272 ("[this=%p] imgCacheValidator::CheckListenerChain -- rv %" PRId32 "=%s",
3273 this, static_cast<uint32_t>(rv),
3274 NS_SUCCEEDED(rv) ? "succeeded" : "failed"));
3275 return rv;
3278 /** nsIInterfaceRequestor methods **/
3280 NS_IMETHODIMP
3281 imgCacheValidator::GetInterface(const nsIID& aIID, void** aResult) {
3282 if (aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
3283 return QueryInterface(aIID, aResult);
3286 return mProgressProxy->GetInterface(aIID, aResult);
3289 // These functions are materially the same as the same functions in imgRequest.
3290 // We duplicate them because we're verifying whether cache loads are necessary,
3291 // not unconditionally loading.
3293 /** nsIChannelEventSink methods **/
3294 NS_IMETHODIMP
3295 imgCacheValidator::AsyncOnChannelRedirect(
3296 nsIChannel* oldChannel, nsIChannel* newChannel, uint32_t flags,
3297 nsIAsyncVerifyRedirectCallback* callback) {
3298 // Note all cache information we get from the old channel.
3299 mNewRequest->SetCacheValidation(mNewEntry, oldChannel);
3301 // If the previous URI is a non-HTTPS URI, record that fact for later use by
3302 // security code, which needs to know whether there is an insecure load at any
3303 // point in the redirect chain.
3304 nsCOMPtr<nsIURI> oldURI;
3305 bool schemeLocal = false;
3306 if (NS_FAILED(oldChannel->GetURI(getter_AddRefs(oldURI))) ||
3307 NS_FAILED(NS_URIChainHasFlags(
3308 oldURI, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &schemeLocal)) ||
3309 (!oldURI->SchemeIs("https") && !oldURI->SchemeIs("chrome") &&
3310 !schemeLocal)) {
3311 mHadInsecureRedirect = true;
3314 // Prepare for callback
3315 mRedirectCallback = callback;
3316 mRedirectChannel = newChannel;
3318 return mProgressProxy->AsyncOnChannelRedirect(oldChannel, newChannel, flags,
3319 this);
3322 NS_IMETHODIMP
3323 imgCacheValidator::OnRedirectVerifyCallback(nsresult aResult) {
3324 // If we've already been told to abort, just do so.
3325 if (NS_FAILED(aResult)) {
3326 mRedirectCallback->OnRedirectVerifyCallback(aResult);
3327 mRedirectCallback = nullptr;
3328 mRedirectChannel = nullptr;
3329 return NS_OK;
3332 // make sure we have a protocol that returns data rather than opens
3333 // an external application, e.g. mailto:
3334 nsCOMPtr<nsIURI> uri;
3335 mRedirectChannel->GetURI(getter_AddRefs(uri));
3336 bool doesNotReturnData = false;
3337 NS_URIChainHasFlags(uri, nsIProtocolHandler::URI_DOES_NOT_RETURN_DATA,
3338 &doesNotReturnData);
3340 nsresult result = NS_OK;
3342 if (doesNotReturnData) {
3343 result = NS_ERROR_ABORT;
3346 mRedirectCallback->OnRedirectVerifyCallback(result);
3347 mRedirectCallback = nullptr;
3348 mRedirectChannel = nullptr;
3349 return NS_OK;