Navigable.cpp 43 KB

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