Truly independent web browser
LibWeb: Look for a page’s meta charset past its first 1024 bytes
sideshowbarker0259d76775b8
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cppindex 682af4c797a..9b1e33f6feb 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp@@ -17,6 +17,7 @@#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>#include <LibWeb/HTML/Parser/RustFFI.h>+#include <LibWeb/HTMLTokenizerRustFFI.h>#include <LibWebCommon/Infra/CharacterTypes.h>namespace Web::HTML {@@ -366,6 +367,29 @@ Optional<ByteString> get_an_xml_encoding(ReadonlyBytes input)return *encoding;}+// https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding+// Step 2 of the prescan algorithm.+Optional<ByteString> prescan_for_utf16_xml_declaration(ReadonlyBytes input)+{+ // 2. Prescan for UTF-16 XML declarations: If position points to:+ if (input.size() < 6)+ return {};++ // * A sequence of bytes starting with: 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0 (case-sensitive UTF-16 little-endian '<?x')+ // Return UTF-16LE.+ if (input.slice(0, 6) == Array<u8, 6> { 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0 })+ return "utf-16le";++ // * A sequence of bytes starting with: 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78 (case-sensitive UTF-16 big-endian '<?x')+ // Return UTF-16BE.+ if (input.slice(0, 6) == Array<u8, 6> { 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78 })+ return "utf-16be";++ // NOTE: For historical reasons, the prefix is two bytes longer than in Appendix F of XML and the encoding name is+ // not checked.+ return {};+}+// https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encodingstatic Optional<ByteString> run_prescan_byte_stream_algorithm_steps(DOM::Document& document, ReadonlyBytes input){@@ -373,20 +397,8 @@ static Optional<ByteString> run_prescan_byte_stream_algorithm_steps(DOM::Documensize_t position = 0;// 2. Prescan for UTF-16 XML declarations: If position points to:- if (!prescan_should_abort(input, position + 5)) {- // * A sequence of bytes starting with: 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0 (case-sensitive UTF-16 little-endian '<?x')- // Return UTF-16LE.- if (input.slice(position, 6) == Array<u8, 6> { 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0 })- return "utf-16le";-- // * A sequence of bytes starting with: 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78 (case-sensitive UTF-16 big-endian '<?x')- // Return UTF-16BE.- if (input.slice(position, 6) == Array<u8, 6> { 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78 })- return "utf-16be";- }-- // NOTE: For historical reasons, the prefix is two bytes longer than in Appendix F of XML and the encoding name is- // not checked.+ if (auto encoding = prescan_for_utf16_xml_declaration(input); encoding.has_value())+ return encoding;// 3. Loop: If position points to:while (!prescan_should_abort(input, position)) {@@ -595,13 +607,50 @@ ByteString extract_tld_hint(URL::URL const& url)return tld_label.is_empty() ? ByteString {} : ByteString { tld_label };}-// https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding-EncodingSniffingResult run_encoding_sniffing_algorithm(DOM::Document& document, ReadonlyBytes input, Optional<MimeSniff::MimeType> maybe_mime_type, GC::Ptr<DOM::Document> loading_container_document)+EncodingDeclarationPrescan::EncodingDeclarationPrescan(bool scripting_enabled)+ : m_scanner(rust_html_meta_charset_scanner_create(scripting_enabled))+{+}++EncodingDeclarationPrescan::~EncodingDeclarationPrescan()+{+ rust_html_meta_charset_scanner_destroy(m_scanner);+}++EncodingDeclarationPrescan::Result EncodingDeclarationPrescan::scan(ReadonlyBytes bytes, bool input_complete)+{+ auto result = rust_html_meta_charset_scanner_scan(m_scanner, bytes, input_complete, &m_encoding,+ [](void* context, u8 const* value, size_t value_length, bool is_content) {+ StringView value_view { value, value_length };+ auto& encoding = *static_cast<Optional<StringView>*>(context);+ encoding = is_content ? extract_character_encoding_from_meta_element(ByteString { value_view }) : TextCodec::get_standardized_encoding(value_view);+ return encoding.has_value();+ });++ switch (result) {+ case RustFfiMetaCharsetScanResult::NeedMoreInput:+ return Result::NeedMoreInput;+ case RustFfiMetaCharsetScanResult::Found:+ // https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding+ // If charset is UTF-16BE/LE, then set charset to UTF-8.+ // If charset is x-user-defined, then set charset to windows-1252.+ if (m_encoding->is_one_of("UTF-16BE"sv, "UTF-16LE"sv))+ m_encoding = "UTF-8"sv;+ else if (*m_encoding == "x-user-defined"sv)+ m_encoding = "windows-1252"sv;+ return Result::Found;+ case RustFfiMetaCharsetScanResult::NotFound:+ return Result::NotFound;+ }+ VERIFY_NOT_REACHED();+}++Optional<EncodingSniffingResult> sniff_encoding_before_prescan(ReadonlyBytes input, Optional<MimeSniff::MimeType> const& maybe_mime_type){// 1. If the result of BOM sniffing is an encoding, return that encoding with confidence certain.auto bom = run_bom_sniff(input);if (bom.has_value())- return { bom.release_value(), EncodingConfidence::Certain };+ return EncodingSniffingResult { bom.release_value(), EncodingConfidence::Certain };// 2. FIXME: If the user has explicitly instructed the user agent to override the document's character encoding with a specific encoding,// optionally return that encoding with the confidence certain.@@ -615,16 +664,42 @@ EncodingSniffingResult run_encoding_sniffing_algorithm(DOM::Document& document,// FIXME: This is awkward because lecacy_extract_an_encoding can not failauto maybe_transport_encoding = Fetch::Infrastructure::legacy_extract_an_encoding(maybe_mime_type, "invalid"sv);if (maybe_transport_encoding != "invalid"sv)- return { maybe_transport_encoding, EncodingConfidence::Certain };+ return EncodingSniffingResult { maybe_transport_encoding, EncodingConfidence::Certain };}+ // 5. Optionally, prescan the byte stream to determine its encoding, ...+ // AD-HOC: Of the prescan algorithm, only its check for a UTF-16 XML declaration runs here. See+ // EncodingDeclarationPrescan for the rest.+ if (auto encoding = prescan_for_utf16_xml_declaration(input); encoding.has_value())+ return EncodingSniffingResult { encoding.release_value(), EncodingConfidence::Tentative };++ return {};+}++// https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding+EncodingSniffingResult run_encoding_sniffing_algorithm(DOM::Document& document, ReadonlyBytes input, Optional<MimeSniff::MimeType> maybe_mime_type, GC::Ptr<DOM::Document> loading_container_document)+{+ if (auto result = sniff_encoding_before_prescan(input, maybe_mime_type); result.has_value())+ return result.release_value();+// 5. Optionally, prescan the byte stream to determine its encoding, with the end condition being when the user agent decides that scanning further bytes would not// be efficient. User agents are encouraged to only prescan the first 1024 bytes. User agents may decide that scanning any bytes is not efficient, in which case// these substeps are entirely skipped.// The aforementioned algorithm returns either a character encoding or failure. If it returns a character encoding, then return the same encoding, with confidence tentative.- auto prescan = run_prescan_byte_stream_algorithm(document, input);- if (prescan.has_value())- return { prescan.release_value(), EncodingConfidence::Tentative };+ // AD-HOC: Find the declaration by tokenizing the bytes as the HTML parser will, as proposed in+ // https://github.com/whatwg/html/issues/6962, rather than with the prescan algorithm.+ EncodingDeclarationPrescan prescan { document.is_scripting_enabled() };+ if (prescan.scan(input, true) == EncodingDeclarationPrescan::Result::Found)+ return { ByteString { prescan.encoding() }, EncodingConfidence::Tentative };++ return sniff_encoding_after_prescan(document, input, loading_container_document);+}++EncodingSniffingResult sniff_encoding_after_prescan(DOM::Document& document, ReadonlyBytes input, GC::Ptr<DOM::Document> loading_container_document)+{+ // AD-HOC: The prescan algorithm gets an XML encoding when it finds no declaration, so do that here.+ if (auto xml_encoding = get_an_xml_encoding(input); xml_encoding.has_value())+ return { xml_encoding.release_value(), EncodingConfidence::Tentative };// 6. If the HTML parser for which this algorithm is being run is associated with a Document d whose container document is non-null, then:auto parent_document = loading_container_document ? loading_container_document : document.container_document();diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.hindex b88b7ce0bb0..dc8b341441b 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h@@ -8,12 +8,15 @@#pragma once#include <AK/ByteString.h>+#include <AK/Noncopyable.h>#include <AK/Optional.h>#include <LibGC/Ptr.h>#include <LibURL/URL.h>#include <LibWeb/Forward.h>#include <LibWebCommon/MimeSniff/MimeType.h>+struct MetaCharsetScanner;+namespace Web::HTML {enum class EncodingConfidence : u8 {@@ -30,6 +33,7 @@ struct EncodingSniffingResult {Optional<StringView> extract_character_encoding_from_meta_element(ByteString const&);GC::Ptr<DOM::Attr> prescan_get_attribute(DOM::Document&, ReadonlyBytes input, size_t& position);Optional<ByteString> run_prescan_byte_stream_algorithm(DOM::Document&, ReadonlyBytes input);+Optional<ByteString> prescan_for_utf16_xml_declaration(ReadonlyBytes input);Optional<ByteString> run_bom_sniff(ReadonlyBytes input);Optional<ByteString> get_an_xml_encoding(ReadonlyBytes input);@@ -38,10 +42,46 @@ Optional<ByteString> get_an_xml_encoding(ReadonlyBytes input);// an absent/empty TLD as equivalent to ".com".ByteString extract_tld_hint(URL::URL const&);+// Finds a document's encoding declaration by tokenizing its bytes as the HTML parser will: the prescan proposed in+// https://github.com/whatwg/html/issues/6962. It looks through the first 1024 bytes, and past them for as long as the+// document's head can still hold a declaration.+class EncodingDeclarationPrescan {+ AK_MAKE_NONCOPYABLE(EncodingDeclarationPrescan);+ AK_MAKE_NONMOVABLE(EncodingDeclarationPrescan);+ AK_ALLOC_WITH_KMALLOC;++public:+ explicit EncodingDeclarationPrescan(bool scripting_enabled);+ ~EncodingDeclarationPrescan();++ enum class Result : u8 {+ NeedMoreInput,+ Found,+ NotFound,+ };++ // Scans the bytes that arrived since the last call.+ Result scan(ReadonlyBytes, bool input_complete);++ // The encoding the declaration names, once scan() has found one.+ StringView encoding() const { return m_encoding.value(); }++private:+ MetaCharsetScanner* m_scanner { nullptr };+ Optional<StringView> m_encoding;+};+// NB: A document that is being loaded by a navigation has no node navigable until it is activated, which can happen// after its parser starts. Pass the container document of the navigable that the document is being loaded into as// loading_container_document in that case.EncodingSniffingResult run_encoding_sniffing_algorithm(DOM::Document&, ReadonlyBytes input,Optional<MimeSniff::MimeType> maybe_mime_type = {}, GC::Ptr<DOM::Document> loading_container_document = {});+// The steps of the encoding sniffing algorithm before its prescan looks for a declaration: the BOM, the transport layer,+// and the prescan's check for a UTF-16 XML declaration.+Optional<EncodingSniffingResult> sniff_encoding_before_prescan(ReadonlyBytes input, Optional<MimeSniff::MimeType> const&);++// The steps of the encoding sniffing algorithm after its prescan, for when the prescan finds no declaration.+EncodingSniffingResult sniff_encoding_after_prescan(DOM::Document&, ReadonlyBytes input, GC::Ptr<DOM::Document> loading_container_document);+}diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.h b/Libraries/LibWeb/HTML/Parser/HTMLParser.hindex aa3ec2109f4..151442ec30f 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.h+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.h@@ -83,6 +83,7 @@ public:HTMLTokenizer& tokenizer() { return m_tokenizer; }bool streaming_body_is_exhausted() const { return m_streaming_body_is_exhausted; }void did_exhaust_streaming_body(Badge<IncrementalDocumentParser>) { m_streaming_body_is_exhausted = true; }+ void set_encoding_confidence(Badge<IncrementalDocumentParser>, EncodingConfidence confidence) { m_encoding_confidence = confidence; }void set_allow_declarative_shadow_roots(AllowDeclarativeShadowRoots allow) { m_allow_declarative_shadow_roots = allow; }diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cppindex 04587fb731b..0cc0c0f7db6 100644--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp@@ -82,30 +82,11 @@ void IncrementalDocumentParser::initialize_parser(ReadonlyBytes sniff_bytes)if (m_parser)return;- // https://html.spec.whatwg.org/multipage/parsing.html#parsing-with-a-known-character-encoding- // https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding- Optional<StringView> standardized_encoding;- auto encoding_confidence = EncodingConfidence::Certain;- if (m_document->has_encoding()) {- standardized_encoding = TextCodec::get_standardized_encoding(m_document->encoding().value());- } else {- auto [encoding, confidence] = run_encoding_sniffing_algorithm(m_document, sniff_bytes, m_mime_type, m_container_document);- standardized_encoding = TextCodec::get_standardized_encoding(encoding);- encoding_confidence = confidence;- }- VERIFY(standardized_encoding.has_value());- dbgln_if(HTML_PARSER_DEBUG, "The incremental HTML parser selected encoding '{}'", standardized_encoding.value());-- m_decoder = make<TextCodec::StreamingDecoder>(standardized_encoding.value(), TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement);-- // https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding- // The document's character encoding must immediately be set to the value returned from this- // algorithm, at the same time as the user agent uses the returned value to select the decoder- // to use for the input byte stream.- m_document->set_encoding(utf16_string_from_standardized_encoding_label(standardized_encoding.value()));-m_document->set_url(m_url);- m_parser = HTMLParser::create_with_open_input_stream(m_document, encoding_confidence);++ // The parser exists while the prescan runs, so that aborting the document aborts it. Its encoding confidence is+ // set along with its encoding.+ m_parser = HTMLParser::create_with_open_input_stream(m_document, EncodingConfidence::Tentative);m_parser->set_change_encoding_callback(GC::create_function(GC::Heap::the(), [this](StringView encoding) {auto result = change_encoding(encoding);if (result.is_error()) {@@ -122,9 +103,55 @@ void IncrementalDocumentParser::initialize_parser(ReadonlyBytes sniff_bytes)}));m_parser->set_allow_declarative_shadow_roots(m_allow_declarative_shadow_roots);+ // https://html.spec.whatwg.org/multipage/parsing.html#parsing-with-a-known-character-encoding+ // https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding+ if (m_document->has_encoding()) {+ set_encoding(m_document->encoding()->to_byte_string(), EncodingConfidence::Certain);+ } else if (auto result = sniff_encoding_before_prescan(sniff_bytes, m_mime_type); result.has_value()) {+ set_encoding(result->encoding, result->confidence);+ } else {+ // The prescan can need bytes past the ones for sniffing, as far as the end of the head, so it reads them as+ // they arrive, and the parser gets them once it's done.+ m_sniff_bytes = MUST(ByteBuffer::copy(sniff_bytes));+ m_prescan = make<EncodingDeclarationPrescan>(m_document->is_scripting_enabled());+ }+start_incremental_read();}+void IncrementalDocumentParser::continue_prescan(bool input_complete)+{+ auto new_bytes = m_input_bytes.span().slice(m_prescanned_byte_count);+ m_prescanned_byte_count = m_input_bytes.size();++ auto result = m_prescan->scan(new_bytes, input_complete);+ if (result == EncodingDeclarationPrescan::Result::NeedMoreInput)+ return;++ auto [encoding, confidence] = result == EncodingDeclarationPrescan::Result::Found+ ? EncodingSniffingResult { ByteString { m_prescan->encoding() }, EncodingConfidence::Tentative }+ : sniff_encoding_after_prescan(m_document, m_sniff_bytes, m_container_document);+ m_prescan = nullptr;+ m_sniff_bytes = {};+ set_encoding(encoding, confidence);+}++void IncrementalDocumentParser::set_encoding(StringView encoding, EncodingConfidence encoding_confidence)+{+ auto standardized_encoding = TextCodec::get_standardized_encoding(encoding);+ VERIFY(standardized_encoding.has_value());+ dbgln_if(HTML_PARSER_DEBUG, "The incremental HTML parser selected encoding '{}'", standardized_encoding.value());++ m_decoder = make<TextCodec::StreamingDecoder>(standardized_encoding.value(), TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement);++ // https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding+ // The document's character encoding must immediately be set to the value returned from this+ // algorithm, at the same time as the user agent uses the returned value to select the decoder+ // to use for the input byte stream.+ m_document->set_encoding(utf16_string_from_standardized_encoding_label(standardized_encoding.value()));+ m_parser->set_encoding_confidence({}, encoding_confidence);+}+void IncrementalDocumentParser::start_incremental_read(){auto parser = GC::Ref { *this };@@ -188,6 +215,8 @@ void IncrementalDocumentParser::process_body_chunk(ByteBuffer bytes)elsem_input_bytes.append(bytes);+ if (m_prescan)+ continue_prescan(false);if (!m_has_queued_task_to_feed_parser)feed_parser();process_link_headers_after_first_task();@@ -237,6 +266,10 @@ void IncrementalDocumentParser::queue_task_to_feed_parser()void IncrementalDocumentParser::feed_parser(){+ // The parser gets no bytes until the prescan has found their encoding.+ if (m_prescan)+ return;+// NB: A document that arrives faster than we can parse it would otherwise keep the event loop for as long as that// takes. The first slices are short, so that the first rendering update has little to lay out. After those,// longer slices spare us laying out a document over and over while it is still growing.@@ -310,6 +343,9 @@ void IncrementalDocumentParser::process_end_of_body()return;}+ if (m_prescan)+ continue_prescan(true);+// Bytes held back for a still-possible encoding declaration are fed first; the implied EOF character waits for// them in finish_body().if (!m_has_queued_task_to_feed_parser)@@ -409,6 +445,10 @@ void IncrementalDocumentParser::process_body_error(JS::Value){m_body = nullptr;+ // The bytes received are all the prescan gets.+ if (m_prescan && should_continue())+ continue_prescan(true);+// Bytes withheld while the tokenizer was behind are still part of the document. This ends the parse, so no// declaration can still change how they decode: feed them to the tokenizer with the encoding as it stands.if (should_continue() && !undecoded_input_bytes().is_empty())diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.h b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.hindex 883c2be78dd..a7dd5f5fa3f 100644--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.h+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.h@@ -18,6 +18,7 @@#include <LibURL/URL.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>+#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWebCommon/MimeSniff/MimeType.h>@@ -39,6 +40,8 @@ private:virtual void visit_edges(Cell::Visitor&) override;void initialize_parser(ReadonlyBytes sniff_bytes);+ void continue_prescan(bool input_complete);+ void set_encoding(StringView encoding, EncodingConfidence);void start_incremental_read();void process_body_chunk(ByteBuffer);void process_end_of_body();@@ -80,6 +83,11 @@ private:bool m_has_queued_task_to_feed_parser { false };u32 m_times_yielded_to_event_loop { 0 };bool m_processed_implied_eof { false };++ // Finds an encoding declaration in m_input_bytes, as far as m_prescanned_byte_count, before the parser starts.+ OwnPtr<EncodingDeclarationPrescan> m_prescan;+ size_t m_prescanned_byte_count { 0 };+ ByteBuffer m_sniff_bytes;};}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rsindex 6f19ebd778c..a8886c474e4 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs@@ -6,6 +6,7 @@pub mod entities;mod known_names;+pub mod meta_charset_scanner;pub mod parser;pub mod preload_scanner;pub mod token;diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rsnew file mode 100644index 00000000000..8ce8aef0574--- /dev/null+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rs@@ -0,0 +1,541 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Finds a document's encoding declaration before the HTML parser starts, by tokenizing the document's first bytes as+//! the parser will: the prescan proposed in https://github.com/whatwg/html/issues/6962.++use crate::known_names::attribute_name;+use crate::known_names::tag_name;+use crate::preload_scanner::tokenizer_state_after_start_tag;+use crate::token::Attribute;+use crate::token::HtmlName;+use crate::token::KnownName;+use crate::token::TokenPayload;+use crate::token::TokenType;+use crate::tokenizer::HtmlTokenizer;+use std::ffi::c_void;++#[repr(C)]+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum RustFfiMetaCharsetScanResult {+ /// The bytes so far hold no declaration, but the bytes still to come may.+ NeedMoreInput = 0,+ /// A declaration names an encoding.+ Found = 1,+ /// No declaration can still come.+ NotFound = 2,+}++/// How many bytes the scan covers even once the head has ended: It looks at every token that ends in them.+const UNCONDITIONAL_SCAN_LENGTH: usize = 1024;++/// Tokenizes a document's bytes as they arrive, as the HTML parser will, and finds the first meta element that the tree+/// builder would take as an encoding declaration: one with a charset attribute, or an http-equiv of Content-Type and a+/// content attribute. It looks at every token in the first 1024 bytes, and past them for as long as the head can still+/// hold a declaration: until the tree builder would leave the head, or start a template.+pub struct MetaCharsetScanner {+ tokenizer: HtmlTokenizer,+ scripting_enabled: bool,+ // Whether the tokenizer is in an element whose contents are text, which ends with its end tag.+ in_text_element: bool,+ // Whether the tree builder is in a noscript element in the head, with scripting disabled: in its "in head noscript"+ // insertion mode.+ in_head_noscript: bool,+ // Whether the tree builder is in a frameset, which ignores a meta element.+ in_frameset: bool,+ // Whether the tree builder has left the head, or started a template: what ends the scan past the first 1024 bytes.+ head_ended: bool,+ // The document offset of the tokenizer's input, which the scanner drops once the tokenizer has consumed it.+ input_offset: usize,+ finished: bool,+}++impl MetaCharsetScanner {+ pub fn new(scripting_enabled: bool) -> Self {+ // The bytes arrive in pieces, so the end of the ones so far isn't the end of the input until the caller says so.+ let mut tokenizer = HtmlTokenizer::new(Vec::new());+ tokenizer.set_input_stream_closed(false);+ Self {+ tokenizer,+ scripting_enabled,+ in_text_element: false,+ in_head_noscript: false,+ in_frameset: false,+ head_ended: false,+ input_offset: 0,+ finished: false,+ }+ }++ /// Scans the bytes that arrived since the last call. `is_encoding` tells whether an attribute's value names an+ /// encoding: a charset attribute's value, or a content attribute's (marked as such).+ pub fn scan(+ &mut self,+ bytes: &[u8],+ input_complete: bool,+ mut is_encoding: impl FnMut(&str, bool) -> bool,+ ) -> RustFfiMetaCharsetScanResult {+ if self.finished {+ return RustFfiMetaCharsetScanResult::NotFound;+ }+ // Bytes before a declaration only ever matter as ASCII, which every encoding a declaration can name reads the+ // same way, so reading them as Latin-1 tokenizes them as the parser will.+ self.tokenizer.append_latin1_input(bytes);+ if input_complete {+ self.tokenizer.set_input_stream_closed(true);+ }++ while !self.past_the_scan() {+ let Some(token) = self.tokenizer.next_token(false, false) else {+ break;+ };+ if self.past_the_scan() {+ break;+ }+ let ends_head = match token.token_type {+ TokenType::StartTag => {+ let name = token.tag_name();+ if *name == tag_name!("meta")+ && !self.in_frameset+ && let TokenPayload::Tag { attributes, .. } = &token.payload+ && declares_encoding(attributes, &mut is_encoding)+ {+ self.finished = true;+ return RustFfiMetaCharsetScanResult::Found;+ }+ if *name == tag_name!("frameset") {+ self.in_frameset = true;+ }+ // The tree builder switches the tokenizer out of the data state for these elements, so their+ // contents are text rather than markup.+ if let Some(state) = tokenizer_state_after_start_tag(name, self.scripting_enabled) {+ self.tokenizer.switch_to(state);+ self.in_text_element = true;+ }+ if self.in_head_noscript && *name != tag_name!("head") && *name != tag_name!("noscript") {+ // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inheadnoscript+ // The tree builder handles these in the noscript, ignores head and noscript there, and for+ // anything else leaves the noscript and handles the tag in the head.+ if !start_tag_keeps_head_noscript_open(name) {+ self.in_head_noscript = false;+ }+ } else if *name == tag_name!("noscript") && !self.scripting_enabled && !self.head_ended {+ self.in_head_noscript = true;+ }+ !self.in_head_noscript && !start_tag_keeps_head_open(name)+ }+ TokenType::EndTag => {+ self.in_text_element = false;+ let name = token.tag_name();+ if self.in_head_noscript {+ // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inheadnoscript+ // The tree builder goes back to the head after this noscript, leaves the head at a br, and+ // ignores any other end tag.+ if *name == tag_name!("noscript") {+ self.in_head_noscript = false;+ }+ *name == tag_name!("br")+ } else {+ end_tag_ends_head(name)+ }+ }+ // Text that isn't whitespace has the tree builder leave the head, unless it's an element's contents.+ TokenType::Character => !self.in_text_element && !is_html_whitespace(token.code_point),+ TokenType::EndOfFile => break,+ _ => false,+ };+ if ends_head {+ self.head_ended = true;+ }+ }++ if input_complete || self.past_the_scan() {+ self.finished = true;+ return RustFfiMetaCharsetScanResult::NotFound;+ }++ // Drop the input the tokenizer has consumed, which it does only once it has consumed all of it.+ let consumed = self.tokenizer.current_offset;+ self.tokenizer.parser_did_run();+ if self.tokenizer.current_offset == 0 {+ self.input_offset += consumed;+ }+ RustFfiMetaCharsetScanResult::NeedMoreInput+ }++ // Whether the tokenizer has gone past the first 1024 bytes once the head has ended.+ fn past_the_scan(&self) -> bool {+ self.head_ended && self.input_offset + self.tokenizer.current_offset > UNCONDITIONAL_SCAN_LENGTH+ }+}++// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inhead (a start tag whose tag name is "meta")+fn declares_encoding(attributes: &[Attribute], is_encoding: &mut impl FnMut(&str, bool) -> bool) -> bool {+ // If the element has a charset attribute, and getting an encoding from its value results in an encoding, ...+ if let Some(charset) = attribute_value(attributes, attribute_name!("charset"))+ && is_encoding(charset, false)+ {+ return true;+ }+ // Otherwise, if the element has an http-equiv attribute whose value is an ASCII case-insensitive match for the+ // string "Content-Type", and the element has a content attribute, and applying the algorithm for extracting a+ // character encoding from a meta element to that attribute's value returns an encoding, ...+ let Some(http_equiv) = attribute_value(attributes, attribute_name!("http-equiv")) else {+ return false;+ };+ if !http_equiv.eq_ignore_ascii_case("content-type") {+ return false;+ }+ attribute_value(attributes, attribute_name!("content")).is_some_and(|content| is_encoding(content, true))+}++fn attribute_value(attributes: &[Attribute], name: KnownName) -> Option<&str> {+ attributes+ .iter()+ .find(|attribute| attribute.local_name == name)+ .map(|attribute| attribute.value.as_str())+}++// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inhead+/// Whether the head can still be open after a start tag with this name: whether the tree builder handles it in the head.+/// It handles template there too, but a template ends the scan.+fn start_tag_keeps_head_open(name: &HtmlName) -> bool {+ *name == tag_name!("html")+ || *name == tag_name!("head")+ || *name == tag_name!("base")+ || *name == tag_name!("basefont")+ || *name == tag_name!("bgsound")+ || *name == tag_name!("link")+ || *name == tag_name!("meta")+ || *name == tag_name!("noframes")+ || *name == tag_name!("noscript")+ || *name == tag_name!("script")+ || *name == tag_name!("style")+ || *name == tag_name!("title")+}++// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inheadnoscript+/// Whether the head can still be open after a start tag with this name, in a noscript element in the head with+/// scripting disabled.+fn start_tag_keeps_head_noscript_open(name: &HtmlName) -> bool {+ *name == tag_name!("html")+ || *name == tag_name!("basefont")+ || *name == tag_name!("bgsound")+ || *name == tag_name!("link")+ || *name == tag_name!("meta")+ || *name == tag_name!("noframes")+ || *name == tag_name!("style")+}++/// Whether an end tag with this name has the tree builder leave the head. It ignores any other end tag there.+fn end_tag_ends_head(name: &HtmlName) -> bool {+ *name == tag_name!("head") || *name == tag_name!("body") || *name == tag_name!("html") || *name == tag_name!("br")+}++fn is_html_whitespace(code_point: u32) -> bool {+ matches!(code_point, 0x09 | 0x0A | 0x0C | 0x0D | 0x20)+}++/// Creates a scanner, for rust_html_meta_charset_scanner_scan().+#[unsafe(no_mangle)]+pub extern "C" fn rust_html_meta_charset_scanner_create(scripting_enabled: bool) -> *mut MetaCharsetScanner {+ Box::into_raw(Box::new(MetaCharsetScanner::new(scripting_enabled)))+}++/// Destroys a scanner.+///+/// # Safety+/// `scanner` must be a valid pointer from `rust_html_meta_charset_scanner_create`, and must not be used after this+/// call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_html_meta_charset_scanner_destroy(scanner: *mut MetaCharsetScanner) {+ if !scanner.is_null() {+ drop(unsafe { Box::from_raw(scanner) });+ }+}++/// Scans the document bytes that arrived since the last call.+///+/// # Safety+/// `scanner` must be a valid pointer from `rust_html_meta_charset_scanner_create`. `is_encoding` must not retain the+/// value pointer beyond the callback invocation.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_html_meta_charset_scanner_scan(+ scanner: *mut MetaCharsetScanner,+ input: ak::Span<'_, u8>,+ input_complete: bool,+ ctx: *mut c_void,+ is_encoding: unsafe extern "C" fn(ctx: *mut c_void, value: *const u8, value_len: usize, is_content: bool) -> bool,+) -> RustFfiMetaCharsetScanResult {+ let scanner = unsafe { &mut *scanner };+ scanner.scan(input.as_slice(), input_complete, |value, is_content| unsafe {+ is_encoding(ctx, value.as_ptr(), value.len(), is_content)+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn is_utf8(value: &str, _: bool) -> bool {+ value.to_ascii_lowercase().contains("utf-8")+ }++ fn scan_all(input: &[u8]) -> RustFfiMetaCharsetScanResult {+ MetaCharsetScanner::new(true).scan(input, true, is_utf8)+ }++ fn padding() -> Vec<u8> {+ let mut padding = b"<!--".to_vec();+ padding.extend(std::iter::repeat_n(b'a', 1500));+ padding.extend(b"-->");+ padding+ }++ #[test]+ fn finds_a_declaration_after_the_first_kilobyte_in_the_head() {+ let mut input = b"<!DOCTYPE html><head>".to_vec();+ input.extend(padding());+ input.extend(b"<title>caf\xe9</title><meta charset=\"utf-8\"></head>");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::Found);+ }++ #[test]+ fn finds_an_http_equiv_declaration() {+ let mut input = padding();+ input.extend(b"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::Found);+ }++ #[test]+ fn ignores_a_declaration_after_the_head_ended() {+ let mut input = padding();+ input.extend(b"<p>text</p><meta charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);+ }++ #[test]+ fn ignores_markup_in_script_style_and_title_text() {+ for (open, close) in [+ ("<script>", "</script>"),+ ("<style>", "</style>"),+ ("<title>", "</title>"),+ ] {+ let mut input = padding();+ input.extend(format!("{open}'<meta charset=\"utf-8\">'{close}</head><body>").bytes());+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound, "{open}");+ }+ }++ #[test]+ fn text_ends_the_head_but_text_in_the_head_does_not() {+ let mut input = padding();+ input.extend(b"text<meta charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);++ let mut input = padding();+ input.extend(b" \n<title>text</title><script>text</script><meta charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::Found);+ }++ #[test]+ fn only_tags_the_head_can_hold_keep_it_open() {+ let head_tags = "<basefont><bgsound><noframes>'<p>'</noframes><link><base>";+ let mut input = padding();+ input.extend(format!("{head_tags}<meta charset=\"utf-8\">").bytes());+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::Found);++ let mut input = padding();+ input.extend(b"<object></object><meta charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);+ }++ #[test]+ fn noscript_with_scripting_disabled_has_rules_of_its_own() {+ let scan_without_scripting = |input: &[u8]| MetaCharsetScanner::new(false).scan(input, true, is_utf8);++ let mut input = padding();+ input.extend(b"<noscript><link></head></body></html></noscript><meta charset=\"utf-8\">");+ assert_eq!(scan_without_scripting(&input), RustFfiMetaCharsetScanResult::Found);++ let mut input = padding();+ input.extend(b"<noscript><meta charset=\"utf-8\"></noscript>");+ assert_eq!(scan_without_scripting(&input), RustFfiMetaCharsetScanResult::Found);++ // A start tag the noscript can't hold ends it, but not the head, if the head can hold it.+ let mut input = padding();+ input.extend(b"<noscript><title>title</title><meta charset=\"utf-8\">");+ assert_eq!(scan_without_scripting(&input), RustFfiMetaCharsetScanResult::Found);++ for leaves_head in ["<noscript></br>", "<noscript><p>", "<noscript>text"] {+ let mut input = padding();+ input.extend(format!("{leaves_head}<meta charset=\"utf-8\">").bytes());+ assert_eq!(+ scan_without_scripting(&input),+ RustFfiMetaCharsetScanResult::NotFound,+ "{leaves_head}"+ );+ }+ }++ #[test]+ fn only_some_end_tags_end_the_head() {+ let mut input = padding();+ input.extend(b"</bogus></p><meta charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::Found);++ for end_tag in ["</head>", "</body>", "</html>", "</br>"] {+ let mut input = padding();+ input.extend(format!("{end_tag}<meta charset=\"utf-8\">").bytes());+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound, "{end_tag}");+ }+ }++ #[test]+ fn counts_a_declaration_anywhere_in_the_first_kilobyte() {+ assert_eq!(+ scan_all(b"<p>text</p><meta charset=\"utf-8\">"),+ RustFfiMetaCharsetScanResult::Found+ );+ assert_eq!(+ scan_all(b"<template><meta charset=\"utf-8\"></template>"),+ RustFfiMetaCharsetScanResult::Found+ );+ }++ #[test]+ fn ignores_a_tag_that_ends_past_the_first_kilobyte_after_the_head() {+ let mut input = b"<body><meta data-padding=\"".to_vec();+ input.extend(std::iter::repeat_n(b'a', 2000));+ input.extend(b"\" charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);+ }++ #[test]+ fn stops_inside_a_comment_once_the_head_ended_past_the_first_kilobyte() {+ let mut input = b"<body><!--".to_vec();+ input.extend(std::iter::repeat_n(b'a', 1500));+ assert_eq!(+ MetaCharsetScanner::new(true).scan(&input, false, is_utf8),+ RustFfiMetaCharsetScanResult::NotFound+ );+ }++ #[test]+ fn a_template_ends_the_scan_past_the_first_kilobyte() {+ let mut input = padding();+ input.extend(b"<template></template><meta charset=\"utf-8\">");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);+ }++ #[test]+ fn stops_without_more_input_once_the_head_ended_past_the_first_kilobyte() {+ let mut input = padding();+ input.extend(b"<p>");+ assert_eq!(+ MetaCharsetScanner::new(true).scan(&input, false, is_utf8),+ RustFfiMetaCharsetScanResult::NotFound+ );+ }++ #[test]+ fn keeps_the_document_offset_across_scans() {+ // Each scan drops the input the tokenizer has consumed, but the 1024-byte boundary stays where it is.+ let mut comment = b"<!--".to_vec();+ comment.extend(std::iter::repeat_n(b'a', 400));+ comment.extend(b"-->");+ let mut scanner = MetaCharsetScanner::new(true);+ for _ in 0..3 {+ assert_eq!(+ scanner.scan(&comment, false, is_utf8),+ RustFfiMetaCharsetScanResult::NeedMoreInput+ );+ }+ assert_eq!(+ scanner.scan(b"<p>", false, is_utf8),+ RustFfiMetaCharsetScanResult::NotFound+ );+ }++ #[test]+ fn a_frameset_holds_no_declaration() {+ let mut input = b"<!DOCTYPE html><frameset><meta data-padding=\"".to_vec();+ input.extend(std::iter::repeat_n(b'a', 2000));+ input.extend(b"\" charset=\"utf-8\"></frameset>");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);+ }++ #[test]+ fn ignores_a_declaration_that_names_no_encoding() {+ let mut input = padding();+ input.extend(b"<meta charset=\"bogus\"></head><body>");+ assert_eq!(scan_all(&input), RustFfiMetaCharsetScanResult::NotFound);+ }++ #[test]+ fn waits_for_more_input_in_the_head() {+ let mut scanner = MetaCharsetScanner::new(true);+ assert_eq!(+ scanner.scan(&padding(), false, is_utf8),+ RustFfiMetaCharsetScanResult::NeedMoreInput+ );+ // A tag that hasn't ended yet doesn't count, until it does.+ assert_eq!(+ scanner.scan(b"<meta charset=\"utf-8\"", false, is_utf8),+ RustFfiMetaCharsetScanResult::NeedMoreInput+ );+ assert_eq!(scanner.scan(b">", false, is_utf8), RustFfiMetaCharsetScanResult::Found);+ }++ #[test]+ fn resumes_inside_a_comment() {+ for (after_comment, expected) in [+ (+ "<title>title</title><meta charset=\"utf-8\">",+ RustFfiMetaCharsetScanResult::Found,+ ),+ (+ "<p>text</p><meta charset=\"utf-8\">",+ RustFfiMetaCharsetScanResult::NotFound,+ ),+ (+ "<script>var markup = '<meta charset=\"utf-8\">';</script><p>",+ RustFfiMetaCharsetScanResult::NotFound,+ ),+ ] {+ let mut input = b"<!DOCTYPE html><!-- ".to_vec();+ input.extend("padding ".repeat(95).bytes());+ input.extend(b"caf\xe9 ");+ input.extend("padding ".repeat(250).bytes());+ input.extend(b"-->");+ input.extend(after_comment.bytes());+ let split = 1800;+ let mut scanner = MetaCharsetScanner::new(true);+ assert_eq!(+ scanner.scan(&input[..split], false, is_utf8),+ RustFfiMetaCharsetScanResult::NeedMoreInput+ );+ assert_eq!(+ scanner.scan(&input[split..], true, is_utf8),+ expected,+ "{after_comment}"+ );+ }+ }++ #[test]+ fn an_unfinished_tag_at_the_end_of_the_input_does_not_count() {+ let mut scanner = MetaCharsetScanner::new(true);+ assert_eq!(+ scanner.scan(&padding(), false, is_utf8),+ RustFfiMetaCharsetScanResult::NeedMoreInput+ );+ assert_eq!(+ scanner.scan(b"<meta charset=\"utf-8\"", true, is_utf8),+ RustFfiMetaCharsetScanResult::NotFound+ );+ }+}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rsindex c0fdd38ed19..bdd2ba952c7 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs@@ -210,7 +210,7 @@ fn process_end_tag(token: &Token, template_depth: &mut u64, foreign_depth: &mut}}-fn tokenizer_state_after_start_tag(tag_name: &HtmlName, scripting_enabled: bool) -> Option<State> {+pub(crate) fn tokenizer_state_after_start_tag(tag_name: &HtmlName, scripting_enabled: bool) -> Option<State> {if *tag_name == tag_name!("script") {Some(State::ScriptData)} else if *tag_name == tag_name!("title") || *tag_name == tag_name!("textarea") {diff --git a/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset-after-non-ascii.txt b/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset-after-non-ascii.txtnew file mode 100644index 00000000000..9165cf30f7d--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset-after-non-ascii.txt@@ -0,0 +1,3 @@+in the head: UTF-8 café+after the head ended: windows-1252 café+in a script's text: windows-1252 cafédiff --git a/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset.txt b/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset.txtindex bad827909f2..05a5407706b 100644--- a/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset.txt+++ b/Tests/LibWeb/Text/expected/HTML/parser-streams-late-meta-charset.txt@@ -4,6 +4,9 @@ charset body: ©http-equiv charset: UTF-8http-equiv script: you’rehttp-equiv body: ©+charset-after-head charset: UTF-8+charset-after-head script: you’re+charset-after-head body: ©charset-less progressive: truepost-eof charset: UTF-8post-eof script: truediff --git a/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-after-non-ascii.html b/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-after-non-ascii.htmlnew file mode 100644index 00000000000..f177727164b--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-after-non-ascii.html@@ -0,0 +1,36 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A page with non-ASCII text in a comment, and its charset declaration only past its first 1024 bytes, arriving in+ // two pieces: the first long enough for encoding sniffing to start, ending inside the comment. The declaration+ // counts while the page's head could still hold it, and only where the tokenizer reads it as a tag.+ asyncTest(async (done) => {+ const httpServer = httpTestServer();+ const encoder = new TextEncoder();++ async function load(name, slug, afterComment) {+ const comment = `<!-- ${"padding ".repeat(95)}caf\u00e9 ${"padding ".repeat(250)}-->`;+ const body = `<!DOCTYPE html>${comment}${afterComment}<p id="text">caf\u00e9</p><script>window.onload = () => parent.postMessage(document.characterSet + " " + document.getElementById("text").textContent, "*");<\/script>`;+ const url = await httpServer.createEcho("GET", `/parser-streams-late-meta-charset-after-non-ascii-${slug}`, {+ status: 200,+ headers: {+ "Content-Type": "text/html",+ },+ body,+ });+ const split = encoder.encode(body.slice(0, body.indexOf("\u00e9"))).length + 1000;++ const frame = document.createElement("iframe");+ const message = new Promise(resolve => window.addEventListener("message", event => resolve(event.data), { once: true }));+ frame.src = `${url}?chunks=${split}&chunk_delay_ms=200`;+ document.body.appendChild(frame);+ println(`${name}: ${await message}`);+ frame.remove();+ }++ await load("in the head", "in-head", `<title>title</title><meta charset="utf-8">`);+ await load("after the head ended", "after-head", `<p>text</p><meta charset="utf-8">`);+ await load("in a script's text", "in-script", `<script>var markup = '<meta charset="utf-8">';<\/script>`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-blocked-parser.html b/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-blocked-parser.htmlindex a6f2060e19d..6101aa7532e 100644--- a/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-blocked-parser.html+++ b/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset-blocked-parser.html@@ -40,8 +40,8 @@frame.remove();}- // The comment keeps the declaration past the 1024 bytes the encoding sniffing algorithm prescans, so only the- // parser can find it. It also exceeds the response sniffing threshold, so the first chunk can be parsed before EOF.+ // The comment keeps the declaration past the first 1024 bytes. It also exceeds the response sniffing threshold,+ // so the first chunk can be parsed before EOF.const padding = `<!--${"a".repeat(2000)}-->`;// The declaration trails a parser-blocking script, so the parser is still paused at that script when the rest@@ -59,11 +59,12 @@}// The blocking script resolves during the gap between chunks, so the parser has drained the first chunk before- // the declaration arrives in the second.+ // the declaration arrives in the second. The declaration comes after the head ended, so the parser can start+ // before it arrives.async function runResumedCase() {const token = crypto.randomUUID();const scriptURL = await createBlockingScript("resumed");- const head = `<!DOCTYPE html><head><script src="${scriptURL}"><\/script>${padding}`;+ const head = `<!DOCTYPE html><body><script src="${scriptURL}"><\/script>${padding}`;const body = `${head}<meta charset="UTF-8"></head><body><span id="target">©</span>`;await runCase("resumed",diff --git a/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset.html b/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset.htmlindex cc4eede5043..877f960e797 100644--- a/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset.html+++ b/Tests/LibWeb/Text/input/HTML/parser-streams-late-meta-charset.html@@ -4,7 +4,9 @@<script>asyncTest(async done => {const httpServer = httpTestServer();- async function runCase(name, declaration) {+ // A declaration in the head is found before the parser starts. One that comes after the head ended, past the+ // first 1024 bytes, is found by the parser, which changes the encoding on the fly.+ async function runCase(name, declaration, { afterHead = false } = {}) {const scriptURL = await httpServer.createEcho("GET", `/parser-streams-late-meta-script-${name}`, {status: 200,headers: {@@ -14,7 +16,9 @@});const token = crypto.randomUUID();- const head = `<!DOCTYPE html><head><!--${"a".repeat(2000)}-->`;+ const head = afterHead+ ? `<!DOCTYPE html><body>${" ".repeat(2000)}`+ : `<!DOCTYPE html><head><!--${"a".repeat(2000)}-->`;const body = `${head}${declaration}<script src="${scriptURL}"><\/script></head><body><span id="target">©</span>`;const url = await httpServer.createEcho("GET", `/parser-streams-late-meta-${name}`, {status: 200,@@ -30,8 +34,12 @@});frame.src = `${url}?chunks=1500&chunk_unblock_tokens=${token}`;document.body.appendChild(frame);- while (!frame.contentDocument.URL.startsWith(url) || !frame.contentDocument.head)- await new Promise(resolve => setTimeout(resolve, 0));+ if (afterHead) {+ while (!frame.contentDocument.URL.startsWith(url) || !frame.contentDocument.head)+ await new Promise(resolve => setTimeout(resolve, 0));+ } else {+ while (!(await fetch(httpServer.recordedRequestHeadersURL(url))).ok) {}+ }await fetch(new URL(`/unblock/${token}`, url));await loaded;@@ -112,6 +120,7 @@await runCase("charset", `<meta charset="UTF-8">`);await runCase("http-equiv", `<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">`);+ await runCase("charset-after-head", `<meta charset="UTF-8">`, { afterHead: true });await runProgressiveCase();await runPostEOFCase();done();diff --git a/Tests/LibWeb/Text/input/HTML/parser-streams-style-split.html b/Tests/LibWeb/Text/input/HTML/parser-streams-style-split.htmlindex 4f6893794e3..78952d02529 100644--- a/Tests/LibWeb/Text/input/HTML/parser-streams-style-split.html+++ b/Tests/LibWeb/Text/input/HTML/parser-streams-style-split.html@@ -8,7 +8,7 @@const url = await httpServer.createEcho("GET", "/parser-streams-style-split", {status: 200,headers: {- "Content-Type": "text/html",+ "Content-Type": "text/html; charset=utf-8",},body,});