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