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