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