XMLHttpRequest.cpp 56 KB

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