XMLHttpRequest.cpp 26 KB

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