WebSocket.cpp 10 KB

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