Truly independent web browser
LibHTTP+LibWeb: Process `Link` headers of document responses
Tim Ledbetterc50c4e1fc51b
diff --git a/Libraries/LibHTTP/Forward.h b/Libraries/LibHTTP/Forward.hindex db690e8b2dc..4fdb4bbe673 100644--- a/Libraries/LibHTTP/Forward.h+++ b/Libraries/LibHTTP/Forward.h@@ -23,6 +23,7 @@ class MemoryCache;class ProxyConfiguration;struct Header;+struct Link;struct NetworkIsolationKey;struct Proxy;diff --git a/Libraries/LibHTTP/Header.cpp b/Libraries/LibHTTP/Header.cppindex 8bb061be319..4c1fdf4509e 100644--- a/Libraries/LibHTTP/Header.cpp+++ b/Libraries/LibHTTP/Header.cpp@@ -9,6 +9,7 @@#include <AK/AllOf.h>#include <AK/AnyOf.h>#include <AK/GenericLexer.h>+#include <AK/HashTable.h>#include <AK/QuickSort.h>#include <AK/Utf16View.h>#include <LibHTTP/HTTP.h>@@ -18,6 +19,7 @@#include <LibIPC/Encoder.h>#include <LibTextCodec/Decoder.h>#include <LibTextCodec/Encoder.h>+#include <LibURL/Parser.h>namespace HTTP {@@ -247,6 +249,69 @@ Vector<String> get_decode_and_split_header_value(StringView value)}}+// https://fetch.spec.whatwg.org/#header-value-get-decode-and-split+// AD-HOC: This does not split at a comma within a link's <...> target, which a URL may contain.+Vector<String> get_decode_and_split_link_header_value(StringView value)+{+ // 1. Let input be the result of isomorphic decoding value.+ auto input = TextCodec::isomorphic_decode(value);++ // 2. Let position be a position variable for input, initially pointing at the start of input.+ GenericLexer lexer { input };++ // 3. Let values be a list of strings, initially « ».+ Vector<String> values;++ // 4. Let temporaryValue be the empty string.+ StringBuilder temporary_value_builder;++ // 5. While true:+ while (true) {+ // 1. Append the result of collecting a sequence of code points that are not U+0022 (") or U+002C (,) from+ // input, given position, to temporaryValue.+ // NOTE: The result might be the empty string.+ temporary_value_builder.append(lexer.consume_until(is_any_of("\",<"sv)));++ // 2. If position is not past the end of input and the code point at position within input is U+0022 ("):+ if (!lexer.is_eof() && lexer.peek() == '"') {+ // 1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue.+ temporary_value_builder.append(collect_an_http_quoted_string(lexer));++ // 2. If position is not past the end of input, then continue.+ if (!lexer.is_eof())+ continue;+ }+ // AD-HOC: Step 1 also stops at U+003C (<). Append the code points from there up to and including the next+ // U+003E (>), and continue unless that reached the end of input.+ else if (!lexer.is_eof() && lexer.peek() == '<') {+ temporary_value_builder.append(lexer.consume_until('>'));+ if (lexer.consume_specific('>'))+ temporary_value_builder.append('>');+ if (!lexer.is_eof())+ continue;+ }++ // 3. Remove all HTTP tab or space from the start and end of temporaryValue.+ auto temporary_value = MUST(String::from_utf8(temporary_value_builder.string_view().trim(HTTP_TAB_OR_SPACE, TrimMode::Both)));++ // 4. Append temporaryValue to values.+ values.append(move(temporary_value));++ // 5. Set temporaryValue to the empty string.+ temporary_value_builder.clear();++ // 6. If position is past the end of input, then return values.+ if (lexer.is_eof())+ return values;++ // 7. Assert: the code point at position within input is U+002C (,).+ VERIFY(lexer.peek() == ',');++ // 8. Advance position by 1.+ lexer.ignore(1);+ }+}+// https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-setVector<ByteString> convert_header_names_to_a_sorted_lowercase_set(ReadonlySpan<ByteString> header_names){@@ -351,6 +416,237 @@ Optional<RangeHeaderValue> parse_single_range_header_value(StringView value, booreturn RangeHeaderValue { range_start_value, range_end_value };}+Optional<String const&> Link::target_attribute(StringView name) const+{+ auto attribute = target_attributes->attributes.first_matching([&](auto const& attribute) { return attribute.name == name; });+ if (!attribute.has_value())+ return {};+ return attribute->value;+}++// https://www.rfc-editor.org/rfc/rfc8288#appendix-B.4+static String parse_a_quoted_string(GenericLexer& lexer)+{+ // 1. Let output be an empty string.+ StringBuilder output;++ // 2. If the first character of input is not DQUOTE, return output.+ // 3. Discard the first character.+ if (!lexer.consume_specific('"'))+ return {};++ // 4. While input has content:+ while (!lexer.is_eof()) {+ // 1. If the first character is a backslash ("\"):+ if (lexer.consume_specific('\\')) {+ // 1. Discard the first character.+ // 2. If there is no more input, return output.+ if (lexer.is_eof())+ break;++ // 3. Else, consume the first character and append it to output.+ output.append(lexer.consume());+ }+ // 2. Else, if the first character is DQUOTE, discard it and return output.+ else if (lexer.consume_specific('"')) {+ break;+ }+ // 3. Else, consume the first character and append it to output.+ else {+ output.append(lexer.consume());+ }+ }++ // 5. Return output.+ return output.to_string_without_validation();+}++// https://www.rfc-editor.org/rfc/rfc8288#appendix-B.3+static Vector<LinkParameter> parse_parameters(GenericLexer& lexer)+{+ // 1. Let parameters be an empty list.+ Vector<LinkParameter> parameters;++ // 2. While input has content:+ while (!lexer.is_eof()) {+ // 1. Consume any leading OWS.+ lexer.ignore_while(is_http_tab_or_space);++ // 2. If the first character is not ";", return parameters.+ // 3. Discard the leading ";" character.+ if (!lexer.consume_specific(';'))+ return parameters;++ // 4. Consume any leading OWS.+ lexer.ignore_while(is_http_tab_or_space);++ // 5. Consume up to but not including the first BWS, "=", ";", or "," character, or up to the end of input,+ // and let the result be parameter_name.+ auto parameter_name = lexer.consume_until(is_any_of("\t =;,"sv));++ // 6. Consume any leading BWS.+ lexer.ignore_while(is_http_tab_or_space);++ String parameter_value;++ // 7. If the next character is "=":+ if (lexer.consume_specific('=')) {+ // 1. Discard the leading "=" character.+ // 2. Consume any leading BWS.+ lexer.ignore_while(is_http_tab_or_space);++ // 3. If the next character is DQUOTE, let parameter_value be the result of Parsing a Quoted String+ // (Appendix B.4) from input (consuming zero or more characters of it).+ if (lexer.next_is('"')) {+ parameter_value = parse_a_quoted_string(lexer);+ }+ // 4. Else, consume the contents up to but not including the first ";" or "," character, or up to the end+ // of input, and let the results be parameter_value.+ // AD-HOC: Drop the OWS before that character, which the ABNF does not allow in a token.+ else {+ auto value = lexer.consume_until(is_any_of(";,"sv)).trim(HTTP_TAB_OR_SPACE, TrimMode::Right);+ parameter_value = String::from_utf8_without_validation(value.bytes());+ }++ // 5. If the last character of parameter_name is an asterisk ("*"), decode parameter_value according to+ // [RFC8187]. Continue processing input if an unrecoverable error is encountered.+ // NB: Step 16 of Parsing a Link Field Value removes these parameters.+ }+ // 8. Else:+ // 1. Let parameter_value be an empty string.++ // 9. Case-normalise parameter_name to lowercase.+ // 10. Append (parameter_name, parameter_value) to parameters.+ parameters.append({ String::from_utf8_without_validation(parameter_name.bytes()).to_ascii_lowercase(), move(parameter_value) });++ // 11. Consume any leading OWS.+ lexer.ignore_while(is_http_tab_or_space);++ // 12. If the next character is "," or the end of input, stop processing input and return parameters.+ if (lexer.is_eof() || lexer.next_is(','))+ return parameters;+ }++ return parameters;+}++// https://www.rfc-editor.org/rfc/rfc8288#appendix-B.2+Vector<Link> parse_link_field_value(StringView field_value, URL::URL const& representation_url)+{+ GenericLexer lexer { field_value };++ // 1. Let links be an empty list.+ Vector<Link> links;++ // 2. While field_value has content:+ while (!lexer.is_eof()) {+ // 1. Consume any leading OWS.+ lexer.ignore_while(is_http_tab_or_space);++ // 2. If the first character is not "<", return links.+ // 3. Discard the first character ("<").+ if (!lexer.consume_specific('<'))+ return links;++ // 4. Consume up to but not including the first ">" character or end of field_value and let the result be+ // target_string.+ auto target_string = lexer.consume_until('>');++ // 5. If the next character is not ">", return links.+ // 6. Discard the leading ">" character.+ if (!lexer.consume_specific('>'))+ return links;++ // 7. Let link_parameters be the result of Parsing Parameters (Appendix B.3) from field_value (consuming zero or+ // more characters of it).+ auto link_parameters = parse_parameters(lexer);++ // 8. Let target_uri be the result of relatively resolving (as per [RFC3986], Section 5.2) target_string. Note+ // that any base URI carried in the payload body is NOT used.+ // NB: The base URI is the URL of the representation. A target that fails to parse has no target_uri.+ auto target_uri = URL::Parser::basic_parse(target_string, representation_url);++ // 9. Let relations_string be the second item of the first tuple of link_parameters whose first item matches+ // the string "rel" or the empty string ("") if it is not present.+ auto relation = link_parameters.first_matching([](auto const& parameter) { return parameter.name == "rel"sv; });+ auto relations_string = relation.has_value() ? relation->value.bytes_as_string_view() : ""sv;++ // 10. Split relations_string on RWS (removing it in the process) into a list of string relation_types.+ auto relation_types = relations_string.split_view_if(is_http_tab_or_space);++ // 11. Let context_string be the second item of the first tuple of link_parameters whose first item matches the+ // string "anchor". If it is not present, context_string is the URL of the representation carrying the+ // Link header [RFC7231], Section 3.1.4.1, serialised as a URI. Where the URL is anonymous,+ // context_string is null.+ // 12. Let context_uri be the result of relatively resolving (as per [RFC3986], Section 5.2) context_string,+ // unless context_string is null, in which case context is null. Note that any base URI carried in the+ // payload body is NOT used.+ auto anchor = link_parameters.first_matching([](auto const& parameter) { return parameter.name == "anchor"sv; });+ auto context_uri = anchor.has_value() ? URL::Parser::basic_parse(anchor->value, representation_url) : Optional<URL::URL> { representation_url };++ // 13. Let target_attributes be an empty list.+ Vector<LinkParameter> target_attributes;++ // 14. For each tuple (param_name, param_value) of link_parameters:+ for (auto& parameter : link_parameters) {+ // 1. If param_name matches "rel" or "anchor", skip this tuple.+ if (parameter.name.is_one_of("rel"sv, "anchor"sv))+ continue;++ // 2. If param_name matches "media", "title", "title*", or "type" and target_attributes already contains a+ // tuple whose first element matches the value of param_name, skip this tuple.+ if (parameter.name.is_one_of("media"sv, "title"sv, "title*"sv, "type"sv)+ && target_attributes.contains([&](auto const& attribute) { return attribute.name == parameter.name; })) {+ continue;+ }++ // 3. Append (param_name, param_value) to target_attributes.+ target_attributes.append(parameter);+ }++ // NB: Steps 15 and 16 are as corrected by https://www.rfc-editor.org/errata/eid5878.+ // 15. Let star_param_names be the set of param_names in the (param_name, param_value) tuples of+ // target_attributes where the last character of param_name is an asterisk ("*").+ // 16. For each star_param_name in star_param_names:+ // 1. Let base_param_name be star_param_name with the last character removed.+ // 2. If the implementation does not choose to support an internationalised form of a parameter named+ // base_param_name for any reason (including, but not limited to, it being prohibited by the+ // parameter's specification), remove all tuples from target_attributes whose first member is+ // star_param_name, and skip to the next star_param_name.+ // 3. Remove all tuples from target_attributes whose first member is base_param_name.+ // 4. Change the first member of all tuples in target_attributes whose first member is star_param_name to+ // base_param_name.+ // NB: No internationalised form of a parameter is supported.+ target_attributes.remove_all_matching([](auto const& attribute) { return attribute.name.ends_with('*'); });++ auto shared_target_attributes = make_ref_counted<LinkTargetAttributes>(move(target_attributes));+ HashTable<String> appended_relation_types;++ // 17. For each relation_type in relation_types:+ for (auto relation_type : relation_types) {+ // 1. Case-normalise relation_type to lowercase.+ auto lowercase_relation_type = String::from_utf8_without_validation(relation_type.bytes()).to_ascii_lowercase();++ // AD-HOC: Skip a relation type that repeats an earlier one, which would only repeat the same link, matching+ // other engines.+ if (appended_relation_types.set(lowercase_relation_type) != HashSetResult::InsertedNewEntry)+ continue;++ // 2. Append a link object to links with the target target_uri, relation type of relation_type, context of+ // context_uri, and target attributes target_attributes.+ links.append({+ .target_uri = target_uri,+ .relation_type = move(lowercase_relation_type),+ .context_uri = context_uri,+ .target_attributes = shared_target_attributes,+ });+ }+ }++ // 3. Return links.+ return links;+}+}namespace IPC {diff --git a/Libraries/LibHTTP/Header.h b/Libraries/LibHTTP/Header.hindex 9fa5da03fed..fa5bc72a5eb 100644--- a/Libraries/LibHTTP/Header.h+++ b/Libraries/LibHTTP/Header.h@@ -8,8 +8,12 @@#pragma once#include <AK/ByteString.h>+#include <AK/NonnullRefPtr.h>+#include <AK/RefCounted.h>+#include <AK/String.h>#include <AK/StringView.h>#include <LibIPC/Forward.h>+#include <LibURL/URL.h>namespace HTTP {@@ -42,6 +46,32 @@ struct RangeHeaderValue {[[nodiscard]] ByteString build_content_range(u64 range_start, u64 range_end, u64 full_length);Optional<RangeHeaderValue> parse_single_range_header_value(StringView, bool allow_whitespace);+struct LinkParameter {+ String name;+ String value;+};++struct LinkTargetAttributes : public RefCounted<LinkTargetAttributes> {+ explicit LinkTargetAttributes(Vector<LinkParameter> attributes)+ : attributes(move(attributes))+ {+ }++ Vector<LinkParameter> attributes;+};++struct Link {+ Optional<String const&> target_attribute(StringView name) const;++ Optional<URL::URL> target_uri;+ String relation_type;+ Optional<URL::URL> context_uri;+ NonnullRefPtr<LinkTargetAttributes const> target_attributes;+};++[[nodiscard]] Vector<String> get_decode_and_split_link_header_value(StringView);+[[nodiscard]] Vector<Link> parse_link_field_value(StringView, URL::URL const& representation_url);+}namespace IPC {diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex d95cd60c8e0..517a3218507 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -622,7 +622,8 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type// FIXME: 18. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints// with document.- // FIXME: 19. Process link headers given document, navigationParams's response, and "pre-media".+ // 19. Process link headers given document, navigationParams's response, and "pre-media".+ HTML::HTMLLinkElement::process_link_headers(*document, navigation_params.response->header_list(), *creation_url, HTML::HTMLLinkElement::LinkHeaderPhase::PreMedia);// FIXME: 20. If navigationParams's navigable is a top-level traversable, then process the `Speculation-Rules`// header given document and navigationParams's response .diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cppindex eeff5b7daef..d6b5ab164a1 100644--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp@@ -26,7 +26,9 @@#include <LibWeb/DOM/IDLEventListener.h>#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>#include <LibWeb/Fetch/Response.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/HTMLHeadElement.h>+#include <LibWeb/HTML/HTMLLinkElement.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/NavigationParams.h>#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>@@ -154,8 +156,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_html_document(HTML::Navi// document's relevant global object to have the parser to process the implied EOF character, which eventually// causes a load event to be fired.else {- auto body = GC::Ref { *navigation_params.response->body() };- auto parser = HTML::IncrementalDocumentParser::create(document, body, navigation_params.response->url().value(), Fetch::Infrastructure::extract_mime_type(navigation_params.response->header_list()));+ auto parser = HTML::IncrementalDocumentParser::create(document, *navigation_params.response);parser->set_allow_declarative_shadow_roots(HTML::HTMLParser::AllowDeclarativeShadowRoots::Yes);parser->start();}@@ -200,7 +201,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigif (auto maybe_encoding = type.parameters().get("charset"sv); maybe_encoding.has_value())content_encoding = *maybe_encoding;- auto process_body = GC::create_function(GC::Heap::the(), [document, url = navigation_params.response->url().value(), content_encoding = move(content_encoding), mime = type](ByteBuffer data) {+ auto process_body = GC::create_function(GC::Heap::the(), [document, url = navigation_params.response->url().value(), response_header_list = navigation_params.response->header_list(), content_encoding = move(content_encoding), mime = type](ByteBuffer data) {Optional<TextCodec::Decoder> decoder;// The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification,// are the ones that must be used when determining the character encoding according to the rules given in the above specifications.@@ -220,7 +221,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigconvert_to_xml_error_document(document, Utf16String::formatted("Failed to decode XML document: {}", source.error()));return;}- auto run_xml_parser = [document, source_string = source.release_value()] {+ auto run_xml_parser = [document, url, response_header_list, source_string = source.release_value()] {XML::Parser parser(source_string, { .preserve_cdata = true, .preserve_comments = true, .resolve_named_html_entity = resolve_named_html_entity });XMLDocumentBuilder builder { *document };auto result = parser.parse_with_listener(builder);@@ -232,6 +233,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigdbgln("Failed to parse XML document: not namespace-well-formed");convert_to_xml_error_document(document, "Failed to parse XML document: not namespace-well-formed"_utf16);}+ HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);};if (document->ready_to_run_scripts()) {run_xml_parser();@@ -278,11 +280,11 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_text_document(HTML::Navi// document's relevant global object to have the parser to process the implied EOF character, which eventually causes a// load event to be fired.// FIXME: Parse as we receive the document data, instead of waiting for the whole document to be fetched first.- auto process_body = GC::create_function(GC::Heap::the(), [document, url = navigation_params.response->url().value(), mime = type](ByteBuffer data) {+ auto process_body = GC::create_function(GC::Heap::the(), [document, url = navigation_params.response->url().value(), response_header_list = navigation_params.response->header_list(), mime = type](ByteBuffer data) {auto [encoding, confidence] = HTML::run_encoding_sniffing_algorithm(document, data, mime);dbgln_if(HTML_PARSER_DEBUG, "The encoding sniffing algorithm returned encoding '{}'", encoding);- auto run_text_parser = [document, data = move(data), url, encoding = move(encoding)] {+ auto run_text_parser = [document, data = move(data), url, response_header_list, encoding = move(encoding)] {auto parser = HTML::HTMLParser::create_with_open_input_stream(document);parser->tokenizer().update_insertion_point();@@ -298,6 +300,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_text_document(HTML::Naviparser->run(url);document->set_encoding(Utf16String::from_ascii_without_validation(encoding.bytes()));+ HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);// 5. User agents may add content to the head element of document, e.g., linking to a style sheet, providing// script, or giving the document a title.@@ -405,13 +408,20 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::NavVERIFY_NOT_REACHED();}- // FIXME: 7. Process link headers given document, navigationParams's response, and "media".+ auto& realm = document->relevant_settings_object().realm();++ // 7. Process link headers given document, navigationParams's response, and "media".+ // AD-HOC: document has no navigable until it is activated, so media queries would be evaluated against an empty+ // viewport. Process the link headers in a networking task instead, which runs once document is fully active+ // and before the task that step 8 queues when the body has been read.+ HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), GC::create_function(GC::Heap::the(), [document, response_header_list = navigation_params.response->header_list(), url = navigation_params.response->url().value()] {+ HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);+ }));// 8. Act as if the user agent had stopped parsing document.// FIXME: We should not need to force the media file to load before saying that parsing has completed!// However, if we don't, then we get stuck in HTMLParser::the_end() waiting for the media file to load, which// never happens.- auto& realm = document->relevant_settings_object().realm();navigation_params.response->body()->fully_read(realm,GC::create_function(GC::Heap::the(), [document](ByteBuffer) { HTML::HTMLParser::the_end(document, nullptr); }),diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cppindex d4c120d71c2..cec42cbd4d9 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp@@ -13,6 +13,8 @@#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/URL.h>#include <LibWeb/CSS/Parser/Parser.h>@@ -610,7 +612,7 @@ void HTMLLinkElement::fetch_and_process_linked_preload_resource()// 6. Preload options, with the following steps given a response response:GC::Weak weak_this { *this };auto fetch_generation = m_current_fetch_generation;- preload(options, [weak_this, fetch_generation](Fetch::Infrastructure::Response& response) {+ m_fetch_controller = preload(options, [weak_this, 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)@@ -937,12 +939,12 @@ static bool type_matches_destination(Utf16View type, Optional<Fetch::Infrastruct}// https://html.spec.whatwg.org/multipage/links.html#preload-void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetch::Infrastructure::Response&)> process_response)+GC::Ptr<Fetch::Infrastructure::FetchController> HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetch::Infrastructure::Response&)> process_response){- auto& realm = HTML::relevant_realm(*this);+ 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;+ 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.@@ -954,14 +956,14 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetcoptions.href = options.source_set->select_an_image_source(device_pixel_ratio).source.url;}if (options.href.is_empty())- return;+ 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;+ return {};// FIXME: 5. Let unsafeEndTime be 0.@@ -1017,9 +1019,9 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetcprocess_response(response);};- m_fetch_controller = Fetch::Fetching::fetch(realm, *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));- controller_holder->set_controller(*m_fetch_controller);- entry->controller = m_fetch_controller;+ 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::Function<void(DOM::Document&)>::create(GC::Heap::the(), [entry, report_timing, key = move(key)](DOM::Document& document) {@@ -1037,6 +1039,252 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetcoptions.on_document_ready = commit;elsecommit->function()(*options.document);++ return controller;+}++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 = create_on_fetch_script_complete(GC::Heap::the(), [](auto) { });+ 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-resourcediff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.h b/Libraries/LibWeb/HTML/HTMLLinkElement.hindex a2a7be09f11..d77704cff0c 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.h+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.h@@ -11,6 +11,7 @@#include <AK/Function.h>#include <AK/Utf16View.h>+#include <LibHTTP/Forward.h>#include <LibWeb/CSS/StyleScope.h>#include <LibWeb/DOM/DocumentLoadEventDelayer.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>@@ -51,6 +52,12 @@ public:static void load_fallback_favicon_if_needed(GC::Ref<DOM::Document>);+ enum class LinkHeaderPhase : u8 {+ PreMedia,+ Media,+ };+ static void process_link_headers(DOM::Document&, HTTP::HeaderList const& response_header_list, URL::URL const& response_url, LinkHeaderPhase);+void set_parser_document(Badge<HTMLParser>, GC::Ref<DOM::Document> document) { m_parser_document = document; }void set_was_enabled_when_created_by_parser(Badge<HTMLParser>, bool was_enabled_when_created_by_parser) { m_was_enabled_when_created_by_parser = was_enabled_when_created_by_parser; }@@ -162,7 +169,8 @@ private:virtual bool is_implicitly_potentially_render_blocking() const override;GC::Ref<LinkProcessingOptions> create_link_options();- GC::Ptr<Fetch::Infrastructure::Request> create_link_request(LinkProcessingOptions const&);+ static GC::Ptr<Fetch::Infrastructure::Request> create_link_request(LinkProcessingOptions const&);+ static bool apply_link_options_from_parsed_header_attributes(LinkProcessingOptions&, HTTP::Link const&);void fetch_and_process_linked_resource();void default_fetch_and_process_linked_resource(u64 fetch_generation);@@ -176,8 +184,9 @@ private:bool icon_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request&);bool stylesheet_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request&);- void preconnect(LinkProcessingOptions const&);- void preload(LinkProcessingOptions&, Function<void(Fetch::Infrastructure::Response&)> process_response = {});+ static void preconnect(LinkProcessingOptions const&);+ static GC::Ptr<Fetch::Infrastructure::FetchController> preload(LinkProcessingOptions&, Function<void(Fetch::Infrastructure::Response&)> process_response = {});+ static void modulepreload(LinkProcessingOptions const&);void process_linked_resource(bool success, Fetch::Infrastructure::Response const&, CSS::StyleScope::OriginClean, Core::ImmutableBytes const*);void process_icon_resource(bool success, Fetch::Infrastructure::Response const&, ByteBuffer);diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cppindex aa55d4b5096..a6d09088f2d 100644--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp@@ -12,6 +12,9 @@#include <LibTextCodec/Decoder.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>+#include <LibWeb/HTML/HTMLLinkElement.h>#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWeb/HTML/Parser/IncrementalDocumentParser.h>@@ -25,16 +28,17 @@ static Utf16String utf16_string_from_standardized_encoding_label(StringView labereturn Utf16String::from_ascii_without_validation(label.bytes());}-GC::Ref<IncrementalDocumentParser> IncrementalDocumentParser::create(GC::Ref<DOM::Document> document, GC::Ref<Fetch::Infrastructure::Body> body, URL::URL url, Optional<MimeSniff::MimeType> mime_type)+GC::Ref<IncrementalDocumentParser> IncrementalDocumentParser::create(GC::Ref<DOM::Document> document, Fetch::Infrastructure::Response const& response){- return GC::Heap::the().allocate<IncrementalDocumentParser>(document, body, move(url), move(mime_type));+ return GC::Heap::the().allocate<IncrementalDocumentParser>(document, response);}-IncrementalDocumentParser::IncrementalDocumentParser(GC::Ref<DOM::Document> document, GC::Ref<Fetch::Infrastructure::Body> body, URL::URL url, Optional<MimeSniff::MimeType> mime_type)+IncrementalDocumentParser::IncrementalDocumentParser(GC::Ref<DOM::Document> document, Fetch::Infrastructure::Response const& response): m_document(document)- , m_body(body)- , m_url(move(url))- , m_mime_type(move(mime_type))+ , m_body(response.body())+ , m_url(response.url().value())+ , m_mime_type(Fetch::Infrastructure::extract_mime_type(response.header_list()))+ , m_response_header_list(response.header_list()){}@@ -180,6 +184,20 @@ void IncrementalDocumentParser::process_body_chunk(ByteBuffer bytes)m_input_bytes.append(bytes);feed_parser();+ process_link_headers_after_first_task();+}++void IncrementalDocumentParser::process_link_headers_after_first_task()+{+ if (!m_response_header_list)+ return;++ // https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-html+ // The first task that the networking task source places on the task queue while fetching runs must process link+ // headers given document, navigationParams's response, and "media", after the task has been processed by the HTML+ // parser.+ auto response_header_list = m_response_header_list.release_nonnull();+ HTMLLinkElement::process_link_headers(m_document, response_header_list, m_url, HTMLLinkElement::LinkHeaderPhase::Media);}static size_t encoding_independent_prefix_length(ReadonlyBytes bytes)@@ -262,6 +280,7 @@ void IncrementalDocumentParser::process_end_of_body()// Bytes held back for a still-possible encoding declaration are fed first; the implied EOF character waits for// them in finish_body().feed_parser();+ process_link_headers_after_first_task();}void IncrementalDocumentParser::finish_body()@@ -393,7 +412,6 @@ void IncrementalDocumentParser::pump()if (m_parser->stopped())return;- // FIXME: Process link headers (read-html step 3, third paragraph) after the first parser pass.if (m_parser->tokenizer().is_input_stream_closed()) {m_parser->run_until_completion();return;diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.h b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.hindex a966bcb5f51..fe24111629c 100644--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.h+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.h@@ -12,6 +12,7 @@#include <AK/OwnPtr.h>#include <AK/Utf16StringBuilder.h>#include <AK/Utf16View.h>+#include <LibHTTP/Forward.h>#include <LibJS/Heap/Cell.h>#include <LibTextCodec/Decoder.h>#include <LibURL/URL.h>@@ -27,13 +28,13 @@ class WEB_API IncrementalDocumentParser final : public JS::Cell {GC_DECLARE_ALLOCATOR(IncrementalDocumentParser);public:- static GC::Ref<IncrementalDocumentParser> create(GC::Ref<DOM::Document>, GC::Ref<Fetch::Infrastructure::Body>, URL::URL, Optional<MimeSniff::MimeType>);+ static GC::Ref<IncrementalDocumentParser> create(GC::Ref<DOM::Document>, Fetch::Infrastructure::Response const&);void start();void set_allow_declarative_shadow_roots(HTMLParser::AllowDeclarativeShadowRoots);private:- IncrementalDocumentParser(GC::Ref<DOM::Document>, GC::Ref<Fetch::Infrastructure::Body>, URL::URL, Optional<MimeSniff::MimeType>);+ IncrementalDocumentParser(GC::Ref<DOM::Document>, Fetch::Infrastructure::Response const&);virtual void visit_edges(Cell::Visitor&) override;@@ -42,6 +43,7 @@ private:void process_body_chunk(ByteBuffer);void process_end_of_body();void process_body_error(JS::Value);+ void process_link_headers_after_first_task();ErrorOr<bool> change_encoding(StringView);void feed_parser();@@ -61,6 +63,7 @@ private:GC::Ptr<Fetch::Infrastructure::Body> m_body;URL::URL m_url;Optional<MimeSniff::MimeType> m_mime_type;+ RefPtr<HTTP::HeaderList> m_response_header_list;HTMLParser::AllowDeclarativeShadowRoots m_allow_declarative_shadow_roots { HTMLParser::AllowDeclarativeShadowRoots::Yes };GC::Ptr<HTMLParser> m_parser;diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex b997c7bca14..09b2b66bf6c 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -633,6 +633,12 @@ Text/input/wpt-import/streams/transferable/audioworklet.https.htmlText/input/wpt-import/preload/prefetch-load-event.htmlText/input/wpt-import/preload/prefetch-events.htmlText/input/HTML/link-preload-image-source-set.html+Text/input/wpt-import/preload/link-header-modulepreload.html+Text/input/wpt-import/preload/link-header-preload-non-html.html+Text/input/wpt-import/preload/link-header-preload-nonce.html+Text/input/HTML/link-header-parsing.html+Text/input/HTML/link-header-image-source-set.html+Text/input/HTML/link-header-media-document.htmlText/input/wpt-import/resource-timing/initiator-type/img.htmlText/input/wpt-import/resource-timing/initiator-type/img-srcset.htmlText/input/wpt-import/resource-timing/initiator-type/picture.htmldiff --git a/Tests/LibWeb/Text/data/link-header-parsing.js b/Tests/LibWeb/Text/data/link-header-parsing.jsnew file mode 100644index 00000000000..cb0ff5c3b54--- /dev/null+++ b/Tests/LibWeb/Text/data/link-header-parsing.js@@ -0,0 +1 @@+export {};diff --git a/Tests/LibWeb/Text/data/link-header-parsing.xhtml b/Tests/LibWeb/Text/data/link-header-parsing.xhtmlnew file mode 100644index 00000000000..ddf13fabe8f--- /dev/null+++ b/Tests/LibWeb/Text/data/link-header-parsing.xhtml@@ -0,0 +1,4 @@+<html xmlns="http://www.w3.org/1999/xhtml">+<head><base href="elsewhere/"/></head>+<body></body>+</html>diff --git a/Tests/LibWeb/Text/data/link-header-parsing.xhtml.headers b/Tests/LibWeb/Text/data/link-header-parsing.xhtml.headersnew file mode 100644index 00000000000..9a7de9061eb--- /dev/null+++ b/Tests/LibWeb/Text/data/link-header-parsing.xhtml.headers@@ -0,0 +1,3 @@+Link: <link-header-parsing.js?a,b>; rel=modulepreload+Link: <link-header-parsing.js?anchored>; rel=modulepreload; anchor="other.xhtml"+Link: <link-header-parsing.js?media>; rel=modulepreload; media="all"diff --git a/Tests/LibWeb/Text/expected/HTML/link-header-image-source-set.txt b/Tests/LibWeb/Text/expected/HTML/link-header-image-source-set.txtnew file mode 100644index 00000000000..4a1135ab2cd--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/link-header-image-source-set.txt@@ -0,0 +1,5 @@+w-fallback: not requested+w-small: requested+w-large: not requested+x-fallback: not requested+x-one: requesteddiff --git a/Tests/LibWeb/Text/expected/HTML/link-header-media-document.txt b/Tests/LibWeb/Text/expected/HTML/link-header-media-document.txtnew file mode 100644index 00000000000..48b3d62dcb1--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/link-header-media-document.txt@@ -0,0 +1,2 @@+wide: requested+narrow: not requesteddiff --git a/Tests/LibWeb/Text/expected/HTML/link-header-media.txt b/Tests/LibWeb/Text/expected/HTML/link-header-media.txtnew file mode 100644index 00000000000..744c8b5318c--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/link-header-media.txt@@ -0,0 +1,2 @@+media="all": 1+media="not all": 0diff --git a/Tests/LibWeb/Text/expected/HTML/link-header-parsing.txt b/Tests/LibWeb/Text/expected/HTML/link-header-parsing.txtnew file mode 100644index 00000000000..df38894464e--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/link-header-parsing.txt@@ -0,0 +1,2 @@+link-header-parsing.js?a,b+link-header-parsing.js?mediadiff --git a/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-modulepreload.txt b/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-modulepreload.txtnew file mode 100644index 00000000000..ed9dcf9c327--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-modulepreload.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass test that a header-preloaded module is loaded and consumed\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-preload-non-html.txt b/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-preload-non-html.txtnew file mode 100644index 00000000000..9c54e10ae12--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-preload-non-html.txt@@ -0,0 +1,10 @@+Harness status: OK++Found 5 tests++5 Pass+Pass XHTML documents should respect preload Link headers+Pass plain text documents should respect preload Link headers+Pass image documents should respect preload Link headers+Pass media documents should respect preload Link headers+Pass invalid image documents should respect preload Link headers\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-preload-nonce.txt b/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-preload-nonce.txtnew file mode 100644index 00000000000..097b08c1c92--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/preload/link-header-preload-nonce.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass without nonce+Pass with nonce\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/HTML/link-header-image-source-set.html b/Tests/LibWeb/Text/input/HTML/link-header-image-source-set.htmlnew file mode 100644index 00000000000..ca38d10120a--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-header-image-source-set.html@@ -0,0 +1,32 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const names = ["w-fallback", "w-small", "w-large", "x-fallback", "x-one"];+ const urls = {};+ for (const name of names)+ urls[name] = await server.createEcho("GET", `/link-header-image-source-set/${name}.png`, { status: 200, headers: { "Content-Type": "image/png" } });++ const page = await server.createEcho("GET", "/link-header-image-source-set/page.xhtml", {+ status: 200,+ headers: {+ "Content-Type": "application/xhtml+xml",+ "Link": '<w-fallback.png>; rel=preload; as=image; imagesrcset="w-small.png 200w, w-large.png 800w"; imagesizes="100px", '+ + '<x-fallback.png>; rel=preload; as=image; imagesrcset="x-one.png 1x"',+ },+ body: '<html xmlns="http://www.w3.org/1999/xhtml"><head><base href="elsewhere/"/></head><body/></html>',+ });++ const iframe = document.createElement("iframe");+ iframe.src = page;+ document.body.appendChild(iframe);++ const isRequested = async url => (await fetch(server.recordedRequestHeadersURL(url))).ok;+ while (!await isRequested(urls["w-small"]) || !await isRequested(urls["x-one"]))+ await timeout(25);++ for (const name of names)+ println(`${name}: ${await isRequested(urls[name]) ? "requested" : "not requested"}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/link-header-media-document.html b/Tests/LibWeb/Text/input/HTML/link-header-media-document.htmlnew file mode 100644index 00000000000..14bc920dcd3--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-header-media-document.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const urls = {};+ for (const name of ["wide", "narrow"])+ urls[name] = await server.createEcho("GET", `/link-header-media-document/${name}.js`, { status: 200, headers: { "Content-Type": "text/javascript" } });++ const page = await server.createEcho("GET", "/link-header-media-document/image.png", {+ status: 200,+ headers: {+ "Content-Type": "image/png",+ "Link": '<wide.js>; rel=preload; as=script; media="(min-width: 1px)", '+ + '<narrow.js>; rel=preload; as=script; media="(max-width: 0px)"',+ },+ body: "",+ });++ const iframe = document.createElement("iframe");+ document.body.appendChild(iframe);+ // Wait for the iframe to be rendered, so that it has a viewport size.+ await animationFrame();+ iframe.src = page;++ const isRequested = async url => (await fetch(server.recordedRequestHeadersURL(url))).ok;+ while (!await isRequested(urls["wide"]))+ await timeout(25);++ for (const name of ["wide", "narrow"])+ println(`${name}: ${await isRequested(urls[name]) ? "requested" : "not requested"}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/link-header-media.html b/Tests/LibWeb/Text/input/HTML/link-header-media.htmlnew file mode 100644index 00000000000..52c3350c73e--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-header-media.html@@ -0,0 +1,18 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const matching = new URL("link-header-media.js?all", location.href).href;+ const notMatching = new URL("link-header-media.js?not-all", location.href).href;+ await new Promise(resolve => {+ new PerformanceObserver((list, observer) => {+ if (list.getEntriesByName(matching).length === 0)+ return;+ observer.disconnect();+ resolve();+ }).observe({ type: "resource", buffered: true });+ });+ println(`media="all": ${performance.getEntriesByName(matching).length}`);+ println(`media="not all": ${performance.getEntriesByName(notMatching).length}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/link-header-media.html.headers b/Tests/LibWeb/Text/input/HTML/link-header-media.html.headersnew file mode 100644index 00000000000..81c4b10842f--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-header-media.html.headers@@ -0,0 +1,2 @@+Link: <link-header-media.js?all>; rel=modulepreload; media="all"+Link: <link-header-media.js?not-all>; rel=modulepreload; media="not all"diff --git a/Tests/LibWeb/Text/input/HTML/link-header-media.js b/Tests/LibWeb/Text/input/HTML/link-header-media.jsnew file mode 100644index 00000000000..cb0ff5c3b54--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-header-media.js@@ -0,0 +1 @@+export {};diff --git a/Tests/LibWeb/Text/input/HTML/link-header-parsing.html b/Tests/LibWeb/Text/input/HTML/link-header-parsing.htmlnew file mode 100644index 00000000000..eafd30dc30c--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-header-parsing.html@@ -0,0 +1,27 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const iframe = document.createElement("iframe");+ iframe.src = "../../data/link-header-parsing.xhtml";+ await new Promise(resolve => {+ iframe.onload = resolve;+ document.body.appendChild(iframe);+ });++ const frameWindow = iframe.contentWindow;+ const names = await new Promise(resolve => {+ new frameWindow.PerformanceObserver((list, observer) => {+ const names = frameWindow.performance.getEntriesByType("resource").map(entry => entry.name).filter(name => name.includes("link-header-parsing.js"));+ if (names.length < 2)+ return;+ observer.disconnect();+ resolve(names);+ }).observe({ type: "resource", buffered: true });+ });++ const directory = new URL(".", frameWindow.location.href).href;+ for (const name of names.sort())+ println(name.substring(directory.length));+ });+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/document-metadata/the-link-element/stylesheet.py b/Tests/LibWeb/Text/input/wpt-import/html/semantics/document-metadata/the-link-element/stylesheet.pynew file mode 100644index 00000000000..241b5eee9ae--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/document-metadata/the-link-element/stylesheet.py@@ -0,0 +1,11 @@+def main(request, response):+ try:+ count = int(request.server.stash.take(request.GET[b"id"]))+ except:+ count = 0++ if b"count" in request.GET:+ return str(count)+ request.server.stash.put(request.GET[b"id"], str(count + 1))+ headers = [(b"Content-Type", b"text/css")]+ return 200, headers, u'body {color: red;}'diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/link-header-modulepreload.html b/Tests/LibWeb/Text/input/wpt-import/preload/link-header-modulepreload.htmlnew file mode 100644index 00000000000..2a758f124a7--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/link-header-modulepreload.html@@ -0,0 +1,30 @@+<!DOCTYPE html>+<meta charset=utf-8>+<title>Makes sure that Link headers support modulepreload</title>+<meta name="timeout" content="long">+<script src="../common/utils.js"></script>+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>+<script src="../preload/resources/preload_helper.js"></script>+<body>+<script>+ promise_test(async t => {+ const id = token();+ const moduleLink = getAbsoluteURL('./resources/module1.js');+ const params = new URLSearchParams();+ params.set('link', `<${moduleLink}>;rel=modulepreload`);+ params.set('type', 'text/html');+ params.set('file', 'modulepreload-iframe.html')+ const docURL = getAbsoluteURL(`./resources/echo-preload-header.py?${params.toString()}`);+ const iframe = document.createElement('iframe');+ t.add_cleanup(() => iframe.remove());+ iframe.src = docURL;+ const messageReceived = new Promise(resolve => window.addEventListener('message', m => {+ resolve(m.data);+ }))+ document.body.appendChild(iframe);+ const result = await messageReceived;+ assert_equals(result, 1);+ }, 'test that a header-preloaded module is loaded and consumed');+</script>+</body>diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/link-header-preload-non-html.html b/Tests/LibWeb/Text/input/wpt-import/preload/link-header-preload-non-html.htmlnew file mode 100644index 00000000000..e172bc95d4b--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/link-header-preload-non-html.html@@ -0,0 +1,59 @@+<!DOCTYPE html>+<meta charset=utf-8>+<title>Makes sure that Link headers preload resources in non-HTML documents</title>+<meta name="timeout" content="long">+<script src="resources/dummy.js?link-header-preload2"></script>+<script src="../common/utils.js"></script>+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>+<script src="../preload/resources/preload_helper.js"></script>+<body>+<script>++ function test_document_type(options, desc) {+ promise_test(async t => {+ const id = token();+ const preloadLink = `/html/semantics/document-metadata/the-link-element/stylesheet.py?id=${id}`;+ const params = new URLSearchParams();+ for (const opt in options)+ params.set(opt, options[opt]);+ params.set('link', `<${preloadLink}>;rel=preload;as=style`);++ const docURL = getAbsoluteURL(`./resources/echo-preload-header.py?${params.toString()}`);+ const iframe = document.createElement('iframe');+ t.add_cleanup(() => iframe.remove());+ iframe.src = docURL;+ document.body.appendChild(iframe);+ await new Promise(resolve => iframe.addEventListener('load', resolve));+ const timeout = 5000;+ const interval = 25;+ let count = 0;+ const before = performance.now();++ while (performance.now() < before + timeout) {+ // count=true returns the number of times the resource was accessed+ const res = await fetch(preloadLink + '&count=true');++ // If count is positive, the resource was accessed.+ count = Number(await res.text());+ if (count > 0)+ break;++ await new Promise(resolve => t.step_timeout(resolve, interval));+ }++ assert_equals(count, 1, "verify that request was issued exactly once");+ }, `${desc} documents should respect preload Link headers`);+ }++ test_document_type({+ type: 'application/xml',+ content: `<?xml version="1.0" encoding="utf-8"?>+ <html xmlns="http://www.w3.org/1999/xhtml">+ </html>`}, "XHTML");+ test_document_type({content: 'Hello', type: 'text/plain'}, 'plain text');+ test_document_type({file: 'square.png', type: 'image/png'}, 'image');+ test_document_type({file: 'white.mp4', type: 'video/mp4'}, 'media');+ test_document_type({content: 'dummy', type: 'image/png'}, 'invalid image');+</script>+</body>diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/link-header-preload-nonce.html b/Tests/LibWeb/Text/input/wpt-import/preload/link-header-preload-nonce.htmlnew file mode 100644index 00000000000..78a93cf1cc8--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/link-header-preload-nonce.html@@ -0,0 +1,53 @@+<!DOCTYPE html>+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>+<script src="../common/utils.js"></script>+<script src="../preload/resources/preload_helper.js"></script>+<body>+<script>++async_test(t => {+ const id = token();+ const pageUrl =+ '/common/blank.html?pipe=' ++ '|header(content-security-policy, script-src \'nonce-abc\')' ++ `|header(link, <${encodedStashPutUrl(id)}>;rel=preload;as=script)`;++ const w = window.open(pageUrl);+ t.add_cleanup(() => w.close());++ step_timeout(async () => {+ try {+ const arrived = await hasArrivedAtServer(id);+ assert_false(arrived, 'The preload should be blocked.');+ t.done();+ } catch (e) {+ t.step(() => {throw e;});+ }+ }, 3000);+}, 'without nonce');++async_test(t => {+ const id = token();+ const pageUrl =+ '/common/blank.html?pipe=' ++ '|header(content-security-policy, script-src \'nonce-az\')' ++ `|header(link, <${encodedStashPutUrl(id)}>;rel=preload;as=script;nonce=az)`;+ const w = window.open(pageUrl);+ t.add_cleanup(() => w.close());++ // TODO: Use step_wait after+ // https://github.com/web-platform-tests/wpt/pull/34289 is merged.+ step_timeout(async () => {+ try {+ const arrived = await hasArrivedAtServer(id);+ assert_true(arrived, 'The preload should have arrived at the server.');+ t.done();+ } catch (e) {+ t.step(() => {throw e;});+ }+ }, 3000);+}, 'with nonce');++</script>+</body>diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/dummy.js b/Tests/LibWeb/Text/input/wpt-import/preload/resources/dummy.jsnew file mode 100644index 00000000000..cfcb9d89a1c--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/dummy.js@@ -0,0 +1 @@+// This is example JS content. Nothing to see here.diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/echo-preload-header.py b/Tests/LibWeb/Text/input/wpt-import/preload/resources/echo-preload-header.pynew file mode 100644index 00000000000..de9551409dc--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/echo-preload-header.py@@ -0,0 +1,34 @@+import os+from wptserve.utils import isomorphic_encode++def main(request, response):+ response.headers.set(b"Content-Type", request.GET.first(b"type"))+ link = request.GET.first(b"link")+ response.headers.set(b"Access-Control-Allow-Origin", b"*")+ response.headers.set(b"Access-Control-Allow-Credentials", b"true")+ if link is not None:+ response.headers.set(b"Link", link)++ if b"file" in request.GET:+ base_dir = os.path.realpath(os.path.dirname(isomorphic_encode(__file__)))+ target_file = request.GET.first(b"file")+ path = os.path.realpath(os.path.join(base_dir, target_file))++ try:+ if os.path.commonpath([base_dir, path]) != base_dir:+ raise ValueError("Path traversal attempt detected.")+ except ValueError:+ # A ValueError is expected in two scenarios:+ # 1) os.path.commonpath raises it if paths are on different drives+ # (e.g., on Windows).+ # 2) We explicitly raise it when a path traversal attempt is detected.+ response.status = 403+ return b"Forbidden"++ try:+ response.content = open(path, mode='rb').read()+ except IOError:+ response.status = 404+ return b"Not found"+ else:+ return request.GET.first(b"content")diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/module1.js b/Tests/LibWeb/Text/input/wpt-import/preload/resources/module1.jsnew file mode 100644index 00000000000..ebaeae7ac7b--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/module1.js@@ -0,0 +1,2 @@+import { y } from './module2.js';+export let x = y + 1;\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/module2.js b/Tests/LibWeb/Text/input/wpt-import/preload/resources/module2.jsnew file mode 100644index 00000000000..e4e3217b8c1--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/module2.js@@ -0,0 +1 @@+export let y = 1;diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/modulepreload-iframe.html b/Tests/LibWeb/Text/input/wpt-import/preload/resources/modulepreload-iframe.htmlnew file mode 100644index 00000000000..1d3d21f4d95--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/modulepreload-iframe.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<body>+ <script>+ const m = new URL('module1.js', location.href).toString();+ const observer = new PerformanceObserver(l => {+ const entries = l.getEntriesByName(m);+ if (entries.length === 1) {+ import(m).then(() => {+ observer.disconnect();+ const all = performance.getEntriesByName(m);+ window.parent.postMessage(all.length, '*');+ });+ }+ });++ observer.observe({type: 'resource', buffered: true});+++ </script>+</body>\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/preload_helper.js b/Tests/LibWeb/Text/input/wpt-import/preload/resources/preload_helper.jsnew file mode 100644index 00000000000..5b7a6eb52ba--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/preload_helper.js@@ -0,0 +1,60 @@+function stashPutUrl(token) {+ return `/preload/resources/stash-put.py?key=${token}`;+}++function encodedStashPutUrl(token) {+ return encodeURIComponent(stashPutUrl(token));+}++async function hasArrivedAtServer(token) {+ const res = await fetch(`/preload/resources/stash-take.py?key=${token}`);+ assert_true(res.status === 200 || res.status === 404,+ 'status must be either 200 or 404');+ return res.status === 200;+}++function verifyPreloadAndRTSupport()+{+ var link = window.document.createElement("link");+ assert_true(link.relList && link.relList.supports("preload"), "Preload not supported");+ assert_true(!!window.PerformanceResourceTiming, "ResourceTiming not supported");+}++function getAbsoluteURL(url)+{+ return new URL(url, location.href).href;+}++function verifyNumberOfResourceTimingEntries(url, number)+{+ assert_equals(numberOfResourceTimingEntries(url), number, url);+}++function numberOfResourceTimingEntries(url)+{+ return performance.getEntriesByName(getAbsoluteURL(url)).length;+}++// Verifies that the resource is loaded, but not downloaded from network+// more than once. This can be used to verify that a preloaded resource is+// not downloaded again when used.+function verifyLoadedAndNoDoubleDownload(url) {+ var entries = performance.getEntriesByName(getAbsoluteURL(url));+ // UA may create separate RT entries for preload and normal load,+ // so we just check (entries.length > 0).+ assert_greater_than(entries.length, 0, url + ' should be loaded');++ var numDownloads = 0;+ entries.forEach(entry => {+ // transferSize is zero if the resource is loaded from cache.+ if (entry.transferSize > 0) {+ numDownloads++;+ }+ });+ // numDownloads can be zero if the resource was already cached before running+ // the test (for example, when the test is running repeatedly without+ // clearing cache between runs).+ assert_less_than_equal(+ numDownloads, 1,+ url + ' should be downloaded from network at most once');+}diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/square.png b/Tests/LibWeb/Text/input/wpt-import/preload/resources/square.pngnew file mode 100644index 00000000000..01c9666a8deBinary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/preload/resources/square.png differdiff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/stash-put.py b/Tests/LibWeb/Text/input/wpt-import/preload/resources/stash-put.pynew file mode 100644index 00000000000..f4bc87940ec--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/stash-put.py@@ -0,0 +1,20 @@+from wptserve.utils import isomorphic_decode++def main(request, response):+ if request.method == u'OPTIONS':+ # CORS preflight+ response.headers.set(b'Access-Control-Allow-Origin', b'*')+ response.headers.set(b'Access-Control-Allow-Methods', b'*')+ response.headers.set(b'Access-Control-Allow-Headers', b'*')+ return 'done'++ url_dir = u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/'+ key = request.GET.first(b"key")+ if b"value" in request.GET:+ value = request.GET.first(b"value")+ else:+ value = b"value"+ # value here must be a text string. It will be json.dump()'ed in stash-take.py.+ request.server.stash.put(key, isomorphic_decode(value), url_dir)+ response.headers.set(b'Access-Control-Allow-Origin', b'*')+ return "done"diff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/stash-take.py b/Tests/LibWeb/Text/input/wpt-import/preload/resources/stash-take.pynew file mode 100644index 00000000000..9977197cae5--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/preload/resources/stash-take.py@@ -0,0 +1,14 @@+from wptserve.handlers import json_handler+++@json_handler+def main(request, response):+ dir = u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/'+ key = request.GET.first(b"key")+ response.headers.set(b'Access-Control-Allow-Origin', b'*')+ value = request.server.stash.take(key, dir)+ if value is None:+ response.status = 404+ return 'No entry is found'+ response.status = 200+ return valuediff --git a/Tests/LibWeb/Text/input/wpt-import/preload/resources/white.mp4 b/Tests/LibWeb/Text/input/wpt-import/preload/resources/white.mp4new file mode 100644index 00000000000..ef609e42813Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/preload/resources/white.mp4 differ