Ejemplo n.º 1
0
void HistoryDelegate::didNavigateWithNavigationData(WebView* webView, WebNavigationData* navigationData, WebFrame* webFrame)
{
    if (!gLayoutTestController->dumpHistoryDelegateCallbacks())
        return;

    const char* url = navigationData->url();
    const char* title = navigationData->title();

    WebMutableURLRequest* request = navigationData->originalRequest();

    const char* httpMethod = request->HTTPMethod();

    WebURLResponse* response = navigationData->response();

    int statusCode = response->statusCode();

    bool hasSubstituteData = navigationData->hasSubstituteData();

    const char* clientRedirectSource = navigationData->clientRedirectSource();
    bool hasClientRedirect = clientRedirectSource && strlen(clientRedirectSource);

    bool wasFailure = hasSubstituteData || (response && statusCode >= 400);

    printf("WebView navigated to url \"%s\" with title \"%s\" with HTTP equivalent method \"%s\".  The navigation was %s and was %s%s.\n",
        url,
        title,
        httpMethod,
        wasFailure ? "a failure" : "successful",
        hasClientRedirect ? "a client redirect from " : "not a client redirect",
        clientRedirectSource);
}
TEST_F(WebEmbeddedWorkerImplTest, ScriptNotFound)
{
    WebURL scriptURL = URLTestHelpers::toKURL("https://www.example.com/sw-404.js");
    WebURLResponse response;
    response.initialize();
    response.setMIMEType("text/javascript");
    response.setHTTPStatusCode(404);
    WebURLError error;
    error.reason = 1010;
    error.domain = "WebEmbeddedWorkerImplTest";
    Platform::current()->unitTestSupport()->registerMockedErrorURL(scriptURL, response, error);
    m_startData.scriptURL = scriptURL;

    EXPECT_CALL(*m_mockClient, workerReadyForInspection())
        .Times(1);
    m_worker->startWorkerContext(m_startData);
    ::testing::Mock::VerifyAndClearExpectations(m_mockClient);

    // Load the shadow page.
    EXPECT_CALL(*m_mockClient, createServiceWorkerNetworkProvider(::testing::_))
        .WillOnce(::testing::Return(nullptr));
    Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
    ::testing::Mock::VerifyAndClearExpectations(m_mockClient);

    // Load the script.
    EXPECT_CALL(*m_mockClient, workerScriptLoaded())
        .Times(0);
    EXPECT_CALL(*m_mockClient, createServiceWorkerProvider())
        .Times(0);
    EXPECT_CALL(*m_mockClient, workerContextFailedToStart())
        .Times(1);
    Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
    ::testing::Mock::VerifyAndClearExpectations(m_mockClient);
}
Ejemplo n.º 3
0
void ResourceLoader::didReceiveResponse(
    const WebURLResponse& response,
    std::unique_ptr<WebDataConsumerHandle> handle) {
  DCHECK(!response.isNull());
  m_fetcher->didReceiveResponse(m_resource.get(), response.toResourceResponse(),
                                std::move(handle));
}
Ejemplo n.º 4
0
WebURLResponse* WebURLResponse::createInstance()
{
    WebURLResponse* instance = new WebURLResponse();
    // fake an http response - so it has the IWebHTTPURLResponse interface
    instance->m_response = ResourceResponse(KURL(ParsedURLString, "http://"), String(), 0, String(), String());
    instance->AddRef();
    return instance;
}
Ejemplo n.º 5
0
void ResourceHandleInternal::willSendRequest(
    WebURLLoader*, WebURLRequest& request, const WebURLResponse& response)
{
    ASSERT(m_client);
    ASSERT(!request.isNull());
    ASSERT(!response.isNull());
    m_client->willSendRequest(m_owner, request.toMutableResourceRequest(), response.toResourceResponse());
}
 void didReceiveResponse(WebURLLoader* loader, const WebURLResponse& response) override
 {
     m_didReceiveResponse = true;
     m_actualResponse = WebURLResponse(response);
     EXPECT_EQ(m_expectedLoader, loader);
     EXPECT_EQ(m_expectedResponse.url(), response.url());
     EXPECT_EQ(m_expectedResponse.httpStatusCode(), response.httpStatusCode());
 }
