summaryrefslogtreecommitdiff
path: root/modules/enet/networked_multiplayer_enet.cpp
blob: 193f1bb48d9b7db0daebed13d38ec894bc0aeb9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
/*************************************************************************/
/*  networked_multiplayer_enet.cpp                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "networked_multiplayer_enet.h"
#include "core/io/ip.h"
#include "core/io/marshalls.h"
#include "core/os/os.h"

void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {

	transfer_mode = p_mode;
}
NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const {

	return transfer_mode;
}

void NetworkedMultiplayerENet::set_target_peer(int p_peer) {

	target_peer = p_peer;
}

int NetworkedMultiplayerENet::get_packet_peer() const {

	ERR_FAIL_COND_V(!active, 1);
	ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);

	return incoming_packets.front()->get().from;
}

int NetworkedMultiplayerENet::get_packet_channel() const {

	ERR_FAIL_COND_V(!active, -1);
	ERR_FAIL_COND_V(incoming_packets.size() == 0, -1);

	return incoming_packets.front()->get().channel;
}

int NetworkedMultiplayerENet::get_last_packet_channel() const {

	ERR_FAIL_COND_V(!active, -1);
	ERR_FAIL_COND_V(!current_packet.packet, -1);

	return current_packet.channel;
}

Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) {

	ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
	ERR_FAIL_COND_V(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(p_max_clients < 0, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(p_in_bandwidth < 0, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);

	ENetAddress address;

#ifdef GODOT_ENET
	if (bind_ip.is_wildcard()) {
		address.wildcard = 1;
	} else {
		enet_address_set_ip(&address, bind_ip.get_ipv6(), 16);
	}
#else
	if (bind_ip.is_wildcard()) {
		address.host = 0;
	} else {
		ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
		address.host = *(uint32_t *)bind_ip.get_ipv4();
	}
#endif
	address.port = p_port;

	host = enet_host_create(&address /* the address to bind the server host to */,
			p_max_clients /* allow up to 32 clients and/or outgoing connections */,
			channel_count /* allow up to channel_count to be used */,
			p_in_bandwidth /* limit incoming bandwidth if > 0 */,
			p_out_bandwidth /* limit outgoing bandwidth if > 0 */);

	ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);

	_setup_compressor();
	active = true;
	server = true;
	refuse_connections = false;
	unique_id = 1;
	connection_status = CONNECTION_CONNECTED;
	return OK;
}
Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_client_port) {

	ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
	ERR_FAIL_COND_V(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(p_client_port < 0 || p_client_port > 65535, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(p_in_bandwidth < 0, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);

	if (p_client_port != 0) {
		ENetAddress c_client;

#ifdef GODOT_ENET
		if (bind_ip.is_wildcard()) {
			c_client.wildcard = 1;
		} else {
			enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16);
		}
#else
		if (bind_ip.is_wildcard()) {
			c_client.host = 0;
		} else {
			ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
			c_client.host = *(uint32_t *)bind_ip.get_ipv4();
		}
#endif

		c_client.port = p_client_port;

		host = enet_host_create(&c_client /* create a client host */,
				1 /* only allow 1 outgoing connection */,
				channel_count /* allow up to channel_count to be used */,
				p_in_bandwidth /* limit incoming bandwidth if > 0 */,
				p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
	} else {
		host = enet_host_create(NULL /* create a client host */,
				1 /* only allow 1 outgoing connection */,
				channel_count /* allow up to channel_count to be used */,
				p_in_bandwidth /* limit incoming bandwidth if > 0 */,
				p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
	}

	ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);

	_setup_compressor();

	IP_Address ip;
	if (p_address.is_valid_ip_address()) {
		ip = p_address;
	} else {
#ifdef GODOT_ENET
		ip = IP::get_singleton()->resolve_hostname(p_address);
#else
		ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
#endif

		ERR_FAIL_COND_V(!ip.is_valid(), ERR_CANT_RESOLVE);
	}

	ENetAddress address;
#ifdef GODOT_ENET
	enet_address_set_ip(&address, ip.get_ipv6(), 16);
#else
	ERR_FAIL_COND_V(!ip.is_ipv4(), ERR_INVALID_PARAMETER);
	address.host = *(uint32_t *)ip.get_ipv4();
#endif
	address.port = p_port;

	unique_id = _gen_unique_id();

	// Initiate connection, allocating enough channels
	ENetPeer *peer = enet_host_connect(host, &address, channel_count, unique_id);

	if (peer == NULL) {
		enet_host_destroy(host);
		ERR_FAIL_COND_V(!peer, ERR_CANT_CREATE);
	}

	// Technically safe to ignore the peer or anything else.

	connection_status = CONNECTION_CONNECTING;
	active = true;
	server = false;
	refuse_connections = false;

	return OK;
}

void NetworkedMultiplayerENet::poll() {

	ERR_FAIL_COND(!active);

	_pop_current_packet();

	ENetEvent event;
	/* Keep servicing until there are no available events left in queue. */
	while (true) {

		if (!host || !active) // Might have been disconnected while emitting a notification
			return;

		int ret = enet_host_service(host, &event, 0);

		if (ret < 0) {
			// Error, do something?
			break;
		} else if (ret == 0) {
			break;
		}

		switch (event.type) {
			case ENET_EVENT_TYPE_CONNECT: {
				// Store any relevant client information here.

				if (server && refuse_connections) {
					enet_peer_reset(event.peer);
					break;
				}

				// A client joined with an invalid ID (neagtive values, 0, and 1 are reserved).
				// Probably trying to exploit us.
				if (server && ((int)event.data < 2 || peer_map.has((int)event.data))) {
					enet_peer_reset(event.peer);
					ERR_CONTINUE(true);
				}

				int *new_id = memnew(int);
				*new_id = event.data;

				if (*new_id == 0) { // Data zero is sent by server (enet won't let you configure this). Server is always 1.
					*new_id = 1;
				}

				event.peer->data = new_id;

				peer_map[*new_id] = event.peer;

				connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something!

				emit_signal("peer_connected", *new_id);

				if (server) {
					// Someone connected, notify all the peers available
					for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {

						if (E->key() == *new_id)
							continue;
						// Send existing peers to new peer
						ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
						encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
						encode_uint32(E->key(), &packet->data[4]);
						enet_peer_send(event.peer, SYSCH_CONFIG, packet);
						// Send the new peer to existing peers
						packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
						encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
						encode_uint32(*new_id, &packet->data[4]);
						enet_peer_send(E->get(), SYSCH_CONFIG, packet);
					}
				} else {

					emit_signal("connection_succeeded");
				}

			} break;
			case ENET_EVENT_TYPE_DISCONNECT: {

				// Reset the peer's client information.

				int *id = (int *)event.peer->data;

				if (!id) {
					if (!server) {
						emit_signal("connection_failed");
					}
				} else {

					if (server) {
						// Someone disconnected, notify everyone else
						for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {

							if (E->key() == *id)
								continue;

							ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
							encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
							encode_uint32(*id, &packet->data[4]);
							enet_peer_send(E->get(), SYSCH_CONFIG, packet);
						}
					} else {
						emit_signal("server_disconnected");
						close_connection();
						return;
					}

					emit_signal("peer_disconnected", *id);
					peer_map.erase(*id);
					memdelete(id);
				}

			} break;
			case ENET_EVENT_TYPE_RECEIVE: {

				if (event.channelID == SYSCH_CONFIG) {
					// Some config message
					ERR_CONTINUE(event.packet->dataLength < 8);

					// Only server can send config messages
					ERR_CONTINUE(server);

					int msg = decode_uint32(&event.packet->data[0]);
					int id = decode_uint32(&event.packet->data[4]);

					switch (msg) {
						case SYSMSG_ADD_PEER: {

							peer_map[id] = NULL;
							emit_signal("peer_connected", id);

						} break;
						case SYSMSG_REMOVE_PEER: {

							peer_map.erase(id);
							emit_signal("peer_disconnected", id);
						} break;
					}

					enet_packet_destroy(event.packet);
				} else if (event.channelID < channel_count) {

					Packet packet;
					packet.packet = event.packet;

					uint32_t *id = (uint32_t *)event.peer->data;

					ERR_CONTINUE(event.packet->dataLength < 12)

					uint32_t source = decode_uint32(&event.packet->data[0]);
					int target = decode_uint32(&event.packet->data[4]);
					uint32_t flags = decode_uint32(&event.packet->data[8]);

					packet.from = source;
					packet.channel = event.channelID;

					if (server) {
						// Someone is cheating and trying to fake the source!
						ERR_CONTINUE(source != *id);

						packet.from = *id;

						if (target == 0) {
							// Re-send to everyone but sender :|

							incoming_packets.push_back(packet);
							// And make copies for sending
							for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {

								if (uint32_t(E->key()) == source) // Do not resend to self
									continue;

								ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);

								enet_peer_send(E->get(), event.channelID, packet2);
							}

						} else if (target < 0) {
							// To all but one

							// And make copies for sending
							for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {

								if (uint32_t(E->key()) == source || E->key() == -target) // Do not resend to self, also do not send to excluded
									continue;

								ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);

								enet_peer_send(E->get(), event.channelID, packet2);
							}

							if (-target != 1) {
								// Server is not excluded
								incoming_packets.push_back(packet);
							} else {
								// Server is excluded, erase packet
								enet_packet_destroy(packet.packet);
							}

						} else if (target == 1) {
							// To myself and only myself
							incoming_packets.push_back(packet);
						} else {
							// To someone else, specifically
							ERR_CONTINUE(!peer_map.has(target));
							enet_peer_send(peer_map[target], event.channelID, packet.packet);
						}
					} else {

						incoming_packets.push_back(packet);
					}

					// Destroy packet later
				} else {
					ERR_CONTINUE(true);
				}

			} break;
			case ENET_EVENT_TYPE_NONE: {
				// Do nothing
			} break;
		}
	}
}

