XMLHttpRequest.cpp 26 KB

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