Drop RefPtr::clear() method
[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::decodedDataDeletionTimerFired, 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_loader = nullptr;
409     deleteIfPossible();
410 }
411
412 void CachedResource::addClient(CachedResourceClient* client)
413 {
414     if (addClientToSet(client))
415         didAddClient(client);
416 }
417
418 void CachedResource::didAddClient(CachedResourceClient* client)
419 {
420     if (m_decodedDataDeletionTimer.isActive())
421         m_decodedDataDeletionTimer.stop();
422
423     if (m_clientsAwaitingCallback.remove(client))
424         m_clients.add(client);
425     if (!isLoading() && !stillNeedsLoad())
426         client->notifyFinished(this);
427 }
428
429 bool CachedResource::addClientToSet(CachedResourceClient* client)
430 {
431     if (m_preloadResult == PreloadNotReferenced) {
432         if (isLoaded())
433             m_preloadResult = PreloadReferencedWhileComplete;
434         else if (m_requestedFromNetworkingLayer)
435             m_preloadResult = PreloadReferencedWhileLoading;
436         else
437             m_preloadResult = PreloadReferenced;
438     }
439     if (!hasClients() && inCache())
440         MemoryCache::singleton().addToLiveResourcesSize(*this);
441
442     if ((m_type == RawResource || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
443         // Certain resources (especially XHRs and main resources) do crazy things if an asynchronous load returns
444         // synchronously (e.g., scripts may not have set all the state they need to handle the load).
445         // Therefore, rather than immediately sending callbacks on a cache hit like other CachedResources,
446         // we schedule the callbacks and ensure we never finish synchronously.
447         ASSERT(!m_clientsAwaitingCallback.contains(client));
448         m_clientsAwaitingCallback.add(client, std::make_unique<Callback>(*this, *client));
449         return false;
450     }
451
452     m_clients.add(client);
453     return true;
454 }
455
456 void CachedResource::removeClient(CachedResourceClient* client)
457 {
458     auto callback = m_clientsAwaitingCallback.take(client);
459     if (callback) {
460         ASSERT(!m_clients.contains(client));
461         callback->cancel();
462         callback = nullptr;
463     } else {
464         ASSERT(m_clients.contains(client));
465         m_clients.remove(client);
466         didRemoveClient(client);
467     }
468
469     bool deleted = deleteIfPossible();
470     if (!deleted && !hasClients()) {
471         auto& memoryCache = MemoryCache::singleton();
472         if (inCache()) {
473             memoryCache.removeFromLiveResourcesSize(*this);
474             memoryCache.removeFromLiveDecodedResourcesList(*this);
475         }
476         if (!m_switchingClientsToRevalidatedResource)
477             allClientsRemoved();
478         destroyDecodedDataIfNeeded();
479         if (response().cacheControlContainsNoStore() && url().protocolIs("https")) {
480             // RFC2616 14.9.2:
481             // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
482             // "... History buffers MAY store such responses as part of their normal operation."
483             // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
484             memoryCache.remove(*this);
485         }
486         memoryCache.pruneSoon();
487     }
488     // This object may be dead here.
489 }
490
491 void CachedResource::destroyDecodedDataIfNeeded()
492 {
493     if (!m_decodedSize)
494         return;
495     if (!MemoryCache::singleton().deadDecodedDataDeletionInterval().count())
496         return;
497     m_decodedDataDeletionTimer.restart();
498 }
499
500 void CachedResource::decodedDataDeletionTimerFired()
501 {
502     destroyDecodedData();
503 }
504
505 bool CachedResource::deleteIfPossible()
506 {
507     if (canDelete() && !inCache()) {
508         InspectorInstrumentation::willDestroyCachedResource(*this);
509         delete this;
510         return true;
511     }
512     return false;
513 }
514
515 void CachedResource::setDecodedSize(unsigned size)
516 {
517     if (size == m_decodedSize)
518         return;
519
520     int delta = size - m_decodedSize;
521
522     // The object must be moved to a different queue, since its size has been changed.
523     // Remove before updating m_decodedSize, so we find the resource in the correct LRU list.
524     if (inCache())
525         MemoryCache::singleton().removeFromLRUList(*this);
526     
527     m_decodedSize = size;
528    
529     if (inCache()) {
530         auto& memoryCache = MemoryCache::singleton();
531         // Now insert into the new LRU list.
532         memoryCache.insertInLRUList(*this);
533         
534         // Insert into or remove from the live decoded list if necessary.
535         // When inserting into the LiveDecodedResourcesList it is possible
536         // that the m_lastDecodedAccessTime is still zero or smaller than
537         // the m_lastDecodedAccessTime of the current list head. This is a
538         // violation of the invariant that the list is to be kept sorted
539         // by access time. The weakening of the invariant does not pose
540         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
541         bool inLiveDecodedResourcesList = memoryCache.inLiveDecodedResourcesList(*this);
542         if (m_decodedSize && !inLiveDecodedResourcesList && hasClients())
543             memoryCache.insertInLiveDecodedResourcesList(*this);
544         else if (!m_decodedSize && inLiveDecodedResourcesList)
545             memoryCache.removeFromLiveDecodedResourcesList(*this);
546
547         // Update the cache's size totals.
548         memoryCache.adjustSize(hasClients(), delta);
549     }
550 }
551
552 void CachedResource::setEncodedSize(unsigned size)
553 {
554     if (size == m_encodedSize)
555         return;
556
557     int delta = size - m_encodedSize;
558
559     // The object must be moved to a different queue, since its size has been changed.
560     // Remove before updating m_encodedSize, so we find the resource in the correct LRU list.
561     if (inCache())
562         MemoryCache::singleton().removeFromLRUList(*this);
563
564     m_encodedSize = size;
565
566     if (inCache()) {
567         auto& memoryCache = MemoryCache::singleton();
568         memoryCache.insertInLRUList(*this);
569         memoryCache.adjustSize(hasClients(), delta);
570     }
571 }
572
573 void CachedResource::didAccessDecodedData(double timeStamp)
574 {
575     m_lastDecodedAccessTime = timeStamp;
576     
577     if (inCache()) {
578         auto& memoryCache = MemoryCache::singleton();
579         if (memoryCache.inLiveDecodedResourcesList(*this)) {
580             memoryCache.removeFromLiveDecodedResourcesList(*this);
581             memoryCache.insertInLiveDecodedResourcesList(*this);
582         }
583         memoryCache.pruneSoon();
584     }
585 }
586     
587 void CachedResource::setResourceToRevalidate(CachedResource* resource) 
588
589     ASSERT(resource);
590     ASSERT(!m_resourceToRevalidate);
591     ASSERT(resource != this);
592     ASSERT(m_handlesToRevalidate.isEmpty());
593     ASSERT(resource->type() == type());
594
595     LOG(ResourceLoading, "CachedResource %p setResourceToRevalidate %p", this, resource);
596
597     // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
598     // https://bugs.webkit.org/show_bug.cgi?id=28604.
599     // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in CachedResource::clearResourceToRevalidate.
600     ASSERT(!resource->m_proxyResource);
601
602     resource->m_proxyResource = this;
603     m_resourceToRevalidate = resource;
604 }
605
606 void CachedResource::clearResourceToRevalidate() 
607
608     ASSERT(m_resourceToRevalidate);
609     if (m_switchingClientsToRevalidatedResource)
610         return;
611
612     // 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.
613     if (m_resourceToRevalidate->m_proxyResource == this) {
614         m_resourceToRevalidate->m_proxyResource = 0;
615         m_resourceToRevalidate->deleteIfPossible();
616     }
617     m_handlesToRevalidate.clear();
618     m_resourceToRevalidate = 0;
619     deleteIfPossible();
620 }
621     
622 void CachedResource::switchClientsToRevalidatedResource()
623 {
624     ASSERT(m_resourceToRevalidate);
625     ASSERT(m_resourceToRevalidate->inCache());
626     ASSERT(!inCache());
627
628     LOG(ResourceLoading, "CachedResource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
629
630     m_switchingClientsToRevalidatedResource = true;
631     HashSet<CachedResourceHandleBase*>::iterator end = m_handlesToRevalidate.end();
632     for (HashSet<CachedResourceHandleBase*>::iterator it = m_handlesToRevalidate.begin(); it != end; ++it) {
633         CachedResourceHandleBase* handle = *it;
634         handle->m_resource = m_resourceToRevalidate;
635         m_resourceToRevalidate->registerHandle(handle);
636         --m_handleCount;
637     }
638     ASSERT(!m_handleCount);
639     m_handlesToRevalidate.clear();
640
641     Vector<CachedResourceClient*> clientsToMove;
642     HashCountedSet<CachedResourceClient*>::iterator end2 = m_clients.end();
643     for (HashCountedSet<CachedResourceClient*>::iterator it = m_clients.begin(); it != end2; ++it) {
644         CachedResourceClient* client = it->key;
645         unsigned count = it->value;
646         while (count) {
647             clientsToMove.append(client);
648             --count;
649         }
650     }
651
652     unsigned moveCount = clientsToMove.size();
653     for (unsigned n = 0; n < moveCount; ++n)
654         removeClient(clientsToMove[n]);
655     ASSERT(m_clients.isEmpty());
656
657     for (unsigned n = 0; n < moveCount; ++n)
658         m_resourceToRevalidate->addClientToSet(clientsToMove[n]);
659     for (unsigned n = 0; n < moveCount; ++n) {
660         // Calling didAddClient may do anything, including trying to cancel revalidation.
661         // Assert that it didn't succeed.
662         ASSERT(m_resourceToRevalidate);
663         // Calling didAddClient for a client may end up removing another client. In that case it won't be in the set anymore.
664         if (m_resourceToRevalidate->m_clients.contains(clientsToMove[n]))
665             m_resourceToRevalidate->didAddClient(clientsToMove[n]);
666     }
667     m_switchingClientsToRevalidatedResource = false;
668 }
669
670 void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
671 {
672     m_responseTimestamp = std::chrono::system_clock::now();
673
674     updateResponseHeadersAfterRevalidation(m_response, validatingResponse);
675 }
676
677 void CachedResource::registerHandle(CachedResourceHandleBase* h)
678 {
679     ++m_handleCount;
680     if (m_resourceToRevalidate)
681         m_handlesToRevalidate.add(h);
682 }
683
684 void CachedResource::unregisterHandle(CachedResourceHandleBase* h)
685 {
686     ASSERT(m_handleCount > 0);
687     --m_handleCount;
688
689     if (m_resourceToRevalidate)
690          m_handlesToRevalidate.remove(h);
691
692     if (!m_handleCount)
693         deleteIfPossible();
694 }
695
696 bool CachedResource::canUseCacheValidator() const
697 {
698     if (m_loading || errorOccurred())
699         return false;
700
701     if (m_response.cacheControlContainsNoStore())
702         return false;
703     return m_response.hasCacheValidatorFields();
704 }
705
706 CachedResource::RevalidationDecision CachedResource::makeRevalidationDecision(CachePolicy cachePolicy) const
707 {    
708     switch (cachePolicy) {
709     case CachePolicyHistoryBuffer:
710         return RevalidationDecision::No;
711
712     case CachePolicyReload:
713     case CachePolicyRevalidate:
714         return RevalidationDecision::YesDueToCachePolicy;
715
716     case CachePolicyVerify:
717         if (m_response.cacheControlContainsNoCache())
718             return RevalidationDecision::YesDueToNoCache;
719         // FIXME: Cache-Control:no-store should prevent storing, not reuse.
720         if (m_response.cacheControlContainsNoStore())
721             return RevalidationDecision::YesDueToNoStore;
722
723         if (isExpired())
724             return RevalidationDecision::YesDueToExpired;
725
726         return RevalidationDecision::No;
727     };
728     ASSERT_NOT_REACHED();
729     return RevalidationDecision::No;
730 }
731
732 bool CachedResource::redirectChainAllowsReuse(ReuseExpiredRedirectionOrNot reuseExpiredRedirection) const
733 {
734     return WebCore::redirectChainAllowsReuse(m_redirectChainCacheStatus, reuseExpiredRedirection);
735 }
736
737 unsigned CachedResource::overheadSize() const
738 {
739     static const int kAverageClientsHashMapSize = 384;
740     return sizeof(CachedResource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
741 }
742
743 bool CachedResource::areAllClientsXMLHttpRequests() const
744 {
745     if (type() != RawResource)
746         return false;
747
748     for (auto& client : m_clients) {
749         if (!client.key->isXMLHttpRequest())
750             return false;
751     }
752     return true;
753 }
754
755 void CachedResource::setLoadPriority(const Optional<ResourceLoadPriority>& loadPriority)
756 {
757     if (loadPriority)
758         m_loadPriority = loadPriority.value();
759     else
760         m_loadPriority = defaultPriorityForResourceType(type());
761 }
762
763 inline CachedResource::Callback::Callback(CachedResource& resource, CachedResourceClient& client)
764     : m_resource(resource)
765     , m_client(client)
766     , m_timer(*this, &Callback::timerFired)
767 {
768     m_timer.startOneShot(0);
769 }
770
771 inline void CachedResource::Callback::cancel()
772 {
773     if (m_timer.isActive())
774         m_timer.stop();
775 }
776
777 void CachedResource::Callback::timerFired()
778 {
779     m_resource.didAddClient(&m_client);
780 }
781
782 #if USE(FOUNDATION) || USE(SOUP)
783
784 void CachedResource::tryReplaceEncodedData(SharedBuffer& newBuffer)
785 {
786     if (!m_data)
787         return;
788     
789     if (!mayTryReplaceEncodedData())
790         return;
791
792     // We have to do the memcmp because we can't tell if the replacement file backed data is for the
793     // same resource or if we made a second request with the same URL which gave us a different
794     // resource. We have seen this happen for cached POST resources.
795     if (m_data->size() != newBuffer.size() || memcmp(m_data->data(), newBuffer.data(), m_data->size()))
796         return;
797
798     m_data->tryReplaceContentsWithPlatformBuffer(newBuffer);
799 }
800
801 #endif
802
803 }