CTTE Timer and DeferrableOneShotTimer
[WebKit-https.git] / Source / WebCore / loader / cache / CachedResource.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) 2006 Samuel Weinig (sam.weinig@gmail.com)
6     Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
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
24 #include "config.h"
25 #include "CachedResource.h"
26
27 #include "CachedResourceClient.h"
28 #include "CachedResourceClientWalker.h"
29 #include "CachedResourceHandle.h"
30 #include "CachedResourceLoader.h"
31 #include "CrossOriginAccessControl.h"
32 #include "Document.h"
33 #include "DocumentLoader.h"
34 #include "FrameLoader.h"
35 #include "FrameLoaderClient.h"
36 #include "InspectorInstrumentation.h"
37 #include "URL.h"
38 #include "LoaderStrategy.h"
39 #include "Logging.h"
40 #include "MemoryCache.h"
41 #include "PlatformStrategies.h"
42 #include "PurgeableBuffer.h"
43 #include "ResourceBuffer.h"
44 #include "ResourceHandle.h"
45 #include "ResourceLoadScheduler.h"
46 #include "SchemeRegistry.h"
47 #include "SecurityOrigin.h"
48 #include "SecurityPolicy.h"
49 #include "SubresourceLoader.h"
50 #include <wtf/CurrentTime.h>
51 #include <wtf/MathExtras.h>
52 #include <wtf/RefCountedLeakCounter.h>
53 #include <wtf/StdLibExtras.h>
54 #include <wtf/text/CString.h>
55 #include <wtf/Vector.h>
56
57 #if USE(QUICK_LOOK)
58 #include "QuickLook.h"
59 #endif
60
61 using namespace WTF;
62
63 namespace WebCore {
64
65 // These response headers are not copied from a revalidated response to the
66 // cached response headers. For compatibility, this list is based on Chromium's
67 // net/http/http_response_headers.cc.
68 const char* const headersToIgnoreAfterRevalidation[] = {
69     "allow",
70     "connection",
71     "etag",
72     "expires",
73     "keep-alive",
74     "last-modified"
75     "proxy-authenticate",
76     "proxy-connection",
77     "trailer",
78     "transfer-encoding",
79     "upgrade",
80     "www-authenticate",
81     "x-frame-options",
82     "x-xss-protection",
83 };
84
85 // Some header prefixes mean "Don't copy this header from a 304 response.".
86 // Rather than listing all the relevant headers, we can consolidate them into
87 // this list, also grabbed from Chromium's net/http/http_response_headers.cc.
88 const char* const headerPrefixesToIgnoreAfterRevalidation[] = {
89     "content-",
90     "x-content-",
91     "x-webkit-"
92 };
93
94 static inline bool shouldUpdateHeaderAfterRevalidation(const AtomicString& header)
95 {
96     for (size_t i = 0; i < WTF_ARRAY_LENGTH(headersToIgnoreAfterRevalidation); i++) {
97         if (equalIgnoringCase(header, headersToIgnoreAfterRevalidation[i]))
98             return false;
99     }
100     for (size_t i = 0; i < WTF_ARRAY_LENGTH(headerPrefixesToIgnoreAfterRevalidation); i++) {
101         if (header.startsWith(headerPrefixesToIgnoreAfterRevalidation[i], false))
102             return false;
103     }
104     return true;
105 }
106
107 static ResourceLoadPriority defaultPriorityForResourceType(CachedResource::Type type)
108 {
109     switch (type) {
110     case CachedResource::MainResource:
111         return ResourceLoadPriorityVeryHigh;
112     case CachedResource::CSSStyleSheet:
113         return ResourceLoadPriorityHigh;
114     case CachedResource::Script:
115     case CachedResource::FontResource:
116     case CachedResource::RawResource:
117         return ResourceLoadPriorityMedium;
118     case CachedResource::ImageResource:
119         return ResourceLoadPriorityLow;
120 #if ENABLE(XSLT)
121     case CachedResource::XSLStyleSheet:
122         return ResourceLoadPriorityHigh;
123 #endif
124 #if ENABLE(SVG)
125     case CachedResource::SVGDocumentResource:
126         return ResourceLoadPriorityLow;
127 #endif
128 #if ENABLE(LINK_PREFETCH)
129     case CachedResource::LinkPrefetch:
130         return ResourceLoadPriorityVeryLow;
131     case CachedResource::LinkSubresource:
132         return ResourceLoadPriorityVeryLow;
133 #endif
134 #if ENABLE(VIDEO_TRACK)
135     case CachedResource::TextTrackResource:
136         return ResourceLoadPriorityLow;
137 #endif
138 #if ENABLE(CSS_SHADERS)
139     case CachedResource::ShaderResource:
140         return ResourceLoadPriorityMedium;
141 #endif
142     }
143     ASSERT_NOT_REACHED();
144     return ResourceLoadPriorityLow;
145 }
146
147 static double deadDecodedDataDeletionIntervalForResourceType(CachedResource::Type type)
148 {
149     if (type == CachedResource::Script)
150         return 0;
151     return memoryCache()->deadDecodedDataDeletionInterval();
152 }
153
154 DEFINE_DEBUG_ONLY_GLOBAL(RefCountedLeakCounter, cachedResourceLeakCounter, ("CachedResource"));
155
156 CachedResource::CachedResource(const ResourceRequest& request, Type type)
157     : m_resourceRequest(request)
158     , m_loadPriority(defaultPriorityForResourceType(type))
159     , m_responseTimestamp(currentTime())
160     , m_decodedDataDeletionTimer(this, &CachedResource::decodedDataDeletionTimerFired, deadDecodedDataDeletionIntervalForResourceType(type))
161     , m_lastDecodedAccessTime(0)
162     , m_loadFinishTime(0)
163     , m_encodedSize(0)
164     , m_decodedSize(0)
165     , m_accessCount(0)
166     , m_handleCount(0)
167     , m_preloadCount(0)
168     , m_preloadResult(PreloadNotReferenced)
169     , m_inLiveDecodedResourcesList(false)
170     , m_requestedFromNetworkingLayer(false)
171     , m_inCache(false)
172     , m_loading(false)
173     , m_switchingClientsToRevalidatedResource(false)
174     , m_type(type)
175     , m_status(Pending)
176 #ifndef NDEBUG
177     , m_deleted(false)
178     , m_lruIndex(0)
179 #endif
180     , m_nextInAllResourcesList(0)
181     , m_prevInAllResourcesList(0)
182     , m_nextInLiveResourcesList(0)
183     , m_prevInLiveResourcesList(0)
184     , m_owningCachedResourceLoader(0)
185     , m_resourceToRevalidate(0)
186     , m_proxyResource(0)
187 {
188     ASSERT(m_type == unsigned(type)); // m_type is a bitfield, so this tests careless updates of the enum.
189 #ifndef NDEBUG
190     cachedResourceLeakCounter.increment();
191 #endif
192
193     if (!m_resourceRequest.url().hasFragmentIdentifier())
194         return;
195     URL urlForCache = MemoryCache::removeFragmentIdentifierIfNeeded(m_resourceRequest.url());
196     if (urlForCache.hasFragmentIdentifier())
197         return;
198     m_fragmentIdentifierForRequest = m_resourceRequest.url().fragmentIdentifier();
199     m_resourceRequest.setURL(urlForCache);
200 }
201
202 CachedResource::~CachedResource()
203 {
204     ASSERT(!m_resourceToRevalidate); // Should be true because canDelete() checks this.
205     ASSERT(canDelete());
206     ASSERT(!inCache());
207     ASSERT(!m_deleted);
208     ASSERT(url().isNull() || memoryCache()->resourceForRequest(resourceRequest()) != this);
209
210 #ifndef NDEBUG
211     m_deleted = true;
212     cachedResourceLeakCounter.decrement();
213 #endif
214
215     if (m_owningCachedResourceLoader)
216         m_owningCachedResourceLoader->removeCachedResource(this);
217 }
218
219 void CachedResource::failBeforeStarting()
220 {
221     // FIXME: What if resources in other frames were waiting for this revalidation?
222     LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
223     if (m_resourceToRevalidate) 
224         memoryCache()->revalidationFailed(this); 
225     error(CachedResource::LoadError);
226 }
227
228 void CachedResource::addAdditionalRequestHeaders(CachedResourceLoader* cachedResourceLoader)
229 {
230     // Note: We skip the Content-Security-Policy check here because we check
231     // the Content-Security-Policy at the CachedResourceLoader layer so we can
232     // handle different resource types differently.
233
234     FrameLoader& frameLoader = cachedResourceLoader->frame()->loader();
235     String outgoingReferrer;
236     String outgoingOrigin;
237     if (m_resourceRequest.httpReferrer().isNull()) {
238         outgoingReferrer = frameLoader.outgoingReferrer();
239         outgoingOrigin = frameLoader.outgoingOrigin();
240     } else {
241         outgoingReferrer = m_resourceRequest.httpReferrer();
242         outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
243     }
244
245     outgoingReferrer = SecurityPolicy::generateReferrerHeader(cachedResourceLoader->document()->referrerPolicy(), m_resourceRequest.url(), outgoingReferrer);
246     if (outgoingReferrer.isEmpty())
247         m_resourceRequest.clearHTTPReferrer();
248     else if (!m_resourceRequest.httpReferrer())
249         m_resourceRequest.setHTTPReferrer(outgoingReferrer);
250     FrameLoader::addHTTPOriginIfNeeded(m_resourceRequest, outgoingOrigin);
251
252     frameLoader.addExtraFieldsToSubresourceRequest(m_resourceRequest);
253 }
254
255 void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const ResourceLoaderOptions& options)
256 {
257     if (!cachedResourceLoader->frame()) {
258         failBeforeStarting();
259         return;
260     }
261
262     FrameLoader& frameLoader = cachedResourceLoader->frame()->loader();
263     if (options.securityCheck == DoSecurityCheck && (frameLoader.state() == FrameStateProvisional || !frameLoader.activeDocumentLoader() || frameLoader.activeDocumentLoader()->isStopping())) {
264         failBeforeStarting();
265         return;
266     }
267
268     m_options = options;
269     m_loading = true;
270
271 #if USE(QUICK_LOOK)
272     if (!m_resourceRequest.isNull() && m_resourceRequest.url().protocolIs(QLPreviewProtocol())) {
273         // When QuickLook is invoked to convert a document, it returns a unique URL in the
274         // NSURLReponse for the main document. To make safeQLURLForDocumentURLAndResourceURL()
275         // work, we need to use the QL URL not the original URL.
276         const URL& documentURL = cachedResourceLoader->frame() ? cachedResourceLoader->frame()->loader().documentLoader()->response().url() : cachedResourceLoader->document()->url();
277         m_resourceRequest.setURL(safeQLURLForDocumentURLAndResourceURL(documentURL, url()));
278     }
279 #endif
280
281     if (!accept().isEmpty())
282         m_resourceRequest.setHTTPAccept(accept());
283
284     if (isCacheValidator()) {
285         CachedResource* resourceToRevalidate = m_resourceToRevalidate;
286         ASSERT(resourceToRevalidate->canUseCacheValidator());
287         ASSERT(resourceToRevalidate->isLoaded());
288         const String& lastModified = resourceToRevalidate->response().httpHeaderField("Last-Modified");
289         const String& eTag = resourceToRevalidate->response().httpHeaderField("ETag");
290         if (!lastModified.isEmpty() || !eTag.isEmpty()) {
291             ASSERT(cachedResourceLoader->cachePolicy(type()) != CachePolicyReload);
292             if (cachedResourceLoader->cachePolicy(type()) == CachePolicyRevalidate)
293                 m_resourceRequest.setHTTPHeaderField("Cache-Control", "max-age=0");
294             if (!lastModified.isEmpty())
295                 m_resourceRequest.setHTTPHeaderField("If-Modified-Since", lastModified);
296             if (!eTag.isEmpty())
297                 m_resourceRequest.setHTTPHeaderField("If-None-Match", eTag);
298         }
299     }
300
301 #if ENABLE(LINK_PREFETCH)
302     if (type() == CachedResource::LinkPrefetch || type() == CachedResource::LinkSubresource)
303         m_resourceRequest.setHTTPHeaderField("Purpose", "prefetch");
304 #endif
305     m_resourceRequest.setPriority(loadPriority());
306
307     if (type() != MainResource)
308         addAdditionalRequestHeaders(cachedResourceLoader);
309
310     // FIXME: It's unfortunate that the cache layer and below get to know anything about fragment identifiers.
311     // We should look into removing the expectation of that knowledge from the platform network stacks.
312     ResourceRequest request(m_resourceRequest);
313     if (!m_fragmentIdentifierForRequest.isNull()) {
314         URL url = request.url();
315         url.setFragmentIdentifier(m_fragmentIdentifierForRequest);
316         request.setURL(url);
317         m_fragmentIdentifierForRequest = String();
318     }
319
320     m_loader = platformStrategies()->loaderStrategy()->resourceLoadScheduler()->scheduleSubresourceLoad(cachedResourceLoader->frame(), this, request, request.priority(), options);
321     if (!m_loader) {
322         failBeforeStarting();
323         return;
324     }
325
326     m_status = Pending;
327 }
328
329 void CachedResource::checkNotify()
330 {
331     if (isLoading())
332         return;
333
334     CachedResourceClientWalker<CachedResourceClient> w(m_clients);
335     while (CachedResourceClient* c = w.next())
336         c->notifyFinished(this);
337 }
338
339 void CachedResource::addDataBuffer(ResourceBuffer*)
340 {
341     ASSERT(m_options.dataBufferingPolicy == BufferData);
342 }
343
344 void CachedResource::addData(const char*, unsigned)
345 {
346     ASSERT(m_options.dataBufferingPolicy == DoNotBufferData);
347 }
348
349 void CachedResource::finishLoading(ResourceBuffer*)
350 {
351     setLoading(false);
352     checkNotify();
353 }
354
355 void CachedResource::error(CachedResource::Status status)
356 {
357     setStatus(status);
358     ASSERT(errorOccurred());
359     m_data.clear();
360
361     setLoading(false);
362     checkNotify();
363 }
364     
365 void CachedResource::cancelLoad()
366 {
367     if (!isLoading())
368         return;
369
370     setStatus(LoadError);
371     setLoading(false);
372     checkNotify();
373 }
374
375 void CachedResource::finish()
376 {
377     if (!errorOccurred())
378         m_status = Cached;
379 }
380
381 bool CachedResource::passesAccessControlCheck(SecurityOrigin* securityOrigin)
382 {
383     String errorDescription;
384     return WebCore::passesAccessControlCheck(m_response, resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription);
385 }
386
387 bool CachedResource::isExpired() const
388 {
389     if (m_response.isNull())
390         return false;
391
392     return currentAge() > freshnessLifetime();
393 }
394
395 double CachedResource::currentAge() const
396 {
397     // RFC2616 13.2.3
398     // No compensation for latency as that is not terribly important in practice
399     double dateValue = m_response.date();
400     double apparentAge = std::isfinite(dateValue) ? std::max(0., m_responseTimestamp - dateValue) : 0;
401     double ageValue = m_response.age();
402     double correctedReceivedAge = std::isfinite(ageValue) ? std::max(apparentAge, ageValue) : apparentAge;
403     double residentTime = currentTime() - m_responseTimestamp;
404     return correctedReceivedAge + residentTime;
405 }
406
407 double CachedResource::freshnessLifetime() const
408 {
409     if (!m_response.url().protocolIsInHTTPFamily()) {
410         // Don't cache non-HTTP main resources since we can't check for freshness.
411         // FIXME: We should not cache subresources either, but when we tried this
412         // it caused performance and flakiness issues in our test infrastructure.
413         if (m_type == MainResource && !SchemeRegistry::shouldCacheResponsesFromURLSchemeIndefinitely(m_response.url().protocol()))
414             return 0;
415
416         return std::numeric_limits<double>::max();
417     }
418
419     // RFC2616 13.2.4
420     double maxAgeValue = m_response.cacheControlMaxAge();
421     if (std::isfinite(maxAgeValue))
422         return maxAgeValue;
423     double expiresValue = m_response.expires();
424     double dateValue = m_response.date();
425     double creationTime = std::isfinite(dateValue) ? dateValue : m_responseTimestamp;
426     if (std::isfinite(expiresValue))
427         return expiresValue - creationTime;
428     double lastModifiedValue = m_response.lastModified();
429     if (std::isfinite(lastModifiedValue))
430         return (creationTime - lastModifiedValue) * 0.1;
431     // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0.
432     return 0;
433 }
434
435 void CachedResource::responseReceived(const ResourceResponse& response)
436 {
437     setResponse(response);
438     m_responseTimestamp = currentTime();
439     String encoding = response.textEncodingName();
440     if (!encoding.isNull())
441         setEncoding(encoding);
442 }
443
444 void CachedResource::clearLoader()
445 {
446     ASSERT(m_loader);
447     m_loader = 0;
448 }
449
450 void CachedResource::addClient(CachedResourceClient* client)
451 {
452     if (addClientToSet(client))
453         didAddClient(client);
454 }
455
456 void CachedResource::didAddClient(CachedResourceClient* c)
457 {
458     if (m_decodedDataDeletionTimer.isActive())
459         m_decodedDataDeletionTimer.stop();
460
461     if (m_clientsAwaitingCallback.contains(c)) {
462         m_clients.add(c);
463         m_clientsAwaitingCallback.remove(c);
464     }
465     if (!isLoading() && !stillNeedsLoad())
466         c->notifyFinished(this);
467 }
468
469 bool CachedResource::addClientToSet(CachedResourceClient* client)
470 {
471     ASSERT(!isPurgeable());
472
473     if (m_preloadResult == PreloadNotReferenced) {
474         if (isLoaded())
475             m_preloadResult = PreloadReferencedWhileComplete;
476         else if (m_requestedFromNetworkingLayer)
477             m_preloadResult = PreloadReferencedWhileLoading;
478         else
479             m_preloadResult = PreloadReferenced;
480     }
481     if (!hasClients() && inCache())
482         memoryCache()->addToLiveResourcesSize(this);
483
484     if ((m_type == RawResource || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
485         // Certain resources (especially XHRs and main resources) do crazy things if an asynchronous load returns
486         // synchronously (e.g., scripts may not have set all the state they need to handle the load).
487         // Therefore, rather than immediately sending callbacks on a cache hit like other CachedResources,
488         // we schedule the callbacks and ensure we never finish synchronously.
489         ASSERT(!m_clientsAwaitingCallback.contains(client));
490         m_clientsAwaitingCallback.add(client, CachedResourceCallback::schedule(this, client));
491         return false;
492     }
493
494     m_clients.add(client);
495     return true;
496 }
497
498 void CachedResource::removeClient(CachedResourceClient* client)
499 {
500     OwnPtr<CachedResourceCallback> callback = m_clientsAwaitingCallback.take(client);
501     if (callback) {
502         ASSERT(!m_clients.contains(client));
503         callback->cancel();
504         callback.clear();
505     } else {
506         ASSERT(m_clients.contains(client));
507         m_clients.remove(client);
508         didRemoveClient(client);
509     }
510
511     bool deleted = deleteIfPossible();
512     if (!deleted && !hasClients()) {
513         if (inCache()) {
514             memoryCache()->removeFromLiveResourcesSize(this);
515             memoryCache()->removeFromLiveDecodedResourcesList(this);
516         }
517         if (!m_switchingClientsToRevalidatedResource)
518             allClientsRemoved();
519         destroyDecodedDataIfNeeded();
520         if (response().cacheControlContainsNoStore()) {
521             // RFC2616 14.9.2:
522             // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
523             // "... History buffers MAY store such responses as part of their normal operation."
524             // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
525             if (url().protocolIs("https"))
526                 memoryCache()->remove(this);
527         } else
528             memoryCache()->prune();
529     }
530     // This object may be dead here.
531 }
532
533 void CachedResource::destroyDecodedDataIfNeeded()
534 {
535     if (!m_decodedSize)
536         return;
537     if (!memoryCache()->deadDecodedDataDeletionInterval())
538         return;
539     m_decodedDataDeletionTimer.restart();
540 }
541
542 void CachedResource::decodedDataDeletionTimerFired(DeferrableOneShotTimer<CachedResource>&)
543 {
544     destroyDecodedData();
545 }
546
547 bool CachedResource::deleteIfPossible()
548 {
549     if (canDelete() && !inCache()) {
550         InspectorInstrumentation::willDestroyCachedResource(this);
551         delete this;
552         return true;
553     }
554     return false;
555 }
556
557 void CachedResource::setDecodedSize(unsigned size)
558 {
559     if (size == m_decodedSize)
560         return;
561
562     int delta = size - m_decodedSize;
563
564     // The object must now be moved to a different queue, since its size has been changed.
565     // We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
566     // queue.
567     if (inCache())
568         memoryCache()->removeFromLRUList(this);
569     
570     m_decodedSize = size;
571    
572     if (inCache()) { 
573         // Now insert into the new LRU list.
574         memoryCache()->insertInLRUList(this);
575         
576         // Insert into or remove from the live decoded list if necessary.
577         // When inserting into the LiveDecodedResourcesList it is possible
578         // that the m_lastDecodedAccessTime is still zero or smaller than
579         // the m_lastDecodedAccessTime of the current list head. This is a
580         // violation of the invariant that the list is to be kept sorted
581         // by access time. The weakening of the invariant does not pose
582         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
583         if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
584             memoryCache()->insertInLiveDecodedResourcesList(this);
585         else if (!m_decodedSize && m_inLiveDecodedResourcesList)
586             memoryCache()->removeFromLiveDecodedResourcesList(this);
587
588         // Update the cache's size totals.
589         memoryCache()->adjustSize(hasClients(), delta);
590     }
591 }
592
593 void CachedResource::setEncodedSize(unsigned size)
594 {
595     if (size == m_encodedSize)
596         return;
597
598     // The size cannot ever shrink (unless it is being nulled out because of an error).  If it ever does, assert.
599     ASSERT(size == 0 || size >= m_encodedSize);
600     
601     int delta = size - m_encodedSize;
602
603     // The object must now be moved to a different queue, since its size has been changed.
604     // We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
605     // queue.
606     if (inCache())
607         memoryCache()->removeFromLRUList(this);
608     
609     m_encodedSize = size;
610    
611     if (inCache()) { 
612         // Now insert into the new LRU list.
613         memoryCache()->insertInLRUList(this);
614         
615         // Update the cache's size totals.
616         memoryCache()->adjustSize(hasClients(), delta);
617     }
618 }
619
620 void CachedResource::didAccessDecodedData(double timeStamp)
621 {
622     m_lastDecodedAccessTime = timeStamp;
623     
624     if (inCache()) {
625         if (m_inLiveDecodedResourcesList) {
626             memoryCache()->removeFromLiveDecodedResourcesList(this);
627             memoryCache()->insertInLiveDecodedResourcesList(this);
628         }
629         memoryCache()->prune();
630     }
631 }
632     
633 void CachedResource::setResourceToRevalidate(CachedResource* resource) 
634
635     ASSERT(resource);
636     ASSERT(!m_resourceToRevalidate);
637     ASSERT(resource != this);
638     ASSERT(m_handlesToRevalidate.isEmpty());
639     ASSERT(resource->type() == type());
640
641     LOG(ResourceLoading, "CachedResource %p setResourceToRevalidate %p", this, resource);
642
643     // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
644     // https://bugs.webkit.org/show_bug.cgi?id=28604.
645     // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in CachedResource::clearResourceToRevalidate.
646     ASSERT(!resource->m_proxyResource);
647
648     resource->m_proxyResource = this;
649     m_resourceToRevalidate = resource;
650 }
651
652 void CachedResource::clearResourceToRevalidate() 
653
654     ASSERT(m_resourceToRevalidate);
655     if (m_switchingClientsToRevalidatedResource)
656         return;
657
658     // A resource may start revalidation before this method has been called, so check that this resource is still the proxy resource before clearing it out.
659     if (m_resourceToRevalidate->m_proxyResource == this) {
660         m_resourceToRevalidate->m_proxyResource = 0;
661         m_resourceToRevalidate->deleteIfPossible();
662     }
663     m_handlesToRevalidate.clear();
664     m_resourceToRevalidate = 0;
665     deleteIfPossible();
666 }
667     
668 void CachedResource::switchClientsToRevalidatedResource()
669 {
670     ASSERT(m_resourceToRevalidate);
671     ASSERT(m_resourceToRevalidate->inCache());
672     ASSERT(!inCache());
673
674     LOG(ResourceLoading, "CachedResource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
675
676     m_switchingClientsToRevalidatedResource = true;
677     HashSet<CachedResourceHandleBase*>::iterator end = m_handlesToRevalidate.end();
678     for (HashSet<CachedResourceHandleBase*>::iterator it = m_handlesToRevalidate.begin(); it != end; ++it) {
679         CachedResourceHandleBase* handle = *it;
680         handle->m_resource = m_resourceToRevalidate;
681         m_resourceToRevalidate->registerHandle(handle);
682         --m_handleCount;
683     }
684     ASSERT(!m_handleCount);
685     m_handlesToRevalidate.clear();
686
687     Vector<CachedResourceClient*> clientsToMove;
688     HashCountedSet<CachedResourceClient*>::iterator end2 = m_clients.end();
689     for (HashCountedSet<CachedResourceClient*>::iterator it = m_clients.begin(); it != end2; ++it) {
690         CachedResourceClient* client = it->key;
691         unsigned count = it->value;
692         while (count) {
693             clientsToMove.append(client);
694             --count;
695         }
696     }
697
698     unsigned moveCount = clientsToMove.size();
699     for (unsigned n = 0; n < moveCount; ++n)
700         removeClient(clientsToMove[n]);
701     ASSERT(m_clients.isEmpty());
702
703     for (unsigned n = 0; n < moveCount; ++n)
704         m_resourceToRevalidate->addClientToSet(clientsToMove[n]);
705     for (unsigned n = 0; n < moveCount; ++n) {
706         // Calling didAddClient may do anything, including trying to cancel revalidation.
707         // Assert that it didn't succeed.
708         ASSERT(m_resourceToRevalidate);
709         // Calling didAddClient for a client may end up removing another client. In that case it won't be in the set anymore.
710         if (m_resourceToRevalidate->m_clients.contains(clientsToMove[n]))
711             m_resourceToRevalidate->didAddClient(clientsToMove[n]);
712     }
713     m_switchingClientsToRevalidatedResource = false;
714 }
715
716 void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
717 {
718     m_responseTimestamp = currentTime();
719
720     // RFC2616 10.3.5
721     // Update cached headers from the 304 response
722     const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields();
723     HTTPHeaderMap::const_iterator end = newHeaders.end();
724     for (HTTPHeaderMap::const_iterator it = newHeaders.begin(); it != end; ++it) {
725         // Entity headers should not be sent by servers when generating a 304
726         // response; misconfigured servers send them anyway. We shouldn't allow
727         // such headers to update the original request. We'll base this on the
728         // list defined by RFC2616 7.1, with a few additions for extension headers
729         // we care about.
730         if (!shouldUpdateHeaderAfterRevalidation(it->key))
731             continue;
732         m_response.setHTTPHeaderField(it->key, it->value);
733     }
734 }
735
736 void CachedResource::registerHandle(CachedResourceHandleBase* h)
737 {
738     ++m_handleCount;
739     if (m_resourceToRevalidate)
740         m_handlesToRevalidate.add(h);
741 }
742
743 void CachedResource::unregisterHandle(CachedResourceHandleBase* h)
744 {
745     ASSERT(m_handleCount > 0);
746     --m_handleCount;
747
748     if (m_resourceToRevalidate)
749          m_handlesToRevalidate.remove(h);
750
751     if (!m_handleCount)
752         deleteIfPossible();
753 }
754
755 bool CachedResource::canUseCacheValidator() const
756 {
757     if (m_loading || errorOccurred())
758         return false;
759
760     if (m_response.cacheControlContainsNoStore())
761         return false;
762     return m_response.hasCacheValidatorFields();
763 }
764
765 bool CachedResource::mustRevalidateDueToCacheHeaders(CachePolicy cachePolicy) const
766 {    
767     ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);
768
769     if (cachePolicy == CachePolicyRevalidate)
770         return true;
771
772     if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
773         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
774         return true;
775     }
776
777     if (cachePolicy == CachePolicyCache) {
778         if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
779             LOG(ResourceLoading, "CachedResource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
780             return true;
781         }
782         return false;
783     }
784
785     // CachePolicyVerify
786     if (isExpired()) {
787         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of isExpired()\n", this);
788         return true;
789     }
790
791     return false;
792 }
793
794 bool CachedResource::isSafeToMakePurgeable() const
795
796 #if ENABLE(DISK_IMAGE_CACHE)
797     // It does not make sense to have a resource in the disk image cache
798     // (memory mapped on disk) and purgeable (in memory). So do not allow
799     // disk image cached resources to be purgeable.
800     if (isUsingDiskImageCache())
801         return false;
802 #endif
803
804     return !hasClients() && !m_proxyResource && !m_resourceToRevalidate;
805 }
806
807 bool CachedResource::makePurgeable(bool purgeable) 
808
809     if (purgeable) {
810         ASSERT(isSafeToMakePurgeable());
811
812         if (m_purgeableData) {
813             ASSERT(!m_data);
814             return true;
815         }
816         if (!m_data)
817             return false;
818         
819         // Should not make buffer purgeable if it has refs other than this since we don't want two copies.
820         if (!m_data->hasOneRef())
821             return false;
822
823         m_data->createPurgeableBuffer();
824         if (!m_data->hasPurgeableBuffer())
825             return false;
826
827         m_purgeableData = m_data->releasePurgeableBuffer();
828         m_purgeableData->setPurgePriority(purgePriority());
829         m_purgeableData->makePurgeable(true);
830         m_data.clear();
831         return true;
832     }
833
834     if (!m_purgeableData)
835         return true;
836     ASSERT(!m_data);
837     ASSERT(!hasClients());
838
839     if (!m_purgeableData->makePurgeable(false))
840         return false; 
841
842     m_data = ResourceBuffer::adoptSharedBuffer(SharedBuffer::adoptPurgeableBuffer(m_purgeableData.release()));
843     return true;
844 }
845
846 bool CachedResource::isPurgeable() const
847 {
848     return m_purgeableData && m_purgeableData->isPurgeable();
849 }
850
851 bool CachedResource::wasPurged() const
852 {
853     return m_purgeableData && m_purgeableData->wasPurged();
854 }
855
856 unsigned CachedResource::overheadSize() const
857 {
858     static const int kAverageClientsHashMapSize = 384;
859     return sizeof(CachedResource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
860 }
861
862 void CachedResource::setLoadPriority(ResourceLoadPriority loadPriority)
863 {
864     if (loadPriority == ResourceLoadPriorityUnresolved)
865         loadPriority = defaultPriorityForResourceType(type());
866     if (loadPriority == m_loadPriority)
867         return;
868     m_loadPriority = loadPriority;
869     if (m_loader)
870         m_loader->didChangePriority(loadPriority);
871 }
872
873 CachedResource::CachedResourceCallback::CachedResourceCallback(CachedResource* resource, CachedResourceClient* client)
874     : m_resource(resource)
875     , m_client(client)
876     , m_callbackTimer(this, &CachedResourceCallback::timerFired)
877 {
878     m_callbackTimer.startOneShot(0);
879 }
880
881 void CachedResource::CachedResourceCallback::cancel()
882 {
883     if (m_callbackTimer.isActive())
884         m_callbackTimer.stop();
885 }
886
887 void CachedResource::CachedResourceCallback::timerFired(Timer<CachedResourceCallback>&)
888 {
889     m_resource->didAddClient(m_client);
890 }
891
892 #if ENABLE(DISK_IMAGE_CACHE)
893 bool CachedResource::isUsingDiskImageCache() const
894 {
895     return m_data && m_data->isUsingDiskImageCache();
896 }
897 #endif
898
899 #if PLATFORM(MAC)
900 void CachedResource::tryReplaceEncodedData(PassRefPtr<SharedBuffer> newBuffer)
901 {
902     if (!m_data)
903         return;
904     
905     if (!mayTryReplaceEncodedData())
906         return;
907     
908     // Because the disk cache is asynchronous and racey with regards to the data we might be asked to replace,
909     // we need to verify that the new buffer has the same contents as our old buffer.
910     if (m_data->size() != newBuffer->size() || memcmp(m_data->data(), newBuffer->data(), m_data->size()))
911         return;
912
913     m_data->tryReplaceSharedBufferContents(newBuffer.get());
914 }
915 #endif
916
917 }