FrameLoader.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/LexicalPath.h>
  8. #include <AK/SourceGenerator.h>
  9. #include <LibGemini/Document.h>
  10. #include <LibGfx/ImageDecoder.h>
  11. #include <LibMarkdown/Document.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/DOM/ElementFactory.h>
  14. #include <LibWeb/DOM/Text.h>
  15. #include <LibWeb/HTML/HTMLIFrameElement.h>
  16. #include <LibWeb/HTML/Parser/HTMLDocumentParser.h>
  17. #include <LibWeb/Loader/FrameLoader.h>
  18. #include <LibWeb/Loader/ResourceLoader.h>
  19. #include <LibWeb/Namespace.h>
  20. #include <LibWeb/Page/BrowsingContext.h>
  21. #include <LibWeb/Page/Page.h>
  22. namespace Web {
  23. FrameLoader::FrameLoader(BrowsingContext& browsing_context)
  24. : m_browsing_context(browsing_context)
  25. {
  26. }
  27. FrameLoader::~FrameLoader()
  28. {
  29. }
  30. static bool build_markdown_document(DOM::Document& document, const ByteBuffer& data)
  31. {
  32. auto markdown_document = Markdown::Document::parse(data);
  33. if (!markdown_document)
  34. return false;
  35. HTML::HTMLDocumentParser parser(document, markdown_document->render_to_html(), "utf-8");
  36. parser.run(document.url());
  37. return true;
  38. }
  39. static bool build_text_document(DOM::Document& document, const ByteBuffer& data)
  40. {
  41. auto html_element = document.create_element("html");
  42. document.append_child(html_element);
  43. auto head_element = document.create_element("head");
  44. html_element->append_child(head_element);
  45. auto title_element = document.create_element("title");
  46. head_element->append_child(title_element);
  47. auto title_text = document.create_text_node(document.url().basename());
  48. title_element->append_child(title_text);
  49. auto body_element = document.create_element("body");
  50. html_element->append_child(body_element);
  51. auto pre_element = document.create_element("pre");
  52. body_element->append_child(pre_element);
  53. pre_element->append_child(document.create_text_node(String::copy(data)));
  54. return true;
  55. }
  56. static bool build_image_document(DOM::Document& document, const ByteBuffer& data)
  57. {
  58. auto image_decoder = Gfx::ImageDecoder::try_create(data.bytes());
  59. if (!image_decoder)
  60. return false;
  61. auto bitmap = image_decoder->bitmap();
  62. if (!bitmap)
  63. return false;
  64. auto html_element = document.create_element("html");
  65. document.append_child(html_element);
  66. auto head_element = document.create_element("head");
  67. html_element->append_child(head_element);
  68. auto title_element = document.create_element("title");
  69. head_element->append_child(title_element);
  70. auto basename = LexicalPath::basename(document.url().path());
  71. auto title_text = adopt_ref(*new DOM::Text(document, String::formatted("{} [{}x{}]", basename, bitmap->width(), bitmap->height())));
  72. title_element->append_child(title_text);
  73. auto body_element = document.create_element("body");
  74. html_element->append_child(body_element);
  75. auto image_element = document.create_element("img");
  76. image_element->set_attribute(HTML::AttributeNames::src, document.url().to_string());
  77. body_element->append_child(image_element);
  78. return true;
  79. }
  80. static bool build_gemini_document(DOM::Document& document, const ByteBuffer& data)
  81. {
  82. StringView gemini_data { data };
  83. auto gemini_document = Gemini::Document::parse(gemini_data, document.url());
  84. String html_data = gemini_document->render_to_html();
  85. dbgln_if(GEMINI_DEBUG, "Gemini data:\n\"\"\"{}\"\"\"", gemini_data);
  86. dbgln_if(GEMINI_DEBUG, "Converted to HTML:\n\"\"\"{}\"\"\"", html_data);
  87. HTML::HTMLDocumentParser parser(document, html_data, "utf-8");
  88. parser.run(document.url());
  89. return true;
  90. }
  91. bool FrameLoader::parse_document(DOM::Document& document, const ByteBuffer& data)
  92. {
  93. auto& mime_type = document.content_type();
  94. if (mime_type == "text/html" || mime_type == "image/svg+xml") {
  95. auto parser = HTML::HTMLDocumentParser::create_with_uncertain_encoding(document, data);
  96. parser->run(document.url());
  97. return true;
  98. }
  99. if (mime_type.starts_with("image/"))
  100. return build_image_document(document, data);
  101. if (mime_type == "text/plain" || mime_type == "application/json")
  102. return build_text_document(document, data);
  103. if (mime_type == "text/markdown")
  104. return build_markdown_document(document, data);
  105. if (mime_type == "text/gemini")
  106. return build_gemini_document(document, data);
  107. return false;
  108. }
  109. bool FrameLoader::load(const LoadRequest& request, Type type)
  110. {
  111. if (!request.is_valid()) {
  112. load_error_page(request.url(), "Invalid request");
  113. return false;
  114. }
  115. if (!m_browsing_context.is_frame_nesting_allowed(request.url())) {
  116. dbgln("No further recursion is allowed for the frame, abort load!");
  117. return false;
  118. }
  119. auto& url = request.url();
  120. if (type == Type::Navigation || type == Type::Reload) {
  121. if (auto* page = browsing_context().page())
  122. page->client().page_did_start_loading(url);
  123. }
  124. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  125. if (type == Type::IFrame)
  126. return true;
  127. if (url.protocol() == "http" || url.protocol() == "https") {
  128. URL favicon_url;
  129. favicon_url.set_protocol(url.protocol());
  130. favicon_url.set_host(url.host());
  131. favicon_url.set_port(url.port());
  132. favicon_url.set_paths({ "favicon.ico" });
  133. ResourceLoader::the().load(
  134. favicon_url,
  135. [this, favicon_url](auto data, auto&, auto) {
  136. dbgln("Favicon downloaded, {} bytes from {}", data.size(), favicon_url);
  137. auto decoder = Gfx::ImageDecoder::try_create(data);
  138. if (!decoder) {
  139. dbgln("No image decoder plugin for favicon {}", favicon_url);
  140. return;
  141. }
  142. auto bitmap = decoder->bitmap();
  143. if (!bitmap) {
  144. dbgln("Could not decode favicon {}", favicon_url);
  145. return;
  146. }
  147. dbgln("Decoded favicon, {}", bitmap->size());
  148. if (auto* page = browsing_context().page())
  149. page->client().page_did_change_favicon(*bitmap);
  150. });
  151. }
  152. return true;
  153. }
  154. bool FrameLoader::load(const URL& url, Type type)
  155. {
  156. dbgln("FrameLoader::load: {}", url);
  157. if (!url.is_valid()) {
  158. load_error_page(url, "Invalid URL");
  159. return false;
  160. }
  161. auto request = LoadRequest::create_for_url_on_page(url, browsing_context().page());
  162. return load(request, type);
  163. }
  164. void FrameLoader::load_html(const StringView& html, const URL& url)
  165. {
  166. auto document = DOM::Document::create(url);
  167. HTML::HTMLDocumentParser parser(document, html, "utf-8");
  168. parser.run(url);
  169. browsing_context().set_document(&parser.document());
  170. }
  171. // FIXME: Use an actual templating engine (our own one when it's built, preferably
  172. // with a way to check these usages at compile time)
  173. void FrameLoader::load_error_page(const URL& failed_url, const String& error)
  174. {
  175. auto error_page_url = "file:///res/html/error.html";
  176. ResourceLoader::the().load(
  177. error_page_url,
  178. [this, failed_url, error](auto data, auto&, auto) {
  179. VERIFY(!data.is_null());
  180. StringBuilder builder;
  181. SourceGenerator generator { builder };
  182. generator.set("failed_url", escape_html_entities(failed_url.to_string()));
  183. generator.set("error", escape_html_entities(error));
  184. generator.append(data);
  185. auto document = HTML::parse_html_document(generator.as_string_view(), failed_url, "utf-8");
  186. VERIFY(document);
  187. browsing_context().set_document(document);
  188. },
  189. [](auto& error, auto) {
  190. dbgln("Failed to load error page: {}", error);
  191. VERIFY_NOT_REACHED();
  192. });
  193. }
  194. void FrameLoader::resource_did_load()
  195. {
  196. auto url = resource()->url();
  197. // FIXME: Also check HTTP status code before redirecting
  198. auto location = resource()->response_headers().get("Location");
  199. if (location.has_value()) {
  200. if (m_redirects_count > maximum_redirects_allowed) {
  201. m_redirects_count = 0;
  202. load_error_page(url, "Too many redirects");
  203. return;
  204. }
  205. m_redirects_count++;
  206. load(url.complete_url(location.value()), FrameLoader::Type::Navigation);
  207. return;
  208. }
  209. m_redirects_count = 0;
  210. if (!resource()->has_encoded_data()) {
  211. load_error_page(url, "No data");
  212. return;
  213. }
  214. if (resource()->has_encoding()) {
  215. dbgln("This content has MIME type '{}', encoding '{}'", resource()->mime_type(), resource()->encoding().value());
  216. } else {
  217. dbgln("This content has MIME type '{}', encoding unknown", resource()->mime_type());
  218. }
  219. auto document = DOM::Document::create();
  220. document->set_url(url);
  221. document->set_encoding(resource()->encoding());
  222. document->set_content_type(resource()->mime_type());
  223. browsing_context().set_document(document);
  224. if (!parse_document(*document, resource()->encoded_data())) {
  225. load_error_page(url, "Failed to parse content.");
  226. return;
  227. }
  228. // FIXME: Support multiple instances of the Set-Cookie response header.
  229. auto set_cookie = resource()->response_headers().get("Set-Cookie");
  230. if (set_cookie.has_value())
  231. document->set_cookie(set_cookie.value(), Cookie::Source::Http);
  232. if (!url.fragment().is_empty())
  233. browsing_context().scroll_to_anchor(url.fragment());
  234. if (auto* host_element = browsing_context().host_element()) {
  235. // FIXME: Perhaps in the future we'll have a better common base class for <frame> and <iframe>
  236. verify_cast<HTML::HTMLIFrameElement>(*host_element).nested_browsing_context_did_load({});
  237. }
  238. if (auto* page = browsing_context().page())
  239. page->client().page_did_finish_loading(url);
  240. }
  241. void FrameLoader::resource_did_fail()
  242. {
  243. load_error_page(resource()->url(), resource()->error());
  244. }
  245. }