XMLHttpRequest.cpp 26 KB

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