bool NetworkedMultiplayerENet::is_server() const {
	ERR_FAIL_COND_V(!active, false);

	return server;
}

void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) {

	ERR_FAIL_COND(!active);

	_pop_current_packet();

	bool peers_disconnected = false;
	for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
		if (E->get()) {
			enet_peer_disconnect_now(E->get(), unique_id);
			peers_disconnected = true;
		}
	}

	if (peers_disconnected) {
		enet_host_flush(host);

		if (wait_usec > 0) {
			OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send
		}
	}

	enet_host_destroy(host);
	active = false;
	incoming_packets.clear();
	unique_id = 1; // Server is 1
	connection_status = CONNECTION_DISCONNECTED;
}

void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {

	ERR_FAIL_COND(!active);
	ERR_FAIL_COND(!is_server());
	ERR_FAIL_COND(!peer_map.has(p_peer))

	if (now) {
		enet_peer_disconnect_now(peer_map[p_peer], 0);

		// enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT,
		// notify everyone else, send disconnect signal & remove from peer_map like in poll()

		for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {

			if (E->key() == p_peer)
				continue;

			ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
			encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
			encode_uint32(p_peer, &packet->data[4]);
			enet_peer_send(E->get(), SYSCH_CONFIG, packet);
		}

		emit_signal("peer_disconnected", p_peer);
		peer_map.erase(p_peer);
	} else {
		enet_peer_disconnect_later(peer_map[p_peer], 0);
	}
}

