XMLHttpRequest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/QuickSort.h>
  8. #include <LibJS/Runtime/FunctionObject.h>
  9. #include <LibWeb/Bindings/EventWrapper.h>
  10. #include <LibWeb/Bindings/XMLHttpRequestWrapper.h>
  11. #include <LibWeb/DOM/DOMException.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/DOM/Event.h>
  14. #include <LibWeb/DOM/EventDispatcher.h>
  15. #include <LibWeb/DOM/EventListener.h>
  16. #include <LibWeb/DOM/ExceptionOr.h>
  17. #include <LibWeb/DOM/Window.h>
  18. #include <LibWeb/HTML/EventHandler.h>
  19. #include <LibWeb/HTML/EventNames.h>
  20. #include <LibWeb/Loader/ResourceLoader.h>
  21. #include <LibWeb/Origin.h>
  22. #include <LibWeb/Page/Page.h>
  23. #include <LibWeb/XHR/EventNames.h>
  24. #include <LibWeb/XHR/ProgressEvent.h>
  25. #include <LibWeb/XHR/XMLHttpRequest.h>
  26. namespace Web::XHR {
  27. XMLHttpRequest::XMLHttpRequest(DOM::Window& window)
  28. : XMLHttpRequestEventTarget()
  29. , m_window(window)
  30. {
  31. }
  32. XMLHttpRequest::~XMLHttpRequest()
  33. {
  34. }
  35. void XMLHttpRequest::set_ready_state(ReadyState ready_state)
  36. {
  37. m_ready_state = ready_state;
  38. dispatch_event(DOM::Event::create(EventNames::readystatechange));
  39. }
  40. void XMLHttpRequest::fire_progress_event(const String& event_name, u64 transmitted, u64 length)
  41. {
  42. ProgressEventInit event_init {};
  43. event_init.length_computable = true;
  44. event_init.loaded = transmitted;
  45. event_init.total = length;
  46. dispatch_event(ProgressEvent::create(event_name, event_init));
  47. }
  48. String XMLHttpRequest::response_text() const
  49. {
  50. if (m_response_object.is_empty())
  51. return {};
  52. return String::copy(m_response_object);
  53. }
  54. // https://fetch.spec.whatwg.org/#forbidden-header-name
  55. static bool is_forbidden_header_name(const String& header_name)
  56. {
  57. if (header_name.starts_with("Proxy-", CaseSensitivity::CaseInsensitive) || header_name.starts_with("Sec-", CaseSensitivity::CaseInsensitive))
  58. return true;
  59. auto lowercase_header_name = header_name.to_lowercase();
  60. return lowercase_header_name.is_one_of("accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "via");
  61. }
  62. // https://fetch.spec.whatwg.org/#forbidden-method
  63. static bool is_forbidden_method(const String& method)
  64. {
  65. auto lowercase_method = method.to_lowercase();
  66. return lowercase_method.is_one_of("connect", "trace", "track");
  67. }
  68. // https://fetch.spec.whatwg.org/#concept-method-normalize
  69. static String normalize_method(const String& method)
  70. {
  71. auto lowercase_method = method.to_lowercase();
  72. if (lowercase_method.is_one_of("delete", "get", "head", "options", "post", "put"))
  73. return method.to_uppercase();
  74. return method;
  75. }
  76. // https://fetch.spec.whatwg.org/#concept-header-value-normalize
  77. static String normalize_header_value(const String& header_value)
  78. {
  79. // FIXME: I'm not sure if this is the right trim, it should only be HTML whitespace bytes.
  80. return header_value.trim_whitespace();
  81. }
  82. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  83. DOM::ExceptionOr<void> XMLHttpRequest::set_request_header(const String& header, const String& value)
  84. {
  85. if (m_ready_state != ReadyState::Opened)
  86. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  87. if (m_send)
  88. return DOM::InvalidStateError::create("XHR send() flag is already set");
  89. // FIXME: Check if name matches the name production.
  90. // FIXME: Check if value matches the value production.
  91. if (is_forbidden_header_name(header))
  92. return {};
  93. // FIXME: Combine
  94. m_request_headers.set(header, normalize_header_value(value));
  95. return {};
  96. }
  97. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  98. DOM::ExceptionOr<void> XMLHttpRequest::open(const String& method, const String& url)
  99. {
  100. // FIXME: Let settingsObject be this’s relevant settings object.
  101. // FIXME: If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  102. // FIXME: Check that the method matches the method token production. https://tools.ietf.org/html/rfc7230#section-3.1.1
  103. if (is_forbidden_method(method))
  104. return DOM::SecurityError::create("Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  105. auto normalized_method = normalize_method(method);
  106. auto parsed_url = m_window->associated_document().parse_url(url);
  107. if (!parsed_url.is_valid())
  108. return DOM::SyntaxError::create("Invalid URL");
  109. if (!parsed_url.host().is_null()) {
  110. // FIXME: If the username argument is not null, set the username given parsedURL and username.
  111. // FIXME: If the password argument is not null, set the password given parsedURL and password.
  112. }
  113. // FIXME: If async is false, the current global object is a Window object, and either this’s timeout is
  114. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  115. // FIXME: If the async argument is omitted, set async to true, and set username and password to null.
  116. // FIXME: Terminate the ongoing fetch operated by the XMLHttpRequest object.
  117. m_send = false;
  118. m_upload_listener = false;
  119. m_method = normalized_method;
  120. m_url = parsed_url;
  121. // FIXME: Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  122. // (We're currently defaulting to async)
  123. m_synchronous = false;
  124. m_request_headers.clear();
  125. // FIXME: Set this’s response to a network error.
  126. // FIXME: Set this’s received bytes to the empty byte sequence.
  127. m_response_object = {};
  128. if (m_ready_state != ReadyState::Opened)
  129. set_ready_state(ReadyState::Opened);
  130. return {};
  131. }
  132. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  133. DOM::ExceptionOr<void> XMLHttpRequest::send(String body)
  134. {
  135. if (m_ready_state != ReadyState::Opened)
  136. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  137. if (m_send)
  138. return DOM::InvalidStateError::create("XHR send() flag is already set");
  139. // If this’s request method is `GET` or `HEAD`, then set body to null.
  140. if (m_method.is_one_of("GET"sv, "HEAD"sv))
  141. body = {};
  142. AK::URL request_url = m_window->associated_document().parse_url(m_url.to_string());
  143. dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url);
  144. // TODO: Add support for preflight requests to support CORS requests
  145. Origin request_url_origin = Origin(request_url.protocol(), request_url.host(), request_url.port_or_default());
  146. bool should_enforce_same_origin_policy = true;
  147. if (auto* page = m_window->page())
  148. should_enforce_same_origin_policy = page->is_same_origin_policy_enabled();
  149. if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same(request_url_origin)) {
  150. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
  151. set_ready_state(ReadyState::Done);
  152. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  153. return {};
  154. }
  155. auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page());
  156. request.set_method(m_method);
  157. if (!body.is_null())
  158. request.set_body(body.to_byte_buffer());
  159. for (auto& it : m_request_headers)
  160. request.set_header(it.key, it.value);
  161. m_upload_complete = false;
  162. m_timed_out = false;
  163. // FIXME: If req’s body is null (which it always is currently)
  164. m_upload_complete = true;
  165. m_send = true;
  166. if (!m_synchronous) {
  167. fire_progress_event(EventNames::loadstart, 0, 0);
  168. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  169. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  170. if (m_ready_state != ReadyState::Opened || !m_send)
  171. return {};
  172. // FIXME: in order to properly set ReadyState::HeadersReceived and ReadyState::Loading,
  173. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  174. ResourceLoader::the().load(
  175. request,
  176. [weak_this = make_weak_ptr()](auto data, auto& response_headers, auto status_code) {
  177. auto strong_this = weak_this.strong_ref();
  178. if (!strong_this)
  179. return;
  180. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  181. // FIXME: Handle OOM failure.
  182. auto response_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  183. // FIXME: There's currently no difference between transmitted and length.
  184. u64 transmitted = response_data.size();
  185. u64 length = response_data.size();
  186. if (!xhr.m_synchronous) {
  187. xhr.m_response_object = response_data;
  188. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  189. }
  190. xhr.m_ready_state = ReadyState::Done;
  191. xhr.m_status = status_code.value_or(0);
  192. xhr.m_response_headers = move(response_headers);
  193. xhr.m_send = false;
  194. xhr.dispatch_event(DOM::Event::create(EventNames::readystatechange));
  195. xhr.fire_progress_event(EventNames::load, transmitted, length);
  196. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  197. },
  198. [weak_this = make_weak_ptr()](auto& error, auto status_code) {
  199. dbgln("XHR failed to load: {}", error);
  200. auto strong_this = weak_this.strong_ref();
  201. if (!strong_this)
  202. return;
  203. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  204. xhr.set_ready_state(ReadyState::Done);
  205. xhr.set_status(status_code.value_or(0));
  206. xhr.dispatch_event(DOM::Event::create(HTML::EventNames::error));
  207. });
  208. } else {
  209. TODO();
  210. }
  211. return {};
  212. }
  213. JS::Object* XMLHttpRequest::create_wrapper(JS::GlobalObject& global_object)
  214. {
  215. return wrap(global_object, *this);
  216. }
  217. Bindings::CallbackType* XMLHttpRequest::onreadystatechange()
  218. {
  219. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  220. }
  221. void XMLHttpRequest::set_onreadystatechange(Optional<Bindings::CallbackType> value)
  222. {
  223. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, move(value));
  224. }
  225. // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
  226. String XMLHttpRequest::get_all_response_headers() const
  227. {
  228. // FIXME: Implement the spec-compliant sort order.
  229. StringBuilder builder;
  230. auto keys = m_response_headers.keys();
  231. quick_sort(keys);
  232. for (auto& key : keys) {
  233. builder.append(key);
  234. builder.append(": ");
  235. builder.append(m_response_headers.get(key).value());
  236. builder.append("\r\n");
  237. }
  238. return builder.to_string();
  239. }
  240. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  241. DOM::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
  242. {
  243. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  244. if (m_ready_state == ReadyState::Loading || m_ready_state == ReadyState::Done)
  245. return DOM::InvalidStateError::create("Cannot override MIME type when state is Loading or Done.");
  246. // 2. Set this’s override MIME type to the result of parsing mime.
  247. m_override_mime_type = MimeSniff::MimeType::from_string(mime);
  248. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  249. if (!m_override_mime_type.has_value())
  250. m_override_mime_type = MimeSniff::MimeType("application"sv, "octet-stream"sv);
  251. return {};
  252. }
  253. }