websocket_multiplayer_peer.cpp 11 KB

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