Truly independent web browser
/*
* Copyright (c) 2018-2025, Andreas Kling <[email protected]>
* Copyright (c) 2021, the SerenityOS developers.
* Copyright (c) 2021, Sam Atkins <[email protected]>
* Copyright (c) 2023, Srikavin Ramkumar <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/ByteBuffer.h>
#include <AK/Debug.h>
#include <AK/ScopeGuard.h>
#include <LibCore/ImmutableBytes.h>
#include <LibGC/Heap.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/DecodedImageFrame.h>
#include <LibHTTP/Header.h>
#include <LibHTTP/HeaderList.h>
#include <LibTextCodec/Decoder.h>
#include <LibURL/Origin.h>
#include <LibURL/URL.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/StyleScope.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/DOM/DOMTokenList.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/HTMLCollection.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/HTMLLinkElement.h>
#include <LibWeb/HTML/LocalTraversableNavigable.h>
#include <LibWeb/HTML/PotentialCORSRequest.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/Fetching.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/ImageCodecPlugin.h>
#include <LibWeb/ReferrerPolicy/AbstractOperations.h>
#include <LibWeb/SVG/SVGDecodedImageData.h>
#include <LibWebCommon/Infra/CharacterTypes.h>
namespace Web::HTML {
GC_DEFINE_ALLOCATOR(HTMLLinkElement);
static GC::Ref<DOM::Event> create_event_for_element(HTMLElement& element, Utf16FlyString const& event_name)
{
return DOM::Event::create(event_name, HighResolutionTime::current_high_resolution_time(relevant_global_object(element)));
}
HTMLLinkElement::HTMLLinkElement(DOM::Document& document, DOM::QualifiedName qualified_name)
: HTMLElement(document, move(qualified_name))
{
}
HTMLLinkElement::~HTMLLinkElement() = default;
// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#blocking-attribute
GC::Ref<DOM::DOMTokenList> HTMLLinkElement::blocking()
{
if (!m_blocking)
m_blocking = DOM::DOMTokenList::create(*this, AttributeNames::blocking);
return *m_blocking;
}
void HTMLLinkElement::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_blocking);
visitor.visit(m_fetch_controller);
visitor.visit(m_loaded_style_sheet);
visitor.visit(m_style_sheet_kept_while_disabled);
visitor.visit(m_rel_list);
visitor.visit(m_sizes);
}
void HTMLLinkElement::adopted_from(DOM::Document& old_document)
{
Base::adopted_from(old_document);
if (m_document_load_event_delayer.has_value())
m_document_load_event_delayer.emplace(document(), DOM::DocumentLoadEventDelayerReason::StyleSheetRequest);
}
void HTMLLinkElement::inserted()
{
HTMLElement::inserted();
if (!document().browsing_context())
return;
if (should_fetch_and_process_resource_type() && is_browsing_context_connected()) {
// The appropriate times to fetch and process this type of link are:
// - When the external resource link is created on a link element that is already browsing-context connected.
// - When the external resource link's link element becomes browsing-context connected.
fetch_and_process_linked_resource();
}
}
void HTMLLinkElement::removed_from(IsSubtreeRoot is_subtree_root, Node* old_ancestor, Node& old_root)
{
Base::removed_from(is_subtree_root, old_ancestor, old_root);
cancel_pending_stylesheet_processing();
m_style_sheet_kept_while_disabled = nullptr;
if (m_loaded_style_sheet) {
// NB: We can't use `old_root` here. When this link element is nested
// inside a shadow tree within a larger removed subtree, `old_root`
// is the outer subtree's root, not the shadow root that actually
// contains our stylesheet. Use the sheet's own tracked owning
// root, which is the one whose style scope owns it.
auto const& owning_roots = m_loaded_style_sheet->owning_documents_or_shadow_roots();
VERIFY(owning_roots.size() == 1);
auto& owning_root = **owning_roots.begin();
auto& style_scope = [&owning_root] -> CSS::StyleScope& {
if (auto* shadow_root = as_if<DOM::ShadowRoot>(owning_root))
return shadow_root->style_scope();
return as<DOM::Document>(owning_root).style_scope();
}();
style_scope.remove_a_css_style_sheet(*m_loaded_style_sheet);
m_loaded_style_sheet = nullptr;
}
}
void HTMLLinkElement::moved_from(IsSubtreeRoot is_subtree_root, GC::Ptr<Node> old_ancestor)
{
Base::moved_from(is_subtree_root, old_ancestor);
if (!m_loaded_style_sheet)
return;
auto const& owning_roots = m_loaded_style_sheet->owning_documents_or_shadow_roots();
VERIFY(owning_roots.size() == 1);
auto& owning_root = **owning_roots.begin();
auto& source = [&owning_root] -> CSS::StyleScope& {
if (auto* shadow_root = as_if<DOM::ShadowRoot>(owning_root))
return shadow_root->style_scope();
return as<DOM::Document>(owning_root).style_scope();
}();
source.move_sheet(*m_loaded_style_sheet, document_or_shadow_root_style_scope());
}
// https://html.spec.whatwg.org/multipage/semantics.html#dom-link-rellist
GC::Ref<DOM::DOMTokenList> HTMLLinkElement::rel_list()
{
// The relList IDL attribute must reflect the rel content attribute.
if (!m_rel_list)
m_rel_list = DOM::DOMTokenList::create(*this, HTML::AttributeNames::rel);
return *m_rel_list;
}
// https://html.spec.whatwg.org/multipage/semantics.html#dom-link-sizes
GC::Ref<DOM::DOMTokenList> HTMLLinkElement::sizes()
{
// The size IDL attribute must reflect the size content attribute.
if (!m_sizes)
m_sizes = DOM::DOMTokenList::create(*this, HTML::AttributeNames::sizes);
return *m_sizes;
}
void HTMLLinkElement::set_media(Utf16View media)
{
set_attribute_value(HTML::AttributeNames::media, media);
if (auto sheet = m_loaded_style_sheet)
sheet->set_media(media);
}
Utf16String HTMLLinkElement::media() const
{
return get_attribute_value(HTML::AttributeNames::media);
}
// https://drafts.csswg.org/cssom/#dom-linkstyle-sheet
CSS::CSSStyleSheet* HTMLLinkElement::cssom_sheet() const
{
return m_loaded_style_sheet ? &m_loaded_style_sheet->cssom_sheet() : nullptr;
}
RefPtr<CSS::StyleSheetState> HTMLLinkElement::sheet() const
{
return m_loaded_style_sheet;
}
void HTMLLinkElement::finished_loading_critical_style_subresources(AnyFailed any_failed)
{
// NB: The style sheet of an older fetch stays associated until a newer fetch's response is processed. That newer
// fetch owns the document load event delayer, so the old sheet's imports must not release it.
if (m_loaded_style_sheet_fetch_generation != m_current_fetch_generation)
return;
m_document_load_event_delayer.clear();
auto fetch_generation = exchange(m_fetch_generation_waiting_for_critical_subresources, {});
if (!fetch_generation.has_value())
return;
queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }, *fetch_generation, any_failed), [](auto& link, auto& fetch_generation, auto& any_failed) {
if (fetch_generation != link->m_current_fetch_generation || !link->m_stylesheet_processing_pending)
return;
// 2. Fire an event named load at el.
// INTEROP: Other browsers fire error instead when an import failed.
auto event_name = any_failed == AnyFailed::Yes ? HTML::EventNames::error : HTML::EventNames::load;
link->dispatch_event(create_event_for_element(*link, event_name));
link->finish_processing_stylesheet_resource(fetch_generation);
}));
}
bool HTMLLinkElement::has_loaded_icon() const
{
return m_relationship & Relationship::Icon && m_loaded_icon;
}
bool HTMLLinkElement::has_icon_keyword() const
{
return m_relationship & Relationship::Icon;
}
static bool is_supported_style_sheet_type_attribute(Optional<Utf16String> const& type)
{
// The default type for resources given by the stylesheet keyword is text/css.
if (!type.has_value())
return true;
auto mime_type = MimeSniff::MimeType::parse(type->utf16_view());
return mime_type.has_value() && mime_type->essence() == "text/css"sv;
}
void HTMLLinkElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_)
{
Base::attribute_changed(name, old_value, value, namespace_);
if (!namespace_.has_value() && name == AttributeNames::blocking && m_blocking)
m_blocking->associated_attribute_changed(value);
if (!namespace_.has_value() && name == AttributeNames::sizes && m_sizes)
m_sizes->associated_attribute_changed(value);
// 4.6.7 Link types - https://html.spec.whatwg.org/multipage/links.html#linkTypes
auto old_relationship = m_relationship;
if (name == HTML::AttributeNames::rel) {
// To determine which link types apply to a link, a, area, or form element,
// the element's rel attribute must be split on ASCII whitespace.
// The resulting tokens are the keywords for the link types that apply to that element.
m_relationship = 0;
auto link_types = value.has_value() ? value->utf16_view() : u""sv;
size_t start = 0;
for (size_t i = 0; i <= link_types.length_in_code_units(); ++i) {
if (i != link_types.length_in_code_units() && !Infra::is_ascii_whitespace(link_types.code_unit_at(i)))
continue;
if (i > start) {
auto token = link_types.substring_view(start, i - start);
if (token.equals_ignoring_ascii_case(u"stylesheet"sv))
m_relationship |= Relationship::Stylesheet;
else if (token.equals_ignoring_ascii_case(u"alternate"sv))
m_relationship |= Relationship::Alternate;
else if (token.equals_ignoring_ascii_case(u"preload"sv))
m_relationship |= Relationship::Preload;
else if (token.equals_ignoring_ascii_case(u"modulepreload"sv))
m_relationship |= Relationship::ModulePreload;
else if (token.equals_ignoring_ascii_case(u"dns-prefetch"sv))
m_relationship |= Relationship::DNSPrefetch;
else if (token.equals_ignoring_ascii_case(u"preconnect"sv))
m_relationship |= Relationship::Preconnect;
else if (token.equals_ignoring_ascii_case(u"icon"sv))
m_relationship |= Relationship::Icon;
else if (token.equals_ignoring_ascii_case(u"prefetch"sv))
m_relationship |= Relationship::Prefetch;
}
start = i + 1;
}
if (!namespace_.has_value() && m_rel_list)
m_rel_list->associated_attribute_changed(value);
// NB: A link that no longer represents a stylesheet will not run stylesheet completion steps.
if ((old_relationship & Relationship::Stylesheet) && !(m_relationship & Relationship::Stylesheet))
cancel_pending_stylesheet_processing();
}
// https://html.spec.whatwg.org/multipage/semantics.html#the-link-element:explicitly-enabled
// Whenever the disabled attribute is removed, set the link element's explicitly enabled attribute to true.
if (!value.has_value() && name == HTML::AttributeNames::disabled)
m_explicitly_enabled = true;
if ((m_relationship & Relationship::Stylesheet) && m_loaded_style_sheet) {
if (name == HTML::AttributeNames::disabled) {
document_or_shadow_root_style_scope().remove_a_css_style_sheet(*m_loaded_style_sheet);
// AD-HOC: The link keeps the sheet aside while it's disabled, so that enabling it again before anything
// else about it changes puts the sheet back at once, rather than leaving the link without a sheet
// until a new fetch completes. Only a sheet from the link's latest fetch is kept.
if (m_loaded_style_sheet_fetch_generation == m_current_fetch_generation)
m_style_sheet_kept_while_disabled = m_loaded_style_sheet;
m_loaded_style_sheet = nullptr;
} else if (name == HTML::AttributeNames::media) {
m_loaded_style_sheet->set_media(value.has_value() ? value->utf16_view() : u""sv);
}
}
if (name == HTML::AttributeNames::disabled && !value.has_value() && m_style_sheet_kept_while_disabled) {
auto sheet = m_style_sheet_kept_while_disabled.release_nonnull();
if ((m_relationship & Relationship::Stylesheet) && is_browsing_context_connected()
&& m_style_sheet_kept_while_disabled_fetch_generation == m_current_fetch_generation) {
associate_style_sheet(sheet, sheet->is_origin_clean() ? CSS::StyleScope::OriginClean::Yes : CSS::StyleScope::OriginClean::No);
return;
}
}
if (should_fetch_and_process_resource_type() && is_browsing_context_connected()) {
// The appropriate times to fetch and process this type of link are:
// - When the href attribute of the link element of an external resource link that is already browsing-context connected is changed.
auto fetch = name == AttributeNames::href;
if (!fetch && (m_relationship & (Relationship::Preconnect | Relationship::Prefetch | Relationship::Stylesheet))) {
// - When the crossorigin attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
fetch = name == AttributeNames::crossorigin;
}
if (!fetch && (m_relationship & Relationship::Preload)) {
fetch =
// - When the as attribute of the link element of an external resource link that is already browsing-context connected is changed.
name == AttributeNames::as
// FIXME: - When the type attribute of the link element of an external resource link that is already browsing-context connected, but was previously not obtained due to the type attribute specifying an unsupported type for the request destination, is set, removed, or changed.
// FIXME: - When the media attribute of the link element of an external resource link that is already browsing-context connected, but was previously not obtained due to the media attribute not matching the environment, is changed or removed.
;
}
if (!fetch && (m_relationship & Relationship::ModulePreload)) {
// - When the external resource link is created on a link element that is already browsing-context connected.
fetch = name == AttributeNames::rel && !(old_relationship & Relationship::ModulePreload);
}
if (!fetch && (m_relationship & Relationship::Prefetch)) {
// - When the external resource link is created on a link element that is already browsing-context connected.
fetch = name == AttributeNames::rel && !(old_relationship & Relationship::Prefetch);
}
if (!fetch && (m_relationship & Relationship::Stylesheet)) {
fetch =
// - When the disabled attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
name == AttributeNames::disabled
// - When the type attribute of the link element of an external resource link that is already browsing-context connected is set or changed to a value that does not or no longer matches the Content-Type metadata of the previous obtained external resource, if any.
// - When the type attribute of the link element of an external resource link that is already browsing-context connected, but was previously not obtained due to the type attribute specifying an unsupported type, is removed or changed.
// NB: Only the Content-Type metadata decides whether the resource applies, so a change between two
// supported types needs no new fetch.
|| (!namespace_.has_value() && name == AttributeNames::type && old_value != value
&& !(is_supported_style_sheet_type_attribute(old_value) && is_supported_style_sheet_type_attribute(value)))
// AD-HOC: When the link element's type becomes a stylesheet
|| !(old_relationship & Relationship::Stylesheet);
}
if (fetch)
fetch_and_process_linked_resource();
}
// NB: Disabling the link starts a fetch, which its setup steps end right away, so the kept sheet belongs with the
// generation that leaves.
if (name == HTML::AttributeNames::disabled && value.has_value() && m_style_sheet_kept_while_disabled)
m_style_sheet_kept_while_disabled_fetch_generation = m_current_fetch_generation;
}
// https://html.spec.whatwg.org/multipage/semantics.html#contributes-a-script-blocking-style-sheet
bool HTMLLinkElement::contributes_a_script_blocking_style_sheet() const
{
// An element el in the context of a Document of an HTML parser or XML parser
// contributes a script-blocking style sheet if all of the following are true:
// el was created by that Document's parser.
if (m_parser_document != &document())
return false;
// FIXME: el is either a style element or a link element that was an external resource link that contributes to the styling processing model when the el was created by the parser.
// el's media attribute's value matches the environment.
if (!CSS::RustMediaList::parse(attribute(AttributeNames::media).value_or({})).evaluate(document()))
return false;
// el's style sheet was enabled when the element was created by the parser.
if (!m_was_enabled_when_created_by_parser)
return false;
// FIXME: The last time the event loop reached step 1, el's root was that Document.
// The user agent hasn't given up on loading that particular style sheet yet.
// A user agent may give up on loading a style sheet at any time.
if (m_fetch_controller && m_fetch_controller->state() == Fetch::Infrastructure::FetchController::State::Terminated)
return false;
if (m_fetch_controller && m_fetch_controller->state() == Fetch::Infrastructure::FetchController::State::Aborted)
return false;
return true;
}
bool HTMLLinkElement::is_implicitly_potentially_render_blocking() const
{
// A link element of this type is implicitly potentially render-blocking if the element was created by its node document's parser.
return &document() == m_parser_document;
}
// https://html.spec.whatwg.org/multipage/semantics.html#create-link-options-from-element
GC::Ref<HTMLLinkElement::LinkProcessingOptions> HTMLLinkElement::create_link_options()
{
// 1. Let document be el's node document.
auto& document = this->document();
auto referrerpolicy = get_attribute(AttributeNames::referrerpolicy);
auto referrerpolicy_value = referrerpolicy.has_value() ? referrerpolicy->utf16_view() : u""sv;
// 2. Let options be a new link processing options with
auto options = GC::Heap::the().allocate<LinkProcessingOptions>(
// crossorigin
// the state of el's crossorigin content attribute
cors_setting_attribute_from_keyword(get_attribute(AttributeNames::crossorigin).map([](auto const& value) { return value.utf16_view(); })),
// referrer policy
// the state of el's referrerpolicy content attribute
ReferrerPolicy::from_string(referrerpolicy_value).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString),
// source set
// el's source set
m_source_set,
// base URL
// document's document base URL
document.base_url(),
// origin
// document's origin
document.origin(),
// environment
// document's relevant settings object
document.relevant_settings_object(),
// policy container
// document's policy container
document.policy_container(),
// document
// document
document,
// cryptographic nonce metadata
// the current value of el's [[CryptographicNonce]] internal slot
nonce(),
// fetch priority
// the state of el's fetchpriority content attribute
Fetch::Infrastructure::request_priority_from_string(attribute(HTML::AttributeNames::fetchpriority).value_or({})).value_or(Fetch::Infrastructure::Request::Priority::Auto));
// 3. If el has an href attribute, then set options's href to the value of el's href attribute.
if (auto maybe_href = get_attribute(AttributeNames::href); maybe_href.has_value())
options->href = maybe_href.release_value();
// 4. If el has an integrity attribute, then set options's integrity to the value of el's integrity content attribute.
if (auto maybe_integrity = get_attribute_ns({}, AttributeNames::integrity); maybe_integrity.has_value())
options->integrity = maybe_integrity.release_value();
// 5. If el has a type attribute, then set options's type to the value of el's type attribute.
if (auto maybe_type = get_attribute(AttributeNames::type); maybe_type.has_value())
options->type = maybe_type.release_value();
// FIXME: 6. Assert: options's href is not the empty string, or options's source set is not null.
// A link element with neither an href or an imagesrcset does not represent a link.
// 7. Return options.
return options;
}
// https://html.spec.whatwg.org/multipage/semantics.html#create-a-link-request
RefPtr<Fetch::Infrastructure::Request> HTMLLinkElement::create_link_request(HTMLLinkElement::LinkProcessingOptions const& options)
{
// 1. Assert: options's href is not the empty string.
VERIFY(!options.href.is_empty());
// FIXME: 2. If options's destination is null, then return null.
// 3. Let url be the result of encoding-parsing a URL given options's href, relative to options's base URL.
// FIXME: Spec issue: We should be parsing this URL relative to a document or environment settings object.
// https://github.com/whatwg/html/issues/9715
auto url = DOMURL::parse(options.href.utf16_view(), options.base_url);
// 4. If url is failure, then return null.
if (!url.has_value())
return nullptr;
// 5. Let request be the result of creating a potential-CORS request given url, options's destination, and options's crossorigin.
auto request = create_potential_CORS_request(*url, options.destination, options.crossorigin);
// 6. Set request's policy container to options's policy container.
// AD-HOC: A clone of it, so that the request and its redirects keep the policies its document had when the request
// was created, its CSP list included, as a request whose policy container is "client" keeps its client's.
request->set_policy_container(options.policy_container->clone());
// 7. Set request's integrity metadata to options's integrity.
request->set_integrity_metadata(options.integrity);
// 8. Set request's cryptographic nonce metadata to options's cryptographic nonce metadata.
request->set_cryptographic_nonce_metadata(options.cryptographic_nonce_metadata);
// 9. Set request's referrer policy to options's referrer policy.
request->set_referrer_policy(options.referrer_policy);
// 10. Set request's client to options's environment.
request->set_client(options.environment->address());
// 11. Set request's priority to options's fetch priority.
request->set_priority(options.fetch_priority);
// 12. Return request.
return request;
}
// https://html.spec.whatwg.org/multipage/semantics.html#fetch-and-process-the-linked-resource
void HTMLLinkElement::fetch_and_process_linked_resource()
{
auto fetch_generation = ++m_current_fetch_generation;
// NB: Replacing a pending stylesheet must preserve its render-blocking entry even after the body was inserted.
cancel_pending_stylesheet_processing(UnblockRendering::No);
ScopeGuard unblock_if_no_blocking_stylesheet = [this] {
if (document().is_render_blocking_element(*this)
&& ((m_relationship & Relationship::Icon) || !(m_relationship & Relationship::Stylesheet) || !m_fetch_controller || !is_potentially_render_blocking()
|| !CSS::RustMediaList::parse(media()).evaluate(document())))
unblock_rendering();
};
if (m_fetch_controller) {
m_fetch_controller->stop_fetch();
m_fetch_controller = nullptr;
document().remove_from_script_blocking_style_sheet_set(*this);
}
if (m_relationship & ~(Relationship::DNSPrefetch | Relationship::Preconnect | Relationship::Preload | Relationship::ModulePreload | Relationship::Prefetch))
default_fetch_and_process_linked_resource(fetch_generation);
else if (m_relationship & Relationship::ModulePreload)
fetch_and_process_linked_modulepreload_resource();
else if (m_relationship & Relationship::Preload)
fetch_and_process_linked_preload_resource();
else if (m_relationship & Relationship::Prefetch)
fetch_and_process_linked_prefetch_resource();
else if (m_relationship & Relationship::Preconnect)
fetch_and_process_linked_preconnect_resource();
else if (m_relationship & Relationship::DNSPrefetch)
fetch_and_process_linked_dns_prefetch_resource();
}
// https://html.spec.whatwg.org/multipage/semantics.html#default-fetch-and-process-the-linked-resource
void HTMLLinkElement::default_fetch_and_process_linked_resource(u64 fetch_generation)
{
// https://html.spec.whatwg.org/multipage/semantics.html#the-link-element:attr-link-href-4
// If both the href and imagesrcset attributes are absent, then the element does not define a link.
// FIXME: Support imagesrcset attribute
if (!has_attribute(AttributeNames::href) || href().is_empty())
return;
// 1. Let options be the result of creating link options from el.
auto options = create_link_options();
// 2. Let request be the result of creating a link request given options.
auto request = create_link_request(options);
// 3. If request is null, then return.
if (request == nullptr) {
return;
}
// FIXME: 4. Set request's synchronous flag.
// 5. Run the linked resource fetch setup steps, given el and request. If the result is false, then return.
if (!linked_resource_fetch_setup_steps(*request))
return;
// 6. Set request's initiator type to "css" if el's rel attribute contains the keyword stylesheet; "link" otherwise.
if (m_relationship & Relationship::Stylesheet) {
request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::CSS);
} else {
request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Link);
}
// 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null, failure, or a byte sequence bodyBytes:
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };
fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, fetch_generation), [](auto& self, auto& fetch_generation, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
// "if, since the resource in question was fetched, it has become appropriate to fetch it again"
if (fetch_generation != self.m_current_fetch_generation)
return;
self.m_fetch_controller = nullptr;
// NB: The unsafe response below is always CORS-same-origin, so determine the origin-clean flag beforehand.
auto origin_clean = response->is_cors_same_origin() ? CSS::StyleScope::OriginClean::Yes : CSS::StyleScope::OriginClean::No;
// FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
// https://github.com/whatwg/html/issues/9355
response = response->unsafe_response();
// 1. Let success be true.
bool success = true;
Core::ImmutableBytes const* successful_body_bytes = nullptr;
// 2. If either of the following conditions are met:
// - bodyBytes is null or failure; or
// - response's status is not an ok status,
// then set success to false.
body_bytes.visit(
[&](Core::ImmutableBytes& body_bytes) {
if (Fetch::Infrastructure::is_ok_status(response->status()))
successful_body_bytes = &body_bytes;
else
success = false;
},
[&](auto) { success = false; });
// FIXME: 3. Otherwise, wait for the link resource's critical subresources to finish loading.
// 4. Process the linked resource given el, success, response, and bodyBytes.
self.process_linked_resource(success, response, origin_clean, successful_body_bytes);
});
m_fetch_controller = Fetch::Fetching::fetch(HTML::relevant_realm(*this), *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
// AD-HOC: A stopped fetch, such as one of a document that was stopped, never processes its response. Stop blocking
// scripts, rendering and the load event on it then, as if the user agent had given up on loading it.
m_fetch_controller->set_stop_steps(GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { *this }, fetch_generation), [](auto& weak_this, auto& fetch_generation) {
auto link_element = weak_this.ptr();
if (!link_element || fetch_generation != link_element->m_current_fetch_generation)
return;
link_element->m_fetch_controller = nullptr;
link_element->stop_blocking_on_style_sheet();
}));
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-dns-prefetch:fetch-and-process-the-linked-resource-2
void HTMLLinkElement::fetch_and_process_linked_dns_prefetch_resource()
{
auto href = get_attribute(AttributeNames::href);
if (!href.has_value())
return;
// 1. Let url be the result of encoding-parsing a URL given el's href attribute's value, relative to el's node document.
auto url = document().encoding_parse_url(*href);
// 2. If url is failure, then return.
if (!url.has_value())
return;
// FIXME: 3. Let partitionKey be the result of determining the network partition key given el's node document's relevant
// settings object.
// 4. The user agent should resolve an origin given partitionKey and url's origin.
// FIXME: This should go through Fetch: https://fetch.spec.whatwg.org/#resolve-an-origin
if (!ResourceLoader::is_initialized())
return;
// AD-HOC: Until then, keep an SVG image off the network as Fetch would.
if (document().is_decoded_svg())
return;
ResourceLoader::the().prefetch_dns(document(), url.value(), document().fallback_base_url());
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-preconnect:fetch-and-process-the-linked-resource-2
void HTMLLinkElement::fetch_and_process_linked_preconnect_resource()
{
// The fetch and process the linked resource steps for this type of linked resource, given a link element el, are to
// create link options from el and to preconnect given the result.
preconnect(create_link_options());
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-preload:fetch-and-process-the-linked-resource-2
void HTMLLinkElement::fetch_and_process_linked_preload_resource()
{
// 1. Update the source set for el.
update_the_source_set(*this);
// 2. Let options be the result of creating link options from el.
auto options = create_link_options();
// 3. Let destination be the result of translating the keyword representing the state of el's as attribute.
auto destination = translate_a_preload_destination(attribute(HTML::AttributeNames::as).value_or({}));
// 4. If destination is null, then return.
if (destination.has<Empty>())
return;
// 5. Set options's destination to destination.
options->destination = destination.get<Optional<Fetch::Infrastructure::Request::Destination>>();
// 6. Preload options, with the following steps given a response response:
// NB: The preload's fetch is not stopped when el is fetched again, since other fetches may be waiting on it as a
// consumer of the preloaded resource.
GC::Weak weak_this { *this };
auto fetch_generation = m_current_fetch_generation;
preload(options, GC::create_function(GC::Heap::the(), GC::captures(weak_this, fetch_generation), [](auto& weak_this, auto& fetch_generation, Fetch::Infrastructure::Response& response) {
// 1. If response is a network error, fire an event named error at el. Otherwise, fire an event named load at el.
if (auto link_element = weak_this.ptr()) {
if (fetch_generation != link_element->m_current_fetch_generation)
return;
if (response.is_network_error())
link_element->dispatch_event(create_event_for_element(*link_element, HTML::EventNames::error));
else
link_element->dispatch_event(create_event_for_element(*link_element, HTML::EventNames::load));
}
}));
}
static bool media_attribute_matches_environment(DOM::Document const& document, Utf16View media)
{
return CSS::RustMediaList::parse(media).evaluate(document);
}
static Optional<Fetch::Infrastructure::Request::Destination> module_preload_destination_from_as_attribute(Utf16View as_attribute)
{
using Destination = Fetch::Infrastructure::Request::Destination;
// A module preload destination is "json", "style", "text", or a script-like destination.
if (as_attribute.equals_ignoring_ascii_case(u"audioworklet"sv))
return Destination::AudioWorklet;
if (as_attribute.equals_ignoring_ascii_case(u"paintworklet"sv))
return Destination::PaintWorklet;
if (as_attribute.equals_ignoring_ascii_case(u"script"sv))
return Destination::Script;
if (as_attribute.equals_ignoring_ascii_case(u"serviceworker"sv))
return Destination::ServiceWorker;
if (as_attribute.equals_ignoring_ascii_case(u"sharedworker"sv))
return Destination::SharedWorker;
if (as_attribute.equals_ignoring_ascii_case(u"worker"sv))
return Destination::Worker;
if (as_attribute.equals_ignoring_ascii_case(u"style"sv))
return Destination::Style;
if (as_attribute.equals_ignoring_ascii_case(u"json"sv))
return Destination::JSON;
if (as_attribute.equals_ignoring_ascii_case(u"text"sv))
return Destination::Text;
// NB: The as attribute is enumerated. Invalid and missing values are in no state, so step 2 uses "script".
if (as_attribute.is_empty()
|| !as_attribute.is_one_of_ignoring_ascii_case(
u"audio"sv, u"document"sv, u"embed"sv, u"fetch"sv, u"font"sv, u"frame"sv,
u"iframe"sv, u"image"sv, u"manifest"sv, u"object"sv, u"report"sv,
u"track"sv, u"video"sv, u"webidentity"sv, u"xslt"sv))
return Destination::Script;
return {};
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload:fetch-and-process-the-linked-resource
void HTMLLinkElement::fetch_and_process_linked_modulepreload_resource()
{
// However, if the link is an external resource link, then the media attribute is prescriptive. The user agent must
// apply the external resource when the media attribute's value matches the environment and the other relevant
// conditions apply, and must not apply it otherwise.
if (!media_attribute_matches_environment(document(), attribute(AttributeNames::media).value_or({})))
return;
// 1. If el's href attribute's value is the empty string, then return.
auto href = attribute(AttributeNames::href).value_or({});
if (href.is_empty())
return;
// 2. Let destination be the current state of el's as attribute, or "script" if it is in no state.
auto destination = module_preload_destination_from_as_attribute(attribute(AttributeNames::as).value_or({}));
// 3. If destination is not a module preload destination, then queue an element task on the networking task source
// given el to fire an event named error at el, and return.
if (!destination.has_value()) {
queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(*this, m_current_fetch_generation), [](auto& self, auto& fetch_generation) {
// NB: The fetch can be superseded before this task runs.
if (fetch_generation != self.m_current_fetch_generation)
return;
self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));
}));
return;
}
// 4. Let url be the result of encoding-parsing a URL given el's href attribute's value, relative to el's node document.
auto url = document().encoding_parse_url(href);
// 5. If url is failure, then return.
if (!url.has_value())
return;
// 6. Let settings object be el's node document's relevant settings object.
auto& settings_object = document().relevant_settings_object();
// 7. Let credentials mode be the CORS settings attribute credentials mode for el's crossorigin attribute.
auto credentials_mode = cors_settings_attribute_credentials_mode(cors_setting_attribute_from_keyword(attribute(AttributeNames::crossorigin).map([](auto const& value) { return value.utf16_view(); })));
// 8. Let cryptographic nonce be el.[[CryptographicNonce]].
auto cryptographic_nonce = nonce();
// 9. Let integrity metadata be the value of el's integrity attribute, if it is specified, or the empty string otherwise.
auto integrity_metadata = attribute(AttributeNames::integrity).value_or({});
// 10. If el does not have an integrity attribute, then set integrity metadata to the result of resolving a module
// integrity metadata with url and settings object.
if (!has_attribute(AttributeNames::integrity))
integrity_metadata = resolve_a_module_integrity_metadata(*url, settings_object);
// 11. Let referrer policy be the current state of el's referrerpolicy attribute.
auto referrer_policy = ReferrerPolicy::from_string(attribute(AttributeNames::referrerpolicy).value_or({})).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);
// 12. Let fetch priority be the current state of el's fetchpriority attribute.
auto fetch_priority = Fetch::Infrastructure::request_priority_from_string(attribute(AttributeNames::fetchpriority).value_or({})).value_or(Fetch::Infrastructure::Request::Priority::Auto);
// 13. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce, integrity metadata is
// integrity metadata, parser metadata is "not-parser-inserted", credentials mode is credentials mode, referrer
// policy is referrer policy, and fetch priority is fetch priority.
ScriptFetchOptions options {
.cryptographic_nonce = move(cryptographic_nonce),
.integrity_metadata = move(integrity_metadata),
.parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
.credentials_mode = credentials_mode,
.referrer_policy = referrer_policy,
.fetch_priority = fetch_priority,
};
// 14. Fetch a modulepreload module script graph given url, destination, settings object, and options.
GC::Weak weak_this { *this };
auto fetch_generation = m_current_fetch_generation;
auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(weak_this, fetch_generation), [](auto& weak_this, auto& fetch_generation, GC::Ptr<Script> result) {
auto link_element = weak_this.ptr();
if (!link_element || fetch_generation != link_element->m_current_fetch_generation)
return;
// 1. If result is null, then fire an event named error at el, and return.
if (!result) {
link_element->dispatch_event(create_event_for_element(*link_element, HTML::EventNames::error));
return;
}
// 2. Fire an event named load at el.
link_element->dispatch_event(create_event_for_element(*link_element, HTML::EventNames::load));
});
fetch_modulepreload_module_script_graph(relevant_realm(*this), *url, *destination, settings_object, options, on_complete);
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-prefetch:fetch-and-process-the-linked-resource-2
void HTMLLinkElement::fetch_and_process_linked_prefetch_resource()
{
// 1. If el's href attribute's value is the empty string, then return.
if (attribute(AttributeNames::href).value_or({}).is_empty())
return;
// 2. Let options be the result of creating link options from el.
auto options = create_link_options();
// 3. Let request be the result of creating a link request given options.
auto request = create_link_request(options);
// 4. If request is null, then return.
if (!request)
return;
// 5. Set request's initiator to "prefetch".
request->set_initiator(Fetch::Infrastructure::Request::Initiator::Prefetch);
// 6. Let processPrefetchResponse be the following steps given a response response and null, failure, or a byte
// sequence bytesOrNull:
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };
fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, m_current_fetch_generation), [](auto& self, auto& fetch_generation, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes) {
if (fetch_generation != self.m_current_fetch_generation)
return;
self.m_fetch_controller = nullptr;
// 1. If response is a network error, fire an event named error at el.
if (response->is_network_error()) {
self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));
}
// 2. Otherwise, fire an event named load at el.
else {
self.dispatch_event(create_event_for_element(self, HTML::EventNames::load));
}
});
// 7. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse. User
// agents may delay the fetching of request to prioritize other requests that are necessary for the current
// document.
m_fetch_controller = Fetch::Fetching::fetch(HTML::relevant_realm(*this), *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
}
// https://html.spec.whatwg.org/multipage/semantics.html#linked-resource-fetch-setup-steps
bool HTMLLinkElement::linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request& request)
{
if (m_relationship & Relationship::Icon)
return icon_linked_resource_fetch_setup_steps(request);
if (m_relationship & Relationship::Stylesheet)
return stylesheet_linked_resource_fetch_setup_steps(request);
return true;
}
// https://html.spec.whatwg.org/multipage/links.html#rel-icon:linked-resource-fetch-setup-steps
bool HTMLLinkElement::icon_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request& request)
{
// 1. Set request's destination to "image".
request.set_destination(Fetch::Infrastructure::Request::Destination::Image);
// 2. Return true.
return true;
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:linked-resource-fetch-setup-steps
bool HTMLLinkElement::stylesheet_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request& request)
{
// https://html.spec.whatwg.org/multipage/semantics.html#processing-the-type-attribute
// If the type attribute is present, then the user agent must assume that the resource is of the given type (even
// if that is not a valid MIME type string, e.g. the empty string). [...] If the UA does not support the given MIME
// type for the given link relationship, then the UA should not fetch and process the linked resource
if (!is_supported_style_sheet_type_attribute(get_attribute_ns({}, AttributeNames::type))) {
// AD-HOC: The style sheet of an earlier fetch no longer applies.
if (m_loaded_style_sheet) {
document_or_shadow_root_style_scope().remove_a_css_style_sheet(*m_loaded_style_sheet);
m_loaded_style_sheet = nullptr;
}
return false;
}
// 1. If el's disabled attribute is set, then return false.
if (has_attribute(AttributeNames::disabled))
return false;
// 2. If el contributes a script-blocking style sheet, append el to its node document's script-blocking style sheet set.
if (contributes_a_script_blocking_style_sheet())
document().script_blocking_style_sheet_set().set(*this);
// 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
if (is_potentially_render_blocking() && CSS::RustMediaList::parse(media()).evaluate(document()))
block_rendering();
m_document_load_event_delayer.emplace(document(), DOM::DocumentLoadEventDelayerReason::StyleSheetRequest);
// 4. If el is currently render-blocking, then set request's render-blocking to true.
if (document().is_render_blocking_element(*this))
request.set_render_blocking(true);
// FIXME: We currently don't set the destination for stylesheets, so we do it here.
// File a spec issue that the destination for stylesheets is not actually set if the `as` attribute is missing.
request.set_destination(Fetch::Infrastructure::Request::Destination::Style);
// 5. Return true.
return true;
}
// https://html.spec.whatwg.org/multipage/links.html#preconnect
void HTMLLinkElement::preconnect(LinkProcessingOptions const& options)
{
// 1. If options's href is an empty string, return.
if (options.href.is_empty())
return;
// 2. Let url be the result of encoding-parsing a URL given options's href, relative to options's base URL.
// FIXME: Spec issue: We should be parsing this URL relative to a document or environment settings object.
// https://github.com/whatwg/html/issues/9715
auto url = DOMURL::parse(options.href.utf16_view(), options.base_url);
// 3. If url is failure, then return.
if (!url.has_value())
return;
// 4. If url's scheme is not an HTTP(S) scheme, then return.
if (!url->scheme().is_one_of("http"sv, "https"sv))
return;
// FIXME: 5. Let partitionKey be the result of determining the network partition key given options's environment.
// FIXME: 6. Let useCredentials be true.
// FIXME: 7. If options's crossorigin is Anonymous and options's origin does not have the same origin as url's origin,
// then set useCredentials to false.
// 8. The user agent should obtain a connection given partitionKey, url's origin, and useCredentials.
// FIXME: This should go through Fetch: https://fetch.spec.whatwg.org/#concept-connection-obtain
if (!ResourceLoader::is_initialized())
return;
// AD-HOC: Until then, keep an SVG image off the network as Fetch would.
if (options.document && options.document->is_decoded_svg())
return;
auto source_url = options.document ? options.document->fallback_base_url() : options.environment->api_base_url();
ResourceLoader::the().preconnect(options.document, *url, source_url);
}
// https://html.spec.whatwg.org/multipage/links.html#match-preload-type
static bool type_matches_destination(Utf16View type, Optional<Fetch::Infrastructure::Request::Destination> destination)
{
using enum Fetch::Infrastructure::Request::Destination;
// 1. If type is an empty string, then return true.
if (type.is_empty())
return true;
// 2. If destination is "fetch", then return true.
// FIXME: Spec issue: "fetch" will have been turned to an empty string by this point.
if (!destination.has_value())
return true;
// 3. Let mimeTypeRecord be the result of parsing type.
auto mime_type_record = MimeSniff::MimeType::parse(type);
// 4. If mimeTypeRecord is failure, then return false.
if (!mime_type_record.has_value())
return false;
// FIXME: 5. If mimeTypeRecord is not supported by the user agent, then return false.
// 6. If any of the following are true:
if (
// destination is "audio" or "video", and mimeTypeRecord is an audio or video MIME type;
((destination == Audio || destination == Video) && mime_type_record->is_audio_or_video())
// destination is a script-like destination and mimeTypeRecord is a JavaScript MIME type;
|| (Fetch::Infrastructure::destination_is_script_like(*destination) && mime_type_record->is_javascript())
// destination is "image" and mimeTypeRecord is an image MIME type;
|| (destination == Image && mime_type_record->is_image())
// destination is "font" and mimeTypeRecord is a font MIME type;
|| (destination == Font && mime_type_record->is_font())
// destination is "json" and mimeTypeRecord is a JSON MIME type;
|| (destination == JSON && mime_type_record->is_json())
// destination is "style" and mimeTypeRecord's essence is text/css; or
|| (destination == Style && mime_type_record->essence() == "text/css"sv)
// destination is "track" and mimeTypeRecord's essence is text/vtt,
|| (destination == Track && mime_type_record->essence() == "text/vtt"sv)) {
// then return true.
return true;
}
// 7. Return false.
return false;
}
// https://html.spec.whatwg.org/multipage/links.html#preload
void HTMLLinkElement::preload(LinkProcessingOptions& options, GC::Ptr<GC::Function<void(Fetch::Infrastructure::Response&)>> process_response)
{
auto& realm = options.environment->realm();
// 1. If options's type doesn't match options's destination, then return.
if (!type_matches_destination(options.type, options.destination))
return;
// 2. If options's destination is "image" and options's source set is not null, then set options's href to the
// result of selecting an image source from options's source set.
// NB: A link with neither an href nor an imagesrcset has an empty source set, with no image source to select.
if (options.destination == Fetch::Infrastructure::Request::Destination::Image && options.source_set.has_value() && !options.source_set->is_empty()) {
auto device_pixel_ratio = 1.0;
if (auto const* window = window_from_global_object(options.environment->global_object()))
device_pixel_ratio = window->device_pixel_ratio();
options.href = options.source_set->select_an_image_source(device_pixel_ratio).source.url;
}
if (options.href.is_empty())
return;
// 3. Let request be the result of creating a link request given options.
auto request = create_link_request(options);
// 4. If request is null, then return.
if (!request)
return;
// FIXME: 5. Let unsafeEndTime be 0.
// 6. Let entry be a new preload entry whose integrity metadata is options's integrity.
auto entry = PreloadEntry::create();
entry->integrity_metadata = options.integrity;
// 7. Let key be the result of creating a preload key given request.
auto key = create_a_preload_key(*request);
// 8. If options's document is null, then set request's initiator type to "early hint".
if (!options.document)
request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::EarlyHint);
// AD-HOC: Otherwise, set request's initiator type to "link", as the default fetch and process the linked resource
// steps do. Without an initiator type, the preload is never reported to Resource Timing, but other engines
// report it with an initiatorType of "link". Fetch then reports the timing itself once the body is read.
else
request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Link);
// 9. Let controller be null.
auto controller_holder = Fetch::Infrastructure::FetchControllerHolder::create();
// 10. Let reportTiming given a Document document be to report timing for controller given document's relevant global object.
auto report_timing = GC::create_function(GC::Heap::the(), GC::captures(controller_holder), [](auto& controller_holder, DOM::Document const& document) {
controller_holder->controller()->report_timing(relevant_global_object(document));
});
// 11. Set controller to the result of fetching request, with processResponseConsumeBody set to the following steps
// given a response response and null, failure, or a byte sequence bodyBytes:
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };
fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { options }, process_response, entry, report_timing), [](auto& options, auto& process_response, auto& entry, auto& report_timing, GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
// FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
// https://github.com/whatwg/html/issues/9355
// NB: Step 1 sets the body of a clone of response, so the response fetch delivered never changes. Nothing can
// observe the difference.
// NB: Keep the filtered response, which main fetch uses as is. Unfiltered, it would be treated as same-origin.
auto response = response_view->record()->clone();
// 1. If bodyBytes is a byte sequence, then set response's body to bodyBytes as a body.
if (auto* byte_sequence = body_bytes.get_pointer<Core::ImmutableBytes>())
response->unsafe_response()->set_body(Fetch::Infrastructure::ResponseBody::from_bytes(*byte_sequence));
// 2. Otherwise, set response to a network error.
else
response = Fetch::Infrastructure::Response::network_error("Expected preload response to contain a body"_string);
// FIXME: 3. Set unsafeEndTime to the unsafe shared current time.
// 4. If options's document is not null, then call reportTiming given options's document.
// AD-HOC: Only when reading the body failed. A preload with a document has the "link" initiator type (see
// above), so fetch has already reported its timing once the body was read, and reporting it again would
// add a second entry. Fetch does not report a failed body read.
if (options->document && body_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>())
report_timing->function()(*options->document);
// 5. If entry's on response available is null, then set entry's response to response; otherwise call entry's
// on response available given response.
if (!entry->on_response_available)
entry->response = response;
else
entry->on_response_available->function()(response);
// 6. If processResponse is given, then call processResponse with response.
if (process_response)
process_response->function()(response);
});
auto controller = Fetch::Fetching::fetch(realm, *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
controller_holder->set_controller(controller);
entry->controller = controller;
// 12. Let commit be the following steps given a Document document:
auto commit = GC::create_function(GC::Heap::the(), GC::captures(entry, report_timing, move(key)), [](auto& entry, auto& report_timing, auto& key, DOM::Document& document) {
// 1. If entry's response is not null, then call reportTiming given document.
if (entry->response)
report_timing->function()(document);
// 2. Set document's map of preloaded resources[key] to entry.
document.map_of_preloaded_resources().set(key, entry);
});
// 13. If options's document is null, then set options's on document ready to commit. Otherwise, call commit with
// options's document.
if (!options.document)
options.on_document_ready = commit;
else
commit->function()(*options.document);
}
void HTMLLinkElement::modulepreload(LinkProcessingOptions const& options)
{
if (options.href.is_empty())
return;
auto url = DOMURL::parse(options.href.utf16_view(), options.base_url);
if (!url.has_value())
return;
auto& settings_object = *options.environment;
auto integrity_metadata = options.integrity;
if (integrity_metadata.is_empty())
integrity_metadata = resolve_a_module_integrity_metadata(*url, settings_object);
ScriptFetchOptions script_fetch_options {
.cryptographic_nonce = options.cryptographic_nonce_metadata,
.integrity_metadata = move(integrity_metadata),
.parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
.credentials_mode = cors_settings_attribute_credentials_mode(options.crossorigin),
.referrer_policy = options.referrer_policy,
.fetch_priority = options.fetch_priority,
};
auto on_complete = GC::create_function(GC::Heap::the(), [](GC::Ptr<Script>) { });
fetch_modulepreload_module_script_graph(settings_object.realm(), *url, *options.destination, settings_object, script_fetch_options, on_complete);
}
// https://html.spec.whatwg.org/multipage/semantics.html#extract-links-from-headers
static Vector<HTTP::Link> extract_links_from_headers(HTTP::HeaderList const& headers, URL::URL const& response_url)
{
// 1. Let links be a new list.
Vector<HTTP::Link> links;
// 2. Let rawLinkHeaders be the result of getting, decoding, and splitting `Link` from headers.
// AD-HOC: Keep a URL that contains a comma in one piece, matching other engines. See:
// https://github.com/whatwg/html/issues/11468
auto value = headers.get("Link"sv);
if (!value.has_value())
return links;
auto raw_link_headers = HTTP::get_decode_and_split_link_header_value(*value);
// NB: The URL of the representation has no fragment, since a request target never has one.
auto representation_url = response_url;
representation_url.set_fragment({});
// 3. For each linkHeader of rawLinkHeaders:
for (auto const& link_header : raw_link_headers) {
// 1. Let linkObject be the result of parsing linkHeader. [WEBLINK]
// NB: Parsing yields one link object for each relation type, and none if linkHeader is not a link.
for (auto& link_object : HTTP::parse_link_field_value(link_header, representation_url)) {
// 2. If linkObject["target_uri"] does not exist, then continue.
if (!link_object.target_uri.has_value())
continue;
// AD-HOC: Skip a link whose anchor makes it about another resource. RFC 8288 forbids processing a link
// without applying its anchor. See: https://www.rfc-editor.org/rfc/rfc8288#section-3.2
if (link_object.context_uri != representation_url)
continue;
// 3. Append linkObject to links.
links.append(move(link_object));
}
}
// 4. Return links.
return links;
}
// https://html.spec.whatwg.org/multipage/semantics.html#process-link-headers
void HTMLLinkElement::process_link_headers(DOM::Document& document, HTTP::HeaderList const& response_header_list, URL::URL const& response_url, LinkHeaderPhase phase)
{
// 1. Let links be the result of extracting links from response's header list.
auto links = extract_links_from_headers(response_header_list, response_url);
// 2. For each linkObject in links:
for (auto const& link_object : links) {
// 1. Let rel be linkObject["relation_type"].
auto const& rel = link_object.relation_type;
// OPTIMIZATION: Step 9 does nothing for any other relation type.
if (!rel.is_one_of("preconnect"sv, "preload"sv, "modulepreload"sv))
continue;
// 2. Let attribs be linkObject["target_attributes"].
auto media = link_object.target_attribute("media"sv);
// 3. Let expectedPhase be "media" if either "srcset", "imagesrcset", or "media" exist in attribs; otherwise
// "pre-media".
auto expected_phase = LinkHeaderPhase::PreMedia;
if (link_object.target_attribute("srcset"sv).has_value() || link_object.target_attribute("imagesrcset"sv).has_value() || media.has_value())
expected_phase = LinkHeaderPhase::Media;
// 4. If expectedPhase is not phase, then continue.
if (expected_phase != phase)
continue;
// 5. If attribs["media"] exists and attribs["media"] does not match the environment, then continue.
if (media.has_value()) {
auto media_query = Utf16String::from_utf8(*media);
if (!media_attribute_matches_environment(document, media_query))
continue;
}
// 6. Let options be a new link processing options with
auto options = GC::Heap::the().allocate<LinkProcessingOptions>(
CORSSettingAttribute::NoCORS,
ReferrerPolicy::ReferrerPolicy::EmptyString,
Optional<SourceSet> {},
// base URL
// doc's document base URL
// AD-HOC: Use the response's URL instead, so that a base element parsed before the "media" phase does not
// apply to the URLs of a source set, matching other engines. See:
// https://github.com/whatwg/html/issues/8330
response_url,
// origin
// doc's origin
document.origin(),
// environment
// doc's relevant settings object
document.relevant_settings_object(),
// policy container
// doc's policy container
document.policy_container(),
// document
// doc
document,
Utf16String {},
Fetch::Infrastructure::Request::Priority::Auto);
// href
// linkObject["target_uri"]
options->href = Utf16String::from_utf8(link_object.target_uri->serialize());
// 7. Apply link options from parsed header attributes to options given attribs and rel. If that returned
// false, then return.
// AD-HOC: Skip only this link, matching other engines.
if (!apply_link_options_from_parsed_header_attributes(options, link_object))
continue;
// 8. If attribs["imagesrcset"] exists and attribs["imagesizes"] exists, then set options's source set to the
// result of creating a source set given linkObject["target_uri"], attribs["imagesrcset"],
// attribs["imagesizes"], and null.
// AD-HOC: Create the source set when attribs["imagesizes"] does not exist as well, as for the element and
// matching other engines.
if (auto image_srcset = link_object.target_attribute("imagesrcset"sv); image_srcset.has_value()) {
auto default_source = Utf16String::from_utf8(link_object.target_uri->serialize());
auto srcset = Utf16String::from_utf8(*image_srcset);
auto image_sizes = link_object.target_attribute("imagesizes"sv);
auto sizes = image_sizes.has_value() ? Utf16String::from_utf8(*image_sizes) : Utf16String {};
options->source_set = SourceSet::create(document, default_source, srcset, sizes);
}
// 9. Run the process a link header steps for rel given options.
if (rel == "preconnect"sv) {
preconnect(options);
} else if (rel == "preload"sv) {
preload(options);
}
// AD-HOC: The process a link header steps for modulepreload are to do nothing. Fetch the module script graph
// as the element does instead, matching other engines. See: https://github.com/whatwg/html/pull/7862
else if (rel == "modulepreload"sv) {
modulepreload(options);
}
}
}
// https://html.spec.whatwg.org/multipage/semantics.html#apply-link-options-from-parsed-header-attributes
bool HTMLLinkElement::apply_link_options_from_parsed_header_attributes(LinkProcessingOptions& options, HTTP::Link const& link_object)
{
// 1. If rel is "preload":
if (link_object.relation_type == "preload"sv) {
// 1. If attribs["as"] does not exist, then return false.
auto as = link_object.target_attribute("as"sv);
if (!as.has_value())
return false;
// 2. Let destination be the result of translating attribs["as"].
auto as_value = Utf16String::from_utf8(*as);
auto destination = translate_a_preload_destination(as_value);
// 3. If destination is null, then return false.
if (destination.has<Empty>())
return false;
// 4. Set options's destination to destination.
options.destination = destination.get<Optional<Fetch::Infrastructure::Request::Destination>>();
}
// AD-HOC: Set options's destination for modulepreload as well, from attribs["as"] as the element does.
else if (link_object.relation_type == "modulepreload"sv) {
auto as = link_object.target_attribute("as"sv);
auto as_value = as.has_value() ? Utf16String::from_utf8(*as) : Utf16String {};
auto destination = module_preload_destination_from_as_attribute(as_value);
if (!destination.has_value())
return false;
options.destination = destination;
}
// 2. If attribs["crossorigin"] exists and is an ASCII case-insensitive match for one of the CORS settings attribute
// keywords, then set options's crossorigin to the CORS settings attribute state corresponding to that keyword.
if (auto crossorigin = link_object.target_attribute("crossorigin"sv); crossorigin.has_value()) {
if (crossorigin->is_empty() || crossorigin->equals_ignoring_ascii_case("anonymous"sv)) {
options.crossorigin = CORSSettingAttribute::Anonymous;
} else if (crossorigin->equals_ignoring_ascii_case("use-credentials"sv)) {
options.crossorigin = CORSSettingAttribute::UseCredentials;
}
}
// 3. If attribs["integrity"] exists, then set options's integrity to attribs["integrity"].
if (auto integrity = link_object.target_attribute("integrity"sv); integrity.has_value())
options.integrity = Utf16String::from_utf8(*integrity);
// 4. If attribs["referrerpolicy"] exists and is an ASCII case-insensitive match for some referrer policy, then set
// options's referrer policy to that referrer policy.
if (auto referrer_policy = link_object.target_attribute("referrerpolicy"sv); referrer_policy.has_value()) {
if (auto policy = ReferrerPolicy::from_string(referrer_policy->bytes_as_string_view()); policy.has_value())
options.referrer_policy = *policy;
}
// 5. If attribs["nonce"] exists, then set options's nonce to attribs["nonce"].
if (auto nonce = link_object.target_attribute("nonce"sv); nonce.has_value())
options.cryptographic_nonce_metadata = Utf16String::from_utf8(*nonce);
// 6. If attribs["type"] exists, then set options's type to attribs["type"].
if (auto type = link_object.target_attribute("type"sv); type.has_value())
options.type = Utf16String::from_utf8(*type);
// 7. If attribs["fetchpriority"] exists and is an ASCII case-insensitive match for a fetch priority attribute
// keyword, then set options's fetch priority to that fetch priority attribute keyword.
if (auto fetch_priority = link_object.target_attribute("fetchpriority"sv); fetch_priority.has_value()) {
if (auto priority = Fetch::Infrastructure::request_priority_from_string(Utf16String::from_utf8(*fetch_priority)); priority.has_value())
options.fetch_priority = *priority;
}
// 8. Return true.
return true;
}
// https://html.spec.whatwg.org/multipage/semantics.html#process-the-linked-resource
void HTMLLinkElement::process_linked_resource(bool success, Fetch::Infrastructure::ResponseView const& response, CSS::StyleScope::OriginClean origin_clean, Core::ImmutableBytes const* body_bytes)
{
if (success)
VERIFY(body_bytes);
if (m_relationship & Relationship::Icon) {
ByteBuffer icon_bytes;
if (success)
icon_bytes = body_bytes->copy_to_byte_buffer().release_value_but_fixme_should_propagate_errors();
process_icon_resource(success, response, move(icon_bytes));
} else if (m_relationship & Relationship::Stylesheet) {
process_stylesheet_resource(success, response, origin_clean, success ? body_bytes->bytes() : ReadonlyBytes {});
}
}
static NonnullRefPtr<Core::Promise<NonnullRefPtr<Gfx::Bitmap const>>> decode_favicon(ReadonlyBytes favicon_data, URL::URL const& favicon_url, Optional<MimeSniff::MimeType> mime_type, GC::Ref<DOM::Document> document)
{
auto promise = Core::Promise<NonnullRefPtr<Gfx::Bitmap const>>::construct();
auto is_svg_icon = (mime_type.has_value() && mime_type.value().essence() == "image/svg+xml"sv) || favicon_url.basename().ends_with(".svg"sv);
if (is_svg_icon) {
SVG::SVGDecodedImageData::decode(document->page(), favicon_url, favicon_data)
->when_resolved([promise](auto& image_data) {
// FIXME: Calculate size based on device pixel ratio
auto decoded_frame = image_data->default_frame({ 32, 32 });
if (!decoded_frame.has_value()) {
promise->reject(Error::from_string_view("Failed to get bitmap from SVG favicon"sv));
return;
}
promise->resolve(decoded_frame->bitmap_sharing_pixels());
})
.when_rejected([promise](Error& error) {
promise->reject(move(error));
});
return promise;
}
auto on_failed_decode = [favicon_url, promise]([[maybe_unused]] Error& error) {
dbgln_if(IMAGE_DECODER_DEBUG, "Failed to decode favicon {}: {}", favicon_url, error);
promise->reject(move(error));
};
auto on_successful_decode = [document = GC::Root(document), promise](Web::Platform::DecodedImage& decoded_image) -> ErrorOr<void> {
// NB: Only the first frame is used, so an animation the decoder opened is stopped right away.
if (decoded_image.session_id != 0)
Platform::ImageCodecPlugin::the().stop_animation_decode(decoded_image.session_id);
auto favicon_bitmap = decoded_image.frames[0].bitmap;
dbgln_if(IMAGE_DECODER_DEBUG, "Decoded favicon, {}", favicon_bitmap->size());
promise->resolve(favicon_bitmap.release_nonnull());
return {};
};
(void)Platform::ImageCodecPlugin::the().decode_image(favicon_data, move(on_successful_decode), move(on_failed_decode));
return promise;
}
// AD-HOC: The spec is underspecified for fetching and processing rel="icon" See:
// https://github.com/whatwg/html/issues/1769
void HTMLLinkElement::process_icon_resource(bool success, Fetch::Infrastructure::ResponseView const& response, ByteBuffer body_bytes)
{
if (!success)
return;
auto generation = m_current_fetch_generation;
decode_favicon(body_bytes.span(), response.url().value_or({}), Fetch::Infrastructure::extract_mime_type(response.header_list()), document())
->when_resolved(GC::weak_callback(*this, [generation](HTMLLinkElement& element, NonnullRefPtr<Gfx::Bitmap const>& favicon) {
if (element.m_current_fetch_generation != generation || !element.document().is_fully_active())
return;
element.m_loaded_icon = favicon;
element.document().check_favicon_after_loading_link_resource();
}))
.when_rejected(GC::weak_callback(*this, [generation](HTMLLinkElement& element, Error&) {
if (element.m_current_fetch_generation != generation || !element.document().is_fully_active())
return;
element.m_loaded_icon = nullptr;
element.document().check_favicon_after_loading_link_resource();
}));
}
// https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:process-the-linked-resource
void HTMLLinkElement::process_stylesheet_resource(bool success, Fetch::Infrastructure::ResponseView const& response, CSS::StyleScope::OriginClean origin_clean, ReadonlyBytes body_bytes)
{
if (!document().is_fully_active())
return;
auto fetch_generation = m_current_fetch_generation;
// 1. If the resource's Content-Type metadata is not text/css, then set success to false.
Optional<StringView> mime_type_charset;
auto extracted_mime_type = Fetch::Infrastructure::extract_mime_type(response.header_list());
if (extracted_mime_type.has_value()) {
if (auto charset = extracted_mime_type->parameters().get("charset"sv); charset.has_value())
mime_type_charset = charset->bytes_as_string_view();
}
// Quirk: If the document has been set to quirks mode, has the same origin as the URL of the external resource,
// and the Content-Type metadata of the external resource is not a supported style sheet type, the user agent
// must instead assume it to be text/css.
auto resource_url = response.url();
auto assume_css_in_quirks_mode = document().in_quirks_mode() && resource_url.has_value()
&& document().origin().is_same_origin(resource_url->origin());
// AD-HOC: A response without a valid Content-Type is used as CSS, matching other engines.
if (extracted_mime_type.has_value() && extracted_mime_type->essence() != "text/css"sv && !assume_css_in_quirks_mode)
success = false;
// 2. If el no longer creates an external resource link that contributes to the styling processing model, or
// if, since the resource in question was fetched, it has become appropriate to fetch it again, then return.
// NB: The "fetch it again" case is handled by the fetch generation check in
// default_fetch_and_process_linked_resource().
// 3. If el has an associated CSS style sheet, remove the CSS style sheet.
if (m_loaded_style_sheet) {
document_or_shadow_root_style_scope().remove_a_css_style_sheet(*m_loaded_style_sheet);
m_loaded_style_sheet = nullptr;
}
// 4. If success is true, then:
if (success) {
// 1. Create a CSS style sheet with the following properties:
// type
// text/css
// location
// response's URL list[0]
// owner node
// element
// media
// The media attribute of element.
// title
// The title attribute of element, if element is in a document tree, or the empty string otherwise.
// alternate flag
// Set if the link is an alternative style sheet and element's explicitly enabled is false; unset otherwise.
// origin-clean flag
// Set if the resource is CORS-same-origin; unset otherwise.
// parent CSS style sheet
// owner CSS rule
// null
// disabled flag
// Left at its default value.
// CSS rules
// Left uninitialized.
//
// The CSS environment encoding is the result of running the following steps: [CSSSYNTAX]
// 1. If the element has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING]
// 2. Otherwise, return the document's character encoding. [DOM]
Optional<StringView> environment_encoding;
if (auto charset = attribute(HTML::AttributeNames::charset); charset.has_value())
environment_encoding = TextCodec::get_standardized_encoding(*charset);
if (!environment_encoding.has_value() && document().encoding().has_value())
environment_encoding = TextCodec::get_standardized_encoding(document().encoding().value());
auto maybe_decoded_string = css_decode_bytes(environment_encoding, mime_type_charset, body_bytes);
if (maybe_decoded_string.is_error()) {
dbgln("Failed to decode CSS file: {}", response.url().value_or(URL::URL()));
associate_empty_style_sheet(response, origin_clean);
dispatch_event(create_event_for_element(*this, HTML::EventNames::error));
} else {
VERIFY(!response.url_list().is_empty());
m_stylesheet_processing_pending = true;
// The sheet's relative URLs resolve against the URL the sheet was fetched from, after any redirect; its
// location stays the URL it was linked at.
CSS::Parser::Parser::parse_stylesheet_off_thread(
CSS::Parser::ParsingParams { document() }, maybe_decoded_string.release_value(),
[link = GC::make_root(*this), loaded_document = GC::make_root(document()), fetch_generation = m_current_fetch_generation, location = response.url_list().first(), base_url = response.url_list().last(), origin_clean, referrer_policy = ReferrerPolicy::parse_a_referrer_policy_from_a_referrer_policy_header(*response.record())](CSS::Parser::RustStyleSheetParse parsed) mutable {
if (fetch_generation != link->m_current_fetch_generation || !link->m_stylesheet_processing_pending)
return;
// NB: An inactive document's element tasks cannot run. Release its result here.
if (&link->document() != loaded_document.ptr() || !loaded_document->is_fully_active()) {
loaded_document->remove_from_script_blocking_style_sheet_set(*link);
link->cancel_pending_stylesheet_processing();
return;
}
// NB: The task's function keeps the element and the document alive as cells it holds, not as GC
// roots: the roots of a function that died would keep them alive through the collection that
// finds it dead.
link->queue_an_element_task(Task::Source::Networking,
GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *link }, GC::Ref { *loaded_document }, fetch_generation, move(location), move(base_url), move(parsed), origin_clean, referrer_policy), [](auto& link, auto& loaded_document, auto& fetch_generation, auto& location, auto& base_url, auto& parsed, auto& origin_clean, auto& referrer_policy) {
if (fetch_generation != link->m_current_fetch_generation || !link->m_stylesheet_processing_pending)
return;
if (&link->document() != loaded_document.ptr() || !loaded_document->is_fully_active()
|| !link->is_browsing_context_connected() || !(link->m_relationship & Relationship::Stylesheet)) {
loaded_document->remove_from_script_blocking_style_sheet_set(*link);
link->finish_processing_stylesheet_resource(fetch_generation);
return;
}
// NB: The sheet records its referrer policy as it is created, before its imports start to load.
auto sheet = CSS::StyleSheetState::create(parsed.native_rules(), loaded_document.ptr(), {}, location, referrer_policy);
if (base_url != location)
sheet->set_base_url(move(base_url));
link->associate_style_sheet(*sheet, origin_clean);
// NB: The sheet has to be associated before its critical subresources (@import rules)
// get fetched. Wait for them before firing load and unblocking scripts.
if (sheet->loading_state() == CSS::StyleSheetState::LoadingState::Loading) {
link->m_fetch_generation_waiting_for_critical_subresources = fetch_generation;
return;
}
// 2. Fire an event named load at el.
// INTEROP: Other browsers fire error instead when an import failed, including before the
// sheet was associated with the link.
auto event_name = sheet->loading_state() == CSS::StyleSheetState::LoadingState::Error ? HTML::EventNames::error : HTML::EventNames::load;
link->dispatch_event(create_event_for_element(*link, event_name));
link->finish_processing_stylesheet_resource(fetch_generation);
}));
});
return;
}
}
// 5. Otherwise, fire an event named error at el.
else {
associate_empty_style_sheet(response, origin_clean);
dispatch_event(create_event_for_element(*this, HTML::EventNames::error));
}
finish_processing_stylesheet_resource(fetch_generation);
}
void HTMLLinkElement::associate_style_sheet(CSS::StyleSheetState& sheet, CSS::StyleScope::OriginClean origin_clean)
{
auto media = attribute(HTML::AttributeNames::media);
auto title = in_a_document_tree() ? attribute(HTML::AttributeNames::title) : Optional<Utf16String> {};
document_or_shadow_root_style_scope().initialize_a_css_style_sheet(
sheet, this, media.has_value() ? media->utf16_view() : u""sv,
title.has_value() ? title.release_value() : Utf16String {},
(m_relationship & Relationship::Alternate && !m_explicitly_enabled) ? CSS::StyleScope::Alternate::Yes : CSS::StyleScope::Alternate::No,
origin_clean, nullptr, nullptr);
m_loaded_style_sheet = sheet;
m_loaded_style_sheet_fetch_generation = m_current_fetch_generation;
// NB: Removing disabled explicitly enables the sheet, even if its title would disable it.
if (m_explicitly_enabled)
sheet.set_disabled(false);
}
// AD-HOC: The spec creates no style sheet for a link whose resource failed to load, but all major engines associate an
// empty one with it. Its origin-clean flag is still set only if the response was CORS-same-origin, which a
// network error never is.
void HTMLLinkElement::associate_empty_style_sheet(Fetch::Infrastructure::ResponseView const& response, CSS::StyleScope::OriginClean origin_clean)
{
// NB: A link that was removed while its resource was being fetched no longer contributes a style sheet.
if (!is_browsing_context_connected())
return;
auto location = response.url_list().is_empty() ? document().encoding_parse_url(href()) : response.url_list().first();
associate_style_sheet(*parse_css_stylesheet(CSS::Parser::ParsingParams { document() }, u""sv, move(location)), origin_clean);
}
void HTMLLinkElement::cancel_pending_stylesheet_processing(UnblockRendering unblock_rendering)
{
m_fetch_generation_waiting_for_critical_subresources = {};
if (!m_stylesheet_processing_pending && !m_document_load_event_delayer.has_value())
return;
m_stylesheet_processing_pending = false;
stop_blocking_on_style_sheet(unblock_rendering);
}
void HTMLLinkElement::stop_blocking_on_style_sheet(UnblockRendering unblock_rendering)
{
document().remove_from_script_blocking_style_sheet_set(*this);
if (unblock_rendering == UnblockRendering::Yes)
this->unblock_rendering();
m_document_load_event_delayer.clear();
}
void HTMLLinkElement::finish_processing_stylesheet_resource(u64 fetch_generation)
{
// NB: A load or error handler can start another fetch, which owns its own blocking state.
if (fetch_generation != m_current_fetch_generation)
return;
// 6. If el contributes a script-blocking style sheet, then:
if (document().script_blocking_style_sheet_set().contains(*this)) {
// 1. Assert: el's node document's script-blocking style sheet set contains el.
VERIFY(document().script_blocking_style_sheet_set().contains(*this));
// 2. Remove el from its node document's script-blocking style sheet set.
document().remove_from_script_blocking_style_sheet_set(*this);
}
// 7. Unblock rendering on el.
unblock_rendering();
m_stylesheet_processing_pending = false;
if (m_loaded_style_sheet) {
auto style_sheet_loading_state = m_loaded_style_sheet->loading_state();
if (style_sheet_loading_state == CSS::StyleSheetState::LoadingState::Loaded || style_sheet_loading_state == CSS::StyleSheetState::LoadingState::Error) {
finished_loading_critical_style_subresources(style_sheet_loading_state == CSS::StyleSheetState::LoadingState::Error ? AnyFailed::Yes : AnyFailed::No);
}
} else {
m_document_load_event_delayer.clear();
}
}
// https://html.spec.whatwg.org/multipage/links.html#rel-icon:the-link-element-3
void HTMLLinkElement::load_fallback_favicon_if_needed(GC::Ref<DOM::Document> document)
{
// NB: A headless page shows no favicon.
if (document->page().client().is_headless())
return;
auto& realm = document->relevant_settings_object().realm();
// In the absence of a link with the icon keyword, for Document objects whose URL's scheme is an HTTP(S) scheme,
// user agents may instead run these steps in parallel:
if (document->has_active_favicon())
return;
if (!document->url().scheme().is_one_of("http"sv, "https"sv))
return;
auto icon_link_elements = DOM::HTMLCollection::create(*document, DOM::HTMLCollection::Scope::Descendants, GC::create_function(GC::Heap::the(), [](DOM::Element const& element) {
if (!is<HTMLLinkElement>(element))
return false;
return static_cast<HTMLLinkElement const&>(element).has_icon_keyword(); }), DOM::HTMLCollection::AttributeInvalidationType::None);
if (icon_link_elements->length() != 0)
return;
// AD-HOC: Don't load fallback favicon for auxiliary browsing contexts (popup windows).
// This matches the behavior observed in Chrome and Firefox, and avoids unnecessary network requests
// that can interfere with Content Security Policy violation reporting.
// See: https://github.com/whatwg/html/issues/12082
if (auto browsing_context = document->browsing_context(); browsing_context->is_auxiliary())
return;
// 1. Let request be a new request whose URL is the URL record obtained by resolving the URL "/favicon.ico" against
// the Document object's URL, client is the Document object's relevant settings object, destination is "image",
// synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.
// NOTE: Fetch requests no longer have a synchronous flag, see https://github.com/whatwg/fetch/pull/1165
auto favicon_url = document->encoding_parse_url("/favicon.ico"_utf16);
// It is possible for the URL parser to fail if the document's base URL is invalid.
if (!favicon_url.has_value())
return;
auto request = Fetch::Infrastructure::Request::create();
request->set_url(favicon_url.release_value());
request->set_client(document->relevant_settings_object().address());
request->set_destination(Fetch::Infrastructure::Request::Destination::Image);
request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
request->set_use_url_credentials(true);
// 2. Let response be the result of fetching request.
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };
fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(document, request), [](auto& document, auto& request, GC::Ref<Fetch::Infrastructure::ResponseView> response) {
auto& realm = document->relevant_settings_object().realm();
auto global = GC::Ref { realm.global_object() };
auto mime_type = Fetch::Infrastructure::extract_mime_type(response->header_list());
auto process_body = GC::create_function(GC::Heap::the(), GC::captures(document, request, mime_type), [](auto& document, auto& request, auto& mime_type, ByteBuffer body) {
// FIXME: We should use the response URL to account for redirects when determining if this is an SVG icon.
decode_favicon(body, request->url(), mime_type, document)
->when_resolved(GC::weak_callback(*document, [](DOM::Document& document, NonnullRefPtr<Gfx::Bitmap const>& favicon) {
if (auto navigable = document.navigable(); navigable && navigable->is_traversable())
navigable->page().client().page_did_change_favicon(*favicon);
}));
});
auto process_body_error = GC::create_function(GC::Heap::the(), [](JS::Value) {
});
// Check for failed favicon response
if (!Fetch::Infrastructure::is_ok_status(response->status()) || !response->body()) {
return;
}
// 3. Use response's unsafe response as an icon as if it had been declared using the icon keyword.
if (auto body = response->unsafe_response()->body())
body->fully_read(realm, process_body, process_body_error, global);
});
Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
}
bool HTMLLinkElement::should_fetch_and_process_resource_type() const
{
// https://html.spec.whatwg.org/multipage/links.html#link-type-dns-prefetch:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-preconnect:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-preload:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload:fetch-and-process-the-linked-resource
// https://html.spec.whatwg.org/multipage/links.html#link-type-prefetch:fetch-and-process-the-linked-resource
if (m_relationship & (Relationship::DNSPrefetch | Relationship::Preconnect | Relationship::Preload | Relationship::ModulePreload | Relationship::Prefetch | Relationship::Stylesheet))
return true;
// AD-HOC: The spec is underspecified for fetching and processing rel="icon". See:
// https://github.com/whatwg/html/issues/1769
return m_relationship & Relationship::Icon;
}
HTMLLinkElement::LinkProcessingOptions::LinkProcessingOptions(
CORSSettingAttribute crossorigin,
ReferrerPolicy::ReferrerPolicy referrer_policy,
Optional<SourceSet> source_set,
URL::URL base_url,
URL::Origin origin,
GC::Ref<HTML::EnvironmentSettingsObject> environment,
NonnullRefPtr<HTML::PolicyContainer> policy_container,
GC::Ptr<Web::DOM::Document> document,
Utf16String cryptographic_nonce_metadata,
Fetch::Infrastructure::Request::Priority fetch_priority)
: cryptographic_nonce_metadata(move(cryptographic_nonce_metadata))
, crossorigin(crossorigin)
, referrer_policy(referrer_policy)
, source_set(move(source_set))
, base_url(move(base_url))
, origin(move(origin))
, environment(environment)
, policy_container(policy_container)
, document(document)
, fetch_priority(fetch_priority)
{
}
void HTMLLinkElement::LinkProcessingOptions::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(environment);
visitor.visit(document);
visitor.visit(on_document_ready);
}
GC_DEFINE_ALLOCATOR(HTMLLinkElement::LinkProcessingOptions);
}