2 Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3 Copyright (C) 2001 Dirk Mueller <mueller@kde.org>
4 Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
5 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version.
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public License
18 along with this library; see the file COPYING.LIB. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.
25 #include "CachePolicy.h"
26 #include "CacheValidation.h"
27 #include "FrameLoaderTypes.h"
28 #include "ResourceError.h"
29 #include "ResourceLoadPriority.h"
30 #include "ResourceLoaderOptions.h"
31 #include "ResourceRequest.h"
32 #include "ResourceResponse.h"
34 #include <pal/SessionID.h>
36 #include <wtf/HashCountedSet.h>
37 #include <wtf/HashSet.h>
38 #include <wtf/TypeCasts.h>
39 #include <wtf/Vector.h>
40 #include <wtf/text/WTFString.h>
44 class CachedResourceClient;
45 class CachedResourceHandleBase;
46 class CachedResourceLoader;
47 class CachedResourceRequest;
52 class SubresourceLoader;
53 class TextResourceDecoder;
55 // A resource that is held in the cache. Classes who want to use this object should derive
56 // from CachedResourceClient, to get the function calls in case the requested data has arrived.
57 // This class also does the actual communication with the loader to obtain the resource from the network.
58 class CachedResource {
59 WTF_MAKE_NONCOPYABLE(CachedResource); WTF_MAKE_FAST_ALLOCATED;
60 friend class MemoryCache;
80 #if ENABLE(LINK_PREFETCH)
84 #if ENABLE(VIDEO_TRACK)
90 Unknown, // let cache decide what to do with it
91 Pending, // only partially loaded
92 Cached, // regular case
97 CachedResource(CachedResourceRequest&&, Type, PAL::SessionID);
98 virtual ~CachedResource();
100 virtual void load(CachedResourceLoader&);
102 virtual void setEncoding(const String&) { }
103 virtual String encoding() const { return String(); }
104 virtual const TextResourceDecoder* textResourceDecoder() const { return nullptr; }
105 virtual void addDataBuffer(SharedBuffer&);
106 virtual void addData(const char* data, unsigned length);
107 virtual void finishLoading(SharedBuffer*);
108 virtual void error(CachedResource::Status);
110 void setResourceError(const ResourceError& error) { m_error = error; }
111 const ResourceError& resourceError() const { return m_error; }
113 virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
115 const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
116 const URL& url() const { return m_resourceRequest.url();}
117 const String& cachePartition() const { return m_resourceRequest.cachePartition(); }
118 PAL::SessionID sessionID() const { return m_sessionID; }
119 Type type() const { return m_type; }
121 ResourceLoadPriority loadPriority() const { return m_loadPriority; }
122 void setLoadPriority(const std::optional<ResourceLoadPriority>&);
124 WEBCORE_EXPORT void addClient(CachedResourceClient&);
125 WEBCORE_EXPORT void removeClient(CachedResourceClient&);
126 bool hasClients() const { return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty(); }
127 bool hasClient(CachedResourceClient& client) { return m_clients.contains(&client) || m_clientsAwaitingCallback.contains(&client); }
128 bool deleteIfPossible();
131 PreloadNotReferenced,
133 PreloadReferencedWhileLoading,
134 PreloadReferencedWhileComplete
136 PreloadResult preloadResult() const { return static_cast<PreloadResult>(m_preloadResult); }
138 virtual void didAddClient(CachedResourceClient&);
139 virtual void didRemoveClient(CachedResourceClient&) { }
140 virtual void allClientsRemoved() { }
141 void destroyDecodedDataIfNeeded();
143 unsigned count() const { return m_clients.size(); }
145 Status status() const { return static_cast<Status>(m_status); }
146 void setStatus(Status status) { m_status = status; }
148 unsigned size() const { return encodedSize() + decodedSize() + overheadSize(); }
149 unsigned encodedSize() const { return m_encodedSize; }
150 unsigned decodedSize() const { return m_decodedSize; }
151 unsigned overheadSize() const;
153 bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
155 bool isLoading() const { return m_loading; }
156 void setLoading(bool b) { m_loading = b; }
157 virtual bool stillNeedsLoad() const { return false; }
159 SubresourceLoader* loader() { return m_loader.get(); }
161 bool areAllClientsXMLHttpRequests() const;
163 bool isImage() const { return type() == ImageResource; }
164 // FIXME: CachedRawResource could be a main resource, an audio/video resource, or a raw XHR/icon resource.
165 bool isMainOrMediaOrIconOrRawResource() const { return type() == MainResource || type() == MediaResource || type() == Icon || type() == RawResource || type() == Beacon; }
167 // Whether this request should impact request counting and delay window.onload.
168 bool ignoreForRequestCount() const
170 return m_ignoreForRequestCount
171 || type() == MainResource
172 #if ENABLE(LINK_PREFETCH)
173 || type() == LinkPrefetch
174 || type() == LinkSubresource
177 || type() == RawResource;
180 void setIgnoreForRequestCount(bool ignoreForRequestCount) { m_ignoreForRequestCount = ignoreForRequestCount; }
182 unsigned accessCount() const { return m_accessCount; }
183 void increaseAccessCount() { m_accessCount++; }
185 // Computes the status of an object after loading.
186 // Updates the expire date on the cache entry file
189 // Called by the cache if the object has been removed from the cache
190 // while still being referenced. This means the object should delete itself
191 // if the number of clients observing it ever drops to 0.
192 // The resource can be brought back to cache after successful revalidation.
193 void setInCache(bool inCache) { m_inCache = inCache; }
194 bool inCache() const { return m_inCache; }
198 SharedBuffer* resourceBuffer() const { return m_data.get(); }
200 virtual void redirectReceived(ResourceRequest&, const ResourceResponse&);
201 virtual void responseReceived(const ResourceResponse&);
202 virtual bool shouldCacheResponse(const ResourceResponse&) { return true; }
203 void setResponse(const ResourceResponse&);
204 const ResourceResponse& response() const { return m_response; }
206 void setCrossOrigin();
207 bool isCrossOrigin() const;
208 bool isCORSSameOrigin() const;
209 ResourceResponse::Tainting responseTainting() const { return m_responseTainting; }
211 void loadFrom(const CachedResource&);
213 SecurityOrigin* origin() const { return m_origin.get(); }
214 AtomicString initiatorName() const { return m_initiatorName; }
216 bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_resourceToRevalidate && !m_proxyResource; }
217 bool hasOneHandle() const { return m_handleCount == 1; }
219 bool isExpired() const;
222 bool wasCanceled() const { return m_error.isCancellation(); }
223 bool errorOccurred() const { return m_status == LoadError || m_status == DecodeError; }
224 bool loadFailedOrCanceled() const { return !m_error.isNull(); }
226 bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
227 DataBufferingPolicy dataBufferingPolicy() const { return m_options.dataBufferingPolicy; }
229 bool allowsCaching() const { return m_options.cachingPolicy == CachingPolicy::AllowCaching; }
230 const FetchOptions& options() const { return m_options; }
232 virtual void destroyDecodedData() { }
234 void setOwningCachedResourceLoader(CachedResourceLoader* cachedResourceLoader) { m_owningCachedResourceLoader = cachedResourceLoader; }
236 bool isPreloaded() const { return m_preloadCount; }
237 void increasePreloadCount() { ++m_preloadCount; }
238 void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; }
239 bool isLinkPreload() { return m_isLinkPreload; }
240 void setLinkPreload() { m_isLinkPreload = true; }
241 bool hasUnknownEncoding() { return m_hasUnknownEncoding; }
242 void setHasUnknownEncoding(bool hasUnknownEncoding) { m_hasUnknownEncoding = hasUnknownEncoding; }
244 void registerHandle(CachedResourceHandleBase*);
245 WEBCORE_EXPORT void unregisterHandle(CachedResourceHandleBase*);
247 bool canUseCacheValidator() const;
249 enum class RevalidationDecision { No, YesDueToCachePolicy, YesDueToNoStore, YesDueToNoCache, YesDueToExpired };
250 virtual RevalidationDecision makeRevalidationDecision(CachePolicy) const;
251 bool redirectChainAllowsReuse(ReuseExpiredRedirectionOrNot) const;
252 bool hasRedirections() const { return m_redirectChainCacheStatus.status != RedirectChainCacheStatus::Status::NoRedirection; }
254 bool varyHeaderValuesMatch(const ResourceRequest&);
256 bool isCacheValidator() const { return m_resourceToRevalidate; }
257 CachedResource* resourceToRevalidate() const { return m_resourceToRevalidate; }
259 // HTTP revalidation support methods for CachedResourceLoader.
260 void setResourceToRevalidate(CachedResource*);
261 virtual void switchClientsToRevalidatedResource();
262 void clearResourceToRevalidate();
263 void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
264 bool validationInProgress() const { return m_proxyResource; }
265 bool validationCompleting() const { return m_proxyResource && m_proxyResource->m_switchingClientsToRevalidatedResource; }
267 virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
269 virtual void didRetrieveDerivedDataFromCache(const String& /* type */, SharedBuffer&) { }
271 #if USE(FOUNDATION) || USE(SOUP)
272 WEBCORE_EXPORT void tryReplaceEncodedData(SharedBuffer&);
276 virtual char* getOrCreateReadBuffer(size_t /* requestedSize */, size_t& /* actualSize */) { return nullptr; }
279 unsigned long identifierForLoadWithoutResourceLoader() const { return m_identifierForLoadWithoutResourceLoader; }
280 static ResourceLoadPriority defaultPriorityForResourceType(Type);
283 // CachedResource constructor that may be used when the CachedResource can already be filled with response data.
284 CachedResource(const URL&, Type, PAL::SessionID);
286 void setEncodedSize(unsigned);
287 void setDecodedSize(unsigned);
288 void didAccessDecodedData(double timeStamp);
290 virtual void didReplaceSharedBufferContents() { }
292 virtual void setBodyDataFrom(const CachedResource&);
294 // FIXME: Make the rest of these data members private and use functions in derived classes instead.
295 HashCountedSet<CachedResourceClient*> m_clients;
296 ResourceRequest m_resourceRequest;
297 HTTPHeaderMap m_originalRequestHeaders;
298 RefPtr<SubresourceLoader> m_loader;
299 ResourceLoaderOptions m_options;
300 ResourceResponse m_response;
301 ResourceResponse::Tainting m_responseTainting { ResourceResponse::Tainting::Basic };
302 RefPtr<SharedBuffer> m_data;
303 DeferrableOneShotTimer m_decodedDataDeletionTimer;
308 bool addClientToSet(CachedResourceClient&);
310 void decodedDataDeletionTimerFired();
312 virtual void checkNotify();
313 virtual bool mayTryReplaceEncodedData() const { return false; }
315 std::chrono::microseconds freshnessLifetime(const ResourceResponse&) const;
317 void addAdditionalRequestHeaders(CachedResourceLoader&);
318 void failBeforeStarting();
320 HashMap<CachedResourceClient*, std::unique_ptr<Callback>> m_clientsAwaitingCallback;
321 PAL::SessionID m_sessionID;
322 ResourceLoadPriority m_loadPriority;
323 std::chrono::system_clock::time_point m_responseTimestamp;
325 String m_fragmentIdentifierForRequest;
327 ResourceError m_error;
328 RefPtr<SecurityOrigin> m_origin;
329 AtomicString m_initiatorName;
331 double m_lastDecodedAccessTime { 0 }; // Used as a "thrash guard" in the cache
333 unsigned m_encodedSize { 0 };
334 unsigned m_decodedSize { 0 };
335 unsigned m_accessCount { 0 };
336 unsigned m_handleCount { 0 };
337 unsigned m_preloadCount { 0 };
339 PreloadResult m_preloadResult { PreloadNotReferenced };
341 bool m_requestedFromNetworkingLayer { false };
343 bool m_inCache { false };
344 bool m_loading { false };
345 bool m_isLinkPreload { false };
346 bool m_hasUnknownEncoding { false };
348 bool m_switchingClientsToRevalidatedResource { false };
351 unsigned m_status { Pending }; // Status
354 bool m_deleted { false };
355 unsigned m_lruIndex { 0 };
358 CachedResourceLoader* m_owningCachedResourceLoader { nullptr }; // only non-null for resources that are not in the cache
360 // If this field is non-null we are using the resource as a proxy for checking whether an existing resource is still up to date
361 // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
362 // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
363 // resources becomes normal resource load.
364 CachedResource* m_resourceToRevalidate { nullptr };
366 // If this field is non-null, the resource has a proxy for checking whether it is still up to date (see m_resourceToRevalidate).
367 CachedResource* m_proxyResource { nullptr };
369 // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
370 HashSet<CachedResourceHandleBase*> m_handlesToRevalidate;
372 RedirectChainCacheStatus m_redirectChainCacheStatus;
374 Vector<std::pair<String, String>> m_varyingHeaderValues;
376 unsigned long m_identifierForLoadWithoutResourceLoader { 0 };
377 bool m_ignoreForRequestCount { false };
380 class CachedResource::Callback {
382 WTF_MAKE_FAST_ALLOCATED;
385 Callback(CachedResource&, CachedResourceClient&);
392 CachedResource& m_resource;
393 CachedResourceClient& m_client;
397 } // namespace WebCore
399 #define SPECIALIZE_TYPE_TRAITS_CACHED_RESOURCE(ToClassName, CachedResourceType) \
400 SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::ToClassName) \
401 static bool isType(const WebCore::CachedResource& resource) { return resource.type() == WebCore::CachedResourceType; } \
402 SPECIALIZE_TYPE_TRAITS_END()