websocket_multiplayer_peer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*************************************************************************/
  2. /* websocket_multiplayer_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. #include "websocket_multiplayer_peer.h"
  31. #include "core/os/os.h"
  32. WebSocketMultiplayerPeer::WebSocketMultiplayerPeer() {
  33. }
  34. WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() {
  35. _clear();
  36. }
  37. void WebSocketMultiplayerPeer::_clear() {
  38. _peer_map.clear();
  39. if (_current_packet.data != nullptr) {
  40. memfree(_current_packet.data);
  41. }
  42. for (Packet &E : _incoming_packets) {
  43. memfree(E.data);
  44. E.data = nullptr;
  45. }
  46. _incoming_packets.clear();
  47. }
  48. void WebSocketMultiplayerPeer::_bind_methods() {
  49. ClassDB::bind_method(D_METHOD("set_buffers", "input_buffer_size_kb", "input_max_packets", "output_buffer_size_kb", "output_max_packets"), &WebSocketMultiplayerPeer::set_buffers);
  50. ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebSocketMultiplayerPeer::get_peer);
  51. ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "peer_source")));
  52. }
  53. //
  54. // PacketPeer
  55. //
  56. int WebSocketMultiplayerPeer::get_available_packet_count() const {
  57. ERR_FAIL_COND_V_MSG(!_is_multiplayer, 0, "Please use get_peer(ID).get_available_packet_count to get available packet count from peers when not using the MultiplayerAPI.");
  58. return _incoming_packets.size();
  59. }
  60. Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  61. ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).get_packet/var to communicate with peers when not using the MultiplayerAPI.");
  62. r_buffer_size = 0;
  63. if (_current_packet.data != nullptr) {
  64. memfree(_current_packet.data);
  65. _current_packet.data = nullptr;
  66. }
  67. ERR_FAIL_COND_V(_incoming_packets.size() == 0, ERR_UNAVAILABLE);
  68. _current_packet = _incoming_packets.front()->get();
  69. _incoming_packets.pop_front();
  70. *r_buffer = _current_packet.data;
  71. r_buffer_size = _current_packet.size;
  72. return OK;
  73. }
  74. Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  75. ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).put_packet/var to communicate with peers when not using the MultiplayerAPI.");
  76. Vector<uint8_t> buffer = _make_pkt(SYS_NONE, get_unique_id(), _target_peer, p_buffer, p_buffer_size);
  77. if (is_server()) {
  78. return _server_relay(1, _target_peer, &(buffer.ptr()[0]), buffer.size());
  79. } else {
  80. return get_peer(1)->put_packet(&(buffer.ptr()[0]), buffer.size());
  81. }
  82. }
  83. //
  84. // MultiplayerPeer
  85. //
  86. void WebSocketMultiplayerPeer::set_transfer_channel(int p_channel) {
  87. // Websocket does not have channels.
  88. }
  89. int WebSocketMultiplayerPeer::get_transfer_channel() const {
  90. return 0;
  91. }
  92. void WebSocketMultiplayerPeer::set_transfer_mode(Multiplayer::TransferMode p_mode) {
  93. // Websocket uses TCP, reliable
  94. }
  95. Multiplayer::TransferMode WebSocketMultiplayerPeer::get_transfer_mode() const {
  96. // Websocket uses TCP, reliable
  97. return Multiplayer::TRANSFER_MODE_RELIABLE;
  98. }
  99. void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) {
  100. _target_peer = p_target_peer;
  101. }
  102. int WebSocketMultiplayerPeer::get_packet_peer() const {
  103. ERR_FAIL_COND_V_MSG(!_is_multiplayer, 1, "This function is not available when not using the MultiplayerAPI.");
  104. ERR_FAIL_COND_V(_incoming_packets.size() == 0, 1);
  105. return _incoming_packets.front()->get().source;
  106. }
  107. int WebSocketMultiplayerPeer::get_unique_id() const {
  108. return _peer_id;
  109. }
  110. void WebSocketMultiplayerPeer::set_refuse_new_connections(bool p_enable) {
  111. _refusing = p_enable;
  112. }
  113. bool WebSocketMultiplayerPeer::is_refusing_new_connections() const {
  114. return _refusing;
  115. }
  116. void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id) {
  117. ERR_FAIL_COND(!p_peer.is_valid());
  118. ERR_FAIL_COND(!p_peer->is_connected_to_host());
  119. Vector<uint8_t> message = _make_pkt(p_type, 1, 0, (uint8_t *)&p_peer_id, 4);
  120. p_peer->put_packet(&(message.ptr()[0]), message.size());
  121. }
  122. Vector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) {
  123. Vector<uint8_t> out;
  124. out.resize(PROTO_SIZE + p_data_size);
  125. uint8_t *w = out.ptrw();
  126. memcpy(&w[0], &p_type, 1);
  127. memcpy(&w[1], &p_from, 4);
  128. memcpy(&w[5], &p_to, 4);
  129. memcpy(&w[PROTO_SIZE], p_data, p_data_size);
  130. return out;
  131. }
  132. void WebSocketMultiplayerPeer::_send_add(int32_t p_peer_id) {
  133. // First of all, confirm the ID!
  134. _send_sys(get_peer(p_peer_id), SYS_ID, p_peer_id);
  135. // Then send the server peer (which will trigger connection_succeded in client)
  136. _send_sys(get_peer(p_peer_id), SYS_ADD, 1);
  137. for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
  138. int32_t id = E->key();
  139. if (p_peer_id == id) {
  140. continue; // Skip the newly added peer (already confirmed)
  141. }
  142. // Send new peer to others
  143. _send_sys(get_peer(id), SYS_ADD, p_peer_id);
  144. // Send others to new peer
  145. _send_sys(get_peer(p_peer_id), SYS_ADD, id);
  146. }
  147. }
  148. void WebSocketMultiplayerPeer::_send_del(int32_t p_peer_id) {
  149. for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
  150. int32_t id = E->key();
  151. if (p_peer_id != id) {
  152. _send_sys(get_peer(id), SYS_DEL, p_peer_id);
  153. }
  154. }
  155. }
  156. void WebSocketMultiplayerPeer::_store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size) {
  157. Packet packet;
  158. packet.data = (uint8_t *)memalloc(p_data_size);
  159. packet.size = p_data_size;
  160. packet.source = p_source;
  161. packet.destination = p_dest;
  162. memcpy(packet.data, &p_data[PROTO_SIZE], p_data_size);
  163. _incoming_packets.push_back(packet);
  164. emit_signal(SNAME("peer_packet"), p_source);
  165. }
  166. Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size) {
  167. if (p_to == 1) {
  168. return OK; // Will not send to self
  169. } else if (p_to == 0) {
  170. for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
  171. if (E->key() != p_from) {
  172. E->get()->put_packet(p_buffer, p_buffer_size);
  173. }
  174. }
  175. return OK; // Sent to all but sender
  176. } else if (p_to < 0) {
  177. for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
  178. if (E->key() != p_from && E->key() != -p_to) {
  179. E->get()->put_packet(p_buffer, p_buffer_size);
  180. }
  181. }
  182. return OK; // Sent to all but sender and excluded
  183. } else {
  184. ERR_FAIL_COND_V(p_to == p_from, FAILED);
  185. Ref<WebSocketPeer> peer_to = get_peer(p_to);
  186. ERR_FAIL_COND_V(peer_to.is_null(), FAILED);
  187. return peer_to->put_packet(p_buffer, p_buffer_size); // Sending to specific peer
  188. }
  189. }
  190. void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id) {
  191. ERR_FAIL_COND(!p_peer.is_valid());
  192. const uint8_t *in_buffer;
  193. int size = 0;
  194. int data_size = 0;
  195. Error err = p_peer->get_packet(&in_buffer, size);
  196. ERR_FAIL_COND(err != OK);
  197. ERR_FAIL_COND(size < PROTO_SIZE);
  198. data_size = size - PROTO_SIZE;
  199. uint8_t type = 0;
  200. uint32_t from = 0;
  201. int32_t to = 0;
  202. memcpy(&type, in_buffer, 1);
  203. memcpy(&from, &in_buffer[1], 4);
  204. memcpy(&to, &in_buffer[5], 4);
  205. if (is_server()) { // Server can resend
  206. ERR_FAIL_COND(type != SYS_NONE); // Only server sends sys messages
  207. ERR_FAIL_COND(from != p_peer_id); // Someone is cheating
  208. if (to == 1) { // This is for the server
  209. _store_pkt(from, to, in_buffer, data_size);
  210. } else if (to == 0) {
  211. // Broadcast, for us too
  212. _store_pkt(from, to, in_buffer, data_size);
  213. } else if (to < 0) {
  214. // All but one, for us if not excluded
  215. if (_peer_id != -(int32_t)p_peer_id) {
  216. _store_pkt(from, to, in_buffer, data_size);
  217. }
  218. }
  219. // Relay if needed (i.e. "to" includes a peer that is not the server)
  220. _server_relay(from, to, in_buffer, size);
  221. } else {
  222. if (type == SYS_NONE) { // Payload message
  223. _store_pkt(from, to, in_buffer, data_size);
  224. return;
  225. }
  226. // System message
  227. ERR_FAIL_COND(data_size < 4);
  228. int id = 0;
  229. memcpy(&id, &in_buffer[PROTO_SIZE], 4);
  230. switch (type) {
  231. case SYS_ADD: // Add peer
  232. _peer_map[id] = Ref<WebSocketPeer>();
  233. emit_signal(SNAME("peer_connected"), id);
  234. if (id == 1) { // We just connected to the server
  235. emit_signal(SNAME("connection_succeeded"));
  236. }
  237. break;
  238. case SYS_DEL: // Remove peer
  239. _peer_map.erase(id);
  240. emit_signal(SNAME("peer_disconnected"), id);
  241. break;
  242. case SYS_ID: // Hello, server assigned ID
  243. _peer_id = id;
  244. break;
  245. default:
  246. ERR_FAIL_MSG("Invalid multiplayer message.");
  247. break;
  248. }
  249. }
  250. }