WebSocket.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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/FunctionObject.h>
  9. #include <LibProtocol/WebSocket.h>
  10. #include <LibProtocol/WebSocketClient.h>
  11. #include <LibWeb/Bindings/EventWrapper.h>
  12. #include <LibWeb/Bindings/WebSocketWrapper.h>
  13. #include <LibWeb/DOM/DOMException.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/Event.h>
  16. #include <LibWeb/DOM/EventDispatcher.h>
  17. #include <LibWeb/DOM/EventListener.h>
  18. #include <LibWeb/DOM/ExceptionOr.h>
  19. #include <LibWeb/DOM/Window.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/WebSocket.h>
  25. #include <LibWeb/Origin.h>
  26. namespace Web::HTML {
  27. WebSocketClientManager& WebSocketClientManager::the()
  28. {
  29. static WebSocketClientManager* s_the;
  30. if (!s_the)
  31. s_the = &WebSocketClientManager::construct().leak_ref();
  32. return *s_the;
  33. }
  34. WebSocketClientManager::WebSocketClientManager()
  35. : m_websocket_client(Protocol::WebSocketClient::construct())
  36. {
  37. }
  38. RefPtr<Protocol::WebSocket> WebSocketClientManager::connect(const AK::URL& url)
  39. {
  40. return m_websocket_client->connect(url);
  41. }
  42. // https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
  43. DOM::ExceptionOr<NonnullRefPtr<WebSocket>> WebSocket::create_with_global_object(Bindings::WindowObject& window, const String& 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(DOM::Window& window, AK::URL& url)
  57. : EventTarget(static_cast<Bindings::ScriptExecutionContext&>(window.associated_document()))
  58. , m_window(window)
  59. {
  60. // FIXME: Integrate properly with FETCH as per https://fetch.spec.whatwg.org/#websocket-opening-handshake
  61. m_websocket = WebSocketClientManager::the().connect(url);
  62. m_websocket->on_open = [weak_this = make_weak_ptr()] {
  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()](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()](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()](auto) {
  81. if (!weak_this)
  82. return;
  83. auto& websocket = const_cast<WebSocket&>(*weak_this);
  84. websocket.on_error();
  85. };
  86. }
  87. WebSocket::~WebSocket()
  88. {
  89. }
  90. // https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
  91. WebSocket::ReadyState WebSocket::ready_state() const
  92. {
  93. if (!m_websocket)
  94. return WebSocket::ReadyState::Closed;
  95. auto ready_state = const_cast<Protocol::WebSocket&>(*m_websocket).ready_state();
  96. switch (ready_state) {
  97. case Protocol::WebSocket::ReadyState::Connecting:
  98. return WebSocket::ReadyState::Connecting;
  99. case Protocol::WebSocket::ReadyState::Open:
  100. return WebSocket::ReadyState::Open;
  101. case Protocol::WebSocket::ReadyState::Closing:
  102. return WebSocket::ReadyState::Closing;
  103. case Protocol::WebSocket::ReadyState::Closed:
  104. return WebSocket::ReadyState::Closed;
  105. }
  106. return WebSocket::ReadyState::Closed;
  107. }
  108. // https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
  109. String WebSocket::extensions() const
  110. {
  111. if (!m_websocket)
  112. return String::empty();
  113. // https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
  114. // FIXME: Change the extensions attribute's value to the extensions in use, if it is not the null value.
  115. return String::empty();
  116. }
  117. // https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
  118. String WebSocket::protocol() const
  119. {
  120. if (!m_websocket)
  121. return String::empty();
  122. // https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
  123. // FIXME: Change the protocol attribute's value to the subprotocol in use, if it is not the null value.
  124. return String::empty();
  125. }
  126. // https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
  127. DOM::ExceptionOr<void> WebSocket::close(u16 code, const String& reason)
  128. {
  129. // HACK : we should have an Optional<u16>
  130. if (code == 0)
  131. code = 1000;
  132. if (code != 1000 && (code < 3000 || code > 4099))
  133. return DOM::InvalidAccessError::create("The close error code is invalid");
  134. if (!reason.is_empty() && reason.bytes().size() > 123)
  135. return DOM::SyntaxError::create("The close reason is longer than 123 bytes");
  136. auto state = ready_state();
  137. if (state == WebSocket::ReadyState::Closing || state == WebSocket::ReadyState::Closed)
  138. return {};
  139. // Note : Both of these are handled by the WebSocket Protocol when calling close()
  140. // 3b. If the WebSocket connection is not yet established [WSP]
  141. // 3c. If the WebSocket closing handshake has not yet been started [WSP]
  142. m_websocket->close(code, reason);
  143. return {};
  144. }
  145. // https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
  146. DOM::ExceptionOr<void> WebSocket::send(const String& data)
  147. {
  148. auto state = ready_state();
  149. if (state == WebSocket::ReadyState::Connecting)
  150. return DOM::InvalidStateError::create("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://html.spec.whatwg.org/multipage/web-sockets.html#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(EventNames::open));
  165. }
  166. // https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
  167. void WebSocket::on_error()
  168. {
  169. dispatch_event(DOM::Event::create(EventNames::error));
  170. }
  171. // https://html.spec.whatwg.org/multipage/web-sockets.html#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. dispatch_event(CloseEvent::create(EventNames::close, was_clean, code, reason));
  177. }
  178. // https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
  179. void WebSocket::on_message(ByteBuffer message, bool is_text)
  180. {
  181. if (m_websocket->ready_state() != Protocol::WebSocket::ReadyState::Open)
  182. return;
  183. if (is_text) {
  184. auto text_message = String(ReadonlyBytes(message));
  185. dispatch_event(MessageEvent::create(EventNames::message, text_message, url()));
  186. return;
  187. }
  188. // type indicates that the data is Binary and binaryType is "blob"
  189. // type indicates that the data is Binary and binaryType is "arraybuffer"
  190. TODO();
  191. }
  192. bool WebSocket::dispatch_event(NonnullRefPtr<DOM::Event> event)
  193. {
  194. return DOM::EventDispatcher::dispatch(*this, move(event));
  195. }
  196. JS::Object* WebSocket::create_wrapper(JS::GlobalObject& global_object)
  197. {
  198. return wrap(global_object, *this);
  199. }
  200. #undef __ENUMERATE
  201. #define __ENUMERATE(attribute_name, event_name) \
  202. void WebSocket::set_##attribute_name(HTML::EventHandler value) \
  203. { \
  204. set_event_handler_attribute(event_name, move(value)); \
  205. } \
  206. HTML::EventHandler WebSocket::attribute_name() \
  207. { \
  208. return event_handler_attribute(event_name); \
  209. }
  210. ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
  211. #undef __ENUMERATE
  212. }