Debian Codegraph @

modules/enet/enet_multiplayer_peer.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* enet_multiplayer_peer.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "enet_multiplayer_peer.h"
32
33 void ENetMultiplayerPeer::set_target_peer(int p_peer) {
34 target_peer = p_peer;
35 }
36
37 int ENetMultiplayerPeer::get_packet_peer() const {
38 ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
39 ERR_FAIL_COND_V(incoming_packets.is_empty(), 1);
40
41 return incoming_packets.front()->get().from;
42 }
43
44 MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_packet_mode() const {
45 ERR_FAIL_COND_V_MSG(!_is_active(), TRANSFER_MODE_RELIABLE, "The multiplayer instance isn't currently active.");
46 ERR_FAIL_COND_V(incoming_packets.is_empty(), TRANSFER_MODE_RELIABLE);
47 return incoming_packets.front()->get().transfer_mode;
48 }
49
50 int ENetMultiplayerPeer::get_packet_channel() const {
51 ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
52 ERR_FAIL_COND_V(incoming_packets.is_empty(), 1);
53 int ch = incoming_packets.front()->get().channel;
54 if (ch >= SYSCH_MAX) { // First 2 channels are reserved.
55 return ch - SYSCH_MAX + 1;
56 }
57 return 0;
58 }
59
60 Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
61 ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
62 set_refuse_new_connections(false);
63 Ref<ENetConnection> host;
64 host.instantiate();
65 Error err = host->create_host_bound(bind_ip, p_port, p_max_clients, 0, p_max_channels > 0 ? p_max_channels + SYSCH_MAX : 0, p_out_bandwidth);
66 if (err != OK) {
67 return err;
68 }
69
70 active_mode = MODE_SERVER;
71 unique_id = 1;
72 connection_status = CONNECTION_CONNECTED;
73 hosts[0] = host;
74 return OK;
75 }
76
77 Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, int p_channel_count, int p_in_bandwidth, int p_out_bandwidth, int p_local_port) {
78 ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
79 set_refuse_new_connections(false);
80 Ref<ENetConnection> host;
81 host.instantiate();
82 Error err;
83 if (p_local_port) {
84 err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth);
85 } else {
86 err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth);
87 }
88 if (err != OK) {
89 return err;
90 }
91
92 unique_id = generate_unique_id();
93
94 Ref<ENetPacketPeer> peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id);
95 if (peer.is_null()) {
96 host->destroy();
97 ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server.");
98 }
99
100 // Need to wait for CONNECT event.
101 connection_status = CONNECTION_CONNECTING;
102 active_mode = MODE_CLIENT;
103 peers[1] = peer;
104 hosts[0] = host;
105
106 return OK;
107 }
108
109 Error ENetMultiplayerPeer::create_mesh(int p_id) {
110 ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0");
111 ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
112 active_mode = MODE_MESH;
113 unique_id = p_id;
114 connection_status = CONNECTION_CONNECTED;
115 return OK;
116 }
117
118 Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) {
119 ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER);
120 ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first.");
121 List<Ref<ENetPacketPeer>> host_peers;
122 p_host->get_peers(host_peers);
123 ERR_FAIL_COND_V_MSG(host_peers.size() != 1 || host_peers.front()->get()->get_state() != ENetPacketPeer::STATE_CONNECTED, ERR_INVALID_PARAMETER, "The provided host must have exactly one peer in the connected state.");
124 hosts[p_id] = p_host;
125 peers[p_id] = host_peers.front()->get();
126 emit_signal(SNAME("peer_connected"), p_id);
127 return OK;
128 }
129
130 void ENetMultiplayerPeer::_store_packet(int32_t p_source, ENetConnection::Event &p_event) {
131 Packet packet;
132 packet.packet = p_event.packet;
133 packet.channel = p_event.channel_id;
134 packet.from = p_source;
135 if (p_event.packet->flags & ENET_PACKET_FLAG_RELIABLE) {
136 packet.transfer_mode = TRANSFER_MODE_RELIABLE;
137 } else if (p_event.packet->flags & ENET_PACKET_FLAG_UNSEQUENCED) {
138 packet.transfer_mode = TRANSFER_MODE_UNRELIABLE;
139 } else {
140 packet.transfer_mode = TRANSFER_MODE_UNRELIABLE_ORDERED;
141 }
142 packet.packet->referenceCount++;
143 incoming_packets.push_back(packet);
144 }
145
146 void ENetMultiplayerPeer::_disconnect_inactive_peers() {
147 HashSet<int> to_drop;
148 for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
149 if (E.value->is_active()) {
150 continue;
151 }
152 to_drop.insert(E.key);
153 }
154 for (const int &P : to_drop) {
155 peers.erase(P);
156 if (hosts.has(P)) {
157 hosts.erase(P);
158 }
159 ERR_CONTINUE(active_mode == MODE_CLIENT && P != TARGET_PEER_SERVER);
160 emit_signal(SNAME("peer_disconnected"), P);
161 }
162 }
163
164 void ENetMultiplayerPeer::poll() {
165 ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active.");
166
167 _pop_current_packet();
168
169 _disconnect_inactive_peers();
170
171 switch (active_mode) {
172 case MODE_CLIENT: {
173 if (!peers.has(1)) {
174 close();
175 return;
176 }
177 ENetConnection::Event event;
178 ENetConnection::EventType ret = hosts[0]->service(0, event);
179 do {
180 if (ret == ENetConnection::EVENT_CONNECT) {
181 connection_status = CONNECTION_CONNECTED;
182 emit_signal(SNAME("peer_connected"), 1);
183 } else if (ret == ENetConnection::EVENT_DISCONNECT) {
184 if (connection_status == CONNECTION_CONNECTED) {
185 // Client just disconnected from server.
186 emit_signal(SNAME("peer_disconnected"), 1);
187 }
188 close();
189 } else if (ret == ENetConnection::EVENT_RECEIVE) {
190 _store_packet(1, event);
191 } else if (ret != ENetConnection::EVENT_NONE) {
192 close(); // Error.
193 }
194 } while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0);
195 } break;
196 case MODE_SERVER: {
197 ENetConnection::Event event;
198 ENetConnection::EventType ret = hosts[0]->service(0, event);
199 do {
200 if (ret == ENetConnection::EVENT_CONNECT) {
201 if (is_refusing_new_connections()) {
202 event.peer->reset();
203 continue;
204 }
205 // Client joined with invalid ID, probably trying to exploit us.
206 if (event.data < 2 || peers.has((int)event.data)) {
207 event.peer->reset();
208 continue;
209 }
210 int id = event.data;
211 event.peer->set_meta(SNAME("_net_id"), id);
212 peers[id] = event.peer;
213 emit_signal(SNAME("peer_connected"), id);
214 } else if (ret == ENetConnection::EVENT_DISCONNECT) {
215 int id = event.peer->get_meta(SNAME("_net_id"));
216 if (!peers.has(id)) {
217 // Never fully connected.
218 continue;
219 }
220 emit_signal(SNAME("peer_disconnected"), id);
221 peers.erase(id);
222 } else if (ret == ENetConnection::EVENT_RECEIVE) {
223 int32_t source = event.peer->get_meta(SNAME("_net_id"));
224 _store_packet(source, event);
225 } else if (ret != ENetConnection::EVENT_NONE) {
226 close(); // Error
227 }
228 } while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0);
229 } break;
230 case MODE_MESH: {
231 HashSet<int> to_drop;
232 for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
233 ENetConnection::Event event;
234 ENetConnection::EventType ret = E.value->service(0, event);
235 do {
236 if (ret == ENetConnection::EVENT_CONNECT) {
237 event.peer->reset();
238 } else if (ret == ENetConnection::EVENT_RECEIVE) {
239 _store_packet(E.key, event);
240 } else if (ret == ENetConnection::EVENT_NONE) {
241 break; // Keep polling the others.
242 } else {
243 to_drop.insert(E.key); // Error or disconnect.
244 break; // Keep polling the others.
245 }
246 } while (E.value->check_events(ret, event) > 0);
247 }
248 for (const int &P : to_drop) {
249 if (peers.has(P)) {
250 emit_signal(SNAME("peer_disconnected"), P);
251 peers.erase(P);
252 }
253 hosts.erase(P);
254 }
255 } break;
256 default:
257 return;
258 }
259 }
260
261 bool ENetMultiplayerPeer::is_server() const {
262 return active_mode == MODE_SERVER;
263 }
264
265 bool ENetMultiplayerPeer::is_server_relay_supported() const {
266 return active_mode == MODE_SERVER || active_mode == MODE_CLIENT;
267 }
268
269 void ENetMultiplayerPeer::disconnect_peer(int p_peer, bool p_force) {
270 ERR_FAIL_COND(!_is_active() || !peers.has(p_peer));
271 peers[p_peer]->peer_disconnect(0); // Will be removed during next poll.
272 if (active_mode == MODE_CLIENT || active_mode == MODE_SERVER) {
273 hosts[0]->flush();
274 } else {
275 ERR_FAIL_COND(!hosts.has(p_peer));
276 hosts[p_peer]->flush();
277 }
278 if (p_force) {
279 peers.erase(p_peer);
280 if (hosts.has(p_peer)) {
281 hosts.erase(p_peer);
282 }
283 if (active_mode == MODE_CLIENT) {
284 hosts.clear(); // Avoid flushing again.
285 close();
286 }
287 }
288 }
289
290 void ENetMultiplayerPeer::close() {
291 if (!_is_active()) {
292 return;
293 }
294
295 _pop_current_packet();
296
297 for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
298 if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) {
299 E.value->peer_disconnect_now(0);
300 }
301 }
302 for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
303 E.value->flush();
304 E.value->destroy();
305 }
306
307 active_mode = MODE_NONE;
308 incoming_packets.clear();
309 peers.clear();
310 hosts.clear();
311 unique_id = 0;
312 connection_status = CONNECTION_DISCONNECTED;
313 set_refuse_new_connections(false);
314 }
315
316 int ENetMultiplayerPeer::get_available_packet_count() const {
317 return incoming_packets.size();
318 }
319
320 Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
321 ERR_FAIL_COND_V_MSG(incoming_packets.is_empty(), ERR_UNAVAILABLE, "No incoming packets available.");
322
323 _pop_current_packet();
324
325 current_packet = incoming_packets.front()->get();
326 incoming_packets.pop_front();
327
328 *r_buffer = (const uint8_t *)(current_packet.packet->data);
329 r_buffer_size = current_packet.packet->dataLength;
330
331 return OK;
332 }
333
334 Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
335 ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");
336 ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");
337 ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(Math::abs(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));
338 ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG);
339
340 int packet_flags = 0;
341 int channel = SYSCH_RELIABLE;
342 int tr_channel = get_transfer_channel();
343 switch (get_transfer_mode()) {
344 case TRANSFER_MODE_UNRELIABLE: {
345 packet_flags = ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
346 channel = SYSCH_UNRELIABLE;
347 } break;
348 case TRANSFER_MODE_UNRELIABLE_ORDERED: {
349 packet_flags = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
350 channel = SYSCH_UNRELIABLE;
351 } break;
352 case TRANSFER_MODE_RELIABLE: {
353 packet_flags = ENET_PACKET_FLAG_RELIABLE;
354 channel = SYSCH_RELIABLE;
355 } break;
356 }
357 if (tr_channel > 0) {
358 channel = SYSCH_MAX + tr_channel - 1;
359 }
360
361 #ifdef DEBUG_ENABLED
362 if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size > ENET_HOST_DEFAULT_MTU) {
363 WARN_PRINT_ONCE(vformat("Sending %d bytes unreliably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size, ENET_HOST_DEFAULT_MTU));
364 }
365 #endif
366
367 ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size, packet_flags);
368 memcpy(&packet->data[0], p_buffer, p_buffer_size);
369
370 if (is_server()) {
371 if (target_peer == 0) {
372 hosts[0]->broadcast(channel, packet);
373
374 } else if (target_peer < 0) {
375 // Send to all but one and make copies for sending.
376 int exclude = -target_peer;
377 for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
378 if (E.key == exclude) {
379 continue;
380 }
381 E.value->send(channel, packet);
382 }
383 _destroy_unused(packet);
384 } else {
385 peers[target_peer]->send(channel, packet);
386 }
387 ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
388 hosts[0]->flush();
389
390 } else if (active_mode == MODE_CLIENT) {
391 peers[1]->send(channel, packet); // Send to server for broadcast.
392 ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
393 hosts[0]->flush();
394
395 } else {
396 if (target_peer <= 0) {
397 int exclude = Math::abs(target_peer);
398 for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
399 if (E.key == exclude) {
400 continue;
401 }
402 E.value->send(channel, packet);
403 ERR_CONTINUE(!hosts.has(E.key));
404 hosts[E.key]->flush();
405 }
406 _destroy_unused(packet);
407 } else {
408 peers[target_peer]->send(channel, packet);
409 ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG);
410 hosts[target_peer]->flush();
411 }
412 }
413
414 return OK;
415 }
416
417 int ENetMultiplayerPeer::get_max_packet_size() const {
418 return 1 << 24; // Anything is good
419 }
420
421 void ENetMultiplayerPeer::_pop_current_packet() {
422 if (current_packet.packet) {
423 current_packet.packet->referenceCount--;
424 _destroy_unused(current_packet.packet);
425 current_packet.packet = nullptr;
426 current_packet.from = 0;
427 current_packet.channel = -1;
428 }
429 }
430
431 MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const {
432 return connection_status;
433 }
434
435 int ENetMultiplayerPeer::get_unique_id() const {
436 ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active.");
437 return unique_id;
438 }
439
440 void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) {
441 #ifdef GODOT_ENET
442 if (_is_active()) {
443 for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
444 E.value->refuse_new_connections(p_enabled);
445 }
446 }
447 #endif
448 MultiplayerPeer::set_refuse_new_connections(p_enabled);
449 }
450
451 Ref<ENetConnection> ENetMultiplayerPeer::get_host() const {
452 ERR_FAIL_COND_V(!_is_active(), nullptr);
453 ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr);
454 return hosts[0];
455 }
456
457 Ref<ENetPacketPeer> ENetMultiplayerPeer::get_peer(int p_id) const {
458 ERR_FAIL_COND_V(!_is_active(), nullptr);
459 ERR_FAIL_COND_V(!peers.has(p_id), nullptr);
460 ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr);
461 return peers[p_id];
462 }
463
464 void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) {
465 if (p_packet->referenceCount == 0) {
466 enet_packet_destroy(p_packet);
467 }
468 }
469
470 void ENetMultiplayerPeer::_bind_methods() {
471 ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
472 ClassDB::bind_method(D_METHOD("create_client", "address", "port", "channel_count", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0), DEFVAL(0));
473 ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh);
474 ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer);
475 ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip);
476
477 ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host);
478 ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer);
479
480 ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host");
481 }
482
483 ENetMultiplayerPeer::ENetMultiplayerPeer() {
484 bind_ip = IPAddress("*");
485 }
486
487 ENetMultiplayerPeer::~ENetMultiplayerPeer() {
488 if (_is_active()) {
489 close();
490 }
491 }
492
493 // Sets IP for ENet to bind when using create_server or create_client
494 // if no IP is set, then ENet bind to ENET_HOST_ANY
495 void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) {
496 ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip)));
497
498 bind_ip = p_ip;
499 }