Replace WTF::move with WTFMove
[WebKit-https.git] / Source / WebCore / loader / DocumentThreadableLoader.cpp
index 73c3e80..469175a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
 #include "config.h"
 #include "DocumentThreadableLoader.h"
 
-#include "AuthenticationChallenge.h"
+#include "CachedRawResource.h"
+#include "CachedResourceLoader.h"
+#include "CachedResourceRequest.h"
+#include "CachedResourceRequestInitiators.h"
 #include "CrossOriginAccessControl.h"
 #include "CrossOriginPreflightResultCache.h"
 #include "Document.h"
-#include "DocumentThreadableLoaderClient.h"
 #include "Frame.h"
 #include "FrameLoader.h"
-#include "ResourceHandle.h"
-#include "ResourceLoadScheduler.h"
+#include "InspectorInstrumentation.h"
+#include "ProgressTracker.h"
+#include "ResourceError.h"
 #include "ResourceRequest.h"
+#include "SchemeRegistry.h"
 #include "SecurityOrigin.h"
 #include "SubresourceLoader.h"
 #include "ThreadableLoaderClient.h"
-#include <wtf/UnusedParam.h>
+#include <wtf/Assertions.h>
+#include <wtf/Ref.h>
 
 namespace WebCore {
 
-void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
+void DocumentThreadableLoader::loadResourceSynchronously(Document& document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
 {
     // The loader will be deleted as soon as this function exits.
-    RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, &client, LoadSynchronously, request, options, String()));
+    RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadSynchronously, request, options));
     ASSERT(loader->hasOneRef());
 }
 
-PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& optionalOutgoingReferrer)
+PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document& document, ThreadableLoaderClient& client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
 {
-    RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options, optionalOutgoingReferrer));
-    if (!loader->m_loader)
-        loader = 0;
+    RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
+    if (!loader->m_resource)
+        loader = nullptr;
     return loader.release();
 }
 
-DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& optionalOutgoingReferrer)
-    : m_client(client)
+DocumentThreadableLoader::DocumentThreadableLoader(Document& document, ThreadableLoaderClient& client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options)
+    : m_client(&client)
     , m_document(document)
     , m_options(options)
-    , m_optionalOutgoingReferrer(optionalOutgoingReferrer)
-    , m_sameOriginRequest(document->securityOrigin()->canRequest(request.url()))
+    , m_sameOriginRequest(securityOrigin()->canRequest(request.url()))
+    , m_simpleRequest(true)
     , m_async(blockingBehavior == LoadAsynchronously)
 {
-    ASSERT(document);
-    ASSERT(client);
     // Setting an outgoing referer is only supported in the async code path.
-    ASSERT(m_async || m_optionalOutgoingReferrer.isEmpty());
+    ASSERT(m_async || request.httpReferrer().isEmpty());
 
     if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
         loadRequest(request, DoSecurityCheck);
@@ -82,22 +85,27 @@ DocumentThreadableLoader::DocumentThreadableLoader(Document* document, Threadabl
     }
 
     if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
-        m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are not supported."));
+        m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Cross origin requests are not supported."));
         return;
     }