int NetworkedMultiplayerENet::get_available_packet_count() const {

	return incoming_packets.size();
}

Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {

	ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);

	_pop_current_packet();

	current_packet = incoming_packets.front()->get();
	incoming_packets.pop_front();

	*r_buffer = (const uint8_t *)(&current_packet.packet->data[12]);
	r_buffer_size = current_packet.packet->dataLength - 12;

	return OK;
}

Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {

	ERR_FAIL_COND_V(!active, ERR_UNCONFIGURED);
	ERR_FAIL_COND_V(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED);

	int packet_flags = 0;
	int channel = SYSCH_RELIABLE;

	switch (transfer_mode) {
		case TRANSFER_MODE_UNRELIABLE: {
			if (always_ordered)
				packet_flags = 0;
			else
				packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
			channel = SYSCH_UNRELIABLE;
		} break;
		case TRANSFER_MODE_UNRELIABLE_ORDERED: {
			packet_flags = 0;
			channel = SYSCH_UNRELIABLE;
		} break;
		case TRANSFER_MODE_RELIABLE: {
			packet_flags = ENET_PACKET_FLAG_RELIABLE;
			channel = SYSCH_RELIABLE;
		} break;
	}

	if (transfer_channel > SYSCH_CONFIG)
		channel = transfer_channel;

	Map<int, ENetPeer *>::Element *E = NULL;

	if (target_peer != 0) {

		E = peer_map.find(ABS(target_peer));
		if (!E) {
			ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
			ERR_FAIL_V(ERR_INVALID_PARAMETER);
		}
	}

	ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 12, packet_flags);
	encode_uint32(unique_id, &packet->data[0]); // Source ID
	encode_uint32(target_peer, &packet->data[4]); // Dest ID
	encode_uint32(packet_flags, &packet->data[8]); // Dest ID
	copymem(&packet->data[12], p_buffer, p_buffer_size);

	if (server) {

		if (target_peer == 0) {
			enet_host_broadcast(host, channel, packet);
		} else if (target_peer < 0) {
			// Send to all but one
			// and make copies for sending

			int exclude = -target_peer;

			for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) {

				if (F->key() == exclude) // Exclude packet
					continue;

				ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);

				enet_peer_send(F->get(), channel, packet2);
			}

			enet_packet_destroy(packet); // Original packet no longer needed
		} else {
			enet_peer_send(E->get(), channel, packet);
		}
	} else {

		ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
		enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast
	}

	enet_host_flush(host);

	return OK;
}

