websocket_multiplayer_peer.cpp 11 KB

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