HTMLEncodingDetection.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /*
  2. * Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <AK/GenericLexer.h>
  8. #include <AK/StringView.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibTextCodec/Decoder.h>
  11. #include <LibWeb/DOM/Attr.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>
  14. #include <LibWeb/Infra/CharacterTypes.h>
  15. #include <ctype.h>
  16. namespace Web::HTML {
  17. bool prescan_should_abort(ByteBuffer const& input, size_t const& position)
  18. {
  19. return position >= input.size() || position >= 1024;
  20. }
  21. bool prescan_is_whitespace_or_slash(u8 const& byte)
  22. {
  23. return byte == '\t' || byte == '\n' || byte == '\f' || byte == '\r' || byte == ' ' || byte == '/';
  24. }
  25. bool prescan_skip_whitespace_and_slashes(ByteBuffer const& input, size_t& position)
  26. {
  27. while (!prescan_should_abort(input, position) && (input[position] == '\t' || input[position] == '\n' || input[position] == '\f' || input[position] == '\r' || input[position] == ' ' || input[position] == '/'))
  28. ++position;
  29. return !prescan_should_abort(input, position);
  30. }
  31. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#algorithm-for-extracting-a-character-encoding-from-a-meta-element
  32. Optional<StringView> extract_character_encoding_from_meta_element(ByteString const& string)
  33. {
  34. // Checking for "charset" is case insensitive, as is getting an encoding.
  35. // Therefore, stick to lowercase from the start for simplicity.
  36. auto lowercase_string = string.to_lowercase();
  37. GenericLexer lexer(lowercase_string);
  38. for (;;) {
  39. auto charset_index = lexer.remaining().find("charset"sv);
  40. if (!charset_index.has_value())
  41. return {};
  42. // 7 is the length of "charset".
  43. lexer.ignore(charset_index.value() + 7);
  44. lexer.ignore_while([](char c) {
  45. return Infra::is_ascii_whitespace(c);
  46. });
  47. if (lexer.peek() != '=')
  48. continue;
  49. break;
  50. }
  51. // Ignore the '='.
  52. lexer.ignore();
  53. lexer.ignore_while([](char c) {
  54. return Infra::is_ascii_whitespace(c);
  55. });
  56. if (lexer.is_eof())
  57. return {};
  58. if (lexer.consume_specific('"')) {
  59. auto matching_double_quote = lexer.remaining().find('"');
  60. if (!matching_double_quote.has_value())
  61. return {};
  62. auto encoding = lexer.remaining().substring_view(0, matching_double_quote.value());
  63. return TextCodec::get_standardized_encoding(encoding);
  64. }
  65. if (lexer.consume_specific('\'')) {
  66. auto matching_single_quote = lexer.remaining().find('\'');
  67. if (!matching_single_quote.has_value())
  68. return {};
  69. auto encoding = lexer.remaining().substring_view(0, matching_single_quote.value());
  70. return TextCodec::get_standardized_encoding(encoding);
  71. }
  72. auto encoding = lexer.consume_until([](char c) {
  73. return Infra::is_ascii_whitespace(c) || c == ';';
  74. });
  75. return TextCodec::get_standardized_encoding(encoding);
  76. }
  77. // https://html.spec.whatwg.org/multipage/parsing.html#concept-get-attributes-when-sniffing
  78. JS::GCPtr<DOM::Attr> prescan_get_attribute(DOM::Document& document, ByteBuffer const& input, size_t& position)
  79. {
  80. // 1. If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x2F (/) then advance position to the next byte and redo this step.
  81. if (!prescan_skip_whitespace_and_slashes(input, position))
  82. return {};
  83. // 2. If the byte at position is 0x3E (>), then abort the get an attribute algorithm. There isn't one.
  84. if (input[position] == '>')
  85. return {};
  86. // 3. Otherwise, the byte at position is the start of the attribute name. Let attribute name and attribute value be the empty string.
  87. // 4. Process the byte at position as follows:
  88. StringBuilder attribute_name;
  89. while (true) {
  90. // -> If it is 0x3D (=), and the attribute name is longer than the empty string
  91. if (input[position] == '=' && !attribute_name.is_empty()) {
  92. // Advance position to the next byte and jump to the step below labeled value.
  93. ++position;
  94. goto value;
  95. }
  96. // -> If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP)
  97. if (input[position] == '\t' || input[position] == '\n' || input[position] == '\f' || input[position] == '\r' || input[position] == ' ') {
  98. // Jump to the step below labeled spaces.
  99. goto spaces;
  100. }
  101. // -> If it is 0x2F (/) or 0x3E (>)
  102. if (input[position] == '/' || input[position] == '>') {
  103. // Abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.
  104. return DOM::Attr::create(document, MUST(attribute_name.to_string()), String {});
  105. }
  106. // -> If it is in the range 0x41 (A) to 0x5A (Z)
  107. if (input[position] >= 'A' && input[position] <= 'Z') {
  108. // Append the code point b+0x20 to attribute name (where b is the value of the byte at position). (This converts the input to lowercase.)
  109. attribute_name.append_code_point(input[position] + 0x20);
  110. }
  111. // -> Anything else
  112. else {
  113. // Append the code point with the same value as the byte at position to attribute name.
  114. // (It doesn't actually matter how bytes outside the ASCII range are handled here,
  115. // since only ASCII bytes can contribute to the detection of a character encoding.)
  116. attribute_name.append_code_point(input[position]);
  117. }
  118. // 5. Advance position to the next byte and return to the previous step.
  119. ++position;
  120. if (prescan_should_abort(input, position))
  121. return {};
  122. }
  123. spaces:
  124. // 6. Spaces: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP)
  125. // then advance position to the next byte, then, repeat this step.
  126. if (!prescan_skip_whitespace_and_slashes(input, position))
  127. return {};
  128. // 7. If the byte at position is not 0x3D (=), abort the get an attribute algorithm.
  129. // The attribute's name is the value of attribute name, its value is the empty string.
  130. if (input[position] != '=')
  131. return DOM::Attr::create(document, MUST(attribute_name.to_string()), String {});
  132. // 8. Advance position past the 0x3D (=) byte.
  133. ++position;
  134. value:
  135. // 9. Value: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP)
  136. // then advance position to the next byte, then, repeat this step.
  137. if (!prescan_skip_whitespace_and_slashes(input, position))
  138. return {};
  139. StringBuilder attribute_value;
  140. // 10. Process the byte at position as follows:
  141. // -> If it is 0x22 (") or 0x27 (')
  142. if (input[position] == '"' || input[position] == '\'') {
  143. // 1. Let b be the value of the byte at position.
  144. u8 quote_character = input[position];
  145. // 2. Quote loop: Advance position to the next byte.
  146. ++position;
  147. for (; !prescan_should_abort(input, position); ++position) {
  148. // 3. If the value of the byte at position is the value of b, then advance position to the next byte
  149. // and abort the "get an attribute" algorithm.
  150. // The attribute's name is the value of attribute name, and its value is the value of attribute value.
  151. if (input[position] == quote_character)
  152. return DOM::Attr::create(document, MUST(attribute_name.to_string()), MUST(attribute_value.to_string()));
  153. // 4. Otherwise, if the value of the byte at position is in the range 0x41 (A) to 0x5A (Z),
  154. // then append a code point to attribute value whose value is 0x20 more than the value of the byte at position.
  155. if (input[position] >= 'A' && input[position] <= 'Z') {
  156. attribute_value.append_code_point(input[position] + 0x20);
  157. }
  158. // 5. Otherwise, append a code point to attribute value whose value is the same as the value of the byte at position.
  159. else {
  160. attribute_value.append_code_point(input[position]);
  161. }
  162. // 6. Return to the step above labeled quote loop.
  163. }
  164. return {};
  165. }
  166. // -> If it is 0x3E (>)
  167. if (input[position] == '>') {
  168. // Abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.
  169. return DOM::Attr::create(document, MUST(attribute_name.to_string()), String {});
  170. }
  171. // -> If it is in the range 0x41 (A) to 0x5A (Z)
  172. if (input[position] >= 'A' && input[position] <= 'Z') {
  173. // Append a code point b+0x20 to attribute value (where b is the value of the byte at position).
  174. attribute_value.append_code_point(input[position] + 0x20);
  175. // Advance position to the next byte.
  176. ++position;
  177. }
  178. // -> Anything else
  179. else {
  180. // Append a code point with the same value as the byte at position to attribute value.
  181. attribute_value.append_code_point(input[position]);
  182. // Advance position to the next byte.
  183. ++position;
  184. }
  185. if (prescan_should_abort(input, position))
  186. return {};
  187. // 11. Process the byte at position as follows:
  188. for (; !prescan_should_abort(input, position); ++position) {
  189. // -> If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>)
  190. if (input[position] == '\t' || input[position] == '\n' || input[position] == '\f' || input[position] == '\r' || input[position] == ' ' || input[position] == '>') {
  191. // Abort the get an attribute algorithm. The attribute's name is the value of attribute name and its value is the value of attribute value.
  192. return DOM::Attr::create(document, MUST(attribute_name.to_string()), MUST(attribute_value.to_string()));
  193. }
  194. // -> If it is in the range 0x41 (A) to 0x5A (Z)
  195. if (input[position] >= 'A' && input[position] <= 'Z') {
  196. // Append a code point b+0x20 to attribute value (where b is the value of the byte at position).
  197. attribute_value.append_code_point(input[position] + 0x20);
  198. }
  199. // -> Anything else
  200. else {
  201. // Append a code point with the same value as the byte at position to attribute value.
  202. attribute_value.append_code_point(input[position]);
  203. }
  204. // 12. Advance position to the next byte and return to the previous step.
  205. }
  206. return {};
  207. }
  208. // https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding
  209. Optional<ByteString> run_prescan_byte_stream_algorithm(DOM::Document& document, ByteBuffer const& input)
  210. {
  211. // https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding
  212. // Detects '<?x'
  213. if (!prescan_should_abort(input, 5)) {
  214. // A sequence of bytes starting with: 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0
  215. if (input[0] == 0x3C && input[1] == 0x00 && input[2] == 0x3F && input[3] == 0x00 && input[4] == 0x78 && input[5] == 0x00)
  216. return "utf-16le";
  217. // A sequence of bytes starting with: 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78
  218. if (input[0] == 0x00 && input[1] == 0x3C && input[2] == 0x00 && input[3] == 0x3F && input[4] == 0x00 && input[5] == 0x78)
  219. return "utf-16be";
  220. }
  221. for (size_t position = 0; !prescan_should_abort(input, position); ++position) {
  222. if (!prescan_should_abort(input, position + 5) && input[position] == '<' && input[position + 1] == '!'
  223. && input[position + 2] == '-' && input[position + 3] == '-') {
  224. position += 2;
  225. for (; !prescan_should_abort(input, position + 3); ++position) {
  226. if (input[position] == '-' && input[position + 1] == '-' && input[position + 2] == '>') {
  227. position += 2;
  228. break;
  229. }
  230. }
  231. } else if (!prescan_should_abort(input, position + 6)
  232. && input[position] == '<'
  233. && (input[position + 1] == 'M' || input[position + 1] == 'm')
  234. && (input[position + 2] == 'E' || input[position + 2] == 'e')
  235. && (input[position + 3] == 'T' || input[position + 3] == 't')
  236. && (input[position + 4] == 'A' || input[position + 4] == 'a')
  237. && prescan_is_whitespace_or_slash(input[position + 5])) {
  238. position += 6;
  239. Vector<FlyString> attribute_list {};
  240. bool got_pragma = false;
  241. Optional<bool> need_pragma {};
  242. Optional<ByteString> charset {};
  243. while (true) {
  244. auto attribute = prescan_get_attribute(document, input, position);
  245. if (!attribute)
  246. break;
  247. if (attribute_list.contains_slow(attribute->name()))
  248. continue;
  249. auto const& attribute_name = attribute->name();
  250. attribute_list.append(attribute->name());
  251. if (attribute_name == "http-equiv") {
  252. got_pragma = attribute->value() == "content-type";
  253. } else if (attribute_name == "content") {
  254. auto encoding = extract_character_encoding_from_meta_element(attribute->value().to_byte_string());
  255. if (encoding.has_value() && !charset.has_value()) {
  256. charset = encoding.value();
  257. need_pragma = true;
  258. }
  259. } else if (attribute_name == "charset") {
  260. auto maybe_charset = TextCodec::get_standardized_encoding(attribute->value());
  261. if (maybe_charset.has_value()) {
  262. charset = Optional<ByteString> { maybe_charset };
  263. need_pragma = { false };
  264. }
  265. }
  266. }
  267. if (!need_pragma.has_value() || (need_pragma.value() && !got_pragma) || !charset.has_value())
  268. continue;
  269. if (charset.value() == "UTF-16BE/LE")
  270. return "UTF-8";
  271. else if (charset.value() == "x-user-defined")
  272. return "windows-1252";
  273. else
  274. return charset.value();
  275. } else if (!prescan_should_abort(input, position + 3) && input[position] == '<'
  276. && ((input[position + 1] == '/' && isalpha(input[position + 2])) || isalpha(input[position + 1]))) {
  277. position += 2;
  278. prescan_skip_whitespace_and_slashes(input, position);
  279. while (prescan_get_attribute(document, input, position)) { };
  280. } else if (!prescan_should_abort(input, position + 1) && input[position] == '<' && (input[position + 1] == '!' || input[position + 1] == '/' || input[position + 1] == '?')) {
  281. position += 1;
  282. do {
  283. position += 1;
  284. if (prescan_should_abort(input, position))
  285. return {};
  286. } while (input[position] != '>');
  287. } else {
  288. // Do nothing.
  289. }
  290. }
  291. return {};
  292. }
  293. // https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding
  294. ByteString run_encoding_sniffing_algorithm(DOM::Document& document, ByteBuffer const& input)
  295. {
  296. if (input.size() >= 2) {
  297. if (input[0] == 0xFE && input[1] == 0xFF) {
  298. return "UTF-16BE";
  299. } else if (input[0] == 0xFF && input[1] == 0xFE) {
  300. return "UTF-16LE";
  301. } else if (input.size() >= 3 && input[0] == 0xEF && input[1] == 0xBB && input[2] == 0xBF) {
  302. return "UTF-8";
  303. }
  304. }
  305. // FIXME: If the user has explicitly instructed the user agent to override the document's character
  306. // encoding with a specific encoding.
  307. // FIXME: The user agent may wait for more bytes of the resource to be available, either in this step or
  308. // at any later step in this algorithm.
  309. // FIXME: If the transport layer specifies a character encoding, and it is supported.
  310. auto optional_encoding = run_prescan_byte_stream_algorithm(document, input);
  311. if (optional_encoding.has_value()) {
  312. return optional_encoding.value();
  313. }
  314. // FIXME: If the HTML parser for which this algorithm is being run is associated with a Document whose browsing context
  315. // is non-null and a child browsing context.
  316. // FIXME: If the user agent has information on the likely encoding for this page, e.g. based on the encoding of the page
  317. // when it was last visited.
  318. if (!Utf8View(StringView(input)).validate()) {
  319. // FIXME: As soon as Locale is supported, this should sometimes return a different encoding based on the locale.
  320. return "windows-1252";
  321. }
  322. // NOTE: This is the authoritative place to actually decide on using the default encoding as per the HTML specification.
  323. // "Otherwise, return an implementation-defined or user-specified default character encoding, [...]."
  324. return "UTF-8";
  325. }
  326. }