XMLHttpRequest.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/GenericLexer.h>
  10. #include <AK/QuickSort.h>
  11. #include <LibJS/Runtime/AbstractOperations.h>
  12. #include <LibJS/Runtime/ArrayBuffer.h>
  13. #include <LibJS/Runtime/FunctionObject.h>
  14. #include <LibJS/Runtime/GlobalObject.h>
  15. #include <LibTextCodec/Decoder.h>
  16. #include <LibWeb/Bindings/EventWrapper.h>
  17. #include <LibWeb/Bindings/XMLHttpRequestWrapper.h>
  18. #include <LibWeb/DOM/DOMException.h>
  19. #include <LibWeb/DOM/Document.h>
  20. #include <LibWeb/DOM/Event.h>
  21. #include <LibWeb/DOM/EventDispatcher.h>
  22. #include <LibWeb/DOM/EventListener.h>
  23. #include <LibWeb/DOM/ExceptionOr.h>
  24. #include <LibWeb/DOM/Window.h>
  25. #include <LibWeb/Fetch/AbstractOperations.h>
  26. #include <LibWeb/HTML/EventHandler.h>
  27. #include <LibWeb/HTML/EventNames.h>
  28. #include <LibWeb/Loader/ResourceLoader.h>
  29. #include <LibWeb/Origin.h>
  30. #include <LibWeb/Page/Page.h>
  31. #include <LibWeb/XHR/EventNames.h>
  32. #include <LibWeb/XHR/ProgressEvent.h>
  33. #include <LibWeb/XHR/XMLHttpRequest.h>
  34. namespace Web::XHR {
  35. XMLHttpRequest::XMLHttpRequest(DOM::Window& window)
  36. : XMLHttpRequestEventTarget()
  37. , m_window(window)
  38. , m_response_type(Bindings::XMLHttpRequestResponseType::Empty)
  39. {
  40. }
  41. XMLHttpRequest::~XMLHttpRequest()
  42. {
  43. }
  44. void XMLHttpRequest::set_ready_state(ReadyState ready_state)
  45. {
  46. m_ready_state = ready_state;
  47. dispatch_event(DOM::Event::create(EventNames::readystatechange));
  48. }
  49. void XMLHttpRequest::fire_progress_event(const String& event_name, u64 transmitted, u64 length)
  50. {
  51. ProgressEventInit event_init {};
  52. event_init.length_computable = true;
  53. event_init.loaded = transmitted;
  54. event_init.total = length;
  55. dispatch_event(ProgressEvent::create(event_name, event_init));
  56. }
  57. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext
  58. DOM::ExceptionOr<String> XMLHttpRequest::response_text() const
  59. {
  60. // 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.
  61. if (m_response_type != Bindings::XMLHttpRequestResponseType::Empty && m_response_type != Bindings::XMLHttpRequestResponseType::Text)
  62. return DOM::InvalidStateError::create("XHR responseText can only be used for responseType \"\" or \"text\"");
  63. // 2. If this’s state is not loading or done, then return the empty string.
  64. if (m_ready_state != ReadyState::Loading && m_ready_state != ReadyState::Done)
  65. return String::empty();
  66. return get_text_response();
  67. }
  68. // https://xhr.spec.whatwg.org/#response
  69. DOM::ExceptionOr<JS::Value> XMLHttpRequest::response()
  70. {
  71. auto& global_object = wrapper()->global_object();
  72. // 1. If this’s response type is the empty string or "text", then:
  73. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty || m_response_type == Bindings::XMLHttpRequestResponseType::Text) {
  74. // 1. If this’s state is not loading or done, then return the empty string.
  75. if (m_ready_state != ReadyState::Loading && m_ready_state != ReadyState::Done)
  76. return JS::Value(JS::js_string(global_object.heap(), ""));
  77. // 2. Return the result of getting a text response for this.
  78. return JS::Value(JS::js_string(global_object.heap(), get_text_response()));
  79. }
  80. // 2. If this’s state is not done, then return null.
  81. if (m_ready_state != ReadyState::Done)
  82. return JS::js_null();
  83. // 3. If this’s response object is failure, then return null.
  84. if (m_response_object.has<Failure>())
  85. return JS::js_null();
  86. // 4. If this’s response object is non-null, then return it.
  87. if (!m_response_object.has<Empty>())
  88. return m_response_object.get<JS::Handle<JS::Value>>().value();
  89. // 5. If this’s response type is "arraybuffer",
  90. if (m_response_type == Bindings::XMLHttpRequestResponseType::Arraybuffer) {
  91. // 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.
  92. auto buffer_result = JS::ArrayBuffer::create(global_object, m_received_bytes.size());
  93. if (buffer_result.is_error()) {
  94. m_response_object = Failure();
  95. return JS::js_null();
  96. }
  97. auto buffer = buffer_result.release_value();
  98. buffer->buffer().overwrite(0, m_received_bytes.data(), m_received_bytes.size());
  99. m_response_object = JS::make_handle(JS::Value(buffer));
  100. }
  101. // 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.
  102. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Blob) {
  103. // FIXME: Implement this once we have 'Blob'.
  104. return DOM::SimpleException { DOM::SimpleExceptionType::TypeError, "XHR Blob type not implemented" };
  105. }
  106. // 7. Otherwise, if this’s response type is "document", set a document response for this.
  107. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Document) {
  108. // FIXME: Implement this.
  109. return DOM::SimpleException { DOM::SimpleExceptionType::TypeError, "XHR Document type not implemented" };
  110. }
  111. // 8. Otherwise:
  112. else {
  113. // 1. Assert: this’s response type is "json".
  114. // Note: Automatically done by the layers above us.
  115. // 2. If this’s response’s body is null, then return null.
  116. // FIXME: Implement this once we have 'Response'.
  117. if (m_received_bytes.is_empty())
  118. return JS::Value(JS::js_null());
  119. // 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.
  120. TextCodec::UTF8Decoder decoder;
  121. auto json_object_result = JS::call(global_object, global_object.json_parse_function(), JS::js_undefined(), JS::js_string(global_object.heap(), decoder.to_utf8({ m_received_bytes.data(), m_received_bytes.size() })));
  122. if (json_object_result.is_error())
  123. return JS::Value(JS::js_null());
  124. // 4. Set this’s response object to jsonObject.
  125. m_response_object = JS::make_handle(json_object_result.release_value());
  126. }
  127. // 9. Return this’s response object.
  128. return m_response_object.get<JS::Handle<JS::Value>>().value();
  129. }
  130. // https://xhr.spec.whatwg.org/#text-response
  131. String XMLHttpRequest::get_text_response() const
  132. {
  133. // FIXME: 1. If xhr’s response’s body is null, then return the empty string.
  134. // 2. Let charset be the result of get a final encoding for xhr.
  135. auto charset = get_final_encoding();
  136. auto is_xml_mime_type = [](MimeSniff::MimeType const& mime_type) {
  137. // An XML MIME type is any MIME type whose subtype ends in "+xml" or whose essence is "text/xml" or "application/xml". [RFC7303]
  138. if (mime_type.essence().is_one_of("text/xml"sv, "application/xml"sv))
  139. return true;
  140. return mime_type.subtype().ends_with("+xml");
  141. };
  142. // 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,
  143. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && !charset.has_value() && is_xml_mime_type(get_final_mime_type())) {
  144. // FIXME: then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
  145. }
  146. // 4. If charset is null, then set charset to UTF-8.
  147. if (!charset.has_value())
  148. charset = "UTF-8";
  149. // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.
  150. auto* decoder = TextCodec::decoder_for(charset.value());
  151. // 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.
  152. VERIFY(decoder);
  153. return TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, m_received_bytes);
  154. }
  155. // https://xhr.spec.whatwg.org/#final-mime-type
  156. MimeSniff::MimeType XMLHttpRequest::get_final_mime_type() const
  157. {
  158. // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.
  159. if (!m_override_mime_type.has_value())
  160. return get_response_mime_type();
  161. // 2. Return xhr’s override MIME type.
  162. return *m_override_mime_type;
  163. }
  164. // https://xhr.spec.whatwg.org/#response-mime-type
  165. MimeSniff::MimeType XMLHttpRequest::get_response_mime_type() const
  166. {
  167. // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.
  168. auto mime_type = extract_mime_type(m_response_headers);
  169. // 2. If mimeType is failure, then set mimeType to text/xml.
  170. if (!mime_type.has_value())
  171. return MimeSniff::MimeType("text"sv, "xml"sv);
  172. // 3. Return mimeType.
  173. return mime_type.release_value();
  174. }
  175. // https://xhr.spec.whatwg.org/#final-charset
  176. Optional<String> XMLHttpRequest::get_final_encoding() const
  177. {
  178. // 1. Let label be null.
  179. Optional<String> label;
  180. // 2. Let responseMIME be the result of get a response MIME type for xhr.
  181. auto response_mime = get_response_mime_type();
  182. // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
  183. auto response_mime_charset_it = response_mime.parameters().find("charset"sv);
  184. if (response_mime_charset_it != response_mime.parameters().end())
  185. label = response_mime_charset_it->value;
  186. // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
  187. if (m_override_mime_type.has_value()) {
  188. auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);
  189. if (override_mime_charset_it != m_override_mime_type->parameters().end())
  190. label = override_mime_charset_it->value;
  191. }
  192. // 5. If label is null, then return null.
  193. if (!label.has_value())
  194. return {};
  195. // 6. Let encoding be the result of getting an encoding from label.
  196. auto encoding = TextCodec::get_standardized_encoding(label.value());
  197. // 7. If encoding is failure, then return null.
  198. // 8. Return encoding.
  199. return encoding;
  200. }
  201. // https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
  202. // FIXME: This is not only used by XHR, it is also used for multiple things in Fetch.
  203. Optional<Vector<String>> XMLHttpRequest::get_decode_and_split(String const& header_name, HashMap<String, String, CaseInsensitiveStringTraits> const& header_list) const
  204. {
  205. // 1. Let initialValue be the result of getting name from list.
  206. auto initial_value_iterator = header_list.find(header_name);
  207. // 2. If initialValue is null, then return null.
  208. if (initial_value_iterator == header_list.end())
  209. return {};
  210. auto& initial_value = initial_value_iterator->value;
  211. // FIXME: 3. Let input be the result of isomorphic decoding initialValue.
  212. // NOTE: We don't store raw byte sequences in the header list as per the spec, so we can't do this step.
  213. // The spec no longer uses initialValue after this step. For our purposes, treat any reference to `input` in the spec comments to initial_value.
  214. // 4. Let position be a position variable for input, initially pointing at the start of input.
  215. GenericLexer lexer(initial_value);
  216. // 5. Let values be a list of strings, initially empty.
  217. Vector<String> values;
  218. // 6. Let value be the empty string.
  219. StringBuilder value;
  220. // 7. While position is not past the end of input:
  221. while (!lexer.is_eof()) {
  222. // 1. Append the result of collecting a sequence of code points that are not U+0022 (") or U+002C (,) from input, given position, to value.
  223. auto value_part = lexer.consume_until([](char ch) {
  224. return ch == '"' || ch == ',';
  225. });
  226. value.append(value_part);
  227. // 2. If position is not past the end of input, then:
  228. if (!lexer.is_eof()) {
  229. // 1. If the code point at position within input is U+0022 ("), then:
  230. if (lexer.peek() == '"') {
  231. // 1. Append the result of collecting an HTTP quoted string from input, given position, to value.
  232. auto quoted_value_part = Fetch::collect_an_http_quoted_string(lexer, Fetch::HttpQuotedStringExtractValue::No);
  233. value.append(quoted_value_part);
  234. // 2. If position is not past the end of input, then continue.
  235. if (!lexer.is_eof())
  236. continue;
  237. }
  238. // 2. Otherwise:
  239. else {
  240. // 1. Assert: the code point at position within input is U+002C (,).
  241. VERIFY(lexer.peek() == ',');
  242. // 2. Advance position by 1.
  243. lexer.ignore(1);
  244. }
  245. }
  246. // 3. Remove all HTTP tab or space from the start and end of value.
  247. // https://fetch.spec.whatwg.org/#http-tab-or-space
  248. // An HTTP tab or space is U+0009 TAB or U+0020 SPACE.
  249. auto trimmed_value = value.to_string().trim("\t ", TrimMode::Both);
  250. // 4. Append value to values.
  251. values.append(move(trimmed_value));
  252. // 5. Set value to the empty string.
  253. value.clear();
  254. }
  255. // 8. Return values.
  256. return values;
  257. }
  258. // https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
  259. // FIXME: This is not only used by XHR, it is also used for multiple things in Fetch.
  260. Optional<MimeSniff::MimeType> XMLHttpRequest::extract_mime_type(HashMap<String, String, CaseInsensitiveStringTraits> const& header_list) const
  261. {
  262. // 1. Let charset be null.
  263. Optional<String> charset;
  264. // 2. Let essence be null.
  265. Optional<String> essence;
  266. // 3. Let mimeType be null.
  267. Optional<MimeSniff::MimeType> mime_type;
  268. // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers.
  269. auto potentially_values = get_decode_and_split("Content-Type"sv, header_list);
  270. // 5. If values is null, then return failure.
  271. if (!potentially_values.has_value())
  272. return {};
  273. auto values = potentially_values.release_value();
  274. // 6. For each value of values:
  275. for (auto& value : values) {
  276. // 1. Let temporaryMimeType be the result of parsing value.
  277. auto temporary_mime_type = MimeSniff::MimeType::from_string(value);
  278. // 2. If temporaryMimeType is failure or its essence is "*/*", then continue.
  279. if (!temporary_mime_type.has_value() || temporary_mime_type->essence() == "*/*"sv)
  280. continue;
  281. // 3. Set mimeType to temporaryMimeType.
  282. mime_type = temporary_mime_type;
  283. // 4. If mimeType’s essence is not essence, then:
  284. if (mime_type->essence() != essence) {
  285. // 1. Set charset to null.
  286. charset = {};
  287. // 2. If mimeType’s parameters["charset"] exists, then set charset to mimeType’s parameters["charset"].
  288. auto charset_it = mime_type->parameters().find("charset"sv);
  289. if (charset_it != mime_type->parameters().end())
  290. charset = charset_it->value;
  291. // 3. Set essence to mimeType’s essence.
  292. essence = mime_type->essence();
  293. } else {
  294. // 5. Otherwise, if mimeType’s parameters["charset"] does not exist, and charset is non-null, set mimeType’s parameters["charset"] to charset.
  295. if (!mime_type->parameters().contains("charset"sv) && charset.has_value())
  296. mime_type->set_parameter("charset"sv, charset.value());
  297. }
  298. }
  299. // 7. If mimeType is null, then return failure.
  300. // 8. Return mimeType.
  301. return mime_type;
  302. }
  303. // https://fetch.spec.whatwg.org/#forbidden-header-name
  304. static bool is_forbidden_header_name(const String& header_name)
  305. {
  306. if (header_name.starts_with("Proxy-", CaseSensitivity::CaseInsensitive) || header_name.starts_with("Sec-", CaseSensitivity::CaseInsensitive))
  307. return true;
  308. auto lowercase_header_name = header_name.to_lowercase();
  309. return lowercase_header_name.is_one_of("accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "via");
  310. }
  311. // https://fetch.spec.whatwg.org/#forbidden-method
  312. static bool is_forbidden_method(const String& method)
  313. {
  314. auto lowercase_method = method.to_lowercase();
  315. return lowercase_method.is_one_of("connect", "trace", "track");
  316. }
  317. // https://fetch.spec.whatwg.org/#concept-method-normalize
  318. static String normalize_method(const String& method)
  319. {
  320. auto lowercase_method = method.to_lowercase();
  321. if (lowercase_method.is_one_of("delete", "get", "head", "options", "post", "put"))
  322. return method.to_uppercase();
  323. return method;
  324. }
  325. // https://fetch.spec.whatwg.org/#concept-header-value-normalize
  326. static String normalize_header_value(const String& header_value)
  327. {
  328. // FIXME: I'm not sure if this is the right trim, it should only be HTML whitespace bytes.
  329. return header_value.trim_whitespace();
  330. }
  331. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  332. DOM::ExceptionOr<void> XMLHttpRequest::set_request_header(const String& header, const String& value)
  333. {
  334. if (m_ready_state != ReadyState::Opened)
  335. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  336. if (m_send)
  337. return DOM::InvalidStateError::create("XHR send() flag is already set");
  338. // FIXME: Check if name matches the name production.
  339. // FIXME: Check if value matches the value production.
  340. if (is_forbidden_header_name(header))
  341. return {};
  342. // FIXME: Combine
  343. m_request_headers.set(header, normalize_header_value(value));
  344. return {};
  345. }
  346. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  347. DOM::ExceptionOr<void> XMLHttpRequest::open(const String& method, const String& url)
  348. {
  349. // FIXME: Let settingsObject be this’s relevant settings object.
  350. // FIXME: If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  351. // FIXME: Check that the method matches the method token production. https://tools.ietf.org/html/rfc7230#section-3.1.1
  352. if (is_forbidden_method(method))
  353. return DOM::SecurityError::create("Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  354. auto normalized_method = normalize_method(method);
  355. auto parsed_url = m_window->associated_document().parse_url(url);
  356. if (!parsed_url.is_valid())
  357. return DOM::SyntaxError::create("Invalid URL");
  358. if (!parsed_url.host().is_null()) {
  359. // FIXME: If the username argument is not null, set the username given parsedURL and username.
  360. // FIXME: If the password argument is not null, set the password given parsedURL and password.
  361. }
  362. // FIXME: If async is false, the current global object is a Window object, and either this’s timeout is
  363. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  364. // FIXME: If the async argument is omitted, set async to true, and set username and password to null.
  365. // FIXME: Terminate the ongoing fetch operated by the XMLHttpRequest object.
  366. m_send = false;
  367. m_upload_listener = false;
  368. m_method = normalized_method;
  369. m_url = parsed_url;
  370. // FIXME: Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  371. // (We're currently defaulting to async)
  372. m_synchronous = false;
  373. m_request_headers.clear();
  374. // FIXME: Set this’s response to a network error.
  375. // FIXME: Set this’s received bytes to the empty byte sequence.
  376. m_response_object = {};
  377. if (m_ready_state != ReadyState::Opened)
  378. set_ready_state(ReadyState::Opened);
  379. return {};
  380. }
  381. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  382. DOM::ExceptionOr<void> XMLHttpRequest::send(String body)
  383. {
  384. if (m_ready_state != ReadyState::Opened)
  385. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  386. if (m_send)
  387. return DOM::InvalidStateError::create("XHR send() flag is already set");
  388. // If this’s request method is `GET` or `HEAD`, then set body to null.
  389. if (m_method.is_one_of("GET"sv, "HEAD"sv))
  390. body = {};
  391. AK::URL request_url = m_window->associated_document().parse_url(m_url.to_string());
  392. dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url);
  393. // TODO: Add support for preflight requests to support CORS requests
  394. Origin request_url_origin = Origin(request_url.protocol(), request_url.host(), request_url.port_or_default());
  395. bool should_enforce_same_origin_policy = true;
  396. if (auto* page = m_window->page())
  397. should_enforce_same_origin_policy = page->is_same_origin_policy_enabled();
  398. if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same_origin(request_url_origin)) {
  399. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
  400. set_ready_state(ReadyState::Done);
  401. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  402. return {};
  403. }
  404. auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page());
  405. request.set_method(m_method);
  406. if (!body.is_null())
  407. request.set_body(body.to_byte_buffer());
  408. for (auto& it : m_request_headers)
  409. request.set_header(it.key, it.value);
  410. m_upload_complete = false;
  411. m_timed_out = false;
  412. // FIXME: If req’s body is null (which it always is currently)
  413. m_upload_complete = true;
  414. m_send = true;
  415. if (!m_synchronous) {
  416. fire_progress_event(EventNames::loadstart, 0, 0);
  417. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  418. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  419. if (m_ready_state != ReadyState::Opened || !m_send)
  420. return {};
  421. // FIXME: in order to properly set ReadyState::HeadersReceived and ReadyState::Loading,
  422. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  423. ResourceLoader::the().load(
  424. request,
  425. [weak_this = make_weak_ptr()](auto data, auto& response_headers, auto status_code) {
  426. auto strong_this = weak_this.strong_ref();
  427. if (!strong_this)
  428. return;
  429. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  430. // FIXME: Handle OOM failure.
  431. auto response_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  432. // FIXME: There's currently no difference between transmitted and length.
  433. u64 transmitted = response_data.size();
  434. u64 length = response_data.size();
  435. if (!xhr.m_synchronous) {
  436. xhr.m_received_bytes = response_data;
  437. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  438. }
  439. xhr.m_ready_state = ReadyState::Done;
  440. xhr.m_status = status_code.value_or(0);
  441. xhr.m_response_headers = move(response_headers);
  442. xhr.m_send = false;
  443. xhr.dispatch_event(DOM::Event::create(EventNames::readystatechange));
  444. xhr.fire_progress_event(EventNames::load, transmitted, length);
  445. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  446. },
  447. [weak_this = make_weak_ptr()](auto& error, auto status_code) {
  448. dbgln("XHR failed to load: {}", error);
  449. auto strong_this = weak_this.strong_ref();
  450. if (!strong_this)
  451. return;
  452. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  453. xhr.set_ready_state(ReadyState::Done);
  454. xhr.set_status(status_code.value_or(0));
  455. xhr.dispatch_event(DOM::Event::create(HTML::EventNames::error));
  456. });
  457. } else {
  458. TODO();
  459. }
  460. return {};
  461. }
  462. JS::Object* XMLHttpRequest::create_wrapper(JS::GlobalObject& global_object)
  463. {
  464. return wrap(global_object, *this);
  465. }
  466. Bindings::CallbackType* XMLHttpRequest::onreadystatechange()
  467. {
  468. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  469. }
  470. void XMLHttpRequest::set_onreadystatechange(Optional<Bindings::CallbackType> value)
  471. {
  472. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, move(value));
  473. }
  474. // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
  475. String XMLHttpRequest::get_all_response_headers() const
  476. {
  477. // FIXME: Implement the spec-compliant sort order.
  478. StringBuilder builder;
  479. auto keys = m_response_headers.keys();
  480. quick_sort(keys);
  481. for (auto& key : keys) {
  482. builder.append(key);
  483. builder.append(": ");
  484. builder.append(m_response_headers.get(key).value());
  485. builder.append("\r\n");
  486. }
  487. return builder.to_string();
  488. }
  489. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  490. DOM::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
  491. {
  492. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  493. if (m_ready_state == ReadyState::Loading || m_ready_state == ReadyState::Done)
  494. return DOM::InvalidStateError::create("Cannot override MIME type when state is Loading or Done.");
  495. // 2. Set this’s override MIME type to the result of parsing mime.
  496. m_override_mime_type = MimeSniff::MimeType::from_string(mime);
  497. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  498. if (!m_override_mime_type.has_value())
  499. m_override_mime_type = MimeSniff::MimeType("application"sv, "octet-stream"sv);
  500. return {};
  501. }
  502. }