XMLHttpRequest.cpp 31 KB

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