XMLHttpRequest.cpp 28 KB

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