Skip to content

Truly independent web browser

LibWeb: Use the encoding declaration of XML responses in XHR

Andreas Kling036d51a3c67a
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cpp
index 9be42f5f57d..d95f4544c1d 100644
--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp
@@ -84,18 +84,29 @@ static void convert_to_xml_error_document(DOM::Document& document, Utf16String e
document.set_ready_for_post_load_tasks(true);
}
-bool build_xml_document(DOM::Document& document, ByteBuffer const& data, Optional<StringView> content_encoding)
+// https://www.rfc-editor.org/rfc/rfc7303#section-3.2
+static StringView determine_xml_encoding(ReadonlyBytes data, Optional<StringView> content_encoding)
{
- 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.
- if (content_encoding.has_value())
- decoder = TextCodec::decoder_for(*content_encoding);
+ // NB: A BOM takes precedence over the transport charset, followed by the XML declaration. Return canonical
+ // encoding labels so that these views do not refer to the temporary sniffing results.
+ if (auto bom_encoding = HTML::run_bom_sniff(data); bom_encoding.has_value())
+ return TextCodec::get_standardized_encoding(*bom_encoding).value();
+ if (content_encoding.has_value()) {
+ if (auto encoding = TextCodec::get_standardized_encoding(*content_encoding); encoding.has_value())
+ return *encoding;
+ }
+ if (auto xml_encoding = HTML::get_an_xml_encoding(data); xml_encoding.has_value())
+ return TextCodec::get_standardized_encoding(*xml_encoding).value();
+
// https://www.w3.org/TR/xml/#charencoding
// [...] it is a fatal error [...] for an entity which begins with neither a Byte Order Mark nor an encoding
// declaration to use an encoding other than UTF-8.
- if (!decoder.has_value())
- decoder = TextCodec::decoder_for("UTF-8"sv);
+ return "UTF-8"sv;
+}
+
+bool build_xml_document(DOM::Document& document, ByteBuffer const& data, Optional<StringView> content_encoding)
+{
+ auto decoder = TextCodec::decoder_for(determine_xml_encoding(data, content_encoding));
VERIFY(decoder.has_value());
// Well-formed XML documents contain only properly encoded characters
auto source_or_error = TextCodec::decode_to_utf8(data, *decoder, TextCodec::ErrorMode::Fatal);
@@ -203,24 +214,13 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navig
content_encoding = *maybe_encoding;
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<StringView> encoding;
- // 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.
- if (content_encoding.has_value())
- encoding = TextCodec::get_standardized_encoding(content_encoding->bytes_as_string_view());
- // https://www.w3.org/TR/xml/#charencoding
- // [...] it is a fatal error [...] for an entity which begins with neither a Byte Order Mark nor an encoding
- // declaration to use an encoding other than UTF-8.
- if (!encoding.has_value())
- encoding = "UTF-8"sv;
+ auto encoding = determine_xml_encoding(data, content_encoding.has_value() ? Optional<StringView> { content_encoding->bytes_as_string_view() } : OptionalNone {});
// Once the character encoding is established, the document's character encoding must be set to that character encoding.
- // NB: Decoding lets a BOM override the encoding.
- auto bom_encoding = HTML::run_bom_sniff(data);
- document->set_encoding(Utf16String::from_utf8(bom_encoding.has_value() ? bom_encoding->view() : *encoding));
+ document->set_encoding(Utf16String::from_utf8(encoding));
// Well-formed XML documents contain only properly encoded characters
- auto source = TextCodec::decode_to_utf8(data, *TextCodec::decoder_for(*encoding), TextCodec::ErrorMode::Fatal);
+ auto source = TextCodec::decode_to_utf8(data, *TextCodec::decoder_for(encoding), TextCodec::ErrorMode::Fatal);
if (source.is_error()) {
// FIXME: Insert error message into the document.
dbgln("Failed to decode XML document: {}", source.error());
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp
index 9cffbae2c2d..682af4c797a 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp
@@ -273,7 +273,7 @@ value:
}
// https://html.spec.whatwg.org/multipage/parsing.html#concept-get-xml-encoding-when-sniffing
-static Optional<ByteString> get_an_xml_encoding(ReadonlyBytes input)
+Optional<ByteString> get_an_xml_encoding(ReadonlyBytes input)
{
// 1. Let encodingPosition be a pointer to the start of the stream.
size_t encoding_position = 0;
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h
index e93909b40f1..b88b7ce0bb0 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h
+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.h
@@ -31,6 +31,7 @@ Optional<StringView> extract_character_encoding_from_meta_element(ByteString con
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> run_bom_sniff(ReadonlyBytes input);
+Optional<ByteString> get_an_xml_encoding(ReadonlyBytes input);
// Extracts the rightmost DNS label from a URL's host as a TLD hint for chardetng.
// Returns an empty string if the host is absent or is an IP address. chardetng treats
diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
index 6b58d9f579b..f1f58b5a182 100644
--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
@@ -381,7 +381,12 @@ Utf16String XMLHttpRequest::get_text_response() const
// 3. If xhr’s response type is the empty string, charset is null, and the result of get a final MIME type for xhr is an XML MIME type,
if (m_response_type == XMLHttpRequest::ResponseType::Empty && !charset.has_value() && get_final_mime_type().is_xml()) {
- // FIXME: then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
+ // then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
+ // NB: The encoding declaration names the encoding, which this finds the way the HTML Standard does when
+ // sniffing an encoding. Without one, charset stays null and is set to UTF-8 below, as the XML
+ // specification requires.
+ if (auto xml_encoding = HTML::get_an_xml_encoding(m_received_bytes); xml_encoding.has_value())
+ charset = TextCodec::get_standardized_encoding(*xml_encoding);
}
// 4. If charset is null, then set charset to UTF-8.
@@ -457,7 +462,7 @@ void XMLHttpRequest::set_document_response()
// 6. Otherwise, let document be a document that represents the result of running the XML parser with XML scripting support disabled on xhr’s received bytes. If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.
else {
document = DOM::XMLDocument::create(page, *m_global_object, m_response->url().value_or({}));
- if (!Web::build_xml_document(*document, m_received_bytes, {})) {
+ if (!Web::build_xml_document(*document, m_received_bytes, get_final_encoding())) {
reset_response_object();
return;
}
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index e0e44a1ae2f..1e777922de0 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -1,4 +1,5 @@
[LoadFromHttpServer]
+Text/input/HTML/xml-document-encoding.html
Text/input/HTML/createImageBitmap-video.html
Text/input/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.html
Text/input/HTML/HTMLVideoElement-cross-origin-media-data-taints-canvas.html
diff --git a/Tests/LibWeb/Text/expected/HTML/xml-document-encoding.txt b/Tests/LibWeb/Text/expected/HTML/xml-document-encoding.txt
new file mode 100644
index 00000000000..f374d44cd85
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/xml-document-encoding.txt
@@ -0,0 +1,48 @@
+declaration navigation: text matches: true
+declaration navigation: characterSet: windows-1252
+declaration XHR default: text matches: true
+declaration XHR default: characterSet: UTF-8
+declaration XHR document: text matches: true
+declaration XHR document: characterSet: UTF-8
+invalid MIME charset navigation: text matches: true
+invalid MIME charset navigation: characterSet: windows-1252
+invalid MIME charset XHR default: text matches: true
+invalid MIME charset XHR default: characterSet: UTF-8
+invalid MIME charset XHR document: text matches: true
+invalid MIME charset XHR document: characterSet: UTF-8
+UTF-8 MIME charset navigation: text matches: true
+UTF-8 MIME charset navigation: characterSet: UTF-8
+UTF-8 MIME charset XHR default: text matches: true
+UTF-8 MIME charset XHR default: characterSet: UTF-8
+UTF-8 MIME charset XHR document: text matches: true
+UTF-8 MIME charset XHR document: characterSet: UTF-8
+windows-1252 MIME charset navigation: text matches: true
+windows-1252 MIME charset navigation: characterSet: windows-1252
+windows-1252 MIME charset XHR default: text matches: true
+windows-1252 MIME charset XHR default: characterSet: UTF-8
+windows-1252 MIME charset XHR document: text matches: true
+windows-1252 MIME charset XHR document: characterSet: UTF-8
+UTF-8 BOM navigation: text matches: true
+UTF-8 BOM navigation: characterSet: UTF-8
+UTF-8 BOM XHR default: text matches: true
+UTF-8 BOM XHR default: characterSet: UTF-8
+UTF-8 BOM XHR document: text matches: true
+UTF-8 BOM XHR document: characterSet: UTF-8
+UTF-16LE BOM navigation: text matches: true
+UTF-16LE BOM navigation: characterSet: UTF-16LE
+UTF-16LE BOM XHR default: text matches: true
+UTF-16LE BOM XHR default: characterSet: UTF-8
+UTF-16LE BOM XHR document: text matches: true
+UTF-16LE BOM XHR document: characterSet: UTF-8
+UTF-16BE BOM navigation: text matches: true
+UTF-16BE BOM navigation: characterSet: UTF-16BE
+UTF-16BE BOM XHR default: text matches: true
+UTF-16BE BOM XHR default: characterSet: UTF-8
+UTF-16BE BOM XHR document: text matches: true
+UTF-16BE BOM XHR document: characterSet: UTF-8
+UTF-8 default navigation: text matches: true
+UTF-8 default navigation: characterSet: UTF-8
+UTF-8 default XHR default: text matches: true
+UTF-8 default XHR default: characterSet: UTF-8
+UTF-8 default XHR document: text matches: true
+UTF-8 default XHR document: characterSet: UTF-8
diff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/responsedocument-decoding.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/responsedocument-decoding.txt
index 9717c106ff0..39bf73b6ef9 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/xhr/responsedocument-decoding.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/responsedocument-decoding.txt
@@ -2,11 +2,10 @@ Harness status: OK
Found 6 tests
-4 Pass
-2 Fail
-Fail XMLHttpRequest: response document decoding (application/xml %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
+6 Pass
+Pass XMLHttpRequest: response document decoding (application/xml %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
Pass XMLHttpRequest: response document decoding (application/xml;charset=utf-8 %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
-Fail XMLHttpRequest: response document decoding (application/xml;charset=windows-1252 %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
+Pass XMLHttpRequest: response document decoding (application/xml;charset=windows-1252 %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
Pass XMLHttpRequest: response document decoding (text/html %3C!doctype%20html%3E%3Cmeta%20charset%3Dwindows-1252%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
Pass XMLHttpRequest: response document decoding (text/html;charset=utf-8 %3C!doctype%20html%3E%3Cmeta%20charset%3Dwindows-1252%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
Pass XMLHttpRequest: response document decoding (text/html;charset=windows-1252 %3C!doctype%20html%3E%3Cmeta%20charset%3Dwindows-1252%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E)
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/responsetext-decoding.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/responsetext-decoding.txt
index dac6c8ac104..ed952a8f292 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/xhr/responsetext-decoding.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/responsetext-decoding.txt
@@ -2,9 +2,8 @@ Harness status: OK
Found 37 tests
-36 Pass
-1 Fail
-Fail XMLHttpRequest: responseText decoding (application/xml %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E empty)
+37 Pass
+Pass XMLHttpRequest: responseText decoding (application/xml %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E empty)
Pass XMLHttpRequest: responseText decoding (text/html %3C!doctype%20html%3E%3Cmeta%20charset%3Dwindows-1252%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E empty)
Pass XMLHttpRequest: responseText decoding (application/xml;charset=utf-8 %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E empty)
Pass XMLHttpRequest: responseText decoding (application/xml;charset=windows-1252 %3C%3Fxml%20version%3D'1.0'%20encoding%3D'windows-1252'%3F%3E%3Cx%3E%e6%a9%9f%3C%2Fx%3E empty)
diff --git a/Tests/LibWeb/Text/input/HTML/xml-document-encoding.html b/Tests/LibWeb/Text/input/HTML/xml-document-encoding.html
new file mode 100644
index 00000000000..300d841f123
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/xml-document-encoding.html
@@ -0,0 +1,74 @@
+<!doctype html>
+<meta charset="utf-8" />
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const ascii = text => Array.from(text, character => character.charCodeAt(0));
+ const xml = (encoding, bytes) => [
+ ...ascii(`<?xml version="1.0"${encoding ? ` encoding="${encoding}"` : ""}?><x>`),
+ ...bytes,
+ ...ascii("</x>"),
+ ];
+ const utf16 = (text, littleEndian) =>
+ Array.from(text).flatMap(character => {
+ const code = character.charCodeAt(0);
+ return littleEndian ? [code & 255, code >> 8] : [code >> 8, code & 255];
+ });
+ const cases = [
+ ["declaration", "application/xml", xml("windows-1252", [0xe9])],
+ ["invalid MIME charset", "application/xml;charset=bogus", xml("windows-1252", [0xe9])],
+ ["UTF-8 MIME charset", "application/xml;charset=UTF-8", xml("windows-1252", [0xc3, 0xa9])],
+ ["windows-1252 MIME charset", "application/xml;charset=windows-1252", xml("UTF-8", [0xe9])],
+ [
+ "UTF-8 BOM",
+ "application/xml;charset=windows-1252",
+ [0xef, 0xbb, 0xbf, ...xml("windows-1252", [0xc3, 0xa9])],
+ ],
+ [
+ "UTF-16LE BOM",
+ "application/xml",
+ [0xff, 0xfe, ...utf16('<?xml version="1.0" encoding="UTF-16"?><x>é</x>', true)],
+ ],
+ [
+ "UTF-16BE BOM",
+ "application/xml;charset=UTF-8",
+ [0xfe, 0xff, ...utf16('<?xml version="1.0" encoding="UTF-16"?><x>é</x>', false)],
+ ],
+ ["UTF-8 default", "application/xml", xml(null, [0xc3, 0xa9])],
+ ];
+ const report = (label, document) => {
+ println(
+ `${label}: text matches: ${document?.documentElement?.localName === "x" && document.documentElement.textContent === "é"}`
+ );
+ println(`${label}: characterSet: ${document?.characterSet}`);
+ };
+ for (const [index, [label, mime, bytes]] of cases.entries()) {
+ const url = await httpTestServer().createEcho("GET", `/xml-document-encoding-${index}`, {
+ status: 200,
+ headers: { "Content-Type": mime },
+ body_encoding: "base64",
+ body: btoa(String.fromCharCode(...bytes)),
+ });
+ const frame = document.createElement("iframe");
+ const loaded = new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+ frame.src = url;
+ document.body.append(frame);
+ await loaded;
+ report(`${label} navigation`, frame.contentDocument);
+ frame.remove();
+
+ for (const responseType of ["", "document"]) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.responseType = responseType;
+ const loaded = new Promise((resolve, reject) => {
+ xhr.onload = resolve;
+ xhr.onerror = reject;
+ });
+ xhr.send();
+ await loaded;
+ report(`${label} XHR ${responseType || "default"}`, xhr.responseXML);
+ }
+ }
+ });
+</script>