XMLHttpRequest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <LibJS/Runtime/Function.h>
  28. #include <LibWeb/Bindings/EventWrapper.h>
  29. #include <LibWeb/Bindings/XMLHttpRequestWrapper.h>
  30. #include <LibWeb/DOM/DOMException.h>
  31. #include <LibWeb/DOM/Document.h>
  32. #include <LibWeb/DOM/Event.h>
  33. #include <LibWeb/DOM/EventDispatcher.h>
  34. #include <LibWeb/DOM/EventListener.h>
  35. #include <LibWeb/DOM/ExceptionOr.h>
  36. #include <LibWeb/DOM/Window.h>
  37. #include <LibWeb/HTML/EventNames.h>
  38. #include <LibWeb/Loader/ResourceLoader.h>
  39. #include <LibWeb/Origin.h>
  40. #include <LibWeb/XHR/EventNames.h>
  41. #include <LibWeb/XHR/ProgressEvent.h>
  42. #include <LibWeb/XHR/XMLHttpRequest.h>
  43. namespace Web::XHR {
  44. XMLHttpRequest::XMLHttpRequest(DOM::Window& window)
  45. : XMLHttpRequestEventTarget(static_cast<Bindings::ScriptExecutionContext&>(window.document()))
  46. , m_window(window)
  47. {
  48. }
  49. XMLHttpRequest::~XMLHttpRequest()
  50. {
  51. }
  52. void XMLHttpRequest::set_ready_state(ReadyState ready_state)
  53. {
  54. m_ready_state = ready_state;
  55. dispatch_event(DOM::Event::create(EventNames::readystatechange));
  56. }
  57. void XMLHttpRequest::fire_progress_event(const String& event_name, u64 transmitted, u64 length)
  58. {
  59. dispatch_event(ProgressEvent::create(event_name, transmitted, length));
  60. }
  61. String XMLHttpRequest::response_text() const
  62. {
  63. if (m_response_object.is_null())
  64. return {};
  65. return String::copy(m_response_object);
  66. }
  67. // https://fetch.spec.whatwg.org/#forbidden-header-name
  68. static bool is_forbidden_header_name(const String& header_name)
  69. {
  70. if (header_name.starts_with("Proxy-", CaseSensitivity::CaseInsensitive) || header_name.starts_with("Sec-", CaseSensitivity::CaseInsensitive))
  71. return true;
  72. auto lowercase_header_name = header_name.to_lowercase();
  73. 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");
  74. }
  75. // https://fetch.spec.whatwg.org/#forbidden-method
  76. static bool is_forbidden_method(const String& method)
  77. {
  78. auto lowercase_method = method.to_lowercase();
  79. return lowercase_method.is_one_of("connect", "trace", "track");
  80. }
  81. // https://fetch.spec.whatwg.org/#concept-method-normalize
  82. static String normalize_method(const String& method)
  83. {
  84. auto lowercase_method = method.to_lowercase();
  85. if (lowercase_method.is_one_of("delete", "get", "head", "options", "post", "put"))
  86. return method.to_uppercase();
  87. return method;
  88. }
  89. // https://fetch.spec.whatwg.org/#concept-header-value-normalize
  90. static String normalize_header_value(const String& header_value)
  91. {
  92. // FIXME: I'm not sure if this is the right trim, it should only be HTML whitespace bytes.
  93. return header_value.trim_whitespace();
  94. }
  95. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  96. DOM::ExceptionOr<void> XMLHttpRequest::set_request_header(const String& header, const String& value)
  97. {
  98. if (m_ready_state != ReadyState::Opened)
  99. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  100. if (m_send)
  101. return DOM::InvalidStateError::create("XHR send() flag is already set");
  102. // FIXME: Check if name matches the name production.
  103. // FIXME: Check if value matches the value production.
  104. if (is_forbidden_header_name(header))
  105. return {};
  106. // FIXME: Combine
  107. m_request_headers.set(header, normalize_header_value(value));
  108. return {};
  109. }
  110. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  111. DOM::ExceptionOr<void> XMLHttpRequest::open(const String& method, const String& url)
  112. {
  113. // FIXME: Let settingsObject be this’s relevant settings object.
  114. // FIXME: If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  115. // FIXME: Check that the method matches the method token production. https://tools.ietf.org/html/rfc7230#section-3.1.1
  116. if (is_forbidden_method(method))
  117. return DOM::SecurityError::create("Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  118. auto normalized_method = normalize_method(method);
  119. auto parsed_url = m_window->document().complete_url(url);
  120. if (!parsed_url.is_valid())
  121. return DOM::SyntaxError::create("Invalid URL");
  122. if (!parsed_url.host().is_null()) {
  123. // FIXME: If the username argument is not null, set the username given parsedURL and username.
  124. // FIXME: If the password argument is not null, set the password given parsedURL and password.
  125. }
  126. // FIXME: If async is false, the current global object is a Window object, and either this’s timeout is
  127. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  128. // FIXME: If the async argument is omitted, set async to true, and set username and password to null.
  129. // FIXME: Terminate the ongoing fetch operated by the XMLHttpRequest object.
  130. m_send = false;
  131. m_upload_listener = false;
  132. m_method = normalized_method;
  133. m_url = parsed_url;
  134. // FIXME: Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  135. // (We're currently defaulting to async)
  136. m_synchronous = false;
  137. m_request_headers.clear();
  138. // FIXME: Set this’s response to a network error.
  139. // FIXME: Set this’s received bytes to the empty byte sequence.
  140. m_response_object = {};
  141. if (m_ready_state != ReadyState::Opened)
  142. set_ready_state(ReadyState::Opened);
  143. return {};
  144. }
  145. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  146. DOM::ExceptionOr<void> XMLHttpRequest::send()
  147. {
  148. if (m_ready_state != ReadyState::Opened)
  149. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  150. if (m_send)
  151. return DOM::InvalidStateError::create("XHR send() flag is already set");
  152. // FIXME: If this’s request method is `GET` or `HEAD`, then set body to null.
  153. // FIXME: If body is not null, then:
  154. URL request_url = m_window->document().complete_url(m_url.to_string());
  155. dbgln("XHR send from {} to {}", m_window->document().url(), request_url);
  156. // TODO: Add support for preflight requests to support CORS requests
  157. Origin request_url_origin = Origin(request_url.protocol(), request_url.host(), request_url.port());
  158. if (!m_window->document().origin().is_same(request_url_origin)) {
  159. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->document().url(), request_url);
  160. auto weak_this = make_weak_ptr();
  161. if (!weak_this)
  162. return {};
  163. const_cast<XMLHttpRequest&>(*weak_this).set_ready_state(ReadyState::Done);
  164. const_cast<XMLHttpRequest&>(*weak_this).dispatch_event(DOM::Event::create(HTML::EventNames::error));
  165. return {};
  166. }
  167. LoadRequest request;
  168. request.set_method(m_method);
  169. request.set_url(request_url);
  170. for (auto& it : m_request_headers)
  171. request.set_header(it.key, it.value);
  172. m_upload_complete = false;
  173. m_timed_out = false;
  174. // FIXME: If req’s body is null (which it always is currently)
  175. m_upload_complete = true;
  176. m_send = true;
  177. if (!m_synchronous) {
  178. fire_progress_event(EventNames::loadstart, 0, 0);
  179. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  180. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  181. if (m_ready_state != ReadyState::Opened || !m_send)
  182. return {};
  183. // FIXME: in order to properly set ReadyState::HeadersReceived and ReadyState::Loading,
  184. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  185. ResourceLoader::the().load(
  186. request,
  187. [weak_this = make_weak_ptr()](auto data, auto&, auto status_code) {
  188. if (!weak_this)
  189. return;
  190. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  191. auto response_data = ByteBuffer::copy(data);
  192. // FIXME: There's currently no difference between transmitted and length.
  193. u64 transmitted = response_data.size();
  194. u64 length = response_data.size();
  195. if (!xhr.m_synchronous) {
  196. xhr.m_response_object = response_data;
  197. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  198. }
  199. xhr.m_ready_state = ReadyState::Done;
  200. xhr.m_status = status_code.value_or(0);
  201. xhr.m_send = false;
  202. xhr.dispatch_event(DOM::Event::create(EventNames::readystatechange));
  203. xhr.fire_progress_event(EventNames::load, transmitted, length);
  204. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  205. },
  206. [weak_this = make_weak_ptr()](auto& error, auto status_code) {
  207. if (!weak_this)
  208. return;
  209. dbgln("XHR failed to load: {}", error);
  210. const_cast<XMLHttpRequest&>(*weak_this).set_ready_state(ReadyState::Done);
  211. const_cast<XMLHttpRequest&>(*weak_this).set_status(status_code.value_or(0));
  212. const_cast<XMLHttpRequest&>(*weak_this).dispatch_event(DOM::Event::create(HTML::EventNames::error));
  213. });
  214. } else {
  215. TODO();
  216. }
  217. return {};
  218. }
  219. bool XMLHttpRequest::dispatch_event(NonnullRefPtr<DOM::Event> event)
  220. {
  221. return DOM::EventDispatcher::dispatch(*this, move(event));
  222. }
  223. JS::Object* XMLHttpRequest::create_wrapper(JS::GlobalObject& global_object)
  224. {
  225. return wrap(global_object, *this);
  226. }
  227. }