XMLHttpRequest.cpp 27 KB

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