XMLHttpRequest.cpp 10 KB

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