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