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