PassRefPtr<Widget> SubframeLoader::loadMediaPlayerProxyPlugin(Node* node, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues) { ASSERT(node->hasTagName(videoTag) || isHTMLAudioElement(node)); KURL completedURL; if (!url.isEmpty()) completedURL = completeURL(url); if (!m_frame->document()->securityOrigin()->canDisplay(completedURL)) { FrameLoader::reportLocalLoadFailed(m_frame, completedURL.string()); return 0; } if (!m_frame->document()->contentSecurityPolicy()->allowMediaFromSource(completedURL)) return 0; HTMLMediaElement* mediaElement = toHTMLMediaElement(node); RenderWidget* renderer = toRenderWidget(node->renderer()); IntSize size; if (renderer) size = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight())); else if (mediaElement->isVideo()) size = RenderVideo::defaultSize(); if (!m_frame->loader().mixedContentChecker().canRunInsecureContent(m_frame->document()->securityOrigin(), completedURL)) return 0; RefPtr<Widget> widget = m_frame->loader().client().createMediaPlayerProxyPlugin(size, mediaElement, completedURL, paramNames, paramValues, "application/x-media-element-proxy-plugin"); if (widget && renderer) { renderer->setWidget(widget); renderer->node()->setNeedsStyleRecalc(SyntheticStyleChange); } m_containsPlugins = true; return widget ? widget.release() : 0; }
PassRefPtr<SharedWorker> SharedWorker::create(const String& url, const String& name, ScriptExecutionContext* context, ExceptionCode& ec) { RefPtr<SharedWorker> worker = adoptRef(new SharedWorker(context)); RefPtr<MessageChannel> channel = MessageChannel::create(context); worker->m_port = channel->port1(); OwnPtr<MessagePortChannel> remotePort = channel->port2()->disentangle(ec); ASSERT(remotePort); KURL scriptURL = worker->resolveURL(url, ec); if (scriptURL.isEmpty()) return 0; SharedWorkerRepository::connect(worker.get(), remotePort.release(), scriptURL, name, ec); #if ENABLE(INSPECTOR) if (InspectorController* inspector = context->inspectorController()) inspector->didCreateWorker(worker->asID(), scriptURL.string(), true); #endif return worker.release(); }
void Pasteboard::writeURL(const KURL& url, const String& titleStr, Frame* frame) { ASSERT(!url.isEmpty()); clear(); String title(titleStr); if (title.isEmpty()) { title = url.lastPathComponent(); if (title.isEmpty()) title = url.host(); } // write to clipboard in format com.apple.safari.bookmarkdata to be able to paste into the bookmarks view with appropriate title if (::OpenClipboard(m_owner)) { HGLOBAL cbData = createGlobalData(url, title); if (!::SetClipboardData(BookmarkClipboardFormat, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // write to clipboard in format CF_HTML to be able to paste into contenteditable areas as a link if (::OpenClipboard(m_owner)) { Vector<char> data; markupToCFHTML(urlToMarkup(url, title), "", data); HGLOBAL cbData = createGlobalData(data); if (!::SetClipboardData(HTMLClipboardFormat, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // bare-bones CF_UNICODETEXT support if (::OpenClipboard(m_owner)) { HGLOBAL cbData = createGlobalData(url.string()); if (!::SetClipboardData(CF_UNICODETEXT, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } }
void KURL::init(const KURL& base, const CHAR* relative, int relativeLength, const WTF::TextEncoding* queryEncoding) { // As a performance optimization, we do not use the charset converter // if encoding is UTF-8 or other Unicode encodings. Note that this is // per HTML5 2.5.3 (resolving URL). The URL canonicalizer will be more // efficient with no charset converter object because it can do UTF-8 // internally with no extra copies. // We feel free to make the charset converter object every time since it's // just a wrapper around a reference. KURLCharsetConverter charsetConverterObject(queryEncoding); KURLCharsetConverter* charsetConverter = (!queryEncoding || isUnicodeEncoding(queryEncoding)) ? 0 : &charsetConverterObject; StringUTF8Adaptor baseUTF8(base.string()); url::RawCanonOutputT<char> output; m_isValid = url::ResolveRelative(baseUTF8.data(), baseUTF8.length(), base.m_parsed, relative, relativeLength, charsetConverter, &output, &m_parsed); // See FIXME in KURLPrivate in the header. If canonicalization has not // changed the string, we can avoid an extra allocation by using assignment. m_string = AtomicString::fromUTF8(output.data(), output.length()); }
void ClipboardGtk::writeURL(const KURL& url, const String& label, Frame*) { String actualLabel(label); if (actualLabel.isEmpty()) actualLabel = url; m_dataObject->setText(actualLabel); Vector<UChar> markup; append(markup, "<a href=\""); append(markup, url.string()); append(markup, "\">"); append(markup, label); append(markup, "</a>"); m_dataObject->setMarkup(String::adopt(markup)); Vector<KURL> uriList; uriList.append(url); m_dataObject->setURIList(uriList); if (m_clipboard) m_helper->writeClipboardContents(m_clipboard); }
bool SubframeLoader::loadPlugin(HTMLPlugInImageElement* pluginElement, const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback) { RenderEmbeddedObject* renderer = pluginElement->renderEmbeddedObject(); // FIXME: This code should not depend on renderer! if (!renderer || useFallback) return false; if (!document()->securityOrigin()->canDisplay(url)) { FrameLoader::reportLocalLoadFailed(m_frame, url.string()); return false; } if (!document()->contentSecurityPolicy()->allowObjectFromSource(url)) return false; FrameLoader* frameLoader = m_frame->loader(); if (!frameLoader->checkIfRunInsecureContent(document()->securityOrigin(), url)) return false; IntSize contentSize(renderer->contentWidth(), renderer->contentHeight()); bool loadManually = document()->isPluginDocument() && !m_containsPlugins && toPluginDocument(document())->shouldLoadPluginManually(); RefPtr<Widget> widget = frameLoader->client()->createPlugin(contentSize, pluginElement, url, paramNames, paramValues, mimeType, loadManually); if (!widget) { renderer->setShowsMissingPluginIndicator(); return false; } renderer->setWidget(widget); m_containsPlugins = true; #if ENABLE(PLUGIN_PROXY_FOR_VIDEO) || ENABLE(3D_PLUGIN) pluginElement->setNeedsStyleRecalc(SyntheticStyleChange); #endif return true; }
void deleteCookie(const NetworkStorageSession& session, const KURL& url, const String& name) { SoupCookieJar* jar = cookieJarForSession(session); if (!jar) return; GOwnPtr<SoupURI> uri(soup_uri_new(url.string().utf8().data())); GOwnPtr<GSList> cookies(soup_cookie_jar_get_cookie_list(jar, uri.get(), TRUE)); if (!cookies) return; CString cookieName = name.utf8(); bool wasDeleted = false; for (GSList* iter = cookies.get(); iter; iter = g_slist_next(iter)) { SoupCookie* cookie = static_cast<SoupCookie*>(iter->data); if (!wasDeleted && cookieName == cookie->name) { soup_cookie_jar_delete_cookie(jar, cookie); wasDeleted = true; } soup_cookie_free(cookie); } }
bool getRawCookies(const NetworkStorageSession& session, const KURL& /*firstParty*/, const KURL& url, Vector<Cookie>& rawCookies) { rawCookies.clear(); SoupCookieJar* jar = cookieJarForSession(session); if (!jar) return false; GOwnPtr<SoupURI> uri(soup_uri_new(url.string().utf8().data())); GOwnPtr<GSList> cookies(soup_cookie_jar_get_cookie_list(jar, uri.get(), TRUE)); if (!cookies) return false; for (GSList* iter = cookies.get(); iter; iter = g_slist_next(iter)) { SoupCookie* cookie = static_cast<SoupCookie*>(iter->data); rawCookies.append(Cookie(String::fromUTF8(cookie->name), String::fromUTF8(cookie->value), String::fromUTF8(cookie->domain), String::fromUTF8(cookie->path), cookie->expires ? static_cast<double>(soup_date_to_time_t(cookie->expires)) * 1000 : 0, cookie->http_only, cookie->secure, !cookie->expires)); soup_cookie_free(cookie); } return true; }
bool HTMLPlugInElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback, bool requireRenderer) { LocalFrame* frame = document().frame(); if (!frame->loader().allowPlugins(AboutToInstantiatePlugin)) return false; RenderEmbeddedObject* renderer = renderEmbeddedObject(); // FIXME: This code should not depend on renderer! if ((!renderer && requireRenderer) || useFallback) return false; WTF_LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data()); WTF_LOG(Plugins, " Loaded URL: %s", url.string().utf8().data()); m_loadedUrl = url; RefPtr<Widget> widget = m_persistedPluginWidget; if (!widget) { bool loadManually = document().isPluginDocument() && !document().containsPlugins() && toPluginDocument(document()).shouldLoadPluginManually(); FrameLoaderClient::DetachedPluginPolicy policy = requireRenderer ? FrameLoaderClient::FailOnDetachedPlugin : FrameLoaderClient::AllowDetachedPlugin; widget = frame->loader().client()->createPlugin(this, url, paramNames, paramValues, mimeType, loadManually, policy); } if (!widget) { if (renderer && !renderer->showsUnavailablePluginIndicator()) renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing); return false; } if (renderer) { setWidget(widget); m_persistedPluginWidget = nullptr; } else if (widget != m_persistedPluginWidget) { m_persistedPluginWidget = widget; } document().setContainsPlugins(); scheduleSVGFilterLayerUpdateHack(); return true; }
static String pathSuitableForTestResult(const char* uriString) { KURL uri = KURL(ParsedURLString, uriString); if (uri.isEmpty()) return "(null)"; if (!uri.isLocalFile()) return uri.string(); KURL mainFrameURL = KURL(ParsedURLString, ewk_frame_uri_get(browser->mainFrame())); if (mainFrameURL.isEmpty()) mainFrameURL = DumpRenderTreeSupportEfl::provisionalURL(browser->mainFrame()); String mainFrameUrlPathString = mainFrameURL.path(); String pathString = uri.path(); String basePath = mainFrameUrlPathString.substring(0, mainFrameUrlPathString.reverseFind('/') + 1); if (!basePath.isEmpty() && pathString.startsWith(basePath)) return pathString.substring(basePath.length()); return uri.lastPathComponent(); }
void DumpRenderTreeChrome::onWillSendRequest(void*, Evas_Object*, void* eventInfo) { Ewk_Frame_Resource_Messages* messages = static_cast<Ewk_Frame_Resource_Messages*>(eventInfo); if (!done && gTestRunner->dumpResourceLoadCallbacks()) printf("%s - willSendRequest %s redirectResponse %s\n", m_dumpAssignedUrls.contains(messages->request->identifier) ? m_dumpAssignedUrls.get(messages->request->identifier).data() : "<unknown>", descriptionSuitableForTestResult(messages->request).data(), descriptionSuitableForTestResult(messages->redirect_response).data()); if (!done && gTestRunner->willSendRequestReturnsNull()) { // As requested by the TestRunner, don't perform the request. messages->request->url = 0; return; } if (!done && gTestRunner->willSendRequestReturnsNullOnRedirect() && messages->redirect_response) { printf("Returning null for this redirect\n"); messages->request->url = 0; return; } KURL url = KURL(ParsedURLString, messages->request->url); if (url.isValid() && url.protocolIsInHTTPFamily() && url.host() != "127.0.0.1" && url.host() != "255.255.255.255" && url.host().lower() != "localhost") { printf("Blocked access to external URL %s\n", messages->request->url); messages->request->url = 0; return; } const std::string& destination = gTestRunner->redirectionDestinationForURL(url.string().utf8().data()); if (destination.length()) messages->request->url = strdup(destination.c_str()); }
bool SubframeLoader::pluginIsLoadable(HTMLPlugInImageElement* pluginElement, const KURL& url, const String& mimeType) { Settings* settings = m_frame->settings(); if (!settings) return false; if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) { if (!settings->isJavaEnabled()) return false; if (document() && document()->securityOrigin()->isLocal() && !settings->isJavaEnabledForLocalFiles()) return false; } if (document()) { if (document()->isSandboxed(SandboxPlugins)) return false; if (!document()->securityOrigin()->canDisplay(url)) { FrameLoader::reportLocalLoadFailed(m_frame, url.string()); return false; } String declaredMimeType = document()->isPluginDocument() && document()->ownerElement() ? document()->ownerElement()->fastGetAttribute(HTMLNames::typeAttr) : pluginElement->fastGetAttribute(HTMLNames::typeAttr); if (!document()->contentSecurityPolicy()->allowObjectFromSource(url) || !document()->contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) { RenderEmbeddedObject* renderer = pluginElement->renderEmbeddedObject(); renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy); return false; } if (m_frame->loader() && !m_frame->loader()->mixedContentChecker()->canRunInsecureContent(document()->securityOrigin(), url)) return false; } return true; }
bool getRawCookies(NetworkingContext* context, const KURL& /*firstParty*/, const KURL& url, Vector<Cookie>& rawCookies) { rawCookies.clear(); SoupCookieJar* jar = context ? cookieJarForContext(context) : soupCookieJar(); if (!jar) return false; GOwnPtr<GSList> cookies(soup_cookie_jar_all_cookies(jar)); if (!cookies) return false; GOwnPtr<SoupURI> uri(soup_uri_new(url.string().utf8().data())); for (GSList* iter = cookies.get(); iter; iter = g_slist_next(iter)) { GOwnPtr<SoupCookie> cookie(static_cast<SoupCookie*>(iter->data)); if (!soup_cookie_applies_to_uri(cookie.get(), uri.get())) continue; rawCookies.append(Cookie(String::fromUTF8(cookie->name), String::fromUTF8(cookie->value), String::fromUTF8(cookie->domain), String::fromUTF8(cookie->path), static_cast<double>(soup_date_to_time_t(cookie->expires)) * 1000, cookie->http_only, cookie->secure, soup_cookie_jar_is_persistent(jar))); } return true; }
void CustomContextMenuProvider::appendMenuItem(HTMLMenuItemElement* menuItem, ContextMenu& contextMenu) { // Avoid menuitems with no label. String labelString = menuItem->fastGetAttribute(labelAttr); if (labelString.isEmpty()) return; m_menuItems.append(menuItem); bool enabled = !menuItem->fastHasAttribute(disabledAttr); String icon = menuItem->fastGetAttribute(iconAttr); if (!icon.isEmpty()) { // To obtain the absolute URL of the icon when the attribute's value is not the empty string, // the attribute's value must be resolved relative to the element. KURL iconURL = KURL(menuItem->baseURI(), icon); icon = iconURL.string(); } ContextMenuAction action = static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + m_menuItems.size() - 1); if (equalIgnoringCase(menuItem->fastGetAttribute(typeAttr), "checkbox") || equalIgnoringCase(menuItem->fastGetAttribute(typeAttr), "radio")) contextMenu.appendItem(ContextMenuItem(CheckableActionType, action, labelString, icon, enabled, menuItem->fastHasAttribute(checkedAttr))); else contextMenu.appendItem(ContextMenuItem(ActionType, action, labelString, icon, enabled, false)); }
PassRefPtr<FormData> HTMLFormElement::prepareFormData() { if (m_formDataBuilder.isPostMethod()) { if (m_formDataBuilder.isMultiPartForm() && isMailtoForm()) { // FIXME: This may fire a DOM Mutation Event. Do we really want this here? setEnctype("application/x-www-form-urlencoded"); ASSERT(!m_formDataBuilder.isMultiPartForm()); } } else m_formDataBuilder.setIsMultiPartForm(false); RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding().encodingForFormSubmission()); for (unsigned i = 0; i < m_associatedElements.size(); ++i) { HTMLFormControlElement* control = m_associatedElements[i]; if (!control->disabled()) control->appendFormData(*domFormData, m_formDataBuilder.isMultiPartForm()); } RefPtr<FormData> result; if (m_formDataBuilder.isMultiPartForm()) result = FormData::createMultiPart(domFormData->items(), domFormData->encoding(), document()); else { result = FormData::create(domFormData->items(), domFormData->encoding()); if (m_formDataBuilder.isPostMethod() && isMailtoForm()) { // Convert the form data into a string that we put into the URL. KURL url = document()->completeURL(m_url); appendMailtoPostFormDataToURL(url, *result, m_formDataBuilder.encodingType()); m_url = url.string(); result = FormData::create(); } } result->setIdentifier(generateFormDataIdentifier()); return result.release(); }
PassRefPtr<Widget> SubframeLoader::createJavaAppletWidget(const IntSize& size, HTMLAppletElement* element, const HashMap<String, String>& args) { String baseURLString; String codeBaseURLString; Vector<String> paramNames; Vector<String> paramValues; HashMap<String, String>::const_iterator end = args.end(); for (HashMap<String, String>::const_iterator it = args.begin(); it != end; ++it) { if (equalIgnoringCase(it->first, "baseurl")) baseURLString = it->second; else if (equalIgnoringCase(it->first, "codebase")) codeBaseURLString = it->second; paramNames.append(it->first); paramValues.append(it->second); } if (!codeBaseURLString.isEmpty()) { KURL codeBaseURL = completeURL(codeBaseURLString); if (!element->document()->securityOrigin()->canDisplay(codeBaseURL)) { FrameLoader::reportLocalLoadFailed(m_frame, codeBaseURL.string()); return 0; } } if (baseURLString.isEmpty()) baseURLString = m_frame->document()->baseURL().string(); KURL baseURL = completeURL(baseURLString); RefPtr<Widget> widget; if (allowPlugins(AboutToInstantiatePlugin)) widget = m_frame->loader()->client()->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues); if (!widget) return 0; m_containsPlugins = true; return widget; }
bool ScriptController::executeIfJavaScriptURL(const KURL& url, bool userGesture, bool replaceDocument) { if (!protocolIsJavaScript(url)) return false; if (m_frame->page() && !m_frame->page()->javaScriptURLsAreAllowed()) return true; if (m_frame->inViewSourceMode()) return true; const int javascriptSchemeLength = sizeof("javascript:") - 1; String script = decodeURLEscapeSequences(url.string().substring(javascriptSchemeLength)); ScriptValue result; if (xssAuditor()->canEvaluateJavaScriptURL(script)) result = executeScript(script, userGesture); String scriptResult; #if USE(JSC) JSDOMWindowShell* shell = windowShell(mainThreadNormalWorld()); JSC::ExecState* exec = shell->window()->globalExec(); if (!result.getString(exec, scriptResult)) return true; #else if (!result.getString(scriptResult)) return true; #endif // FIXME: We should always replace the document, but doing so // synchronously can cause crashes: // http://bugs.webkit.org/show_bug.cgi?id=16782 if (replaceDocument) m_frame->loader()->replaceDocument(scriptResult); return true; }
void WebFrameLoaderClient::setTitle(const String& title, const KURL& url) { BOOL privateBrowsingEnabled = FALSE; COMPtr<IWebPreferences> preferences; if (SUCCEEDED(m_webFrame->webView()->preferences(&preferences))) preferences->privateBrowsingEnabled(&privateBrowsingEnabled); if (privateBrowsingEnabled) return; // update title in global history COMPtr<WebHistory> history = webHistory(); if (!history) return; COMPtr<IWebHistoryItem> item; if (FAILED(history->itemForURL(BString(url.string()), &item))) return; COMPtr<IWebHistoryItemPrivate> itemPrivate(Query, item); if (!itemPrivate) return; itemPrivate->setTitle(BString(title)); }
bool HTMLTrackElement::canLoadUrl(const KURL& url) { if (!RuntimeEnabledFeatures::webkitVideoTrackEnabled()) return false; HTMLMediaElement* parent = mediaElement(); if (!parent) return false; // 4.8.10.12.3 Sourcing out-of-band text tracks // 4. Download: If URL is not the empty string, perform a potentially CORS-enabled fetch of URL, with the // mode being the state of the media element's crossorigin content attribute, the origin being the // origin of the media element's Document, and the default origin behaviour set to fail. if (url.isEmpty()) return false; if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) { LOG(Media, "HTMLTrackElement::canLoadUrl(%s) -> rejected by Content Security Policy", urlForLoggingTrack(url).utf8().data()); return false; } return dispatchBeforeLoadEvent(url.string()); }
void MediaPlayerPrivate::load(const String& url) { String modifiedUrl(url); if (modifiedUrl.startsWith("local://")) { KURL kurl = KURL(KURL(), modifiedUrl); kurl.setProtocol("file"); String tempPath(BlackBerry::Platform::Client::get()->getApplicationLocalDirectory().c_str()); tempPath.append(kurl.path()); kurl.setPath(tempPath); modifiedUrl = kurl.string(); } if (modifiedUrl.startsWith("file://")) { // The QNX Multimedia Framework cannot handle filenames containing URL escape sequences. modifiedUrl = decodeURLEscapeSequences(modifiedUrl); } void* tabId = 0; if (frameView() && frameView()->hostWindow()) tabId = frameView()->hostWindow()->platformPageClient(); deleteGuardedObject(m_platformPlayer); #if USE(ACCELERATED_COMPOSITING) m_platformPlayer = PlatformPlayer::create(this, tabId, true, modifiedUrl.utf8().data()); #else m_platformPlayer = PlatformPlayer::create(this, tabId, false, modifiedUrl.utf8().data()); #endif String cookiePairs; if (!url.isEmpty()) cookiePairs = cookieManager().getCookie(KURL(ParsedURLString, url.utf8().data()), WithHttpOnlyCookies); if (!cookiePairs.isEmpty() && cookiePairs.utf8().data()) m_platformPlayer->load(modifiedUrl.utf8().data(), m_webCorePlayer->userAgent().utf8().data(), cookiePairs.utf8().data()); else m_platformPlayer->load(modifiedUrl.utf8().data(), m_webCorePlayer->userAgent().utf8().data(), 0); }
// http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing void PingLoader::sendLinkAuditPing(LocalFrame* frame, const KURL& pingURL, const KURL& destinationURL) { ResourceRequest request(pingURL); request.setHTTPMethod(HTTPNames::POST); request.setHTTPContentType("text/ping"); request.setHTTPBody(EncodedFormData::create("PING")); request.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); finishPingRequestInitialization(request, frame); RefPtr<SecurityOrigin> pingOrigin = SecurityOrigin::create(pingURL); // addAdditionalRequestHeaders() will have added a referrer for same origin requests, // but the spec omits the referrer. request.clearHTTPReferrer(); request.setHTTPHeaderField(HTTPNames::Ping_To, AtomicString(destinationURL.string())); // Ping-From follows the same rules as the default referrer beahavior for subresource requests. if (!SecurityPolicy::shouldHideReferrer(pingURL, frame->document()->url().string())) request.setHTTPHeaderField(HTTPNames::Ping_From, AtomicString(frame->document()->url().string())); FetchInitiatorInfo initiatorInfo; initiatorInfo.name = FetchInitiatorTypeNames::ping; PingLoader::start(frame, request, initiatorInfo); }
String CookieManager::getCookie(const KURL& url, HttpOnlyCookieFiltering filter) { bool isConnectionSecure = false; static String httpsPrefix("https:"); if (url.string().startsWith(httpsPrefix, false)) isConnectionSecure = true; // The max size is the number of cookie per host multiplied by the maximum length of a cookie. We add 1 for the final '\0'. static const size_t cookiesMaxLength = s_maxCookieLength * s_maxCookieCountPerHost + 1; Vector<UChar> cookiePairs; cookiePairs.reserveInitialCapacity(cookiesMaxLength); for (HashMap<String, CookieMap*>::iterator it = m_managerMap.begin(); it != m_managerMap.end(); ++it) { // Handle sub-domain by only looking at the end of the host. if (it->first.endsWith(url.host()) || (it->first.startsWith(".", false) && ("." + url.host()).endsWith(it->first, false))) { // Get CookieMap to check for expired cookies. Vector<ParsedCookie*> cookies = it->second->getCookies(); for (size_t i = 0; i < cookies.size(); ++i) { ParsedCookie* cookie = cookies[i]; // Get the cookies filtering out the secure cookies on an unsecure connection and HttpOnly cookies if requested. if (url.path().startsWith(cookie->path(), false) && (isConnectionSecure || !cookie->isSecure()) && (filter == WithHttpOnlyCookies || !cookie->isHttpOnly())) { String nameValuePair = cookie->toNameValuePair(); append(cookiePairs, nameValuePair); } } } } // Per construction of our cookies, we should not grow our vector. ASSERT(cookiePairs.capacity() == cookiesMaxLength); // Append the final '\0'. static const String nullTerminator("\0"); append(cookiePairs, nullTerminator); return String::adopt(cookiePairs); }
ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, FetchRequest& request) { ASSERT(request.options().synchronousPolicy == RequestAsynchronously || type == Resource::Raw); TRACE_EVENT0("blink", "ResourceFetcher::requestResource"); KURL url = request.resourceRequest().url(); WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource '%s', charset '%s', priority=%d, type=%s", url.elidedString().latin1().data(), request.charset().latin1().data(), request.priority(), ResourceTypeName(type)); // If only the fragment identifiers differ, it is the same resource. url = MemoryCache::removeFragmentIdentifierIfNeeded(url); if (!url.isValid()) return 0; if (!canRequest(type, url, request.options(), request.originRestriction())) return 0; if (LocalFrame* f = frame()) f->loaderClient()->dispatchWillRequestResource(&request); // See if we can use an existing resource from the cache. ResourcePtr<Resource> resource = memoryCache()->resourceForURL(url); const RevalidationPolicy policy = determineRevalidationPolicy(type, request, resource.get()); switch (policy) { case Reload: memoryCache()->remove(resource.get()); // Fall through case Load: resource = createResourceForLoading(type, request, request.charset()); break; case Revalidate: resource = createResourceForRevalidation(request, resource.get()); break; case Use: memoryCache()->updateForAccess(resource.get()); break; } if (!resource) return 0; if (!resource->hasClients()) m_deadStatsRecorder.update(policy); if (policy != Use) resource->setIdentifier(createUniqueIdentifier()); ResourceLoadPriority priority = loadPriority(type, request); if (priority != resource->resourceRequest().priority()) { resource->mutableResourceRequest().setPriority(priority); resource->didChangePriority(priority, 0); } if (resourceNeedsLoad(resource.get(), request, policy)) { if (!shouldLoadNewResource(type)) { if (memoryCache()->contains(resource.get())) memoryCache()->remove(resource.get()); return 0; } resource->load(this, request.options()); // For asynchronous loads that immediately fail, it's sufficient to return a // null Resource, as it indicates that something prevented the load from starting. // If there's a network error, that failure will happen asynchronously. However, if // a sync load receives a network error, it will have already happened by this point. // In that case, the requester should have access to the relevant ResourceError, so // we need to return a non-null Resource. if (resource->errorOccurred()) { if (memoryCache()->contains(resource.get())) memoryCache()->remove(resource.get()); return 0; } } requestLoadStarted(resource.get(), request, policy == Use ? ResourceLoadingFromCache : ResourceLoadingFromNetwork); ASSERT(resource->url() == url.string()); m_documentResources.set(resource->url(), resource); return resource; }
void HistoryItem::setURL(const KURL& url) { setURLString(url.string()); clearDocumentState(); }
bool ContentSecurityPolicy::checkSourceAndReportViolation(CSPDirective* directive, const KURL& url, const String& type) const { if (!directive || directive->allows(url)) return true; reportViolation(directive->text(), makeString("Refused to load ", type, " from '", url.string(), "' because of Content-Security-Policy.\n")); return false; }
void InspectorResourceAgent::didCreateWebSocket(unsigned long identifier, const KURL& requestURL) { m_frontend->didCreateWebSocket(identifier, requestURL.string()); }
static inline void addVisitedLink(Page* page, const KURL& url) { #if USE(PLATFORM_STRATEGIES) platformStrategies()->visitedLinkStrategy()->addVisitedLink(page, visitedLinkHash(url.string().characters(), url.string().length())); #else page->group().addVisitedLink(url); #endif }
bool CachedResourceLoader::canRequest(CachedResource::Type type, const KURL& url, bool forPreload) { if (!document()->securityOrigin()->canDisplay(url)) { if (!forPreload) FrameLoader::reportLocalLoadFailed(document()->frame(), url.string()); LOG(ResourceLoading, "CachedResourceLoader::requestResource URL was not allowed by SecurityOrigin::canDisplay"); return 0; } // Some types of resources can be loaded only from the same origin. Other // types of resources, like Images, Scripts, and CSS, can be loaded from // any URL. switch (type) { case CachedResource::ImageResource: case CachedResource::CSSStyleSheet: case CachedResource::Script: case CachedResource::FontResource: case CachedResource::RawResource: #if ENABLE(LINK_PREFETCH) case CachedResource::LinkPrefetch: case CachedResource::LinkPrerender: case CachedResource::LinkSubresource: #endif #if ENABLE(VIDEO_TRACK) case CachedResource::TextTrackResource: #endif #if ENABLE(CSS_SHADERS) case CachedResource::ShaderResource: #endif // These types of resources can be loaded from any origin. // FIXME: Are we sure about CachedResource::FontResource? break; #if ENABLE(XSLT) case CachedResource::XSLStyleSheet: if (!m_document->securityOrigin()->canRequest(url)) { printAccessDeniedMessage(url); return false; } break; #endif } switch (type) { #if ENABLE(XSLT) case CachedResource::XSLStyleSheet: #endif case CachedResource::Script: if (!m_document->contentSecurityPolicy()->allowScriptFromSource(url)) return false; if (frame()) { Settings* settings = frame()->settings(); if (!frame()->loader()->client()->allowScriptFromSource(!settings || settings->isScriptEnabled(), url)) { frame()->loader()->client()->didNotAllowScript(); return false; } } break; #if ENABLE(CSS_SHADERS) case CachedResource::ShaderResource: // Since shaders are referenced from CSS Styles use the same rules here. #endif case CachedResource::CSSStyleSheet: if (!m_document->contentSecurityPolicy()->allowStyleFromSource(url)) return false; break; case CachedResource::ImageResource: if (!m_document->contentSecurityPolicy()->allowImageFromSource(url)) return false; if (frame()) { Settings* settings = frame()->settings(); if (!frame()->loader()->client()->allowImage(!settings || settings->areImagesEnabled(), url)) return false; } break; case CachedResource::FontResource: { if (!m_document->contentSecurityPolicy()->allowFontFromSource(url)) return false; break; } case CachedResource::RawResource: #if ENABLE(LINK_PREFETCH) case CachedResource::LinkPrefetch: case CachedResource::LinkPrerender: case CachedResource::LinkSubresource: #endif break; #if ENABLE(VIDEO_TRACK) case CachedResource::TextTrackResource: // Cues aren't called out in the CPS spec yet, but they only work with a media element // so use the media policy. if (!m_document->contentSecurityPolicy()->allowMediaFromSource(url)) return false; break; #endif } // Last of all, check for insecure content. We do this last so that when // folks block insecure content with a CSP policy, they don't get a warning. // They'll still get a warning in the console about CSP blocking the load. // FIXME: Should we consider forPreload here? if (!checkInsecureContent(type, url)) return false; return true; }
void HTMLAnchorElement::setProtocol(const String& value) { KURL url = href(); url.setProtocol(value); setHref(url.string()); }
static bool logCanCacheFrameDecision(Frame* frame, int indentLevel) { // Only bother logging for frames that have actually loaded and have content. if (frame->loader()->creatingInitialEmptyDocument()) return false; KURL currentURL = frame->loader()->documentLoader() ? frame->loader()->documentLoader()->url() : KURL(); if (currentURL.isEmpty()) return false; PCLOG("+---"); KURL newURL = frame->loader()->provisionalDocumentLoader() ? frame->loader()->provisionalDocumentLoader()->url() : KURL(); if (!newURL.isEmpty()) PCLOG(" Determining if frame can be cached navigating from (%s) to (%s):", currentURL.string().utf8().data(), newURL.string().utf8().data()); else PCLOG(" Determining if subframe with URL (%s) can be cached:", currentURL.string().utf8().data()); bool cannotCache = false; do { if (!frame->loader()->documentLoader()) { PCLOG(" -There is no DocumentLoader object"); cannotCache = true; break; } if (!frame->loader()->documentLoader()->mainDocumentError().isNull()) { PCLOG(" -Main document has an error"); cannotCache = true; } if (frame->loader()->containsPlugins()) { PCLOG(" -Frame contains plugins"); cannotCache = true; } if (frame->loader()->url().protocolIs("https")) { PCLOG(" -Frame is HTTPS"); cannotCache = true; } if (frame->domWindow() && frame->domWindow()->hasEventListeners(eventNames().unloadEvent)) { PCLOG(" -Frame has an unload event listener"); cannotCache = true; } #if ENABLE(DATABASE) if (frame->document()->hasOpenDatabases()) { PCLOG(" -Frame has open database handles"); cannotCache = true; } #endif #if ENABLE(SHARED_WORKERS) if (SharedWorkerRepository::hasSharedWorkers(frame->document())) { PCLOG(" -Frame has associated SharedWorkers"); cannotCache = true; } #endif if (frame->document()->usingGeolocation()) { PCLOG(" -Frame uses Geolocation"); cannotCache = true; } if (!frame->loader()->history()->currentItem()) { PCLOG(" -No current history item"); cannotCache = true; } if (frame->loader()->quickRedirectComing()) { PCLOG(" -Quick redirect is coming"); cannotCache = true; } if (frame->loader()->documentLoader()->isLoadingInAPISense()) { PCLOG(" -DocumentLoader is still loading in API sense"); cannotCache = true; } if (frame->loader()->documentLoader()->isStopping()) { PCLOG(" -DocumentLoader is in the middle of stopping"); cannotCache = true; } if (!frame->document()->canSuspendActiveDOMObjects()) { PCLOG(" -The document cannot suspect its active DOM Objects"); cannotCache = true; } #if ENABLE(OFFLINE_WEB_APPLICATIONS) if (!frame->loader()->documentLoader()->applicationCacheHost()->canCacheInPageCache()) { PCLOG(" -The DocumentLoader uses an application cache"); cannotCache = true; } #endif if (!frame->loader()->client()->canCachePage()) { PCLOG(" -The client says this frame cannot be cached"); cannotCache = true; } } while (false); for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) if (!logCanCacheFrameDecision(child, indentLevel + 1)) cannotCache = true; PCLOG(cannotCache ? " Frame CANNOT be cached" : " Frame CAN be cached"); PCLOG("+---"); return !cannotCache; }