FrameLoader.cpp 19 KB

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