Drop ResourceLoadPriorityUnresolved resource load priority and use Optional<> instead
[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, 2005, 2006, 2007, 2008, 2009, 2010, 2011 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 "ContentSecurityPolicy.h"
42 #include "DOMWindow.h"
43 #include "DiagnosticLoggingClient.h"
44 #include "DiagnosticLoggingKeys.h"
45 #include "Document.h"
46 #include "DocumentLoader.h"
47 #include "Frame.h"
48 #include "FrameLoader.h"
49 #include "FrameLoaderClient.h"
50 #include "HTMLElement.h"
51 #include "HTMLFrameOwnerElement.h"
52 #include "LoaderStrategy.h"
53 #include "Logging.h"
54 #include "MainFrame.h"
55 #include "MemoryCache.h"
56 #include "Page.h"
57 #include "PingLoader.h"
58 #include "PlatformStrategies.h"
59 #include "RenderElement.h"
60 #include "ResourceLoadScheduler.h"
61 #include "ScriptController.h"
62 #include "SecurityOrigin.h"
63 #include "SessionID.h"
64 #include "Settings.h"
65 #include "UserContentController.h"
66 #include <wtf/text/CString.h>
67 #include <wtf/text/WTFString.h>
68
69 #if ENABLE(VIDEO_TRACK)
70 #include "CachedTextTrack.h"
71 #endif
72
73 #if ENABLE(RESOURCE_TIMING)
74 #include "Performance.h"
75 #endif
76
77 #define PRELOAD_DEBUG 0
78
79 namespace WebCore {
80
81 static CachedResource* createResource(CachedResource::Type type, ResourceRequest& request, const String& charset, SessionID sessionID)
82 {
83     switch (type) {
84     case CachedResource::ImageResource:
85         return new CachedImage(request, sessionID);
86     case CachedResource::CSSStyleSheet:
87         return new CachedCSSStyleSheet(request, charset, sessionID);
88     case CachedResource::Script:
89         return new CachedScript(request, charset, sessionID);
90     case CachedResource::SVGDocumentResource:
91         return new CachedSVGDocument(request, sessionID);
92 #if ENABLE(SVG_FONTS)
93     case CachedResource::SVGFontResource:
94         return new CachedSVGFont(request, sessionID);
95 #endif
96     case CachedResource::FontResource:
97         return new CachedFont(request, sessionID);
98     case CachedResource::RawResource:
99     case CachedResource::MainResource:
100         return new CachedRawResource(request, type, sessionID);
101 #if ENABLE(XSLT)
102     case CachedResource::XSLStyleSheet:
103         return new CachedXSLStyleSheet(request, sessionID);
104 #endif
105 #if ENABLE(LINK_PREFETCH)
106     case CachedResource::LinkPrefetch:
107         return new CachedResource(request, CachedResource::LinkPrefetch, sessionID);
108     case CachedResource::LinkSubresource:
109         return new CachedResource(request, CachedResource::LinkSubresource, sessionID);
110 #endif
111 #if ENABLE(VIDEO_TRACK)
112     case CachedResource::TextTrackResource:
113         return new CachedTextTrack(request, sessionID);
114 #endif
115     }
116     ASSERT_NOT_REACHED();
117     return 0;
118 }
119
120 CachedResourceLoader::CachedResourceLoader(DocumentLoader* documentLoader)
121     : m_document(0)
122     , m_documentLoader(documentLoader)
123     , m_requestCount(0)
124     , m_garbageCollectDocumentResourcesTimer(*this, &CachedResourceLoader::garbageCollectDocumentResourcesTimerFired)
125     , m_autoLoadImages(true)
126     , m_imagesEnabled(true)
127     , m_allowStaleResources(false)
128 {
129 }
130
131 CachedResourceLoader::~CachedResourceLoader()
132 {
133     m_documentLoader = 0;
134     m_document = 0;
135
136     clearPreloads();
137     DocumentResourceMap::iterator end = m_documentResources.end();
138     for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != end; ++it)
139         it->value->setOwningCachedResourceLoader(0);
140
141     // Make sure no requests still point to this CachedResourceLoader
142     ASSERT(m_requestCount == 0);
143 }
144
145 CachedResource* CachedResourceLoader::cachedResource(const String& resourceURL) const 
146 {
147     URL url = m_document->completeURL(resourceURL);
148     return cachedResource(url); 
149 }
150
151 CachedResource* CachedResourceLoader::cachedResource(const URL& resourceURL) const
152 {
153     URL url = MemoryCache::removeFragmentIdentifierIfNeeded(resourceURL);
154     return m_documentResources.get(url).get(); 
155 }
156
157 Frame* CachedResourceLoader::frame() const
158 {
159     return m_documentLoader ? m_documentLoader->frame() : 0;
160 }
161
162 SessionID CachedResourceLoader::sessionID() const
163 {
164     SessionID sessionID = SessionID::defaultSessionID();
165
166     if (Frame* f = frame())
167         sessionID = f->page()->sessionID();
168
169     return sessionID;
170 }
171
172 CachedResourceHandle<CachedImage> CachedResourceLoader::requestImage(CachedResourceRequest& request)
173 {
174     if (Frame* frame = this->frame()) {
175         if (frame->loader().pageDismissalEventBeingDispatched() != FrameLoader::NoDismissal) {
176             URL requestURL = request.resourceRequest().url();
177             if (requestURL.isValid() && canRequest(CachedResource::ImageResource, requestURL, request.options(), request.forPreload()))
178                 PingLoader::loadImage(*frame, requestURL);
179             return nullptr;
180         }
181     }
182     
183     request.setDefer(clientDefersImage(request.resourceRequest().url()) ? CachedResourceRequest::DeferredByClient : CachedResourceRequest::NoDefer);
184     return downcast<CachedImage>(requestResource(CachedResource::ImageResource, request).get());
185 }
186
187 CachedResourceHandle<CachedFont> CachedResourceLoader::requestFont(CachedResourceRequest& request, bool isSVG)
188 {
189 #if ENABLE(SVG_FONTS)
190     if (isSVG)
191         return downcast<CachedSVGFont>(requestResource(CachedResource::SVGFontResource, request).get());
192 #else
193     UNUSED_PARAM(isSVG);
194 #endif
195     return downcast<CachedFont>(requestResource(CachedResource::FontResource, request).get());
196 }
197
198 #if ENABLE(VIDEO_TRACK)
199 CachedResourceHandle<CachedTextTrack> CachedResourceLoader::requestTextTrack(CachedResourceRequest& request)
200 {
201     return downcast<CachedTextTrack>(requestResource(CachedResource::TextTrackResource, request).get());
202 }
203 #endif
204
205 CachedResourceHandle<CachedCSSStyleSheet> CachedResourceLoader::requestCSSStyleSheet(CachedResourceRequest& request)
206 {
207     return downcast<CachedCSSStyleSheet>(requestResource(CachedResource::CSSStyleSheet, request).get());
208 }
209
210 CachedResourceHandle<CachedCSSStyleSheet> CachedResourceLoader::requestUserCSSStyleSheet(CachedResourceRequest& request)
211 {
212     URL url = MemoryCache::removeFragmentIdentifierIfNeeded(request.resourceRequest().url());
213
214 #if ENABLE(CACHE_PARTITIONING)
215     request.mutableResourceRequest().setDomainForCachePartition(document()->topOrigin()->domainForCachePartition());
216 #endif
217
218     auto& memoryCache = MemoryCache::singleton();
219     if (CachedResource* existing = memoryCache.resourceForRequest(request.resourceRequest(), sessionID())) {
220         if (is<CachedCSSStyleSheet>(*existing))
221             return downcast<CachedCSSStyleSheet>(existing);
222         memoryCache.remove(*existing);
223     }
224     if (url.string() != request.resourceRequest().url())
225         request.mutableResourceRequest().setURL(url);
226
227     CachedResourceHandle<CachedCSSStyleSheet> userSheet = new CachedCSSStyleSheet(request.resourceRequest(), request.charset(), sessionID());
228
229     memoryCache.add(*userSheet);
230     // FIXME: loadResource calls setOwningCachedResourceLoader() if the resource couldn't be added to cache. Does this function need to call it, too?
231
232     userSheet->load(*this, ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, AskClientForAllCredentials, SkipSecurityCheck, UseDefaultOriginRestrictionsForType, DoNotIncludeCertificateInfo));
233     
234     return userSheet;
235 }
236
237 CachedResourceHandle<CachedScript> CachedResourceLoader::requestScript(CachedResourceRequest& request)
238 {
239     return downcast<CachedScript>(requestResource(CachedResource::Script, request).get());
240 }
241
242 #if ENABLE(XSLT)
243 CachedResourceHandle<CachedXSLStyleSheet> CachedResourceLoader::requestXSLStyleSheet(CachedResourceRequest& request)
244 {
245     return downcast<CachedXSLStyleSheet>(requestResource(CachedResource::XSLStyleSheet, request).get());
246 }
247 #endif
248
249 CachedResourceHandle<CachedSVGDocument> CachedResourceLoader::requestSVGDocument(CachedResourceRequest& request)
250 {
251     return downcast<CachedSVGDocument>(requestResource(CachedResource::SVGDocumentResource, request).get());
252 }
253
254 #if ENABLE(LINK_PREFETCH)
255 CachedResourceHandle<CachedResource> CachedResourceLoader::requestLinkResource(CachedResource::Type type, CachedResourceRequest& request)
256 {
257     ASSERT(frame());
258     ASSERT(type == CachedResource::LinkPrefetch || type == CachedResource::LinkSubresource);
259     return requestResource(type, request);
260 }
261 #endif
262
263 CachedResourceHandle<CachedRawResource> CachedResourceLoader::requestRawResource(CachedResourceRequest& request)
264 {
265     return downcast<CachedRawResource>(requestResource(CachedResource::RawResource, request).get());
266 }
267
268 CachedResourceHandle<CachedRawResource> CachedResourceLoader::requestMainResource(CachedResourceRequest& request)
269 {
270     return downcast<CachedRawResource>(requestResource(CachedResource::MainResource, request).get());
271 }
272
273 bool CachedResourceLoader::checkInsecureContent(CachedResource::Type type, const URL& url) const
274 {
275     switch (type) {
276     case CachedResource::Script:
277 #if ENABLE(XSLT)
278     case CachedResource::XSLStyleSheet:
279 #endif
280     case CachedResource::SVGDocumentResource:
281     case CachedResource::CSSStyleSheet:
282         // These resource can inject script into the current document (Script,
283         // XSL) or exfiltrate the content of the current document (CSS).
284         if (Frame* f = frame())
285             if (!f->loader().mixedContentChecker().canRunInsecureContent(m_document->securityOrigin(), url))
286                 return false;
287         break;
288 #if ENABLE(VIDEO_TRACK)
289     case CachedResource::TextTrackResource:
290 #endif
291     case CachedResource::RawResource:
292     case CachedResource::ImageResource:
293 #if ENABLE(SVG_FONTS)
294     case CachedResource::SVGFontResource:
295 #endif
296     case CachedResource::FontResource: {
297         // These resources can corrupt only the frame's pixels.
298         if (Frame* f = frame()) {
299             Frame& topFrame = f->tree().top();
300             if (!topFrame.loader().mixedContentChecker().canDisplayInsecureContent(topFrame.document()->securityOrigin(), url))
301                 return false;
302         }
303         break;
304     }
305     case CachedResource::MainResource:
306 #if ENABLE(LINK_PREFETCH)
307     case CachedResource::LinkPrefetch:
308     case CachedResource::LinkSubresource:
309         // Prefetch cannot affect the current document.
310 #endif
311         break;
312     }
313     return true;
314 }
315
316 bool CachedResourceLoader::canRequest(CachedResource::Type type, const URL& url, const ResourceLoaderOptions& options, bool forPreload)
317 {
318     if (document() && !document()->securityOrigin()->canDisplay(url)) {
319         if (!forPreload)
320             FrameLoader::reportLocalLoadFailed(frame(), url.stringCenterEllipsizedToLength());
321         LOG(ResourceLoading, "CachedResourceLoader::requestResource URL was not allowed by SecurityOrigin::canDisplay");
322         return 0;
323     }
324
325     // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
326     bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script().shouldBypassMainWorldContentSecurityPolicy());
327
328     // Some types of resources can be loaded only from the same origin.  Other
329     // types of resources, like Images, Scripts, and CSS, can be loaded from
330     // any URL.
331     switch (type) {
332     case CachedResource::MainResource:
333     case CachedResource::ImageResource:
334     case CachedResource::CSSStyleSheet:
335     case CachedResource::Script:
336 #if ENABLE(SVG_FONTS)
337     case CachedResource::SVGFontResource:
338 #endif
339     case CachedResource::FontResource:
340     case CachedResource::RawResource:
341 #if ENABLE(LINK_PREFETCH)
342     case CachedResource::LinkPrefetch:
343     case CachedResource::LinkSubresource:
344 #endif
345 #if ENABLE(VIDEO_TRACK)
346     case CachedResource::TextTrackResource:
347 #endif
348         if (options.requestOriginPolicy() == RestrictToSameOrigin && !m_document->securityOrigin()->canRequest(url)) {
349             printAccessDeniedMessage(url);
350             return false;
351         }
352         break;
353     case CachedResource::SVGDocumentResource:
354 #if ENABLE(XSLT)
355     case CachedResource::XSLStyleSheet:
356         if (!m_document->securityOrigin()->canRequest(url)) {
357             printAccessDeniedMessage(url);
358             return false;
359         }
360 #endif
361         break;
362     }
363
364     switch (type) {
365 #if ENABLE(XSLT)
366     case CachedResource::XSLStyleSheet:
367         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url))
368             return false;
369         break;
370 #endif
371     case CachedResource::Script:
372         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url))
373             return false;
374         if (frame() && !frame()->settings().isScriptEnabled())
375             return false;
376         break;
377     case CachedResource::CSSStyleSheet:
378         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowStyleFromSource(url))
379             return false;
380         break;
381     case CachedResource::SVGDocumentResource:
382     case CachedResource::ImageResource:
383         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowImageFromSource(url))
384             return false;
385         break;
386 #if ENABLE(SVG_FONTS)
387     case CachedResource::SVGFontResource:
388 #endif
389     case CachedResource::FontResource: {
390         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowFontFromSource(url))
391             return false;
392         break;
393     }
394     case CachedResource::MainResource:
395     case CachedResource::RawResource:
396 #if ENABLE(LINK_PREFETCH)
397     case CachedResource::LinkPrefetch:
398     case CachedResource::LinkSubresource:
399 #endif
400         break;
401 #if ENABLE(VIDEO_TRACK)
402     case CachedResource::TextTrackResource:
403         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url))
404             return false;
405         break;
406 #endif
407     }
408
409     // SVG Images have unique security rules that prevent all subresource requests except for data urls.
410     if (type != CachedResource::MainResource && frame() && frame()->page()) {
411         if (frame()->page()->chrome().client().isSVGImageChromeClient() && !url.protocolIsData())
412             return false;
413     }
414
415     // Last of all, check for insecure content. We do this last so that when
416     // folks block insecure content with a CSP policy, they don't get a warning.
417     // They'll still get a warning in the console about CSP blocking the load.
418
419     // FIXME: Should we consider forPreload here?
420     if (!checkInsecureContent(type, url))
421         return false;
422
423     return true;
424 }
425
426 bool CachedResourceLoader::shouldContinueAfterNotifyingLoadedFromMemoryCache(const CachedResourceRequest& request, CachedResource* resource)
427 {
428     if (!resource || !frame() || resource->status() != CachedResource::Cached)
429         return true;
430
431     ResourceRequest newRequest = ResourceRequest(resource->url());
432     if (request.resourceRequest().hiddenFromInspector())
433         newRequest.setHiddenFromInspector(true);
434     frame()->loader().loadedResourceFromMemoryCache(resource, newRequest);
435
436     // FIXME <http://webkit.org/b/113251>: If the delegate modifies the request's
437     // URL, it is no longer appropriate to use this CachedResource.
438     return !newRequest.isNull();
439 }
440
441 static inline void logMemoryCacheResourceRequest(Frame* frame, const String& description, const String& value = String())
442 {
443     if (!frame)
444         return;
445     if (value.isNull())
446         frame->mainFrame().diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::resourceRequestKey(), description);
447     else
448         frame->mainFrame().diagnosticLoggingClient().logDiagnosticMessageWithValue(DiagnosticLoggingKeys::resourceRequestKey(), description, value);
449 }
450
451 CachedResourceHandle<CachedResource> CachedResourceLoader::requestResource(CachedResource::Type type, CachedResourceRequest& request)
452 {
453     URL url = request.resourceRequest().url();
454     
455     LOG(ResourceLoading, "CachedResourceLoader::requestResource '%s', charset '%s', priority=%d, forPreload=%u", url.stringCenterEllipsizedToLength().latin1().data(), request.charset().latin1().data(), request.priority() ? request.priority().value() : -1, request.forPreload());
456     
457     // If only the fragment identifiers differ, it is the same resource.
458     url = MemoryCache::removeFragmentIdentifierIfNeeded(url);
459
460     if (!url.isValid())
461         return nullptr;
462
463     if (!canRequest(type, url, request.options(), request.forPreload()))
464         return nullptr;
465
466 #if ENABLE(CONTENT_EXTENSIONS)
467     if (frame() && frame()->page() && frame()->page()->userContentController() && frame()->page()->userContentController()->contentFilterBlocksURL(url))
468         return nullptr;
469 #endif
470
471     auto& memoryCache = MemoryCache::singleton();
472     if (memoryCache.disabled()) {
473         DocumentResourceMap::iterator it = m_documentResources.find(url.string());
474         if (it != m_documentResources.end()) {
475             it->value->setOwningCachedResourceLoader(0);
476             m_documentResources.remove(it);
477         }
478     }
479
480     // See if we can use an existing resource from the cache.
481     CachedResourceHandle<CachedResource> resource;
482 #if ENABLE(CACHE_PARTITIONING)
483     if (document())
484         request.mutableResourceRequest().setDomainForCachePartition(document()->topOrigin()->domainForCachePartition());
485 #endif
486
487     resource = memoryCache.resourceForRequest(request.resourceRequest(), sessionID());
488
489     logMemoryCacheResourceRequest(frame(), resource ? DiagnosticLoggingKeys::inMemoryCacheKey() : DiagnosticLoggingKeys::notInMemoryCacheKey());
490
491     const RevalidationPolicy policy = determineRevalidationPolicy(type, request.mutableResourceRequest(), request.forPreload(), resource.get(), request.defer());
492     switch (policy) {
493     case Reload:
494         memoryCache.remove(*resource);
495         FALLTHROUGH;
496     case Load:
497         if (resource)
498             logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedKey());
499         resource = loadResource(type, request);
500         break;
501     case Revalidate:
502         if (resource)
503             logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::revalidatingKey());
504         resource = revalidateResource(request, resource.get());
505         break;
506     case Use:
507         if (!shouldContinueAfterNotifyingLoadedFromMemoryCache(request, resource.get()))
508             return nullptr;
509         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::usedKey());
510         memoryCache.resourceAccessed(*resource);
511         break;
512     }
513
514     if (!resource)
515         return nullptr;
516
517     if (!request.forPreload() || policy != Use)
518         resource->setLoadPriority(request.priority());
519
520     if ((policy != Use || resource->stillNeedsLoad()) && CachedResourceRequest::NoDefer == request.defer()) {
521         resource->load(*this, request.options());
522
523         // We don't support immediate loads, but we do support immediate failure.
524         if (resource->errorOccurred()) {
525             if (resource->inCache())
526                 memoryCache.remove(*resource);
527             return nullptr;
528         }
529     }
530
531     if (document() && !document()->loadEventFinished() && !request.resourceRequest().url().protocolIsData())
532         m_validatedURLs.add(request.resourceRequest().url());
533
534     ASSERT(resource->url() == url.string());
535     m_documentResources.set(resource->url(), resource);
536     return resource;
537 }
538
539 void CachedResourceLoader::documentDidFinishLoadEvent()
540 {
541     m_validatedURLs.clear();
542 }
543
544 CachedResourceHandle<CachedResource> CachedResourceLoader::revalidateResource(const CachedResourceRequest& request, CachedResource* resource)
545 {
546     ASSERT(resource);
547     ASSERT(resource->inCache());
548     auto& memoryCache = MemoryCache::singleton();
549     ASSERT(!memoryCache.disabled());
550     ASSERT(resource->canUseCacheValidator());
551     ASSERT(!resource->resourceToRevalidate());
552     ASSERT(resource->sessionID() == sessionID());
553
554     CachedResourceHandle<CachedResource> newResource = createResource(resource->type(), resource->resourceRequest(), resource->encoding(), resource->sessionID());
555     
556     LOG(ResourceLoading, "Resource %p created to revalidate %p", newResource.get(), resource);
557     newResource->setResourceToRevalidate(resource);
558     
559     memoryCache.remove(*resource);
560     memoryCache.add(*newResource);
561 #if ENABLE(RESOURCE_TIMING)
562     storeResourceTimingInitiatorInformation(resource, request);
563 #else
564     UNUSED_PARAM(request);
565 #endif
566     return newResource;
567 }
568
569 CachedResourceHandle<CachedResource> CachedResourceLoader::loadResource(CachedResource::Type type, CachedResourceRequest& request)
570 {
571     auto& memoryCache = MemoryCache::singleton();
572     ASSERT(!memoryCache.resourceForRequest(request.resourceRequest(), sessionID()));
573
574     LOG(ResourceLoading, "Loading CachedResource for '%s'.", request.resourceRequest().url().stringCenterEllipsizedToLength().latin1().data());
575
576     CachedResourceHandle<CachedResource> resource = createResource(type, request.mutableResourceRequest(), request.charset(), sessionID());
577
578     if (!memoryCache.add(*resource))
579         resource->setOwningCachedResourceLoader(this);
580 #if ENABLE(RESOURCE_TIMING)
581     storeResourceTimingInitiatorInformation(resource, request);
582 #endif
583     return resource;
584 }
585
586 #if ENABLE(RESOURCE_TIMING)
587 void CachedResourceLoader::storeResourceTimingInitiatorInformation(const CachedResourceHandle<CachedResource>& resource, const CachedResourceRequest& request)
588 {
589     if (resource->type() == CachedResource::MainResource) {
590         // <iframe>s should report the initial navigation requested by the parent document, but not subsequent navigations.
591         if (frame()->ownerElement() && m_documentLoader->frameLoader()->stateMachine().committingFirstRealLoad()) {
592             InitiatorInfo info = { frame()->ownerElement()->localName(), monotonicallyIncreasingTime() };
593             m_initiatorMap.add(resource.get(), info);
594         }
595     } else {
596         InitiatorInfo info = { request.initiatorName(), monotonicallyIncreasingTime() };
597         m_initiatorMap.add(resource.get(), info);
598     }
599 }
600 #endif // ENABLE(RESOURCE_TIMING)
601
602 CachedResourceLoader::RevalidationPolicy CachedResourceLoader::determineRevalidationPolicy(CachedResource::Type type, ResourceRequest& request, bool forPreload, CachedResource* existingResource, CachedResourceRequest::DeferOption defer) const
603 {
604     if (!existingResource)
605         return Load;
606
607     // We already have a preload going for this URL.
608     if (forPreload && existingResource->isPreloaded())
609         return Use;
610
611     // If the same URL has been loaded as a different type, we need to reload.
612     if (existingResource->type() != type) {
613         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to type mismatch.");
614         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonTypeMismatchKey());
615         return Reload;
616     }
617
618     if (!existingResource->canReuse(request))
619         return Reload;
620
621     // Conditional requests should have failed canReuse check.
622     ASSERT(!request.isConditional());
623
624     // Do not load from cache if images are not enabled. The load for this image will be blocked
625     // in CachedImage::load.
626     if (CachedResourceRequest::DeferredByClient == defer)
627         return Reload;
628     
629     // Don't reload resources while pasting.
630     if (m_allowStaleResources)
631         return Use;
632     
633     // Alwaus use preloads.
634     if (existingResource->isPreloaded())
635         return Use;
636
637     // Validate the redirect chain.
638     bool cachePolicyIsHistoryBuffer = cachePolicy(type) == CachePolicyHistoryBuffer;
639     if (!existingResource->redirectChainAllowsReuse(cachePolicyIsHistoryBuffer ? ReuseExpiredRedirection : DoNotReuseExpiredRedirection)) {
640         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to not cached or expired redirections.");
641         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonRedirectChainKey());
642         return Reload;
643     }
644
645     // CachePolicyHistoryBuffer uses the cache except if this is a main resource with "cache-control: no-store".
646     if (cachePolicyIsHistoryBuffer) {
647         // FIXME: Ignoring "cache-control: no-cache" for sub-resources on history navigation but not the main
648         // resource is inconsistent. We should probably harmonize this.
649         if (!existingResource->response().cacheControlContainsNoStore() || type != CachedResource::MainResource)
650             return Use;
651     }
652
653     // Don't reuse resources with Cache-control: no-store.
654     if (existingResource->response().cacheControlContainsNoStore()) {
655         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to Cache-control: no-store.");
656         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonNoStoreKey());
657         return Reload;
658     }
659
660     // If credentials were sent with the previous request and won't be
661     // with this one, or vice versa, re-fetch the resource.
662     //
663     // This helps with the case where the server sends back
664     // "Access-Control-Allow-Origin: *" all the time, but some of the
665     // client's requests are made without CORS and some with.
666     if (existingResource->resourceRequest().allowCookies() != request.allowCookies()) {
667         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to difference in credentials settings.");
668         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonCredentialSettingsKey());
669         return Reload;
670     }
671
672     // During the initial load, avoid loading the same resource multiple times for a single document, even if the cache policies would tell us to.
673     if (document() && !document()->loadEventFinished() && m_validatedURLs.contains(existingResource->url()))
674         return Use;
675
676     // CachePolicyReload always reloads
677     if (cachePolicy(type) == CachePolicyReload) {
678         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to CachePolicyReload.");
679         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonReloadKey());
680         return Reload;
681     }
682     
683     // We'll try to reload the resource if it failed last time.
684     if (existingResource->errorOccurred()) {
685         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicye reloading due to resource being in the error state");
686         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonErrorKey());
687         return Reload;
688     }
689     
690     // For resources that are not yet loaded we ignore the cache policy.
691     if (existingResource->isLoading())
692         return Use;
693
694     // Check if the cache headers requires us to revalidate (cache expiration for example).
695     if (existingResource->mustRevalidateDueToCacheHeaders(*this, cachePolicy(type))) {
696         // See if the resource has usable ETag or Last-modified headers.
697         if (existingResource->canUseCacheValidator())
698             return Revalidate;
699         
700         // No, must reload.
701         LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading due to missing cache validators.");
702         logMemoryCacheResourceRequest(frame(), DiagnosticLoggingKeys::inMemoryCacheKey(), DiagnosticLoggingKeys::unusedReasonMustRevalidateNoValidatorKey());
703         return Reload;
704     }
705
706     return Use;
707 }
708
709 void CachedResourceLoader::printAccessDeniedMessage(const URL& url) const
710 {
711     if (url.isNull())
712         return;
713
714     if (!frame())
715         return;
716
717     String message;
718     if (!m_document || m_document->url().isNull())
719         message = "Unsafe attempt to load URL " + url.stringCenterEllipsizedToLength() + '.';
720     else
721         message = "Unsafe attempt to load URL " + url.stringCenterEllipsizedToLength() + " from frame with URL " + m_document->url().stringCenterEllipsizedToLength() + ". Domains, protocols and ports must match.\n";
722
723     frame()->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
724 }
725
726 void CachedResourceLoader::setAutoLoadImages(bool enable)
727 {
728     if (enable == m_autoLoadImages)
729         return;
730
731     m_autoLoadImages = enable;
732
733     if (!m_autoLoadImages)
734         return;
735
736     reloadImagesIfNotDeferred();
737 }
738
739 void CachedResourceLoader::setImagesEnabled(bool enable)
740 {
741     if (enable == m_imagesEnabled)
742         return;
743
744     m_imagesEnabled = enable;
745
746     if (!m_imagesEnabled)
747         return;
748
749     reloadImagesIfNotDeferred();
750 }
751
752 bool CachedResourceLoader::clientDefersImage(const URL&) const
753 {
754     return !m_imagesEnabled;
755 }
756
757 bool CachedResourceLoader::shouldDeferImageLoad(const URL& url) const
758 {
759     return clientDefersImage(url) || !m_autoLoadImages;
760 }
761
762 void CachedResourceLoader::reloadImagesIfNotDeferred()
763 {
764     DocumentResourceMap::iterator end = m_documentResources.end();
765     for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != end; ++it) {
766         CachedResource* resource = it->value.get();
767         if (is<CachedImage>(*resource) && resource->stillNeedsLoad() && !clientDefersImage(resource->url()))
768             downcast<CachedImage>(*resource).load(*this, defaultCachedResourceOptions());
769     }
770 }
771
772 CachePolicy CachedResourceLoader::cachePolicy(CachedResource::Type type) const
773 {
774     if (!frame())
775         return CachePolicyVerify;
776
777     if (type != CachedResource::MainResource)
778         return frame()->loader().subresourceCachePolicy();
779     
780     switch (frame()->loader().loadType()) {
781     case FrameLoadType::ReloadFromOrigin:
782     case FrameLoadType::Reload:
783         return CachePolicyReload;
784     case FrameLoadType::Back:
785     case FrameLoadType::Forward:
786     case FrameLoadType::IndexedBackForward:
787         // Do not revalidate cached main resource on back/forward navigation.
788         return CachePolicyHistoryBuffer;
789     default:
790         return CachePolicyVerify;
791     }
792 }
793
794 void CachedResourceLoader::removeCachedResource(CachedResource& resource)
795 {
796 #ifndef NDEBUG
797     DocumentResourceMap::iterator it = m_documentResources.find(resource.url());
798     if (it != m_documentResources.end())
799         ASSERT(it->value.get() == &resource);
800 #endif
801     m_documentResources.remove(resource.url());
802 }
803
804 void CachedResourceLoader::addCachedResource(CachedResource& resource)
805 {
806     m_documentResources.set(resource.url(), &resource);
807
808     if (!MemoryCache::singleton().add(resource))
809         resource.setOwningCachedResourceLoader(this);
810 }
811
812 void CachedResourceLoader::loadDone(CachedResource* resource, bool shouldPerformPostLoadActions)
813 {
814     RefPtr<DocumentLoader> protectDocumentLoader(m_documentLoader);
815     RefPtr<Document> protectDocument(m_document);
816
817 #if ENABLE(RESOURCE_TIMING)
818     if (resource && resource->response().isHTTP() && ((!resource->errorOccurred() && !resource->wasCanceled()) || resource->response().httpStatusCode() == 304)) {
819         HashMap<CachedResource*, InitiatorInfo>::iterator initiatorIt = m_initiatorMap.find(resource);
820         if (initiatorIt != m_initiatorMap.end()) {
821             ASSERT(document());
822             Document* initiatorDocument = document();
823             if (resource->type() == CachedResource::MainResource)
824                 initiatorDocument = document()->parentDocument();
825             ASSERT(initiatorDocument);
826             const InitiatorInfo& info = initiatorIt->value;
827             initiatorDocument->domWindow()->performance()->addResourceTiming(info.name, initiatorDocument, resource->resourceRequest(), resource->response(), info.startTime, resource->loadFinishTime());
828             m_initiatorMap.remove(initiatorIt);
829         }
830     }
831 #else
832     UNUSED_PARAM(resource);
833 #endif // ENABLE(RESOURCE_TIMING)
834
835     if (frame())
836         frame()->loader().loadDone();
837
838     if (shouldPerformPostLoadActions)
839         performPostLoadActions();
840
841     if (!m_garbageCollectDocumentResourcesTimer.isActive())
842         m_garbageCollectDocumentResourcesTimer.startOneShot(0);
843 }
844
845 // Garbage collecting m_documentResources is a workaround for the
846 // CachedResourceHandles on the RHS being strong references. Ideally this
847 // would be a weak map, however CachedResourceHandles perform additional
848 // bookkeeping on CachedResources, so instead pseudo-GC them -- when the
849 // reference count reaches 1, m_documentResources is the only reference, so
850 // remove it from the map.
851 void CachedResourceLoader::garbageCollectDocumentResourcesTimerFired()
852 {
853     garbageCollectDocumentResources();
854 }
855
856 void CachedResourceLoader::garbageCollectDocumentResources()
857 {
858     typedef Vector<String, 10> StringVector;
859     StringVector resourcesToDelete;
860
861     for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != m_documentResources.end(); ++it) {
862         if (it->value->hasOneHandle()) {
863             resourcesToDelete.append(it->key);
864             it->value->setOwningCachedResourceLoader(0);
865         }
866     }
867
868     for (StringVector::const_iterator it = resourcesToDelete.begin(); it != resourcesToDelete.end(); ++it)
869         m_documentResources.remove(*it);
870 }
871
872 void CachedResourceLoader::performPostLoadActions()
873 {
874     checkForPendingPreloads();
875
876     platformStrategies()->loaderStrategy()->resourceLoadScheduler()->servePendingRequests();
877 }
878
879 void CachedResourceLoader::incrementRequestCount(const CachedResource* res)
880 {
881     if (res->ignoreForRequestCount())
882         return;
883
884     ++m_requestCount;
885 }
886
887 void CachedResourceLoader::decrementRequestCount(const CachedResource* res)
888 {
889     if (res->ignoreForRequestCount())
890         return;
891
892     --m_requestCount;
893     ASSERT(m_requestCount > -1);
894 }
895
896 void CachedResourceLoader::preload(CachedResource::Type type, CachedResourceRequest& request, const String& charset)
897 {
898     // We always preload resources on iOS. See <https://bugs.webkit.org/show_bug.cgi?id=91276>.
899     // FIXME: We should consider adding a setting to toggle aggressive preloading behavior as opposed
900     // to making this behavior specific to iOS.
901 #if !PLATFORM(IOS)
902     bool hasRendering = m_document->bodyOrFrameset() && m_document->renderView();
903     bool canBlockParser = type == CachedResource::Script || type == CachedResource::CSSStyleSheet;
904     if (!hasRendering && !canBlockParser) {
905         // Don't preload subresources that can't block the parser before we have something to draw.
906         // This helps prevent preloads from delaying first display when bandwidth is limited.
907         PendingPreload pendingPreload = { type, request, charset };
908         m_pendingPreloads.append(pendingPreload);
909         return;
910     }
911 #endif
912     requestPreload(type, request, charset);
913 }
914
915 void CachedResourceLoader::checkForPendingPreloads() 
916 {
917     if (m_pendingPreloads.isEmpty())
918         return;
919     auto* body = m_document->bodyOrFrameset();
920     if (!body || !body->renderer())
921         return;
922 #if PLATFORM(IOS)
923     // We always preload resources on iOS. See <https://bugs.webkit.org/show_bug.cgi?id=91276>.
924     // So, we should never have any pending preloads.
925     // FIXME: We should look to avoid compiling this code entirely when building for iOS.
926     ASSERT_NOT_REACHED();
927 #endif
928     while (!m_pendingPreloads.isEmpty()) {
929         PendingPreload preload = m_pendingPreloads.takeFirst();
930         // 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).
931         if (!cachedResource(preload.m_request.resourceRequest().url()))
932             requestPreload(preload.m_type, preload.m_request, preload.m_charset);
933     }
934     m_pendingPreloads.clear();
935 }
936
937 void CachedResourceLoader::requestPreload(CachedResource::Type type, CachedResourceRequest& request, const String& charset)
938 {
939     String encoding;
940     if (type == CachedResource::Script || type == CachedResource::CSSStyleSheet)
941         encoding = charset.isEmpty() ? m_document->charset() : charset;
942
943     request.setCharset(encoding);
944     request.setForPreload(true);
945
946     CachedResourceHandle<CachedResource> resource = requestResource(type, request);
947     if (!resource || (m_preloads && m_preloads->contains(resource.get())))
948         return;
949     resource->increasePreloadCount();
950
951     if (!m_preloads)
952         m_preloads = std::make_unique<ListHashSet<CachedResource*>>();
953     m_preloads->add(resource.get());
954
955 #if PRELOAD_DEBUG
956     printf("PRELOADING %s\n",  resource->url().latin1().data());
957 #endif
958 }
959
960 bool CachedResourceLoader::isPreloaded(const String& urlString) const
961 {
962     const URL& url = m_document->completeURL(urlString);
963
964     if (m_preloads) {
965         ListHashSet<CachedResource*>::iterator end = m_preloads->end();
966         for (ListHashSet<CachedResource*>::iterator it = m_preloads->begin(); it != end; ++it) {
967             CachedResource* resource = *it;
968             if (resource->url() == url)
969                 return true;
970         }
971     }
972
973     Deque<PendingPreload>::const_iterator dequeEnd = m_pendingPreloads.end();
974     for (Deque<PendingPreload>::const_iterator it = m_pendingPreloads.begin(); it != dequeEnd; ++it) {
975         PendingPreload pendingPreload = *it;
976         if (pendingPreload.m_request.resourceRequest().url() == url)
977             return true;
978     }
979     return false;
980 }
981
982 void CachedResourceLoader::clearPreloads()
983 {
984 #if PRELOAD_DEBUG
985     printPreloadStats();
986 #endif
987     if (!m_preloads)
988         return;
989
990     for (auto* resource : *m_preloads) {
991         resource->decreasePreloadCount();
992         bool deleted = resource->deleteIfPossible();
993         if (!deleted && resource->preloadResult() == CachedResource::PreloadNotReferenced)
994             MemoryCache::singleton().remove(*resource);
995     }
996     m_preloads = nullptr;
997 }
998
999 void CachedResourceLoader::clearPendingPreloads()
1000 {
1001     m_pendingPreloads.clear();
1002 }
1003
1004 #if PRELOAD_DEBUG
1005 void CachedResourceLoader::printPreloadStats()
1006 {
1007     unsigned scripts = 0;
1008     unsigned scriptMisses = 0;
1009     unsigned stylesheets = 0;
1010     unsigned stylesheetMisses = 0;
1011     unsigned images = 0;
1012     unsigned imageMisses = 0;
1013     ListHashSet<CachedResource*>::iterator end = m_preloads.end();
1014     for (ListHashSet<CachedResource*>::iterator it = m_preloads.begin(); it != end; ++it) {
1015         CachedResource* res = *it;
1016         if (res->preloadResult() == CachedResource::PreloadNotReferenced)
1017             printf("!! UNREFERENCED PRELOAD %s\n", res->url().latin1().data());
1018         else if (res->preloadResult() == CachedResource::PreloadReferencedWhileComplete)
1019             printf("HIT COMPLETE PRELOAD %s\n", res->url().latin1().data());
1020         else if (res->preloadResult() == CachedResource::PreloadReferencedWhileLoading)
1021             printf("HIT LOADING PRELOAD %s\n", res->url().latin1().data());
1022         
1023         if (res->type() == CachedResource::Script) {
1024             scripts++;
1025             if (res->preloadResult() < CachedResource::PreloadReferencedWhileLoading)
1026                 scriptMisses++;
1027         } else if (res->type() == CachedResource::CSSStyleSheet) {
1028             stylesheets++;
1029             if (res->preloadResult() < CachedResource::PreloadReferencedWhileLoading)
1030                 stylesheetMisses++;
1031         } else {
1032             images++;
1033             if (res->preloadResult() < CachedResource::PreloadReferencedWhileLoading)
1034                 imageMisses++;
1035         }
1036         
1037         if (res->errorOccurred())
1038             MemoryCache::singleton().remove(res);
1039         
1040         res->decreasePreloadCount();
1041     }
1042     m_preloads = nullptr;
1043     
1044     if (scripts)
1045         printf("SCRIPTS: %d (%d hits, hit rate %d%%)\n", scripts, scripts - scriptMisses, (scripts - scriptMisses) * 100 / scripts);
1046     if (stylesheets)
1047         printf("STYLESHEETS: %d (%d hits, hit rate %d%%)\n", stylesheets, stylesheets - stylesheetMisses, (stylesheets - stylesheetMisses) * 100 / stylesheets);
1048     if (images)
1049         printf("IMAGES:  %d (%d hits, hit rate %d%%)\n", images, images - imageMisses, (images - imageMisses) * 100 / images);
1050 }
1051 #endif
1052
1053 const ResourceLoaderOptions& CachedResourceLoader::defaultCachedResourceOptions()
1054 {
1055     static ResourceLoaderOptions options(SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, AskClientForAllCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType, DoNotIncludeCertificateInfo);
1056     return options;
1057 }
1058
1059 }