Navigable.cpp 44 KB

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