XMLHttpRequest.cpp 11 KB

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