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