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.
26 #include "core/fetch/CachePolicy.h"
27 #include "core/fetch/ResourceLoaderOptions.h"
28 #include "platform/Timer.h"
29 #include "platform/network/ResourceError.h"
30 #include "platform/network/ResourceLoadPriority.h"
31 #include "platform/network/ResourceRequest.h"
32 #include "platform/network/ResourceResponse.h"
33 #include "wtf/HashCountedSet.h"
34 #include "wtf/HashSet.h"
35 #include "wtf/OwnPtr.h"
36 #include "wtf/text/WTFString.h"
43 class ResourcePtrBase;
44 class ResourceFetcher;
45 class InspectorResource;
46 class PurgeableBuffer;
51 // A resource that is held in the cache. Classes who want to use this object should derive
52 // from ResourceClient, to get the function calls in case the requested data has arrived.
53 // This class also does the actual communication with the loader to obtain the resource from the network.
55 WTF_MAKE_NONCOPYABLE(Resource); WTF_MAKE_FAST_ALLOCATED;
56 friend class MemoryCache;
57 friend class InspectorResource;
77 Unknown, // let cache decide what to do with it
78 Pending, // only partially loaded
79 Cached, // regular case
84 Resource(const ResourceRequest&, Type);
87 // Determines the order in which CachedResources are evicted
88 // from the decoded resources cache.
89 enum CacheLiveResourcePriority {
90 CacheLiveResourcePriorityLow = 0,
91 CacheLiveResourcePriorityHigh
94 virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
96 virtual void setEncoding(const String&) { }
97 virtual String encoding() const { return String(); }
98 virtual void appendData(const char*, int);
99 virtual void error(Resource::Status);
101 void setResourceError(const ResourceError& error) { m_error = error; }
102 const ResourceError& resourceError() const { return m_error; }
104 void setIdentifier(unsigned long identifier) { m_identifier = identifier; }
105 unsigned long identifier() const { return m_identifier; }
107 virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
109 ResourceRequest& resourceRequest() { return m_resourceRequest; }
110 const KURL& url() const { return m_resourceRequest.url();}
111 Type type() const { return static_cast<Type>(m_type); }
112 const ResourceLoaderOptions& options() const { return m_options; }
113 void setOptions(const ResourceLoaderOptions& options) { m_options = options; }
115 void didChangePriority(ResourceLoadPriority);
117 void addClient(ResourceClient*);
118 void removeClient(ResourceClient*);
119 bool hasClients() const { return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty(); }
120 bool deleteIfPossible();
123 PreloadNotReferenced,
125 PreloadReferencedWhileLoading,
126 PreloadReferencedWhileComplete
128 PreloadResult preloadResult() const { return static_cast<PreloadResult>(m_preloadResult); }
130 virtual void didAddClient(ResourceClient*);
131 virtual void didRemoveClient(ResourceClient*) { }
132 virtual void allClientsRemoved();
134 unsigned count() const { return m_clients.size(); }
136 Status status() const { return static_cast<Status>(m_status); }
137 void setStatus(Status status) { m_status = status; }
139 unsigned size() const { return encodedSize() + decodedSize() + overheadSize(); }
140 unsigned encodedSize() const { return m_encodedSize; }
141 unsigned decodedSize() const { return m_decodedSize; }
142 unsigned overheadSize() const;
144 bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
146 bool isLoading() const { return m_loading; }
147 void setLoading(bool b) { m_loading = b; }
148 virtual bool stillNeedsLoad() const { return false; }
150 ResourceLoader* loader() const { return m_loader.get(); }
152 virtual bool isImage() const { return false; }
153 bool ignoreForRequestCount() const
155 return type() == MainResource
156 || type() == LinkPrefetch
157 || type() == LinkSubresource
161 void updateForAccess();
162 unsigned accessCount() const { return m_accessCount; }
164 // Computes the status of an object after loading.
165 // Updates the expire date on the cache entry file
166 void finish(double finishTime = 0.0);
168 // FIXME: Remove the stringless variant once all the callsites' error messages are updated.
169 bool passesAccessControlCheck(SecurityOrigin*);
170 bool passesAccessControlCheck(SecurityOrigin*, String& errorDescription);
172 // Called by the cache if the object has been removed from the cache
173 // while still being referenced. This means the object should delete itself
174 // if the number of clients observing it ever drops to 0.
175 // The resource can be brought back to cache after successful revalidation.
176 void setInCache(bool inCache) { m_inCache = inCache; }
177 bool inCache() const { return m_inCache; }
179 void setCacheLiveResourcePriority(CacheLiveResourcePriority);
180 unsigned cacheLiveResourcePriority() const { return m_cacheLiveResourcePriority; }
181 bool inLiveDecodedResourcesList() { return m_inLiveDecodedResourcesList; }
185 SharedBuffer* resourceBuffer() const { ASSERT(!m_purgeableData); return m_data.get(); }
186 void setResourceBuffer(PassRefPtr<SharedBuffer>);
188 virtual void willSendRequest(ResourceRequest&, const ResourceResponse&) { m_requestedFromNetworkingLayer = true; }
189 virtual void responseReceived(const ResourceResponse&);
190 void setResponse(const ResourceResponse& response) { m_response = response; }
191 const ResourceResponse& response() const { return m_response; }
193 // Sets the serialized metadata retrieved from the platform's cache.
194 void setSerializedCachedMetadata(const char*, size_t);
196 // Caches the given metadata in association with this resource and suggests
197 // that the platform persist it. The dataTypeID is a pseudo-randomly chosen
198 // identifier that is used to distinguish data generated by the caller.
199 void setCachedMetadata(unsigned dataTypeID, const char*, size_t);
201 // Returns cached metadata of the given type associated with this resource.
202 CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
204 bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_resourceToRevalidate && !m_proxyResource; }
205 bool hasOneHandle() const { return m_handleCount == 1; }
207 bool isExpired() const;
209 // List of acceptable MIME types separated by ",".
210 // A MIME type may contain a wildcard, e.g. "text/*".
211 AtomicString accept() const { return m_accept; }
212 void setAccept(const AtomicString& accept) { m_accept = accept; }
214 bool wasCanceled() const { return m_error.isCancellation(); }
215 bool errorOccurred() const { return m_status == LoadError || m_status == DecodeError; }
216 bool loadFailedOrCanceled() { return !m_error.isNull(); }
218 bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
219 DataBufferingPolicy dataBufferingPolicy() const { return m_options.dataBufferingPolicy; }
221 virtual void destroyDecodedData() { }
223 bool isPreloaded() const { return m_preloadCount; }
224 void increasePreloadCount() { ++m_preloadCount; }
225 void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; }
227 void registerHandle(ResourcePtrBase* h);
228 void unregisterHandle(ResourcePtrBase* h);
230 bool canUseCacheValidator() const;
231 bool mustRevalidateDueToCacheHeaders(CachePolicy) const;
232 bool isCacheValidator() const { return m_resourceToRevalidate; }
233 Resource* resourceToRevalidate() const { return m_resourceToRevalidate; }
234 void setResourceToRevalidate(Resource*);
236 bool isPurgeable() const;
237 bool wasPurged() const;
239 // This is used by the archive machinery to get at a purged resource without
240 // triggering a load. We should make it protected again if we can find a
241 // better way to handle the archive case.
242 bool makePurgeable(bool purgeable);
244 virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
245 virtual void didDownloadData(int) { }
247 double loadFinishTime() const { return m_loadFinishTime; }
249 virtual bool canReuse(const ResourceRequest&) const { return true; }
252 virtual void checkNotify();
253 virtual void finishOnePart();
255 void setEncodedSize(unsigned);
256 void setDecodedSize(unsigned);
257 void didAccessDecodedData(double timeStamp);
259 bool isSafeToMakePurgeable() const;
261 virtual void switchClientsToRevalidatedResource();
262 void clearResourceToRevalidate();
263 void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
265 void finishPendingClients();
267 HashCountedSet<ResourceClient*> m_clients;
268 HashCountedSet<ResourceClient*> m_clientsAwaitingCallback;
270 class ResourceCallback {
272 static ResourceCallback* callbackHandler();
273 void schedule(Resource*);
274 void cancel(Resource*);
277 void timerFired(Timer<ResourceCallback>*);
278 Timer<ResourceCallback> m_callbackTimer;
279 HashSet<Resource*> m_resourcesWithPendingClients;
282 bool hasClient(ResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
284 ResourceRequest m_resourceRequest;
285 AtomicString m_accept;
286 RefPtr<ResourceLoader> m_loader;
287 ResourceLoaderOptions m_options;
289 ResourceResponse m_response;
290 double m_responseTimestamp;
292 RefPtr<SharedBuffer> m_data;
293 OwnPtr<PurgeableBuffer> m_purgeableData;
294 Timer<Resource> m_cancelTimer;
297 bool addClientToSet(ResourceClient*);
298 void cancelTimerFired(Timer<Resource>*);
300 void revalidationSucceeded(const ResourceResponse&);
301 void revalidationFailed();
303 double currentAge() const;
304 double freshnessLifetime() const;
306 void failBeforeStarting();
308 String m_fragmentIdentifierForRequest;
310 RefPtr<CachedMetadata> m_cachedMetadata;
312 ResourceError m_error;
314 double m_lastDecodedAccessTime; // Used as a "thrash guard" in the cache
315 double m_loadFinishTime;
317 unsigned long m_identifier;
319 unsigned m_encodedSize;
320 unsigned m_decodedSize;
321 unsigned m_accessCount;
322 unsigned m_handleCount;
323 unsigned m_preloadCount;
325 unsigned m_preloadResult : 2; // PreloadResult
326 unsigned m_cacheLiveResourcePriority : 2; // CacheLiveResourcePriority
327 unsigned m_inLiveDecodedResourcesList : 1;
328 unsigned m_requestedFromNetworkingLayer : 1;
330 unsigned m_inCache : 1;
331 unsigned m_loading : 1;
333 unsigned m_switchingClientsToRevalidatedResource : 1;
335 unsigned m_type : 4; // Type
336 unsigned m_status : 3; // Status
343 Resource* m_nextInAllResourcesList;
344 Resource* m_prevInAllResourcesList;
346 Resource* m_nextInLiveResourcesList;
347 Resource* m_prevInLiveResourcesList;
349 // 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
350 // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
351 // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
352 // resources becomes normal resource load.
353 Resource* m_resourceToRevalidate;
355 // If this field is non-null, the resource has a proxy for checking whether it is still up to date (see m_resourceToRevalidate).
356 Resource* m_proxyResource;
358 // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
359 HashSet<ResourcePtrBase*> m_handlesToRevalidate;
363 // Intended to be used in LOG statements.
364 const char* ResourceTypeName(Resource::Type);