Fetching.cpp 147 KB

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