WebSocket.cpp 13 KB

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