int NetworkedMultiplayerENet::get_max_packet_size() const {

	return 1 << 24; // Anything is good
}

void NetworkedMultiplayerENet::_pop_current_packet() {

	if (current_packet.packet) {
		enet_packet_destroy(current_packet.packet);
		current_packet.packet = NULL;
		current_packet.from = 0;
		current_packet.channel = -1;
	}
}

NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {

	return connection_status;
}

uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {

	uint32_t hash = 0;

	while (hash == 0 || hash == 1) {

		hash = hash_djb2_one_32(
				(uint32_t)OS::get_singleton()->get_ticks_usec());
		hash = hash_djb2_one_32(
				(uint32_t)OS::get_singleton()->get_unix_time(), hash);
		hash = hash_djb2_one_32(
				(uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
		hash = hash_djb2_one_32(
				(uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
		hash = hash_djb2_one_32(
				(uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack

		hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
	}

	return hash;
}

int NetworkedMultiplayerENet::get_unique_id() const {

	ERR_FAIL_COND_V(!active, 0);
	return unique_id;
}

void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {

	refuse_connections = p_enable;
}

bool NetworkedMultiplayerENet::is_refusing_new_connections() const {

	return refuse_connections;
}

void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {

	compression_mode = p_mode;
}

NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const {

	return compression_mode;
}

size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {

	NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);

	if (size_t(enet->src_compressor_mem.size()) < inLimit) {
		enet->src_compressor_mem.resize(inLimit);
	}

	int total = inLimit;
	int ofs = 0;
	while (total) {
		for (size_t i = 0; i < inBufferCount; i++) {
			int to_copy = MIN(total, int(inBuffers[i].dataLength));
			copymem(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy);
			ofs += to_copy;
			total -= to_copy;
		}
	}

	Compression::Mode mode;

	switch (enet->compression_mode) {
		case COMPRESS_FASTLZ: {
			mode = Compression::MODE_FASTLZ;
		} break;
		case COMPRESS_ZLIB: {
			mode = Compression::MODE_DEFLATE;
		} break;
		case COMPRESS_ZSTD: {
			mode = Compression::MODE_ZSTD;
		} break;
		default: {
			ERR_FAIL_V(0);
		}
	}

	int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
	if (enet->dst_compressor_mem.size() < req_size) {
		enet->dst_compressor_mem.resize(req_size);
	}
	int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode);

	if (ret < 0)
		return 0;

	if (ret > int(outLimit))
		return 0; // Do not bother

	copymem(outData, enet->dst_compressor_mem.ptr(), ret);

	return ret;
}

size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {

	NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
	int ret = -1;
	switch (enet->compression_mode) {
		case COMPRESS_FASTLZ: {

			ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
		} break;
		case COMPRESS_ZLIB: {

			ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
		} break;
		case COMPRESS_ZSTD: {

			ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
		} break;
		default: {
		}
	}
	if (ret < 0) {
		return 0;
	} else {
		return ret;
	}
}

void NetworkedMultiplayerENet::_setup_compressor() {

	switch (compression_mode) {

		case COMPRESS_NONE: {

			enet_host_compress(host, NULL);
		} break;
		case COMPRESS_RANGE_CODER: {
			enet_host_compress_with_range_coder(host);
		} break;
		case COMPRESS_FASTLZ:
		case COMPRESS_ZLIB:
		case COMPRESS_ZSTD: {

			enet_host_compress(host, &enet_compressor);
		} break;
	}
}

void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {

	// Nothing to do
}

IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {

	ERR_FAIL_COND_V(!peer_map.has(p_peer_id), IP_Address());
	ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, IP_Address());
	ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, IP_Address());

	IP_Address out;
#ifdef GODOT_ENET
	out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host));
#else
	out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host));
