HTMLParser.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Function.h>
  27. #include <AK/NonnullRefPtrVector.h>
  28. #include <AK/StringBuilder.h>
  29. #include <AK/StringUtils.h>
  30. #include <LibTextCodec/Decoder.h>
  31. #include <LibWeb/DOM/Comment.h>
  32. #include <LibWeb/DOM/DocumentFragment.h>
  33. #include <LibWeb/DOM/DocumentType.h>
  34. #include <LibWeb/DOM/Element.h>
  35. #include <LibWeb/DOM/ElementFactory.h>
  36. #include <LibWeb/DOM/Event.h>
  37. #include <LibWeb/DOM/Text.h>
  38. #include <LibWeb/Parser/HTMLParser.h>
  39. #include <ctype.h>
  40. #include <stdio.h>
  41. namespace Web {
  42. static bool is_valid_in_attribute_name(char ch)
  43. {
  44. return isalnum(ch) || ch == '_' || ch == '-';
  45. }
  46. static bool is_void_element(const StringView& tag_name)
  47. {
  48. return tag_name == "area"
  49. || tag_name == "base"
  50. || tag_name == "br"
  51. || tag_name == "col"
  52. || tag_name == "embed"
  53. || tag_name == "hr"
  54. || tag_name == "img"
  55. || tag_name == "input"
  56. || tag_name == "link"
  57. || tag_name == "meta"
  58. || tag_name == "param"
  59. || tag_name == "source"
  60. || tag_name == "track"
  61. || tag_name == "wbr";
  62. }
  63. static Vector<char> codepoint_to_bytes(const u32 codepoint)
  64. {
  65. Vector<char, 0> bytes;
  66. if (codepoint < 0x80) {
  67. bytes.insert(0, (char)codepoint);
  68. } else if (codepoint < 0x800) {
  69. char b2 = (codepoint & 0x3F) + 0x80;
  70. char b1 = ((codepoint >> 6) & 0x1F) + +0xC0;
  71. bytes.insert(0, b1);
  72. bytes.insert(1, b2);
  73. }
  74. return bytes;
  75. }
  76. static bool deprecated_parse_html_document(const StringView& html, Document& document, ParentNode& root)
  77. {
  78. NonnullRefPtrVector<ParentNode> node_stack;
  79. node_stack.append(root);
  80. enum class State {
  81. Free = 0,
  82. BeforeTagName,
  83. InTagName,
  84. InDoctype,
  85. InComment,
  86. InAttributeList,
  87. InAttributeName,
  88. BeforeAttributeValue,
  89. InAttributeValueNoQuote,
  90. InAttributeValueSingleQuote,
  91. InAttributeValueDoubleQuote,
  92. };
  93. auto state = State::Free;
  94. StringBuilder text_buffer;
  95. Vector<char, 32> tag_name_buffer;
  96. Vector<Attribute> attributes;
  97. Vector<char, 256> attribute_name_buffer;
  98. Vector<char, 256> attribute_value_buffer;
  99. bool is_slash_tag = false;
  100. bool is_exclamation_tag = false;
  101. auto commit_text_node = [&] {
  102. auto text_node = adopt(*new Text(document, text_buffer.to_string()));
  103. node_stack.last().append_child(text_node);
  104. text_buffer.clear();
  105. };
  106. auto move_to_state = [&](State new_state) {
  107. if (new_state == State::BeforeTagName) {
  108. is_slash_tag = false;
  109. is_exclamation_tag = false;
  110. tag_name_buffer.clear();
  111. attributes.clear();
  112. }
  113. if (new_state == State::InAttributeName)
  114. attribute_name_buffer.clear();
  115. if (new_state == State::BeforeAttributeValue)
  116. attribute_value_buffer.clear();
  117. if (state == State::Free && !text_buffer.is_empty()) {
  118. commit_text_node();
  119. }
  120. state = new_state;
  121. text_buffer.clear();
  122. };
  123. auto close_tag = [&] {
  124. if (node_stack.size() > 1)
  125. node_stack.take_last();
  126. };
  127. auto open_tag = [&] {
  128. auto new_element = create_element(document, String::copy(tag_name_buffer));
  129. tag_name_buffer.clear();
  130. new_element->set_attributes(move(attributes));
  131. node_stack.append(new_element);
  132. if (node_stack.size() != 1) {
  133. node_stack[node_stack.size() - 2].append_child(new_element);
  134. }
  135. if (is_void_element(new_element->tag_name()))
  136. close_tag();
  137. };
  138. auto commit_doctype = [&] {
  139. node_stack.last().append_child(adopt(*new DocumentType(document)));
  140. };
  141. auto commit_comment = [&] {
  142. node_stack.last().append_child(adopt(*new Comment(document, text_buffer.to_string())));
  143. };
  144. auto commit_tag = [&] {
  145. if (is_slash_tag)
  146. close_tag();
  147. else
  148. open_tag();
  149. };
  150. auto commit_attribute = [&] {
  151. if (!attribute_name_buffer.is_empty()) {
  152. auto name = String::copy(attribute_name_buffer);
  153. String value;
  154. if (attribute_value_buffer.is_empty())
  155. value = String::empty();
  156. else
  157. value = String::copy(attribute_value_buffer);
  158. attributes.empend(name, value);
  159. }
  160. };
  161. for (size_t i = 0; i < html.length(); ++i) {
  162. auto peek = [&](size_t offset) -> char {
  163. if (i + offset >= html.length())
  164. return '\0';
  165. return html[i + offset];
  166. };
  167. char ch = html[i];
  168. switch (state) {
  169. case State::Free:
  170. if (ch == '<') {
  171. bool should_treat_as_text = false;
  172. if (node_stack.last().node_name() == "script") {
  173. bool is_script_close_tag = peek(1) == '/'
  174. && tolower(peek(2)) == 's'
  175. && tolower(peek(3)) == 'c'
  176. && tolower(peek(4)) == 'r'
  177. && tolower(peek(5)) == 'i'
  178. && tolower(peek(6)) == 'p'
  179. && tolower(peek(7)) == 't'
  180. && tolower(peek(8)) == '>';
  181. if (!is_script_close_tag)
  182. should_treat_as_text = true;
  183. }
  184. if (!should_treat_as_text) {
  185. is_slash_tag = false;
  186. move_to_state(State::BeforeTagName);
  187. break;
  188. }
  189. }
  190. if (ch != '&') {
  191. text_buffer.append(ch);
  192. } else {
  193. struct Escape {
  194. const char* code;
  195. const char* value;
  196. };
  197. static Escape escapes[] = {
  198. { "&lt;", "<" },
  199. { "&gt;", ">" },
  200. { "&amp;", "&" },
  201. { "&mdash;", "-" },
  202. { "&nbsp;", " " }, // FIXME: Should actually be *non-breaking*
  203. { "&quot;", "\"" },
  204. { "&raquo;", ">>" },
  205. { "&laquo;", "<<" },
  206. { "&copy;", "©" },
  207. { "&reg;", "®" },
  208. { "&szlig;", "ß" },
  209. { "&auml;", "ä" },
  210. { "&euml;", "ë" },
  211. { "&iuml;", "ï" },
  212. { "&ouml;", "ö" },
  213. { "&uuml;", "ü" },
  214. { "&yuml;", "ÿ" },
  215. { "&Auml;", "Ä" },
  216. { "&Euml;", "Ë" },
  217. { "&Iuml;", "Ï" },
  218. { "&Ouml;", "Ö" },
  219. { "&Uuml;", "Ü" },
  220. { "&Yuml;", "Ÿ" },
  221. };
  222. auto rest_of_html = html.substring_view(i, html.length() - i);
  223. bool found = false;
  224. for (auto& escape : escapes) {
  225. if (rest_of_html.starts_with(escape.code)) {
  226. text_buffer.append(escape.value);
  227. found = true;
  228. i += strlen(escape.code) - 1;
  229. break;
  230. }
  231. }
  232. if (!found) {
  233. char num_sign = html[i + 1];
  234. if (num_sign && num_sign == '#') {
  235. int j = 2; // spip '&#' and search for ';'
  236. while (html[i + j] != ';' && j < 7) {
  237. j++;
  238. }
  239. if (j < 7) { // We found ; char
  240. Optional<u32> codepoint;
  241. String str_code_point = html.substring_view(i + 2, j - 2);
  242. if (str_code_point.starts_with('x')) {
  243. String str = str_code_point.substring(1, str_code_point.length() - 1);
  244. codepoint = AK::StringUtils::convert_to_uint_from_hex(str);
  245. } else {
  246. codepoint = str_code_point.to_uint();
  247. }
  248. if (codepoint.has_value()) {
  249. Vector<char> bytes = codepoint_to_bytes(codepoint.value());
  250. if (bytes.size() > 0) {
  251. for (size_t i = 0; i < bytes.size(); i++) {
  252. text_buffer.append(bytes.at(i));
  253. }
  254. found = true;
  255. i = i + j;
  256. }
  257. }
  258. }
  259. }
  260. }
  261. if (!found) {
  262. dbg() << "Unhandled escape sequence:" << html.substring_view(i, min((size_t)5, html.length()));
  263. }
  264. }
  265. break;
  266. case State::BeforeTagName:
  267. if (ch == '/') {
  268. is_slash_tag = true;
  269. break;
  270. }
  271. if (ch == '!') {
  272. if (toupper(peek(1)) == 'D'
  273. && toupper(peek(2)) == 'O'
  274. && toupper(peek(3)) == 'C'
  275. && toupper(peek(4)) == 'T'
  276. && toupper(peek(5)) == 'Y'
  277. && toupper(peek(6)) == 'P'
  278. && toupper(peek(7)) == 'E') {
  279. i += 7;
  280. move_to_state(State::InDoctype);
  281. break;
  282. }
  283. if (peek(1) == '-' && peek(2) == '-') {
  284. i += 2;
  285. move_to_state(State::InComment);
  286. break;
  287. }
  288. break;
  289. }
  290. if (ch == '>') {
  291. move_to_state(State::Free);
  292. break;
  293. }
  294. if (!isalpha(ch))
  295. break;
  296. move_to_state(State::InTagName);
  297. [[fallthrough]];
  298. case State::InTagName:
  299. if (isspace(ch)) {
  300. move_to_state(State::InAttributeList);
  301. break;
  302. }
  303. if (ch == '/' && peek(1) == '>') {
  304. open_tag();
  305. close_tag();
  306. i += 1;
  307. move_to_state(State::Free);
  308. break;
  309. }
  310. if (ch == '>') {
  311. commit_tag();
  312. move_to_state(State::Free);
  313. break;
  314. }
  315. tag_name_buffer.append(ch);
  316. break;
  317. case State::InDoctype:
  318. if (ch == '>') {
  319. commit_doctype();
  320. move_to_state(State::Free);
  321. break;
  322. }
  323. break;
  324. case State::InComment:
  325. if (ch == '-' && peek(1) == '-' && peek(2) == '>') {
  326. commit_comment();
  327. i += 2;
  328. move_to_state(State::Free);
  329. break;
  330. }
  331. text_buffer.append(ch);
  332. break;
  333. case State::InAttributeList:
  334. if (ch == '>') {
  335. commit_tag();
  336. move_to_state(State::Free);
  337. break;
  338. }
  339. if (!isalpha(ch))
  340. break;
  341. move_to_state(State::InAttributeName);
  342. [[fallthrough]];
  343. case State::InAttributeName:
  344. if (is_valid_in_attribute_name(ch)) {
  345. attribute_name_buffer.append(ch);
  346. break;
  347. }
  348. if (isspace(ch)) {
  349. commit_attribute();
  350. break;
  351. }
  352. if (ch == '>') {
  353. commit_attribute();
  354. commit_tag();
  355. move_to_state(State::Free);
  356. break;
  357. }
  358. if (ch == '=') {
  359. move_to_state(State::BeforeAttributeValue);
  360. break;
  361. }
  362. break;
  363. case State::BeforeAttributeValue:
  364. if (ch == '\'') {
  365. move_to_state(State::InAttributeValueSingleQuote);
  366. break;
  367. }
  368. if (ch == '"') {
  369. move_to_state(State::InAttributeValueDoubleQuote);
  370. break;
  371. }
  372. if (ch == '>') {
  373. commit_tag();
  374. move_to_state(State::Free);
  375. break;
  376. }
  377. if (isspace(ch)) {
  378. commit_attribute();
  379. move_to_state(State::InAttributeList);
  380. break;
  381. }
  382. move_to_state(State::InAttributeValueNoQuote);
  383. [[fallthrough]];
  384. case State::InAttributeValueNoQuote:
  385. if (isspace(ch)) {
  386. commit_attribute();
  387. move_to_state(State::InAttributeList);
  388. break;
  389. }
  390. if (ch == '>') {
  391. commit_attribute();
  392. commit_tag();
  393. move_to_state(State::Free);
  394. break;
  395. }
  396. attribute_value_buffer.append(ch);
  397. break;
  398. case State::InAttributeValueSingleQuote:
  399. if (ch == '\'') {
  400. commit_attribute();
  401. move_to_state(State::InAttributeList);
  402. break;
  403. }
  404. attribute_value_buffer.append(ch);
  405. break;
  406. case State::InAttributeValueDoubleQuote:
  407. if (ch == '"') {
  408. commit_attribute();
  409. move_to_state(State::InAttributeList);
  410. break;
  411. }
  412. attribute_value_buffer.append(ch);
  413. break;
  414. default:
  415. fprintf(stderr, "Unhandled state %d\n", (int)state);
  416. ASSERT_NOT_REACHED();
  417. }
  418. }
  419. if (!text_buffer.is_empty())
  420. commit_text_node();
  421. return true;
  422. }
  423. String to_utf8(const StringView& input, const String& encoding)
  424. {
  425. auto* decoder = TextCodec::decoder_for(encoding);
  426. ASSERT(decoder);
  427. return decoder->to_utf8(input);
  428. }
  429. RefPtr<DocumentFragment> parse_html_fragment(Document& document, const StringView& raw_html, const String& encoding)
  430. {
  431. auto fragment = adopt(*new DocumentFragment(document));
  432. if (!deprecated_parse_html_document(to_utf8(raw_html, encoding), document, *fragment))
  433. return nullptr;
  434. return fragment;
  435. }
  436. RefPtr<Document> deprecated_parse_html_document(const StringView& raw_html, const URL& url, const String& encoding)
  437. {
  438. String html = to_utf8(raw_html, encoding);
  439. auto document = adopt(*new Document(url));
  440. document->set_source(html);
  441. if (!deprecated_parse_html_document(html, *document, *document))
  442. return nullptr;
  443. document->fixup();
  444. #if 0
  445. Function<void(Node&)> fire_insertion_callbacks = [&](Node& node) {
  446. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  447. fire_insertion_callbacks(*child);
  448. }
  449. if (node.parent())
  450. node.inserted_into(*node.parent());
  451. };
  452. fire_insertion_callbacks(document);
  453. #endif
  454. document->dispatch_event(Event::create("DOMContentLoaded"));
  455. return document;
  456. }
  457. }