Ejemplo n.º 1
0
void MainResourceLoader::handleSubstituteDataLoadNow(MainResourceLoaderTimer*)
{
    RefPtr<MainResourceLoader> protect(this);

    KURL url = m_substituteData.responseURL();
    if (url.isEmpty())
        url = m_initialRequest.url();

    // Clear the initial request here so that subsequent entries into the
    // loader will not think there's still a deferred load left to do.
    m_initialRequest = ResourceRequest();
        
    ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
    responseReceived(0, response);
}
Ejemplo n.º 2
0
void WebInspector::openInNewTab(const String& urlString)
{
    Page* inspectedPage = m_page->corePage();
    if (!inspectedPage)
        return;

    Frame& inspectedMainFrame = inspectedPage->mainFrame();
    FrameLoadRequest request(inspectedMainFrame.document()->securityOrigin(), ResourceRequest(urlString), "_blank", LockHistory::No, LockBackForwardList::No, MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, ReplaceDocumentIfJavaScriptURL, ShouldOpenExternalURLsPolicy::ShouldNotAllow);

    Page* newPage = inspectedPage->chrome().createWindow(&inspectedMainFrame, request, WindowFeatures(), NavigationAction(request.resourceRequest(), NavigationType::LinkClicked));
    if (!newPage)
        return;

    newPage->mainFrame().loader().load(request);
}
    void expectHeader(const char* input, const char* headerName, bool isPresent, const char* headerValue, float width = 0)
    {
        KURL inputURL(ParsedURLString, input);
        FetchRequest fetchRequest = FetchRequest(ResourceRequest(inputURL), FetchInitiatorInfo());
        if (width > 0) {
            FetchRequest::ResourceWidth resourceWidth;
            resourceWidth.width = width;
            resourceWidth.isSet = true;
            fetchRequest.setResourceWidth(resourceWidth);
        }
        fetchContext->addClientHintsIfNecessary(fetchRequest);

        EXPECT_STREQ(isPresent ? headerValue : "",
            fetchRequest.resourceRequest().httpHeaderField(headerName).utf8().data());
    }
Ejemplo n.º 4
0
static xmlDocPtr docLoaderFunc(const xmlChar* uri,
                               xmlDictPtr,
                               int options,
                               void* ctxt,
                               xsltLoadType type)
{
    if (!globalProcessor)
        return 0;

    switch (type) {
    case XSLT_LOAD_DOCUMENT: {
        xsltTransformContextPtr context = (xsltTransformContextPtr)ctxt;
        xmlChar* base = xmlNodeGetBase(context->document->doc, context->node);
        KURL url(KURL(ParsedURLString, reinterpret_cast<const char*>(base)), reinterpret_cast<const char*>(uri));
        xmlFree(base);

        ResourceLoaderOptions fetchOptions(ResourceFetcher::defaultResourceOptions());
        FetchRequest request(ResourceRequest(url), FetchInitiatorTypeNames::xml, fetchOptions);
        request.setOriginRestriction(FetchRequest::RestrictToSameOrigin);
        ResourcePtr<Resource> resource = globalResourceFetcher->fetchSynchronously(request);
        if (!resource || !globalProcessor)
            return 0;

        PageConsole* console = 0;
        Frame* frame = globalProcessor->xslStylesheet()->ownerDocument()->frame();
        if (frame && frame->page())
            console = &frame->page()->console();
        xmlSetStructuredErrorFunc(console, XSLTProcessor::parseErrorFunc);
        xmlSetGenericErrorFunc(console, XSLTProcessor::genericErrorFunc);

        // We don't specify an encoding here. Neither Gecko nor WinIE respects
        // the encoding specified in the HTTP headers.
        SharedBuffer* data = resource->resourceBuffer();
        xmlDocPtr doc = data ? xmlReadMemory(data->data(), data->size(), (const char*)uri, 0, options) : 0;

        xmlSetStructuredErrorFunc(0, 0);
        xmlSetGenericErrorFunc(0, 0);

        return doc;
    }
    case XSLT_LOAD_STYLESHEET:
        return globalProcessor->xslStylesheet()->locateStylesheetSubResource(((xsltStylesheetPtr)ctxt)->doc, uri);
    default:
        break;
    }

    return 0;
}
Ejemplo n.º 5
0
    virtual void fire(Frame* frame)
    {
        OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();

        if (!m_historySteps) {
            FrameLoadRequest frameRequest(frame->document()->securityOrigin(), ResourceRequest(frame->document()->url()));
            frameRequest.setLockBackForwardList(lockBackForwardList());
            // Special case for go(0) from a frame -> reload only the frame
            // To follow Firefox and IE's behavior, history reload can only navigate the self frame.
            frame->loader().load(frameRequest);
            return;
        }
        // go(i!=0) from a frame navigates into the history of the frame only,
        // in both IE and NS (but not in Mozilla). We can't easily do that.
        frame->page()->mainFrame()->loader().client()->navigateBackForward(m_historySteps);
    }
