XMLHttpRequest.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/GenericLexer.h>
  9. #include <AK/QuickSort.h>
  10. #include <LibJS/Runtime/FunctionObject.h>
  11. #include <LibTextCodec/Decoder.h>
  12. #include <LibWeb/Bindings/EventWrapper.h>
  13. #include <LibWeb/Bindings/XMLHttpRequestWrapper.h>
  14. #include <LibWeb/DOM/DOMException.h>
  15. #include <LibWeb/DOM/Document.h>
  16. #include <LibWeb/DOM/Event.h>
  17. #include <LibWeb/DOM/EventDispatcher.h>
  18. #include <LibWeb/DOM/EventListener.h>
  19. #include <LibWeb/DOM/ExceptionOr.h>
  20. #include <LibWeb/DOM/Window.h>
  21. #include <LibWeb/Fetch/AbstractOperations.h>
  22. #include <LibWeb/HTML/EventHandler.h>
  23. #include <LibWeb/HTML/EventNames.h>
  24. #include <LibWeb/Loader/ResourceLoader.h>
  25. #include <LibWeb/Origin.h>
  26. #include <LibWeb/Page/Page.h>
  27. #include <LibWeb/XHR/EventNames.h>
  28. #include <LibWeb/XHR/ProgressEvent.h>
  29. #include <LibWeb/XHR/XMLHttpRequest.h>
  30. namespace Web::XHR {
  31. XMLHttpRequest::XMLHttpRequest(DOM::Window& window)
  32. : XMLHttpRequestEventTarget()
  33. , m_window(window)
  34. {
  35. }
  36. XMLHttpRequest::~XMLHttpRequest()
  37. {
  38. }
  39. void XMLHttpRequest::set_ready_state(ReadyState ready_state)
  40. {
  41. m_ready_state = ready_state;
  42. dispatch_event(DOM::Event::create(EventNames::readystatechange));
  43. }
  44. void XMLHttpRequest::fire_progress_event(const String& event_name, u64 transmitted, u64 length)
  45. {
  46. ProgressEventInit event_init {};
  47. event_init.length_computable = true;
  48. event_init.loaded = transmitted;
  49. event_init.total = length;
  50. dispatch_event(ProgressEvent::create(event_name, event_init));
  51. }
  52. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext
  53. String XMLHttpRequest::response_text() const
  54. {
  55. // FIXME: 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.
  56. // 2. If this’s state is not loading or done, then return the empty string.
  57. if (m_ready_state != ReadyState::Loading && m_ready_state != ReadyState::Done)
  58. return String::empty();
  59. return get_text_response();
  60. }
  61. // https://xhr.spec.whatwg.org/#text-response
  62. String XMLHttpRequest::get_text_response() const
  63. {
  64. // FIXME: 1. If xhr’s response’s body is null, then return the empty string.
  65. // 2. Let charset be the result of get a final encoding for xhr.
  66. auto charset = get_final_encoding();
  67. // FIXME: 3. If xhr’s response type is the empty string, charset is null, and the result of get a final MIME type for xhr is an XML MIME type,
  68. // then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
  69. // 4. If charset is null, then set charset to UTF-8.
  70. if (!charset.has_value())
  71. charset = "UTF-8";
  72. // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.
  73. auto* decoder = TextCodec::decoder_for(charset.value());
  74. // If we don't support the decoder yet, let's crash instead of attempting to return something, as the result would be incorrect and create obscure bugs.
  75. VERIFY(decoder);
  76. return TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, m_response_object);
  77. }
  78. // https://xhr.spec.whatwg.org/#response-mime-type
  79. MimeSniff::MimeType XMLHttpRequest::get_response_mime_type() const
  80. {
  81. // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.
  82. auto mime_type = extract_mime_type(m_response_headers);
  83. // 2. If mimeType is failure, then set mimeType to text/xml.
  84. if (!mime_type.has_value())
  85. return MimeSniff::MimeType("text"sv, "xml"sv);
  86. // 3. Return mimeType.
  87. return mime_type.release_value();
  88. }
  89. // https://xhr.spec.whatwg.org/#final-charset
  90. Optional<String> XMLHttpRequest::get_final_encoding() const
  91. {
  92. // 1. Let label be null.
  93. Optional<String> label;
  94. // 2. Let responseMIME be the result of get a response MIME type for xhr.
  95. auto response_mime = get_response_mime_type();
  96. // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
  97. auto response_mime_charset_it = response_mime.parameters().find("charset"sv);
  98. if (response_mime_charset_it != response_mime.parameters().end())
  99. label = response_mime_charset_it->value;
  100. // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
  101. if (m_override_mime_type.has_value()) {
  102. auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);
  103. if (override_mime_charset_it != m_override_mime_type->parameters().end())
  104. label = override_mime_charset_it->value;
  105. }
  106. // 5. If label is null, then return null.
  107. if (!label.has_value())
  108. return {};
  109. // 6. Let encoding be the result of getting an encoding from label.
  110. auto encoding = TextCodec::get_standardized_encoding(label.value());
  111. // 7. If encoding is failure, then return null.
  112. // 8. Return encoding.
  113. return encoding;
  114. }
  115. // https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
  116. // FIXME: This is not only used by XHR, it is also used for multiple things in Fetch.
  117. Optional<Vector<String>> XMLHttpRequest::get_decode_and_split(String const& header_name, HashMap<String, String, CaseInsensitiveStringTraits> const& header_list) const
  118. {
  119. // 1. Let initialValue be the result of getting name from list.
  120. auto initial_value_iterator = header_list.find(header_name);
  121. // 2. If initialValue is null, then return null.
  122. if (initial_value_iterator == header_list.end())
  123. return {};
  124. auto& initial_value = initial_value_iterator->value;
  125. // FIXME: 3. Let input be the result of isomorphic decoding initialValue.
  126. // NOTE: We don't store raw byte sequences in the header list as per the spec, so we can't do this step.
  127. // The spec no longer uses initialValue after this step. For our purposes, treat any reference to `input` in the spec comments to initial_value.
  128. // 4. Let position be a position variable for input, initially pointing at the start of input.
  129. GenericLexer lexer(initial_value);
  130. // 5. Let values be a list of strings, initially empty.
  131. Vector<String> values;
  132. // 6. Let value be the empty string.
  133. StringBuilder value;
  134. // 7. While position is not past the end of input:
  135. while (!lexer.is_eof()) {
  136. // 1. Append the result of collecting a sequence of code points that are not U+0022 (") or U+002C (,) from input, given position, to value.
  137. auto value_part = lexer.consume_until([](char ch) {
  138. return ch == '"' || ch == ',';
  139. });
  140. value.append(value_part);
  141. // 2. If position is not past the end of input, then:
  142. if (!lexer.is_eof()) {
  143. // 1. If the code point at position within input is U+0022 ("), then:
  144. if (lexer.peek() == '"') {
  145. // 1. Append the result of collecting an HTTP quoted string from input, given position, to value.
  146. auto quoted_value_part = Fetch::collect_an_http_quoted_string(lexer, Fetch::HttpQuotedStringExtractValue::No);
  147. value.append(quoted_value_part);
  148. // 2. If position is not past the end of input, then continue.
  149. if (!lexer.is_eof())
  150. continue;
  151. }
  152. // 2. Otherwise:
  153. else {
  154. // 1. Assert: the code point at position within input is U+002C (,).
  155. VERIFY(lexer.peek() == ',');
  156. // 2. Advance position by 1.
  157. lexer.ignore(1);
  158. }
  159. }
  160. // 3. Remove all HTTP tab or space from the start and end of value.
  161. // https://fetch.spec.whatwg.org/#http-tab-or-space
  162. // An HTTP tab or space is U+0009 TAB or U+0020 SPACE.
  163. auto trimmed_value = value.to_string().trim("\t ", TrimMode::Both);
  164. // 4. Append value to values.
  165. values.append(move(trimmed_value));
  166. // 5. Set value to the empty string.
  167. value.clear();
  168. }
  169. // 8. Return values.
  170. return values;
  171. }
  172. // https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
  173. // FIXME: This is not only used by XHR, it is also used for multiple things in Fetch.
  174. Optional<MimeSniff::MimeType> XMLHttpRequest::extract_mime_type(HashMap<String, String, CaseInsensitiveStringTraits> const& header_list) const
  175. {
  176. // 1. Let charset be null.
  177. Optional<String> charset;
  178. // 2. Let essence be null.
  179. Optional<String> essence;
  180. // 3. Let mimeType be null.
  181. Optional<MimeSniff::MimeType> mime_type;
  182. // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers.
  183. auto potentially_values = get_decode_and_split("Content-Type"sv, header_list);
  184. // 5. If values is null, then return failure.
  185. if (!potentially_values.has_value())
  186. return {};
  187. auto values = potentially_values.release_value();
  188. // 6. For each value of values:
  189. for (auto& value : values) {
  190. // 1. Let temporaryMimeType be the result of parsing value.
  191. auto temporary_mime_type = MimeSniff::MimeType::from_string(value);
  192. // 2. If temporaryMimeType is failure or its essence is "*/*", then continue.
  193. if (!temporary_mime_type.has_value() || temporary_mime_type->essence() == "*/*"sv)
  194. continue;
  195. // 3. Set mimeType to temporaryMimeType.
  196. mime_type = temporary_mime_type;
  197. // 4. If mimeType’s essence is not essence, then:
  198. if (mime_type->essence() != essence) {
  199. // 1. Set charset to null.
  200. charset = {};
  201. // 2. If mimeType’s parameters["charset"] exists, then set charset to mimeType’s parameters["charset"].
  202. auto charset_it = mime_type->parameters().find("charset"sv);
  203. if (charset_it != mime_type->parameters().end())
  204. charset = charset_it->value;
  205. // 3. Set essence to mimeType’s essence.
  206. essence = mime_type->essence();
  207. } else {
  208. // 5. Otherwise, if mimeType’s parameters["charset"] does not exist, and charset is non-null, set mimeType’s parameters["charset"] to charset.
  209. if (!mime_type->parameters().contains("charset"sv) && charset.has_value())
  210. mime_type->set_parameter("charset"sv, charset.value());
  211. }
  212. }
  213. // 7. If mimeType is null, then return failure.
  214. // 8. Return mimeType.
  215. return mime_type;
  216. }
  217. // https://fetch.spec.whatwg.org/#forbidden-header-name
  218. static bool is_forbidden_header_name(const String& header_name)
  219. {
  220. if (header_name.starts_with("Proxy-", CaseSensitivity::CaseInsensitive) || header_name.starts_with("Sec-", CaseSensitivity::CaseInsensitive))
  221. return true;
  222. auto lowercase_header_name = header_name.to_lowercase();
  223. 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");
  224. }
  225. // https://fetch.spec.whatwg.org/#forbidden-method
  226. static bool is_forbidden_method(const String& method)
  227. {
  228. auto lowercase_method = method.to_lowercase();
  229. return lowercase_method.is_one_of("connect", "trace", "track");
  230. }
  231. // https://fetch.spec.whatwg.org/#concept-method-normalize
  232. static String normalize_method(const String& method)
  233. {
  234. auto lowercase_method = method.to_lowercase();
  235. if (lowercase_method.is_one_of("delete", "get", "head", "options", "post", "put"))
  236. return method.to_uppercase();
  237. return method;
  238. }
  239. // https://fetch.spec.whatwg.org/#concept-header-value-normalize
  240. static String normalize_header_value(const String& header_value)
  241. {
  242. // FIXME: I'm not sure if this is the right trim, it should only be HTML whitespace bytes.
  243. return header_value.trim_whitespace();
  244. }
  245. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  246. DOM::ExceptionOr<void> XMLHttpRequest::set_request_header(const String& header, const String& value)
  247. {
  248. if (m_ready_state != ReadyState::Opened)
  249. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  250. if (m_send)
  251. return DOM::InvalidStateError::create("XHR send() flag is already set");
  252. // FIXME: Check if name matches the name production.
  253. // FIXME: Check if value matches the value production.
  254. if (is_forbidden_header_name(header))
  255. return {};
  256. // FIXME: Combine
  257. m_request_headers.set(header, normalize_header_value(value));
  258. return {};
  259. }
  260. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  261. DOM::ExceptionOr<void> XMLHttpRequest::open(const String& method, const String& url)
  262. {
  263. // FIXME: Let settingsObject be this’s relevant settings object.
  264. // FIXME: If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  265. // FIXME: Check that the method matches the method token production. https://tools.ietf.org/html/rfc7230#section-3.1.1
  266. if (is_forbidden_method(method))
  267. return DOM::SecurityError::create("Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  268. auto normalized_method = normalize_method(method);
  269. auto parsed_url = m_window->associated_document().parse_url(url);
  270. if (!parsed_url.is_valid())
  271. return DOM::SyntaxError::create("Invalid URL");
  272. if (!parsed_url.host().is_null()) {
  273. // FIXME: If the username argument is not null, set the username given parsedURL and username.
  274. // FIXME: If the password argument is not null, set the password given parsedURL and password.
  275. }
  276. // FIXME: If async is false, the current global object is a Window object, and either this’s timeout is
  277. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  278. // FIXME: If the async argument is omitted, set async to true, and set username and password to null.
  279. // FIXME: Terminate the ongoing fetch operated by the XMLHttpRequest object.
  280. m_send = false;
  281. m_upload_listener = false;
  282. m_method = normalized_method;
  283. m_url = parsed_url;
  284. // FIXME: Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  285. // (We're currently defaulting to async)
  286. m_synchronous = false;
  287. m_request_headers.clear();
  288. // FIXME: Set this’s response to a network error.
  289. // FIXME: Set this’s received bytes to the empty byte sequence.
  290. m_response_object = {};
  291. if (m_ready_state != ReadyState::Opened)
  292. set_ready_state(ReadyState::Opened);
  293. return {};
  294. }
  295. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  296. DOM::ExceptionOr<void> XMLHttpRequest::send(String body)
  297. {
  298. if (m_ready_state != ReadyState::Opened)
  299. return DOM::InvalidStateError::create("XHR readyState is not OPENED");
  300. if (m_send)
  301. return DOM::InvalidStateError::create("XHR send() flag is already set");
  302. // If this’s request method is `GET` or `HEAD`, then set body to null.
  303. if (m_method.is_one_of("GET"sv, "HEAD"sv))
  304. body = {};
  305. AK::URL request_url = m_window->associated_document().parse_url(m_url.to_string());
  306. dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url);
  307. // TODO: Add support for preflight requests to support CORS requests
  308. Origin request_url_origin = Origin(request_url.protocol(), request_url.host(), request_url.port_or_default());
  309. bool should_enforce_same_origin_policy = true;
  310. if (auto* page = m_window->page())
  311. should_enforce_same_origin_policy = page->is_same_origin_policy_enabled();
  312. if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same_origin(request_url_origin)) {
  313. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
  314. set_ready_state(ReadyState::Done);
  315. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  316. return {};
  317. }
  318. auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page());
  319. request.set_method(m_method);
  320. if (!body.is_null())
  321. request.set_body(body.to_byte_buffer());
  322. for (auto& it : m_request_headers)
  323. request.set_header(it.key, it.value);
  324. m_upload_complete = false;
  325. m_timed_out = false;
  326. // FIXME: If req’s body is null (which it always is currently)
  327. m_upload_complete = true;
  328. m_send = true;
  329. if (!m_synchronous) {
  330. fire_progress_event(EventNames::loadstart, 0, 0);
  331. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  332. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  333. if (m_ready_state != ReadyState::Opened || !m_send)
  334. return {};
  335. // FIXME: in order to properly set ReadyState::HeadersReceived and ReadyState::Loading,
  336. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  337. ResourceLoader::the().load(
  338. request,
  339. [weak_this = make_weak_ptr()](auto data, auto& response_headers, auto status_code) {
  340. auto strong_this = weak_this.strong_ref();
  341. if (!strong_this)
  342. return;
  343. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  344. // FIXME: Handle OOM failure.
  345. auto response_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  346. // FIXME: There's currently no difference between transmitted and length.
  347. u64 transmitted = response_data.size();
  348. u64 length = response_data.size();
  349. if (!xhr.m_synchronous) {
  350. xhr.m_response_object = response_data;
  351. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  352. }
  353. xhr.m_ready_state = ReadyState::Done;
  354. xhr.m_status = status_code.value_or(0);
  355. xhr.m_response_headers = move(response_headers);
  356. xhr.m_send = false;
  357. xhr.dispatch_event(DOM::Event::create(EventNames::readystatechange));
  358. xhr.fire_progress_event(EventNames::load, transmitted, length);
  359. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  360. },
  361. [weak_this = make_weak_ptr()](auto& error, auto status_code) {
  362. dbgln("XHR failed to load: {}", error);
  363. auto strong_this = weak_this.strong_ref();
  364. if (!strong_this)
  365. return;
  366. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  367. xhr.set_ready_state(ReadyState::Done);
  368. xhr.set_status(status_code.value_or(0));
  369. xhr.dispatch_event(DOM::Event::create(HTML::EventNames::error));
  370. });
  371. } else {
  372. TODO();
  373. }
  374. return {};
  375. }
  376. JS::Object* XMLHttpRequest::create_wrapper(JS::GlobalObject& global_object)
  377. {
  378. return wrap(global_object, *this);
  379. }
  380. Bindings::CallbackType* XMLHttpRequest::onreadystatechange()
  381. {
  382. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  383. }
  384. void XMLHttpRequest::set_onreadystatechange(Optional<Bindings::CallbackType> value)
  385. {
  386. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, move(value));
  387. }
  388. // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
  389. String XMLHttpRequest::get_all_response_headers() const
  390. {
  391. // FIXME: Implement the spec-compliant sort order.
  392. StringBuilder builder;
  393. auto keys = m_response_headers.keys();
  394. quick_sort(keys);
  395. for (auto& key : keys) {
  396. builder.append(key);
  397. builder.append(": ");
  398. builder.append(m_response_headers.get(key).value());
  399. builder.append("\r\n");
  400. }
  401. return builder.to_string();
  402. }
  403. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  404. DOM::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
  405. {
  406. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  407. if (m_ready_state == ReadyState::Loading || m_ready_state == ReadyState::Done)
  408. return DOM::InvalidStateError::create("Cannot override MIME type when state is Loading or Done.");
  409. // 2. Set this’s override MIME type to the result of parsing mime.
  410. m_override_mime_type = MimeSniff::MimeType::from_string(mime);
  411. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  412. if (!m_override_mime_type.has_value())
  413. m_override_mime_type = MimeSniff::MimeType("application"sv, "octet-stream"sv);
  414. return {};
  415. }
  416. }