Fetching.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Base64.h>
  9. #include <AK/Debug.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <LibJS/Runtime/Completion.h>
  12. #include <LibWeb/Bindings/MainThreadVM.h>
  13. #include <LibWeb/Cookie/Cookie.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/Fetch/BodyInit.h>
  16. #include <LibWeb/Fetch/Fetching/Checks.h>
  17. #include <LibWeb/Fetch/Fetching/Fetching.h>
  18. #include <LibWeb/Fetch/Fetching/PendingResponse.h>
  19. #include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
  20. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  21. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  22. #include <LibWeb/Fetch/Infrastructure/FetchParams.h>
  23. #include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
  24. #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
  25. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  26. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  27. #include <LibWeb/Fetch/Infrastructure/HTTP/Statuses.h>
  28. #include <LibWeb/Fetch/Infrastructure/MimeTypeBlocking.h>
  29. #include <LibWeb/Fetch/Infrastructure/NoSniffBlocking.h>
  30. #include <LibWeb/Fetch/Infrastructure/PortBlocking.h>
  31. #include <LibWeb/Fetch/Infrastructure/Task.h>
  32. #include <LibWeb/Fetch/Infrastructure/URL.h>
  33. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  34. #include <LibWeb/HTML/Scripting/Environments.h>
  35. #include <LibWeb/HTML/Window.h>
  36. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  37. #include <LibWeb/Loader/LoadRequest.h>
  38. #include <LibWeb/Loader/ResourceLoader.h>
  39. #include <LibWeb/Platform/EventLoopPlugin.h>
  40. #include <LibWeb/ReferrerPolicy/AbstractOperations.h>
  41. #include <LibWeb/SRI/SRI.h>
  42. #include <LibWeb/URL/URL.h>
  43. #include <LibWeb/WebIDL/DOMException.h>
  44. namespace Web::Fetch::Fetching {
  45. #define TRY_OR_IGNORE(expression) \
  46. ({ \
  47. auto&& _temporary_result = (expression); \
  48. if (_temporary_result.is_error()) \
  49. return; \
  50. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  51. "Do not return a reference from a fallible expression"); \
  52. _temporary_result.release_value(); \
  53. })
  54. // https://fetch.spec.whatwg.org/#concept-fetch
  55. WebIDL::ExceptionOr<JS::NonnullGCPtr<Infrastructure::FetchController>> fetch(JS::Realm& realm, Infrastructure::Request& request, Infrastructure::FetchAlgorithms const& algorithms, UseParallelQueue use_parallel_queue)
  56. {
  57. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch' with: request @ {}", &request);
  58. auto& vm = realm.vm();
  59. // 1. Assert: request’s mode is "navigate" or processEarlyHintsResponse is null.
  60. VERIFY(request.mode() == Infrastructure::Request::Mode::Navigate || !algorithms.process_early_hints_response().has_value());
  61. // 2. Let taskDestination be null.
  62. JS::GCPtr<JS::Object> task_destination;
  63. // 3. Let crossOriginIsolatedCapability be false.
  64. auto cross_origin_isolated_capability = HTML::CanUseCrossOriginIsolatedAPIs::No;
  65. // 4. If request’s client is non-null, then:
  66. if (request.client() != nullptr) {
  67. // 1. Set taskDestination to request’s client’s global object.
  68. task_destination = request.client()->global_object();
  69. // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin isolated capability.
  70. cross_origin_isolated_capability = request.client()->cross_origin_isolated_capability();
  71. }
  72. // FIXME: 5. If useParallelQueue is true, then set taskDestination to the result of starting a new parallel queue.
  73. (void)use_parallel_queue;
  74. (void)task_destination;
  75. // 6. Let timingInfo be a new fetch timing info whose start time and post-redirect start time are the coarsened
  76. // shared current time given crossOriginIsolatedCapability, and render-blocking is set to request’s
  77. // render-blocking.
  78. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  79. auto now = HighResolutionTime::coarsened_shared_current_time(cross_origin_isolated_capability == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  80. timing_info->set_start_time(now);
  81. timing_info->set_post_redirect_start_time(now);
  82. timing_info->set_render_blocking(request.render_blocking());
  83. // 7. Let fetchParams be a new fetch params whose request is request, timing info is timingInfo, process request
  84. // body chunk length is processRequestBodyChunkLength, process request end-of-body is processRequestEndOfBody,
  85. // process early hints response is processEarlyHintsResponse, process response is processResponse, process
  86. // response consume body is processResponseConsumeBody, process response end-of-body is processResponseEndOfBody,
  87. // task destination is taskDestination, and cross-origin isolated capability is crossOriginIsolatedCapability.
  88. auto fetch_params = Infrastructure::FetchParams::create(vm, request, timing_info);
  89. fetch_params->set_algorithms(algorithms);
  90. if (task_destination)
  91. fetch_params->set_task_destination({ *task_destination });
  92. fetch_params->set_cross_origin_isolated_capability(cross_origin_isolated_capability);
  93. // 8. If request’s body is a byte sequence, then set request’s body to request’s body as a body.
  94. if (auto const* buffer = request.body().get_pointer<ByteBuffer>())
  95. request.set_body(TRY(Infrastructure::byte_sequence_as_body(realm, buffer->bytes())));
  96. // 9. If request’s window is "client", then set request’s window to request’s client, if request’s client’s global
  97. // object is a Window object; otherwise "no-window".
  98. auto const* window = request.window().get_pointer<Infrastructure::Request::Window>();
  99. if (window && *window == Infrastructure::Request::Window::Client) {
  100. if (is<HTML::Window>(request.client()->global_object())) {
  101. request.set_window(request.client());
  102. } else {
  103. request.set_window(Infrastructure::Request::Window::NoWindow);
  104. }
  105. }
  106. // 10. If request’s origin is "client", then set request’s origin to request’s client’s origin.
  107. auto const* origin = request.origin().get_pointer<Infrastructure::Request::Origin>();
  108. if (origin && *origin == Infrastructure::Request::Origin::Client)
  109. request.set_origin(request.client()->origin());
  110. // 12. If request’s policy container is "client", then:
  111. auto const* policy_container = request.policy_container().get_pointer<Infrastructure::Request::PolicyContainer>();
  112. if (policy_container) {
  113. VERIFY(*policy_container == Infrastructure::Request::PolicyContainer::Client);
  114. // 1. If request’s client is non-null, then set request’s policy container to a clone of request’s client’s
  115. // policy container.
  116. if (request.client() != nullptr)
  117. request.set_policy_container(request.client()->policy_container());
  118. // 2. Otherwise, set request’s policy container to a new policy container.
  119. else
  120. request.set_policy_container(HTML::PolicyContainer {});
  121. }
  122. // 13. If request’s header list does not contain `Accept`, then:
  123. if (!request.header_list()->contains("Accept"sv.bytes())) {
  124. // 1. Let value be `*/*`.
  125. auto value = "*/*"sv;
  126. // 2. A user agent should set value to the first matching statement, if any, switching on request’s
  127. // destination:
  128. if (request.destination().has_value()) {
  129. switch (*request.destination()) {
  130. // -> "document"
  131. // -> "frame"
  132. // -> "iframe"
  133. case Infrastructure::Request::Destination::Document:
  134. case Infrastructure::Request::Destination::Frame:
  135. case Infrastructure::Request::Destination::IFrame:
  136. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  137. value = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"sv;
  138. break;
  139. // -> "image"
  140. case Infrastructure::Request::Destination::Image:
  141. // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
  142. value = "image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5"sv;
  143. break;
  144. // -> "style"
  145. case Infrastructure::Request::Destination::Style:
  146. // `text/css,*/*;q=0.1`
  147. value = "text/css,*/*;q=0.1"sv;
  148. break;
  149. default:
  150. break;
  151. }
  152. }
  153. // 3. Append (`Accept`, value) to request’s header list.
  154. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Accept"sv, value.bytes()));
  155. TRY_OR_THROW_OOM(vm, request.header_list()->append(move(header)));
  156. }
  157. // 14. If request’s header list does not contain `Accept-Language`, then user agents should append
  158. // (`Accept-Language, an appropriate header value) to request’s header list.
  159. if (!request.header_list()->contains("Accept-Language"sv.bytes())) {
  160. auto header = MUST(Infrastructure::Header::from_string_pair("Accept-Language"sv, "*"sv));
  161. TRY_OR_THROW_OOM(vm, request.header_list()->append(move(header)));
  162. }
  163. // 15. If request’s priority is null, then use request’s initiator, destination, and render-blocking appropriately
  164. // in setting request’s priority to a user-agent-defined object.
  165. // NOTE: The user-agent-defined object could encompass stream weight and dependency for HTTP/2, and equivalent
  166. // information used to prioritize dispatch and processing of HTTP/1 fetches.
  167. // 16. If request is a subresource request, then:
  168. if (request.is_subresource_request()) {
  169. // FIXME: 1. Let record be a new fetch record whose request is request and controller is fetchParams’s controller.
  170. // FIXME: 2. Append record to request’s client’s fetch group list of fetch records.
  171. }
  172. // 17. Run main fetch given fetchParams.
  173. (void)TRY(main_fetch(realm, fetch_params));
  174. // 18. Return fetchParams’s controller.
  175. return fetch_params->controller();
  176. }
  177. // https://fetch.spec.whatwg.org/#concept-main-fetch
  178. WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> main_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Recursive recursive)
  179. {
  180. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' with: fetch_params @ {}", &fetch_params);
  181. auto& vm = realm.vm();
  182. // 1. Let request be fetchParams’s request.
  183. auto request = fetch_params.request();
  184. // 2. Let response be null.
  185. JS::GCPtr<Infrastructure::Response> response;
  186. // 3. If request’s local-URLs-only flag is set and request’s current URL is not local, then set response to a
  187. // network error.
  188. if (request->local_urls_only() && !Infrastructure::is_local_url(request->current_url()))
  189. response = Infrastructure::Response::network_error(vm, "Request with 'local-URLs-only' flag must have a local URL"sv);
  190. // FIXME: 4. Run report Content Security Policy violations for request.
  191. // FIXME: 5. Upgrade request to a potentially trustworthy URL, if appropriate.
  192. // FIXME: 6. Upgrade a mixed content request to a potentially trustworthy URL, if appropriate.
  193. // 7. If should request be blocked due to a bad port, should fetching request be blocked as mixed content, or
  194. // should request be blocked by Content Security Policy returns blocked, then set response to a network error.
  195. if (Infrastructure::block_bad_port(request) == Infrastructure::RequestOrResponseBlocking::Blocked
  196. || false // FIXME: "should fetching request be blocked as mixed content"
  197. || false // FIXME: "should request be blocked by Content Security Policy returns blocked"
  198. ) {
  199. response = Infrastructure::Response::network_error(vm, "Request was blocked"sv);
  200. }
  201. // 8. If request’s referrer policy is the empty string, then set request’s referrer policy to request’s policy
  202. // container’s referrer policy.
  203. if (!request->referrer_policy().has_value()) {
  204. VERIFY(request->policy_container().has<HTML::PolicyContainer>());
  205. request->set_referrer_policy(request->policy_container().get<HTML::PolicyContainer>().referrer_policy);
  206. }
  207. // 9. If request’s referrer is not "no-referrer", then set request’s referrer to the result of invoking determine
  208. // request’s referrer.
  209. // NOTE: As stated in Referrer Policy, user agents can provide the end user with options to override request’s
  210. // referrer to "no-referrer" or have it expose less sensitive information.
  211. auto const* referrer = request->referrer().get_pointer<Infrastructure::Request::Referrer>();
  212. if (!referrer || *referrer != Infrastructure::Request::Referrer::NoReferrer) {
  213. auto determined_referrer = ReferrerPolicy::determine_requests_referrer(request);
  214. if (determined_referrer.has_value())
  215. request->set_referrer(*determined_referrer);
  216. else
  217. request->set_referrer(Infrastructure::Request::Referrer::NoReferrer);
  218. }
  219. // 10. Set request’s current URL’s scheme to "https" if all of the following conditions are true:
  220. if (
  221. // - request’s current URL’s scheme is "http"
  222. request->current_url().scheme() == "http"sv
  223. // - request’s current URL’s host is a domain
  224. && URL::host_is_domain(request->current_url().host())
  225. // FIXME: - Matching request’s current URL’s host per Known HSTS Host Domain Name Matching results in either a
  226. // superdomain match with an asserted includeSubDomains directive or a congruent match (with or without an
  227. // asserted includeSubDomains directive) [HSTS]; or DNS resolution for the request finds a matching HTTPS RR
  228. // per section 9.5 of [SVCB].
  229. && false
  230. ) {
  231. request->current_url().set_scheme("https"sv);
  232. }
  233. JS::SafeFunction<WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>>()> get_response = [&realm, &vm, &fetch_params, request]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> {
  234. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' get_response() function");
  235. // -> fetchParams’s preloaded response candidate is not null
  236. if (!fetch_params.preloaded_response_candidate().has<Empty>()) {
  237. // 1. Wait until fetchParams’s preloaded response candidate is not "pending".
  238. HTML::main_thread_event_loop().spin_until([&] {
  239. return !fetch_params.preloaded_response_candidate().has<Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag>();
  240. });
  241. // 2. Assert: fetchParams’s preloaded response candidate is a response.
  242. VERIFY(fetch_params.preloaded_response_candidate().has<JS::NonnullGCPtr<Infrastructure::Response>>());
  243. // 3. Return fetchParams’s preloaded response candidate.
  244. return PendingResponse::create(vm, request, fetch_params.preloaded_response_candidate().get<JS::NonnullGCPtr<Infrastructure::Response>>());
  245. }
  246. // -> request’s current URL’s origin is same origin with request’s origin, and request’s response tainting
  247. // is "basic"
  248. // -> request’s current URL’s scheme is "data"
  249. // -> request’s mode is "navigate" or "websocket"
  250. else if (
  251. (request->origin().has<HTML::Origin>() && URL::url_origin(request->current_url()).is_same_origin(request->origin().get<HTML::Origin>()) && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  252. || request->current_url().scheme() == "data"sv
  253. || (request->mode() == Infrastructure::Request::Mode::Navigate || request->mode() == Infrastructure::Request::Mode::WebSocket)) {
  254. // 1. Set request’s response tainting to "basic".
  255. request->set_response_tainting(Infrastructure::Request::ResponseTainting::Basic);
  256. // 2. Return the result of running scheme fetch given fetchParams.
  257. return scheme_fetch(realm, fetch_params);
  258. // NOTE: HTML assigns any documents and workers created from URLs whose scheme is "data" a unique
  259. // opaque origin. Service workers can only be created from URLs whose scheme is an HTTP(S) scheme.
  260. }
  261. // -> request’s mode is "same-origin"
  262. else if (request->mode() == Infrastructure::Request::Mode::SameOrigin) {
  263. // Return a network error.
  264. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'same-origin' mode must have same URL and request origin"sv));
  265. }
  266. // -> request’s mode is "no-cors"
  267. else if (request->mode() == Infrastructure::Request::Mode::NoCORS) {
  268. // 1. If request’s redirect mode is not "follow", then return a network error.
  269. if (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow)
  270. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'no-cors' mode must have redirect mode set to 'follow'"sv));
  271. // 2. Set request’s response tainting to "opaque".
  272. request->set_response_tainting(Infrastructure::Request::ResponseTainting::Opaque);
  273. // 3. Return the result of running scheme fetch given fetchParams.
  274. return scheme_fetch(realm, fetch_params);
  275. }
  276. // -> request’s current URL’s scheme is not an HTTP(S) scheme
  277. else if (!Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  278. // NOTE: At this point all other request modes have been handled. Ensure we're not lying in the error message :^)
  279. VERIFY(request->mode() == Infrastructure::Request::Mode::CORS);
  280. // Return a network error.
  281. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' mode must have URL with HTTP or HTTPS scheme"sv));
  282. }
  283. // -> request’s use-CORS-preflight flag is set
  284. // -> request’s unsafe-request flag is set and either request’s method is not a CORS-safelisted method or
  285. // CORS-unsafe request-header names with request’s header list is not empty
  286. else if (
  287. request->use_cors_preflight()
  288. || (request->unsafe_request()
  289. && (!Infrastructure::is_cors_safelisted_method(request->method())
  290. || !TRY_OR_THROW_OOM(vm, Infrastructure::get_cors_unsafe_header_names(request->header_list())).is_empty()))) {
  291. // 1. Set request’s response tainting to "cors".
  292. request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  293. auto returned_pending_response = PendingResponse::create(vm, request);
  294. // 2. Let corsWithPreflightResponse be the result of running HTTP fetch given fetchParams and true.
  295. auto cors_with_preflight_response = TRY(http_fetch(realm, fetch_params, MakeCORSPreflight::Yes));
  296. cors_with_preflight_response->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> cors_with_preflight_response) {
  297. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' cors_with_preflight_response load callback");
  298. // 3. If corsWithPreflightResponse is a network error, then clear cache entries using request.
  299. if (cors_with_preflight_response->is_network_error()) {
  300. // FIXME: Clear cache entries
  301. }
  302. // 4. Return corsWithPreflightResponse.
  303. returned_pending_response->resolve(cors_with_preflight_response);
  304. });
  305. return returned_pending_response;
  306. }
  307. // -> Otherwise
  308. else {
  309. // 1. Set request’s response tainting to "cors".
  310. request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  311. // 2. Return the result of running HTTP fetch given fetchParams.
  312. return http_fetch(realm, fetch_params);
  313. }
  314. };
  315. if (recursive == Recursive::Yes) {
  316. // 12. If response is null, then set response to the result of running the steps corresponding to the first
  317. // matching statement:
  318. auto pending_response = !response
  319. ? TRY(get_response())
  320. : PendingResponse::create(vm, request, *response);
  321. // 13. If recursive is true, then return response.
  322. return pending_response;
  323. }
  324. // 11. If recursive is false, then run the remaining steps in parallel.
  325. Platform::EventLoopPlugin::the().deferred_invoke([&realm, &vm, &fetch_params, request, response, get_response = move(get_response)] {
  326. // 12. If response is null, then set response to the result of running the steps corresponding to the first
  327. // matching statement:
  328. auto pending_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  329. if (!response) {
  330. auto pending_response_or_error = get_response();
  331. if (pending_response_or_error.is_error())
  332. return;
  333. pending_response = pending_response_or_error.release_value();
  334. }
  335. pending_response->when_loaded([&realm, &vm, &fetch_params, request, response, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_response) mutable {
  336. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' pending_response load callback");
  337. if (response_was_null)
  338. response = resolved_response;
  339. // 14. If response is not a network error and response is not a filtered response, then:
  340. if (!response->is_network_error() && !is<Infrastructure::FilteredResponse>(*response)) {
  341. // 1. If request’s response tainting is "cors", then:
  342. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS) {
  343. // FIXME: 1. Let headerNames be the result of extracting header list values given
  344. // `Access-Control-Expose-Headers` and response’s header list.
  345. // FIXME: 2. If request’s credentials mode is not "include" and headerNames contains `*`, then set
  346. // response’s CORS-exposed header-name list to all unique header names in response’s header
  347. // list.
  348. // FIXME: 3. Otherwise, if headerNames is not null or failure, then set response’s CORS-exposed
  349. // header-name list to headerNames.
  350. }
  351. // 2. Set response to the following filtered response with response as its internal response, depending
  352. // on request’s response tainting:
  353. response = TRY_OR_IGNORE([&]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<Infrastructure::Response>> {
  354. switch (request->response_tainting()) {
  355. // -> "basic"
  356. case Infrastructure::Request::ResponseTainting::Basic:
  357. // basic filtered response
  358. return TRY_OR_THROW_OOM(vm, Infrastructure::BasicFilteredResponse::create(vm, *response));
  359. // -> "cors"
  360. case Infrastructure::Request::ResponseTainting::CORS:
  361. // CORS filtered response
  362. return TRY_OR_THROW_OOM(vm, Infrastructure::CORSFilteredResponse::create(vm, *response));
  363. // -> "opaque"
  364. case Infrastructure::Request::ResponseTainting::Opaque:
  365. // opaque filtered response
  366. return Infrastructure::OpaqueFilteredResponse::create(vm, *response);
  367. default:
  368. VERIFY_NOT_REACHED();
  369. }
  370. }());
  371. }
  372. // 15. Let internalResponse be response, if response is a network error, and response’s internal response
  373. // otherwise.
  374. auto internal_response = response->is_network_error()
  375. ? JS::NonnullGCPtr { *response }
  376. : static_cast<Infrastructure::FilteredResponse&>(*response).internal_response();
  377. // 16. If internalResponse’s URL list is empty, then set it to a clone of request’s URL list.
  378. // NOTE: A response’s URL list can be empty (for example, when the response represents an about URL).
  379. if (internal_response->url_list().is_empty())
  380. internal_response->set_url_list(request->url_list());
  381. // 17. If request has a redirect-tainted origin, then set internalResponse’s has-cross-origin-redirects to true.
  382. if (request->has_redirect_tainted_origin())
  383. internal_response->set_has_cross_origin_redirects(true);
  384. // 18. If request’s timing allow failed flag is unset, then set internalResponse’s timing allow passed flag.
  385. if (!request->timing_allow_failed())
  386. internal_response->set_timing_allow_passed(true);
  387. // 19. If response is not a network error and any of the following returns blocked
  388. if (!response->is_network_error() && (
  389. // FIXME: - should internalResponse to request be blocked as mixed content
  390. false
  391. // FIXME: - should internalResponse to request be blocked by Content Security Policy
  392. || false
  393. // - should internalResponse to request be blocked due to its MIME type
  394. || TRY_OR_IGNORE(Infrastructure::should_response_to_request_be_blocked_due_to_its_mime_type(internal_response, request)) == Infrastructure::RequestOrResponseBlocking::Blocked
  395. // - should internalResponse to request be blocked due to nosniff
  396. || TRY_OR_IGNORE(Infrastructure::should_response_to_request_be_blocked_due_to_nosniff(internal_response, request)) == Infrastructure::RequestOrResponseBlocking::Blocked)) {
  397. // then set response and internalResponse to a network error.
  398. response = internal_response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Response was blocked"_string));
  399. }
  400. // 20. If response’s type is "opaque", internalResponse’s status is 206, internalResponse’s range-requested
  401. // flag is set, and request’s header list does not contain `Range`, then set response and
  402. // internalResponse to a network error.
  403. // NOTE: Traditionally, APIs accept a ranged response even if a range was not requested. This prevents a
  404. // partial response from an earlier ranged request being provided to an API that did not make a range
  405. // request.
  406. if (response->type() == Infrastructure::Response::Type::Opaque
  407. && internal_response->status() == 206
  408. && internal_response->range_requested()
  409. && !request->header_list()->contains("Range"sv.bytes())) {
  410. response = internal_response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Response has status 206 and 'range-requested' flag set, but request has no 'Range' header"_string));
  411. }
  412. // 21. If response is not a network error and either request’s method is `HEAD` or `CONNECT`, or
  413. // internalResponse’s status is a null body status, set internalResponse’s body to null and disregard
  414. // any enqueuing toward it (if any).
  415. // NOTE: This standardizes the error handling for servers that violate HTTP.
  416. if (!response->is_network_error() && (StringView { request->method() }.is_one_of("HEAD"sv, "CONNECT"sv) || Infrastructure::is_null_body_status(internal_response->status())))
  417. internal_response->set_body({});
  418. // 22. If request’s integrity metadata is not the empty string, then:
  419. if (!request->integrity_metadata().is_empty()) {
  420. // 1. Let processBodyError be this step: run fetch response handover given fetchParams and a network
  421. // error.
  422. // FIXME: The spec disagrees on whether fully_read()'s process_body_error should take an argument or not.
  423. // See https://github.com/whatwg/fetch/issues/1636
  424. // For now, define two versions of processBodyError
  425. auto process_body_error_no_argument = [&realm, &vm, &fetch_params]() {
  426. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error(vm, "Response body could not be processed"sv)));
  427. };
  428. Infrastructure::Body::ProcessBodyErrorCallback process_body_error = [&realm, &vm, &fetch_params](auto&) {
  429. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error(vm, "Response body could not be processed"sv)));
  430. };
  431. // 2. If response’s body is null, then run processBodyError and abort these steps.
  432. if (!response->body().has_value()) {
  433. process_body_error_no_argument();
  434. return;
  435. }
  436. // 3. Let processBody given bytes be these steps:
  437. Infrastructure::Body::ProcessBodyCallback process_body = [&realm, &request, &response, &fetch_params, process_body_error = move(process_body_error_no_argument)](ByteBuffer bytes) {
  438. // 1. If bytes do not match request’s integrity metadata, then run processBodyError and abort these steps.
  439. if (!TRY_OR_IGNORE(SRI::do_bytes_match_metadata_list(bytes, request->integrity_metadata()))) {
  440. process_body_error();
  441. return;
  442. }
  443. // 2. Set response’s body to bytes as a body.
  444. response->set_body(TRY_OR_IGNORE(Infrastructure::byte_sequence_as_body(realm, bytes)));
  445. // 3. Run fetch response handover given fetchParams and response.
  446. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, *response));
  447. };
  448. // 4. Fully read response’s body given processBody and processBodyError.
  449. TRY_OR_IGNORE(response->body()->fully_read(realm, move(process_body), move(process_body_error), fetch_params.task_destination()));
  450. }
  451. // 23. Otherwise, run fetch response handover given fetchParams and response.
  452. else {
  453. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, *response));
  454. }
  455. });
  456. });
  457. return Optional<JS::NonnullGCPtr<PendingResponse>> {};
  458. }
  459. // https://fetch.spec.whatwg.org/#fetch-finale
  460. WebIDL::ExceptionOr<void> fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  461. {
  462. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);
  463. auto& vm = realm.vm();
  464. // 1. Let timingInfo be fetchParams’s timing info.
  465. auto timing_info = fetch_params.timing_info();
  466. // 2. If response is not a network error and fetchParams’s request’s client is a secure context, then set
  467. // timingInfo’s server-timing headers to the result of getting, decoding, and splitting `Server-Timing` from
  468. // response’s header list.
  469. // The user agent may decide to expose `Server-Timing` headers to non-secure contexts requests as well.
  470. auto client = fetch_params.request()->client();
  471. if (!response.is_network_error() && client != nullptr && HTML::is_secure_context(*client)) {
  472. auto server_timing_headers = TRY_OR_THROW_OOM(vm, response.header_list()->get_decode_and_split("Server-Timing"sv.bytes()));
  473. if (server_timing_headers.has_value())
  474. timing_info->set_server_timing_headers(server_timing_headers.release_value());
  475. }
  476. // 3. Let processResponseEndOfBody be the following steps:
  477. auto process_response_end_of_body = [&vm, &response, &fetch_params, timing_info] {
  478. // 1. Let unsafeEndTime be the unsafe shared current time.
  479. auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
  480. // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s full timing
  481. // info to fetchParams’s timing info.
  482. if (fetch_params.request()->destination() == Infrastructure::Request::Destination::Document)
  483. fetch_params.controller()->set_full_timing_info(fetch_params.timing_info());
  484. // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
  485. fetch_params.controller()->set_report_timing_steps([&vm, &response, &fetch_params, timing_info, unsafe_end_time](JS::Object const& global) mutable {
  486. // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
  487. if (!Infrastructure::is_http_or_https_scheme(fetch_params.request()->url().scheme()))
  488. return;
  489. // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
  490. timing_info->set_end_time(HighResolutionTime::relative_high_resolution_time(unsafe_end_time, global));
  491. // 3. Let cacheState be response’s cache state.
  492. auto cache_state = response.cache_state();
  493. // 4. Let bodyInfo be response’s body info.
  494. auto body_info = response.body_info();
  495. // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
  496. // opaque timing info for timingInfo, set bodyInfo to a new response body info, and set cacheState to
  497. // the empty string.
  498. // NOTE: This covers the case of response being a network error.
  499. if (!response.timing_allow_passed()) {
  500. timing_info = Infrastructure::create_opaque_timing_info(vm, timing_info);
  501. body_info = Infrastructure::Response::BodyInfo {};
  502. cache_state = {};
  503. }
  504. // 6. Let responseStatus be 0 if fetchParams’s request’s mode is "navigate" and response’s has-cross-origin-redirects is true; otherwise response’s status.
  505. auto response_status = fetch_params.request()->mode() == Infrastructure::Request::Mode::Navigate && response.has_cross_origin_redirects()
  506. ? 0
  507. : response.status();
  508. // FIXME: 7. If fetchParams’s request’s initiator type is not null, then mark resource timing given timingInfo,
  509. // request’s URL, request’s initiator type, global, cacheState, bodyInfo, and responseStatus.
  510. (void)timing_info;
  511. (void)global;
  512. (void)cache_state;
  513. (void)body_info;
  514. (void)response_status;
  515. });
  516. // 4. Let processResponseEndOfBodyTask be the following steps:
  517. auto process_response_end_of_body_task = [&fetch_params, &response] {
  518. // 1. Set fetchParams’s request’s done flag.
  519. fetch_params.request()->set_done(true);
  520. // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response
  521. // end-of-body given response.
  522. if (fetch_params.algorithms()->process_response_end_of_body().has_value())
  523. (*fetch_params.algorithms()->process_response_end_of_body())(response);
  524. // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s global
  525. // object is fetchParams’s task destination, then run fetchParams’s controller’s report timing steps
  526. // given fetchParams’s request’s client’s global object.
  527. auto client = fetch_params.request()->client();
  528. auto const* task_destination_global_object = fetch_params.task_destination().get_pointer<JS::NonnullGCPtr<JS::Object>>();
  529. if (client != nullptr && task_destination_global_object != nullptr) {
  530. if (fetch_params.request()->initiator_type().has_value() && &client->global_object() == task_destination_global_object->ptr())
  531. fetch_params.controller()->report_timing(client->global_object());
  532. }
  533. };
  534. // FIXME: Handle 'parallel queue' task destination
  535. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  536. // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination.
  537. Infrastructure::queue_fetch_task(task_destination, move(process_response_end_of_body_task));
  538. };
  539. // FIXME: Handle 'parallel queue' task destination
  540. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  541. // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response
  542. // given response, with fetchParams’s task destination.
  543. if (fetch_params.algorithms()->process_response().has_value()) {
  544. Infrastructure::queue_fetch_task(task_destination, [&fetch_params, &response]() {
  545. (*fetch_params.algorithms()->process_response())(response);
  546. });
  547. }
  548. // 5. If response’s body is null, then run processResponseEndOfBody.
  549. if (!response.body().has_value()) {
  550. process_response_end_of_body();
  551. }
  552. // 6. Otherwise:
  553. else {
  554. // FIXME: 1. Let transformStream be a new TransformStream.
  555. // FIXME: 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
  556. // FIXME: 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set
  557. // to processResponseEndOfBody.
  558. // FIXME: 4. Set response’s body’s stream to the result of response’s body’s stream piped through transformStream.
  559. }
  560. // 7. If fetchParams’s process response consume body is non-null, then:
  561. if (fetch_params.algorithms()->process_response_consume_body().has_value()) {
  562. // 1. Let processBody given nullOrBytes be this step: run fetchParams’s process response consume body given
  563. // response and nullOrBytes.
  564. auto process_body = [&fetch_params, &response](Variant<ByteBuffer, Empty> const& null_or_bytes) {
  565. (*fetch_params.algorithms()->process_response_consume_body())(response, null_or_bytes);
  566. };
  567. // 2. Let processBodyError be this step: run fetchParams’s process response consume body given response and
  568. // failure.
  569. auto process_body_error = [&fetch_params, &response](auto&) {
  570. (*fetch_params.algorithms()->process_response_consume_body())(response, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
  571. };
  572. // 3. If response’s body is null, then queue a fetch task to run processBody given null, with fetchParams’s
  573. // task destination.
  574. if (!response.body().has_value()) {
  575. Infrastructure::queue_fetch_task(task_destination, [process_body = move(process_body)]() {
  576. process_body({});
  577. });
  578. }
  579. // 4. Otherwise, fully read response’s body given processBody, processBodyError, and fetchParams’s task
  580. // destination.
  581. else {
  582. TRY(response.body()->fully_read(realm, move(process_body), move(process_body_error), fetch_params.task_destination()));
  583. }
  584. }
  585. return {};
  586. }
  587. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  588. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params)
  589. {
  590. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'scheme fetch' with: fetch_params @ {}", &fetch_params);
  591. auto& vm = realm.vm();
  592. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  593. if (fetch_params.is_canceled())
  594. return PendingResponse::create(vm, fetch_params.request(), Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  595. // 2. Let request be fetchParams’s request.
  596. auto request = fetch_params.request();
  597. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  598. // -> "about"
  599. if (request->current_url().scheme() == "about"sv) {
  600. // If request’s current URL’s path is the string "blank", then return a new response whose status message is
  601. // `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », and body is the empty byte sequence as
  602. // a body.
  603. // NOTE: URLs such as "about:config" are handled during navigation and result in a network error in the context
  604. // of fetching.
  605. if (request->current_url().serialize_path() == "blank"sv) {
  606. auto response = Infrastructure::Response::create(vm);
  607. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  608. auto header = MUST(Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=utf-8"sv));
  609. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  610. response->set_body(MUST(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes())));
  611. return PendingResponse::create(vm, request, response);
  612. }
  613. }
  614. // -> "blob"
  615. else if (request->current_url().scheme() == "blob"sv) {
  616. // FIXME: Support 'blob://' URLs
  617. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has 'blob:' URL which is currently unsupported"sv));
  618. }
  619. // -> "data"
  620. else if (request->current_url().scheme() == "data"sv) {
  621. // 1. Let dataURLStruct be the result of running the data: URL processor on request’s current URL.
  622. auto const& url = request->current_url();
  623. auto data_or_error = url.data_payload_is_base64()
  624. ? decode_base64(url.data_payload())
  625. : TRY_OR_THROW_OOM(vm, ByteBuffer::copy(url.data_payload().bytes()));
  626. // 2. If dataURLStruct is failure, then return a network error.
  627. if (data_or_error.is_error())
  628. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has invalid base64 'data:' URL"sv));
  629. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  630. auto const& mime_type = url.data_mime_type();
  631. // 4. Return a new response whose status message is `OK`, header list is « (`Content-Type`, mimeType) », and
  632. // body is dataURLStruct’s body as a body.
  633. auto response = Infrastructure::Response::create(vm);
  634. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  635. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Content-Type"sv, mime_type));
  636. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  637. response->set_body(TRY(Infrastructure::byte_sequence_as_body(realm, data_or_error.value().span())));
  638. return PendingResponse::create(vm, request, response);
  639. }
  640. // -> "file"
  641. else if (request->current_url().scheme() == "file"sv) {
  642. // For now, unfortunate as it is, file: URLs are left as an exercise for the reader.
  643. // When in doubt, return a network error.
  644. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  645. }
  646. // -> HTTP(S) scheme
  647. else if (Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  648. // Return the result of running HTTP fetch given fetchParams.
  649. return http_fetch(realm, fetch_params);
  650. }
  651. // 4. Return a network error.
  652. auto message = request->current_url().scheme() == "about"sv
  653. ? TRY_OR_THROW_OOM(vm, "Request has invalid 'about:' URL, only 'about:blank' can be fetched"_string)
  654. : TRY_OR_THROW_OOM(vm, "Request URL has invalid scheme, must be one of 'about', 'blob', 'data', 'file', 'http', or 'https'"_string);
  655. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, move(message)));
  656. }
  657. // https://fetch.spec.whatwg.org/#concept-http-fetch
  658. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, MakeCORSPreflight make_cors_preflight)
  659. {
  660. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' with: fetch_params @ {}, make_cors_preflight = {}",
  661. &fetch_params, make_cors_preflight == MakeCORSPreflight::Yes ? "Yes"sv : "No"sv);
  662. auto& vm = realm.vm();
  663. // 1. Let request be fetchParams’s request.
  664. auto request = fetch_params.request();
  665. // 2. Let response be null.
  666. JS::GCPtr<Infrastructure::Response> response;
  667. // 3. Let actualResponse be null.
  668. JS::GCPtr<Infrastructure::Response> actual_response;
  669. // 4. If request’s service-workers mode is "all", then:
  670. if (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {
  671. // 1. Let requestForServiceWorker be a clone of request.
  672. auto request_for_service_worker = TRY(request->clone(realm));
  673. // 2. If requestForServiceWorker’s body is non-null, then:
  674. if (!request_for_service_worker->body().has<Empty>()) {
  675. // FIXME: 1. Let transformStream be a new TransformStream.
  676. // FIXME: 2. Let transformAlgorithm given chunk be these steps:
  677. // FIXME: 3. Set up transformStream with transformAlgorithm set to transformAlgorithm.
  678. // FIXME: 4. Set requestForServiceWorker’s body’s stream to the result of requestForServiceWorker’s body’s stream
  679. // piped through transformStream.
  680. }
  681. // 3. Let serviceWorkerStartTime be the coarsened shared current time given fetchParams’s cross-origin isolated
  682. // capability.
  683. auto service_worker_start_time = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  684. // FIXME: 4. Set response to the result of invoking handle fetch for requestForServiceWorker, with fetchParams’s
  685. // controller and fetchParams’s cross-origin isolated capability.
  686. // 5. If response is not null, then:
  687. if (response) {
  688. // 1. Set fetchParams’s timing info’s final service worker start time to serviceWorkerStartTime.
  689. fetch_params.timing_info()->set_final_service_worker_start_time(service_worker_start_time);
  690. // 2. If request’s body is non-null, then cancel request’s body with undefined.
  691. if (!request->body().has<Empty>()) {
  692. // FIXME: Implement cancelling streams
  693. }
  694. // 3. Set actualResponse to response, if response is not a filtered response, and to response’s internal
  695. // response otherwise.
  696. actual_response = !is<Infrastructure::FilteredResponse>(*response)
  697. ? JS::NonnullGCPtr { *response }
  698. : static_cast<Infrastructure::FilteredResponse const&>(*response).internal_response();
  699. // 4. If one of the following is true
  700. if (
  701. // - response’s type is "error"
  702. response->type() == Infrastructure::Response::Type::Error
  703. // - request’s mode is "same-origin" and response’s type is "cors"
  704. || (request->mode() == Infrastructure::Request::Mode::SameOrigin && response->type() == Infrastructure::Response::Type::CORS)
  705. // - request’s mode is not "no-cors" and response’s type is "opaque"
  706. || (request->mode() != Infrastructure::Request::Mode::NoCORS && response->type() == Infrastructure::Response::Type::Opaque)
  707. // - request’s redirect mode is not "manual" and response’s type is "opaqueredirect"
  708. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Manual && response->type() == Infrastructure::Response::Type::OpaqueRedirect)
  709. // - request’s redirect mode is not "follow" and response’s URL list has more than one item.
  710. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow && response->url_list().size() > 1)) {
  711. // then return a network error.
  712. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Invalid request/response state combination"sv));
  713. }
  714. }
  715. }
  716. JS::GCPtr<PendingResponse> pending_actual_response;
  717. auto returned_pending_response = PendingResponse::create(vm, request);
  718. // 5. If response is null, then:
  719. if (!response) {
  720. // 1. If makeCORSPreflight is true and one of these conditions is true:
  721. // NOTE: This step checks the CORS-preflight cache and if there is no suitable entry it performs a
  722. // CORS-preflight fetch which, if successful, populates the cache. The purpose of the CORS-preflight
  723. // fetch is to ensure the fetched resource is familiar with the CORS protocol. The cache is there to
  724. // minimize the number of CORS-preflight fetches.
  725. JS::GCPtr<PendingResponse> pending_preflight_response;
  726. if (make_cors_preflight == MakeCORSPreflight::Yes && (
  727. // - There is no method cache entry match for request’s method using request, and either request’s
  728. // method is not a CORS-safelisted method or request’s use-CORS-preflight flag is set.
  729. // FIXME: We currently have no cache, so there will always be no method cache entry.
  730. (!Infrastructure::is_cors_safelisted_method(request->method()) || request->use_cors_preflight())
  731. // - There is at least one item in the CORS-unsafe request-header names with request’s header list for
  732. // which there is no header-name cache entry match using request.
  733. // FIXME: We currently have no cache, so there will always be no header-name cache entry.
  734. || !TRY_OR_THROW_OOM(vm, Infrastructure::get_cors_unsafe_header_names(request->header_list())).is_empty())) {
  735. // 1. Let preflightResponse be the result of running CORS-preflight fetch given request.
  736. pending_preflight_response = TRY(cors_preflight_fetch(realm, request));
  737. // NOTE: Step 2 is performed in pending_preflight_response's load callback below.
  738. }
  739. auto fetch_main_content = [request = JS::make_handle(request), realm = JS::make_handle(realm), fetch_params = JS::make_handle(fetch_params)]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> {
  740. // 2. If request’s redirect mode is "follow", then set request’s service-workers mode to "none".
  741. // NOTE: Redirects coming from the network (as opposed to from a service worker) are not to be exposed to a
  742. // service worker.
  743. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Follow)
  744. request->set_service_workers_mode(Infrastructure::Request::ServiceWorkersMode::None);
  745. // 3. Set response and actualResponse to the result of running HTTP-network-or-cache fetch given fetchParams.
  746. return http_network_or_cache_fetch(*realm, *fetch_params);
  747. };
  748. if (pending_preflight_response) {
  749. pending_actual_response = PendingResponse::create(vm, request);
  750. pending_preflight_response->when_loaded([returned_pending_response, pending_actual_response, fetch_main_content = move(fetch_main_content)](JS::NonnullGCPtr<Infrastructure::Response> preflight_response) {
  751. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_preflight_response load callback");
  752. // 2. If preflightResponse is a network error, then return preflightResponse.
  753. if (preflight_response->is_network_error()) {
  754. returned_pending_response->resolve(preflight_response);
  755. return;
  756. }
  757. auto pending_main_content_response = TRY_OR_IGNORE(fetch_main_content());
  758. pending_main_content_response->when_loaded([pending_actual_response](JS::NonnullGCPtr<Infrastructure::Response> main_content_response) {
  759. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_main_content_response load callback");
  760. pending_actual_response->resolve(main_content_response);
  761. });
  762. });
  763. } else {
  764. pending_actual_response = TRY(fetch_main_content());
  765. }
  766. } else {
  767. pending_actual_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  768. }
  769. pending_actual_response->when_loaded([&realm, &vm, &fetch_params, request, response, actual_response, returned_pending_response, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_actual_response) mutable {
  770. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_actual_response load callback");
  771. if (response_was_null) {
  772. response = actual_response = resolved_actual_response;
  773. // 4. If request’s response tainting is "cors" and a CORS check for request and response returns failure,
  774. // then return a network error.
  775. // NOTE: As the CORS check is not to be applied to responses whose status is 304 or 407, or responses from
  776. // a service worker for that matter, it is applied here.
  777. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS
  778. && !TRY_OR_IGNORE(cors_check(request, *response))) {
  779. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request with 'cors' response tainting failed CORS check"_string)));
  780. return;
  781. }
  782. // 5. If the TAO check for request and response returns failure, then set request’s timing allow failed flag.
  783. if (!TRY_OR_IGNORE(tao_check(request, *response)))
  784. request->set_timing_allow_failed(true);
  785. }
  786. // 6. If either request’s response tainting or response’s type is "opaque", and the cross-origin resource
  787. // policy check with request’s origin, request’s client, request’s destination, and actualResponse returns
  788. // blocked, then return a network error.
  789. // NOTE: The cross-origin resource policy check runs for responses coming from the network and responses coming
  790. // from the service worker. This is different from the CORS check, as request’s client and the service
  791. // worker can have different embedder policies.
  792. if ((request->response_tainting() == Infrastructure::Request::ResponseTainting::Opaque || response->type() == Infrastructure::Response::Type::Opaque)
  793. && false // FIXME: "and the cross-origin resource policy check with request’s origin, request’s client, request’s destination, and actualResponse returns blocked"
  794. ) {
  795. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Response was blocked by cross-origin resource policy check"_string)));
  796. return;
  797. }
  798. Optional<JS::NonnullGCPtr<PendingResponse>> inner_pending_response;
  799. // 7. If actualResponse’s status is a redirect status, then:
  800. if (Infrastructure::is_redirect_status(actual_response->status())) {
  801. // FIXME: 1. If actualResponse’s status is not 303, request’s body is not null, and the connection uses HTTP/2,
  802. // then user agents may, and are even encouraged to, transmit an RST_STREAM frame.
  803. // NOTE: 303 is excluded as certain communities ascribe special status to it.
  804. // 2. Switch on request’s redirect mode:
  805. switch (request->redirect_mode()) {
  806. // -> "error"
  807. case Infrastructure::Request::RedirectMode::Error:
  808. // Set response to a network error.
  809. response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request with 'error' redirect mode received redirect response"_string));
  810. break;
  811. // -> "manual"
  812. case Infrastructure::Request::RedirectMode::Manual:
  813. // 1. If request’s mode is "navigate", then set fetchParams’s controller’s next manual redirect steps
  814. // to run HTTP-redirect fetch given fetchParams and response.
  815. if (request->mode() == Infrastructure::Request::Mode::Navigate) {
  816. fetch_params.controller()->set_next_manual_redirect_steps([&realm, &fetch_params, response] {
  817. (void)http_redirect_fetch(realm, fetch_params, *response);
  818. });
  819. }
  820. // 2. Otherwise, set response to an opaque-redirect filtered response whose internal response is
  821. // actualResponse.
  822. else {
  823. response = Infrastructure::OpaqueRedirectFilteredResponse::create(vm, *actual_response);
  824. }
  825. break;
  826. // -> "follow"
  827. case Infrastructure::Request::RedirectMode::Follow:
  828. // Set response to the result of running HTTP-redirect fetch given fetchParams and response.
  829. inner_pending_response = TRY_OR_IGNORE(http_redirect_fetch(realm, fetch_params, *response));
  830. break;
  831. default:
  832. VERIFY_NOT_REACHED();
  833. }
  834. }
  835. if (inner_pending_response.has_value()) {
  836. inner_pending_response.value()->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  837. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' inner_pending_response load callback");
  838. returned_pending_response->resolve(response);
  839. });
  840. } else {
  841. returned_pending_response->resolve(*response);
  842. }
  843. });
  844. // 8. Return response.
  845. // NOTE: Typically actualResponse’s body’s stream is still being enqueued to after returning.
  846. return returned_pending_response;
  847. }
  848. // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch
  849. WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> http_redirect_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  850. {
  851. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-redirect fetch' with: fetch_params @ {}, response = {}", &fetch_params, &response);
  852. auto& vm = realm.vm();
  853. // 1. Let request be fetchParams’s request.
  854. auto request = fetch_params.request();
  855. // 2. Let actualResponse be response, if response is not a filtered response, and response’s internal response
  856. // otherwise.
  857. auto actual_response = !is<Infrastructure::FilteredResponse>(response)
  858. ? JS::NonnullGCPtr { response }
  859. : static_cast<Infrastructure::FilteredResponse const&>(response).internal_response();
  860. // 3. Let locationURL be actualResponse’s location URL given request’s current URL’s fragment.
  861. auto const& fragment = request->current_url().fragment();
  862. auto fragment_string = fragment.is_null() ? Optional<String> {} : TRY_OR_THROW_OOM(vm, String::from_deprecated_string(fragment));
  863. auto location_url_or_error = actual_response->location_url(fragment_string);
  864. // 4. If locationURL is null, then return response.
  865. if (!location_url_or_error.is_error() && !location_url_or_error.value().has_value())
  866. return PendingResponse::create(vm, request, response);
  867. // 5. If locationURL is failure, then return a network error.
  868. if (location_url_or_error.is_error())
  869. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL is invalid"sv));
  870. auto location_url = location_url_or_error.release_value().release_value();
  871. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network error.
  872. if (!Infrastructure::is_http_or_https_scheme(location_url.scheme()))
  873. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL must have HTTP or HTTPS scheme"sv));
  874. // 7. If request’s redirect count is 20, then return a network error.
  875. if (request->redirect_count() == 20)
  876. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has reached maximum redirect count of 20"sv));
  877. // 8. Increase request’s redirect count by 1.
  878. request->set_redirect_count(request->redirect_count() + 1);
  879. // 8. If request’s mode is "cors", locationURL includes credentials, and request’s origin is not same origin with
  880. // locationURL’s origin, then return a network error.
  881. if (request->mode() == Infrastructure::Request::Mode::CORS
  882. && location_url.includes_credentials()
  883. && request->origin().has<HTML::Origin>()
  884. && !request->origin().get<HTML::Origin>().is_same_origin(URL::url_origin(location_url))) {
  885. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' mode and different URL and request origin must not include credentials in redirect URL"sv));
  886. }
  887. // 10. If request’s response tainting is "cors" and locationURL includes credentials, then return a network error.
  888. // NOTE: This catches a cross-origin resource redirecting to a same-origin URL.
  889. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS && location_url.includes_credentials())
  890. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' response tainting must not include credentials in redirect URL"sv));
  891. // 11. If actualResponse’s status is not 303, request’s body is non-null, and request’s body’s source is null, then
  892. // return a network error.
  893. if (actual_response->status() != 303
  894. && !request->body().has<Empty>()
  895. && request->body().get<Infrastructure::Body>().source().has<Empty>()) {
  896. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has body but no body source"sv));
  897. }
  898. // 12. If one of the following is true
  899. if (
  900. // - actualResponse’s status is 301 or 302 and request’s method is `POST`
  901. ((actual_response->status() == 301 || actual_response->status() == 302) && request->method() == "POST"sv.bytes())
  902. // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  903. || (actual_response->status() == 303 && !(request->method() == "GET"sv.bytes() || request->method() == "HEAD"sv.bytes()))
  904. // then:
  905. ) {
  906. // 1. Set request’s method to `GET` and request’s body to null.
  907. request->set_method(MUST(ByteBuffer::copy("GET"sv.bytes())));
  908. request->set_body({});
  909. static constexpr Array request_body_header_names {
  910. "Content-Encoding"sv,
  911. "Content-Language"sv,
  912. "Content-Location"sv,
  913. "Content-Type"sv
  914. };
  915. // 2. For each headerName of request-body-header name, delete headerName from request’s header list.
  916. for (auto header_name : request_body_header_names.span())
  917. request->header_list()->delete_(header_name.bytes());
  918. }
  919. // 13. If request’s current URL’s origin is not same origin with locationURL’s origin, then for each headerName of
  920. // CORS non-wildcard request-header name, delete headerName from request’s header list.
  921. // NOTE: I.e., the moment another origin is seen after the initial request, the `Authorization` header is removed.
  922. if (!URL::url_origin(request->current_url()).is_same_origin(URL::url_origin(location_url))) {
  923. static constexpr Array cors_non_wildcard_request_header_names {
  924. "Authorization"sv
  925. };
  926. for (auto header_name : cors_non_wildcard_request_header_names)
  927. request->header_list()->delete_(header_name.bytes());
  928. }
  929. // 14. If request’s body is non-null, then set request’s body to the body of the result of safely extracting
  930. // request’s body’s source.
  931. // NOTE: request’s body’s source’s nullity has already been checked.
  932. if (!request->body().has<Empty>()) {
  933. auto const& source = request->body().get<Infrastructure::Body>().source();
  934. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  935. auto converted_source = source.has<ByteBuffer>()
  936. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  937. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  938. auto [body, _] = TRY(safely_extract_body(realm, converted_source));
  939. request->set_body(move(body));
  940. }
  941. // 15. Let timingInfo be fetchParams’s timing info.
  942. auto timing_info = fetch_params.timing_info();
  943. // 16. Set timingInfo’s redirect end time and post-redirect start time to the coarsened shared current time given
  944. // fetchParams’s cross-origin isolated capability.
  945. auto now = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  946. timing_info->set_redirect_end_time(now);
  947. timing_info->set_post_redirect_start_time(now);
  948. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s redirect start time to timingInfo’s start
  949. // time.
  950. if (timing_info->redirect_start_time() == 0)
  951. timing_info->set_redirect_start_time(timing_info->start_time());
  952. // 18. Append locationURL to request’s URL list.
  953. request->url_list().append(location_url);
  954. // FIXME: 19. Invoke set request’s referrer policy on redirect on request and actualResponse.
  955. // 20. Let recursive be true.
  956. auto recursive = Recursive::Yes;
  957. // 21. If request’s redirect mode is "manual", then:
  958. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Manual) {
  959. // 1. Assert: request’s mode is "navigate".
  960. VERIFY(request->mode() == Infrastructure::Request::Mode::Navigate);
  961. // 2. Set recursive to false.
  962. recursive = Recursive::No;
  963. }
  964. // 22. Return the result of running main fetch given fetchParams and recursive.
  965. return main_fetch(realm, fetch_params, recursive);
  966. }
  967. // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
  968. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch)
  969. {
  970. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' with: fetch_params @ {}, is_authentication_fetch = {}, is_new_connection_fetch = {}",
  971. &fetch_params, is_authentication_fetch == IsAuthenticationFetch::Yes ? "Yes"sv : "No"sv, is_new_connection_fetch == IsNewConnectionFetch::Yes ? "Yes"sv : "No"sv);
  972. auto& vm = realm.vm();
  973. // 1. Let request be fetchParams’s request.
  974. auto request = fetch_params.request();
  975. // 2. Let httpFetchParams be null.
  976. JS::GCPtr<Infrastructure::FetchParams const> http_fetch_params;
  977. // 3. Let httpRequest be null.
  978. JS::GCPtr<Infrastructure::Request> http_request;
  979. // 4. Let response be null.
  980. JS::GCPtr<Infrastructure::Response> response;
  981. // 5. Let storedResponse be null.
  982. JS::GCPtr<Infrastructure::Response> stored_response;
  983. // 6. Let httpCache be null.
  984. // (Typeless until we actually implement it, needed for checks below)
  985. void* http_cache = nullptr;
  986. // 7. Let the revalidatingFlag be unset.
  987. auto revalidating_flag = RefCountedFlag::create(false);
  988. auto include_credentials = IncludeCredentials::No;
  989. // 8. Run these steps, but abort when fetchParams is canceled:
  990. // NOTE: There's an 'if aborted' check after this anyway, so not doing this is fine and only incurs a small delay.
  991. // For now, support for aborting fetch requests is limited anyway as ResourceLoader doesn't support it.
  992. auto aborted = false;
  993. {
  994. ScopeGuard set_aborted = [&] {
  995. if (fetch_params.is_canceled())
  996. aborted = true;
  997. };
  998. // 1. If request’s window is "no-window" and request’s redirect mode is "error", then set httpFetchParams to
  999. // fetchParams and httpRequest to request.
  1000. if (request->window().has<Infrastructure::Request::Window>()
  1001. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow
  1002. && request->redirect_mode() == Infrastructure::Request::RedirectMode::Error) {
  1003. http_fetch_params = fetch_params;
  1004. http_request = request;
  1005. }
  1006. // 2. Otherwise:
  1007. else {
  1008. // 1. Set httpRequest to a clone of request.
  1009. // NOTE: Implementations are encouraged to avoid teeing request’s body’s stream when request’s body’s
  1010. // source is null as only a single body is needed in that case. E.g., when request’s body’s source
  1011. // is null, redirects and authentication will end up failing the fetch.
  1012. http_request = TRY(request->clone(realm));
  1013. // 2. Set httpFetchParams to a copy of fetchParams.
  1014. // 3. Set httpFetchParams’s request to httpRequest.
  1015. auto new_http_fetch_params = Infrastructure::FetchParams::create(vm, *http_request, fetch_params.timing_info());
  1016. new_http_fetch_params->set_algorithms(fetch_params.algorithms());
  1017. new_http_fetch_params->set_task_destination(fetch_params.task_destination());
  1018. new_http_fetch_params->set_cross_origin_isolated_capability(fetch_params.cross_origin_isolated_capability());
  1019. new_http_fetch_params->set_preloaded_response_candidate(fetch_params.preloaded_response_candidate());
  1020. http_fetch_params = new_http_fetch_params;
  1021. }
  1022. // 3. Let includeCredentials be true if one of
  1023. if (
  1024. // - request’s credentials mode is "include"
  1025. request->credentials_mode() == Infrastructure::Request::CredentialsMode::Include
  1026. // - request’s credentials mode is "same-origin" and request’s response tainting is "basic"
  1027. || (request->credentials_mode() == Infrastructure::Request::CredentialsMode::SameOrigin
  1028. && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  1029. // is true; otherwise false.
  1030. ) {
  1031. include_credentials = IncludeCredentials::Yes;
  1032. } else {
  1033. include_credentials = IncludeCredentials::No;
  1034. }
  1035. // 4. If Cross-Origin-Embedder-Policy allows credentials with request returns false, then set
  1036. // includeCredentials to false.
  1037. if (!request->cross_origin_embedder_policy_allows_credentials())
  1038. include_credentials = IncludeCredentials::No;
  1039. // 5. Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null; otherwise null.
  1040. auto content_length = http_request->body().has<Infrastructure::Body>()
  1041. ? http_request->body().get<Infrastructure::Body>().length()
  1042. : Optional<u64> {};
  1043. // 6. Let contentLengthHeaderValue be null.
  1044. auto content_length_header_value = Optional<ByteBuffer> {};
  1045. // 7. If httpRequest’s body is null and httpRequest’s method is `POST` or `PUT`, then set
  1046. // contentLengthHeaderValue to `0`.
  1047. if (http_request->body().has<Empty>() && StringView { http_request->method() }.is_one_of("POST"sv, "PUT"sv))
  1048. content_length_header_value = MUST(ByteBuffer::copy("0"sv.bytes()));
  1049. // 8. If contentLength is non-null, then set contentLengthHeaderValue to contentLength, serialized and
  1050. // isomorphic encoded.
  1051. if (content_length.has_value())
  1052. content_length_header_value = MUST(ByteBuffer::copy(TRY_OR_THROW_OOM(vm, String::number(*content_length)).bytes()));
  1053. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, contentLengthHeaderValue) to
  1054. // httpRequest’s header list.
  1055. if (content_length_header_value.has_value()) {
  1056. auto header = Infrastructure::Header {
  1057. .name = MUST(ByteBuffer::copy("Content-Length"sv.bytes())),
  1058. .value = content_length_header_value.release_value(),
  1059. };
  1060. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1061. }
  1062. // FIXME: 10. If contentLength is non-null and httpRequest’s keepalive is true, then:
  1063. if (content_length.has_value() && http_request->keepalive()) {
  1064. // FIXME: 1-5., requires 'fetch records' and 'fetch group' concepts.
  1065. // NOTE: The above limit ensures that requests that are allowed to outlive the environment settings object
  1066. // and contain a body, have a bounded size and are not allowed to stay alive indefinitely.
  1067. }
  1068. // 11. If httpRequest’s referrer is a URL, then:
  1069. if (http_request->referrer().has<AK::URL>()) {
  1070. // 1. Let referrerValue be httpRequest’s referrer, serialized and isomorphic encoded.
  1071. auto referrer_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(http_request->referrer().get<AK::URL>().serialize().bytes()));
  1072. // 2. Append (`Referer`, referrerValue) to httpRequest’s header list.
  1073. auto header = Infrastructure::Header {
  1074. .name = MUST(ByteBuffer::copy("Referer"sv.bytes())),
  1075. .value = move(referrer_value),
  1076. };
  1077. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1078. }
  1079. // 12. Append a request `Origin` header for httpRequest.
  1080. TRY_OR_THROW_OOM(vm, http_request->add_origin_header());
  1081. // FIXME: 13. Append the Fetch metadata headers for httpRequest.
  1082. // 14. If httpRequest’s header list does not contain `User-Agent`, then user agents should append
  1083. // (`User-Agent`, default `User-Agent` value) to httpRequest’s header list.
  1084. if (!http_request->header_list()->contains("User-Agent"sv.bytes())) {
  1085. auto header = Infrastructure::Header {
  1086. .name = MUST(ByteBuffer::copy("User-Agent"sv.bytes())),
  1087. .value = TRY_OR_THROW_OOM(vm, Infrastructure::default_user_agent_value()),
  1088. };
  1089. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1090. }
  1091. // 15. If httpRequest’s cache mode is "default" and httpRequest’s header list contains `If-Modified-Since`,
  1092. // `If-None-Match`, `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set httpRequest’s cache mode to
  1093. // "no-store".
  1094. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::Default
  1095. && (http_request->header_list()->contains("If-Modified-Since"sv.bytes())
  1096. || http_request->header_list()->contains("If-None-Match"sv.bytes())
  1097. || http_request->header_list()->contains("If-Unmodified-Since"sv.bytes())
  1098. || http_request->header_list()->contains("If-Match"sv.bytes())
  1099. || http_request->header_list()->contains("If-Range"sv.bytes()))) {
  1100. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1101. }
  1102. // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache cache-control header
  1103. // modification flag is unset, and httpRequest’s header list does not contain `Cache-Control`, then append
  1104. // (`Cache-Control`, `max-age=0`) to httpRequest’s header list.
  1105. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoCache
  1106. && !http_request->prevent_no_cache_cache_control_header_modification()
  1107. && !http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1108. auto header = MUST(Infrastructure::Header::from_string_pair("Cache-Control"sv, "max-age=0"sv));
  1109. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1110. }
  1111. // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
  1112. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoStore
  1113. || http_request->cache_mode() == Infrastructure::Request::CacheMode::Reload) {
  1114. // 1. If httpRequest’s header list does not contain `Pragma`, then append (`Pragma`, `no-cache`) to
  1115. // httpRequest’s header list.
  1116. if (!http_request->header_list()->contains("Pragma"sv.bytes())) {
  1117. auto header = MUST(Infrastructure::Header::from_string_pair("Pragma"sv, "no-cache"sv));
  1118. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1119. }
  1120. // 2. If httpRequest’s header list does not contain `Cache-Control`, then append
  1121. // (`Cache-Control`, `no-cache`) to httpRequest’s header list.
  1122. if (!http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1123. auto header = MUST(Infrastructure::Header::from_string_pair("Cache-Control"sv, "no-cache"sv));
  1124. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1125. }
  1126. }
  1127. // 18. If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`) to
  1128. // httpRequest’s header list.
  1129. // NOTE: This avoids a failure when handling content codings with a part of an encoded response.
  1130. // Additionally, many servers mistakenly ignore `Range` headers if a non-identity encoding is accepted.
  1131. if (http_request->header_list()->contains("Range"sv.bytes())) {
  1132. auto header = MUST(Infrastructure::Header::from_string_pair("Accept-Encoding"sv, "identity"sv));
  1133. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1134. }
  1135. // 19. Modify httpRequest’s header list per HTTP. Do not append a given header if httpRequest’s header list
  1136. // contains that header’s name.
  1137. // NOTE: It would be great if we could make this more normative somehow. At this point headers such as
  1138. // `Accept-Encoding`, `Connection`, `DNT`, and `Host`, are to be appended if necessary.
  1139. // `Accept`, `Accept-Charset`, and `Accept-Language` must not be included at this point.
  1140. // NOTE: `Accept` and `Accept-Language` are already included (unless fetch() is used, which does not include
  1141. // the latter by default), and `Accept-Charset` is a waste of bytes. See HTTP header layer division for
  1142. // more details.
  1143. // 20. If includeCredentials is true, then:
  1144. if (include_credentials == IncludeCredentials::Yes) {
  1145. // 1. If the user agent is not configured to block cookies for httpRequest (see section 7 of [COOKIES]),
  1146. // then:
  1147. if (true) {
  1148. // 1. Let cookies be the result of running the "cookie-string" algorithm (see section 5.4 of [COOKIES])
  1149. // with the user agent’s cookie store and httpRequest’s current URL.
  1150. auto cookies = ([&] {
  1151. // FIXME: Getting to the page client reliably is way too complicated, and going via the document won't work in workers.
  1152. auto document = Bindings::host_defined_environment_settings_object(realm).responsible_document();
  1153. if (!document)
  1154. return DeprecatedString::empty();
  1155. auto* page = document->page();
  1156. if (!page)
  1157. return DeprecatedString::empty();
  1158. return page->client().page_did_request_cookie(http_request->current_url(), Cookie::Source::Http);
  1159. })();
  1160. // 2. If cookies is not the empty string, then append (`Cookie`, cookies) to httpRequest’s header list.
  1161. if (!cookies.is_empty()) {
  1162. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Cookie"sv, cookies));
  1163. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1164. }
  1165. }
  1166. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1167. if (!http_request->header_list()->contains("Authorization"sv.bytes())) {
  1168. // 1. Let authorizationValue be null.
  1169. auto authorization_value = Optional<String> {};
  1170. // 2. If there’s an authentication entry for httpRequest and either httpRequest’s use-URL-credentials
  1171. // flag is unset or httpRequest’s current URL does not include credentials, then set
  1172. // authorizationValue to authentication entry.
  1173. if (false // FIXME: "If there’s an authentication entry for httpRequest"
  1174. && (!http_request->use_url_credentials() || !http_request->current_url().includes_credentials())) {
  1175. // FIXME: "set authorizationValue to authentication entry."
  1176. }
  1177. // 3. Otherwise, if httpRequest’s current URL does include credentials and isAuthenticationFetch is
  1178. // true, set authorizationValue to httpRequest’s current URL, converted to an `Authorization` value.
  1179. else if (http_request->current_url().includes_credentials() && is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1180. auto const& url = http_request->current_url();
  1181. auto payload = TRY_OR_THROW_OOM(vm, String::formatted("{}:{}", url.username(), url.password()));
  1182. authorization_value = TRY_OR_THROW_OOM(vm, encode_base64(payload.bytes()));
  1183. }
  1184. // 4. If authorizationValue is non-null, then append (`Authorization`, authorizationValue) to
  1185. // httpRequest’s header list.
  1186. if (authorization_value.has_value()) {
  1187. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Authorization"sv, *authorization_value));
  1188. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1189. }
  1190. }
  1191. }
  1192. // FIXME: 21. If there’s a proxy-authentication entry, use it as appropriate.
  1193. // NOTE: This intentionally does not depend on httpRequest’s credentials mode.
  1194. // FIXME: 22. Set httpCache to the result of determining the HTTP cache partition, given httpRequest.
  1195. // 23. If httpCache is null, then set httpRequest’s cache mode to "no-store".
  1196. if (!http_cache)
  1197. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1198. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", then:
  1199. if (http_request->cache_mode() != Infrastructure::Request::CacheMode::NoStore
  1200. && http_request->cache_mode() != Infrastructure::Request::CacheMode::Reload) {
  1201. // 1. Set storedResponse to the result of selecting a response from the httpCache, possibly needing
  1202. // validation, as per the "Constructing Responses from Caches" chapter of HTTP Caching [HTTP-CACHING],
  1203. // if any.
  1204. // NOTE: As mandated by HTTP, this still takes the `Vary` header into account.
  1205. stored_response = nullptr;
  1206. // 2. If storedResponse is non-null, then:
  1207. if (stored_response) {
  1208. // FIXME: Caching is not implemented yet.
  1209. VERIFY_NOT_REACHED();
  1210. }
  1211. }
  1212. }
  1213. // 9. If aborted, then return the appropriate network error for fetchParams.
  1214. if (aborted)
  1215. return PendingResponse::create(vm, request, Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1216. JS::GCPtr<PendingResponse> pending_forward_response;
  1217. // 10. If response is null, then:
  1218. if (!response) {
  1219. // 1. If httpRequest’s cache mode is "only-if-cached", then return a network error.
  1220. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::OnlyIfCached)
  1221. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'only-if-cached' cache mode doesn't have a cached response"sv));
  1222. // 2. Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams, includeCredentials,
  1223. // and isNewConnectionFetch.
  1224. pending_forward_response = TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, *http_fetch_params, include_credentials, is_new_connection_fetch));
  1225. } else {
  1226. pending_forward_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  1227. }
  1228. auto returned_pending_response = PendingResponse::create(vm, request);
  1229. pending_forward_response->when_loaded([&realm, &vm, &fetch_params, request, response, stored_response, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, revalidating_flag, include_credentials, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_forward_response) mutable {
  1230. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");
  1231. if (response_was_null) {
  1232. auto forward_response = resolved_forward_response;
  1233. // NOTE: TRACE is omitted as it is a forbidden method in Fetch.
  1234. auto method_is_unsafe = StringView { http_request->method() }.is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv);
  1235. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399, inclusive,
  1236. // invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP
  1237. // Caching, and set storedResponse to null.
  1238. if (method_is_unsafe && forward_response->status() >= 200 && forward_response->status() <= 399) {
  1239. // FIXME: "invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP Caching"
  1240. stored_response = nullptr;
  1241. }
  1242. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, then:
  1243. if (revalidating_flag->value() && forward_response->status() == 304) {
  1244. // FIXME: 1. Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening
  1245. // Stored Responses upon Validation" chapter of HTTP Caching.
  1246. // NOTE: This updates the stored response in cache as well.
  1247. // 2. Set response to storedResponse.
  1248. response = stored_response;
  1249. // 3. Set response’s cache state to "validated".
  1250. if (response)
  1251. response->set_cache_state(Infrastructure::Response::CacheState::Validated);
  1252. }
  1253. // 5. If response is null, then:
  1254. if (!response) {
  1255. // 1. Set response to forwardResponse.
  1256. response = forward_response;
  1257. // FIXME: 2. Store httpRequest and forwardResponse in httpCache, as per the "Storing Responses in Caches"
  1258. // chapter of HTTP Caching.
  1259. // NOTE: If forwardResponse is a network error, this effectively caches the network error, which is
  1260. // sometimes known as "negative caching".
  1261. // NOTE: The associated body info is stored in the cache alongside the response.
  1262. }
  1263. }
  1264. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1265. response->set_url_list(http_request->url_list());
  1266. // 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.
  1267. if (http_request->header_list()->contains("Range"sv.bytes()))
  1268. response->set_range_requested(true);
  1269. // 13. Set response’s request-includes-credentials to includeCredentials.
  1270. response->set_request_includes_credentials(include_credentials == IncludeCredentials::Yes);
  1271. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1272. // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", includeCredentials is true,
  1273. // and request’s window is an environment settings object, then:
  1274. if (response->status() == 401
  1275. && http_request->response_tainting() != Infrastructure::Request::ResponseTainting::CORS
  1276. && include_credentials == IncludeCredentials::Yes
  1277. && request->window().has<JS::GCPtr<HTML::EnvironmentSettingsObject>>()) {
  1278. // 1. Needs testing: multiple `WWW-Authenticate` headers, missing, parsing issues.
  1279. // (Red box in the spec, no-op)
  1280. // 2. If request’s body is non-null, then:
  1281. if (!request->body().has<Empty>()) {
  1282. // 1. If request’s body’s source is null, then return a network error.
  1283. if (request->body().get<Infrastructure::Body>().source().has<Empty>()) {
  1284. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request has body but no body source"_string)));
  1285. return;
  1286. }
  1287. // 2. Set request’s body to the body of the result of safely extracting request’s body’s source.
  1288. auto const& source = request->body().get<Infrastructure::Body>().source();
  1289. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  1290. auto converted_source = source.has<ByteBuffer>()
  1291. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  1292. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  1293. auto [body, _] = TRY_OR_IGNORE(safely_extract_body(realm, converted_source));
  1294. request->set_body(move(body));
  1295. }
  1296. // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
  1297. if (!request->use_url_credentials() || is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1298. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1299. if (fetch_params.is_canceled()) {
  1300. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1301. return;
  1302. }
  1303. // FIXME: 2. Let username and password be the result of prompting the end user for a username and password,
  1304. // respectively, in request’s window.
  1305. dbgln("Fetch: Username/password prompt is not implemented, using empty strings. This request will probably fail.");
  1306. auto username = DeprecatedString::empty();
  1307. auto password = DeprecatedString::empty();
  1308. // 3. Set the username given request’s current URL and username.
  1309. request->current_url().set_username(move(username));
  1310. // 4. Set the password given request’s current URL and password.
  1311. request->current_url().set_password(move(password));
  1312. }
  1313. // 4. Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.
  1314. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes));
  1315. }
  1316. inner_pending_response->when_loaded([&realm, &vm, &fetch_params, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1317. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");
  1318. // 15. If response’s status is 407, then:
  1319. if (response->status() == 407) {
  1320. // 1. If request’s window is "no-window", then return a network error.
  1321. if (request->window().has<Infrastructure::Request::Window>()
  1322. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow) {
  1323. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request requires proxy authentication but has 'no-window' set"_string)));
  1324. return;
  1325. }
  1326. // 2. Needs testing: multiple `Proxy-Authenticate` headers, missing, parsing issues.
  1327. // (Red box in the spec, no-op)
  1328. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1329. if (fetch_params.is_canceled()) {
  1330. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1331. return;
  1332. }
  1333. // FIXME: 4. Prompt the end user as appropriate in request’s window and store the result as a
  1334. // proxy-authentication entry.
  1335. // NOTE: Remaining details surrounding proxy authentication are defined by HTTP.
  1336. // FIXME: 5. Set response to the result of running HTTP-network-or-cache fetch given fetchParams.
  1337. // (Doing this without step 4 would potentially lead to an infinite request cycle.)
  1338. }
  1339. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1340. // 16. If all of the following are true
  1341. if (
  1342. // - response’s status is 421
  1343. response->status() == 421
  1344. // - isNewConnectionFetch is false
  1345. && is_new_connection_fetch == IsNewConnectionFetch::No
  1346. // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1347. && (request->body().has<Empty>() || !request->body().get<Infrastructure::Body>().source().has<Empty>())
  1348. // then:
  1349. ) {
  1350. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1351. if (fetch_params.is_canceled()) {
  1352. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1353. return;
  1354. }
  1355. // 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,
  1356. // isAuthenticationFetch, and true.
  1357. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes));
  1358. }
  1359. inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1360. // 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given
  1361. // realm.
  1362. if (is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1363. // FIXME: "create an authentication entry for request and the given realm"
  1364. }
  1365. returned_pending_response->resolve(response);
  1366. });
  1367. });
  1368. });
  1369. // 18. Return response.
  1370. // NOTE: Typically response’s body’s stream is still being enqueued to after returning.
  1371. return returned_pending_response;
  1372. }
  1373. #if defined(WEB_FETCH_DEBUG)
  1374. static void log_load_request(auto const& load_request)
  1375. {
  1376. dbgln("Fetch: Invoking ResourceLoader");
  1377. dbgln("> {} {} HTTP/1.1", load_request.method(), load_request.url());
  1378. for (auto const& [name, value] : load_request.headers())
  1379. dbgln("> {}: {}", name, value);
  1380. dbgln(">");
  1381. for (auto line : StringView { load_request.body() }.split_view('\n', SplitBehavior::KeepEmpty))
  1382. dbgln("> {}", line);
  1383. }
  1384. static void log_response(auto const& status_code, auto const& headers, auto const& data)
  1385. {
  1386. dbgln("< HTTP/1.1 {}", status_code.value_or(0));
  1387. for (auto const& [name, value] : headers)
  1388. dbgln("< {}: {}", name, value);
  1389. dbgln("<");
  1390. for (auto line : StringView { data }.split_view('\n', SplitBehavior::KeepEmpty))
  1391. dbgln("< {}", line);
  1392. }
  1393. #endif
  1394. // https://fetch.spec.whatwg.org/#concept-http-network-fetch
  1395. // Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)
  1396. // It also handles file:// URLs since those can also go through ResourceLoader.
  1397. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> nonstandard_resource_loader_file_or_http_network_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, IncludeCredentials include_credentials, IsNewConnectionFetch is_new_connection_fetch)
  1398. {
  1399. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'non-standard HTTP-network fetch' with: fetch_params @ {}", &fetch_params);
  1400. auto& vm = realm.vm();
  1401. (void)include_credentials;
  1402. (void)is_new_connection_fetch;
  1403. auto request = fetch_params.request();
  1404. Page* page = nullptr;
  1405. auto& global_object = realm.global_object();
  1406. if (is<HTML::Window>(global_object))
  1407. page = static_cast<HTML::Window&>(global_object).page();
  1408. // NOTE: Using LoadRequest::create_for_url_on_page here will unconditionally add cookies as long as there's a page available.
  1409. // However, it is up to http_network_or_cache_fetch to determine if cookies should be added to the request.
  1410. LoadRequest load_request;
  1411. load_request.set_url(request->current_url());
  1412. if (page)
  1413. load_request.set_page(*page);
  1414. load_request.set_method(DeprecatedString::copy(request->method()));
  1415. for (auto const& header : *request->header_list())
  1416. load_request.set_header(DeprecatedString::copy(header.name), DeprecatedString::copy(header.value));
  1417. if (auto const* body = request->body().get_pointer<Infrastructure::Body>()) {
  1418. TRY(body->source().visit(
  1419. [&](ByteBuffer const& byte_buffer) -> WebIDL::ExceptionOr<void> {
  1420. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(byte_buffer)));
  1421. return {};
  1422. },
  1423. [&](JS::Handle<FileAPI::Blob> const& blob_handle) -> WebIDL::ExceptionOr<void> {
  1424. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob_handle->bytes())));
  1425. return {};
  1426. },
  1427. [](Empty) -> WebIDL::ExceptionOr<void> {
  1428. return {};
  1429. }));
  1430. }
  1431. auto pending_response = PendingResponse::create(vm, request);
  1432. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Invoking ResourceLoader");
  1433. if constexpr (WEB_FETCH_DEBUG)
  1434. log_load_request(load_request);
  1435. ResourceLoader::the().load(
  1436. load_request,
  1437. [&realm, &vm, request, pending_response](auto data, auto& response_headers, auto status_code) {
  1438. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' complete", request->url());
  1439. if constexpr (WEB_FETCH_DEBUG)
  1440. log_response(status_code, response_headers, data);
  1441. auto [body, _] = TRY_OR_IGNORE(extract_body(realm, data));
  1442. auto response = Infrastructure::Response::create(vm);
  1443. response->set_status(status_code.value_or(200));
  1444. response->set_body(move(body));
  1445. for (auto const& [name, value] : response_headers) {
  1446. auto header = TRY_OR_IGNORE(Infrastructure::Header::from_string_pair(name, value));
  1447. TRY_OR_IGNORE(response->header_list()->append(header));
  1448. }
  1449. // FIXME: Set response status message
  1450. pending_response->resolve(response);
  1451. },
  1452. [&vm, request, pending_response](auto& error, auto status_code) {
  1453. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' failed: {} (status {})", request->url(), error, status_code.value_or(0));
  1454. auto response = Infrastructure::Response::create(vm);
  1455. // FIXME: This is ugly, ResourceLoader should tell us.
  1456. if (status_code.value_or(0) == 0) {
  1457. response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("HTTP request failed"_string));
  1458. } else {
  1459. response->set_type(Infrastructure::Response::Type::Error);
  1460. response->set_status(status_code.value_or(400));
  1461. // FIXME: Set response status message and body
  1462. }
  1463. pending_response->resolve(response);
  1464. });
  1465. return pending_response;
  1466. }
  1467. // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0
  1468. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> cors_preflight_fetch(JS::Realm& realm, Infrastructure::Request& request)
  1469. {
  1470. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' with request @ {}", &request);
  1471. auto& vm = realm.vm();
  1472. // 1. Let preflight be a new request whose method is `OPTIONS`, URL list is a clone of request’s URL list, initiator is
  1473. // request’s initiator, destination is request’s destination, origin is request’s origin, referrer is request’s referrer,
  1474. // referrer policy is request’s referrer policy, mode is "cors", and response tainting is "cors".
  1475. auto preflight = Fetch::Infrastructure::Request::create(vm);
  1476. preflight->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("OPTIONS"sv.bytes())));
  1477. preflight->set_url_list(request.url_list());
  1478. preflight->set_initiator(request.initiator());
  1479. preflight->set_destination(request.destination());
  1480. preflight->set_origin(request.origin());
  1481. preflight->set_referrer(request.referrer());
  1482. preflight->set_referrer_policy(request.referrer_policy());
  1483. preflight->set_mode(Infrastructure::Request::Mode::CORS);
  1484. preflight->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  1485. // 2. Append (`Accept`, `*/*`) to preflight’s header list.
  1486. auto temp_header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Accept"sv, "*/*"sv));
  1487. TRY_OR_THROW_OOM(vm, preflight->header_list()->append(move(temp_header)));
  1488. // 3. Append (`Access-Control-Request-Method`, request’s method) to preflight’s header list.
  1489. temp_header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Access-Control-Request-Method"sv, request.method()));
  1490. TRY_OR_THROW_OOM(vm, preflight->header_list()->append(move(temp_header)));
  1491. // 4. Let headers be the CORS-unsafe request-header names with request’s header list.
  1492. auto headers = TRY_OR_THROW_OOM(vm, Infrastructure::get_cors_unsafe_header_names(request.header_list()));
  1493. // 5. If headers is not empty, then:
  1494. if (!headers.is_empty()) {
  1495. // 1. Let value be the items in headers separated from each other by `,`.
  1496. // NOTE: This intentionally does not use combine, as 0x20 following 0x2C is not the way this was implemented,
  1497. // for better or worse.
  1498. ByteBuffer value;
  1499. bool first = true;
  1500. for (auto const& header : headers) {
  1501. if (!first)
  1502. TRY_OR_THROW_OOM(vm, value.try_append(','));
  1503. TRY_OR_THROW_OOM(vm, value.try_append(header));
  1504. first = false;
  1505. }
  1506. // 2. Append (`Access-Control-Request-Headers`, value) to preflight’s header list.
  1507. temp_header = Infrastructure::Header {
  1508. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("Access-Control-Request-Headers"sv.bytes())),
  1509. .value = move(value),
  1510. };
  1511. TRY_OR_THROW_OOM(vm, preflight->header_list()->append(move(temp_header)));
  1512. }
  1513. // 6. Let response be the result of running HTTP-network-or-cache fetch given a new fetch params whose request is preflight.
  1514. // FIXME: The spec doesn't say anything about timing_info here, but FetchParams requires a non-null FetchTimingInfo object.
  1515. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  1516. auto fetch_params = Infrastructure::FetchParams::create(vm, preflight, timing_info);
  1517. auto returned_pending_response = PendingResponse::create(vm, request);
  1518. auto preflight_response = TRY(http_network_or_cache_fetch(realm, fetch_params));
  1519. preflight_response->when_loaded([&vm, &request, returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1520. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");
  1521. // 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
  1522. // NOTE: The CORS check is done on request rather than preflight to ensure the correct credentials mode is used.
  1523. if (TRY_OR_IGNORE(cors_check(request, response)) && Infrastructure::is_ok_status(response->status())) {
  1524. // 1. Let methods be the result of extracting header list values given `Access-Control-Allow-Methods` and response’s header list.
  1525. auto methods_or_failure = TRY_OR_IGNORE(Infrastructure::extract_header_list_values("Access-Control-Allow-Methods"sv.bytes(), response->header_list()));
  1526. // 2. Let headerNames be the result of extracting header list values given `Access-Control-Allow-Headers` and
  1527. // response’s header list.
  1528. auto header_names_or_failure = TRY_OR_IGNORE(Infrastructure::extract_header_list_values("Access-Control-Allow-Headers"sv.bytes(), response->header_list()));
  1529. // 3. If either methods or headerNames is failure, return a network error.
  1530. if (methods_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  1531. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("The Access-Control-Allow-Methods in the CORS-preflight response is syntactically invalid"_string)));
  1532. return;
  1533. }
  1534. if (header_names_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  1535. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("The Access-Control-Allow-Headers in the CORS-preflight response is syntactically invalid"_string)));
  1536. return;
  1537. }
  1538. // NOTE: We treat "methods_or_failure" being `Empty` as empty Vector here.
  1539. auto methods = methods_or_failure.has<Vector<ByteBuffer>>() ? methods_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  1540. // NOTE: We treat "header_names_or_failure" being `Empty` as empty Vector here.
  1541. auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  1542. // FIXME: Remove this once extract_header_list_values validates the header and returns multiple values.
  1543. if (!methods.is_empty()) {
  1544. VERIFY(methods.size() == 1);
  1545. auto split_methods = StringView { methods.first() }.split_view(',');
  1546. Vector<ByteBuffer> trimmed_methods;
  1547. for (auto const& method : split_methods) {
  1548. auto trimmed_method = method.trim(" \t"sv);
  1549. auto trimmed_method_as_byte_buffer = TRY_OR_IGNORE(ByteBuffer::copy(trimmed_method.bytes()));
  1550. TRY_OR_IGNORE(trimmed_methods.try_append(move(trimmed_method_as_byte_buffer)));
  1551. }
  1552. methods = move(trimmed_methods);
  1553. }
  1554. // FIXME: Remove this once extract_header_list_values validates the header and returns multiple values.
  1555. if (!header_names.is_empty()) {
  1556. VERIFY(header_names.size() == 1);
  1557. auto split_header_names = StringView { header_names.first() }.split_view(',');
  1558. Vector<ByteBuffer> trimmed_header_names;
  1559. for (auto const& header_name : split_header_names) {
  1560. auto trimmed_header_name = header_name.trim(" \t"sv);
  1561. auto trimmed_header_name_as_byte_buffer = TRY_OR_IGNORE(ByteBuffer::copy(trimmed_header_name.bytes()));
  1562. TRY_OR_IGNORE(trimmed_header_names.try_append(move(trimmed_header_name_as_byte_buffer)));
  1563. }
  1564. header_names = move(trimmed_header_names);
  1565. }
  1566. // 4. If methods is null and request’s use-CORS-preflight flag is set, then set methods to a new list containing request’s method.
  1567. // NOTE: This ensures that a CORS-preflight fetch that happened due to request’s use-CORS-preflight flag being set is cached.
  1568. if (methods.is_empty() && request.use_cors_preflight())
  1569. methods = Vector { TRY_OR_IGNORE(ByteBuffer::copy(request.method())) };
  1570. // 5. If request’s method is not in methods, request’s method is not a CORS-safelisted method, and request’s credentials mode
  1571. // is "include" or methods does not contain `*`, then return a network error.
  1572. if (!methods.contains_slow(request.method()) && !Infrastructure::is_cors_safelisted_method(request.method())) {
  1573. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  1574. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("Non-CORS-safelisted method '{}' not found in the CORS-preflight response's Access-Control-Allow-Methods header (the header may be missing). '*' is not allowed as the main request includes credentials."sv, StringView { request.method() }))));
  1575. return;
  1576. }
  1577. if (!methods.contains_slow("*"sv.bytes())) {
  1578. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("Non-CORS-safelisted method '{}' not found in the CORS-preflight response's Access-Control-Allow-Methods header and there was no '*' entry. The header may be missing."sv, StringView { request.method() }))));
  1579. return;
  1580. }
  1581. }
  1582. // 6. If one of request’s header list’s names is a CORS non-wildcard request-header name and is not a byte-case-insensitive match
  1583. // for an item in headerNames, then return a network error.
  1584. for (auto const& header : *request.header_list()) {
  1585. if (Infrastructure::is_cors_non_wildcard_request_header_name(header.name)) {
  1586. bool is_in_header_names = false;
  1587. for (auto const& allowed_header_name : header_names) {
  1588. if (StringView { allowed_header_name }.equals_ignoring_ascii_case(header.name)) {
  1589. is_in_header_names = true;
  1590. break;
  1591. }
  1592. }
  1593. if (!is_in_header_names) {
  1594. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("Main request contains the header '{}' that is not specified in the CORS-preflight response's Access-Control-Allow-Headers header (the header may be missing). '*' does not capture this header."sv, StringView { header.name }))));
  1595. return;
  1596. }
  1597. }
  1598. }
  1599. // 7. For each unsafeName of the CORS-unsafe request-header names with request’s header list, if unsafeName is not a
  1600. // byte-case-insensitive match for an item in headerNames and request’s credentials mode is "include" or headerNames
  1601. // does not contain `*`, return a network error.
  1602. auto unsafe_names = TRY_OR_IGNORE(Infrastructure::get_cors_unsafe_header_names(request.header_list()));
  1603. for (auto const& unsafe_name : unsafe_names) {
  1604. bool is_in_header_names = false;
  1605. for (auto const& header_name : header_names) {
  1606. if (StringView { unsafe_name }.equals_ignoring_ascii_case(header_name)) {
  1607. is_in_header_names = true;
  1608. break;
  1609. }
  1610. }
  1611. if (!is_in_header_names) {
  1612. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  1613. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("CORS-unsafe request-header '{}' not found in the CORS-preflight response's Access-Control-Allow-Headers header (the header may be missing). '*' is not allowed as the main request includes credentials."sv, StringView { unsafe_name }))));
  1614. return;
  1615. }
  1616. if (!header_names.contains_slow("*"sv.bytes())) {
  1617. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("CORS-unsafe request-header '{}' not found in the CORS-preflight response's Access-Control-Allow-Headers header and there was no '*' entry. The header may be missing."sv, StringView { unsafe_name }))));
  1618. return;
  1619. }
  1620. }
  1621. }
  1622. // FIXME: 8. Let max-age be the result of extracting header list values given `Access-Control-Max-Age` and response’s header list.
  1623. // FIXME: 9. If max-age is failure or null, then set max-age to 5.
  1624. // FIXME: 10. If max-age is greater than an imposed limit on max-age, then set max-age to the imposed limit.
  1625. // 11. If the user agent does not provide for a cache, then return response.
  1626. // NOTE: Since we don't currently have a cache, this is always true.
  1627. returned_pending_response->resolve(response);
  1628. return;
  1629. // FIXME: 12. For each method in methods for which there is a method cache entry match using request, set matching entry’s max-age
  1630. // to max-age.
  1631. // FIXME: 13. For each method in methods for which there is no method cache entry match using request, create a new cache entry
  1632. // with request, max-age, method, and null.
  1633. // FIXME: 14. For each headerName in headerNames for which there is a header-name cache entry match using request, set matching
  1634. // entry’s max-age to max-age.
  1635. // FIXME: 15. For each headerName in headerNames for which there is no header-name cache entry match using request, create a
  1636. // new cache entry with request, max-age, null, and headerName.
  1637. // FIXME: 16. Return response.
  1638. }
  1639. // 8. Otherwise, return a network error.
  1640. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("CORS-preflight check failed"_string)));
  1641. });
  1642. return returned_pending_response;
  1643. }
  1644. }