XMLHttpRequest.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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(String const& 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(String const& 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(String const& 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
  316. static bool is_method(String const& method)
  317. {
  318. Regex<ECMA262Parser> regex { R"~~~(^.*["(),\/:;<=>?@\\[\]{}]+.*$)~~~" };
  319. return !regex.has_match(method);
  320. }
  321. // https://fetch.spec.whatwg.org/#concept-method-normalize
  322. static String normalize_method(String const& method)
  323. {
  324. auto lowercase_method = method.to_lowercase();
  325. if (lowercase_method.is_one_of("delete", "get", "head", "options", "post", "put"))
  326. return method.to_uppercase();
  327. return method;
  328. }
  329. // https://fetch.spec.whatwg.org/#concept-header-value-normalize
  330. static String normalize_header_value(String const& header_value)
  331. {
  332. // FIXME: I'm not sure if this is the right trim, it should only be HTML whitespace bytes.
  333. return header_value.trim_whitespace();
  334. }
  335. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  336. DOM::ExceptionOr<void> XMLHttpRequest::set_request_header(String const& name, String const& value)
  337. {
  338. // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
  339. if (m_ready_state != ReadyState::Opened)
  340. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  341. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  342. if (m_send)
  343. return DOM::InvalidStateError::create("XHR send() flag is already set");
  344. // 3. Normalize value.
  345. auto normalized_value = normalize_header_value(value);
  346. // FIXME: 4. If name is not a header name or value is not a header value,
  347. // then throw a "SyntaxError" DOMException.
  348. // 5. If name is a forbidden header name, then return.
  349. if (is_forbidden_header_name(name))
  350. return {};
  351. // 6. Combine (name, value) in this’s author request headers.
  352. // FIXME: The header name look-up should be case-insensitive.
  353. if (m_request_headers.contains(name)) {
  354. // 1. If list contains name, then set the value of the first such header to its value,
  355. // followed by 0x2C 0x20, followed by value.
  356. auto maybe_header_value = m_request_headers.get(name);
  357. m_request_headers.set(name, String::formatted("{}, {}", maybe_header_value.release_value(), normalized_value));
  358. } else {
  359. // 2. Otherwise, append (name, value) to list.
  360. m_request_headers.set(name, normalized_value);
  361. }
  362. return {};
  363. }
  364. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  365. DOM::ExceptionOr<void> XMLHttpRequest::open(String const& method, String const& url)
  366. {
  367. return open(method, url, true, {}, {});
  368. }
  369. DOM::ExceptionOr<void> XMLHttpRequest::open(String const& method, String const& url, bool async, String const& username, String const& password)
  370. {
  371. // FIXME: 1. Let settingsObject be this’s relevant settings object.
  372. // FIXME: 2. If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  373. // 3. If method is not a method, then throw a "SyntaxError" DOMException.
  374. if (!is_method(method))
  375. return DOM::SyntaxError::create("An invalid or illegal string was specified.");
  376. // 4. If method is a forbidden method, then throw a "SecurityError" DOMException.
  377. if (is_forbidden_method(method))
  378. return DOM::SecurityError::create("Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  379. // 5. Normalize method.
  380. auto normalized_method = normalize_method(method);
  381. // 6. Let parsedURL be the result of parsing url with settingsObject’s API base URL and settingsObject’s API URL character encoding.
  382. // FIXME: Should use relevant settings object and not assume it's the Window object
  383. auto parsed_url = m_window->associated_document().parse_url(url);
  384. // 7. If parsedURL is failure, then throw a "SyntaxError" DOMException.
  385. if (!parsed_url.is_valid())
  386. return DOM::SyntaxError::create("Invalid URL");
  387. // FIXME: 8. If the async argument is omitted, set async to true, and set username and password to null.
  388. // 9. If parsedURL’s host is non-null, then:
  389. if (!parsed_url.host().is_null()) {
  390. // 1. If the username argument is not null, set the username given parsedURL and username.
  391. if (!username.is_null())
  392. parsed_url.set_username(username);
  393. // 2. If the password argument is not null, set the password given parsedURL and password.
  394. if (!password.is_null())
  395. parsed_url.set_password(password);
  396. }
  397. // FIXME: 10. If async is false, the current global object is a Window object, and either this’s timeout is
  398. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  399. // FIXME: 11. Terminate the ongoing fetch operated by the XMLHttpRequest object.
  400. // 12. Set variables associated with the object as follows:
  401. // Unset this’s send() flag.
  402. m_send = false;
  403. // Unset this’s upload listener flag.
  404. m_upload_listener = false;
  405. // Set this’s request method to method.
  406. m_method = normalized_method;
  407. // Set this’s request URL to parsedURL.
  408. m_url = parsed_url;
  409. // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  410. m_synchronous = !async;
  411. // Empty this’s author request headers.
  412. m_request_headers.clear();
  413. // FIXME: Set this’s response to a network error.
  414. // Set this’s received bytes to the empty byte sequence.
  415. m_received_bytes = {};
  416. // Set this’s response object to null.
  417. m_response_object = {};
  418. // 13. If this’s state is not opened, then:
  419. if (m_ready_state != ReadyState::Opened) {
  420. // 1. Set this’s state to opened.
  421. // 2. Fire an event named readystatechange at this.
  422. set_ready_state(ReadyState::Opened);
  423. }
  424. return {};
  425. }
  426. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  427. DOM::ExceptionOr<void> XMLHttpRequest::send(String body)
  428. {
  429. if (m_ready_state != ReadyState::Opened)
  430. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  431. if (m_send)
  432. return DOM::InvalidStateError::create("XHR send() flag is already set");
  433. // If this’s request method is `GET` or `HEAD`, then set body to null.
  434. if (m_method.is_one_of("GET"sv, "HEAD"sv))
  435. body = {};
  436. AK::URL request_url = m_window->associated_document().parse_url(m_url.to_string());
  437. dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url);
  438. // TODO: Add support for preflight requests to support CORS requests
  439. Origin request_url_origin = Origin(request_url.protocol(), request_url.host(), request_url.port_or_default());
  440. bool should_enforce_same_origin_policy = true;
  441. if (auto* page = m_window->page())
  442. should_enforce_same_origin_policy = page->is_same_origin_policy_enabled();
  443. if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same_origin(request_url_origin)) {
  444. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
  445. set_ready_state(ReadyState::Done);
  446. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  447. return {};
  448. }
  449. auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page());
  450. request.set_method(m_method);
  451. if (!body.is_null())
  452. request.set_body(body.to_byte_buffer());
  453. for (auto& it : m_request_headers)
  454. request.set_header(it.key, it.value);
  455. m_upload_complete = false;
  456. m_timed_out = false;
  457. // FIXME: If req’s body is null (which it always is currently)
  458. m_upload_complete = true;
  459. m_send = true;
  460. if (!m_synchronous) {
  461. fire_progress_event(EventNames::loadstart, 0, 0);
  462. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  463. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  464. if (m_ready_state != ReadyState::Opened || !m_send)
  465. return {};
  466. // FIXME: in order to properly set ReadyState::HeadersReceived and ReadyState::Loading,
  467. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  468. ResourceLoader::the().load(
  469. request,
  470. [weak_this = make_weak_ptr()](auto data, auto& response_headers, auto status_code) {
  471. auto strong_this = weak_this.strong_ref();
  472. if (!strong_this)
  473. return;
  474. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  475. // FIXME: Handle OOM failure.
  476. auto response_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  477. // FIXME: There's currently no difference between transmitted and length.
  478. u64 transmitted = response_data.size();
  479. u64 length = response_data.size();
  480. if (!xhr.m_synchronous) {
  481. xhr.m_received_bytes = response_data;
  482. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  483. }
  484. xhr.m_ready_state = ReadyState::Done;
  485. xhr.m_status = status_code.value_or(0);
  486. xhr.m_response_headers = move(response_headers);
  487. xhr.m_send = false;
  488. xhr.dispatch_event(DOM::Event::create(EventNames::readystatechange));
  489. xhr.fire_progress_event(EventNames::load, transmitted, length);
  490. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  491. },
  492. [weak_this = make_weak_ptr()](auto& error, auto status_code) {
  493. dbgln("XHR failed to load: {}", error);
  494. auto strong_this = weak_this.strong_ref();
  495. if (!strong_this)
  496. return;
  497. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  498. xhr.set_ready_state(ReadyState::Done);
  499. xhr.set_status(status_code.value_or(0));
  500. xhr.dispatch_event(DOM::Event::create(HTML::EventNames::error));
  501. });
  502. } else {
  503. TODO();
  504. }
  505. return {};
  506. }
  507. JS::Object* XMLHttpRequest::create_wrapper(JS::GlobalObject& global_object)
  508. {
  509. return wrap(global_object, *this);
  510. }
  511. Bindings::CallbackType* XMLHttpRequest::onreadystatechange()
  512. {
  513. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  514. }
  515. void XMLHttpRequest::set_onreadystatechange(Optional<Bindings::CallbackType> value)
  516. {
  517. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, move(value));
  518. }
  519. // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
  520. String XMLHttpRequest::get_all_response_headers() const
  521. {
  522. // FIXME: Implement the spec-compliant sort order.
  523. StringBuilder builder;
  524. auto keys = m_response_headers.keys();
  525. quick_sort(keys);
  526. for (auto& key : keys) {
  527. builder.append(key);
  528. builder.append(": ");
  529. builder.append(m_response_headers.get(key).value());
  530. builder.append("\r\n");
  531. }
  532. return builder.to_string();
  533. }
  534. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  535. DOM::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
  536. {
  537. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  538. if (m_ready_state == ReadyState::Loading || m_ready_state == ReadyState::Done)
  539. return DOM::InvalidStateError::create("Cannot override MIME type when state is Loading or Done.");
  540. // 2. Set this’s override MIME type to the result of parsing mime.
  541. m_override_mime_type = MimeSniff::MimeType::from_string(mime);
  542. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  543. if (!m_override_mime_type.has_value())
  544. m_override_mime_type = MimeSniff::MimeType("application"sv, "octet-stream"sv);
  545. return {};
  546. }
  547. }