Fetching.cpp 158 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734
  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. * Copyright (c) 2024, Jamie Mansfield <jmansfield@cadixdev.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Base64.h>
  10. #include <AK/Debug.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <LibJS/Runtime/Completion.h>
  13. #include <LibWeb/Bindings/MainThreadVM.h>
  14. #include <LibWeb/Cookie/Cookie.h>
  15. #include <LibWeb/DOM/Document.h>
  16. #include <LibWeb/DOMURL/DOMURL.h>
  17. #include <LibWeb/Fetch/BodyInit.h>
  18. #include <LibWeb/Fetch/Fetching/Checks.h>
  19. #include <LibWeb/Fetch/Fetching/FetchedDataReceiver.h>
  20. #include <LibWeb/Fetch/Fetching/Fetching.h>
  21. #include <LibWeb/Fetch/Fetching/PendingResponse.h>
  22. #include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
  23. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  24. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  25. #include <LibWeb/Fetch/Infrastructure/FetchParams.h>
  26. #include <LibWeb/Fetch/Infrastructure/FetchRecord.h>
  27. #include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
  28. #include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
  29. #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
  30. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  31. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  32. #include <LibWeb/Fetch/Infrastructure/HTTP/Statuses.h>
  33. #include <LibWeb/Fetch/Infrastructure/MimeTypeBlocking.h>
  34. #include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>
  35. #include <LibWeb/Fetch/Infrastructure/NoSniffBlocking.h>
  36. #include <LibWeb/Fetch/Infrastructure/PortBlocking.h>
  37. #include <LibWeb/Fetch/Infrastructure/Task.h>
  38. #include <LibWeb/Fetch/Infrastructure/URL.h>
  39. #include <LibWeb/FileAPI/Blob.h>
  40. #include <LibWeb/FileAPI/BlobURLStore.h>
  41. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  42. #include <LibWeb/HTML/Scripting/Environments.h>
  43. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  44. #include <LibWeb/HTML/Window.h>
  45. #include <LibWeb/HTML/WorkerGlobalScope.h>
  46. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  47. #include <LibWeb/Loader/LoadRequest.h>
  48. #include <LibWeb/Loader/ResourceLoader.h>
  49. #include <LibWeb/MixedContent/AbstractOperations.h>
  50. #include <LibWeb/Platform/EventLoopPlugin.h>
  51. #include <LibWeb/ReferrerPolicy/AbstractOperations.h>
  52. #include <LibWeb/SRI/SRI.h>
  53. #include <LibWeb/SecureContexts/AbstractOperations.h>
  54. #include <LibWeb/Streams/TransformStream.h>
  55. #include <LibWeb/Streams/TransformStreamDefaultController.h>
  56. #include <LibWeb/Streams/Transformer.h>
  57. #include <LibWeb/WebIDL/DOMException.h>
  58. namespace Web::Fetch::Fetching {
  59. bool g_http_cache_enabled;
  60. #define TRY_OR_IGNORE(expression) \
  61. ({ \
  62. auto&& _temporary_result = (expression); \
  63. if (_temporary_result.is_error()) \
  64. return; \
  65. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  66. "Do not return a reference from a fallible expression"); \
  67. _temporary_result.release_value(); \
  68. })
  69. // https://fetch.spec.whatwg.org/#concept-fetch
  70. WebIDL::ExceptionOr<JS::NonnullGCPtr<Infrastructure::FetchController>> fetch(JS::Realm& realm, Infrastructure::Request& request, Infrastructure::FetchAlgorithms const& algorithms, UseParallelQueue use_parallel_queue)
  71. {
  72. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch' with: request @ {}", &request);
  73. auto& vm = realm.vm();
  74. // 1. Assert: request’s mode is "navigate" or processEarlyHintsResponse is null.
  75. VERIFY(request.mode() == Infrastructure::Request::Mode::Navigate || !algorithms.process_early_hints_response());
  76. // 2. Let taskDestination be null.
  77. JS::GCPtr<JS::Object> task_destination;
  78. // 3. Let crossOriginIsolatedCapability be false.
  79. auto cross_origin_isolated_capability = HTML::CanUseCrossOriginIsolatedAPIs::No;
  80. // 4. If request’s client is non-null, then:
  81. if (request.client() != nullptr) {
  82. // 1. Set taskDestination to request’s client’s global object.
  83. task_destination = request.client()->global_object();
  84. // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin isolated capability.
  85. cross_origin_isolated_capability = request.client()->cross_origin_isolated_capability();
  86. }
  87. // FIXME: 5. If useParallelQueue is true, then set taskDestination to the result of starting a new parallel queue.
  88. (void)use_parallel_queue;
  89. // 6. Let timingInfo be a new fetch timing info whose start time and post-redirect start time are the coarsened
  90. // shared current time given crossOriginIsolatedCapability, and render-blocking is set to request’s
  91. // render-blocking.
  92. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  93. auto now = HighResolutionTime::coarsened_shared_current_time(cross_origin_isolated_capability == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  94. timing_info->set_start_time(now);
  95. timing_info->set_post_redirect_start_time(now);
  96. timing_info->set_render_blocking(request.render_blocking());
  97. // 7. Let fetchParams be a new fetch params whose request is request, timing info is timingInfo, process request
  98. // body chunk length is processRequestBodyChunkLength, process request end-of-body is processRequestEndOfBody,
  99. // process early hints response is processEarlyHintsResponse, process response is processResponse, process
  100. // response consume body is processResponseConsumeBody, process response end-of-body is processResponseEndOfBody,
  101. // task destination is taskDestination, and cross-origin isolated capability is crossOriginIsolatedCapability.
  102. auto fetch_params = Infrastructure::FetchParams::create(vm, request, timing_info);
  103. fetch_params->set_algorithms(algorithms);
  104. if (task_destination)
  105. fetch_params->set_task_destination({ *task_destination });
  106. fetch_params->set_cross_origin_isolated_capability(cross_origin_isolated_capability);
  107. // 8. If request’s body is a byte sequence, then set request’s body to request’s body as a body.
  108. if (auto const* buffer = request.body().get_pointer<ByteBuffer>())
  109. request.set_body(TRY(Infrastructure::byte_sequence_as_body(realm, buffer->bytes())));
  110. // 9. If request’s window is "client", then set request’s window to request’s client, if request’s client’s global
  111. // object is a Window object; otherwise "no-window".
  112. auto const* window = request.window().get_pointer<Infrastructure::Request::Window>();
  113. if (window && *window == Infrastructure::Request::Window::Client) {
  114. if (is<HTML::Window>(request.client()->global_object())) {
  115. request.set_window(request.client());
  116. } else {
  117. request.set_window(Infrastructure::Request::Window::NoWindow);
  118. }
  119. }
  120. // 10. If request’s origin is "client", then set request’s origin to request’s client’s origin.
  121. auto const* origin = request.origin().get_pointer<Infrastructure::Request::Origin>();
  122. if (origin && *origin == Infrastructure::Request::Origin::Client)
  123. request.set_origin(request.client()->origin());
  124. // 11. If all of the following conditions are true:
  125. if (
  126. // - request’s URL’s scheme is an HTTP(S) scheme
  127. Infrastructure::is_http_or_https_scheme(request.url().scheme())
  128. // - request’s mode is "same-origin", "cors", or "no-cors"
  129. && (request.mode() == Infrastructure::Request::Mode::SameOrigin || request.mode() == Infrastructure::Request::Mode::CORS || request.mode() == Infrastructure::Request::Mode::NoCORS)
  130. // - request’s window is an environment settings object
  131. && request.window().has<JS::GCPtr<HTML::EnvironmentSettingsObject>>()
  132. // - request’s method is `GET`
  133. && StringView { request.method() }.equals_ignoring_ascii_case("GET"sv)
  134. // - request’s unsafe-request flag is not set or request’s header list is empty
  135. && (!request.unsafe_request() || request.header_list()->is_empty())) {
  136. // 1. Assert: request’s origin is same origin with request’s client’s origin.
  137. VERIFY(request.origin().has<URL::Origin>() && request.origin().get<URL::Origin>().is_same_origin(request.client()->origin()));
  138. // 2. Let onPreloadedResponseAvailable be an algorithm that runs the following step given a response
  139. // response: set fetchParams’s preloaded response candidate to response.
  140. auto on_preloaded_response_available = JS::create_heap_function(realm.heap(), [fetch_params](JS::NonnullGCPtr<Infrastructure::Response> response) {
  141. fetch_params->set_preloaded_response_candidate(response);
  142. });
  143. // FIXME: 3. Let foundPreloadedResource be the result of invoking consume a preloaded resource for request’s
  144. // window, given request’s URL, request’s destination, request’s mode, request’s credentials mode,
  145. // request’s integrity metadata, and onPreloadedResponseAvailable.
  146. auto found_preloaded_resource = false;
  147. (void)on_preloaded_response_available;
  148. // 4. If foundPreloadedResource is true and fetchParams’s preloaded response candidate is null, then set
  149. // fetchParams’s preloaded response candidate to "pending".
  150. if (found_preloaded_resource && fetch_params->preloaded_response_candidate().has<Empty>())
  151. fetch_params->set_preloaded_response_candidate(Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag {});
  152. }
  153. // 12. If request’s policy container is "client", then:
  154. auto const* policy_container = request.policy_container().get_pointer<Infrastructure::Request::PolicyContainer>();
  155. if (policy_container) {
  156. VERIFY(*policy_container == Infrastructure::Request::PolicyContainer::Client);
  157. // 1. If request’s client is non-null, then set request’s policy container to a clone of request’s client’s
  158. // policy container.
  159. if (request.client() != nullptr)
  160. request.set_policy_container(request.client()->policy_container());
  161. // 2. Otherwise, set request’s policy container to a new policy container.
  162. else
  163. request.set_policy_container(HTML::PolicyContainer {});
  164. }
  165. // 13. If request’s header list does not contain `Accept`, then:
  166. if (!request.header_list()->contains("Accept"sv.bytes())) {
  167. // 1. Let value be `*/*`.
  168. auto value = "*/*"sv;
  169. // 2. If request’s initiator is "prefetch", then set value to the document `Accept` header value.
  170. if (request.initiator() == Infrastructure::Request::Initiator::Prefetch) {
  171. value = document_accept_header_value;
  172. }
  173. // 3. Otherwise, the user agent should set value to the first matching statement, if any, switching on request’s destination:
  174. else if (request.destination().has_value()) {
  175. switch (*request.destination()) {
  176. // -> "document"
  177. // -> "frame"
  178. // -> "iframe"
  179. case Infrastructure::Request::Destination::Document:
  180. case Infrastructure::Request::Destination::Frame:
  181. case Infrastructure::Request::Destination::IFrame:
  182. // the document `Accept` header value
  183. value = document_accept_header_value;
  184. break;
  185. // -> "image"
  186. case Infrastructure::Request::Destination::Image:
  187. // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
  188. value = "image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5"sv;
  189. break;
  190. // -> "json"
  191. case Infrastructure::Request::Destination::JSON:
  192. // `application/json,*/*;q=0.5`
  193. value = "application/json,*/*;q=0.5"sv;
  194. break;
  195. // -> "style"
  196. case Infrastructure::Request::Destination::Style:
  197. // `text/css,*/*;q=0.1`
  198. value = "text/css,*/*;q=0.1"sv;
  199. break;
  200. default:
  201. break;
  202. }
  203. }
  204. // 4. Append (`Accept`, value) to request’s header list.
  205. auto header = Infrastructure::Header::from_string_pair("Accept"sv, value.bytes());
  206. request.header_list()->append(move(header));
  207. }
  208. // 14. If request’s header list does not contain `Accept-Language`, then user agents should append
  209. // (`Accept-Language, an appropriate header value) to request’s header list.
  210. if (!request.header_list()->contains("Accept-Language"sv.bytes())) {
  211. StringBuilder accept_language;
  212. accept_language.join(","sv, ResourceLoader::the().preferred_languages());
  213. auto header = Infrastructure::Header::from_string_pair("Accept-Language"sv, accept_language.string_view());
  214. request.header_list()->append(move(header));
  215. }
  216. // 15. If request’s priority is null, then use request’s initiator, destination, and render-blocking appropriately
  217. // in setting request’s priority to a user-agent-defined object.
  218. // NOTE: The user-agent-defined object could encompass stream weight and dependency for HTTP/2, and equivalent
  219. // information used to prioritize dispatch and processing of HTTP/1 fetches.
  220. // 16. If request is a subresource request, then:
  221. if (request.is_subresource_request()) {
  222. // 1. Let record be a new fetch record whose request is request and controller is fetchParams’s controller.
  223. auto record = Infrastructure::FetchRecord::create(vm, request, fetch_params->controller());
  224. // 2. Append record to request’s client’s fetch group list of fetch records.
  225. request.client()->fetch_group().append(record);
  226. }
  227. // 17. Run main fetch given fetchParams.
  228. (void)TRY(main_fetch(realm, fetch_params));
  229. // 18. Return fetchParams’s controller.
  230. return fetch_params->controller();
  231. }
  232. // https://fetch.spec.whatwg.org/#concept-main-fetch
  233. WebIDL::ExceptionOr<JS::GCPtr<PendingResponse>> main_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Recursive recursive)
  234. {
  235. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' with: fetch_params @ {}", &fetch_params);
  236. auto& vm = realm.vm();
  237. // 1. Let request be fetchParams’s request.
  238. auto request = fetch_params.request();
  239. // 2. Let response be null.
  240. JS::GCPtr<Infrastructure::Response> response;
  241. // 3. If request’s local-URLs-only flag is set and request’s current URL is not local, then set response to a
  242. // network error.
  243. if (request->local_urls_only() && !Infrastructure::is_local_url(request->current_url()))
  244. response = Infrastructure::Response::network_error(vm, "Request with 'local-URLs-only' flag must have a local URL"sv);
  245. // FIXME: 4. Run report Content Security Policy violations for request.
  246. // FIXME: 5. Upgrade request to a potentially trustworthy URL, if appropriate.
  247. // 6. Upgrade a mixed content request to a potentially trustworthy URL, if appropriate.
  248. MixedContent::upgrade_a_mixed_content_request_to_a_potentially_trustworthy_url_if_appropriate(request);
  249. // 7. If should request be blocked due to a bad port, should fetching request be blocked as mixed content, or
  250. // should request be blocked by Content Security Policy returns blocked, then set response to a network error.
  251. if (Infrastructure::block_bad_port(request) == Infrastructure::RequestOrResponseBlocking::Blocked
  252. || MixedContent::should_fetching_request_be_blocked_as_mixed_content(request) == Infrastructure::RequestOrResponseBlocking::Blocked
  253. || false // FIXME: "should request be blocked by Content Security Policy returns blocked"
  254. ) {
  255. response = Infrastructure::Response::network_error(vm, "Request was blocked"sv);
  256. }
  257. // 8. If request’s referrer policy is the empty string, then set request’s referrer policy to request’s policy
  258. // container’s referrer policy.
  259. if (request->referrer_policy() == ReferrerPolicy::ReferrerPolicy::EmptyString) {
  260. VERIFY(request->policy_container().has<HTML::PolicyContainer>());
  261. request->set_referrer_policy(request->policy_container().get<HTML::PolicyContainer>().referrer_policy);
  262. }
  263. // 9. If request’s referrer is not "no-referrer", then set request’s referrer to the result of invoking determine
  264. // request’s referrer.
  265. // NOTE: As stated in Referrer Policy, user agents can provide the end user with options to override request’s
  266. // referrer to "no-referrer" or have it expose less sensitive information.
  267. auto const* referrer = request->referrer().get_pointer<Infrastructure::Request::Referrer>();
  268. if (!referrer || *referrer != Infrastructure::Request::Referrer::NoReferrer) {
  269. auto determined_referrer = ReferrerPolicy::determine_requests_referrer(request);
  270. if (determined_referrer.has_value())
  271. request->set_referrer(*determined_referrer);
  272. else
  273. request->set_referrer(Infrastructure::Request::Referrer::NoReferrer);
  274. }
  275. // 10. Set request’s current URL’s scheme to "https" if all of the following conditions are true:
  276. if (
  277. // - request’s current URL’s scheme is "http"
  278. request->current_url().scheme() == "http"sv
  279. // - request’s current URL’s host is a domain
  280. && DOMURL::host_is_domain(request->current_url().host())
  281. // FIXME: - Matching request’s current URL’s host per Known HSTS Host Domain Name Matching results in either a
  282. // superdomain match with an asserted includeSubDomains directive or a congruent match (with or without an
  283. // asserted includeSubDomains directive) [HSTS]; or DNS resolution for the request finds a matching HTTPS RR
  284. // per section 9.5 of [SVCB].
  285. && false
  286. ) {
  287. request->current_url().set_scheme("https"_string);
  288. }
  289. JS::SafeFunction<WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>>()> get_response = [&realm, &vm, &fetch_params, request]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> {
  290. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' get_response() function");
  291. // -> fetchParams’s preloaded response candidate is not null
  292. if (!fetch_params.preloaded_response_candidate().has<Empty>()) {
  293. // 1. Wait until fetchParams’s preloaded response candidate is not "pending".
  294. HTML::main_thread_event_loop().spin_until([&] {
  295. return !fetch_params.preloaded_response_candidate().has<Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag>();
  296. });
  297. // 2. Assert: fetchParams’s preloaded response candidate is a response.
  298. VERIFY(fetch_params.preloaded_response_candidate().has<JS::NonnullGCPtr<Infrastructure::Response>>());
  299. // 3. Return fetchParams’s preloaded response candidate.
  300. return PendingResponse::create(vm, request, fetch_params.preloaded_response_candidate().get<JS::NonnullGCPtr<Infrastructure::Response>>());
  301. }
  302. // -> request’s current URL’s origin is same origin with request’s origin, and request’s response tainting
  303. // is "basic"
  304. // -> request’s current URL’s scheme is "data"
  305. // -> request’s mode is "navigate" or "websocket"
  306. else if (
  307. (request->origin().has<URL::Origin>() && request->current_url().origin().is_same_origin(request->origin().get<URL::Origin>()) && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  308. || request->current_url().scheme() == "data"sv
  309. || (request->mode() == Infrastructure::Request::Mode::Navigate || request->mode() == Infrastructure::Request::Mode::WebSocket)) {
  310. // 1. Set request’s response tainting to "basic".
  311. request->set_response_tainting(Infrastructure::Request::ResponseTainting::Basic);
  312. // 2. Return the result of running scheme fetch given fetchParams.
  313. return scheme_fetch(realm, fetch_params);
  314. // NOTE: HTML assigns any documents and workers created from URLs whose scheme is "data" a unique
  315. // opaque origin. Service workers can only be created from URLs whose scheme is an HTTP(S) scheme.
  316. }
  317. // -> request’s mode is "same-origin"
  318. else if (request->mode() == Infrastructure::Request::Mode::SameOrigin) {
  319. // Return a network error.
  320. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'same-origin' mode must have same URL and request origin"sv));
  321. }
  322. // -> request’s mode is "no-cors"
  323. else if (request->mode() == Infrastructure::Request::Mode::NoCORS) {
  324. // 1. If request’s redirect mode is not "follow", then return a network error.
  325. if (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow)
  326. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'no-cors' mode must have redirect mode set to 'follow'"sv));
  327. // 2. Set request’s response tainting to "opaque".
  328. request->set_response_tainting(Infrastructure::Request::ResponseTainting::Opaque);
  329. // 3. Return the result of running scheme fetch given fetchParams.
  330. return scheme_fetch(realm, fetch_params);
  331. }
  332. // -> request’s current URL’s scheme is not an HTTP(S) scheme
  333. else if (!Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  334. // NOTE: At this point all other request modes have been handled. Ensure we're not lying in the error message :^)
  335. VERIFY(request->mode() == Infrastructure::Request::Mode::CORS);
  336. // Return a network error.
  337. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' mode must have URL with HTTP or HTTPS scheme"sv));
  338. }
  339. // -> request’s use-CORS-preflight flag is set
  340. // -> request’s unsafe-request flag is set and either request’s method is not a CORS-safelisted method or
  341. // CORS-unsafe request-header names with request’s header list is not empty
  342. else if (
  343. request->use_cors_preflight()
  344. || (request->unsafe_request()
  345. && (!Infrastructure::is_cors_safelisted_method(request->method())
  346. || !Infrastructure::get_cors_unsafe_header_names(request->header_list()).is_empty()))) {
  347. // 1. Set request’s response tainting to "cors".
  348. request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  349. auto returned_pending_response = PendingResponse::create(vm, request);
  350. // 2. Let corsWithPreflightResponse be the result of running HTTP fetch given fetchParams and true.
  351. auto cors_with_preflight_response = TRY(http_fetch(realm, fetch_params, MakeCORSPreflight::Yes));
  352. cors_with_preflight_response->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> cors_with_preflight_response) {
  353. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' cors_with_preflight_response load callback");
  354. // 3. If corsWithPreflightResponse is a network error, then clear cache entries using request.
  355. if (cors_with_preflight_response->is_network_error()) {
  356. // FIXME: Clear cache entries
  357. }
  358. // 4. Return corsWithPreflightResponse.
  359. returned_pending_response->resolve(cors_with_preflight_response);
  360. });
  361. return returned_pending_response;
  362. }
  363. // -> Otherwise
  364. else {
  365. // 1. Set request’s response tainting to "cors".
  366. request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  367. // 2. Return the result of running HTTP fetch given fetchParams.
  368. return http_fetch(realm, fetch_params);
  369. }
  370. };
  371. if (recursive == Recursive::Yes) {
  372. // 12. If response is null, then set response to the result of running the steps corresponding to the first
  373. // matching statement:
  374. auto pending_response = !response
  375. ? TRY(get_response())
  376. : PendingResponse::create(vm, request, *response);
  377. // 13. If recursive is true, then return response.
  378. return pending_response;
  379. }
  380. // 11. If recursive is false, then run the remaining steps in parallel.
  381. Platform::EventLoopPlugin::the().deferred_invoke([&realm, &vm, &fetch_params, request, response, get_response = move(get_response)] {
  382. // 12. If response is null, then set response to the result of running the steps corresponding to the first
  383. // matching statement:
  384. auto pending_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  385. if (!response) {
  386. auto pending_response_or_error = get_response();
  387. if (pending_response_or_error.is_error())
  388. return;
  389. pending_response = pending_response_or_error.release_value();
  390. }
  391. pending_response->when_loaded([&realm, &vm, &fetch_params, request, response, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_response) mutable {
  392. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' pending_response load callback");
  393. if (response_was_null)
  394. response = resolved_response;
  395. // 14. If response is not a network error and response is not a filtered response, then:
  396. if (!response->is_network_error() && !is<Infrastructure::FilteredResponse>(*response)) {
  397. // 1. If request’s response tainting is "cors", then:
  398. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS) {
  399. // 1. Let headerNames be the result of extracting header list values given
  400. // `Access-Control-Expose-Headers` and response’s header list.
  401. auto header_names_or_failure = Infrastructure::extract_header_list_values("Access-Control-Expose-Headers"sv.bytes(), response->header_list());
  402. auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  403. // 2. If request’s credentials mode is not "include" and headerNames contains `*`, then set
  404. // response’s CORS-exposed header-name list to all unique header names in response’s header
  405. // list.
  406. if (request->credentials_mode() != Infrastructure::Request::CredentialsMode::Include && header_names.contains_slow("*"sv.bytes())) {
  407. auto unique_header_names = response->header_list()->unique_names();
  408. response->set_cors_exposed_header_name_list(move(unique_header_names));
  409. }
  410. // 3. Otherwise, if headerNames is not null or failure, then set response’s CORS-exposed
  411. // header-name list to headerNames.
  412. else if (!header_names.is_empty()) {
  413. response->set_cors_exposed_header_name_list(move(header_names));
  414. }
  415. }
  416. // 2. Set response to the following filtered response with response as its internal response, depending
  417. // on request’s response tainting:
  418. response = [&]() -> JS::NonnullGCPtr<Infrastructure::Response> {
  419. switch (request->response_tainting()) {
  420. // -> "basic"
  421. case Infrastructure::Request::ResponseTainting::Basic:
  422. // basic filtered response
  423. return Infrastructure::BasicFilteredResponse::create(vm, *response);
  424. // -> "cors"
  425. case Infrastructure::Request::ResponseTainting::CORS:
  426. // CORS filtered response
  427. return Infrastructure::CORSFilteredResponse::create(vm, *response);
  428. // -> "opaque"
  429. case Infrastructure::Request::ResponseTainting::Opaque:
  430. // opaque filtered response
  431. return Infrastructure::OpaqueFilteredResponse::create(vm, *response);
  432. default:
  433. VERIFY_NOT_REACHED();
  434. }
  435. }();
  436. }
  437. // 15. Let internalResponse be response, if response is a network error, and response’s internal response
  438. // otherwise.
  439. auto internal_response = response->is_network_error()
  440. ? JS::NonnullGCPtr { *response }
  441. : static_cast<Infrastructure::FilteredResponse&>(*response).internal_response();
  442. // 16. If internalResponse’s URL list is empty, then set it to a clone of request’s URL list.
  443. // NOTE: A response’s URL list can be empty (for example, when the response represents an about URL).
  444. if (internal_response->url_list().is_empty())
  445. internal_response->set_url_list(request->url_list());
  446. // 17. If request has a redirect-tainted origin, then set internalResponse’s has-cross-origin-redirects to true.
  447. if (request->has_redirect_tainted_origin())
  448. internal_response->set_has_cross_origin_redirects(true);
  449. // 18. If request’s timing allow failed flag is unset, then set internalResponse’s timing allow passed flag.
  450. if (!request->timing_allow_failed())
  451. internal_response->set_timing_allow_passed(true);
  452. // 19. If response is not a network error and any of the following returns blocked
  453. if (!response->is_network_error() && (
  454. // - should internalResponse to request be blocked as mixed content
  455. MixedContent::should_response_to_request_be_blocked_as_mixed_content(request, internal_response) == Infrastructure::RequestOrResponseBlocking::Blocked
  456. // FIXME: - should internalResponse to request be blocked by Content Security Policy
  457. || false
  458. // - should internalResponse to request be blocked due to its MIME type
  459. || Infrastructure::should_response_to_request_be_blocked_due_to_its_mime_type(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked
  460. // - should internalResponse to request be blocked due to nosniff
  461. || Infrastructure::should_response_to_request_be_blocked_due_to_nosniff(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked)) {
  462. // then set response and internalResponse to a network error.
  463. response = internal_response = Infrastructure::Response::network_error(vm, "Response was blocked"_string);
  464. }
  465. // 20. If response’s type is "opaque", internalResponse’s status is 206, internalResponse’s range-requested
  466. // flag is set, and request’s header list does not contain `Range`, then set response and
  467. // internalResponse to a network error.
  468. // NOTE: Traditionally, APIs accept a ranged response even if a range was not requested. This prevents a
  469. // partial response from an earlier ranged request being provided to an API that did not make a range
  470. // request.
  471. if (response->type() == Infrastructure::Response::Type::Opaque
  472. && internal_response->status() == 206
  473. && internal_response->range_requested()
  474. && !request->header_list()->contains("Range"sv.bytes())) {
  475. response = internal_response = Infrastructure::Response::network_error(vm, "Response has status 206 and 'range-requested' flag set, but request has no 'Range' header"_string);
  476. }
  477. // 21. If response is not a network error and either request’s method is `HEAD` or `CONNECT`, or
  478. // internalResponse’s status is a null body status, set internalResponse’s body to null and disregard
  479. // any enqueuing toward it (if any).
  480. // NOTE: This standardizes the error handling for servers that violate HTTP.
  481. if (!response->is_network_error() && (StringView { request->method() }.is_one_of("HEAD"sv, "CONNECT"sv) || Infrastructure::is_null_body_status(internal_response->status())))
  482. internal_response->set_body({});
  483. // 22. If request’s integrity metadata is not the empty string, then:
  484. if (!request->integrity_metadata().is_empty()) {
  485. // 1. Let processBodyError be this step: run fetch response handover given fetchParams and a network
  486. // error.
  487. auto process_body_error = JS::create_heap_function(vm.heap(), [&realm, &vm, &fetch_params](JS::Value) {
  488. fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error(vm, "Response body could not be processed"sv));
  489. });
  490. // 2. If response’s body is null, then run processBodyError and abort these steps.
  491. if (!response->body()) {
  492. process_body_error->function()({});
  493. return;
  494. }
  495. // 3. Let processBody given bytes be these steps:
  496. auto process_body = JS::create_heap_function(vm.heap(), [&realm, request, response, &fetch_params, process_body_error = move(process_body_error)](ByteBuffer bytes) {
  497. // 1. If bytes do not match request’s integrity metadata, then run processBodyError and abort these steps.
  498. if (!TRY_OR_IGNORE(SRI::do_bytes_match_metadata_list(bytes, request->integrity_metadata()))) {
  499. process_body_error->function()({});
  500. return;
  501. }
  502. // 2. Set response’s body to bytes as a body.
  503. response->set_body(TRY_OR_IGNORE(Infrastructure::byte_sequence_as_body(realm, bytes)));
  504. // 3. Run fetch response handover given fetchParams and response.
  505. fetch_response_handover(realm, fetch_params, *response);
  506. });
  507. // 4. Fully read response’s body given processBody and processBodyError.
  508. response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
  509. }
  510. // 23. Otherwise, run fetch response handover given fetchParams and response.
  511. else {
  512. fetch_response_handover(realm, fetch_params, *response);
  513. }
  514. });
  515. });
  516. return JS::GCPtr<PendingResponse> {};
  517. }
  518. // https://fetch.spec.whatwg.org/#fetch-finale
  519. void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  520. {
  521. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);
  522. auto& vm = realm.vm();
  523. // 1. Let timingInfo be fetchParams’s timing info.
  524. auto timing_info = fetch_params.timing_info();
  525. // 2. If response is not a network error and fetchParams’s request’s client is a secure context, then set
  526. // timingInfo’s server-timing headers to the result of getting, decoding, and splitting `Server-Timing` from
  527. // response’s header list.
  528. // The user agent may decide to expose `Server-Timing` headers to non-secure contexts requests as well.
  529. auto client = fetch_params.request()->client();
  530. if (!response.is_network_error() && client != nullptr && HTML::is_secure_context(*client)) {
  531. auto server_timing_headers = response.header_list()->get_decode_and_split("Server-Timing"sv.bytes());
  532. if (server_timing_headers.has_value())
  533. timing_info->set_server_timing_headers(server_timing_headers.release_value());
  534. }
  535. // 3. Let processResponseEndOfBody be the following steps:
  536. auto process_response_end_of_body = [&vm, &response, &fetch_params, timing_info] {
  537. // 1. Let unsafeEndTime be the unsafe shared current time.
  538. auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
  539. // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s full timing
  540. // info to fetchParams’s timing info.
  541. if (fetch_params.request()->destination() == Infrastructure::Request::Destination::Document)
  542. fetch_params.controller()->set_full_timing_info(fetch_params.timing_info());
  543. // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
  544. fetch_params.controller()->set_report_timing_steps([&vm, &response, &fetch_params, timing_info, unsafe_end_time](JS::Object const& global) mutable {
  545. // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
  546. if (!Infrastructure::is_http_or_https_scheme(fetch_params.request()->url().scheme()))
  547. return;
  548. // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
  549. timing_info->set_end_time(HighResolutionTime::relative_high_resolution_time(unsafe_end_time, global));
  550. // 3. Let cacheState be response’s cache state.
  551. auto cache_state = response.cache_state();
  552. // 4. Let bodyInfo be response’s body info.
  553. auto body_info = response.body_info();
  554. // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
  555. // opaque timing info for timingInfo, set bodyInfo to a new response body info, and set cacheState to
  556. // the empty string.
  557. // NOTE: This covers the case of response being a network error.
  558. if (!response.timing_allow_passed()) {
  559. timing_info = Infrastructure::create_opaque_timing_info(vm, timing_info);
  560. body_info = Infrastructure::Response::BodyInfo {};
  561. cache_state = {};
  562. }
  563. // 6. Let responseStatus be 0.
  564. auto response_status = 0;
  565. // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
  566. if (fetch_params.request()->mode() != Infrastructure::Request::Mode::Navigate || !response.has_cross_origin_redirects()) {
  567. // 1. Set responseStatus to response’s status.
  568. response_status = response.status();
  569. // 2. Let mimeType be the result of extracting a MIME type from response’s header list.
  570. auto mime_type = response.header_list()->extract_mime_type();
  571. // 3. If mimeType is non-null, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
  572. if (mime_type.has_value())
  573. body_info.content_type = MimeSniff::minimise_a_supported_mime_type(mime_type.value());
  574. }
  575. // FIXME: 8. If fetchParams’s request’s initiator type is not null, then mark resource timing given timingInfo,
  576. // request’s URL, request’s initiator type, global, cacheState, bodyInfo, and responseStatus.
  577. (void)timing_info;
  578. (void)global;
  579. (void)cache_state;
  580. (void)body_info;
  581. (void)response_status;
  582. });
  583. // 4. Let processResponseEndOfBodyTask be the following steps:
  584. auto process_response_end_of_body_task = JS::create_heap_function(vm.heap(), [&fetch_params, &response] {
  585. // 1. Set fetchParams’s request’s done flag.
  586. fetch_params.request()->set_done(true);
  587. // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response
  588. // end-of-body given response.
  589. if (fetch_params.algorithms()->process_response_end_of_body())
  590. (fetch_params.algorithms()->process_response_end_of_body())(response);
  591. // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s global
  592. // object is fetchParams’s task destination, then run fetchParams’s controller’s report timing steps
  593. // given fetchParams’s request’s client’s global object.
  594. auto client = fetch_params.request()->client();
  595. auto const* task_destination_global_object = fetch_params.task_destination().get_pointer<JS::NonnullGCPtr<JS::Object>>();
  596. if (client != nullptr && task_destination_global_object != nullptr) {
  597. if (fetch_params.request()->initiator_type().has_value() && &client->global_object() == task_destination_global_object->ptr())
  598. fetch_params.controller()->report_timing(client->global_object());
  599. }
  600. });
  601. // FIXME: Handle 'parallel queue' task destination
  602. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  603. // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination.
  604. Infrastructure::queue_fetch_task(fetch_params.controller(), task_destination, move(process_response_end_of_body_task));
  605. };
  606. // FIXME: Handle 'parallel queue' task destination
  607. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  608. // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response
  609. // given response, with fetchParams’s task destination.
  610. if (fetch_params.algorithms()->process_response()) {
  611. Infrastructure::queue_fetch_task(fetch_params.controller(), task_destination, JS::create_heap_function(vm.heap(), [&fetch_params, &response]() {
  612. fetch_params.algorithms()->process_response()(response);
  613. }));
  614. }
  615. // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
  616. auto internal_response = response.is_network_error() ? JS::NonnullGCPtr { response } : response.unsafe_response();
  617. // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
  618. if (!internal_response->body()) {
  619. process_response_end_of_body();
  620. }
  621. // 7. Otherwise:
  622. else {
  623. HTML::TemporaryExecutionContext const execution_context { Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  624. // 1. Let transformStream be a new TransformStream.
  625. auto transform_stream = realm.heap().allocate<Streams::TransformStream>(realm, realm);
  626. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
  627. auto identity_transform_algorithm = JS::create_heap_function(realm.heap(), [&realm, transform_stream](JS::Value chunk) -> JS::NonnullGCPtr<WebIDL::Promise> {
  628. MUST(Streams::transform_stream_default_controller_enqueue(*transform_stream->controller(), chunk));
  629. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  630. });
  631. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set
  632. // to processResponseEndOfBody.
  633. auto flush_algorithm = JS::create_heap_function(realm.heap(), [&realm, process_response_end_of_body]() -> JS::NonnullGCPtr<WebIDL::Promise> {
  634. process_response_end_of_body();
  635. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  636. });
  637. Streams::transform_stream_set_up(transform_stream, identity_transform_algorithm, flush_algorithm);
  638. // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
  639. auto promise = Streams::readable_stream_pipe_to(internal_response->body()->stream(), transform_stream->writable(), false, false, false, {});
  640. WebIDL::mark_promise_as_handled(*promise);
  641. internal_response->body()->set_stream(transform_stream->readable());
  642. }
  643. // 8. If fetchParams’s process response consume body is non-null, then:
  644. if (fetch_params.algorithms()->process_response_consume_body()) {
  645. // 1. Let processBody given nullOrBytes be this step: run fetchParams’s process response consume body given
  646. // response and nullOrBytes.
  647. auto process_body = JS::create_heap_function(vm.heap(), [&fetch_params, &response](ByteBuffer null_or_bytes) {
  648. (fetch_params.algorithms()->process_response_consume_body())(response, null_or_bytes);
  649. });
  650. // 2. Let processBodyError be this step: run fetchParams’s process response consume body given response and
  651. // failure.
  652. auto process_body_error = JS::create_heap_function(vm.heap(), [&fetch_params, &response](JS::Value) {
  653. (fetch_params.algorithms()->process_response_consume_body())(response, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
  654. });
  655. // 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with
  656. // fetchParams’s task destination.
  657. if (!internal_response->body()) {
  658. Infrastructure::queue_fetch_task(fetch_params.controller(), task_destination, JS::create_heap_function(vm.heap(), [process_body = move(process_body)]() {
  659. process_body->function()({});
  660. }));
  661. }
  662. // 4. Otherwise, fully read internalResponse body given processBody, processBodyError, and fetchParams’s task
  663. // destination.
  664. else {
  665. internal_response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
  666. }
  667. }
  668. }
  669. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  670. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params)
  671. {
  672. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'scheme fetch' with: fetch_params @ {}", &fetch_params);
  673. auto& vm = realm.vm();
  674. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  675. if (fetch_params.is_canceled())
  676. return PendingResponse::create(vm, fetch_params.request(), Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  677. // 2. Let request be fetchParams’s request.
  678. auto request = fetch_params.request();
  679. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  680. // -> "about"
  681. if (request->current_url().scheme() == "about"sv) {
  682. // If request’s current URL’s path is the string "blank", then return a new response whose status message is
  683. // `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », and body is the empty byte sequence as
  684. // a body.
  685. // NOTE: URLs such as "about:config" are handled during navigation and result in a network error in the context
  686. // of fetching.
  687. if (request->current_url().paths().size() == 1 && request->current_url().paths()[0] == "blank"sv) {
  688. auto response = Infrastructure::Response::create(vm);
  689. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  690. auto header = Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=utf-8"sv);
  691. response->header_list()->append(move(header));
  692. response->set_body(MUST(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes())));
  693. return PendingResponse::create(vm, request, response);
  694. }
  695. // FIXME: This is actually wrong, see note above.
  696. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  697. }
  698. // -> "blob"
  699. else if (request->current_url().scheme() == "blob"sv) {
  700. // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
  701. auto const& blob_url_entry = request->current_url().blob_url_entry();
  702. // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s object is not a Blob object,
  703. // then return a network error. [FILEAPI]
  704. if (request->method() != "GET"sv.bytes() || !blob_url_entry.has_value()) {
  705. // FIXME: Handle "blobURLEntry’s object is not a Blob object". It could be a MediaSource object, but we
  706. // have not yet implemented the Media Source Extensions spec.
  707. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has an invalid 'blob:' URL"sv));
  708. }
  709. // 3. Let blob be blobURLEntry’s object.
  710. auto const blob = FileAPI::Blob::create(realm, blob_url_entry.value().byte_buffer, blob_url_entry.value().type);
  711. // 4. Let response be a new response.
  712. auto response = Infrastructure::Response::create(vm);
  713. // 5. Let fullLength be blob’s size.
  714. auto full_length = blob->size();
  715. // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
  716. auto serialized_full_length = String::number(full_length);
  717. // 7. Let type be blob’s type.
  718. auto const& type = blob->type();
  719. // 8. If request’s header list does not contain `Range`:
  720. if (!request->header_list()->contains("Range"sv.bytes())) {
  721. // 1. Let bodyWithType be the result of safely extracting blob.
  722. auto body_with_type = TRY(safely_extract_body(realm, blob->raw_bytes()));
  723. // 2. Set response’s status message to `OK`.
  724. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  725. // 3. Set response’s body to bodyWithType’s body.
  726. response->set_body(move(body_with_type.body));
  727. // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
  728. auto content_length_header = Infrastructure::Header::from_string_pair("Content-Length"sv, serialized_full_length);
  729. response->header_list()->append(move(content_length_header));
  730. auto content_type_header = Infrastructure::Header::from_string_pair("Content-Type"sv, type);
  731. response->header_list()->append(move(content_type_header));
  732. }
  733. // FIXME: 9. Otherwise:
  734. else {
  735. // 1. Set response’s range-requested flag.
  736. // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
  737. // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
  738. // 4. If rangeValue is failure, then return a network error.
  739. // 5. Let (rangeStart, rangeEnd) be rangeValue.
  740. // 6. If rangeStart is null:
  741. // 1. Set rangeStart to fullLength − rangeEnd.
  742. // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
  743. // 7. Otherwise:
  744. // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
  745. // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set rangeEnd to fullLength − 1.
  746. // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, rangeEnd + 1, and type.
  747. // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
  748. // 10. Set response’s body to slicedBodyWithType’s body.
  749. // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
  750. // 12. Let contentRange be `bytes `.
  751. // 13. Append rangeStart, serialized and isomorphic encoded, to contentRange.
  752. // 14. Append 0x2D (-) to contentRange.
  753. // 15. Append rangeEnd, serialized and isomorphic encoded to contentRange.
  754. // 16. Append 0x2F (/) to contentRange.
  755. // 17. Append serializedFullLength to contentRange.
  756. // 18. Set response’s status to 206.
  757. // 19. Set response’s status message to `Partial Content`.
  758. // 20. Set response’s header list to « (`Content-Length`, serializedSlicedLength), (`Content-Type`, type), (`Content-Range`, contentRange) ».
  759. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has a 'blob:' URL with a Content-Range header, which is currently unsupported"sv));
  760. }
  761. // 10. Return response.
  762. return PendingResponse::create(vm, request, response);
  763. }
  764. // -> "data"
  765. else if (request->current_url().scheme() == "data"sv) {
  766. // 1. Let dataURLStruct be the result of running the data: URL processor on request’s current URL.
  767. auto data_url_struct = Infrastructure::process_data_url(request->current_url());
  768. // 2. If dataURLStruct is failure, then return a network error.
  769. if (data_url_struct.is_error())
  770. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Failed to process 'data:' URL"sv));
  771. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  772. auto const& mime_type = data_url_struct.value().mime_type.serialized();
  773. // 4. Return a new response whose status message is `OK`, header list is « (`Content-Type`, mimeType) », and
  774. // body is dataURLStruct’s body as a body.
  775. auto response = Infrastructure::Response::create(vm);
  776. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  777. auto header = Infrastructure::Header::from_string_pair("Content-Type"sv, mime_type);
  778. response->header_list()->append(move(header));
  779. response->set_body(TRY(Infrastructure::byte_sequence_as_body(realm, data_url_struct.value().body)));
  780. return PendingResponse::create(vm, request, response);
  781. }
  782. // -> "file"
  783. // AD-HOC: "resource"
  784. else if (request->current_url().scheme() == "file"sv || request->current_url().scheme() == "resource"sv) {
  785. // For now, unfortunate as it is, file: URLs are left as an exercise for the reader.
  786. // When in doubt, return a network error.
  787. if (request->origin().has<URL::Origin>() && (request->origin().get<URL::Origin>().is_opaque() || request->origin().get<URL::Origin>().scheme() == "file"sv || request->origin().get<URL::Origin>().scheme() == "resource"sv))
  788. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  789. else
  790. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'file:' or 'resource:' URL blocked"sv));
  791. }
  792. // -> HTTP(S) scheme
  793. else if (Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  794. // Return the result of running HTTP fetch given fetchParams.
  795. return http_fetch(realm, fetch_params);
  796. }
  797. // 4. Return a network error.
  798. auto message = request->current_url().scheme() == "about"sv
  799. ? "Request has invalid 'about:' URL, only 'about:blank' can be fetched"_string
  800. : "Request URL has invalid scheme, must be one of 'about', 'blob', 'data', 'file', 'http', or 'https'"_string;
  801. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, move(message)));
  802. }
  803. // https://fetch.spec.whatwg.org/#concept-http-fetch
  804. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, MakeCORSPreflight make_cors_preflight)
  805. {
  806. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' with: fetch_params @ {}, make_cors_preflight = {}",
  807. &fetch_params, make_cors_preflight == MakeCORSPreflight::Yes ? "Yes"sv : "No"sv);
  808. auto& vm = realm.vm();
  809. // 1. Let request be fetchParams’s request.
  810. auto request = fetch_params.request();
  811. // 2. Let response and internalResponse be null.
  812. JS::GCPtr<Infrastructure::Response> response;
  813. JS::GCPtr<Infrastructure::Response> internal_response;
  814. // 3. If request’s service-workers mode is "all", then:
  815. if (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {
  816. // 1. Let requestForServiceWorker be a clone of request.
  817. auto request_for_service_worker = request->clone(realm);
  818. // 2. If requestForServiceWorker’s body is non-null, then:
  819. if (!request_for_service_worker->body().has<Empty>()) {
  820. // FIXME: 1. Let transformStream be a new TransformStream.
  821. // FIXME: 2. Let transformAlgorithm given chunk be these steps:
  822. // FIXME: 3. Set up transformStream with transformAlgorithm set to transformAlgorithm.
  823. // FIXME: 4. Set requestForServiceWorker’s body’s stream to the result of requestForServiceWorker’s body’s stream
  824. // piped through transformStream.
  825. }
  826. // 3. Let serviceWorkerStartTime be the coarsened shared current time given fetchParams’s cross-origin isolated
  827. // capability.
  828. auto service_worker_start_time = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  829. // FIXME: 4. Set response to the result of invoking handle fetch for requestForServiceWorker, with fetchParams’s
  830. // controller and fetchParams’s cross-origin isolated capability.
  831. // 5. If response is non-null, then:
  832. if (response) {
  833. // 1. Set fetchParams’s timing info’s final service worker start time to serviceWorkerStartTime.
  834. fetch_params.timing_info()->set_final_service_worker_start_time(service_worker_start_time);
  835. // 2. If request’s body is non-null, then cancel request’s body with undefined.
  836. if (!request->body().has<Empty>()) {
  837. // FIXME: Implement cancelling streams
  838. }
  839. // 3. Set internalResponse to response, if response is not a filtered response; otherwise to response’s
  840. // internal response.
  841. internal_response = !is<Infrastructure::FilteredResponse>(*response)
  842. ? JS::NonnullGCPtr { *response }
  843. : static_cast<Infrastructure::FilteredResponse const&>(*response).internal_response();
  844. // 4. If one of the following is true
  845. if (
  846. // - response’s type is "error"
  847. response->type() == Infrastructure::Response::Type::Error
  848. // - request’s mode is "same-origin" and response’s type is "cors"
  849. || (request->mode() == Infrastructure::Request::Mode::SameOrigin && response->type() == Infrastructure::Response::Type::CORS)
  850. // - request’s mode is not "no-cors" and response’s type is "opaque"
  851. || (request->mode() != Infrastructure::Request::Mode::NoCORS && response->type() == Infrastructure::Response::Type::Opaque)
  852. // - request’s redirect mode is not "manual" and response’s type is "opaqueredirect"
  853. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Manual && response->type() == Infrastructure::Response::Type::OpaqueRedirect)
  854. // - request’s redirect mode is not "follow" and response’s URL list has more than one item.
  855. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow && response->url_list().size() > 1)) {
  856. // then return a network error.
  857. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Invalid request/response state combination"sv));
  858. }
  859. }
  860. }
  861. JS::GCPtr<PendingResponse> pending_actual_response;
  862. auto returned_pending_response = PendingResponse::create(vm, request);
  863. // 4. If response is null, then:
  864. if (!response) {
  865. // 1. If makeCORSPreflight is true and one of these conditions is true:
  866. // NOTE: This step checks the CORS-preflight cache and if there is no suitable entry it performs a
  867. // CORS-preflight fetch which, if successful, populates the cache. The purpose of the CORS-preflight
  868. // fetch is to ensure the fetched resource is familiar with the CORS protocol. The cache is there to
  869. // minimize the number of CORS-preflight fetches.
  870. JS::GCPtr<PendingResponse> pending_preflight_response;
  871. if (make_cors_preflight == MakeCORSPreflight::Yes && (
  872. // - There is no method cache entry match for request’s method using request, and either request’s
  873. // method is not a CORS-safelisted method or request’s use-CORS-preflight flag is set.
  874. // FIXME: We currently have no cache, so there will always be no method cache entry.
  875. (!Infrastructure::is_cors_safelisted_method(request->method()) || request->use_cors_preflight())
  876. // - There is at least one item in the CORS-unsafe request-header names with request’s header list for
  877. // which there is no header-name cache entry match using request.
  878. // FIXME: We currently have no cache, so there will always be no header-name cache entry.
  879. || !Infrastructure::get_cors_unsafe_header_names(request->header_list()).is_empty())) {
  880. // 1. Let preflightResponse be the result of running CORS-preflight fetch given request.
  881. pending_preflight_response = TRY(cors_preflight_fetch(realm, request));
  882. // NOTE: Step 2 is performed in pending_preflight_response's load callback below.
  883. }
  884. 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>> {
  885. // 2. If request’s redirect mode is "follow", then set request’s service-workers mode to "none".
  886. // NOTE: Redirects coming from the network (as opposed to from a service worker) are not to be exposed to a
  887. // service worker.
  888. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Follow)
  889. request->set_service_workers_mode(Infrastructure::Request::ServiceWorkersMode::None);
  890. // 3. Set response and internalResponse to the result of running HTTP-network-or-cache fetch given fetchParams.
  891. return http_network_or_cache_fetch(*realm, *fetch_params);
  892. };
  893. if (pending_preflight_response) {
  894. pending_actual_response = PendingResponse::create(vm, request);
  895. pending_preflight_response->when_loaded([returned_pending_response, pending_actual_response, fetch_main_content = move(fetch_main_content)](JS::NonnullGCPtr<Infrastructure::Response> preflight_response) {
  896. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_preflight_response load callback");
  897. // 2. If preflightResponse is a network error, then return preflightResponse.
  898. if (preflight_response->is_network_error()) {
  899. returned_pending_response->resolve(preflight_response);
  900. return;
  901. }
  902. auto pending_main_content_response = TRY_OR_IGNORE(fetch_main_content());
  903. pending_main_content_response->when_loaded([pending_actual_response](JS::NonnullGCPtr<Infrastructure::Response> main_content_response) {
  904. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_main_content_response load callback");
  905. pending_actual_response->resolve(main_content_response);
  906. });
  907. });
  908. } else {
  909. pending_actual_response = TRY(fetch_main_content());
  910. }
  911. } else {
  912. pending_actual_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  913. }
  914. pending_actual_response->when_loaded([&realm, &vm, &fetch_params, request, response, internal_response, returned_pending_response, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_actual_response) mutable {
  915. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_actual_response load callback");
  916. if (response_was_null) {
  917. response = internal_response = resolved_actual_response;
  918. // 4. If request’s response tainting is "cors" and a CORS check for request and response returns failure,
  919. // then return a network error.
  920. // NOTE: As the CORS check is not to be applied to responses whose status is 304 or 407, or responses from
  921. // a service worker for that matter, it is applied here.
  922. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS
  923. && !cors_check(request, *response)) {
  924. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request with 'cors' response tainting failed CORS check"_string));
  925. return;
  926. }
  927. // 5. If the TAO check for request and response returns failure, then set request’s timing allow failed flag.
  928. if (!tao_check(request, *response))
  929. request->set_timing_allow_failed(true);
  930. }
  931. // 5. If either request’s response tainting or response’s type is "opaque", and the cross-origin resource
  932. // policy check with request’s origin, request’s client, request’s destination, and internalResponse returns
  933. // blocked, then return a network error.
  934. // NOTE: The cross-origin resource policy check runs for responses coming from the network and responses coming
  935. // from the service worker. This is different from the CORS check, as request’s client and the service
  936. // worker can have different embedder policies.
  937. if ((request->response_tainting() == Infrastructure::Request::ResponseTainting::Opaque || response->type() == Infrastructure::Response::Type::Opaque)
  938. && false // FIXME: "and the cross-origin resource policy check with request’s origin, request’s client, request’s destination, and actualResponse returns blocked"
  939. ) {
  940. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Response was blocked by cross-origin resource policy check"_string));
  941. return;
  942. }
  943. JS::GCPtr<PendingResponse> inner_pending_response;
  944. // 6. If internalResponse’s status is a redirect status:
  945. if (Infrastructure::is_redirect_status(internal_response->status())) {
  946. // FIXME: 1. If internalResponse’s status is not 303, request’s body is non-null, and the connection uses HTTP/2,
  947. // then user agents may, and are even encouraged to, transmit an RST_STREAM frame.
  948. // NOTE: 303 is excluded as certain communities ascribe special status to it.
  949. // 2. Switch on request’s redirect mode:
  950. switch (request->redirect_mode()) {
  951. // -> "error"
  952. case Infrastructure::Request::RedirectMode::Error:
  953. // 1. Set response to a network error.
  954. response = Infrastructure::Response::network_error(vm, "Request with 'error' redirect mode received redirect response"_string);
  955. break;
  956. // -> "manual"
  957. case Infrastructure::Request::RedirectMode::Manual:
  958. // 1. If request’s mode is "navigate", then set fetchParams’s controller’s next manual redirect steps
  959. // to run HTTP-redirect fetch given fetchParams and response.
  960. if (request->mode() == Infrastructure::Request::Mode::Navigate) {
  961. fetch_params.controller()->set_next_manual_redirect_steps([&realm, &fetch_params, response] {
  962. (void)http_redirect_fetch(realm, fetch_params, *response);
  963. });
  964. }
  965. // 2. Otherwise, set response to an opaque-redirect filtered response whose internal response is
  966. // internalResponse.
  967. else {
  968. response = Infrastructure::OpaqueRedirectFilteredResponse::create(vm, *internal_response);
  969. }
  970. break;
  971. // -> "follow"
  972. case Infrastructure::Request::RedirectMode::Follow:
  973. // 1. Set response to the result of running HTTP-redirect fetch given fetchParams and response.
  974. inner_pending_response = TRY_OR_IGNORE(http_redirect_fetch(realm, fetch_params, *response));
  975. break;
  976. default:
  977. VERIFY_NOT_REACHED();
  978. }
  979. }
  980. if (inner_pending_response) {
  981. inner_pending_response->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  982. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' inner_pending_response load callback");
  983. returned_pending_response->resolve(response);
  984. });
  985. } else {
  986. returned_pending_response->resolve(*response);
  987. }
  988. });
  989. // 7. Return response.
  990. // NOTE: Typically internalResponse’s body’s stream is still being enqueued to after returning.
  991. return returned_pending_response;
  992. }
  993. // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch
  994. WebIDL::ExceptionOr<JS::GCPtr<PendingResponse>> http_redirect_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  995. {
  996. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-redirect fetch' with: fetch_params @ {}, response = {}", &fetch_params, &response);
  997. auto& vm = realm.vm();
  998. // 1. Let request be fetchParams’s request.
  999. auto request = fetch_params.request();
  1000. // 2. Let internalResponse be response, if response is not a filtered response; otherwise response’s internal
  1001. // response.
  1002. auto internal_response = !is<Infrastructure::FilteredResponse>(response)
  1003. ? JS::NonnullGCPtr { response }
  1004. : static_cast<Infrastructure::FilteredResponse const&>(response).internal_response();
  1005. // 3. Let locationURL be internalResponse’s location URL given request’s current URL’s fragment.
  1006. auto location_url_or_error = internal_response->location_url(request->current_url().fragment());
  1007. // 4. If locationURL is null, then return response.
  1008. if (!location_url_or_error.is_error() && !location_url_or_error.value().has_value())
  1009. return PendingResponse::create(vm, request, response);
  1010. // 5. If locationURL is failure, then return a network error.
  1011. if (location_url_or_error.is_error())
  1012. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL is invalid"sv));
  1013. auto location_url = location_url_or_error.release_value().release_value();
  1014. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network error.
  1015. if (!Infrastructure::is_http_or_https_scheme(location_url.scheme()))
  1016. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL must have HTTP or HTTPS scheme"sv));
  1017. // 7. If request’s redirect count is 20, then return a network error.
  1018. if (request->redirect_count() == 20)
  1019. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has reached maximum redirect count of 20"sv));
  1020. // 8. Increase request’s redirect count by 1.
  1021. request->set_redirect_count(request->redirect_count() + 1);
  1022. // 9. If request’s mode is "cors", locationURL includes credentials, and request’s origin is not same origin with
  1023. // locationURL’s origin, then return a network error.
  1024. if (request->mode() == Infrastructure::Request::Mode::CORS
  1025. && location_url.includes_credentials()
  1026. && request->origin().has<URL::Origin>()
  1027. && !request->origin().get<URL::Origin>().is_same_origin(location_url.origin())) {
  1028. 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));
  1029. }
  1030. // 10. If request’s response tainting is "cors" and locationURL includes credentials, then return a network error.
  1031. // NOTE: This catches a cross-origin resource redirecting to a same-origin URL.
  1032. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS && location_url.includes_credentials())
  1033. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' response tainting must not include credentials in redirect URL"sv));
  1034. // 11. If internalResponse’s status is not 303, request’s body is non-null, and request’s body’s source is null, then
  1035. // return a network error.
  1036. if (internal_response->status() != 303
  1037. && !request->body().has<Empty>()
  1038. && request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) {
  1039. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has body but no body source"sv));
  1040. }
  1041. // 12. If one of the following is true
  1042. if (
  1043. // - internalResponse’s status is 301 or 302 and request’s method is `POST`
  1044. ((internal_response->status() == 301 || internal_response->status() == 302) && request->method() == "POST"sv.bytes())
  1045. // - internalResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  1046. || (internal_response->status() == 303 && !(request->method() == "GET"sv.bytes() || request->method() == "HEAD"sv.bytes()))
  1047. // then:
  1048. ) {
  1049. // 1. Set request’s method to `GET` and request’s body to null.
  1050. request->set_method(MUST(ByteBuffer::copy("GET"sv.bytes())));
  1051. request->set_body({});
  1052. static constexpr Array request_body_header_names {
  1053. "Content-Encoding"sv,
  1054. "Content-Language"sv,
  1055. "Content-Location"sv,
  1056. "Content-Type"sv
  1057. };
  1058. // 2. For each headerName of request-body-header name, delete headerName from request’s header list.
  1059. for (auto header_name : request_body_header_names.span())
  1060. request->header_list()->delete_(header_name.bytes());
  1061. }
  1062. // 13. If request’s current URL’s origin is not same origin with locationURL’s origin, then for each headerName of
  1063. // CORS non-wildcard request-header name, delete headerName from request’s header list.
  1064. // NOTE: I.e., the moment another origin is seen after the initial request, the `Authorization` header is removed.
  1065. if (!request->current_url().origin().is_same_origin(location_url.origin())) {
  1066. static constexpr Array cors_non_wildcard_request_header_names {
  1067. "Authorization"sv
  1068. };
  1069. for (auto header_name : cors_non_wildcard_request_header_names)
  1070. request->header_list()->delete_(header_name.bytes());
  1071. }
  1072. // 14. If request’s body is non-null, then set request’s body to the body of the result of safely extracting
  1073. // request’s body’s source.
  1074. // NOTE: request’s body’s source’s nullity has already been checked.
  1075. if (!request->body().has<Empty>()) {
  1076. auto const& source = request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source();
  1077. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  1078. auto converted_source = source.has<ByteBuffer>()
  1079. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  1080. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  1081. auto [body, _] = TRY(safely_extract_body(realm, converted_source));
  1082. request->set_body(move(body));
  1083. }
  1084. // 15. Let timingInfo be fetchParams’s timing info.
  1085. auto timing_info = fetch_params.timing_info();
  1086. // 16. Set timingInfo’s redirect end time and post-redirect start time to the coarsened shared current time given
  1087. // fetchParams’s cross-origin isolated capability.
  1088. auto now = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  1089. timing_info->set_redirect_end_time(now);
  1090. timing_info->set_post_redirect_start_time(now);
  1091. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s redirect start time to timingInfo’s start
  1092. // time.
  1093. if (timing_info->redirect_start_time() == 0)
  1094. timing_info->set_redirect_start_time(timing_info->start_time());
  1095. // 18. Append locationURL to request’s URL list.
  1096. request->url_list().append(location_url);
  1097. // 19. Invoke set request’s referrer policy on redirect on request and internalResponse.
  1098. ReferrerPolicy::set_request_referrer_policy_on_redirect(request, internal_response);
  1099. // 20. Let recursive be true.
  1100. auto recursive = Recursive::Yes;
  1101. // 21. If request’s redirect mode is "manual", then:
  1102. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Manual) {
  1103. // 1. Assert: request’s mode is "navigate".
  1104. VERIFY(request->mode() == Infrastructure::Request::Mode::Navigate);
  1105. // 2. Set recursive to false.
  1106. recursive = Recursive::No;
  1107. }
  1108. // 22. Return the result of running main fetch given fetchParams and recursive.
  1109. return main_fetch(realm, fetch_params, recursive);
  1110. }
  1111. class CachedResponse : public RefCounted<CachedResponse> {
  1112. public:
  1113. HTTP::HeaderMap headers;
  1114. ByteBuffer body;
  1115. Infrastructure::Response::BodyInfo body_info;
  1116. ByteBuffer method;
  1117. Infrastructure::Status status;
  1118. URL::URL url;
  1119. UnixDateTime current_age;
  1120. };
  1121. class CachePartition : public RefCounted<CachePartition> {
  1122. public:
  1123. // https://httpwg.org/specs/rfc9111.html#constructing.responses.from.caches
  1124. JS::GCPtr<Infrastructure::Response> select_response(JS::Realm& realm, URL::URL const& url, ReadonlyBytes method, Vector<Infrastructure::Header> const& headers) const
  1125. {
  1126. // When presented with a request, a cache MUST NOT reuse a stored response unless:
  1127. // - the presented target URI (Section 7.1 of [HTTP]) and that of the stored response match, and
  1128. auto it = m_cache.find(url);
  1129. if (it == m_cache.end()) {
  1130. dbgln("\033[31;1mHTTP CACHE MISS!\033[0m {}", url);
  1131. return {};
  1132. }
  1133. auto const& cached_response = *it->value;
  1134. // - the request method associated with the stored response allows it to be used for the presented request, and
  1135. if (method != cached_response.method) {
  1136. dbgln("\033[31;1mHTTP CACHE MISS!\033[0m (Bad method) {}", url);
  1137. return {};
  1138. }
  1139. // FIXME: - request header fields nominated by the stored response (if any) match those presented (see Section 4.1), and
  1140. (void)headers;
  1141. // FIXME: - the stored response does not contain the no-cache directive (Section 5.2.2.4), unless it is successfully validated (Section 4.3), and
  1142. // FIXME: Any remaining responses at this point should be saved as "The initial set of stored responses", for use in `freshen_stored_responses_upon_validation`.
  1143. // FIXME: - the stored response is one of the following:
  1144. // + fresh (see Section 4.2), or
  1145. // + allowed to be served stale (see Section 4.2.4), or
  1146. // + successfully validated (see Section 4.3).
  1147. dbgln("\033[32;1mHTTP CACHE HIT!\033[0m {}", url);
  1148. // FIXME: It appears that the spec intends this operation to return a reference to the stored response, rather than a copy.
  1149. // This is because some (or all?) state changes of the returned response should be propagated to the stored response as well.
  1150. // This is noticable in `freshen_stored_responses_upon_validation`, which must currently change both the content of the response
  1151. // returned by this function as well as the cached_response.
  1152. auto [body, _] = MUST(extract_body(realm, ReadonlyBytes(cached_response.body)));
  1153. auto response = Infrastructure::Response::create(realm.vm());
  1154. response->set_body(body);
  1155. response->set_body_info(cached_response.body_info);
  1156. response->set_status(cached_response.status);
  1157. for (auto& [name, value] : cached_response.headers.headers()) {
  1158. response->header_list()->append(Infrastructure::Header::from_string_pair(name, value));
  1159. }
  1160. return response;
  1161. }
  1162. void store_response(Infrastructure::Request const& http_request, Infrastructure::Response const& response)
  1163. {
  1164. if (!is_cacheable(http_request, response))
  1165. return;
  1166. auto cached_response = adopt_ref(*new CachedResponse);
  1167. store_header_and_trailer_fields(response, cached_response->headers);
  1168. cached_response->body = response.body()->source().get<ByteBuffer>();
  1169. cached_response->body_info = response.body_info();
  1170. cached_response->method = MUST(ByteBuffer::copy(http_request.method()));
  1171. cached_response->status = response.status();
  1172. cached_response->url = http_request.current_url();
  1173. cached_response->current_age = UnixDateTime::now();
  1174. m_cache.set(http_request.current_url(), move(cached_response));
  1175. }
  1176. // https://httpwg.org/specs/rfc9111.html#freshening.responses
  1177. void freshen_stored_responses_upon_validation(Infrastructure::Request const& http_request, Infrastructure::Response const& response, Infrastructure::Response& stored_response)
  1178. {
  1179. // When a cache receives a 304 (Not Modified) response, it needs to identify stored
  1180. // responses that are suitable for updating with the new information provided, and then do so.
  1181. // The initial set of stored responses to update are those that could have been
  1182. // chosen for that request — i.e., those that meet the requirements in Section 4,
  1183. // except the last requirement to be fresh, able to be served stale, or just validated.
  1184. // NOTE: This corresponds to the logic in `select_response`.
  1185. auto it = m_cache.find(http_request.current_url());
  1186. if (it == m_cache.end())
  1187. return;
  1188. // Then, that initial set of stored responses is further filtered by the first match of:
  1189. // - FIXME: If the new response contains one or more strong validators (see Section 8.8.1 of [HTTP]),
  1190. // then each of those strong validators identifies a selected representation for update.
  1191. // All the stored responses in the initial set with one of those same strong validators
  1192. // are identified for update.
  1193. // If none of the initial set contains at least one of the same strong validators,
  1194. // then the cache MUST NOT use the new response to update any stored responses.
  1195. // - FIXME: If the new response contains no strong validators but does contain one or more weak validators,
  1196. // and those validators correspond to one of the initial set's stored responses,
  1197. // then the most recent of those matching stored responses is identified for update.
  1198. // - FIXME: If the new response does not include any form of validator (such as where a client generates an
  1199. // `If-Modified-Since` request from a source other than the `Last-Modified` response header field),
  1200. // and there is only one stored response in the initial set, and that stored response also lacks a validator,
  1201. // then that stored response is identified for update.
  1202. // For each stored response identified, the cache MUST update its header fields
  1203. // with the header fields provided in the 304 (Not Modified) response, as per Section 3.2.
  1204. auto& cached_response = *it->value;
  1205. update_stored_header_fields(response, cached_response.headers);
  1206. // FIXME: We shouldn't have to update the same response twice,
  1207. // and the intention of the spec seems to be that `stored_response == cached_response` here.
  1208. // They are not, because the response gets copied in `select_response`.
  1209. update_header_fields_for_stored_response(response, stored_response);
  1210. }
  1211. private:
  1212. // https://httpwg.org/specs/rfc9111.html#storing.fields
  1213. bool is_exempted_for_storage(StringView header_name)
  1214. {
  1215. // Caches MUST include all received response header fields — including unrecognized ones — when storing a response;
  1216. // this assures that new HTTP header fields can be successfully deployed. However, the following exceptions are made:
  1217. // - The Connection header field and fields whose names are listed in it are required by Section 7.6.1 of [HTTP]
  1218. // to be removed before forwarding the message. This MAY be implemented by doing so before storage.
  1219. // - Likewise, some fields' semantics require them to be removed before forwarding the message, and this MAY be
  1220. // implemented by doing so before storage; see Section 7.6.1 of [HTTP] for some examples.
  1221. // FIXME: - The no-cache (Section 5.2.2.4) and private (Section 5.2.2.7) cache directives can have arguments that
  1222. // prevent storage of header fields by all caches and shared caches, respectively.
  1223. // FIXME: - Header fields that are specific to the proxy that a cache uses when forwarding a request MUST NOT be stored,
  1224. // unless the cache incorporates the identity of the proxy into the cache key.
  1225. // Effectively, this is limited to Proxy-Authenticate (Section 11.7.1 of [HTTP]), Proxy-Authentication-Info (Section 11.7.3 of [HTTP]), and Proxy-Authorization (Section 11.7.2 of [HTTP]).
  1226. return header_name.is_one_of_ignoring_ascii_case(
  1227. "Connection"sv,
  1228. "Proxy-Connection"sv,
  1229. "Keep-Alive"sv,
  1230. "TE"sv,
  1231. "Transfer-Encoding"sv,
  1232. "Upgrade"sv);
  1233. }
  1234. // https://httpwg.org/specs/rfc9111.html#update
  1235. bool is_exempted_for_updating(StringView header_name)
  1236. {
  1237. // Caches are required to update a stored response's header fields from another
  1238. // (typically newer) response in several situations; for example, see Sections 3.4, 4.3.4, and 4.3.5.
  1239. // When doing so, the cache MUST add each header field in the provided response to the stored response,
  1240. // replacing field values that are already present, with the following exceptions:
  1241. // - Header fields excepted from storage in Section 3.1,
  1242. return is_exempted_for_storage(header_name)
  1243. // - Header fields that the cache's stored response depends upon, as described below,
  1244. || false
  1245. // - Header fields that are automatically processed and removed by the recipient, as described below, and
  1246. || false
  1247. // - The Content-Length header field.
  1248. || header_name.equals_ignoring_ascii_case("Content-Length"sv);
  1249. // In some cases, caches (especially in user agents) store the results of processing
  1250. // the received response, rather than the response itself, and updating header fields
  1251. // that affect that processing can result in inconsistent behavior and security issues.
  1252. // Caches in this situation MAY omit these header fields from updating stored responses
  1253. // on an exceptional basis but SHOULD limit such omission to those fields necessary to
  1254. // assure integrity of the stored response.
  1255. // For example, a browser might decode the content coding of a response while it is being received,
  1256. // creating a disconnect between the data it has stored and the response's original metadata.
  1257. // Updating that stored metadata with a different Content-Encoding header field would be problematic.
  1258. // Likewise, a browser might store a post-parse HTML tree rather than the content received in the response;
  1259. // updating the Content-Type header field would not be workable in this case because any assumptions about
  1260. // the format made in parsing would now be invalid.
  1261. // Furthermore, some fields are automatically processed and removed by the HTTP implementation,
  1262. // such as the Content-Range header field. Implementations MAY automatically omit such header fields from updates,
  1263. // even when the processing does not actually occur.
  1264. // Note that the Content-* prefix is not a signal that a header field is omitted from update; it is a convention for MIME header fields, not HTTP.
  1265. }
  1266. // https://httpwg.org/specs/rfc9111.html#update
  1267. void update_stored_header_fields(Infrastructure::Response const& response, HTTP::HeaderMap& headers)
  1268. {
  1269. for (auto& header : *response.header_list()) {
  1270. auto name = StringView(header.name);
  1271. if (is_exempted_for_updating(name))
  1272. continue;
  1273. headers.set(ByteString::copy(header.name), ByteString::copy(header.value));
  1274. }
  1275. }
  1276. void update_header_fields_for_stored_response(Infrastructure::Response const& response, Infrastructure::Response& stored_response)
  1277. {
  1278. auto headers = stored_response.header_list();
  1279. for (auto& header : *response.header_list()) {
  1280. auto name = StringView(header.name);
  1281. if (is_exempted_for_updating(name))
  1282. continue;
  1283. headers->set(Infrastructure::Header {
  1284. .name = MUST(ByteBuffer::copy(header.name)),
  1285. .value = MUST(ByteBuffer::copy(header.value)),
  1286. });
  1287. }
  1288. }
  1289. // https://httpwg.org/specs/rfc9111.html#storing.fields
  1290. void store_header_and_trailer_fields(Infrastructure::Response const& response, HTTP::HeaderMap& headers)
  1291. {
  1292. for (auto& header : *response.header_list()) {
  1293. auto name = StringView(header.name);
  1294. if (is_exempted_for_storage(name))
  1295. continue;
  1296. headers.set(ByteString::copy(header.name), ByteString::copy(header.value));
  1297. }
  1298. }
  1299. // https://httpwg.org/specs/rfc9111.html#response.cacheability
  1300. static bool is_cacheable(Infrastructure::Request const& request, Infrastructure::Response const& response)
  1301. {
  1302. // A cache MUST NOT store a response to a request unless:
  1303. // - AD-HOC: For now, we simply don't cache responses without a simple ByteBuffer body.
  1304. if (!response.body() || !response.body()->source().has<ByteBuffer>())
  1305. return false;
  1306. // - the request method is understood by the cache;
  1307. if (request.method() != "GET"sv.bytes() && request.method() != "HEAD"sv.bytes())
  1308. return false;
  1309. // - the response status code is final (see Section 15 of [HTTP]);
  1310. if (response.status() < 200)
  1311. return false;
  1312. // - if the response status code is 206 or 304,
  1313. // or the must-understand cache directive (see Section 5.2.2.3) is present:
  1314. // the cache understands the response status code;
  1315. if (response.status() == 206 || response.status() == 304) {
  1316. // FIXME: Implement must-understand cache directive
  1317. }
  1318. // - the no-store cache directive is not present in the response (see Section 5.2.2.5);
  1319. if (request.cache_mode() == Infrastructure::Request::CacheMode::NoStore)
  1320. return false;
  1321. // FIXME: - if the cache is shared: the private response directive is either not present
  1322. // or allows a shared cache to store a modified response; see Section 5.2.2.7);
  1323. // FIXME: - if the cache is shared: the Authorization header field is not present in the
  1324. // request (see Section 11.6.2 of [HTTP]) or a response directive is present
  1325. // that explicitly allows shared caching (see Section 3.5); and
  1326. // FIXME: - the response contains at least one of the following:
  1327. // + a public response directive (see Section 5.2.2.9);
  1328. // + a private response directive, if the cache is not shared (see Section 5.2.2.7);
  1329. // + an Expires header field (see Section 5.3);
  1330. // + a max-age response directive (see Section 5.2.2.1);
  1331. // + if the cache is shared: an s-maxage response directive (see Section 5.2.2.10);
  1332. // + a cache extension that allows it to be cached (see Section 5.2.3); or
  1333. // + a status code that is defined as heuristically cacheable (see Section 4.2.2).
  1334. return true;
  1335. }
  1336. HashMap<URL::URL, NonnullRefPtr<CachedResponse>> m_cache;
  1337. };
  1338. class HTTPCache {
  1339. public:
  1340. CachePartition& get(Infrastructure::NetworkPartitionKey const& key)
  1341. {
  1342. return *m_cache.ensure(key, [] {
  1343. return adopt_ref(*new CachePartition);
  1344. });
  1345. }
  1346. static HTTPCache& the()
  1347. {
  1348. static HTTPCache s_cache;
  1349. return s_cache;
  1350. }
  1351. private:
  1352. HashMap<Infrastructure::NetworkPartitionKey, NonnullRefPtr<CachePartition>> m_cache;
  1353. };
  1354. // https://fetch.spec.whatwg.org/#determine-the-http-cache-partition
  1355. static RefPtr<CachePartition> determine_the_http_cache_partition(Infrastructure::Request const& request)
  1356. {
  1357. if (!g_http_cache_enabled)
  1358. return nullptr;
  1359. // 1. Let key be the result of determining the network partition key given request.
  1360. auto key = Infrastructure::determine_the_network_partition_key(request);
  1361. // 2. If key is null, then return null.
  1362. if (!key.has_value())
  1363. return nullptr;
  1364. // 3. Return the unique HTTP cache associated with key. [HTTP-CACHING]
  1365. return HTTPCache::the().get(key.value());
  1366. }
  1367. // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
  1368. 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)
  1369. {
  1370. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' with: fetch_params @ {}, is_authentication_fetch = {}, is_new_connection_fetch = {}",
  1371. &fetch_params, is_authentication_fetch == IsAuthenticationFetch::Yes ? "Yes"sv : "No"sv, is_new_connection_fetch == IsNewConnectionFetch::Yes ? "Yes"sv : "No"sv);
  1372. auto& vm = realm.vm();
  1373. // 1. Let request be fetchParams’s request.
  1374. auto request = fetch_params.request();
  1375. // 2. Let httpFetchParams be null.
  1376. JS::GCPtr<Infrastructure::FetchParams const> http_fetch_params;
  1377. // 3. Let httpRequest be null.
  1378. JS::GCPtr<Infrastructure::Request> http_request;
  1379. // 4. Let response be null.
  1380. JS::GCPtr<Infrastructure::Response> response;
  1381. // 5. Let storedResponse be null.
  1382. JS::GCPtr<Infrastructure::Response> stored_response;
  1383. // 6. Let httpCache be null.
  1384. // (Typeless until we actually implement it, needed for checks below)
  1385. RefPtr<CachePartition> http_cache;
  1386. // 7. Let the revalidatingFlag be unset.
  1387. auto revalidating_flag = RefCountedFlag::create(false);
  1388. auto include_credentials = IncludeCredentials::No;
  1389. // 8. Run these steps, but abort when fetchParams is canceled:
  1390. // NOTE: There's an 'if aborted' check after this anyway, so not doing this is fine and only incurs a small delay.
  1391. // For now, support for aborting fetch requests is limited anyway as ResourceLoader doesn't support it.
  1392. auto aborted = false;
  1393. {
  1394. ScopeGuard set_aborted = [&] {
  1395. if (fetch_params.is_canceled())
  1396. aborted = true;
  1397. };
  1398. // 1. If request’s window is "no-window" and request’s redirect mode is "error", then set httpFetchParams to
  1399. // fetchParams and httpRequest to request.
  1400. if (request->window().has<Infrastructure::Request::Window>()
  1401. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow
  1402. && request->redirect_mode() == Infrastructure::Request::RedirectMode::Error) {
  1403. http_fetch_params = fetch_params;
  1404. http_request = request;
  1405. }
  1406. // 2. Otherwise:
  1407. else {
  1408. // 1. Set httpRequest to a clone of request.
  1409. // NOTE: Implementations are encouraged to avoid teeing request’s body’s stream when request’s body’s
  1410. // source is null as only a single body is needed in that case. E.g., when request’s body’s source
  1411. // is null, redirects and authentication will end up failing the fetch.
  1412. http_request = request->clone(realm);
  1413. // 2. Set httpFetchParams to a copy of fetchParams.
  1414. // 3. Set httpFetchParams’s request to httpRequest.
  1415. auto new_http_fetch_params = Infrastructure::FetchParams::create(vm, *http_request, fetch_params.timing_info());
  1416. new_http_fetch_params->set_algorithms(fetch_params.algorithms());
  1417. new_http_fetch_params->set_task_destination(fetch_params.task_destination());
  1418. new_http_fetch_params->set_cross_origin_isolated_capability(fetch_params.cross_origin_isolated_capability());
  1419. new_http_fetch_params->set_preloaded_response_candidate(fetch_params.preloaded_response_candidate());
  1420. http_fetch_params = new_http_fetch_params;
  1421. }
  1422. // 3. Let includeCredentials be true if one of
  1423. if (
  1424. // - request’s credentials mode is "include"
  1425. request->credentials_mode() == Infrastructure::Request::CredentialsMode::Include
  1426. // - request’s credentials mode is "same-origin" and request’s response tainting is "basic"
  1427. || (request->credentials_mode() == Infrastructure::Request::CredentialsMode::SameOrigin
  1428. && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  1429. // is true; otherwise false.
  1430. ) {
  1431. include_credentials = IncludeCredentials::Yes;
  1432. } else {
  1433. include_credentials = IncludeCredentials::No;
  1434. }
  1435. // 4. If Cross-Origin-Embedder-Policy allows credentials with request returns false, then set
  1436. // includeCredentials to false.
  1437. if (!request->cross_origin_embedder_policy_allows_credentials())
  1438. include_credentials = IncludeCredentials::No;
  1439. // 5. Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null; otherwise null.
  1440. auto content_length = http_request->body().has<JS::NonnullGCPtr<Infrastructure::Body>>()
  1441. ? http_request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->length()
  1442. : Optional<u64> {};
  1443. // 6. Let contentLengthHeaderValue be null.
  1444. auto content_length_header_value = Optional<ByteBuffer> {};
  1445. // 7. If httpRequest’s body is null and httpRequest’s method is `POST` or `PUT`, then set
  1446. // contentLengthHeaderValue to `0`.
  1447. if (http_request->body().has<Empty>() && StringView { http_request->method() }.is_one_of("POST"sv, "PUT"sv))
  1448. content_length_header_value = MUST(ByteBuffer::copy("0"sv.bytes()));
  1449. // 8. If contentLength is non-null, then set contentLengthHeaderValue to contentLength, serialized and
  1450. // isomorphic encoded.
  1451. if (content_length.has_value())
  1452. content_length_header_value = MUST(ByteBuffer::copy(String::number(*content_length).bytes()));
  1453. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, contentLengthHeaderValue) to
  1454. // httpRequest’s header list.
  1455. if (content_length_header_value.has_value()) {
  1456. auto header = Infrastructure::Header {
  1457. .name = MUST(ByteBuffer::copy("Content-Length"sv.bytes())),
  1458. .value = content_length_header_value.release_value(),
  1459. };
  1460. http_request->header_list()->append(move(header));
  1461. }
  1462. // 10. If contentLength is non-null and httpRequest’s keepalive is true, then:
  1463. if (content_length.has_value() && http_request->keepalive()) {
  1464. // 1. Let inflightKeepaliveBytes be 0.
  1465. u64 inflight_keep_alive_bytes = 0;
  1466. // 2. Let group be httpRequest’s client’s fetch group.
  1467. auto& group = http_request->client()->fetch_group();
  1468. // 3. Let inflightRecords be the set of fetch records in group whose request’s keepalive is true and done flag is unset.
  1469. Vector<JS::NonnullGCPtr<Infrastructure::FetchRecord>> in_flight_records;
  1470. for (auto const& fetch_record : group) {
  1471. if (fetch_record->request()->keepalive() && !fetch_record->request()->done())
  1472. in_flight_records.append(fetch_record);
  1473. }
  1474. // 4. For each fetchRecord of inflightRecords:
  1475. for (auto const& fetch_record : in_flight_records) {
  1476. // 1. Let inflightRequest be fetchRecord’s request.
  1477. auto const& in_flight_request = fetch_record->request();
  1478. // 2. Increment inflightKeepaliveBytes by inflightRequest’s body’s length.
  1479. inflight_keep_alive_bytes += in_flight_request->body().visit(
  1480. [](Empty) -> u64 { return 0; },
  1481. [](ByteBuffer const& buffer) -> u64 { return buffer.size(); },
  1482. [](JS::NonnullGCPtr<Infrastructure::Body> body) -> u64 {
  1483. return body->length().has_value() ? body->length().value() : 0;
  1484. });
  1485. }
  1486. // 5. If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.
  1487. if ((content_length.value() + inflight_keep_alive_bytes) > keepalive_maximum_size)
  1488. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Keepalive request exceeded maximum allowed size of 64 KiB"sv));
  1489. // NOTE: The above limit ensures that requests that are allowed to outlive the environment settings object
  1490. // and contain a body, have a bounded size and are not allowed to stay alive indefinitely.
  1491. }
  1492. // 11. If httpRequest’s referrer is a URL, then:
  1493. if (http_request->referrer().has<URL::URL>()) {
  1494. // 1. Let referrerValue be httpRequest’s referrer, serialized and isomorphic encoded.
  1495. auto referrer_string = http_request->referrer().get<URL::URL>().serialize();
  1496. auto referrer_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(referrer_string.bytes()));
  1497. // 2. Append (`Referer`, referrerValue) to httpRequest’s header list.
  1498. auto header = Infrastructure::Header {
  1499. .name = MUST(ByteBuffer::copy("Referer"sv.bytes())),
  1500. .value = move(referrer_value),
  1501. };
  1502. http_request->header_list()->append(move(header));
  1503. }
  1504. // 12. Append a request `Origin` header for httpRequest.
  1505. http_request->add_origin_header();
  1506. // 13. Append the Fetch metadata headers for httpRequest.
  1507. append_fetch_metadata_headers_for_request(*http_request);
  1508. // 14. FIXME If httpRequest’s initiator is "prefetch", then set a structured field value
  1509. // given (`Sec-Purpose`, the token prefetch) in httpRequest’s header list.
  1510. // 15. If httpRequest’s header list does not contain `User-Agent`, then user agents should append
  1511. // (`User-Agent`, default `User-Agent` value) to httpRequest’s header list.
  1512. if (!http_request->header_list()->contains("User-Agent"sv.bytes())) {
  1513. auto header = Infrastructure::Header {
  1514. .name = MUST(ByteBuffer::copy("User-Agent"sv.bytes())),
  1515. .value = Infrastructure::default_user_agent_value(),
  1516. };
  1517. http_request->header_list()->append(move(header));
  1518. }
  1519. // 16. If httpRequest’s cache mode is "default" and httpRequest’s header list contains `If-Modified-Since`,
  1520. // `If-None-Match`, `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set httpRequest’s cache mode to
  1521. // "no-store".
  1522. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::Default
  1523. && (http_request->header_list()->contains("If-Modified-Since"sv.bytes())
  1524. || http_request->header_list()->contains("If-None-Match"sv.bytes())
  1525. || http_request->header_list()->contains("If-Unmodified-Since"sv.bytes())
  1526. || http_request->header_list()->contains("If-Match"sv.bytes())
  1527. || http_request->header_list()->contains("If-Range"sv.bytes()))) {
  1528. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1529. }
  1530. // 17. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache cache-control header
  1531. // modification flag is unset, and httpRequest’s header list does not contain `Cache-Control`, then append
  1532. // (`Cache-Control`, `max-age=0`) to httpRequest’s header list.
  1533. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoCache
  1534. && !http_request->prevent_no_cache_cache_control_header_modification()
  1535. && !http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1536. auto header = Infrastructure::Header::from_string_pair("Cache-Control"sv, "max-age=0"sv);
  1537. http_request->header_list()->append(move(header));
  1538. }
  1539. // 18. If httpRequest’s cache mode is "no-store" or "reload", then:
  1540. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoStore
  1541. || http_request->cache_mode() == Infrastructure::Request::CacheMode::Reload) {
  1542. // 1. If httpRequest’s header list does not contain `Pragma`, then append (`Pragma`, `no-cache`) to
  1543. // httpRequest’s header list.
  1544. if (!http_request->header_list()->contains("Pragma"sv.bytes())) {
  1545. auto header = Infrastructure::Header::from_string_pair("Pragma"sv, "no-cache"sv);
  1546. http_request->header_list()->append(move(header));
  1547. }
  1548. // 2. If httpRequest’s header list does not contain `Cache-Control`, then append
  1549. // (`Cache-Control`, `no-cache`) to httpRequest’s header list.
  1550. if (!http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1551. auto header = Infrastructure::Header::from_string_pair("Cache-Control"sv, "no-cache"sv);
  1552. http_request->header_list()->append(move(header));
  1553. }
  1554. }
  1555. // 19. If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`) to
  1556. // httpRequest’s header list.
  1557. // NOTE: This avoids a failure when handling content codings with a part of an encoded response.
  1558. // Additionally, many servers mistakenly ignore `Range` headers if a non-identity encoding is accepted.
  1559. if (http_request->header_list()->contains("Range"sv.bytes())) {
  1560. auto header = Infrastructure::Header::from_string_pair("Accept-Encoding"sv, "identity"sv);
  1561. http_request->header_list()->append(move(header));
  1562. }
  1563. // 20. Modify httpRequest’s header list per HTTP. Do not append a given header if httpRequest’s header list
  1564. // contains that header’s name.
  1565. // NOTE: It would be great if we could make this more normative somehow. At this point headers such as
  1566. // `Accept-Encoding`, `Connection`, `DNT`, and `Host`, are to be appended if necessary.
  1567. // `Accept`, `Accept-Charset`, and `Accept-Language` must not be included at this point.
  1568. // NOTE: `Accept` and `Accept-Language` are already included (unless fetch() is used, which does not include
  1569. // the latter by default), and `Accept-Charset` is a waste of bytes. See HTTP header layer division for
  1570. // more details.
  1571. if (ResourceLoader::the().enable_do_not_track() && !http_request->header_list()->contains("DNT"sv.bytes())) {
  1572. auto header = Infrastructure::Header::from_string_pair("DNT"sv, "1"sv);
  1573. http_request->header_list()->append(move(header));
  1574. }
  1575. // 21. If includeCredentials is true, then:
  1576. if (include_credentials == IncludeCredentials::Yes) {
  1577. // 1. If the user agent is not configured to block cookies for httpRequest (see section 7 of [COOKIES]),
  1578. // then:
  1579. if (true) {
  1580. // 1. Let cookies be the result of running the "cookie-string" algorithm (see section 5.4 of [COOKIES])
  1581. // with the user agent’s cookie store and httpRequest’s current URL.
  1582. auto cookies = ([&] {
  1583. // FIXME: Getting to the page client reliably is way too complicated, and going via the document won't work in workers.
  1584. auto document = Bindings::host_defined_environment_settings_object(realm).responsible_document();
  1585. if (!document)
  1586. return String {};
  1587. return document->page().client().page_did_request_cookie(http_request->current_url(), Cookie::Source::Http);
  1588. })();
  1589. // 2. If cookies is not the empty string, then append (`Cookie`, cookies) to httpRequest’s header list.
  1590. if (!cookies.is_empty()) {
  1591. auto header = Infrastructure::Header::from_string_pair("Cookie"sv, cookies);
  1592. http_request->header_list()->append(move(header));
  1593. }
  1594. }
  1595. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1596. if (!http_request->header_list()->contains("Authorization"sv.bytes())) {
  1597. // 1. Let authorizationValue be null.
  1598. auto authorization_value = Optional<String> {};
  1599. // 2. If there’s an authentication entry for httpRequest and either httpRequest’s use-URL-credentials
  1600. // flag is unset or httpRequest’s current URL does not include credentials, then set
  1601. // authorizationValue to authentication entry.
  1602. if (false // FIXME: "If there’s an authentication entry for httpRequest"
  1603. && (!http_request->use_url_credentials() || !http_request->current_url().includes_credentials())) {
  1604. // FIXME: "set authorizationValue to authentication entry."
  1605. }
  1606. // 3. Otherwise, if httpRequest’s current URL does include credentials and isAuthenticationFetch is
  1607. // true, set authorizationValue to httpRequest’s current URL, converted to an `Authorization` value.
  1608. else if (http_request->current_url().includes_credentials() && is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1609. auto const& url = http_request->current_url();
  1610. auto payload = MUST(String::formatted("{}:{}", URL::percent_decode(url.username()), URL::percent_decode(url.password())));
  1611. authorization_value = TRY_OR_THROW_OOM(vm, encode_base64(payload.bytes()));
  1612. }
  1613. // 4. If authorizationValue is non-null, then append (`Authorization`, authorizationValue) to
  1614. // httpRequest’s header list.
  1615. if (authorization_value.has_value()) {
  1616. auto header = Infrastructure::Header::from_string_pair("Authorization"sv, *authorization_value);
  1617. http_request->header_list()->append(move(header));
  1618. }
  1619. }
  1620. }
  1621. // FIXME: 22. If there’s a proxy-authentication entry, use it as appropriate.
  1622. // NOTE: This intentionally does not depend on httpRequest’s credentials mode.
  1623. // 23. Set httpCache to the result of determining the HTTP cache partition, given httpRequest.
  1624. http_cache = determine_the_http_cache_partition(*http_request);
  1625. // 24. If httpCache is null, then set httpRequest’s cache mode to "no-store".
  1626. if (!http_cache)
  1627. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1628. // 25. If httpRequest’s cache mode is neither "no-store" nor "reload", then:
  1629. if (http_request->cache_mode() != Infrastructure::Request::CacheMode::NoStore
  1630. && http_request->cache_mode() != Infrastructure::Request::CacheMode::Reload) {
  1631. // 1. Set storedResponse to the result of selecting a response from the httpCache, possibly needing
  1632. // validation, as per the "Constructing Responses from Caches" chapter of HTTP Caching [HTTP-CACHING],
  1633. // if any.
  1634. // NOTE: As mandated by HTTP, this still takes the `Vary` header into account.
  1635. stored_response = http_cache->select_response(realm, http_request->current_url(), http_request->method(), *http_request->header_list());
  1636. // 2. If storedResponse is non-null, then:
  1637. if (stored_response) {
  1638. // 1. If cache mode is "default", storedResponse is a stale-while-revalidate response,
  1639. // and httpRequest’s client is non-null, then:
  1640. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::Default
  1641. && stored_response->is_stale_while_revalidate()
  1642. && http_request->client() != nullptr) {
  1643. // 1. Set response to storedResponse.
  1644. response = stored_response;
  1645. // 2. Set response’s cache state to "local".
  1646. response->set_cache_state(Infrastructure::Response::CacheState::Local);
  1647. // 3. Let revalidateRequest be a clone of request.
  1648. auto revalidate_request = request->clone(realm);
  1649. // 4. Set revalidateRequest’s cache mode set to "no-cache".
  1650. revalidate_request->set_cache_mode(Infrastructure::Request::CacheMode::NoCache);
  1651. // 5. Set revalidateRequest’s prevent no-cache cache-control header modification flag.
  1652. revalidate_request->set_prevent_no_cache_cache_control_header_modification(true);
  1653. // 6. Set revalidateRequest’s service-workers mode set to "none".
  1654. revalidate_request->set_service_workers_mode(Infrastructure::Request::ServiceWorkersMode::None);
  1655. // 7. In parallel, run main fetch given a new fetch params whose request is revalidateRequest.
  1656. Platform::EventLoopPlugin::the().deferred_invoke([&vm, &realm, revalidate_request, fetch_params = JS::NonnullGCPtr(fetch_params)] {
  1657. (void)main_fetch(realm, Infrastructure::FetchParams::create(vm, revalidate_request, fetch_params->timing_info()));
  1658. });
  1659. }
  1660. // 2. Otherwise:
  1661. else {
  1662. // 1. If storedResponse is a stale response, then set the revalidatingFlag.
  1663. if (stored_response->is_stale())
  1664. revalidating_flag->set_value(true);
  1665. // 2. If the revalidatingFlag is set and httpRequest’s cache mode is neither "force-cache" nor "only-if-cached", then:
  1666. if (revalidating_flag->value()
  1667. && http_request->cache_mode() != Infrastructure::Request::CacheMode::ForceCache
  1668. && http_request->cache_mode() != Infrastructure::Request::CacheMode::OnlyIfCached) {
  1669. // 1. If storedResponse’s header list contains `ETag`, then append (`If-None-Match`, `ETag`'s value) to httpRequest’s header list.
  1670. if (auto etag = stored_response->header_list()->get("ETag"sv.bytes()); etag.has_value()) {
  1671. http_request->header_list()->append(Infrastructure::Header::from_string_pair("If-None-Match"sv, *etag));
  1672. }
  1673. // 2. If storedResponse’s header list contains `Last-Modified`, then append (`If-Modified-Since`, `Last-Modified`'s value) to httpRequest’s header list.
  1674. if (auto last_modified = stored_response->header_list()->get("Last-Modified"sv.bytes()); last_modified.has_value()) {
  1675. http_request->header_list()->append(Infrastructure::Header::from_string_pair("If-Modified-Since"sv, *last_modified));
  1676. }
  1677. }
  1678. // 3. Otherwise, set response to storedResponse and set response’s cache state to "local".
  1679. else {
  1680. response = stored_response;
  1681. response->set_cache_state(Infrastructure::Response::CacheState::Local);
  1682. }
  1683. }
  1684. }
  1685. }
  1686. }
  1687. // 9. If aborted, then return the appropriate network error for fetchParams.
  1688. if (aborted)
  1689. return PendingResponse::create(vm, request, Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1690. JS::GCPtr<PendingResponse> pending_forward_response;
  1691. // 10. If response is null, then:
  1692. if (!response) {
  1693. // 1. If httpRequest’s cache mode is "only-if-cached", then return a network error.
  1694. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::OnlyIfCached)
  1695. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'only-if-cached' cache mode doesn't have a cached response"sv));
  1696. // 2. Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams, includeCredentials,
  1697. // and isNewConnectionFetch.
  1698. pending_forward_response = TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, *http_fetch_params, include_credentials, is_new_connection_fetch));
  1699. } else {
  1700. pending_forward_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  1701. }
  1702. auto returned_pending_response = PendingResponse::create(vm, request);
  1703. 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, http_cache](JS::NonnullGCPtr<Infrastructure::Response> resolved_forward_response) mutable {
  1704. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");
  1705. if (response_was_null) {
  1706. auto forward_response = resolved_forward_response;
  1707. // NOTE: TRACE is omitted as it is a forbidden method in Fetch.
  1708. auto method_is_unsafe = !(StringView { http_request->method() }.is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv));
  1709. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399, inclusive,
  1710. // invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP
  1711. // Caching, and set storedResponse to null.
  1712. if (method_is_unsafe && forward_response->status() >= 200 && forward_response->status() <= 399) {
  1713. // FIXME: "invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP Caching"
  1714. stored_response = nullptr;
  1715. }
  1716. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, then:
  1717. if (revalidating_flag->value() && forward_response->status() == 304) {
  1718. dbgln("\033[34;1mHTTP CACHE REVALIDATE (304)\033[0m {}", http_request->current_url());
  1719. // 1. Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening
  1720. // Stored Responses upon Validation" chapter of HTTP Caching.
  1721. // NOTE: This updates the stored response in cache as well.
  1722. http_cache->freshen_stored_responses_upon_validation(*http_request, *forward_response, *stored_response);
  1723. // 2. Set response to storedResponse.
  1724. response = stored_response;
  1725. // 3. Set response’s cache state to "validated".
  1726. if (response)
  1727. response->set_cache_state(Infrastructure::Response::CacheState::Validated);
  1728. }
  1729. // 5. If response is null, then:
  1730. if (!response) {
  1731. // 1. Set response to forwardResponse.
  1732. response = forward_response;
  1733. // 2. Store httpRequest and forwardResponse in httpCache, as per the "Storing Responses in Caches" chapter of HTTP Caching.
  1734. // NOTE: If forwardResponse is a network error, this effectively caches the network error, which is
  1735. // sometimes known as "negative caching".
  1736. // NOTE: The associated body info is stored in the cache alongside the response.
  1737. if (http_cache)
  1738. http_cache->store_response(*http_request, *forward_response);
  1739. }
  1740. }
  1741. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1742. response->set_url_list(http_request->url_list());
  1743. // 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.
  1744. if (http_request->header_list()->contains("Range"sv.bytes()))
  1745. response->set_range_requested(true);
  1746. // 13. Set response’s request-includes-credentials to includeCredentials.
  1747. response->set_request_includes_credentials(include_credentials == IncludeCredentials::Yes);
  1748. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1749. // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", includeCredentials is true,
  1750. // and request’s window is an environment settings object, then:
  1751. if (response->status() == 401
  1752. && http_request->response_tainting() != Infrastructure::Request::ResponseTainting::CORS
  1753. && include_credentials == IncludeCredentials::Yes
  1754. && request->window().has<JS::GCPtr<HTML::EnvironmentSettingsObject>>()
  1755. // AD-HOC: Require at least one WWW-Authenticate header to be set before automatically retrying an authenticated
  1756. // request (see rule 1 below). See: https://github.com/whatwg/fetch/issues/1766
  1757. && request->header_list()->contains("WWW-Authenticate"sv.bytes())) {
  1758. // 1. Needs testing: multiple `WWW-Authenticate` headers, missing, parsing issues.
  1759. // (Red box in the spec, no-op)
  1760. // 2. If request’s body is non-null, then:
  1761. if (!request->body().has<Empty>()) {
  1762. // 1. If request’s body’s source is null, then return a network error.
  1763. if (request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) {
  1764. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request has body but no body source"_string));
  1765. return;
  1766. }
  1767. // 2. Set request’s body to the body of the result of safely extracting request’s body’s source.
  1768. auto const& source = request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source();
  1769. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  1770. auto converted_source = source.has<ByteBuffer>()
  1771. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  1772. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  1773. auto [body, _] = TRY_OR_IGNORE(safely_extract_body(realm, converted_source));
  1774. request->set_body(move(body));
  1775. }
  1776. // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
  1777. if (!request->use_url_credentials() || is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1778. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1779. if (fetch_params.is_canceled()) {
  1780. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1781. return;
  1782. }
  1783. // FIXME: 2. Let username and password be the result of prompting the end user for a username and password,
  1784. // respectively, in request’s window.
  1785. dbgln("Fetch: Username/password prompt is not implemented, using empty strings. This request will probably fail.");
  1786. auto username = ByteString::empty();
  1787. auto password = ByteString::empty();
  1788. // 3. Set the username given request’s current URL and username.
  1789. request->current_url().set_username(username);
  1790. // 4. Set the password given request’s current URL and password.
  1791. request->current_url().set_password(password);
  1792. }
  1793. // 4. Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.
  1794. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes));
  1795. }
  1796. 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) {
  1797. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");
  1798. // 15. If response’s status is 407, then:
  1799. if (response->status() == 407) {
  1800. // 1. If request’s window is "no-window", then return a network error.
  1801. if (request->window().has<Infrastructure::Request::Window>()
  1802. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow) {
  1803. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request requires proxy authentication but has 'no-window' set"_string));
  1804. return;
  1805. }
  1806. // 2. Needs testing: multiple `Proxy-Authenticate` headers, missing, parsing issues.
  1807. // (Red box in the spec, no-op)
  1808. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1809. if (fetch_params.is_canceled()) {
  1810. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1811. return;
  1812. }
  1813. // FIXME: 4. Prompt the end user as appropriate in request’s window and store the result as a
  1814. // proxy-authentication entry.
  1815. // NOTE: Remaining details surrounding proxy authentication are defined by HTTP.
  1816. // FIXME: 5. Set response to the result of running HTTP-network-or-cache fetch given fetchParams.
  1817. // (Doing this without step 4 would potentially lead to an infinite request cycle.)
  1818. }
  1819. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1820. // 16. If all of the following are true
  1821. if (
  1822. // - response’s status is 421
  1823. response->status() == 421
  1824. // - isNewConnectionFetch is false
  1825. && is_new_connection_fetch == IsNewConnectionFetch::No
  1826. // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1827. && (request->body().has<Empty>() || !request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>())
  1828. // then:
  1829. ) {
  1830. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1831. if (fetch_params.is_canceled()) {
  1832. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1833. return;
  1834. }
  1835. // 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,
  1836. // isAuthenticationFetch, and true.
  1837. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes));
  1838. }
  1839. inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1840. // 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given
  1841. // realm.
  1842. if (is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1843. // FIXME: "create an authentication entry for request and the given realm"
  1844. }
  1845. returned_pending_response->resolve(response);
  1846. });
  1847. });
  1848. });
  1849. // 18. Return response.
  1850. // NOTE: Typically response’s body’s stream is still being enqueued to after returning.
  1851. return returned_pending_response;
  1852. }
  1853. #if defined(WEB_FETCH_DEBUG)
  1854. static void log_load_request(auto const& load_request)
  1855. {
  1856. dbgln("Fetch: Invoking ResourceLoader");
  1857. dbgln("> {} {} HTTP/1.1", load_request.method(), load_request.url());
  1858. for (auto const& [name, value] : load_request.headers())
  1859. dbgln("> {}: {}", name, value);
  1860. dbgln(">");
  1861. for (auto line : StringView { load_request.body() }.split_view('\n', SplitBehavior::KeepEmpty))
  1862. dbgln("> {}", line);
  1863. }
  1864. static void log_response(auto const& status_code, auto const& headers, auto const& data)
  1865. {
  1866. dbgln("< HTTP/1.1 {}", status_code.value_or(0));
  1867. for (auto const& [name, value] : headers.headers())
  1868. dbgln("< {}: {}", name, value);
  1869. dbgln("<");
  1870. for (auto line : StringView { data }.split_view('\n', SplitBehavior::KeepEmpty))
  1871. dbgln("< {}", line);
  1872. }
  1873. #endif
  1874. // https://fetch.spec.whatwg.org/#concept-http-network-fetch
  1875. // Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)
  1876. // It also handles file:// URLs since those can also go through ResourceLoader.
  1877. 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)
  1878. {
  1879. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'non-standard HTTP-network fetch' with: fetch_params @ {}", &fetch_params);
  1880. auto& vm = realm.vm();
  1881. (void)include_credentials;
  1882. (void)is_new_connection_fetch;
  1883. auto request = fetch_params.request();
  1884. auto& page = Bindings::host_defined_page(realm);
  1885. // NOTE: Using LoadRequest::create_for_url_on_page here will unconditionally add cookies as long as there's a page available.
  1886. // However, it is up to http_network_or_cache_fetch to determine if cookies should be added to the request.
  1887. LoadRequest load_request;
  1888. load_request.set_url(request->current_url());
  1889. load_request.set_page(page);
  1890. load_request.set_method(ByteString::copy(request->method()));
  1891. for (auto const& header : *request->header_list())
  1892. load_request.set_header(ByteString::copy(header.name), ByteString::copy(header.value));
  1893. if (auto const* body = request->body().get_pointer<JS::NonnullGCPtr<Infrastructure::Body>>()) {
  1894. TRY((*body)->source().visit(
  1895. [&](ByteBuffer const& byte_buffer) -> WebIDL::ExceptionOr<void> {
  1896. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(byte_buffer)));
  1897. return {};
  1898. },
  1899. [&](JS::Handle<FileAPI::Blob> const& blob_handle) -> WebIDL::ExceptionOr<void> {
  1900. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob_handle->raw_bytes())));
  1901. return {};
  1902. },
  1903. [](Empty) -> WebIDL::ExceptionOr<void> {
  1904. return {};
  1905. }));
  1906. }
  1907. auto pending_response = PendingResponse::create(vm, request);
  1908. if constexpr (WEB_FETCH_DEBUG) {
  1909. dbgln("Fetch: Invoking ResourceLoader");
  1910. log_load_request(load_request);
  1911. }
  1912. // FIXME: This check should be removed and all HTTP requests should go through the `ResourceLoader::load_unbuffered`
  1913. // path. The buffer option should then be supplied to the steps below that allow us to buffer data up to a
  1914. // user-agent-defined limit (or not). However, we will need to fully use stream operations throughout the
  1915. // fetch process to enable this (e.g. Body::fully_read must use streams for this to work).
  1916. if (request->buffer_policy() == Infrastructure::Request::BufferPolicy::DoNotBufferResponse) {
  1917. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  1918. // 12. Let stream be a new ReadableStream.
  1919. auto stream = realm.heap().allocate<Streams::ReadableStream>(realm, realm);
  1920. auto fetched_data_receiver = realm.heap().allocate<FetchedDataReceiver>(realm, fetch_params, stream);
  1921. // 10. Let pullAlgorithm be the followings steps:
  1922. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, fetched_data_receiver]() {
  1923. // 1. Let promise be a new promise.
  1924. auto promise = WebIDL::create_promise(realm);
  1925. // 2. Run the following steps in parallel:
  1926. // NOTE: This is handled by FetchedDataReceiver.
  1927. fetched_data_receiver->set_pending_promise(promise);
  1928. // 3. Return promise.
  1929. return promise;
  1930. });
  1931. // 11. Let cancelAlgorithm be an algorithm that aborts fetchParams’s controller with reason, given reason.
  1932. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, &fetch_params](JS::Value reason) {
  1933. fetch_params.controller()->abort(realm, reason);
  1934. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1935. });
  1936. // 13. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, cancelAlgorithm set to cancelAlgorithm.
  1937. Streams::set_up_readable_stream_controller_with_byte_reading_support(stream, pull_algorithm, cancel_algorithm);
  1938. auto on_headers_received = [&vm, request, pending_response, stream](auto const& response_headers, Optional<u32> status_code) {
  1939. if (pending_response->is_resolved()) {
  1940. // RequestServer will send us the response headers twice, the second time being for HTTP trailers. This
  1941. // fetch algorithm is not interested in trailers, so just drop them here.
  1942. return;
  1943. }
  1944. auto response = Infrastructure::Response::create(vm);
  1945. response->set_status(status_code.value_or(200));
  1946. // FIXME: Set response status message
  1947. if constexpr (WEB_FETCH_DEBUG) {
  1948. dbgln("Fetch: ResourceLoader load for '{}' {}: (status {})",
  1949. request->url(),
  1950. Infrastructure::is_ok_status(response->status()) ? "complete"sv : "failed"sv,
  1951. response->status());
  1952. log_response(status_code, response_headers, ReadonlyBytes {});
  1953. }
  1954. for (auto const& [name, value] : response_headers.headers()) {
  1955. auto header = Infrastructure::Header::from_string_pair(name, value);
  1956. response->header_list()->append(move(header));
  1957. }
  1958. // 14. Set response’s body to a new body whose stream is stream.
  1959. response->set_body(Infrastructure::Body::create(vm, stream));
  1960. // 17. Return response.
  1961. // NOTE: Typically response’s body’s stream is still being enqueued to after returning.
  1962. pending_response->resolve(response);
  1963. };
  1964. // 16. Run these steps in parallel:
  1965. // FIXME: 1. Run these steps, but abort when fetchParams is canceled:
  1966. auto on_data_received = [fetched_data_receiver](auto bytes) {
  1967. // 1. If one or more bytes have been transmitted from response’s message body, then:
  1968. if (!bytes.is_empty()) {
  1969. // 1. Let bytes be the transmitted bytes.
  1970. // FIXME: 2. Let codings be the result of extracting header list values given `Content-Encoding` and response’s header list.
  1971. // FIXME: 3. Increase response’s body info’s encoded size by bytes’s length.
  1972. // FIXME: 4. Set bytes to the result of handling content codings given codings and bytes.
  1973. // FIXME: 5. Increase response’s body info’s decoded size by bytes’s length.
  1974. // FIXME: 6. If bytes is failure, then terminate fetchParams’s controller.
  1975. // 7. Append bytes to buffer.
  1976. fetched_data_receiver->on_data_received(bytes);
  1977. // FIXME: 8. If the size of buffer is larger than an upper limit chosen by the user agent, ask the user agent
  1978. // to suspend the ongoing fetch.
  1979. }
  1980. };
  1981. auto on_complete = [&vm, &realm, pending_response, stream](auto success, auto error_message) {
  1982. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  1983. // 16.1.1.2. Otherwise, if the bytes transmission for response’s message body is done normally and stream is readable,
  1984. // then close stream, and abort these in-parallel steps.
  1985. if (success) {
  1986. if (stream->is_readable())
  1987. stream->close();
  1988. }
  1989. // 16.1.2.2. Otherwise, if stream is readable, error stream with a TypeError.
  1990. else {
  1991. auto error = MUST(String::formatted("Load failed: {}", error_message));
  1992. if (stream->is_readable())
  1993. stream->error(JS::TypeError::create(realm, error));
  1994. if (!pending_response->is_resolved())
  1995. pending_response->resolve(Infrastructure::Response::network_error(vm, error));
  1996. }
  1997. };
  1998. ResourceLoader::the().load_unbuffered(load_request, move(on_headers_received), move(on_data_received), move(on_complete));
  1999. } else {
  2000. auto on_load_success = [&realm, &vm, request, pending_response](auto data, auto& response_headers, auto status_code) {
  2001. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' complete", request->url());
  2002. if constexpr (WEB_FETCH_DEBUG)
  2003. log_response(status_code, response_headers, data);
  2004. auto [body, _] = TRY_OR_IGNORE(extract_body(realm, data));
  2005. auto response = Infrastructure::Response::create(vm);
  2006. response->set_status(status_code.value_or(200));
  2007. response->set_body(move(body));
  2008. for (auto const& [name, value] : response_headers.headers()) {
  2009. auto header = Infrastructure::Header::from_string_pair(name, value);
  2010. response->header_list()->append(move(header));
  2011. }
  2012. // FIXME: Set response status message
  2013. pending_response->resolve(response);
  2014. };
  2015. auto on_load_error = [&realm, &vm, request, pending_response](auto& error, auto status_code, auto data, auto& response_headers) {
  2016. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' failed: {} (status {})", request->url(), error, status_code.value_or(0));
  2017. if constexpr (WEB_FETCH_DEBUG)
  2018. log_response(status_code, response_headers, data);
  2019. auto response = Infrastructure::Response::create(vm);
  2020. // FIXME: This is ugly, ResourceLoader should tell us.
  2021. if (status_code.value_or(0) == 0) {
  2022. response = Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::from_byte_string(error)));
  2023. } else {
  2024. response->set_type(Infrastructure::Response::Type::Error);
  2025. response->set_status(status_code.value_or(400));
  2026. auto [body, _] = TRY_OR_IGNORE(extract_body(realm, data));
  2027. response->set_body(move(body));
  2028. for (auto const& [name, value] : response_headers.headers()) {
  2029. auto header = Infrastructure::Header::from_string_pair(name, value);
  2030. response->header_list()->append(move(header));
  2031. }
  2032. // FIXME: Set response status message
  2033. }
  2034. pending_response->resolve(response);
  2035. };
  2036. ResourceLoader::the().load(load_request, move(on_load_success), move(on_load_error));
  2037. }
  2038. return pending_response;
  2039. }
  2040. // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0
  2041. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> cors_preflight_fetch(JS::Realm& realm, Infrastructure::Request& request)
  2042. {
  2043. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' with request @ {}", &request);
  2044. auto& vm = realm.vm();
  2045. // 1. Let preflight be a new request whose method is `OPTIONS`, URL list is a clone of request’s URL list, initiator is
  2046. // request’s initiator, destination is request’s destination, origin is request’s origin, referrer is request’s referrer,
  2047. // referrer policy is request’s referrer policy, mode is "cors", and response tainting is "cors".
  2048. auto preflight = Fetch::Infrastructure::Request::create(vm);
  2049. preflight->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("OPTIONS"sv.bytes())));
  2050. preflight->set_url_list(request.url_list());
  2051. preflight->set_initiator(request.initiator());
  2052. preflight->set_destination(request.destination());
  2053. preflight->set_origin(request.origin());
  2054. preflight->set_referrer(request.referrer());
  2055. preflight->set_referrer_policy(request.referrer_policy());
  2056. preflight->set_mode(Infrastructure::Request::Mode::CORS);
  2057. preflight->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  2058. // 2. Append (`Accept`, `*/*`) to preflight’s header list.
  2059. auto temp_header = Infrastructure::Header::from_string_pair("Accept"sv, "*/*"sv);
  2060. preflight->header_list()->append(move(temp_header));
  2061. // 3. Append (`Access-Control-Request-Method`, request’s method) to preflight’s header list.
  2062. temp_header = Infrastructure::Header::from_string_pair("Access-Control-Request-Method"sv, request.method());
  2063. preflight->header_list()->append(move(temp_header));
  2064. // 4. Let headers be the CORS-unsafe request-header names with request’s header list.
  2065. auto headers = Infrastructure::get_cors_unsafe_header_names(request.header_list());
  2066. // 5. If headers is not empty, then:
  2067. if (!headers.is_empty()) {
  2068. // 1. Let value be the items in headers separated from each other by `,`.
  2069. // NOTE: This intentionally does not use combine, as 0x20 following 0x2C is not the way this was implemented,
  2070. // for better or worse.
  2071. ByteBuffer value;
  2072. bool first = true;
  2073. for (auto const& header : headers) {
  2074. if (!first)
  2075. TRY_OR_THROW_OOM(vm, value.try_append(','));
  2076. TRY_OR_THROW_OOM(vm, value.try_append(header));
  2077. first = false;
  2078. }
  2079. // 2. Append (`Access-Control-Request-Headers`, value) to preflight’s header list.
  2080. temp_header = Infrastructure::Header {
  2081. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("Access-Control-Request-Headers"sv.bytes())),
  2082. .value = move(value),
  2083. };
  2084. preflight->header_list()->append(move(temp_header));
  2085. }
  2086. // 6. Let response be the result of running HTTP-network-or-cache fetch given a new fetch params whose request is preflight.
  2087. // FIXME: The spec doesn't say anything about timing_info here, but FetchParams requires a non-null FetchTimingInfo object.
  2088. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  2089. auto fetch_params = Infrastructure::FetchParams::create(vm, preflight, timing_info);
  2090. auto returned_pending_response = PendingResponse::create(vm, request);
  2091. auto preflight_response = TRY(http_network_or_cache_fetch(realm, fetch_params));
  2092. preflight_response->when_loaded([&vm, &request, returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  2093. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");
  2094. // 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
  2095. // NOTE: The CORS check is done on request rather than preflight to ensure the correct credentials mode is used.
  2096. if (cors_check(request, response) && Infrastructure::is_ok_status(response->status())) {
  2097. // 1. Let methods be the result of extracting header list values given `Access-Control-Allow-Methods` and response’s header list.
  2098. auto methods_or_failure = Infrastructure::extract_header_list_values("Access-Control-Allow-Methods"sv.bytes(), response->header_list());
  2099. // 2. Let headerNames be the result of extracting header list values given `Access-Control-Allow-Headers` and
  2100. // response’s header list.
  2101. auto header_names_or_failure = Infrastructure::extract_header_list_values("Access-Control-Allow-Headers"sv.bytes(), response->header_list());
  2102. // 3. If either methods or headerNames is failure, return a network error.
  2103. if (methods_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  2104. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "The Access-Control-Allow-Methods in the CORS-preflight response is syntactically invalid"_string));
  2105. return;
  2106. }
  2107. if (header_names_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  2108. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "The Access-Control-Allow-Headers in the CORS-preflight response is syntactically invalid"_string));
  2109. return;
  2110. }
  2111. // NOTE: We treat "methods_or_failure" being `Empty` as empty Vector here.
  2112. auto methods = methods_or_failure.has<Vector<ByteBuffer>>() ? methods_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  2113. // NOTE: We treat "header_names_or_failure" being `Empty` as empty Vector here.
  2114. auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  2115. // 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.
  2116. // NOTE: This ensures that a CORS-preflight fetch that happened due to request’s use-CORS-preflight flag being set is cached.
  2117. if (methods.is_empty() && request.use_cors_preflight())
  2118. methods = Vector { TRY_OR_IGNORE(ByteBuffer::copy(request.method())) };
  2119. // 5. If request’s method is not in methods, request’s method is not a CORS-safelisted method, and request’s credentials mode
  2120. // is "include" or methods does not contain `*`, then return a network error.
  2121. if (!methods.contains_slow(request.method()) && !Infrastructure::is_cors_safelisted_method(request.method())) {
  2122. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  2123. 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() }))));
  2124. return;
  2125. }
  2126. if (!methods.contains_slow("*"sv.bytes())) {
  2127. 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() }))));
  2128. return;
  2129. }
  2130. }
  2131. // 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
  2132. // for an item in headerNames, then return a network error.
  2133. for (auto const& header : *request.header_list()) {
  2134. if (Infrastructure::is_cors_non_wildcard_request_header_name(header.name)) {
  2135. bool is_in_header_names = false;
  2136. for (auto const& allowed_header_name : header_names) {
  2137. if (StringView { allowed_header_name }.equals_ignoring_ascii_case(header.name)) {
  2138. is_in_header_names = true;
  2139. break;
  2140. }
  2141. }
  2142. if (!is_in_header_names) {
  2143. 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 }))));
  2144. return;
  2145. }
  2146. }
  2147. }
  2148. // 7. For each unsafeName of the CORS-unsafe request-header names with request’s header list, if unsafeName is not a
  2149. // byte-case-insensitive match for an item in headerNames and request’s credentials mode is "include" or headerNames
  2150. // does not contain `*`, return a network error.
  2151. auto unsafe_names = Infrastructure::get_cors_unsafe_header_names(request.header_list());
  2152. for (auto const& unsafe_name : unsafe_names) {
  2153. bool is_in_header_names = false;
  2154. for (auto const& header_name : header_names) {
  2155. if (StringView { unsafe_name }.equals_ignoring_ascii_case(header_name)) {
  2156. is_in_header_names = true;
  2157. break;
  2158. }
  2159. }
  2160. if (!is_in_header_names) {
  2161. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  2162. 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 }))));
  2163. return;
  2164. }
  2165. if (!header_names.contains_slow("*"sv.bytes())) {
  2166. 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 }))));
  2167. return;
  2168. }
  2169. }
  2170. }
  2171. // FIXME: 8. Let max-age be the result of extracting header list values given `Access-Control-Max-Age` and response’s header list.
  2172. // FIXME: 9. If max-age is failure or null, then set max-age to 5.
  2173. // FIXME: 10. If max-age is greater than an imposed limit on max-age, then set max-age to the imposed limit.
  2174. // 11. If the user agent does not provide for a cache, then return response.
  2175. // NOTE: Since we don't currently have a cache, this is always true.
  2176. returned_pending_response->resolve(response);
  2177. return;
  2178. // FIXME: 12. For each method in methods for which there is a method cache entry match using request, set matching entry’s max-age
  2179. // to max-age.
  2180. // FIXME: 13. For each method in methods for which there is no method cache entry match using request, create a new cache entry
  2181. // with request, max-age, method, and null.
  2182. // FIXME: 14. For each headerName in headerNames for which there is a header-name cache entry match using request, set matching
  2183. // entry’s max-age to max-age.
  2184. // FIXME: 15. For each headerName in headerNames for which there is no header-name cache entry match using request, create a
  2185. // new cache entry with request, max-age, null, and headerName.
  2186. // FIXME: 16. Return response.
  2187. }
  2188. // 8. Otherwise, return a network error.
  2189. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "CORS-preflight check failed"_string));
  2190. });
  2191. return returned_pending_response;
  2192. }
  2193. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-dest
  2194. void set_sec_fetch_dest_header(Infrastructure::Request& request)
  2195. {
  2196. // 1. Assert: r’s url is a potentially trustworthy URL.
  2197. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  2198. // 2. Let header be a Structured Header whose value is a token.
  2199. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  2200. // 3. If r’s destination is the empty string, set header’s value to the string "empty". Otherwise, set header’s value to r’s destination.
  2201. ByteBuffer header_value;
  2202. if (!request.destination().has_value()) {
  2203. header_value = MUST(ByteBuffer::copy("empty"sv.bytes()));
  2204. } else {
  2205. header_value = MUST(ByteBuffer::copy(Infrastructure::request_destination_to_string(request.destination().value()).bytes()));
  2206. }
  2207. // 4. Set a structured field value `Sec-Fetch-Dest`/header in r’s header list.
  2208. auto header = Infrastructure::Header {
  2209. .name = MUST(ByteBuffer::copy("Sec-Fetch-Dest"sv.bytes())),
  2210. .value = move(header_value),
  2211. };
  2212. request.header_list()->append(move(header));
  2213. }
  2214. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-dest
  2215. void set_sec_fetch_mode_header(Infrastructure::Request& request)
  2216. {
  2217. // 1. Assert: r’s url is a potentially trustworthy URL.
  2218. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  2219. // 2. Let header be a Structured Header whose value is a token.
  2220. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  2221. // 3. Set header’s value to r’s mode.
  2222. auto header_value = MUST(ByteBuffer::copy(Infrastructure::request_mode_to_string(request.mode()).bytes()));
  2223. // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
  2224. auto header = Infrastructure::Header {
  2225. .name = MUST(ByteBuffer::copy("Sec-Fetch-Mode"sv.bytes())),
  2226. .value = move(header_value),
  2227. };
  2228. request.header_list()->append(move(header));
  2229. }
  2230. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-site
  2231. void set_sec_fetch_site_header(Infrastructure::Request& request)
  2232. {
  2233. // 1. Assert: r’s url is a potentially trustworthy URL.
  2234. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  2235. // 2. Let header be a Structured Header whose value is a token.
  2236. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  2237. // 3. Set header’s value to same-origin.
  2238. auto header_value = "same-origin"sv;
  2239. // FIXME: 4. If r is a navigation request that was explicitly caused by a user’s interaction with the user agent (by typing an address
  2240. // into the user agent directly, for example, or by clicking a bookmark, etc.), then set header’s value to none.
  2241. // 5. If header’s value is not none, then for each url in r’s url list:
  2242. if (!header_value.equals_ignoring_ascii_case("none"sv)) {
  2243. for (auto& url : request.url_list()) {
  2244. // 1. If url is same origin with r’s origin, continue.
  2245. if (url.origin().is_same_origin(request.current_url().origin()))
  2246. continue;
  2247. // 2. Set header’s value to cross-site.
  2248. header_value = "cross-site"sv;
  2249. // FIXME: 3. If r’s origin is not same site with url’s origin, then break.
  2250. // FIXME: 4. Set header’s value to same-site.
  2251. }
  2252. }
  2253. // 6. Set a structured field value `Sec-Fetch-Site`/header in r’s header list.
  2254. auto header = Infrastructure::Header {
  2255. .name = MUST(ByteBuffer::copy("Sec-Fetch-Site"sv.bytes())),
  2256. .value = MUST(ByteBuffer::copy(header_value.bytes())),
  2257. };
  2258. request.header_list()->append(move(header));
  2259. }
  2260. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-user
  2261. void set_sec_fetch_user_header(Infrastructure::Request& request)
  2262. {
  2263. // 1. Assert: r’s url is a potentially trustworthy URL.
  2264. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  2265. // 2. If r is not a navigation request, or if r’s user-activation is false, return.
  2266. if (!request.is_navigation_request() || !request.user_activation())
  2267. return;
  2268. // 3. Let header be a Structured Header whose value is a token.
  2269. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  2270. // 4. Set header’s value to true.
  2271. // NOTE: See https://datatracker.ietf.org/doc/html/rfc8941#name-booleans for boolean format in RFC 8941.
  2272. auto header_value = MUST(ByteBuffer::copy("?1"sv.bytes()));
  2273. // 5. Set a structured field value `Sec-Fetch-User`/header in r’s header list.
  2274. auto header = Infrastructure::Header {
  2275. .name = MUST(ByteBuffer::copy("Sec-Fetch-User"sv.bytes())),
  2276. .value = move(header_value),
  2277. };
  2278. request.header_list()->append(move(header));
  2279. }
  2280. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-append-the-fetch-metadata-headers-for-a-request
  2281. void append_fetch_metadata_headers_for_request(Infrastructure::Request& request)
  2282. {
  2283. // 1. If r’s url is not an potentially trustworthy URL, return.
  2284. if (SecureContexts::is_url_potentially_trustworthy(request.url()) != SecureContexts::Trustworthiness::PotentiallyTrustworthy)
  2285. return;
  2286. // 2. Set the Sec-Fetch-Dest header for r.
  2287. set_sec_fetch_dest_header(request);
  2288. // 3. Set the Sec-Fetch-Mode header for r.
  2289. set_sec_fetch_mode_header(request);
  2290. // 4. Set the Sec-Fetch-Site header for r.
  2291. set_sec_fetch_site_header(request);
  2292. // 5. Set the Sec-Fetch-User header for r.
  2293. set_sec_fetch_user_header(request);
  2294. }
  2295. }