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