XMLHttpRequest.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. auto author_request_headers = Fetch::Infrastructure::HeaderList::create(realm.vm());
  44. return *realm.heap().allocate<XMLHttpRequest>(realm, window, *author_request_headers);
  45. }
  46. XMLHttpRequest::XMLHttpRequest(HTML::Window& window, Fetch::Infrastructure::HeaderList& author_request_headers)
  47. : XMLHttpRequestEventTarget(window.realm())
  48. , m_window(window)
  49. , m_author_request_headers(author_request_headers)
  50. , m_response_type(Bindings::XMLHttpRequestResponseType::Empty)
  51. {
  52. set_overrides_must_survive_garbage_collection(true);
  53. set_prototype(&Bindings::cached_web_prototype(window.realm(), "XMLHttpRequest"));
  54. }
  55. XMLHttpRequest::~XMLHttpRequest() = default;
  56. void XMLHttpRequest::visit_edges(Cell::Visitor& visitor)
  57. {
  58. Base::visit_edges(visitor);
  59. visitor.visit(m_window.ptr());
  60. visitor.visit(m_author_request_headers);
  61. if (auto* value = m_response_object.get_pointer<JS::Value>())
  62. visitor.visit(*value);
  63. }
  64. void XMLHttpRequest::fire_progress_event(DeprecatedString 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(realm(), event_name, event_init));
  71. }
  72. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext
  73. WebIDL::ExceptionOr<DeprecatedString> 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(realm(), "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_state != State::Loading && m_state != State::Done)
  80. return DeprecatedString::empty();
  81. return get_text_response();
  82. }
  83. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype
  84. WebIDL::ExceptionOr<void> XMLHttpRequest::set_response_type(Bindings::XMLHttpRequestResponseType response_type)
  85. {
  86. // 1. If the current global object is not a Window object and the given value is "document", then return.
  87. if (!is<HTML::Window>(HTML::current_global_object()) && response_type == Bindings::XMLHttpRequestResponseType::Document)
  88. return {};
  89. // 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  90. if (m_state == State::Loading || m_state == State::Done)
  91. return WebIDL::InvalidStateError::create(realm(), "Can't readyState when XHR is loading or done");
  92. // 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.
  93. if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
  94. return WebIDL::InvalidAccessError::create(realm(), "Can't set readyState on synchronous XHR in Window environment");
  95. // 4. Set this’s response type to the given value.
  96. m_response_type = response_type;
  97. return {};
  98. }
  99. // https://xhr.spec.whatwg.org/#response
  100. WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response()
  101. {
  102. auto& vm = this->vm();
  103. // 1. If this’s response type is the empty string or "text", then:
  104. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty || m_response_type == Bindings::XMLHttpRequestResponseType::Text) {
  105. // 1. If this’s state is not loading or done, then return the empty string.
  106. if (m_state != State::Loading && m_state != State::Done)
  107. return JS::PrimitiveString::create(vm, "");
  108. // 2. Return the result of getting a text response for this.
  109. return JS::PrimitiveString::create(vm, get_text_response());
  110. }
  111. // 2. If this’s state is not done, then return null.
  112. if (m_state != State::Done)
  113. return JS::js_null();
  114. // 3. If this’s response object is failure, then return null.
  115. if (m_response_object.has<Failure>())
  116. return JS::js_null();
  117. // 4. If this’s response object is non-null, then return it.
  118. if (!m_response_object.has<Empty>())
  119. return m_response_object.get<JS::Value>();
  120. // 5. If this’s response type is "arraybuffer",
  121. if (m_response_type == Bindings::XMLHttpRequestResponseType::Arraybuffer) {
  122. // 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.
  123. auto buffer_result = JS::ArrayBuffer::create(realm(), m_received_bytes.size());
  124. if (buffer_result.is_error()) {
  125. m_response_object = Failure();
  126. return JS::js_null();
  127. }
  128. auto buffer = buffer_result.release_value();
  129. buffer->buffer().overwrite(0, m_received_bytes.data(), m_received_bytes.size());
  130. m_response_object = JS::Value(buffer);
  131. }
  132. // 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.
  133. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Blob) {
  134. auto blob_part = FileAPI::Blob::create(realm(), m_received_bytes, get_final_mime_type().type());
  135. auto blob = TRY(FileAPI::Blob::create(realm(), Vector<FileAPI::BlobPart> { JS::make_handle(*blob_part) }));
  136. m_response_object = JS::Value(blob.ptr());
  137. }
  138. // 7. Otherwise, if this’s response type is "document", set a document response for this.
  139. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Document) {
  140. // FIXME: Implement this.
  141. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "XHR Document type not implemented"sv };
  142. }
  143. // 8. Otherwise:
  144. else {
  145. // 1. Assert: this’s response type is "json".
  146. // Note: Automatically done by the layers above us.
  147. // 2. If this’s response’s body is null, then return null.
  148. // FIXME: Implement this once we have 'Response'.
  149. if (m_received_bytes.is_empty())
  150. return JS::js_null();
  151. // 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.
  152. auto json_object_result = Infra::parse_json_bytes_to_javascript_value(vm, m_received_bytes);
  153. if (json_object_result.is_error())
  154. return JS::js_null();
  155. // 4. Set this’s response object to jsonObject.
  156. m_response_object = json_object_result.release_value();
  157. }
  158. // 9. Return this’s response object.
  159. return m_response_object.get<JS::Value>();
  160. }
  161. // https://xhr.spec.whatwg.org/#text-response
  162. DeprecatedString XMLHttpRequest::get_text_response() const
  163. {
  164. // FIXME: 1. If xhr’s response’s body is null, then return the empty string.
  165. // 2. Let charset be the result of get a final encoding for xhr.
  166. auto charset = get_final_encoding();
  167. auto is_xml_mime_type = [](MimeSniff::MimeType const& mime_type) {
  168. // An XML MIME type is any MIME type whose subtype ends in "+xml" or whose essence is "text/xml" or "application/xml". [RFC7303]
  169. if (mime_type.essence().is_one_of("text/xml"sv, "application/xml"sv))
  170. return true;
  171. return mime_type.subtype().ends_with("+xml"sv);
  172. };
  173. // 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,
  174. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && !charset.has_value() && is_xml_mime_type(get_final_mime_type())) {
  175. // FIXME: then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
  176. }
  177. // 4. If charset is null, then set charset to UTF-8.
  178. if (!charset.has_value())
  179. charset = "UTF-8"sv;
  180. // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.
  181. auto* decoder = TextCodec::decoder_for(charset.value());
  182. // 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.
  183. VERIFY(decoder);
  184. return TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, m_received_bytes);
  185. }
  186. // https://xhr.spec.whatwg.org/#final-mime-type
  187. MimeSniff::MimeType XMLHttpRequest::get_final_mime_type() const
  188. {
  189. // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.
  190. if (!m_override_mime_type.has_value())
  191. return get_response_mime_type();
  192. // 2. Return xhr’s override MIME type.
  193. return *m_override_mime_type;
  194. }
  195. // https://xhr.spec.whatwg.org/#response-mime-type
  196. MimeSniff::MimeType XMLHttpRequest::get_response_mime_type() const
  197. {
  198. auto& vm = this->vm();
  199. // FIXME: Use an actual HeaderList for XHR headers.
  200. auto header_list = Fetch::Infrastructure::HeaderList::create(vm);
  201. for (auto const& entry : m_response_headers) {
  202. auto header = Fetch::Infrastructure::Header::from_string_pair(entry.key, entry.value).release_value_but_fixme_should_propagate_errors();
  203. header_list->append(move(header)).release_value_but_fixme_should_propagate_errors();
  204. }
  205. // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.
  206. auto mime_type = header_list->extract_mime_type();
  207. // 2. If mimeType is failure, then set mimeType to text/xml.
  208. if (!mime_type.has_value())
  209. return MimeSniff::MimeType("text"sv, "xml"sv);
  210. // 3. Return mimeType.
  211. return mime_type.release_value();
  212. }
  213. // https://xhr.spec.whatwg.org/#final-charset
  214. Optional<StringView> XMLHttpRequest::get_final_encoding() const
  215. {
  216. // 1. Let label be null.
  217. Optional<DeprecatedString> label;
  218. // 2. Let responseMIME be the result of get a response MIME type for xhr.
  219. auto response_mime = get_response_mime_type();
  220. // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
  221. auto response_mime_charset_it = response_mime.parameters().find("charset"sv);
  222. if (response_mime_charset_it != response_mime.parameters().end())
  223. label = response_mime_charset_it->value;
  224. // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
  225. if (m_override_mime_type.has_value()) {
  226. auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);
  227. if (override_mime_charset_it != m_override_mime_type->parameters().end())
  228. label = override_mime_charset_it->value;
  229. }
  230. // 5. If label is null, then return null.
  231. if (!label.has_value())
  232. return {};
  233. // 6. Let encoding be the result of getting an encoding from label.
  234. auto encoding = TextCodec::get_standardized_encoding(label.value());
  235. // 7. If encoding is failure, then return null.
  236. // 8. Return encoding.
  237. return encoding;
  238. }
  239. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  240. WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(DeprecatedString const& name_string, DeprecatedString const& value_string)
  241. {
  242. auto& realm = this->realm();
  243. auto name = name_string.to_byte_buffer();
  244. auto value = value_string.to_byte_buffer();
  245. // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
  246. if (m_state != State::Opened)
  247. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED");
  248. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  249. if (m_send)
  250. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set");
  251. // 3. Normalize value.
  252. value = MUST(Fetch::Infrastructure::normalize_header_value(value));
  253. // 4. If name is not a header name or value is not a header value, then throw a "SyntaxError" DOMException.
  254. if (!Fetch::Infrastructure::is_header_name(name))
  255. return WebIDL::SyntaxError::create(realm, "Header name contains invalid characters.");
  256. if (!Fetch::Infrastructure::is_header_value(value))
  257. return WebIDL::SyntaxError::create(realm, "Header value contains invalid characters.");
  258. auto header = Fetch::Infrastructure::Header {
  259. .name = move(name),
  260. .value = move(value),
  261. };
  262. // 5. If (name, value) is a forbidden request-header, then return.
  263. if (TRY_OR_RETURN_OOM(realm, Fetch::Infrastructure::is_forbidden_request_header(header)))
  264. return {};
  265. // 6. Combine (name, value) in this’s author request headers.
  266. TRY_OR_RETURN_OOM(realm, m_author_request_headers->combine(move(header)));
  267. return {};
  268. }
  269. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  270. WebIDL::ExceptionOr<void> XMLHttpRequest::open(DeprecatedString const& method_string, DeprecatedString const& url)
  271. {
  272. // 8. If the async argument is omitted, set async to true, and set username and password to null.
  273. return open(method_string, url, true, {}, {});
  274. }
  275. WebIDL::ExceptionOr<void> XMLHttpRequest::open(DeprecatedString const& method_string, DeprecatedString const& url, bool async, DeprecatedString const& username, DeprecatedString const& password)
  276. {
  277. auto method = method_string.to_byte_buffer();
  278. // 1. Let settingsObject be this’s relevant settings object.
  279. auto& settings_object = m_window->associated_document().relevant_settings_object();
  280. // 2. If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  281. if (settings_object.responsible_document() && !settings_object.responsible_document()->is_active())
  282. return WebIDL::InvalidStateError::create(realm(), "Invalid state: Responsible document is not fully active.");
  283. // 3. If method is not a method, then throw a "SyntaxError" DOMException.
  284. if (!Fetch::Infrastructure::is_method(method))
  285. return WebIDL::SyntaxError::create(realm(), "An invalid or illegal string was specified.");
  286. // 4. If method is a forbidden method, then throw a "SecurityError" DOMException.
  287. if (Fetch::Infrastructure::is_forbidden_method(method))
  288. return WebIDL::SecurityError::create(realm(), "Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  289. // 5. Normalize method.
  290. method = MUST(Fetch::Infrastructure::normalize_method(method));
  291. // 6. Let parsedURL be the result of parsing url with settingsObject’s API base URL and settingsObject’s API URL character encoding.
  292. auto parsed_url = settings_object.api_base_url().complete_url(url);
  293. // 7. If parsedURL is failure, then throw a "SyntaxError" DOMException.
  294. if (!parsed_url.is_valid())
  295. return WebIDL::SyntaxError::create(realm(), "Invalid URL");
  296. // 8. If the async argument is omitted, set async to true, and set username and password to null.
  297. // NOTE: This is handled in the overload lacking the async argument.
  298. // 9. If parsedURL’s host is non-null, then:
  299. if (!parsed_url.host().is_null()) {
  300. // 1. If the username argument is not null, set the username given parsedURL and username.
  301. if (!username.is_null())
  302. parsed_url.set_username(username);
  303. // 2. If the password argument is not null, set the password given parsedURL and password.
  304. if (!password.is_null())
  305. parsed_url.set_password(password);
  306. }
  307. // 10. If async is false, the current global object is a Window object, and either this’s timeout is
  308. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  309. if (!async
  310. && is<HTML::Window>(HTML::current_global_object())
  311. && (m_timeout != 0 || m_response_type != Bindings::XMLHttpRequestResponseType::Empty)) {
  312. return WebIDL::InvalidAccessError::create(realm(), "synchronous XMLHttpRequests do not support timeout and responseType");
  313. }
  314. // FIXME: 11. Terminate the ongoing fetch operated by the XMLHttpRequest object.
  315. // 12. Set variables associated with the object as follows:
  316. // Unset this’s send() flag.
  317. m_send = false;
  318. // Unset this’s upload listener flag.
  319. m_upload_listener = false;
  320. // Set this’s request method to method.
  321. m_request_method = move(method);
  322. // Set this’s request URL to parsedURL.
  323. m_request_url = parsed_url;
  324. // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  325. m_synchronous = !async;
  326. // Empty this’s author request headers.
  327. m_author_request_headers->clear();
  328. // FIXME: Set this’s response to a network error.
  329. // Set this’s received bytes to the empty byte sequence.
  330. m_received_bytes = {};
  331. // Set this’s response object to null.
  332. m_response_object = {};
  333. // 13. If this’s state is not opened, then:
  334. if (m_state != State::Opened) {
  335. // 1. Set this’s state to opened.
  336. m_state = State::Opened;
  337. // 2. Fire an event named readystatechange at this.
  338. dispatch_event(*DOM::Event::create(realm(), EventNames::readystatechange));
  339. }
  340. return {};
  341. }
  342. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  343. WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequestBodyInit> body)
  344. {
  345. auto& vm = this->vm();
  346. auto& realm = *vm.current_realm();
  347. if (m_state != State::Opened)
  348. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED");
  349. if (m_send)
  350. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set");
  351. // If this’s request method is `GET` or `HEAD`, then set body to null.
  352. if (m_request_method.is_one_of("GET"sv, "HEAD"sv))
  353. body = {};
  354. Optional<Fetch::Infrastructure::BodyWithType> body_with_type {};
  355. Optional<DeprecatedString> serialized_document {};
  356. if (body.has_value()) {
  357. if (body->has<JS::Handle<DOM::Document>>())
  358. serialized_document = TRY(body->get<JS::Handle<DOM::Document>>().cell()->serialize_fragment(DOMParsing::RequireWellFormed::No));
  359. else
  360. body_with_type = TRY(Fetch::extract_body(realm, body->downcast<Fetch::BodyInitOrReadableBytes>()));
  361. }
  362. AK::URL request_url = m_window->associated_document().parse_url(m_request_url.to_deprecated_string());
  363. dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url);
  364. // TODO: Add support for preflight requests to support CORS requests
  365. auto request_url_origin = HTML::Origin(request_url.scheme(), request_url.host(), request_url.port_or_default());
  366. bool should_enforce_same_origin_policy = true;
  367. if (auto* page = m_window->page())
  368. should_enforce_same_origin_policy = page->is_same_origin_policy_enabled();
  369. if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same_origin(request_url_origin)) {
  370. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
  371. m_state = State::Done;
  372. dispatch_event(*DOM::Event::create(realm, EventNames::readystatechange));
  373. dispatch_event(*DOM::Event::create(realm, HTML::EventNames::error));
  374. return {};
  375. }
  376. auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page());
  377. request.set_method(m_request_method);
  378. if (serialized_document.has_value()) {
  379. request.set_body(serialized_document->to_byte_buffer());
  380. } else if (body_with_type.has_value()) {
  381. TRY(body_with_type->body.source().visit(
  382. [&](ByteBuffer const& buffer) -> WebIDL::ExceptionOr<void> {
  383. auto byte_buffer = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(buffer));
  384. request.set_body(move(byte_buffer));
  385. return {};
  386. },
  387. [&](JS::Handle<FileAPI::Blob> const& blob) -> WebIDL::ExceptionOr<void> {
  388. auto byte_buffer = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(blob->bytes()));
  389. request.set_body(move(byte_buffer));
  390. return {};
  391. },
  392. [](auto&) -> WebIDL::ExceptionOr<void> {
  393. return {};
  394. }));
  395. }
  396. // If this’s headers’s header list does not contain `Content-Type`, then append (`Content-Type`, type) to this’s headers.
  397. if (!m_author_request_headers->contains("Content-Type"sv.bytes())) {
  398. if (body_with_type.has_value() && body_with_type->type.has_value()) {
  399. request.set_header("Content-Type", DeprecatedString { body_with_type->type->span() });
  400. } else if (body.has_value() && body->has<JS::Handle<DOM::Document>>()) {
  401. request.set_header("Content-Type", "text/html;charset=UTF-8");
  402. }
  403. }
  404. for (auto& it : *m_author_request_headers)
  405. request.set_header(DeprecatedString::copy(it.name), DeprecatedString::copy(it.value));
  406. m_upload_complete = false;
  407. m_timed_out = false;
  408. // FIXME: If req’s body is null (which it always is currently)
  409. m_upload_complete = true;
  410. m_send = true;
  411. if (!m_synchronous) {
  412. fire_progress_event(EventNames::loadstart, 0, 0);
  413. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  414. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  415. if (m_state != State::Opened || !m_send)
  416. return {};
  417. // FIXME: in order to properly set State::HeadersReceived and State::Loading,
  418. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  419. // FIXME: In the Fetch spec, which XHR gets its definition of `status` from, the status code is 0-999.
  420. // We could clamp, wrap around (current browser behavior!), or error out.
  421. // See: https://github.com/whatwg/fetch/issues/1142
  422. ResourceLoader::the().load(
  423. request,
  424. [weak_this = make_weak_ptr<XMLHttpRequest>()](auto data, auto& response_headers, auto status_code) {
  425. JS::GCPtr<XMLHttpRequest> strong_this = weak_this.ptr();
  426. if (!strong_this)
  427. return;
  428. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  429. // FIXME: Handle OOM failure.
  430. auto response_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  431. // FIXME: There's currently no difference between transmitted and length.
  432. u64 transmitted = response_data.size();
  433. u64 length = response_data.size();
  434. if (!xhr.m_synchronous) {
  435. xhr.m_received_bytes = response_data;
  436. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  437. }
  438. xhr.m_state = State::Done;
  439. xhr.m_status = status_code.value_or(0);
  440. xhr.m_response_headers = move(response_headers);
  441. xhr.m_send = false;
  442. xhr.dispatch_event(*DOM::Event::create(xhr.realm(), EventNames::readystatechange));
  443. xhr.fire_progress_event(EventNames::load, transmitted, length);
  444. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  445. },
  446. [weak_this = make_weak_ptr<XMLHttpRequest>()](auto& error, auto status_code) {
  447. dbgln("XHR failed to load: {}", error);
  448. JS::GCPtr<XMLHttpRequest> strong_this = weak_this.ptr();
  449. if (!strong_this)
  450. return;
  451. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  452. xhr.m_state = State::Done;
  453. xhr.set_status(status_code.value_or(0));
  454. xhr.dispatch_event(*DOM::Event::create(xhr.realm(), EventNames::readystatechange));
  455. xhr.dispatch_event(*DOM::Event::create(xhr.realm(), HTML::EventNames::error));
  456. },
  457. m_timeout,
  458. [weak_this = make_weak_ptr<XMLHttpRequest>()] {
  459. JS::GCPtr<XMLHttpRequest> strong_this = weak_this.ptr();
  460. if (!strong_this)
  461. return;
  462. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  463. xhr.dispatch_event(*DOM::Event::create(xhr.realm(), EventNames::timeout));
  464. });
  465. } else {
  466. TODO();
  467. }
  468. return {};
  469. }
  470. WebIDL::CallbackType* XMLHttpRequest::onreadystatechange()
  471. {
  472. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  473. }
  474. void XMLHttpRequest::set_onreadystatechange(WebIDL::CallbackType* value)
  475. {
  476. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, value);
  477. }
  478. // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
  479. DeprecatedString XMLHttpRequest::get_all_response_headers() const
  480. {
  481. // FIXME: Implement the spec-compliant sort order.
  482. StringBuilder builder;
  483. auto keys = m_response_headers.keys();
  484. quick_sort(keys);
  485. for (auto& key : keys) {
  486. builder.append(key);
  487. builder.append(": "sv);
  488. builder.append(m_response_headers.get(key).value());
  489. builder.append("\r\n"sv);
  490. }
  491. return builder.to_deprecated_string();
  492. }
  493. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  494. WebIDL::ExceptionOr<void> XMLHttpRequest::override_mime_type(DeprecatedString const& mime)
  495. {
  496. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  497. if (m_state == State::Loading || m_state == State::Done)
  498. return WebIDL::InvalidStateError::create(realm(), "Cannot override MIME type when state is Loading or Done.");
  499. // 2. Set this’s override MIME type to the result of parsing mime.
  500. m_override_mime_type = MimeSniff::MimeType::from_string(mime);
  501. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  502. if (!m_override_mime_type.has_value())
  503. m_override_mime_type = MimeSniff::MimeType("application"sv, "octet-stream"sv);
  504. return {};
  505. }
  506. // https://xhr.spec.whatwg.org/#ref-for-dom-xmlhttprequest-timeout%E2%91%A2
  507. WebIDL::ExceptionOr<void> XMLHttpRequest::set_timeout(u32 timeout)
  508. {
  509. // 1. If the current global object is a Window object and this’s synchronous flag is set,
  510. // then throw an "InvalidAccessError" DOMException.
  511. if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
  512. return WebIDL::InvalidAccessError::create(realm(), "Use of XMLHttpRequest's timeout attribute is not supported in the synchronous mode in window context.");
  513. // 2. Set this’s timeout to the given value.
  514. m_timeout = timeout;
  515. return {};
  516. }
  517. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-timeout
  518. u32 XMLHttpRequest::timeout() const { return m_timeout; }
  519. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
  520. bool XMLHttpRequest::with_credentials() const
  521. {
  522. // The withCredentials getter steps are to return this’s cross-origin credentials.
  523. return m_cross_origin_credentials;
  524. }
  525. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
  526. WebIDL::ExceptionOr<void> XMLHttpRequest::set_with_credentials(bool with_credentials)
  527. {
  528. auto& realm = this->realm();
  529. // 1. If this’s state is not unsent or opened, then throw an "InvalidStateError" DOMException.
  530. if (m_state != State::Unsent && m_state != State::Opened)
  531. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not UNSENT or OPENED");
  532. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  533. if (m_send)
  534. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set");
  535. // 3. Set this’s cross-origin credentials to the given value.
  536. m_cross_origin_credentials = with_credentials;
  537. return {};
  538. }
  539. // https://xhr.spec.whatwg.org/#garbage-collection
  540. bool XMLHttpRequest::must_survive_garbage_collection() const
  541. {
  542. // An XMLHttpRequest object must not be garbage collected
  543. // if its state is either opened with the send() flag set, headers received, or loading,
  544. // and it has one or more event listeners registered whose type is one of
  545. // readystatechange, progress, abort, error, load, timeout, and loadend.
  546. if ((m_state == State::Opened && m_send)
  547. || m_state == State::HeadersReceived
  548. || m_state == State::Loading) {
  549. if (has_event_listener(EventNames::readystatechange))
  550. return true;
  551. if (has_event_listener(EventNames::progress))
  552. return true;
  553. if (has_event_listener(EventNames::abort))
  554. return true;
  555. if (has_event_listener(EventNames::error))
  556. return true;
  557. if (has_event_listener(EventNames::load))
  558. return true;
  559. if (has_event_listener(EventNames::timeout))
  560. return true;
  561. if (has_event_listener(EventNames::loadend))
  562. return true;
  563. }
  564. // FIXME: If an XMLHttpRequest object is garbage collected while its connection is still open,
  565. // the user agent must terminate the XMLHttpRequest object’s fetch controller.
  566. // NOTE: This would go in XMLHttpRequest::finalize().
  567. return false;
  568. }
  569. void XMLHttpRequest::abort()
  570. {
  571. dbgln("(STUBBED) XMLHttpRequest::abort()");
  572. }
  573. }