WebSocket.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*
  2. * Copyright (c) 2021-2022, Dex♪ <dexes.ttp@gmail.com>
  3. * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/QuickSort.h>
  8. #include <LibJS/Runtime/ArrayBuffer.h>
  9. #include <LibJS/Runtime/FunctionObject.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/Event.h>
  12. #include <LibWeb/DOM/EventDispatcher.h>
  13. #include <LibWeb/DOM/IDLEventListener.h>
  14. #include <LibWeb/FileAPI/Blob.h>
  15. #include <LibWeb/HTML/CloseEvent.h>
  16. #include <LibWeb/HTML/EventHandler.h>
  17. #include <LibWeb/HTML/EventNames.h>
  18. #include <LibWeb/HTML/MessageEvent.h>
  19. #include <LibWeb/HTML/Origin.h>
  20. #include <LibWeb/HTML/Window.h>
  21. #include <LibWeb/Loader/ResourceLoader.h>
  22. #include <LibWeb/WebIDL/AbstractOperations.h>
  23. #include <LibWeb/WebIDL/Buffers.h>
  24. #include <LibWeb/WebIDL/DOMException.h>
  25. #include <LibWeb/WebIDL/ExceptionOr.h>
  26. #include <LibWeb/WebSockets/WebSocket.h>
  27. namespace Web::WebSockets {
  28. JS_DEFINE_ALLOCATOR(WebSocket);
  29. WebSocketClientSocket::~WebSocketClientSocket() = default;
  30. // https://websockets.spec.whatwg.org/#dom-websocket-websocket
  31. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebSocket>> WebSocket::construct_impl(JS::Realm& realm, String const& url, Optional<Variant<String, Vector<String>>> const& protocols)
  32. {
  33. auto& vm = realm.vm();
  34. auto web_socket = realm.heap().allocate<WebSocket>(realm, realm);
  35. auto& relevant_settings_object = HTML::relevant_settings_object(*web_socket);
  36. // 1. Let baseURL be this's relevant settings object's API base URL.
  37. auto base_url = relevant_settings_object.api_base_url();
  38. // 2. Let urlRecord be the result of applying the URL parser to url with baseURL.
  39. // FIXME: This should call an implementation of https://url.spec.whatwg.org/#concept-url-parser, currently it calls https://url.spec.whatwg.org/#concept-basic-url-parser
  40. auto url_record = base_url.complete_url(url);
  41. // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
  42. if (!url_record.is_valid())
  43. return WebIDL::SyntaxError::create(realm, "Invalid URL"_fly_string);
  44. // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
  45. if (url_record.scheme() == "http"sv)
  46. url_record.set_scheme("ws"_string);
  47. // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
  48. else if (url_record.scheme() == "https"sv)
  49. url_record.set_scheme("wss"_string);
  50. // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
  51. if (!url_record.scheme().is_one_of("ws"sv, "wss"sv))
  52. return WebIDL::SyntaxError::create(realm, "Invalid protocol"_fly_string);
  53. // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" DOMException.
  54. if (url_record.fragment().has_value())
  55. return WebIDL::SyntaxError::create(realm, "Presence of URL fragment is invalid"_fly_string);
  56. Vector<String> protocols_sequence;
  57. // 8. If protocols is a string, set protocols to a sequence consisting of just that string.
  58. if (protocols.has_value() && protocols->has<String>())
  59. protocols_sequence = { protocols.value().get<String>() };
  60. else if (protocols.has_value() && protocols->has<Vector<String>>())
  61. protocols_sequence = protocols.value().get<Vector<String>>();
  62. else
  63. protocols_sequence = {};
  64. // 9. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise
  65. // the value of `Sec-WebSocket-Protocol` fields as defined by The WebSocket protocol, then throw a "SyntaxError" DOMException. [WSP]
  66. auto sorted_protocols = protocols_sequence;
  67. quick_sort(sorted_protocols);
  68. for (size_t i = 0; i < sorted_protocols.size(); i++) {
  69. // https://datatracker.ietf.org/doc/html/rfc6455
  70. // The elements that comprise this value MUST be non-empty strings with characters in the range U+0021 to U+007E not including
  71. // separator characters as defined in [RFC2616] and MUST all be unique strings.
  72. auto protocol = sorted_protocols[i];
  73. if (i < sorted_protocols.size() - 1 && protocol == sorted_protocols[i + 1])
  74. return WebIDL::SyntaxError::create(realm, "Found a duplicate protocol name in the specified list"_fly_string);
  75. for (auto code_point : protocol.code_points()) {
  76. if (code_point < '\x21' || code_point > '\x7E')
  77. return WebIDL::SyntaxError::create(realm, "Found invalid character in subprotocol name"_fly_string);
  78. }
  79. }
  80. // 10. Set this's url to urlRecord.
  81. web_socket->set_url(url_record);
  82. // 11. Let client be this’s relevant settings object.
  83. auto& client = relevant_settings_object;
  84. // FIXME: 12. Run this step in parallel:
  85. // 1. Establish a WebSocket connection given urlRecord, protocols, and client. [FETCH]
  86. TRY_OR_THROW_OOM(vm, web_socket->establish_web_socket_connection(url_record, protocols_sequence, client));
  87. return web_socket;
  88. }
  89. WebSocket::WebSocket(JS::Realm& realm)
  90. : EventTarget(realm)
  91. {
  92. }
  93. WebSocket::~WebSocket() = default;
  94. void WebSocket::initialize(JS::Realm& realm)
  95. {
  96. Base::initialize(realm);
  97. WEB_SET_PROTOTYPE_FOR_INTERFACE(WebSocket);
  98. }
  99. ErrorOr<void> WebSocket::establish_web_socket_connection(URL& url_record, Vector<String>& protocols, HTML::EnvironmentSettingsObject& client)
  100. {
  101. // FIXME: Integrate properly with FETCH as per https://fetch.spec.whatwg.org/#websocket-opening-handshake
  102. auto& window = verify_cast<HTML::Window>(client.global_object());
  103. auto origin_string = window.associated_document().origin().serialize();
  104. Vector<ByteString> protcol_byte_strings;
  105. for (auto const& protocol : protocols)
  106. TRY(protcol_byte_strings.try_append(protocol.to_byte_string()));
  107. m_websocket = ResourceLoader::the().connector().websocket_connect(url_record, origin_string, protcol_byte_strings);
  108. m_websocket->on_open = [weak_this = make_weak_ptr<WebSocket>()] {
  109. if (!weak_this)
  110. return;
  111. auto& websocket = const_cast<WebSocket&>(*weak_this);
  112. websocket.on_open();
  113. };
  114. m_websocket->on_message = [weak_this = make_weak_ptr<WebSocket>()](auto message) {
  115. if (!weak_this)
  116. return;
  117. auto& websocket = const_cast<WebSocket&>(*weak_this);
  118. websocket.on_message(move(message.data), message.is_text);
  119. };
  120. m_websocket->on_close = [weak_this = make_weak_ptr<WebSocket>()](auto code, auto reason, bool was_clean) {
  121. if (!weak_this)
  122. return;
  123. auto& websocket = const_cast<WebSocket&>(*weak_this);
  124. websocket.on_close(code, String::from_byte_string(reason).release_value_but_fixme_should_propagate_errors(), was_clean);
  125. };
  126. m_websocket->on_error = [weak_this = make_weak_ptr<WebSocket>()](auto) {
  127. if (!weak_this)
  128. return;
  129. auto& websocket = const_cast<WebSocket&>(*weak_this);
  130. websocket.on_error();
  131. };
  132. return {};
  133. }
  134. // https://websockets.spec.whatwg.org/#dom-websocket-readystate
  135. WebSocket::ReadyState WebSocket::ready_state() const
  136. {
  137. if (!m_websocket)
  138. return WebSocket::ReadyState::Closed;
  139. return const_cast<WebSocketClientSocket&>(*m_websocket).ready_state();
  140. }
  141. // https://websockets.spec.whatwg.org/#dom-websocket-extensions
  142. String WebSocket::extensions() const
  143. {
  144. if (!m_websocket)
  145. return String {};
  146. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  147. // FIXME: Change the extensions attribute's value to the extensions in use, if it is not the null value.
  148. return String {};
  149. }
  150. // https://websockets.spec.whatwg.org/#dom-websocket-protocol
  151. WebIDL::ExceptionOr<String> WebSocket::protocol() const
  152. {
  153. if (!m_websocket)
  154. return String {};
  155. return TRY_OR_THROW_OOM(vm(), String::from_byte_string(m_websocket->subprotocol_in_use()));
  156. }
  157. // https://websockets.spec.whatwg.org/#dom-websocket-close
  158. WebIDL::ExceptionOr<void> WebSocket::close(Optional<u16> code, Optional<String> reason)
  159. {
  160. // 1. If code is present, but is neither an integer equal to 1000 nor an integer in the range 3000 to 4999, inclusive, throw an "InvalidAccessError" DOMException.
  161. if (code.has_value() && *code != 1000 && (*code < 3000 || *code > 4099))
  162. return WebIDL::InvalidAccessError::create(realm(), "The close error code is invalid"_fly_string);
  163. // 2. If reason is present, then run these substeps:
  164. if (reason.has_value()) {
  165. // 1. Let reasonBytes be the result of encoding reason.
  166. // 2. If reasonBytes is longer than 123 bytes, then throw a "SyntaxError" DOMException.
  167. if (reason->bytes().size() > 123)
  168. return WebIDL::SyntaxError::create(realm(), "The close reason is longer than 123 bytes"_fly_string);
  169. }
  170. // 3. Run the first matching steps from the following list:
  171. auto state = ready_state();
  172. // -> If this's ready state is CLOSING (2) or CLOSED (3)
  173. if (state == WebSocket::ReadyState::Closing || state == WebSocket::ReadyState::Closed)
  174. return {};
  175. // -> If the WebSocket connection is not yet established [WSP]
  176. // -> If the WebSocket closing handshake has not yet been started [WSP]
  177. // -> Otherwise
  178. // NOTE: All of these are handled by the WebSocket Protocol when calling close()
  179. // FIXME: LibProtocol does not yet support sending empty Close messages, so we use default values for now
  180. m_websocket->close(code.value_or(1000), reason.value_or(String {}).to_byte_string());
  181. return {};
  182. }
  183. // https://websockets.spec.whatwg.org/#dom-websocket-send
  184. WebIDL::ExceptionOr<void> WebSocket::send(Variant<JS::Handle<WebIDL::BufferSource>, JS::Handle<FileAPI::Blob>, String> const& data)
  185. {
  186. auto state = ready_state();
  187. if (state == WebSocket::ReadyState::Connecting)
  188. return WebIDL::InvalidStateError::create(realm(), "Websocket is still CONNECTING"_fly_string);
  189. if (state == WebSocket::ReadyState::Open) {
  190. TRY_OR_THROW_OOM(vm(),
  191. data.visit(
  192. [this](String const& string) -> ErrorOr<void> {
  193. m_websocket->send(string);
  194. return {};
  195. },
  196. [this](JS::Handle<WebIDL::BufferSource> const& buffer_source) -> ErrorOr<void> {
  197. // FIXME: While the spec doesn't say to do this, it's not observable except from potentially throwing OOM.
  198. // Can we avoid this copy?
  199. auto data_buffer = TRY(WebIDL::get_buffer_source_copy(*buffer_source->raw_object()));
  200. m_websocket->send(data_buffer, false);
  201. return {};
  202. },
  203. [this](JS::Handle<FileAPI::Blob> const& blob) -> ErrorOr<void> {
  204. auto byte_buffer = TRY(ByteBuffer::copy(blob->bytes()));
  205. m_websocket->send(byte_buffer, false);
  206. return {};
  207. }));
  208. // TODO : If the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection.
  209. // TODO : Any invocation of this method with a string argument that does not throw an exception must increase the bufferedAmount attribute by the number of bytes needed to express the argument as UTF-8.
  210. }
  211. return {};
  212. }
  213. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  214. void WebSocket::on_open()
  215. {
  216. // 1. Change the readyState attribute's value to OPEN (1).
  217. // 2. Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]
  218. // 3. Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]
  219. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::open));
  220. }
  221. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  222. void WebSocket::on_error()
  223. {
  224. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
  225. }
  226. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  227. void WebSocket::on_close(u16 code, String reason, bool was_clean)
  228. {
  229. // 1. Change the readyState attribute's value to CLOSED. This is handled by the Protocol's WebSocket
  230. // 2. If [needed], fire an event named error at the WebSocket object. This is handled by the Protocol's WebSocket
  231. HTML::CloseEventInit event_init {};
  232. event_init.was_clean = was_clean;
  233. event_init.code = code;
  234. event_init.reason = reason;
  235. dispatch_event(HTML::CloseEvent::create(realm(), HTML::EventNames::close, event_init));
  236. }
  237. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  238. void WebSocket::on_message(ByteBuffer message, bool is_text)
  239. {
  240. if (m_websocket->ready_state() != WebSocket::ReadyState::Open)
  241. return;
  242. if (is_text) {
  243. auto text_message = ByteString(ReadonlyBytes(message));
  244. HTML::MessageEventInit event_init;
  245. event_init.data = JS::PrimitiveString::create(vm(), text_message);
  246. event_init.origin = url().release_value_but_fixme_should_propagate_errors();
  247. dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init));
  248. return;
  249. }
  250. if (m_binary_type == "blob") {
  251. // type indicates that the data is Binary and binaryType is "blob"
  252. TODO();
  253. } else if (m_binary_type == "arraybuffer") {
  254. // type indicates that the data is Binary and binaryType is "arraybuffer"
  255. HTML::MessageEventInit event_init;
  256. event_init.data = JS::ArrayBuffer::create(realm(), message);
  257. event_init.origin = url().release_value_but_fixme_should_propagate_errors();
  258. dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init));
  259. return;
  260. }
  261. dbgln("Unsupported WebSocket message type {}", m_binary_type);
  262. TODO();
  263. }
  264. #undef __ENUMERATE
  265. #define __ENUMERATE(attribute_name, event_name) \
  266. void WebSocket::set_##attribute_name(WebIDL::CallbackType* value) \
  267. { \
  268. set_event_handler_attribute(event_name, value); \
  269. } \
  270. WebIDL::CallbackType* WebSocket::attribute_name() \
  271. { \
  272. return event_handler_attribute(event_name); \
  273. }
  274. ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
  275. #undef __ENUMERATE
  276. }