wsl_peer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*************************************************************************/
  2. /* wsl_peer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifndef JAVASCRIPT_ENABLED
  31. #include "wsl_peer.h"
  32. #include "wsl_client.h"
  33. #include "wsl_server.h"
  34. #include "core/crypto/crypto_core.h"
  35. #include "core/math/random_number_generator.h"
  36. #include "core/os/os.h"
  37. String WSLPeer::generate_key() {
  38. // Random key
  39. RandomNumberGenerator rng;
  40. rng.set_seed(OS::get_singleton()->get_unix_time());
  41. PoolVector<uint8_t> bkey;
  42. int len = 16; // 16 bytes, as per RFC
  43. bkey.resize(len);
  44. PoolVector<uint8_t>::Write w = bkey.write();
  45. for (int i = 0; i < len; i++) {
  46. w[i] = (uint8_t)rng.randi_range(0, 255);
  47. }
  48. return CryptoCore::b64_encode_str(&w[0], len);
  49. }
  50. String WSLPeer::compute_key_response(String p_key) {
  51. String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC
  52. Vector<uint8_t> sha = key.sha1_buffer();
  53. return CryptoCore::b64_encode_str(sha.ptr(), sha.size());
  54. }
  55. void WSLPeer::_wsl_destroy(struct PeerData **p_data) {
  56. if (!p_data || !(*p_data))
  57. return;
  58. struct PeerData *data = *p_data;
  59. if (data->polling) {
  60. data->destroy = true;
  61. return;
  62. }
  63. wslay_event_context_free(data->ctx);
  64. memdelete(data);
  65. *p_data = NULL;
  66. }
  67. bool WSLPeer::_wsl_poll(struct PeerData *p_data) {
  68. p_data->polling = true;
  69. int err = 0;
  70. if ((err = wslay_event_recv(p_data->ctx)) != 0 || (err = wslay_event_send(p_data->ctx)) != 0) {
  71. print_verbose("Websocket (wslay) poll error: " + itos(err));
  72. p_data->destroy = true;
  73. }
  74. p_data->polling = false;
  75. if (p_data->destroy || (wslay_event_get_close_sent(p_data->ctx) && wslay_event_get_close_received(p_data->ctx))) {
  76. bool valid = p_data->valid;
  77. _wsl_destroy(&p_data);
  78. return valid;
  79. }
  80. return false;
  81. }
  82. ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) {
  83. struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
  84. if (!peer_data->valid) {
  85. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  86. return -1;
  87. }
  88. Ref<StreamPeer> conn = peer_data->conn;
  89. int read = 0;
  90. Error err = conn->get_partial_data(data, len, read);
  91. if (err != OK) {
  92. print_verbose("Websocket get data error: " + itos(err) + ", read (should be 0!): " + itos(read));
  93. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  94. return -1;
  95. }
  96. if (read == 0) {
  97. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  98. return -1;
  99. }
  100. return read;
  101. }
  102. ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) {
  103. struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
  104. if (!peer_data->valid) {
  105. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  106. return -1;
  107. }
  108. Ref<StreamPeer> conn = peer_data->conn;
  109. int sent = 0;
  110. Error err = conn->put_partial_data(data, len, sent);
  111. if (err != OK) {
  112. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  113. return -1;
  114. }
  115. if (sent == 0) {
  116. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  117. return -1;
  118. }
  119. return sent;
  120. }
  121. int wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) {
  122. RandomNumberGenerator rng;
  123. // TODO maybe use crypto in the future?
  124. rng.set_seed(OS::get_singleton()->get_unix_time());
  125. for (unsigned int i = 0; i < len; i++) {
  126. buf[i] = (uint8_t)rng.randi_range(0, 255);
  127. }
  128. return 0;
  129. }
  130. void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
  131. struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
  132. if (!peer_data->valid || peer_data->closing) {
  133. return;
  134. }
  135. WSLPeer *peer = (WSLPeer *)peer_data->peer;
  136. if (peer->parse_message(arg) != OK)
  137. return;
  138. if (peer_data->is_server) {
  139. WSLServer *helper = (WSLServer *)peer_data->obj;
  140. helper->_on_peer_packet(peer_data->id);
  141. } else {
  142. WSLClient *helper = (WSLClient *)peer_data->obj;
  143. helper->_on_peer_packet();
  144. }
  145. }
  146. wslay_event_callbacks wsl_callbacks = {
  147. wsl_recv_callback,
  148. wsl_send_callback,
  149. wsl_genmask_callback,
  150. NULL, /* on_frame_recv_start_callback */
  151. NULL, /* on_frame_recv_callback */
  152. NULL, /* on_frame_recv_end_callback */
  153. wsl_msg_recv_callback
  154. };
  155. Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) {
  156. uint8_t is_string = 0;
  157. if (arg->opcode == WSLAY_TEXT_FRAME) {
  158. is_string = 1;
  159. } else if (arg->opcode == WSLAY_CONNECTION_CLOSE) {
  160. close_code = arg->status_code;
  161. size_t len = arg->msg_length;
  162. close_reason = "";
  163. if (len > 2 /* first 2 bytes = close code */) {
  164. close_reason.parse_utf8((char *)arg->msg + 2, len - 2);
  165. }
  166. if (!wslay_event_get_close_sent(_data->ctx)) {
  167. if (_data->is_server) {
  168. WSLServer *helper = (WSLServer *)_data->obj;
  169. helper->_on_close_request(_data->id, close_code, close_reason);
  170. } else {
  171. WSLClient *helper = (WSLClient *)_data->obj;
  172. helper->_on_close_request(close_code, close_reason);
  173. }
  174. }
  175. return ERR_FILE_EOF;
  176. } else if (arg->opcode != WSLAY_BINARY_FRAME) {
  177. // Ping or pong
  178. return ERR_SKIP;
  179. }
  180. _in_buffer.write_packet(arg->msg, arg->msg_length, &is_string);
  181. return OK;
  182. }
  183. void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) {
  184. ERR_FAIL_COND(_data != NULL);
  185. ERR_FAIL_COND(p_data == NULL);
  186. _in_buffer.resize(p_in_pkt_size, p_in_buf_size);
  187. _packet_buffer.resize(1 << p_in_buf_size);
  188. _out_buf_size = p_out_buf_size;
  189. _out_pkt_size = p_out_pkt_size;
  190. _data = p_data;
  191. _data->peer = this;
  192. _data->valid = true;
  193. if (_data->is_server)
  194. wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data);
  195. else
  196. wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data);
  197. wslay_event_config_set_max_recv_msg_length(_data->ctx, (1ULL << p_in_buf_size));
  198. }
  199. void WSLPeer::set_write_mode(WriteMode p_mode) {
  200. write_mode = p_mode;
  201. }
  202. WSLPeer::WriteMode WSLPeer::get_write_mode() const {
  203. return write_mode;
  204. }
  205. void WSLPeer::poll() {
  206. if (!_data)
  207. return;
  208. if (_wsl_poll(_data)) {
  209. _data = NULL;
  210. }
  211. }
  212. Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  213. ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
  214. ERR_FAIL_COND_V(_out_pkt_size && (wslay_event_get_queued_msg_count(_data->ctx) >= (1ULL << _out_pkt_size)), ERR_OUT_OF_MEMORY);
  215. ERR_FAIL_COND_V(_out_buf_size && (wslay_event_get_queued_msg_length(_data->ctx) >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY);
  216. struct wslay_event_msg msg; // Should I use fragmented?
  217. msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME;
  218. msg.msg = p_buffer;
  219. msg.msg_length = p_buffer_size;
  220. wslay_event_queue_msg(_data->ctx, &msg);
  221. if (wslay_event_send(_data->ctx) < 0) {
  222. close_now();
  223. return FAILED;
  224. }
  225. return OK;
  226. }
  227. Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  228. r_buffer_size = 0;
  229. ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
  230. if (_in_buffer.packets_left() == 0)
  231. return ERR_UNAVAILABLE;
  232. int read = 0;
  233. PoolVector<uint8_t>::Write rw = _packet_buffer.write();
  234. _in_buffer.read_packet(rw.ptr(), _packet_buffer.size(), &_is_string, read);
  235. *r_buffer = rw.ptr();
  236. r_buffer_size = read;
  237. return OK;
  238. }
  239. int WSLPeer::get_available_packet_count() const {
  240. if (!is_connected_to_host())
  241. return 0;
  242. return _in_buffer.packets_left();
  243. }
  244. int WSLPeer::get_current_outbound_buffered_amount() const {
  245. ERR_FAIL_COND_V(!_data, 0);
  246. return wslay_event_get_queued_msg_length(_data->ctx);
  247. }
  248. bool WSLPeer::was_string_packet() const {
  249. return _is_string;
  250. }
  251. bool WSLPeer::is_connected_to_host() const {
  252. return _data != NULL;
  253. }
  254. void WSLPeer::close_now() {
  255. close(1000, "");
  256. _wsl_destroy(&_data);
  257. }
  258. void WSLPeer::close(int p_code, String p_reason) {
  259. if (_data && !wslay_event_get_close_sent(_data->ctx)) {
  260. CharString cs = p_reason.utf8();
  261. wslay_event_queue_close(_data->ctx, p_code, (uint8_t *)cs.ptr(), cs.size());
  262. wslay_event_send(_data->ctx);
  263. _data->closing = true;
  264. }
  265. _in_buffer.clear();
  266. _packet_buffer.resize(0);
  267. }
  268. IP_Address WSLPeer::get_connected_host() const {
  269. ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IP_Address());
  270. return _data->tcp->get_connected_host();
  271. }
  272. uint16_t WSLPeer::get_connected_port() const {
  273. ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), 0);
  274. return _data->tcp->get_connected_port();
  275. }
  276. void WSLPeer::set_no_delay(bool p_enabled) {
  277. ERR_FAIL_COND(!is_connected_to_host() || _data->tcp.is_null());
  278. _data->tcp->set_no_delay(p_enabled);
  279. }
  280. void WSLPeer::invalidate() {
  281. if (_data)
  282. _data->valid = false;
  283. }
  284. WSLPeer::WSLPeer() {
  285. _data = NULL;
  286. _is_string = 0;
  287. close_code = -1;
  288. write_mode = WRITE_MODE_BINARY;
  289. _out_buf_size = 0;
  290. _out_pkt_size = 0;
  291. }
  292. WSLPeer::~WSLPeer() {
  293. close();
  294. invalidate();
  295. _wsl_destroy(&_data);
  296. _data = NULL;
  297. }
  298. #endif // JAVASCRIPT_ENABLED