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/ResourceLoaderOptions.h"
27 #include "platform/Timer.h"
28 #include "platform/network/ResourceError.h"
29 #include "platform/network/ResourceLoadPriority.h"
30 #include "platform/network/ResourceRequest.h"
31 #include "platform/network/ResourceResponse.h"
32 #include "public/platform/WebDataConsumerHandle.h"
33 #include "wtf/HashCountedSet.h"
34 #include "wtf/HashSet.h"
35 #include "wtf/OwnPtr.h"
36 #include "wtf/text/WTFString.h"
38 // FIXME(crbug.com/352043): This is temporarily enabled even on RELEASE to diagnose a wild crash.
39 #define ENABLE_RESOURCE_IS_DELETED_CHECK
43 struct FetchInitiatorInfo;
46 class ResourcePtrBase;
47 class ResourceFetcher;
48 class InspectorResource;
53 // A resource that is held in the cache. Classes who want to use this object should derive
54 // from ResourceClient, to get the function calls in case the requested data has arrived.
55 // This class also does the actual communication with the loader to obtain the resource from the network.
56 class Resource : public NoBaseWillBeGarbageCollectedFinalized<Resource> {
57 WTF_MAKE_NONCOPYABLE(Resource); WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
58 friend class InspectorResource;
74 Media // Audio or video file requested by a HTML5 media element
78 Unknown, // let cache decide what to do with it
79 Pending, // only partially loaded
80 Cached, // regular case
85 enum MetadataCacheType {
86 SendToPlatform, // send cache data to blink::Platform::cacheMetadata
87 CacheLocally // cache only in Resource's member variables
90 Resource(const ResourceRequest&, Type);
95 // Only deleteIfPossible should delete this.
99 virtual void dispose();
100 virtual void trace(Visitor*);
101 static unsigned instanceCount() { return s_instanceCount; }
103 virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
105 virtual void setEncoding(const String&) { }
106 virtual String encoding() const { return String(); }
107 virtual void appendData(const char*, unsigned);
108 virtual void error(Resource::Status);
110 void setNeedsSynchronousCacheHit(bool needsSynchronousCacheHit) { m_needsSynchronousCacheHit = needsSynchronousCacheHit; }
112 void setResourceError(const ResourceError& error) { m_error = error; }
113 const ResourceError& resourceError() const { return m_error; }
115 void setIdentifier(unsigned long identifier) { m_identifier = identifier; }
116 unsigned long identifier() const { return m_identifier; }
118 virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
120 ResourceRequest& mutableResourceRequest() { return m_resourceRequest; }
121 const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
122 const ResourceRequest& lastResourceRequest() const;
124 const KURL& url() const { return m_resourceRequest.url();}
125 Type type() const { return static_cast<Type>(m_type); }
126 const ResourceLoaderOptions& options() const { return m_options; }
127 void setOptions(const ResourceLoaderOptions& options) { m_options = options; }
129 void didChangePriority(ResourceLoadPriority, int intraPriorityValue);
131 void addClient(ResourceClient*);
132 void removeClient(ResourceClient*);
133 bool hasClients() const { return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty(); }
134 bool deleteIfPossible();
137 PreloadNotReferenced,
139 PreloadReferencedWhileLoading,
140 PreloadReferencedWhileComplete
142 PreloadResult preloadResult() const { return static_cast<PreloadResult>(m_preloadResult); }
144 virtual void didAddClient(ResourceClient*);
145 virtual void didRemoveClient(ResourceClient*) { }
146 virtual void allClientsRemoved();
148 unsigned count() const { return m_clients.size(); }
150 Status status() const { return static_cast<Status>(m_status); }
151 void setStatus(Status status) { m_status = status; }
153 size_t size() const { return encodedSize() + decodedSize() + overheadSize(); }
154 size_t encodedSize() const { return m_encodedSize; }
155 size_t decodedSize() const { return m_decodedSize; }
156 size_t overheadSize() const;
158 bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
160 bool isLoading() const { return m_loading; }
161 void setLoading(bool b) { m_loading = b; }
162 virtual bool stillNeedsLoad() const { return false; }
164 ResourceLoader* loader() const { return m_loader.get(); }
166 virtual bool isImage() const { return false; }
167 bool ignoreForRequestCount() const
169 return type() == MainResource
170 || type() == LinkPrefetch
171 || type() == LinkSubresource
174 || type() == TextTrack;
177 // Computes the status of an object after loading.
178 // Updates the expire date on the cache entry file
179 void setLoadFinishTime(double finishTime) { m_loadFinishTime = finishTime; }
182 // FIXME: Remove the stringless variant once all the callsites' error messages are updated.
183 bool passesAccessControlCheck(SecurityOrigin*);
184 bool passesAccessControlCheck(SecurityOrigin*, String& errorDescription);
188 SharedBuffer* resourceBuffer() const { return m_data.get(); }
189 void setResourceBuffer(PassRefPtr<SharedBuffer>);
191 virtual void willFollowRedirect(ResourceRequest&, const ResourceResponse&);
193 virtual void updateRequest(const ResourceRequest&) { }
194 virtual void responseReceived(const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>);
195 void setResponse(const ResourceResponse& response) { m_response = response; }
196 const ResourceResponse& response() const { return m_response; }
198 // Sets the serialized metadata retrieved from the platform's cache.
199 void setSerializedCachedMetadata(const char*, size_t);
201 // Caches the given metadata in association with this resource and suggests
202 // that the platform persist it. The dataTypeID is a pseudo-randomly chosen
203 // identifier that is used to distinguish data generated by the caller.
204 void setCachedMetadata(unsigned dataTypeID, const char*, size_t, MetadataCacheType = SendToPlatform);
206 // Reset existing metadata, to allow setting new data.
207 void clearCachedMetadata();
209 // Returns cached metadata of the given type associated with this resource.
210 CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
212 bool hasOneHandle() const;
213 bool canDelete() const;
215 // List of acceptable MIME types separated by ",".
216 // A MIME type may contain a wildcard, e.g. "text/*".
217 AtomicString accept() const { return m_accept; }
218 void setAccept(const AtomicString& accept) { m_accept = accept; }
220 bool wasCanceled() const { return m_error.isCancellation(); }
221 bool errorOccurred() const { return m_status == LoadError || m_status == DecodeError; }
222 bool loadFailedOrCanceled() { return !m_error.isNull(); }
224 DataBufferingPolicy dataBufferingPolicy() const { return m_options.dataBufferingPolicy; }
225 void setDataBufferingPolicy(DataBufferingPolicy);
227 bool isUnusedPreload() const { return isPreloaded() && preloadResult() == PreloadNotReferenced; }
228 bool isPreloaded() const { return m_preloadCount; }
229 void increasePreloadCount() { ++m_preloadCount; }
230 void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; }
232 void registerHandle(ResourcePtrBase* h);
233 void unregisterHandle(ResourcePtrBase* h);
235 bool canReuseRedirectChain();
236 bool mustRevalidateDueToCacheHeaders();
237 bool canUseCacheValidator();
238 bool isCacheValidator() const { return m_resourceToRevalidate; }
239 Resource* resourceToRevalidate() const { return m_resourceToRevalidate; }
240 void setResourceToRevalidate(Resource*);
241 bool hasCacheControlNoStoreHeader();
243 bool isPurgeable() const;
244 bool wasPurged() const;
247 void setCacheIdentifier(const String& cacheIdentifier) { m_cacheIdentifier = cacheIdentifier; }
248 String cacheIdentifier() const { return m_cacheIdentifier; };
250 virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
251 virtual void didDownloadData(int) { }
253 double loadFinishTime() const { return m_loadFinishTime; }
255 virtual bool canReuse(const ResourceRequest&) const { return true; }
257 // Used by the MemoryCache to reduce the memory consumption of the entry.
260 static const char* resourceTypeToString(Type, const FetchInitiatorInfo&);
262 #ifdef ENABLE_RESOURCE_IS_DELETED_CHECK
263 void assertAlive() const { RELEASE_ASSERT(!m_deleted); }
265 void assertAlive() const { }
269 virtual void checkNotify();
270 virtual void finishOnePart();
272 // Normal resource pointers will silently switch what Resource* they reference when we
273 // successfully revalidated the resource. We need a way to guarantee that the Resource
274 // that received the 304 response survives long enough to switch everything over to the
275 // revalidatedresource. The normal mechanisms for keeping a Resource alive externally
276 // (ResourcePtrs and ResourceClients registering themselves) don't work in this case, so
277 // have a separate internal protector).
278 class InternalResourcePtr {
280 explicit InternalResourcePtr(Resource* resource)
281 : m_resource(resource)
283 m_resource->incrementProtectorCount();
286 ~InternalResourcePtr()
288 m_resource->decrementProtectorCount();
289 m_resource->deleteIfPossible();
292 Resource* m_resource;
295 void incrementProtectorCount() { m_protectorCount++; }
296 void decrementProtectorCount() { m_protectorCount--; }
298 void setEncodedSize(size_t);
299 void setDecodedSize(size_t);
300 void didAccessDecodedData();
302 virtual void switchClientsToRevalidatedResource();
303 void clearResourceToRevalidate();
304 void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
306 void finishPendingClients();
308 HashCountedSet<ResourceClient*> m_clients;
309 HashCountedSet<ResourceClient*> m_clientsAwaitingCallback;
311 class ResourceCallback {
313 static ResourceCallback* callbackHandler();
314 void schedule(Resource*);
315 void cancel(Resource*);
316 bool isScheduled(Resource*) const;
319 void timerFired(Timer<ResourceCallback>*);
320 Timer<ResourceCallback> m_callbackTimer;
321 HashSet<Resource*> m_resourcesWithPendingClients;
324 bool hasClient(ResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
326 struct RedirectPair {
328 explicit RedirectPair(const ResourceRequest& request, const ResourceResponse& redirectResponse)
330 , m_redirectResponse(redirectResponse)
334 ResourceRequest m_request;
335 ResourceResponse m_redirectResponse;
337 const Vector<RedirectPair>& redirectChain() const { return m_redirectChain; }
339 virtual bool isSafeToUnlock() const { return false; }
340 virtual void destroyDecodedDataIfPossible() { }
342 ResourceRequest m_resourceRequest;
343 AtomicString m_accept;
344 RefPtrWillBeMember<ResourceLoader> m_loader;
345 ResourceLoaderOptions m_options;
347 ResourceResponse m_response;
348 double m_responseTimestamp;
350 RefPtr<SharedBuffer> m_data;
351 Timer<Resource> m_cancelTimer;
354 bool addClientToSet(ResourceClient*);
355 void cancelTimerFired(Timer<Resource>*);
357 void revalidationSucceeded(const ResourceResponse&);
358 void revalidationFailed();
362 bool hasRightHandleCountApartFromCache(unsigned targetCount) const;
364 void failBeforeStarting();
366 String m_fragmentIdentifierForRequest;
368 RefPtr<CachedMetadata> m_cachedMetadata;
370 ResourceError m_error;
372 double m_loadFinishTime;
374 unsigned long m_identifier;
376 size_t m_encodedSize;
377 size_t m_decodedSize;
378 unsigned m_handleCount;
379 unsigned m_preloadCount;
380 unsigned m_protectorCount;
382 String m_cacheIdentifier;
384 unsigned m_preloadResult : 2; // PreloadResult
385 unsigned m_requestedFromNetworkingLayer : 1;
387 unsigned m_loading : 1;
389 unsigned m_switchingClientsToRevalidatedResource : 1;
391 unsigned m_type : 4; // Type
392 unsigned m_status : 3; // Status
394 unsigned m_wasPurged : 1;
396 unsigned m_needsSynchronousCacheHit : 1;
398 #ifdef ENABLE_RESOURCE_IS_DELETED_CHECK
402 // 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
403 // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
404 // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
405 // resources becomes normal resource load.
406 RawPtrWillBeMember<Resource> m_resourceToRevalidate;
408 // If this field is non-null, the resource has a proxy for checking whether it is still up to date (see m_resourceToRevalidate).
409 RawPtrWillBeMember<Resource> m_proxyResource;
411 // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
412 HashSet<ResourcePtrBase*> m_handlesToRevalidate;
414 // Ordered list of all redirects followed while fetching this resource.
415 Vector<RedirectPair> m_redirectChain;
417 static unsigned s_instanceCount;
421 // Intended to be used in LOG statements.
422 const char* ResourceTypeName(Resource::Type);
425 #define DEFINE_RESOURCE_TYPE_CASTS(typeName) \
426 DEFINE_TYPE_CASTS(typeName##Resource, Resource, resource, resource->type() == Resource::typeName, resource.type() == Resource::typeName); \
427 inline typeName##Resource* to##typeName##Resource(const ResourcePtr<Resource>& ptr) { return to##typeName##Resource(ptr.get()); }