Upstream version 11.40.277.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 "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"
37
38 // FIXME(crbug.com/352043): This is temporarily enabled even on RELEASE to diagnose a wild crash.
39 #define ENABLE_RESOURCE_IS_DELETED_CHECK
40
41 namespace blink {
42
43 struct FetchInitiatorInfo;
44 class CachedMetadata;
45 class ResourceClient;
46 class ResourcePtrBase;
47 class ResourceFetcher;
48 class InspectorResource;
49 class ResourceLoader;
50 class SecurityOrigin;
51 class SharedBuffer;
52
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;
59
60 public:
61     enum Type {
62         MainResource,
63         Image,
64         CSSStyleSheet,
65         Script,
66         Font,
67         Raw,
68         SVGDocument,
69         XSLStyleSheet,
70         LinkPrefetch,
71         LinkSubresource,
72         TextTrack,
73         ImportResource,
74         Media // Audio or video file requested by a HTML5 media element
75     };
76
77     enum Status {
78         Unknown, // let cache decide what to do with it
79         Pending, // only partially loaded
80         Cached, // regular case
81         LoadError,
82         DecodeError
83     };
84
85     enum MetadataCacheType {
86         SendToPlatform, // send cache data to blink::Platform::cacheMetadata
87         CacheLocally // cache only in Resource's member variables
88     };
89
90     Resource(const ResourceRequest&, Type);
91 #if ENABLE(OILPAN)
92     virtual ~Resource();
93 #else
94 protected:
95     // Only deleteIfPossible should delete this.
96     virtual ~Resource();
97 public:
98 #endif
99     virtual void dispose();
100     virtual void trace(Visitor*);
101     static unsigned instanceCount() { return s_instanceCount; }
102
103     virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
104
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);
109
110     void setNeedsSynchronousCacheHit(bool needsSynchronousCacheHit) { m_needsSynchronousCacheHit = needsSynchronousCacheHit; }
111
112     void setResourceError(const ResourceError& error) { m_error = error; }
113     const ResourceError& resourceError() const { return m_error; }
114
115     void setIdentifier(unsigned long identifier) { m_identifier = identifier; }
116     unsigned long identifier() const { return m_identifier; }
117
118     virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return false; }
119
120     ResourceRequest& mutableResourceRequest() { return m_resourceRequest; }
121     const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
122     const ResourceRequest& lastResourceRequest() const;
123
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; }
128
129     void didChangePriority(ResourceLoadPriority, int intraPriorityValue);
130
131     void addClient(ResourceClient*);
132     void removeClient(ResourceClient*);
133     bool hasClients() const { return !m_clients.isEmpty() || !m_clientsAwaitingCallback.isEmpty(); }
134     bool deleteIfPossible();
135
136     enum PreloadResult {
137         PreloadNotReferenced,
138         PreloadReferenced,
139         PreloadReferencedWhileLoading,
140         PreloadReferencedWhileComplete
141     };
142     PreloadResult preloadResult() const { return static_cast<PreloadResult>(m_preloadResult); }
143
144     virtual void didAddClient(ResourceClient*);
145     virtual void didRemoveClient(ResourceClient*) { }
146     virtual void allClientsRemoved();
147
148     unsigned count() const { return m_clients.size(); }
149
150     Status status() const { return static_cast<Status>(m_status); }
151     void setStatus(Status status) { m_status = status; }
152
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;
157
158     bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
159
160     bool isLoading() const { return m_loading; }
161     void setLoading(bool b) { m_loading = b; }
162     virtual bool stillNeedsLoad() const { return false; }
163
164     ResourceLoader* loader() const { return m_loader.get(); }
165
166     virtual bool isImage() const { return false; }
167     bool ignoreForRequestCount() const
168     {
169         return type() == MainResource
170             || type() == LinkPrefetch
171             || type() == LinkSubresource
172             || type() == Media
173             || type() == Raw
174             || type() == TextTrack;
175     }
176
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; }
180     void finish();
181
182     // FIXME: Remove the stringless variant once all the callsites' error messages are updated.
183     bool passesAccessControlCheck(SecurityOrigin*);
184     bool passesAccessControlCheck(SecurityOrigin*, String& errorDescription);
185
186     void clearLoader();
187
188     SharedBuffer* resourceBuffer() const { return m_data.get(); }
189     void setResourceBuffer(PassRefPtr<SharedBuffer>);
190
191     virtual void willFollowRedirect(ResourceRequest&, const ResourceResponse&);
192
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; }
197
198     // Sets the serialized metadata retrieved from the platform's cache.
199     void setSerializedCachedMetadata(const char*, size_t);
200
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);
205
206     // Reset existing metadata, to allow setting new data.
207     void clearCachedMetadata();
208
209     // Returns cached metadata of the given type associated with this resource.
210     CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
211
212     bool hasOneHandle() const;
213     bool canDelete() const;
214
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; }
219
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(); }
223
224     DataBufferingPolicy dataBufferingPolicy() const { return m_options.dataBufferingPolicy; }
225     void setDataBufferingPolicy(DataBufferingPolicy);
226
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; }
231
232     void registerHandle(ResourcePtrBase* h);
233     void unregisterHandle(ResourcePtrBase* h);
234
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();
242
243     bool isPurgeable() const;
244     bool wasPurged() const;
245     bool lock();
246
247     void setCacheIdentifier(const String& cacheIdentifier) { m_cacheIdentifier = cacheIdentifier; }
248     String cacheIdentifier() const { return m_cacheIdentifier; };
249
250     virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
251     virtual void didDownloadData(int) { }
252
253     double loadFinishTime() const { return m_loadFinishTime; }
254
255     virtual bool canReuse(const ResourceRequest&) const { return true; }
256
257     // Used by the MemoryCache to reduce the memory consumption of the entry.
258     void prune();
259
260     static const char* resourceTypeToString(Type, const FetchInitiatorInfo&);
261
262 #ifdef ENABLE_RESOURCE_IS_DELETED_CHECK
263     void assertAlive() const { RELEASE_ASSERT(!m_deleted); }
264 #else
265     void assertAlive() const { }
266 #endif
267
268 protected:
269     virtual void checkNotify();
270     virtual void finishOnePart();
271
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 {
279     public:
280         explicit InternalResourcePtr(Resource* resource)
281             : m_resource(resource)
282         {
283             m_resource->incrementProtectorCount();
284         }
285
286         ~InternalResourcePtr()
287         {
288             m_resource->decrementProtectorCount();
289             m_resource->deleteIfPossible();
290         }
291     private:
292         Resource* m_resource;
293     };
294
295     void incrementProtectorCount() { m_protectorCount++; }
296     void decrementProtectorCount() { m_protectorCount--; }
297
298     void setEncodedSize(size_t);
299     void setDecodedSize(size_t);
300     void didAccessDecodedData();
301
302     virtual void switchClientsToRevalidatedResource();
303     void clearResourceToRevalidate();
304     void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse);
305
306     void finishPendingClients();
307
308     HashCountedSet<ResourceClient*> m_clients;
309     HashCountedSet<ResourceClient*> m_clientsAwaitingCallback;
310
311     class ResourceCallback {
312     public:
313         static ResourceCallback* callbackHandler();
314         void schedule(Resource*);
315         void cancel(Resource*);
316         bool isScheduled(Resource*) const;
317     private:
318         ResourceCallback();
319         void timerFired(Timer<ResourceCallback>*);
320         Timer<ResourceCallback> m_callbackTimer;
321         HashSet<Resource*> m_resourcesWithPendingClients;
322     };
323
324     bool hasClient(ResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
325
326     struct RedirectPair {
327     public:
328         explicit RedirectPair(const ResourceRequest& request, const ResourceResponse& redirectResponse)
329             : m_request(request)
330             , m_redirectResponse(redirectResponse)
331         {
332         }
333
334         ResourceRequest m_request;
335         ResourceResponse m_redirectResponse;
336     };
337     const Vector<RedirectPair>& redirectChain() const { return m_redirectChain; }
338
339     virtual bool isSafeToUnlock() const { return false; }
340     virtual void destroyDecodedDataIfPossible() { }
341
342     ResourceRequest m_resourceRequest;
343     AtomicString m_accept;
344     RefPtrWillBeMember<ResourceLoader> m_loader;
345     ResourceLoaderOptions m_options;
346
347     ResourceResponse m_response;
348     double m_responseTimestamp;
349
350     RefPtr<SharedBuffer> m_data;
351     Timer<Resource> m_cancelTimer;
352
353 private:
354     bool addClientToSet(ResourceClient*);
355     void cancelTimerFired(Timer<Resource>*);
356
357     void revalidationSucceeded(const ResourceResponse&);
358     void revalidationFailed();
359
360     bool unlock();
361
362     bool hasRightHandleCountApartFromCache(unsigned targetCount) const;
363
364     void failBeforeStarting();
365
366     String m_fragmentIdentifierForRequest;
367
368     RefPtr<CachedMetadata> m_cachedMetadata;
369
370     ResourceError m_error;
371
372     double m_loadFinishTime;
373
374     unsigned long m_identifier;
375
376     size_t m_encodedSize;
377     size_t m_decodedSize;
378     unsigned m_handleCount;
379     unsigned m_preloadCount;
380     unsigned m_protectorCount;
381
382     String m_cacheIdentifier;
383
384     unsigned m_preloadResult : 2; // PreloadResult
385     unsigned m_requestedFromNetworkingLayer : 1;
386
387     unsigned m_loading : 1;
388
389     unsigned m_switchingClientsToRevalidatedResource : 1;
390
391     unsigned m_type : 4; // Type
392     unsigned m_status : 3; // Status
393
394     unsigned m_wasPurged : 1;
395
396     unsigned m_needsSynchronousCacheHit : 1;
397
398 #ifdef ENABLE_RESOURCE_IS_DELETED_CHECK
399     bool m_deleted;
400 #endif
401
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;
407
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;
410
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;
413
414     // Ordered list of all redirects followed while fetching this resource.
415     Vector<RedirectPair> m_redirectChain;
416
417     static unsigned s_instanceCount;
418 };
419
420 #if !LOG_DISABLED
421 // Intended to be used in LOG statements.
422 const char* ResourceTypeName(Resource::Type);
423 #endif
424
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()); }
428
429 }
430
431 #endif