-    
+
+    makeCrossOriginAccessRequest(request);
+}
+
+void DocumentThreadableLoader::makeCrossOriginAccessRequest(const ResourceRequest& request)
+{
     ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
 
-    OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
-    crossOriginRequest->removeCredentials();
-    crossOriginRequest->setAllowCookies(m_options.allowCredentials);
+    auto crossOriginRequest = std::make_unique<ResourceRequest>(request);
+    updateRequestForAccessControl(*crossOriginRequest, securityOrigin(), m_options.allowCredentials());
 
-    if (!m_options.forcePreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields()))
+    if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight)
         makeSimpleCrossOriginAccessRequest(*crossOriginRequest);
     else {
-        m_actualRequest = crossOriginRequest.release();
+        m_simpleRequest = false;
+        m_actualRequest = WTFMove(crossOriginRequest);
 
-        if (CrossOriginPreflightResultCache::shared().canSkipPreflight(document->securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
+        if (CrossOriginPreflightResultCache::singleton().canSkipPreflight(securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials(), m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
             preflightSuccess();
         else
             makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
@@ -106,166 +114,197 @@ DocumentThreadableLoader::DocumentThreadableLoader(Document* document, Threadabl
 
 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
 {
-    ASSERT(isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
+    ASSERT(m_options.preflightPolicy != ForcePreflight);
+    ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
 
-    // Cross-origin requests are only defined for HTTP. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
-    if (!request.url().protocolInHTTPFamily()) {
-        m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
+    // Cross-origin requests are only allowed for HTTP and registered schemes. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
+    if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol())) {
+        m_client->didFailAccessControlCheck(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Cross origin requests are only supported for HTTP."));
         return;
     }
 
-    // Make a copy of the passed request so that we can modify some details.
-    ResourceRequest crossOriginRequest(request);
-    crossOriginRequest.setHTTPOrigin(m_document->securityOrigin()->toString());
-
-    loadRequest(crossOriginRequest, DoSecurityCheck);
+    loadRequest(request, DoSecurityCheck);
 }
 
 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
 {
-    ResourceRequest preflightRequest(request.url());
-    preflightRequest.removeCredentials();
-    preflightRequest.setHTTPOrigin(m_document->securityOrigin()->toString());
-    preflightRequest.setAllowCookies(m_options.allowCredentials);
-    preflightRequest.setHTTPMethod("OPTIONS");
-    preflightRequest.setHTTPHeaderField("Access-Control-Request-Method", request.httpMethod());
-
-    const HTTPHeaderMap& requestHeaderFields = request.httpHeaderFields();
-
-    if (requestHeaderFields.size() > 0) {
-        Vector<UChar> headerBuffer;
-        HTTPHeaderMap::const_iterator it = requestHeaderFields.begin();
-        append(headerBuffer, it->first);
-        ++it;
-
-        HTTPHeaderMap::const_iterator end = requestHeaderFields.end();
-        for (; it != end; ++it) {
-            headerBuffer.append(',');
-            headerBuffer.append(' ');
-            append(headerBuffer, it->first);
-        }
-
-        preflightRequest.setHTTPHeaderField("Access-Control-Request-Headers", String::adopt(headerBuffer));
-    }
-
-    preflightRequest.setPriority(request.priority());
-
+    ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin());
     loadRequest(preflightRequest, DoSecurityCheck);
 }
 
 DocumentThreadableLoader::~DocumentThreadableLoader()
 {
-    if (m_loader)
-        m_loader->clearClient();
+    if (m_resource)
+        m_resource->removeClient(this);
 }
 
 void DocumentThreadableLoader::cancel()
 {
-    if (!m_loader)
-        return;
-
-    m_loader->cancel();
-    m_loader->clearClient();
-    m_loader = 0;
-    m_client = 0;
+    Ref<DocumentThreadableLoader> protect(*this);
+
+    // Cancel can re-enter and m_resource might be null here as a result.
+    if (m_client && m_resource) {
+        // FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
+        ResourceError error(errorDomainWebKitInternal, 0, m_resource->url(), "Load cancelled");
+        error.setIsCancellation(true);
+        didFail(m_resource->identifier(), error);
+    }
+    clearResource();
+    m_client = nullptr;
 }
 
 void DocumentThreadableLoader::setDefersLoading(bool value)
 {
-    if (m_loader)
-        m_loader->setDefersLoading(value);
+    if (m_resource)
+        m_resource->setDefersLoading(value);
+}
+
+void DocumentThreadableLoader::clearResource()
+{
+    // Script can cancel and restart a request reentrantly within removeClient(),
+    // which could lead to calling CachedResource::removeClient() multiple times for
+    // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
+    // prevent the reentrancy.
+    if (CachedResourceHandle<CachedRawResource> resource = m_resource) {
+        m_resource = nullptr;
+        resource->removeClient(this);
+    }
 }
 
-void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse& redirectResponse)
+void DocumentThreadableLoader::redirectReceived(CachedResource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(loader, loader == m_loader);
+    ASSERT_UNUSED(resource, resource == m_resource);
 
-    if (!isAllowedRedirect(request.url())) {
-        RefPtr<DocumentThreadableLoader> protect(this);
-        m_client->didFailRedirectCheck();
-        request = ResourceRequest();
-    } else {
-        if (m_client->isDocumentThreadableLoaderClient())
-            static_cast<DocumentThreadableLoaderClient*>(m_client)->willSendRequest(request, redirectResponse);
+    Ref<DocumentThreadableLoader> protect(*this);
+    // Allow same origin requests to continue after allowing clients to audit the redirect.
+    if (isAllowedRedirect(request.url()))
+        return;
+
+    // When using access control, only simple cross origin requests are allowed to redirect. The new request URL must have a supported
+    // scheme and not contain the userinfo production. In addition, the redirect response must pass the access control check.
+    if (m_options.crossOriginRequestPolicy == UseAccessControl) {
+        bool allowRedirect = false;
+        if (m_simpleRequest) {
+            String accessControlErrorDescription;
+            allowRedirect = SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol())
+                            && request.url().user().isEmpty()
+                            && request.url().pass().isEmpty()
+                            && passesAccessControlCheck(redirectResponse, m_options.allowCredentials(), securityOrigin(), accessControlErrorDescription);
+        }
+
+        if (allowRedirect) {
+            if (m_resource)
+                clearResource();
+
+            RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::createFromString(redirectResponse.url());
+            RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::createFromString(request.url());
+            // If the request URL origin is not same origin with the original URL origin, set source origin to a globally unique identifier.
+            if (!originalOrigin->isSameSchemeHostPort(requestOrigin.get()))
+                m_options.securityOrigin = SecurityOrigin::createUnique();
+            // Force any subsequent requests to use these checks.
+            m_sameOriginRequest = false;
+
+            // Remove any headers that may have been added by the network layer that cause access control to fail.
+            request.clearHTTPContentType();
+            request.clearHTTPReferrer();
+            request.clearHTTPOrigin();
+            request.clearHTTPUserAgent();
+            request.clearHTTPAccept();
+            makeCrossOriginAccessRequest(request);
+            return;
+        }
     }
+
+    m_client->didFailRedirectCheck();
+    request = ResourceRequest();
 }
 
-void DocumentThreadableLoader::didSendData(SubresourceLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+void DocumentThreadableLoader::dataSent(CachedResource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(loader, loader == m_loader);
-
+    ASSERT_UNUSED(resource, resource == m_resource);
     m_client->didSendData(bytesSent, totalBytesToBeSent);
 }
 
-void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response)
+void DocumentThreadableLoader::responseReceived(CachedResource* resource, const ResourceResponse& response)
+{
+    ASSERT_UNUSED(resource, resource == m_resource);
+    didReceiveResponse(m_resource->identifier(), response);
+}
+
+void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(loader, loader == m_loader);
 
     String accessControlErrorDescription;
     if (m_actualRequest) {
-        if (!passesAccessControlCheck(response, m_options.allowCredentials, m_document->securityOrigin(), accessControlErrorDescription)) {
-            preflightFailure(response.url(), accessControlErrorDescription);
+        DocumentLoader* loader = m_document.frame()->loader().documentLoader();
+        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_document.frame());
+        InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, response, 0);
+
+        if (!passesAccessControlCheck(response, m_options.allowCredentials(), securityOrigin(), accessControlErrorDescription)) {
+            preflightFailure(identifier, response.url(), accessControlErrorDescription);
             return;
         }
 
-        OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new CrossOriginPreflightResultCacheItem(m_options.allowCredentials));
+        StoredCredentials allowCredentials = m_options.allowCredentials();
+        auto preflightResult = std::make_unique<CrossOriginPreflightResultCacheItem>(allowCredentials);
         if (!preflightResult->parse(response, accessControlErrorDescription)
             || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod(), accessControlErrorDescription)
             || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeaderFields(), accessControlErrorDescription)) {
-            preflightFailure(response.url(), accessControlErrorDescription);
+            preflightFailure(identifier, response.url(), accessControlErrorDescription);
             return;
         }
 
-        CrossOriginPreflightResultCache::shared().appendEntry(m_document->securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
+        CrossOriginPreflightResultCache::singleton().appendEntry(securityOrigin()->toString(), m_actualRequest->url(), WTFMove(preflightResult));
     } else {
         if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessControl) {
-            if (!passesAccessControlCheck(response, m_options.allowCredentials, m_document->securityOrigin(), accessControlErrorDescription)) {
-                m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, response.url().string(), accessControlErrorDescription));
+            if (!passesAccessControlCheck(response, m_options.allowCredentials(), securityOrigin(), accessControlErrorDescription)) {
+                m_client->didFailAccessControlCheck(ResourceError(errorDomainWebKitInternal, 0, response.url(), accessControlErrorDescription));
                 return;
             }
         }
 
-        m_client->didReceiveResponse(response);
+        m_client->didReceiveResponse(identifier, response);
     }
 }
 