Ejemplo n.º 7
0
 void registerRedirect(const WebString& fromURL, const WebString& toURL) {
     KURL redirectURL(ParsedURLString, fromURL);
     WebURLResponse redirectResponse;
     redirectResponse.setURL(redirectURL);
     redirectResponse.setHTTPStatusCode(301);
     redirectResponse.setHTTPHeaderField(HTTPNames::Location, toURL);
     redirectResponse.addToEncodedDataLength(kRedirectResponseOverheadBytes);
     Platform::current()->getURLLoaderMockFactory()->registerURL(
         redirectURL, redirectResponse, "");
 }
 // WebURLLoaderClient implementation.
 void willSendRequest(WebURLLoader* loader, WebURLRequest& newRequest, const WebURLResponse& redirectResponse) override
 {
     m_willSendRequest = true;
     EXPECT_EQ(m_expectedLoader, loader);
     EXPECT_EQ(m_expectedNewRequest.url(), newRequest.url());
     // Check that CORS simple headers are transferred to the new request.
     EXPECT_EQ(m_expectedNewRequest.httpHeaderField("accept"), newRequest.httpHeaderField("accept"));
     EXPECT_EQ(m_expectedRedirectResponse.url(), redirectResponse.url());
     EXPECT_EQ(m_expectedRedirectResponse.httpStatusCode(), redirectResponse.httpStatusCode());
     EXPECT_EQ(m_expectedRedirectResponse.mimeType(), redirectResponse.mimeType());
 }
Ejemplo n.º 9
0
void printResponseDescription(WebTestDelegate* delegate, const WebURLResponse& response)
{
    if (response.isNull()) {
        delegate->printMessage("(null)");
        return;
    }
    string url = response.url().spec();
    char data[100];
    snprintf(data, sizeof(data), "%d", response. httpStatusCode());
    delegate->printMessage(string("<NSURLResponse ") + descriptionSuitableForTestResult(url) + ", http status code " + data + ">");
}
 KURL RegisterMockedUrl(const std::string& urlRoot, const WTF::String& filename)
 {
     WebURLResponse response;
     response.initialize();
     response.setMIMEType("text/html");
     WTF::String localPath = m_baseFilePath;
     localPath.append(filename);
     KURL url = toKURL(urlRoot + filename.utf8().data());
     Platform::current()->unitTestSupport()->registerMockedURL(url, response, localPath);
     return url;
 }
Ejemplo n.º 11
0
static void printResponseDescription(const WebURLResponse& response)
{
    if (response.isNull()) {
        fputs("(null)", stdout);
        return;
    }
    string url = response.url().spec();
    printf("<NSURLResponse %s, http status code %d>",
           descriptionSuitableForTestResult(url).c_str(),
           response.httpStatusCode());
}
Ejemplo n.º 12
0
WebURLResponse* WebURLResponse::createInstance(const ResourceResponse& response)
{
    if (response.isNull())
        return 0;

    WebURLResponse* instance = new WebURLResponse();
    instance->AddRef();
    instance->m_response = response;

    return instance;
}
Ejemplo n.º 13
0
void ResourceHandleInternal::didReceiveResponse(WebURLLoader*, const WebURLResponse& response)
{
    ASSERT(m_client);
    ASSERT(!response.isNull());
    bool isMultipart = response.isMultipartPayload();
    bool isValidStateTransition = (m_state == ConnectionStateStarted || m_state == ConnectionStateReceivedResponse);
    // In the case of multipart loads, calls to didReceiveData & didReceiveResponse can be interleaved.
    if (!isMultipart && !isValidStateTransition)
        CRASH();
    m_state = ConnectionStateReceivedResponse;
    m_client->didReceiveResponse(m_owner, response.toResourceResponse());
}
    void registerErrorURL(const char* file, int statusCode)
    {
        WebURLError error;
        error.reason = 0xdead + statusCode;
        error.domain = "PageSerializerTest";

        WebURLResponse response;
        response.initialize();
        response.setMIMEType("text/html");
        response.setHTTPStatusCode(statusCode);

        Platform::current()->unitTestSupport()->registerMockedErrorURL(KURL(m_baseUrl, file), response, error);
    }
