networked_multiplayer_enet.cpp 33 KB

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