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