Web Inspector: pass parameters to inspector instrumentation by reference where possible
[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-2011, 2014 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 "FeatureCounter.h"
35 #include "FrameLoader.h"
36 #include "FrameLoaderClient.h"
37 #include "HTTPHeaderNames.h"
38 #include "InspectorInstrumentation.h"
39 #include "URL.h"
40 #include "LoaderStrategy.h"
41 #include "Logging.h"
42 #include "MemoryCache.h"
43 #include "PlatformStrategies.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 static ResourceLoadPriority defaultPriorityForResourceType(CachedResource::Type type)
66 {
67     switch (type) {
68     case CachedResource::MainResource:
69         return ResourceLoadPriorityVeryHigh;
70     case CachedResource::CSSStyleSheet:
71         return ResourceLoadPriorityHigh;
72     case CachedResource::Script:
73 #if ENABLE(SVG_FONTS)
74     case CachedResource::SVGFontResource:
75 #endif
76     case CachedResource::FontResource:
77     case CachedResource::RawResource:
78         return ResourceLoadPriorityMedium;
79     case CachedResource::ImageResource:
80         return ResourceLoadPriorityLow;
81 #if ENABLE(XSLT)
82     case CachedResource::XSLStyleSheet:
83         return ResourceLoadPriorityHigh;
84 #endif
85     case CachedResource::SVGDocumentResource:
86         return ResourceLoadPriorityLow;
87 #if ENABLE(LINK_PREFETCH)
88     case CachedResource::LinkPrefetch:
89         return ResourceLoadPriorityVeryLow;
90     case CachedResource::LinkSubresource:
91         return ResourceLoadPriorityVeryLow;
92 #endif
93 #if ENABLE(VIDEO_TRACK)
94     case CachedResource::TextTrackResource:
95         return ResourceLoadPriorityLow;
96 #endif
97     }
98     ASSERT_NOT_REACHED();
99     return ResourceLoadPriorityLow;
100 }
101
102 static std::chrono::milliseconds deadDecodedDataDeletionIntervalForResourceType(CachedResource::Type type)
103 {
104     if (type == CachedResource::Script)
105         return std::chrono::milliseconds { 0 };
106
107     return memoryCache().deadDecodedDataDeletionInterval();
108 }
109
110 DEFINE_DEBUG_ONLY_GLOBAL(RefCountedLeakCounter, cachedResourceLeakCounter, ("CachedResource"));
111
112 CachedResource::CachedResource(const ResourceRequest& request, Type type, SessionID sessionID)
113     : m_resourceRequest(request)
114     , m_decodedDataDeletionTimer(*this, &CachedResource::decodedDataDeletionTimerFired, deadDecodedDataDeletionIntervalForResourceType(type))
115     , m_sessionID(sessionID)
116     , m_loadPriority(defaultPriorityForResourceType(type))
117     , m_responseTimestamp(currentTime())
118     , m_lastDecodedAccessTime(0)
119     , m_loadFinishTime(0)
120     , m_encodedSize(0)
121     , m_decodedSize(0)
122     , m_accessCount(0)
123     , m_handleCount(0)
124     , m_preloadCount(0)
125     , m_preloadResult(PreloadNotReferenced)
126     , m_inLiveDecodedResourcesList(false)
127     , m_requestedFromNetworkingLayer(false)
128     , m_inCache(false)
129     , m_loading(false)
130     , m_switchingClientsToRevalidatedResource(false)
131     , m_type(type)
132     , m_status(Pending)
133 #ifndef NDEBUG
134     , m_deleted(false)
135     , m_lruIndex(0)
136 #endif
137     , m_nextInAllResourcesList(0)
138     , m_prevInAllResourcesList(0)
139     , m_nextInLiveResourcesList(0)
140     , m_prevInLiveResourcesList(0)
141     , m_owningCachedResourceLoader(0)
142     , m_resourceToRevalidate(0)
143     , m_proxyResource(0)
144 {
145     ASSERT(m_type == unsigned(type)); // m_type is a bitfield, so this tests careless updates of the enum.
146     ASSERT(sessionID.isValid());
147 #ifndef NDEBUG
148     cachedResourceLeakCounter.increment();
149 #endif
150
151     if (!m_resourceRequest.url().hasFragmentIdentifier())
152         return;
153     URL urlForCache = MemoryCache::removeFragmentIdentifierIfNeeded(m_resourceRequest.url());
154     if (urlForCache.hasFragmentIdentifier())
155         return;
156     m_fragmentIdentifierForRequest = m_resourceRequest.url().fragmentIdentifier();
157     m_resourceRequest.setURL(urlForCache);
158 }
159
160 CachedResource::~CachedResource()
161 {
162     ASSERT(!m_resourceToRevalidate); // Should be true because canDelete() checks this.
163     ASSERT(canDelete());
164     ASSERT(!inCache());
165     ASSERT(!m_deleted);
166     ASSERT(url().isNull() || memoryCache().resourceForRequest(resourceRequest(), sessionID()) != this);
167
168 #ifndef NDEBUG
169     m_deleted = true;
170     cachedResourceLeakCounter.decrement();
171 #endif
172
173     if (m_owningCachedResourceLoader)
174         m_owningCachedResourceLoader->removeCachedResource(this);
175 }
176
177 void CachedResource::failBeforeStarting()
178 {
179     // FIXME: What if resources in other frames were waiting for this revalidation?
180     LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
181     if (m_resourceToRevalidate) 
182         memoryCache().revalidationFailed(this); 
183     error(CachedResource::LoadError);
184 }
185
186 void CachedResource::addAdditionalRequestHeaders(CachedResourceLoader* cachedResourceLoader)
187 {
188     // Note: We skip the Content-Security-Policy check here because we check
189     // the Content-Security-Policy at the CachedResourceLoader layer so we can
190     // handle different resource types differently.
191
192     FrameLoader& frameLoader = cachedResourceLoader->frame()->loader();
193     String outgoingReferrer;
194     String outgoingOrigin;
195     if (m_resourceRequest.httpReferrer().isNull()) {
196         outgoingReferrer = frameLoader.outgoingReferrer();
197         outgoingOrigin = frameLoader.outgoingOrigin();
198     } else {
199         outgoingReferrer = m_resourceRequest.httpReferrer();
200         outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
201     }
202
203     outgoingReferrer = SecurityPolicy::generateReferrerHeader(cachedResourceLoader->document()->referrerPolicy(), m_resourceRequest.url(), outgoingReferrer);
204     if (outgoingReferrer.isEmpty())
205         m_resourceRequest.clearHTTPReferrer();
206     else
207         m_resourceRequest.setHTTPReferrer(outgoingReferrer);
208     FrameLoader::addHTTPOriginIfNeeded(m_resourceRequest, outgoingOrigin);
209
210     frameLoader.addExtraFieldsToSubresourceRequest(m_resourceRequest);
211 }
212
213 void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const ResourceLoaderOptions& options)
214 {
215     if (!cachedResourceLoader->frame()) {
216         failBeforeStarting();
217         return;
218     }
219
220     FrameLoader& frameLoader = cachedResourceLoader->frame()->loader();
221     if (options.securityCheck() == DoSecurityCheck && (frameLoader.state() == FrameStateProvisional || !frameLoader.activeDocumentLoader() || frameLoader.activeDocumentLoader()->isStopping())) {
222         failBeforeStarting();
223         return;
224     }
225
226     m_options = options;
227     m_loading = true;
228
229 #if USE(QUICK_LOOK)
230     if (!m_resourceRequest.isNull() && m_resourceRequest.url().protocolIs(QLPreviewProtocol())) {
231         // When QuickLook is invoked to convert a document, it returns a unique URL in the
232         // NSURLReponse for the main document. To make safeQLURLForDocumentURLAndResourceURL()
233         // work, we need to use the QL URL not the original URL.
234         const URL& documentURL = cachedResourceLoader->frame() ? cachedResourceLoader->frame()->loader().documentLoader()->response().url() : cachedResourceLoader->document()->url();
235         m_resourceRequest.setURL(safeQLURLForDocumentURLAndResourceURL(documentURL, url()));
236     }
237 #endif
238
239     if (!accept().isEmpty())
240         m_resourceRequest.setHTTPAccept(accept());
241
242     if (isCacheValidator()) {
243         CachedResource* resourceToRevalidate = m_resourceToRevalidate;
244         ASSERT(resourceToRevalidate->canUseCacheValidator());
245         ASSERT(resourceToRevalidate->isLoaded());
246         const String& lastModified = resourceToRevalidate->response().httpHeaderField(HTTPHeaderName::LastModified);
247         const String& eTag = resourceToRevalidate->response().httpHeaderField(HTTPHeaderName::ETag);
248         if (!lastModified.isEmpty() || !eTag.isEmpty()) {
249             ASSERT(cachedResourceLoader->cachePolicy(type()) != CachePolicyReload);
250             if (cachedResourceLoader->cachePolicy(type()) == CachePolicyRevalidate)
251                 m_resourceRequest.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
252             if (!lastModified.isEmpty())
253                 m_resourceRequest.setHTTPHeaderField(HTTPHeaderName::IfModifiedSince, lastModified);
254             if (!eTag.isEmpty())
255                 m_resourceRequest.setHTTPHeaderField(HTTPHeaderName::IfNoneMatch, eTag);
256         }
257     }
258
259 #if ENABLE(LINK_PREFETCH)
260     if (type() == CachedResource::LinkPrefetch || type() == CachedResource::LinkSubresource)
261         m_resourceRequest.setHTTPHeaderField(HTTPHeaderName::Purpose, "prefetch");
262 #endif
263     m_resourceRequest.setPriority(loadPriority());
264
265     if (type() != MainResource)
266         addAdditionalRequestHeaders(cachedResourceLoader);
267
268     // FIXME: It's unfortunate that the cache layer and below get to know anything about fragment identifiers.
269     // We should look into removing the expectation of that knowledge from the platform network stacks.
270     ResourceRequest request(m_resourceRequest);
271     if (!m_fragmentIdentifierForRequest.isNull()) {
272         URL url = request.url();
273         url.setFragmentIdentifier(m_fragmentIdentifierForRequest);
274         request.setURL(url);
275         m_fragmentIdentifierForRequest = String();
276     }
277
278     m_loader = platformStrategies()->loaderStrategy()->resourceLoadScheduler()->scheduleSubresourceLoad(cachedResourceLoader->frame(), this, request, options);
279     if (!m_loader) {
280         failBeforeStarting();
281         return;
282     }
283
284     m_status = Pending;
285 }
286
287 void CachedResource::checkNotify()
288 {
289     if (isLoading() || stillNeedsLoad())
290         return;
291
292     CachedResourceClientWalker<CachedResourceClient> walker(m_clients);
293     while (CachedResourceClient* client = walker.next())
294         client->notifyFinished(this);
295 }
296
297 void CachedResource::addDataBuffer(SharedBuffer&)
298 {
299     ASSERT(dataBufferingPolicy() == BufferData);
300 }
301
302 void CachedResource::addData(const char*, unsigned)
303 {
304     ASSERT(dataBufferingPolicy() == DoNotBufferData);
305 }
306
307 void CachedResource::finishLoading(SharedBuffer*)
308 {
309     setLoading(false);
310     checkNotify();
311 }
312
313 void CachedResource::error(CachedResource::Status status)
314 {
315     setStatus(status);
316     ASSERT(errorOccurred());
317     m_data.clear();
318
319     setLoading(false);
320     checkNotify();
321 }
322     
323 void CachedResource::cancelLoad()
324 {
325     if (!isLoading() && !stillNeedsLoad())
326         return;
327
328     setStatus(LoadError);
329     setLoading(false);
330     checkNotify();
331 }
332
333 void CachedResource::finish()
334 {
335     if (!errorOccurred())
336         m_status = Cached;
337 }
338
339 bool CachedResource::passesAccessControlCheck(SecurityOrigin* securityOrigin)
340 {
341     String errorDescription;
342     return WebCore::passesAccessControlCheck(m_response, resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription);
343 }
344
345 bool CachedResource::isExpired() const
346 {
347     if (m_response.isNull())
348         return false;
349
350     return computeCurrentAge(m_response, m_responseTimestamp) > freshnessLifetime(m_response);
351 }
352
353 double CachedResource::freshnessLifetime(const ResourceResponse& response) const
354 {
355     if (!response.url().protocolIsInHTTPFamily()) {
356         // Don't cache non-HTTP main resources since we can't check for freshness.
357         // FIXME: We should not cache subresources either, but when we tried this
358         // it caused performance and flakiness issues in our test infrastructure.
359         if (m_type == MainResource && !SchemeRegistry::shouldCacheResponsesFromURLSchemeIndefinitely(response.url().protocol()))
360             return 0;
361
362         return std::numeric_limits<double>::max();
363     }
364
365     return computeFreshnessLifetimeForHTTPFamily(response, m_responseTimestamp);
366 }
367
368 void CachedResource::willSendRequest(ResourceRequest&, const ResourceResponse& response)
369 {
370     m_requestedFromNetworkingLayer = true;
371     if (response.isNull())
372         return;
373     updateRedirectChainStatus(m_redirectChainCacheStatus, response);
374 }
375
376 void CachedResource::responseReceived(const ResourceResponse& response)
377 {
378     setResponse(response);
379     m_responseTimestamp = currentTime();
380     String encoding = response.textEncodingName();
381     if (!encoding.isNull())
382         setEncoding(encoding);
383 }
384
385 void CachedResource::clearLoader()
386 {
387     ASSERT(m_loader);
388     m_loader = 0;
389 }
390
391 void CachedResource::addClient(CachedResourceClient* client)
392 {
393     if (addClientToSet(client))
394         didAddClient(client);
395 }
396
397 void CachedResource::didAddClient(CachedResourceClient* client)
398 {
399     if (m_decodedDataDeletionTimer.isActive())
400         m_decodedDataDeletionTimer.stop();
401
402     if (m_clientsAwaitingCallback.remove(client))
403         m_clients.add(client);
404     if (!isLoading() && !stillNeedsLoad())
405         client->notifyFinished(this);
406 }
407
408 bool CachedResource::addClientToSet(CachedResourceClient* client)
409 {
410     if (m_preloadResult == PreloadNotReferenced) {
411         if (isLoaded())
412             m_preloadResult = PreloadReferencedWhileComplete;
413         else if (m_requestedFromNetworkingLayer)
414             m_preloadResult = PreloadReferencedWhileLoading;
415         else
416             m_preloadResult = PreloadReferenced;
417     }
418     if (!hasClients() && inCache())
419         memoryCache().addToLiveResourcesSize(this);
420
421     if ((m_type == RawResource || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
422         // Certain resources (especially XHRs and main resources) do crazy things if an asynchronous load returns
423         // synchronously (e.g., scripts may not have set all the state they need to handle the load).
424         // Therefore, rather than immediately sending callbacks on a cache hit like other CachedResources,
425         // we schedule the callbacks and ensure we never finish synchronously.
426         ASSERT(!m_clientsAwaitingCallback.contains(client));
427         m_clientsAwaitingCallback.add(client, std::make_unique<Callback>(*this, *client));
428         return false;
429     }
430
431     m_clients.add(client);
432     return true;
433 }
434
435 void CachedResource::removeClient(CachedResourceClient* client)
436 {
437     auto callback = m_clientsAwaitingCallback.take(client);
438     if (callback) {
439         ASSERT(!m_clients.contains(client));
440         callback->cancel();
441         callback = nullptr;
442     } else {
443         ASSERT(m_clients.contains(client));
444         m_clients.remove(client);
445         didRemoveClient(client);
446     }
447
448     bool deleted = deleteIfPossible();
449     if (!deleted && !hasClients()) {
450         if (inCache()) {
451             memoryCache().removeFromLiveResourcesSize(this);
452             memoryCache().removeFromLiveDecodedResourcesList(this);
453         }
454         if (!m_switchingClientsToRevalidatedResource)
455             allClientsRemoved();
456         destroyDecodedDataIfNeeded();
457         if (response().cacheControlContainsNoStore() && url().protocolIs("https")) {
458             // RFC2616 14.9.2:
459             // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
460             // "... History buffers MAY store such responses as part of their normal operation."
461             // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
462             memoryCache().remove(this);
463         }
464         memoryCache().prune();
465     }
466     // This object may be dead here.
467 }
468
469 void CachedResource::destroyDecodedDataIfNeeded()
470 {
471     if (!m_decodedSize)
472         return;
473     if (!memoryCache().deadDecodedDataDeletionInterval().count())
474         return;
475     m_decodedDataDeletionTimer.restart();
476 }
477
478 void CachedResource::decodedDataDeletionTimerFired()
479 {
480     destroyDecodedData();
481 }
482
483 bool CachedResource::deleteIfPossible()
484 {
485     if (canDelete() && !inCache()) {
486         InspectorInstrumentation::willDestroyCachedResource(*this);
487         delete this;
488         return true;
489     }
490     return false;
491 }
492
493 void CachedResource::setDecodedSize(unsigned size)
494 {
495     if (size == m_decodedSize)
496         return;
497
498     int delta = size - m_decodedSize;
499
500     // The object must be moved to a different queue, since its size has been changed.
501     // Remove before updating m_decodedSize, so we find the resource in the correct LRU list.
502     if (inCache())
503         memoryCache().removeFromLRUList(this);
504     
505     m_decodedSize = size;
506    
507     if (inCache()) { 
508         // Now insert into the new LRU list.
509         memoryCache().insertInLRUList(this);
510         
511         // Insert into or remove from the live decoded list if necessary.
512         // When inserting into the LiveDecodedResourcesList it is possible
513         // that the m_lastDecodedAccessTime is still zero or smaller than
514         // the m_lastDecodedAccessTime of the current list head. This is a
515         // violation of the invariant that the list is to be kept sorted
516         // by access time. The weakening of the invariant does not pose
517         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
518         if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
519             memoryCache().insertInLiveDecodedResourcesList(this);
520         else if (!m_decodedSize && m_inLiveDecodedResourcesList)
521             memoryCache().removeFromLiveDecodedResourcesList(this);
522
523         // Update the cache's size totals.
524         memoryCache().adjustSize(hasClients(), delta);
525     }
526 }
527
528 void CachedResource::setEncodedSize(unsigned size)
529 {
530     if (size == m_encodedSize)
531         return;
532
533     int delta = size - m_encodedSize;
534
535     // The object must be moved to a different queue, since its size has been changed.
536     // Remove before updating m_encodedSize, so we find the resource in the correct LRU list.
537     if (inCache())
538         memoryCache().removeFromLRUList(this);
539
540     m_encodedSize = size;
541
542     if (inCache()) { 
543         memoryCache().insertInLRUList(this);
544         memoryCache().adjustSize(hasClients(), delta);
545     }
546 }
547
548 void CachedResource::didAccessDecodedData(double timeStamp)
549 {
550     m_lastDecodedAccessTime = timeStamp;
551     
552     if (inCache()) {
553         if (m_inLiveDecodedResourcesList) {
554             memoryCache().removeFromLiveDecodedResourcesList(this);
555             memoryCache().insertInLiveDecodedResourcesList(this);
556         }
557         memoryCache().prune();
558     }
559 }
560     
561 void CachedResource::setResourceToRevalidate(CachedResource* resource) 
562
563     ASSERT(resource);
564     ASSERT(!m_resourceToRevalidate);
565     ASSERT(resource != this);
566     ASSERT(m_handlesToRevalidate.isEmpty());
567     ASSERT(resource->type() == type());
568
569     LOG(ResourceLoading, "CachedResource %p setResourceToRevalidate %p", this, resource);
570
571     // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
572     // https://bugs.webkit.org/show_bug.cgi?id=28604.
573     // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in CachedResource::clearResourceToRevalidate.
574     ASSERT(!resource->m_proxyResource);
575
576     resource->m_proxyResource = this;
577     m_resourceToRevalidate = resource;
578 }
579
580 void CachedResource::clearResourceToRevalidate() 
581
582     ASSERT(m_resourceToRevalidate);
583     if (m_switchingClientsToRevalidatedResource)
584         return;
585
586     // 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.
587     if (m_resourceToRevalidate->m_proxyResource == this) {
588         m_resourceToRevalidate->m_proxyResource = 0;
589         m_resourceToRevalidate->deleteIfPossible();
590     }
591     m_handlesToRevalidate.clear();
592     m_resourceToRevalidate = 0;
593     deleteIfPossible();
594 }
595     
596 void CachedResource::switchClientsToRevalidatedResource()
597 {
598     ASSERT(m_resourceToRevalidate);
599     ASSERT(m_resourceToRevalidate->inCache());
600     ASSERT(!inCache());
601
602     LOG(ResourceLoading, "CachedResource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
603
604     m_switchingClientsToRevalidatedResource = true;
605     HashSet<CachedResourceHandleBase*>::iterator end = m_handlesToRevalidate.end();
606     for (HashSet<CachedResourceHandleBase*>::iterator it = m_handlesToRevalidate.begin(); it != end; ++it) {
607         CachedResourceHandleBase* handle = *it;
608         handle->m_resource = m_resourceToRevalidate;
609         m_resourceToRevalidate->registerHandle(handle);
610         --m_handleCount;
611     }
612     ASSERT(!m_handleCount);
613     m_handlesToRevalidate.clear();
614
615     Vector<CachedResourceClient*> clientsToMove;
616     HashCountedSet<CachedResourceClient*>::iterator end2 = m_clients.end();
617     for (HashCountedSet<CachedResourceClient*>::iterator it = m_clients.begin(); it != end2; ++it) {
618         CachedResourceClient* client = it->key;
619         unsigned count = it->value;
620         while (count) {
621             clientsToMove.append(client);
622             --count;
623         }
624     }
625
626     unsigned moveCount = clientsToMove.size();
627     for (unsigned n = 0; n < moveCount; ++n)
628         removeClient(clientsToMove[n]);
629     ASSERT(m_clients.isEmpty());
630
631     for (unsigned n = 0; n < moveCount; ++n)
632         m_resourceToRevalidate->addClientToSet(clientsToMove[n]);
633     for (unsigned n = 0; n < moveCount; ++n) {
634         // Calling didAddClient may do anything, including trying to cancel revalidation.
635         // Assert that it didn't succeed.
636         ASSERT(m_resourceToRevalidate);
637         // Calling didAddClient for a client may end up removing another client. In that case it won't be in the set anymore.
638         if (m_resourceToRevalidate->m_clients.contains(clientsToMove[n]))
639             m_resourceToRevalidate->didAddClient(clientsToMove[n]);
640     }
641     m_switchingClientsToRevalidatedResource = false;
642 }
643
644 void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
645 {
646     m_responseTimestamp = currentTime();
647
648     updateResponseHeadersAfterRevalidation(m_response, validatingResponse);
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(const CachedResourceLoader& cachedResourceLoader, CachePolicy cachePolicy) const
681 {    
682     ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);
683
684     if (cachePolicy == CachePolicyRevalidate) {
685         FEATURE_COUNTER_INCREMENT_KEY(cachedResourceLoader.frame()->page(), FeatureCounterCachedResourceRevalidationReasonReloadKey);
686         return true;
687     }
688
689     if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
690         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
691         if (m_response.cacheControlContainsNoStore())
692             FEATURE_COUNTER_INCREMENT_KEY(cachedResourceLoader.frame()->page(), FeatureCounterCachedResourceRevalidationReasonNoStoreKey);
693         else
694             FEATURE_COUNTER_INCREMENT_KEY(cachedResourceLoader.frame()->page(), FeatureCounterCachedResourceRevalidationReasonNoCacheKey);
695
696         return true;
697     }
698
699     if (cachePolicy == CachePolicyCache) {
700         if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
701             LOG(ResourceLoading, "CachedResource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
702             FEATURE_COUNTER_INCREMENT_KEY(cachedResourceLoader.frame()->page(), FeatureCounterCachedResourceRevalidationReasonMustRevalidateIsExpiredKey);
703             return true;
704         }
705         return false;
706     }
707
708     // CachePolicyVerify
709     if (isExpired()) {
710         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of isExpired()\n", this);
711         FEATURE_COUNTER_INCREMENT_KEY(cachedResourceLoader.frame()->page(), FeatureCounterCachedResourceRevalidationReasonIsExpiredKey);
712         return true;
713     }
714
715     return false;
716 }
717
718 bool CachedResource::redirectChainAllowsReuse() const
719 {
720     return WebCore::redirectChainAllowsReuse(m_redirectChainCacheStatus);
721 }
722
723 unsigned CachedResource::overheadSize() const
724 {
725     static const int kAverageClientsHashMapSize = 384;
726     return sizeof(CachedResource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
727 }
728
729 void CachedResource::setLoadPriority(ResourceLoadPriority loadPriority)
730 {
731     if (loadPriority == ResourceLoadPriorityUnresolved)
732         loadPriority = defaultPriorityForResourceType(type());
733     m_loadPriority = loadPriority;
734 }
735
736 inline CachedResource::Callback::Callback(CachedResource& resource, CachedResourceClient& client)
737     : m_resource(resource)
738     , m_client(client)
739     , m_timer(*this, &Callback::timerFired)
740 {
741     m_timer.startOneShot(0);
742 }
743
744 inline void CachedResource::Callback::cancel()
745 {
746     if (m_timer.isActive())
747         m_timer.stop();
748 }
749
750 void CachedResource::Callback::timerFired()
751 {
752     m_resource.didAddClient(&m_client);
753 }
754
755 #if USE(FOUNDATION)
756
757 void CachedResource::tryReplaceEncodedData(SharedBuffer& newBuffer)
758 {
759     if (!m_data)
760         return;
761     
762     if (!mayTryReplaceEncodedData())
763         return;
764
765     // We have to do the memcmp because we can't tell if the replacement file backed data is for the
766     // same resource or if we made a second request with the same URL which gave us a different
767     // resource. We have seen this happen for cached POST resources.
768     if (m_data->size() != newBuffer.size() || memcmp(m_data->data(), newBuffer.data(), m_data->size()))
769         return;
770
771     m_data->tryReplaceContentsWithPlatformBuffer(newBuffer);
772 }
773
774 #endif
775
776 }