XMLHttpRequest.cpp 10.0 KB

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