FrameLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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/JsonArray.h>
  8. #include <AK/LexicalPath.h>
  9. #include <AK/SourceGenerator.h>
  10. #include <LibGemini/Document.h>
  11. #include <LibGfx/ImageDecoder.h>
  12. #include <LibMarkdown/Document.h>
  13. #include <LibWeb/Cookie/ParsedCookie.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/ElementFactory.h>
  16. #include <LibWeb/DOM/Text.h>
  17. #include <LibWeb/HTML/BrowsingContext.h>
  18. #include <LibWeb/HTML/HTMLIFrameElement.h>
  19. #include <LibWeb/HTML/Parser/HTMLParser.h>
  20. #include <LibWeb/ImageDecoding.h>
  21. #include <LibWeb/Loader/FrameLoader.h>
  22. #include <LibWeb/Loader/ResourceLoader.h>
  23. #include <LibWeb/Page/Page.h>
  24. #include <LibWeb/XML/XMLDocumentBuilder.h>
  25. namespace Web {
  26. static RefPtr<Gfx::Bitmap> s_default_favicon_bitmap;
  27. FrameLoader::FrameLoader(HTML::BrowsingContext& browsing_context)
  28. : m_browsing_context(browsing_context)
  29. {
  30. if (!s_default_favicon_bitmap) {
  31. s_default_favicon_bitmap = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-browser.png").release_value_but_fixme_should_propagate_errors();
  32. VERIFY(s_default_favicon_bitmap);
  33. }
  34. }
  35. FrameLoader::~FrameLoader() = default;
  36. static bool build_markdown_document(DOM::Document& document, ByteBuffer const& data)
  37. {
  38. auto markdown_document = Markdown::Document::parse(data);
  39. if (!markdown_document)
  40. return false;
  41. auto parser = HTML::HTMLParser::create(document, markdown_document->render_to_html(), "utf-8");
  42. parser->run(document.url());
  43. return true;
  44. }
  45. static bool build_text_document(DOM::Document& document, ByteBuffer const& data)
  46. {
  47. auto html_element = document.create_element("html").release_value();
  48. document.append_child(html_element);
  49. auto head_element = document.create_element("head").release_value();
  50. html_element->append_child(head_element);
  51. auto title_element = document.create_element("title").release_value();
  52. head_element->append_child(title_element);
  53. auto title_text = document.create_text_node(document.url().basename());
  54. title_element->append_child(title_text);
  55. auto body_element = document.create_element("body").release_value();
  56. html_element->append_child(body_element);
  57. auto pre_element = document.create_element("pre").release_value();
  58. body_element->append_child(pre_element);
  59. pre_element->append_child(document.create_text_node(String::copy(data)));
  60. return true;
  61. }
  62. static bool build_image_document(DOM::Document& document, ByteBuffer const& data)
  63. {
  64. NonnullRefPtr decoder = image_decoder_client();
  65. auto image = decoder->decode_image(data);
  66. if (!image.has_value() || image->frames.is_empty())
  67. return false;
  68. auto const& frame = image->frames[0];
  69. auto const& bitmap = frame.bitmap;
  70. if (!bitmap)
  71. return false;
  72. auto html_element = document.create_element("html").release_value();
  73. document.append_child(html_element);
  74. auto head_element = document.create_element("head").release_value();
  75. html_element->append_child(head_element);
  76. auto title_element = document.create_element("title").release_value();
  77. head_element->append_child(title_element);
  78. auto basename = LexicalPath::basename(document.url().path());
  79. auto title_text = adopt_ref(*new DOM::Text(document, String::formatted("{} [{}x{}]", basename, bitmap->width(), bitmap->height())));
  80. title_element->append_child(title_text);
  81. auto body_element = document.create_element("body").release_value();
  82. html_element->append_child(body_element);
  83. auto image_element = document.create_element("img").release_value();
  84. image_element->set_attribute(HTML::AttributeNames::src, document.url().to_string());
  85. body_element->append_child(image_element);
  86. return true;
  87. }
  88. static bool build_gemini_document(DOM::Document& document, ByteBuffer const& data)
  89. {
  90. StringView gemini_data { data };
  91. auto gemini_document = Gemini::Document::parse(gemini_data, document.url());
  92. String html_data = gemini_document->render_to_html();
  93. dbgln_if(GEMINI_DEBUG, "Gemini data:\n\"\"\"{}\"\"\"", gemini_data);
  94. dbgln_if(GEMINI_DEBUG, "Converted to HTML:\n\"\"\"{}\"\"\"", html_data);
  95. auto parser = HTML::HTMLParser::create(document, html_data, "utf-8");
  96. parser->run(document.url());
  97. return true;
  98. }
  99. static bool build_xml_document(DOM::Document& document, ByteBuffer const& data)
  100. {
  101. XML::Parser parser(data, { .resolve_external_resource = resolve_xml_resource });
  102. XMLDocumentBuilder builder { document };
  103. auto result = parser.parse_with_listener(builder);
  104. return !result.is_error() && !builder.has_error();
  105. }
  106. bool FrameLoader::parse_document(DOM::Document& document, ByteBuffer const& data)
  107. {
  108. auto& mime_type = document.content_type();
  109. if (mime_type == "text/html" || mime_type == "image/svg+xml") {
  110. auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, data);
  111. parser->run(document.url());
  112. return true;
  113. }
  114. if (mime_type.ends_with("+xml") || mime_type.is_one_of("text/xml", "application/xml"))
  115. return build_xml_document(document, data);
  116. if (mime_type.starts_with("image/"))
  117. return build_image_document(document, data);
  118. if (mime_type == "text/plain" || mime_type == "application/json")
  119. return build_text_document(document, data);
  120. if (mime_type == "text/markdown")
  121. return build_markdown_document(document, data);
  122. if (mime_type == "text/gemini")
  123. return build_gemini_document(document, data);
  124. return false;
  125. }
  126. bool FrameLoader::load(LoadRequest& request, Type type)
  127. {
  128. if (!request.is_valid()) {
  129. load_error_page(request.url(), "Invalid request");
  130. return false;
  131. }
  132. if (!m_browsing_context.is_frame_nesting_allowed(request.url())) {
  133. dbgln("No further recursion is allowed for the frame, abort load!");
  134. return false;
  135. }
  136. auto& url = request.url();
  137. if (type == Type::Navigation || type == Type::Reload) {
  138. if (auto* page = browsing_context().page())
  139. page->client().page_did_start_loading(url);
  140. }
  141. // https://fetch.spec.whatwg.org/#concept-fetch
  142. // Step 12: If request’s header list does not contain `Accept`, then:
  143. // 1. Let value be `*/*`. (NOTE: Not necessary as we're about to override it)
  144. // 2. A user agent should set value to the first matching statement, if any, switching on request’s destination:
  145. // -> "document"
  146. // -> "frame"
  147. // -> "iframe"
  148. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  149. // FIXME: This should be case-insensitive.
  150. if (!request.headers().contains("Accept"))
  151. request.set_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  152. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  153. if (type == Type::IFrame)
  154. return true;
  155. auto* document = browsing_context().active_document();
  156. if (document && document->has_active_favicon())
  157. return true;
  158. if (url.protocol() == "http" || url.protocol() == "https") {
  159. AK::URL favicon_url;
  160. favicon_url.set_protocol(url.protocol());
  161. favicon_url.set_host(url.host());
  162. favicon_url.set_port(url.port_or_default());
  163. favicon_url.set_paths({ "favicon.ico" });
  164. ResourceLoader::the().load(
  165. favicon_url,
  166. [this, favicon_url](auto data, auto&, auto) {
  167. // Always fetch the current document
  168. auto* document = this->browsing_context().active_document();
  169. if (document && document->has_active_favicon())
  170. return;
  171. dbgln_if(SPAM_DEBUG, "Favicon downloaded, {} bytes from {}", data.size(), favicon_url);
  172. if (data.is_empty())
  173. return;
  174. RefPtr<Gfx::Bitmap> favicon_bitmap;
  175. auto decoded_image = image_decoder_client().decode_image(data);
  176. if (!decoded_image.has_value() || decoded_image->frames.is_empty()) {
  177. dbgln("Could not decode favicon {}", favicon_url);
  178. } else {
  179. favicon_bitmap = decoded_image->frames[0].bitmap;
  180. dbgln_if(IMAGE_DECODER_DEBUG, "Decoded favicon, {}", favicon_bitmap->size());
  181. }
  182. load_favicon(favicon_bitmap);
  183. },
  184. [this](auto&, auto) {
  185. // Always fetch the current document
  186. auto* document = this->browsing_context().active_document();
  187. if (document && document->has_active_favicon())
  188. return;
  189. load_favicon();
  190. });
  191. } else {
  192. load_favicon();
  193. }
  194. return true;
  195. }
  196. bool FrameLoader::load(const AK::URL& url, Type type)
  197. {
  198. dbgln_if(SPAM_DEBUG, "FrameLoader::load: {}", url);
  199. if (!url.is_valid()) {
  200. load_error_page(url, "Invalid URL");
  201. return false;
  202. }
  203. auto request = LoadRequest::create_for_url_on_page(url, browsing_context().page());
  204. return load(request, type);
  205. }
  206. void FrameLoader::load_html(StringView html, const AK::URL& url)
  207. {
  208. auto document = DOM::Document::create(url);
  209. auto parser = HTML::HTMLParser::create(document, html, "utf-8");
  210. parser->run(url);
  211. browsing_context().set_active_document(&parser->document());
  212. }
  213. // FIXME: Use an actual templating engine (our own one when it's built, preferably
  214. // with a way to check these usages at compile time)
  215. void FrameLoader::load_error_page(const AK::URL& failed_url, String const& error)
  216. {
  217. auto error_page_url = "file:///res/html/error.html";
  218. ResourceLoader::the().load(
  219. error_page_url,
  220. [this, failed_url, error](auto data, auto&, auto) {
  221. VERIFY(!data.is_null());
  222. StringBuilder builder;
  223. SourceGenerator generator { builder };
  224. generator.set("failed_url", escape_html_entities(failed_url.to_string()));
  225. generator.set("error", escape_html_entities(error));
  226. generator.append(data);
  227. load_html(generator.as_string_view(), failed_url);
  228. },
  229. [](auto& error, auto) {
  230. dbgln("Failed to load error page: {}", error);
  231. VERIFY_NOT_REACHED();
  232. });
  233. }
  234. void FrameLoader::load_favicon(RefPtr<Gfx::Bitmap> bitmap)
  235. {
  236. if (auto* page = browsing_context().page()) {
  237. if (bitmap)
  238. page->client().page_did_change_favicon(*bitmap);
  239. else
  240. page->client().page_did_change_favicon(*s_default_favicon_bitmap);
  241. }
  242. }
  243. void FrameLoader::store_response_cookies(AK::URL const& url, String const& cookies)
  244. {
  245. auto* page = browsing_context().page();
  246. if (!page)
  247. return;
  248. auto set_cookie_json_value = MUST(JsonValue::from_string(cookies));
  249. VERIFY(set_cookie_json_value.type() == JsonValue::Type::Array);
  250. for (auto const& set_cookie_entry : set_cookie_json_value.as_array().values()) {
  251. VERIFY(set_cookie_entry.type() == JsonValue::Type::String);
  252. auto cookie = Cookie::parse_cookie(set_cookie_entry.as_string());
  253. if (!cookie.has_value())
  254. continue;
  255. page->client().page_did_set_cookie(url, cookie.value(), Cookie::Source::Http); // FIXME: Determine cookie source correctly
  256. }
  257. }
  258. void FrameLoader::resource_did_load()
  259. {
  260. auto url = resource()->url();
  261. if (auto set_cookie = resource()->response_headers().get("Set-Cookie"); set_cookie.has_value())
  262. store_response_cookies(url, *set_cookie);
  263. // For 3xx (Redirection) responses, the Location value refers to the preferred target resource for automatically redirecting the request.
  264. auto status_code = resource()->status_code();
  265. if (status_code.has_value() && *status_code >= 300 && *status_code <= 399) {
  266. auto location = resource()->response_headers().get("Location");
  267. if (location.has_value()) {
  268. if (m_redirects_count > maximum_redirects_allowed) {
  269. m_redirects_count = 0;
  270. load_error_page(url, "Too many redirects");
  271. return;
  272. }
  273. m_redirects_count++;
  274. load(url.complete_url(location.value()), FrameLoader::Type::Navigation);
  275. return;
  276. }
  277. }
  278. m_redirects_count = 0;
  279. if (!resource()->has_encoded_data()) {
  280. load_error_page(url, "No data");
  281. return;
  282. }
  283. if (resource()->has_encoding()) {
  284. dbgln_if(RESOURCE_DEBUG, "This content has MIME type '{}', encoding '{}'", resource()->mime_type(), resource()->encoding().value());
  285. } else {
  286. dbgln_if(RESOURCE_DEBUG, "This content has MIME type '{}', encoding unknown", resource()->mime_type());
  287. }
  288. auto document = DOM::Document::create();
  289. document->set_url(url);
  290. document->set_encoding(resource()->encoding());
  291. document->set_content_type(resource()->mime_type());
  292. browsing_context().set_active_document(document);
  293. if (!parse_document(*document, resource()->encoded_data())) {
  294. load_error_page(url, "Failed to parse content.");
  295. return;
  296. }
  297. if (!url.fragment().is_empty())
  298. browsing_context().scroll_to_anchor(url.fragment());
  299. else
  300. browsing_context().scroll_to({ 0, 0 });
  301. if (auto* page = browsing_context().page())
  302. page->client().page_did_finish_loading(url);
  303. }
  304. void FrameLoader::resource_did_fail()
  305. {
  306. load_error_page(resource()->url(), resource()->error());
  307. }
  308. }