beb7da0878ba56cfb2a717b8f0f153f3eb8524fa
[WebKit-https.git] / Source / WebCore / loader / cache / CachedResourceLoader.cpp
1 /*
2     Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3     Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
4     Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
5     Copyright (C) 2004-2016 Apple Inc. All rights reserved.
6     Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
7
8     This library is free software; you can redistribute it and/or
9     modify it under the terms of the GNU Library General Public
10     License as published by the Free Software Foundation; either
11     version 2 of the License, or (at your option) any later version.
12
13     This library is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16     Library General Public License for more details.
17
18     You should have received a copy of the GNU Library General Public License
19     along with this library; see the file COPYING.LIB.  If not, write to
20     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21     Boston, MA 02110-1301, USA.
22
23     This class provides all functionality needed for loading images, style sheets and html
24     pages from the web. It has a memory cache for these objects.
25 */
26
27 #include "config.h"
28 #include "CachedResourceLoader.h"
29
30 #include "CachedCSSStyleSheet.h"
31 #include "CachedSVGDocument.h"
32 #include "CachedFont.h"
33 #include "CachedImage.h"
34 #include "CachedRawResource.h"
35 #include "CachedResourceRequest.h"
36 #include "CachedSVGFont.h"
37 #include "CachedScript.h"
38 #include "CachedXSLStyleSheet.h"
39 #include "Chrome.h"
40 #include "ChromeClient.h"
41 #include "ContentExtensionError.h"
42 #include "ContentExtensionRule.h"
43 #include "ContentSecurityPolicy.h"
44 #include "DOMWindow.h"
45 #include "DiagnosticLoggingClient.h"
46 #include "DiagnosticLoggingKeys.h"
47 #include "Document.h"
48 #include "DocumentLoader.h"
49 #include "Frame.h"
50 #include "FrameLoader.h"
51 #include "FrameLoaderClient.h"
52 #include "HTMLElement.h"
53 #include "HTMLFrameOwnerElement.h"
54 #include "LoaderStrategy.h"
55 #include "LocalizedStrings.h"
56 #include "Logging.h"
57 #include "MainFrame.h"
58 #include "MemoryCache.h"
59 #include "Page.h"
60 #include "Performance.h"
61 #include "PingLoader.h"
62 #include "PlatformStrategies.h"
63 #include "RenderElement.h"
64 #include "ResourceLoadInfo.h"
65 #include "RuntimeEnabledFeatures.h"
66 #include "ScriptController.h"
67 #include "SecurityOrigin.h"
68 #include "SecurityPolicy.h"
69 #include "SessionID.h"
70 #include "Settings.h"
71 #include "StyleSheetContents.h"
72 #include "SubresourceLoader.h"
73 #include "UserContentController.h"
74 #include "UserStyleSheet.h"
75 #include <wtf/text/CString.h>
76 #include <wtf/text/WTFString.h>
77
78 #if ENABLE(VIDEO_TRACK)
79 #include "CachedTextTrack.h"
80 #endif
81
82 #define PRELOAD_DEBUG 0
83
84 #define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - CachedResourceLoader::" fmt, this, ##__VA_ARGS__)
85
86 namespace WebCore {
87
88 static CachedResource* createResource(CachedResource::Type type, CachedResourceRequest&& request, SessionID sessionID)
89 {
90     switch (type) {
91     case CachedResource::ImageResource:
92         return new CachedImage(WTFMove(request), sessionID);
93     case CachedResource::CSSStyleSheet:
94         return new CachedCSSStyleSheet(WTFMove(request), sessionID);
95     case CachedResource::Script:
96         return new CachedScript(WTFMove(request), sessionID);
97     case CachedResource::SVGDocumentResource:
98         return new CachedSVGDocument(WTFMove(request), sessionID);
99 #if ENABLE(SVG_FONTS)
100     case CachedResource::SVGFontResource:
101         return new CachedSVGFont(WTFMove(request), sessionID);
102 #endif
103     case CachedResource::FontResource:
104         return new CachedFont(WTFMove(request), sessionID);
105     case CachedResource::MediaResource:
106     case CachedResource::RawResource:
107     case CachedResource::MainResource:
108         return new CachedRawResource(WTFMove(request), type, sessionID);
109 #if ENABLE(XSLT)
110     case CachedResource::XSLStyleSheet:
111         return new CachedXSLStyleSheet(WTFMove(request), sessionID);
112 #endif
113 #if ENABLE(LINK_PREFETCH)
114     case CachedResource::LinkPrefetch:
115         return new CachedResource(WTFMove(request), CachedResource::LinkPrefetch, sessionID);
116     case CachedResource::LinkSubresource:
117         return new CachedResource(WTFMove(request), CachedResource::LinkSubresource, sessionID);
118 #endif
119 #if ENABLE(VIDEO_TRACK)
120     case CachedResource::TextTrackResource:
121         return new CachedTextTrack(WTFMove(request), sessionID);
122 #endif
123     }
124     ASSERT_NOT_REACHED();
125     return nullptr;
126 }
127
128 CachedResourceLoader::CachedResourceLoader(DocumentLoader* documentLoader)
129     : m_document(nullptr)
130     , m_documentLoader(documentLoader)
131     , m_requestCount(0)
132     , m_garbageCollectDocumentResourcesTimer(*this, &CachedResourceLoader::garbageCollectDocumentResources)
133     , m_autoLoadImages(true)
134     , m_imagesEnabled(true)
135     , m_allowStaleResources(false)
136 {
137 }
138
139 CachedResourceLoader::~CachedResourceLoader()
140 {
141     m_documentLoader = nullptr;
142     m_document = nullptr;
143
144     clearPreloads();
145     for (auto& resource : m_documentResources.values())
146         resource->setOwningCachedResourceLoader(nullptr);
147
148     // Make sure no requests still point to this CachedResourceLoader
149     ASSERT(m_requestCount == 0);
150 }
151
152 CachedResource* CachedResourceLoader::cachedResource(const String& resourceURL) const
153 {
154     ASSERT(!resourceURL.isNull());
155     return cachedResource(MemoryCache::removeFragmentIdentifierIfNeeded(m_document->completeURL(resourceURL)));
156 }
157
158 CachedResource* CachedResourceLoader::cachedResource(const URL& url) const
159 {
160     ASSERT(!MemoryCache::shouldRemoveFragmentIdentifier(url));
161     return m_documentResources.get(url).get();
162 }
163
164 Frame* CachedResourceLoader::frame() const
165 {
166     return m_documentLoader ? m_documentLoader->frame() : nullptr;
167 }
168
169 SessionID CachedResourceLoader::sessionID() const
170 {
171     SessionID sessionID = SessionID::defaultSessionID();
172
173     if (Frame* f = frame())
174         sessionID = f->page()->sessionID();
175
176     return sessionID;
177 }
178
179 CachedResourceHandle<CachedImage> CachedResourceLoader::requestImage(CachedResourceRequest&& request)
180 {
181     if (Frame* frame = this->frame()) {
182         if (frame->loader().pageDismissalEventBeingDispatched() != FrameLoader::PageDismissalType::None) {
183             if (Document* document = frame->document())
184                 request.upgradeInsecureRequestIfNeeded(*document);
185             URL requestURL = request.resourceRequest().url();
186             if (requestURL.isValid() && canRequest(CachedResource::ImageResource, requestURL, request, ForPreload::No))
187                 PingLoader::loadImage(*frame, requestURL);
188             return nullptr;
189         }
190     }
191
192     auto defer = clientDefersImage(request.resourceRequest().url()) ? DeferOption::DeferredByClient : DeferOption::NoDefer;
193     return downcast<CachedImage>(requestResource(CachedResource::ImageResource, WTFMove(request), ForPreload::No, defer).get());
194 }
195
196 CachedResourceHandle<CachedFont> CachedResourceLoader::requestFont(CachedResourceRequest&& request, bool isSVG)
197 {
198 #if ENABLE(SVG_FONTS)
199     if (isSVG)
200         return downcast<CachedSVGFont>(requestResource(CachedResource::SVGFontResource, WTFMove(request)).get());
201 #else
202     UNUSED_PARAM(isSVG);
203 #endif
204     return downcast<CachedFont>(requestResource(CachedResource::FontResource, WTFMove(request)).get());
205 }
206
207 #if ENABLE(VIDEO_TRACK)
208 CachedResourceHandle<CachedTextTrack> CachedResourceLoader::requestTextTrack(CachedResourceRequest&& request)
209 {
210     return downcast<CachedTextTrack>(requestResource(CachedResource::TextTrackResource, WTFMove(request)).get());
211 }
212 #endif
213
214 CachedResourceHandle<CachedCSSStyleSheet> CachedResourceLoader::requestCSSStyleSheet(CachedResourceRequest&& request)
215 {
216     return downcast<CachedCSSStyleSheet>(requestResource(CachedResource::CSSStyleSheet, WTFMove(request)).get());
217 }
218
219 CachedResourceHandle<CachedCSSStyleSheet> CachedResourceLoader::requestUserCSSStyleSheet(CachedResourceRequest&& request)
220 {
221 #if ENABLE(CACHE_PARTITIONING)
222     ASSERT(document());
223     request.setDomainForCachePartition(*document());
224 #endif
225
226     auto& memoryCache = MemoryCache::singleton();
227     if (request.allowsCaching()) {
228         if (CachedResource* existing = memoryCache.resourceForRequest(request.resourceRequest(), sessionID())) {
229             if (is<CachedCSSStyleSheet>(*existing))
230                 return downcast<CachedCSSStyleSheet>(existing);
231             memoryCache.remove(*existing);
232         }
233     }
234
235     request.removeFragmentIdentifierIfNeeded();
236
237     CachedResourceHandle<CachedCSSStyleSheet> userSheet = new CachedCSSStyleSheet(WTFMove(request), sessionID());
238
239     if (userSheet->allowsCaching())
240         memoryCache.add(*userSheet);
241     // FIXME: loadResource calls setOwningCachedResourceLoader() if the resource couldn't be added to cache. Does this function need to call it, too?
242
243     userSheet->load(*this);
244     return userSheet;
245 }
246
247 CachedResourceHandle<CachedScript> CachedResourceLoader::requestScript(CachedResourceRequest&& request)
248 {
249     return downcast<CachedScript>(requestResource(CachedResource::Script, WTFMove(request)).get());
250 }
251
252 #if ENABLE(XSLT)
253 CachedResourceHandle<CachedXSLStyleSheet> CachedResourceLoader::requestXSLStyleSheet(CachedResourceRequest&& request)
254 {
255     return downcast<CachedXSLStyleSheet>(requestResource(CachedResource::XSLStyleSheet, WTFMove(request)).get());
256 }
257 #endif
258
259 CachedResourceHandle<CachedSVGDocument> CachedResourceLoader::requestSVGDocument(CachedResourceRequest&& request)
260 {
261     return downcast<CachedSVGDocument>(requestResource(CachedResource::SVGDocumentResource, WTFMove(request)).get());
262 }
263
264 #if ENABLE(LINK_PREFETCH)
265 CachedResourceHandle<CachedResource> CachedResourceLoader::requestLinkResource(CachedResource::Type type, CachedResourceRequest&& request)
266 {
267     ASSERT(frame());
268     ASSERT(type == CachedResource::LinkPrefetch || type == CachedResource::LinkSubresource);
269     return requestResource(type, WTFMove(request));
270 }
271 #endif
272
273 CachedResourceHandle<CachedRawResource> CachedResourceLoader::requestMedia(CachedResourceRequest&& request)
274 {
275     return downcast<CachedRawResource>(requestResource(CachedResource::MediaResource, WTFMove(request)).get());
276 }
277
278 CachedResourceHandle<CachedRawResource> CachedResourceLoader::requestRawResource(CachedResourceRequest&& request)
279 {
280     return downcast<CachedRawResource>(requestResource(CachedResource::RawResource, WTFMove(request)).get());
281 }
282
283 CachedResourceHandle<CachedRawResource> CachedResourceLoader::requestMainResource(CachedResourceRequest&& request)
284 {
285     return downcast<CachedRawResource>(requestResource(CachedResource::MainResource, WTFMove(request)).get());
286 }
287
288 static MixedContentChecker::ContentType contentTypeFromResourceType(CachedResource::Type type)
289 {
290     switch (type) {
291     // https://w3c.github.io/webappsec-mixed-content/#category-optionally-blockable
292     // Editor's Draft, 11 February 2016
293     // 3.1. Optionally-blockable Content
294     case CachedResource::ImageResource:
295     case CachedResource::MediaResource:
296             return MixedContentChecker::ContentType::ActiveCanWarn;
297
298     case CachedResource::CSSStyleSheet:
299     case CachedResource::Script:
300     case CachedResource::FontResource:
301         return MixedContentChecker::ContentType::Active;
302
303 #if ENABLE(SVG_FONTS)
304     case CachedResource::SVGFontResource:
305         return MixedContentChecker::ContentType::Active;
306 #endif
307
308     case CachedResource::RawResource:
309     case CachedResource::SVGDocumentResource:
310         return MixedContentChecker::ContentType::Active;
311 #if ENABLE(XSLT)
312     case CachedResource::XSLStyleSheet:
313         return MixedContentChecker::ContentType::Active;
314 #endif
315
316 #if ENABLE(LINK_PREFETCH)
317     case CachedResource::LinkPrefetch:
318     case CachedResource::LinkSubresource:
319         return MixedContentChecker::ContentType::Active;
320 #endif
321
322 #if ENABLE(VIDEO_TRACK)
323     case CachedResource::TextTrackResource:
324         return MixedContentChecker::ContentType::Active;
325 #endif
326     default:
327         ASSERT_NOT_REACHED();
328         return MixedContentChecker::ContentType::Active;
329     }
330 }
331
332 bool CachedResourceLoader::checkInsecureContent(CachedResource::Type type, const URL& url) const
333 {
334     if (!canRequestInContentDispositionAttachmentSandbox(type, url))
335         return false;
336
337     switch (type) {
338     case CachedResource::Script:
339 #if ENABLE(XSLT)
340     case CachedResource::XSLStyleSheet:
341 #endif
342     case CachedResource::SVGDocumentResource:
343     case CachedResource::CSSStyleSheet:
344         // These resource can inject script into the current document (Script,
345         // XSL) or exfiltrate the content of the current document (CSS).
346         if (Frame* frame = this->frame()) {
347             if (!frame->loader().mixedContentChecker().canRunInsecureContent(m_document->securityOrigin(), url))
348                 return false;
349             Frame& top = frame->tree().top();
350             if (&top != frame && !top.loader().mixedContentChecker().canRunInsecureContent(top.document()->securityOrigin(), url))
351                 return false;
352         }
353         break;
354 #if ENABLE(VIDEO_TRACK)
355     case CachedResource::TextTrackResource:
356 #endif
357     case CachedResource::MediaResource:
358     case CachedResource::RawResource:
359     case CachedResource::ImageResource:
360 #if ENABLE(SVG_FONTS)
361     case CachedResource::SVGFontResource:
362 #endif
363     case CachedResource::FontResource: {
364         // These resources can corrupt only the frame's pixels.
365         if (Frame* frame = this->frame()) {
366             if (!frame->loader().mixedContentChecker().canDisplayInsecureContent(m_document->securityOrigin(), contentTypeFromResourceType(type), url, MixedContentChecker::AlwaysDisplayInNonStrictMode::Yes))
367                 return false;
368             Frame& topFrame = frame->tree().top();
369             if (!topFrame.loader().mixedContentChecker().canDisplayInsecureContent(topFrame.document()->securityOrigin(), contentTypeFromResourceType(type), url))
370                 return false;
371         }
372         break;
373     }
374     case CachedResource::MainResource:
375 #if ENABLE(LINK_PREFETCH)
376     case CachedResource::LinkPrefetch:
377     case CachedResource::LinkSubresource:
378         // Prefetch cannot affect the current document.
379 #endif
380         break;
381     }
382     return true;
383 }
384
385 bool CachedResourceLoader::allowedByContentSecurityPolicy(CachedResource::Type type, const URL& url, const ResourceLoaderOptions& options, ContentSecurityPolicy::RedirectResponseReceived redirectResponseReceived) const
386 {
387     if (options.contentSecurityPolicyImposition == ContentSecurityPolicyImposition::SkipPolicyCheck)
388         return true;
389
390     ASSERT(m_document);
391     ASSERT(m_document->contentSecurityPolicy());
392
393     switch (type) {
394 #if ENABLE(XSLT)
395     case CachedResource::XSLStyleSheet:
396 #endif
397     case CachedResource::Script:
398         if (!m_document->contentSecurityPolicy()->allowScriptFromSource(url, redirectResponseReceived))
399             return false;
400         break;
401     case CachedResource::CSSStyleSheet:
402         if (!m_document->contentSecurityPolicy()->allowStyleFromSource(url, redirectResponseReceived))
403             return false;
404         break;
405     case CachedResource::SVGDocumentResource:
406     case CachedResource::ImageResource:
407         if (!m_document->contentSecurityPolicy()->allowImageFromSource(url, redirectResponseReceived))
408             return false;
409         break;
410 #if ENABLE(SVG_FONTS)
411     case CachedResource::SVGFontResource:
412 #endif
413     case CachedResource::FontResource:
414         if (!m_document->contentSecurityPolicy()->allowFontFromSource(url, redirectResponseReceived))
415             return false;
416         break;
417     case CachedResource::MediaResource:
418 #if ENABLE(VIDEO_TRACK)
419     case CachedResource::TextTrackResource:
420 #endif
421         if (!m_document->contentSecurityPolicy()->allowMediaFromSource(url, redirectResponseReceived))
422             return false;
423         break;
424     case CachedResource::RawResource:
425         return true;
426     default:
427         ASSERT_NOT_REACHED();
428     }
429
430     return true;
431 }
432
433 static inline bool isSameOriginDataURL(const URL& url, const ResourceLoaderOptions& options)
434 {
435     // FIXME: Remove same-origin data URL flag since it was removed from fetch spec (https://github.com/whatwg/fetch/issues/381).
436     return url.protocolIsData() && options.sameOriginDataURLFlag == SameOriginDataURLFlag::Set;
437 }
438
439 bool CachedResourceLoader::canRequest(CachedResource::Type type, const URL& url, const CachedResourceRequest& request, ForPreload forPreload)
440 {
441     auto& options = request.options();
442
443     if (document() && !document()->securityOrigin()->canDisplay(url)) {
444         if (forPreload == ForPreload::No)
445             FrameLoader::reportLocalLoadFailed(frame(), url.stringCenterEllipsizedToLength());
446         LOG(ResourceLoading, "CachedResourceLoader::requestResource URL was not allowed by SecurityOrigin::canDisplay");
447         return false;
448     }
449
450     if (options.mode == FetchOptions::Mode::SameOrigin && !m_document->securityOrigin()->canRequest(url) && !isSameOriginDataURL(url, options)) {
451         printAccessDeniedMessage(url);
452         return false;
453     }
454
455     if (!allowedByContentSecurityPolicy(type, url, options, ContentSecurityPolicy::RedirectResponseReceived::No))
456         return false;
457
458     // SVG Images have unique security rules that prevent all subresource requests except for data urls.
459     if (type != CachedResource::MainResource && frame() && frame()->page()) {
460         if (frame()->page()->chrome().client().isSVGImageChromeClient() && !url.protocolIsData())
461             return false;
462     }
463
464     // Last of all, check for insecure content. We do this last so that when folks block insecure content with a CSP policy, they don't get a warning.
465     // They'll still get a warning in the console about CSP blocking the load.
466
467     // FIXME: Should we consider whether the request is for preload here?
468     if (!checkInsecureContent(type, url))
469         return false;
470
471     return true;
472 }
473
474 // FIXME: Should we find a way to know whether the redirection is for a preload request like we do for CachedResourceLoader::canRequest?
475 bool CachedResourceLoader::canRequestAfterRedirection(CachedResource::Type type, const URL& url, const ResourceLoaderOptions& options) const
476 {
477     if (document() && !document()->securityOrigin()->canDisplay(url)) {
478         FrameLoader::reportLocalLoadFailed(frame(), url.stringCenterEllipsizedToLength());
479         LOG(ResourceLoading, "CachedResourceLoader::requestResource URL was not allowed by SecurityOrigin::canDisplay");
480         return false;
481     }
482
483     // FIXME: According to https://fetch.spec.whatwg.org/#http-redirect-fetch, we should check that the URL is HTTP(s) except if in navigation mode.
484     // But we currently allow at least data URLs to be loaded.
485
486     if (options.mode == FetchOptions::Mode::SameOrigin && !m_document->securityOrigin()->canRequest(url)) {
487         printAccessDeniedMessage(url);
488         return false;
489     }
490
491     if (!allowedByContentSecurityPolicy(type, url, options, ContentSecurityPolicy::RedirectResponseReceived::Yes))
492         return false;
493
494     // Last of all, check for insecure content. We do this last so that when folks block insecure content with a CSP policy, they don't get a warning.
495     // They'll still get a warning in the console about CSP blocking the load.
496     if (!checkInsecureContent(type, url))
497         return false;
498
499     return true;
500 }
501
502 bool CachedResourceLoader::updateRequestAfterRedirection(CachedResource::Type type, ResourceRequest& request, const ResourceLoaderOptions& options)
503 {
504     ASSERT(m_documentLoader);
505     if (auto* document = m_documentLoader->cachedResourceLoader().document())
506         upgradeInsecureResourceRequestIfNeeded(request, *document);
507
508     // FIXME: We might want to align the checks done here with the ones done in CachedResourceLoader::requestResource, content extensions blocking in particular.
509
510     return canRequestAfterRedirection(type, request.url(), options);
511 }
512
513 bool CachedResourceLoader::canRequestInContentDispositionAttachmentSandbox(CachedResource::Type type, const URL& url) const
514 {
515     Document* document;
516
517     // FIXME: Do we want to expand this to all resource types that the mixed content checker would consider active content?
518     switch (type) {
519     case CachedResource::MainResource:
520         if (auto ownerElement = frame() ? frame()->ownerElement() : nullptr) {
521             document = &ownerElement->document();
522             break;
523         }
524         return true;
525     case CachedResource::CSSStyleSheet:
526         document = m_document;
527         break;
528     default:
529         return true;
530     }
531
532     if (!document->shouldEnforceContentDispositionAttachmentSandbox() || document->securityOrigin()->canRequest(url))
533         return true;
534
535     String message = "Unsafe attempt to load URL " + url.stringCenterEllipsizedToLength() + " from document with Content-Disposition: attachment at URL " + document->url().stringCenterEllipsizedToLength() + ".";
536     document->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
537     return false;
538 }
539
540 bool CachedResourceLoader::shouldContinueAfterNotifyingLoadedFromMemoryCache(const CachedResourceRequest& request, CachedResource* resource)
541 {
542     if (!resource || !frame() || resource->status() != CachedResource::Cached)
543         return true;
544
545     ResourceRequest newRequest = ResourceRequest(resource->url());
546     newRequest.setInitiatorIdentifier(request.resourceRequest().initiatorIdentifier());
547     if (request.resourceRequest().hiddenFromInspector())
548         newRequest.setHiddenFromInspector(true);
549     frame()->loader().loadedResourceFromMemoryCache(resource, newRequest);
550
551     // FIXME <http://webkit.org/b/113251>: If the delegate modifies the request's
552     // URL, it is no longer appropriate to use this CachedResource.
553     return !newRequest.isNull();
554 }
555
556 bool CachedResourceLoader::shouldUpdateCachedResourceWithCurrentRequest(const CachedResource& resource, const CachedResourceRequest& request)
557 {
558     // WebKit is not supporting CORS for fonts (https://bugs.webkit.org/show_bug.cgi?id=86817), no need to update the resource before reusing it.
559     if (resource.type() == CachedResource::Type::FontResource)
560         return false;
561
562 #if ENABLE(SVG_FONTS)
563     if (resource.type() == CachedResource::Type::SVGFontResource)
564         return false;
565 #endif
566
567 #if ENABLE(XSLT)
568     // Load is same-origin, we do not check for CORS.
569     if (resource.type() == CachedResource::XSLStyleSheet)
570         return false;
571 #endif
572
573     // FIXME: We should enable resource reuse for these resource types
574     switch (resource.type()) {
575     case CachedResource::SVGDocumentResource:
576         return false;
577     case CachedResource::MainResource:
578         return false;
579 #if ENABLE(LINK_PREFETCH)
580     case CachedResource::LinkPrefetch:
581         return false;
582     case CachedResource::LinkSubresource:
583         return false;
584 #endif
585     default:
586         break;
587     }
588
589     if (resource.options().mode != request.options().mode || !originsMatch(request.origin(), resource.origin()))
590         return true;
591
592     if (resource.options().redirect != request.options().redirect && resource.hasRedirections())
593         return true;
594
595     return false;
596 }
597
598 static inline bool isResourceSuitableForDirectReuse(const CachedResource& resource, const CachedResourceRequest& request)
599 {
600     // FIXME: For being loaded requests, the response tainting may not be correctly computed if the fetch mode is not the same.
601     // Even if the fetch mode is the same, we are not sure that the resource can be reused (Vary: Origin header for instance).
602     // We should find a way to improve this.
603     if (resource.status() != CachedResource::Cached)
604         return false;
605
606     // If the cached resource has not followed redirections, it is incomplete and we should not use it.
607     // Let's make sure the memory cache has no such resource.
608     ASSERT(resource.response().type() != ResourceResponse::Type::Opaqueredirect);
609
610     // We could support redirect modes other than Follow in case of a redirected resource.
611     // This case is rare and is not worth optimizing currently.
612     if (request.options().redirect != FetchOptions::Redirect::Follow && resource.hasRedirections())
613         return false;
614
615     // FIXME: Implement reuse of cached raw resources.
616     if (resource.type() == CachedResource::Type::RawResource || resource.type() == CachedResource::Type::MediaResource)
617         return false;
618
619     return true;
620 }
621
622 CachedResourceHandle<CachedResource> CachedResourceLoader::updateCachedResourceWithCurrentRequest(const CachedResource& resource, CachedResourceRequest&& request)
623 {
624     if (!isResourceSuitableForDirectReuse(resource, request)) {
625         request.setCachingPolicy(CachingPolicy::DisallowCaching);
626         return loadResource(resource.type(), WTFMove(request));
627     }
628
629     auto resourceHandle = createResource(resource.type(), WTFMove(request), sessionID());
630     resourceHandle->loadFrom(resource);
631     return resourceHandle;
632 }
633
634 static inline void logMemoryCacheResourceRequest(Frame* frame, const String& description, const String& value = String())
635 {
636     if (!frame || !frame->page())
637         return;
638     if (value.isNull())
639         frame->page()->diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::resourceRequestKey(), description, ShouldSample::Yes);
640     else
641         frame->page()->diagnosticLoggingClient().logDiagnosticMessageWithValue(DiagnosticLoggingKeys::resourceRequestKey(), description, value, ShouldSample::Yes);
642 }
643
644 void CachedResourceLoader::prepareFetch(CachedResource::Type type, CachedResourceRequest& request)
645 {
646     // Implementing step 1 to 7 of https://fetch.spec.whatwg.org/#fetching
647
648     if (!request.origin() && document())
649         request.setOrigin(document()->securityOrigin());
650
651     request.setAcceptHeaderIfNone(type);
652
653     // Accept-Language value is handled in underlying port-specific code.
654     // FIXME: Decide whether to support client hints
655 }
656
657 void CachedResourceLoader::updateHTTPRequestHeaders(CachedResource::Type type, CachedResourceRequest& request)
658 {
659     // Implementing steps 7 to 12 of https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
660
661     // FIXME: We should reconcile handling of MainResource with other resources.
662     if (type != CachedResource::Type::MainResource) {
663         // In some cases we may try to load resources in frameless documents. Such loads always fail.
664         // FIXME: We shouldn't need to do the check on frame.
665         if (auto* frame = this->frame())
666             request.updateReferrerOriginAndUserAgentHeaders(frame->loader(), document() ? document()->referrerPolicy() : ReferrerPolicy::Default);
667     }
668
669     request.updateAccordingCacheMode();
670 }
671
672 CachedResourceHandle<CachedResource> CachedResourceLoader::requestResource(CachedResource::Type type, CachedResourceRequest&& request, ForPreload forPreload, DeferOption defer)
673 {
674     if (Document* document = this->document())
675         request.upgradeInsecureRequestIfNeeded(*document);
676
677     URL url = request.resourceRequest().url();
678
679     LOG(ResourceLoading, "CachedResourceLoader::requestResource '%s', charset '%s', priority=%d, forPreload=%u", url.stringCenterEllipsizedToLength().latin1().data(), request.charset().latin1().data(), request.priority() ? static_cast<int>(request.priority().value()) : -1, forPreload == ForPreload::Yes);
680
681     if (!url.isValid()) {
682         RELEASE_LOG_IF_ALLOWED("requestResource: URL is invalid (frame = %p)", frame());
683         return nullptr;
684     }
685
686     prepareFetch(type, request);
687
688     // We are passing url as well as request, as request url may contain a fragment identifier.
689     if (!canRequest(type, url, request, forPreload)) {
690         RELEASE_LOG_IF_ALLOWED("requestResource: Not allowed to request resource (frame = %p)", frame());
691         return nullptr;
692     }
693
694 #if ENABLE(CONTENT_EXTENSIONS)
695     if (frame() && frame()->mainFrame().page() && m_documentLoader) {
696         const auto& resourceRequest = request.resourceRequest();
697         auto blockedStatus = frame()->mainFrame().page()->userContentProvider().processContentExtensionRulesForLoad(resourceRequest.url(), toResourceType(type), *m_documentLoader);
698         request.applyBlockedStatus(blockedStatus);
699         if (blockedStatus.blockedLoad) {
700             RELEASE_LOG_IF_ALLOWED("requestResource: Resource blocked by content blocker (frame = %p)", frame());
701             if (type == CachedResource::Type::MainResource) {
702                 auto resource = createResource(type, WTFMove(request), sessionID());
703                 ASSERT(resource);
704                 resource->error(CachedResource::Status::LoadError);
705                 resource->setResourceError(ResourceError(ContentExtensions::WebKitContentBlockerDomain, 0, resourceRequest.url(), WEB_UI_STRING("The URL was blocked by a content blocker", "WebKitErrorBlockedByContentBlocker description")));
706                 return resource;
707             }
708             return nullptr;
709         }
710         if (blockedStatus.madeHTTPS
711             && type == CachedResource::Type::MainResource
712             && m_documentLoader->isLoadingMainResource()) {
713             // This is to make sure the correct 'new' URL shows in the location bar.
714             m_documentLoader->frameLoader()->client().dispatchDidChangeProvisionalURL();
715         }
716         url = request.resourceRequest().url(); // The content extension could have changed it from http to https.
717         url = MemoryCache::removeFragmentIdentifierIfNeeded(url); // Might need to remove fragment identifier again.
718     }
719 #endif
720
721 #if ENABLE(WEB_TIMING)
722     LoadTiming loadTiming;
723     loadTiming.markStartTimeAndFetchStart();
724 #endif
725
726     if (request.resourceRequest().url().protocolIsInHTTPFamily())
727         updateHTTPRequestHeaders(type, request);
728
729     auto& memoryCache = MemoryCache::singleton();
730     if (request.allowsCaching() && memoryCache.disabled()) {
731         DocumentResourceMap::iterator it = m_documentResources.find(url.string());
732         if (it != m_documentResources.end()) {
733             it->value->setOwningCachedResourceLoader(nullptr);
734             m_documentResources.remove(it);
735         }
736     }
737
738     // See if we can use an existing resource from the cache.
739     CachedResourceHandle<CachedResource> resource;
740 #if ENABLE(CACHE_PARTITIONING)
741     if (document())
742         request.setDomainForCachePartition(*document());
743 #endif
744
745     if (request.allowsCaching())
746         resource = memoryCache.resourceForRequest(request.resourceRequest(), sessionID());
747
748     logMemoryCacheResourceRequest(frame(), resource ? DiagnosticLoggingKeys::inMemoryCacheKey() : DiagnosticLoggingKeys::notInMemoryCacheKey());
749
750     RevalidationPolicy policy = determineRevalidationPolicy(type, request, resource.get(), forPreload, defer);
751     switch (policy) {
752     case Reload:
753         memoryCache.remove(*resource);
754         FALLTHROUGH;
755     case Load:
756         if (resource)
757             logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedKey());
758         resource = loadResource(type, WTFMove(request));
759         break;
760     case Revalidate:
761         if (resource)
762             logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::revalidatingKey());
763         resource = revalidateResource(WTFMove(request), *resource);
764         break;
765     case Use:
766         ASSERT(resource);
767         if (shouldUpdateCachedResourceWithCurrentRequest(*resource, request)) {
768             resource = updateCachedResourceWithCurrentRequest(*resource, WTFMove(request));
769             if (resource->status() != CachedResource::Status::Cached)
770                 policy = Load;
771         } else {
772             if (!shouldContinueAfterNotifyingLoadedFromMemoryCache(request, resource.get()))
773                 return nullptr;
774             logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::usedKey());
775             memoryCache.resourceAccessed(*resource);
776 #if ENABLE(WEB_TIMING)
777             if (document() && RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled()) {
778                 // FIXME (161170): The networkLoadTiming shouldn't be stored on the ResourceResponse.
779                 resource->response().networkLoadTiming().reset();
780                 loadTiming.setResponseEnd(monotonicallyIncreasingTime());
781                 m_resourceTimingInfo.storeResourceTimingInitiatorInformation(resource, request.initiatorName(), frame());
782                 m_resourceTimingInfo.addResourceTiming(resource.get(), *document(), loadTiming);
783             }
784 #endif
785             if (forPreload == ForPreload::No)
786                 resource->setLoadPriority(request.priority());
787         }
788         break;
789     }
790
791     if (!resource)
792         return nullptr;
793
794     if (forPreload == ForPreload::No && resource->loader() && resource->resourceRequest().ignoreForRequestCount()) {
795         resource->resourceRequest().setIgnoreForRequestCount(false);
796         incrementRequestCount(*resource);
797     }
798
799     if ((policy != Use || resource->stillNeedsLoad()) && defer == DeferOption::NoDefer) {
800         resource->load(*this);
801
802         // We don't support immediate loads, but we do support immediate failure.
803         if (resource->errorOccurred()) {
804             if (resource->allowsCaching() && resource->inCache())
805                 memoryCache.remove(*resource);
806             return nullptr;
807         }
808     }
809
810     if (document() && !document()->loadEventFinished() && !resource->resourceRequest().url().protocolIsData())
811         m_validatedURLs.add(resource->resourceRequest().url());
812
813     ASSERT(resource->url() == url.string());
814     m_documentResources.set(resource->url(), resource);
815     return resource;
816 }
817
818 void CachedResourceLoader::documentDidFinishLoadEvent()
819 {
820     m_validatedURLs.clear();
821 }
822
823 CachedResourceHandle<CachedResource> CachedResourceLoader::revalidateResource(CachedResourceRequest&& request, CachedResource& resource)
824 {
825     ASSERT(resource.inCache());
826     auto& memoryCache = MemoryCache::singleton();
827     ASSERT(!memoryCache.disabled());
828     ASSERT(resource.canUseCacheValidator());
829     ASSERT(!resource.resourceToRevalidate());
830     ASSERT(resource.sessionID() == sessionID());
831     ASSERT(resource.allowsCaching());
832
833 #if ENABLE(WEB_TIMING)
834     AtomicString initiatorName = request.initiatorName();
835 #endif
836     CachedResourceHandle<CachedResource> newResource = createResource(resource.type(), WTFMove(request), resource.sessionID());
837
838     LOG(ResourceLoading, "Resource %p created to revalidate %p", newResource.get(), &resource);
839     newResource->setResourceToRevalidate(&resource);
840
841     memoryCache.remove(resource);
842     memoryCache.add(*newResource);
843 #if ENABLE(WEB_TIMING)
844     if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
845         m_resourceTimingInfo.storeResourceTimingInitiatorInformation(newResource, initiatorName, frame());
846 #endif
847     return newResource;
848 }
849
850 CachedResourceHandle<CachedResource> CachedResourceLoader::loadResource(CachedResource::Type type, CachedResourceRequest&& request)
851 {
852     auto& memoryCache = MemoryCache::singleton();
853     ASSERT(!request.allowsCaching() || !memoryCache.resourceForRequest(request.resourceRequest(), sessionID())
854         || request.resourceRequest().cachePolicy() == DoNotUseAnyCache || request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData || request.resourceRequest().cachePolicy() == RefreshAnyCacheData);
855
856     LOG(ResourceLoading, "Loading CachedResource for '%s'.", request.resourceRequest().url().stringCenterEllipsizedToLength().latin1().data());
857
858 #if ENABLE(WEB_TIMING)
859     AtomicString initiatorName = request.initiatorName();
860 #endif
861     CachedResourceHandle<CachedResource> resource = createResource(type, WTFMove(request), sessionID());
862
863     if (resource->allowsCaching() && !memoryCache.add(*resource))
864         resource->setOwningCachedResourceLoader(this);
865 #if ENABLE(WEB_TIMING)
866     if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
867         m_resourceTimingInfo.storeResourceTimingInitiatorInformation(resource, initiatorName, frame());
868 #endif
869     return resource;
870 }
871
872 static void logRevalidation(const String& reason, DiagnosticLoggingClient& logClient)
873 {
874     logClient.logDiagnosticMessageWithValue(DiagnosticLoggingKeys::cachedResourceRevalidationKey(), DiagnosticLoggingKeys::reasonKey(), reason, ShouldSample::Yes);
875 }
876
877 static void logResourceRevalidationDecision(CachedResource::RevalidationDecision reason, const Frame* frame)
878 {
879     if (!frame || !frame->page())
880         return;
881     auto& logClient = frame->page()->diagnosticLoggingClient();
882     switch (reason) {
883     case CachedResource::RevalidationDecision::No:
884         break;
885     case CachedResource::RevalidationDecision::YesDueToExpired:
886         logRevalidation(DiagnosticLoggingKeys::isExpiredKey(), logClient);
887         break;
888     case CachedResource::RevalidationDecision::YesDueToNoStore:
889         logRevalidation(DiagnosticLoggingKeys::noStoreKey(), logClient);
890         break;
891     case CachedResource::RevalidationDecision::YesDueToNoCache:
892         logRevalidation(DiagnosticLoggingKeys::noCacheKey(), logClient);
893         break;
894     case CachedResource::RevalidationDecision::YesDueToCachePolicy:
895         logRevalidation(DiagnosticLoggingKeys::reloadKey(), logClient);
896         break;
897     }
898 }
899
900 CachedResourceLoader::RevalidationPolicy CachedResourceLoader::determineRevalidationPolicy(CachedResource::Type type, CachedResourceRequest& cachedResourceRequest, CachedResource* existingResource, ForPreload forPreload, DeferOption defer) const
901 {
902     auto& request = cachedResourceRequest.resourceRequest();
903
904     if (!existingResource)
905         return Load;
906
907     if (request.cachePolicy() == DoNotUseAnyCache || request.cachePolicy() == ReloadIgnoringCacheData)
908         return Load;
909
910     if (request.cachePolicy() == RefreshAnyCacheData)
911         return Reload;
912
913     // We already have a preload going for this URL.
914     if (forPreload == ForPreload::Yes && existingResource->isPreloaded())
915         return Use;
916
917     // If the same URL has been loaded as a different type, we need to reload.
918     if (existingResource->type() != type) {
919         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to type mismatch.");
920         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonTypeMismatchKey());
921         return Reload;
922     }
923
924     if (!existingResource->varyHeaderValuesMatch(request))
925         return Reload;
926
927     auto* textDecoder = existingResource->textResourceDecoder();
928     if (textDecoder && !textDecoder->hasEqualEncodingForCharset(cachedResourceRequest.charset()))
929         return Reload;
930
931     // FIXME: We should use the same cache policy for all resource types. The raw resource policy is overly strict
932     //        while the normal subresource policy is too loose.
933     if (existingResource->isMainOrMediaOrRawResource() && frame()) {
934         bool strictPolicyDisabled = frame()->loader().isStrictRawResourceValidationPolicyDisabledForTesting();
935         bool canReuseRawResource = strictPolicyDisabled || downcast<CachedRawResource>(*existingResource).canReuse(request);
936         if (!canReuseRawResource)
937             return Reload;
938     }
939
940     // Conditional requests should have failed canReuse check.
941     ASSERT(!request.isConditional());
942
943     // Do not load from cache if images are not enabled. The load for this image will be blocked in CachedImage::load.
944     if (defer == DeferOption::DeferredByClient)
945         return Reload;
946
947     // Don't reload resources while pasting or if cache mode allows stale resources.
948     if (m_allowStaleResources || cachedResourceRequest.options().cache == FetchOptions::Cache::ForceCache || cachedResourceRequest.options().cache == FetchOptions::Cache::OnlyIfCached)
949         return Use;
950
951     ASSERT(cachedResourceRequest.options().cache == FetchOptions::Cache::Default || cachedResourceRequest.options().cache == FetchOptions::Cache::NoCache);
952
953     // Always use preloads.
954     if (existingResource->isPreloaded())
955         return Use;
956
957     // We can find resources that are being validated from cache only when validation is just successfully completing.
958     if (existingResource->validationCompleting())
959         return Use;
960     ASSERT(!existingResource->validationInProgress());
961
962     // Validate the redirect chain.
963     bool cachePolicyIsHistoryBuffer = cachePolicy(type) == CachePolicyHistoryBuffer;
964     if (!existingResource->redirectChainAllowsReuse(cachePolicyIsHistoryBuffer ? ReuseExpiredRedirection : DoNotReuseExpiredRedirection)) {
965         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to not cached or expired redirections.");
966         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonRedirectChainKey());
967         return Reload;
968     }
969
970     // CachePolicyHistoryBuffer uses the cache except if this is a main resource with "cache-control: no-store".
971     if (cachePolicyIsHistoryBuffer) {
972         // FIXME: Ignoring "cache-control: no-cache" for sub-resources on history navigation but not the main
973         // resource is inconsistent. We should probably harmonize this.
974         if (!existingResource->response().cacheControlContainsNoStore() || type != CachedResource::MainResource)
975             return Use;
976     }
977
978     // Don't reuse resources with Cache-control: no-store.
979     if (existingResource->response().cacheControlContainsNoStore()) {
980         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to Cache-control: no-store.");
981         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonNoStoreKey());
982         return Reload;
983     }
984
985     // If credentials were sent with the previous request and won't be
986     // with this one, or vice versa, re-fetch the resource.
987     //
988     // This helps with the case where the server sends back
989     // "Access-Control-Allow-Origin: *" all the time, but some of the
990     // client's requests are made without CORS and some with.
991     if (existingResource->resourceRequest().allowCookies() != request.allowCookies()) {
992         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to difference in credentials settings.");
993         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonCredentialSettingsKey());
994         return Reload;
995     }
996
997     // During the initial load, avoid loading the same resource multiple times for a single document, even if the cache policies would tell us to.
998     if (document() && !document()->loadEventFinished() && m_validatedURLs.contains(existingResource->url()))
999         return Use;
1000
1001     // CachePolicyReload always reloads
1002     if (cachePolicy(type) == CachePolicyReload) {
1003         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to CachePolicyReload.");
1004         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonReloadKey());
1005         return Reload;
1006     }
1007     
1008     // We'll try to reload the resource if it failed last time.
1009     if (existingResource->errorOccurred()) {
1010         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicye reloading due to resource being in the error state");
1011         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonErrorKey());
1012         return Reload;
1013     }
1014
1015     if (existingResource->isLoading()) {
1016         // Do not use cached main resources that are still loading because sharing
1017         // loading CachedResources in this case causes issues with regards to cancellation.
1018         // If one of the DocumentLoader clients decides to cancel the load, then the load
1019         // would be cancelled for all other DocumentLoaders as well.
1020         if (type == CachedResource::Type::MainResource)
1021             return Reload;
1022         // For cached subresources that are still loading we ignore the cache policy.
1023         return Use;
1024     }
1025
1026     auto revalidationDecision = existingResource->makeRevalidationDecision(cachePolicy(type));
1027     logResourceRevalidationDecision(revalidationDecision, frame());
1028
1029     // Check if the cache headers requires us to revalidate (cache expiration for example).
1030     if (revalidationDecision != CachedResource::RevalidationDecision::No) {
1031         // See if the resource has usable ETag or Last-modified headers.
1032         if (existingResource->canUseCacheValidator())
1033             return Revalidate;
1034         
1035         // No, must reload.
1036         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to missing cache validators.");
1037         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonMustRevalidateNoValidatorKey());
1038         return Reload;
1039     }
1040
1041     return Use;
1042 }
1043
1044 void CachedResourceLoader::printAccessDeniedMessage(const URL& url) const
1045 {
1046     if (url.isNull())
1047         return;
1048
1049     if (!frame())
1050         return;
1051
1052     String message;
1053     if (!m_document || m_document->url().isNull())
1054         message = "Unsafe attempt to load URL " + url.stringCenterEllipsizedToLength() + '.';
1055     else
1056         message = "Unsafe attempt to load URL " + url.stringCenterEllipsizedToLength() + " from frame with URL " + m_document->url().stringCenterEllipsizedToLength() + ". Domains, protocols and ports must match.\n";
1057
1058     frame()->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
1059 }
1060
1061 void CachedResourceLoader::setAutoLoadImages(bool enable)
1062 {
1063     if (enable == m_autoLoadImages)
1064         return;
1065
1066     m_autoLoadImages = enable;
1067
1068     if (!m_autoLoadImages)
1069         return;
1070
1071     reloadImagesIfNotDeferred();
1072 }
1073
1074 void CachedResourceLoader::setImagesEnabled(bool enable)
1075 {
1076     if (enable == m_imagesEnabled)
1077         return;
1078
1079     m_imagesEnabled = enable;
1080
1081     if (!m_imagesEnabled)
1082         return;
1083
1084     reloadImagesIfNotDeferred();
1085 }
1086
1087 bool CachedResourceLoader::clientDefersImage(const URL&) const
1088 {
1089     return !m_imagesEnabled;
1090 }
1091
1092 bool CachedResourceLoader::shouldPerformImageLoad(const URL& url) const
1093 {
1094     return m_autoLoadImages || url.protocolIsData();
1095 }
1096
1097 bool CachedResourceLoader::shouldDeferImageLoad(const URL& url) const
1098 {
1099     return clientDefersImage(url) || !shouldPerformImageLoad(url);
1100 }
1101
1102 void CachedResourceLoader::reloadImagesIfNotDeferred()
1103 {
1104     for (auto& resource : m_documentResources.values()) {
1105         if (is<CachedImage>(*resource) && resource->stillNeedsLoad() && !clientDefersImage(resource->url()))
1106             downcast<CachedImage>(*resource).load(*this);
1107     }
1108 }
1109
1110 CachePolicy CachedResourceLoader::cachePolicy(CachedResource::Type type) const
1111 {
1112     Frame* frame = this->frame();
1113     if (!frame)
1114         return CachePolicyVerify;
1115
1116     if (type != CachedResource::MainResource)
1117         return frame->loader().subresourceCachePolicy();
1118
1119     if (Page* page = frame->page()) {
1120         if (page->isResourceCachingDisabled())
1121             return CachePolicyReload;
1122     }
1123
1124     switch (frame->loader().loadType()) {
1125     case FrameLoadType::ReloadFromOrigin:
1126     case FrameLoadType::Reload:
1127         return CachePolicyReload;
1128     case FrameLoadType::Back:
1129     case FrameLoadType::Forward:
1130     case FrameLoadType::IndexedBackForward:
1131         // Do not revalidate cached main resource on back/forward navigation.
1132         return CachePolicyHistoryBuffer;
1133     default:
1134         return CachePolicyVerify;
1135     }
1136 }
1137
1138 void CachedResourceLoader::removeCachedResource(CachedResource& resource)
1139 {
1140 #ifndef NDEBUG
1141     DocumentResourceMap::iterator it = m_documentResources.find(resource.url());
1142     if (it != m_documentResources.end())
1143         ASSERT(it->value.get() == &resource);
1144 #endif
1145     m_documentResources.remove(resource.url());
1146 }
1147
1148 void CachedResourceLoader::loadDone(CachedResource* resource, bool shouldPerformPostLoadActions)
1149 {
1150     RefPtr<DocumentLoader> protectDocumentLoader(m_documentLoader);
1151     RefPtr<Document> protectDocument(m_document);
1152
1153 #if ENABLE(WEB_TIMING)
1154     if (resource && document() && RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
1155         m_resourceTimingInfo.addResourceTiming(resource, *document(), resource->loader()->loadTiming());
1156 #else
1157     UNUSED_PARAM(resource);
1158 #endif
1159
1160     if (frame())
1161         frame()->loader().loadDone();
1162
1163     if (shouldPerformPostLoadActions)
1164         performPostLoadActions();
1165
1166     if (!m_garbageCollectDocumentResourcesTimer.isActive())
1167         m_garbageCollectDocumentResourcesTimer.startOneShot(0);
1168 }
1169
1170 // Garbage collecting m_documentResources is a workaround for the
1171 // CachedResourceHandles on the RHS being strong references. Ideally this
1172 // would be a weak map, however CachedResourceHandles perform additional
1173 // bookkeeping on CachedResources, so instead pseudo-GC them -- when the
1174 // reference count reaches 1, m_documentResources is the only reference, so
1175 // remove it from the map.
1176 void CachedResourceLoader::garbageCollectDocumentResources()
1177 {
1178     typedef Vector<String, 10> StringVector;
1179     StringVector resourcesToDelete;
1180
1181     for (auto& resource : m_documentResources) {
1182         if (resource.value->hasOneHandle()) {
1183             resourcesToDelete.append(resource.key);
1184             resource.value->setOwningCachedResourceLoader(nullptr);
1185         }
1186     }
1187
1188     for (auto& resource : resourcesToDelete)
1189         m_documentResources.remove(resource);
1190 }
1191
1192 void CachedResourceLoader::performPostLoadActions()
1193 {
1194     platformStrategies()->loaderStrategy()->servePendingRequests();
1195 }
1196
1197 void CachedResourceLoader::incrementRequestCount(const CachedResource& resource)
1198 {
1199     if (resource.ignoreForRequestCount())
1200         return;
1201
1202     ++m_requestCount;
1203 }
1204
1205 void CachedResourceLoader::decrementRequestCount(const CachedResource& resource)
1206 {
1207     if (resource.ignoreForRequestCount())
1208         return;
1209
1210     --m_requestCount;
1211     ASSERT(m_requestCount > -1);
1212 }
1213
1214 CachedResourceHandle<CachedResource> CachedResourceLoader::preload(CachedResource::Type type, CachedResourceRequest&& request)
1215 {
1216     if (request.charset().isEmpty() && (type == CachedResource::Script || type == CachedResource::CSSStyleSheet))
1217         request.setCharset(m_document->charset());
1218
1219     CachedResourceHandle<CachedResource> resource = requestResource(type, WTFMove(request), ForPreload::Yes);
1220     if (!resource || (m_preloads && m_preloads->contains(resource.get())))
1221         return nullptr;
1222     // Fonts need special treatment since just creating the resource doesn't trigger a load.
1223     if (type == CachedResource::FontResource)
1224         downcast<CachedFont>(resource.get())->beginLoadIfNeeded(*this);
1225     resource->increasePreloadCount();
1226
1227     if (!m_preloads)
1228         m_preloads = std::make_unique<ListHashSet<CachedResource*>>();
1229     m_preloads->add(resource.get());
1230
1231 #if PRELOAD_DEBUG
1232     printf("PRELOADING %s\n",  resource->url().latin1().data());
1233 #endif
1234     return resource;
1235 }
1236
1237 bool CachedResourceLoader::isPreloaded(const String& urlString) const
1238 {
1239     const URL& url = m_document->completeURL(urlString);
1240
1241     if (m_preloads) {
1242         for (auto& resource : *m_preloads) {
1243             if (resource->url() == url)
1244                 return true;
1245         }
1246     }
1247     return false;
1248 }
1249
1250 void CachedResourceLoader::clearPreloads()
1251 {
1252 #if PRELOAD_DEBUG
1253     printPreloadStats();
1254 #endif
1255     if (!m_preloads)
1256         return;
1257
1258     for (auto* resource : *m_preloads) {
1259         resource->decreasePreloadCount();
1260         bool deleted = resource->deleteIfPossible();
1261         if (!deleted && resource->preloadResult() == CachedResource::PreloadNotReferenced)
1262             MemoryCache::singleton().remove(*resource);
1263     }
1264     m_preloads = nullptr;
1265 }
1266
1267 #if PRELOAD_DEBUG
1268 void CachedResourceLoader::printPreloadStats()
1269 {
1270     unsigned scripts = 0;
1271     unsigned scriptMisses = 0;
1272     unsigned stylesheets = 0;
1273     unsigned stylesheetMisses = 0;
1274     unsigned images = 0;
1275     unsigned imageMisses = 0;
1276     for (auto& resource : m_preloads) {
1277         if (resource->preloadResult() == CachedResource::PreloadNotReferenced)
1278             printf("!! UNREFERENCED PRELOAD %s\n", resource->url().latin1().data());
1279         else if (resource->preloadResult() == CachedResource::PreloadReferencedWhileComplete)
1280             printf("HIT COMPLETE PRELOAD %s\n", resource->url().latin1().data());
1281         else if (resource->preloadResult() == CachedResource::PreloadReferencedWhileLoading)
1282             printf("HIT LOADING PRELOAD %s\n", resource->url().latin1().data());
1283
1284         if (resource->type() == CachedResource::Script) {
1285             scripts++;
1286             if (resource->preloadResult() < CachedResource::PreloadReferencedWhileLoading)
1287                 scriptMisses++;
1288         } else if (resource->type() == CachedResource::CSSStyleSheet) {
1289             stylesheets++;
1290             if (resource->preloadResult() < CachedResource::PreloadReferencedWhileLoading)
1291                 stylesheetMisses++;
1292         } else {
1293             images++;
1294             if (resource->preloadResult() < CachedResource::PreloadReferencedWhileLoading)
1295                 imageMisses++;
1296         }
1297
1298         if (resource->errorOccurred() && resource->preloadResult() == CachedResource::PreloadNotReferenced)
1299             MemoryCache::singleton().remove(resource);
1300
1301         resource->decreasePreloadCount();
1302     }
1303     m_preloads = nullptr;
1304
1305     if (scripts)
1306         printf("SCRIPTS: %d (%d hits, hit rate %d%%)\n", scripts, scripts - scriptMisses, (scripts - scriptMisses) * 100 / scripts);
1307     if (stylesheets)
1308         printf("STYLESHEETS: %d (%d hits, hit rate %d%%)\n", stylesheets, stylesheets - stylesheetMisses, (stylesheets - stylesheetMisses) * 100 / stylesheets);
1309     if (images)
1310         printf("IMAGES:  %d (%d hits, hit rate %d%%)\n", images, images - imageMisses, (images - imageMisses) * 100 / images);
1311 }
1312 #endif
1313
1314 const ResourceLoaderOptions& CachedResourceLoader::defaultCachedResourceOptions()
1315 {
1316     static NeverDestroyed<ResourceLoaderOptions> options(SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientCredentialPolicy::MayAskClientForCredentials, FetchOptions::Credentials::Include, DoSecurityCheck, FetchOptions::Mode::NoCors, DoNotIncludeCertificateInfo, ContentSecurityPolicyImposition::DoPolicyCheck, DefersLoadingPolicy::AllowDefersLoading, CachingPolicy::AllowCaching);
1317     return options;
1318 }
1319
1320 bool CachedResourceLoader::isAlwaysOnLoggingAllowed() const
1321 {
1322     return m_documentLoader ? m_documentLoader->isAlwaysOnLoggingAllowed() : true;
1323 }
1324
1325 }