Fetching.cpp 158 KB

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