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