WebSocket.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Copyright (c) 2021-2022, Dex♪ <dexes.ttp@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibJS/Runtime/ArrayBuffer.h>
  8. #include <LibJS/Runtime/FunctionObject.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/DOM/Event.h>
  11. #include <LibWeb/DOM/EventDispatcher.h>
  12. #include <LibWeb/DOM/IDLEventListener.h>
  13. #include <LibWeb/HTML/CloseEvent.h>
  14. #include <LibWeb/HTML/EventHandler.h>
  15. #include <LibWeb/HTML/EventNames.h>
  16. #include <LibWeb/HTML/MessageEvent.h>
  17. #include <LibWeb/HTML/Origin.h>
  18. #include <LibWeb/HTML/Window.h>
  19. #include <LibWeb/WebIDL/DOMException.h>
  20. #include <LibWeb/WebIDL/ExceptionOr.h>
  21. #include <LibWeb/WebSockets/WebSocket.h>
  22. namespace Web::WebSockets {
  23. static RefPtr<WebSocketClientManager> s_websocket_client_manager;
  24. void WebSocketClientManager::initialize(RefPtr<WebSocketClientManager> websocket_client_manager)
  25. {
  26. s_websocket_client_manager = websocket_client_manager;
  27. }
  28. WebSocketClientManager& WebSocketClientManager::the()
  29. {
  30. if (!s_websocket_client_manager) [[unlikely]] {
  31. dbgln("Web::WebSockets::WebSocketClientManager was not initialized!");
  32. VERIFY_NOT_REACHED();
  33. }
  34. return *s_websocket_client_manager;
  35. }
  36. WebSocketClientSocket::WebSocketClientSocket() = default;
  37. WebSocketClientSocket::~WebSocketClientSocket() = default;
  38. WebSocketClientManager::WebSocketClientManager() = default;
  39. // https://websockets.spec.whatwg.org/#dom-websocket-websocket
  40. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebSocket>> WebSocket::construct_impl(JS::Realm& realm, DeprecatedString const& url, Optional<Variant<DeprecatedString, Vector<DeprecatedString>>> const& protocols)
  41. {
  42. auto& window = verify_cast<HTML::Window>(realm.global_object());
  43. AK::URL url_record(url);
  44. if (!url_record.is_valid())
  45. return WebIDL::SyntaxError::create(realm, "Invalid URL");
  46. if (!url_record.scheme().is_one_of("ws", "wss"))
  47. return WebIDL::SyntaxError::create(realm, "Invalid protocol");
  48. if (!url_record.fragment().is_empty())
  49. return WebIDL::SyntaxError::create(realm, "Presence of URL fragment is invalid");
  50. Vector<DeprecatedString> protocols_sequence;
  51. if (protocols.has_value()) {
  52. // 5. If `protocols` is a string, set `protocols` to a sequence consisting of just that string
  53. if (protocols.value().has<DeprecatedString>())
  54. protocols_sequence = { protocols.value().get<DeprecatedString>() };
  55. else
  56. protocols_sequence = protocols.value().get<Vector<DeprecatedString>>();
  57. // 6. If any of the values in `protocols` occur more than once or otherwise fail to match the requirements, throw SyntaxError
  58. auto sorted_protocols = protocols_sequence;
  59. quick_sort(sorted_protocols);
  60. for (size_t i = 0; i < sorted_protocols.size(); i++) {
  61. // https://datatracker.ietf.org/doc/html/rfc6455
  62. // The elements that comprise this value MUST be non-empty strings with characters in the range U+0021 to U+007E not including
  63. // separator characters as defined in [RFC2616] and MUST all be unique strings.
  64. auto protocol = sorted_protocols[i];
  65. if (i < sorted_protocols.size() - 1 && protocol == sorted_protocols[i + 1])
  66. return WebIDL::SyntaxError::create(realm, "Found a duplicate protocol name in the specified list");
  67. for (auto character : protocol) {
  68. if (character < '\x21' || character > '\x7E')
  69. return WebIDL::SyntaxError::create(realm, "Found invalid character in subprotocol name");
  70. }
  71. }
  72. }
  73. return MUST_OR_THROW_OOM(realm.heap().allocate<WebSocket>(realm, window, url_record, protocols_sequence));
  74. }
  75. WebSocket::WebSocket(HTML::Window& window, AK::URL& url, Vector<DeprecatedString> const& protocols)
  76. : EventTarget(window.realm())
  77. , m_window(window)
  78. {
  79. // FIXME: Integrate properly with FETCH as per https://fetch.spec.whatwg.org/#websocket-opening-handshake
  80. auto origin_string = m_window->associated_document().origin().serialize();
  81. m_websocket = WebSocketClientManager::the().connect(url, origin_string, protocols);
  82. m_websocket->on_open = [weak_this = make_weak_ptr<WebSocket>()] {
  83. if (!weak_this)
  84. return;
  85. auto& websocket = const_cast<WebSocket&>(*weak_this);
  86. websocket.on_open();
  87. };
  88. m_websocket->on_message = [weak_this = make_weak_ptr<WebSocket>()](auto message) {
  89. if (!weak_this)
  90. return;
  91. auto& websocket = const_cast<WebSocket&>(*weak_this);
  92. websocket.on_message(move(message.data), message.is_text);
  93. };
  94. m_websocket->on_close = [weak_this = make_weak_ptr<WebSocket>()](auto code, auto reason, bool was_clean) {
  95. if (!weak_this)
  96. return;
  97. auto& websocket = const_cast<WebSocket&>(*weak_this);
  98. websocket.on_close(code, reason, was_clean);
  99. };
  100. m_websocket->on_error = [weak_this = make_weak_ptr<WebSocket>()](auto) {
  101. if (!weak_this)
  102. return;
  103. auto& websocket = const_cast<WebSocket&>(*weak_this);
  104. websocket.on_error();
  105. };
  106. }
  107. WebSocket::~WebSocket() = default;
  108. JS::ThrowCompletionOr<void> WebSocket::initialize(JS::Realm& realm)
  109. {
  110. MUST_OR_THROW_OOM(Base::initialize(realm));
  111. set_prototype(&Bindings::ensure_web_prototype<Bindings::WebSocketPrototype>(realm, "WebSocket"));
  112. return {};
  113. }
  114. void WebSocket::visit_edges(Cell::Visitor& visitor)
  115. {
  116. Base::visit_edges(visitor);
  117. visitor.visit(m_window.ptr());
  118. }
  119. // https://websockets.spec.whatwg.org/#dom-websocket-readystate
  120. WebSocket::ReadyState WebSocket::ready_state() const
  121. {
  122. if (!m_websocket)
  123. return WebSocket::ReadyState::Closed;
  124. return const_cast<WebSocketClientSocket&>(*m_websocket).ready_state();
  125. }
  126. // https://websockets.spec.whatwg.org/#dom-websocket-extensions
  127. DeprecatedString WebSocket::extensions() const
  128. {
  129. if (!m_websocket)
  130. return DeprecatedString::empty();
  131. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  132. // FIXME: Change the extensions attribute's value to the extensions in use, if it is not the null value.
  133. return DeprecatedString::empty();
  134. }
  135. // https://websockets.spec.whatwg.org/#dom-websocket-protocol
  136. DeprecatedString WebSocket::protocol() const
  137. {
  138. if (!m_websocket)
  139. return DeprecatedString::empty();
  140. return m_websocket->subprotocol_in_use();
  141. }
  142. // https://websockets.spec.whatwg.org/#dom-websocket-close
  143. WebIDL::ExceptionOr<void> WebSocket::close(Optional<u16> code, Optional<DeprecatedString> reason)
  144. {
  145. // 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.
  146. if (code.has_value() && *code != 1000 && (*code < 3000 || *code > 4099))
  147. return WebIDL::InvalidAccessError::create(realm(), "The close error code is invalid");
  148. // 2. If reason is present, then run these substeps:
  149. if (reason.has_value()) {
  150. // 1. Let reasonBytes be the result of encoding reason.
  151. // 2. If reasonBytes is longer than 123 bytes, then throw a "SyntaxError" DOMException.
  152. if (reason->bytes().size() > 123)
  153. return WebIDL::SyntaxError::create(realm(), "The close reason is longer than 123 bytes");
  154. }
  155. // 3. Run the first matching steps from the following list:
  156. auto state = ready_state();
  157. // -> If this's ready state is CLOSING (2) or CLOSED (3)
  158. if (state == WebSocket::ReadyState::Closing || state == WebSocket::ReadyState::Closed)
  159. return {};
  160. // -> If the WebSocket connection is not yet established [WSP]
  161. // -> If the WebSocket closing handshake has not yet been started [WSP]
  162. // -> Otherwise
  163. // NOTE: All of these are handled by the WebSocket Protocol when calling close()
  164. // FIXME: LibProtocol does not yet support sending empty Close messages, so we use default values for now
  165. m_websocket->close(code.value_or(1000), reason.value_or(DeprecatedString::empty()));
  166. return {};
  167. }
  168. // https://websockets.spec.whatwg.org/#dom-websocket-send
  169. WebIDL::ExceptionOr<void> WebSocket::send(DeprecatedString const& data)
  170. {
  171. auto state = ready_state();
  172. if (state == WebSocket::ReadyState::Connecting)
  173. return WebIDL::InvalidStateError::create(realm(), "Websocket is still CONNECTING");
  174. if (state == WebSocket::ReadyState::Open) {
  175. m_websocket->send(data);
  176. // 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.
  177. // 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.
  178. }
  179. return {};
  180. }
  181. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  182. void WebSocket::on_open()
  183. {
  184. // 1. Change the readyState attribute's value to OPEN (1).
  185. // 2. Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]
  186. // 3. Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]
  187. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::open).release_value_but_fixme_should_propagate_errors());
  188. }
  189. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  190. void WebSocket::on_error()
  191. {
  192. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error).release_value_but_fixme_should_propagate_errors());
  193. }
  194. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  195. void WebSocket::on_close(u16 code, DeprecatedString reason, bool was_clean)
  196. {
  197. // 1. Change the readyState attribute's value to CLOSED. This is handled by the Protocol's WebSocket
  198. // 2. If [needed], fire an event named error at the WebSocket object. This is handled by the Protocol's WebSocket
  199. HTML::CloseEventInit event_init {};
  200. event_init.was_clean = was_clean;
  201. event_init.code = code;
  202. event_init.reason = move(reason);
  203. dispatch_event(*HTML::CloseEvent::create(realm(), HTML::EventNames::close, event_init));
  204. }
  205. // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  206. void WebSocket::on_message(ByteBuffer message, bool is_text)
  207. {
  208. if (m_websocket->ready_state() != WebSocket::ReadyState::Open)
  209. return;
  210. if (is_text) {
  211. auto text_message = DeprecatedString(ReadonlyBytes(message));
  212. HTML::MessageEventInit event_init;
  213. event_init.data = JS::PrimitiveString::create(vm(), text_message);
  214. event_init.origin = url();
  215. dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init).release_value_but_fixme_should_propagate_errors());
  216. return;
  217. }
  218. if (m_binary_type == "blob") {
  219. // type indicates that the data is Binary and binaryType is "blob"
  220. TODO();
  221. } else if (m_binary_type == "arraybuffer") {
  222. // type indicates that the data is Binary and binaryType is "arraybuffer"
  223. HTML::MessageEventInit event_init;
  224. event_init.data = JS::ArrayBuffer::create(realm(), message);
  225. event_init.origin = url();
  226. dispatch_event(HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init).release_value_but_fixme_should_propagate_errors());
  227. return;
  228. }
  229. dbgln("Unsupported WebSocket message type {}", m_binary_type);
  230. TODO();
  231. }
  232. #undef __ENUMERATE
  233. #define __ENUMERATE(attribute_name, event_name) \
  234. void WebSocket::set_##attribute_name(WebIDL::CallbackType* value) \
  235. { \
  236. set_event_handler_attribute(event_name, value); \
  237. } \
  238. WebIDL::CallbackType* WebSocket::attribute_name() \
  239. { \
  240. return event_handler_attribute(event_name); \
  241. }
  242. ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
  243. #undef __ENUMERATE
  244. }