FrameLoader.cpp 16 KB

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