-void DocumentThreadableLoader::didReceiveData(SubresourceLoader* loader, const char* data, int lengthReceived)
+void DocumentThreadableLoader::dataReceived(CachedResource* resource, const char* data, int dataLength)
 {
-    ASSERT(m_client);
-    ASSERT_UNUSED(loader, loader == m_loader);
-
-    // Preflight data should be invisible to clients.
-    if (m_actualRequest)
-        return;
-
-    m_client->didReceiveData(data, lengthReceived);
+    ASSERT_UNUSED(resource, resource == m_resource);
+    didReceiveData(m_resource->identifier(), data, dataLength);
 }
 
-void DocumentThreadableLoader::didReceiveCachedMetadata(SubresourceLoader* loader, const char* data, int lengthReceived)
+void DocumentThreadableLoader::didReceiveData(unsigned long identifier, const char* data, int dataLength)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(loader, loader == m_loader);
 
     // Preflight data should be invisible to clients.
-    if (m_actualRequest)
+    if (m_actualRequest) {
+        InspectorInstrumentation::didReceiveData(m_document.frame(), identifier, 0, 0, dataLength);
         return;
+    }
 
-    m_client->didReceiveCachedMetadata(data, lengthReceived);
+    m_client->didReceiveData(data, dataLength);
 }
 
