FrameLoader.cpp 16 KB

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