Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / fetch / Resource.h
1 /*
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.
6
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.
11
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.
16
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.
21 */
22
23 #ifndef Resource_h
24 #define Resource_h
25
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 "wtf/HashCountedSet.h"
33 #include "wtf/HashSet.h"
34 #include "wtf/OwnPtr.h"
35 #include "wtf/text/WTFString.h"
36
37 namespace WebCore {
38
39 struct FetchInitiatorInfo;
40 class MemoryCache;
41 class CachedMetadata;
42 class ResourceClient;
43 class ResourcePtrBase;
44 class ResourceFetcher;
45 class InspectorResource;
46 class PurgeableBuffer;
47 class ResourceLoader;
48 class SecurityOrigin;
49 class SharedBuffer;
50
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.
54 class Resource {
55     WTF_MAKE_NONCOPYABLE(Resource); WTF_MAKE_FAST_ALLOCATED;
56     friend class MemoryCache;
57     friend class InspectorResource;
58
59 public:
60     enum Type {
61         MainResource,
62         Image,
63         CSSStyleSheet,
64         Script,
65         Font,
66         Raw,
67         SVGDocument,
68         XSLStyleSheet,
69         LinkPrefetch,
70         LinkSubresource,
71         TextTrack,
72         Shader,
73         ImportResource
74     };
75
76     enum Status {
77         Unknown, // let cache decide what to do with it
78         Pending, // only partially loaded
79         Cached, // regular case
80         LoadError,
81         DecodeError
82     };
83
84     Resource(const ResourceRequest&, Type);
85     virtual ~Resource();
86
87     // Determines the order in which CachedResources are evicted
88     // from the decoded resources cache.
89     enum CacheLiveResourcePriority {
90         CacheLiveResourcePriorityLow = 0,
91         CacheLiveResourcePriorityHigh
92     };
93
94     virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
95
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);
100
101     void setNeedsSynchronousCacheHit(bool needsSynchronousCacheHit) { m_needsSynchronousCacheHit = needsSynchronousCacheHit; }
102
103     void setResourceError(const ResourceError& error) { m_error = error; }
104     const ResourceError& resourceError() const { return m_error; }
105
106     void setIdentifier(unsigned long identifier) { m_identifier = identifier; }
107     unsigned long identifier() const { return m_identifier; }
108
109     virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
110
111     ResourceRequest& resourceRequest() { return m_resourceRequest; }
112     const KURL& url() const { return m_resourceRequest.url();}
113     Type type() const { return static_cast<Type>(m_type); }
114     const ResourceLoaderOptions& options() const { return m_options; }
115     void setOptions(const ResourceLoaderOptions& options) { m_options = options; }
116
117     void didChangePriority(ResourceLoadPriority);
118
119     void addClient(ResourceClient*);
120     void removeClient(ResourceClient*);
121     bool hasClients() const { return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty(); }
122     bool deleteIfPossible();
123
124     enum PreloadResult {
125         PreloadNotReferenced,
126         PreloadReferenced,
127         PreloadReferencedWhileLoading,
128         PreloadReferencedWhileComplete
129     };
130     PreloadResult preloadResult() const { return static_cast<PreloadResult>(m_preloadResult); }
131
132     virtual void didAddClient(ResourceClient*);
133     virtual void didRemoveClient(ResourceClient*) { }
134     virtual void allClientsRemoved();
135
136     unsigned count() const { return m_clients.size(); }
137
138     Status status() const { return static_cast<Status>(m_status); }
139     void setStatus(Status status) { m_status = status; }
140
141     size_t size() const { return encodedSize() + decodedSize() + overheadSize(); }
142     size_t encodedSize() const { return m_encodedSize; }
143     size_t decodedSize() const { return m_decodedSize; }
144     size_t overheadSize() const;
145
146     bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
147
148     bool isLoading() const { return m_loading; }
149     void setLoading(bool b) { m_loading = b; }
150     virtual bool stillNeedsLoad() const { return false; }
151
152     ResourceLoader* loader() const { return m_loader.get(); }
153
154     virtual bool isImage() const { return false; }
155     bool ignoreForRequestCount() const
156     {
157         return type() == MainResource
158             || type() == LinkPrefetch
159             || type() == LinkSubresource
160             || type() == Raw;
161     }
162
163     void updateForAccess();
164     unsigned accessCount() const { return m_accessCount; }
165
166     // Computes the status of an object after loading.
167     // Updates the expire date on the cache entry file
168     void finish(double finishTime = 0.0);
169
170     // FIXME: Remove the stringless variant once all the callsites' error messages are updated.
171     bool passesAccessControlCheck(SecurityOrigin*);
172     bool passesAccessControlCheck(SecurityOrigin*, String& errorDescription);
173
174     // Called by the cache if the object has been removed from the cache
175     // while still being referenced. This means the object should delete itself
176     // if the number of clients observing it ever drops to 0.
177     // The resource can be brought back to cache after successful revalidation.
178     void setInCache(bool inCache) { m_inCache = inCache; }
179     bool inCache() const { return m_inCache; }
180
181     void setCacheLiveResourcePriority(CacheLiveResourcePriority);
182     unsigned cacheLiveResourcePriority() const { return m_cacheLiveResourcePriority; }
183     bool inLiveDecodedResourcesList() { return m_inLiveDecodedResourcesList; }
184
185     void clearLoader();
186
187     SharedBuffer* resourceBuffer() const { ASSERT(!m_purgeableData); return m_data.get(); }
188     void setResourceBuffer(PassRefPtr<SharedBuffer>);
189
190     virtual void willSendRequest(ResourceRequest&, const ResourceResponse&);
191
192     virtual void updateRequest(const ResourceRequest&) { }
193     virtual void responseReceived(const ResourceResponse&);
194     void setResponse(const ResourceResponse& response) { m_response = response; }
195     const ResourceResponse& response() const { return m_response; }
196
197     // Sets the serialized metadata retrieved from the platform's cache.
198     void setSerializedCachedMetadata(const char*, size_t);
199
200     // Caches the given metadata in association with this resource and suggests
201     // that the platform persist it. The dataTypeID is a pseudo-randomly chosen
202     // identifier that is used to distinguish data generated by the caller.
203     void setCachedMetadata(unsigned dataTypeID, const char*, size_t);
204
205     // Returns cached metadata of the given type associated with this resource.
206     CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
207
208     bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_protectorCount && !m_resourceToRevalidate && !m_proxyResource; }
209     bool hasOneHandle() const { return m_handleCount == 1; }
210
211     // List of acceptable MIME types separated by ",".
212     // A MIME type may contain a wildcard, e.g. "text/*".
213     AtomicString accept() const { return m_accept; }
214     void setAccept(const AtomicString& accept) { m_accept = accept; }
215
216     bool wasCanceled() const { return m_error.isCancellation(); }
217     bool errorOccurred() const { return m_status == LoadError || m_status == DecodeError; }
218     bool loadFailedOrCanceled() { return !m_error.isNull(); }
219
220     DataBufferingPolicy dataBufferingPolicy() const { return m_options.dataBufferingPolicy; }
221     void setDataBufferingPolicy(DataBufferingPolicy);
222
223     bool isPreloaded() const { return m_preloadCount; }
224     void increasePreloadCount() { ++m_preloadCount; }
225     void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; }
226
227     void registerHandle(ResourcePtrBase* h);
228     void unregisterHandle(ResourcePtrBase* h);
229
230     bool canReuseRedirectChain() const;
231     bool mustRevalidateDueToCacheHeaders() const;
232     bool canUseCacheValidator() const;
233     bool isCacheValidator() const { return m_resourceToRevalidate; }
234     Resource* resourceToRevalidate() const { return m_resourceToRevalidate; }
235     void setResourceToRevalidate(Resource*);
236
237     bool isPurgeable() const;
238     bool wasPurged() const;
239     bool lock();
240
241     virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
242     virtual void didDownloadData(int) { }
243
244     double loadFinishTime() const { return m_loadFinishTime; }
245
246     virtual bool canReuse(const ResourceRequest&) const { return true; }
247
248     void prune();
249
250     static const char* resourceTypeToString(Type, const FetchInitiatorInfo&);
251
252 protected:
253     virtual void checkNotify();
254     virtual void finishOnePart();
255
256     // Normal resource pointers will silently switch what Resource* they reference when we
257     // successfully revalidated the resource. We need a way to guarantee that the Resource
258     // that received the 304 response survives long enough to switch everything over to the
259     // revalidatedresource. The normal mechanisms for keeping a Resource alive externally
260     // (ResourcePtrs and ResourceClients registering themselves) don't work in this case, so
261     // have a separate internal protector).
262     class InternalResourcePtr {
263     public:
264         explicit InternalResourcePtr(Resource* resource)
265             : m_resource(resource)
266         {
267             m_resource->incrementProtectorCount();
268         }
269
270         ~InternalResourcePtr()
271         {
272             m_resource->decrementProtectorCount();
273             m_resource->deleteIfPossible();
274         }
275     private:
276         Resource* m_resource;
277     };
278
279     void incrementProtectorCount() { m_protectorCount++; }
280     void decrementProtectorCount() { m_protectorCount--; }
281
282     void setEncodedSize(size_t);
283     void setDecodedSize(size_t);
284     void didAccessDecodedData(double timeStamp);
285
286     virtual void switchClientsToRevalidatedResource();
287     void clearResourceToRevalidate();
288     void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
289
290     void finishPendingClients();
291
292     HashCountedSet<ResourceClient*> m_clients;
293     HashCountedSet<ResourceClient*> m_clientsAwaitingCallback;
294
295     class ResourceCallback {
296     public:
297         static ResourceCallback* callbackHandler();
298         void schedule(Resource*);
299         void cancel(Resource*);
300     private:
301         ResourceCallback();
302         void timerFired(Timer<ResourceCallback>*);
303         Timer<ResourceCallback> m_callbackTimer;
304         HashSet<Resource*> m_resourcesWithPendingClients;
305     };
306
307     bool hasClient(ResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
308
309     struct RedirectPair {
310     public:
311         explicit RedirectPair(const ResourceRequest& request, const ResourceResponse& redirectResponse)
312             : m_request(request)
313             , m_redirectResponse(redirectResponse)
314         {
315         }
316
317         const ResourceRequest m_request;
318         const ResourceResponse m_redirectResponse;
319     };
320     const Vector<RedirectPair>& redirectChain() const { return m_redirectChain; }
321
322     virtual bool isSafeToUnlock() const { return false; }
323     virtual void destroyDecodedDataIfPossible() { }
324
325     ResourceRequest m_resourceRequest;
326     AtomicString m_accept;
327     RefPtr<ResourceLoader> m_loader;
328     ResourceLoaderOptions m_options;
329
330     ResourceResponse m_response;
331     double m_responseTimestamp;
332
333     RefPtr<SharedBuffer> m_data;
334     OwnPtr<PurgeableBuffer> m_purgeableData;
335     Timer<Resource> m_cancelTimer;
336
337 private:
338     bool addClientToSet(ResourceClient*);
339     void cancelTimerFired(Timer<Resource>*);
340
341     void revalidationSucceeded(const ResourceResponse&);
342     void revalidationFailed();
343
344     bool unlock();
345
346     void failBeforeStarting();
347
348     String m_fragmentIdentifierForRequest;
349
350     RefPtr<CachedMetadata> m_cachedMetadata;
351
352     ResourceError m_error;
353
354     double m_lastDecodedAccessTime; // Used as a "thrash guard" in the cache
355     double m_loadFinishTime;
356
357     unsigned long m_identifier;
358
359     size_t m_encodedSize;
360     size_t m_decodedSize;
361     unsigned m_accessCount;
362     unsigned m_handleCount;
363     unsigned m_preloadCount;
364     unsigned m_protectorCount;
365
366     unsigned m_preloadResult : 2; // PreloadResult
367     unsigned m_cacheLiveResourcePriority : 2; // CacheLiveResourcePriority
368     unsigned m_inLiveDecodedResourcesList : 1;
369     unsigned m_requestedFromNetworkingLayer : 1;
370
371     unsigned m_inCache : 1;
372     unsigned m_loading : 1;
373
374     unsigned m_switchingClientsToRevalidatedResource : 1;
375
376     unsigned m_type : 4; // Type
377     unsigned m_status : 3; // Status
378
379     unsigned m_wasPurged : 1;
380
381     unsigned m_needsSynchronousCacheHit : 1;
382
383 #ifndef NDEBUG
384     bool m_deleted;
385     unsigned m_lruIndex;
386 #endif
387
388     Resource* m_nextInAllResourcesList;
389     Resource* m_prevInAllResourcesList;
390
391     Resource* m_nextInLiveResourcesList;
392     Resource* m_prevInLiveResourcesList;
393
394     // 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
395     // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
396     // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
397     // resources becomes normal resource load.
398     Resource* m_resourceToRevalidate;
399
400     // If this field is non-null, the resource has a proxy for checking whether it is still up to date (see m_resourceToRevalidate).
401     Resource* m_proxyResource;
402
403     // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
404     HashSet<ResourcePtrBase*> m_handlesToRevalidate;
405
406     // Ordered list of all redirects followed while fetching this resource.
407     Vector<RedirectPair> m_redirectChain;
408 };
409
410 #if !LOG_DISABLED
411 // Intended to be used in LOG statements.
412 const char* ResourceTypeName(Resource::Type);
413 #endif
414
415 #define DEFINE_RESOURCE_TYPE_CASTS(typeName) \
416     DEFINE_TYPE_CASTS(typeName##Resource, Resource, resource, resource->type() == Resource::typeName, resource.type() == Resource::typeName); \
417     inline typeName##Resource* to##typeName##Resource(const ResourcePtr<Resource>& ptr) { return to##typeName##Resource(ptr.get()); }
418
419 }
420
421 #endif