Fetching.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  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. Infrastructure::Body::ProcessBodyErrorCallback process_body_error = [&realm, &vm, &fetch_params](auto) {
  423. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error(vm, "Response body could not be processed"sv)));
  424. };
  425. // 2. If response’s body is null, then run processBodyError and abort these steps.
  426. if (!response->body().has_value()) {
  427. process_body_error({});
  428. return;
  429. }
  430. // 3. Let processBody given bytes be these steps:
  431. Infrastructure::Body::ProcessBodyCallback process_body = [&realm, request, response, &fetch_params, process_body_error = move(process_body_error)](ByteBuffer bytes) {
  432. // 1. If bytes do not match request’s integrity metadata, then run processBodyError and abort these steps.
  433. if (!TRY_OR_IGNORE(SRI::do_bytes_match_metadata_list(bytes, request->integrity_metadata()))) {
  434. process_body_error({});
  435. return;
  436. }
  437. // 2. Set response’s body to bytes as a body.
  438. response->set_body(TRY_OR_IGNORE(Infrastructure::byte_sequence_as_body(realm, bytes)));
  439. // 3. Run fetch response handover given fetchParams and response.
  440. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, *response));
  441. };
  442. // 4. Fully read response’s body given processBody and processBodyError.
  443. TRY_OR_IGNORE(response->body()->fully_read(realm, move(process_body), move(process_body_error), fetch_params.task_destination()));
  444. }
  445. // 23. Otherwise, run fetch response handover given fetchParams and response.
  446. else {
  447. TRY_OR_IGNORE(fetch_response_handover(realm, fetch_params, *response));
  448. }
  449. });
  450. });
  451. return Optional<JS::NonnullGCPtr<PendingResponse>> {};
  452. }
  453. // https://fetch.spec.whatwg.org/#fetch-finale
  454. WebIDL::ExceptionOr<void> fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  455. {
  456. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);
  457. auto& vm = realm.vm();
  458. // 1. Let timingInfo be fetchParams’s timing info.
  459. auto timing_info = fetch_params.timing_info();
  460. // 2. If response is not a network error and fetchParams’s request’s client is a secure context, then set
  461. // timingInfo’s server-timing headers to the result of getting, decoding, and splitting `Server-Timing` from
  462. // response’s header list.
  463. // The user agent may decide to expose `Server-Timing` headers to non-secure contexts requests as well.
  464. auto client = fetch_params.request()->client();
  465. if (!response.is_network_error() && client != nullptr && HTML::is_secure_context(*client)) {
  466. auto server_timing_headers = TRY_OR_THROW_OOM(vm, response.header_list()->get_decode_and_split("Server-Timing"sv.bytes()));
  467. if (server_timing_headers.has_value())
  468. timing_info->set_server_timing_headers(server_timing_headers.release_value());
  469. }
  470. // 3. Let processResponseEndOfBody be the following steps:
  471. auto process_response_end_of_body = [&vm, &response, &fetch_params, timing_info] {
  472. // 1. Let unsafeEndTime be the unsafe shared current time.
  473. auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
  474. // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s full timing
  475. // info to fetchParams’s timing info.
  476. if (fetch_params.request()->destination() == Infrastructure::Request::Destination::Document)
  477. fetch_params.controller()->set_full_timing_info(fetch_params.timing_info());
  478. // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
  479. fetch_params.controller()->set_report_timing_steps([&vm, &response, &fetch_params, timing_info, unsafe_end_time](JS::Object const& global) mutable {
  480. // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
  481. if (!Infrastructure::is_http_or_https_scheme(fetch_params.request()->url().scheme()))
  482. return;
  483. // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
  484. timing_info->set_end_time(HighResolutionTime::relative_high_resolution_time(unsafe_end_time, global));
  485. // 3. Let cacheState be response’s cache state.
  486. auto cache_state = response.cache_state();
  487. // 4. Let bodyInfo be response’s body info.
  488. auto body_info = response.body_info();
  489. // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
  490. // opaque timing info for timingInfo, set bodyInfo to a new response body info, and set cacheState to
  491. // the empty string.
  492. // NOTE: This covers the case of response being a network error.
  493. if (!response.timing_allow_passed()) {
  494. timing_info = Infrastructure::create_opaque_timing_info(vm, timing_info);
  495. body_info = Infrastructure::Response::BodyInfo {};
  496. cache_state = {};
  497. }
  498. // 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.
  499. auto response_status = fetch_params.request()->mode() == Infrastructure::Request::Mode::Navigate && response.has_cross_origin_redirects()
  500. ? 0
  501. : response.status();
  502. // FIXME: 7. If fetchParams’s request’s initiator type is not null, then mark resource timing given timingInfo,
  503. // request’s URL, request’s initiator type, global, cacheState, bodyInfo, and responseStatus.
  504. (void)timing_info;
  505. (void)global;
  506. (void)cache_state;
  507. (void)body_info;
  508. (void)response_status;
  509. });
  510. // 4. Let processResponseEndOfBodyTask be the following steps:
  511. auto process_response_end_of_body_task = [&fetch_params, &response] {
  512. // 1. Set fetchParams’s request’s done flag.
  513. fetch_params.request()->set_done(true);
  514. // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response
  515. // end-of-body given response.
  516. if (fetch_params.algorithms()->process_response_end_of_body().has_value())
  517. (*fetch_params.algorithms()->process_response_end_of_body())(response);
  518. // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s global
  519. // object is fetchParams’s task destination, then run fetchParams’s controller’s report timing steps
  520. // given fetchParams’s request’s client’s global object.
  521. auto client = fetch_params.request()->client();
  522. auto const* task_destination_global_object = fetch_params.task_destination().get_pointer<JS::NonnullGCPtr<JS::Object>>();
  523. if (client != nullptr && task_destination_global_object != nullptr) {
  524. if (fetch_params.request()->initiator_type().has_value() && &client->global_object() == task_destination_global_object->ptr())
  525. fetch_params.controller()->report_timing(client->global_object());
  526. }
  527. };
  528. // FIXME: Handle 'parallel queue' task destination
  529. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  530. // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination.
  531. Infrastructure::queue_fetch_task(task_destination, move(process_response_end_of_body_task));
  532. };
  533. // FIXME: Handle 'parallel queue' task destination
  534. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  535. // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response
  536. // given response, with fetchParams’s task destination.
  537. if (fetch_params.algorithms()->process_response().has_value()) {
  538. Infrastructure::queue_fetch_task(task_destination, [&fetch_params, &response]() {
  539. (*fetch_params.algorithms()->process_response())(response);
  540. });
  541. }
  542. // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
  543. auto internal_response = response.is_network_error() ? JS::NonnullGCPtr { response } : response.unsafe_response();
  544. // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
  545. if (!internal_response->body().has_value()) {
  546. process_response_end_of_body();
  547. }
  548. // 7. Otherwise:
  549. else {
  550. // FIXME: 1. Let transformStream be a new TransformStream.
  551. // FIXME: 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
  552. // FIXME: 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set
  553. // to processResponseEndOfBody.
  554. // FIXME: 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
  555. }
  556. // 8. If fetchParams’s process response consume body is non-null, then:
  557. if (fetch_params.algorithms()->process_response_consume_body().has_value()) {
  558. // 1. Let processBody given nullOrBytes be this step: run fetchParams’s process response consume body given
  559. // response and nullOrBytes.
  560. auto process_body = [&fetch_params, &response](Variant<ByteBuffer, Empty> const& null_or_bytes) {
  561. (*fetch_params.algorithms()->process_response_consume_body())(response, null_or_bytes);
  562. };
  563. // 2. Let processBodyError be this step: run fetchParams’s process response consume body given response and
  564. // failure.
  565. auto process_body_error = [&fetch_params, &response](auto) {
  566. (*fetch_params.algorithms()->process_response_consume_body())(response, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
  567. };
  568. // 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with
  569. // fetchParams’s task destination.
  570. if (!internal_response->body().has_value()) {
  571. Infrastructure::queue_fetch_task(task_destination, [process_body = move(process_body)]() {
  572. process_body({});
  573. });
  574. }
  575. // 4. Otherwise, fully read internalResponse body given processBody, processBodyError, and fetchParams’s task
  576. // destination.
  577. else {
  578. TRY(internal_response->body()->fully_read(realm, move(process_body), move(process_body_error), fetch_params.task_destination()));
  579. }
  580. }
  581. return {};
  582. }
  583. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  584. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params)
  585. {
  586. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'scheme fetch' with: fetch_params @ {}", &fetch_params);
  587. auto& vm = realm.vm();
  588. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  589. if (fetch_params.is_canceled())
  590. return PendingResponse::create(vm, fetch_params.request(), Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  591. // 2. Let request be fetchParams’s request.
  592. auto request = fetch_params.request();
  593. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  594. // -> "about"
  595. if (request->current_url().scheme() == "about"sv) {
  596. // If request’s current URL’s path is the string "blank", then return a new response whose status message is
  597. // `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », and body is the empty byte sequence as
  598. // a body.
  599. // NOTE: URLs such as "about:config" are handled during navigation and result in a network error in the context
  600. // of fetching.
  601. if (request->current_url().serialize_path() == "blank"sv) {
  602. auto response = Infrastructure::Response::create(vm);
  603. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  604. auto header = MUST(Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=utf-8"sv));
  605. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  606. response->set_body(MUST(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes())));
  607. return PendingResponse::create(vm, request, response);
  608. }
  609. }
  610. // -> "blob"
  611. else if (request->current_url().scheme() == "blob"sv) {
  612. // FIXME: Support 'blob://' URLs
  613. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has 'blob:' URL which is currently unsupported"sv));
  614. }
  615. // -> "data"
  616. else if (request->current_url().scheme() == "data"sv) {
  617. // 1. Let dataURLStruct be the result of running the data: URL processor on request’s current URL.
  618. auto const& url = request->current_url();
  619. auto data_or_error = url.data_payload_is_base64()
  620. ? decode_base64(url.data_payload())
  621. : TRY_OR_THROW_OOM(vm, ByteBuffer::copy(url.data_payload().bytes()));
  622. // 2. If dataURLStruct is failure, then return a network error.
  623. if (data_or_error.is_error())
  624. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has invalid base64 'data:' URL"sv));
  625. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  626. auto const& mime_type = url.data_mime_type();
  627. // 4. Return a new response whose status message is `OK`, header list is « (`Content-Type`, mimeType) », and
  628. // body is dataURLStruct’s body as a body.
  629. auto response = Infrastructure::Response::create(vm);
  630. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  631. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Content-Type"sv, mime_type));
  632. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  633. response->set_body(TRY(Infrastructure::byte_sequence_as_body(realm, data_or_error.value().span())));
  634. return PendingResponse::create(vm, request, response);
  635. }
  636. // -> "file"
  637. else if (request->current_url().scheme() == "file"sv) {
  638. // For now, unfortunate as it is, file: URLs are left as an exercise for the reader.
  639. // When in doubt, return a network error.
  640. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  641. }
  642. // -> HTTP(S) scheme
  643. else if (Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  644. // Return the result of running HTTP fetch given fetchParams.
  645. return http_fetch(realm, fetch_params);
  646. }
  647. // 4. Return a network error.
  648. auto message = request->current_url().scheme() == "about"sv
  649. ? TRY_OR_THROW_OOM(vm, "Request has invalid 'about:' URL, only 'about:blank' can be fetched"_string)
  650. : TRY_OR_THROW_OOM(vm, "Request URL has invalid scheme, must be one of 'about', 'blob', 'data', 'file', 'http', or 'https'"_string);
  651. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, move(message)));
  652. }
  653. // https://fetch.spec.whatwg.org/#concept-http-fetch
  654. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, MakeCORSPreflight make_cors_preflight)
  655. {
  656. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' with: fetch_params @ {}, make_cors_preflight = {}",
  657. &fetch_params, make_cors_preflight == MakeCORSPreflight::Yes ? "Yes"sv : "No"sv);
  658. auto& vm = realm.vm();
  659. // 1. Let request be fetchParams’s request.
  660. auto request = fetch_params.request();
  661. // 2. Let response be null.
  662. JS::GCPtr<Infrastructure::Response> response;
  663. // 3. Let actualResponse be null.
  664. JS::GCPtr<Infrastructure::Response> actual_response;
  665. // 4. If request’s service-workers mode is "all", then:
  666. if (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {
  667. // 1. Let requestForServiceWorker be a clone of request.
  668. auto request_for_service_worker = TRY(request->clone(realm));
  669. // 2. If requestForServiceWorker’s body is non-null, then:
  670. if (!request_for_service_worker->body().has<Empty>()) {
  671. // FIXME: 1. Let transformStream be a new TransformStream.
  672. // FIXME: 2. Let transformAlgorithm given chunk be these steps:
  673. // FIXME: 3. Set up transformStream with transformAlgorithm set to transformAlgorithm.
  674. // FIXME: 4. Set requestForServiceWorker’s body’s stream to the result of requestForServiceWorker’s body’s stream
  675. // piped through transformStream.
  676. }
  677. // 3. Let serviceWorkerStartTime be the coarsened shared current time given fetchParams’s cross-origin isolated
  678. // capability.
  679. auto service_worker_start_time = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  680. // FIXME: 4. Set response to the result of invoking handle fetch for requestForServiceWorker, with fetchParams’s
  681. // controller and fetchParams’s cross-origin isolated capability.
  682. // 5. If response is not null, then:
  683. if (response) {
  684. // 1. Set fetchParams’s timing info’s final service worker start time to serviceWorkerStartTime.
  685. fetch_params.timing_info()->set_final_service_worker_start_time(service_worker_start_time);
  686. // 2. If request’s body is non-null, then cancel request’s body with undefined.
  687. if (!request->body().has<Empty>()) {
  688. // FIXME: Implement cancelling streams
  689. }
  690. // 3. Set actualResponse to response, if response is not a filtered response, and to response’s internal
  691. // response otherwise.
  692. actual_response = !is<Infrastructure::FilteredResponse>(*response)
  693. ? JS::NonnullGCPtr { *response }
  694. : static_cast<Infrastructure::FilteredResponse const&>(*response).internal_response();
  695. // 4. If one of the following is true
  696. if (
  697. // - response’s type is "error"
  698. response->type() == Infrastructure::Response::Type::Error
  699. // - request’s mode is "same-origin" and response’s type is "cors"
  700. || (request->mode() == Infrastructure::Request::Mode::SameOrigin && response->type() == Infrastructure::Response::Type::CORS)
  701. // - request’s mode is not "no-cors" and response’s type is "opaque"
  702. || (request->mode() != Infrastructure::Request::Mode::NoCORS && response->type() == Infrastructure::Response::Type::Opaque)
  703. // - request’s redirect mode is not "manual" and response’s type is "opaqueredirect"
  704. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Manual && response->type() == Infrastructure::Response::Type::OpaqueRedirect)
  705. // - request’s redirect mode is not "follow" and response’s URL list has more than one item.
  706. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow && response->url_list().size() > 1)) {
  707. // then return a network error.
  708. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Invalid request/response state combination"sv));
  709. }
  710. }
  711. }
  712. JS::GCPtr<PendingResponse> pending_actual_response;
  713. auto returned_pending_response = PendingResponse::create(vm, request);
  714. // 5. If response is null, then:
  715. if (!response) {
  716. // 1. If makeCORSPreflight is true and one of these conditions is true:
  717. // NOTE: This step checks the CORS-preflight cache and if there is no suitable entry it performs a
  718. // CORS-preflight fetch which, if successful, populates the cache. The purpose of the CORS-preflight
  719. // fetch is to ensure the fetched resource is familiar with the CORS protocol. The cache is there to
  720. // minimize the number of CORS-preflight fetches.
  721. JS::GCPtr<PendingResponse> pending_preflight_response;
  722. if (make_cors_preflight == MakeCORSPreflight::Yes && (
  723. // - There is no method cache entry match for request’s method using request, and either request’s
  724. // method is not a CORS-safelisted method or request’s use-CORS-preflight flag is set.
  725. // FIXME: We currently have no cache, so there will always be no method cache entry.
  726. (!Infrastructure::is_cors_safelisted_method(request->method()) || request->use_cors_preflight())
  727. // - There is at least one item in the CORS-unsafe request-header names with request’s header list for
  728. // which there is no header-name cache entry match using request.
  729. // FIXME: We currently have no cache, so there will always be no header-name cache entry.
  730. || !TRY_OR_THROW_OOM(vm, Infrastructure::get_cors_unsafe_header_names(request->header_list())).is_empty())) {
  731. // 1. Let preflightResponse be the result of running CORS-preflight fetch given request.
  732. pending_preflight_response = TRY(cors_preflight_fetch(realm, request));
  733. // NOTE: Step 2 is performed in pending_preflight_response's load callback below.
  734. }
  735. 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>> {
  736. // 2. If request’s redirect mode is "follow", then set request’s service-workers mode to "none".
  737. // NOTE: Redirects coming from the network (as opposed to from a service worker) are not to be exposed to a
  738. // service worker.
  739. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Follow)
  740. request->set_service_workers_mode(Infrastructure::Request::ServiceWorkersMode::None);
  741. // 3. Set response and actualResponse to the result of running HTTP-network-or-cache fetch given fetchParams.
  742. return http_network_or_cache_fetch(*realm, *fetch_params);
  743. };
  744. if (pending_preflight_response) {
  745. pending_actual_response = PendingResponse::create(vm, request);
  746. pending_preflight_response->when_loaded([returned_pending_response, pending_actual_response, fetch_main_content = move(fetch_main_content)](JS::NonnullGCPtr<Infrastructure::Response> preflight_response) {
  747. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_preflight_response load callback");
  748. // 2. If preflightResponse is a network error, then return preflightResponse.
  749. if (preflight_response->is_network_error()) {
  750. returned_pending_response->resolve(preflight_response);
  751. return;
  752. }
  753. auto pending_main_content_response = TRY_OR_IGNORE(fetch_main_content());
  754. pending_main_content_response->when_loaded([pending_actual_response](JS::NonnullGCPtr<Infrastructure::Response> main_content_response) {
  755. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_main_content_response load callback");
  756. pending_actual_response->resolve(main_content_response);
  757. });
  758. });
  759. } else {
  760. pending_actual_response = TRY(fetch_main_content());
  761. }
  762. } else {
  763. pending_actual_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  764. }
  765. 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 {
  766. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_actual_response load callback");
  767. if (response_was_null) {
  768. response = actual_response = resolved_actual_response;
  769. // 4. If request’s response tainting is "cors" and a CORS check for request and response returns failure,
  770. // then return a network error.
  771. // NOTE: As the CORS check is not to be applied to responses whose status is 304 or 407, or responses from
  772. // a service worker for that matter, it is applied here.
  773. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS
  774. && !TRY_OR_IGNORE(cors_check(request, *response))) {
  775. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request with 'cors' response tainting failed CORS check"_string)));
  776. return;
  777. }
  778. // 5. If the TAO check for request and response returns failure, then set request’s timing allow failed flag.
  779. if (!TRY_OR_IGNORE(tao_check(request, *response)))
  780. request->set_timing_allow_failed(true);
  781. }
  782. // 6. If either request’s response tainting or response’s type is "opaque", and the cross-origin resource
  783. // policy check with request’s origin, request’s client, request’s destination, and actualResponse returns
  784. // blocked, then return a network error.
  785. // NOTE: The cross-origin resource policy check runs for responses coming from the network and responses coming
  786. // from the service worker. This is different from the CORS check, as request’s client and the service
  787. // worker can have different embedder policies.
  788. if ((request->response_tainting() == Infrastructure::Request::ResponseTainting::Opaque || response->type() == Infrastructure::Response::Type::Opaque)
  789. && false // FIXME: "and the cross-origin resource policy check with request’s origin, request’s client, request’s destination, and actualResponse returns blocked"
  790. ) {
  791. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Response was blocked by cross-origin resource policy check"_string)));
  792. return;
  793. }
  794. Optional<JS::NonnullGCPtr<PendingResponse>> inner_pending_response;
  795. // 7. If actualResponse’s status is a redirect status, then:
  796. if (Infrastructure::is_redirect_status(actual_response->status())) {
  797. // FIXME: 1. If actualResponse’s status is not 303, request’s body is not null, and the connection uses HTTP/2,
  798. // then user agents may, and are even encouraged to, transmit an RST_STREAM frame.
  799. // NOTE: 303 is excluded as certain communities ascribe special status to it.
  800. // 2. Switch on request’s redirect mode:
  801. switch (request->redirect_mode()) {
  802. // -> "error"
  803. case Infrastructure::Request::RedirectMode::Error:
  804. // Set response to a network error.
  805. response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request with 'error' redirect mode received redirect response"_string));
  806. break;
  807. // -> "manual"
  808. case Infrastructure::Request::RedirectMode::Manual:
  809. // 1. If request’s mode is "navigate", then set fetchParams’s controller’s next manual redirect steps
  810. // to run HTTP-redirect fetch given fetchParams and response.
  811. if (request->mode() == Infrastructure::Request::Mode::Navigate) {
  812. fetch_params.controller()->set_next_manual_redirect_steps([&realm, &fetch_params, response] {
  813. (void)http_redirect_fetch(realm, fetch_params, *response);
  814. });
  815. }
  816. // 2. Otherwise, set response to an opaque-redirect filtered response whose internal response is
  817. // actualResponse.
  818. else {
  819. response = Infrastructure::OpaqueRedirectFilteredResponse::create(vm, *actual_response);
  820. }
  821. break;
  822. // -> "follow"
  823. case Infrastructure::Request::RedirectMode::Follow:
  824. // Set response to the result of running HTTP-redirect fetch given fetchParams and response.
  825. inner_pending_response = TRY_OR_IGNORE(http_redirect_fetch(realm, fetch_params, *response));
  826. break;
  827. default:
  828. VERIFY_NOT_REACHED();
  829. }
  830. }
  831. if (inner_pending_response.has_value()) {
  832. inner_pending_response.value()->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  833. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' inner_pending_response load callback");
  834. returned_pending_response->resolve(response);
  835. });
  836. } else {
  837. returned_pending_response->resolve(*response);
  838. }
  839. });
  840. // 8. Return response.
  841. // NOTE: Typically actualResponse’s body’s stream is still being enqueued to after returning.
  842. return returned_pending_response;
  843. }
  844. // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch
  845. WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> http_redirect_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  846. {
  847. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-redirect fetch' with: fetch_params @ {}, response = {}", &fetch_params, &response);
  848. auto& vm = realm.vm();
  849. // 1. Let request be fetchParams’s request.
  850. auto request = fetch_params.request();
  851. // 2. Let actualResponse be response, if response is not a filtered response, and response’s internal response
  852. // otherwise.
  853. auto actual_response = !is<Infrastructure::FilteredResponse>(response)
  854. ? JS::NonnullGCPtr { response }
  855. : static_cast<Infrastructure::FilteredResponse const&>(response).internal_response();
  856. // 3. Let locationURL be actualResponse’s location URL given request’s current URL’s fragment.
  857. auto const& fragment = request->current_url().fragment();
  858. auto fragment_string = fragment.is_null() ? Optional<String> {} : TRY_OR_THROW_OOM(vm, String::from_deprecated_string(fragment));
  859. auto location_url_or_error = actual_response->location_url(fragment_string);
  860. // 4. If locationURL is null, then return response.
  861. if (!location_url_or_error.is_error() && !location_url_or_error.value().has_value())
  862. return PendingResponse::create(vm, request, response);
  863. // 5. If locationURL is failure, then return a network error.
  864. if (location_url_or_error.is_error())
  865. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL is invalid"sv));
  866. auto location_url = location_url_or_error.release_value().release_value();
  867. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network error.
  868. if (!Infrastructure::is_http_or_https_scheme(location_url.scheme()))
  869. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL must have HTTP or HTTPS scheme"sv));
  870. // 7. If request’s redirect count is 20, then return a network error.
  871. if (request->redirect_count() == 20)
  872. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has reached maximum redirect count of 20"sv));
  873. // 8. Increase request’s redirect count by 1.
  874. request->set_redirect_count(request->redirect_count() + 1);
  875. // 8. If request’s mode is "cors", locationURL includes credentials, and request’s origin is not same origin with
  876. // locationURL’s origin, then return a network error.
  877. if (request->mode() == Infrastructure::Request::Mode::CORS
  878. && location_url.includes_credentials()
  879. && request->origin().has<HTML::Origin>()
  880. && !request->origin().get<HTML::Origin>().is_same_origin(URL::url_origin(location_url))) {
  881. 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));
  882. }
  883. // 10. If request’s response tainting is "cors" and locationURL includes credentials, then return a network error.
  884. // NOTE: This catches a cross-origin resource redirecting to a same-origin URL.
  885. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS && location_url.includes_credentials())
  886. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' response tainting must not include credentials in redirect URL"sv));
  887. // 11. If actualResponse’s status is not 303, request’s body is non-null, and request’s body’s source is null, then
  888. // return a network error.
  889. if (actual_response->status() != 303
  890. && !request->body().has<Empty>()
  891. && request->body().get<Infrastructure::Body>().source().has<Empty>()) {
  892. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has body but no body source"sv));
  893. }
  894. // 12. If one of the following is true
  895. if (
  896. // - actualResponse’s status is 301 or 302 and request’s method is `POST`
  897. ((actual_response->status() == 301 || actual_response->status() == 302) && request->method() == "POST"sv.bytes())
  898. // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  899. || (actual_response->status() == 303 && !(request->method() == "GET"sv.bytes() || request->method() == "HEAD"sv.bytes()))
  900. // then:
  901. ) {
  902. // 1. Set request’s method to `GET` and request’s body to null.
  903. request->set_method(MUST(ByteBuffer::copy("GET"sv.bytes())));
  904. request->set_body({});
  905. static constexpr Array request_body_header_names {
  906. "Content-Encoding"sv,
  907. "Content-Language"sv,
  908. "Content-Location"sv,
  909. "Content-Type"sv
  910. };
  911. // 2. For each headerName of request-body-header name, delete headerName from request’s header list.
  912. for (auto header_name : request_body_header_names.span())
  913. request->header_list()->delete_(header_name.bytes());
  914. }
  915. // 13. If request’s current URL’s origin is not same origin with locationURL’s origin, then for each headerName of
  916. // CORS non-wildcard request-header name, delete headerName from request’s header list.
  917. // NOTE: I.e., the moment another origin is seen after the initial request, the `Authorization` header is removed.
  918. if (!URL::url_origin(request->current_url()).is_same_origin(URL::url_origin(location_url))) {
  919. static constexpr Array cors_non_wildcard_request_header_names {
  920. "Authorization"sv
  921. };
  922. for (auto header_name : cors_non_wildcard_request_header_names)
  923. request->header_list()->delete_(header_name.bytes());
  924. }
  925. // 14. If request’s body is non-null, then set request’s body to the body of the result of safely extracting
  926. // request’s body’s source.
  927. // NOTE: request’s body’s source’s nullity has already been checked.
  928. if (!request->body().has<Empty>()) {
  929. auto const& source = request->body().get<Infrastructure::Body>().source();
  930. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  931. auto converted_source = source.has<ByteBuffer>()
  932. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  933. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  934. auto [body, _] = TRY(safely_extract_body(realm, converted_source));
  935. request->set_body(move(body));
  936. }
  937. // 15. Let timingInfo be fetchParams’s timing info.
  938. auto timing_info = fetch_params.timing_info();
  939. // 16. Set timingInfo’s redirect end time and post-redirect start time to the coarsened shared current time given
  940. // fetchParams’s cross-origin isolated capability.
  941. auto now = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  942. timing_info->set_redirect_end_time(now);
  943. timing_info->set_post_redirect_start_time(now);
  944. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s redirect start time to timingInfo’s start
  945. // time.
  946. if (timing_info->redirect_start_time() == 0)
  947. timing_info->set_redirect_start_time(timing_info->start_time());
  948. // 18. Append locationURL to request’s URL list.
  949. request->url_list().append(location_url);
  950. // FIXME: 19. Invoke set request’s referrer policy on redirect on request and actualResponse.
  951. // 20. Let recursive be true.
  952. auto recursive = Recursive::Yes;
  953. // 21. If request’s redirect mode is "manual", then:
  954. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Manual) {
  955. // 1. Assert: request’s mode is "navigate".
  956. VERIFY(request->mode() == Infrastructure::Request::Mode::Navigate);
  957. // 2. Set recursive to false.
  958. recursive = Recursive::No;
  959. }
  960. // 22. Return the result of running main fetch given fetchParams and recursive.
  961. return main_fetch(realm, fetch_params, recursive);
  962. }
  963. // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
  964. 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)
  965. {
  966. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' with: fetch_params @ {}, is_authentication_fetch = {}, is_new_connection_fetch = {}",
  967. &fetch_params, is_authentication_fetch == IsAuthenticationFetch::Yes ? "Yes"sv : "No"sv, is_new_connection_fetch == IsNewConnectionFetch::Yes ? "Yes"sv : "No"sv);
  968. auto& vm = realm.vm();
  969. // 1. Let request be fetchParams’s request.
  970. auto request = fetch_params.request();
  971. // 2. Let httpFetchParams be null.
  972. JS::GCPtr<Infrastructure::FetchParams const> http_fetch_params;
  973. // 3. Let httpRequest be null.
  974. JS::GCPtr<Infrastructure::Request> http_request;
  975. // 4. Let response be null.
  976. JS::GCPtr<Infrastructure::Response> response;
  977. // 5. Let storedResponse be null.
  978. JS::GCPtr<Infrastructure::Response> stored_response;
  979. // 6. Let httpCache be null.
  980. // (Typeless until we actually implement it, needed for checks below)
  981. void* http_cache = nullptr;
  982. // 7. Let the revalidatingFlag be unset.
  983. auto revalidating_flag = RefCountedFlag::create(false);
  984. auto include_credentials = IncludeCredentials::No;
  985. // 8. Run these steps, but abort when fetchParams is canceled:
  986. // NOTE: There's an 'if aborted' check after this anyway, so not doing this is fine and only incurs a small delay.
  987. // For now, support for aborting fetch requests is limited anyway as ResourceLoader doesn't support it.
  988. auto aborted = false;
  989. {
  990. ScopeGuard set_aborted = [&] {
  991. if (fetch_params.is_canceled())
  992. aborted = true;
  993. };
  994. // 1. If request’s window is "no-window" and request’s redirect mode is "error", then set httpFetchParams to
  995. // fetchParams and httpRequest to request.
  996. if (request->window().has<Infrastructure::Request::Window>()
  997. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow
  998. && request->redirect_mode() == Infrastructure::Request::RedirectMode::Error) {
  999. http_fetch_params = fetch_params;
  1000. http_request = request;
  1001. }
  1002. // 2. Otherwise:
  1003. else {
  1004. // 1. Set httpRequest to a clone of request.
  1005. // NOTE: Implementations are encouraged to avoid teeing request’s body’s stream when request’s body’s
  1006. // source is null as only a single body is needed in that case. E.g., when request’s body’s source
  1007. // is null, redirects and authentication will end up failing the fetch.
  1008. http_request = TRY(request->clone(realm));
  1009. // 2. Set httpFetchParams to a copy of fetchParams.
  1010. // 3. Set httpFetchParams’s request to httpRequest.
  1011. auto new_http_fetch_params = Infrastructure::FetchParams::create(vm, *http_request, fetch_params.timing_info());
  1012. new_http_fetch_params->set_algorithms(fetch_params.algorithms());
  1013. new_http_fetch_params->set_task_destination(fetch_params.task_destination());
  1014. new_http_fetch_params->set_cross_origin_isolated_capability(fetch_params.cross_origin_isolated_capability());
  1015. new_http_fetch_params->set_preloaded_response_candidate(fetch_params.preloaded_response_candidate());
  1016. http_fetch_params = new_http_fetch_params;
  1017. }
  1018. // 3. Let includeCredentials be true if one of
  1019. if (
  1020. // - request’s credentials mode is "include"
  1021. request->credentials_mode() == Infrastructure::Request::CredentialsMode::Include
  1022. // - request’s credentials mode is "same-origin" and request’s response tainting is "basic"
  1023. || (request->credentials_mode() == Infrastructure::Request::CredentialsMode::SameOrigin
  1024. && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  1025. // is true; otherwise false.
  1026. ) {
  1027. include_credentials = IncludeCredentials::Yes;
  1028. } else {
  1029. include_credentials = IncludeCredentials::No;
  1030. }
  1031. // 4. If Cross-Origin-Embedder-Policy allows credentials with request returns false, then set
  1032. // includeCredentials to false.
  1033. if (!request->cross_origin_embedder_policy_allows_credentials())
  1034. include_credentials = IncludeCredentials::No;
  1035. // 5. Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null; otherwise null.
  1036. auto content_length = http_request->body().has<Infrastructure::Body>()
  1037. ? http_request->body().get<Infrastructure::Body>().length()
  1038. : Optional<u64> {};
  1039. // 6. Let contentLengthHeaderValue be null.
  1040. auto content_length_header_value = Optional<ByteBuffer> {};
  1041. // 7. If httpRequest’s body is null and httpRequest’s method is `POST` or `PUT`, then set
  1042. // contentLengthHeaderValue to `0`.
  1043. if (http_request->body().has<Empty>() && StringView { http_request->method() }.is_one_of("POST"sv, "PUT"sv))
  1044. content_length_header_value = MUST(ByteBuffer::copy("0"sv.bytes()));
  1045. // 8. If contentLength is non-null, then set contentLengthHeaderValue to contentLength, serialized and
  1046. // isomorphic encoded.
  1047. if (content_length.has_value())
  1048. content_length_header_value = MUST(ByteBuffer::copy(TRY_OR_THROW_OOM(vm, String::number(*content_length)).bytes()));
  1049. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, contentLengthHeaderValue) to
  1050. // httpRequest’s header list.
  1051. if (content_length_header_value.has_value()) {
  1052. auto header = Infrastructure::Header {
  1053. .name = MUST(ByteBuffer::copy("Content-Length"sv.bytes())),
  1054. .value = content_length_header_value.release_value(),
  1055. };
  1056. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1057. }
  1058. // FIXME: 10. If contentLength is non-null and httpRequest’s keepalive is true, then:
  1059. if (content_length.has_value() && http_request->keepalive()) {
  1060. // FIXME: 1-5., requires 'fetch records' and 'fetch group' concepts.
  1061. // NOTE: The above limit ensures that requests that are allowed to outlive the environment settings object
  1062. // and contain a body, have a bounded size and are not allowed to stay alive indefinitely.
  1063. }
  1064. // 11. If httpRequest’s referrer is a URL, then:
  1065. if (http_request->referrer().has<AK::URL>()) {
  1066. // 1. Let referrerValue be httpRequest’s referrer, serialized and isomorphic encoded.
  1067. auto referrer_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(http_request->referrer().get<AK::URL>().serialize().bytes()));
  1068. // 2. Append (`Referer`, referrerValue) to httpRequest’s header list.
  1069. auto header = Infrastructure::Header {
  1070. .name = MUST(ByteBuffer::copy("Referer"sv.bytes())),
  1071. .value = move(referrer_value),
  1072. };
  1073. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1074. }
  1075. // 12. Append a request `Origin` header for httpRequest.
  1076. TRY_OR_THROW_OOM(vm, http_request->add_origin_header());
  1077. // FIXME: 13. Append the Fetch metadata headers for httpRequest.
  1078. // 14. If httpRequest’s header list does not contain `User-Agent`, then user agents should append
  1079. // (`User-Agent`, default `User-Agent` value) to httpRequest’s header list.
  1080. if (!http_request->header_list()->contains("User-Agent"sv.bytes())) {
  1081. auto header = Infrastructure::Header {
  1082. .name = MUST(ByteBuffer::copy("User-Agent"sv.bytes())),
  1083. .value = TRY_OR_THROW_OOM(vm, Infrastructure::default_user_agent_value()),
  1084. };
  1085. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1086. }
  1087. // 15. If httpRequest’s cache mode is "default" and httpRequest’s header list contains `If-Modified-Since`,
  1088. // `If-None-Match`, `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set httpRequest’s cache mode to
  1089. // "no-store".
  1090. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::Default
  1091. && (http_request->header_list()->contains("If-Modified-Since"sv.bytes())
  1092. || http_request->header_list()->contains("If-None-Match"sv.bytes())
  1093. || http_request->header_list()->contains("If-Unmodified-Since"sv.bytes())
  1094. || http_request->header_list()->contains("If-Match"sv.bytes())
  1095. || http_request->header_list()->contains("If-Range"sv.bytes()))) {
  1096. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1097. }
  1098. // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache cache-control header
  1099. // modification flag is unset, and httpRequest’s header list does not contain `Cache-Control`, then append
  1100. // (`Cache-Control`, `max-age=0`) to httpRequest’s header list.
  1101. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoCache
  1102. && !http_request->prevent_no_cache_cache_control_header_modification()
  1103. && !http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1104. auto header = MUST(Infrastructure::Header::from_string_pair("Cache-Control"sv, "max-age=0"sv));
  1105. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1106. }
  1107. // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
  1108. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoStore
  1109. || http_request->cache_mode() == Infrastructure::Request::CacheMode::Reload) {
  1110. // 1. If httpRequest’s header list does not contain `Pragma`, then append (`Pragma`, `no-cache`) to
  1111. // httpRequest’s header list.
  1112. if (!http_request->header_list()->contains("Pragma"sv.bytes())) {
  1113. auto header = MUST(Infrastructure::Header::from_string_pair("Pragma"sv, "no-cache"sv));
  1114. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1115. }
  1116. // 2. If httpRequest’s header list does not contain `Cache-Control`, then append
  1117. // (`Cache-Control`, `no-cache`) to httpRequest’s header list.
  1118. if (!http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1119. auto header = MUST(Infrastructure::Header::from_string_pair("Cache-Control"sv, "no-cache"sv));
  1120. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1121. }
  1122. }
  1123. // 18. If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`) to
  1124. // httpRequest’s header list.
  1125. // NOTE: This avoids a failure when handling content codings with a part of an encoded response.
  1126. // Additionally, many servers mistakenly ignore `Range` headers if a non-identity encoding is accepted.
  1127. if (http_request->header_list()->contains("Range"sv.bytes())) {
  1128. auto header = MUST(Infrastructure::Header::from_string_pair("Accept-Encoding"sv, "identity"sv));
  1129. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1130. }
  1131. // 19. Modify httpRequest’s header list per HTTP. Do not append a given header if httpRequest’s header list
  1132. // contains that header’s name.
  1133. // NOTE: It would be great if we could make this more normative somehow. At this point headers such as
  1134. // `Accept-Encoding`, `Connection`, `DNT`, and `Host`, are to be appended if necessary.
  1135. // `Accept`, `Accept-Charset`, and `Accept-Language` must not be included at this point.
  1136. // NOTE: `Accept` and `Accept-Language` are already included (unless fetch() is used, which does not include
  1137. // the latter by default), and `Accept-Charset` is a waste of bytes. See HTTP header layer division for
  1138. // more details.
  1139. // 20. If includeCredentials is true, then:
  1140. if (include_credentials == IncludeCredentials::Yes) {
  1141. // 1. If the user agent is not configured to block cookies for httpRequest (see section 7 of [COOKIES]),
  1142. // then:
  1143. if (true) {
  1144. // 1. Let cookies be the result of running the "cookie-string" algorithm (see section 5.4 of [COOKIES])
  1145. // with the user agent’s cookie store and httpRequest’s current URL.
  1146. auto cookies = ([&] {
  1147. // FIXME: Getting to the page client reliably is way too complicated, and going via the document won't work in workers.
  1148. auto document = Bindings::host_defined_environment_settings_object(realm).responsible_document();
  1149. if (!document)
  1150. return DeprecatedString::empty();
  1151. auto* page = document->page();
  1152. if (!page)
  1153. return DeprecatedString::empty();
  1154. return page->client().page_did_request_cookie(http_request->current_url(), Cookie::Source::Http);
  1155. })();
  1156. // 2. If cookies is not the empty string, then append (`Cookie`, cookies) to httpRequest’s header list.
  1157. if (!cookies.is_empty()) {
  1158. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Cookie"sv, cookies));
  1159. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1160. }
  1161. }
  1162. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1163. if (!http_request->header_list()->contains("Authorization"sv.bytes())) {
  1164. // 1. Let authorizationValue be null.
  1165. auto authorization_value = Optional<String> {};
  1166. // 2. If there’s an authentication entry for httpRequest and either httpRequest’s use-URL-credentials
  1167. // flag is unset or httpRequest’s current URL does not include credentials, then set
  1168. // authorizationValue to authentication entry.
  1169. if (false // FIXME: "If there’s an authentication entry for httpRequest"
  1170. && (!http_request->use_url_credentials() || !http_request->current_url().includes_credentials())) {
  1171. // FIXME: "set authorizationValue to authentication entry."
  1172. }
  1173. // 3. Otherwise, if httpRequest’s current URL does include credentials and isAuthenticationFetch is
  1174. // true, set authorizationValue to httpRequest’s current URL, converted to an `Authorization` value.
  1175. else if (http_request->current_url().includes_credentials() && is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1176. auto const& url = http_request->current_url();
  1177. auto payload = TRY_OR_THROW_OOM(vm, String::formatted("{}:{}", url.username(), url.password()));
  1178. authorization_value = TRY_OR_THROW_OOM(vm, encode_base64(payload.bytes()));
  1179. }
  1180. // 4. If authorizationValue is non-null, then append (`Authorization`, authorizationValue) to
  1181. // httpRequest’s header list.
  1182. if (authorization_value.has_value()) {
  1183. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Authorization"sv, *authorization_value));
  1184. TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
  1185. }
  1186. }
  1187. }
  1188. // FIXME: 21. If there’s a proxy-authentication entry, use it as appropriate.
  1189. // NOTE: This intentionally does not depend on httpRequest’s credentials mode.
  1190. // FIXME: 22. Set httpCache to the result of determining the HTTP cache partition, given httpRequest.
  1191. // 23. If httpCache is null, then set httpRequest’s cache mode to "no-store".
  1192. if (!http_cache)
  1193. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1194. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", then:
  1195. if (http_request->cache_mode() != Infrastructure::Request::CacheMode::NoStore
  1196. && http_request->cache_mode() != Infrastructure::Request::CacheMode::Reload) {
  1197. // 1. Set storedResponse to the result of selecting a response from the httpCache, possibly needing
  1198. // validation, as per the "Constructing Responses from Caches" chapter of HTTP Caching [HTTP-CACHING],
  1199. // if any.
  1200. // NOTE: As mandated by HTTP, this still takes the `Vary` header into account.
  1201. stored_response = nullptr;
  1202. // 2. If storedResponse is non-null, then:
  1203. if (stored_response) {
  1204. // FIXME: Caching is not implemented yet.
  1205. VERIFY_NOT_REACHED();
  1206. }
  1207. }
  1208. }
  1209. // 9. If aborted, then return the appropriate network error for fetchParams.
  1210. if (aborted)
  1211. return PendingResponse::create(vm, request, Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1212. JS::GCPtr<PendingResponse> pending_forward_response;
  1213. // 10. If response is null, then:
  1214. if (!response) {
  1215. // 1. If httpRequest’s cache mode is "only-if-cached", then return a network error.
  1216. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::OnlyIfCached)
  1217. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'only-if-cached' cache mode doesn't have a cached response"sv));
  1218. // 2. Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams, includeCredentials,
  1219. // and isNewConnectionFetch.
  1220. pending_forward_response = TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, *http_fetch_params, include_credentials, is_new_connection_fetch));
  1221. } else {
  1222. pending_forward_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  1223. }
  1224. auto returned_pending_response = PendingResponse::create(vm, request);
  1225. 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 {
  1226. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");
  1227. if (response_was_null) {
  1228. auto forward_response = resolved_forward_response;
  1229. // NOTE: TRACE is omitted as it is a forbidden method in Fetch.
  1230. auto method_is_unsafe = StringView { http_request->method() }.is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv);
  1231. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399, inclusive,
  1232. // invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP
  1233. // Caching, and set storedResponse to null.
  1234. if (method_is_unsafe && forward_response->status() >= 200 && forward_response->status() <= 399) {
  1235. // FIXME: "invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP Caching"
  1236. stored_response = nullptr;
  1237. }
  1238. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, then:
  1239. if (revalidating_flag->value() && forward_response->status() == 304) {
  1240. // FIXME: 1. Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening
  1241. // Stored Responses upon Validation" chapter of HTTP Caching.
  1242. // NOTE: This updates the stored response in cache as well.
  1243. // 2. Set response to storedResponse.
  1244. response = stored_response;
  1245. // 3. Set response’s cache state to "validated".
  1246. if (response)
  1247. response->set_cache_state(Infrastructure::Response::CacheState::Validated);
  1248. }
  1249. // 5. If response is null, then:
  1250. if (!response) {
  1251. // 1. Set response to forwardResponse.
  1252. response = forward_response;
  1253. // FIXME: 2. Store httpRequest and forwardResponse in httpCache, as per the "Storing Responses in Caches"
  1254. // chapter of HTTP Caching.
  1255. // NOTE: If forwardResponse is a network error, this effectively caches the network error, which is
  1256. // sometimes known as "negative caching".
  1257. // NOTE: The associated body info is stored in the cache alongside the response.
  1258. }
  1259. }
  1260. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1261. response->set_url_list(http_request->url_list());
  1262. // 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.
  1263. if (http_request->header_list()->contains("Range"sv.bytes()))
  1264. response->set_range_requested(true);
  1265. // 13. Set response’s request-includes-credentials to includeCredentials.
  1266. response->set_request_includes_credentials(include_credentials == IncludeCredentials::Yes);
  1267. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1268. // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", includeCredentials is true,
  1269. // and request’s window is an environment settings object, then:
  1270. if (response->status() == 401
  1271. && http_request->response_tainting() != Infrastructure::Request::ResponseTainting::CORS
  1272. && include_credentials == IncludeCredentials::Yes
  1273. && request->window().has<JS::GCPtr<HTML::EnvironmentSettingsObject>>()) {
  1274. // 1. Needs testing: multiple `WWW-Authenticate` headers, missing, parsing issues.
  1275. // (Red box in the spec, no-op)
  1276. // 2. If request’s body is non-null, then:
  1277. if (!request->body().has<Empty>()) {
  1278. // 1. If request’s body’s source is null, then return a network error.
  1279. if (request->body().get<Infrastructure::Body>().source().has<Empty>()) {
  1280. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request has body but no body source"_string)));
  1281. return;
  1282. }
  1283. // 2. Set request’s body to the body of the result of safely extracting request’s body’s source.
  1284. auto const& source = request->body().get<Infrastructure::Body>().source();
  1285. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  1286. auto converted_source = source.has<ByteBuffer>()
  1287. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  1288. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  1289. auto [body, _] = TRY_OR_IGNORE(safely_extract_body(realm, converted_source));
  1290. request->set_body(move(body));
  1291. }
  1292. // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
  1293. if (!request->use_url_credentials() || is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1294. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1295. if (fetch_params.is_canceled()) {
  1296. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1297. return;
  1298. }
  1299. // FIXME: 2. Let username and password be the result of prompting the end user for a username and password,
  1300. // respectively, in request’s window.
  1301. dbgln("Fetch: Username/password prompt is not implemented, using empty strings. This request will probably fail.");
  1302. auto username = DeprecatedString::empty();
  1303. auto password = DeprecatedString::empty();
  1304. // 3. Set the username given request’s current URL and username.
  1305. request->current_url().set_username(move(username));
  1306. // 4. Set the password given request’s current URL and password.
  1307. request->current_url().set_password(move(password));
  1308. }
  1309. // 4. Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.
  1310. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes));
  1311. }
  1312. 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) {
  1313. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");
  1314. // 15. If response’s status is 407, then:
  1315. if (response->status() == 407) {
  1316. // 1. If request’s window is "no-window", then return a network error.
  1317. if (request->window().has<Infrastructure::Request::Window>()
  1318. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow) {
  1319. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("Request requires proxy authentication but has 'no-window' set"_string)));
  1320. return;
  1321. }
  1322. // 2. Needs testing: multiple `Proxy-Authenticate` headers, missing, parsing issues.
  1323. // (Red box in the spec, no-op)
  1324. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1325. if (fetch_params.is_canceled()) {
  1326. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1327. return;
  1328. }
  1329. // FIXME: 4. Prompt the end user as appropriate in request’s window and store the result as a
  1330. // proxy-authentication entry.
  1331. // NOTE: Remaining details surrounding proxy authentication are defined by HTTP.
  1332. // FIXME: 5. Set response to the result of running HTTP-network-or-cache fetch given fetchParams.
  1333. // (Doing this without step 4 would potentially lead to an infinite request cycle.)
  1334. }
  1335. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1336. // 16. If all of the following are true
  1337. if (
  1338. // - response’s status is 421
  1339. response->status() == 421
  1340. // - isNewConnectionFetch is false
  1341. && is_new_connection_fetch == IsNewConnectionFetch::No
  1342. // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1343. && (request->body().has<Empty>() || !request->body().get<Infrastructure::Body>().source().has<Empty>())
  1344. // then:
  1345. ) {
  1346. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1347. if (fetch_params.is_canceled()) {
  1348. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1349. return;
  1350. }
  1351. // 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,
  1352. // isAuthenticationFetch, and true.
  1353. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes));
  1354. }
  1355. inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1356. // 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given
  1357. // realm.
  1358. if (is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1359. // FIXME: "create an authentication entry for request and the given realm"
  1360. }
  1361. returned_pending_response->resolve(response);
  1362. });
  1363. });
  1364. });
  1365. // 18. Return response.
  1366. // NOTE: Typically response’s body’s stream is still being enqueued to after returning.
  1367. return returned_pending_response;
  1368. }
  1369. #if defined(WEB_FETCH_DEBUG)
  1370. static void log_load_request(auto const& load_request)
  1371. {
  1372. dbgln("Fetch: Invoking ResourceLoader");
  1373. dbgln("> {} {} HTTP/1.1", load_request.method(), load_request.url());
  1374. for (auto const& [name, value] : load_request.headers())
  1375. dbgln("> {}: {}", name, value);
  1376. dbgln(">");
  1377. for (auto line : StringView { load_request.body() }.split_view('\n', SplitBehavior::KeepEmpty))
  1378. dbgln("> {}", line);
  1379. }
  1380. static void log_response(auto const& status_code, auto const& headers, auto const& data)
  1381. {
  1382. dbgln("< HTTP/1.1 {}", status_code.value_or(0));
  1383. for (auto const& [name, value] : headers)
  1384. dbgln("< {}: {}", name, value);
  1385. dbgln("<");
  1386. for (auto line : StringView { data }.split_view('\n', SplitBehavior::KeepEmpty))
  1387. dbgln("< {}", line);
  1388. }
  1389. #endif
  1390. // https://fetch.spec.whatwg.org/#concept-http-network-fetch
  1391. // Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)
  1392. // It also handles file:// URLs since those can also go through ResourceLoader.
  1393. 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)
  1394. {
  1395. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'non-standard HTTP-network fetch' with: fetch_params @ {}", &fetch_params);
  1396. auto& vm = realm.vm();
  1397. (void)include_credentials;
  1398. (void)is_new_connection_fetch;
  1399. auto request = fetch_params.request();
  1400. Page* page = nullptr;
  1401. auto& global_object = realm.global_object();
  1402. if (is<HTML::Window>(global_object))
  1403. page = static_cast<HTML::Window&>(global_object).page();
  1404. // NOTE: Using LoadRequest::create_for_url_on_page here will unconditionally add cookies as long as there's a page available.
  1405. // However, it is up to http_network_or_cache_fetch to determine if cookies should be added to the request.
  1406. LoadRequest load_request;
  1407. load_request.set_url(request->current_url());
  1408. if (page)
  1409. load_request.set_page(*page);
  1410. load_request.set_method(DeprecatedString::copy(request->method()));
  1411. for (auto const& header : *request->header_list())
  1412. load_request.set_header(DeprecatedString::copy(header.name), DeprecatedString::copy(header.value));
  1413. if (auto const* body = request->body().get_pointer<Infrastructure::Body>()) {
  1414. TRY(body->source().visit(
  1415. [&](ByteBuffer const& byte_buffer) -> WebIDL::ExceptionOr<void> {
  1416. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(byte_buffer)));
  1417. return {};
  1418. },
  1419. [&](JS::Handle<FileAPI::Blob> const& blob_handle) -> WebIDL::ExceptionOr<void> {
  1420. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob_handle->bytes())));
  1421. return {};
  1422. },
  1423. [](Empty) -> WebIDL::ExceptionOr<void> {
  1424. return {};
  1425. }));
  1426. }
  1427. auto pending_response = PendingResponse::create(vm, request);
  1428. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Invoking ResourceLoader");
  1429. if constexpr (WEB_FETCH_DEBUG)
  1430. log_load_request(load_request);
  1431. ResourceLoader::the().load(
  1432. load_request,
  1433. [&realm, &vm, request, pending_response](auto data, auto& response_headers, auto status_code) {
  1434. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' complete", request->url());
  1435. if constexpr (WEB_FETCH_DEBUG)
  1436. log_response(status_code, response_headers, data);
  1437. auto [body, _] = TRY_OR_IGNORE(extract_body(realm, data));
  1438. auto response = Infrastructure::Response::create(vm);
  1439. response->set_status(status_code.value_or(200));
  1440. response->set_body(move(body));
  1441. for (auto const& [name, value] : response_headers) {
  1442. auto header = TRY_OR_IGNORE(Infrastructure::Header::from_string_pair(name, value));
  1443. TRY_OR_IGNORE(response->header_list()->append(header));
  1444. }
  1445. // FIXME: Set response status message
  1446. pending_response->resolve(response);
  1447. },
  1448. [&vm, request, pending_response](auto& error, auto status_code) {
  1449. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' failed: {} (status {})", request->url(), error, status_code.value_or(0));
  1450. auto response = Infrastructure::Response::create(vm);
  1451. // FIXME: This is ugly, ResourceLoader should tell us.
  1452. if (status_code.value_or(0) == 0) {
  1453. response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("HTTP request failed"_string));
  1454. } else {
  1455. response->set_type(Infrastructure::Response::Type::Error);
  1456. response->set_status(status_code.value_or(400));
  1457. // FIXME: Set response status message and body
  1458. }
  1459. pending_response->resolve(response);
  1460. });
  1461. return pending_response;
  1462. }
  1463. // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0
  1464. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> cors_preflight_fetch(JS::Realm& realm, Infrastructure::Request& request)
  1465. {
  1466. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' with request @ {}", &request);
  1467. auto& vm = realm.vm();
  1468. // 1. Let preflight be a new request whose method is `OPTIONS`, URL list is a clone of request’s URL list, initiator is
  1469. // request’s initiator, destination is request’s destination, origin is request’s origin, referrer is request’s referrer,
  1470. // referrer policy is request’s referrer policy, mode is "cors", and response tainting is "cors".
  1471. auto preflight = Fetch::Infrastructure::Request::create(vm);
  1472. preflight->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("OPTIONS"sv.bytes())));
  1473. preflight->set_url_list(request.url_list());
  1474. preflight->set_initiator(request.initiator());
  1475. preflight->set_destination(request.destination());
  1476. preflight->set_origin(request.origin());
  1477. preflight->set_referrer(request.referrer());
  1478. preflight->set_referrer_policy(request.referrer_policy());
  1479. preflight->set_mode(Infrastructure::Request::Mode::CORS);
  1480. preflight->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  1481. // 2. Append (`Accept`, `*/*`) to preflight’s header list.
  1482. auto temp_header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Accept"sv, "*/*"sv));
  1483. TRY_OR_THROW_OOM(vm, preflight->header_list()->append(move(temp_header)));
  1484. // 3. Append (`Access-Control-Request-Method`, request’s method) to preflight’s header list.
  1485. temp_header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Access-Control-Request-Method"sv, request.method()));
  1486. TRY_OR_THROW_OOM(vm, preflight->header_list()->append(move(temp_header)));
  1487. // 4. Let headers be the CORS-unsafe request-header names with request’s header list.
  1488. auto headers = TRY_OR_THROW_OOM(vm, Infrastructure::get_cors_unsafe_header_names(request.header_list()));
  1489. // 5. If headers is not empty, then:
  1490. if (!headers.is_empty()) {
  1491. // 1. Let value be the items in headers separated from each other by `,`.
  1492. // NOTE: This intentionally does not use combine, as 0x20 following 0x2C is not the way this was implemented,
  1493. // for better or worse.
  1494. ByteBuffer value;
  1495. bool first = true;
  1496. for (auto const& header : headers) {
  1497. if (!first)
  1498. TRY_OR_THROW_OOM(vm, value.try_append(','));
  1499. TRY_OR_THROW_OOM(vm, value.try_append(header));
  1500. first = false;
  1501. }
  1502. // 2. Append (`Access-Control-Request-Headers`, value) to preflight’s header list.
  1503. temp_header = Infrastructure::Header {
  1504. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("Access-Control-Request-Headers"sv.bytes())),
  1505. .value = move(value),
  1506. };
  1507. TRY_OR_THROW_OOM(vm, preflight->header_list()->append(move(temp_header)));
  1508. }
  1509. // 6. Let response be the result of running HTTP-network-or-cache fetch given a new fetch params whose request is preflight.
  1510. // FIXME: The spec doesn't say anything about timing_info here, but FetchParams requires a non-null FetchTimingInfo object.
  1511. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  1512. auto fetch_params = Infrastructure::FetchParams::create(vm, preflight, timing_info);
  1513. auto returned_pending_response = PendingResponse::create(vm, request);
  1514. auto preflight_response = TRY(http_network_or_cache_fetch(realm, fetch_params));
  1515. preflight_response->when_loaded([&vm, &request, returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1516. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");
  1517. // 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
  1518. // NOTE: The CORS check is done on request rather than preflight to ensure the correct credentials mode is used.
  1519. if (TRY_OR_IGNORE(cors_check(request, response)) && Infrastructure::is_ok_status(response->status())) {
  1520. // 1. Let methods be the result of extracting header list values given `Access-Control-Allow-Methods` and response’s header list.
  1521. auto methods_or_failure = TRY_OR_IGNORE(Infrastructure::extract_header_list_values("Access-Control-Allow-Methods"sv.bytes(), response->header_list()));
  1522. // 2. Let headerNames be the result of extracting header list values given `Access-Control-Allow-Headers` and
  1523. // response’s header list.
  1524. auto header_names_or_failure = TRY_OR_IGNORE(Infrastructure::extract_header_list_values("Access-Control-Allow-Headers"sv.bytes(), response->header_list()));
  1525. // 3. If either methods or headerNames is failure, return a network error.
  1526. if (methods_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  1527. 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)));
  1528. return;
  1529. }
  1530. if (header_names_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  1531. 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)));
  1532. return;
  1533. }
  1534. // NOTE: We treat "methods_or_failure" being `Empty` as empty Vector here.
  1535. auto methods = methods_or_failure.has<Vector<ByteBuffer>>() ? methods_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  1536. // NOTE: We treat "header_names_or_failure" being `Empty` as empty Vector here.
  1537. auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  1538. // FIXME: Remove this once extract_header_list_values validates the header and returns multiple values.
  1539. if (!methods.is_empty()) {
  1540. VERIFY(methods.size() == 1);
  1541. auto split_methods = StringView { methods.first() }.split_view(',');
  1542. Vector<ByteBuffer> trimmed_methods;
  1543. for (auto const& method : split_methods) {
  1544. auto trimmed_method = method.trim(" \t"sv);
  1545. auto trimmed_method_as_byte_buffer = TRY_OR_IGNORE(ByteBuffer::copy(trimmed_method.bytes()));
  1546. TRY_OR_IGNORE(trimmed_methods.try_append(move(trimmed_method_as_byte_buffer)));
  1547. }
  1548. methods = move(trimmed_methods);
  1549. }
  1550. // FIXME: Remove this once extract_header_list_values validates the header and returns multiple values.
  1551. if (!header_names.is_empty()) {
  1552. VERIFY(header_names.size() == 1);
  1553. auto split_header_names = StringView { header_names.first() }.split_view(',');
  1554. Vector<ByteBuffer> trimmed_header_names;
  1555. for (auto const& header_name : split_header_names) {
  1556. auto trimmed_header_name = header_name.trim(" \t"sv);
  1557. auto trimmed_header_name_as_byte_buffer = TRY_OR_IGNORE(ByteBuffer::copy(trimmed_header_name.bytes()));
  1558. TRY_OR_IGNORE(trimmed_header_names.try_append(move(trimmed_header_name_as_byte_buffer)));
  1559. }
  1560. header_names = move(trimmed_header_names);
  1561. }
  1562. // 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.
  1563. // NOTE: This ensures that a CORS-preflight fetch that happened due to request’s use-CORS-preflight flag being set is cached.
  1564. if (methods.is_empty() && request.use_cors_preflight())
  1565. methods = Vector { TRY_OR_IGNORE(ByteBuffer::copy(request.method())) };
  1566. // 5. If request’s method is not in methods, request’s method is not a CORS-safelisted method, and request’s credentials mode
  1567. // is "include" or methods does not contain `*`, then return a network error.
  1568. if (!methods.contains_slow(request.method()) && !Infrastructure::is_cors_safelisted_method(request.method())) {
  1569. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  1570. 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() }))));
  1571. return;
  1572. }
  1573. if (!methods.contains_slow("*"sv.bytes())) {
  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 and there was no '*' entry. The header may be missing."sv, StringView { request.method() }))));
  1575. return;
  1576. }
  1577. }
  1578. // 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
  1579. // for an item in headerNames, then return a network error.
  1580. for (auto const& header : *request.header_list()) {
  1581. if (Infrastructure::is_cors_non_wildcard_request_header_name(header.name)) {
  1582. bool is_in_header_names = false;
  1583. for (auto const& allowed_header_name : header_names) {
  1584. if (StringView { allowed_header_name }.equals_ignoring_ascii_case(header.name)) {
  1585. is_in_header_names = true;
  1586. break;
  1587. }
  1588. }
  1589. if (!is_in_header_names) {
  1590. 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 }))));
  1591. return;
  1592. }
  1593. }
  1594. }
  1595. // 7. For each unsafeName of the CORS-unsafe request-header names with request’s header list, if unsafeName is not a
  1596. // byte-case-insensitive match for an item in headerNames and request’s credentials mode is "include" or headerNames
  1597. // does not contain `*`, return a network error.
  1598. auto unsafe_names = TRY_OR_IGNORE(Infrastructure::get_cors_unsafe_header_names(request.header_list()));
  1599. for (auto const& unsafe_name : unsafe_names) {
  1600. bool is_in_header_names = false;
  1601. for (auto const& header_name : header_names) {
  1602. if (StringView { unsafe_name }.equals_ignoring_ascii_case(header_name)) {
  1603. is_in_header_names = true;
  1604. break;
  1605. }
  1606. }
  1607. if (!is_in_header_names) {
  1608. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  1609. 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 }))));
  1610. return;
  1611. }
  1612. if (!header_names.contains_slow("*"sv.bytes())) {
  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 and there was no '*' entry. The header may be missing."sv, StringView { unsafe_name }))));
  1614. return;
  1615. }
  1616. }
  1617. }
  1618. // FIXME: 8. Let max-age be the result of extracting header list values given `Access-Control-Max-Age` and response’s header list.
  1619. // FIXME: 9. If max-age is failure or null, then set max-age to 5.
  1620. // FIXME: 10. If max-age is greater than an imposed limit on max-age, then set max-age to the imposed limit.
  1621. // 11. If the user agent does not provide for a cache, then return response.
  1622. // NOTE: Since we don't currently have a cache, this is always true.
  1623. returned_pending_response->resolve(response);
  1624. return;
  1625. // FIXME: 12. For each method in methods for which there is a method cache entry match using request, set matching entry’s max-age
  1626. // to max-age.
  1627. // FIXME: 13. For each method in methods for which there is no method cache entry match using request, create a new cache entry
  1628. // with request, max-age, method, and null.
  1629. // FIXME: 14. For each headerName in headerNames for which there is a header-name cache entry match using request, set matching
  1630. // entry’s max-age to max-age.
  1631. // FIXME: 15. For each headerName in headerNames for which there is no header-name cache entry match using request, create a
  1632. // new cache entry with request, max-age, null, and headerName.
  1633. // FIXME: 16. Return response.
  1634. }
  1635. // 8. Otherwise, return a network error.
  1636. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE("CORS-preflight check failed"_string)));
  1637. });
  1638. return returned_pending_response;
  1639. }
  1640. }