FrameLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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::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())).release_allocated_value_but_fixme_should_propagate_errors();
  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. request.set_main_resource(true);
  181. auto& url = request.url();
  182. if (type == Type::Navigation || type == Type::Reload || type == Type::Redirect) {
  183. if (auto* page = browsing_context().page()) {
  184. if (&page->top_level_browsing_context() == m_browsing_context)
  185. page->client().page_did_start_loading(url, type == Type::Redirect);
  186. }
  187. }
  188. // https://fetch.spec.whatwg.org/#concept-fetch
  189. // Step 12: If request’s header list does not contain `Accept`, then:
  190. // 1. Let value be `*/*`. (NOTE: Not necessary as we're about to override it)
  191. // 2. A user agent should set value to the first matching statement, if any, switching on request’s destination:
  192. // -> "document"
  193. // -> "frame"
  194. // -> "iframe"
  195. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  196. if (!request.headers().contains("Accept"))
  197. request.set_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  198. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  199. if (type == Type::IFrame)
  200. return true;
  201. auto* document = browsing_context().active_document();
  202. if (document && document->has_active_favicon())
  203. return true;
  204. if (url.scheme() == "http" || url.scheme() == "https") {
  205. AK::URL favicon_url;
  206. favicon_url.set_scheme(url.scheme());
  207. favicon_url.set_host(url.host());
  208. favicon_url.set_port(url.port_or_default());
  209. favicon_url.set_paths({ "favicon.ico" });
  210. ResourceLoader::the().load(
  211. favicon_url,
  212. [this, favicon_url](auto data, auto&, auto) {
  213. // Always fetch the current document
  214. auto* document = this->browsing_context().active_document();
  215. if (document && document->has_active_favicon())
  216. return;
  217. dbgln_if(SPAM_DEBUG, "Favicon downloaded, {} bytes from {}", data.size(), favicon_url);
  218. if (data.is_empty())
  219. return;
  220. RefPtr<Gfx::Bitmap> favicon_bitmap;
  221. auto decoded_image = Platform::ImageCodecPlugin::the().decode_image(data);
  222. if (!decoded_image.has_value() || decoded_image->frames.is_empty()) {
  223. dbgln("Could not decode favicon {}", favicon_url);
  224. } else {
  225. favicon_bitmap = decoded_image->frames[0].bitmap;
  226. dbgln_if(IMAGE_DECODER_DEBUG, "Decoded favicon, {}", favicon_bitmap->size());
  227. }
  228. load_favicon(favicon_bitmap);
  229. },
  230. [this](auto&, auto) {
  231. // Always fetch the current document
  232. auto* document = this->browsing_context().active_document();
  233. if (document && document->has_active_favicon())
  234. return;
  235. load_favicon();
  236. });
  237. } else {
  238. load_favicon();
  239. }
  240. return true;
  241. }
  242. bool FrameLoader::load(const AK::URL& url, Type type)
  243. {
  244. dbgln_if(SPAM_DEBUG, "FrameLoader::load: {}", url);
  245. if (!url.is_valid()) {
  246. load_error_page(url, "Invalid URL");
  247. return false;
  248. }
  249. auto request = LoadRequest::create_for_url_on_page(url, browsing_context().page());
  250. return load(request, type);
  251. }
  252. void FrameLoader::load_html(StringView html, const AK::URL& url)
  253. {
  254. auto& vm = Bindings::main_thread_vm();
  255. auto response = Fetch::Infrastructure::Response::create(vm);
  256. response->url_list().append(url);
  257. HTML::NavigationParams navigation_params {
  258. .id = {},
  259. .request = nullptr,
  260. .response = response,
  261. .origin = HTML::Origin {},
  262. .policy_container = HTML::PolicyContainer {},
  263. .final_sandboxing_flag_set = HTML::SandboxingFlagSet {},
  264. .cross_origin_opener_policy = HTML::CrossOriginOpenerPolicy {},
  265. .coop_enforcement_result = HTML::CrossOriginOpenerPolicyEnforcementResult {},
  266. .reserved_environment = {},
  267. .browsing_context = browsing_context(),
  268. };
  269. auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html", move(navigation_params)).release_value_but_fixme_should_propagate_errors();
  270. browsing_context().set_active_document(document);
  271. auto parser = HTML::HTMLParser::create(document, html, "utf-8");
  272. parser->run(url);
  273. }
  274. static DeprecatedString s_error_page_url = "file:///res/html/error.html";
  275. void FrameLoader::set_error_page_url(DeprecatedString error_page_url)
  276. {
  277. s_error_page_url = error_page_url;
  278. }
  279. // FIXME: Use an actual templating engine (our own one when it's built, preferably
  280. // with a way to check these usages at compile time)
  281. void FrameLoader::load_error_page(const AK::URL& failed_url, DeprecatedString const& error)
  282. {
  283. LoadRequest request = LoadRequest::create_for_url_on_page(s_error_page_url, browsing_context().page());
  284. ResourceLoader::the().load(
  285. request,
  286. [this, failed_url, error](auto data, auto&, auto) {
  287. VERIFY(!data.is_null());
  288. StringBuilder builder;
  289. SourceGenerator generator { builder };
  290. generator.set("failed_url", escape_html_entities(failed_url.to_deprecated_string()));
  291. generator.set("error", escape_html_entities(error));
  292. generator.append(data);
  293. load_html(generator.as_string_view(), s_error_page_url);
  294. },
  295. [](auto& error, auto) {
  296. dbgln("Failed to load error page: {}", error);
  297. VERIFY_NOT_REACHED();
  298. });
  299. }
  300. void FrameLoader::load_favicon(RefPtr<Gfx::Bitmap> bitmap)
  301. {
  302. if (auto* page = browsing_context().page()) {
  303. if (bitmap)
  304. page->client().page_did_change_favicon(*bitmap);
  305. else if (s_default_favicon_bitmap)
  306. page->client().page_did_change_favicon(*s_default_favicon_bitmap);
  307. }
  308. }
  309. void FrameLoader::resource_did_load()
  310. {
  311. // This prevents us setting up the document of a removed browsing context container (BCC, e.g. <iframe>), which will cause a crash
  312. // if the document contains a script that inserts another BCC as this will use the stale browsing context it previously set up,
  313. // even if it's reinserted.
  314. // Example:
  315. // index.html:
  316. // ```
  317. // <body><script>
  318. // var i = document.createElement("iframe");
  319. // i.src = "b.html";
  320. // document.body.append(i);
  321. // i.remove();
  322. // </script>
  323. // ```
  324. // b.html:
  325. // ```
  326. // <body><script>
  327. // var i = document.createElement("iframe");
  328. // document.body.append(i);
  329. // </script>
  330. // ```
  331. // Required by Prebid.js, which does this by inserting an <iframe> into a <div> in the active document via innerHTML,
  332. // then transfers it to the <html> element:
  333. // https://github.com/prebid/Prebid.js/blob/7b7389c5abdd05626f71c3df606a93713d1b9f85/src/utils.js#L597
  334. // This is done in the spec by removing all tasks and aborting all fetches when a document is destroyed:
  335. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document
  336. if (browsing_context().has_been_discarded())
  337. return;
  338. auto url = resource()->url();
  339. // For 3xx (Redirection) responses, the Location value refers to the preferred target resource for automatically redirecting the request.
  340. auto status_code = resource()->status_code();
  341. if (status_code.has_value() && *status_code >= 300 && *status_code <= 399) {
  342. auto location = resource()->response_headers().get("Location");
  343. if (location.has_value()) {
  344. if (m_redirects_count > maximum_redirects_allowed) {
  345. m_redirects_count = 0;
  346. load_error_page(url, "Too many redirects");
  347. return;
  348. }
  349. m_redirects_count++;
  350. load(url.complete_url(location.value()), Type::Redirect);
  351. return;
  352. }
  353. }
  354. m_redirects_count = 0;
  355. if (resource()->has_encoding()) {
  356. dbgln_if(RESOURCE_DEBUG, "This content has MIME type '{}', encoding '{}'", resource()->mime_type(), resource()->encoding().value());
  357. } else {
  358. dbgln_if(RESOURCE_DEBUG, "This content has MIME type '{}', encoding unknown", resource()->mime_type());
  359. }
  360. auto final_sandboxing_flag_set = HTML::SandboxingFlagSet {};
  361. // (Part of https://html.spec.whatwg.org/#navigating-across-documents)
  362. // 3. Let responseOrigin be the result of determining the origin given browsingContext, resource's url, finalSandboxFlags, and incumbentNavigationOrigin.
  363. // FIXME: Pass incumbentNavigationOrigin
  364. auto response_origin = HTML::determine_the_origin(browsing_context(), url, final_sandboxing_flag_set, {});
  365. auto& vm = Bindings::main_thread_vm();
  366. auto response = Fetch::Infrastructure::Response::create(vm);
  367. response->url_list().append(url);
  368. HTML::NavigationParams navigation_params {
  369. .id = {},
  370. .request = nullptr,
  371. .response = response,
  372. .origin = move(response_origin),
  373. .policy_container = HTML::PolicyContainer {},
  374. .final_sandboxing_flag_set = final_sandboxing_flag_set,
  375. .cross_origin_opener_policy = HTML::CrossOriginOpenerPolicy {},
  376. .coop_enforcement_result = HTML::CrossOriginOpenerPolicyEnforcementResult {},
  377. .reserved_environment = {},
  378. .browsing_context = browsing_context(),
  379. };
  380. auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html", move(navigation_params)).release_value_but_fixme_should_propagate_errors();
  381. document->set_url(url);
  382. document->set_encoding(resource()->encoding());
  383. document->set_content_type(resource()->mime_type());
  384. browsing_context().set_active_document(document);
  385. if (auto* page = browsing_context().page())
  386. page->client().page_did_create_main_document();
  387. if (!parse_document(*document, resource()->encoded_data())) {
  388. load_error_page(url, "Failed to parse content.");
  389. return;
  390. }
  391. if (!url.fragment().is_empty())
  392. browsing_context().scroll_to_anchor(url.fragment());
  393. else
  394. browsing_context().scroll_to({ 0, 0 });
  395. if (auto* page = browsing_context().page())
  396. page->client().page_did_finish_loading(url);
  397. }
  398. void FrameLoader::resource_did_fail()
  399. {
  400. // See comment in resource_did_load() about why this is done.
  401. if (browsing_context().has_been_discarded())
  402. return;
  403. load_error_page(resource()->url(), resource()->error());
  404. }
  405. }