Fetching.cpp 151 KB

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