WebSocket.cpp 10 KB

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