Fetching.cpp 118 KB

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