Fetching.cpp 138 KB

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