OSDN Git Service

e519c29f181e23b5be53146b7773416263926940
[android-x86/external-webkit.git] / WebCore / loader / CachedResource.cpp
1 /*
2     Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3     Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
4     Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
5     Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
6     Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
7
8     This library is free software; you can redistribute it and/or
9     modify it under the terms of the GNU Library General Public
10     License as published by the Free Software Foundation; either
11     version 2 of the License, or (at your option) any later version.
12
13     This library is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16     Library General Public License for more details.
17
18     You should have received a copy of the GNU Library General Public License
19     along with this library; see the file COPYING.LIB.  If not, write to
20     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21     Boston, MA 02110-1301, USA.
22 */
23
24 #include "config.h"
25 #include "CachedResource.h"
26
27 #include "Cache.h"
28 #include "CachedMetadata.h"
29 #include "CachedResourceClient.h"
30 #include "CachedResourceClientWalker.h"
31 #include "CachedResourceHandle.h"
32 #include "CachedResourceLoader.h"
33 #include "Frame.h"
34 #include "FrameLoaderClient.h"
35 #include "KURL.h"
36 #include "Logging.h"
37 #include "PurgeableBuffer.h"
38 #include "Request.h"
39 #include "ResourceHandle.h"
40 #include "SharedBuffer.h"
41 #include <wtf/CurrentTime.h>
42 #include <wtf/MathExtras.h>
43 #include <wtf/RefCountedLeakCounter.h>
44 #include <wtf/StdLibExtras.h>
45 #include <wtf/Vector.h>
46
47 using namespace WTF;
48
49 namespace WebCore {
50
51 #ifndef NDEBUG
52 static RefCountedLeakCounter cachedResourceLeakCounter("CachedResource");
53 #endif
54
55 CachedResource::CachedResource(const String& url, Type type)
56     : m_url(url)
57     , m_request(0)
58     , m_responseTimestamp(currentTime())
59     , m_lastDecodedAccessTime(0)
60     , m_encodedSize(0)
61     , m_decodedSize(0)
62     , m_accessCount(0)
63     , m_handleCount(0)
64     , m_preloadCount(0)
65     , m_preloadResult(PreloadNotReferenced)
66     , m_inLiveDecodedResourcesList(false)
67     , m_requestedFromNetworkingLayer(false)
68     , m_sendResourceLoadCallbacks(true)
69     , m_errorOccurred(false)
70     , m_inCache(false)
71     , m_loading(false)
72     , m_type(type)
73     , m_status(Pending)
74 #ifndef NDEBUG
75     , m_deleted(false)
76     , m_lruIndex(0)
77 #endif
78     , m_nextInAllResourcesList(0)
79     , m_prevInAllResourcesList(0)
80     , m_nextInLiveResourcesList(0)
81     , m_prevInLiveResourcesList(0)
82     , m_cachedResourceLoader(0)
83     , m_resourceToRevalidate(0)
84     , m_proxyResource(0)
85 {
86 #ifndef NDEBUG
87     cachedResourceLeakCounter.increment();
88 #endif
89 }
90
91 CachedResource::~CachedResource()
92 {
93     ASSERT(!m_resourceToRevalidate); // Should be true because canDelete() checks this.
94     ASSERT(canDelete());
95     ASSERT(!inCache());
96     ASSERT(!m_deleted);
97     ASSERT(url().isNull() || cache()->resourceForURL(url()) != this);
98 #ifndef NDEBUG
99     m_deleted = true;
100     cachedResourceLeakCounter.decrement();
101 #endif
102
103     if (m_cachedResourceLoader)
104         m_cachedResourceLoader->removeCachedResource(this);
105 }
106
107 void CachedResource::load(CachedResourceLoader* cachedResourceLoader, bool incremental, SecurityCheckPolicy securityCheck, bool sendResourceLoadCallbacks)
108 {
109     m_sendResourceLoadCallbacks = sendResourceLoadCallbacks;
110     cache()->loader()->load(cachedResourceLoader, this, incremental, securityCheck, sendResourceLoadCallbacks);
111     m_loading = true;
112 }
113
114 void CachedResource::data(PassRefPtr<SharedBuffer>, bool allDataReceived)
115 {
116     if (!allDataReceived)
117         return;
118     
119     CachedResourceClientWalker w(m_clients);
120     while (CachedResourceClient* c = w.next())
121         c->notifyFinished(this);
122 }
123
124 void CachedResource::finish()
125 {
126     m_status = Cached;
127 }
128
129 bool CachedResource::isExpired() const
130 {
131     if (m_response.isNull())
132         return false;
133
134     return currentAge() > freshnessLifetime();
135 }
136     
137 double CachedResource::currentAge() const
138 {
139     // RFC2616 13.2.3
140     // No compensation for latency as that is not terribly important in practice
141     double dateValue = m_response.date();
142     double apparentAge = isfinite(dateValue) ? max(0., m_responseTimestamp - dateValue) : 0;
143     double ageValue = m_response.age();
144     double correctedReceivedAge = isfinite(ageValue) ? max(apparentAge, ageValue) : apparentAge;
145     double residentTime = currentTime() - m_responseTimestamp;
146     return correctedReceivedAge + residentTime;
147 }
148     
149 double CachedResource::freshnessLifetime() const
150 {
151     // Cache non-http resources liberally
152     if (!m_response.url().protocolInHTTPFamily())
153         return std::numeric_limits<double>::max();
154
155     // RFC2616 13.2.4
156     double maxAgeValue = m_response.cacheControlMaxAge();
157     if (isfinite(maxAgeValue))
158         return maxAgeValue;
159     double expiresValue = m_response.expires();
160     double dateValue = m_response.date();
161     double creationTime = isfinite(dateValue) ? dateValue : m_responseTimestamp;
162     if (isfinite(expiresValue))
163         return expiresValue - creationTime;
164     double lastModifiedValue = m_response.lastModified();
165     if (isfinite(lastModifiedValue))
166         return (creationTime - lastModifiedValue) * 0.1;
167     // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0.
168     return 0;
169 }
170
171 void CachedResource::setResponse(const ResourceResponse& response)
172 {
173     m_response = response;
174     m_responseTimestamp = currentTime();
175 }
176
177 void CachedResource::setSerializedCachedMetadata(const char* data, size_t size)
178 {
179     // We only expect to receive cached metadata from the platform once.
180     // If this triggers, it indicates an efficiency problem which is most
181     // likely unexpected in code designed to improve performance.
182     ASSERT(!m_cachedMetadata);
183
184     m_cachedMetadata = CachedMetadata::deserialize(data, size);
185 }
186
187 void CachedResource::setCachedMetadata(unsigned dataTypeID, const char* data, size_t size)
188 {
189     // Currently, only one type of cached metadata per resource is supported.
190     // If the need arises for multiple types of metadata per resource this could
191     // be enhanced to store types of metadata in a map.
192     ASSERT(!m_cachedMetadata);
193
194     m_cachedMetadata = CachedMetadata::create(dataTypeID, data, size);
195     ResourceHandle::cacheMetadata(m_response, m_cachedMetadata->serialize());
196 }
197
198 CachedMetadata* CachedResource::cachedMetadata(unsigned dataTypeID) const
199 {
200     if (!m_cachedMetadata || m_cachedMetadata->dataTypeID() != dataTypeID)
201         return 0;
202     return m_cachedMetadata.get();
203 }
204
205 void CachedResource::setRequest(Request* request)
206 {
207     if (request && !m_request)
208         m_status = Pending;
209     m_request = request;
210     if (canDelete() && !inCache())
211         delete this;
212 }
213
214 void CachedResource::addClient(CachedResourceClient* client)
215 {
216     addClientToSet(client);
217     didAddClient(client);
218 }
219
220 void CachedResource::didAddClient(CachedResourceClient* c)
221 {
222     if (!isLoading())
223         c->notifyFinished(this);
224 }
225
226 void CachedResource::addClientToSet(CachedResourceClient* client)
227 {
228     ASSERT(!isPurgeable());
229
230     if (m_preloadResult == PreloadNotReferenced) {
231         if (isLoaded())
232             m_preloadResult = PreloadReferencedWhileComplete;
233         else if (m_requestedFromNetworkingLayer)
234             m_preloadResult = PreloadReferencedWhileLoading;
235         else
236             m_preloadResult = PreloadReferenced;
237     }
238     if (!hasClients() && inCache())
239         cache()->addToLiveResourcesSize(this);
240     m_clients.add(client);
241 }
242
243 void CachedResource::removeClient(CachedResourceClient* client)
244 {
245     ASSERT(m_clients.contains(client));
246     m_clients.remove(client);
247
248     if (canDelete() && !inCache())
249         delete this;
250     else if (!hasClients() && inCache()) {
251         cache()->removeFromLiveResourcesSize(this);
252         cache()->removeFromLiveDecodedResourcesList(this);
253         allClientsRemoved();
254         if (response().cacheControlContainsNoStore()) {
255             // RFC2616 14.9.2:
256             // "no-store: ...MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
257             cache()->remove(this);
258         } else
259             cache()->prune();
260     }
261     // This object may be dead here.
262 }
263
264 void CachedResource::deleteIfPossible()
265 {
266     if (canDelete() && !inCache())
267         delete this;
268 }
269     
270 void CachedResource::setDecodedSize(unsigned size)
271 {
272     if (size == m_decodedSize)
273         return;
274
275     int delta = size - m_decodedSize;
276
277     // The object must now be moved to a different queue, since its size has been changed.
278     // We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
279     // queue.
280     if (inCache())
281         cache()->removeFromLRUList(this);
282     
283     m_decodedSize = size;
284    
285     if (inCache()) { 
286         // Now insert into the new LRU list.
287         cache()->insertInLRUList(this);
288         
289         // Insert into or remove from the live decoded list if necessary.
290         // When inserting into the LiveDecodedResourcesList it is possible
291         // that the m_lastDecodedAccessTime is still zero or smaller than
292         // the m_lastDecodedAccessTime of the current list head. This is a
293         // violation of the invariant that the list is to be kept sorted
294         // by access time. The weakening of the invariant does not pose
295         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
296         if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
297             cache()->insertInLiveDecodedResourcesList(this);
298         else if (!m_decodedSize && m_inLiveDecodedResourcesList)
299             cache()->removeFromLiveDecodedResourcesList(this);
300
301         // Update the cache's size totals.
302         cache()->adjustSize(hasClients(), delta);
303     }
304 }
305
306 void CachedResource::setEncodedSize(unsigned size)
307 {
308     if (size == m_encodedSize)
309         return;
310
311     // The size cannot ever shrink (unless it is being nulled out because of an error).  If it ever does, assert.
312     ASSERT(size == 0 || size >= m_encodedSize);
313     
314     int delta = size - m_encodedSize;
315
316     // The object must now be moved to a different queue, since its size has been changed.
317     // We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
318     // queue.
319     if (inCache())
320         cache()->removeFromLRUList(this);
321     
322     m_encodedSize = size;
323    
324     if (inCache()) { 
325         // Now insert into the new LRU list.
326         cache()->insertInLRUList(this);
327         
328         // Update the cache's size totals.
329         cache()->adjustSize(hasClients(), delta);
330     }
331 }
332
333 void CachedResource::didAccessDecodedData(double timeStamp)
334 {
335     m_lastDecodedAccessTime = timeStamp;
336     
337     if (inCache()) {
338         if (m_inLiveDecodedResourcesList) {
339             cache()->removeFromLiveDecodedResourcesList(this);
340             cache()->insertInLiveDecodedResourcesList(this);
341         }
342         cache()->prune();
343     }
344 }
345     
346 void CachedResource::setResourceToRevalidate(CachedResource* resource) 
347
348     ASSERT(resource);
349     ASSERT(!m_resourceToRevalidate);
350     ASSERT(resource != this);
351     ASSERT(m_handlesToRevalidate.isEmpty());
352     ASSERT(resource->type() == type());
353
354     LOG(ResourceLoading, "CachedResource %p setResourceToRevalidate %p", this, resource);
355
356     // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
357     // https://bugs.webkit.org/show_bug.cgi?id=28604.
358     // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in CachedResource::clearResourceToRevalidate.
359     ASSERT(!resource->m_proxyResource);
360
361     resource->m_proxyResource = this;
362     m_resourceToRevalidate = resource;
363 }
364
365 void CachedResource::clearResourceToRevalidate() 
366
367     ASSERT(m_resourceToRevalidate);
368     // A resource may start revalidation before this method has been called, so check that this resource is still the proxy resource before clearing it out.
369     if (m_resourceToRevalidate->m_proxyResource == this) {
370         m_resourceToRevalidate->m_proxyResource = 0;
371         m_resourceToRevalidate->deleteIfPossible();
372     }
373     m_handlesToRevalidate.clear();
374     m_resourceToRevalidate = 0;
375     deleteIfPossible();
376 }
377     
378 void CachedResource::switchClientsToRevalidatedResource()
379 {
380     ASSERT(m_resourceToRevalidate);
381     ASSERT(m_resourceToRevalidate->inCache());
382     ASSERT(!inCache());
383
384     LOG(ResourceLoading, "CachedResource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
385
386     HashSet<CachedResourceHandleBase*>::iterator end = m_handlesToRevalidate.end();
387     for (HashSet<CachedResourceHandleBase*>::iterator it = m_handlesToRevalidate.begin(); it != end; ++it) {
388         CachedResourceHandleBase* handle = *it;
389         handle->m_resource = m_resourceToRevalidate;
390         m_resourceToRevalidate->registerHandle(handle);
391         --m_handleCount;
392     }
393     ASSERT(!m_handleCount);
394     m_handlesToRevalidate.clear();
395
396     Vector<CachedResourceClient*> clientsToMove;
397     HashCountedSet<CachedResourceClient*>::iterator end2 = m_clients.end();
398     for (HashCountedSet<CachedResourceClient*>::iterator it = m_clients.begin(); it != end2; ++it) {
399         CachedResourceClient* client = it->first;
400         unsigned count = it->second;
401         while (count) {
402             clientsToMove.append(client);
403             --count;
404         }
405     }
406     // Equivalent of calling removeClient() for all clients
407     m_clients.clear();
408
409     unsigned moveCount = clientsToMove.size();
410     for (unsigned n = 0; n < moveCount; ++n)
411         m_resourceToRevalidate->addClientToSet(clientsToMove[n]);
412     for (unsigned n = 0; n < moveCount; ++n) {
413         // Calling didAddClient for a client may end up removing another client. In that case it won't be in the set anymore.
414         if (m_resourceToRevalidate->m_clients.contains(clientsToMove[n]))
415             m_resourceToRevalidate->didAddClient(clientsToMove[n]);
416     }
417 }
418     
419 void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
420 {
421     m_responseTimestamp = currentTime();
422
423     DEFINE_STATIC_LOCAL(const AtomicString, contentHeaderPrefix, ("content-"));
424     // RFC2616 10.3.5
425     // Update cached headers from the 304 response
426     const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields();
427     HTTPHeaderMap::const_iterator end = newHeaders.end();
428     for (HTTPHeaderMap::const_iterator it = newHeaders.begin(); it != end; ++it) {
429         // Don't allow 304 response to update content headers, these can't change but some servers send wrong values.
430         if (it->first.startsWith(contentHeaderPrefix, false))
431             continue;
432         m_response.setHTTPHeaderField(it->first, it->second);
433     }
434 }
435
436 void CachedResource::registerHandle(CachedResourceHandleBase* h)
437 {
438     ++m_handleCount;
439     if (m_resourceToRevalidate)
440         m_handlesToRevalidate.add(h);
441 }
442
443 void CachedResource::unregisterHandle(CachedResourceHandleBase* h)
444 {
445     ASSERT(m_handleCount > 0);
446     --m_handleCount;
447
448     if (m_resourceToRevalidate)
449          m_handlesToRevalidate.remove(h);
450
451     if (!m_handleCount)
452         deleteIfPossible();
453 }
454
455 bool CachedResource::canUseCacheValidator() const
456 {
457     if (m_loading || m_errorOccurred)
458         return false;
459
460     if (m_response.cacheControlContainsNoStore())
461         return false;
462
463     DEFINE_STATIC_LOCAL(const AtomicString, lastModifiedHeader, ("last-modified"));
464     DEFINE_STATIC_LOCAL(const AtomicString, eTagHeader, ("etag"));
465     return !m_response.httpHeaderField(lastModifiedHeader).isEmpty() || !m_response.httpHeaderField(eTagHeader).isEmpty();
466 }
467     
468 bool CachedResource::mustRevalidate(CachePolicy cachePolicy) const
469 {
470     if (m_errorOccurred) {
471         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_errorOccurred\n", this);
472         return true;
473     }
474
475     if (m_loading)
476         return false;
477     
478     if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
479         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
480         return true;
481     }
482
483     if (cachePolicy == CachePolicyCache) {
484         if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
485             LOG(ResourceLoading, "CachedResource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
486             return true;
487         }
488         return false;
489     }
490
491     if (isExpired()) {
492         LOG(ResourceLoading, "CachedResource %p mustRevalidate because of isExpired()\n", this);
493         return true;
494     }
495
496     return false;
497 }
498
499 bool CachedResource::isSafeToMakePurgeable() const
500
501     return !hasClients() && !m_proxyResource && !m_resourceToRevalidate;
502 }
503
504 bool CachedResource::makePurgeable(bool purgeable) 
505
506     if (purgeable) {
507         ASSERT(isSafeToMakePurgeable());
508
509         if (m_purgeableData) {
510             ASSERT(!m_data);
511             return true;
512         }
513         if (!m_data)
514             return false;
515         
516         // Should not make buffer purgeable if it has refs other than this since we don't want two copies.
517         if (!m_data->hasOneRef())
518             return false;
519         
520         // Purgeable buffers are allocated in multiples of the page size (4KB in common CPUs) so it does not make sense for very small buffers.
521         const size_t purgeableThreshold = 4 * 4096;
522         if (m_data->size() < purgeableThreshold)
523             return false;
524         
525         if (m_data->hasPurgeableBuffer()) {
526             m_purgeableData = m_data->releasePurgeableBuffer();
527         } else {
528             m_purgeableData = PurgeableBuffer::create(m_data->data(), m_data->size());
529             if (!m_purgeableData)
530                 return false;
531         }
532         
533         m_purgeableData->makePurgeable(true);
534         m_data.clear();
535         return true;
536     }
537
538     if (!m_purgeableData)
539         return true;
540     ASSERT(!m_data);
541     ASSERT(!hasClients());
542
543     if (!m_purgeableData->makePurgeable(false))
544         return false; 
545
546     m_data = SharedBuffer::adoptPurgeableBuffer(m_purgeableData.release());
547     return true;
548 }
549
550 bool CachedResource::isPurgeable() const
551 {
552     return m_purgeableData && m_purgeableData->isPurgeable();
553 }
554
555 bool CachedResource::wasPurged() const
556 {
557     return m_purgeableData && m_purgeableData->wasPurged();
558 }
559
560 unsigned CachedResource::overheadSize() const
561 {
562     return sizeof(CachedResource) + m_response.memoryUsage() + 576;
563     /*
564         576 = 192 +                   // average size of m_url
565               384;                    // average size of m_clients hash map
566     */
567 }
568
569 }