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