Fetching.cpp 117 KB

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