Ejemplo n.º 15
0
bool ResourceLoader::willFollowRedirect(
    WebURLRequest& passedNewRequest,
    const WebURLResponse& passedRedirectResponse) {
  DCHECK(!passedNewRequest.isNull());
  DCHECK(!passedRedirectResponse.isNull());

  if (m_isCacheAwareLoadingActivated) {
    // Fail as cache miss if cached response is a redirect.
    didFail(
        ResourceError::cacheMissError(m_resource->lastResourceRequest().url()));
    return false;
  }

  ResourceRequest& newRequest(passedNewRequest.toMutableResourceRequest());
  const ResourceResponse& redirectResponse(
      passedRedirectResponse.toResourceResponse());
  newRequest.setRedirectStatus(
      ResourceRequest::RedirectStatus::FollowedRedirect);

  const KURL originalURL = newRequest.url();

  ResourceRequestBlockedReason blockedReason = m_fetcher->willFollowRedirect(
      m_resource.get(), newRequest, redirectResponse);
  if (blockedReason != ResourceRequestBlockedReason::None) {
    cancelForRedirectAccessCheckError(newRequest.url(), blockedReason);
    return false;
  }

  // ResourceFetcher::willFollowRedirect() may rewrite the URL to
  // something else not for rejecting redirect but for other reasons.
  // E.g. WebFrameTestClient::willSendRequest() and
  // RenderFrameImpl::willSendRequest(). We should reflect the
  // rewriting but currently we cannot. So, return false to make the
  // redirect fail.
  if (newRequest.url() != originalURL) {
    cancelForRedirectAccessCheckError(newRequest.url(),
                                      ResourceRequestBlockedReason::Other);
    return false;
  }

  if (!m_resource->willFollowRedirect(newRequest, redirectResponse)) {
    cancelForRedirectAccessCheckError(newRequest.url(),
                                      ResourceRequestBlockedReason::Other);
    return false;
  }

  return true;
}
Ejemplo n.º 16
0
void BeaconLoader::willSendRequest(WebURLLoader*, WebURLRequest& passedNewRequest, const WebURLResponse& passedRedirectResponse)
{
    passedNewRequest.setAllowStoredCredentials(true);
    ResourceRequest& newRequest(passedNewRequest.toMutableResourceRequest());
    const ResourceResponse& redirectResponse(passedRedirectResponse.toResourceResponse());

    ASSERT(!newRequest.isNull());
    ASSERT(!redirectResponse.isNull());

    String errorDescription;
    StoredCredentials withCredentials = AllowStoredCredentials;
    ResourceLoaderOptions options;
    if (!CrossOriginAccessControl::handleRedirect(m_beaconOrigin.get(), newRequest, redirectResponse, withCredentials, options, errorDescription)) {
        if (page() && page()->mainFrame()) {
            if (page()->mainFrame()->isLocalFrame()) {
                LocalFrame* localFrame = toLocalFrame(page()->mainFrame());
                if (localFrame->document())
                    localFrame->document()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorDescription));
            }
        }
        // Cancel the load and self destruct.
        dispose();
        return;
    }
    // FIXME: http://crbug.com/427429 is needed to correctly propagate
    // updates of Origin: following this successful redirect.
}
Ejemplo n.º 17
0
void ResourceLoader::willFollowRedirect(WebURLLoader*, WebURLRequest& passedNewRequest, const WebURLResponse& passedRedirectResponse)
{
    ASSERT(m_state != Terminated);

    ResourceRequest& newRequest(applyOptions(passedNewRequest.toMutableResourceRequest()));

    ASSERT(!newRequest.isNull());
    const ResourceResponse& redirectResponse(passedRedirectResponse.toResourceResponse());
    ASSERT(!redirectResponse.isNull());
    newRequest.setFollowedRedirect(true);
    if (!isManualRedirectFetchRequest(m_resource->resourceRequest()) && !m_fetcher->canAccessRedirect(m_resource, newRequest, redirectResponse, m_options)) {
        cancel(ResourceError::cancelledDueToAccessCheckError(newRequest.url()));
        return;
    }
    ASSERT(m_state != Terminated);

    applyOptions(newRequest); // canAccessRedirect() can modify m_options so we should re-apply it.
    m_fetcher->redirectReceived(m_resource, redirectResponse);
    ASSERT(m_state != Terminated);
    m_resource->willFollowRedirect(newRequest, redirectResponse);
    if (newRequest.isNull() || m_state == Terminated)
        return;

    m_fetcher->willSendRequest(m_resource->identifier(), newRequest, redirectResponse, m_options.initiatorInfo);
    ASSERT(m_state != Terminated);
    ASSERT(!newRequest.isNull());
    m_resource->updateRequest(newRequest);
    m_request = newRequest;
}
Ejemplo n.º 18
0
void WebViewHost::didReceiveResponse(WebFrame*, unsigned identifier, const WebURLResponse& response)
{
    if (m_shell->shouldDumpResourceLoadCallbacks()) {
        printResourceDescription(identifier);
        fputs(" - didReceiveResponse ", stdout);
        printResponseDescription(response);
        fputs("\n", stdout);
    }
    if (m_shell->shouldDumpResourceResponseMIMETypes()) {
        GURL url = response.url();
        WebString mimeType = response.mimeType();
        printf("%s has MIME type %s\n",
            url.ExtractFileName().c_str(),
            // Simulate NSURLResponse's mapping of empty/unknown MIME types to application/octet-stream
            mimeType.isEmpty() ? "application/octet-stream" : mimeType.utf8().data());
    }
}
Ejemplo n.º 19
0
void ResourceLoader::requestSynchronously()
{
    OwnPtr<WebURLLoader> loader = adoptPtr(Platform::current()->createURLLoader());
    ASSERT(loader);

    // downloadToFile is not supported for synchronous requests.
    ASSERT(!m_request.downloadToFile());

    ResourcePtr<Resource> protectResource(m_resource);

    RELEASE_ASSERT(m_connectionState == ConnectionStateNew);
    m_connectionState = ConnectionStateStarted;

    WrappedResourceRequest requestIn(m_request);
    WebURLResponse responseOut;
    responseOut.initialize();
    WebURLError errorOut;
    WebData dataOut;
    loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut);
    if (errorOut.reason) {
        if (m_state == Terminated) {
            // A message dispatched while synchronously fetching the resource
            // can bring about the cancellation of this load.
            ASSERT(!m_resource);
            return;
        }
        didFail(0, errorOut);
        return;
    }
    didReceiveResponse(0, responseOut);
    if (m_state == Terminated)
        return;
    RefPtr<ResourceLoadInfo> resourceLoadInfo = responseOut.toResourceResponse().resourceLoadInfo();
    int64_t encodedDataLength = resourceLoadInfo ? resourceLoadInfo->encodedDataLength : WebURLLoaderClient::kUnknownEncodedDataLength;

    // Follow the async case convention of not calling didReceiveData or
    // appending data to m_resource if the response body is empty. Copying the
    // empty buffer is a noop in most cases, but is destructive in the case of
    // a 304, where it will overwrite the cached data we should be reusing.
    if (dataOut.size()) {
        m_fetcher->didReceiveData(m_resource, dataOut.data(), dataOut.size(), encodedDataLength);
        m_resource->setResourceBuffer(dataOut);
    }
    didFinishLoading(0, monotonicallyIncreasingTime(), encodedDataLength);
}
Ejemplo n.º 20
0
void AssociatedURLLoader::ClientAdapter::didReceiveResponse(unsigned long, const ResourceResponse& response)
{
    // Try to use the original ResourceResponse if possible.
    WebURLResponse validatedResponse = WrappedResourceResponse(response);
    HTTPResponseHeaderValidator validator(m_options.crossOriginRequestPolicy == WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl);
    if (!m_options.exposeAllResponseHeaders)
        validatedResponse.visitHTTPHeaderFields(&validator);

    // If there are blocked headers, copy the response so we can remove them.
    const HTTPHeaderSet& blockedHeaders = validator.blockedHeaders();
    if (!blockedHeaders.isEmpty()) {
        validatedResponse = WebURLResponse(validatedResponse);
        HTTPHeaderSet::const_iterator end = blockedHeaders.end();
        for (HTTPHeaderSet::const_iterator it = blockedHeaders.begin(); it != end; ++it)
            validatedResponse.clearHTTPHeaderField(*it);
    }
    m_client->didReceiveResponse(m_loader, validatedResponse);
}
Ejemplo n.º 21
0
void PingLoader::didReceiveResponse(WebURLLoader*, const WebURLResponse& response)
{
    if (LocalFrame* frame = this->frame()) {
        TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceFinish", TRACE_EVENT_SCOPE_THREAD, "data", InspectorResourceFinishEvent::data(m_identifier, 0, true));
        const ResourceResponse& resourceResponse = response.toResourceResponse();
        InspectorInstrumentation::didReceiveResourceResponse(frame, m_identifier, 0, resourceResponse, 0);
        didFailLoading(frame);
    }
    dispose();
}
Ejemplo n.º 22
0
void SimNetwork::didReceiveResponse(WebURLLoaderClient* client, WebURLLoader* loader, const WebURLResponse& response)
{
    auto it = m_requests.find(response.url().string());
    if (it == m_requests.end()) {
        client->didReceiveResponse(loader, response);
        return;
    }
    ASSERT(it->value);
    m_currentRequest = it->value;
    m_currentRequest->didReceiveResponse(client, loader, response);
}
Ejemplo n.º 23
0
void WebAssociatedURLLoaderImpl::ClientAdapter::didReceiveResponse(
    unsigned long,
    const ResourceResponse& response,
    std::unique_ptr<WebDataConsumerHandle> handle) {
  ALLOW_UNUSED_LOCAL(handle);
  DCHECK(!handle);
  if (!m_client)
    return;

  if (m_options.exposeAllResponseHeaders ||
      m_options.crossOriginRequestPolicy !=
          WebAssociatedURLLoaderOptions::
              CrossOriginRequestPolicyUseAccessControl) {
    // Use the original ResourceResponse.
    m_client->didReceiveResponse(WrappedResourceResponse(response));
    return;
  }

  HTTPHeaderSet exposedHeaders;
  extractCorsExposedHeaderNamesList(response, exposedHeaders);
  HTTPHeaderSet blockedHeaders;
  for (const auto& header : response.httpHeaderFields()) {
    if (FetchUtils::isForbiddenResponseHeaderName(header.key) ||
        (!isOnAccessControlResponseHeaderWhitelist(header.key) &&
         !exposedHeaders.contains(header.key)))
      blockedHeaders.add(header.key);
  }

  if (blockedHeaders.isEmpty()) {
    // Use the original ResourceResponse.
    m_client->didReceiveResponse(WrappedResourceResponse(response));
    return;
  }

  // If there are blocked headers, copy the response so we can remove them.
  WebURLResponse validatedResponse = WrappedResourceResponse(response);
  for (const auto& header : blockedHeaders)
    validatedResponse.clearHTTPHeaderField(header);
  m_client->didReceiveResponse(validatedResponse);
}
Ejemplo n.º 24
0
void WebViewHost::willSendRequest(WebFrame*, unsigned identifier, WebURLRequest& request, const WebURLResponse& redirectResponse)
{
    // Need to use GURL for host() and SchemeIs()
    GURL url = request.url();
    string requestURL = url.possibly_invalid_spec();

    if (layoutTestController()->shouldDumpResourceLoadCallbacks()) {
        GURL mainDocumentURL = request.firstPartyForCookies();
        printResourceDescription(identifier);
        printf(" - willSendRequest <NSURLRequest URL %s, main document URL %s,"
               " http method %s> redirectResponse ",
               descriptionSuitableForTestResult(requestURL).c_str(),
               URLDescription(mainDocumentURL).c_str(),
               request.httpMethod().utf8().data());
        printResponseDescription(redirectResponse);
        fputs("\n", stdout);
    }

    if (!redirectResponse.isNull() && m_blocksRedirects) {
        fputs("Returning null for this redirect\n", stdout);
        // To block the request, we set its URL to an empty one.
        request.setURL(WebURL());
        return;
    }

    if (m_requestReturnNull) {
        // To block the request, we set its URL to an empty one.
        request.setURL(WebURL());
        return;
    }

    string host = url.host();
    // 255.255.255.255 is used in some tests that expect to get back an error.
    if (!host.empty() && (url.SchemeIs("http") || url.SchemeIs("https"))
        && host != "127.0.0.1"
        && host != "255.255.255.255"
        && host != "localhost"
        && !m_shell->allowExternalPages()) {
        printf("Blocked access to external URL %s\n", requestURL.c_str());

        // To block the request, we set its URL to an empty one.
        request.setURL(WebURL());
        return;
    }

    HashSet<String>::const_iterator end = m_clearHeaders.end();
    for (HashSet<String>::const_iterator header = m_clearHeaders.begin(); header != end; ++header)
        request.clearHTTPHeaderField(WebString(header->characters(), header->length()));

    // Set the new substituted URL.
    request.setURL(webkit_support::RewriteLayoutTestsURL(request.url().spec()));
}
Ejemplo n.º 25
0
void ResourceLoader::requestSynchronously(const ResourceRequest& request) {
  // downloadToFile is not supported for synchronous requests.
  DCHECK(!request.downloadToFile());
  DCHECK(m_loader);
  DCHECK_EQ(request.priority(), ResourceLoadPriorityHighest);

  WrappedResourceRequest requestIn(request);
  WebURLResponse responseOut;
  WebURLError errorOut;
  WebData dataOut;
  int64_t encodedDataLength = WebURLLoaderClient::kUnknownEncodedDataLength;
  int64_t encodedBodyLength = 0;
  m_loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut,
                              encodedDataLength, encodedBodyLength);

  // A message dispatched while synchronously fetching the resource
  // can bring about the cancellation of this load.
  if (!m_loader)
    return;
  if (errorOut.reason) {
    didFail(errorOut, encodedDataLength, encodedBodyLength);
    return;
  }
  didReceiveResponse(responseOut);
  if (!m_loader)
    return;
  DCHECK_GE(responseOut.toResourceResponse().encodedBodyLength(), 0);

  // Follow the async case convention of not calling didReceiveData or
  // appending data to m_resource if the response body is empty. Copying the
  // empty buffer is a noop in most cases, but is destructive in the case of
  // a 304, where it will overwrite the cached data we should be reusing.
  if (dataOut.size()) {
    m_fetcher->didReceiveData(m_resource.get(), dataOut.data(), dataOut.size());
    m_resource->setResourceBuffer(dataOut);
  }
  didFinishLoading(monotonicallyIncreasingTime(), encodedDataLength,
                   encodedBodyLength);
}
void ResourceLoader::requestSynchronously()
{
    OwnPtr<WebURLLoader> loader = adoptPtr(Platform::current()->createURLLoader());
    ASSERT(loader);

    // downloadToFile is not supported for synchronous requests.
    ASSERT(!m_request.downloadToFile());

    ResourcePtr<Resource> protectResource(m_resource);

    RELEASE_ASSERT(m_connectionState == ConnectionStateNew);
    m_connectionState = ConnectionStateStarted;

    WrappedResourceRequest requestIn(m_request);
    WebURLResponse responseOut;
    responseOut.initialize();
    WebURLError errorOut;
    WebData dataOut;
    loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut);
    if (errorOut.reason) {
        if (m_state == Terminated) {
            // A message dispatched while synchronously fetching the resource
            // can bring about the cancellation of this load.
            ASSERT(!m_resource);
            return;
        }
        didFail(0, errorOut);
        return;
    }
    didReceiveResponse(0, responseOut);
    if (m_state == Terminated)
        return;
    RefPtr<ResourceLoadInfo> resourceLoadInfo = responseOut.toResourceResponse().resourceLoadInfo();
    int64_t encodedDataLength = resourceLoadInfo ? resourceLoadInfo->encodedDataLength : WebURLLoaderClient::kUnknownEncodedDataLength;
    m_fetcher->didReceiveData(m_resource, dataOut.data(), dataOut.size(), encodedDataLength);
    m_resource->setResourceBuffer(dataOut);
    didFinishLoading(0, monotonicallyIncreasingTime(), encodedDataLength);
}
Ejemplo n.º 27
0
void WebDevToolsAgentImpl::didReceiveResponse(unsigned long resourceId, const WebURLResponse& response)
{
    if (InspectorController* ic = inspectorController())
        ic->didReceiveResponse(resourceId, response.toResourceResponse());
}
static void didReceiveWebViewMessageFromInjectedBundle(WebKitWebView* webView, const char* messageName, ImmutableDictionary& message)
{
    if (g_str_equal(messageName, "DidInitiateLoadForResource")) {
        WebFrameProxy* frame = static_cast<WebFrameProxy*>(message.get(String::fromUTF8("Frame")));
        WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier")));
        WebURLRequest* webRequest = static_cast<WebURLRequest*>(message.get(String::fromUTF8("Request")));
        GRefPtr<WebKitURIRequest> request = adoptGRef(webkitURIRequestCreateForResourceRequest(webRequest->resourceRequest()));

        webkitWebViewResourceLoadStarted(webView, frame, resourceIdentifier->value(), request.get());
    } else if (g_str_equal(messageName, "DidSendRequestForResource")) {
        WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier")));
        GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value());
        if (!resource)
            return;

        WebURLRequest* webRequest = static_cast<WebURLRequest*>(message.get(String::fromUTF8("Request")));
        GRefPtr<WebKitURIRequest> request = adoptGRef(webkitURIRequestCreateForResourceRequest(webRequest->resourceRequest()));
        WebURLResponse* webRedirectResponse = static_cast<WebURLResponse*>(message.get(String::fromUTF8("RedirectResponse")));
        GRefPtr<WebKitURIResponse> redirectResponse = webRedirectResponse ? adoptGRef(webkitURIResponseCreateForResourceResponse(webRedirectResponse->resourceResponse())) : 0;

        webkitWebResourceSentRequest(resource.get(), request.get(), redirectResponse.get());
    } else if (g_str_equal(messageName, "DidReceiveResponseForResource")) {
        WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier")));
        GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value());
        if (!resource)
            return;

        WebURLResponse* webResponse = static_cast<WebURLResponse*>(message.get(String::fromUTF8("Response")));
        GRefPtr<WebKitURIResponse> response = adoptGRef(webkitURIResponseCreateForResourceResponse(webResponse->resourceResponse()));

        webkitWebResourceSetResponse(resource.get(), response.get());
    } else if (g_str_equal(messageName, "DidReceiveContentLengthForResource")) {
        WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier")));
        GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value());
        if (!resource)
            return;

        WebUInt64* contentLength = static_cast<WebUInt64*>(message.get(String::fromUTF8("ContentLength")));
        webkitWebResourceNotifyProgress(resource.get(), contentLength->value());
    } else if (g_str_equal(messageName, "DidFinishLoadForResource")) {
        WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier")));
        GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value());
        if (!resource)
            return;

        webkitWebResourceFinished(resource.get());
        webkitWebViewRemoveLoadingWebResource(webView, resourceIdentifier->value());
    } else if (g_str_equal(messageName, "DidFailLoadForResource")) {
        WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier")));
        GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value());
        if (!resource)
            return;

        WebError* webError = static_cast<WebError*>(message.get(String::fromUTF8("Error")));
        const ResourceError& platformError = webError->platformError();
        GOwnPtr<GError> resourceError(g_error_new_literal(g_quark_from_string(platformError.domain().utf8().data()),
            platformError.errorCode(), platformError.localizedDescription().utf8().data()));

        webkitWebResourceFailed(resource.get(), resourceError.get());
        webkitWebViewRemoveLoadingWebResource(webView, resourceIdentifier->value());
    } else if (g_str_equal(messageName, "DidGetSnapshot")) {
        WebUInt64* callbackID = static_cast<WebUInt64*>(message.get("CallbackID"));
        WebImage* image = static_cast<WebImage*>(message.get("Snapshot"));
        webKitWebViewDidReceiveSnapshot(webView, callbackID->value(), image);
    } else
        ASSERT_NOT_REACHED();
}
Ejemplo n.º 29
0
void ResourceLoader::didReceiveResponse(WebURLLoader*, const WebURLResponse& response, WebDataConsumerHandle* rawHandle)
{
    ASSERT(!response.isNull());
    ASSERT(m_state == Initialized);
    // |rawHandle|'s ownership is transferred to the callee.
    OwnPtr<WebDataConsumerHandle> handle = adoptPtr(rawHandle);

    bool isMultipartPayload = response.isMultipartPayload();
    bool isValidStateTransition = (m_connectionState == ConnectionStateStarted || m_connectionState == ConnectionStateReceivedResponse);
    // In the case of multipart loads, calls to didReceiveData & didReceiveResponse can be interleaved.
    RELEASE_ASSERT(isMultipartPayload || isValidStateTransition);
    m_connectionState = ConnectionStateReceivedResponse;

    const ResourceResponse& resourceResponse = response.toResourceResponse();

    if (responseNeedsAccessControlCheck()) {
        if (response.wasFetchedViaServiceWorker()) {
            if (response.wasFallbackRequiredByServiceWorker()) {
                m_loader->cancel();
                m_loader.clear();
                m_connectionState = ConnectionStateStarted;
                m_loader = adoptPtr(Platform::current()->createURLLoader());
                ASSERT(m_loader);
                ASSERT(!m_request.skipServiceWorker());
                m_request.setSkipServiceWorker(true);
                WrappedResourceRequest wrappedRequest(m_request);
                m_loader->loadAsynchronously(wrappedRequest, this);
                return;
            }
        } else {
            // If the response successfully validated a cached resource, perform
            // the access control with respect to it. Need to do this right here
            // before the resource switches clients over to that validated resource.
            Resource* resource = m_resource;
            if (!resource->isCacheValidator() || resourceResponse.httpStatusCode() != 304)
                m_resource->setResponse(resourceResponse);
            if (!m_fetcher->canAccessResource(resource, m_options.securityOrigin.get(), response.url(), ResourceFetcher::ShouldLogAccessControlErrors)) {
                m_fetcher->didReceiveResponse(m_resource, resourceResponse);
                cancel(ResourceError::cancelledDueToAccessCheckError(KURL(response.url())));
                return;
            }
        }
    }

    m_resource->responseReceived(resourceResponse, handle.release());
    if (m_state == Terminated)
        return;

    m_fetcher->didReceiveResponse(m_resource, resourceResponse);
    if (m_state == Terminated)
        return;

    if (response.toResourceResponse().isMultipart()) {
        // We only support multipart for images, though the image may be loaded
        // as a main resource that we end up displaying through an ImageDocument.
        if (!m_resource->isImage() && m_resource->type() != Resource::MainResource) {
            cancel();
            return;
        }
        m_loadingMultipartContent = true;
    } else if (isMultipartPayload) {
        // Since a subresource loader does not load multipart sections progressively, data was delivered to the loader all at once.
        // After the first multipart section is complete, signal to delegates that this load is "finished"
        m_fetcher->subresourceLoaderFinishedLoadingOnePart(this);
        didFinishLoadingOnePart(0, WebURLLoaderClient::kUnknownEncodedDataLength);
    }
    if (m_state == Terminated)
        return;

    if (m_resource->response().httpStatusCode() < 400 || m_resource->shouldIgnoreHTTPStatusCodeErrors())
        return;
    m_state = Finishing;

    if (!m_notifiedLoadComplete) {
        m_notifiedLoadComplete = true;
        m_fetcher->didFailLoading(m_resource, ResourceError::cancelledError(m_request.url()));
    }

    ASSERT(m_state != Terminated);
    m_resource->error(Resource::LoadError);
    cancel();
}