MainResourceLoader.cpp [plain text]
#include "config.h"
#include "MainResourceLoader.h"
#include "ApplicationCacheHost.h"
#include "Console.h"
#include "DOMWindow.h"
#include "Document.h"
#include "DocumentLoadTiming.h"
#include "DocumentLoader.h"
#include "FormState.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "HTMLFormElement.h"
#include "InspectorInstrumentation.h"
#include "Page.h"
#include "ResourceError.h"
#include "ResourceHandle.h"
#include "ResourceLoadScheduler.h"
#include "SchemeRegistry.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include <wtf/CurrentTime.h>
#if PLATFORM(QT)
#include "PluginDatabase.h"
#endif
namespace WebCore {
MainResourceLoader::MainResourceLoader(Frame* frame)
: ResourceLoader(frame, true, true)
, m_dataLoadTimer(this, &MainResourceLoader::handleDataLoadNow)
, m_loadingMultipartContent(false)
, m_waitingForContentPolicy(false)
, m_timeOfLastDataReceived(0.0)
{
}
MainResourceLoader::~MainResourceLoader()
{
}
PassRefPtr<MainResourceLoader> MainResourceLoader::create(Frame* frame)
{
return adoptRef(new MainResourceLoader(frame));
}
void MainResourceLoader::receivedError(const ResourceError& error)
{
RefPtr<MainResourceLoader> protect(this);
RefPtr<Frame> protectFrame(m_frame);
frameLoader()->receivedMainResourceError(error, true);
if (!cancelled()) {
ASSERT(!reachedTerminalState());
frameLoader()->notifier()->didFailToLoad(this, error);
releaseResources();
}
ASSERT(reachedTerminalState());
}
void MainResourceLoader::willCancel(const ResourceError&)
{
m_dataLoadTimer.stop();
if (m_waitingForContentPolicy) {
frameLoader()->policyChecker()->cancelCheck();
ASSERT(m_waitingForContentPolicy);
m_waitingForContentPolicy = false;
deref(); }
}
void MainResourceLoader::didCancel(const ResourceError& error)
{
frameLoader()->receivedMainResourceError(error, true);
}
ResourceError MainResourceLoader::interruptionForPolicyChangeError() const
{
return frameLoader()->interruptionForPolicyChangeError(request());
}
void MainResourceLoader::stopLoadingForPolicyChange()
{
ResourceError error = interruptionForPolicyChangeError();
error.setIsCancellation(true);
cancel(error);
}
void MainResourceLoader::callContinueAfterNavigationPolicy(void* argument, const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
{
static_cast<MainResourceLoader*>(argument)->continueAfterNavigationPolicy(request, shouldContinue);
}
void MainResourceLoader::continueAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
{
if (!shouldContinue)
stopLoadingForPolicyChange();
else if (m_substituteData.isValid()) {
ASSERT(documentLoader()->timing()->redirectCount);
handle()->cancel();
handleDataLoadSoon(request);
}
deref(); }
bool MainResourceLoader::isPostOrRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
if (newRequest.httpMethod() == "POST")
return true;
int status = redirectResponse.httpStatusCode();
if (((status >= 301 && status <= 303) || status == 307)
&& frameLoader()->initialRequest().httpMethod() == "POST")
return true;
return false;
}
void MainResourceLoader::addData(const char* data, int length, bool allAtOnce)
{
ResourceLoader::addData(data, length, allAtOnce);
documentLoader()->receivedData(data, length);
}
void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
ASSERT(!newRequest.isNull());
RefPtr<MainResourceLoader> protect(this);
ASSERT(documentLoader()->timing()->fetchStart);
if (!redirectResponse.isNull()) {
DocumentLoadTiming* documentLoadTiming = documentLoader()->timing();
RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(newRequest.url());
if (!securityOrigin->canRequest(redirectResponse.url()))
documentLoadTiming->hasCrossOriginRedirect = true;
documentLoadTiming->redirectCount++;
if (!documentLoadTiming->redirectStart)
documentLoadTiming->redirectStart = documentLoadTiming->fetchStart;
documentLoadTiming->redirectEnd = currentTime();
documentLoadTiming->fetchStart = documentLoadTiming->redirectEnd;
}
if (frameLoader()->isLoadingMainFrame())
newRequest.setFirstPartyForCookies(newRequest.url());
if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
newRequest.setCachePolicy(ReloadIgnoringCacheData);
Frame* top = m_frame->tree()->top();
if (top != m_frame) {
if (!frameLoader()->checkIfDisplayInsecureContent(top->document()->securityOrigin(), newRequest.url())) {
cancel();
return;
}
}
ResourceLoader::willSendRequest(newRequest, redirectResponse);
m_documentLoader->setRequest(newRequest);
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
if (!redirectResponse.isNull()) {
ASSERT(!m_substituteData.isValid());
documentLoader()->applicationCacheHost()->maybeLoadMainResourceForRedirect(newRequest, m_substituteData);
}
#endif
if (!redirectResponse.isNull()) {
ref(); frameLoader()->policyChecker()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this);
}
}
static bool shouldLoadAsEmptyDocument(const KURL& url)
{
#if PLATFORM(TORCHMOBILE)
return url.isEmpty() || (url.protocolIs("about") && equalIgnoringRef(url, blankURL()));
#else
return url.isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(url.protocol());
#endif
}
void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r)
{
KURL url = request().url();
const String& mimeType = r.mimeType();
switch (contentPolicy) {
case PolicyUse: {
bool isRemoteWebArchive = equalIgnoringCase("application/x-webarchive", mimeType) && !m_substituteData.isValid() && !url.isLocalFile();
if (!frameLoader()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
frameLoader()->policyChecker()->cannotShowMIMEType(r);
if (!reachedTerminalState())
stopLoadingForPolicyChange();
return;
}
break;
}
case PolicyDownload:
if (!m_handle) {
receivedError(cannotShowURLError());
return;
}
InspectorInstrumentation::continueWithPolicyDownload(m_frame.get(), documentLoader(), identifier(), r);
frameLoader()->client()->download(m_handle.get(), request(), m_handle.get()->firstRequest(), r);
if (frameLoader())
receivedError(interruptionForPolicyChangeError());
return;
case PolicyIgnore:
InspectorInstrumentation::continueWithPolicyIgnore(m_frame.get(), documentLoader(), identifier(), r);
stopLoadingForPolicyChange();
return;
default:
ASSERT_NOT_REACHED();
}
RefPtr<MainResourceLoader> protect(this);
if (r.isHTTP()) {
int status = r.httpStatusCode();
if (status < 200 || status >= 300) {
bool hostedByObject = frameLoader()->isHostedByObjectElement();
frameLoader()->handleFallbackContent();
if (hostedByObject)
cancel();
}
}
if (!reachedTerminalState())
ResourceLoader::didReceiveResponse(r);
if (frameLoader() && !frameLoader()->isStopping()) {
if (m_substituteData.isValid()) {
if (m_substituteData.content()->size())
didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
if (frameLoader() && !frameLoader()->isStopping())
didFinishLoading(0);
} else if (shouldLoadAsEmptyDocument(url) || frameLoader()->representationExistsForURLScheme(url.protocol()))
didFinishLoading(0);
}
}
void MainResourceLoader::callContinueAfterContentPolicy(void* argument, PolicyAction policy)
{
static_cast<MainResourceLoader*>(argument)->continueAfterContentPolicy(policy);
}
void MainResourceLoader::continueAfterContentPolicy(PolicyAction policy)
{
ASSERT(m_waitingForContentPolicy);
m_waitingForContentPolicy = false;
if (frameLoader() && !frameLoader()->isStopping())
continueAfterContentPolicy(policy, m_response);
deref(); }
#if PLATFORM(QT)
void MainResourceLoader::substituteMIMETypeFromPluginDatabase(const ResourceResponse& r)
{
if (!m_frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
return;
String filename = r.url().lastPathComponent();
if (filename.endsWith("/"))
return;
size_t extensionPos = filename.reverseFind('.');
if (extensionPos == notFound)
return;
String extension = filename.substring(extensionPos + 1);
String mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
if (!mimeType.isEmpty()) {
ResourceResponse* response = const_cast<ResourceResponse*>(&r);
response->setMimeType(mimeType);
}
}
#endif
void MainResourceLoader::didReceiveResponse(const ResourceResponse& r)
{
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainResponse(request(), r))
return;
#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())) {
InspectorInstrumentation::continueAfterXFrameOptionsDenied(m_frame.get(), documentLoader(), identifier(), r);
DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
m_frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage, 1, String());
cancel();
return;
}
}
#if !USE(CF)
ASSERT(shouldLoadAsEmptyDocument(r.url()) || !defersLoading());
#endif
#if PLATFORM(QT)
if (r.mimeType() == "application/octet-stream")
substituteMIMETypeFromPluginDatabase(r);
#endif
if (m_loadingMultipartContent) {
frameLoader()->setupForReplaceByMIMEType(r.mimeType());
clearResourceData();
}
if (r.isMultipart())
m_loadingMultipartContent = true;
RefPtr<MainResourceLoader> protect(this);
m_documentLoader->setResponse(r);
m_response = r;
ASSERT(!m_waitingForContentPolicy);
m_waitingForContentPolicy = true;
ref();
ASSERT(frameLoader()->activeDocumentLoader());
if (frameLoader()->activeDocumentLoader()->substituteData().isValid()) {
callContinueAfterContentPolicy(this, PolicyUse);
return;
}
#if ENABLE(FTPDIR)
Settings* settings = m_frame->settings();
if (settings && settings->forceFTPDirectoryListings() && m_response.mimeType() == "application/x-ftp-directory") {
callContinueAfterContentPolicy(this, PolicyUse);
return;
}
#endif
frameLoader()->policyChecker()->checkContentPolicy(m_response, callContinueAfterContentPolicy, this);
}
void MainResourceLoader::didReceiveData(const char* data, int length, long long encodedDataLength, bool allAtOnce)
{
ASSERT(data);
ASSERT(length != 0);
ASSERT(!m_response.isNull());
#if USE(CFNETWORK) || PLATFORM(MAC)
if (m_response.isNull()) {
m_response = ResourceResponse(KURL(), "text/html", 0, String(), String());
if (DocumentLoader* documentLoader = frameLoader()->activeDocumentLoader())
documentLoader->setResponse(m_response);
}
#endif
#if !USE(CF)
ASSERT(!defersLoading());
#endif
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
documentLoader()->applicationCacheHost()->mainResourceDataReceived(data, length, encodedDataLength, allAtOnce);
#endif
RefPtr<MainResourceLoader> protect(this);
m_timeOfLastDataReceived = currentTime();
ResourceLoader::didReceiveData(data, length, encodedDataLength, allAtOnce);
}
void MainResourceLoader::didFinishLoading(double finishTime)
{
#if !USE(CF)
ASSERT(shouldLoadAsEmptyDocument(frameLoader()->activeDocumentLoader()->url()) || !defersLoading());
#endif
RefPtr<MainResourceLoader> protect(this);
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
RefPtr<DocumentLoader> dl = documentLoader();
#endif
ASSERT(!documentLoader()->timing()->responseEnd);
documentLoader()->timing()->responseEnd = finishTime ? finishTime : (m_timeOfLastDataReceived ? m_timeOfLastDataReceived : currentTime());
frameLoader()->finishedLoading();
ResourceLoader::didFinishLoading(finishTime);
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
dl->applicationCacheHost()->finishedLoadingMainResource();
#endif
}
void MainResourceLoader::didFail(const ResourceError& error)
{
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainError(request(), error))
return;
#endif
#if !USE(CF)
ASSERT(!defersLoading());
#endif
receivedError(error);
}
void MainResourceLoader::handleEmptyLoad(const KURL& url, bool forURLScheme)
{
String mimeType;
if (forURLScheme)
mimeType = frameLoader()->generatedMIMETypeForURLScheme(url.protocol());
else
mimeType = "text/html";
ResourceResponse response(url, mimeType, 0, String(), String());
didReceiveResponse(response);
}
void MainResourceLoader::handleDataLoadNow(MainResourceLoaderTimer*)
{
RefPtr<MainResourceLoader> protect(this);
KURL url = m_substituteData.responseURL();
if (url.isEmpty())
url = m_initialRequest.url();
m_initialRequest = ResourceRequest();
ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
didReceiveResponse(response);
}
void MainResourceLoader::startDataLoadTimer()
{
m_dataLoadTimer.startOneShot(0);
#if HAVE(RUNLOOP_TIMER)
if (SchedulePairHashSet* scheduledPairs = m_frame->page()->scheduledRunLoopPairs())
m_dataLoadTimer.schedule(*scheduledPairs);
#endif
}
void MainResourceLoader::handleDataLoadSoon(const ResourceRequest& r)
{
m_initialRequest = r;
if (m_documentLoader->deferMainResourceDataLoad())
startDataLoadTimer();
else
handleDataLoadNow(0);
}
bool MainResourceLoader::loadNow(ResourceRequest& r)
{
bool shouldLoadEmptyBeforeRedirect = shouldLoadAsEmptyDocument(r.url());
ASSERT(!m_handle);
ASSERT(shouldLoadEmptyBeforeRedirect || !defersLoading());
willSendRequest(r, ResourceResponse());
if (!frameLoader())
return false;
const KURL& url = r.url();
bool shouldLoadEmpty = shouldLoadAsEmptyDocument(url) && !m_substituteData.isValid();
if (shouldLoadEmptyBeforeRedirect && !shouldLoadEmpty && defersLoading())
return true;
resourceLoadScheduler()->addMainResourceLoad(this);
if (m_substituteData.isValid())
handleDataLoadSoon(r);
else if (shouldLoadEmpty || frameLoader()->representationExistsForURLScheme(url.protocol()))
handleEmptyLoad(url, !shouldLoadEmpty);
else
m_handle = ResourceHandle::create(m_frame->loader()->networkingContext(), r, this, false, true);
return false;
}
bool MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& substituteData)
{
ASSERT(!m_handle);
m_substituteData = substituteData;
ASSERT(documentLoader()->timing()->navigationStart);
ASSERT(!documentLoader()->timing()->fetchStart);
documentLoader()->timing()->fetchStart = currentTime();
ResourceRequest request(r);
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData);
#endif
bool defer = defersLoading();
if (defer) {
bool shouldLoadEmpty = shouldLoadAsEmptyDocument(request.url());
if (shouldLoadEmpty)
defer = false;
}
if (!defer) {
if (loadNow(request)) {
ASSERT(defersLoading());
defer = true;
}
}
if (defer)
m_initialRequest = request;
return true;
}
void MainResourceLoader::setDefersLoading(bool defers)
{
ResourceLoader::setDefersLoading(defers);
if (defers) {
if (m_dataLoadTimer.isActive())
m_dataLoadTimer.stop();
} else {
if (m_initialRequest.isNull())
return;
if (m_substituteData.isValid() && m_documentLoader->deferMainResourceDataLoad())
startDataLoadTimer();
else {
ResourceRequest r(m_initialRequest);
m_initialRequest = ResourceRequest();
loadNow(r);
}
}
}
}