wsl_peer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**************************************************************************/
  2. /* wsl_peer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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. }
  59. struct PeerData *data = *p_data;
  60. if (data->polling) {
  61. data->destroy = true;
  62. return;
  63. }
  64. wslay_event_context_free(data->ctx);
  65. memdelete(data);
  66. *p_data = nullptr;
  67. }
  68. bool WSLPeer::_wsl_poll(struct PeerData *p_data) {
  69. p_data->polling = true;
  70. int err = 0;
  71. if ((err = wslay_event_recv(p_data->ctx)) != 0 || (err = wslay_event_send(p_data->ctx)) != 0) {
  72. print_verbose("Websocket (wslay) poll error: " + itos(err));
  73. p_data->destroy = true;
  74. }
  75. p_data->polling = false;
  76. if (p_data->destroy || (wslay_event_get_close_sent(p_data->ctx) && wslay_event_get_close_received(p_data->ctx))) {
  77. bool valid = p_data->valid;
  78. _wsl_destroy(&p_data);
  79. return valid;
  80. }
  81. return false;
  82. }
  83. ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) {
  84. struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
  85. if (!peer_data->valid) {
  86. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  87. return -1;
  88. }
  89. Ref<StreamPeer> conn = peer_data->conn;
  90. int read = 0;
  91. Error err = conn->get_partial_data(data, len, read);
  92. if (err != OK) {
  93. print_verbose("Websocket get data error: " + itos(err) + ", read (should be 0!): " + itos(read));
  94. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  95. return -1;
  96. }
  97. if (read == 0) {
  98. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  99. return -1;
  100. }
  101. return read;
  102. }
  103. ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) {
  104. struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
  105. if (!peer_data->valid) {
  106. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  107. return -1;
  108. }
  109. Ref<StreamPeer> conn = peer_data->conn;
  110. int sent = 0;
  111. Error err = conn->put_partial_data(data, len, sent);
  112. if (err != OK) {
  113. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  114. return -1;
  115. }
  116. if (sent == 0) {
  117. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  118. return -1;
  119. }
  120. return sent;
  121. }
  122. int wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) {
  123. RandomNumberGenerator rng;
  124. // TODO maybe use crypto in the future?
  125. rng.set_seed(OS::get_singleton()->get_unix_time());
  126. for (unsigned int i = 0; i < len; i++) {
  127. buf[i] = (uint8_t)rng.randi_range(0, 255);
  128. }
  129. return 0;
  130. }
  131. void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
  132. struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
  133. if (!peer_data->valid || peer_data->closing) {
  134. return;
  135. }
  136. WSLPeer *peer = (WSLPeer *)peer_data->peer;
  137. if (peer->parse_message(arg) != OK) {
  138. return;
  139. }
  140. if (peer_data->is_server) {
  141. WSLServer *helper = (WSLServer *)peer_data->obj;
  142. helper->_on_peer_packet(peer_data->id);
  143. } else {
  144. WSLClient *helper = (WSLClient *)peer_data->obj;
  145. helper->_on_peer_packet();
  146. }
  147. }
  148. wslay_event_callbacks wsl_callbacks = {
  149. wsl_recv_callback,
  150. wsl_send_callback,
  151. wsl_genmask_callback,
  152. nullptr, /* on_frame_recv_start_callback */
  153. nullptr, /* on_frame_recv_callback */
  154. nullptr, /* on_frame_recv_end_callback */
  155. wsl_msg_recv_callback
  156. };
  157. Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) {
  158. uint8_t is_string = 0;
  159. if (arg->opcode == WSLAY_TEXT_FRAME) {
  160. is_string = 1;
  161. } else if (arg->opcode == WSLAY_CONNECTION_CLOSE) {
  162. close_code = arg->status_code;
  163. size_t len = arg->msg_length;
  164. close_reason = "";
  165. if (len > 2 /* first 2 bytes = close code */) {
  166. close_reason.parse_utf8((char *)arg->msg + 2, len - 2);
  167. }
  168. if (!wslay_event_get_close_sent(_data->ctx)) {
  169. if (_data->is_server) {
  170. WSLServer *helper = (WSLServer *)_data->obj;
  171. helper->_on_close_request(_data->id, close_code, close_reason);
  172. } else {
  173. WSLClient *helper = (WSLClient *)_data->obj;
  174. helper->_on_close_request(close_code, close_reason);
  175. }
  176. }
  177. return ERR_FILE_EOF;
  178. } else if (arg->opcode != WSLAY_BINARY_FRAME) {
  179. // Ping or pong
  180. return ERR_SKIP;
  181. }
  182. _in_buffer.write_packet(arg->msg, arg->msg_length, &is_string);
  183. return OK;
  184. }
  185. 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) {
  186. ERR_FAIL_COND(_data != nullptr);
  187. ERR_FAIL_COND(p_data == nullptr);
  188. _in_buffer.resize(p_in_pkt_size, p_in_buf_size);
  189. _packet_buffer.resize(1 << p_in_buf_size);
  190. _out_buf_size = p_out_buf_size;
  191. _out_pkt_size = p_out_pkt_size;
  192. _data = p_data;
  193. _data->peer = this;
  194. _data->valid = true;
  195. if (_data->is_server) {
  196. wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data);
  197. } else {
  198. wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data);
  199. }
  200. wslay_event_config_set_max_recv_msg_length(_data->ctx, (1ULL << p_in_buf_size));
  201. }
  202. void WSLPeer::set_write_mode(WriteMode p_mode) {
  203. write_mode = p_mode;
  204. }
  205. WSLPeer::WriteMode WSLPeer::get_write_mode() const {
  206. return write_mode;
  207. }
  208. void WSLPeer::poll() {
  209. if (!_data) {
  210. return;
  211. }
  212. if (_wsl_poll(_data)) {
  213. _data = nullptr;
  214. }
  215. }
  216. Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  217. ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
  218. ERR_FAIL_COND_V(_out_pkt_size && (wslay_event_get_queued_msg_count(_data->ctx) >= (1ULL << _out_pkt_size)), ERR_OUT_OF_MEMORY);
  219. ERR_FAIL_COND_V(_out_buf_size && (wslay_event_get_queued_msg_length(_data->ctx) + p_buffer_size >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY);
  220. struct wslay_event_msg msg;
  221. msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME;
  222. msg.msg = p_buffer;
  223. msg.msg_length = p_buffer_size;
  224. if (wslay_event_queue_msg(_data->ctx, &msg) != 0 || wslay_event_send(_data->ctx) != 0) {
  225. close_now();
  226. return FAILED;
  227. }
  228. return OK;
  229. }
  230. Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  231. r_buffer_size = 0;
  232. ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
  233. if (_in_buffer.packets_left() == 0) {
  234. return ERR_UNAVAILABLE;
  235. }
  236. int read = 0;
  237. PoolVector<uint8_t>::Write rw = _packet_buffer.write();
  238. _in_buffer.read_packet(rw.ptr(), _packet_buffer.size(), &_is_string, read);
  239. *r_buffer = rw.ptr();
  240. r_buffer_size = read;
  241. return OK;
  242. }
  243. int WSLPeer::get_available_packet_count() const {
  244. if (!is_connected_to_host()) {
  245. return 0;
  246. }
  247. return _in_buffer.packets_left();
  248. }
  249. int WSLPeer::get_current_outbound_buffered_amount() const {
  250. ERR_FAIL_COND_V(!_data, 0);
  251. return wslay_event_get_queued_msg_length(_data->ctx);
  252. }
  253. bool WSLPeer::was_string_packet() const {
  254. return _is_string;
  255. }
  256. bool WSLPeer::is_connected_to_host() const {
  257. return _data != nullptr;
  258. }
  259. void WSLPeer::close_now() {
  260. close(1000, "");
  261. _wsl_destroy(&_data);
  262. }
  263. void WSLPeer::close(int p_code, String p_reason) {
  264. if (_data && !wslay_event_get_close_sent(_data->ctx)) {
  265. CharString cs = p_reason.utf8();
  266. wslay_event_queue_close(_data->ctx, p_code, (uint8_t *)cs.ptr(), cs.size());
  267. wslay_event_send(_data->ctx);
  268. _data->closing = true;
  269. }
  270. _in_buffer.clear();
  271. _packet_buffer.resize(0);
  272. }
  273. IP_Address WSLPeer::get_connected_host() const {
  274. ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IP_Address());
  275. return _data->tcp->get_connected_host();
  276. }
  277. uint16_t WSLPeer::get_connected_port() const {
  278. ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), 0);
  279. return _data->tcp->get_connected_port();
  280. }
  281. void WSLPeer::set_no_delay(bool p_enabled) {
  282. ERR_FAIL_COND(!is_connected_to_host() || _data->tcp.is_null());
  283. _data->tcp->set_no_delay(p_enabled);
  284. }
  285. void WSLPeer::invalidate() {
  286. if (_data) {
  287. _data->valid = false;
  288. }
  289. }
  290. WSLPeer::WSLPeer() {
  291. _data = nullptr;
  292. _is_string = 0;
  293. close_code = -1;
  294. write_mode = WRITE_MODE_BINARY;
  295. _out_buf_size = 0;
  296. _out_pkt_size = 0;
  297. }
  298. WSLPeer::~WSLPeer() {
  299. close();
  300. invalidate();
  301. _wsl_destroy(&_data);
  302. _data = nullptr;
  303. }
  304. #endif // JAVASCRIPT_ENABLED