WebSocket.cpp 10 KB

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