Unreviewed, rolling out r124000.
[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 "MemoryCache.h"
28 #include "CachedMetadata.h"
29 #include "CachedResourceClient.h"
30 #include "CachedResourceClientWalker.h"
31 #include "CachedResourceHandle.h"
32 #include "CachedResourceLoader.h"
33 #include "CrossOriginAccessControl.h"
34 #include "Document.h"
35 #include "Frame.h"
36 #include "FrameLoaderClient.h"
37 #include "KURL.h"
38 #include "Logging.h"
39 #include "PurgeableBuffer.h"
40 #include "ResourceHandle.h"
41 #include "ResourceLoadScheduler.h"
42 #include "SharedBuffer.h"
43 #include "SubresourceLoader.h"
44 #include <wtf/CurrentTime.h>
45 #include <wtf/MathExtras.h>
46 #include <wtf/RefCountedLeakCounter.h>
47 #include <wtf/StdLibExtras.h>
48 #include <wtf/text/CString.h>
49 #include <wtf/Vector.h>
50
51 using namespace WTF;
52
53 namespace WebCore {
54     
55 static ResourceLoadPriority defaultPriorityForResourceType(CachedResource::Type type)
56 {
57     switch (type) {
58         case CachedResource::CSSStyleSheet:
59             return ResourceLoadPriorityHigh;
60         case CachedResource::Script:
61         case CachedResource::FontResource:
62         case CachedResource::RawResource:
63             return ResourceLoadPriorityMedium;
64         case CachedResource::ImageResource:
65             return ResourceLoadPriorityLow;
66 #if ENABLE(XSLT)
67         case CachedResource::XSLStyleSheet:
68             return ResourceLoadPriorityHigh;
69 #endif
70 #if ENABLE(SVG)
71         case CachedResource::SVGDocumentResource:
72             return ResourceLoadPriorityLow;
73 #endif
74 #if ENABLE(LINK_PREFETCH)
75         case CachedResource::LinkPrefetch:
76             return ResourceLoadPriorityVeryLow;
77         case CachedResource::LinkSubresource:
78             return ResourceLoadPriorityVeryLow;
79 #endif
80 #if ENABLE(VIDEO_TRACK)
81         case CachedResource::TextTrackResource:
82             return ResourceLoadPriorityLow;
83 #endif
84 #if ENABLE(CSS_SHADERS)
85         case CachedResource::ShaderResource:
86             return ResourceLoadPriorityMedium;
87 #endif
88     }
89     ASSERT_NOT_REACHED();
90     return ResourceLoadPriorityLow;
91 }
92
93 #if PLATFORM(CHROMIUM) || PLATFORM(BLACKBERRY)
94 static ResourceRequest::TargetType cachedResourceTypeToTargetType(CachedResource::Type type)
95 {
96     switch (type) {
97     case CachedResource::CSSStyleSheet:
98 #if ENABLE(XSLT)
99     case CachedResource::XSLStyleSheet:
100 #endif
101         return ResourceRequest::TargetIsStyleSheet;
102     case CachedResource::Script: 
103         return ResourceRequest::TargetIsScript;
104     case CachedResource::FontResource:
105         return ResourceRequest::TargetIsFontResource;
106     case CachedResource::ImageResource:
107         return ResourceRequest::TargetIsImage;
108 #if ENABLE(CSS_SHADERS)
109     case CachedResource::ShaderResource:
110 #endif
111     case CachedResource::RawResource:
112         return ResourceRequest::TargetIsSubresource;    
113 #if ENABLE(LINK_PREFETCH)
114     case CachedResource::LinkPrefetch:
115         return ResourceRequest::TargetIsPrefetch;
116     case CachedResource::LinkSubresource:
117         return ResourceRequest::TargetIsSubresource;
118 #endif
119 #if ENABLE(VIDEO_TRACK)
120     case CachedResource::TextTrackResource:
121         return ResourceRequest::TargetIsTextTrack;
122 #endif
123 #if ENABLE(SVG)
124     case CachedResource::SVGDocumentResource:
125         return ResourceRequest::TargetIsImage;
126 #endif
127     }
128     ASSERT_NOT_REACHED();
129     return ResourceRequest::TargetIsSubresource;
130 }
131 #endif
132
133 DEFINE_DEBUG_ONLY_GLOBAL(RefCountedLeakCounter, cachedResourceLeakCounter, ("CachedResource"));
134
135 CachedResource::CachedResource(const ResourceRequest& request, Type type)
136     : m_resourceRequest(request)
137     , m_loadPriority(defaultPriorityForResourceType(type))
138     , m_responseTimestamp(currentTime())
139     , m_decodedDataDeletionTimer(this, &CachedResource::decodedDataDeletionTimerFired)
140     , m_lastDecodedAccessTime(0)
141     , m_loadFinishTime(0)
142     , m_encodedSize(0)
143     , m_decodedSize(0)
144     , m_accessCount(0)
145     , m_handleCount(0)
146     , m_preloadCount(0)
147     , m_preloadResult(PreloadNotReferenced)
148     , m_inLiveDecodedResourcesList(false)
149     , m_requestedFromNetworkingLayer(false)
150     , m_inCache(false)
151     , m_loading(false)
152     , m_switchingClientsToRevalidatedResource(false)
153     , m_type(type)
154     , m_status(Pending)
155 #ifndef NDEBUG
156     , m_deleted(false)
157     , m_lruIndex(0)
158 #endif
159     , m_nextInAllResourcesList(0)
160     , m_prevInAllResourcesList(0)
161     , m_nextInLiveResourcesList(0)
162     , m_prevInLiveResourcesList(0)
163     , m_owningCachedResourceLoader(0)
164     , m_resourceToRevalidate(0)
165     , m_proxyResource(0)
166 {
167     ASSERT(m_type == unsigned(type)); // m_type is a bitfield, so this tests careless updates of the enum.
168 #ifndef NDEBUG
169     cachedResourceLeakCounter.increment();
170 #endif
171 }
172
173 CachedResource::~CachedResource()
174 {
175     ASSERT(!m_resourceToRevalidate); // Should be true because canDelete() checks this.
176     ASSERT(canDelete());
177     ASSERT(!inCache());
178     ASSERT(!m_deleted);
179     ASSERT(url().isNull() || memoryCache()->resourceForURL(KURL(ParsedURLString, url())) != this);
180     
181 #ifndef NDEBUG
182     m_deleted = true;
183     cachedResourceLeakCounter.decrement();
184 #endif
185
186     if (m_owningCachedResourceLoader)
187         m_owningCachedResourceLoader->removeCachedResource(this);
188 }
189
190 void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const ResourceLoaderOptions& options)
191 {
192     m_options = options;
193     m_loading = true;
194
195 #if PLATFORM(CHROMIUM) || PLATFORM(BLACKBERRY)
196     if (m_resourceRequest.targetType() == ResourceRequest::TargetIsUnspecified)
197         m_resourceRequest.setTargetType(cachedResourceTypeToTargetType(type()));
198 #endif
199
200     if (!accept().isEmpty())
201         m_resourceRequest.setHTTPAccept(accept());
202
203     if (isCacheValidator()) {
204         CachedResource* resourceToRevalidate = m_resourceToRevalidate;
205         ASSERT(resourceToRevalidate->canUseCacheValidator());
206         ASSERT(resourceToRevalidate->isLoaded());
207         const String& lastModified = resourceToRevalidate->response().httpHeaderField("Last-Modified");
208         const String& eTag = resourceToRevalidate->response().httpHeaderField("ETag");
209         if (!lastModified.isEmpty() || !eTag.isEmpty()) {
210             ASSERT(cachedResourceLoader->cachePolicy() != CachePolicyReload);
211             if (cachedResourceLoader->cachePolicy() == CachePolicyRevalidate)
212                 m_resourceRequest.setHTTPHeaderField("Cache-Control", "max-age=0");
213             if (!lastModified.isEmpty())
214                 m_resourceRequest.setHTTPHeaderField("If-Modified-Since", lastModified);
215             if (!eTag.isEmpty())
216                 m_resourceRequest.setHTTPHeaderField("If-None-Match", eTag);
217         }
218     }
219
220 #if ENABLE(LINK_PREFETCH)
221     if (type() == CachedResource::LinkPrefetch || type() == CachedResource::LinkSubresource)
222         m_resourceRequest.setHTTPHeaderField("Purpose", "prefetch");
223 #endif
224     m_resourceRequest.setPriority(loadPriority());
225     
226     m_loader = resourceLoadScheduler()->scheduleSubresourceLoad(cachedResourceLoader->document()->frame(), this, m_resourceRequest, m_resourceRequest.priority(), options);
227     if (!m_loader) {
228         // FIXME: What if resources in other frames were waiting for this revalidation?
229         LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
230         if (m_resourceToRevalidate) 
231             memoryCache()->revalidationFailed(this); 
232         error(CachedResource::LoadError);
233         return;
234     }
235
236     m_status = Pending;
237 }
238
239 void CachedResource::checkNotify()
240 {
241     if (isLoading())
242         return;
243
244     CachedResourceClientWalker<CachedResourceClient> w(m_clients);
245     while (CachedResourceClient* c = w.next())
246         c->notifyFinished(this);
247 }
248
249 void CachedResource::data(PassRefPtr<SharedBuffer>, bool allDataReceived)
250 {
251     if (!allDataReceived)
252         return;
253     
254     setLoading(false);
255     checkNotify();
256 }
257
258 void CachedResource::error(CachedResource::Status status)
259 {
260     setStatus(status);
261     ASSERT(errorOccurred());
262     m_data.clear();
263
264     setLoading(false);
265     checkNotify();
266 }
267
268 void CachedResource::finish()
269 {
270     if (!errorOccurred())
271         m_status = Cached;
272 }
273
274 bool CachedResource::passesAccessControlCheck(SecurityOrigin* securityOrigin)
275 {
276     String errorDescription;
277     return WebCore::passesAccessControlCheck(m_response, resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription);
278 }
279
280 bool CachedResource::isExpired() const
281 {
282     if (m_response.isNull())
283         return false;
284
285     return currentAge() > freshnessLifetime();
286 }
287     
288 double CachedResource::currentAge() const
289 {
290     // RFC2616 13.2.3
291     // No compensation for latency as that is not terribly important in practice
292     double dateValue = m_response.date();
293     double apparentAge = isfinite(dateValue) ? max(0., m_responseTimestamp - dateValue) : 0;
294     double ageValue = m_response.age();
295     double correctedReceivedAge = isfinite(ageValue) ? max(apparentAge, ageValue) : apparentAge;
296     double residentTime = currentTime() - m_responseTimestamp;
297     return correctedReceivedAge + residentTime;
298 }
299     
300 double CachedResource::freshnessLifetime() const
301 {
302     // Cache non-http resources liberally
303     if (!m_response.url().protocolIsInHTTPFamily())
304         return std::numeric_limits<double>::max();
305
306     // RFC2616 13.2.4
307     double maxAgeValue = m_response.cacheControlMaxAge();
308     if (isfinite(maxAgeValue))
309         return maxAgeValue;
310     double expiresValue = m_response.expires();
311     double dateValue = m_response.date();
312     double creationTime = isfinite(dateValue) ? dateValue : m_responseTimestamp;
313     if (isfinite(expiresValue))
314         return expiresValue - creationTime;
315     double lastModifiedValue = m_response.lastModified();
316     if (isfinite(lastModifiedValue))
317         return (creationTime - lastModifiedValue) * 0.1;
318     // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0.
319     return 0;
320 }
321
322 void CachedResource::setResponse(const ResourceResponse& response)
323 {
324     m_response = response;
325     m_responseTimestamp = currentTime();
326     String encoding = response.textEncodingName();
327     if (!encoding.isNull())
328         setEncoding(encoding);
329 }
330
331 void CachedResource::setSerializedCachedMetadata(const char* data, size_t size)
332 {
333     // We only expect to receive cached metadata from the platform once.
334     // If this triggers, it indicates an efficiency problem which is most
335     // likely unexpected in code designed to improve performance.
336     ASSERT(!m_cachedMetadata);
337
338     m_cachedMetadata = CachedMetadata::deserialize(data, size);
339 }
340
341 void CachedResource::setCachedMetadata(unsigned dataTypeID, const char* data, size_t size)
342 {
343     // Currently, only one type of cached metadata per resource is supported.
344     // If the need arises for multiple types of metadata per resource this could
345     // be enhanced to store types of metadata in a map.
346     ASSERT(!m_cachedMetadata);
347
348     m_cachedMetadata = CachedMetadata::create(dataTypeID, data, size);
349     ResourceHandle::cacheMetadata(m_response, m_cachedMetadata->serialize());
350 }
351
352 CachedMetadata* CachedResource::cachedMetadata(unsigned dataTypeID) const
353 {
354     if (!m_cachedMetadata || m_cachedMetadata->dataTypeID() != dataTypeID)
355         return 0;
356     return m_cachedMetadata.get();
357 }
358
359 void CachedResource::stopLoading()
360 {
361     ASSERT(m_loader);            
362     m_loader = 0;
363
364     CachedResourceHandle<CachedResource> protect(this);
365
366     // All loads finish with data(allDataReceived = true) or error(), except for
367     // canceled loads, which silently set our request to 0. Be sure to notify our
368     // client in that case, so we don't seem to continue loading forever.
369     if (isLoading()) {
370         setLoading(false);
371         setStatus(Canceled);
372         checkNotify();
373     }
374 }
375
376 void CachedResource::addClient(CachedResourceClient* client)
377 {
378     if (addClientToSet(client))
379         didAddClient(client);
380 }
381
382 void CachedResource::didAddClient(CachedResourceClient* c)
383 {
384     if (m_decodedDataDeletionTimer.isActive())
385         m_decodedDataDeletionTimer.stop();
386
387     if (m_clientsAwaitingCallback.contains(c)) {
388         m_clients.add(c);
389         m_clientsAwaitingCallback.remove(c);
390     }
391     if (!isLoading())
392         c->notifyFinished(this);
393 }
394
395 bool CachedResource::addClientToSet(CachedResourceClient* client)
396 {
397     ASSERT(!isPurgeable());
398
399     if (m_preloadResult == PreloadNotReferenced) {
400         if (isLoaded())
401             m_preloadResult = PreloadReferencedWhileComplete;
402         else if (m_requestedFromNetworkingLayer)
403             m_preloadResult = PreloadReferencedWhileLoading;
404         else
405             m_preloadResult = PreloadReferenced;
406     }
407     if (!hasClients() && inCache())
408         memoryCache()->addToLiveResourcesSize(this);
409
410     if (m_type == RawResource && !m_response.isNull() && !m_proxyResource) {
411         // Certain resources (especially XHRs) do crazy things if an asynchronous load returns
412         // synchronously (e.g., scripts may not have set all the state they need to handle the load).
413         // Therefore, rather than immediately sending callbacks on a cache hit like other CachedResources,
414         // we schedule the callbacks and ensure we never finish synchronously.
415         ASSERT(!m_clientsAwaitingCallback.contains(client));
416         m_clientsAwaitingCallback.add(client, CachedResourceCallback::schedule(this, client));
417         return false;
418     }
419
420     m_clients.add(client);
421     return true;
422 }
423
424 void CachedResource::removeClient(CachedResourceClient* client)
425 {
426     OwnPtr<CachedResourceCallback> callback = m_clientsAwaitingCallback.take(client);
427     if (callback) {
428         ASSERT(!m_clients.contains(client));
429         callback->cancel();
430         callback.clear();
431     } else {
432         ASSERT(m_clients.contains(client));
433         m_clients.remove(client);
434         didRemoveClient(client);
435     }
436
437     if (canDelete() && !inCache())
438         delete this;
439     else if (!hasClients() && inCache()) {
440         memoryCache()->removeFromLiveResourcesSize(this);
441         memoryCache()->removeFromLiveDecodedResourcesList(this);
442         allClientsRemoved();
443         destroyDecodedDataIfNeeded();
444         if (response().cacheControlContainsNoStore()) {
445             // RFC2616 14.9.2:
446             // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
447             // "... History buffers MAY store such responses as part of their normal operation."
448             // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
449             if (protocolIs(url(), "https"))
450                 memoryCache()->remove(this);
451         } else
452             memoryCache()->prune();
453     }
454     // This object may be dead here.
455 }
456
457 void CachedResource::destroyDecodedDataIfNeeded()
458 {
459     if (!m_decodedSize)
460         return;
461
462     if (double interval = memoryCache()->deadDecodedDataDeletionInterval())
463         m_decodedDataDeletionTimer.startOneShot(interval);
464 }
465
466 void CachedResource::decodedDataDeletionTimerFired(Timer<CachedResource>*)
467 {
468     destroyDecodedData();
469 }
470
471 void CachedResource::deleteIfPossible()
472 {
473     if (canDelete() && !inCache())
474         delete this;
475 }
476     
477 void CachedResource::setDecodedSize(unsigned size)
478 {
479     if (size == m_decodedSize)
480         return;
481
482     int delta = size - m_decodedSize;
483
484     // The object must now be moved to a different queue, since its size has been changed.
485     // We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
486     // queue.
487     if (inCache())
488         memoryCache()->removeFromLRUList(this);
489     
490     m_decodedSize = size;
491    
492     if (inCache()) { 
493         // Now insert into the new LRU list.
494         memoryCache()->insertInLRUList(this);
495         
496         // Insert into or remove from the live decoded list if necessary.
497         // When inserting into the LiveDecodedResourcesList it is possible
498         // that the m_lastDecodedAccessTime is still zero or smaller than
499         // the m_lastDecodedAccessTime of the current list head. This is a
500         // violation of the invariant that the list is to be kept sorted
501         // by access time. The weakening of the invariant does not pose
502         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
503         if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
504             memoryCache()->insertInLiveDecodedResourcesList(this);
505         else if (!m_decodedSize && m_inLiveDecodedResourcesList)
506             memoryCache()->removeFromLiveDecodedResourcesList(this);
507
508         // Update the cache's size totals.
509         memoryCache()->adjustSize(hasClients(), delta);
510     }
511 }
512
513 void CachedResource::setEncodedSize(unsigned size)
514 {
515     if (size == m_encodedSize)
516         return;
517
518     // The size cannot ever shrink (unless it is being nulled out because of an error).  If it ever does, assert.
519     ASSERT(size == 0 || size >= m_encodedSize);
520     
521     int delta = size - m_encodedSize;
522
523     // The object must now be moved to a different queue, since its size has been changed.
524     // We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
525     // queue.
526     if (inCache())
527         memoryCache()->removeFromLRUList(this);
528     
529     m_encodedSize = size;
530    
531     if (inCache()) { 
532         // Now insert into the new LRU list.
533         memoryCache()->insertInLRUList(this);
534         
535         // Update the cache's size totals.
536         memoryCache()->adjustSize(hasClients(), delta);
537     }
538 }
539
540 void CachedResource::didAccessDecodedData(double timeStamp)
541 {
542     m_lastDecodedAccessTime = timeStamp;
543     
544     if (inCache()) {
545         if (m_inLiveDecodedResourcesList) {
546             memoryCache()->removeFromLiveDecodedResourcesList(this);
547             memoryCache()->insertInLiveDecodedResourcesList(this);
548         }
549         memoryCache()->prune();
550     }
551 }
552     
553 void CachedResource::setResourceToRevalidate(CachedResource* resource) 
554
555     ASSERT(resource);
556     ASSERT(!m_resourceToRevalidate);
557     ASSERT(resource != this);
558     ASSERT(m_handlesToRevalidate.isEmpty());
559     ASSERT(resource->type() == type());
560
561     LOG(ResourceLoading, "CachedResource %p setResourceToRevalidate %p", this, resource);
562
563     // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
564     // https://bugs.webkit.org/show_bug.cgi?id=28604.
565     // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in CachedResource::clearResourceToRevalidate.
566     ASSERT(!resource->m_proxyResource);
567
568     resource->m_proxyResource = this;
569     m_resourceToRevalidate = resource;
570 }
571
572 void CachedResource::clearResourceToRevalidate() 
573
574     ASSERT(m_resourceToRevalidate);
575     if (m_switchingClientsToRevalidatedResource)
576         return;
577
578     // 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.
579     if (m_resourceToRevalidate->m_proxyResource == this) {
580         m_resourceToRevalidate->m_proxyResource = 0;
581         m_resourceToRevalidate->deleteIfPossible();
582     }
583     m_handlesToRevalidate.clear();
584     m_resourceToRevalidate = 0;
585     deleteIfPossible();
586 }
587     
588 void CachedResource::switchClientsToRevalidatedResource()
589 {
590     ASSERT(m_resourceToRevalidate);
591     ASSERT(m_resourceToRevalidate->inCache());
592     ASSERT(!inCache());
593
594     LOG(ResourceLoading, "CachedResource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
595
596     m_switchingClientsToRevalidatedResource = true;
597     HashSet<CachedResourceHandleBase*>::iterator end = m_handlesToRevalidate.end();
598     for (HashSet<CachedResourceHandleBase*>::iterator it = m_handlesToRevalidate.begin(); it != end; ++it) {
599         CachedResourceHandleBase* handle = *it;
600         handle->m_resource = m_resourceToRevalidate;
601         m_resourceToRevalidate->registerHandle(handle);
602         --m_handleCount;
603     }
604     ASSERT(!m_handleCount);
605     m_handlesToRevalidate.clear();
606
607     Vector<CachedResourceClient*> clientsToMove;
608     HashCountedSet<CachedResourceClient*>::iterator end2 = m_clients.end();
609     for (HashCountedSet<CachedResourceClient*>::iterator it = m_clients.begin(); it != end2; ++it) {
610         CachedResourceClient* client = it->first;
611         unsigned count = it->second;
612         while (count) {
613             clientsToMove.append(client);
614             --count;
615         }
616     }
617     // Equivalent of calling removeClient() for all clients
618     m_clients.clear();
619
620     unsigned moveCount = clientsToMove.size();
621     for (unsigned n = 0; n < moveCount; ++n)
622         m_resourceToRevalidate->addClientToSet(clientsToMove[n]);
623     for (unsigned n = 0; n < moveCount; ++n) {
624         // Calling didAddClient may do anything, including trying to cancel revalidation.
625         // Assert that it didn't succeed.
626         ASSERT(m_resourceToRevalidate);
627         // Calling didAddClient for a client may end up removing another client. In that case it won't be in the set anymore.
628         if (m_resourceToRevalidate->m_clients.contains(clientsToMove[n]))
629             m_resourceToRevalidate->didAddClient(clientsToMove[n]);
630     }
631     m_switchingClientsToRevalidatedResource = false;
632 }
633     
634 void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
635 {
636     m_responseTimestamp = currentTime();
637
638     DEFINE_STATIC_LOCAL(const AtomicString, contentHeaderPrefix, ("content-"));
639     // RFC2616 10.3.5
640     // Update cached headers from the 304 response
641     const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields();
642     HTTPHeaderMap::const_iterator end = newHeaders.end();
643     for (HTTPHeaderMap::const_iterator it = newHeaders.begin(); it != end; ++it) {
644         // Don't allow 304 response to update content headers, these can't change but some servers send wrong values.
645         if (it->first.startsWith(contentHeaderPrefix, false))
646             continue;
647         m_response.setHTTPHeaderField(it->first, it->second);
648     }
649 }
650
651 void CachedResource::registerHandle(CachedResourceHandleBase* h)
652 {
653     ++m_handleCount;
654     if (m_resourceToRevalidate)
655         m_handlesToRevalidate.add(h);
656 }
657
658 void CachedResource::unregisterHandle(CachedResourceHandleBase* h)
659 {
660     ASSERT(m_handleCount > 0);
661     --m_handleCount;
662
663     if (m_resourceToRevalidate)
664          m_handlesToRevalidate.remove(h);
665
666     if (!m_handleCount)
667         deleteIfPossible();
668 }
669
670 bool CachedResource::canUseCacheValidator() const
671 {
672     if (m_loading || errorOccurred())
673         return false;
674
675     if (m_response.cacheControlContainsNoStore())
676         return false;
677     return m_response.hasCacheValidatorFields();
678 }
679
680 bool CachedResource::mustRevalidateDueToCacheHeaders(CachePolicy cachePolicy) const
681 {    
682     ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);
683
684     if (cachePolicy == CachePolicyRevalidate)
685         return true;
686
687     if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
688         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
689         return true;
690     }
691
692     if (cachePolicy == CachePolicyCache) {
693         if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
694             LOG(ResourceLoading, "CachedResource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
695             return true;
696         }
697         return false;
698     }
699
700     // CachePolicyVerify
701     if (isExpired()) {
702         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of isExpired()\n", this);
703         return true;
704     }
705
706     return false;
707 }
708
709 bool CachedResource::isSafeToMakePurgeable() const
710
711     return !hasClients() && !m_proxyResource && !m_resourceToRevalidate;
712 }
713
714 bool CachedResource::makePurgeable(bool purgeable) 
715
716     if (purgeable) {
717         ASSERT(isSafeToMakePurgeable());
718
719         if (m_purgeableData) {
720             ASSERT(!m_data);
721             return true;
722         }
723         if (!m_data)
724             return false;
725         
726         // Should not make buffer purgeable if it has refs other than this since we don't want two copies.
727         if (!m_data->hasOneRef())
728             return false;
729         
730         if (m_data->hasPurgeableBuffer()) {
731             m_purgeableData = m_data->releasePurgeableBuffer();
732         } else {
733             m_purgeableData = PurgeableBuffer::create(m_data->data(), m_data->size());
734             if (!m_purgeableData)
735                 return false;
736             m_purgeableData->setPurgePriority(purgePriority());
737         }
738         
739         m_purgeableData->makePurgeable(true);
740         m_data.clear();
741         return true;
742     }
743
744     if (!m_purgeableData)
745         return true;
746     ASSERT(!m_data);
747     ASSERT(!hasClients());
748
749     if (!m_purgeableData->makePurgeable(false))
750         return false; 
751
752     m_data = SharedBuffer::adoptPurgeableBuffer(m_purgeableData.release());
753     return true;
754 }
755
756 bool CachedResource::isPurgeable() const
757 {
758     return m_purgeableData && m_purgeableData->isPurgeable();
759 }
760
761 bool CachedResource::wasPurged() const
762 {
763     return m_purgeableData && m_purgeableData->wasPurged();
764 }
765
766 unsigned CachedResource::overheadSize() const
767 {
768     static const int kAverageClientsHashMapSize = 384;
769     return sizeof(CachedResource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
770 }
771     
772 void CachedResource::setLoadPriority(ResourceLoadPriority loadPriority) 
773
774     if (loadPriority == ResourceLoadPriorityUnresolved)
775         return;
776     m_loadPriority = loadPriority;
777 }
778
779
780 CachedResource::CachedResourceCallback::CachedResourceCallback(CachedResource* resource, CachedResourceClient* client)
781     : m_resource(resource)
782     , m_client(client)
783     , m_callbackTimer(this, &CachedResourceCallback::timerFired)
784 {
785     m_callbackTimer.startOneShot(0);
786 }
787
788 void CachedResource::CachedResourceCallback::cancel()
789 {
790     if (m_callbackTimer.isActive())
791         m_callbackTimer.stop();
792 }
793
794 void CachedResource::CachedResourceCallback::timerFired(Timer<CachedResourceCallback>*)
795 {
796     m_resource->didAddClient(m_client);
797 }
798
799 }