diff options
author | Feng Qian <fqian@google.com> | 2009-06-17 12:12:20 -0700 |
---|---|---|
committer | Feng Qian <fqian@google.com> | 2009-06-17 12:12:20 -0700 |
commit | 5f1ab04193ad0130ca8204aadaceae083aca9881 (patch) | |
tree | 5a92cd389e2cfe7fb67197ce14b38469462379f8 /WebCore/loader | |
parent | 194315e5a908cc8ed67d597010544803eef1ac59 (diff) | |
download | external_webkit-5f1ab04193ad0130ca8204aadaceae083aca9881.zip external_webkit-5f1ab04193ad0130ca8204aadaceae083aca9881.tar.gz external_webkit-5f1ab04193ad0130ca8204aadaceae083aca9881.tar.bz2 |
Get WebKit r44544.
Diffstat (limited to 'WebCore/loader')
40 files changed, 1150 insertions, 775 deletions
diff --git a/WebCore/loader/Cache.cpp b/WebCore/loader/Cache.cpp index 539c5fc..6eeba77 100644 --- a/WebCore/loader/Cache.cpp +++ b/WebCore/loader/Cache.cpp @@ -182,6 +182,7 @@ CachedCSSStyleSheet* Cache::requestUserCSSStyleSheet(DocLoader* docLoader, const void Cache::revalidateResource(CachedResource* resource, DocLoader* docLoader) { ASSERT(resource); + ASSERT(resource->inCache()); ASSERT(!disabled()); if (resource->resourceToRevalidate()) return; @@ -211,7 +212,7 @@ void Cache::revalidationSucceeded(CachedResource* revalidatingResource, const Re ASSERT(!m_resources.get(resource->url())); m_resources.set(resource->url(), resource); resource->setInCache(true); - resource->setExpirationDate(response.expirationDate()); + resource->updateResponseAfterRevalidation(response); insertInLRUList(resource); int delta = resource->size(); if (resource->decodedSize() && resource->hasClients()) @@ -391,15 +392,6 @@ void Cache::evict(CachedResource* resource) // The resource may have already been removed by someone other than our caller, // who needed a fresh copy for a reload. See <http://bugs.webkit.org/show_bug.cgi?id=12479#c6>. if (resource->inCache()) { - if (!resource->isCacheValidator()) { - // Notify all doc loaders that might be observing this object still that it has been - // extracted from the set of resources. - // No need to do this for cache validator resources, they are replaced automatically by using CachedResourceHandles. - HashSet<DocLoader*>::iterator end = m_docLoaders.end(); - for (HashSet<DocLoader*>::iterator itr = m_docLoaders.begin(); itr != end; ++itr) - (*itr)->removeCachedResource(resource); - } - // Remove from the resource map. m_resources.remove(resource->url()); resource->setInCache(false); diff --git a/WebCore/loader/CachedCSSStyleSheet.cpp b/WebCore/loader/CachedCSSStyleSheet.cpp index 1fb1a9180..11d1213 100644 --- a/WebCore/loader/CachedCSSStyleSheet.cpp +++ b/WebCore/loader/CachedCSSStyleSheet.cpp @@ -29,6 +29,7 @@ #include "CachedResourceClient.h" #include "CachedResourceClientWalker.h" +#include "HTTPParsers.h" #include "TextResourceDecoder.h" #include "loader.h" #include <wtf/Vector.h> @@ -131,8 +132,14 @@ bool CachedCSSStyleSheet::canUseSheet(bool enforceMIMEType) const if (!enforceMIMEType) return true; - // This check exactly matches Firefox. - String mimeType = response().mimeType(); + // This check exactly matches Firefox. Note that we grab the Content-Type + // header directly because we want to see what the value is BEFORE content + // sniffing. Firefox does this by setting a "type hint" on the channel. + // This implementation should be observationally equivalent. + // + // This code defaults to allowing the stylesheet for non-HTTP protocols so + // folks can use standards mode for local HTML documents. + String mimeType = extractMIMETypeFromMediaType(response().httpHeaderField("Content-Type")); return mimeType.isEmpty() || equalIgnoringCase(mimeType, "text/css") || equalIgnoringCase(mimeType, "application/x-unknown-content-type"); } diff --git a/WebCore/loader/CachedFont.h b/WebCore/loader/CachedFont.h index fd19cdb..e4414c6 100644 --- a/WebCore/loader/CachedFont.h +++ b/WebCore/loader/CachedFont.h @@ -39,10 +39,11 @@ namespace WebCore { class DocLoader; class Cache; -class FontCustomPlatformData; class FontPlatformData; class SVGFontElement; +struct FontCustomPlatformData; + class CachedFont : public CachedResource { public: CachedFont(const String& url); diff --git a/WebCore/loader/CachedImage.cpp b/WebCore/loader/CachedImage.cpp index 5e06eb4..eac02dc 100644 --- a/WebCore/loader/CachedImage.cpp +++ b/WebCore/loader/CachedImage.cpp @@ -53,6 +53,7 @@ CachedImage::CachedImage(const String& url) : CachedResource(url, ImageResource) , m_image(0) , m_decodedDataDeletionTimer(this, &CachedImage::decodedDataDeletionTimerFired) + , m_httpStatusCodeErrorOccurred(false) { m_status = Unknown; } @@ -61,6 +62,7 @@ CachedImage::CachedImage(Image* image) : CachedResource(String(), ImageResource) , m_image(image) , m_decodedDataDeletionTimer(this, &CachedImage::decodedDataDeletionTimerFired) + , m_httpStatusCodeErrorOccurred(false) { m_status = Cached; m_loading = false; @@ -312,6 +314,7 @@ void CachedImage::error() { clear(); m_errorOccurred = true; + m_data.clear(); notifyObservers(); m_loading = false; checkNotify(); diff --git a/WebCore/loader/CachedImage.h b/WebCore/loader/CachedImage.h index 9c3442f..22a3774 100644 --- a/WebCore/loader/CachedImage.h +++ b/WebCore/loader/CachedImage.h @@ -67,7 +67,10 @@ public: virtual void data(PassRefPtr<SharedBuffer> data, bool allDataReceived); virtual void error(); - + + virtual void httpStatusCodeError() { m_httpStatusCodeErrorOccurred = true; } + bool httpStatusCodeErrorOccurred() const { return m_httpStatusCodeErrorOccurred; } + virtual bool schedule() const { return true; } void checkNotify(); @@ -96,6 +99,7 @@ private: RefPtr<Image> m_image; Timer<CachedImage> m_decodedDataDeletionTimer; + bool m_httpStatusCodeErrorOccurred; }; } diff --git a/WebCore/loader/CachedResource.cpp b/WebCore/loader/CachedResource.cpp index b4ee533..a2eaa2c 100644 --- a/WebCore/loader/CachedResource.cpp +++ b/WebCore/loader/CachedResource.cpp @@ -32,7 +32,10 @@ #include "KURL.h" #include "PurgeableBuffer.h" #include "Request.h" +#include <wtf/CurrentTime.h> +#include <wtf/MathExtras.h> #include <wtf/RefCountedLeakCounter.h> +#include <wtf/StdLibExtras.h> #include <wtf/Vector.h> using namespace WTF; @@ -45,6 +48,7 @@ static RefCountedLeakCounter cachedResourceLeakCounter("CachedResource"); CachedResource::CachedResource(const String& url, Type type) : m_url(url) + , m_responseTimestamp(currentTime()) , m_lastDecodedAccessTime(0) , m_sendResourceLoadCallbacks(true) , m_preloadCount(0) @@ -56,7 +60,6 @@ CachedResource::CachedResource(const String& url, Type type) , m_handleCount(0) , m_resourceToRevalidate(0) , m_isBeingRevalidated(false) - , m_expirationDate(0) { #ifndef NDEBUG cachedResourceLeakCounter.increment(); @@ -115,16 +118,50 @@ void CachedResource::finish() bool CachedResource::isExpired() const { - if (!m_expirationDate) + if (m_response.isNull()) return false; - time_t now = time(0); - return difftime(now, m_expirationDate) >= 0; + + return currentAge() > freshnessLifetime(); +} + +double CachedResource::currentAge() const +{ + // RFC2616 13.2.3 + // No compensation for latency as that is not terribly important in practice + double dateValue = m_response.date(); + double apparentAge = isfinite(dateValue) ? max(0., m_responseTimestamp - dateValue) : 0; + double ageValue = m_response.age(); + double correctedReceivedAge = isfinite(ageValue) ? max(apparentAge, ageValue) : apparentAge; + double residentTime = currentTime() - m_responseTimestamp; + return correctedReceivedAge + residentTime; +} + +double CachedResource::freshnessLifetime() const +{ + // Cache non-http resources liberally + if (!m_response.url().protocolInHTTPFamily()) + return std::numeric_limits<double>::max(); + + // RFC2616 13.2.4 + double maxAgeValue = m_response.cacheControlMaxAge(); + if (isfinite(maxAgeValue)) + return maxAgeValue; + double expiresValue = m_response.expires(); + double dateValue = m_response.date(); + double creationTime = isfinite(dateValue) ? dateValue : m_responseTimestamp; + if (isfinite(expiresValue)) + return expiresValue - creationTime; + double lastModifiedValue = m_response.lastModified(); + if (isfinite(lastModifiedValue)) + return (creationTime - lastModifiedValue) * 0.1; + // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0. + return 0; } void CachedResource::setResponse(const ResourceResponse& response) { m_response = response; - m_expirationDate = response.expirationDate(); + m_responseTimestamp = currentTime(); } void CachedResource::setRequest(Request* request) @@ -258,7 +295,6 @@ void CachedResource::setResourceToRevalidate(CachedResource* resource) void CachedResource::clearResourceToRevalidate() { ASSERT(m_resourceToRevalidate); - ASSERT(m_resourceToRevalidate->m_isBeingRevalidated); m_resourceToRevalidate->m_isBeingRevalidated = false; m_resourceToRevalidate->deleteIfPossible(); m_handlesToRevalidate.clear(); @@ -269,6 +305,7 @@ void CachedResource::clearResourceToRevalidate() void CachedResource::switchClientsToRevalidatedResource() { ASSERT(m_resourceToRevalidate); + ASSERT(m_resourceToRevalidate->inCache()); ASSERT(!inCache()); HashSet<CachedResourceHandleBase*>::iterator end = m_handlesToRevalidate.end(); @@ -299,6 +336,23 @@ void CachedResource::switchClientsToRevalidatedResource() m_resourceToRevalidate->addClient(clientsToMove[n]); } +void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse) +{ + m_responseTimestamp = currentTime(); + + DEFINE_STATIC_LOCAL(const AtomicString, contentHeaderPrefix, ("content-")); + // RFC2616 10.3.5 + // Update cached headers from the 304 response + const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields(); + HTTPHeaderMap::const_iterator end = newHeaders.end(); + for (HTTPHeaderMap::const_iterator it = newHeaders.begin(); it != end; ++it) { + // Don't allow 304 response to update content headers, these can't change but some servers send wrong values. + if (it->first.startsWith(contentHeaderPrefix, false)) + continue; + m_response.setHTTPHeaderField(it->first, it->second); + } +} + bool CachedResource::canUseCacheValidator() const { return !m_loading && (!m_response.httpHeaderField("Last-Modified").isEmpty() || !m_response.httpHeaderField("ETag").isEmpty()); @@ -309,9 +363,9 @@ bool CachedResource::mustRevalidate(CachePolicy cachePolicy) const if (m_loading) return false; - // FIXME: Also look at max-age, min-fresh, max-stale in Cache-Control if (cachePolicy == CachePolicyCache) return m_response.cacheControlContainsNoCache() || (isExpired() && m_response.cacheControlContainsMustRevalidate()); + return isExpired() || m_response.cacheControlContainsNoCache(); } diff --git a/WebCore/loader/CachedResource.h b/WebCore/loader/CachedResource.h index 63c250b..16cce26 100644 --- a/WebCore/loader/CachedResource.h +++ b/WebCore/loader/CachedResource.h @@ -82,6 +82,7 @@ public: virtual String encoding() const { return String(); } virtual void data(PassRefPtr<SharedBuffer> data, bool allDataReceived) = 0; virtual void error() = 0; + virtual void httpStatusCodeError() { error(); } // Images keep loading in spite of HTTP errors (for legacy compat with <img>, etc.). const String &url() const { return m_url; } Type type() const { return m_type; } @@ -126,7 +127,8 @@ public: // Called by the cache if the object has been removed from the cache // while still being referenced. This means the object should delete itself // if the number of clients observing it ever drops to 0. - void setInCache(bool b) { m_inCache = b; } + // The resource can be brought back to cache after successful revalidation. + void setInCache(bool b) { m_inCache = b; if (b) m_isBeingRevalidated = false; } bool inCache() const { return m_inCache; } void setInLiveDecodedResourcesList(bool b) { m_inLiveDecodedResourcesList = b; } @@ -162,7 +164,7 @@ public: void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; } void registerHandle(CachedResourceHandleBase* h) { ++m_handleCount; if (m_resourceToRevalidate) m_handlesToRevalidate.add(h); } - void unregisterHandle(CachedResourceHandleBase* h) { --m_handleCount; if (m_resourceToRevalidate) m_handlesToRevalidate.remove(h); if (!m_handleCount) deleteIfPossible(); } + void unregisterHandle(CachedResourceHandleBase* h) { ASSERT(m_handleCount > 0); --m_handleCount; if (m_resourceToRevalidate) m_handlesToRevalidate.remove(h); if (!m_handleCount) deleteIfPossible(); } bool canUseCacheValidator() const; bool mustRevalidate(CachePolicy) const; @@ -172,12 +174,16 @@ public: bool isPurgeable() const; bool wasPurged() const; + // This is used by the archive machinery to get at a purged resource without + // triggering a load. We should make it protected again if we can find a + // better way to handle the archive case. + bool makePurgeable(bool purgeable); + protected: void setEncodedSize(unsigned); void setDecodedSize(unsigned); void didAccessDecodedData(double timeStamp); - bool makePurgeable(bool purgeable); bool isSafeToMakePurgeable() const; HashCountedSet<CachedResourceClient*> m_clients; @@ -187,6 +193,8 @@ protected: Request* m_request; ResourceResponse m_response; + double m_responseTimestamp; + RefPtr<SharedBuffer> m_data; OwnPtr<PurgeableBuffer> m_purgeableData; @@ -200,7 +208,10 @@ private: void setResourceToRevalidate(CachedResource*); void switchClientsToRevalidatedResource(); void clearResourceToRevalidate(); - void setExpirationDate(time_t expirationDate) { m_expirationDate = expirationDate; } + void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse); + + double currentAge() const; + double freshnessLifetime() const; unsigned m_encodedSize; unsigned m_decodedSize; @@ -217,7 +228,6 @@ private: protected: bool m_inCache; bool m_loading; - bool m_expireDateChanged; #ifndef NDEBUG bool m_deleted; unsigned m_lruIndex; @@ -241,8 +251,6 @@ private: bool m_isBeingRevalidated; // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response. HashSet<CachedResourceHandleBase*> m_handlesToRevalidate; - - time_t m_expirationDate; }; } diff --git a/WebCore/loader/DocLoader.cpp b/WebCore/loader/DocLoader.cpp index c96348d..7b62074 100644 --- a/WebCore/loader/DocLoader.cpp +++ b/WebCore/loader/DocLoader.cpp @@ -37,6 +37,7 @@ #include "CString.h" #include "Document.h" #include "DOMWindow.h" +#include "HTMLElement.h" #include "Frame.h" #include "FrameLoader.h" #include "loader.h" @@ -63,6 +64,9 @@ DocLoader::DocLoader(Document* doc) DocLoader::~DocLoader() { + if (m_requestCount) + m_cache->loader()->cancelRequests(this); + clearPreloads(); DocumentResourceMap::iterator end = m_documentResources.end(); for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != end; ++it) @@ -316,11 +320,16 @@ void DocLoader::setBlockNetworkImage(bool block) CachePolicy DocLoader::cachePolicy() const { - return frame() ? frame()->loader()->cachePolicy() : CachePolicyVerify; + return frame() ? frame()->loader()->subresourceCachePolicy() : CachePolicyVerify; } void DocLoader::removeCachedResource(CachedResource* resource) const { +#ifndef NDEBUG + DocumentResourceMap::iterator it = m_documentResources.find(resource->url()); + if (it != m_documentResources.end()) + ASSERT(it->second.get() == resource); +#endif m_documentResources.remove(resource->url()); } @@ -389,7 +398,9 @@ void DocLoader::checkForPendingPreloads() return; for (unsigned i = 0; i < count; ++i) { PendingPreload& preload = m_pendingPreloads[i]; - requestPreload(preload.m_type, preload.m_url, preload.m_charset); + // Don't request preload if the resource already loaded normally (this will result in double load if the page is being reloaded with cached results ignored). + if (!cachedResource(m_doc->completeURL(preload.m_url))) + requestPreload(preload.m_type, preload.m_url, preload.m_charset); } m_pendingPreloads.clear(); } diff --git a/WebCore/loader/DocumentLoader.cpp b/WebCore/loader/DocumentLoader.cpp index d0443e8..ffc61df 100644 --- a/WebCore/loader/DocumentLoader.cpp +++ b/WebCore/loader/DocumentLoader.cpp @@ -411,6 +411,10 @@ void DocumentLoader::setupForReplaceByMIMEType(const String& newMIMEType) void DocumentLoader::updateLoading() { + if (!m_frame) { + setLoading(false); + return; + } ASSERT(this == frameLoader()->activeDocumentLoader()); setLoading(frameLoader()->isLoading()); } @@ -556,13 +560,20 @@ PassRefPtr<ArchiveResource> DocumentLoader::subresource(const KURL& url) const if (!isCommitted()) return 0; - Document* doc = m_frame->document(); - - CachedResource* resource = doc->docLoader()->cachedResource(url); - if (!resource || resource->preloadResult() == CachedResource::PreloadReferenced) + CachedResource* resource = m_frame->document()->docLoader()->cachedResource(url); + if (!resource || !resource->isLoaded()) return archiveResourceForURL(url); - - return ArchiveResource::create(resource->data(), url, resource->response()); + + // FIXME: This has the side effect of making the resource non-purgeable. + // It would be better if it didn't have this permanent effect. + if (!resource->makePurgeable(false)) + return 0; + + RefPtr<SharedBuffer> data = resource->data(); + if (!data) + return 0; + + return ArchiveResource::create(data.release(), url, resource->response()); } void DocumentLoader::getSubresources(Vector<PassRefPtr<ArchiveResource> >& subresources) const diff --git a/WebCore/loader/DocumentThreadableLoader.cpp b/WebCore/loader/DocumentThreadableLoader.cpp index 685db8c..0de62ce 100644 --- a/WebCore/loader/DocumentThreadableLoader.cpp +++ b/WebCore/loader/DocumentThreadableLoader.cpp @@ -43,7 +43,7 @@ namespace WebCore { -void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client) +void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, StoredCredentials storedCredentials) { bool sameOriginRequest = document->securityOrigin()->canRequest(request.url()); @@ -52,7 +52,7 @@ void DocumentThreadableLoader::loadResourceSynchronously(Document* document, con ResourceResponse response; unsigned long identifier = std::numeric_limits<unsigned long>::max(); if (document->frame()) - identifier = document->frame()->loader()->loadResourceSynchronously(request, error, response, data); + identifier = document->frame()->loader()->loadResourceSynchronously(request, storedCredentials, error, response, data); // No exception for file:/// resources, see <rdar://problem/4962298>. // Also, if we have an HTTP response, then it wasn't a network error in fact. @@ -77,21 +77,26 @@ void DocumentThreadableLoader::loadResourceSynchronously(Document* document, con client.didFinishLoading(identifier); } -PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) { ASSERT(document); - RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, request, callbacksSetting, contentSniff)); + RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck)); if (!loader->m_loader) loader = 0; return loader.release(); } -DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) : m_client(client) , m_document(document) + , m_allowStoredCredentials(storedCredentials == AllowStoredCredentials) + , m_sameOriginRequest(document->securityOrigin()->canRequest(request.url())) + , m_checkRedirectOrigin(redirectOriginCheck == RequireSameRedirectOrigin) { ASSERT(document); ASSERT(client); + ASSERT(storedCredentials == AllowStoredCredentials || storedCredentials == DoNotAllowStoredCredentials); + ASSERT(redirectOriginCheck == RequireSameRedirectOrigin || redirectOriginCheck == AllowDifferentRedirectOrigin); m_loader = SubresourceLoader::create(document->frame(), this, request, false, callbacksSetting == SendLoadCallbacks, contentSniff == SniffContent); } @@ -112,52 +117,85 @@ void DocumentThreadableLoader::cancel() m_client = 0; } -void DocumentThreadableLoader::willSendRequest(SubresourceLoader*, ResourceRequest& request, const ResourceResponse&) +void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse&) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); // FIXME: This needs to be fixed to follow the redirect correctly even for cross-domain requests. - if (!m_document->securityOrigin()->canRequest(request.url())) { + if (m_checkRedirectOrigin && !m_document->securityOrigin()->canRequest(request.url())) { RefPtr<DocumentThreadableLoader> protect(this); m_client->didFailRedirectCheck(); - cancel(); + request = ResourceRequest(); } } -void DocumentThreadableLoader::didSendData(SubresourceLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) +void DocumentThreadableLoader::didSendData(SubresourceLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didSendData(bytesSent, totalBytesToBeSent); } -void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader*, const ResourceResponse& response) +void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didReceiveResponse(response); } -void DocumentThreadableLoader::didReceiveData(SubresourceLoader*, const char* data, int lengthReceived) +void DocumentThreadableLoader::didReceiveData(SubresourceLoader* loader, const char* data, int lengthReceived) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didReceiveData(data, lengthReceived); } void DocumentThreadableLoader::didFinishLoading(SubresourceLoader* loader) { - ASSERT(loader); + ASSERT(loader == m_loader); ASSERT(m_client); m_client->didFinishLoading(loader->identifier()); } -void DocumentThreadableLoader::didFail(SubresourceLoader*, const ResourceError& error) +void DocumentThreadableLoader::didFail(SubresourceLoader* loader, const ResourceError& error) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didFail(error); } -void DocumentThreadableLoader::receivedCancellation(SubresourceLoader*, const AuthenticationChallenge& challenge) +bool DocumentThreadableLoader::getShouldUseCredentialStorage(SubresourceLoader* loader, bool& shouldUseCredentialStorage) +{ + ASSERT_UNUSED(loader, loader == m_loader); + + if (!m_allowStoredCredentials) { + shouldUseCredentialStorage = false; + return true; + } + + return false; // Only FrameLoaderClient can ultimately permit credential use. +} + +void DocumentThreadableLoader::didReceiveAuthenticationChallenge(SubresourceLoader* loader, const AuthenticationChallenge&) +{ + ASSERT(loader == m_loader); + // Users are not prompted for credentials for cross-origin requests. + if (!m_sameOriginRequest) { + RefPtr<DocumentThreadableLoader> protect(this); + m_client->didFail(loader->blockedError()); + cancel(); + } +} + +void DocumentThreadableLoader::receivedCancellation(SubresourceLoader* loader, const AuthenticationChallenge& challenge) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); m_client->didReceiveAuthenticationCancellation(challenge.failureResponse()); } diff --git a/WebCore/loader/DocumentThreadableLoader.h b/WebCore/loader/DocumentThreadableLoader.h index ddf8570..079c725 100644 --- a/WebCore/loader/DocumentThreadableLoader.h +++ b/WebCore/loader/DocumentThreadableLoader.h @@ -44,8 +44,8 @@ namespace WebCore { class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private SubresourceLoaderClient { public: - static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&); - static PassRefPtr<DocumentThreadableLoader> create(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff); + static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&, StoredCredentials); + static PassRefPtr<DocumentThreadableLoader> create(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); virtual ~DocumentThreadableLoader(); virtual void cancel(); @@ -58,7 +58,7 @@ namespace WebCore { virtual void derefThreadableLoader() { deref(); } private: - DocumentThreadableLoader(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff); + DocumentThreadableLoader(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); virtual void willSendRequest(SubresourceLoader*, ResourceRequest&, const ResourceResponse& redirectResponse); virtual void didSendData(SubresourceLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent); @@ -67,11 +67,16 @@ namespace WebCore { virtual void didFinishLoading(SubresourceLoader*); virtual void didFail(SubresourceLoader*, const ResourceError&); + virtual bool getShouldUseCredentialStorage(SubresourceLoader*, bool& shouldUseCredentialStorage); + virtual void didReceiveAuthenticationChallenge(SubresourceLoader*, const AuthenticationChallenge&); virtual void receivedCancellation(SubresourceLoader*, const AuthenticationChallenge&); RefPtr<SubresourceLoader> m_loader; ThreadableLoaderClient* m_client; Document* m_document; + bool m_allowStoredCredentials; + bool m_sameOriginRequest; + bool m_checkRedirectOrigin; }; } // namespace WebCore diff --git a/WebCore/loader/EmptyClients.h b/WebCore/loader/EmptyClients.h index 4d75b7a..f6916ef 100644 --- a/WebCore/loader/EmptyClients.h +++ b/WebCore/loader/EmptyClients.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2006 Eric Seidel (eric@webkit.org) + * Copyright (C) 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,12 +29,14 @@ #include "ChromeClient.h" #include "ContextMenuClient.h" -#include "DragClient.h" +#include "Console.h" #include "DocumentLoader.h" +#include "DragClient.h" #include "EditCommand.h" #include "EditorClient.h" -#include "FocusDirection.h" #include "FloatRect.h" +#include "FocusDirection.h" +#include "FormState.h" #include "FrameLoaderClient.h" #include "InspectorClient.h" #include "ResourceError.h" @@ -92,7 +95,7 @@ public: virtual void setResizable(bool) { } - virtual void addMessageToConsole(const String&, unsigned, const String&) { } + virtual void addMessageToConsole(MessageSource, MessageLevel, const String&, unsigned, const String&) { } virtual bool canRunBeforeUnloadConfirmPanel() { return false; } virtual bool runBeforeUnloadConfirmPanel(const String&, Frame*) { return true; } @@ -133,6 +136,14 @@ public: virtual void runOpenPanel(Frame*, PassRefPtr<FileChooser>) { } virtual void formStateDidChange(const Node*) { } + + virtual PassOwnPtr<HTMLParserQuirks> createHTMLParserQuirks() { return 0; } + + virtual bool setCursor(PlatformCursorHandle) { return false; } + + virtual void scrollRectIntoView(const IntRect&, const ScrollView*) const {} + + virtual void requestGeolocationPermissionForFrame(Frame*, Geolocation*) {} }; class EmptyFrameLoaderClient : public FrameLoaderClient { @@ -163,6 +174,7 @@ public: virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long) { } virtual void dispatchDidFailLoading(DocumentLoader*, unsigned long, const ResourceError&) { } virtual bool dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int) { return false; } + virtual void dispatchDidLoadResourceByXMLHttpRequest(unsigned long, const ScriptString&) { } virtual void dispatchDidHandleOnloadEvents() { } virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() { } @@ -347,12 +359,31 @@ public: virtual NSArray* pasteboardTypesForSelection(Frame*) { return 0; } #endif #endif +#if PLATFORM(MAC) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) + virtual void uppercaseWord() { } + virtual void lowercaseWord() { } + virtual void capitalizeWord() { } + virtual void showSubstitutionsPanel(bool) { } + virtual bool substitutionsPanelIsShowing() { return false; } + virtual void toggleSmartInsertDelete() { } + virtual bool isAutomaticQuoteSubstitutionEnabled() { return false; } + virtual void toggleAutomaticQuoteSubstitution() { } + virtual bool isAutomaticLinkDetectionEnabled() { return false; } + virtual void toggleAutomaticLinkDetection() { } + virtual bool isAutomaticDashSubstitutionEnabled() { return false; } + virtual void toggleAutomaticDashSubstitution() { } + virtual bool isAutomaticTextReplacementEnabled() { return false; } + virtual void toggleAutomaticTextReplacement() { } + virtual bool isAutomaticSpellingCorrectionEnabled() { return false; } + virtual void toggleAutomaticSpellingCorrection() { } +#endif virtual void ignoreWordInSpellDocument(const String&) { } virtual void learnWord(const String&) { } virtual void checkSpellingOfString(const UChar*, int, int*, int*) { } + virtual String getAutoCorrectSuggestionForMisspelledWord(const String&) { return String(); } virtual void checkGrammarOfString(const UChar*, int, Vector<GrammarDetail>&, int*, int*) { } #if PLATFORM(MAC) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) - virtual void checkSpellingAndGrammarOfParagraph(const UChar*, int, bool, Vector<TextCheckingResult>&) { } + virtual void checkTextOfParagraph(const UChar*, int, uint64_t, Vector<TextCheckingResult>&) { }; #endif virtual void updateSpellingUIWithGrammarString(const String&, const GrammarDetail&) { } virtual void updateSpellingUIWithMisspelledWord(const String&) { } @@ -428,3 +459,4 @@ public: } #endif // EmptyClients_h + diff --git a/WebCore/loader/FTPDirectoryDocument.cpp b/WebCore/loader/FTPDirectoryDocument.cpp index 188c84c..ace4cfe 100644 --- a/WebCore/loader/FTPDirectoryDocument.cpp +++ b/WebCore/loader/FTPDirectoryDocument.cpp @@ -235,7 +235,11 @@ static struct tm *localTimeQt(const time_t *const timep, struct tm *result) #define localtime_r(x, y) localTimeQt(x, y) #elif PLATFORM(WIN_OS) && !defined(localtime_r) +#if defined(_MSC_VER) && (_MSC_VER >= 1400) #define localtime_r(x, y) localtime_s((y), (x)) +#else /* !_MSC_VER */ +#define localtime_r(x,y) (localtime(x)?(*(y)=*localtime(x),(y)):0) +#endif #endif static String processFileDateString(const FTPTime& fileTime) diff --git a/WebCore/loader/FTPDirectoryParser.cpp b/WebCore/loader/FTPDirectoryParser.cpp index 8c76e97..6573fb6 100644 --- a/WebCore/loader/FTPDirectoryParser.cpp +++ b/WebCore/loader/FTPDirectoryParser.cpp @@ -50,7 +50,11 @@ static struct tm *gmtimeQt(const time_t *const timep, struct tm *result) #define gmtime_r(x, y) gmtimeQt(x, y) #elif PLATFORM(WIN_OS) && !defined(gmtime_r) +#if defined(_MSC_VER) && (_MSC_VER >= 1400) #define gmtime_r(x, y) gmtime_s((y), (x)) +#else /* !_MSC_VER */ +#define gmtime_r(x,y) (gmtime(x)?(*(y)=*gmtime(x),(y)):0) +#endif #endif FTPEntryType parseOneFTPLine(const char* line, ListState& state, ListResult& result) diff --git a/WebCore/loader/FormState.cpp b/WebCore/loader/FormState.cpp index c55b8ac..bd37086 100644 --- a/WebCore/loader/FormState.cpp +++ b/WebCore/loader/FormState.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,16 +34,16 @@ namespace WebCore { -PassRefPtr<FormState> FormState::create(PassRefPtr<HTMLFormElement> form, const HashMap<String, String>& values, PassRefPtr<Frame> sourceFrame) +inline FormState::FormState(PassRefPtr<HTMLFormElement> form, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Frame> sourceFrame) + : m_form(form) + , m_sourceFrame(sourceFrame) { - return adoptRef(new FormState(form, values, sourceFrame)); + m_textFieldValues.swap(textFieldValuesToAdopt); } -FormState::FormState(PassRefPtr<HTMLFormElement> form, const HashMap<String, String>& values, PassRefPtr<Frame> sourceFrame) - : m_form(form) - , m_values(values) - , m_sourceFrame(sourceFrame) +PassRefPtr<FormState> FormState::create(PassRefPtr<HTMLFormElement> form, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Frame> sourceFrame) { + return adoptRef(new FormState(form, textFieldValuesToAdopt, sourceFrame)); } } diff --git a/WebCore/loader/FormState.h b/WebCore/loader/FormState.h index 5370e8a..03317b1 100644 --- a/WebCore/loader/FormState.h +++ b/WebCore/loader/FormState.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,28 +29,28 @@ #ifndef FormState_h #define FormState_h -#include <wtf/RefCounted.h> -#include "StringHash.h" -#include <wtf/HashMap.h> +#include "PlatformString.h" namespace WebCore { class Frame; class HTMLFormElement; + typedef Vector<std::pair<String, String> > StringPairVector; + class FormState : public RefCounted<FormState> { public: - static PassRefPtr<FormState> create(PassRefPtr<HTMLFormElement> form, const HashMap<String, String>& values, PassRefPtr<Frame> sourceFrame); + static PassRefPtr<FormState> create(PassRefPtr<HTMLFormElement>, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Frame>); HTMLFormElement* form() const { return m_form.get(); } - const HashMap<String, String>& values() const { return m_values; } + const StringPairVector& textFieldValues() const { return m_textFieldValues; } Frame* sourceFrame() const { return m_sourceFrame.get(); } private: - FormState(PassRefPtr<HTMLFormElement> form, const HashMap<String, String>& values, PassRefPtr<Frame> sourceFrame); + FormState(PassRefPtr<HTMLFormElement>, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Frame>); RefPtr<HTMLFormElement> m_form; - HashMap<String, String> m_values; + StringPairVector m_textFieldValues; RefPtr<Frame> m_sourceFrame; }; diff --git a/WebCore/loader/FrameLoader.cpp b/WebCore/loader/FrameLoader.cpp index e5ce94a..88beb24 100644 --- a/WebCore/loader/FrameLoader.cpp +++ b/WebCore/loader/FrameLoader.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) + * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -83,6 +83,7 @@ #include "ResourceRequest.h" #include "ScriptController.h" #include "ScriptSourceCode.h" +#include "ScriptString.h" #include "ScriptValue.h" #include "SecurityOrigin.h" #include "SegmentedString.h" @@ -154,45 +155,22 @@ static URLSchemesMap& noAccessSchemes() return noAccessSchemes; } -struct FormSubmission { - FormSubmission(const char* action, const String& url, PassRefPtr<FormData> formData, - const String& target, const String& contentType, const String& boundary, - PassRefPtr<Event> event, bool lockHistory, bool lockBackForwardList) - : action(action) - , url(url) - , formData(formData) - , target(target) - , contentType(contentType) - , boundary(boundary) - , event(event) - , lockHistory(lockHistory) - , lockBackForwardList(lockBackForwardList) - { - } - - const char* action; - String url; - RefPtr<FormData> formData; - String target; - String contentType; - String boundary; - RefPtr<Event> event; - bool lockHistory; - bool lockBackForwardList; -}; - struct ScheduledRedirection { - enum Type { redirection, locationChange, historyNavigation, locationChangeDuringLoad }; + enum Type { redirection, locationChange, historyNavigation, formSubmission }; const Type type; const double delay; const String url; const String referrer; + const FrameLoadRequest frameRequest; + const RefPtr<Event> event; + const RefPtr<FormState> formState; const int historySteps; const bool lockHistory; const bool lockBackForwardList; const bool wasUserGesture; const bool wasRefresh; + const bool wasDuringLoad; ScheduledRedirection(double delay, const String& url, bool lockHistory, bool lockBackForwardList, bool wasUserGesture, bool refresh) : type(redirection) @@ -203,12 +181,13 @@ struct ScheduledRedirection { , lockBackForwardList(lockBackForwardList) , wasUserGesture(wasUserGesture) , wasRefresh(refresh) + , wasDuringLoad(false) { ASSERT(!url.isEmpty()); } - ScheduledRedirection(Type locationChangeType, const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool wasUserGesture, bool refresh) - : type(locationChangeType) + ScheduledRedirection(const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool wasUserGesture, bool refresh, bool duringLoad) + : type(locationChange) , delay(0) , url(url) , referrer(referrer) @@ -217,8 +196,8 @@ struct ScheduledRedirection { , lockBackForwardList(lockBackForwardList) , wasUserGesture(wasUserGesture) , wasRefresh(refresh) + , wasDuringLoad(duringLoad) { - ASSERT(locationChangeType == locationChange || locationChangeType == locationChangeDuringLoad); ASSERT(!url.isEmpty()); } @@ -230,10 +209,35 @@ struct ScheduledRedirection { , lockBackForwardList(false) , wasUserGesture(false) , wasRefresh(false) + , wasDuringLoad(false) { } -}; + ScheduledRedirection(const FrameLoadRequest& frameRequest, + bool lockHistory, bool lockBackForwardList, PassRefPtr<Event> event, PassRefPtr<FormState> formState, + bool duringLoad) + : type(formSubmission) + , delay(0) + , frameRequest(frameRequest) + , event(event) + , formState(formState) + , historySteps(0) + , lockHistory(lockHistory) + , lockBackForwardList(lockBackForwardList) + , wasUserGesture(false) + , wasRefresh(false) + , wasDuringLoad(duringLoad) + { + ASSERT(!frameRequest.isEmpty()); + ASSERT(this->formState); + } +}; + +#if ENABLE(XHTMLMP) +static const char defaultAcceptHeader[] = "application/xml,application/vnd.wap.xhtml+xml,application/xhtml+xml;profile='http://www.wapforum.org/xhtml',text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; +#else +static const char defaultAcceptHeader[] = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; +#endif static double storedTimeOfLastCompletedLoad; static FrameLoader::LocalLoadPolicy localLoadPolicy = FrameLoader::AllowLocalLoadsForLocalOnly; @@ -282,11 +286,11 @@ FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client) , m_quickRedirectComing(false) , m_sentRedirectNotification(false) , m_inStopAllLoaders(false) - , m_navigationDuringLoad(false) , m_isExecutingJavaScriptFormAction(false) , m_isRunningScript(false) , m_didCallImplicitClose(false) , m_wasUnloadEventEmitted(false) + , m_unloadEventBeingDispatched(false) , m_isComplete(false) , m_isLoadingMainResource(false) , m_cancellingWithLoadInProgress(false) @@ -358,7 +362,7 @@ Frame* FrameLoader::createWindow(FrameLoader* frameLoaderForFrameLookup, const F Frame* frame = frameLoaderForFrameLookup->frame()->tree()->find(request.frameName()); if (frame && shouldAllowNavigation(frame)) { if (!request.resourceRequest().url().isEmpty()) - frame->loader()->loadFrameRequestWithFormAndValues(request, false, false, 0, 0, HashMap<String, String>()); + frame->loader()->loadFrameRequest(request, false, false, 0, 0); if (Page* page = frame->page()) page->chrome()->focus(); created = false; @@ -416,11 +420,6 @@ bool FrameLoader::canHandleRequest(const ResourceRequest& request) return m_client->canHandleRequest(request); } -void FrameLoader::changeLocation(const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool userGesture, bool refresh) -{ - changeLocation(completeURL(url), referrer, lockHistory, lockBackForwardList, userGesture, refresh); -} - void FrameLoader::changeLocation(const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool userGesture, bool refresh) { RefPtr<Frame> protect(m_frame); @@ -436,22 +435,12 @@ void FrameLoader::changeLocation(const KURL& url, const String& referrer, bool l urlSelected(request, "_self", 0, lockHistory, lockBackForwardList, userGesture); } -void FrameLoader::urlSelected(const FrameLoadRequest& request, Event* event, bool lockHistory, bool lockBackForwardList) -{ - FrameLoadRequest copy = request; - if (copy.resourceRequest().httpReferrer().isEmpty()) - copy.resourceRequest().setHTTPReferrer(m_outgoingReferrer); - addHTTPOriginIfNeeded(copy.resourceRequest(), outgoingOrigin()); - - loadFrameRequestWithFormAndValues(copy, lockHistory, lockBackForwardList, event, 0, HashMap<String, String>()); -} - -void FrameLoader::urlSelected(const ResourceRequest& request, const String& _target, Event* triggeringEvent, bool lockHistory, bool lockBackForwardList, bool userGesture) +void FrameLoader::urlSelected(const ResourceRequest& request, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, bool userGesture) { if (executeIfJavaScriptURL(request.url(), userGesture, false)) return; - String target = _target; + String target = passedTarget; if (target.isEmpty()) target = m_frame->document()->baseTarget(); @@ -460,7 +449,11 @@ void FrameLoader::urlSelected(const ResourceRequest& request, const String& _tar frameRequest.setWasUserGesture(userGesture); #endif - urlSelected(frameRequest, triggeringEvent, lockHistory, lockBackForwardList); + if (frameRequest.resourceRequest().httpReferrer().isEmpty()) + frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer); + addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin()); + + loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0); } bool FrameLoader::requestFrame(HTMLFrameOwnerElement* ownerElement, const String& urlString, const AtomicString& frameName) @@ -468,7 +461,7 @@ bool FrameLoader::requestFrame(HTMLFrameOwnerElement* ownerElement, const String // Support for <frame src="javascript:string"> KURL scriptURL; KURL url; - if (protocolIs(urlString, "javascript")) { + if (protocolIsJavaScript(urlString)) { scriptURL = completeURL(urlString); // completeURL() encodes the URL. url = blankURL(); } else @@ -507,8 +500,7 @@ Frame* FrameLoader::loadSubframe(HTMLFrameOwnerElement* ownerElement, const KURL } bool hideReferrer = shouldHideReferrer(url, referrer); - RefPtr<Frame> frame = m_client->createFrame(url, name, ownerElement, hideReferrer ? String() : referrer, - allowsScrolling, marginWidth, marginHeight); + RefPtr<Frame> frame = m_client->createFrame(url, name, ownerElement, hideReferrer ? String() : referrer, allowsScrolling, marginWidth, marginHeight); if (!frame) { checkCallImplicitClose(); @@ -538,47 +530,61 @@ Frame* FrameLoader::loadSubframe(HTMLFrameOwnerElement* ownerElement, const KURL return frame.get(); } -void FrameLoader::submitFormAgain() -{ - if (m_isRunningScript) - return; - OwnPtr<FormSubmission> form(m_deferredFormSubmission.release()); - if (!form) - return; - submitForm(form->action, form->url, form->formData, form->target, form->contentType, form->boundary, form->event.get(), form->lockHistory, form->lockBackForwardList); -} - void FrameLoader::submitForm(const char* action, const String& url, PassRefPtr<FormData> formData, - const String& target, const String& contentType, const String& boundary, Event* event, bool lockHistory, bool lockBackForwardList) + const String& target, const String& contentType, const String& boundary, + bool lockHistory, bool lockBackForwardList, PassRefPtr<Event> event, PassRefPtr<FormState> formState) { + ASSERT(action); + ASSERT(strcmp(action, "GET") == 0 || strcmp(action, "POST") == 0); ASSERT(formData); + ASSERT(formState); + ASSERT(formState->sourceFrame() == m_frame); if (!m_frame->page()) return; KURL u = completeURL(url.isNull() ? "" : url); - // FIXME: Do we really need to special-case an empty URL? - // Would it be better to just go on with the form submisson and let the I/O fail? if (u.isEmpty()) return; - if (u.protocolIs("javascript")) { + if (protocolIsJavaScript(u)) { m_isExecutingJavaScriptFormAction = true; executeIfJavaScriptURL(u, false, false); m_isExecutingJavaScriptFormAction = false; return; } - if (m_isRunningScript) { - if (m_deferredFormSubmission) - return; - m_deferredFormSubmission.set(new FormSubmission(action, url, formData, target, contentType, boundary, event, lockHistory, lockBackForwardList)); + FrameLoadRequest frameRequest; + + String targetOrBaseTarget = target.isEmpty() ? m_frame->document()->baseTarget() : target; + Frame* targetFrame = findFrameForNavigation(targetOrBaseTarget); + if (!targetFrame) { + targetFrame = m_frame; + frameRequest.setFrameName(targetOrBaseTarget); + } + if (!targetFrame->page()) return; + + // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way. + + // We do not want to submit more than one form from the same page, nor do we want to submit a single + // form more than once. This flag prevents these from happening; not sure how other browsers prevent this. + // The flag is reset in each time we start handle a new mouse or key down event, and + // also in setView since this part may get reused for a page from the back/forward cache. + // The form multi-submit logic here is only needed when we are submitting a form that affects this frame. + + // FIXME: Frame targeting is only one of the ways the submission could end up doing something other + // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly + // needed any more now that we reset m_submittedFormURL on each mouse or key down event. + + if (m_frame->tree()->isDescendantOf(targetFrame)) { + if (m_submittedFormURL == u) + return; + m_submittedFormURL = u; } formData->generateFiles(m_frame->page()->chrome()->client()); - FrameLoadRequest frameRequest; #ifdef ANDROID_USER_GESTURE frameRequest.setWasUserGesture(userGestureHint()); #endif @@ -586,25 +592,11 @@ void FrameLoader::submitForm(const char* action, const String& url, PassRefPtr<F if (!m_outgoingReferrer.isEmpty()) frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer); - frameRequest.setFrameName(target.isEmpty() ? m_frame->document()->baseTarget() : target); - - // Handle mailto: forms - bool isMailtoForm = equalIgnoringCase(u.protocol(), "mailto"); - if (isMailtoForm && strcmp(action, "GET") != 0) { - // Append body= for POST mailto, replace the whole query string for GET one. - String body = formData->flattenToString(); - String query = u.query(); - if (!query.isEmpty()) - query.append('&'); - u.setQuery(query + body); - } - - if (strcmp(action, "GET") == 0) { + if (strcmp(action, "GET") == 0) u.setQuery(formData->flattenToString()); - } else { - if (!isMailtoForm) - frameRequest.resourceRequest().setHTTPBody(formData.get()); + else { frameRequest.resourceRequest().setHTTPMethod("POST"); + frameRequest.resourceRequest().setHTTPBody(formData); // construct some user headers if necessary if (contentType.isNull() || contentType == "application/x-www-form-urlencoded") @@ -616,7 +608,20 @@ void FrameLoader::submitForm(const char* action, const String& url, PassRefPtr<F frameRequest.resourceRequest().setURL(u); addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin()); - submitForm(frameRequest, event, lockHistory, lockBackForwardList); + // Navigation of a subframe during loading of the main frame does not create a new back/forward item. + // Strangely, we only implement this rule for form submission; time will tell if we need it for other types of navigation. + // The definition of "during load" is any time before the load event has been handled. + // See https://bugs.webkit.org/show_bug.cgi?id=14957 for the original motivation for this. + if (Page* targetPage = targetFrame->page()) { + Frame* mainFrame = targetPage->mainFrame(); + if (mainFrame != targetFrame) { + Document* document = mainFrame->document(); + if (!mainFrame->loader()->isComplete() || (document && document->processingLoadEvent())) + lockBackForwardList = true; + } + } + + targetFrame->loader()->scheduleFormSubmission(frameRequest, lockHistory, lockBackForwardList, event, formState); } void FrameLoader::stopLoading(bool sendUnload, DatabasePolicy databasePolicy) @@ -630,18 +635,19 @@ void FrameLoader::stopLoading(bool sendUnload, DatabasePolicy databasePolicy) Node* currentFocusedNode = m_frame->document()->focusedNode(); if (currentFocusedNode) currentFocusedNode->aboutToUnload(); - m_frame->document()->dispatchWindowEvent(eventNames().unloadEvent, false, false); + m_unloadEventBeingDispatched = true; + if (m_frame->domWindow()) + m_frame->domWindow()->dispatchUnloadEvent(); + m_unloadEventBeingDispatched = false; if (m_frame->document()) - m_frame->document()->updateRendering(); + m_frame->document()->updateStyleIfNeeded(); m_wasUnloadEventEmitted = true; - if (m_frame->eventHandler()->pendingFrameUnloadEventCount()) - m_frame->eventHandler()->clearPendingFrameUnloadEventCount(); - if (m_frame->eventHandler()->pendingFrameBeforeUnloadEventCount()) - m_frame->eventHandler()->clearPendingFrameBeforeUnloadEventCount(); } } + + // Dispatching the unload event could have made m_frame->document() null. if (m_frame->document() && !m_frame->document()->inPageCache()) - m_frame->document()->removeAllEventListenersFromAllNodes(); + m_frame->document()->removeAllEventListeners(); } m_isComplete = true; // to avoid calling completed() in finishedParsing() (David) @@ -714,7 +720,7 @@ KURL FrameLoader::iconURL() return KURL(m_frame->document()->iconURL()); // Don't return a favicon iconURL unless we're http or https - if (!m_URL.protocolIs("http") && !m_URL.protocolIs("https")) + if (!m_URL.protocolInHTTPFamily()) return KURL(); KURL url; @@ -728,10 +734,11 @@ KURL FrameLoader::iconURL() bool FrameLoader::didOpenURL(const KURL& url) { - if (m_scheduledRedirection && m_scheduledRedirection->type == ScheduledRedirection::locationChangeDuringLoad) + if (m_scheduledRedirection && m_scheduledRedirection->wasDuringLoad) { // A redirect was scheduled before the document was created. // This can happen when one frame changes another frame's location. return false; + } cancelRedirection(); m_frame->editor()->clearLastEditCommand(); @@ -741,11 +748,15 @@ bool FrameLoader::didOpenURL(const KURL& url) m_isLoadingMainResource = true; m_didCallImplicitClose = false; - m_frame->setJSStatusBarText(String()); - m_frame->setJSDefaultStatusBarText(String()); - + // If we are still in the process of initializing an empty document then + // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText + // since it may cause clients to attempt to render the frame. + if (!m_creatingInitialEmptyDocument) { + m_frame->setJSStatusBarText(String()); + m_frame->setJSDefaultStatusBarText(String()); + } m_URL = url; - if ((m_URL.protocolIs("http") || m_URL.protocolIs("https")) && !m_URL.host().isEmpty() && m_URL.path().isEmpty()) + if (m_URL.protocolInHTTPFamily() && !m_URL.host().isEmpty() && m_URL.path().isEmpty()) m_URL.setPath("/"); m_workingURL = m_URL; @@ -773,9 +784,12 @@ void FrameLoader::didExplicitOpen() bool FrameLoader::executeIfJavaScriptURL(const KURL& url, bool userGesture, bool replaceDocument) { - if (!url.protocolIs("javascript")) + if (!protocolIsJavaScript(url)) return false; + if (m_frame->page() && !m_frame->page()->javaScriptURLsAreAllowed()) + return true; + String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:"))); ScriptValue result = executeScript(script, userGesture); @@ -816,8 +830,7 @@ ScriptValue FrameLoader::executeScript(const ScriptSourceCode& sourceCode) if (!wasRunningScript) { m_isRunningScript = false; - submitFormAgain(); - Document::updateDocumentsRendering(); + Document::updateStyleForAllDocuments(); } return result; @@ -896,10 +909,12 @@ void FrameLoader::receivedFirstData() dispatchDidCommitLoad(); dispatchWindowObjectAvailable(); - String ptitle = m_documentLoader->title(); - // If we have a title let the WebView know about it. - if (!ptitle.isNull()) - m_client->dispatchDidReceiveTitle(ptitle); + if (m_documentLoader) { + String ptitle = m_documentLoader->title(); + // If we have a title let the WebView know about it. + if (!ptitle.isNull()) + m_client->dispatchDidReceiveTitle(ptitle); + } m_workingURL = KURL(); @@ -979,7 +994,7 @@ void FrameLoader::begin(const KURL& url, bool dispatch, SecurityOrigin* origin) m_frame->domWindow()->setURL(document->url()); m_frame->domWindow()->setSecurityOrigin(document->securityOrigin()); - updatePolicyBaseURL(); + updateFirstPartyForCookies(); Settings* settings = document->settings(); document->docLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically()); @@ -1351,12 +1366,6 @@ KURL FrameLoader::baseURL() const return m_frame->document()->baseURL(); } -String FrameLoader::baseTarget() const -{ - ASSERT(m_frame->document()); - return m_frame->document()->baseTarget(); -} - KURL FrameLoader::completeURL(const String& url) { ASSERT(m_frame->document()); @@ -1401,7 +1410,7 @@ void FrameLoader::scheduleLocationChange(const String& url, const String& referr // fragment part, we don't need to schedule the location change. KURL parsedURL(url); if (parsedURL.hasRef() && equalIgnoringRef(m_URL, parsedURL)) { - changeLocation(url, referrer, lockHistory, lockBackForwardList, wasUserGesture); + changeLocation(completeURL(url), referrer, lockHistory, lockBackForwardList, wasUserGesture); return; } @@ -1409,18 +1418,23 @@ void FrameLoader::scheduleLocationChange(const String& url, const String& referr // This may happen when a frame changes the location of another frame. bool duringLoad = !m_committedFirstRealDocumentLoad; - // If a redirect was scheduled during a load, then stop the current load. - // Otherwise when the current load transitions from a provisional to a - // committed state, pending redirects may be cancelled. - if (duringLoad) { - if (m_provisionalDocumentLoader) - m_provisionalDocumentLoader->stopLoading(); - stopLoading(true); - } + scheduleRedirection(new ScheduledRedirection(url, referrer, lockHistory, lockBackForwardList, wasUserGesture, false, duringLoad)); +} - ScheduledRedirection::Type type = duringLoad - ? ScheduledRedirection::locationChangeDuringLoad : ScheduledRedirection::locationChange; - scheduleRedirection(new ScheduledRedirection(type, url, referrer, lockHistory, lockBackForwardList, wasUserGesture, false)); +void FrameLoader::scheduleFormSubmission(const FrameLoadRequest& frameRequest, + bool lockHistory, bool lockBackForwardList, PassRefPtr<Event> event, PassRefPtr<FormState> formState) +{ + ASSERT(m_frame->page()); + ASSERT(!frameRequest.isEmpty()); + + // FIXME: Do we need special handling for form submissions where the URL is the same + // as the current one except for the fragment part? See scheduleLocationChange above. + + // Handle a location change of a page with no document as a special case. + // This may happen when a frame changes the location of another frame. + bool duringLoad = !m_committedFirstRealDocumentLoad; + + scheduleRedirection(new ScheduledRedirection(frameRequest, lockHistory, lockBackForwardList, event, formState, duringLoad)); } void FrameLoader::scheduleRefresh(bool wasUserGesture) @@ -1431,8 +1445,7 @@ void FrameLoader::scheduleRefresh(bool wasUserGesture) if (m_URL.isEmpty()) return; - ScheduledRedirection::Type type = ScheduledRedirection::locationChange; - scheduleRedirection(new ScheduledRedirection(type, m_URL.string(), m_outgoingReferrer, true, true, wasUserGesture, true)); + scheduleRedirection(new ScheduledRedirection(m_URL.string(), m_outgoingReferrer, true, true, wasUserGesture, true, false)); } bool FrameLoader::isLocationChange(const ScheduledRedirection& redirection) @@ -1442,7 +1455,7 @@ bool FrameLoader::isLocationChange(const ScheduledRedirection& redirection) return false; case ScheduledRedirection::historyNavigation: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: + case ScheduledRedirection::formSubmission: return true; } ASSERT_NOT_REACHED(); @@ -1460,18 +1473,6 @@ void FrameLoader::scheduleHistoryNavigation(int steps) return; } - // If the steps to navigate is not zero (which needs to force a reload), and if we think the navigation is going to be a fragment load - // (when the URL we're going to navigate to is the same as the current one, except for the fragment part - but not exactly the same because that's a reload), - // then we don't need to schedule the navigation. - if (steps != 0) { - KURL destination = historyURL(steps); - // FIXME: This doesn't seem like a reliable way to tell whether or not the load will be a fragment load. - if (equalIgnoringRef(m_URL, destination) && m_URL != destination) { - goBackOrForward(steps); - return; - } - } - scheduleRedirection(new ScheduledRedirection(steps)); } @@ -1514,8 +1515,7 @@ void FrameLoader::redirectionTimerFired(Timer<FrameLoader>*) switch (redirection->type) { case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: - changeLocation(redirection->url, redirection->referrer, + changeLocation(KURL(redirection->url), redirection->referrer, redirection->lockHistory, redirection->lockBackForwardList, redirection->wasUserGesture, redirection->wasRefresh); return; case ScheduledRedirection::historyNavigation: @@ -1528,17 +1528,21 @@ void FrameLoader::redirectionTimerFired(Timer<FrameLoader>*) // in both IE and NS (but not in Mozilla). We can't easily do that. goBackOrForward(redirection->historySteps); return; + case ScheduledRedirection::formSubmission: + // The submitForm function will find a target frame before using the redirection timer. + // Now that the timer has fired, we need to repeat the security check which normally is done when + // selecting a target, in case conditions have changed. Other code paths avoid this by targeting + // without leaving a time window. If we fail the check just silently drop the form submission. + if (!redirection->formState->sourceFrame()->loader()->shouldAllowNavigation(m_frame)) + return; + loadFrameRequest(redirection->frameRequest, redirection->lockHistory, redirection->lockBackForwardList, + redirection->event, redirection->formState); + return; } ASSERT_NOT_REACHED(); } -/* - In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree. - The item that was the target of the user's navigation is designated as the "targetItem". - When this method is called with doClip=YES we're able to create the whole tree except for the target's children, - which will be loaded in the future. That part of the tree will be filled out as the child loads are committed. -*/ void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame) { ASSERT(childFrame); @@ -1552,14 +1556,14 @@ void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, // If we're moving in the back/forward list, we might want to replace the content // of this child frame with whatever was there at that point. if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType)) { - HistoryItem* childItem = parentItem->childItemWithName(childFrame->tree()->name()); + HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->name()); if (childItem) { // Use the original URL to ensure we get all the side-effects, such as // onLoad handlers, of any redirects that happened. An example of where // this is needed is Radar 3213556. workingURL = KURL(childItem->originalURLString()); childLoadType = loadType; - childFrame->loader()->setProvisionalHistoryItem(childItem); + childFrame->loader()->m_provisionalHistoryItem = childItem; } } @@ -1570,11 +1574,7 @@ void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, childFrame->loader()->loadArchive(subframeArchive.release()); else #endif -#ifdef ANDROID_USER_GESTURE - childFrame->loader()->loadURL(workingURL, referer, String(), false, childLoadType, 0, 0, false); -#else childFrame->loader()->loadURL(workingURL, referer, String(), false, childLoadType, 0, 0); -#endif } #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size @@ -1654,7 +1654,7 @@ bool FrameLoader::gotoAnchor(const String& name) // We need to update the layout before scrolling, otherwise we could // really mess things up if an anchor scroll comes at a bad moment. - m_frame->document()->updateRendering(); + m_frame->document()->updateStyleIfNeeded(); // Only do a layout if changes have occurred that make it necessary. if (m_frame->view() && m_frame->contentRenderer() && m_frame->contentRenderer()->needsLayout()) m_frame->view()->layout(); @@ -1672,8 +1672,11 @@ bool FrameLoader::gotoAnchor(const String& name) #ifdef ANDROID_SCROLL_ON_GOTO_ANCHOR android::WebFrame::getWebFrame(m_frame)->setUserInitiatedClick(true); #endif - if (renderer) + if (renderer) { renderer->enclosingLayer()->scrollRectToVisible(rect, true, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways); + if (m_frame->view()) + m_frame->view()->setLockedToAnchor(true); + } #ifdef ANDROID_SCROLL_ON_GOTO_ANCHOR android::WebFrame::getWebFrame(m_frame)->setUserInitiatedClick(false); #endif @@ -1760,9 +1763,9 @@ bool FrameLoader::loadPlugin(RenderPart* renderer, const KURL& url, const String return false; } - widget = m_client->createPlugin(IntSize(renderer->contentWidth(), renderer->contentHeight()), + widget = m_client->createPlugin(IntSize(renderer->contentWidth(), renderer->contentHeight()), element, url, paramNames, paramValues, mimeType, - m_frame->document()->isPluginDocument()); + m_frame->document()->isPluginDocument() && !m_containsPlugIns); if (widget) { renderer->setWidget(widget); m_containsPlugIns = true; @@ -1772,22 +1775,6 @@ bool FrameLoader::loadPlugin(RenderPart* renderer, const KURL& url, const String return widget != 0; } -void FrameLoader::clearRecordedFormValues() -{ - m_formAboutToBeSubmitted = 0; - m_formValuesAboutToBeSubmitted.clear(); -} - -void FrameLoader::setFormAboutToBeSubmitted(PassRefPtr<HTMLFormElement> element) -{ - m_formAboutToBeSubmitted = element; -} - -void FrameLoader::recordFormValue(const String& name, const String& value) -{ - m_formValuesAboutToBeSubmitted.set(name, value); -} - void FrameLoader::parentCompleted() { if (m_scheduledRedirection && !m_redirectionTimer.isActive()) @@ -1842,22 +1829,11 @@ void FrameLoader::handleFallbackContent() } void FrameLoader::provisionalLoadStarted() -{ +{ #ifdef ANDROID_INSTRUMENT if (!m_frame->tree()->parent()) android::TimeCounter::reset(); #endif - - Page* page = m_frame->page(); - - // this is used to update the current history item - // in the event of a navigation aytime during loading - m_navigationDuringLoad = false; - if (page) { - Document *document = page->mainFrame()->document(); - m_navigationDuringLoad = !page->mainFrame()->loader()->isComplete() || (document && document->processingLoadEvent()); - } - m_firstLayoutDone = false; cancelRedirection(true); m_client->provisionalLoadStarted(); @@ -1871,12 +1847,6 @@ bool FrameLoader::userGestureHint() return frame->script()->processingUserGesture(); // FIXME: Use pageIsProcessingUserGesture. } -void FrameLoader::didNotOpenURL(const KURL& url) -{ - if (m_submittedFormURL == url) - m_submittedFormURL = KURL(); -} - void FrameLoader::resetMultipleFormSubmissionProtection() { m_submittedFormURL = KURL(); @@ -1910,13 +1880,13 @@ bool FrameLoader::canCachePageContainingThisFrame() // the right NPObjects. See <rdar://problem/5197041> for more information. && !m_containsPlugIns && !m_URL.protocolIs("https") - && !m_frame->document()->hasWindowEventListener(eventNames().unloadEvent) + && (!m_frame->domWindow() || !m_frame->domWindow()->hasEventListener(eventNames().unloadEvent)) #if ENABLE(DATABASE) && !m_frame->document()->hasOpenDatabases() #endif && !m_frame->document()->usingGeolocation() && m_currentHistoryItem - && !isQuickRedirectComing() + && !m_quickRedirectComing && !m_documentLoader->isLoadingInAPISense() && !m_documentLoader->isStopping() && m_frame->document()->canSuspendActiveDOMObjects() @@ -2052,7 +2022,7 @@ bool FrameLoader::logCanCacheFrameDecision(int indentLevel) { PCLOG(" -Frame contains plugins"); cannotCache = true; } if (m_URL.protocolIs("https")) { PCLOG(" -Frame is HTTPS"); cannotCache = true; } - if (m_frame->document()->hasWindowEventListener(eventNames().unloadEvent)) + if (m_frame->domWindow() && m_frame->domWindow()->hasEventListener(eventNames().unloadEvent)) { PCLOG(" -Frame has an unload event listener"); cannotCache = true; } #if ENABLE(DATABASE) if (m_frame->document()->hasOpenDatabases()) @@ -2062,7 +2032,7 @@ bool FrameLoader::logCanCacheFrameDecision(int indentLevel) { PCLOG(" -Frame uses Geolocation"); cannotCache = true; } if (!m_currentHistoryItem) { PCLOG(" -No current history item"); cannotCache = true; } - if (isQuickRedirectComing()) + if (m_quickRedirectComing) { PCLOG(" -Quick redirect is coming"); cannotCache = true; } if (m_documentLoader->isLoadingInAPISense()) { PCLOG(" -DocumentLoader is still loading in API sense"); cannotCache = true; } @@ -2091,19 +2061,19 @@ bool FrameLoader::logCanCacheFrameDecision(int indentLevel) } #endif -void FrameLoader::updatePolicyBaseURL() +void FrameLoader::updateFirstPartyForCookies() { if (m_frame->tree()->parent()) - setPolicyBaseURL(m_frame->tree()->parent()->document()->policyBaseURL()); + setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies()); else - setPolicyBaseURL(m_URL); + setFirstPartyForCookies(m_URL); } -void FrameLoader::setPolicyBaseURL(const KURL& url) +void FrameLoader::setFirstPartyForCookies(const KURL& url) { - m_frame->document()->setPolicyBaseURL(url); + m_frame->document()->setFirstPartyForCookies(url); for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) - child->loader()->setPolicyBaseURL(url); + child->loader()->setFirstPartyForCookies(url); } // This does the same kind of work that didOpenURL does, except it relies on the fact @@ -2133,6 +2103,15 @@ void FrameLoader::scheduleRedirection(ScheduledRedirection* redirection) { ASSERT(m_frame->page()); + // If a redirect was scheduled during a load, then stop the current load. + // Otherwise when the current load transitions from a provisional to a + // committed state, pending redirects may be cancelled. + if (redirection->wasDuringLoad) { + if (m_provisionalDocumentLoader) + m_provisionalDocumentLoader->stopLoading(); + stopLoading(true); + } + stopRedirectionTimer(); m_scheduledRedirection.set(redirection); if (!m_isComplete && redirection->type != ScheduledRedirection::redirection) @@ -2150,14 +2129,17 @@ void FrameLoader::startRedirectionTimer() m_redirectionTimer.startOneShot(m_scheduledRedirection->delay); switch (m_scheduledRedirection->type) { - case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: + case ScheduledRedirection::redirection: clientRedirected(KURL(m_scheduledRedirection->url), m_scheduledRedirection->delay, currentTime() + m_redirectionTimer.nextFireInterval(), - m_scheduledRedirection->lockBackForwardList, - m_isExecutingJavaScriptFormAction); + m_scheduledRedirection->lockBackForwardList); + return; + case ScheduledRedirection::formSubmission: + // FIXME: It would make sense to report form submissions as client redirects too. + // But we didn't do that in the past when form submission used a separate delay + // mechanism, so doing it will be a behavior change. return; case ScheduledRedirection::historyNavigation: // Don't report history navigations. @@ -2175,11 +2157,15 @@ void FrameLoader::stopRedirectionTimer() if (m_scheduledRedirection) { switch (m_scheduledRedirection->type) { - case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: + case ScheduledRedirection::redirection: clientRedirectCancelledOrFinished(m_cancellingWithLoadInProgress); return; + case ScheduledRedirection::formSubmission: + // FIXME: It would make sense to report form submissions as client redirects too. + // But we didn't do that in the past when form submission used a separate delay + // mechanism, so doing it will be a behavior change. + return; case ScheduledRedirection::historyNavigation: // Don't report history navigations. return; @@ -2195,7 +2181,8 @@ void FrameLoader::completed() child->loader()->parentCompleted(); if (Frame* parent = m_frame->tree()->parent()) parent->loader()->checkCompleted(); - submitFormAgain(); + if (m_frame->view()) + m_frame->view()->setLockedToAnchor(false); } void FrameLoader::started() @@ -2229,13 +2216,24 @@ void FrameLoader::setupForReplaceByMIMEType(const String& newMIMEType) activeDocumentLoader()->setupForReplaceByMIMEType(newMIMEType); } -void FrameLoader::loadFrameRequestWithFormAndValues(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList, Event* event, - HTMLFormElement* submitForm, const HashMap<String, String>& formValues) +// This is a hack to allow keep navigation to http/https feeds working. To remove this +// we need to introduce new API akin to registerURLSchemeAsLocal, that registers a +// protocols navigation policy. +static bool isFeedWithNestedProtocolInHTTPFamily(const KURL& url) { - RefPtr<FormState> formState; - if (submitForm) - formState = FormState::create(submitForm, formValues, m_frame); - + const String& urlString = url.string(); + if (!urlString.startsWith("feed", false)) + return false; + + return urlString.startsWith("feed://", false) + || urlString.startsWith("feed:http:", false) || urlString.startsWith("feed:https:", false) + || urlString.startsWith("feeds:http:", false) || urlString.startsWith("feeds:https:", false) + || urlString.startsWith("feedsearch:http:", false) || urlString.startsWith("feedsearch:https:", false); +} + +void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList, + PassRefPtr<Event> event, PassRefPtr<FormState> formState) +{ KURL url = request.resourceRequest().url(); String referrer; @@ -2246,7 +2244,7 @@ void FrameLoader::loadFrameRequestWithFormAndValues(const FrameLoadRequest& requ referrer = m_outgoingReferrer; ASSERT(frame()->document()); - if (url.protocolIs("file")) { + if (shouldTreatURLAsLocal(url.string()) && !isFeedWithNestedProtocolInHTTPFamily(url)) { if (!canLoad(url, String(), frame()->document()) && !canLoad(url, referrer)) { FrameLoader::reportLocalLoadFailed(m_frame, url.string()); return; @@ -2265,30 +2263,37 @@ void FrameLoader::loadFrameRequestWithFormAndValues(const FrameLoadRequest& requ loadType = FrameLoadTypeStandard; if (request.resourceRequest().httpMethod() == "POST") -#ifdef ANDROID_USER_GESTURE - loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.release(), request.wasUserGesture()); -#else - loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.release()); -#endif + loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get()); else -#ifdef ANDROID_USER_GESTURE - loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.release(), request.wasUserGesture()); -#else - loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.release()); -#endif + loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get()); - Frame* targetFrame = findFrameForNavigation(request.frameName()); - if (targetFrame && targetFrame != m_frame) + // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual + // load if frame names have changed. + Frame* sourceFrame = formState ? formState->sourceFrame() : m_frame; + Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName()); + if (targetFrame && targetFrame != sourceFrame) { if (Page* page = targetFrame->page()) page->chrome()->focus(); + } } #ifdef ANDROID_USER_GESTURE +void FrameLoader::loadPostRequest(const ResourceRequest& request, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType type, PassRefPtr<Event> event, PassRefPtr<FormState> state) +{ + loadPostRequest(request, referrer, frameName, lockHistory, type, event, state, false); +} + +void FrameLoader::loadURL(const KURL& url, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType type, PassRefPtr<Event> event, PassRefPtr<FormState> state) +{ + loadURL(url, referrer, frameName, lockHistory, type, event, state, false); +} + void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType, - Event* event, PassRefPtr<FormState> prpFormState, bool userGesture) + PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState, + bool userGesture) #else void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType, - Event* event, PassRefPtr<FormState> prpFormState) + PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState) #endif { RefPtr<FormState> formState = prpFormState; @@ -2309,17 +2314,17 @@ void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const Stri ASSERT(newLoadType != FrameLoadTypeSame); + // The search for a target frame is done earlier in the case of form submission. + Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName); + if (targetFrame && targetFrame != m_frame) { + targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState.release()); + return; + } + NavigationAction action(newURL, newLoadType, isFormSubmission, event); - if (!frameName.isEmpty()) { - if (Frame* targetFrame = findFrameForNavigation(frameName)) -#ifdef ANDROID_USER_GESTURE - targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState, userGesture); -#else - targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState); -#endif - else - checkNewWindowPolicy(action, request, formState, frameName); + if (!targetFrame && !frameName.isEmpty()) { + checkNewWindowPolicy(action, request, formState.release(), frameName); return; } @@ -2333,12 +2338,12 @@ void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const Stri if (shouldScrollToAnchor(isFormSubmission, newLoadType, newURL)) { oldDocumentLoader->setTriggeringAction(action); stopPolicyCheck(); - checkNavigationPolicy(request, oldDocumentLoader.get(), formState, + checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(), callContinueFragmentScrollAfterNavigationPolicy, this); } else { // must grab this now, since this load may stop the previous load and clear this flag bool isRedirect = m_quickRedirectComing; - loadWithNavigationAction(request, action, lockHistory, newLoadType, formState); + loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release()); if (isRedirect) { m_quickRedirectComing = false; if (m_provisionalDocumentLoader) @@ -2457,6 +2462,8 @@ void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType t stopPolicyCheck(); setPolicyDocumentLoader(loader); + if (loader->triggeringAction().isEmpty()) + loader->setTriggeringAction(NavigationAction(newURL, m_policyLoadType, isFormSubmission)); checkNavigationPolicy(loader->request(), loader, formState, callContinueLoadAfterNavigationPolicy, this); @@ -2465,18 +2472,22 @@ void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType t bool FrameLoader::canLoad(const KURL& url, const String& referrer, const Document* doc) { - // We can always load any URL that isn't considered local (e.g. http URLs) + return canLoad(url, referrer, doc ? doc->securityOrigin() : 0); +} + +bool FrameLoader::canLoad(const KURL& url, const String& referrer, const SecurityOrigin* securityOrigin) +{ + // We can always load any URL that isn't considered local (e.g. http URLs). if (!shouldTreatURLAsLocal(url.string())) return true; // If we were provided a document, we let its local file policy dictate the result, // otherwise we allow local loads only if the supplied referrer is also local. - if (doc) - return doc->securityOrigin()->canLoadLocalResources(); - else if (!referrer.isEmpty()) + if (securityOrigin) + return securityOrigin->canLoadLocalResources(); + if (!referrer.isEmpty()) return shouldTreatURLAsLocal(referrer); - else - return false; + return false; } void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url) @@ -2716,6 +2727,9 @@ void FrameLoader::stopLoadingSubframes() void FrameLoader::stopAllLoaders(DatabasePolicy databasePolicy) { + if (m_unloadEventBeingDispatched) + return; + // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this. if (m_inStopAllLoaders) return; @@ -3038,7 +3052,7 @@ void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgres m_sentRedirectNotification = false; } -void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList, bool isJavaScriptFormAction) +void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList) { m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate); @@ -3046,10 +3060,11 @@ void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireD // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame: m_sentRedirectNotification = true; - // If a "quick" redirect comes in an, we set a special mode so we treat the next - // load as part of the same navigation. If we don't have a document loader, we have + // If a "quick" redirect comes in, we set a special mode so we treat the next + // load as part of the original navigation. If we don't have a document loader, we have // no "original" load on which to base a redirect, so we treat the redirect as a normal load. - m_quickRedirectComing = lockBackForwardList && m_documentLoader && !isJavaScriptFormAction; + // Loads triggered by JavaScript form submissions never count as quick redirects. + m_quickRedirectComing = lockBackForwardList && m_documentLoader && !m_isExecutingJavaScriptFormAction; } #if ENABLE(WML) @@ -3120,7 +3135,7 @@ void FrameLoader::open(CachedFrame& cachedFrame) KURL url = cachedFrame.url(); - if ((url.protocolIs("http") || url.protocolIs("https")) && !url.host().isEmpty() && url.path().isEmpty()) + if (url.protocolInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty()) url.setPath("/"); m_URL = url; @@ -3154,7 +3169,7 @@ void FrameLoader::open(CachedFrame& cachedFrame) m_decoder = document->decoder(); - updatePolicyBaseURL(); + updateFirstPartyForCookies(); cachedFrame.restore(); } @@ -3250,10 +3265,20 @@ void FrameLoader::finishedLoadingDocument(DocumentLoader* loader) ArchiveResource* mainResource = archive->mainResource(); loader->setParsedArchiveData(mainResource->data()); - continueLoadWithData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), mainResource->url()); + + m_responseMIMEType = mainResource->mimeType(); + didOpenURL(mainResource->url()); + + String userChosenEncoding = documentLoader()->overrideEncoding(); + bool encodingIsUserChosen = !userChosenEncoding.isNull(); + setEncoding(encodingIsUserChosen ? userChosenEncoding : mainResource->textEncoding(), encodingIsUserChosen); + + ASSERT(m_frame->document()); + + addData(mainResource->data()->data(), mainResource->data()->size()); #else m_client->finishedLoading(loader); -#endif +#endif // ARCHIVE } bool FrameLoader::isReplacing() const @@ -3296,20 +3321,28 @@ FrameLoadType FrameLoader::loadType() const return m_loadType; } -CachePolicy FrameLoader::cachePolicy() const +CachePolicy FrameLoader::subresourceCachePolicy() const { if (m_isComplete) return CachePolicyVerify; - - if (m_loadType == FrameLoadTypeReloadFromOrigin || documentLoader()->request().cachePolicy() == ReloadIgnoringCacheData) + + if (m_loadType == FrameLoadTypeReloadFromOrigin) return CachePolicyReload; - + if (Frame* parentFrame = m_frame->tree()->parent()) { - CachePolicy parentCachePolicy = parentFrame->loader()->cachePolicy(); + CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy(); if (parentCachePolicy != CachePolicyVerify) return parentCachePolicy; } + // FIXME: POST documents are always Reloads, but their subresources should still be Revalidate. + // If we bring the CachePolicy.h and ResourceRequest cache policy enums in sync with each other and + // remember "Revalidate" in ResourceRequests, we can remove this "POST" check and return either "Reload" + // or "Revalidate" if the DocumentLoader was requested with either. + const ResourceRequest& request(documentLoader()->request()); + if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post")) + return CachePolicyRevalidate; + if (m_loadType == FrameLoadTypeReload) return CachePolicyRevalidate; @@ -3349,7 +3382,7 @@ void FrameLoader::checkLoadCompleteForThisFrame() item = m_currentHistoryItem; bool shouldReset = true; - if (!pdl->isLoadingInAPISense()) { + if (!(pdl->isLoadingInAPISense() && !pdl->isStopping())) { m_delegateIsHandlingProvisionalLoadError = true; m_client->dispatchDidFailProvisionalLoad(error); m_delegateIsHandlingProvisionalLoadError = false; @@ -3381,7 +3414,7 @@ void FrameLoader::checkLoadCompleteForThisFrame() case FrameStateCommittedPage: { DocumentLoader* dl = m_documentLoader.get(); - if (!dl || dl->isLoadingInAPISense()) + if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping())) return; markLoadComplete(); @@ -3501,11 +3534,6 @@ bool FrameLoader::firstLayoutDone() const return m_firstLayoutDone; } -bool FrameLoader::isQuickRedirectComing() const -{ - return m_quickRedirectComing; -} - void FrameLoader::detachChildren() { // FIXME: Is it really necessary to do this in reverse order? @@ -3564,30 +3592,6 @@ int FrameLoader::numPendingOrLoadingRequests(bool recurse) const return count; } -void FrameLoader::submitForm(const FrameLoadRequest& request, Event* event, bool lockHistory, bool lockBackForwardList) -{ - // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way. - // We do not want to submit more than one form from the same page, - // nor do we want to submit a single form more than once. - // This flag prevents these from happening; not sure how other browsers prevent this. - // The flag is reset in each time we start handle a new mouse or key down event, and - // also in setView since this part may get reused for a page from the back/forward cache. - // The form multi-submit logic here is only needed when we are submitting a form that affects this frame. - // FIXME: Frame targeting is only one of the ways the submission could end up doing something other - // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly - // needed any more now that we reset m_submittedFormURL on each mouse or key down event. - Frame* target = m_frame->tree()->find(request.frameName()); - if (m_frame->tree()->isDescendantOf(target)) { - if (m_submittedFormURL == request.resourceRequest().url()) - return; - m_submittedFormURL = request.resourceRequest().url(); - } - - loadFrameRequestWithFormAndValues(request, lockHistory, lockBackForwardList, event, m_formAboutToBeSubmitted.get(), m_formValuesAboutToBeSubmitted); - - clearRecordedFormValues(); -} - String FrameLoader::userAgent(const KURL& url) const { return m_client->userAgent(url); @@ -3595,9 +3599,6 @@ String FrameLoader::userAgent(const KURL& url) const void FrameLoader::tokenizerProcessedData() { -// ASSERT(m_frame->page()); -// ASSERT(m_frame->document()); - checkCompleted(); } @@ -3651,13 +3652,13 @@ void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadTyp { // Don't set the cookie policy URL if it's already been set. // But make sure to set it on all requests, as it has significance beyond the cookie policy for all protocols (<rdar://problem/6616664>). - if (request.mainDocumentURL().isEmpty()) { + if (request.firstPartyForCookies().isEmpty()) { if (mainResource && (isLoadingMainFrame() || cookiePolicyURLFromRequest)) - request.setMainDocumentURL(request.url()); - else if (Page* page = m_frame->page()) - request.setMainDocumentURL(page->mainFrame()->loader()->url()); + request.setFirstPartyForCookies(request.url()); + else if (Document* document = m_frame->document()) + request.setFirstPartyForCookies(document->firstPartyForCookies()); } - + // The remaining modifications are only necessary for HTTP and HTTPS. if (!request.url().isEmpty() && !request.url().protocolInHTTPFamily()) return; @@ -3674,7 +3675,7 @@ void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadTyp } if (mainResource) - request.setHTTPAccept("application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); + request.setHTTPAccept(defaultAcceptHeader); // Make sure we send the Origin header. addHTTPOriginIfNeeded(request, String()); @@ -3721,9 +3722,9 @@ void FrameLoader::committedLoad(DocumentLoader* loader, const char* data, int le } #ifdef ANDROID_USER_GESTURE -void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, Event* event, PassRefPtr<FormState> prpFormState, bool userGesture) +void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState, bool userGesture) #else -void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, Event* event, PassRefPtr<FormState> prpFormState) +void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState) #endif { RefPtr<FormState> formState = prpFormState; @@ -3759,7 +3760,8 @@ void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String NavigationAction action(url, loadType, true, event); if (!frameName.isEmpty()) { - if (Frame* targetFrame = findFrameForNavigation(frameName)) + // The search for a target frame is done earlier in the case of form submission. + if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName)) targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release()); else checkNewWindowPolicy(action, workingResourceRequest, formState.release(), frameName); @@ -3767,16 +3769,8 @@ void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release()); } -void FrameLoader::loadEmptyDocumentSynchronously() -{ - ResourceRequest request(KURL("")); - load(request, false); -} - -unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data) +unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data) { - // Since this is a subresource, we can load any URL (we ignore the return value). - // But we still want to know whether we should hide the referrer or not, so we call the canLoad method. String referrer = m_outgoingReferrer; if (shouldHideReferrer(request.url(), referrer)) referrer = String(); @@ -3794,7 +3788,7 @@ unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& requ addHTTPOriginIfNeeded(initialRequest, outgoingOrigin()); if (Page* page = m_frame->page()) - initialRequest.setMainDocumentURL(page->mainFrame()->loader()->documentLoader()->request().url()); + initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url()); initialRequest.setHTTPUserAgent(client()->userAgent(request.url())); unsigned long identifier = 0; @@ -3814,7 +3808,7 @@ unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& requ error = cannotShowURLError(newRequest); } else { #endif - ResourceHandle::loadResourceSynchronously(newRequest, error, response, data, m_frame); + ResourceHandle::loadResourceSynchronously(newRequest, storedCredentials, error, response, data, m_frame); #if ENABLE(OFFLINE_WEB_APPLICATIONS) // 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, @@ -3872,6 +3866,11 @@ void FrameLoader::didFailToLoad(ResourceLoader* loader, const ResourceError& err m_client->dispatchDidFailLoading(loader->documentLoader(), loader->identifier(), error); } +void FrameLoader::didLoadResourceByXMLHttpRequest(unsigned long identifier, const ScriptString& sourceString) +{ + m_client->dispatchDidLoadResourceByXMLHttpRequest(identifier, sourceString); +} + const ResourceRequest& FrameLoader::originalRequest() const { return activeDocumentLoader()->originalRequestCopy(); @@ -3893,8 +3892,8 @@ void FrameLoader::receivedMainResourceError(const ResourceError& error, bool isC } if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) { - KURL failedURL = m_provisionalDocumentLoader->originalRequestCopy().url(); - didNotOpenURL(failedURL); + if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url()) + m_submittedFormURL = KURL(); // We might have made a page cache item, but now we're bailing out due to an error before we ever // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state @@ -4127,7 +4126,14 @@ void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, Pass // might detach the current FrameLoader, in which case we should bail on this newly defunct load. if (!m_frame->page()) return; - + +#if ENABLE(JAVASCRIPT_DEBUGGER) + if (Page* page = m_frame->page()) { + if (page->mainFrame() == m_frame) + page->inspectorController()->resumeDebugger(); + } +#endif + setProvisionalDocumentLoader(m_policyDocumentLoader.get()); m_loadType = type; setState(FrameStateProvisional); @@ -4242,6 +4248,24 @@ void FrameLoader::applyUserAgent(ResourceRequest& request) request.setHTTPUserAgent(userAgent); } +bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url) +{ + Frame* topFrame = m_frame->tree()->top(); + if (m_frame == topFrame) + return false; + + if (equalIgnoringCase(content, "deny")) + return true; + + if (equalIgnoringCase(content, "sameorigin")) { + RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url); + if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin())) + return true; + } + + return false; +} + bool FrameLoader::canGoBackOrForward(int distance) const { if (Page* page = m_frame->page()) { @@ -4262,28 +4286,6 @@ int FrameLoader::getHistoryLength() return 0; } -KURL FrameLoader::historyURL(int distance) -{ - if (Page* page = m_frame->page()) { - BackForwardList* list = page->backForwardList(); - HistoryItem* item = list->itemAtIndex(distance); - if (!item) { - if (distance > 0) { - int forwardListCount = list->forwardListCount(); - if (forwardListCount > 0) - item = list->itemAtIndex(forwardListCount); - } else { - int backListCount = list->backListCount(); - if (backListCount > 0) - item = list->itemAtIndex(-backListCount); - } - } - if (item) - return item->url(); - } - return KURL(); -} - void FrameLoader::addHistoryItemForFragmentScroll() { addBackForwardItemClippedAtTarget(false); @@ -4375,6 +4377,11 @@ PassRefPtr<HistoryItem> FrameLoader::createHistoryItem(bool useOriginal) void FrameLoader::addBackForwardItemClippedAtTarget(bool doClip) { + // In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree. + // The item that was the target of the user's navigation is designated as the "targetItem". + // When this function is called with doClip=true we're able to create the whole tree except for the target's children, + // which will be loaded in the future. That part of the tree will be filled out as the child loads are committed. + Page* page = m_frame->page(); if (!page) return; @@ -4424,9 +4431,9 @@ PassRefPtr<HistoryItem> FrameLoader::createHistoryItemTree(Frame* targetFrame, b Frame* FrameLoader::findFrameForNavigation(const AtomicString& name) { Frame* frame = m_frame->tree()->find(name); - if (shouldAllowNavigation(frame)) - return frame; - return 0; + if (!shouldAllowNavigation(frame)) + return 0; + return frame; } void FrameLoader::saveScrollPositionAndViewStateToItem(HistoryItem* item) @@ -4539,13 +4546,16 @@ void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType) // Note if we have child frames we do a real reload, since the child frames might not // match our current frame structure, or they might not have the right content. We could // check for all that as an additional optimization. - // We also do not do anchor-style navigation if we're posting a form. - + // We also do not do anchor-style navigation if we're posting a form or navigating from + // a page that was resulted from a form post. + bool shouldScroll = !formData && !(m_currentHistoryItem && m_currentHistoryItem->formData()) && urlsMatchItem(item); + #if ENABLE(WML) - if (!formData && urlsMatchItem(item) && !m_frame->document()->isWMLDocument()) { -#else - if (!formData && urlsMatchItem(item)) { + if (m_frame->document()->isWMLDocument()) + shouldScroll = false; #endif + + if (shouldScroll) { // Must do this maintenance here, since we don't go through a real page reload saveScrollPositionAndViewStateToItem(m_currentHistoryItem.get()); @@ -4756,10 +4766,10 @@ void FrameLoader::recursiveGoToItem(HistoryItem* item, HistoryItem* fromItem, Fr int size = childItems.size(); for (int i = 0; i < size; ++i) { - String childName = childItems[i]->target(); - HistoryItem* fromChildItem = fromItem->childItemWithName(childName); + String childFrameName = childItems[i]->target(); + HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName); ASSERT(fromChildItem || fromItem->isTargetItem()); - Frame* childFrame = m_frame->tree()->child(childName); + Frame* childFrame = m_frame->tree()->child(childFrameName); ASSERT(childFrame); childFrame->loader()->recursiveGoToItem(childItems[i].get(), fromChildItem, type); } @@ -4777,9 +4787,10 @@ bool FrameLoader::childFramesMatchItem(HistoryItem* item) const return false; unsigned size = childItems.size(); - for (unsigned i = 0; i < size; ++i) + for (unsigned i = 0; i < size; ++i) { if (!m_frame->tree()->child(childItems[i]->target())) return false; + } // Found matches for all item targets return true; @@ -4799,22 +4810,14 @@ void FrameLoader::updateHistoryForStandardLoad() bool needPrivacy = !settings || settings->privateBrowsingEnabled(); const KURL& historyURL = documentLoader()->urlForHistory(); - // If the navigation occured during load and this is a subframe, update the current - // back/forward item rather than adding a new one and don't add the new URL to global - // history at all. But do add it to visited links. <rdar://problem/5333496> - bool frameNavigationDuringLoad = false; - if (m_navigationDuringLoad) { - HTMLFrameOwnerElement* owner = m_frame->ownerElement(); - frameNavigationDuringLoad = owner && !owner->createdByParser(); - m_navigationDuringLoad = false; - } - - if (!frameNavigationDuringLoad && !documentLoader()->isClientRedirect()) { + if (!documentLoader()->isClientRedirect()) { if (!historyURL.isEmpty()) { addBackForwardItemClippedAtTarget(true); if (!needPrivacy) { m_client->updateGlobalHistory(); m_documentLoader->setDidCreateGlobalHistoryEntry(true); + if (m_documentLoader->unreachableURL().isEmpty()) + m_client->updateGlobalHistoryRedirectLinks(); } if (Page* page = m_frame->page()) page->setGlobalHistoryItem(needPrivacy ? 0 : page->backForwardList()->currentItem()); @@ -4905,6 +4908,8 @@ void FrameLoader::updateHistoryForRedirectWithLockedBackForwardList() if (!needPrivacy) { m_client->updateGlobalHistory(); m_documentLoader->setDidCreateGlobalHistoryEntry(true); + if (m_documentLoader->unreachableURL().isEmpty()) + m_client->updateGlobalHistoryRedirectLinks(); } if (Page* page = m_frame->page()) page->setGlobalHistoryItem(needPrivacy ? 0 : page->backForwardList()->currentItem()); @@ -4917,7 +4922,7 @@ void FrameLoader::updateHistoryForRedirectWithLockedBackForwardList() } else { Frame* parentFrame = m_frame->tree()->parent(); if (parentFrame && parentFrame->loader()->m_currentHistoryItem) - parentFrame->loader()->m_currentHistoryItem->addChildItem(createHistoryItem(true)); + parentFrame->loader()->m_currentHistoryItem->setChildItem(createHistoryItem(true)); } if (!historyURL.isEmpty() && !needPrivacy) { @@ -4975,8 +4980,6 @@ void FrameLoader::saveDocumentAndScrollState() } } -// FIXME: These 3 setter/getters are here for a dwindling number of users in WebKit, WebFrame -// being the primary one. After they're no longer needed there, they can be removed! HistoryItem* FrameLoader::currentHistoryItem() { return m_currentHistoryItem.get(); @@ -4987,11 +4990,6 @@ void FrameLoader::setCurrentHistoryItem(PassRefPtr<HistoryItem> item) m_currentHistoryItem = item; } -void FrameLoader::setProvisionalHistoryItem(PassRefPtr<HistoryItem> item) -{ - m_provisionalHistoryItem = item; -} - void FrameLoader::setMainDocumentError(DocumentLoader* loader, const ResourceError& error) { m_client->setMainDocumentError(loader, error); @@ -5193,19 +5191,24 @@ Widget* FrameLoader::createJavaAppletWidget(const IntSize& size, HTMLAppletEleme paramNames.append(it->first); paramValues.append(it->second); } - + + if (!codeBaseURLString.isEmpty()) { + KURL codeBaseURL = completeURL(codeBaseURLString); + if (!canLoad(codeBaseURL, String(), element->document())) { + FrameLoader::reportLocalLoadFailed(m_frame, codeBaseURL.string()); + return 0; + } + } + if (baseURLString.isEmpty()) baseURLString = m_frame->document()->baseURL().string(); KURL baseURL = completeURL(baseURLString); - Widget* widget = 0; - KURL codeBaseURL = completeURL(codeBaseURLString); - if (canLoad(codeBaseURL, String(), element->document())) { - widget = m_client->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues); - if (widget) - m_containsPlugIns = true; - } + Widget* widget = m_client->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues); + if (!widget) + return 0; + m_containsPlugIns = true; return widget; } @@ -5225,24 +5228,6 @@ void FrameLoader::didChangeTitle(DocumentLoader* loader) } } -void FrameLoader::continueLoadWithData(SharedBuffer* buffer, const String& mimeType, const String& textEncoding, const KURL& url) -{ - m_responseMIMEType = mimeType; - didOpenURL(url); - - String encoding; - if (m_frame) - encoding = documentLoader()->overrideEncoding(); - bool userChosen = !encoding.isNull(); - if (encoding.isNull()) - encoding = textEncoding; - setEncoding(encoding, userChosen); - - ASSERT(m_frame->document()); - - addData(buffer->data(), buffer->size()); -} - void FrameLoader::registerURLSchemeAsLocal(const String& scheme) { localSchemes().add(scheme); diff --git a/WebCore/loader/FrameLoader.h b/WebCore/loader/FrameLoader.h index 07acff3..07e530e 100644 --- a/WebCore/loader/FrameLoader.h +++ b/WebCore/loader/FrameLoader.h @@ -31,9 +31,9 @@ #define FrameLoader_h #include "CachePolicy.h" -#include "FormState.h" #include "FrameLoaderTypes.h" #include "ResourceRequest.h" +#include "ThreadableLoader.h" #include "Timer.h" namespace WebCore { @@ -47,9 +47,9 @@ namespace WebCore { class CachedResource; class Document; class DocumentLoader; - class Element; class Event; class FormData; + class FormState; class Frame; class FrameLoaderClient; class HistoryItem; @@ -64,6 +64,7 @@ namespace WebCore { class ResourceLoader; class ResourceResponse; class ScriptSourceCode; + class ScriptString; class ScriptValue; class SecurityOrigin; class SharedBuffer; @@ -71,7 +72,6 @@ namespace WebCore { class TextResourceDecoder; class Widget; - struct FormSubmission; struct FrameLoadRequest; struct ScheduledRedirection; struct WindowFeatures; @@ -122,56 +122,40 @@ namespace WebCore { Frame* frame() const { return m_frame; } - // FIXME: This is not cool, people. We should aim to consolidate these variety of loading related methods into a smaller set, - // and try to reuse more of the same logic by extracting common code paths. + // FIXME: This is not cool, people. There are too many different functions that all start loads. + // We should aim to consolidate these into a smaller set of functions, and try to reuse more of + // the logic by extracting common code paths. + void prepareForLoadStart(); void setupForReplace(); void setupForReplaceByMIMEType(const String& newMIMEType); - void loadWithDocumentLoader(DocumentLoader*, FrameLoadType, PassRefPtr<FormState>); // Calls continueLoadAfterNavigationPolicy - void load(DocumentLoader*); // Calls loadWithDocumentLoader - - void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&, // Calls loadWithDocumentLoader() - bool lockHistory, FrameLoadType, PassRefPtr<FormState>); - -#ifdef ANDROID_USER_GESTURE - void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction - const String& frameName, bool lockHistory, FrameLoadType, Event*, PassRefPtr<FormState>, bool userGesture); - - void loadURL(const KURL& newURL, const String& referrer, const String& frameName, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction or else dispatches to navigation policy delegate - bool lockHistory, FrameLoadType, Event*, PassRefPtr<FormState>, bool userGesture); -#else - void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction - const String& frameName, bool lockHistory, FrameLoadType, Event*, PassRefPtr<FormState>); - - void loadURL(const KURL& newURL, const String& referrer, const String& frameName, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction or else dispatches to navigation policy delegate - bool lockHistory, FrameLoadType, Event*, PassRefPtr<FormState>); -#endif void loadURLIntoChildFrame(const KURL&, const String& referer, Frame*); - void loadFrameRequestWithFormAndValues(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, // Called by submitForm, calls loadPostRequest() - Event*, HTMLFormElement*, const HashMap<String, String>& formValues); + void loadFrameRequest(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, // Called by submitForm, calls loadPostRequest and loadURL. + PassRefPtr<Event>, PassRefPtr<FormState>); - void load(const ResourceRequest&, bool lockHistory); // Called by WebFrame, calls (ResourceRequest, SubstituteData) - void load(const ResourceRequest&, const SubstituteData&, bool lockHistory); // Called both by WebFrame and internally, calls (DocumentLoader*) - void load(const ResourceRequest&, const String& frameName, bool lockHistory); // Called by WebPluginController + void load(const ResourceRequest&, bool lockHistory); // Called by WebFrame, calls load(ResourceRequest, SubstituteData). + void load(const ResourceRequest&, const SubstituteData&, bool lockHistory); // Called both by WebFrame and internally, calls load(DocumentLoader*). + void load(const ResourceRequest&, const String& frameName, bool lockHistory); // Called by WebPluginController. #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size - void loadArchive(PassRefPtr<Archive> archive); + void loadArchive(PassRefPtr<Archive>); #endif - // Returns true for any non-local URL. If Document parameter is supplied, its local load policy dictates, + // Returns true for any non-local URL. If document parameter is supplied, its local load policy dictates, // otherwise if referrer is non-empty and represents a local file, then the local load is allowed. - static bool canLoad(const KURL&, const String& referrer, const Document* theDocument = 0); + static bool canLoad(const KURL&, const String& referrer, const Document*); + static bool canLoad(const KURL&, const String& referrer, const SecurityOrigin* = 0); static void reportLocalLoadFailed(Frame*, const String& url); - static bool shouldHideReferrer(const KURL& url, const String& referrer); + static bool shouldHideReferrer(const KURL&, const String& referrer); // Called by createWindow in JSDOMWindowBase.cpp, e.g. to fulfill a modal dialog creation Frame* createWindow(FrameLoader* frameLoaderForFrameLookup, const FrameLoadRequest&, const WindowFeatures&, bool& created); - unsigned long loadResourceSynchronously(const ResourceRequest&, ResourceError&, ResourceResponse&, Vector<char>& data); + unsigned long loadResourceSynchronously(const ResourceRequest&, StoredCredentials, ResourceError&, ResourceResponse&, Vector<char>& data); bool canHandleRequest(const ResourceRequest&); @@ -187,7 +171,6 @@ namespace WebCore { String referrer() const; String outgoingReferrer() const; String outgoingOrigin() const; - void loadEmptyDocumentSynchronously(); DocumentLoader* activeDocumentLoader() const; DocumentLoader* documentLoader() const { return m_documentLoader.get(); } @@ -206,6 +189,7 @@ namespace WebCore { void didReceiveData(ResourceLoader*, const char*, int, int lengthReceived); void didFinishLoad(ResourceLoader*); void didFailToLoad(ResourceLoader*, const ResourceError&); + void didLoadResourceByXMLHttpRequest(unsigned long identifier, const ScriptString& sourceString); const ResourceRequest& originalRequest() const; const ResourceRequest& initialRequest() const; void receivedMainResourceError(const ResourceError&, bool isComplete); @@ -230,8 +214,6 @@ namespace WebCore { bool representationExistsForURLScheme(const String& URLScheme); String generatedMIMETypeForURLScheme(const String& URLScheme); - void notifyIconChanged(); - void checkNavigationPolicy(const ResourceRequest&, NavigationPolicyDecisionFunction function, void* argument); void checkContentPolicy(const String& MIMEType, ContentPolicyDecisionFunction, void* argument); void cancelContentPolicyCheck(); @@ -252,32 +234,22 @@ namespace WebCore { void didChangeTitle(DocumentLoader*); FrameLoadType loadType() const; - CachePolicy cachePolicy() const; + CachePolicy subresourceCachePolicy() const; void didFirstLayout(); bool firstLayoutDone() const; void didFirstVisuallyNonEmptyLayout(); - void clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress); - void clientRedirected(const KURL&, double delay, double fireDate, bool lockBackForwardList, bool isJavaScriptFormAction); - bool shouldReload(const KURL& currentURL, const KURL& destinationURL); #if ENABLE(WML) void setForceReloadWmlDeck(bool); #endif - bool isQuickRedirectComing() const; - - void sendRemainingDelegateMessages(unsigned long identifier, const ResourceResponse&, int length, const ResourceError&); - void requestFromDelegate(ResourceRequest&, unsigned long& identifier, ResourceError&); void loadedResourceFromMemoryCache(const CachedResource*); void tellClientAboutPastMemoryCacheLoads(); - void recursiveCheckLoadComplete(); void checkLoadComplete(); void detachFromParent(); - void detachChildren(); - void closeAndRemoveChild(Frame*); void addExtraFieldsToSubresourceRequest(ResourceRequest&); void addExtraFieldsToMainResourceRequest(ResourceRequest&); @@ -288,17 +260,13 @@ namespace WebCore { void setDefersLoading(bool); - void changeLocation(const String& url, const String& referrer, bool lockHistory = true, bool lockBackForwardList = true, bool userGesture = false, bool refresh = false); void changeLocation(const KURL&, const String& referrer, bool lockHistory = true, bool lockBackForwardList = true, bool userGesture = false, bool refresh = false); - void urlSelected(const ResourceRequest&, const String& target, Event*, bool lockHistory, bool lockBackForwardList, bool userGesture); - void urlSelected(const FrameLoadRequest&, Event*, bool lockHistory, bool lockBackForwardList); - + void urlSelected(const ResourceRequest&, const String& target, PassRefPtr<Event>, bool lockHistory, bool lockBackForwardList, bool userGesture); bool requestFrame(HTMLFrameOwnerElement*, const String& url, const AtomicString& frameName); - Frame* loadSubframe(HTMLFrameOwnerElement*, const KURL&, const String& name, const String& referrer); - void submitForm(const char* action, const String& url, PassRefPtr<FormData>, const String& target, const String& contentType, const String& boundary, Event*, bool lockHistory, bool lockBackForwardList); - void submitFormAgain(); - void submitForm(const FrameLoadRequest&, Event*, bool lockHistory, bool lockBackForwardList); + void submitForm(const char* action, const String& url, + PassRefPtr<FormData>, const String& target, const String& contentType, const String& boundary, + bool lockHistory, bool lockBackForwardList, PassRefPtr<Event>, PassRefPtr<FormState>); void stop(); void stopLoading(bool sendUnload, DatabasePolicy = DatabasePolicyStop); @@ -310,8 +278,6 @@ namespace WebCore { void commitIconURLToIconDatabase(const KURL&); KURL baseURL() const; - String baseTarget() const; - KURL dataURLBaseFromRequest(const ResourceRequest& request) const; bool isScheduledLocationChangePending() const { return m_scheduledRedirection && isLocationChange(*m_scheduledRedirection); } void scheduleHTTPRedirection(double delay, const String& url); @@ -322,12 +288,11 @@ namespace WebCore { bool canGoBackOrForward(int distance) const; void goBackOrForward(int distance); int getHistoryLength(); - KURL historyURL(int distance); void begin(); void begin(const KURL&, bool dispatchWindowObjectAvailable = true, SecurityOrigin* forcedSecurityOrigin = 0); - void write(const char* str, int len = -1, bool flush = false); + void write(const char* string, int length = -1, bool flush = false); void write(const String&); void end(); void endIfNotLoadingMainResource(); @@ -335,15 +300,10 @@ namespace WebCore { void setEncoding(const String& encoding, bool userChosen); String encoding() const; - // Returns true if url is a JavaScript URL. - bool executeIfJavaScriptURL(const KURL& url, bool userGesture = false, bool replaceDocument = true); - ScriptValue executeScript(const ScriptSourceCode&); ScriptValue executeScript(const String& script, bool forceUserGesture = false); void gotoAnchor(); - bool gotoAnchor(const String& name); // returns true if the anchor was found - void scrollToAnchor(const KURL&); void tokenizerProcessedData(); @@ -361,26 +321,18 @@ namespace WebCore { bool openedByDOM() const; void setOpenedByDOM(); - void provisionalLoadStarted(); - bool userGestureHint(); void resetMultipleFormSubmissionProtection(); - void didNotOpenURL(const KURL&); void addData(const char* bytes, int length); - bool canCachePage(); - void checkCallImplicitClose(); - bool didOpenURL(const KURL&); void frameDetached(); const KURL& url() const { return m_URL; } - void updateBaseURLForEmptyDocument(); - void setResponseMIMEType(const String&); const String& responseMIMEType() const; @@ -389,12 +341,6 @@ namespace WebCore { void loadDone(); void finishedParsing(); void checkCompleted(); - void scheduleCheckCompleted(); - void scheduleCheckLoadComplete(); - - void clearRecordedFormValues(); - void setFormAboutToBeSubmitted(PassRefPtr<HTMLFormElement> element); - void recordFormValue(const String& name, const String& value); bool isComplete() const; @@ -403,32 +349,22 @@ namespace WebCore { KURL completeURL(const String& url); - KURL originalRequestURL() const; - void cancelAndClear(); void setTitle(const String&); - - bool shouldTreatURLAsSameAsCurrent(const KURL&) const; void commitProvisionalLoad(PassRefPtr<CachedPage>); void goToItem(HistoryItem*, FrameLoadType); void saveDocumentAndScrollState(); - void saveScrollPositionAndViewStateToItem(HistoryItem*); - // FIXME: These accessors are here for a dwindling number of users in WebKit, WebFrame - // being the primary one. After they're no longer needed there, they can be removed! HistoryItem* currentHistoryItem(); void setCurrentHistoryItem(PassRefPtr<HistoryItem>); - void setProvisionalHistoryItem(PassRefPtr<HistoryItem>); - - void continueLoadWithData(SharedBuffer*, const String& mimeType, const String& textEncoding, const KURL&); enum LocalLoadPolicy { - AllowLocalLoadsForAll, // No restriction on local loads. - AllowLocalLoadsForLocalAndSubstituteData, - AllowLocalLoadsForLocalOnly, + AllowLocalLoadsForAll, // No restriction on local loads. + AllowLocalLoadsForLocalAndSubstituteData, + AllowLocalLoadsForLocalOnly, }; static void setLocalLoadPolicy(LocalLoadPolicy); static bool restrictAccessToLocal(); @@ -452,6 +388,8 @@ namespace WebCore { void applyUserAgent(ResourceRequest& request); + bool shouldInterruptLoadForXFrameOptions(const String&, const KURL&); + private: PassRefPtr<HistoryItem> createHistoryItem(bool useOriginal); PassRefPtr<HistoryItem> createHistoryItemTree(Frame* targetFrame, bool clipAtTarget); @@ -499,8 +437,8 @@ namespace WebCore { void receivedFirstData(); - void updatePolicyBaseURL(); - void setPolicyBaseURL(const KURL&); + void updateFirstPartyForCookies(); + void setFirstPartyForCookies(const KURL&); void addExtraFieldsToRequest(ResourceRequest&, FrameLoadType loadType, bool isMainResource, bool cookiePolicyURLFromRequest); @@ -516,10 +454,8 @@ namespace WebCore { void setLoadType(FrameLoadType); - void checkNavigationPolicy(const ResourceRequest&, DocumentLoader*, PassRefPtr<FormState>, - NavigationPolicyDecisionFunction, void* argument); - void checkNewWindowPolicy(const NavigationAction&, const ResourceRequest&, - PassRefPtr<FormState>, const String& frameName); + void checkNavigationPolicy(const ResourceRequest&, DocumentLoader*, PassRefPtr<FormState>, NavigationPolicyDecisionFunction, void* argument); + void checkNewWindowPolicy(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, const String& frameName); void continueAfterNavigationPolicy(PolicyAction); void continueAfterNewWindowPolicy(PolicyAction); @@ -532,13 +468,11 @@ namespace WebCore { void continueLoadAfterNewWindowPolicy(const ResourceRequest&, PassRefPtr<FormState>, const String& frameName, bool shouldContinue); static void callContinueFragmentScrollAfterNavigationPolicy(void*, const ResourceRequest&, PassRefPtr<FormState>, bool shouldContinue); void continueFragmentScrollAfterNavigationPolicy(const ResourceRequest&, bool shouldContinue); - bool shouldScrollToAnchor(bool isFormSubmission, FrameLoadType loadType, const KURL& url); + bool shouldScrollToAnchor(bool isFormSubmission, FrameLoadType, const KURL&); void addHistoryItemForFragmentScroll(); void stopPolicyCheck(); - void closeDocument(); - void checkLoadCompleteForThisFrame(); void setDocumentLoader(DocumentLoader*); @@ -570,6 +504,65 @@ namespace WebCore { void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier); static bool isLocationChange(const ScheduledRedirection&); + void scheduleFormSubmission(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, PassRefPtr<Event>, PassRefPtr<FormState>); + + void loadWithDocumentLoader(DocumentLoader*, FrameLoadType, PassRefPtr<FormState>); // Calls continueLoadAfterNavigationPolicy + void load(DocumentLoader*); // Calls loadWithDocumentLoader + + void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&, // Calls loadWithDocumentLoader + bool lockHistory, FrameLoadType, PassRefPtr<FormState>); + +#ifdef ANDROID_USER_GESTURE +// FIXME (klobag): WebKit/android/jni/WebCoreFrameBridge.cpp uses +// loadPostRequest, figure out if we can use load(...) instead of +// making loadPostRequest public. +public: + void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequest, calls loadWithNavigationAction + const String& frameName, bool lockHistory, FrameLoadType, PassRefPtr<Event>, PassRefPtr<FormState>, bool userGesture); +private: + void loadURL(const KURL&, const String& referrer, const String& frameName, // Called by loadFrameRequest, calls loadWithNavigationAction or dispatches to navigation policy delegate + bool lockHistory, FrameLoadType, PassRefPtr<Event>, PassRefPtr<FormState>, bool userGesture); +#endif // ANDROID_USER_GESTURE + + void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequest, calls loadWithNavigationAction + const String& frameName, bool lockHistory, FrameLoadType, PassRefPtr<Event>, PassRefPtr<FormState>); + void loadURL(const KURL&, const String& referrer, const String& frameName, // Called by loadFrameRequest, calls loadWithNavigationAction or dispatches to navigation policy delegate + bool lockHistory, FrameLoadType, PassRefPtr<Event>, PassRefPtr<FormState>); + + void clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress); + void clientRedirected(const KURL&, double delay, double fireDate, bool lockBackForwardList); + bool shouldReload(const KURL& currentURL, const KURL& destinationURL); + + void sendRemainingDelegateMessages(unsigned long identifier, const ResourceResponse&, int length, const ResourceError&); + void requestFromDelegate(ResourceRequest&, unsigned long& identifier, ResourceError&); + + void recursiveCheckLoadComplete(); + + void detachChildren(); + void closeAndRemoveChild(Frame*); + + Frame* loadSubframe(HTMLFrameOwnerElement*, const KURL&, const String& name, const String& referrer); + + // Returns true if argument is a JavaScript URL. + bool executeIfJavaScriptURL(const KURL&, bool userGesture = false, bool replaceDocument = true); + + bool gotoAnchor(const String& name); // returns true if the anchor was found + void scrollToAnchor(const KURL&); + + void provisionalLoadStarted(); + + bool canCachePage(); + + bool didOpenURL(const KURL&); + + void scheduleCheckCompleted(); + void scheduleCheckLoadComplete(); + + KURL originalRequestURL() const; + + bool shouldTreatURLAsSameAsCurrent(const KURL&) const; + + void saveScrollPositionAndViewStateToItem(HistoryItem*); Frame* m_frame; FrameLoaderClient* m_client; @@ -599,12 +592,9 @@ namespace WebCore { bool m_quickRedirectComing; bool m_sentRedirectNotification; bool m_inStopAllLoaders; - bool m_navigationDuringLoad; String m_outgoingReferrer; - OwnPtr<FormSubmission> m_deferredFormSubmission; - bool m_isExecutingJavaScriptFormAction; bool m_isRunningScript; @@ -612,6 +602,7 @@ namespace WebCore { bool m_didCallImplicitClose; bool m_wasUnloadEventEmitted; + bool m_unloadEventBeingDispatched; bool m_isComplete; bool m_isLoadingMainResource; @@ -634,8 +625,6 @@ namespace WebCore { bool m_containsPlugIns; - RefPtr<HTMLFormElement> m_formAboutToBeSubmitted; - HashMap<String, String> m_formValuesAboutToBeSubmitted; KURL m_submittedFormURL; Timer<FrameLoader> m_redirectionTimer; diff --git a/WebCore/loader/FrameLoaderClient.h b/WebCore/loader/FrameLoaderClient.h index 4f2b86e..5e5191b 100644 --- a/WebCore/loader/FrameLoaderClient.h +++ b/WebCore/loader/FrameLoaderClient.h @@ -64,6 +64,7 @@ namespace WebCore { class ResourceLoader; struct ResourceRequest; class ResourceResponse; + class ScriptString; class SharedBuffer; class SubstituteData; class String; @@ -109,6 +110,7 @@ namespace WebCore { virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier) = 0; virtual void dispatchDidFailLoading(DocumentLoader*, unsigned long identifier, const ResourceError&) = 0; virtual bool dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int length) = 0; + virtual void dispatchDidLoadResourceByXMLHttpRequest(unsigned long identifier, const ScriptString&) = 0; virtual void dispatchDidHandleOnloadEvents() = 0; virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() = 0; diff --git a/WebCore/loader/ImageDocument.cpp b/WebCore/loader/ImageDocument.cpp index ca3f785..08f2e9a 100644 --- a/WebCore/loader/ImageDocument.cpp +++ b/WebCore/loader/ImageDocument.cpp @@ -25,6 +25,7 @@ #include "config.h" #include "ImageDocument.h" +#include "CSSStyleDeclaration.h" #include "CachedImage.h" #include "DocumentLoader.h" #include "Element.h" @@ -37,6 +38,7 @@ #include "HTMLNames.h" #include "LocalizedStrings.h" #include "MouseEvent.h" +#include "NotImplemented.h" #include "Page.h" #include "SegmentedString.h" #include "Settings.h" @@ -93,7 +95,8 @@ private: void ImageTokenizer::write(const SegmentedString&, bool) { - ASSERT_NOT_REACHED(); + // <https://bugs.webkit.org/show_bug.cgi?id=25397>: JS code can always call document.write, we need to handle it. + notImplemented(); } bool ImageTokenizer::writeRawData(const char*, int) @@ -124,9 +127,9 @@ void ImageTokenizer::finish() IntSize size = cachedImage->imageSize(m_doc->frame()->pageZoomFactor()); if (size.width()) { - // Compute the title, we use the filename of the resource, falling - // back on the hostname if there is no path. - String fileName = m_doc->url().lastPathComponent(); + // Compute the title, we use the decoded filename of the resource, falling + // back on the (decoded) hostname if there is no path. + String fileName = decodeURLEscapeSequences(m_doc->url().lastPathComponent()); if (fileName.isEmpty()) fileName = m_doc->url().host(); m_doc->setTitle(imageTitle(fileName, size)); @@ -184,7 +187,8 @@ void ImageDocument::createDocumentStructure() if (shouldShrinkToFit()) { // Add event listeners RefPtr<EventListener> listener = ImageEventListener::create(this); - addWindowEventListener("resize", listener, false); + if (DOMWindow* domWindow = this->domWindow()) + domWindow->addEventListener("resize", listener, false); imageElement->addEventListener("click", listener.release(), false); } diff --git a/WebCore/loader/MainResourceLoader.cpp b/WebCore/loader/MainResourceLoader.cpp index 5aa1cde..39e5b90 100644 --- a/WebCore/loader/MainResourceLoader.cpp +++ b/WebCore/loader/MainResourceLoader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * Redistribution and use in source and binary forms, with or without @@ -30,12 +30,8 @@ #include "config.h" #include "MainResourceLoader.h" -#if ENABLE(OFFLINE_WEB_APPLICATIONS) -#include "ApplicationCache.h" -#include "ApplicationCacheGroup.h" -#include "ApplicationCacheResource.h" -#endif #include "DocumentLoader.h" +#include "FormState.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" @@ -45,6 +41,12 @@ #include "ResourceHandle.h" #include "Settings.h" +#if ENABLE(OFFLINE_WEB_APPLICATIONS) +#include "ApplicationCache.h" +#include "ApplicationCacheGroup.h" +#include "ApplicationCacheResource.h" +#endif + // FIXME: More that is in common with SubresourceLoader should move up into ResourceLoader. namespace WebCore { @@ -161,7 +163,7 @@ void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const Reso // Update cookie policy base URL as URL changes, except for subframes, which use the // URL of the main frame which doesn't change when we redirect. if (frameLoader()->isLoadingMainFrame()) - newRequest.setMainDocumentURL(newRequest.url()); + newRequest.setFirstPartyForCookies(newRequest.url()); // If we're fielding a redirect in response to a POST, force a load from origin, since // this is a common site technique to return to a page viewing some data that the POST @@ -179,9 +181,10 @@ void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const Reso // listener. But there's no way to do that in practice. So instead we cancel later if the // listener tells us to. In practice that means the navigation policy needs to be decided // synchronously for these redirect cases. - - ref(); // balanced by deref in continueAfterNavigationPolicy - frameLoader()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this); + if (!redirectResponse.isNull()) { + ref(); // balanced by deref in continueAfterNavigationPolicy + frameLoader()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this); + } } static bool shouldLoadAsEmptyDocument(const KURL& url) @@ -291,6 +294,15 @@ void MainResourceLoader::didReceiveResponse(const ResourceResponse& r) } #endif + HTTPHeaderMap::const_iterator it = r.httpHeaderFields().find(AtomicString("x-frame-options")); + if (it != r.httpHeaderFields().end()) { + String content = it->second; + if (m_frame->loader()->shouldInterruptLoadForXFrameOptions(content, r.url())) { + cancel(); + return; + } + } + // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred. // See <rdar://problem/6304600> for more details. #if !PLATFORM(CF) diff --git a/WebCore/loader/MediaDocument.cpp b/WebCore/loader/MediaDocument.cpp index b89ac10..0b1fd59 100644 --- a/WebCore/loader/MediaDocument.cpp +++ b/WebCore/loader/MediaDocument.cpp @@ -38,7 +38,9 @@ #include "HTMLEmbedElement.h" #include "HTMLNames.h" #include "HTMLVideoElement.h" +#include "KeyboardEvent.h" #include "MainResourceLoader.h" +#include "NodeList.h" #include "Page.h" #include "SegmentedString.h" #include "Settings.h" @@ -133,10 +135,16 @@ bool MediaTokenizer::isWaitingForScripts() const MediaDocument::MediaDocument(Frame* frame) : HTMLDocument(frame) + , m_replaceMediaElementTimer(this, &MediaDocument::replaceMediaElementTimerFired) { setParseMode(Compat); } +MediaDocument::~MediaDocument() +{ + ASSERT(!m_replaceMediaElementTimer.isActive()); +} + Tokenizer* MediaDocument::createTokenizer() { return new MediaTokenizer(this); @@ -161,6 +169,69 @@ void MediaDocument::defaultEventHandler(Event* event) } } } + + if (event->type() == eventNames().keydownEvent && event->isKeyboardEvent()) { + HTMLVideoElement* video = 0; + if (targetNode) { + if (targetNode->hasTagName(videoTag)) + video = static_cast<HTMLVideoElement*>(targetNode); + else { + RefPtr<NodeList> nodeList = targetNode->getElementsByTagName("video"); + if (nodeList.get()->length() > 0) + video = static_cast<HTMLVideoElement*>(nodeList.get()->item(0)); + } + } + if (video) { + KeyboardEvent* keyboardEvent = static_cast<KeyboardEvent*>(event); + if (keyboardEvent->keyIdentifier() == "U+0020") { // space + if (video->paused()) { + if (video->canPlay()) + video->play(); + } else + video->pause(); + event->setDefaultHandled(); + } + } + } +} + +void MediaDocument::mediaElementSawUnsupportedTracks() +{ + // The HTMLMediaElement was told it has something that the underlying + // MediaPlayer cannot handle so we should switch from <video> to <embed> + // and let the plugin handle this. Don't do it immediately as this + // function may be called directly from a media engine callback, and + // replaceChild will destroy the element, media player, and media engine. + m_replaceMediaElementTimer.startOneShot(0); +} + +void MediaDocument::replaceMediaElementTimerFired(Timer<MediaDocument>*) +{ + HTMLElement* htmlBody = body(); + if (!htmlBody) + return; + + // Set body margin width and height to 0 as that is what a PluginDocument uses. + htmlBody->setAttribute(marginwidthAttr, "0"); + htmlBody->setAttribute(marginheightAttr, "0"); + + RefPtr<NodeList> nodeList = htmlBody->getElementsByTagName("video"); + + if (nodeList.get()->length() > 0) { + HTMLVideoElement* videoElement = static_cast<HTMLVideoElement*>(nodeList.get()->item(0)); + + RefPtr<Element> element = Document::createElement(embedTag, false); + HTMLEmbedElement* embedElement = static_cast<HTMLEmbedElement*>(element.get()); + + embedElement->setAttribute(widthAttr, "100%"); + embedElement->setAttribute(heightAttr, "100%"); + embedElement->setAttribute(nameAttr, "plugin"); + embedElement->setSrc(url().string()); + embedElement->setType(frame()->loader()->responseMIMEType()); + + ExceptionCode ec; + videoElement->parent()->replaceChild(embedElement, videoElement, ec); + } } } diff --git a/WebCore/loader/MediaDocument.h b/WebCore/loader/MediaDocument.h index e5167e4..ac286f0 100644 --- a/WebCore/loader/MediaDocument.h +++ b/WebCore/loader/MediaDocument.h @@ -41,11 +41,17 @@ public: virtual void defaultEventHandler(Event*); + void mediaElementSawUnsupportedTracks(); + private: MediaDocument(Frame*); + virtual ~MediaDocument(); + Timer<MediaDocument> m_replaceMediaElementTimer; virtual bool isMediaDocument() const { return true; } virtual Tokenizer* createTokenizer(); + + void replaceMediaElementTimerFired(Timer<MediaDocument>*); }; } diff --git a/WebCore/loader/ProgressTracker.cpp b/WebCore/loader/ProgressTracker.cpp index 38df80f..e682b9b 100644 --- a/WebCore/loader/ProgressTracker.cpp +++ b/WebCore/loader/ProgressTracker.cpp @@ -26,6 +26,7 @@ #include "config.h" #include "ProgressTracker.h" +#include "DocumentLoader.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" @@ -196,8 +197,11 @@ void ProgressTracker::incrementProgress(unsigned long identifier, const char*, i else percentOfRemainingBytes = 1.0; - // Treat the first layout as the half-way point. - double maxProgressValue = m_originatingProgressFrame->loader()->firstLayoutDone() ? finalProgressValue : .5; + // For documents that use WebCore's layout system, treat first layout as the half-way point. + // FIXME: The hasHTMLView function is a sort of roundabout way of asking "do you use WebCore's layout system". + bool useClampedMaxProgress = m_originatingProgressFrame->loader()->client()->hasHTMLView() + && !m_originatingProgressFrame->loader()->firstLayoutDone(); + double maxProgressValue = useClampedMaxProgress ? 0.5 : finalProgressValue; increment = (maxProgressValue - m_progressValue) * percentOfRemainingBytes; m_progressValue += increment; m_progressValue = min(m_progressValue, maxProgressValue); diff --git a/WebCore/loader/SubresourceLoader.cpp b/WebCore/loader/SubresourceLoader.cpp index 4a339ef..047cc6d 100644 --- a/WebCore/loader/SubresourceLoader.cpp +++ b/WebCore/loader/SubresourceLoader.cpp @@ -66,7 +66,7 @@ PassRefPtr<SubresourceLoader> SubresourceLoader::create(Frame* frame, Subresourc return 0; FrameLoader* fl = frame->loader(); - if (!skipCanLoadCheck && fl->state() == FrameStateProvisional) + if (!skipCanLoadCheck && (fl->state() == FrameStateProvisional || fl->activeDocumentLoader()->isStopping())) return 0; ResourceRequest newRequest = request; @@ -222,6 +222,13 @@ void SubresourceLoader::didCancel(const ResourceError& error) if (cancelled()) return; + + // The only way the subresource loader can reach the terminal state here is if the run loop spins when calling + // m_client->didFail. This should in theory not happen which is why the assert is here. + ASSERT(!reachedTerminalState()); + if (reachedTerminalState()) + return; + m_documentLoader->removeSubresourceLoader(this); ResourceLoader::didCancel(error); } diff --git a/WebCore/loader/ThreadableLoader.cpp b/WebCore/loader/ThreadableLoader.cpp index 1b2cc88..7b9c6c6 100644 --- a/WebCore/loader/ThreadableLoader.cpp +++ b/WebCore/loader/ThreadableLoader.cpp @@ -40,33 +40,33 @@ namespace WebCore { -PassRefPtr<ThreadableLoader> ThreadableLoader::create(ScriptExecutionContext* context, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +PassRefPtr<ThreadableLoader> ThreadableLoader::create(ScriptExecutionContext* context, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) { ASSERT(client); ASSERT(context); #if ENABLE(WORKERS) if (context->isWorkerContext()) - return WorkerThreadableLoader::create(static_cast<WorkerContext*>(context), client, WorkerRunLoop::defaultMode(), request, callbacksSetting, contentSniff); + return WorkerThreadableLoader::create(static_cast<WorkerContext*>(context), client, WorkerRunLoop::defaultMode(), request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck); #endif // ENABLE(WORKERS) ASSERT(context->isDocument()); - return DocumentThreadableLoader::create(static_cast<Document*>(context), client, request, callbacksSetting, contentSniff); + return DocumentThreadableLoader::create(static_cast<Document*>(context), client, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck); } -void ThreadableLoader::loadResourceSynchronously(ScriptExecutionContext* context, const ResourceRequest& request, ThreadableLoaderClient& client) +void ThreadableLoader::loadResourceSynchronously(ScriptExecutionContext* context, const ResourceRequest& request, ThreadableLoaderClient& client, StoredCredentials storedCredentials) { ASSERT(context); #if ENABLE(WORKERS) if (context->isWorkerContext()) { - WorkerThreadableLoader::loadResourceSynchronously(static_cast<WorkerContext*>(context), request, client); + WorkerThreadableLoader::loadResourceSynchronously(static_cast<WorkerContext*>(context), request, client, storedCredentials, RequireSameRedirectOrigin); return; } #endif // ENABLE(WORKERS) ASSERT(context->isDocument()); - DocumentThreadableLoader::loadResourceSynchronously(static_cast<Document*>(context), request, client); + DocumentThreadableLoader::loadResourceSynchronously(static_cast<Document*>(context), request, client, storedCredentials); } } // namespace WebCore diff --git a/WebCore/loader/ThreadableLoader.h b/WebCore/loader/ThreadableLoader.h index b051b32..0a4c4e3 100644 --- a/WebCore/loader/ThreadableLoader.h +++ b/WebCore/loader/ThreadableLoader.h @@ -53,12 +53,22 @@ namespace WebCore { DoNotSniffContent }; + enum StoredCredentials { + AllowStoredCredentials, + DoNotAllowStoredCredentials + }; + + enum RedirectOriginCheck { + RequireSameRedirectOrigin, + AllowDifferentRedirectOrigin + }; + // Useful for doing loader operations from any thread (not threadsafe, // just able to run on threads other than the main thread). class ThreadableLoader : Noncopyable { public: - static void loadResourceSynchronously(ScriptExecutionContext*, const ResourceRequest&, ThreadableLoaderClient&); - static PassRefPtr<ThreadableLoader> create(ScriptExecutionContext*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff); + static void loadResourceSynchronously(ScriptExecutionContext*, const ResourceRequest&, ThreadableLoaderClient&, StoredCredentials); + static PassRefPtr<ThreadableLoader> create(ScriptExecutionContext*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); virtual void cancel() = 0; void ref() { refThreadableLoader(); } diff --git a/WebCore/loader/WorkerThreadableLoader.cpp b/WebCore/loader/WorkerThreadableLoader.cpp index 731ffcb..8153ad8 100644 --- a/WebCore/loader/WorkerThreadableLoader.cpp +++ b/WebCore/loader/WorkerThreadableLoader.cpp @@ -40,7 +40,7 @@ #include "ResourceResponse.h" #include "ThreadableLoader.h" #include "WorkerContext.h" -#include "WorkerMessagingProxy.h" +#include "WorkerLoaderProxy.h" #include "WorkerThread.h" #include <memory> #include <wtf/OwnPtr.h> @@ -53,13 +53,11 @@ namespace WebCore { static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode"; -// FIXME: The assumption that we can upcast worker object proxy to WorkerMessagingProxy will not be true in multi-process implementation. WorkerThreadableLoader::WorkerThreadableLoader(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, LoadCallbacks callbacksSetting, - ContentSniff contentSniff) + ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) : m_workerContext(workerContext) , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client)) - , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, *(static_cast<WorkerMessagingProxy*>(m_workerContext->thread()->workerObjectProxy())), taskMode, request, callbacksSetting, - contentSniff))) + , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, m_workerContext->thread()->workerLoaderProxy(), taskMode, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck))) { } @@ -68,7 +66,7 @@ WorkerThreadableLoader::~WorkerThreadableLoader() m_bridge.destroy(); } -void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerContext, const ResourceRequest& request, ThreadableLoaderClient& client) +void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerContext, const ResourceRequest& request, ThreadableLoaderClient& client, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) { WorkerRunLoop& runLoop = workerContext->thread()->runLoop(); @@ -77,7 +75,7 @@ void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerCont mode.append(String::number(runLoop.createUniqueId())); ContentSniff contentSniff = request.url().isLocalFile() ? SniffContent : DoNotSniffContent; - RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerContext, &client, mode, request, DoNotSendLoadCallbacks, contentSniff); + RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerContext, &client, mode, request, DoNotSendLoadCallbacks, contentSniff, storedCredentials, redirectOriginCheck); MessageQueueWaitResult result = MessageQueueMessageReceived; while (!loader->done() && result != MessageQueueTerminated) @@ -92,32 +90,26 @@ void WorkerThreadableLoader::cancel() m_bridge.cancel(); } -WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, WorkerMessagingProxy& messagingProxy, const String& taskMode, - const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, WorkerLoaderProxy& loaderProxy, const String& taskMode, + const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, + RedirectOriginCheck redirectOriginCheck) : m_workerClientWrapper(workerClientWrapper) - , m_messagingProxy(messagingProxy) + , m_loaderProxy(loaderProxy) , m_taskMode(taskMode.copy()) { ASSERT(m_workerClientWrapper.get()); - m_messagingProxy.postTaskToWorkerObject(createCallbackTask(&MainThreadBridge::mainThreadCreateLoader, this, request, callbacksSetting, contentSniff)); + m_loaderProxy.postTaskToLoader(createCallbackTask(&MainThreadBridge::mainThreadCreateLoader, this, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck)); } WorkerThreadableLoader::MainThreadBridge::~MainThreadBridge() { } -void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExecutionContext* context, MainThreadBridge* thisPtr, auto_ptr<CrossThreadResourceRequestData> requestData, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExecutionContext* context, MainThreadBridge* thisPtr, auto_ptr<CrossThreadResourceRequestData> requestData, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) { - // FIXME: This assert fails for nested workers. Removing the assert would allow it to work, - // but then there would be one WorkerThreadableLoader in every intermediate worker simply - // chaining the requests, which is not very good. Instead, the postTaskToWorkerObject should be a - // postTaskToDocumentContext. ASSERT(isMainThread()); ASSERT(context->isDocument()); - if (thisPtr->m_messagingProxy.askedToTerminate()) - return; - // FIXME: the created loader has no knowledge of the origin of the worker doing the load request. // Basically every setting done in SubresourceLoader::create (including the contents of addExtraFieldsToRequest) // needs to be examined for how it should take into account a different originator. @@ -125,7 +117,7 @@ void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExec // FIXME: If the a site requests a local resource, then this will return a non-zero value but the sync path // will return a 0 value. Either this should return 0 or the other code path should do a callback with // a failure. - thisPtr->m_mainThreadLoader = ThreadableLoader::create(context, thisPtr, *request, callbacksSetting, contentSniff); + thisPtr->m_mainThreadLoader = ThreadableLoader::create(context, thisPtr, *request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck); ASSERT(thisPtr->m_mainThreadLoader); } @@ -142,7 +134,7 @@ void WorkerThreadableLoader::MainThreadBridge::destroy() clearClientWrapper(); // "delete this" and m_mainThreadLoader::deref() on the worker object's thread. - m_messagingProxy.postTaskToWorkerObject(createCallbackTask(&MainThreadBridge::mainThreadDestroy, this)); + m_loaderProxy.postTaskToLoader(createCallbackTask(&MainThreadBridge::mainThreadDestroy, this)); } void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ScriptExecutionContext* context, MainThreadBridge* thisPtr) @@ -158,7 +150,7 @@ void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ScriptExecutionC void WorkerThreadableLoader::MainThreadBridge::cancel() { - m_messagingProxy.postTaskToWorkerObject(createCallbackTask(&MainThreadBridge::mainThreadCancel, this)); + m_loaderProxy.postTaskToLoader(createCallbackTask(&MainThreadBridge::mainThreadCancel, this)); ThreadableLoaderClientWrapper* clientWrapper = static_cast<ThreadableLoaderClientWrapper*>(m_workerClientWrapper.get()); if (!clientWrapper->done()) { // If the client hasn't reached a termination state, then transition it by sending a cancellation error. @@ -183,7 +175,7 @@ static void workerContextDidSendData(ScriptExecutionContext* context, RefPtr<Thr void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) { - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode); } static void workerContextDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<CrossThreadResourceResponseData> responseData) @@ -195,7 +187,7 @@ static void workerContextDidReceiveResponse(ScriptExecutionContext* context, Ref void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(const ResourceResponse& response) { - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveResponse, m_workerClientWrapper, response), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveResponse, m_workerClientWrapper, response), m_taskMode); } static void workerContextDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<Vector<char> > vectorData) @@ -208,7 +200,7 @@ void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data, { auto_ptr<Vector<char> > vector(new Vector<char>(lengthReceived)); // needs to be an auto_ptr for usage with createCallbackTask. memcpy(vector->data(), data, lengthReceived); - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveData, m_workerClientWrapper, vector), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveData, m_workerClientWrapper, vector), m_taskMode); } static void workerContextDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier) @@ -219,7 +211,7 @@ static void workerContextDidFinishLoading(ScriptExecutionContext* context, RefPt void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long identifier) { - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFinishLoading, m_workerClientWrapper, identifier), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFinishLoading, m_workerClientWrapper, identifier), m_taskMode); } static void workerContextDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error) @@ -230,7 +222,7 @@ static void workerContextDidFail(ScriptExecutionContext* context, RefPtr<Threada void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error) { - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFail, m_workerClientWrapper, error), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFail, m_workerClientWrapper, error), m_taskMode); } static void workerContextDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper) @@ -241,7 +233,7 @@ static void workerContextDidFailRedirectCheck(ScriptExecutionContext* context, R void WorkerThreadableLoader::MainThreadBridge::didFailRedirectCheck() { - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailRedirectCheck, m_workerClientWrapper), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailRedirectCheck, m_workerClientWrapper), m_taskMode); } static void workerContextDidReceiveAuthenticationCancellation(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<CrossThreadResourceResponseData> responseData) @@ -253,7 +245,7 @@ static void workerContextDidReceiveAuthenticationCancellation(ScriptExecutionCon void WorkerThreadableLoader::MainThreadBridge::didReceiveAuthenticationCancellation(const ResourceResponse& response) { - m_messagingProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveAuthenticationCancellation, m_workerClientWrapper, response), m_taskMode); + m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveAuthenticationCancellation, m_workerClientWrapper, response), m_taskMode); } } // namespace WebCore diff --git a/WebCore/loader/WorkerThreadableLoader.h b/WebCore/loader/WorkerThreadableLoader.h index 5462a97..a36bedf 100644 --- a/WebCore/loader/WorkerThreadableLoader.h +++ b/WebCore/loader/WorkerThreadableLoader.h @@ -49,16 +49,16 @@ namespace WebCore { class ResourceError; struct ResourceRequest; class WorkerContext; - class WorkerMessagingProxy; + class WorkerLoaderProxy; struct CrossThreadResourceResponseData; struct CrossThreadResourceRequestData; class WorkerThreadableLoader : public RefCounted<WorkerThreadableLoader>, public ThreadableLoader { public: - static void loadResourceSynchronously(WorkerContext*, const ResourceRequest&, ThreadableLoaderClient&); - static PassRefPtr<WorkerThreadableLoader> create(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) + static void loadResourceSynchronously(WorkerContext*, const ResourceRequest&, ThreadableLoaderClient&, StoredCredentials, RedirectOriginCheck); + static PassRefPtr<WorkerThreadableLoader> create(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) { - return adoptRef(new WorkerThreadableLoader(workerContext, client, taskMode, request, callbacksSetting, contentSniff)); + return adoptRef(new WorkerThreadableLoader(workerContext, client, taskMode, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck)); } ~WorkerThreadableLoader(); @@ -86,7 +86,7 @@ namespace WebCore { // // case 1. worker.terminate is called. // In this case, no more tasks are posted from the worker object's thread to the worker - // context's thread -- WorkerMessagingProxy enforces this. + // context's thread -- WorkerContextProxy implementation enforces this. // // case 2. xhr gets aborted and the worker context continues running. // The ThreadableLoaderClientWrapper has the underlying client cleared, so no more calls @@ -97,7 +97,7 @@ namespace WebCore { class MainThreadBridge : ThreadableLoaderClient { public: // All executed on the worker context's thread. - MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper>, WorkerMessagingProxy&, const String& taskMode, const ResourceRequest&, LoadCallbacks, ContentSniff); + MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper>, WorkerLoaderProxy&, const String& taskMode, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); void cancel(); void destroy(); @@ -109,7 +109,7 @@ namespace WebCore { static void mainThreadDestroy(ScriptExecutionContext*, MainThreadBridge*); ~MainThreadBridge(); - static void mainThreadCreateLoader(ScriptExecutionContext*, MainThreadBridge*, std::auto_ptr<CrossThreadResourceRequestData>, LoadCallbacks, ContentSniff); + static void mainThreadCreateLoader(ScriptExecutionContext*, MainThreadBridge*, std::auto_ptr<CrossThreadResourceRequestData>, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); static void mainThreadCancel(ScriptExecutionContext*, MainThreadBridge*); virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent); virtual void didReceiveResponse(const ResourceResponse&); @@ -127,13 +127,13 @@ namespace WebCore { RefPtr<ThreadSafeShared<ThreadableLoaderClientWrapper> > m_workerClientWrapper; // May be used on either thread. - WorkerMessagingProxy& m_messagingProxy; + WorkerLoaderProxy& m_loaderProxy; // For use on the main thread. String m_taskMode; }; - WorkerThreadableLoader(WorkerContext*, ThreadableLoaderClient*, const String& taskMode, const ResourceRequest&, LoadCallbacks, ContentSniff); + WorkerThreadableLoader(WorkerContext*, ThreadableLoaderClient*, const String& taskMode, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); RefPtr<WorkerContext> m_workerContext; RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper; diff --git a/WebCore/loader/appcache/ApplicationCache.cpp b/WebCore/loader/appcache/ApplicationCache.cpp index e411852..42f5b6a 100644 --- a/WebCore/loader/appcache/ApplicationCache.cpp +++ b/WebCore/loader/appcache/ApplicationCache.cpp @@ -111,7 +111,7 @@ ApplicationCacheResource* ApplicationCache::resourceForURL(const String& url) bool ApplicationCache::requestIsHTTPOrHTTPSGet(const ResourceRequest& request) { - if (!request.url().protocolIs("http") && !request.url().protocolIs("https")) + if (!request.url().protocolInHTTPFamily()) return false; if (!equalIgnoringCase(request.httpMethod(), "GET")) diff --git a/WebCore/loader/appcache/ApplicationCache.h b/WebCore/loader/appcache/ApplicationCache.h index 77653f7..afdab27 100644 --- a/WebCore/loader/appcache/ApplicationCache.h +++ b/WebCore/loader/appcache/ApplicationCache.h @@ -41,7 +41,8 @@ class ApplicationCacheGroup; class ApplicationCacheResource; class DocumentLoader; class KURL; -class ResourceRequest; + +struct ResourceRequest; typedef Vector<std::pair<KURL, KURL> > FallbackURLVector; diff --git a/WebCore/loader/appcache/ApplicationCacheGroup.cpp b/WebCore/loader/appcache/ApplicationCacheGroup.cpp index 1b16b50..9f2f6a4 100644 --- a/WebCore/loader/appcache/ApplicationCacheGroup.cpp +++ b/WebCore/loader/appcache/ApplicationCacheGroup.cpp @@ -47,6 +47,7 @@ namespace WebCore { ApplicationCacheGroup::ApplicationCacheGroup(const KURL& manifestURL, bool isCopy) : m_manifestURL(manifestURL) , m_updateStatus(Idle) + , m_downloadingPendingMasterResourceLoadersCount(0) , m_frame(0) , m_storageID(0) , m_isObsolete(false) @@ -166,6 +167,7 @@ void ApplicationCacheGroup::selectCache(Frame* frame, const KURL& manifestURL) documentLoader->setCandidateApplicationCacheGroup(group); group->m_pendingMasterResourceLoaders.add(documentLoader); + group->m_downloadingPendingMasterResourceLoadersCount++; ASSERT(!group->m_cacheBeingUpdated || group->m_updateStatus != Idle); group->update(frame, ApplicationCacheUpdateWithBrowsingContext); @@ -232,7 +234,7 @@ void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader) break; } - m_pendingMasterResourceLoaders.remove(loader); + m_downloadingPendingMasterResourceLoadersCount--; checkIfLoadIsComplete(); } @@ -276,7 +278,7 @@ void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader* loader) break; } - m_pendingMasterResourceLoaders.remove(loader); + m_downloadingPendingMasterResourceLoadersCount--; checkIfLoadIsComplete(); } @@ -347,8 +349,6 @@ void ApplicationCacheGroup::cacheDestroyed(ApplicationCache* cache) void ApplicationCacheGroup::setNewestCache(PassRefPtr<ApplicationCache> newestCache) { - ASSERT(!m_caches.contains(newestCache.get())); - m_newestCache = newestCache; m_caches.add(m_newestCache.get()); @@ -681,6 +681,7 @@ void ApplicationCacheGroup::manifestNotFound() m_pendingMasterResourceLoaders.remove(it); } + m_downloadingPendingMasterResourceLoadersCount = 0; m_updateStatus = Idle; m_frame = 0; @@ -693,7 +694,7 @@ void ApplicationCacheGroup::manifestNotFound() void ApplicationCacheGroup::checkIfLoadIsComplete() { - if (m_manifestHandle || !m_pendingEntries.isEmpty() || !m_pendingMasterResourceLoaders.isEmpty()) + if (m_manifestHandle || !m_pendingEntries.isEmpty() || m_downloadingPendingMasterResourceLoadersCount) return; // We're done, all resources have finished downloading (successfully or not). @@ -732,16 +733,43 @@ void ApplicationCacheGroup::checkIfLoadIsComplete() RefPtr<ApplicationCache> oldNewestCache = (m_newestCache == m_cacheBeingUpdated) ? 0 : m_newestCache; setNewestCache(m_cacheBeingUpdated.release()); - cacheStorage().storeNewestCache(this); - - if (oldNewestCache) - cacheStorage().remove(oldNewestCache.get()); - - postListenerTask(isUpgradeAttempt ? &DOMApplicationCache::callUpdateReadyListener : &DOMApplicationCache::callCachedListener, m_associatedDocumentLoaders); + if (cacheStorage().storeNewestCache(this)) {
+ // New cache stored, now remove the old cache.
+ if (oldNewestCache)
+ cacheStorage().remove(oldNewestCache.get());
+ // Fire the success events.
+ postListenerTask(isUpgradeAttempt ? &DOMApplicationCache::callUpdateReadyListener : &DOMApplicationCache::callCachedListener, m_associatedDocumentLoaders);
+ } else {
+ // Run the "cache failure steps"
+ // Fire the error events to all pending master entries, as well any other cache hosts
+ // currently associated with a cache in this group.
+ postListenerTask(&DOMApplicationCache::callErrorListener, m_associatedDocumentLoaders);
+ // Disassociate the pending master entries from the failed new cache. Note that
+ // all other loaders in the m_associatedDocumentLoaders are still associated with
+ // some other cache in this group. They are not associated with the failed new cache.
+
+ // Need to copy loaders, because the cache group may be destroyed at the end of iteration. + Vector<DocumentLoader*> loaders; + copyToVector(m_pendingMasterResourceLoaders, loaders); + size_t count = loaders.size(); + for (size_t i = 0; i != count; ++i)
+ disassociateDocumentLoader(loaders[i]); // This can delete this group.
+
+ // Reinstate the oldNewestCache, if there was one.
+ if (oldNewestCache) {
+ // This will discard the failed new cache.
+ setNewestCache(oldNewestCache.release());
+ } else {
+ // We must have been deleted by the last call to disassociateDocumentLoader().
+ return;
+ }
+ }
break; } } + // Empty cache group's list of pending master entries. + m_pendingMasterResourceLoaders.clear(); m_completionType = None; m_updateStatus = Idle; m_frame = 0; diff --git a/WebCore/loader/appcache/ApplicationCacheGroup.h b/WebCore/loader/appcache/ApplicationCacheGroup.h index aebf0ab..063fb3b 100644 --- a/WebCore/loader/appcache/ApplicationCacheGroup.h +++ b/WebCore/loader/appcache/ApplicationCacheGroup.h @@ -134,6 +134,8 @@ private: // List of pending master entries, used during the update process to ensure that new master entries are cached. HashSet<DocumentLoader*> m_pendingMasterResourceLoaders; + // How many of the above pending master entries have not yet finished downloading. + int m_downloadingPendingMasterResourceLoadersCount; // These are all the document loaders that are associated with a cache in this group. HashSet<DocumentLoader*> m_associatedDocumentLoaders; diff --git a/WebCore/loader/appcache/ApplicationCacheStorage.cpp b/WebCore/loader/appcache/ApplicationCacheStorage.cpp index 791df22..1c59581 100644 --- a/WebCore/loader/appcache/ApplicationCacheStorage.cpp +++ b/WebCore/loader/appcache/ApplicationCacheStorage.cpp @@ -43,6 +43,44 @@ using namespace std; namespace WebCore { +class ResourceStorageIDJournal { +public: + ~ResourceStorageIDJournal() + { + size_t size = m_records.size(); + for (size_t i = 0; i < size; ++i) + m_records[i].restore(); + } + + void add(ApplicationCacheResource* resource, unsigned storageID) + { + m_records.append(Record(resource, storageID)); + } + + void commit() + { + m_records.clear(); + } + +private: + class Record { + public: + Record() : m_resource(0), m_storageID(0) { } + Record(ApplicationCacheResource* resource, unsigned storageID) : m_resource(resource), m_storageID(storageID) { } + + void restore() + { + m_resource->setStorageID(m_storageID); + } + + private: + ApplicationCacheResource* m_resource; + unsigned m_storageID; + }; + + Vector<Record> m_records; +}; + static unsigned urlHostHash(const KURL& url) { unsigned hostStart = url.hostStart(); @@ -436,10 +474,11 @@ bool ApplicationCacheStorage::store(ApplicationCacheGroup* group) return true; } -bool ApplicationCacheStorage::store(ApplicationCache* cache) +bool ApplicationCacheStorage::store(ApplicationCache* cache, ResourceStorageIDJournal* storageIDJournal) { ASSERT(cache->storageID() == 0); ASSERT(cache->group()->storageID() != 0); + ASSERT(storageIDJournal); SQLiteStatement statement(m_database, "INSERT INTO Caches (cacheGroup) VALUES (?)"); if (statement.prepare() != SQLResultOk) @@ -456,8 +495,13 @@ bool ApplicationCacheStorage::store(ApplicationCache* cache) { ApplicationCache::ResourceMap::const_iterator end = cache->end(); for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) { + unsigned oldStorageID = it->second->storageID(); if (!store(it->second.get(), cacheStorageID)) return false; + + // Storing the resource succeeded. Log its old storageID in case + // it needs to be restored later. + storageIDJournal->add(it->second.get(), oldStorageID); } } @@ -618,8 +662,13 @@ bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group) ASSERT(!group->isObsolete()); ASSERT(!group->newestCache()->storageID()); + // Log the storageID changes to the in-memory resource objects. The journal + // object will roll them back automatically in case a database operation + // fails and this method returns early. + ResourceStorageIDJournal storageIDJournal; + // Store the newest cache - if (!store(group->newestCache())) + if (!store(group->newestCache(), &storageIDJournal)) return false; // Update the newest cache in the group. @@ -634,6 +683,7 @@ bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group) if (!executeStatement(statement)) return false; + storageIDJournal.commit(); storeCacheTransaction.commit(); return true; } diff --git a/WebCore/loader/appcache/ApplicationCacheStorage.h b/WebCore/loader/appcache/ApplicationCacheStorage.h index a0eb4ee..b13b596 100644 --- a/WebCore/loader/appcache/ApplicationCacheStorage.h +++ b/WebCore/loader/appcache/ApplicationCacheStorage.h @@ -40,6 +40,7 @@ class ApplicationCache; class ApplicationCacheGroup; class ApplicationCacheResource; class KURL; +class ResourceStorageIDJournal; class ApplicationCacheStorage { public: @@ -69,7 +70,7 @@ private: ApplicationCacheGroup* loadCacheGroup(const KURL& manifestURL); bool store(ApplicationCacheGroup*); - bool store(ApplicationCache*); + bool store(ApplicationCache*, ResourceStorageIDJournal*); bool store(ApplicationCacheResource*, unsigned cacheStorageID); void loadManifestHostHashes(); diff --git a/WebCore/loader/appcache/DOMApplicationCache.idl b/WebCore/loader/appcache/DOMApplicationCache.idl index 4cf8f3a..1156c9c 100644 --- a/WebCore/loader/appcache/DOMApplicationCache.idl +++ b/WebCore/loader/appcache/DOMApplicationCache.idl @@ -43,7 +43,7 @@ module offline { void swapCache() raises(DOMException); -#if ENABLE_APPLICATION_CAHE_DYNAMIC_ENTRIES +#if defined(ENABLE_APPLICATION_CACHE_DYNAMIC_ENTRIES) && ENABLE_APPLICATION_CACHE_DYNAMIC_ENTRIES // dynamic entries readonly attribute DOMStringList items; [Custom] boolean hasItem(in DOMString url) diff --git a/WebCore/loader/icon/IconDatabase.cpp b/WebCore/loader/icon/IconDatabase.cpp index 7e339c1..1f49c88 100644 --- a/WebCore/loader/icon/IconDatabase.cpp +++ b/WebCore/loader/icon/IconDatabase.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com) * * Redistribution and use in source and binary forms, with or without @@ -28,39 +28,23 @@ #include "IconDatabase.h" #include "AutodrainedPool.h" -#include "CString.h" #include "DocumentLoader.h" #include "FileSystem.h" #include "IconDatabaseClient.h" #include "IconRecord.h" -#include "Image.h" #include "IntSize.h" -#include "KURL.h" #include "Logging.h" -#include "PageURLRecord.h" #include "SQLiteStatement.h" #include "SQLiteTransaction.h" -#include <wtf/CurrentTime.h> -#include <wtf/MainThread.h> -#include <wtf/StdLibExtras.h> - +#include "SuddenTermination.h" #if USE(JSC) #include <runtime/InitializeThreading.h> #elif USE(V8) #include "V8InitializeThreading.h" #endif - -#if PLATFORM(WIN_OS) -#include <windows.h> -#include <winbase.h> -#include <shlobj.h> -#else -#include <sys/stat.h> -#endif - -#if PLATFORM(DARWIN) -#include <pthread.h> -#endif +#include <wtf/CurrentTime.h> +#include <wtf/MainThread.h> +#include <wtf/StdLibExtras.h> // For methods that are meant to support API from the main thread - should not be called internally #define ASSERT_NOT_SYNC_THREAD() ASSERT(!m_syncThreadRunning || !IS_ICON_SYNC_THREAD()) @@ -69,7 +53,7 @@ #define IS_ICON_SYNC_THREAD() (m_syncThread == currentThread()) #define ASSERT_ICON_SYNC_THREAD() ASSERT(IS_ICON_SYNC_THREAD()) -#if PLATFORM(QT) +#if PLATFORM(QT) || PLATFORM(GTK) #define CAN_THEME_URL_ICON #endif @@ -82,12 +66,12 @@ static int databaseCleanupCounter = 0; // Currently, a mismatched schema causes the DB to be wiped and reset. This isn't // so bad during development but in the future, we would need to write a conversion // function to advance older released schemas to "current" -const int currentDatabaseVersion = 6; +static const int currentDatabaseVersion = 6; // Icons expire once every 4 days -const int iconExpirationTime = 60*60*24*4; +static const int iconExpirationTime = 60*60*24*4; -const int updateTimerDelay = 5; +static const int updateTimerDelay = 5; static bool checkIntegrityOnOpen = false; @@ -159,6 +143,7 @@ bool IconDatabase::open(const String& databasePath) // completes and m_syncThreadRunning is properly set m_syncLock.lock(); m_syncThread = createThread(IconDatabase::iconDatabaseSyncThreadStart, this, "WebCore: IconDatabase"); + m_syncThreadRunning = m_syncThread; m_syncLock.unlock(); if (!m_syncThread) return false; @@ -782,8 +767,8 @@ size_t IconDatabase::iconRecordCountWithData() } IconDatabase::IconDatabase() - : m_syncThreadRunning(false) - , m_defaultIconRecord(0) + : m_syncTimer(this, &IconDatabase::syncTimerFired) + , m_syncThreadRunning(false) , m_isEnabled(false) , m_privateBrowsingEnabled(false) , m_threadTerminationRequested(false) @@ -794,9 +779,7 @@ IconDatabase::IconDatabase() , m_imported(false) , m_isImportedSet(false) { -#if PLATFORM(DARWIN) - ASSERT(pthread_main_np()); -#endif + ASSERT(isMainThread()); } IconDatabase::~IconDatabase() @@ -829,6 +812,12 @@ void IconDatabase::notifyPendingLoadDecisions() void IconDatabase::wakeSyncThread() { + // The following is balanced by the call to enableSuddenTermination in the + // syncThreadMainLoop function. + // FIXME: It would be better to only disable sudden termination if we have + // something to write, not just if we have something to read. + disableSuddenTermination(); + MutexLocker locker(m_syncLock); m_syncCondition.signal(); } @@ -836,16 +825,24 @@ void IconDatabase::wakeSyncThread() void IconDatabase::scheduleOrDeferSyncTimer() { ASSERT_NOT_SYNC_THREAD(); - if (!m_syncTimer) - m_syncTimer.set(new Timer<IconDatabase>(this, &IconDatabase::syncTimerFired)); - m_syncTimer->startOneShot(updateTimerDelay); + if (!m_syncTimer.isActive()) { + // The following is balanced by the call to enableSuddenTermination in the + // syncTimerFired function. + disableSuddenTermination(); + } + + m_syncTimer.startOneShot(updateTimerDelay); } void IconDatabase::syncTimerFired(Timer<IconDatabase>*) { ASSERT_NOT_SYNC_THREAD(); wakeSyncThread(); + + // The following is balanced by the call to disableSuddenTermination in the + // scheduleOrDeferSyncTimer function. + enableSuddenTermination(); } // ****************** @@ -1342,7 +1339,8 @@ void IconDatabase::performURLImport() void* IconDatabase::syncThreadMainLoop() { ASSERT_ICON_SYNC_THREAD(); - static bool prunedUnretainedIcons = false; + + bool shouldReenableSuddenTermination = false; m_syncLock.lock(); @@ -1381,6 +1379,7 @@ void* IconDatabase::syncThreadMainLoop() // or if private browsing is enabled // We also don't want to prune if the m_databaseCleanupCounter count is non-zero - that means someone // has asked to delay pruning + static bool prunedUnretainedIcons = false; if (didWrite && !m_privateBrowsingEnabled && !prunedUnretainedIcons && !databaseCleanupCounter) { #ifndef NDEBUG double time = currentTime(); @@ -1413,13 +1412,32 @@ void* IconDatabase::syncThreadMainLoop() // We handle those at the top of this main loop so continue to jump back up there if (shouldStopThreadActivity()) continue; - - m_syncCondition.wait(m_syncLock); + + if (shouldReenableSuddenTermination) { + // The following is balanced by the call to disableSuddenTermination in the + // wakeSyncThread function. Any time we wait on the condition, we also have + // to enableSuddenTermation, after doing the next batch of work. + enableSuddenTermination(); + } + + m_syncCondition.wait(m_syncLock); + + shouldReenableSuddenTermination = true; } + m_syncLock.unlock(); // Thread is terminating at this point - return cleanupSyncThread(); + cleanupSyncThread(); + + if (shouldReenableSuddenTermination) { + // The following is balanced by the call to disableSuddenTermination in the + // wakeSyncThread function. Any time we wait on the condition, we also have + // to enableSuddenTermation, after doing the next batch of work. + enableSuddenTermination(); + } + + return 0; } bool IconDatabase::readFromDatabase() @@ -1706,23 +1724,23 @@ void IconDatabase::removeAllIconsOnThread() } void IconDatabase::deleteAllPreparedStatements() -{ +{ ASSERT_ICON_SYNC_THREAD(); - m_setIconIDForPageURLStatement.set(0); - m_removePageURLStatement.set(0); - m_getIconIDForIconURLStatement.set(0); - m_getImageDataForIconURLStatement.set(0); - m_addIconToIconInfoStatement.set(0); - m_addIconToIconDataStatement.set(0); - m_getImageDataStatement.set(0); - m_deletePageURLsForIconURLStatement.set(0); - m_deleteIconFromIconInfoStatement.set(0); - m_deleteIconFromIconDataStatement.set(0); - m_updateIconInfoStatement.set(0); - m_updateIconDataStatement.set(0); - m_setIconInfoStatement.set(0); - m_setIconDataStatement.set(0); + m_setIconIDForPageURLStatement.clear(); + m_removePageURLStatement.clear(); + m_getIconIDForIconURLStatement.clear(); + m_getImageDataForIconURLStatement.clear(); + m_addIconToIconInfoStatement.clear(); + m_addIconToIconDataStatement.clear(); + m_getImageDataStatement.clear(); + m_deletePageURLsForIconURLStatement.clear(); + m_deleteIconFromIconInfoStatement.clear(); + m_deleteIconFromIconDataStatement.clear(); + m_updateIconInfoStatement.clear(); + m_updateIconDataStatement.clear(); + m_setIconInfoStatement.clear(); + m_setIconDataStatement.clear(); } void* IconDatabase::cleanupSyncThread() diff --git a/WebCore/loader/icon/IconDatabase.h b/WebCore/loader/icon/IconDatabase.h index 4303ae1..40f641a 100644 --- a/WebCore/loader/icon/IconDatabase.h +++ b/WebCore/loader/icon/IconDatabase.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com) * * Redistribution and use in source and binary forms, with or without @@ -27,17 +27,15 @@ #ifndef IconDatabase_h #define IconDatabase_h -#if ENABLE(ICONDATABASE) -#include "SQLiteDatabase.h" -#endif - #include "StringHash.h" #include "Timer.h" #include <wtf/HashMap.h> #include <wtf/HashSet.h> #include <wtf/Noncopyable.h> #include <wtf/OwnPtr.h> + #if ENABLE(ICONDATABASE) +#include "SQLiteDatabase.h" #include <wtf/Threading.h> #endif @@ -116,9 +114,9 @@ private: void wakeSyncThread(); void scheduleOrDeferSyncTimer(); - OwnPtr<Timer<IconDatabase> > m_syncTimer; void syncTimerFired(Timer<IconDatabase>*); + Timer<IconDatabase> m_syncTimer; ThreadIdentifier m_syncThread; bool m_syncThreadRunning; diff --git a/WebCore/loader/loader.cpp b/WebCore/loader/loader.cpp index b8d1ab7..a5549d1 100644 --- a/WebCore/loader/loader.cpp +++ b/WebCore/loader/loader.cpp @@ -48,20 +48,22 @@ namespace WebCore { #if REQUEST_MANAGEMENT_ENABLED // Match the parallel connection count used by the networking layer -// FIXME should not hardcode something like this -static const unsigned maxRequestsInFlightPerHost = 4; +static unsigned maxRequestsInFlightPerHost; // Having a limit might still help getting more important resources first static const unsigned maxRequestsInFlightForNonHTTPProtocols = 20; #else static const unsigned maxRequestsInFlightPerHost = 10000; static const unsigned maxRequestsInFlightForNonHTTPProtocols = 10000; #endif - - + Loader::Loader() - : m_nonHTTPProtocolHost(AtomicString(), maxRequestsInFlightForNonHTTPProtocols) - , m_requestTimer(this, &Loader::requestTimerFired) + : m_requestTimer(this, &Loader::requestTimerFired) + , m_isSuspendingPendingRequests(false) { + m_nonHTTPProtocolHost = Host::create(AtomicString(), maxRequestsInFlightForNonHTTPProtocols); +#if REQUEST_MANAGEMENT_ENABLED + maxRequestsInFlightPerHost = initializeMaximumHTTPConnectionCountPerHost(); +#endif } Loader::~Loader() @@ -99,25 +101,24 @@ void Loader::load(DocLoader* docLoader, CachedResource* resource, bool increment ASSERT(docLoader); Request* request = new Request(docLoader, resource, incremental, skipCanLoadCheck, sendResourceLoadCallbacks); - Host* host; + RefPtr<Host> host; KURL url(resource->url()); - bool isHTTP = url.protocolIs("http") || url.protocolIs("https"); - if (isHTTP) { + if (url.protocolInHTTPFamily()) { AtomicString hostName = url.host(); host = m_hosts.get(hostName.impl()); if (!host) { - host = new Host(hostName, maxRequestsInFlightPerHost); + host = Host::create(hostName, maxRequestsInFlightPerHost); m_hosts.add(hostName.impl(), host); } } else - host = &m_nonHTTPProtocolHost; + host = m_nonHTTPProtocolHost; bool hadRequests = host->hasRequests(); Priority priority = determinePriority(resource); host->addRequest(request, priority); docLoader->incrementRequestCount(); - if (priority > Low || !isHTTP || !hadRequests) { + if (priority > Low || !url.protocolInHTTPFamily() || !hadRequests) { // Try to request important resources immediately host->servePendingRequests(priority); } else { @@ -139,33 +140,57 @@ void Loader::requestTimerFired(Timer<Loader>*) void Loader::servePendingRequests(Priority minimumPriority) { + if (m_isSuspendingPendingRequests) + return; + m_requestTimer.stop(); - m_nonHTTPProtocolHost.servePendingRequests(minimumPriority); + m_nonHTTPProtocolHost->servePendingRequests(minimumPriority); Vector<Host*> hostsToServe; - copyValuesToVector(m_hosts, hostsToServe); + HostMap::iterator i = m_hosts.begin(); + HostMap::iterator end = m_hosts.end(); + for (;i != end; ++i) + hostsToServe.append(i->second.get()); + for (unsigned n = 0; n < hostsToServe.size(); ++n) { Host* host = hostsToServe[n]; if (host->hasRequests()) host->servePendingRequests(minimumPriority); else if (!host->processingResource()){ AtomicString name = host->name(); - delete host; m_hosts.remove(name.impl()); } } } - + +void Loader::suspendPendingRequests() +{ + ASSERT(!m_isSuspendingPendingRequests); + m_isSuspendingPendingRequests = true; +} + +void Loader::resumePendingRequests() +{ + ASSERT(m_isSuspendingPendingRequests); + m_isSuspendingPendingRequests = false; + if (!m_hosts.isEmpty() || m_nonHTTPProtocolHost->hasRequests()) + scheduleServePendingRequests(); +} + void Loader::cancelRequests(DocLoader* docLoader) { docLoader->clearPendingPreloads(); - if (m_nonHTTPProtocolHost.hasRequests()) - m_nonHTTPProtocolHost.cancelRequests(docLoader); + if (m_nonHTTPProtocolHost->hasRequests()) + m_nonHTTPProtocolHost->cancelRequests(docLoader); Vector<Host*> hostsToCancel; - copyValuesToVector(m_hosts, hostsToCancel); + HostMap::iterator i = m_hosts.begin(); + HostMap::iterator end = m_hosts.end(); + for (;i != end; ++i) + hostsToCancel.append(i->second.get()); + for (unsigned n = 0; n < hostsToCancel.size(); ++n) { Host* host = hostsToCancel[n]; if (host->hasRequests()) @@ -176,7 +201,7 @@ void Loader::cancelRequests(DocLoader* docLoader) ASSERT(docLoader->requestCount() == (docLoader->loadInProgress() ? 1 : 0)); } - + Loader::Host::Host(const AtomicString& name, unsigned maxRequestsInFlight) : m_name(name) , m_maxRequestsInFlight(maxRequestsInFlight) @@ -209,6 +234,9 @@ bool Loader::Host::hasRequests() const void Loader::Host::servePendingRequests(Loader::Priority minimumPriority) { + if (cache()->loader()->isSuspendingPendingRequests()) + return; + bool serveMore = true; for (int priority = High; priority >= minimumPriority && serveMore; --priority) servePendingRequests(m_requestsPending[priority], serveMore); @@ -238,11 +266,7 @@ void Loader::Host::servePendingRequests(RequestQueue& requestsPending, bool& ser if (!request->cachedResource()->accept().isEmpty()) resourceRequest.setHTTPAccept(request->cachedResource()->accept()); - KURL referrer = docLoader->doc()->url(); - if ((referrer.protocolIs("http") || referrer.protocolIs("https")) && referrer.path().isEmpty()) - referrer.setPath("/"); - resourceRequest.setHTTPReferrer(referrer.string()); - FrameLoader::addHTTPOriginIfNeeded(resourceRequest, docLoader->doc()->securityOrigin()->toString()); + // Do not set the referrer or HTTP origin here. That's handled by SubresourceLoader::create. if (resourceIsCacheValidator) { CachedResource* resourceToRevalidate = request->cachedResource()->resourceToRevalidate(); @@ -262,7 +286,7 @@ void Loader::Host::servePendingRequests(RequestQueue& requestsPending, bool& ser } RefPtr<SubresourceLoader> loader = SubresourceLoader::create(docLoader->doc()->frame(), - this, resourceRequest, request->shouldSkipCanLoadCheck(), request->sendResourceLoadCallbacks()); + this, resourceRequest, request->shouldSkipCanLoadCheck(), request->sendResourceLoadCallbacks()); if (loader) { m_requestsLoading.add(loader.release(), request); request->cachedResource()->setRequestedFromNetworkingLayer(); @@ -281,12 +305,12 @@ void Loader::Host::servePendingRequests(RequestQueue& requestsPending, bool& ser void Loader::Host::didFinishLoading(SubresourceLoader* loader) { + RefPtr<Host> myProtector(this); + RequestMap::iterator i = m_requestsLoading.find(loader); if (i == m_requestsLoading.end()) return; - ProcessingResource processingResource(this); - Request* request = i->second; m_requestsLoading.remove(i); DocLoader* docLoader = request->docLoader(); @@ -327,13 +351,13 @@ void Loader::Host::didFail(SubresourceLoader* loader, const ResourceError&) void Loader::Host::didFail(SubresourceLoader* loader, bool cancelled) { + RefPtr<Host> myProtector(this); + loader->clearClient(); RequestMap::iterator i = m_requestsLoading.find(loader); if (i == m_requestsLoading.end()) return; - - ProcessingResource processingResource(this); Request* request = i->second; m_requestsLoading.remove(i); @@ -367,6 +391,8 @@ void Loader::Host::didFail(SubresourceLoader* loader, bool cancelled) void Loader::Host::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response) { + RefPtr<Host> protector(this); + Request* request = m_requestsLoading.get(loader); // FIXME: This is a workaround for <rdar://problem/5236843> @@ -428,6 +454,8 @@ void Loader::Host::didReceiveResponse(SubresourceLoader* loader, const ResourceR void Loader::Host::didReceiveData(SubresourceLoader* loader, const char* data, int size) { + RefPtr<Host> protector(this); + Request* request = m_requestsLoading.get(loader); if (!request) return; @@ -437,12 +465,11 @@ void Loader::Host::didReceiveData(SubresourceLoader* loader, const char* data, i if (resource->errorOccurred()) return; - - ProcessingResource processingResource(this); - + if (resource->response().httpStatusCode() / 100 == 4) { - // Treat a 4xx response like a network error. - resource->error(); + // Treat a 4xx response like a network error for all resources but images (which will ignore the error and continue to load for + // legacy compatibility). + resource->httpStatusCodeError(); return; } diff --git a/WebCore/loader/loader.h b/WebCore/loader/loader.h index 19c3fda..c5b9416 100644 --- a/WebCore/loader/loader.h +++ b/WebCore/loader/loader.h @@ -49,15 +49,22 @@ namespace WebCore { enum Priority { Low, Medium, High }; void servePendingRequests(Priority minimumPriority = Low); + bool isSuspendingPendingRequests() { return m_isSuspendingPendingRequests; } + void suspendPendingRequests(); + void resumePendingRequests(); + private: Priority determinePriority(const CachedResource*) const; void scheduleServePendingRequests(); void requestTimerFired(Timer<Loader>*); - class Host : private SubresourceLoaderClient { + class Host : public RefCounted<Host>, private SubresourceLoaderClient { public: - Host(const AtomicString& name, unsigned maxRequestsInFlight); + static PassRefPtr<Host> create(const AtomicString& name, unsigned maxRequestsInFlight) + { + return adoptRef(new Host(name, maxRequestsInFlight)); + } ~Host(); const AtomicString& name() const { return m_name; } @@ -69,22 +76,7 @@ namespace WebCore { bool processingResource() const { return m_numResourcesProcessing != 0; } private: - class ProcessingResource { - public: - ProcessingResource(Host* host) - : m_host(host) - { - m_host->m_numResourcesProcessing++; - } - - ~ProcessingResource() - { - m_host->m_numResourcesProcessing--; - } - - private: - Host* m_host; - }; + Host(const AtomicString&, unsigned); virtual void didReceiveResponse(SubresourceLoader*, const ResourceResponse&); virtual void didReceiveData(SubresourceLoader*, const char*, int); @@ -103,11 +95,13 @@ namespace WebCore { const int m_maxRequestsInFlight; int m_numResourcesProcessing; }; - typedef HashMap<AtomicStringImpl*, Host*> HostMap; + typedef HashMap<AtomicStringImpl*, RefPtr<Host> > HostMap; HostMap m_hosts; - Host m_nonHTTPProtocolHost; + RefPtr<Host> m_nonHTTPProtocolHost; Timer<Loader> m_requestTimer; + + bool m_isSuspendingPendingRequests; }; } |