XMLHttpRequest.cpp 10 KB

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