Navigable.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/Crypto/Crypto.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/DOM/DocumentLoading.h>
  10. #include <LibWeb/Fetch/Fetching/Fetching.h>
  11. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  12. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  13. #include <LibWeb/Fetch/Infrastructure/URL.h>
  14. #include <LibWeb/HTML/BrowsingContext.h>
  15. #include <LibWeb/HTML/DocumentState.h>
  16. #include <LibWeb/HTML/Navigable.h>
  17. #include <LibWeb/HTML/NavigationParams.h>
  18. #include <LibWeb/HTML/SessionHistoryEntry.h>
  19. #include <LibWeb/HTML/TraversableNavigable.h>
  20. #include <LibWeb/Platform/EventLoopPlugin.h>
  21. namespace Web::HTML {
  22. static HashTable<Navigable*>& all_navigables()
  23. {
  24. static HashTable<Navigable*> set;
  25. return set;
  26. }
  27. Navigable::Navigable()
  28. {
  29. all_navigables().set(this);
  30. }
  31. Navigable::~Navigable()
  32. {
  33. all_navigables().remove(this);
  34. }
  35. void Navigable::visit_edges(Cell::Visitor& visitor)
  36. {
  37. Base::visit_edges(visitor);
  38. visitor.visit(m_parent);
  39. visitor.visit(m_current_session_history_entry);
  40. visitor.visit(m_active_session_history_entry);
  41. visitor.visit(m_container);
  42. }
  43. JS::GCPtr<Navigable> Navigable::navigable_with_active_document(JS::NonnullGCPtr<DOM::Document> document)
  44. {
  45. for (auto* navigable : all_navigables()) {
  46. if (navigable->active_document() == document)
  47. return navigable;
  48. }
  49. return nullptr;
  50. }
  51. // https://html.spec.whatwg.org/multipage/document-sequences.html#initialize-the-navigable
  52. ErrorOr<void> Navigable::initialize_navigable(JS::NonnullGCPtr<DocumentState> document_state, JS::GCPtr<Navigable> parent)
  53. {
  54. static int next_id = 0;
  55. m_id = TRY(String::number(next_id++));
  56. // 1. Let entry be a new session history entry, with
  57. JS::NonnullGCPtr<SessionHistoryEntry> entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  58. // URL: document's URL
  59. entry->url = document_state->document()->url();
  60. // document state: documentState
  61. entry->document_state = document_state;
  62. // 2. Set navigable's current session history entry to entry.
  63. m_current_session_history_entry = entry;
  64. // 3. Set navigable's active session history entry to entry.
  65. m_active_session_history_entry = entry;
  66. // 4. Set navigable's parent to parent.
  67. m_parent = parent;
  68. return {};
  69. }
  70. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-target-history-entry
  71. JS::GCPtr<SessionHistoryEntry> Navigable::get_the_target_history_entry(int target_step) const
  72. {
  73. // 1. Let entries be the result of getting session history entries for navigable.
  74. auto& entries = get_session_history_entries();
  75. // 2. Return the item in entries that has the greatest step less than or equal to step.
  76. JS::GCPtr<SessionHistoryEntry> result = nullptr;
  77. for (auto& entry : entries) {
  78. auto entry_step = entry->step.get<int>();
  79. if (entry_step <= target_step) {
  80. if (!result || result->step.get<int>() < entry_step) {
  81. result = entry;
  82. }
  83. }
  84. }
  85. return result;
  86. }
  87. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-document
  88. JS::GCPtr<DOM::Document> Navigable::active_document()
  89. {
  90. // A navigable's active document is its active session history entry's document.
  91. return m_active_session_history_entry->document_state->document();
  92. }
  93. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-bc
  94. JS::GCPtr<BrowsingContext> Navigable::active_browsing_context()
  95. {
  96. // A navigable's active browsing context is its active document's browsing context.
  97. // If this navigable is a traversable navigable, then its active browsing context will be a top-level browsing context.
  98. if (auto document = active_document())
  99. return document->browsing_context();
  100. return nullptr;
  101. }
  102. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-wp
  103. JS::GCPtr<HTML::WindowProxy> Navigable::active_window_proxy()
  104. {
  105. // A navigable's active WindowProxy is its active browsing context's associated WindowProxy.
  106. if (auto browsing_context = active_browsing_context())
  107. return browsing_context->window_proxy();
  108. return nullptr;
  109. }
  110. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-window
  111. JS::GCPtr<HTML::Window> Navigable::active_window()
  112. {
  113. // A navigable's active window is its active WindowProxy's [[Window]].
  114. if (auto window_proxy = active_window_proxy())
  115. return window_proxy->window();
  116. return nullptr;
  117. }
  118. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-target
  119. String Navigable::target_name() const
  120. {
  121. // FIXME: A navigable's target name is its active session history entry's document state's navigable target name.
  122. dbgln("FIXME: Implement Navigable::target_name()");
  123. return {};
  124. }
  125. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container
  126. JS::GCPtr<NavigableContainer> Navigable::container() const
  127. {
  128. // The container of a navigable navigable is the navigable container whose nested navigable is navigable, or null if there is no such element.
  129. return m_container;
  130. }
  131. void Navigable::set_container(JS::GCPtr<NavigableContainer> container)
  132. {
  133. m_container = container;
  134. }
  135. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-traversable
  136. JS::GCPtr<TraversableNavigable> Navigable::traversable_navigable() const
  137. {
  138. // 1. Let navigable be inputNavigable.
  139. auto navigable = const_cast<Navigable*>(this);
  140. // 2. While navigable is not a traversable navigable, set navigable to navigable's parent.
  141. while (navigable && !is<TraversableNavigable>(*navigable))
  142. navigable = navigable->parent();
  143. // 3. Return navigable.
  144. return static_cast<TraversableNavigable*>(navigable);
  145. }
  146. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-top
  147. JS::GCPtr<TraversableNavigable> Navigable::top_level_traversable()
  148. {
  149. // 1. Let navigable be inputNavigable.
  150. auto navigable = this;
  151. // 2. While navigable's parent is not null, set navigable to navigable's parent.
  152. while (navigable->parent())
  153. navigable = navigable->parent();
  154. // 3. Return navigable.
  155. return verify_cast<TraversableNavigable>(navigable);
  156. }
  157. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-session-history-entries
  158. Vector<JS::NonnullGCPtr<SessionHistoryEntry>>& Navigable::get_session_history_entries() const
  159. {
  160. // 1. Let traversable be navigable's traversable navigable.
  161. auto traversable = traversable_navigable();
  162. // FIXME 2. Assert: this is running within traversable's session history traversal queue.
  163. // 3. If navigable is traversable, return traversable's session history entries.
  164. if (this == traversable)
  165. return traversable->session_history_entries();
  166. // 4. Let docStates be an empty ordered set of document states.
  167. Vector<JS::GCPtr<DocumentState>> doc_states;
  168. // 5. For each entry of traversable's session history entries, append entry's document state to docStates.
  169. for (auto& entry : traversable->session_history_entries())
  170. doc_states.append(entry->document_state);
  171. // 6. For each docState of docStates:
  172. while (!doc_states.is_empty()) {
  173. auto doc_state = doc_states.take_first();
  174. // 1. For each nestedHistory of docState's nested histories:
  175. for (auto& nested_history : doc_state->nested_histories()) {
  176. // 1. If nestedHistory's id equals navigable's id, return nestedHistory's entries.
  177. if (nested_history.id == id())
  178. return nested_history.entries;
  179. // 2. For each entry of nestedHistory's entries, append entry's document state to docStates.
  180. for (auto& entry : nested_history.entries)
  181. doc_states.append(entry->document_state);
  182. }
  183. }
  184. VERIFY_NOT_REACHED();
  185. }
  186. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-from-a-srcdoc-resource
  187. static WebIDL::ExceptionOr<NavigationParams> create_navigation_params_from_a_srcdoc_resource(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const&, Optional<String> navigation_id)
  188. {
  189. auto& vm = navigable->vm();
  190. auto& realm = navigable->active_window()->realm();
  191. // 1. Let documentResource be entry's document state's resource.
  192. auto document_resource = entry->document_state->resource();
  193. VERIFY(document_resource.has<String>());
  194. // 2. Let response be a new response with
  195. // URL: about:srcdoc
  196. // header list: (`Content-Type`, `text/html`)
  197. // body: the UTF-8 encoding of documentResource, as a body
  198. auto response = Fetch::Infrastructure::Response::create(vm);
  199. response->url_list().append(AK::URL("about:srcdoc"));
  200. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
  201. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  202. response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, document_resource.get<String>().bytes())));
  203. // FIXME: 3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, null, and entry's document state's origin.
  204. // 4. Let coop be a new cross-origin opener policy.
  205. CrossOriginOpenerPolicy coop;
  206. // 5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
  207. // url: response's URL
  208. // FIXME: origin: responseOrigin
  209. // cross-origin opener policy: coop
  210. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
  211. .url = *response->url(),
  212. .origin = Origin {},
  213. .cross_origin_opener_policy = coop
  214. };
  215. // FIXME: 6. Let policyContainer be the result of determining navigation params policy container given response's URL, entry's document state's history policy container, null, navigable's container document's policy container, and null.
  216. // 7. Return a new navigation params, with
  217. // id: navigationId
  218. // request: null
  219. // response: response
  220. // FIXME: origin: responseOrigin
  221. // FIXME: policy container: policyContainer
  222. // FIXME: final sandboxing flag set: targetSnapshotParams's sandboxing flags
  223. // cross-origin opener policy: coop
  224. // COOP enforcement result: coopEnforcementResult
  225. // reserved environment: null
  226. // navigable: navigable
  227. // FIXME: navigation timing type: navTimingType
  228. // fetch controller: null
  229. // commit early hints: null
  230. HTML::NavigationParams navigation_params {
  231. .id = navigation_id,
  232. .request = {},
  233. .response = *response,
  234. .origin = Origin {},
  235. .policy_container = PolicyContainer {},
  236. .final_sandboxing_flag_set = SandboxingFlagSet {},
  237. .cross_origin_opener_policy = move(coop),
  238. .coop_enforcement_result = move(coop_enforcement_result),
  239. .reserved_environment = {},
  240. .browsing_context = navigable->active_browsing_context(),
  241. .navigable = navigable,
  242. };
  243. return { navigation_params };
  244. }
  245. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
  246. static WebIDL::ExceptionOr<Optional<NavigationParams>> create_navigation_params_by_fetching(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const& source_snapshot_params, Optional<String> navigation_id)
  247. {
  248. auto& vm = navigable->vm();
  249. auto& realm = navigable->active_window()->realm();
  250. // FIXME: 1. Assert: this is running in parallel.
  251. // 2. Let documentResource be entry's document state's resource.
  252. auto document_resource = entry->document_state->resource();
  253. // 3. Let request be a new request, with
  254. // url: entry's URL
  255. // client: sourceSnapshotParams's fetch client
  256. // destination: "document"
  257. // credentials mode: "include"
  258. // use-URL-credentials flag: set
  259. // redirect mode: "manual"
  260. // replaces client id: navigable's active document's relevant settings object's id
  261. // mode: "navigate"
  262. // referrer: entry's document state's request referrer
  263. // FIXME: referrer policy: entry's document state's request referrer policy
  264. auto request = Fetch::Infrastructure::Request::create(vm);
  265. request->set_url(entry->url);
  266. request->set_client(source_snapshot_params.fetch_client);
  267. request->set_destination(Fetch::Infrastructure::Request::Destination::Document);
  268. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
  269. request->set_use_url_credentials(true);
  270. request->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Manual);
  271. auto replaces_client_id = TRY_OR_THROW_OOM(vm, String::from_deprecated_string(navigable->active_document()->relevant_settings_object().id));
  272. request->set_replaces_client_id(replaces_client_id);
  273. request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);
  274. request->set_referrer(entry->document_state->request_referrer());
  275. // 4. If documentResource is a POST resource, then:
  276. if (document_resource.has<POSTResource>()) {
  277. // 1. Set request's method to `POST`.
  278. request->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("post"sv.bytes())));
  279. // 2. Set request's body to documentResource's request body.
  280. request->set_body(document_resource.get<POSTResource>().request_body.value());
  281. // 3. Set `Content-Type` to documentResource's request content-type in request's header list.
  282. auto request_content_type = document_resource.get<POSTResource>().request_content_type;
  283. auto request_content_type_string = [request_content_type]() {
  284. switch (request_content_type) {
  285. case POSTResource::RequestContentType::ApplicationXWWWFormUrlencoded:
  286. return "application/x-www-form-urlencoded"sv;
  287. case POSTResource::RequestContentType::MultipartFormData:
  288. return "multipart/form-data"sv;
  289. case POSTResource::RequestContentType::TextPlain:
  290. return "text/plain"sv;
  291. default:
  292. VERIFY_NOT_REACHED();
  293. }
  294. }();
  295. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, request_content_type_string));
  296. TRY_OR_THROW_OOM(vm, request->header_list()->append(move(header)));
  297. }
  298. // 5. If entry's document state's reload pending is true, then set request's reload-navigation flag.
  299. if (entry->document_state->reload_pending())
  300. request->set_reload_navigation(true);
  301. // 6. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.
  302. if (entry->document_state->ever_populated())
  303. request->set_history_navigation(true);
  304. // 9. Let response be null.
  305. JS::GCPtr<Fetch::Infrastructure::Response> response = nullptr;
  306. // 10. Let responseOrigin be null.
  307. Optional<HTML::Origin> response_origin;
  308. // 11. Let fetchController be null.
  309. JS::GCPtr<Fetch::Infrastructure::FetchController> fetch_controller = nullptr;
  310. // 13. Let finalSandboxFlags be an empty sandboxing flag set.
  311. SandboxingFlagSet final_sandbox_flags;
  312. // 16. Let locationURL be null.
  313. ErrorOr<Optional<AK::URL>> location_url { OptionalNone {} };
  314. // 17. Let currentURL be request's current URL.
  315. AK::URL current_url = request->current_url();
  316. // FIXME: 18. Let commitEarlyHints be null.
  317. // 19. While true:
  318. while (true) {
  319. // FIXME: 1. If request's reserved client is not null and currentURL's origin is not the same as request's reserved client's creation URL's origin, then:
  320. // FIXME: 2. If request's reserved client is null, then:
  321. // FIXME: 3. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then set response to a network error and break. [CSP]
  322. // 4. Set response to null.
  323. response = nullptr;
  324. // 5. If fetchController is null, then set fetchController to the result of fetching request,
  325. // with processEarlyHintsResponse set to processEarlyHintsResponseas defined below, processResponse
  326. // set to processResponse as defined below, and useParallelQueue set to true.
  327. if (!fetch_controller) {
  328. // FIXME: Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:
  329. // Let processResponse be the following algorithm given a response fetchedResponse:
  330. auto process_response = [&response](JS::NonnullGCPtr<Fetch::Infrastructure::Response> fetch_response) {
  331. // 1. Set response to fetchedResponse.
  332. response = fetch_response;
  333. };
  334. fetch_controller = TRY(Fetch::Fetching::fetch(
  335. realm,
  336. request,
  337. Fetch::Infrastructure::FetchAlgorithms::create(vm,
  338. {
  339. .process_request_body_chunk_length = {},
  340. .process_request_end_of_body = {},
  341. .process_early_hints_response = {},
  342. .process_response = move(process_response),
  343. .process_response_end_of_body = {},
  344. .process_response_consume_body = {},
  345. }),
  346. Fetch::Fetching::UseParallelQueue::Yes));
  347. }
  348. // 6. Otherwise, process the next manual redirect for fetchController.
  349. else {
  350. fetch_controller->process_next_manual_redirect();
  351. }
  352. // 7. Wait until either response is non-null, or navigable's ongoing navigation changes to no longer equal navigationId.
  353. Platform::EventLoopPlugin::the().spin_until([&]() {
  354. if (response != nullptr)
  355. return true;
  356. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id))
  357. return true;
  358. return false;
  359. });
  360. // If the latter condition occurs, then abort fetchController, and return. Otherwise, proceed onward.
  361. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id)) {
  362. fetch_controller->abort(realm, {});
  363. return OptionalNone {};
  364. }
  365. // 8. If request's body is null, then set entry's document state's resource to null.
  366. if (!request->body().has<Empty>()) {
  367. entry->document_state->set_resource(Empty {});
  368. }
  369. // 11. Set responseOrigin to the result of determining the origin given response's URL, finalSandboxFlags,
  370. // entry's document state's initiator origin, and null.
  371. response_origin = determine_the_origin(*response->url(), final_sandbox_flags, entry->document_state->initiator_origin(), {});
  372. // 14. Set locationURL to response's location URL given currentURL's fragment.
  373. auto const& fragment = current_url.fragment();
  374. auto fragment_string = fragment.is_null() ? Optional<String> {} : TRY_OR_THROW_OOM(vm, String::from_deprecated_string(fragment));
  375. auto location_url = response->location_url(fragment_string);
  376. VERIFY(!location_url.is_error());
  377. // 15. If locationURL is failure or null, then break.
  378. if (location_url.is_error() || !location_url.value().has_value()) {
  379. break;
  380. }
  381. // 16. Assert: locationURL is a URL.
  382. VERIFY(location_url.value()->is_valid());
  383. // FIXME: 17. Set entry's serialized state to StructuredSerializeForStorage(null).
  384. // 18. Let oldDocState be entry's document state.
  385. auto old_doc_state = entry->document_state;
  386. // 19. Set entry's document state to a new document state, with
  387. // history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
  388. // request referrer: oldDocState's request referrer
  389. // request referrer policy: oldDocState's request referrer policy
  390. // origin: oldDocState's origin
  391. // resource: oldDocState's resource
  392. // ever populated: oldDocState's ever populated
  393. // navigable target name: oldDocState's navigable target name
  394. entry->document_state = navigable->heap().allocate_without_realm<DocumentState>();
  395. entry->document_state->set_history_policy_container(old_doc_state->history_policy_container());
  396. entry->document_state->set_request_referrer(old_doc_state->request_referrer());
  397. entry->document_state->set_request_referrer_policy(old_doc_state->request_referrer_policy());
  398. entry->document_state->set_origin(old_doc_state->origin());
  399. entry->document_state->set_resource(old_doc_state->resource());
  400. entry->document_state->set_ever_populated(old_doc_state->ever_populated());
  401. entry->document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
  402. // 20. If locationURL's scheme is not an HTTP(S) scheme, then:
  403. if (!Fetch::Infrastructure::is_http_or_https_scheme(location_url.value()->scheme())) {
  404. // 1. Set entry's document state's resource to null.
  405. entry->document_state->set_resource(Empty {});
  406. // 2. Break.
  407. break;
  408. }
  409. // 21. Set currentURL to locationURL.
  410. current_url = location_url.value().value();
  411. // 22. Set entry's URL to currentURL.
  412. entry->url = current_url;
  413. }
  414. // FIXME: 20. If locationURL is a URL whose scheme is not a fetch scheme, then return a new non-fetch scheme navigation params, with
  415. // initiator origin request's current URL's origin
  416. if (!location_url.is_error() && location_url.value().has_value() && !Fetch::Infrastructure::is_fetch_scheme(location_url.value().value().scheme())) {
  417. TODO();
  418. }
  419. // 21. If any of the following are true:
  420. // - response is a network error;
  421. // - locationURL is failure; or
  422. // - locationURL is a URL whose scheme is a fetch scheme
  423. // then return null.
  424. if (response->is_network_error() || location_url.is_error() || (location_url.value().has_value() && Fetch::Infrastructure::is_fetch_scheme(location_url.value().value().scheme()))) {
  425. return OptionalNone {};
  426. }
  427. // 22. Assert: locationURL is null and response is not a network error.
  428. VERIFY(!location_url.value().has_value());
  429. VERIFY(!response->is_network_error());
  430. // FIXME: 23. Let resultPolicyContainer be the result of determining navigation params policy container given response's
  431. // URL, entry's document state's history policy container, sourceSnapshotParams's source policy container,
  432. // null, and responsePolicyContainer.
  433. // 25. Return a new navigation params, with
  434. // id: navigationId
  435. // request: request
  436. // response: response
  437. // origin: responseOrigin
  438. // FIXME: policy container: resultPolicyContainer
  439. // FIXME: final sandboxing flag set: finalSandboxFlags
  440. // FIXME: cross-origin opener policy: responseCOOP
  441. // FIXME: COOP enforcement result: coopEnforcementResult
  442. // FIXME: reserved environment: request's reserved client
  443. // navigable: navigable
  444. // FIXME: navigation timing type: navTimingType
  445. // fetch controller: fetchController
  446. // FIXME: commit early hints: commitEarlyHints
  447. HTML::NavigationParams navigation_params {
  448. .id = navigation_id,
  449. .request = request,
  450. .response = *response,
  451. .origin = *response_origin,
  452. .policy_container = PolicyContainer {},
  453. .final_sandboxing_flag_set = SandboxingFlagSet {},
  454. .cross_origin_opener_policy = CrossOriginOpenerPolicy {},
  455. .coop_enforcement_result = CrossOriginOpenerPolicyEnforcementResult {},
  456. .reserved_environment = {},
  457. .browsing_context = navigable->active_browsing_context(),
  458. .navigable = navigable,
  459. .fetch_controller = fetch_controller,
  460. };
  461. return { navigation_params };
  462. }
  463. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-populate-the-history-entry's-document
  464. WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document(JS::GCPtr<SessionHistoryEntry> entry, Optional<NavigationParams> navigation_params, Optional<String> navigation_id, SourceSnapshotParams const& source_snapshot_params, Function<void()> completion_steps)
  465. {
  466. // FIXME: 1. Assert: this is running in parallel.
  467. // 2. Assert: if navigationParams is non-null, then navigationParams's response is non-null.
  468. if (navigation_params.has_value())
  469. VERIFY(navigation_params->response);
  470. // 3. Let currentBrowsingContext be navigable's active browsing context.
  471. [[maybe_unused]] auto current_browsing_context = active_browsing_context();
  472. // 4. Let documentResource be entry's document state's resource.
  473. auto document_resource = entry->document_state->resource();
  474. // 5. If navigationParams is null, then:
  475. if (!navigation_params.has_value()) {
  476. // 1. If documentResource is a string, then set navigationParams to the result
  477. // of creating navigation params from a srcdoc resource given entry, navigable,
  478. // targetSnapshotParams, navigationId, and navTimingType.
  479. if (document_resource.has<String>()) {
  480. navigation_params = create_navigation_params_from_a_srcdoc_resource(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
  481. }
  482. // 2. Otherwise, if both of the following are true:
  483. // - entry's URL's scheme is a fetch scheme; and
  484. // - documentResource is null, FIXME: or allowPOST is true and documentResource's request body is not failure
  485. else if (Fetch::Infrastructure::is_fetch_scheme(entry->url.scheme()) && document_resource.has<Empty>()) {
  486. navigation_params = create_navigation_params_by_fetching(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
  487. }
  488. // FIXME: 3. Otherwise, if entry's URL's scheme is not a fetch scheme, then set navigationParams to a new non-fetch scheme navigation params, with
  489. // initiator origin: entry's document state's initiator origin
  490. else {
  491. TODO();
  492. }
  493. }
  494. // 6. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:
  495. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, entry, navigation_params, navigation_id, completion_steps = move(completion_steps)] {
  496. // 1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and return.
  497. if (navigation_id.has_value() && (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != *navigation_id)) {
  498. completion_steps();
  499. return;
  500. }
  501. // 2. Let failure be false.
  502. auto failure = false;
  503. // FIXME: 3. If navigationParams is a non-fetch scheme navigation params, then set entry's document state's document to the result of running attempt to create a non-fetch
  504. // scheme document given entry's URL, navigable, targetSnapshotParams's sandboxing flags, navigationId, navTimingType, sourceSnapshotParams's has transient
  505. // activation, and navigationParams's initiator origin.
  506. // 4. Otherwise, if navigationParams is null, then set failure to true.
  507. if (!navigation_params.has_value()) {
  508. failure = true;
  509. }
  510. // FIXME: 5. Otherwise, if the result of should navigation response to navigation request of type in target be blocked by Content Security Policy? given navigationParams's request,
  511. // navigationParams's response, navigationParams's policy container's CSP list, cspNavigationType, and navigable is "Blocked", then set failure to true.
  512. // FIXME: 6. Otherwise, if navigationParams's reserved environment is non-null and the result of checking a navigation response's adherence to its embedder policy given
  513. // navigationParams's response, navigable, and navigationParams's policy container's embedder policy is false, then set failure to true.
  514. // 8. If failure is true, then:
  515. if (failure) {
  516. // 1. Set entry's document state's document to the result of creating a document for inline content that doesn't have a DOM, given navigable, null, and navTimingType.
  517. // The inline content should indicate to the user the sort of error that occurred.
  518. // FIXME: Use SourceGenerator to produce error page from file:///res/html/error.html
  519. // and display actual error from fetch response.
  520. auto error_html = String::formatted("<h1>Failed to load {}</h1>"sv, entry->url).release_value_but_fixme_should_propagate_errors();
  521. entry->document_state->set_document(create_document_for_inline_content(this, navigation_id, error_html));
  522. // 2. Set entry's document state's document's salvageable to false.
  523. entry->document_state->document()->set_salvageable(false);
  524. // FIXME: 3. If navigationParams is not null, then:
  525. if (navigation_params.has_value()) {
  526. TODO();
  527. }
  528. }
  529. // FIXME: 9. Otherwise, if navigationParams's response's status is 204 or 205, then:
  530. else if (navigation_params->response->status() == 204 || navigation_params->response->status() == 205) {
  531. // 1. Run completionSteps.
  532. completion_steps();
  533. // 2. Return.
  534. return;
  535. }
  536. // FIXME: 10. Otherwise, if navigationParams's response has a `Content-Disposition`
  537. // header specifying the attachment disposition type, then:
  538. // 11. Otherwise:
  539. else {
  540. // 1. Let document be the result of loading a document given navigationParams, sourceSnapshotParams,
  541. // and entry's document state's initiator origin.
  542. auto document = load_document(navigation_params);
  543. // 2. If document is null, then run completionSteps and return.
  544. if (!document) {
  545. VERIFY_NOT_REACHED();
  546. completion_steps();
  547. return;
  548. }
  549. // 3. Set entry's document state's document to document.
  550. entry->document_state->set_document(document.ptr());
  551. // 4. Set entry's document state's origin to document's origin.
  552. entry->document_state->set_origin(document->origin());
  553. }
  554. // FIXME: 12. If entry's document state's request referrer is "client", then set it to request's referrer.
  555. // 13. If entry's document state's document is not null, then set entry's document state's ever populated to true.
  556. if (entry->document_state->document()) {
  557. entry->document_state->set_ever_populated(true);
  558. }
  559. // 14. Run completionSteps.
  560. completion_steps();
  561. });
  562. return {};
  563. }
  564. // To navigate a navigable navigable to a URL url using a Document sourceDocument,
  565. // with an optional POST resource, string, or null documentResource (default null),
  566. // an optional response-or-null response (default null), an optional boolean exceptionsEnabled (default false),
  567. // an optional history handling behavior historyHandling (default "push"),
  568. // an optional string cspNavigationType (default "other"),
  569. // and an optional referrer policy referrerPolicy (default the empty string):
  570. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  571. WebIDL::ExceptionOr<void> Navigable::navigate(
  572. AK::URL const& url,
  573. JS::NonnullGCPtr<DOM::Document> source_document,
  574. Variant<Empty, String, POSTResource> document_resource,
  575. JS::GCPtr<Fetch::Infrastructure::Response> response,
  576. bool exceptions_enabled,
  577. HistoryHandlingBehavior history_handling,
  578. CSPNavigationType csp_navigation_type,
  579. ReferrerPolicy::ReferrerPolicy referrer_policy)
  580. {
  581. // 1. Let sourceSnapshotParams be the result of snapshotting source snapshot params given sourceDocument.
  582. auto source_snapshot_params = SourceSnapshotParams {
  583. .has_transient_activation = false,
  584. .sandboxing_flags = source_document->active_sandboxing_flag_set(),
  585. .allows_downloading = true,
  586. .fetch_client = source_document->relevant_settings_object(),
  587. .source_policy_container = source_document->policy_container()
  588. };
  589. // 2. Let initiatorOriginSnapshot be sourceDocument's origin.
  590. auto initiator_origin_snapshot = source_document->origin();
  591. // FIXME: 3. If sourceDocument's node navigable is not allowed by sandboxing to navigate navigable given and sourceSnapshotParams, then:
  592. if constexpr (false) {
  593. // 1. If exceptionsEnabled is true, then throw a "SecurityError" DOMException.
  594. if (exceptions_enabled) {
  595. return WebIDL::SecurityError::create(*vm().current_realm(), "Source document's node navigable is not allowed to navigate"sv);
  596. }
  597. // 2 Return.
  598. return {};
  599. }
  600. // 4. Let navigationId be the result of generating a random UUID.
  601. String navigation_id = TRY_OR_THROW_OOM(vm(), Crypto::generate_random_uuid());
  602. // FIXME: 5. If the surrounding agent is equal to navigable's active document's relevant agent, then continue these steps.
  603. // Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to continue these steps.
  604. // FIXME: 6. If navigable's active document's unload counter is greater than 0,
  605. // then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId,
  606. // status is "canceled", and url is url, and return.
  607. // 7. If any of the following are true:
  608. // - url equals navigable's active document's URL;
  609. // - url's scheme is "javascript"; or
  610. // - navigable's active document's is initial about:blank is true
  611. if (url.equals(active_document()->url())
  612. || url.scheme() == "javascript"sv
  613. || active_document()->is_initial_about_blank()) {
  614. // then set historyHandling to "replace".
  615. history_handling = HistoryHandlingBehavior::Replace;
  616. }
  617. // 8. If all of the following are true:
  618. // - documentResource is null;
  619. // - response is null;
  620. // - url equals navigable's active session history entry's URL with exclude fragments set to true; and
  621. // - url's fragment is non-null
  622. if (document_resource.has<Empty>()
  623. && !response
  624. && url.equals(active_session_history_entry()->url, AK::URL::ExcludeFragment::Yes)
  625. && !url.fragment().is_null()) {
  626. // 1. Navigate to a fragment given navigable, url, historyHandling, and navigationId.
  627. TRY(navigate_to_a_fragment(url, history_handling, navigation_id));
  628. // 2. Return.
  629. return {};
  630. }
  631. // 9. If navigable's parent is non-null, then set navigable's is delaying load events to true.
  632. if (parent() != nullptr) {
  633. set_delaying_load_events(true);
  634. }
  635. // 10. Let targetBrowsingContext be navigable's active browsing context.
  636. [[maybe_unused]] auto target_browsing_context = active_browsing_context();
  637. // FIXME: 11. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  638. // FIXME: 12. Invoke WebDriver BiDi navigation started with targetBrowsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is url, and status is "pending".
  639. // 13. If navigable's ongoing navigation is "traversal", then:
  640. if (ongoing_navigation().has<Traversal>()) {
  641. // FIXME: 1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url.
  642. // 2. Return.
  643. return {};
  644. }
  645. // 14. Set navigable's ongoing navigation to navigationId.
  646. m_ongoing_navigation = navigation_id;
  647. // 15. If url's scheme is "javascript", then:
  648. if (url.scheme() == "javascript"sv) {
  649. // 1. Queue a global task on the navigation and traversal task source given navigable's active window to navigate to a javascript: URL given navigable, url, historyHandling, initiatorOriginSnapshot, and cspNavigationType.
  650. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, url, history_handling, initiator_origin_snapshot, csp_navigation_type] {
  651. (void)navigate_to_a_javascript_url(url, history_handling, initiator_origin_snapshot, csp_navigation_type);
  652. });
  653. // 2. Return.
  654. return {};
  655. }
  656. // 16. In parallel, run these steps:
  657. Platform::EventLoopPlugin::the().deferred_invoke([this, source_snapshot_params = move(source_snapshot_params), document_resource, url, navigation_id, referrer_policy, initiator_origin_snapshot, response, history_handling] {
  658. // FIXME: 1. Let unloadPromptCanceled be the result of checking if unloading is user-canceled for navigable's active document's inclusive descendant navigables.
  659. // FIXME: 2. If unloadPromptCanceled is true, or navigable's ongoing navigation is no longer navigationId, then:
  660. // 3. Queue a global task on the navigation and traversal task source given navigable's active window to abort navigable's active document.
  661. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this] {
  662. VERIFY(active_document());
  663. active_document()->abort();
  664. });
  665. // 4. Let documentState be a new document state with
  666. // request referrer policy: referrerPolicy
  667. // initiator origin: initiatorOriginSnapshot
  668. // resource: documentResource
  669. // navigable target name: navigable's target name
  670. JS::NonnullGCPtr<DocumentState> document_state = *heap().allocate_without_realm<DocumentState>();
  671. document_state->set_request_referrer_policy(referrer_policy);
  672. document_state->set_resource(document_resource);
  673. document_state->set_initiator_origin(initiator_origin_snapshot);
  674. document_state->set_navigable_target_name(target_name());
  675. // 5. If url is about:blank, then set documentState's origin to documentState's initiator origin.
  676. if (url == "about:blank"sv) {
  677. document_state->set_origin(document_state->initiator_origin());
  678. }
  679. // 6. Otherwise, if url is about:srcdoc, then set documentState's origin to navigable's parent's active document's origin.
  680. else if (url == "about:srcdoc"sv) {
  681. document_state->set_origin(parent()->active_document()->origin());
  682. }
  683. // 7. Let historyEntry be a new session history entry, with its URL set to url and its document state set to documentState.
  684. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  685. history_entry->url = url;
  686. history_entry->document_state = document_state;
  687. // 8. Let navigationParams be null.
  688. Optional<NavigationParams> navigation_params;
  689. // FIXME: 9. If response is non-null:
  690. if (response) {
  691. }
  692. // 10. Attempt to populate the history entry's document
  693. // for historyEntry, given navigable, "navigate", sourceSnapshotParams,
  694. // targetSnapshotParams, navigationId, navigationParams, cspNavigationType, with allowPOST
  695. // set to true and completionSteps set to the following step:
  696. populate_session_history_entry_document(history_entry, navigation_params, navigation_id, source_snapshot_params, [this, history_entry, history_handling] {
  697. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-cross-document-navigation
  698. // 1. FIXME: Assert: this is running on navigable's traversable navigable's session history traversal queue.
  699. // 2. Set navigable's is delaying load events to false.
  700. set_delaying_load_events(false);
  701. // 3. If historyEntry's document is null, then return.
  702. if (!history_entry->document_state->document())
  703. return;
  704. // 4. FIXME: If all of the following are true:
  705. // - navigable's parent is null;
  706. // - historyEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  707. // - historyEntry's document's origin is not navigable's active document's origin
  708. // then set historyEntry's document state's navigable target name to the empty string.
  709. // 5. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  710. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_session_history_entry() : nullptr;
  711. // 6. Let traversable be navigable's traversable navigable.
  712. auto traversable = traversable_navigable();
  713. // 7. Let targetStep be null.
  714. int target_step;
  715. // 8. Let targetEntries be the result of getting session history entries for navigable.
  716. auto& target_entries = get_session_history_entries();
  717. // 9. If entryToReplace is null, then:
  718. if (entry_to_replace == nullptr) {
  719. // FIXME: 1. Clear the forward session history of traversable.
  720. // 2. Set targetStep to traversable's current session history step + 1.
  721. target_step = traversable->current_session_history_step() + 1;
  722. // 3. Set historyEntry's step to targetStep.
  723. history_entry->step = target_step;
  724. // 4. Append historyEntry to targetEntries.
  725. target_entries.append(move(history_entry));
  726. } else {
  727. // 1. Replace entryToReplace with historyEntry in targetEntries.
  728. *(target_entries.find(*entry_to_replace)) = history_entry;
  729. // 2. Set historyEntry's step to entryToReplace's step.
  730. history_entry->step = entry_to_replace->step;
  731. // 3. Set targetStep to traversable's current session history step.
  732. target_step = traversable->current_session_history_step();
  733. }
  734. // FIXME: 10. Apply the history step targetStep to traversable.
  735. }).release_value_but_fixme_should_propagate_errors();
  736. });
  737. return {};
  738. }
  739. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_fragment(AK::URL const&, HistoryHandlingBehavior, String navigation_id)
  740. {
  741. (void)navigation_id;
  742. TODO();
  743. }
  744. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_javascript_url(AK::URL const&, HistoryHandlingBehavior, Origin const& initiator_origin, CSPNavigationType csp_navigation_type)
  745. {
  746. (void)initiator_origin;
  747. (void)csp_navigation_type;
  748. TODO();
  749. }
  750. }