FrameLoader.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 <LibWeb/Bindings/MainThreadVM.h>
  11. #include <LibWeb/DOM/Document.h>
  12. #include <LibWeb/DOM/DocumentLoading.h>
  13. #include <LibWeb/DOM/ElementFactory.h>
  14. #include <LibWeb/DOM/Text.h>
  15. #include <LibWeb/HTML/NavigationParams.h>
  16. #include <LibWeb/HTML/Parser/HTMLParser.h>
  17. #include <LibWeb/Loader/FrameLoader.h>
  18. #include <LibWeb/Loader/ResourceLoader.h>
  19. #include <LibWeb/Namespace.h>
  20. #include <LibWeb/Page/Page.h>
  21. #include <LibWeb/Platform/ImageCodecPlugin.h>
  22. #include <LibWeb/XML/XMLDocumentBuilder.h>
  23. namespace Web {
  24. static DeprecatedString s_default_favicon_path = "/res/icons/16x16/app-browser.png";
  25. static RefPtr<Gfx::Bitmap> s_default_favicon_bitmap;
  26. void FrameLoader::set_default_favicon_path(DeprecatedString path)
  27. {
  28. s_default_favicon_path = move(path);
  29. }
  30. FrameLoader::FrameLoader(HTML::BrowsingContext& browsing_context)
  31. : m_browsing_context(browsing_context)
  32. {
  33. if (!s_default_favicon_bitmap) {
  34. s_default_favicon_bitmap = Gfx::Bitmap::load_from_file(s_default_favicon_path).release_value_but_fixme_should_propagate_errors();
  35. VERIFY(s_default_favicon_bitmap);
  36. }
  37. }
  38. FrameLoader::~FrameLoader() = default;
  39. bool FrameLoader::load(LoadRequest& request, Type type)
  40. {
  41. if (!request.is_valid()) {
  42. load_error_page(request.url(), "Invalid request");
  43. return false;
  44. }
  45. if (!m_browsing_context->is_frame_nesting_allowed(request.url())) {
  46. dbgln("No further recursion is allowed for the frame, abort load!");
  47. return false;
  48. }
  49. request.set_main_resource(true);
  50. auto& url = request.url();
  51. if (type == Type::Navigation || type == Type::Reload || type == Type::Redirect) {
  52. if (auto* page = browsing_context().page()) {
  53. if (&page->top_level_browsing_context() == m_browsing_context)
  54. page->client().page_did_start_loading(url, type == Type::Redirect);
  55. }
  56. }
  57. // https://fetch.spec.whatwg.org/#concept-fetch
  58. // Step 12: If request’s header list does not contain `Accept`, then:
  59. // 1. Let value be `*/*`. (NOTE: Not necessary as we're about to override it)
  60. // 2. A user agent should set value to the first matching statement, if any, switching on request’s destination:
  61. // -> "document"
  62. // -> "frame"
  63. // -> "iframe"
  64. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  65. if (!request.headers().contains("Accept"))
  66. request.set_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  67. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  68. if (type == Type::IFrame)
  69. return true;
  70. if (url.scheme() == "http" || url.scheme() == "https") {
  71. AK::URL favicon_url;
  72. favicon_url.set_scheme(url.scheme());
  73. favicon_url.set_host(url.host());
  74. favicon_url.set_port(url.port_or_default());
  75. favicon_url.set_paths({ "favicon.ico" });
  76. ResourceLoader::the().load(
  77. favicon_url,
  78. [this, favicon_url](auto data, auto&, auto) {
  79. // Always fetch the current document
  80. auto* document = this->browsing_context().active_document();
  81. if (document && document->has_active_favicon())
  82. return;
  83. dbgln_if(SPAM_DEBUG, "Favicon downloaded, {} bytes from {}", data.size(), favicon_url);
  84. if (data.is_empty())
  85. return;
  86. RefPtr<Gfx::Bitmap> favicon_bitmap;
  87. auto decoded_image = Platform::ImageCodecPlugin::the().decode_image(data);
  88. if (!decoded_image.has_value() || decoded_image->frames.is_empty()) {
  89. dbgln("Could not decode favicon {}", favicon_url);
  90. } else {
  91. favicon_bitmap = decoded_image->frames[0].bitmap;
  92. dbgln_if(IMAGE_DECODER_DEBUG, "Decoded favicon, {}", favicon_bitmap->size());
  93. }
  94. load_favicon(favicon_bitmap);
  95. },
  96. [this](auto&, auto) {
  97. // Always fetch the current document
  98. auto* document = this->browsing_context().active_document();
  99. if (document && document->has_active_favicon())
  100. return;
  101. load_favicon();
  102. });
  103. } else {
  104. load_favicon();
  105. }
  106. return true;
  107. }
  108. bool FrameLoader::load(const AK::URL& url, Type type)
  109. {
  110. dbgln_if(SPAM_DEBUG, "FrameLoader::load: {}", url);
  111. if (!url.is_valid()) {
  112. load_error_page(url, "Invalid URL");
  113. return false;
  114. }
  115. auto request = LoadRequest::create_for_url_on_page(url, browsing_context().page());
  116. return load(request, type);
  117. }
  118. void FrameLoader::load_html(StringView html, const AK::URL& url)
  119. {
  120. auto& vm = Bindings::main_thread_vm();
  121. auto response = Fetch::Infrastructure::Response::create(vm);
  122. response->url_list().append(url);
  123. HTML::NavigationParams navigation_params {
  124. .id = {},
  125. .request = nullptr,
  126. .response = response,
  127. .origin = HTML::Origin {},
  128. .policy_container = HTML::PolicyContainer {},
  129. .final_sandboxing_flag_set = HTML::SandboxingFlagSet {},
  130. .cross_origin_opener_policy = HTML::CrossOriginOpenerPolicy {},
  131. .coop_enforcement_result = HTML::CrossOriginOpenerPolicyEnforcementResult {},
  132. .reserved_environment = {},
  133. .browsing_context = browsing_context(),
  134. .navigable = nullptr,
  135. };
  136. auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html", move(navigation_params)).release_value_but_fixme_should_propagate_errors();
  137. browsing_context().set_active_document(document);
  138. auto parser = HTML::HTMLParser::create(document, html, "utf-8");
  139. parser->run(url);
  140. }
  141. static DeprecatedString s_error_page_url = "file:///res/html/error.html";
  142. void FrameLoader::set_error_page_url(DeprecatedString error_page_url)
  143. {
  144. s_error_page_url = error_page_url;
  145. }
  146. // FIXME: Use an actual templating engine (our own one when it's built, preferably
  147. // with a way to check these usages at compile time)
  148. void FrameLoader::load_error_page(const AK::URL& failed_url, DeprecatedString const& error)
  149. {
  150. LoadRequest request = LoadRequest::create_for_url_on_page(s_error_page_url, browsing_context().page());
  151. ResourceLoader::the().load(
  152. request,
  153. [this, failed_url, error](auto data, auto&, auto) {
  154. VERIFY(!data.is_null());
  155. StringBuilder builder;
  156. SourceGenerator generator { builder };
  157. generator.set("failed_url", escape_html_entities(failed_url.to_deprecated_string()));
  158. generator.set("error", escape_html_entities(error));
  159. generator.append(data);
  160. load_html(generator.as_string_view(), s_error_page_url);
  161. },
  162. [](auto& error, auto) {
  163. dbgln("Failed to load error page: {}", error);
  164. VERIFY_NOT_REACHED();
  165. });
  166. }
  167. void FrameLoader::load_favicon(RefPtr<Gfx::Bitmap> bitmap)
  168. {
  169. if (auto* page = browsing_context().page()) {
  170. if (bitmap)
  171. page->client().page_did_change_favicon(*bitmap);
  172. else if (s_default_favicon_bitmap)
  173. page->client().page_did_change_favicon(*s_default_favicon_bitmap);
  174. }
  175. }
  176. void FrameLoader::resource_did_load()
  177. {
  178. // This prevents us setting up the document of a removed browsing context container (BCC, e.g. <iframe>), which will cause a crash
  179. // if the document contains a script that inserts another BCC as this will use the stale browsing context it previously set up,
  180. // even if it's reinserted.
  181. // Example:
  182. // index.html:
  183. // ```
  184. // <body><script>
  185. // var i = document.createElement("iframe");
  186. // i.src = "b.html";
  187. // document.body.append(i);
  188. // i.remove();
  189. // </script>
  190. // ```
  191. // b.html:
  192. // ```
  193. // <body><script>
  194. // var i = document.createElement("iframe");
  195. // document.body.append(i);
  196. // </script>
  197. // ```
  198. // Required by Prebid.js, which does this by inserting an <iframe> into a <div> in the active document via innerHTML,
  199. // then transfers it to the <html> element:
  200. // https://github.com/prebid/Prebid.js/blob/7b7389c5abdd05626f71c3df606a93713d1b9f85/src/utils.js#L597
  201. // This is done in the spec by removing all tasks and aborting all fetches when a document is destroyed:
  202. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document
  203. if (browsing_context().has_been_discarded())
  204. return;
  205. auto url = resource()->url();
  206. // For 3xx (Redirection) responses, the Location value refers to the preferred target resource for automatically redirecting the request.
  207. auto status_code = resource()->status_code();
  208. if (status_code.has_value() && *status_code >= 300 && *status_code <= 399) {
  209. auto location = resource()->response_headers().get("Location");
  210. if (location.has_value()) {
  211. if (m_redirects_count > maximum_redirects_allowed) {
  212. m_redirects_count = 0;
  213. load_error_page(url, "Too many redirects");
  214. return;
  215. }
  216. m_redirects_count++;
  217. load(url.complete_url(location.value()), Type::Redirect);
  218. return;
  219. }
  220. }
  221. m_redirects_count = 0;
  222. if (resource()->has_encoding()) {
  223. dbgln_if(RESOURCE_DEBUG, "This content has MIME type '{}', encoding '{}'", resource()->mime_type(), resource()->encoding().value());
  224. } else {
  225. dbgln_if(RESOURCE_DEBUG, "This content has MIME type '{}', encoding unknown", resource()->mime_type());
  226. }
  227. auto final_sandboxing_flag_set = HTML::SandboxingFlagSet {};
  228. // (Part of https://html.spec.whatwg.org/#navigating-across-documents)
  229. // 3. Let responseOrigin be the result of determining the origin given browsingContext, resource's url, finalSandboxFlags, and incumbentNavigationOrigin.
  230. // FIXME: Pass incumbentNavigationOrigin
  231. auto response_origin = HTML::determine_the_origin(browsing_context(), url, final_sandboxing_flag_set, {});
  232. auto& vm = Bindings::main_thread_vm();
  233. auto response = Fetch::Infrastructure::Response::create(vm);
  234. response->url_list().append(url);
  235. HTML::NavigationParams navigation_params {
  236. .id = {},
  237. .request = nullptr,
  238. .response = response,
  239. .origin = move(response_origin),
  240. .policy_container = HTML::PolicyContainer {},
  241. .final_sandboxing_flag_set = final_sandboxing_flag_set,
  242. .cross_origin_opener_policy = HTML::CrossOriginOpenerPolicy {},
  243. .coop_enforcement_result = HTML::CrossOriginOpenerPolicyEnforcementResult {},
  244. .reserved_environment = {},
  245. .browsing_context = browsing_context(),
  246. .navigable = nullptr,
  247. };
  248. auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html", move(navigation_params)).release_value_but_fixme_should_propagate_errors();
  249. document->set_url(url);
  250. document->set_encoding(resource()->encoding());
  251. document->set_content_type(resource()->mime_type());
  252. browsing_context().set_active_document(document);
  253. if (auto* page = browsing_context().page())
  254. page->client().page_did_create_main_document();
  255. if (!parse_document(*document, resource()->encoded_data())) {
  256. load_error_page(url, "Failed to parse content.");
  257. return;
  258. }
  259. if (!url.fragment().is_empty())
  260. browsing_context().scroll_to_anchor(url.fragment());
  261. else
  262. browsing_context().scroll_to({ 0, 0 });
  263. if (auto* page = browsing_context().page())
  264. page->client().page_did_finish_loading(url);
  265. }
  266. void FrameLoader::resource_did_fail()
  267. {
  268. // See comment in resource_did_load() about why this is done.
  269. if (browsing_context().has_been_discarded())
  270. return;
  271. load_error_page(resource()->url(), resource()->error());
  272. }
  273. }