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