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