XMLHttpRequest.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  6. * Copyright (c) 2022-2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/ByteBuffer.h>
  11. #include <AK/GenericLexer.h>
  12. #include <AK/QuickSort.h>
  13. #include <LibJS/Runtime/ArrayBuffer.h>
  14. #include <LibJS/Runtime/Completion.h>
  15. #include <LibJS/Runtime/FunctionObject.h>
  16. #include <LibJS/Runtime/GlobalObject.h>
  17. #include <LibTextCodec/Decoder.h>
  18. #include <LibWeb/Bindings/XMLHttpRequestPrototype.h>
  19. #include <LibWeb/DOM/Document.h>
  20. #include <LibWeb/DOM/Event.h>
  21. #include <LibWeb/DOM/EventDispatcher.h>
  22. #include <LibWeb/DOM/IDLEventListener.h>
  23. #include <LibWeb/Fetch/BodyInit.h>
  24. #include <LibWeb/Fetch/Infrastructure/HTTP.h>
  25. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  26. #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
  27. #include <LibWeb/FileAPI/Blob.h>
  28. #include <LibWeb/HTML/EventHandler.h>
  29. #include <LibWeb/HTML/EventNames.h>
  30. #include <LibWeb/HTML/Origin.h>
  31. #include <LibWeb/HTML/Window.h>
  32. #include <LibWeb/Infra/JSON.h>
  33. #include <LibWeb/Loader/ResourceLoader.h>
  34. #include <LibWeb/Page/Page.h>
  35. #include <LibWeb/WebIDL/DOMException.h>
  36. #include <LibWeb/WebIDL/ExceptionOr.h>
  37. #include <LibWeb/XHR/EventNames.h>
  38. #include <LibWeb/XHR/ProgressEvent.h>
  39. #include <LibWeb/XHR/XMLHttpRequest.h>
  40. namespace Web::XHR {
  41. WebIDL::ExceptionOr<JS::NonnullGCPtr<XMLHttpRequest>> XMLHttpRequest::construct_impl(JS::Realm& realm)
  42. {
  43. auto& window = verify_cast<HTML::Window>(realm.global_object());
  44. auto author_request_headers = Fetch::Infrastructure::HeaderList::create(realm.vm());
  45. return MUST_OR_THROW_OOM(realm.heap().allocate<XMLHttpRequest>(realm, window, *author_request_headers));
  46. }
  47. XMLHttpRequest::XMLHttpRequest(HTML::Window& window, Fetch::Infrastructure::HeaderList& author_request_headers)
  48. : XMLHttpRequestEventTarget(window.realm())
  49. , m_window(window)
  50. , m_author_request_headers(author_request_headers)
  51. , m_response_type(Bindings::XMLHttpRequestResponseType::Empty)
  52. {
  53. set_overrides_must_survive_garbage_collection(true);
  54. }
  55. XMLHttpRequest::~XMLHttpRequest() = default;
  56. JS::ThrowCompletionOr<void> XMLHttpRequest::initialize(JS::Realm& realm)
  57. {
  58. MUST_OR_THROW_OOM(Base::initialize(realm));
  59. set_prototype(&Bindings::ensure_web_prototype<Bindings::XMLHttpRequestPrototype>(realm, "XMLHttpRequest"));
  60. return {};
  61. }
  62. void XMLHttpRequest::visit_edges(Cell::Visitor& visitor)
  63. {
  64. Base::visit_edges(visitor);
  65. visitor.visit(m_window.ptr());
  66. visitor.visit(m_author_request_headers);
  67. if (auto* value = m_response_object.get_pointer<JS::Value>())
  68. visitor.visit(*value);
  69. }
  70. void XMLHttpRequest::fire_progress_event(DeprecatedString const& event_name, u64 transmitted, u64 length)
  71. {
  72. ProgressEventInit event_init {};
  73. event_init.length_computable = true;
  74. event_init.loaded = transmitted;
  75. event_init.total = length;
  76. dispatch_event(*ProgressEvent::create(realm(), event_name, event_init).release_value_but_fixme_should_propagate_errors());
  77. }
  78. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext
  79. WebIDL::ExceptionOr<DeprecatedString> XMLHttpRequest::response_text() const
  80. {
  81. // 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.
  82. if (m_response_type != Bindings::XMLHttpRequestResponseType::Empty && m_response_type != Bindings::XMLHttpRequestResponseType::Text)
  83. return WebIDL::InvalidStateError::create(realm(), "XHR responseText can only be used for responseType \"\" or \"text\"");
  84. // 2. If this’s state is not loading or done, then return the empty string.
  85. if (m_state != State::Loading && m_state != State::Done)
  86. return DeprecatedString::empty();
  87. return get_text_response();
  88. }
  89. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype
  90. WebIDL::ExceptionOr<void> XMLHttpRequest::set_response_type(Bindings::XMLHttpRequestResponseType response_type)
  91. {
  92. // 1. If the current global object is not a Window object and the given value is "document", then return.
  93. if (!is<HTML::Window>(HTML::current_global_object()) && response_type == Bindings::XMLHttpRequestResponseType::Document)
  94. return {};
  95. // 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  96. if (m_state == State::Loading || m_state == State::Done)
  97. return WebIDL::InvalidStateError::create(realm(), "Can't readyState when XHR is loading or done");
  98. // 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.
  99. if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
  100. return WebIDL::InvalidAccessError::create(realm(), "Can't set readyState on synchronous XHR in Window environment");
  101. // 4. Set this’s response type to the given value.
  102. m_response_type = response_type;
  103. return {};
  104. }
  105. // https://xhr.spec.whatwg.org/#response
  106. WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response()
  107. {
  108. auto& vm = this->vm();
  109. // 1. If this’s response type is the empty string or "text", then:
  110. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty || m_response_type == Bindings::XMLHttpRequestResponseType::Text) {
  111. // 1. If this’s state is not loading or done, then return the empty string.
  112. if (m_state != State::Loading && m_state != State::Done)
  113. return JS::PrimitiveString::create(vm, String {});
  114. // 2. Return the result of getting a text response for this.
  115. return JS::PrimitiveString::create(vm, get_text_response());
  116. }
  117. // 2. If this’s state is not done, then return null.
  118. if (m_state != State::Done)
  119. return JS::js_null();
  120. // 3. If this’s response object is failure, then return null.
  121. if (m_response_object.has<Failure>())
  122. return JS::js_null();
  123. // 4. If this’s response object is non-null, then return it.
  124. if (!m_response_object.has<Empty>())
  125. return m_response_object.get<JS::Value>();
  126. // 5. If this’s response type is "arraybuffer",
  127. if (m_response_type == Bindings::XMLHttpRequestResponseType::Arraybuffer) {
  128. // then set this’s response object to a new ArrayBuffer object representing this’s received bytes. If this throws an exception, then set this’s response object to failure and return null.
  129. auto buffer_result = JS::ArrayBuffer::create(realm(), m_received_bytes.size());
  130. if (buffer_result.is_error()) {
  131. m_response_object = Failure();
  132. return JS::js_null();
  133. }
  134. auto buffer = buffer_result.release_value();
  135. buffer->buffer().overwrite(0, m_received_bytes.data(), m_received_bytes.size());
  136. m_response_object = JS::Value(buffer);
  137. }
  138. // 6. Otherwise, if this’s response type is "blob", set this’s response object to a new Blob object representing this’s received bytes with type set to the result of get a final MIME type for this.
  139. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Blob) {
  140. auto mime_type_as_string = TRY_OR_THROW_OOM(vm, String::from_deprecated_string(get_final_mime_type().serialized()));
  141. auto blob_part = TRY(FileAPI::Blob::create(realm(), m_received_bytes, move(mime_type_as_string)));
  142. auto blob = TRY(FileAPI::Blob::create(realm(), Vector<FileAPI::BlobPart> { JS::make_handle(*blob_part) }));
  143. m_response_object = JS::Value(blob.ptr());
  144. }
  145. // 7. Otherwise, if this’s response type is "document", set a document response for this.
  146. else if (m_response_type == Bindings::XMLHttpRequestResponseType::Document) {
  147. // FIXME: Implement this.
  148. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "XHR Document type not implemented"sv };
  149. }
  150. // 8. Otherwise:
  151. else {
  152. // 1. Assert: this’s response type is "json".
  153. // Note: Automatically done by the layers above us.
  154. // 2. If this’s response’s body is null, then return null.
  155. // FIXME: Implement this once we have 'Response'.
  156. if (m_received_bytes.is_empty())
  157. return JS::js_null();
  158. // 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an exception, then return null.
  159. auto json_object_result = Infra::parse_json_bytes_to_javascript_value(vm, m_received_bytes);
  160. if (json_object_result.is_error())
  161. return JS::js_null();
  162. // 4. Set this’s response object to jsonObject.
  163. m_response_object = json_object_result.release_value();
  164. }
  165. // 9. Return this’s response object.
  166. return m_response_object.get<JS::Value>();
  167. }
  168. // https://xhr.spec.whatwg.org/#text-response
  169. DeprecatedString XMLHttpRequest::get_text_response() const
  170. {
  171. // FIXME: 1. If xhr’s response’s body is null, then return the empty string.
  172. // 2. Let charset be the result of get a final encoding for xhr.
  173. auto charset = get_final_encoding();
  174. auto is_xml_mime_type = [](MimeSniff::MimeType const& mime_type) {
  175. // An XML MIME type is any MIME type whose subtype ends in "+xml" or whose essence is "text/xml" or "application/xml". [RFC7303]
  176. if (mime_type.essence().is_one_of("text/xml"sv, "application/xml"sv))
  177. return true;
  178. return mime_type.subtype().ends_with("+xml"sv);
  179. };
  180. // 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,
  181. if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty && !charset.has_value() && is_xml_mime_type(get_final_mime_type())) {
  182. // FIXME: then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]
  183. }
  184. // 4. If charset is null, then set charset to UTF-8.
  185. if (!charset.has_value())
  186. charset = "UTF-8"sv;
  187. // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.
  188. auto decoder = TextCodec::decoder_for(charset.value());
  189. // 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.
  190. VERIFY(decoder.has_value());
  191. return TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, m_received_bytes).release_value_but_fixme_should_propagate_errors().to_deprecated_string();
  192. }
  193. // https://xhr.spec.whatwg.org/#final-mime-type
  194. MimeSniff::MimeType XMLHttpRequest::get_final_mime_type() const
  195. {
  196. // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.
  197. if (!m_override_mime_type.has_value())
  198. return get_response_mime_type();
  199. // 2. Return xhr’s override MIME type.
  200. return *m_override_mime_type;
  201. }
  202. // https://xhr.spec.whatwg.org/#response-mime-type
  203. MimeSniff::MimeType XMLHttpRequest::get_response_mime_type() const
  204. {
  205. auto& vm = this->vm();
  206. // FIXME: Use an actual HeaderList for XHR headers.
  207. auto header_list = Fetch::Infrastructure::HeaderList::create(vm);
  208. for (auto const& entry : m_response_headers) {
  209. auto header = Fetch::Infrastructure::Header::from_string_pair(entry.key, entry.value).release_value_but_fixme_should_propagate_errors();
  210. header_list->append(move(header)).release_value_but_fixme_should_propagate_errors();
  211. }
  212. // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.
  213. auto mime_type = header_list->extract_mime_type();
  214. // 2. If mimeType is failure, then set mimeType to text/xml.
  215. if (!mime_type.has_value())
  216. return MimeSniff::MimeType("text"sv, "xml"sv);
  217. // 3. Return mimeType.
  218. return mime_type.release_value();
  219. }
  220. // https://xhr.spec.whatwg.org/#final-charset
  221. Optional<StringView> XMLHttpRequest::get_final_encoding() const
  222. {
  223. // 1. Let label be null.
  224. Optional<DeprecatedString> label;
  225. // 2. Let responseMIME be the result of get a response MIME type for xhr.
  226. auto response_mime = get_response_mime_type();
  227. // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
  228. auto response_mime_charset_it = response_mime.parameters().find("charset"sv);
  229. if (response_mime_charset_it != response_mime.parameters().end())
  230. label = response_mime_charset_it->value;
  231. // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
  232. if (m_override_mime_type.has_value()) {
  233. auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);
  234. if (override_mime_charset_it != m_override_mime_type->parameters().end())
  235. label = override_mime_charset_it->value;
  236. }
  237. // 5. If label is null, then return null.
  238. if (!label.has_value())
  239. return {};
  240. // 6. Let encoding be the result of getting an encoding from label.
  241. auto encoding = TextCodec::get_standardized_encoding(label.value());
  242. // 7. If encoding is failure, then return null.
  243. // 8. Return encoding.
  244. return encoding;
  245. }
  246. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader
  247. WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(DeprecatedString const& name_string, DeprecatedString const& value_string)
  248. {
  249. auto& realm = this->realm();
  250. auto& vm = realm.vm();
  251. auto name = name_string.to_byte_buffer();
  252. auto value = value_string.to_byte_buffer();
  253. // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
  254. if (m_state != State::Opened)
  255. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED");
  256. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  257. if (m_send)
  258. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set");
  259. // 3. Normalize value.
  260. value = MUST(Fetch::Infrastructure::normalize_header_value(value));
  261. // 4. If name is not a header name or value is not a header value, then throw a "SyntaxError" DOMException.
  262. if (!Fetch::Infrastructure::is_header_name(name))
  263. return WebIDL::SyntaxError::create(realm, "Header name contains invalid characters.");
  264. if (!Fetch::Infrastructure::is_header_value(value))
  265. return WebIDL::SyntaxError::create(realm, "Header value contains invalid characters.");
  266. auto header = Fetch::Infrastructure::Header {
  267. .name = move(name),
  268. .value = move(value),
  269. };
  270. // 5. If (name, value) is a forbidden request-header, then return.
  271. if (TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::is_forbidden_request_header(header)))
  272. return {};
  273. // 6. Combine (name, value) in this’s author request headers.
  274. TRY_OR_THROW_OOM(vm, m_author_request_headers->combine(move(header)));
  275. return {};
  276. }
  277. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open
  278. WebIDL::ExceptionOr<void> XMLHttpRequest::open(DeprecatedString const& method_string, DeprecatedString const& url)
  279. {
  280. // 8. If the async argument is omitted, set async to true, and set username and password to null.
  281. return open(method_string, url, true, {}, {});
  282. }
  283. WebIDL::ExceptionOr<void> XMLHttpRequest::open(DeprecatedString const& method_string, DeprecatedString const& url, bool async, DeprecatedString const& username, DeprecatedString const& password)
  284. {
  285. auto method = method_string.to_byte_buffer();
  286. // 1. Let settingsObject be this’s relevant settings object.
  287. auto& settings_object = m_window->associated_document().relevant_settings_object();
  288. // 2. If settingsObject has a responsible document and it is not fully active, then throw an "InvalidStateError" DOMException.
  289. if (settings_object.responsible_document() && !settings_object.responsible_document()->is_active())
  290. return WebIDL::InvalidStateError::create(realm(), "Invalid state: Responsible document is not fully active.");
  291. // 3. If method is not a method, then throw a "SyntaxError" DOMException.
  292. if (!Fetch::Infrastructure::is_method(method))
  293. return WebIDL::SyntaxError::create(realm(), "An invalid or illegal string was specified.");
  294. // 4. If method is a forbidden method, then throw a "SecurityError" DOMException.
  295. if (Fetch::Infrastructure::is_forbidden_method(method))
  296. return WebIDL::SecurityError::create(realm(), "Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'");
  297. // 5. Normalize method.
  298. method = MUST(Fetch::Infrastructure::normalize_method(method));
  299. // 6. Let parsedURL be the result of parsing url with settingsObject’s API base URL and settingsObject’s API URL character encoding.
  300. auto parsed_url = settings_object.api_base_url().complete_url(url);
  301. // 7. If parsedURL is failure, then throw a "SyntaxError" DOMException.
  302. if (!parsed_url.is_valid())
  303. return WebIDL::SyntaxError::create(realm(), "Invalid URL");
  304. // 8. If the async argument is omitted, set async to true, and set username and password to null.
  305. // NOTE: This is handled in the overload lacking the async argument.
  306. // 9. If parsedURL’s host is non-null, then:
  307. if (!parsed_url.host().is_null()) {
  308. // 1. If the username argument is not null, set the username given parsedURL and username.
  309. if (!username.is_null())
  310. parsed_url.set_username(username);
  311. // 2. If the password argument is not null, set the password given parsedURL and password.
  312. if (!password.is_null())
  313. parsed_url.set_password(password);
  314. }
  315. // 10. If async is false, the current global object is a Window object, and either this’s timeout is
  316. // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.
  317. if (!async
  318. && is<HTML::Window>(HTML::current_global_object())
  319. && (m_timeout != 0 || m_response_type != Bindings::XMLHttpRequestResponseType::Empty)) {
  320. return WebIDL::InvalidAccessError::create(realm(), "synchronous XMLHttpRequests do not support timeout and responseType");
  321. }
  322. // FIXME: 11. Terminate the ongoing fetch operated by the XMLHttpRequest object.
  323. // 12. Set variables associated with the object as follows:
  324. // Unset this’s send() flag.
  325. m_send = false;
  326. // Unset this’s upload listener flag.
  327. m_upload_listener = false;
  328. // Set this’s request method to method.
  329. m_request_method = move(method);
  330. // Set this’s request URL to parsedURL.
  331. m_request_url = parsed_url;
  332. // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.
  333. m_synchronous = !async;
  334. // Empty this’s author request headers.
  335. m_author_request_headers->clear();
  336. // FIXME: Set this’s response to a network error.
  337. // Set this’s received bytes to the empty byte sequence.
  338. m_received_bytes = {};
  339. // Set this’s response object to null.
  340. m_response_object = {};
  341. // 13. If this’s state is not opened, then:
  342. if (m_state != State::Opened) {
  343. // 1. Set this’s state to opened.
  344. m_state = State::Opened;
  345. // 2. Fire an event named readystatechange at this.
  346. dispatch_event(TRY(DOM::Event::create(realm(), EventNames::readystatechange)));
  347. }
  348. return {};
  349. }
  350. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send
  351. WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequestBodyInit> body)
  352. {
  353. auto& vm = this->vm();
  354. auto& realm = *vm.current_realm();
  355. if (m_state != State::Opened)
  356. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED");
  357. if (m_send)
  358. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set");
  359. // If this’s request method is `GET` or `HEAD`, then set body to null.
  360. if (m_request_method.is_one_of("GET"sv, "HEAD"sv))
  361. body = {};
  362. Optional<Fetch::Infrastructure::BodyWithType> body_with_type {};
  363. Optional<DeprecatedString> serialized_document {};
  364. if (body.has_value()) {
  365. if (body->has<JS::Handle<DOM::Document>>())
  366. serialized_document = TRY(body->get<JS::Handle<DOM::Document>>().cell()->serialize_fragment(DOMParsing::RequireWellFormed::No));
  367. else
  368. body_with_type = TRY(Fetch::extract_body(realm, body->downcast<Fetch::BodyInitOrReadableBytes>()));
  369. }
  370. AK::URL request_url = m_window->associated_document().parse_url(m_request_url.to_deprecated_string());
  371. dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url);
  372. // TODO: Add support for preflight requests to support CORS requests
  373. auto request_url_origin = HTML::Origin(request_url.scheme(), request_url.host(), request_url.port_or_default());
  374. bool should_enforce_same_origin_policy = true;
  375. if (auto* page = m_window->page())
  376. should_enforce_same_origin_policy = page->is_same_origin_policy_enabled();
  377. if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same_origin(request_url_origin)) {
  378. dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
  379. m_state = State::Done;
  380. dispatch_event(TRY(DOM::Event::create(realm, EventNames::readystatechange)));
  381. dispatch_event(TRY(DOM::Event::create(realm, HTML::EventNames::error)));
  382. return {};
  383. }
  384. auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page());
  385. request.set_method(m_request_method);
  386. if (serialized_document.has_value()) {
  387. request.set_body(serialized_document->to_byte_buffer());
  388. } else if (body_with_type.has_value()) {
  389. TRY(body_with_type->body.source().visit(
  390. [&](ByteBuffer const& buffer) -> WebIDL::ExceptionOr<void> {
  391. auto byte_buffer = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(buffer));
  392. request.set_body(move(byte_buffer));
  393. return {};
  394. },
  395. [&](JS::Handle<FileAPI::Blob> const& blob) -> WebIDL::ExceptionOr<void> {
  396. auto byte_buffer = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob->bytes()));
  397. request.set_body(move(byte_buffer));
  398. return {};
  399. },
  400. [](auto&) -> WebIDL::ExceptionOr<void> {
  401. return {};
  402. }));
  403. }
  404. // If this’s headers’s header list does not contain `Content-Type`, then append (`Content-Type`, type) to this’s headers.
  405. if (!m_author_request_headers->contains("Content-Type"sv.bytes())) {
  406. if (body_with_type.has_value() && body_with_type->type.has_value()) {
  407. request.set_header("Content-Type", DeprecatedString { body_with_type->type->span() });
  408. } else if (body.has_value() && body->has<JS::Handle<DOM::Document>>()) {
  409. request.set_header("Content-Type", "text/html;charset=UTF-8");
  410. }
  411. }
  412. for (auto& it : *m_author_request_headers)
  413. request.set_header(DeprecatedString::copy(it.name), DeprecatedString::copy(it.value));
  414. m_upload_complete = false;
  415. m_timed_out = false;
  416. // FIXME: If req’s body is null (which it always is currently)
  417. m_upload_complete = true;
  418. m_send = true;
  419. if (!m_synchronous) {
  420. fire_progress_event(EventNames::loadstart, 0, 0);
  421. // FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
  422. // then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
  423. if (m_state != State::Opened || !m_send)
  424. return {};
  425. // FIXME: in order to properly set State::HeadersReceived and State::Loading,
  426. // we need to make ResourceLoader give us more detailed updates than just "done" and "error".
  427. // FIXME: In the Fetch spec, which XHR gets its definition of `status` from, the status code is 0-999.
  428. // We could clamp, wrap around (current browser behavior!), or error out.
  429. // See: https://github.com/whatwg/fetch/issues/1142
  430. ResourceLoader::the().load(
  431. request,
  432. [weak_this = make_weak_ptr<XMLHttpRequest>()](auto data, auto& response_headers, auto status_code) {
  433. JS::GCPtr<XMLHttpRequest> strong_this = weak_this.ptr();
  434. if (!strong_this)
  435. return;
  436. auto& xhr = const_cast<XMLHttpRequest&>(*weak_this);
  437. // FIXME: Handle OOM failure.
  438. auto response_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  439. // FIXME: There's currently no difference between transmitted and length.
  440. u64 transmitted = response_data.size();
  441. u64 length = response_data.size();
  442. if (!xhr.m_synchronous) {
  443. xhr.m_received_bytes = response_data;
  444. xhr.fire_progress_event(EventNames::progress, transmitted, length);
  445. }
  446. xhr.m_state = State::Done;
  447. xhr.m_status = status_code.value_or(0);
  448. xhr.m_response_headers = move(response_headers);
  449. xhr.m_send = false;
  450. xhr.dispatch_event(DOM::Event::create(xhr.realm(), EventNames::readystatechange).release_value_but_fixme_should_propagate_errors());
  451. xhr.fire_progress_event(EventNames::load, transmitted, length);
  452. xhr.fire_progress_event(EventNames::loadend, transmitted, length);
  453. },
  454. [weak_this = make_weak_ptr<XMLHttpRequest>()](auto& error, auto status_code) {
  455. dbgln("XHR failed to load: {}", error);
  456. JS::GCPtr<XMLHttpRequest> strong_this = weak_this.ptr();
  457. if (!strong_this)
  458. return;
  459. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  460. xhr.m_state = State::Done;
  461. xhr.set_status(status_code.value_or(0));
  462. xhr.dispatch_event(DOM::Event::create(xhr.realm(), EventNames::readystatechange).release_value_but_fixme_should_propagate_errors());
  463. xhr.dispatch_event(DOM::Event::create(xhr.realm(), HTML::EventNames::error).release_value_but_fixme_should_propagate_errors());
  464. },
  465. m_timeout,
  466. [weak_this = make_weak_ptr<XMLHttpRequest>()] {
  467. JS::GCPtr<XMLHttpRequest> strong_this = weak_this.ptr();
  468. if (!strong_this)
  469. return;
  470. auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
  471. xhr.dispatch_event(DOM::Event::create(xhr.realm(), EventNames::timeout).release_value_but_fixme_should_propagate_errors());
  472. });
  473. } else {
  474. TODO();
  475. }
  476. return {};
  477. }
  478. WebIDL::CallbackType* XMLHttpRequest::onreadystatechange()
  479. {
  480. return event_handler_attribute(Web::XHR::EventNames::readystatechange);
  481. }
  482. void XMLHttpRequest::set_onreadystatechange(WebIDL::CallbackType* value)
  483. {
  484. set_event_handler_attribute(Web::XHR::EventNames::readystatechange, value);
  485. }
  486. // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
  487. DeprecatedString XMLHttpRequest::get_all_response_headers() const
  488. {
  489. // FIXME: Implement the spec-compliant sort order.
  490. StringBuilder builder;
  491. auto keys = m_response_headers.keys();
  492. quick_sort(keys);
  493. for (auto& key : keys) {
  494. builder.append(key);
  495. builder.append(": "sv);
  496. builder.append(m_response_headers.get(key).value());
  497. builder.append("\r\n"sv);
  498. }
  499. return builder.to_deprecated_string();
  500. }
  501. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype
  502. WebIDL::ExceptionOr<void> XMLHttpRequest::override_mime_type(DeprecatedString const& mime)
  503. {
  504. // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
  505. if (m_state == State::Loading || m_state == State::Done)
  506. return WebIDL::InvalidStateError::create(realm(), "Cannot override MIME type when state is Loading or Done.");
  507. // 2. Set this’s override MIME type to the result of parsing mime.
  508. m_override_mime_type = MimeSniff::MimeType::parse(mime);
  509. // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.
  510. if (!m_override_mime_type.has_value())
  511. m_override_mime_type = MimeSniff::MimeType("application"sv, "octet-stream"sv);
  512. return {};
  513. }
  514. // https://xhr.spec.whatwg.org/#ref-for-dom-xmlhttprequest-timeout%E2%91%A2
  515. WebIDL::ExceptionOr<void> XMLHttpRequest::set_timeout(u32 timeout)
  516. {
  517. // 1. If the current global object is a Window object and this’s synchronous flag is set,
  518. // then throw an "InvalidAccessError" DOMException.
  519. if (is<HTML::Window>(HTML::current_global_object()) && m_synchronous)
  520. return WebIDL::InvalidAccessError::create(realm(), "Use of XMLHttpRequest's timeout attribute is not supported in the synchronous mode in window context.");
  521. // 2. Set this’s timeout to the given value.
  522. m_timeout = timeout;
  523. return {};
  524. }
  525. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-timeout
  526. u32 XMLHttpRequest::timeout() const { return m_timeout; }
  527. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
  528. bool XMLHttpRequest::with_credentials() const
  529. {
  530. // The withCredentials getter steps are to return this’s cross-origin credentials.
  531. return m_cross_origin_credentials;
  532. }
  533. // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
  534. WebIDL::ExceptionOr<void> XMLHttpRequest::set_with_credentials(bool with_credentials)
  535. {
  536. auto& realm = this->realm();
  537. // 1. If this’s state is not unsent or opened, then throw an "InvalidStateError" DOMException.
  538. if (m_state != State::Unsent && m_state != State::Opened)
  539. return WebIDL::InvalidStateError::create(realm, "XHR readyState is not UNSENT or OPENED");
  540. // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
  541. if (m_send)
  542. return WebIDL::InvalidStateError::create(realm, "XHR send() flag is already set");
  543. // 3. Set this’s cross-origin credentials to the given value.
  544. m_cross_origin_credentials = with_credentials;
  545. return {};
  546. }
  547. // https://xhr.spec.whatwg.org/#garbage-collection
  548. bool XMLHttpRequest::must_survive_garbage_collection() const
  549. {
  550. // An XMLHttpRequest object must not be garbage collected
  551. // if its state is either opened with the send() flag set, headers received, or loading,
  552. // and it has one or more event listeners registered whose type is one of
  553. // readystatechange, progress, abort, error, load, timeout, and loadend.
  554. if ((m_state == State::Opened && m_send)
  555. || m_state == State::HeadersReceived
  556. || m_state == State::Loading) {
  557. if (has_event_listener(EventNames::readystatechange))
  558. return true;
  559. if (has_event_listener(EventNames::progress))
  560. return true;
  561. if (has_event_listener(EventNames::abort))
  562. return true;
  563. if (has_event_listener(EventNames::error))
  564. return true;
  565. if (has_event_listener(EventNames::load))
  566. return true;
  567. if (has_event_listener(EventNames::timeout))
  568. return true;
  569. if (has_event_listener(EventNames::loadend))
  570. return true;
  571. }
  572. // FIXME: If an XMLHttpRequest object is garbage collected while its connection is still open,
  573. // the user agent must terminate the XMLHttpRequest object’s fetch controller.
  574. // NOTE: This would go in XMLHttpRequest::finalize().
  575. return false;
  576. }
  577. void XMLHttpRequest::abort()
  578. {
  579. dbgln("(STUBBED) XMLHttpRequest::abort()");
  580. }
  581. }