networked_multiplayer_enet.cpp 26 KB

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