#endif

	return out;
}

int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {

	ERR_FAIL_COND_V(!peer_map.has(p_peer_id), 0);
	ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, 0);
	ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, 0);
#ifdef GODOT_ENET
	return peer_map[p_peer_id]->address.port;
#else
	return peer_map[p_peer_id]->address.port;
#endif
}

void NetworkedMultiplayerENet::set_transfer_channel(int p_channel) {

	ERR_FAIL_COND(p_channel < -1 || p_channel >= channel_count);

	if (p_channel == SYSCH_CONFIG) {
		ERR_EXPLAIN("Channel " + itos(SYSCH_CONFIG) + " is reserved");
		ERR_FAIL();
	}
	transfer_channel = p_channel;
}

int NetworkedMultiplayerENet::get_transfer_channel() const {
	return transfer_channel;
}

void NetworkedMultiplayerENet::set_channel_count(int p_channel) {

	ERR_FAIL_COND(active);
	ERR_FAIL_COND(p_channel < SYSCH_MAX);
	channel_count = p_channel;
}

int NetworkedMultiplayerENet::get_channel_count() const {
	return channel_count;
}

void NetworkedMultiplayerENet::set_always_ordered(bool p_ordered) {
	always_ordered = p_ordered;
}

bool NetworkedMultiplayerENet::is_always_ordered() const {
	return always_ordered;
}

void NetworkedMultiplayerENet::_bind_methods() {

	ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0));
	ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "client_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0));
	ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100));
	ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false));
	ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode);
	ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode);
	ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip);
	ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &NetworkedMultiplayerENet::get_peer_address);
	ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &NetworkedMultiplayerENet::get_peer_port);

	ClassDB::bind_method(D_METHOD("get_packet_channel"), &NetworkedMultiplayerENet::get_packet_channel);
	ClassDB::bind_method(D_METHOD("get_last_packet_channel"), &NetworkedMultiplayerENet::get_last_packet_channel);
	ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &NetworkedMultiplayerENet::set_transfer_channel);
	ClassDB::bind_method(D_METHOD("get_transfer_channel"), &NetworkedMultiplayerENet::get_transfer_channel);
	ClassDB::bind_method(D_METHOD("set_channel_count", "channels"), &NetworkedMultiplayerENet::set_channel_count);
	ClassDB::bind_method(D_METHOD("get_channel_count"), &NetworkedMultiplayerENet::get_channel_count);
	ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &NetworkedMultiplayerENet::set_always_ordered);
	ClassDB::bind_method(D_METHOD("is_always_ordered"), &NetworkedMultiplayerENet::is_always_ordered);

	ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel"), "set_transfer_channel", "get_transfer_channel");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "channel_count"), "set_channel_count", "get_channel_count");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "always_ordered"), "set_always_ordered", "is_always_ordered");

	BIND_ENUM_CONSTANT(COMPRESS_NONE);
	BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
	BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
	BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
	BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
}

NetworkedMultiplayerENet::NetworkedMultiplayerENet() {

	active = false;
	server = false;
	refuse_connections = false;
	unique_id = 0;
	target_peer = 0;
	current_packet.packet = NULL;
	transfer_mode = TRANSFER_MODE_RELIABLE;
	channel_count = SYSCH_MAX;
	transfer_channel = -1;
	always_ordered = false;
	connection_status = CONNECTION_DISCONNECTED;
	compression_mode = COMPRESS_NONE;
	enet_compressor.context = this;
	enet_compressor.compress = enet_compress;
	enet_compressor.decompress = enet_decompress;
	enet_compressor.destroy = enet_compressor_destroy;

	bind_ip = IP_Address("*");
}

NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {

	close_connection();
}

// Sets IP for ENet to bind when using create_server or create_client
// if no IP is set, then ENet bind to ENET_HOST_ANY
void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) {
	ERR_FAIL_COND(!p_ip.is_valid() && !p_ip.is_wildcard());

	bind_ip = p_ip;
}