FrameLoader.cpp 12 KB

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