2 * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "ApplicationCacheHost.h"
29 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
31 #include "ApplicationCache.h"
32 #include "ApplicationCacheGroup.h"
33 #include "ApplicationCacheResource.h"
34 #include "DocumentLoader.h"
35 #include "DOMApplicationCache.h"
37 #include "FrameLoader.h"
38 #include "FrameLoaderClient.h"
39 #include "MainResourceLoader.h"
40 #include "ProgressEvent.h"
41 #include "ResourceLoader.h"
42 #include "ResourceRequest.h"
47 ApplicationCacheHost::ApplicationCacheHost(DocumentLoader* documentLoader)
48 : m_domApplicationCache(0)
49 , m_documentLoader(documentLoader)
50 , m_defersEvents(true)
51 , m_candidateApplicationCacheGroup(0)
53 ASSERT(m_documentLoader);
56 ApplicationCacheHost::~ApplicationCacheHost()
58 if (m_applicationCache)
59 m_applicationCache->group()->disassociateDocumentLoader(m_documentLoader);
60 else if (m_candidateApplicationCacheGroup)
61 m_candidateApplicationCacheGroup->disassociateDocumentLoader(m_documentLoader);
64 void ApplicationCacheHost::selectCacheWithoutManifest()
66 ApplicationCacheGroup::selectCacheWithoutManifestURL(m_documentLoader->frame());
69 void ApplicationCacheHost::selectCacheWithManifest(const KURL& manifestURL)
71 ApplicationCacheGroup::selectCache(m_documentLoader->frame(), manifestURL);
74 void ApplicationCacheHost::maybeLoadMainResource(ResourceRequest& request, SubstituteData& substituteData)
76 // Check if this request should be loaded from the application cache
77 if (!substituteData.isValid() && isApplicationCacheEnabled()) {
78 ASSERT(!m_mainResourceApplicationCache);
80 m_mainResourceApplicationCache = ApplicationCacheGroup::cacheForMainRequest(request, m_documentLoader);
82 if (m_mainResourceApplicationCache) {
83 // Get the resource from the application cache. By definition, cacheForMainRequest() returns a cache that contains the resource.
84 ApplicationCacheResource* resource = m_mainResourceApplicationCache->resourceForRequest(request);
85 substituteData = SubstituteData(resource->data(),
86 resource->response().mimeType(),
87 resource->response().textEncodingName(), KURL());
92 bool ApplicationCacheHost::maybeLoadFallbackForMainResponse(const ResourceRequest& request, const ResourceResponse& r)
94 if (r.httpStatusCode() / 100 == 4 || r.httpStatusCode() / 100 == 5) {
95 ASSERT(!m_mainResourceApplicationCache);
96 if (isApplicationCacheEnabled()) {
97 m_mainResourceApplicationCache = ApplicationCacheGroup::fallbackCacheForMainRequest(request, documentLoader());
99 if (scheduleLoadFallbackResourceFromApplicationCache(documentLoader()->mainResourceLoader(), m_mainResourceApplicationCache.get()))
106 bool ApplicationCacheHost::maybeLoadFallbackForMainError(const ResourceRequest& request, const ResourceError& error)
108 if (!error.isCancellation()) {
109 ASSERT(!m_mainResourceApplicationCache);
110 if (isApplicationCacheEnabled()) {
111 m_mainResourceApplicationCache = ApplicationCacheGroup::fallbackCacheForMainRequest(request, m_documentLoader);
113 if (scheduleLoadFallbackResourceFromApplicationCache(documentLoader()->mainResourceLoader(), m_mainResourceApplicationCache.get()))
120 void ApplicationCacheHost::mainResourceDataReceived(const char*, int, long long, bool)
122 // This method is here to facilitate alternate implemetations of this interface by the host browser.
125 void ApplicationCacheHost::failedLoadingMainResource()
127 ApplicationCacheGroup* group = m_candidateApplicationCacheGroup;
128 if (!group && m_applicationCache) {
129 ASSERT(!mainResourceApplicationCache()); // If the main resource were loaded from a cache, it wouldn't fail.
130 group = m_applicationCache->group();
134 group->failedLoadingMainResource(m_documentLoader);
137 void ApplicationCacheHost::finishedLoadingMainResource()
139 ApplicationCacheGroup* group = candidateApplicationCacheGroup();
140 if (!group && applicationCache() && !mainResourceApplicationCache())
141 group = applicationCache()->group();
144 group->finishedLoadingMainResource(m_documentLoader);
147 bool ApplicationCacheHost::maybeLoadResource(ResourceLoader* loader, ResourceRequest& request, const KURL& originalURL)
149 if (!isApplicationCacheEnabled())
152 if (request.url() != originalURL)
155 ApplicationCacheResource* resource;
156 if (!shouldLoadResourceFromApplicationCache(request, resource))
159 m_documentLoader->m_pendingSubstituteResources.set(loader, resource);
160 m_documentLoader->deliverSubstituteResourcesAfterDelay();
165 bool ApplicationCacheHost::maybeLoadFallbackForRedirect(ResourceLoader* resourceLoader, ResourceRequest& request, const ResourceResponse& redirectResponse)
167 if (!redirectResponse.isNull() && !protocolHostAndPortAreEqual(request.url(), redirectResponse.url()))
168 if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader))
173 bool ApplicationCacheHost::maybeLoadFallbackForResponse(ResourceLoader* resourceLoader, const ResourceResponse& response)
175 if (response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5)
176 if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader))
181 bool ApplicationCacheHost::maybeLoadFallbackForError(ResourceLoader* resourceLoader, const ResourceError& error)
183 if (!error.isCancellation())
184 if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader))
189 bool ApplicationCacheHost::maybeLoadSynchronously(ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data)
191 ApplicationCacheResource* resource;
192 if (shouldLoadResourceFromApplicationCache(request, resource)) {
194 response = resource->response();
195 data.append(resource->data()->data(), resource->data()->size());
197 error = documentLoader()->frameLoader()->client()->cannotShowURLError(request);
204 void ApplicationCacheHost::maybeLoadFallbackSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data)
206 // If normal loading results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code or equivalent,
207 // or if there were network errors (but not if the user canceled the download), then instead get, from the cache, the resource of the fallback entry
208 // corresponding to the matched namespace.
209 if ((!error.isNull() && !error.isCancellation())
210 || response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5
211 || !protocolHostAndPortAreEqual(request.url(), response.url())) {
212 ApplicationCacheResource* resource;
213 if (getApplicationCacheFallbackResource(request, resource)) {
214 response = resource->response();
216 data.append(resource->data()->data(), resource->data()->size());
221 bool ApplicationCacheHost::canCacheInPageCache() const
223 return !applicationCache() && !candidateApplicationCacheGroup();
226 void ApplicationCacheHost::setDOMApplicationCache(DOMApplicationCache* domApplicationCache)
228 ASSERT(!m_domApplicationCache || !domApplicationCache);
229 m_domApplicationCache = domApplicationCache;
232 void ApplicationCacheHost::notifyDOMApplicationCache(EventID id, int total, int done)
234 if (m_defersEvents) {
235 // Event dispatching is deferred until document.onload has fired.
236 m_deferredEvents.append(DeferredEvent(id, total, done));
239 dispatchDOMEvent(id, total, done);
242 void ApplicationCacheHost::stopDeferringEvents()
244 RefPtr<DocumentLoader> protect(documentLoader());
245 for (unsigned i = 0; i < m_deferredEvents.size(); ++i) {
246 const DeferredEvent& deferred = m_deferredEvents[i];
247 dispatchDOMEvent(deferred.eventID, deferred.progressTotal, deferred.progressDone);
249 m_deferredEvents.clear();
250 m_defersEvents = false;
253 #if ENABLE(INSPECTOR)
254 void ApplicationCacheHost::fillResourceList(ResourceInfoList* resources)
256 ApplicationCache* cache = applicationCache();
257 if (!cache || !cache->isComplete())
260 ApplicationCache::ResourceMap::const_iterator end = cache->end();
261 for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) {
262 RefPtr<ApplicationCacheResource> resource = it->second;
263 unsigned type = resource->type();
264 bool isMaster = type & ApplicationCacheResource::Master;
265 bool isManifest = type & ApplicationCacheResource::Manifest;
266 bool isExplicit = type & ApplicationCacheResource::Explicit;
267 bool isForeign = type & ApplicationCacheResource::Foreign;
268 bool isFallback = type & ApplicationCacheResource::Fallback;
269 resources->append(ResourceInfo(resource->url(), isMaster, isManifest, isFallback, isForeign, isExplicit, resource->estimatedSizeInStorage()));
273 ApplicationCacheHost::CacheInfo ApplicationCacheHost::applicationCacheInfo()
275 ApplicationCache* cache = applicationCache();
276 if (!cache || !cache->isComplete())
277 return CacheInfo(KURL(), 0, 0, 0);
279 // FIXME: Add "Creation Time" and "Update Time" to Application Caches.
280 return CacheInfo(cache->manifestResource()->url(), 0, 0, cache->estimatedSizeInStorage());
284 void ApplicationCacheHost::dispatchDOMEvent(EventID id, int total, int done)
286 if (m_domApplicationCache) {
287 const AtomicString& eventType = DOMApplicationCache::toEventType(id);
288 ExceptionCode ec = 0;
290 if (id == PROGRESS_EVENT)
291 event = ProgressEvent::create(eventType, true, done, total);
293 event = Event::create(eventType, false, false);
294 m_domApplicationCache->dispatchEvent(event, ec);
299 void ApplicationCacheHost::setCandidateApplicationCacheGroup(ApplicationCacheGroup* group)
301 ASSERT(!m_applicationCache);
302 m_candidateApplicationCacheGroup = group;
305 void ApplicationCacheHost::setApplicationCache(PassRefPtr<ApplicationCache> applicationCache)
307 if (m_candidateApplicationCacheGroup) {
308 ASSERT(!m_applicationCache);
309 m_candidateApplicationCacheGroup = 0;
312 m_applicationCache = applicationCache;
315 bool ApplicationCacheHost::shouldLoadResourceFromApplicationCache(const ResourceRequest& request, ApplicationCacheResource*& resource)
317 ApplicationCache* cache = applicationCache();
318 if (!cache || !cache->isComplete())
321 // If the resource is not to be fetched using the HTTP GET mechanism or equivalent, or if its URL has a different
322 // <scheme> component than the application cache's manifest, then fetch the resource normally.
323 if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request) || !equalIgnoringCase(request.url().protocol(), cache->manifestResource()->url().protocol()))
326 // If the resource's URL is an master entry, the manifest, an explicit entry, or a fallback entry
327 // in the application cache, then get the resource from the cache (instead of fetching it).
328 resource = cache->resourceForURL(request.url());
330 // Resources that match fallback namespaces or online whitelist entries are fetched from the network,
331 // unless they are also cached.
332 if (!resource && (cache->urlMatchesFallbackNamespace(request.url()) || cache->isURLInOnlineWhitelist(request.url())))
335 // Resources that are not present in the manifest will always fail to load (at least, after the
336 // cache has been primed the first time), making the testing of offline applications simpler.
340 bool ApplicationCacheHost::getApplicationCacheFallbackResource(const ResourceRequest& request, ApplicationCacheResource*& resource, ApplicationCache* cache)
343 cache = applicationCache();
347 if (!cache->isComplete())
350 // If the resource is not a HTTP/HTTPS GET, then abort
351 if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
355 if (!cache->urlMatchesFallbackNamespace(request.url(), &fallbackURL))
358 resource = cache->resourceForURL(fallbackURL);
364 bool ApplicationCacheHost::scheduleLoadFallbackResourceFromApplicationCache(ResourceLoader* loader, ApplicationCache* cache)
366 if (!isApplicationCacheEnabled())
369 ApplicationCacheResource* resource;
370 if (!getApplicationCacheFallbackResource(loader->request(), resource, cache))
373 m_documentLoader->m_pendingSubstituteResources.set(loader, resource);
374 m_documentLoader->deliverSubstituteResourcesAfterDelay();
376 loader->handle()->cancel();
381 ApplicationCacheHost::Status ApplicationCacheHost::status() const
383 ApplicationCache* cache = applicationCache();
387 switch (cache->group()->updateStatus()) {
388 case ApplicationCacheGroup::Checking:
390 case ApplicationCacheGroup::Downloading:
392 case ApplicationCacheGroup::Idle: {
393 if (cache->group()->isObsolete())
395 if (cache != cache->group()->newestCache())
401 ASSERT_NOT_REACHED();
405 bool ApplicationCacheHost::update()
407 ApplicationCache* cache = applicationCache();
410 cache->group()->update(m_documentLoader->frame(), ApplicationCacheUpdateWithoutBrowsingContext);
414 bool ApplicationCacheHost::swapCache()
416 ApplicationCache* cache = applicationCache();
420 // If the group of application caches to which cache belongs has the lifecycle status obsolete, unassociate document from cache.
421 if (cache->group()->isObsolete()) {
422 cache->group()->disassociateDocumentLoader(m_documentLoader);
426 // If there is no newer cache, raise an INVALID_STATE_ERR exception.
427 ApplicationCache* newestCache = cache->group()->newestCache();
428 if (cache == newestCache)
431 ASSERT(cache->group() == newestCache->group());
432 setApplicationCache(newestCache);
437 bool ApplicationCacheHost::isApplicationCacheEnabled()
439 return m_documentLoader->frame()->settings()
440 && m_documentLoader->frame()->settings()->offlineWebApplicationCacheEnabled();
443 } // namespace WebCore
445 #endif // ENABLE(OFFLINE_WEB_APPLICATIONS)