XMLHttpRequest.cpp 29 KB

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