XMLHttpRequest.cpp 61 KB

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