XMLHttpRequest.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022-2023, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  6. * Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/ByteBuffer.h>
  11. #include <AK/Debug.h>
  12. #include <AK/GenericLexer.h>
  13. #include <AK/QuickSort.h>
  14. #include <LibJS/Runtime/ArrayBuffer.h>
  15. #include <LibJS/Runtime/Completion.h>
  16. #include <LibJS/Runtime/FunctionObject.h>
  17. #include <LibJS/Runtime/GlobalObject.h>
  18. #include <LibTextCodec/Decoder.h>
  19. #include <LibURL/Origin.h>
  20. #include <LibWeb/Bindings/XMLHttpRequestPrototype.h>
  21. #include <LibWeb/DOM/Document.h>
  22. #include <LibWeb/DOM/DocumentLoading.h>
  23. #include <LibWeb/DOM/Event.h>
  24. #include <LibWeb/DOM/EventDispatcher.h>
  25. #include <LibWeb/DOM/IDLEventListener.h>
  26. #include <LibWeb/DOM/XMLDocument.h>
  27. #include <LibWeb/Fetch/BodyInit.h>
  28. #include <LibWeb/Fetch/Fetching/Fetching.h>
  29. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  30. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  31. #include <LibWeb/Fetch/Infrastructure/HTTP.h>
  32. #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
  33. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  34. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  35. #include <LibWeb/FileAPI/Blob.h>
  36. #include <LibWeb/HTML/EventHandler.h>
  37. #include <LibWeb/HTML/EventNames.h>
  38. #include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>
  39. #include <LibWeb/HTML/Parser/HTMLParser.h>
  40. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  41. #include <LibWeb/HTML/Window.h>
  42. #include <LibWeb/Infra/ByteSequences.h>
  43. #include <LibWeb/Infra/JSON.h>
  44. #include <LibWeb/Infra/Strings.h>
  45. #include <LibWeb/Loader/ResourceLoader.h>
  46. #include <LibWeb/Page/Page.h>
  47. #include <LibWeb/Platform/EventLoopPlugin.h>
  48. #include <LibWeb/WebIDL/DOMException.h>
  49. #include <LibWeb/WebIDL/ExceptionOr.h>
  50. #include <LibWeb/XHR/EventNames.h>
  51. #include <LibWeb/XHR/ProgressEvent.h>
  52. #include <LibWeb/XHR/XMLHttpRequest.h>
  53. #include <LibWeb/XHR/XMLHttpRequestUpload.h>
  54. namespace Web::XHR {
  55. JS_DEFINE_ALLOCATOR(XMLHttpRequest);
  56. WebIDL::ExceptionOr<JS::NonnullGCPtr<XMLHttpRequest>> XMLHttpRequest::construct_impl(JS::Realm& realm)
  57. {
  58. auto upload_object = realm.heap().allocate<XMLHttpRequestUpload>(realm, realm);
  59. auto author_request_headers = Fetch::Infrastructure::HeaderList::create(realm.vm());
  60. auto response = Fetch::Infrastructure::Response::network_error(realm.vm(), "Not sent yet"sv);
  61. auto fetch_controller = Fetch::Infrastructure::FetchController::create(realm.vm());
  62. return realm.heap().allocate<XMLHttpRequest>(realm, realm, *upload_object, *author_request_headers, *response, *fetch_controller);
  63. }
  64. XMLHttpRequest::XMLHttpRequest(JS::Realm& realm, XMLHttpRequestUpload& upload_object, Fetch::Infrastructure::HeaderList& author_request_headers, Fetch::Infrastructure::Response& response, Fetch::Infrastructure::FetchController& fetch_controller)
  65. : XMLHttpRequestEventTarget(realm)
  66. , m_upload_object(upload_object)
  67. , m_author_request_headers(author_request_headers)
  68. , m_response(response)
  69. , m_response_type(Bindings::XMLHttpRequestResponseType::Empty)
  70. , m_fetch_controller(fetch_controller)
  71. {
  72. set_overrides_must_survive_garbage_collection(true);
  73. }
  74. XMLHttpRequest::~XMLHttpRequest() = default;
  75. void XMLHttpRequest::initialize(JS::Realm& realm)
  76. {
  77. Base::initialize(realm);
  78. WEB_SET_PROTOTYPE_FOR_INTERFACE(XMLHttpRequest);
  79. }
  80. void XMLHttpRequest::visit_edges(Cell::Visitor& visitor)
  81. {
  82. Base::visit_edges(visitor);
  83. visitor.visit(m_upload_object);
  84. visitor.visit(m_author_request_headers);
  85. visitor.visit(m_request_body);
  86. visitor.visit(m_response);
  87. visitor.visit(m_fetch_controller);
  88. if (auto* value = m_response_object.get_pointer<JS::NonnullGCPtr<JS::Object>>())
  89. visitor.visit(*value);
  90. }
  91. // https://xhr.spec.whatwg.org/#concept-event-fire-progress
  92. static void fire_progress_event(XMLHttpRequestEventTarget& target, FlyString const& event_name, u64 transmitted, u64 length)
  93. {
  94. // To fire a progress event named e at target, given transmitted and length, means to fire an event named e at target, using ProgressEvent,
  95. // with the loaded attribute initialized to transmitted, and if length is not 0, with the lengthComputable attribute initialized to true
  96. // and the total attribute initialized to length.
  97. ProgressEventInit event_init {};
  98. event_init.length_computable = true;
  99. event_init.loaded = transmitted;
  100. event_init.total = length;
  101. // FIXME: If we're in an async context, this will propagate to a callback context which can't propagate it anywhere else and does not expect this to fail.
  102. target.dispatch_event(*ProgressEvent::create(target.realm(), event_name, event_init));
  103. }
  104. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext
  105. WebIDL::ExceptionOr<String> XMLHttpRequest::response_text() const
  106. {
  107. // 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.
  108. if (m_response_type != Bindings::XMLHttpRequestResponseType::Empty && m_response_type != Bindings::XMLHttpRequestResponseType::Text)
  109. return WebIDL::InvalidStateError::create(realm(), "XHR responseText can only be used for responseType \"\" or \"text\""_string);
  110. // 2. If this’s state is not loading or done, then return the empty string.
  111. if (m_state != State::Loading && m_state != State::Done)
  112. return String {};
  113. // 3. Return the result of getting a text response for this.
  114. return get_text_response();
  115. }
  116. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsexml
  117. WebIDL::ExceptionOr<JS::GCPtr<DOM::Document>> XMLHttpRequest::response_xml()
  118. {
  119. // 1. If this’s response type is not the empty string or "document", then throw an "InvalidStateError" DOMException.
  120. if (m_response_type != Bindings::XMLHttpRequestResponseType::Empty && m_response_type != Bindings::XMLHttpRequestResponseType::Document)
  121. return WebIDL::InvalidStateError::create(realm(), "XHR responseXML can only be used for responseXML \"\" or \"document\""_string);
  122. // 2. If this’s state is not done, then return null.
  123. if (m_state != State::Done)
  124. return nullptr;
  125. // 3. Assert: this’s response object is not failure.
  126. VERIFY(!m_response_object.has<Failure>());
  127. // 4. If this’s response object is non-null, then return it.
  128. if (!m_response_object.has<Empty>())
  129. return &verify_cast<DOM::Document>(*m_response_object.get<JS::NonnullGCPtr<JS::Object>>());
  130. // 5. Set a document response for this.
  131. set_document_response();
  132. // 6. Return this’s response object.
  133. if (m_response_object.has<Empty>())
  134. return nullptr;
  135. return &verify_cast<DOM::Document>(*m_response_object.get<JS::NonnullGCPtr<JS::Object>>());
  136. }
  137. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype
  138. WebIDL::ExceptionOr<void> XMLHttpRequest::set_response_type(Bindings::XMLHttpRequestResponseType response_type)
  139. {
  140. // 1. If the current global object is not a Window object and the given value is "document", then return.
  141. if (!is<HTML::Window>(HTML::current_global_object()) && response_type == Bindings::XMLHttpRequestResponseType::Document)
  142. return {};
  143. // 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  144. if (m_state == State::Loading || m_state == State::Done)
  145. return WebIDL::InvalidStateError::create(realm(), "Can't readyState when XHR is loading or done"_string);
  146. // 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.
  147. if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
  148. return WebIDL::InvalidAccessError::create(realm(), "Can't set readyState on synchronous XHR in Window environment"_string);
  149. // 4. Set this’s response type to the given value.
  150. m_response_type = response_type;
  151. return {};
  152. }
  153. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-response
  154. WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response()
  155. {
  156. auto& vm = this->vm();
  157. // 1. If this’s response type is the empty string or "text", then:
  158. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty || m_response_type == Bindings::XMLHttpRequestResponseType::Text) {
  159. // 1. If this’s state is not loading or done, then return the empty string.
  160. if (m_state != State::Loading && m_state != State::Done)
  161. return JS::PrimitiveString::create(vm, String {});
  162. // 2. Return the result of getting a text response for this.
  163. return JS::PrimitiveString::create(vm, get_text_response());
  164. }
  165. // 2. If this’s state is not done, then return null.
  166. if (m_state != State::Done)
  167. return JS::js_null();
  168. // 3. If this’s response object is failure, then return null.
  169. if (m_response_object.has<Failure>())
  170. return JS::js_null();
  171. // 4. If this’s response object is non-null, then return it.
  172. if (!m_response_object.has<Empty>())
  173. return m_response_object.get<JS::NonnullGCPtr<JS::Object>>();
  174. // 5. If this’s response type is "arraybuffer",
  175. if (m_response_type == Bindings::XMLHttpRequestResponseType::Arraybuffer) {
  176. // then set this’s response object to a new ArrayBuffer object representing this’s received bytes. If this throws an exception, then set this’s response object to failure and return null.
  177. auto buffer_result = JS::ArrayBuffer::create(realm(), m_received_bytes.size());
  178. if (buffer_result.is_error()) {
  179. m_response_object = Failure();
  180. return JS::js_null();
  181. }
  182. auto buffer = buffer_result.release_value();
  183. buffer->buffer().overwrite(0, m_received_bytes.data(), m_received_bytes.size());
  184. m_response_object = JS::NonnullGCPtr<JS::Object> { buffer };
  185. }
  186. // 6. Otherwise, if this’s response type is "blob", set this’s response object to a new Blob object representing this’s received bytes with type set to the result of get a final MIME type for this.
  187. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Blob) {
  188. auto mime_type_as_string = TRY_OR_THROW_OOM(vm, TRY_OR_THROW_OOM(vm, get_final_mime_type()).serialized());
  189. auto blob_part = FileAPI::Blob::create(realm(), m_received_bytes, move(mime_type_as_string));
  190. auto blob = FileAPI::Blob::create(realm(), Vector<FileAPI::BlobPart> { JS::make_handle(*blob_part) });
  191. m_response_object = JS::NonnullGCPtr<JS::Object> { blob };
  192. }
  193. // 7. Otherwise, if this’s response type is "document", set a document response for this.
  194. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Document) {
  195. set_document_response();
  196. }
  197. // 8. Otherwise:
  198. else {
  199. // 1. Assert: this’s response type is "json".
  200. // Note: Automatically done by the layers above us.
  201. // 2. If this’s response’s body is null, then return null.
  202. if (!m_response->body())
  203. return JS::js_null();
  204. // 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an exception, then return null.
  205. auto json_object_result = Infra::parse_json_bytes_to_javascript_value(realm(), m_received_bytes);
  206. if (json_object_result.is_error())
  207. return JS::js_null();
  208. // 4. Set this’s response object to jsonObject.
  209. if (json_object_result.value().is_object())
  210. m_response_object = JS::NonnullGCPtr<JS::Object> { json_object_result.release_value().as_object() };
  211. else
  212. m_response_object = Empty {};
  213. }
  214. // 9. Return this’s response object.
  215. return m_response_object.visit(
  216. [](JS::NonnullGCPtr<JS::Object> object) -> JS::Value { return object; },
  217. [](auto const&) -> JS::Value { return JS::js_null(); });
  218. }
  219. // https://xhr.spec.whatwg.org/#text-response
  220. String XMLHttpRequest::get_text_response() const
  221. {
  222. // 1. If xhr’s response’s body is null, then return the empty string.
  223. if (!m_response->body())
  224. return String {};
  225. // 2. Let charset be the result of get a final encoding for xhr.
  226. auto charset = get_final_encoding().release_value_but_fixme_should_propagate_errors();
  227. // 3. If xhr’s response type is the empty string, charset is null, and the result of get a final MIME type for xhr is an XML MIME type,
  228. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && !charset.has_value() && get_final_mime_type().release_value_but_fixme_should_propagate_errors().is_xml()) {
  229. // FIXME: then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
  230. }
  231. // 4. If charset is null, then set charset to UTF-8.
  232. if (!charset.has_value())
  233. charset = "UTF-8"sv;
  234. // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.
  235. auto decoder = TextCodec::decoder_for(charset.value());
  236. // If we don't support the decoder yet, let's crash instead of attempting to return something, as the result would be incorrect and create obscure bugs.
  237. VERIFY(decoder.has_value());
  238. return TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, m_received_bytes).release_value_but_fixme_should_propagate_errors();
  239. }
  240. // https://xhr.spec.whatwg.org/#document-response
  241. void XMLHttpRequest::set_document_response()
  242. {
  243. // 1. If xhr’s response’s body is null, then return.
  244. if (!m_response->body())
  245. return;
  246. // 2. Let finalMIME be the result of get a final MIME type for xhr.
  247. auto final_mine = MUST(get_final_mime_type());
  248. // 3. If finalMIME is not an HTML MIME type or an XML MIME type, then return.
  249. if (!final_mine.is_html() && !final_mine.is_xml())
  250. return;
  251. // 4. If xhr’s response type is the empty string and finalMIME is an HTML MIME type, then return.
  252. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && final_mine.is_html())
  253. return;
  254. // 5. If finalMIME is an HTML MIME type, then:
  255. Optional<String> charset;
  256. JS::GCPtr<DOM::Document> document;
  257. if (final_mine.is_html()) {
  258. // 5.1. Let charset be the result of get a final encoding for xhr.
  259. if (auto final_encoding = MUST(get_final_encoding()); final_encoding.has_value())
  260. charset = MUST(String::from_utf8(*final_encoding));
  261. // 5.2. If charset is null, prescan the first 1024 bytes of xhr’s received bytes and if that does not terminate unsuccessfully then let charset be the return value.
  262. document = DOM::Document::create(realm());
  263. if (!charset.has_value())
  264. if (auto found_charset = HTML::run_prescan_byte_stream_algorithm(*document, m_received_bytes); found_charset.has_value())
  265. charset = MUST(String::from_byte_string(found_charset.value()));
  266. // 5.3. If charset is null, then set charset to UTF-8.
  267. if (!charset.has_value())
  268. charset = "UTF-8"_string;
  269. // 5.4. Let document be a document that represents the result parsing xhr’s received bytes following the rules set forth in the HTML Standard for an HTML parser with scripting disabled and a known definite encoding charset.
  270. auto parser = HTML::HTMLParser::create(*document, m_received_bytes, charset.value());
  271. parser->run(document->url());
  272. // 5.5. Flag document as an HTML document.
  273. document->set_document_type(DOM::Document::Type::HTML);
  274. }
  275. // 6. Otherwise, let document be a document that represents the result of running the XML parser with XML scripting support disabled on xhr’s received bytes. If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.
  276. else {
  277. document = DOM::XMLDocument::create(realm(), m_response->url().value_or({}));
  278. if (!Web::build_xml_document(*document, m_received_bytes, {})) {
  279. m_response_object = Empty {};
  280. return;
  281. }
  282. }
  283. // 7. If charset is null, then set charset to UTF-8.
  284. if (!charset.has_value())
  285. charset = "UTF-8"_string;
  286. // 8. Set document’s encoding to charset.
  287. document->set_encoding(move(charset));
  288. // 9. Set document’s content type to finalMIME.
  289. document->set_content_type(MUST(final_mine.serialized()));
  290. // 10. Set document’s URL to xhr’s response’s URL.
  291. document->set_url(m_response->url().value_or({}));
  292. // 11. Set document’s origin to xhr’s relevant settings object’s origin.
  293. document->set_origin(HTML::relevant_settings_object(*this).origin());
  294. // 12. Set xhr’s response object to document.
  295. m_response_object = JS::NonnullGCPtr<JS::Object> { *document };
  296. }
  297. // https://xhr.spec.whatwg.org/#final-mime-type
  298. ErrorOr<MimeSniff::MimeType> XMLHttpRequest::get_final_mime_type() const
  299. {
  300. // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.
  301. if (!m_override_mime_type.has_value())
  302. return get_response_mime_type();
  303. // 2. Return xhr’s override MIME type.
  304. return *m_override_mime_type;
  305. }
  306. // https://xhr.spec.whatwg.org/#response-mime-type
  307. ErrorOr<MimeSniff::MimeType> XMLHttpRequest::get_response_mime_type() const
  308. {
  309. // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.
  310. auto mime_type = m_response->header_list()->extract_mime_type();
  311. // 2. If mimeType is failure, then set mimeType to text/xml.
  312. if (!mime_type.has_value())
  313. return MimeSniff::MimeType::create("text"_string, "xml"_string);
  314. // 3. Return mimeType.
  315. return mime_type.release_value();
  316. }
  317. // https://xhr.spec.whatwg.org/#final-charset
  318. ErrorOr<Optional<StringView>> XMLHttpRequest::get_final_encoding() const
  319. {
  320. // 1. Let label be null.
  321. Optional<String> label;
  322. // 2. Let responseMIME be the result of get a response MIME type for xhr.
  323. auto response_mime = TRY(get_response_mime_type());
  324. // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
  325. auto response_mime_charset_it = response_mime.parameters().find("charset"sv);
  326. if (response_mime_charset_it != response_mime.parameters().end())
  327. label = response_mime_charset_it->value;
  328. // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
  329. if (m_override_mime_type.has_value()) {
  330. auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);
  331. if (override_mime_charset_it != m_override_mime_type->parameters().end())
  332. label = override_mime_charset_it->value;
  333. }
  334. // 5. If label is null, then return null.
  335. if (!label.has_value())
  336. return OptionalNone {};
  337. // 6. Let encoding be the result of getting an encoding from label.
  338. auto encoding = TextCodec::get_standardized_encoding(label.value());
  339. // 7. If encoding is failure, then return null.
  340. // 8. Return encoding.
  341. return encoding;
  342. }
  343. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  344. WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(String const& name_string, String const& value_string)
  345. {
  346. auto& realm = this->realm();
  347. auto& vm = realm.vm();
  348. auto name = name_string.bytes();
  349. auto value = value_string.bytes();
  350. // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
  351. if (m_state != State::Opened)
  352. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED"_string);
  353. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  354. if (m_send)
  355. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set"_string);
  356. // 3. Normalize value.
  357. auto normalized_value = Fetch::Infrastructure::normalize_header_value(value);
  358. // 4. If name is not a header name or value is not a header value, then throw a "SyntaxError" DOMException.
  359. if (!Fetch::Infrastructure::is_header_name(name))
  360. return WebIDL::SyntaxError::create(realm, "Header name contains invalid characters."_string);
  361. if (!Fetch::Infrastructure::is_header_value(value))
  362. return WebIDL::SyntaxError::create(realm, "Header value contains invalid characters."_string);
  363. auto header = Fetch::Infrastructure::Header {
  364. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name)),
  365. .value = move(normalized_value),
  366. };
  367. // 5. If (name, value) is a forbidden request-header, then return.
  368. if (Fetch::Infrastructure::is_forbidden_request_header(header))
  369. return {};
  370. // 6. Combine (name, value) in this’s author request headers.
  371. m_author_request_headers->combine(move(header));
  372. return {};
  373. }
  374. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  375. WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method_string, String const& url)
  376. {
  377. // 7. If the async argument is omitted, set async to true, and set username and password to null.
  378. return open(method_string, url, true, Optional<String> {}, Optional<String> {});
  379. }
  380. WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method_string, String const& url, bool async, Optional<String> const& username, Optional<String> const& password)
  381. {
  382. auto method = method_string.bytes();
  383. // 1. If this’s relevant global object is a Window object and its associated Document is not fully active, then throw an "InvalidStateError" DOMException.
  384. if (is<HTML::Window>(HTML::relevant_global_object(*this))) {
  385. auto const& window = static_cast<HTML::Window const&>(HTML::relevant_global_object(*this));
  386. if (!window.associated_document().is_fully_active())
  387. return WebIDL::InvalidStateError::create(realm(), "Invalid state: Window's associated document is not fully active."_string);
  388. }
  389. // 2. If method is not a method, then throw a "SyntaxError" DOMException.
  390. if (!Fetch::Infrastructure::is_method(method))
  391. return WebIDL::SyntaxError::create(realm(), "An invalid or illegal string was specified."_string);
  392. // 3. If method is a forbidden method, then throw a "SecurityError" DOMException.
  393. if (Fetch::Infrastructure::is_forbidden_method(method))
  394. return WebIDL::SecurityError::create(realm(), "Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'"_string);
  395. // 4. Normalize method.
  396. auto normalized_method = Fetch::Infrastructure::normalize_method(method);
  397. // 5. Let parsedURL be the result of parsing url with this’s relevant settings object’s API base URL and this’s relevant settings object’s API URL character encoding.
  398. // FIXME: Pass in this’s relevant settings object’s API URL character encoding.
  399. auto parsed_url = HTML::relevant_settings_object(*this).api_base_url().complete_url(url);
  400. // 6. If parsedURL is failure, then throw a "SyntaxError" DOMException.
  401. if (!parsed_url.is_valid())
  402. return WebIDL::SyntaxError::create(realm(), "Invalid URL"_string);
  403. // 7. If the async argument is omitted, set async to true, and set username and password to null.
  404. // NOTE: This is handled in the overload lacking the async argument.
  405. // 8. If parsedURL’s host is non-null, then:
  406. if (!parsed_url.host().has<Empty>()) {
  407. // 1. If the username argument is not null, set the username given parsedURL and username.
  408. if (username.has_value())
  409. parsed_url.set_username(username.value());
  410. // 2. If the password argument is not null, set the password given parsedURL and password.
  411. if (password.has_value())
  412. parsed_url.set_password(password.value());
  413. }
  414. // 9. If async is false, the current global object is a Window object, and either this’s timeout is
  415. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  416. if (!async
  417. && is<HTML::Window>(HTML::current_global_object())
  418. && (m_timeout != 0 || m_response_type != Bindings::XMLHttpRequestResponseType::Empty)) {
  419. return WebIDL::InvalidAccessError::create(realm(), "Synchronous XMLHttpRequests in a Window context do not support timeout or a non-empty responseType"_string);
  420. }
  421. // 10. Terminate this’s fetch controller.
  422. // Spec Note: A fetch can be ongoing at this point.
  423. m_fetch_controller->terminate();
  424. // 11. Set variables associated with the object as follows:
  425. // Unset this’s send() flag.
  426. m_send = false;
  427. // Unset this’s upload listener flag.
  428. m_upload_listener = false;
  429. // Set this’s request method to method.
  430. m_request_method = normalized_method.span();
  431. // Set this’s request URL to parsedURL.
  432. m_request_url = parsed_url;
  433. // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  434. m_synchronous = !async;
  435. // Empty this’s author request headers.
  436. m_author_request_headers->clear();
  437. // Set this’s response to a network error.
  438. m_response = Fetch::Infrastructure::Response::network_error(realm().vm(), "Not yet sent"sv);
  439. // Set this’s received bytes to the empty byte sequence.
  440. m_received_bytes = {};
  441. // Set this’s response object to null.
  442. m_response_object = {};
  443. // Spec Note: Override MIME type is not overridden here as the overrideMimeType() method can be invoked before the open() method.
  444. // 12. If this’s state is not opened, then:
  445. if (m_state != State::Opened) {
  446. // 1. Set this’s state to opened.
  447. m_state = State::Opened;
  448. // 2. Fire an event named readystatechange at this.
  449. dispatch_event(DOM::Event::create(realm(), EventNames::readystatechange));
  450. }
  451. return {};
  452. }
  453. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  454. WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequestBodyInit> body)
  455. {
  456. auto& vm = this->vm();
  457. auto& realm = *vm.current_realm();
  458. // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
  459. if (m_state != State::Opened)
  460. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED"_string);
  461. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  462. if (m_send)
  463. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set"_string);
  464. // 3. If this’s request method is `GET` or `HEAD`, then set body to null.
  465. if (m_request_method.is_one_of("GET"sv, "HEAD"sv))
  466. body = {};
  467. // 4. If body is not null, then:
  468. if (body.has_value()) {
  469. // 1. Let extractedContentType be null.
  470. Optional<ByteBuffer> extracted_content_type;
  471. // 2. If body is a Document, then set this’s request body to body, serialized, converted, and UTF-8 encoded.
  472. if (body->has<JS::Handle<DOM::Document>>()) {
  473. auto string_serialized_document = TRY(body->get<JS::Handle<DOM::Document>>().cell()->serialize_fragment(DOMParsing::RequireWellFormed::No));
  474. m_request_body = TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, string_serialized_document.bytes()));
  475. }
  476. // 3. Otherwise:
  477. else {
  478. // 1. Let bodyWithType be the result of safely extracting body.
  479. auto body_with_type = TRY(Fetch::safely_extract_body(realm, body->downcast<Fetch::BodyInitOrReadableBytes>()));
  480. // 2. Set this’s request body to bodyWithType’s body.
  481. m_request_body = move(body_with_type.body);
  482. // 3. Set extractedContentType to bodyWithType’s type.
  483. extracted_content_type = move(body_with_type.type);
  484. }
  485. // 4. Let originalAuthorContentType be the result of getting `Content-Type` from this’s author request headers.
  486. auto original_author_content_type = m_author_request_headers->get("Content-Type"sv.bytes());
  487. // 5. If originalAuthorContentType is non-null, then:
  488. if (original_author_content_type.has_value()) {
  489. // 1. If body is a Document or a USVString, then:
  490. if (body->has<JS::Handle<DOM::Document>>() || body->has<String>()) {
  491. // 1. Let contentTypeRecord be the result of parsing originalAuthorContentType.
  492. auto content_type_record = TRY_OR_THROW_OOM(vm, MimeSniff::MimeType::parse(original_author_content_type.value()));
  493. // 2. If contentTypeRecord is not failure, contentTypeRecord’s parameters["charset"] exists, and parameters["charset"] is not an ASCII case-insensitive match for "UTF-8", then:
  494. if (content_type_record.has_value()) {
  495. auto charset_parameter_iterator = content_type_record->parameters().find("charset"sv);
  496. if (charset_parameter_iterator != content_type_record->parameters().end() && !Infra::is_ascii_case_insensitive_match(charset_parameter_iterator->value, "UTF-8"sv)) {
  497. // 1. Set contentTypeRecord’s parameters["charset"] to "UTF-8".
  498. TRY_OR_THROW_OOM(vm, content_type_record->set_parameter("charset"_string, "UTF-8"_string));
  499. // 2. Let newContentTypeSerialized be the result of serializing contentTypeRecord.
  500. auto new_content_type_serialized = TRY_OR_THROW_OOM(vm, content_type_record->serialized());
  501. // 3. Set (`Content-Type`, newContentTypeSerialized) in this’s author request headers.
  502. auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, new_content_type_serialized);
  503. m_author_request_headers->set(move(header));
  504. }
  505. }
  506. }
  507. }
  508. // 6. Otherwise:
  509. else {
  510. if (body->has<JS::Handle<DOM::Document>>()) {
  511. auto document = body->get<JS::Handle<DOM::Document>>();
  512. // NOTE: A document can only be an HTML document or XML document.
  513. // 1. If body is an HTML document, then set (`Content-Type`, `text/html;charset=UTF-8`) in this’s author request headers.
  514. if (document->is_html_document()) {
  515. auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=UTF-8"sv);
  516. m_author_request_headers->set(move(header));
  517. }
  518. // 2. Otherwise, if body is an XML document, set (`Content-Type`, `application/xml;charset=UTF-8`) in this’s author request headers.
  519. else if (document->is_xml_document()) {
  520. auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "application/xml;charset=UTF-8"sv);
  521. m_author_request_headers->set(move(header));
  522. } else {
  523. VERIFY_NOT_REACHED();
  524. }
  525. }
  526. // 3. Otherwise, if extractedContentType is not null, set (`Content-Type`, extractedContentType) in this’s author request headers.
  527. else if (extracted_content_type.has_value()) {
  528. auto header = Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, extracted_content_type.value());
  529. m_author_request_headers->set(move(header));
  530. }
  531. }
  532. }
  533. // 5. If one or more event listeners are registered on this’s upload object, then set this’s upload listener flag.
  534. m_upload_listener = m_upload_object->has_event_listeners();
  535. // 6. Let req be a new request, initialized as follows:
  536. auto request = Fetch::Infrastructure::Request::create(vm);
  537. // method
  538. // This’s request method.
  539. request->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(m_request_method.bytes())));
  540. // URL
  541. // This’s request URL.
  542. request->set_url(m_request_url);
  543. // header list
  544. // This’s author request headers.
  545. request->set_header_list(m_author_request_headers);
  546. // unsafe-request flag
  547. // Set.
  548. request->set_unsafe_request(true);
  549. // body
  550. // This’s request body.
  551. if (m_request_body)
  552. request->set_body(JS::NonnullGCPtr { *m_request_body });
  553. // client
  554. // This’s relevant settings object.
  555. request->set_client(&HTML::relevant_settings_object(*this));
  556. // mode
  557. // "cors".
  558. request->set_mode(Fetch::Infrastructure::Request::Mode::CORS);
  559. // use-CORS-preflight flag
  560. // Set if this’s upload listener flag is set.
  561. request->set_use_cors_preflight(m_upload_listener);
  562. // credentials mode
  563. // If this’s cross-origin credentials is true, then "include"; otherwise "same-origin".
  564. request->set_credentials_mode(m_cross_origin_credentials ? Fetch::Infrastructure::Request::CredentialsMode::Include : Fetch::Infrastructure::Request::CredentialsMode::SameOrigin);
  565. // use-URL-credentials flag
  566. // Set if this’s request URL includes credentials.
  567. request->set_use_url_credentials(m_request_url.includes_credentials());
  568. // initiator type
  569. // "xmlhttprequest".
  570. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::XMLHttpRequest);
  571. // 7. Unset this’s upload complete flag.
  572. m_upload_complete = false;
  573. // 8. Unset this’s timed out flag.
  574. m_timed_out = false;
  575. // 9. If req’s body is null, then set this’s upload complete flag.
  576. // NOTE: req's body is always m_request_body here, see step 6.
  577. if (!m_request_body)
  578. m_upload_complete = true;
  579. // 10. Set this’s send() flag.
  580. m_send = true;
  581. dbgln_if(SPAM_DEBUG, "{}XHR send from {} to {}", m_synchronous ? "\033[33;1mSynchronous\033[0m " : "", HTML::relevant_settings_object(*this).creation_url, m_request_url);
  582. // 11. If this’s synchronous flag is unset, then:
  583. if (!m_synchronous) {
  584. // 1. Fire a progress event named loadstart at this with 0 and 0.
  585. fire_progress_event(*this, EventNames::loadstart, 0, 0);
  586. // 2. Let requestBodyTransmitted be 0.
  587. // NOTE: This is kept on the XHR object itself instead of the stack, as we cannot capture references to stack variables in an async context.
  588. m_request_body_transmitted = 0;
  589. // 3. Let requestBodyLength be req’s body’s length, if req’s body is non-null; otherwise 0.
  590. // NOTE: req's body is always m_request_body here, see step 6.
  591. // 4. Assert: requestBodyLength is an integer.
  592. // NOTE: This is done to provide a better assertion failure message, whereas below the message would be "m_has_value"
  593. if (m_request_body)
  594. VERIFY(m_request_body->length().has_value());
  595. // NOTE: This is const to allow the callback functions to take a copy of it and know it won't change.
  596. auto const request_body_length = m_request_body ? m_request_body->length().value() : 0;
  597. // 5. If this’s upload complete flag is unset and this’s upload listener flag is set, then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted and requestBodyLength.
  598. if (!m_upload_complete && m_upload_listener)
  599. fire_progress_event(m_upload_object, EventNames::loadstart, m_request_body_transmitted, request_body_length);
  600. // 6. If this’s state is not opened or this’s send() flag is unset, then return.
  601. if (m_state != State::Opened || !m_send)
  602. return {};
  603. // 7. Let processRequestBodyChunkLength, given a bytesLength, be these steps:
  604. // NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.
  605. // NOTE: `this` is kept alive by FetchAlgorithms using JS::SafeFunction.
  606. auto process_request_body_chunk_length = [this, request_body_length](u64 bytes_length) {
  607. // 1. Increase requestBodyTransmitted by bytesLength.
  608. m_request_body_transmitted += bytes_length;
  609. // FIXME: 2. If not roughly 50ms have passed since these steps were last invoked, then return.
  610. // 3. If this’s upload listener flag is set, then fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.
  611. if (m_upload_listener)
  612. fire_progress_event(m_upload_object, EventNames::progress, m_request_body_transmitted, request_body_length);
  613. };
  614. // 8. Let processRequestEndOfBody be these steps:
  615. // NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.
  616. // NOTE: `this` is kept alive by FetchAlgorithms using JS::SafeFunction.
  617. auto process_request_end_of_body = [this, request_body_length]() {
  618. // 1. Set this’s upload complete flag.
  619. m_upload_complete = true;
  620. // 2. If this’s upload listener flag is unset, then return.
  621. if (!m_upload_listener)
  622. return;
  623. // 3. Fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.
  624. fire_progress_event(m_upload_object, EventNames::progress, m_request_body_transmitted, request_body_length);
  625. // 4. Fire a progress event named load at this’s upload object with requestBodyTransmitted and requestBodyLength.
  626. fire_progress_event(m_upload_object, EventNames::load, m_request_body_transmitted, request_body_length);
  627. // 5. Fire a progress event named loadend at this’s upload object with requestBodyTransmitted and requestBodyLength.
  628. fire_progress_event(m_upload_object, EventNames::loadend, m_request_body_transmitted, request_body_length);
  629. };
  630. // 9. Let processResponse, given a response, be these steps:
  631. // NOTE: `this` is kept alive by FetchAlgorithms using JS::SafeFunction.
  632. auto process_response = [this](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response) {
  633. // 1. Set this’s response to response.
  634. m_response = response;
  635. // 2. Handle errors for this.
  636. // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.
  637. // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
  638. handle_errors().release_value_but_fixme_should_propagate_errors();
  639. // 3. If this’s response is a network error, then return.
  640. if (m_response->is_network_error())
  641. return;
  642. // 4. Set this’s state to headers received.
  643. m_state = State::HeadersReceived;
  644. // 5. Fire an event named readystatechange at this.
  645. // FIXME: We're in an async context, so we can't propagate the error anywhere.
  646. dispatch_event(*DOM::Event::create(this->realm(), EventNames::readystatechange));
  647. // 6. If this’s state is not headers received, then return.
  648. if (m_state != State::HeadersReceived)
  649. return;
  650. // 7. If this’s response’s body is null, then run handle response end-of-body for this and return.
  651. if (!m_response->body()) {
  652. // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.
  653. // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
  654. handle_response_end_of_body().release_value_but_fixme_should_propagate_errors();
  655. return;
  656. }
  657. // 8. Let length be the result of extracting a length from this’s response’s header list.
  658. // FIXME: We're in an async context, so we can't propagate the error anywhere.
  659. auto length = m_response->header_list()->extract_length();
  660. // 9. If length is not an integer, then set it to 0.
  661. if (!length.has<u64>())
  662. length = 0;
  663. // FIXME: We can't implement these steps yet, as we don't fully implement the Streams standard.
  664. // 10. Let processBodyChunk given bytes be these steps:
  665. auto process_body_chunks = JS::create_heap_function(heap(), [this, length](ByteBuffer byte_buffer) {
  666. // 1. Append bytes to this’s received bytes.
  667. m_received_bytes.append(byte_buffer);
  668. // FIXME: 2. If not roughly 50ms have passed since these steps were last invoked, then return.
  669. // 3. If this’s state is headers received, then set this’s state to loading.
  670. if (m_state == State::HeadersReceived)
  671. m_state = State::Loading;
  672. // 4. Fire an event named readystatechange at this.
  673. // Spec Note: Web compatibility is the reason readystatechange fires more often than this’s state changes.
  674. dispatch_event(*DOM::Event::create(this->realm(), EventNames::readystatechange));
  675. // 5. Fire a progress event named progress at this with this’s received bytes’s length and length.
  676. fire_progress_event(*this, EventNames::progress, m_received_bytes.size(), length.get<u64>());
  677. });
  678. // 11. Let processEndOfBody be this step: run handle response end-of-body for this.
  679. auto process_end_of_body = JS::create_heap_function(heap(), [this]() {
  680. // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.
  681. // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
  682. handle_response_end_of_body().release_value_but_fixme_should_propagate_errors();
  683. });
  684. // 12. Let processBodyError be these steps:
  685. auto process_body_error = JS::create_heap_function(heap(), [this](JS::Value) {
  686. auto& vm = this->vm();
  687. // 1. Set this’s response to a network error.
  688. m_response = Fetch::Infrastructure::Response::network_error(vm, "A network error occurred processing body."sv);
  689. // 2. Run handle errors for this.
  690. // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.
  691. // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently.
  692. handle_errors().release_value_but_fixme_should_propagate_errors();
  693. });
  694. // 13. Incrementally read this’s response’s body, given processBodyChunk, processEndOfBody, processBodyError, and this’s relevant global object.
  695. auto global_object = JS::NonnullGCPtr<JS::Object> { HTML::relevant_global_object(*this) };
  696. response->body()->incrementally_read(process_body_chunks, process_end_of_body, process_body_error, global_object);
  697. };
  698. // 10. Set this’s fetch controller to the result of fetching req with processRequestBodyChunkLength set to processRequestBodyChunkLength, processRequestEndOfBody set to processRequestEndOfBody, and processResponse set to processResponse.
  699. m_fetch_controller = TRY(Fetch::Fetching::fetch(
  700. realm,
  701. request,
  702. Fetch::Infrastructure::FetchAlgorithms::create(vm,
  703. {
  704. .process_request_body_chunk_length = move(process_request_body_chunk_length),
  705. .process_request_end_of_body = move(process_request_end_of_body),
  706. .process_early_hints_response = {},
  707. .process_response = move(process_response),
  708. .process_response_end_of_body = {},
  709. .process_response_consume_body = {},
  710. })));
  711. // 11. Let now be the present time.
  712. // 12. Run these steps in parallel:
  713. // 1. Wait until either req’s done flag is set or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.
  714. // 2. If req’s done flag is unset, then set this’s timed out flag and terminate this’s fetch controller.
  715. if (m_timeout != 0) {
  716. auto timer = Platform::Timer::create_single_shot(m_timeout, nullptr);
  717. // NOTE: `timer` is kept alive by copying the NNRP into the lambda, incrementing its ref-count.
  718. // NOTE: `this` and `request` is kept alive by Platform::Timer using JS::SafeFunction.
  719. timer->on_timeout = [this, request, timer]() {
  720. if (!request->done()) {
  721. m_timed_out = true;
  722. m_fetch_controller->terminate();
  723. }
  724. };
  725. timer->start();
  726. }
  727. } else {
  728. // 1. Let processedResponse be false.
  729. bool processed_response = false;
  730. // 2. Let processResponseConsumeBody, given a response and nullOrFailureOrBytes, be these steps:
  731. auto process_response_consume_body = [this, &processed_response](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response, Variant<Empty, Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag, ByteBuffer> null_or_failure_or_bytes) {
  732. // 1. If nullOrFailureOrBytes is not failure, then set this’s response to response.
  733. if (!null_or_failure_or_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>())
  734. m_response = response;
  735. // 2. If nullOrFailureOrBytes is a byte sequence, then append nullOrFailureOrBytes to this’s received bytes.
  736. if (null_or_failure_or_bytes.has<ByteBuffer>()) {
  737. // NOTE: We are not in a context where we can throw if this fails due to OOM.
  738. m_received_bytes.append(null_or_failure_or_bytes.get<ByteBuffer>());
  739. }
  740. // 3. Set processedResponse to true.
  741. processed_response = true;
  742. };
  743. // 3. Set this’s fetch controller to the result of fetching req with processResponseConsumeBody set to processResponseConsumeBody and useParallelQueue set to true.
  744. m_fetch_controller = TRY(Fetch::Fetching::fetch(
  745. realm,
  746. request,
  747. Fetch::Infrastructure::FetchAlgorithms::create(vm,
  748. {
  749. .process_request_body_chunk_length = {},
  750. .process_request_end_of_body = {},
  751. .process_early_hints_response = {},
  752. .process_response = {},
  753. .process_response_end_of_body = {},
  754. .process_response_consume_body = move(process_response_consume_body),
  755. }),
  756. Fetch::Fetching::UseParallelQueue::Yes));
  757. // 4. Let now be the present time.
  758. // 5. Pause until either processedResponse is true or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.
  759. bool did_time_out = false;
  760. if (m_timeout != 0) {
  761. auto timer = Platform::Timer::create_single_shot(m_timeout, nullptr);
  762. // NOTE: `timer` is kept alive by copying the NNRP into the lambda, incrementing its ref-count.
  763. timer->on_timeout = [timer, &did_time_out]() {
  764. did_time_out = true;
  765. };
  766. timer->start();
  767. }
  768. // FIXME: This is not exactly correct, as it allows the HTML event loop to continue executing tasks.
  769. Platform::EventLoopPlugin::the().spin_until([&]() {
  770. return processed_response || did_time_out;
  771. });
  772. // 6. If processedResponse is false, then set this’s timed out flag and terminate this’s fetch controller.
  773. if (!processed_response) {
  774. m_timed_out = true;
  775. m_fetch_controller->terminate();
  776. }
  777. // FIXME: 7. Report timing for this’s fetch controller given the current global object.
  778. // We cannot do this for responses that have a body yet, as we do not setup the stream that then calls processResponseEndOfBody in `fetch_response_handover`.
  779. // 8. Run handle response end-of-body for this.
  780. TRY(handle_response_end_of_body());
  781. }
  782. return {};
  783. }
  784. WebIDL::CallbackType* XMLHttpRequest::onreadystatechange()
  785. {
  786. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  787. }
  788. void XMLHttpRequest::set_onreadystatechange(WebIDL::CallbackType* value)
  789. {
  790. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, value);
  791. }
  792. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getresponseheader
  793. WebIDL::ExceptionOr<Optional<String>> XMLHttpRequest::get_response_header(String const& name) const
  794. {
  795. auto& vm = this->vm();
  796. // The getResponseHeader(name) method steps are to return the result of getting name from this’s response’s header list.
  797. auto header_bytes = m_response->header_list()->get(name.bytes());
  798. return header_bytes.has_value() ? TRY_OR_THROW_OOM(vm, String::from_utf8(*header_bytes)) : Optional<String> {};
  799. }
  800. // https://xhr.spec.whatwg.org/#legacy-uppercased-byte-less-than
  801. static ErrorOr<bool> is_legacy_uppercased_byte_less_than(ReadonlyBytes a, ReadonlyBytes b)
  802. {
  803. // 1. Let A be a, byte-uppercased.
  804. auto uppercased_a = TRY(ByteBuffer::copy(a));
  805. Infra::byte_uppercase(uppercased_a);
  806. // 2. Let B be b, byte-uppercased.
  807. auto uppercased_b = TRY(ByteBuffer::copy(b));
  808. Infra::byte_uppercase(uppercased_b);
  809. // 3. Return A is byte less than B.
  810. return Infra::is_byte_less_than(uppercased_a, uppercased_b);
  811. }
  812. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getallresponseheaders
  813. WebIDL::ExceptionOr<String> XMLHttpRequest::get_all_response_headers() const
  814. {
  815. auto& vm = this->vm();
  816. // 1. Let output be an empty byte sequence.
  817. ByteBuffer output;
  818. // 2. Let initialHeaders be the result of running sort and combine with this’s response’s header list.
  819. auto initial_headers = m_response->header_list()->sort_and_combine();
  820. // 3. Let headers be the result of sorting initialHeaders in ascending order, with a being less than b if a’s name is legacy-uppercased-byte less than b’s name.
  821. // Spec Note: Unfortunately, this is needed for compatibility with deployed content.
  822. // NOTE: quick_sort mutates the collection instead of returning a sorted copy.
  823. quick_sort(initial_headers, [](Fetch::Infrastructure::Header const& a, Fetch::Infrastructure::Header const& b) {
  824. // FIXME: We are not in a context where we can throw from OOM.
  825. return is_legacy_uppercased_byte_less_than(a.name, b.name).release_value_but_fixme_should_propagate_errors();
  826. });
  827. // 4. For each header in headers, append header’s name, followed by a 0x3A 0x20 byte pair, followed by header’s value, followed by a 0x0D 0x0A byte pair, to output.
  828. for (auto const& header : initial_headers) {
  829. TRY_OR_THROW_OOM(vm, output.try_append(header.name));
  830. TRY_OR_THROW_OOM(vm, output.try_append(0x3A)); // ':'
  831. TRY_OR_THROW_OOM(vm, output.try_append(0x20)); // ' '
  832. TRY_OR_THROW_OOM(vm, output.try_append(header.value));
  833. TRY_OR_THROW_OOM(vm, output.try_append(0x0D)); // '\r'
  834. TRY_OR_THROW_OOM(vm, output.try_append(0x0A)); // '\n'
  835. }
  836. // 5. Return output.
  837. return TRY_OR_THROW_OOM(vm, String::from_utf8(output));
  838. }
  839. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  840. WebIDL::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
  841. {
  842. auto& vm = this->vm();
  843. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  844. if (m_state == State::Loading || m_state == State::Done)
  845. return WebIDL::InvalidStateError::create(realm(), "Cannot override MIME type when state is Loading or Done."_string);
  846. // 2. Set this’s override MIME type to the result of parsing mime.
  847. m_override_mime_type = TRY_OR_THROW_OOM(vm, MimeSniff::MimeType::parse(mime));
  848. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  849. if (!m_override_mime_type.has_value())
  850. m_override_mime_type = MimeSniff::MimeType::create("application"_string, "octet-stream"_string);
  851. return {};
  852. }
  853. // https://xhr.spec.whatwg.org/#ref-for-dom-xmlhttprequest-timeout%E2%91%A2
  854. WebIDL::ExceptionOr<void> XMLHttpRequest::set_timeout(u32 timeout)
  855. {
  856. // 1. If the current global object is a Window object and this’s synchronous flag is set,
  857. // then throw an "InvalidAccessError" DOMException.
  858. if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
  859. return WebIDL::InvalidAccessError::create(realm(), "Use of XMLHttpRequest's timeout attribute is not supported in the synchronous mode in window context."_string);
  860. // 2. Set this’s timeout to the given value.
  861. m_timeout = timeout;
  862. return {};
  863. }
  864. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-timeout
  865. u32 XMLHttpRequest::timeout() const { return m_timeout; }
  866. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
  867. bool XMLHttpRequest::with_credentials() const
  868. {
  869. // The withCredentials getter steps are to return this’s cross-origin credentials.
  870. return m_cross_origin_credentials;
  871. }
  872. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
  873. WebIDL::ExceptionOr<void> XMLHttpRequest::set_with_credentials(bool with_credentials)
  874. {
  875. auto& realm = this->realm();
  876. // 1. If this’s state is not unsent or opened, then throw an "InvalidStateError" DOMException.
  877. if (m_state != State::Unsent && m_state != State::Opened)
  878. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not UNSENT or OPENED"_string);
  879. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  880. if (m_send)
  881. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set"_string);
  882. // 3. Set this’s cross-origin credentials to the given value.
  883. m_cross_origin_credentials = with_credentials;
  884. return {};
  885. }
  886. // https://xhr.spec.whatwg.org/#garbage-collection
  887. bool XMLHttpRequest::must_survive_garbage_collection() const
  888. {
  889. // An XMLHttpRequest object must not be garbage collected
  890. // if its state is either opened with the send() flag set, headers received, or loading,
  891. // and it has one or more event listeners registered whose type is one of
  892. // readystatechange, progress, abort, error, load, timeout, and loadend.
  893. if ((m_state == State::Opened && m_send)
  894. || m_state == State::HeadersReceived
  895. || m_state == State::Loading) {
  896. if (has_event_listener(EventNames::readystatechange))
  897. return true;
  898. if (has_event_listener(EventNames::progress))
  899. return true;
  900. if (has_event_listener(EventNames::abort))
  901. return true;
  902. if (has_event_listener(EventNames::error))
  903. return true;
  904. if (has_event_listener(EventNames::load))
  905. return true;
  906. if (has_event_listener(EventNames::timeout))
  907. return true;
  908. if (has_event_listener(EventNames::loadend))
  909. return true;
  910. }
  911. // FIXME: If an XMLHttpRequest object is garbage collected while its connection is still open,
  912. // the user agent must terminate the XMLHttpRequest object’s fetch controller.
  913. // NOTE: This would go in XMLHttpRequest::finalize().
  914. return false;
  915. }
  916. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-abort
  917. void XMLHttpRequest::abort()
  918. {
  919. // 1. Abort this’s fetch controller.
  920. m_fetch_controller->abort(realm(), {});
  921. // 2. If this’s state is opened with this’s send() flag set, headers received, or loading, then run the request error steps for this and abort.
  922. if ((m_state == State::Opened || m_state == State::HeadersReceived || m_state == State::Loading) && m_send) {
  923. // NOTE: This cannot throw as we don't pass in an exception. XHR::abort cannot be reached in a synchronous context where the state matches above.
  924. // This is because it pauses inside XHR::send until the request is done or times out and then immediately calls `handle_response_end_of_body`
  925. // which will always set `m_state` to `Done`.
  926. MUST(request_error_steps(EventNames::abort));
  927. }
  928. // 3. If this’s state is done, then set this’s state to unsent and this’s response to a network error.
  929. // Spec Note: No readystatechange event is dispatched.
  930. if (m_state == State::Done) {
  931. m_state = State::Unsent;
  932. m_response = Fetch::Infrastructure::Response::network_error(vm(), "Not yet sent"sv);
  933. }
  934. }
  935. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-upload
  936. JS::NonnullGCPtr<XMLHttpRequestUpload> XMLHttpRequest::upload() const
  937. {
  938. // The upload getter steps are to return this’s upload object.
  939. return m_upload_object;
  940. }
  941. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-status
  942. Fetch::Infrastructure::Status XMLHttpRequest::status() const
  943. {
  944. // The status getter steps are to return this’s response’s status.
  945. return m_response->status();
  946. }
  947. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-statustext
  948. WebIDL::ExceptionOr<String> XMLHttpRequest::status_text() const
  949. {
  950. auto& vm = this->vm();
  951. // The statusText getter steps are to return this’s response’s status message.
  952. return TRY_OR_THROW_OOM(vm, String::from_utf8(m_response->status_message()));
  953. }
  954. // https://xhr.spec.whatwg.org/#handle-response-end-of-body
  955. WebIDL::ExceptionOr<void> XMLHttpRequest::handle_response_end_of_body()
  956. {
  957. auto& realm = this->realm();
  958. // 1. Handle errors for xhr.
  959. TRY(handle_errors());
  960. // 2. If xhr’s response is a network error, then return.
  961. if (m_response->is_network_error())
  962. return {};
  963. // 3. Let transmitted be xhr’s received bytes’s length.
  964. auto transmitted = m_received_bytes.size();
  965. // 4. Let length be the result of extracting a length from this’s response’s header list.
  966. auto maybe_length = m_response->header_list()->extract_length();
  967. // 5. If length is not an integer, then set it to 0.
  968. if (!maybe_length.has<u64>())
  969. maybe_length = 0;
  970. auto length = maybe_length.get<u64>();
  971. // 6. If xhr’s synchronous flag is unset, then fire a progress event named progress at xhr with transmitted and length.
  972. if (!m_synchronous)
  973. fire_progress_event(*this, EventNames::progress, transmitted, length);
  974. // 7. Set xhr’s state to done.
  975. m_state = State::Done;
  976. // 8. Unset xhr’s send() flag.
  977. m_send = false;
  978. // 9. Fire an event named readystatechange at xhr.
  979. // FIXME: If we're in an async context, this will propagate to a callback context which can't propagate it anywhere else and does not expect this to fail.
  980. dispatch_event(*DOM::Event::create(realm, EventNames::readystatechange));
  981. // 10. Fire a progress event named load at xhr with transmitted and length.
  982. fire_progress_event(*this, EventNames::load, transmitted, length);
  983. // 11. Fire a progress event named loadend at xhr with transmitted and length.
  984. fire_progress_event(*this, EventNames::loadend, transmitted, length);
  985. return {};
  986. }
  987. // https://xhr.spec.whatwg.org/#handle-errors
  988. WebIDL::ExceptionOr<void> XMLHttpRequest::handle_errors()
  989. {
  990. // 1. If xhr’s send() flag is unset, then return.
  991. if (!m_send)
  992. return {};
  993. // 2. If xhr’s timed out flag is set, then run the request error steps for xhr, timeout, and "TimeoutError" DOMException.
  994. if (m_timed_out)
  995. return TRY(request_error_steps(EventNames::timeout, WebIDL::TimeoutError::create(realm(), "Timed out"_string)));
  996. // 3. Otherwise, if xhr’s response’s aborted flag is set, run the request error steps for xhr, abort, and "AbortError" DOMException.
  997. if (m_response->aborted())
  998. return TRY(request_error_steps(EventNames::abort, WebIDL::AbortError::create(realm(), "Aborted"_string)));
  999. // 4. Otherwise, if xhr’s response is a network error, then run the request error steps for xhr, error, and "NetworkError" DOMException.
  1000. if (m_response->is_network_error())
  1001. return TRY(request_error_steps(EventNames::error, WebIDL::NetworkError::create(realm(), "Network error"_string)));
  1002. return {};
  1003. }
  1004. JS::ThrowCompletionOr<void> XMLHttpRequest::request_error_steps(FlyString const& event_name, JS::GCPtr<WebIDL::DOMException> exception)
  1005. {
  1006. // 1. Set xhr’s state to done.
  1007. m_state = State::Done;
  1008. // 2. Unset xhr’s send() flag.
  1009. m_send = false;
  1010. // 3. Set xhr’s response to a network error.
  1011. m_response = Fetch::Infrastructure::Response::network_error(realm().vm(), "Failed to load"sv);
  1012. // 4. If xhr’s synchronous flag is set, then throw exception.
  1013. if (m_synchronous) {
  1014. VERIFY(exception);
  1015. return JS::throw_completion(exception.ptr());
  1016. }
  1017. // 5. Fire an event named readystatechange at xhr.
  1018. // FIXME: Since we're in an async context, this will propagate to a callback context which can't propagate it anywhere else and does not expect this to fail.
  1019. dispatch_event(*DOM::Event::create(realm(), EventNames::readystatechange));
  1020. // 6. If xhr’s upload complete flag is unset, then:
  1021. if (!m_upload_complete) {
  1022. // 1. Set xhr’s upload complete flag.
  1023. m_upload_complete = true;
  1024. // 2. If xhr’s upload listener flag is set, then:
  1025. if (m_upload_listener) {
  1026. // 1. Fire a progress event named event at xhr’s upload object with 0 and 0.
  1027. fire_progress_event(m_upload_object, event_name, 0, 0);
  1028. // 2. Fire a progress event named loadend at xhr’s upload object with 0 and 0.
  1029. fire_progress_event(m_upload_object, EventNames::loadend, 0, 0);
  1030. }
  1031. }
  1032. // 7. Fire a progress event named event at xhr with 0 and 0.
  1033. fire_progress_event(*this, event_name, 0, 0);
  1034. // 8. Fire a progress event named loadend at xhr with 0 and 0.
  1035. fire_progress_event(*this, EventNames::loadend, 0, 0);
  1036. return {};
  1037. }
  1038. // https://xhr.spec.whatwg.org/#the-responseurl-attribute
  1039. String XMLHttpRequest::response_url()
  1040. {
  1041. // The responseURL getter steps are to return the empty string if this’s response’s URL is null;
  1042. // otherwise its serialization with the exclude fragment flag set.
  1043. if (!m_response->url().has_value())
  1044. return String {};
  1045. auto serialized = m_response->url().value().serialize(URL::ExcludeFragment::Yes);
  1046. return String::from_utf8_without_validation(serialized.bytes());
  1047. }
  1048. }