WebSocket.cpp 15 KB

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