2
0

networked_multiplayer_enet.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*************************************************************************/
  2. /* networked_multiplayer_enet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "networked_multiplayer_enet.h"
  31. #include "core/io/ip.h"
  32. #include "core/io/marshalls.h"
  33. #include "core/os/os.h"
  34. void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {
  35. transfer_mode = p_mode;
  36. }
  37. NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const {
  38. return transfer_mode;
  39. }
  40. void NetworkedMultiplayerENet::set_target_peer(int p_peer) {
  41. target_peer = p_peer;
  42. }
  43. int NetworkedMultiplayerENet::get_packet_peer() const {
  44. ERR_FAIL_COND_V(!active, 1);
  45. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  46. return incoming_packets.front()->get().from;
  47. }
  48. int NetworkedMultiplayerENet::get_packet_channel() const {
  49. ERR_FAIL_COND_V(!active, -1);
  50. ERR_FAIL_COND_V(incoming_packets.size() == 0, -1);
  51. return incoming_packets.front()->get().channel;
  52. }
  53. int NetworkedMultiplayerENet::get_last_packet_channel() const {
  54. ERR_FAIL_COND_V(!active, -1);
  55. ERR_FAIL_COND_V(!current_packet.packet, -1);
  56. return current_packet.channel;
  57. }
  58. Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) {
  59. ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
  60. ERR_FAIL_COND_V(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER);
  61. ERR_FAIL_COND_V(p_max_clients < 0, ERR_INVALID_PARAMETER);
  62. ERR_FAIL_COND_V(p_in_bandwidth < 0, ERR_INVALID_PARAMETER);
  63. ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);
  64. ENetAddress address;
  65. #ifdef GODOT_ENET
  66. if (bind_ip.is_wildcard()) {
  67. address.wildcard = 1;
  68. } else {
  69. enet_address_set_ip(&address, bind_ip.get_ipv6(), 16);
  70. }
  71. #else
  72. if (bind_ip.is_wildcard()) {
  73. address.host = 0;
  74. } else {
  75. ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
  76. address.host = *(uint32_t *)bind_ip.get_ipv4();
  77. }
  78. #endif
  79. address.port = p_port;
  80. host = enet_host_create(&address /* the address to bind the server host to */,
  81. p_max_clients /* allow up to 32 clients and/or outgoing connections */,
  82. channel_count /* allow up to channel_count to be used */,
  83. p_in_bandwidth /* limit incoming bandwidth if > 0 */,
  84. p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
  85. ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
  86. _setup_compressor();
  87. active = true;
  88. server = true;
  89. refuse_connections = false;
  90. unique_id = 1;
  91. connection_status = CONNECTION_CONNECTED;
  92. return OK;
  93. }
  94. Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_client_port) {
  95. ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
  96. ERR_FAIL_COND_V(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER);
  97. ERR_FAIL_COND_V(p_client_port < 0 || p_client_port > 65535, ERR_INVALID_PARAMETER);
  98. ERR_FAIL_COND_V(p_in_bandwidth < 0, ERR_INVALID_PARAMETER);
  99. ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);
  100. if (p_client_port != 0) {
  101. ENetAddress c_client;
  102. #ifdef GODOT_ENET
  103. if (bind_ip.is_wildcard()) {
  104. c_client.wildcard = 1;
  105. } else {
  106. enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16);
  107. }
  108. #else
  109. if (bind_ip.is_wildcard()) {
  110. c_client.host = 0;
  111. } else {
  112. ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
  113. c_client.host = *(uint32_t *)bind_ip.get_ipv4();
  114. }
  115. #endif
  116. c_client.port = p_client_port;
  117. host = enet_host_create(&c_client /* create a client host */,
  118. 1 /* only allow 1 outgoing connection */,
  119. channel_count /* allow up to channel_count to be used */,
  120. p_in_bandwidth /* limit incoming bandwidth if > 0 */,
  121. p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
  122. } else {
  123. host = enet_host_create(NULL /* create a client host */,
  124. 1 /* only allow 1 outgoing connection */,
  125. channel_count /* allow up to channel_count to be used */,
  126. p_in_bandwidth /* limit incoming bandwidth if > 0 */,
  127. p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
  128. }
  129. ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
  130. _setup_compressor();
  131. IP_Address ip;
  132. if (p_address.is_valid_ip_address()) {
  133. ip = p_address;
  134. } else {
  135. #ifdef GODOT_ENET
  136. ip = IP::get_singleton()->resolve_hostname(p_address);
  137. #else
  138. ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
  139. #endif
  140. ERR_FAIL_COND_V(!ip.is_valid(), ERR_CANT_RESOLVE);
  141. }
  142. ENetAddress address;
  143. #ifdef GODOT_ENET
  144. enet_address_set_ip(&address, ip.get_ipv6(), 16);
  145. #else
  146. ERR_FAIL_COND_V(!ip.is_ipv4(), ERR_INVALID_PARAMETER);
  147. address.host = *(uint32_t *)ip.get_ipv4();
  148. #endif
  149. address.port = p_port;
  150. unique_id = _gen_unique_id();
  151. // Initiate connection, allocating enough channels
  152. ENetPeer *peer = enet_host_connect(host, &address, channel_count, unique_id);
  153. if (peer == NULL) {
  154. enet_host_destroy(host);
  155. ERR_FAIL_COND_V(!peer, ERR_CANT_CREATE);
  156. }
  157. // Technically safe to ignore the peer or anything else.
  158. connection_status = CONNECTION_CONNECTING;
  159. active = true;
  160. server = false;
  161. refuse_connections = false;
  162. return OK;
  163. }
  164. void NetworkedMultiplayerENet::poll() {
  165. ERR_FAIL_COND(!active);
  166. _pop_current_packet();
  167. ENetEvent event;
  168. /* Keep servicing until there are no available events left in queue. */
  169. while (true) {
  170. if (!host || !active) // Might have been disconnected while emitting a notification
  171. return;
  172. int ret = enet_host_service(host, &event, 0);
  173. if (ret < 0) {
  174. // Error, do something?
  175. break;
  176. } else if (ret == 0) {
  177. break;
  178. }
  179. switch (event.type) {
  180. case ENET_EVENT_TYPE_CONNECT: {
  181. // Store any relevant client information here.
  182. if (server && refuse_connections) {
  183. enet_peer_reset(event.peer);
  184. break;
  185. }
  186. // A client joined with an invalid ID (neagtive values, 0, and 1 are reserved).
  187. // Probably trying to exploit us.
  188. if (server && ((int)event.data < 2 || peer_map.has((int)event.data))) {
  189. enet_peer_reset(event.peer);
  190. ERR_CONTINUE(true);
  191. }
  192. int *new_id = memnew(int);
  193. *new_id = event.data;
  194. if (*new_id == 0) { // Data zero is sent by server (enet won't let you configure this). Server is always 1.
  195. *new_id = 1;
  196. }
  197. event.peer->data = new_id;
  198. peer_map[*new_id] = event.peer;
  199. connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something!
  200. emit_signal("peer_connected", *new_id);
  201. if (server) {
  202. // Someone connected, notify all the peers available
  203. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  204. if (E->key() == *new_id)
  205. continue;
  206. // Send existing peers to new peer
  207. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  208. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  209. encode_uint32(E->key(), &packet->data[4]);
  210. enet_peer_send(event.peer, SYSCH_CONFIG, packet);
  211. // Send the new peer to existing peers
  212. packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  213. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  214. encode_uint32(*new_id, &packet->data[4]);
  215. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  216. }
  217. } else {
  218. emit_signal("connection_succeeded");
  219. }
  220. } break;
  221. case ENET_EVENT_TYPE_DISCONNECT: {
  222. // Reset the peer's client information.
  223. int *id = (int *)event.peer->data;
  224. if (!id) {
  225. if (!server) {
  226. emit_signal("connection_failed");
  227. }
  228. } else {
  229. if (server) {
  230. // Someone disconnected, notify everyone else
  231. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  232. if (E->key() == *id)
  233. continue;
  234. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  235. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  236. encode_uint32(*id, &packet->data[4]);
  237. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  238. }
  239. } else {
  240. emit_signal("server_disconnected");
  241. close_connection();
  242. return;
  243. }
  244. emit_signal("peer_disconnected", *id);
  245. peer_map.erase(*id);
  246. memdelete(id);
  247. }
  248. } break;
  249. case ENET_EVENT_TYPE_RECEIVE: {
  250. if (event.channelID == SYSCH_CONFIG) {
  251. // Some config message
  252. ERR_CONTINUE(event.packet->dataLength < 8);
  253. // Only server can send config messages
  254. ERR_CONTINUE(server);
  255. int msg = decode_uint32(&event.packet->data[0]);
  256. int id = decode_uint32(&event.packet->data[4]);
  257. switch (msg) {
  258. case SYSMSG_ADD_PEER: {
  259. peer_map[id] = NULL;
  260. emit_signal("peer_connected", id);
  261. } break;
  262. case SYSMSG_REMOVE_PEER: {
  263. peer_map.erase(id);
  264. emit_signal("peer_disconnected", id);
  265. } break;
  266. }
  267. enet_packet_destroy(event.packet);
  268. } else if (event.channelID < channel_count) {
  269. Packet packet;
  270. packet.packet = event.packet;
  271. uint32_t *id = (uint32_t *)event.peer->data;
  272. ERR_CONTINUE(event.packet->dataLength < 12)
  273. uint32_t source = decode_uint32(&event.packet->data[0]);
  274. int target = decode_uint32(&event.packet->data[4]);
  275. uint32_t flags = decode_uint32(&event.packet->data[8]);
  276. packet.from = source;
  277. packet.channel = event.channelID;
  278. if (server) {
  279. // Someone is cheating and trying to fake the source!
  280. ERR_CONTINUE(source != *id);
  281. packet.from = *id;
  282. if (target == 0) {
  283. // Re-send to everyone but sender :|
  284. incoming_packets.push_back(packet);
  285. // And make copies for sending
  286. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  287. if (uint32_t(E->key()) == source) // Do not resend to self
  288. continue;
  289. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
  290. enet_peer_send(E->get(), event.channelID, packet2);
  291. }
  292. } else if (target < 0) {
  293. // To all but one
  294. // And make copies for sending
  295. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  296. if (uint32_t(E->key()) == source || E->key() == -target) // Do not resend to self, also do not send to excluded
  297. continue;
  298. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
  299. enet_peer_send(E->get(), event.channelID, packet2);
  300. }
  301. if (-target != 1) {
  302. // Server is not excluded
  303. incoming_packets.push_back(packet);
  304. } else {
  305. // Server is excluded, erase packet
  306. enet_packet_destroy(packet.packet);
  307. }
  308. } else if (target == 1) {
  309. // To myself and only myself
  310. incoming_packets.push_back(packet);
  311. } else {
  312. // To someone else, specifically
  313. ERR_CONTINUE(!peer_map.has(target));
  314. enet_peer_send(peer_map[target], event.channelID, packet.packet);
  315. }
  316. } else {
  317. incoming_packets.push_back(packet);
  318. }
  319. // Destroy packet later
  320. } else {
  321. ERR_CONTINUE(true);
  322. }
  323. } break;
  324. case ENET_EVENT_TYPE_NONE: {
  325. // Do nothing
  326. } break;
  327. }
  328. }
  329. }
  330. bool NetworkedMultiplayerENet::is_server() const {
  331. ERR_FAIL_COND_V(!active, false);
  332. return server;
  333. }
  334. void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) {
  335. ERR_FAIL_COND(!active);
  336. _pop_current_packet();
  337. bool peers_disconnected = false;
  338. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  339. if (E->get()) {
  340. enet_peer_disconnect_now(E->get(), unique_id);
  341. peers_disconnected = true;
  342. }
  343. }
  344. if (peers_disconnected) {
  345. enet_host_flush(host);
  346. if (wait_usec > 0) {
  347. OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send
  348. }
  349. }
  350. enet_host_destroy(host);
  351. active = false;
  352. incoming_packets.clear();
  353. unique_id = 1; // Server is 1
  354. connection_status = CONNECTION_DISCONNECTED;
  355. }
  356. void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
  357. ERR_FAIL_COND(!active);
  358. ERR_FAIL_COND(!is_server());
  359. ERR_FAIL_COND(!peer_map.has(p_peer))
  360. if (now) {
  361. enet_peer_disconnect_now(peer_map[p_peer], 0);
  362. // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT,
  363. // notify everyone else, send disconnect signal & remove from peer_map like in poll()
  364. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  365. if (E->key() == p_peer)
  366. continue;
  367. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  368. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  369. encode_uint32(p_peer, &packet->data[4]);
  370. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  371. }
  372. emit_signal("peer_disconnected", p_peer);
  373. peer_map.erase(p_peer);
  374. } else {
  375. enet_peer_disconnect_later(peer_map[p_peer], 0);
  376. }
  377. }
  378. int NetworkedMultiplayerENet::get_available_packet_count() const {
  379. return incoming_packets.size();
  380. }
  381. Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  382. ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);
  383. _pop_current_packet();
  384. current_packet = incoming_packets.front()->get();
  385. incoming_packets.pop_front();
  386. *r_buffer = (const uint8_t *)(&current_packet.packet->data[12]);
  387. r_buffer_size = current_packet.packet->dataLength - 12;
  388. return OK;
  389. }
  390. Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  391. ERR_FAIL_COND_V(!active, ERR_UNCONFIGURED);
  392. ERR_FAIL_COND_V(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  393. int packet_flags = 0;
  394. int channel = SYSCH_RELIABLE;
  395. switch (transfer_mode) {
  396. case TRANSFER_MODE_UNRELIABLE: {
  397. if (always_ordered)
  398. packet_flags = 0;
  399. else
  400. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
  401. channel = SYSCH_UNRELIABLE;
  402. } break;
  403. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  404. packet_flags = 0;
  405. channel = SYSCH_UNRELIABLE;
  406. } break;
  407. case TRANSFER_MODE_RELIABLE: {
  408. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  409. channel = SYSCH_RELIABLE;
  410. } break;
  411. }
  412. if (transfer_channel > SYSCH_CONFIG)
  413. channel = transfer_channel;
  414. Map<int, ENetPeer *>::Element *E = NULL;
  415. if (target_peer != 0) {
  416. E = peer_map.find(ABS(target_peer));
  417. if (!E) {
  418. ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
  419. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  420. }
  421. }
  422. ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 12, packet_flags);
  423. encode_uint32(unique_id, &packet->data[0]); // Source ID
  424. encode_uint32(target_peer, &packet->data[4]); // Dest ID
  425. encode_uint32(packet_flags, &packet->data[8]); // Dest ID
  426. copymem(&packet->data[12], p_buffer, p_buffer_size);
  427. if (server) {
  428. if (target_peer == 0) {
  429. enet_host_broadcast(host, channel, packet);
  430. } else if (target_peer < 0) {
  431. // Send to all but one
  432. // and make copies for sending
  433. int exclude = -target_peer;
  434. for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) {
  435. if (F->key() == exclude) // Exclude packet
  436. continue;
  437. ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);
  438. enet_peer_send(F->get(), channel, packet2);
  439. }
  440. enet_packet_destroy(packet); // Original packet no longer needed
  441. } else {
  442. enet_peer_send(E->get(), channel, packet);
  443. }
  444. } else {
  445. ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
  446. enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast
  447. }
  448. enet_host_flush(host);
  449. return OK;
  450. }
  451. int NetworkedMultiplayerENet::get_max_packet_size() const {
  452. return 1 << 24; // Anything is good
  453. }
  454. void NetworkedMultiplayerENet::_pop_current_packet() {
  455. if (current_packet.packet) {
  456. enet_packet_destroy(current_packet.packet);
  457. current_packet.packet = NULL;
  458. current_packet.from = 0;
  459. current_packet.channel = -1;
  460. }
  461. }
  462. NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
  463. return connection_status;
  464. }
  465. uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
  466. uint32_t hash = 0;
  467. while (hash == 0 || hash == 1) {
  468. hash = hash_djb2_one_32(
  469. (uint32_t)OS::get_singleton()->get_ticks_usec());
  470. hash = hash_djb2_one_32(
  471. (uint32_t)OS::get_singleton()->get_unix_time(), hash);
  472. hash = hash_djb2_one_32(
  473. (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
  474. hash = hash_djb2_one_32(
  475. (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
  476. hash = hash_djb2_one_32(
  477. (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack
  478. hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
  479. }
  480. return hash;
  481. }
  482. int NetworkedMultiplayerENet::get_unique_id() const {
  483. ERR_FAIL_COND_V(!active, 0);
  484. return unique_id;
  485. }
  486. void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
  487. refuse_connections = p_enable;
  488. }
  489. bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
  490. return refuse_connections;
  491. }
  492. void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
  493. compression_mode = p_mode;
  494. }
  495. NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const {
  496. return compression_mode;
  497. }
  498. size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  499. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  500. if (size_t(enet->src_compressor_mem.size()) < inLimit) {
  501. enet->src_compressor_mem.resize(inLimit);
  502. }
  503. int total = inLimit;
  504. int ofs = 0;
  505. while (total) {
  506. for (size_t i = 0; i < inBufferCount; i++) {
  507. int to_copy = MIN(total, int(inBuffers[i].dataLength));
  508. copymem(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy);
  509. ofs += to_copy;
  510. total -= to_copy;
  511. }
  512. }
  513. Compression::Mode mode;
  514. switch (enet->compression_mode) {
  515. case COMPRESS_FASTLZ: {
  516. mode = Compression::MODE_FASTLZ;
  517. } break;
  518. case COMPRESS_ZLIB: {
  519. mode = Compression::MODE_DEFLATE;
  520. } break;
  521. case COMPRESS_ZSTD: {
  522. mode = Compression::MODE_ZSTD;
  523. } break;
  524. default: { ERR_FAIL_V(0); }
  525. }
  526. int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
  527. if (enet->dst_compressor_mem.size() < req_size) {
  528. enet->dst_compressor_mem.resize(req_size);
  529. }
  530. int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode);
  531. if (ret < 0)
  532. return 0;
  533. if (ret > int(outLimit))
  534. return 0; // Do not bother
  535. copymem(outData, enet->dst_compressor_mem.ptr(), ret);
  536. return ret;
  537. }
  538. size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  539. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  540. int ret = -1;
  541. switch (enet->compression_mode) {
  542. case COMPRESS_FASTLZ: {
  543. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
  544. } break;
  545. case COMPRESS_ZLIB: {
  546. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
  547. } break;
  548. case COMPRESS_ZSTD: {
  549. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
  550. } break;
  551. default: {}
  552. }
  553. if (ret < 0) {
  554. return 0;
  555. } else {
  556. return ret;
  557. }
  558. }
  559. void NetworkedMultiplayerENet::_setup_compressor() {
  560. switch (compression_mode) {
  561. case COMPRESS_NONE: {
  562. enet_host_compress(host, NULL);
  563. } break;
  564. case COMPRESS_RANGE_CODER: {
  565. enet_host_compress_with_range_coder(host);
  566. } break;
  567. case COMPRESS_FASTLZ:
  568. case COMPRESS_ZLIB:
  569. case COMPRESS_ZSTD: {
  570. enet_host_compress(host, &enet_compressor);
  571. } break;
  572. }
  573. }
  574. void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {
  575. // Nothing to do
  576. }
  577. IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {
  578. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), IP_Address());
  579. ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, IP_Address());
  580. ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, IP_Address());
  581. IP_Address out;
  582. #ifdef GODOT_ENET
  583. out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host));
  584. #else
  585. out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host));
  586. #endif
  587. return out;
  588. }
  589. int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {
  590. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), 0);
  591. ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, 0);
  592. ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, 0);
  593. #ifdef GODOT_ENET
  594. return peer_map[p_peer_id]->address.port;
  595. #else
  596. return peer_map[p_peer_id]->address.port;
  597. #endif
  598. }
  599. void NetworkedMultiplayerENet::set_transfer_channel(int p_channel) {
  600. ERR_FAIL_COND(p_channel < -1 || p_channel >= channel_count);
  601. if (p_channel == SYSCH_CONFIG) {
  602. ERR_EXPLAIN("Channel " + itos(SYSCH_CONFIG) + " is reserved");
  603. ERR_FAIL();
  604. }
  605. transfer_channel = p_channel;
  606. }
  607. int NetworkedMultiplayerENet::get_transfer_channel() const {
  608. return transfer_channel;
  609. }
  610. void NetworkedMultiplayerENet::set_channel_count(int p_channel) {
  611. ERR_FAIL_COND(active);
  612. ERR_FAIL_COND(p_channel < SYSCH_MAX);
  613. channel_count = p_channel;
  614. }
  615. int NetworkedMultiplayerENet::get_channel_count() const {
  616. return channel_count;
  617. }
  618. void NetworkedMultiplayerENet::set_always_ordered(bool p_ordered) {
  619. always_ordered = p_ordered;
  620. }
  621. bool NetworkedMultiplayerENet::is_always_ordered() const {
  622. return always_ordered;
  623. }
  624. void NetworkedMultiplayerENet::_bind_methods() {
  625. ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0));
  626. ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "client_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0));
  627. ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100));
  628. ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false));
  629. ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode);
  630. ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode);
  631. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip);
  632. ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &NetworkedMultiplayerENet::get_peer_address);
  633. ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &NetworkedMultiplayerENet::get_peer_port);
  634. ClassDB::bind_method(D_METHOD("get_packet_channel"), &NetworkedMultiplayerENet::get_packet_channel);
  635. ClassDB::bind_method(D_METHOD("get_last_packet_channel"), &NetworkedMultiplayerENet::get_last_packet_channel);
  636. ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &NetworkedMultiplayerENet::set_transfer_channel);
  637. ClassDB::bind_method(D_METHOD("get_transfer_channel"), &NetworkedMultiplayerENet::get_transfer_channel);
  638. ClassDB::bind_method(D_METHOD("set_channel_count", "channels"), &NetworkedMultiplayerENet::set_channel_count);
  639. ClassDB::bind_method(D_METHOD("get_channel_count"), &NetworkedMultiplayerENet::get_channel_count);
  640. ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &NetworkedMultiplayerENet::set_always_ordered);
  641. ClassDB::bind_method(D_METHOD("is_always_ordered"), &NetworkedMultiplayerENet::is_always_ordered);
  642. ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode");
  643. ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel"), "set_transfer_channel", "get_transfer_channel");
  644. ADD_PROPERTY(PropertyInfo(Variant::INT, "channel_count"), "set_channel_count", "get_channel_count");
  645. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "always_ordered"), "set_always_ordered", "is_always_ordered");
  646. BIND_ENUM_CONSTANT(COMPRESS_NONE);
  647. BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
  648. BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
  649. BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
  650. BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
  651. }
  652. NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
  653. active = false;
  654. server = false;
  655. refuse_connections = false;
  656. unique_id = 0;
  657. target_peer = 0;
  658. current_packet.packet = NULL;
  659. transfer_mode = TRANSFER_MODE_RELIABLE;
  660. channel_count = SYSCH_MAX;
  661. transfer_channel = -1;
  662. always_ordered = false;
  663. connection_status = CONNECTION_DISCONNECTED;
  664. compression_mode = COMPRESS_NONE;
  665. enet_compressor.context = this;
  666. enet_compressor.compress = enet_compress;
  667. enet_compressor.decompress = enet_decompress;
  668. enet_compressor.destroy = enet_compressor_destroy;
  669. bind_ip = IP_Address("*");
  670. }
  671. NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
  672. close_connection();
  673. }
  674. // Sets IP for ENet to bind when using create_server or create_client
  675. // if no IP is set, then ENet bind to ENET_HOST_ANY
  676. void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) {
  677. ERR_FAIL_COND(!p_ip.is_valid() && !p_ip.is_wildcard());
  678. bind_ip = p_ip;
  679. }