XMLHttpRequest.cpp 29 KB

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