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