Ejemplo n.º 6
0
StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
{
    ASSERT(fetcher);

    if (!m_accessedImage) {
        m_accessedImage = true;

        FetchRequest request(ResourceRequest(m_absoluteURL), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
        request.mutableResourceRequest().setHTTPReferrer(m_referrer);

        if (ResourcePtr<ImageResource> cachedImage = fetcher->fetchImage(request))
            m_image = StyleFetchedImage::create(cachedImage.get());
    }

    return (m_image && m_image->isImageResource()) ? toStyleFetchedImage(m_image) : 0;
}
TEST_F(CachingCorrectnessTest, PostToSameURLTwice)
{
    ResourceRequest request1(KURL(ParsedURLString, kResourceURL));
    request1.setHTTPMethod(HTTPNames::POST);
    ResourcePtr<Resource> resource1 = new Resource(ResourceRequest(request1.url()), Resource::Raw);
    resource1->setLoading(true);
    memoryCache()->add(resource1.get());

    ResourceRequest request2(KURL(ParsedURLString, kResourceURL));
    request2.setHTTPMethod(HTTPNames::POST);
    FetchRequest fetch2(request2, FetchInitiatorInfo());
    ResourcePtr<Resource> resource2 = RawResource::fetchSynchronously(fetch2, fetcher());

    EXPECT_EQ(resource2, memoryCache()->resourceForURL(request2.url()));
    EXPECT_NE(resource1, resource2);
}
Ejemplo n.º 8
0
void MainResourceLoader::setDefersLoading(bool defers)
{
    ResourceLoader::setDefersLoading(defers);

    if (defers) {
        if (m_dataLoadTimer.isActive())
            m_dataLoadTimer.stop();
    } else {
        if (m_initialRequest.isNull())
            return;

        ResourceRequest initialRequest(m_initialRequest);
        m_initialRequest = ResourceRequest();
        loadNow(initialRequest);
    }
}
void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse&)
{
    ASSERT(m_client);
    ASSERT_UNUSED(loader, loader == m_loader);

// apollo integrate
//#if PLATFORM(APOLLO)
//    if (!m_document->securityOrigin()->canRequestExt(request.url(), m_document)) {
//#endif
// end apollo integrate
    if (!isAllowedRedirect(request.url())) {
        RefPtr<DocumentThreadableLoader> protect(this);
        m_client->didFailRedirectCheck();
        request = ResourceRequest();
    }
}
TEST_F(FrameFetchContextTest, ModifyPriorityForLowPriorityIframes)
{
    Settings* settings = document->frame()->settings();
    settings->setLowPriorityIframes(false);
    FetchRequest request(ResourceRequest("http://www.example.com"), FetchInitiatorInfo());
    FrameFetchContext* childFetchContext = createChildFrame();

    // No low priority iframes, expect default values.
    EXPECT_EQ(ResourceLoadPriorityVeryHigh, childFetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryHigh));
    EXPECT_EQ(ResourceLoadPriorityMedium, childFetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium));

    // Low priority iframes enabled, everything should be low priority
    settings->setLowPriorityIframes(true);
    EXPECT_EQ(ResourceLoadPriorityVeryLow, childFetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryHigh));
    EXPECT_EQ(ResourceLoadPriorityVeryLow, childFetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium));
}
Ejemplo n.º 11
0
void ContentFilter::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
{
    LOG(ContentFiltering, "ContentFilter received request for <%s> with redirect response from <%s>.\n", request.url().string().ascii().data(), redirectResponse.url().string().ascii().data());
    ResourceRequest requestCopy { request };
    ASSERT(m_state == State::Initialized || m_state == State::Filtering);
    forEachContentFilterUntilBlocked([&requestCopy, &redirectResponse](PlatformContentFilter& contentFilter) {
        contentFilter.willSendRequest(requestCopy, redirectResponse);
        if (contentFilter.didBlockData())
            requestCopy = ResourceRequest();
    });
#if !LOG_DISABLED
    if (request != requestCopy)
        LOG(ContentFiltering, "ContentFilter changed request url to <%s>.\n", requestCopy.url().string().ascii().data());
#endif
    request = requestCopy;
}
Ejemplo n.º 12
0
void Resource::error(Resource::Status status)
{
    if (!m_revalidatingRequest.isNull())
        m_revalidatingRequest = ResourceRequest();

    if (!m_error.isNull() && (m_error.isCancellation() || !isPreloaded()))
        memoryCache()->remove(this);

    setStatus(status);
    ASSERT(errorOccurred());
    m_data.clear();

    setLoading(false);
    checkNotify();
    markClientsFinished();
}
Ejemplo n.º 13
0
DownloadProxy* WebProcessPool::resumeDownload(const API::Data* resumeData, const String& path)
{
    DownloadProxy* downloadProxy = createDownloadProxy(ResourceRequest());

    SandboxExtension::Handle sandboxExtensionHandle;
    if (!path.isEmpty())
        SandboxExtension::createHandle(path, SandboxExtension::ReadWrite, sandboxExtensionHandle);

    if (networkProcess()) {
        // FIXME: If we started a download in an ephemeral session and that session still exists, we should find a way to use that same session.
        networkProcess()->send(Messages::NetworkProcess::ResumeDownload(SessionID::defaultSessionID(), downloadProxy->downloadID(), resumeData->dataReference(), path, sandboxExtensionHandle), 0);
        return downloadProxy;
    }

    return downloadProxy;
}
Ejemplo n.º 14
0
void CSSImageValue::restoreCachedResourceIfNeeded(Document& document) const
{
    if (m_isCachePending || !m_cachedImage || !document.fetcher())
        return;
    if (document.fetcher()->cachedResource(KURL(ParsedURLString, m_absoluteURL)))
        return;

    ImageResource* resource = m_cachedImage->cachedImage();
    if (!resource)
        return;

    FetchRequest request(ResourceRequest(m_absoluteURL), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, resource->options());
    MixedContentChecker::shouldBlockFetch(document.frame(), resource->lastResourceRequest(),
        resource->lastResourceRequest().url(), MixedContentChecker::SendReport);
    document.fetcher()->requestLoadStarted(resource, request, ResourceFetcher::ResourceLoadingFromCache);
}
 void SetUp() override
 {
     url = KURL(KURL(), "https://example.test/foo");
     securityInfo = "security info";
     mainResourceUrl = KURL(KURL(), "https://www.example.test");
     MockFrameLoaderClient* client = new MockFrameLoaderClient;
     EXPECT_CALL(*client, didDisplayContentWithCertificateErrors(url, securityInfo));
     dummyPageHolder = DummyPageHolder::create(IntSize(500, 500), nullptr, client);
     dummyPageHolder->page().setDeviceScaleFactor(1.0);
     documentLoader = DocumentLoader::create(&dummyPageHolder->frame(), ResourceRequest(mainResourceUrl), SubstituteData());
     document = toHTMLDocument(&dummyPageHolder->document());
     document->setURL(mainResourceUrl);
     fetchContext = static_cast<FrameFetchContext*>(&documentLoader->fetcher()->context());
     owner = DummyFrameOwner::create();
     FrameFetchContext::provideDocumentToContext(*fetchContext, document.get());
 }
