networked_multiplayer_enet.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. /**************************************************************************/
  2. /* networked_multiplayer_enet.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "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 port number must be set 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_client_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 < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The server port number must be set between 0 and 65535 (inclusive).");
  105. ERR_FAIL_COND_V_MSG(p_client_port < 0 || p_client_port > 65535, ERR_INVALID_PARAMETER, "The client port number must be set 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. if (p_client_port != 0) {
  109. ENetAddress c_client;
  110. #ifdef GODOT_ENET
  111. if (bind_ip.is_wildcard()) {
  112. c_client.wildcard = 1;
  113. } else {
  114. enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16);
  115. }
  116. #else
  117. if (bind_ip.is_wildcard()) {
  118. c_client.host = 0;
  119. } else {
  120. ERR_FAIL_COND_V_MSG(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER, "Wildcard IP addresses are only permitted in IPv4, not IPv6.");
  121. c_client.host = *(uint32_t *)bind_ip.get_ipv4();
  122. }
  123. #endif
  124. c_client.port = p_client_port;
  125. host = enet_host_create(&c_client /* create a client host */,
  126. 1 /* only allow 1 outgoing connection */,
  127. channel_count /* allow up to channel_count to be used */,
  128. p_in_bandwidth /* limit incoming bandwidth if > 0 */,
  129. p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
  130. } else {
  131. host = enet_host_create(nullptr /* create a client host */,
  132. 1 /* only allow 1 outgoing connection */,
  133. channel_count /* allow up to channel_count to be used */,
  134. p_in_bandwidth /* limit incoming bandwidth if > 0 */,
  135. p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
  136. }
  137. ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create the ENet client host.");
  138. #ifdef GODOT_ENET
  139. if (dtls_enabled) {
  140. enet_host_dtls_client_setup(host, dtls_cert.ptr(), dtls_verify, dtls_hostname.empty() ? p_address.utf8().get_data() : dtls_hostname.utf8().get_data());
  141. }
  142. enet_host_refuse_new_connections(host, refuse_connections);
  143. #endif
  144. _setup_compressor();
  145. IP_Address ip;
  146. if (p_address.is_valid_ip_address()) {
  147. ip = p_address;
  148. } else {
  149. #ifdef GODOT_ENET
  150. ip = IP::get_singleton()->resolve_hostname(p_address);
  151. #else
  152. ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
  153. #endif
  154. if (!ip.is_valid()) {
  155. enet_host_destroy(host);
  156. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Couldn't resolve the server IP address or domain name.");
  157. }
  158. }
  159. ENetAddress address;
  160. #ifdef GODOT_ENET
  161. enet_address_set_ip(&address, ip.get_ipv6(), 16);
  162. #else
  163. if (!ip.is_ipv4()) {
  164. enet_host_destroy(host);
  165. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library.");
  166. }
  167. address.host = *(uint32_t *)ip.get_ipv4();
  168. #endif
  169. address.port = p_port;
  170. unique_id = _gen_unique_id();
  171. // Initiate connection, allocating enough channels
  172. ENetPeer *peer = enet_host_connect(host, &address, channel_count, unique_id);
  173. if (peer == nullptr) {
  174. enet_host_destroy(host);
  175. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server.");
  176. }
  177. // Technically safe to ignore the peer or anything else.
  178. connection_status = CONNECTION_CONNECTING;
  179. active = true;
  180. server = false;
  181. refuse_connections = false;
  182. return OK;
  183. }
  184. void NetworkedMultiplayerENet::poll() {
  185. ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active.");
  186. _pop_current_packet();
  187. if (!host || !active) { // Might be disconnected
  188. return;
  189. }
  190. ENetEvent event;
  191. int ret = enet_host_service(host, &event, 0);
  192. if (ret < 0) {
  193. ERR_FAIL_MSG("Enet host service error");
  194. } else if (ret == 0) {
  195. return; // No events
  196. }
  197. /* Keep servicing until there are no available events left in the queue. */
  198. do {
  199. if (!host || !active) { // Check again after every event
  200. return;
  201. }
  202. switch (event.type) {
  203. case ENET_EVENT_TYPE_CONNECT: {
  204. // Store any relevant client information here.
  205. if (server && refuse_connections) {
  206. enet_peer_reset(event.peer);
  207. break;
  208. }
  209. // A client joined with an invalid ID (negative values, 0, and 1 are reserved).
  210. // Probably trying to exploit us.
  211. if (server && ((int)event.data < 2 || peer_map.has((int)event.data))) {
  212. enet_peer_reset(event.peer);
  213. ERR_CONTINUE(true);
  214. }
  215. int *new_id = memnew(int);
  216. *new_id = event.data;
  217. if (*new_id == 0) { // Data zero is sent by server (enet won't let you configure this). Server is always 1.
  218. *new_id = 1;
  219. }
  220. event.peer->data = new_id;
  221. peer_map[*new_id] = event.peer;
  222. connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something!
  223. emit_signal("peer_connected", *new_id);
  224. if (server) {
  225. // Do not notify other peers when server_relay is disabled.
  226. if (!server_relay) {
  227. break;
  228. }
  229. // Someone connected, notify all the peers available
  230. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  231. if (E->key() == *new_id) {
  232. continue;
  233. }
  234. // Send existing peers to new peer
  235. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  236. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  237. encode_uint32(E->key(), &packet->data[4]);
  238. enet_peer_send(event.peer, SYSCH_CONFIG, packet);
  239. // Send the new peer to existing peers
  240. packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  241. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  242. encode_uint32(*new_id, &packet->data[4]);
  243. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  244. }
  245. } else {
  246. emit_signal("connection_succeeded");
  247. }
  248. } break;
  249. case ENET_EVENT_TYPE_DISCONNECT: {
  250. // Reset the peer's client information.
  251. int *id = (int *)event.peer->data;
  252. if (!id) {
  253. if (!server) {
  254. emit_signal("connection_failed");
  255. }
  256. // Never fully connected.
  257. break;
  258. }
  259. if (!server) {
  260. // Client just disconnected from server.
  261. emit_signal("server_disconnected");
  262. close_connection();
  263. return;
  264. } else if (server_relay) {
  265. // Server just received a client disconnect and is in relay mode, notify everyone else.
  266. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  267. if (E->key() == *id) {
  268. continue;
  269. }
  270. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  271. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  272. encode_uint32(*id, &packet->data[4]);
  273. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  274. }
  275. }
  276. emit_signal("peer_disconnected", *id);
  277. peer_map.erase(*id);
  278. memdelete(id);
  279. } break;
  280. case ENET_EVENT_TYPE_RECEIVE: {
  281. if (event.channelID == SYSCH_CONFIG) {
  282. // Some config message
  283. ERR_CONTINUE(event.packet->dataLength < 8);
  284. // Only server can send config messages
  285. ERR_CONTINUE(server);
  286. int msg = decode_uint32(&event.packet->data[0]);
  287. int id = decode_uint32(&event.packet->data[4]);
  288. switch (msg) {
  289. case SYSMSG_ADD_PEER: {
  290. peer_map[id] = NULL;
  291. emit_signal("peer_connected", id);
  292. } break;
  293. case SYSMSG_REMOVE_PEER: {
  294. peer_map.erase(id);
  295. emit_signal("peer_disconnected", id);
  296. } break;
  297. }
  298. enet_packet_destroy(event.packet);
  299. } else if (event.channelID < channel_count) {
  300. Packet packet;
  301. packet.packet = event.packet;
  302. uint32_t *id = (uint32_t *)event.peer->data;
  303. ERR_CONTINUE(event.packet->dataLength < 8);
  304. uint32_t source = decode_uint32(&event.packet->data[0]);
  305. int target = decode_uint32(&event.packet->data[4]);
  306. packet.from = source;
  307. packet.channel = event.channelID;
  308. if (server) {
  309. // Someone is cheating and trying to fake the source!
  310. ERR_CONTINUE(source != *id);
  311. packet.from = *id;
  312. if (target == 1) {
  313. // To myself and only myself
  314. incoming_packets.push_back(packet);
  315. } else if (!server_relay) {
  316. // When relaying is disabled, other destinations will only be processed by the server.
  317. if (target == 0 || target < -1) {
  318. incoming_packets.push_back(packet);
  319. }
  320. continue;
  321. } else if (target == 0) {
  322. // Re-send to everyone but sender :|
  323. incoming_packets.push_back(packet);
  324. // And make copies for sending
  325. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  326. if (uint32_t(E->key()) == source) { // Do not resend to self
  327. continue;
  328. }
  329. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags);
  330. enet_peer_send(E->get(), event.channelID, packet2);
  331. }
  332. } else if (target < 0) {
  333. // To all but one
  334. // And make copies for sending
  335. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  336. if (uint32_t(E->key()) == source || E->key() == -target) { // Do not resend to self, also do not send to excluded
  337. continue;
  338. }
  339. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags);
  340. enet_peer_send(E->get(), event.channelID, packet2);
  341. }
  342. if (-target != 1) {
  343. // Server is not excluded
  344. incoming_packets.push_back(packet);
  345. } else {
  346. // Server is excluded, erase packet
  347. enet_packet_destroy(packet.packet);
  348. }
  349. } else {
  350. // To someone else, specifically
  351. ERR_CONTINUE(!peer_map.has(target));
  352. enet_peer_send(peer_map[target], event.channelID, packet.packet);
  353. }
  354. } else {
  355. incoming_packets.push_back(packet);
  356. }
  357. // Destroy packet later
  358. } else {
  359. ERR_CONTINUE(true);
  360. }
  361. } break;
  362. case ENET_EVENT_TYPE_NONE: {
  363. // Do nothing
  364. } break;
  365. }
  366. } while (enet_host_check_events(host, &event) > 0);
  367. }
  368. bool NetworkedMultiplayerENet::is_server() const {
  369. ERR_FAIL_COND_V_MSG(!active, false, "The multiplayer instance isn't currently active.");
  370. return server;
  371. }
  372. void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) {
  373. if (!active) {
  374. return;
  375. }
  376. _pop_current_packet();
  377. bool peers_disconnected = false;
  378. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  379. if (E->get()) {
  380. enet_peer_disconnect_now(E->get(), unique_id);
  381. int *id = (int *)(E->get()->data);
  382. memdelete(id);
  383. peers_disconnected = true;
  384. }
  385. }
  386. if (peers_disconnected) {
  387. enet_host_flush(host);
  388. if (wait_usec > 0) {
  389. OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send
  390. }
  391. }
  392. enet_host_destroy(host);
  393. active = false;
  394. incoming_packets.clear();
  395. peer_map.clear();
  396. unique_id = 1; // Server is 1
  397. connection_status = CONNECTION_DISCONNECTED;
  398. }
  399. void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
  400. ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active.");
  401. ERR_FAIL_COND_MSG(!is_server(), "Can't disconnect a peer when not acting as a server.");
  402. ERR_FAIL_COND_MSG(!peer_map.has(p_peer), vformat("Peer ID %d not found in the list of peers.", p_peer));
  403. if (now) {
  404. int *id = (int *)peer_map[p_peer]->data;
  405. enet_peer_disconnect_now(peer_map[p_peer], 0);
  406. // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT,
  407. // notify everyone else, send disconnect signal & remove from peer_map like in poll()
  408. if (server_relay) {
  409. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  410. if (E->key() == p_peer) {
  411. continue;
  412. }
  413. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  414. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  415. encode_uint32(p_peer, &packet->data[4]);
  416. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  417. }
  418. }
  419. if (id) {
  420. memdelete(id);
  421. }
  422. emit_signal("peer_disconnected", p_peer);
  423. peer_map.erase(p_peer);
  424. } else {
  425. enet_peer_disconnect_later(peer_map[p_peer], 0);
  426. }
  427. }
  428. int NetworkedMultiplayerENet::get_available_packet_count() const {
  429. return incoming_packets.size();
  430. }
  431. Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  432. ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available.");
  433. _pop_current_packet();
  434. current_packet = incoming_packets.front()->get();
  435. incoming_packets.pop_front();
  436. *r_buffer = (const uint8_t *)(&current_packet.packet->data[8]);
  437. r_buffer_size = current_packet.packet->dataLength - 8;
  438. return OK;
  439. }
  440. Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  441. ERR_FAIL_COND_V_MSG(!active, ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");
  442. ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");
  443. int packet_flags = 0;
  444. int channel = SYSCH_RELIABLE;
  445. switch (transfer_mode) {
  446. case TRANSFER_MODE_UNRELIABLE: {
  447. if (always_ordered) {
  448. packet_flags = 0;
  449. } else {
  450. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
  451. }
  452. channel = SYSCH_UNRELIABLE;
  453. packet_flags |= ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
  454. } break;
  455. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  456. packet_flags = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
  457. channel = SYSCH_UNRELIABLE;
  458. } break;
  459. case TRANSFER_MODE_RELIABLE: {
  460. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  461. channel = SYSCH_RELIABLE;
  462. } break;
  463. }
  464. if (transfer_channel > SYSCH_CONFIG) {
  465. channel = transfer_channel;
  466. }
  467. #ifdef DEBUG_ENABLED
  468. if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size + 8 > ENET_HOST_DEFAULT_MTU) {
  469. WARN_PRINT_ONCE(vformat("Sending %d bytes unrealiably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size + 8, host->mtu));
  470. }
  471. #endif
  472. Map<int, ENetPeer *>::Element *E = nullptr;
  473. if (target_peer != 0) {
  474. E = peer_map.find(ABS(target_peer));
  475. ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));
  476. }
  477. ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size + 8, packet_flags);
  478. encode_uint32(unique_id, &packet->data[0]); // Source ID
  479. encode_uint32(target_peer, &packet->data[4]); // Dest ID
  480. memcpy(&packet->data[8], p_buffer, p_buffer_size);
  481. if (server) {
  482. if (target_peer == 0) {
  483. enet_host_broadcast(host, channel, packet);
  484. } else if (target_peer < 0) {
  485. // Send to all but one
  486. // and make copies for sending
  487. int exclude = -target_peer;
  488. for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) {
  489. if (F->key() == exclude) { // Exclude packet
  490. continue;
  491. }
  492. ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);
  493. enet_peer_send(F->get(), channel, packet2);
  494. }
  495. enet_packet_destroy(packet); // Original packet no longer needed
  496. } else {
  497. enet_peer_send(E->get(), channel, packet);
  498. }
  499. } else {
  500. ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
  501. enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast
  502. }
  503. enet_host_flush(host);
  504. return OK;
  505. }
  506. int NetworkedMultiplayerENet::get_max_packet_size() const {
  507. return 1 << 24; // Anything is good
  508. }
  509. void NetworkedMultiplayerENet::_pop_current_packet() {
  510. if (current_packet.packet) {
  511. enet_packet_destroy(current_packet.packet);
  512. current_packet.packet = nullptr;
  513. current_packet.from = 0;
  514. current_packet.channel = -1;
  515. }
  516. }
  517. NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
  518. return connection_status;
  519. }
  520. uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
  521. uint32_t hash = 0;
  522. while (hash == 0 || hash == 1) {
  523. hash = hash_djb2_one_32(
  524. (uint32_t)OS::get_singleton()->get_ticks_usec());
  525. hash = hash_djb2_one_32(
  526. (uint32_t)OS::get_singleton()->get_unix_time(), hash);
  527. hash = hash_djb2_one_32(
  528. (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
  529. hash = hash_djb2_one_32(
  530. (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
  531. hash = hash_djb2_one_32(
  532. (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack
  533. hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
  534. }
  535. return hash;
  536. }
  537. int NetworkedMultiplayerENet::get_unique_id() const {
  538. ERR_FAIL_COND_V_MSG(!active, 0, "The multiplayer instance isn't currently active.");
  539. return unique_id;
  540. }
  541. void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
  542. refuse_connections = p_enable;
  543. #ifdef GODOT_ENET
  544. if (active) {
  545. enet_host_refuse_new_connections(host, p_enable);
  546. }
  547. #endif
  548. }
  549. bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
  550. return refuse_connections;
  551. }
  552. void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
  553. compression_mode = p_mode;
  554. }
  555. NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const {
  556. return compression_mode;
  557. }
  558. size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  559. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  560. if (size_t(enet->src_compressor_mem.size()) < inLimit) {
  561. enet->src_compressor_mem.resize(inLimit);
  562. }
  563. int total = inLimit;
  564. int ofs = 0;
  565. while (total) {
  566. for (size_t i = 0; i < inBufferCount; i++) {
  567. int to_copy = MIN(total, int(inBuffers[i].dataLength));
  568. memcpy(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy);
  569. ofs += to_copy;
  570. total -= to_copy;
  571. }
  572. }
  573. Compression::Mode mode;
  574. switch (enet->compression_mode) {
  575. case COMPRESS_FASTLZ: {
  576. mode = Compression::MODE_FASTLZ;
  577. } break;
  578. case COMPRESS_ZLIB: {
  579. mode = Compression::MODE_DEFLATE;
  580. } break;
  581. case COMPRESS_ZSTD: {
  582. mode = Compression::MODE_ZSTD;
  583. } break;
  584. default: {
  585. ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", enet->compression_mode));
  586. }
  587. }
  588. int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
  589. if (enet->dst_compressor_mem.size() < req_size) {
  590. enet->dst_compressor_mem.resize(req_size);
  591. }
  592. int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode);
  593. if (ret < 0) {
  594. return 0;
  595. }
  596. if (ret > int(outLimit)) {
  597. return 0; // Do not bother
  598. }
  599. memcpy(outData, enet->dst_compressor_mem.ptr(), ret);
  600. return ret;
  601. }
  602. size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  603. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  604. int ret = -1;
  605. switch (enet->compression_mode) {
  606. case COMPRESS_FASTLZ: {
  607. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
  608. } break;
  609. case COMPRESS_ZLIB: {
  610. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
  611. } break;
  612. case COMPRESS_ZSTD: {
  613. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
  614. } break;
  615. default: {
  616. }
  617. }
  618. if (ret < 0) {
  619. return 0;
  620. } else {
  621. return ret;
  622. }
  623. }
  624. void NetworkedMultiplayerENet::_setup_compressor() {
  625. switch (compression_mode) {
  626. case COMPRESS_NONE: {
  627. enet_host_compress(host, nullptr);
  628. } break;
  629. case COMPRESS_RANGE_CODER: {
  630. enet_host_compress_with_range_coder(host);
  631. } break;
  632. case COMPRESS_FASTLZ:
  633. case COMPRESS_ZLIB:
  634. case COMPRESS_ZSTD: {
  635. enet_host_compress(host, &enet_compressor);
  636. } break;
  637. }
  638. }
  639. void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {
  640. // Nothing to do
  641. }
  642. IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {
  643. ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), IP_Address(), vformat("Peer ID %d not found in the list of peers.", p_peer_id));
  644. ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, IP_Address(), "Can't get the address of peers other than the server (ID -1) when acting as a client.");
  645. ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == NULL, IP_Address(), vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id));
  646. IP_Address out;
  647. #ifdef GODOT_ENET
  648. out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host));
  649. #else
  650. out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host));
  651. #endif
  652. return out;
  653. }
  654. int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {
  655. 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));
  656. 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.");
  657. ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == NULL, 0, vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id));
  658. #ifdef GODOT_ENET
  659. return peer_map[p_peer_id]->address.port;
  660. #else
  661. return peer_map[p_peer_id]->address.port;
  662. #endif
  663. }
  664. void NetworkedMultiplayerENet::set_peer_timeout(int p_peer_id, int p_timeout_limit, int p_timeout_min, int p_timeout_max) {
  665. ERR_FAIL_COND_MSG(!peer_map.has(p_peer_id), vformat("Peer ID %d not found in the list of peers.", p_peer_id));
  666. 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.");
  667. 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));
  668. 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");
  669. enet_peer_timeout(peer_map[p_peer_id], p_timeout_limit, p_timeout_min, p_timeout_max);
  670. }
  671. void NetworkedMultiplayerENet::set_transfer_channel(int p_channel) {
  672. 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));
  673. ERR_FAIL_COND_MSG(p_channel == SYSCH_CONFIG, vformat("The channel %d is reserved.", SYSCH_CONFIG));
  674. transfer_channel = p_channel;
  675. }
  676. int NetworkedMultiplayerENet::get_transfer_channel() const {
  677. return transfer_channel;
  678. }
  679. void NetworkedMultiplayerENet::set_channel_count(int p_channel) {
  680. ERR_FAIL_COND_MSG(active, "The channel count can't be set while the multiplayer instance is active.");
  681. 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));
  682. channel_count = p_channel;
  683. }
  684. int NetworkedMultiplayerENet::get_channel_count() const {
  685. return channel_count;
  686. }
  687. void NetworkedMultiplayerENet::set_always_ordered(bool p_ordered) {
  688. always_ordered = p_ordered;
  689. }
  690. bool NetworkedMultiplayerENet::is_always_ordered() const {
  691. return always_ordered;
  692. }
  693. void NetworkedMultiplayerENet::set_server_relay_enabled(bool p_enabled) {
  694. ERR_FAIL_COND_MSG(active, "Server relaying can't be toggled while the multiplayer instance is active.");
  695. server_relay = p_enabled;
  696. }
  697. bool NetworkedMultiplayerENet::is_server_relay_enabled() const {
  698. return server_relay;
  699. }
  700. void NetworkedMultiplayerENet::_bind_methods() {
  701. ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0));
  702. ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "client_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0));
  703. ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100));
  704. ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false));
  705. ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode);
  706. ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode);
  707. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip);
  708. ClassDB::bind_method(D_METHOD("set_dtls_enabled", "enabled"), &NetworkedMultiplayerENet::set_dtls_enabled);
  709. ClassDB::bind_method(D_METHOD("is_dtls_enabled"), &NetworkedMultiplayerENet::is_dtls_enabled);
  710. ClassDB::bind_method(D_METHOD("set_dtls_key", "key"), &NetworkedMultiplayerENet::set_dtls_key);
  711. ClassDB::bind_method(D_METHOD("set_dtls_certificate", "certificate"), &NetworkedMultiplayerENet::set_dtls_certificate);
  712. ClassDB::bind_method(D_METHOD("set_dtls_verify_enabled", "enabled"), &NetworkedMultiplayerENet::set_dtls_verify_enabled);
  713. ClassDB::bind_method(D_METHOD("is_dtls_verify_enabled"), &NetworkedMultiplayerENet::is_dtls_verify_enabled);
  714. ClassDB::bind_method(D_METHOD("set_dtls_hostname", "hostname"), &NetworkedMultiplayerENet::set_dtls_hostname);
  715. ClassDB::bind_method(D_METHOD("get_dtls_hostname"), &NetworkedMultiplayerENet::get_dtls_hostname);
  716. ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &NetworkedMultiplayerENet::get_peer_address);
  717. ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &NetworkedMultiplayerENet::get_peer_port);
  718. ClassDB::bind_method(D_METHOD("set_peer_timeout", "id", "timeout_limit", "timeout_min", "timeout_max"), &NetworkedMultiplayerENet::set_peer_timeout);
  719. ClassDB::bind_method(D_METHOD("get_packet_channel"), &NetworkedMultiplayerENet::get_packet_channel);
  720. ClassDB::bind_method(D_METHOD("get_last_packet_channel"), &NetworkedMultiplayerENet::get_last_packet_channel);
  721. ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &NetworkedMultiplayerENet::set_transfer_channel);
  722. ClassDB::bind_method(D_METHOD("get_transfer_channel"), &NetworkedMultiplayerENet::get_transfer_channel);
  723. ClassDB::bind_method(D_METHOD("set_channel_count", "channels"), &NetworkedMultiplayerENet::set_channel_count);
  724. ClassDB::bind_method(D_METHOD("get_channel_count"), &NetworkedMultiplayerENet::get_channel_count);
  725. ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &NetworkedMultiplayerENet::set_always_ordered);
  726. ClassDB::bind_method(D_METHOD("is_always_ordered"), &NetworkedMultiplayerENet::is_always_ordered);
  727. ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &NetworkedMultiplayerENet::set_server_relay_enabled);
  728. ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &NetworkedMultiplayerENet::is_server_relay_enabled);
  729. ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode");
  730. ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel"), "set_transfer_channel", "get_transfer_channel");
  731. ADD_PROPERTY(PropertyInfo(Variant::INT, "channel_count"), "set_channel_count", "get_channel_count");
  732. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "always_ordered"), "set_always_ordered", "is_always_ordered");
  733. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
  734. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dtls_verify"), "set_dtls_verify_enabled", "is_dtls_verify_enabled");
  735. ADD_PROPERTY(PropertyInfo(Variant::STRING, "dtls_hostname"), "set_dtls_hostname", "get_dtls_hostname");
  736. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_dtls"), "set_dtls_enabled", "is_dtls_enabled");
  737. BIND_ENUM_CONSTANT(COMPRESS_NONE);
  738. BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
  739. BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
  740. BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
  741. BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
  742. }
  743. NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
  744. active = false;
  745. server = false;
  746. refuse_connections = false;
  747. server_relay = true;
  748. unique_id = 0;
  749. target_peer = 0;
  750. current_packet.packet = nullptr;
  751. transfer_mode = TRANSFER_MODE_RELIABLE;
  752. channel_count = SYSCH_MAX;
  753. transfer_channel = -1;
  754. always_ordered = false;
  755. connection_status = CONNECTION_DISCONNECTED;
  756. compression_mode = COMPRESS_RANGE_CODER;
  757. enet_compressor.context = this;
  758. enet_compressor.compress = enet_compress;
  759. enet_compressor.decompress = enet_decompress;
  760. enet_compressor.destroy = enet_compressor_destroy;
  761. bind_ip = IP_Address("*");
  762. dtls_enabled = false;
  763. dtls_verify = true;
  764. }
  765. NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
  766. if (active) {
  767. close_connection();
  768. }
  769. }
  770. // Sets IP for ENet to bind when using create_server or create_client
  771. // if no IP is set, then ENet bind to ENET_HOST_ANY
  772. void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) {
  773. ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip)));
  774. bind_ip = p_ip;
  775. }
  776. void NetworkedMultiplayerENet::set_dtls_enabled(bool p_enabled) {
  777. ERR_FAIL_COND(active);
  778. dtls_enabled = p_enabled;
  779. }
  780. bool NetworkedMultiplayerENet::is_dtls_enabled() const {
  781. return dtls_enabled;
  782. }
  783. void NetworkedMultiplayerENet::set_dtls_verify_enabled(bool p_enabled) {
  784. ERR_FAIL_COND(active);
  785. dtls_verify = p_enabled;
  786. }
  787. bool NetworkedMultiplayerENet::is_dtls_verify_enabled() const {
  788. return dtls_verify;
  789. }
  790. void NetworkedMultiplayerENet::set_dtls_key(Ref<CryptoKey> p_key) {
  791. ERR_FAIL_COND(active);
  792. dtls_key = p_key;
  793. }
  794. void NetworkedMultiplayerENet::set_dtls_certificate(Ref<X509Certificate> p_cert) {
  795. ERR_FAIL_COND(active);
  796. dtls_cert = p_cert;
  797. }
  798. void NetworkedMultiplayerENet::set_dtls_hostname(const String &p_hostname) {
  799. ERR_FAIL_COND(active);
  800. dtls_hostname = p_hostname;
  801. }
  802. String NetworkedMultiplayerENet::get_dtls_hostname() const {
  803. return dtls_hostname;
  804. }