-void DocumentThreadableLoader::didFinishLoading(SubresourceLoader* loader, double finishTime)
+void DocumentThreadableLoader::notifyFinished(CachedResource* resource)
 {
-    ASSERT(loader == m_loader);
     ASSERT(m_client);
-    didFinishLoading(loader->identifier(), finishTime);
+    ASSERT_UNUSED(resource, resource == m_resource);
+        
+    if (m_resource->errorOccurred())
+        didFail(m_resource->identifier(), m_resource->resourceError());
+    else
+        didFinishLoading(m_resource->identifier(), m_resource->loadFinishTime());
 }
 
 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
 {
     if (m_actualRequest) {
+        InspectorInstrumentation::didFinishLoading(m_document.frame(), m_document.frame()->loader().documentLoader(), identifier, finishTime);
+
         ASSERT(!m_sameOriginRequest);
         ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
         preflightSuccess();
@@ -273,100 +312,84 @@ void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double
         m_client->didFinishLoading(identifier, finishTime);
 }
 
-void DocumentThreadableLoader::didFail(SubresourceLoader* loader, const ResourceError& error)
+void DocumentThreadableLoader::didFail(unsigned long identifier, const ResourceError& error)
 {
-    ASSERT(m_client);
-    // m_loader may be null if we arrive here via SubresourceLoader::create in the ctor
-    ASSERT_UNUSED(loader, loader == m_loader || !m_loader);
+    if (m_actualRequest)
+        InspectorInstrumentation::didFailLoading(m_document.frame(), m_document.frame()->loader().documentLoader(), identifier, error);
 
     m_client->didFail(error);
 }
 
-bool DocumentThreadableLoader::getShouldUseCredentialStorage(SubresourceLoader* loader, bool& shouldUseCredentialStorage)
-{
-    ASSERT_UNUSED(loader, loader == m_loader || !m_loader);
-
-    if (!m_options.allowCredentials) {
-        shouldUseCredentialStorage = false;
-        return true;
-    }
-
-    return false; // Only FrameLoaderClient can ultimately permit credential use.
-}
-
-void DocumentThreadableLoader::didReceiveAuthenticationChallenge(SubresourceLoader* loader, const AuthenticationChallenge& challenge)
-{
-    ASSERT(loader == m_loader);
-    // Users are not prompted for credentials for cross-origin requests.
-    if (!m_sameOriginRequest) {
-#if PLATFORM(MAC) || USE(CFNETWORK) || USE(CURL)
-        loader->handle()->receivedRequestToContinueWithoutCredential(challenge);
-#else
-        // These platforms don't provide a way to continue without credentials, cancel the load altogether.
-        UNUSED_PARAM(challenge);
-        RefPtr<DocumentThreadableLoader> protect(this);
-        m_client->didFail(loader->blockedError());
-        cancel();
-#endif
-    }
-}
-
-void DocumentThreadableLoader::receivedCancellation(SubresourceLoader* loader, const AuthenticationChallenge& challenge)
-{
-    ASSERT(m_client);
-    ASSERT_UNUSED(loader, loader == m_loader);
-    m_client->didReceiveAuthenticationCancellation(challenge.failureResponse());
-}
-
 void DocumentThreadableLoader::preflightSuccess()
 {
-    OwnPtr<ResourceRequest> actualRequest;
+    std::unique_ptr<ResourceRequest> actualRequest;
     actualRequest.swap(m_actualRequest);
 
-    actualRequest->setHTTPOrigin(m_document->securityOrigin()->toString());
+    actualRequest->setHTTPOrigin(securityOrigin()->toString());
+
+    clearResource();
 
     // It should be ok to skip the security check since we already asked about the preflight request.
     loadRequest(*actualRequest, SkipSecurityCheck);
 }
 
-void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
+void DocumentThreadableLoader::preflightFailure(unsigned long identifier, const URL& url, const String& errorDescription)
 {
-    m_actualRequest = 0; // Prevent didFinishLoading() from bypassing access check.
-    m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, url, errorDescription));
+    ResourceError error(errorDomainWebKitInternal, 0, url, errorDescription);
+    if (m_actualRequest)
+        InspectorInstrumentation::didFailLoading(m_document.frame(), m_document.frame()->loader().documentLoader(), identifier, error);
+
+    m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
+    m_client->didFailAccessControlCheck(error);
 }
 
 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, SecurityCheckPolicy securityCheck)
 {
     // Any credential should have been removed from the cross-site requests.
-    const KURL& requestURL = request.url();
+    const URL& requestURL = request.url();
+    m_options.setSecurityCheck(securityCheck);
     ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
     ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
 
     if (m_async) {
-        // Don't sniff content or send load callbacks for the preflight request.
-        bool sendLoadCallbacks = m_options.sendLoadCallbacks && !m_actualRequest;
-        bool sniffContent = m_options.sniffContent && !m_actualRequest;
-
-        // Clear the loader so that any callbacks from SubresourceLoader::create will not have the old loader.
-        m_loader = 0;
-        m_loader = resourceLoadScheduler()->scheduleSubresourceLoad(m_document->frame(), this, request, ResourceLoadPriorityMedium, securityCheck, sendLoadCallbacks,
-                                                                    sniffContent, m_optionalOutgoingReferrer);
+        ThreadableLoaderOptions options = m_options;
+        options.setClientCredentialPolicy(DoNotAskClientForCrossOriginCredentials);
+        if (m_actualRequest) {
+            // Don't sniff content or send load callbacks for the preflight request.
+            options.setSendLoadCallbacks(DoNotSendCallbacks);
+            options.setSniffContent(DoNotSniffContent);
+            // Keep buffering the data for the preflight request.
+            options.setDataBufferingPolicy(BufferData);
+        }
+
+        CachedResourceRequest newRequest(request, options);
+#if ENABLE(RESOURCE_TIMING)
+        newRequest.setInitiator(m_options.initiator);
+#endif
+        ASSERT(!m_resource);
+        m_resource = m_document.cachedResourceLoader().requestRawResource(newRequest);
+        if (m_resource)
+            m_resource->addClient(this);
+
         return;
     }
     
     // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
-    StoredCredentials storedCredentials = m_options.allowCredentials ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-
-    Vector<char> data;
+    RefPtr<SharedBuffer> data;
     ResourceError error;
     ResourceResponse response;
     unsigned long identifier = std::numeric_limits<unsigned long>::max();
-    if (m_document->frame())
-        identifier = m_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.
-    if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
+    if (m_document.frame())
+        identifier = m_document.frame()->loader().loadResourceSynchronously(request, m_options.allowCredentials(), m_options.clientCredentialPolicy(), error, response, data);
+
+    if (!error.isNull() && response.httpStatusCode() <= 0) {
+        if (requestURL.isLocalFile()) {
+            // We don't want XMLHttpRequest to raise an exception for file:// resources, see <rdar://problem/4962298>.
+            // FIXME: XMLHttpRequest quirks should be in XMLHttpRequest code, not in DocumentThreadableLoader.cpp.
+            didReceiveResponse(identifier, response);
+            didFinishLoading(identifier, 0.0);
+            return;
+        }
         m_client->didFail(error);
         return;
     }
@@ -379,24 +402,29 @@ void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, Secur
         return;
     }
 
-    didReceiveResponse(0, response);
-
-    const char* bytes = static_cast<const char*>(data.data());
-    int len = static_cast<int>(data.size());
-    didReceiveData(0, bytes, len);
+    didReceiveResponse(identifier, response);
 
+    if (data)
+        didReceiveData(identifier, data->data(), data->size());
     didFinishLoading(identifier, 0.0);
 }
 
-bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url)
+bool DocumentThreadableLoader::isAllowedRedirect(const URL& url)
 {
     if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
         return true;
 
-    // FIXME: We need to implement access control for each redirect. This will require some refactoring though, because the code
-    // that processes redirects doesn't know about access control and expects a synchronous answer from its client about whether
-    // a redirect should proceed.
-    return m_sameOriginRequest && m_document->securityOrigin()->canRequest(url);
+    return m_sameOriginRequest && securityOrigin()->canRequest(url);
+}
+
+bool DocumentThreadableLoader::isXMLHttpRequest() const
+{
+    return m_options.initiator == cachedResourceRequestInitiators().xmlhttprequest;
+}
+
+SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
+{
+    return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document.securityOrigin();
 }
 
 } // namespace WebCore