Ejemplo n.º 16
0
void ResourceLoader::setDefersLoading(bool defers)
{
    if (m_options.defersLoadingPolicy() == DefersLoadingPolicy::DisallowDefersLoading)
        return;

    m_defersLoading = defers;
    if (m_handle)
        m_handle->setDefersLoading(defers);
    if (!defers && !m_deferredRequest.isNull()) {
        m_request = m_deferredRequest;
        m_deferredRequest = ResourceRequest();
        start();
    }

    platformStrategies()->loaderStrategy()->resourceLoadScheduler()->setDefersLoading(this, defers);
}
Ejemplo n.º 17
0
void NetworkResourceLoader::continueWillSendRequest(const ResourceRequest& newRequest)
{
    m_suggestedRequestForWillSendRequest.updateFromDelegatePreservingOldHTTPBody(newRequest.nsURLRequest(DoNotUpdateHTTPBody));

    RunLoop::main()->dispatch(bind(&NetworkResourceLoadScheduler::receivedRedirect, &NetworkProcess::shared().networkResourceLoadScheduler(), this, m_suggestedRequestForWillSendRequest.url()));

    m_request = m_suggestedRequestForWillSendRequest;
    m_suggestedRequestForWillSendRequest = ResourceRequest();

    m_handle->continueWillSendRequest(m_request);

    if (m_request.isNull()) {
        m_handle->cancel();
        didFail(m_handle.get(), cancelledError(m_request));
    }
}
Ejemplo n.º 18
0
void IconLoader::startLoading()
{
    if (m_resource || !m_frame.document())
        return;

    CachedResourceRequest request(ResourceRequest(m_frame.loader().icon().url()), ResourceLoaderOptions(SendCallbacks, SniffContent, BufferData, DoNotAllowStoredCredentials, DoNotAskClientForAnyCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType, DoNotIncludeCertificateInfo));

    request.mutableResourceRequest().setPriority(ResourceLoadPriorityLow);
    request.setInitiator(cachedResourceRequestInitiators().icon);

    m_resource = m_frame.document()->cachedResourceLoader().requestRawResource(request);
    if (m_resource)
        m_resource->addClient(this);
    else
        LOG_ERROR("Failed to start load for icon at url %s", m_frame.loader().icon().url().string().ascii().data());
}
Ejemplo n.º 19
0
void StyleRuleImport::requestStyleSheet()
{
    if (!m_parentStyleSheet)
        return;
    Document* document = m_parentStyleSheet->singleOwnerDocument();
    if (!document)
        return;

    CachedResourceLoader* cachedResourceLoader = document->cachedResourceLoader();
    if (!cachedResourceLoader)
        return;

    URL absURL;
    if (!m_parentStyleSheet->baseURL().isNull())
        // use parent styleheet's URL as the base URL
        absURL = URL(m_parentStyleSheet->baseURL(), m_strHref);
    else
        absURL = document->completeURL(m_strHref);

    // Check for a cycle in our import chain.  If we encounter a stylesheet
    // in our parent chain with the same URL, then just bail.
    StyleSheetContents* rootSheet = m_parentStyleSheet;
    for (StyleSheetContents* sheet = m_parentStyleSheet; sheet; sheet = sheet->parentStyleSheet()) {
        if (equalIgnoringFragmentIdentifier(absURL, sheet->baseURL())
            || equalIgnoringFragmentIdentifier(absURL, document->completeURL(sheet->originalURL())))
            return;
        rootSheet = sheet;
    }

    CachedResourceRequest request(ResourceRequest(absURL), m_parentStyleSheet->charset());
    request.setInitiator(cachedResourceRequestInitiators().css);
    if (m_cachedSheet)
        m_cachedSheet->removeClient(&m_styleSheetClient);
    if (m_parentStyleSheet->isUserStyleSheet())
        m_cachedSheet = cachedResourceLoader->requestUserCSSStyleSheet(request);
    else
        m_cachedSheet = cachedResourceLoader->requestCSSStyleSheet(request);
    if (m_cachedSheet) {
        // if the import rule is issued dynamically, the sheet may be
        // removed from the pending sheet count, so let the doc know
        // the sheet being imported is pending.
        if (m_parentStyleSheet && m_parentStyleSheet->loadCompleted() && rootSheet == m_parentStyleSheet)
            m_parentStyleSheet->startLoadingDynamicSheet();
        m_loading = true;
        m_cachedSheet->addClient(&m_styleSheetClient);
    }
}
Ejemplo n.º 20
0
void MainResourceLoader::load(const ResourceRequest& initialRequest, const SubstituteData& substituteData)
{
    // It appears that it is possible for this load to be cancelled and derefenced by the DocumentLoader
    // in willSendRequest() if loadNow() is called.
    RefPtr<MainResourceLoader> protect(this);

    m_substituteData = substituteData;

    ASSERT(documentLoader()->timing()->navigationStart());
    ASSERT(!documentLoader()->timing()->fetchStart());
    documentLoader()->timing()->markFetchStart();
    ResourceRequest request(initialRequest);

    // Send this synthetic delegate callback since clients expect it, and
    // we no longer send the callback from within NSURLConnection for
    // initial requests.
    willSendRequest(request, ResourceResponse());
    ASSERT(!deletionHasBegun());

    // willSendRequest() may lead to our DocumentLoader being detached or cancelling the load via nulling the ResourceRequest.
    if (!documentLoader()->frame() || request.isNull())
        return;

    documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData);

    if (m_substituteData.isValid()) {
        handleSubstituteDataLoadSoon(request);
        return;
    }

    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, mainResourceLoadOptions,
        (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck));
    CachedResourceRequest cachedResourceRequest(request, mainResourceLoadOptions);
    m_resource = documentLoader()->cachedResourceLoader()->requestMainResource(cachedResourceRequest);
    if (!m_resource) {
        documentLoader()->setRequest(ResourceRequest());
        return;
    }
    m_resource->addClient(this);

    // We need to wait until after requestMainResource() is called to setRequest(), because there are a bunch of headers set when
    // the underlying ResourceLoader is created, and DocumentLoader::m_request needs to include those. However, the cache will
    // strip the fragment identifier (which DocumentLoader::m_request should also include), so add that back in.
    if (loader())
        request = loader()->originalRequest();
    documentLoader()->setRequest(request);
}
Ejemplo n.º 21
0
void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
{
    if (attrName == SVGNames::xAttr
        || attrName == SVGNames::yAttr
        || attrName == SVGNames::widthAttr
        || attrName == SVGNames::heightAttr) {
        SVGElement::InvalidationGuard invalidationGuard(this);

        if (attrName == SVGNames::xAttr
            || attrName == SVGNames::yAttr) {
            invalidateSVGPresentationAttributeStyle();
            setNeedsStyleRecalc(LocalStyleChange,
                StyleChangeReasonForTracing::fromAttribute(attrName));
        }

        updateRelativeLengthsInformation();
        if (m_targetElementInstance) {
            ASSERT(m_targetElementInstance->correspondingElement());
            transferUseWidthAndHeightIfNeeded(*this, m_targetElementInstance.get(), *m_targetElementInstance->correspondingElement());
        }

        LayoutObject* object = this->layoutObject();
        if (object)
            markForLayoutAndParentResourceInvalidation(object);
        return;
    }

    if (SVGURIReference::isKnownAttribute(attrName)) {
        SVGElement::InvalidationGuard invalidationGuard(this);
        if (isStructurallyExternal()) {
            KURL url = document().completeURL(hrefString());
            const KURL& existingURL = m_resource ? m_resource->url() : KURL();
            if (url.hasFragmentIdentifier() && !equalIgnoringFragmentIdentifier(url, existingURL)) {
                FetchRequest request(ResourceRequest(url), localName());
                setDocumentResource(DocumentResource::fetchSVGDocument(request, document().fetcher()));
            }
        } else {
            setDocumentResource(nullptr);
        }

        invalidateShadowTree();

        return;
    }

    SVGGraphicsElement::svgAttributeChanged(attrName);
}
Ejemplo n.º 22
0
LocalFrame* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
    DOMWindow& callingWindow, LocalFrame& firstFrame, LocalFrame& openerFrame, DOMWindow::PrepareDialogFunction function, void* functionContext)
{
    LocalFrame* activeFrame = callingWindow.frame();
    ASSERT(activeFrame);

    KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, emptyString()) : firstFrame.document()->completeURL(urlString);
    if (!completedURL.isEmpty() && !completedURL.isValid()) {
        // Don't expose client code to invalid URLs.
        callingWindow.printErrorMessage("Unable to open a window with invalid URL '" + completedURL.string() + "'.\n");
        return 0;
    }

    // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
    Referrer referrer(SecurityPolicy::generateReferrerHeader(firstFrame.document()->referrerPolicy(), completedURL, firstFrame.document()->outgoingReferrer()), firstFrame.document()->referrerPolicy());

    ResourceRequest request(completedURL, referrer);
    FrameLoader::addHTTPOriginIfNeeded(request, AtomicString(firstFrame.document()->outgoingOrigin()));
    FrameLoadRequest frameRequest(callingWindow.document(), request, frameName);

    // We pass the opener frame for the lookupFrame in case the active frame is different from
    // the opener frame, and the name references a frame relative to the opener frame.
    bool created;
    LocalFrame* newFrame = createWindow(*activeFrame, openerFrame, frameRequest, windowFeatures, NavigationPolicyIgnore, MaybeSendReferrer, created);
    if (!newFrame)
        return 0;

    if (newFrame != &openerFrame && newFrame != openerFrame.tree().top())
        newFrame->loader().forceSandboxFlags(openerFrame.document()->sandboxFlags());

    newFrame->loader().setOpener(&openerFrame);
    newFrame->page()->setOpenedByDOM();

    if (newFrame->domWindow()->isInsecureScriptAccess(callingWindow, completedURL))
        return newFrame;

    if (function)
        function(newFrame->domWindow(), functionContext);

    if (created) {
        FrameLoadRequest request(callingWindow.document(), ResourceRequest(completedURL, referrer));
        newFrame->loader().load(request);
    } else if (!urlString.isEmpty()) {
        newFrame->navigationScheduler().scheduleLocationChange(callingWindow.document(), completedURL.string(), referrer, false);
    }
    return newFrame;
}
FontResource* CSSFontFaceSrcValue::fetch(Document* document)
{
    if (!m_fetched) {
        FetchRequest request(ResourceRequest(document->completeURL(m_resource)), FetchInitiatorTypeNames::css);
        SecurityOrigin* securityOrigin = document->securityOrigin();
        if (shouldSetCrossOriginAccessControl(request.url(), securityOrigin)) {
            request.setCrossOriginAccessControl(securityOrigin, DoNotAllowStoredCredentials);
        }
        request.mutableResourceRequest().setHTTPReferrer(m_referrer);
        m_fetched = document->fetcher()->fetchFont(request);
    } else {
        // FIXME: CSSFontFaceSrcValue::fetch is invoked when @font-face rule
        // is processed by StyleResolver / StyleEngine.
        restoreCachedResourceIfNeeded(document);
    }
    return m_fetched.get();
}
Ejemplo n.º 24
0
bool ScriptLoader::fetchScript(const String& sourceUrl, FetchRequest::DeferOption defer)
{
    DCHECK(m_element);

    Document* elementDocument = &(m_element->document());
    if (!m_element->inShadowIncludingDocument() || m_element->document() != elementDocument)
        return false;

    DCHECK(!m_resource);
    if (!stripLeadingAndTrailingHTMLSpaces(sourceUrl).isEmpty()) {
        FetchRequest request(ResourceRequest(elementDocument->completeURL(sourceUrl)), m_element->localName());

        CrossOriginAttributeValue crossOrigin = crossOriginAttributeValue(m_element->fastGetAttribute(HTMLNames::crossoriginAttr));
        if (crossOrigin != CrossOriginAttributeNotSet)
            request.setCrossOriginAccessControl(elementDocument->getSecurityOrigin(), crossOrigin);
        request.setCharset(scriptCharset());

        // Skip fetch-related CSP checks if dynamically injected script is whitelisted and this script is not parser-inserted.
        bool scriptPassesCSPDynamic = (!isParserInserted() && elementDocument->contentSecurityPolicy()->allowDynamic());

        request.setContentSecurityPolicyNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr));

        if (scriptPassesCSPDynamic) {
            UseCounter::count(elementDocument->frame(), UseCounter::ScriptPassesCSPDynamic);
            request.setContentSecurityCheck(DoNotCheckContentSecurityPolicy);
        }
        request.setDefer(defer);

        String integrityAttr = m_element->fastGetAttribute(HTMLNames::integrityAttr);
        if (!integrityAttr.isEmpty()) {
            IntegrityMetadataSet metadataSet;
            SubresourceIntegrity::parseIntegrityAttribute(integrityAttr, metadataSet, elementDocument);
            request.setIntegrityMetadata(metadataSet);
        }

        m_resource = ScriptResource::fetch(request, elementDocument->fetcher());

        m_isExternalScript = true;
    }

    if (m_resource)
        return true;

    dispatchErrorEvent();
    return false;
}
Ejemplo n.º 25
0
void SVGUseElement::updateTargetReference() {
  SVGURLReferenceResolver resolver(hrefString(), document());
  m_elementIdentifier = resolver.fragmentIdentifier();
  m_elementIdentifierIsLocal = resolver.isLocal();
  if (m_elementIdentifierIsLocal) {
    setDocumentResource(nullptr);
    return;
  }
  KURL resolvedUrl = resolver.absoluteUrl();
  if (m_elementIdentifier.isEmpty() ||
      (m_resource &&
       equalIgnoringFragmentIdentifier(resolvedUrl, m_resource->url())))
    return;
  FetchRequest request(ResourceRequest(resolvedUrl), localName());
  setDocumentResource(
      DocumentResource::fetchSVGDocument(request, document().fetcher()));
}
Ejemplo n.º 26
0
void DocumentThreadableLoader::loadActualRequest() {
  ResourceRequest actualRequest = m_actualRequest;
  ResourceLoaderOptions actualOptions = m_actualOptions;
  m_actualRequest = ResourceRequest();
  m_actualOptions = ResourceLoaderOptions();

  clearResource();

  // Explicitly set the SkipServiceWorker flag here. Even if the page was not
  // controlled by a SW when the preflight request was sent, a new SW may be
  // controlling the page now by calling clients.claim(). We should not send
  // the actual request to the SW. https://crbug.com/604583
  actualRequest.setSkipServiceWorker(WebURLRequest::SkipServiceWorker::All);

  prepareCrossOriginRequest(actualRequest);
  loadRequest(actualRequest, actualOptions);
}
Ejemplo n.º 27
0
bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, CrossOriginAttributeValue crossOrigin, const String& type,
    const String& as, const String& media, const KURL& href, Document& document, const NetworkHintsInterface& networkHintsInterface)
{
    // TODO(yoav): Do all links need to load only after they're in document???

    // TODO(yoav): Convert all uses of the CrossOriginAttribute to CrossOriginAttributeValue. crbug.com/486689
    // FIXME(crbug.com/463266): We're ignoring type here, for everything but preload. Maybe we shouldn't.
    dnsPrefetchIfNeeded(relAttribute, href, document, networkHintsInterface, LinkCalledFromMarkup);

    preconnectIfNeeded(relAttribute, href, document, crossOrigin, networkHintsInterface, LinkCalledFromMarkup);

    bool errorOccurred = false;
    if (m_client->shouldLoadLink())
        createLinkPreloadResourceClient(preloadIfNeeded(relAttribute, href, document, as, type, media, crossOrigin, LinkCalledFromMarkup, errorOccurred, nullptr));
    if (errorOccurred)
        m_linkLoadingErrorTimer.startOneShot(0, BLINK_FROM_HERE);

    if (href.isEmpty() || !href.isValid())
        released();

    // FIXME(crbug.com/323096): Should take care of import.
    if (relAttribute.isLinkPrefetch() && href.isValid() && document.frame()) {
        if (!m_client->shouldLoadLink())
            return false;
        UseCounter::count(document, UseCounter::LinkRelPrefetch);

        FetchRequest linkRequest(ResourceRequest(document.completeURL(href)), FetchInitiatorTypeNames::link);
        if (crossOrigin != CrossOriginAttributeNotSet)
            linkRequest.setCrossOriginAccessControl(document.getSecurityOrigin(), crossOrigin);
        setResource(LinkFetchResource::fetch(Resource::LinkPrefetch, linkRequest, document.fetcher()));
    }

    if (const unsigned prerenderRelTypes = prerenderRelTypesFromRelAttribute(relAttribute, document)) {
        if (!m_prerender) {
            m_prerender = PrerenderHandle::create(document, this, href, prerenderRelTypes);
        } else if (m_prerender->url() != href) {
            m_prerender->cancel();
            m_prerender = PrerenderHandle::create(document, this, href, prerenderRelTypes);
        }
        // TODO(gavinp): Handle changes to rel types of existing prerenders.
    } else if (m_prerender) {
        m_prerender->cancel();
        m_prerender.clear();
    }
    return true;
}
Ejemplo n.º 28
0
Resource* MemoryCacheCorrectnessTestHelper::resourceFromResourceResponse(
    ResourceResponse response,
    Resource::Type type) {
  if (response.url().isNull())
    response.setURL(KURL(ParsedURLString, kResourceURL));
  Resource* resource = createResource(ResourceRequest(response.url()), type);
  resource->setResponse(response);
  resource->finish();
  // Because we didn't give any real data, an image will have set its status
  // to DecodeError. Override it so the resource is cacaheable for testing
  // purposes.
  if (type == Resource::Image)
    resource->setStatus(Resource::Cached);
  memoryCache()->add(resource);

  return resource;
}
Ejemplo n.º 29
0
void StyleRuleImport::requestStyleSheet() {
  if (!m_parentStyleSheet)
    return;
  Document* document = m_parentStyleSheet->singleOwnerDocument();
  if (!document)
    return;

  ResourceFetcher* fetcher = document->fetcher();
  if (!fetcher)
    return;

  KURL absURL;
  if (!m_parentStyleSheet->baseURL().isNull()) {
    // use parent styleheet's URL as the base URL
    absURL = KURL(m_parentStyleSheet->baseURL(), m_strHref);
  } else {
    absURL = document->completeURL(m_strHref);
  }

  // Check for a cycle in our import chain.  If we encounter a stylesheet
  // in our parent chain with the same URL, then just bail.
  StyleSheetContents* rootSheet = m_parentStyleSheet;
  for (StyleSheetContents* sheet = m_parentStyleSheet; sheet;
       sheet = sheet->parentStyleSheet()) {
    if (equalIgnoringFragmentIdentifier(absURL, sheet->baseURL()) ||
        equalIgnoringFragmentIdentifier(
            absURL, document->completeURL(sheet->originalURL())))
      return;
    rootSheet = sheet;
  }

  FetchRequest request(ResourceRequest(absURL), FetchInitiatorTypeNames::css,
                       m_parentStyleSheet->charset());
  m_resource = CSSStyleSheetResource::fetch(request, fetcher);
  if (m_resource) {
    // if the import rule is issued dynamically, the sheet may be
    // removed from the pending sheet count, so let the doc know
    // the sheet being imported is pending.
    if (m_parentStyleSheet && m_parentStyleSheet->loadCompleted() &&
        rootSheet == m_parentStyleSheet)
      m_parentStyleSheet->startLoadingDynamicSheet();
    m_loading = true;
    m_resource->addClient(m_styleSheetClient);
  }
}
Ejemplo n.º 30
0
void ResourceRequest::doUpdateResourceRequest()
{
    if (!m_cfRequest) {
        *this = ResourceRequest();
        return;
    }

    m_url = CFURLRequestGetURL(m_cfRequest.get());

    m_cachePolicy = (ResourceRequestCachePolicy)CFURLRequestGetCachePolicy(m_cfRequest.get());
    m_timeoutInterval = CFURLRequestGetTimeoutInterval(m_cfRequest.get());
    m_firstPartyForCookies = CFURLRequestGetMainDocumentURL(m_cfRequest.get());
    if (CFStringRef method = CFURLRequestCopyHTTPRequestMethod(m_cfRequest.get())) {
        m_httpMethod = method;
        CFRelease(method);
    }
    m_allowCookies = CFURLRequestShouldHandleHTTPCookies(m_cfRequest.get());

    if (httpPipeliningEnabled())
        m_priority = toResourceLoadPriority(wkGetHTTPPipeliningPriority(m_cfRequest.get()));

    m_httpHeaderFields.clear();
    if (CFDictionaryRef headers = CFURLRequestCopyAllHTTPHeaderFields(m_cfRequest.get())) {
        CFIndex headerCount = CFDictionaryGetCount(headers);
        Vector<const void*, 128> keys(headerCount);
        Vector<const void*, 128> values(headerCount);
        CFDictionaryGetKeysAndValues(headers, keys.data(), values.data());
        for (int i = 0; i < headerCount; ++i)
            m_httpHeaderFields.set((CFStringRef)keys[i], (CFStringRef)values[i]);
        CFRelease(headers);
    }

    m_responseContentDispositionEncodingFallbackArray.clear();
    RetainPtr<CFArrayRef> encodingFallbacks(AdoptCF, copyContentDispositionEncodingFallbackArray(m_cfRequest.get()));
    if (encodingFallbacks) {
        CFIndex count = CFArrayGetCount(encodingFallbacks.get());
        for (CFIndex i = 0; i < count; ++i) {
            CFStringEncoding encoding = reinterpret_cast<CFIndex>(CFArrayGetValueAtIndex(encodingFallbacks.get(), i));
            if (encoding != kCFStringEncodingInvalidId)
                m_responseContentDispositionEncodingFallbackArray.append(CFStringConvertEncodingToIANACharSetName(encoding));
        }
    }

    m_httpBody = httpBodyFromRequest(m_cfRequest.get());
}