forked from dkfans/keeperfx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbflib_enet.cpp
More file actions
1016 lines (944 loc) · 37.8 KB
/
bflib_enet.cpp
File metadata and controls
1016 lines (944 loc) · 37.8 KB
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************/
// Free implementation of Bullfrog's Dungeon Keeper strategy game.
/******************************************************************************/
/**
* @author KeeperFX Team
* @date 18 Oct 2022
* @par Copying and copyrights:
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
/******************************************************************************/
#include "pre_inc.h"
#include "bflib_enet.h"
#include "bflib_datetm.h"
#include "net_main.h"
#include "front_network.h"
#include "bflib_math.h"
#include "net_portforward.h"
#include "net_holepunch.h"
#include "net_matchmaking.h"
#include "game_legacy.h"
#include "player_data.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#endif
#include <enet6/enet.h>
#include <cstddef>
#include <climits>
#include "post_inc.h"
#define NUM_CHANNELS 2
#define HOLEPUNCH_CONNECT_DELAY_MS 1000
#define HOLEPUNCH_PRE_CONNECT_DELAY_MS 500
#define HAPPY_EYEBALLS_DELAY_MS 250
#define JOIN_CONNECT_POLL_DELAY_MS 16
#define ENET_ADDRESS_BUFFER_SIZE 128
#define INCOMING_QUEUE_WARNING_THRESHOLD 200
#define INCOMING_QUEUE_WARNING_INTERVAL 100
uint16_t external_ipv4_port = 0;
int skip_holepunch = 0;
namespace
{
struct TransferRateTracker {
enet_uint32 sample_time;
unsigned int bytes_per_second;
};
NetDropCallback g_drop_callback = nullptr;
ENetHost *host = nullptr;
ENetPeer *client_peer = nullptr;
int host_is_dual_stack = 0;
TransferRateTracker download_rate_tracker = {0, 0};
TransferRateTracker upload_rate_tracker = {0, 0};
// List
ENetPacket *oldest_packet[MAX_NET_USERS] = {nullptr};
ENetPacket *newest_packet[MAX_NET_USERS] = {nullptr};
int incoming_queue_size = 0;
TbBool not_expected_user(NetUserId *);
unsigned int sample_transfer_bytes_per_second(TransferRateTracker *tracker, enet_uint32 *total)
{
enet_uint32 now = enet_time_get();
if (tracker->sample_time == 0) {
tracker->sample_time = now;
tracker->bytes_per_second = 0;
*total = 0;
return 0;
}
enet_uint32 elapsed = now - tracker->sample_time;
if (elapsed < 1000) {
return tracker->bytes_per_second;
}
tracker->bytes_per_second = static_cast<unsigned int>((static_cast<unsigned long long>(*total) * 1000ULL) / elapsed);
tracker->sample_time = now;
*total = 0;
return tracker->bytes_per_second;
}
void enqueue_incoming_packet(ENetPacket *packet, NetUserId source)
{
packet->userData = nullptr;
if (oldest_packet[source] == nullptr) {
newest_packet[source] = packet;
oldest_packet[source] = packet;
} else {
newest_packet[source]->userData = packet;
newest_packet[source] = packet;
}
incoming_queue_size += 1;
if (incoming_queue_size == INCOMING_QUEUE_WARNING_THRESHOLD) {
fprintf(stderr, "Too many packets %d\n", incoming_queue_size);
WARNLOG("Too many packets %d", incoming_queue_size);
} else if (incoming_queue_size > INCOMING_QUEUE_WARNING_THRESHOLD && (incoming_queue_size % INCOMING_QUEUE_WARNING_INTERVAL) == 0) {
fprintf(stderr, "Too many packets %d\n", incoming_queue_size);
WARNLOG("Too many packets %d", incoming_queue_size);
}
}
void destroy_incoming_queue(NetUserId source)
{
for (ENetPacket *packet = oldest_packet[source]; packet != nullptr;) {
ENetPacket *current_packet = packet;
packet = static_cast<ENetPacket *>(packet->userData);
enet_packet_destroy(current_packet);
incoming_queue_size -= 1;
}
oldest_packet[source] = nullptr;
newest_packet[source] = nullptr;
}
void destroy_incoming_queue()
{
for (NetUserId source = 0; source < MAX_NET_USERS; source++) {
destroy_incoming_queue(source);
}
}
ENetHost *create_ipv6_host(enet_uint16 port)
{
ENetAddress bind_address;
enet_address_build_any(&bind_address, ENET_ADDRESS_TYPE_IPV6);
bind_address.port = port;
return enet_host_create(ENET_ADDRESS_TYPE_IPV6, &bind_address, MAX_NET_PEERS, NUM_CHANNELS, 0, 0);
}
TbError bf_enet_init(NetDropCallback drop_callback)
{
if (enet_initialize())
return Lb_FAIL;
g_drop_callback = drop_callback;
return Lb_OK;
}
void host_destroy()
{
destroy_incoming_queue();
download_rate_tracker = TransferRateTracker();
upload_rate_tracker = TransferRateTracker();
client_peer = nullptr;
if (host)
{
for (ENetPeer *peer = host->peers; peer < &host->peers[host->peerCount]; peer++) {
if (peer->state == ENET_PEER_STATE_CONNECTED) {
enet_peer_disconnect(peer, 0);
}
}
enet_host_flush(host);
enet_host_destroy(host);
host = nullptr;
}
external_ipv4_port = 0;
host_is_dual_stack = 0;
}
void bf_enet_exit()
{
port_forward_remove_mapping();
host_destroy();
g_drop_callback = nullptr;
enet_deinitialize();
}
/**
* Sets this service provider up as a host for a new network game.
* @param session String representing the network game to be hosted.
* This could be a hostname:port pair for TCP for instance.
* @param options
* @return Lb_FAIL or Lb_OK
*/
TbError bf_enet_host(const char *session, void *)
{
if (!*session)
return Lb_FAIL;
const char *port_string = session;
if (*port_string == ':') port_string++;
int port = atoi(port_string);
enet_uint16 actual_port = ENET_DEFAULT_PORT;
if (port > 0)
actual_port = (enet_uint16)port;
ENetAddress address;
enet_address_build_any(&address, ENET_ADDRESS_TYPE_IPV6);
address.port = actual_port;
host = enet_host_create(ENET_ADDRESS_TYPE_ANY, &address, MAX_NET_PEERS, NUM_CHANNELS, 0, 0);
if (host) {
host_is_dual_stack = 1;
address = host->address;
LbNetLog("ENet: host created (dual-stack IPv4+IPv6) on port %d\n", (int)address.port);
} else {
LbNetLog("ENet: dual-stack host creation failed, falling back to IPv4-only\n");
enet_address_build_any(&address, ENET_ADDRESS_TYPE_IPV4);
address.port = actual_port;
host = enet_host_create(ENET_ADDRESS_TYPE_IPV4, &address, MAX_NET_PEERS, NUM_CHANNELS, 0, 0);
if (!host)
return Lb_FAIL;
host_is_dual_stack = 0;
address = host->address;
LbNetLog("ENet: host created (IPv4) on port %d\n", (int)address.port);
}
enet_host_compress_with_range_coder(host);
port_forward_add_mapping(address.port);
external_ipv4_port = holepunch_stun_query(host, NULL, 0);
return Lb_OK;
}
enet_uint16 parse_session_address(const char *session, char *output_hostname, size_t hostname_buffer_size)
{
enet_uint16 port = ENET_DEFAULT_PORT;
if (session[0] == '[') {
const char *bracket_end = strchr(session, ']');
if (!bracket_end) {
return 0;
}
size_t address_length = bracket_end - session - 1;
if (address_length >= hostname_buffer_size) {
return 0;
}
strncpy(output_hostname, session + 1, address_length);
output_hostname[address_length] = '\0';
if (bracket_end[1] == ':') {
port = strtoul(bracket_end + 2, NULL, 10);
if (port == 0) {
return 0;
}
}
} else {
const char *first_colon = strchr(session, ':');
const char *last_colon = strrchr(session, ':');
if (first_colon && first_colon != last_colon) {
strncpy(output_hostname, session, hostname_buffer_size - 1);
output_hostname[hostname_buffer_size - 1] = '\0';
} else if (first_colon) {
size_t address_length = first_colon - session;
if (address_length >= hostname_buffer_size) {
return 0;
}
strncpy(output_hostname, session, address_length);
output_hostname[address_length] = '\0';
port = strtoul(first_colon + 1, NULL, 10);
if (port == 0) {
return 0;
}
} else {
strncpy(output_hostname, session, hostname_buffer_size - 1);
output_hostname[hostname_buffer_size - 1] = '\0';
}
}
return port;
}
int resolve_punch_address(const char *address_string, ENetAddressType type, int port, ENetAddress *output)
{
if (!address_string[0]) return 0;
if (enet_address_set_host(output, type, address_string) < 0) return 0;
output->port = (enet_uint16)port;
return 1;
}
void cleanup_join_host(ENetHost *network_host, ENetPeer *peer) {
if (!network_host)
return;
if (network_host == host) {
host_destroy();
return;
}
if (peer) {
enet_peer_disconnect_now(peer, 0);
enet_host_flush(network_host);
}
enet_host_destroy(network_host);
}
TbError finish_join(ENetHost *next_host, ENetPeer *next_peer, ENetHost *old_host, ENetPeer *old_peer,
const char *join_type, const char *ip_version) {
LbNetLog("Join: connected successfully via %s (%s)\n", join_type, ip_version);
enet_peer_timeout(next_peer, PEER_TIMEOUT_LIMIT, PEER_TIMEOUT_MIN_MS, PEER_TIMEOUT_MAX_MS);
cleanup_join_host(old_host, old_peer);
host = next_host;
client_peer = next_peer;
return Lb_OK;
}
TbError create_join_host(ENetAddressType address_type)
{
host_destroy();
host = enet_host_create(address_type, NULL, MAX_NET_PEERS, NUM_CHANNELS, 0, 0);
if (!host) {
LbNetLog("Join: failed to create ENet host\n");
return Lb_FAIL;
}
return Lb_OK;
}
TbError connect_to_current_join_host(const ENetAddress *connect_address, const char *join_type,
TbClockMSec display_deadline, TbClockMSec timeout_ms)
{
if (timeout_ms <= 0)
return Lb_FAIL;
enet_host_compress_with_range_coder(host);
client_peer = enet_host_connect(host, connect_address, NUM_CHANNELS, 0);
if (!client_peer) {
LbNetLog("Join: enet_host_connect returned NULL\n");
host_destroy();
return Lb_FAIL;
}
ENetEvent enet_event;
TbClockMSec connection_deadline = LbTimerClock() + timeout_ms;
while (LbTimerClock() < connection_deadline) {
int service_result = enet_host_service(host, &enet_event, 0);
if (service_result > 0 && enet_event.type == ENET_EVENT_TYPE_CONNECT) {
LbNetLog("Join: connected successfully via %s\n", join_type);
enet_peer_timeout(client_peer, PEER_TIMEOUT_LIMIT, PEER_TIMEOUT_MIN_MS, PEER_TIMEOUT_MAX_MS);
return Lb_OK;
}
if (service_result > 0 && (enet_event.type == ENET_EVENT_TYPE_DISCONNECT || enet_event.type == ENET_EVENT_TYPE_DISCONNECT_TIMEOUT)) {
LbNetLog("Join: connection rejected by host\n");
break;
}
if (service_result > 0) {
LbNetLog("Join: unexpected event type=%d\n", (int)enet_event.type);
} else if (service_result < 0) {
LbNetLog("Join: enet_host_service error %d\n", service_result);
ERRORLOG("Unable to connect: %d", service_result);
break;
}
TbClockMSec time_remaining = connection_deadline - LbTimerClock();
if (time_remaining <= 0)
break;
enet_uint32 wait_ms = (enet_uint32)min((TbClockMSec)JOIN_CONNECT_POLL_DELAY_MS, time_remaining);
SDL_Delay(wait_ms);
display_attempting_to_join_message((int)((display_deadline - LbTimerClock()) / 1000));
if (attempting_to_join_cancel_requested()) {
LbNetLog("Join: cancelled by user\n");
host_destroy();
return Lb_FAIL;
}
}
LbNetLog("Join: connection timed out or failed\n");
host_destroy();
return Lb_FAIL;
}
TbError join_direct_session(const char *session, TbClockMSec display_deadline, TbClockMSec timeout_ms, const char *join_label)
{
ENetAddress connect_address;
char address_string[ENET_ADDRESS_BUFFER_SIZE] = {0};
enet_uint16 port = parse_session_address(session, address_string, sizeof(address_string));
if (port == 0 || address_string[0] == '\0')
return Lb_FAIL;
ENetAddressType connect_type = ENET_ADDRESS_TYPE_IPV4;
const char *ip_version = "IPv4";
if (strchr(address_string, ':') != NULL) {
connect_type = ENET_ADDRESS_TYPE_IPV6;
ip_version = "IPv6";
}
char join_type[64];
snprintf(join_type, sizeof(join_type), "%s (%s)", join_label, ip_version);
LbNetLog("Join: connecting via %s\n", join_type);
if (enet_address_set_host(&connect_address, connect_type, address_string) < 0)
return Lb_FAIL;
connect_address.port = port;
if (create_join_host(connect_type) != Lb_OK)
return Lb_FAIL;
TbClockMSec stage_start = LbTimerClock();
TbError result = connect_to_current_join_host(&connect_address, join_type, display_deadline, timeout_ms);
const char *stage_name = (connect_type == ENET_ADDRESS_TYPE_IPV6) ? "TIMEOUT_CONNECT_DIRECT_IPV6" : "TIMEOUT_CONNECT_DIRECT_IPV4";
LbNetLog("Join: %s took %d ms (%s)\n", stage_name, (int)(LbTimerClock() - stage_start), result == Lb_OK ? "connected" : "failed");
return result;
}
TbError join_direct_fallback(const PunchAddresses *punch_addresses, TbClockMSec display_deadline) {
const int has_ipv4 = (punch_addresses->ipv4[0] != '\0');
const int has_ipv6 = (punch_addresses->ipv6[0] != '\0');
if (!has_ipv4 && !has_ipv6) {
LbNetLog("Join: direct-connect fallback has no usable address\n");
return Lb_FAIL;
}
LbNetLog("Join: hole-punch phase timed out, retrying via direct connect\n");
char session[ENET_ADDRESS_BUFFER_SIZE];
if (has_ipv6) {
snprintf(session, sizeof(session), "[%s]:%d", punch_addresses->ipv6, ENET_DEFAULT_PORT);
if (join_direct_session(session, display_deadline, TIMEOUT_CONNECT_DIRECT_IPV6, "direct connect fallback") == Lb_OK)
return Lb_OK;
}
if (!has_ipv4)
return Lb_FAIL;
snprintf(session, sizeof(session), "%s:%d", punch_addresses->ipv4, ENET_DEFAULT_PORT);
return join_direct_session(session, display_deadline, TIMEOUT_CONNECT_DIRECT_IPV4, "direct connect fallback");
}
TbError join_via_holepunch(TbClockMSec join_start_ms) {
LbNetLog("Join: connecting via matchmaking server (UDP hole punching)\n");
if (create_join_host(ENET_ADDRESS_TYPE_IPV4) != Lb_OK)
return Lb_FAIL;
uint16_t my_external_ipv4_port = holepunch_stun_query(host, NULL, 0);
if (my_external_ipv4_port == 0)
LbNetLog("Join: STUN failed, proceeding with port 0\n");
ENetHost *ipv6_host = create_ipv6_host(ENET_PORT_ANY);
int my_ipv6_port = 0;
if (ipv6_host) {
enet_host_compress_with_range_coder(ipv6_host);
my_ipv6_port = (int)ipv6_host->address.port;
}
PunchAddresses punch_addresses;
if (matchmaking_punch(join_lobby_id, (int)my_external_ipv4_port, my_ipv6_port, &punch_addresses) != 0) {
LbNetLog("Join: matchmaking_punch failed\n");
cleanup_join_host(ipv6_host, nullptr);
host_destroy();
return Lb_FAIL;
}
ENetAddress ipv4_address = {};
ENetAddress ipv6_address = {};
int has_ipv4 = resolve_punch_address(punch_addresses.ipv4, ENET_ADDRESS_TYPE_IPV4, punch_addresses.ipv4_port, &ipv4_address);
int has_ipv6 = (ipv6_host != nullptr) && resolve_punch_address(punch_addresses.ipv6, ENET_ADDRESS_TYPE_IPV6, punch_addresses.ipv6_port, &ipv6_address);
if (!has_ipv4 && !has_ipv6) {
LbNetLog("Join: failed to resolve any peer address from punch\n");
cleanup_join_host(ipv6_host, nullptr);
host_destroy();
return Lb_FAIL;
}
join_lobby_id[0] = '\0';
if (skip_holepunch) {
LbNetLog("Join: skipping hole-punch phase\n");
cleanup_join_host(ipv6_host, nullptr);
host_destroy();
TbClockMSec direct_display_ms = 0;
if (punch_addresses.ipv6[0] != '\0') {
direct_display_ms += TIMEOUT_CONNECT_DIRECT_IPV6;
}
if (punch_addresses.ipv4[0] != '\0') {
direct_display_ms += TIMEOUT_CONNECT_DIRECT_IPV4;
}
return join_direct_fallback(&punch_addresses, LbTimerClock() + direct_display_ms);
}
enet_host_compress_with_range_coder(host);
if (has_ipv6) holepunch_punch_to(ipv6_host, &ipv6_address);
if (has_ipv4) holepunch_punch_to(host, &ipv4_address);
SDL_Delay(HOLEPUNCH_PRE_CONNECT_DELAY_MS);
ENetPeer *ipv4_peer = nullptr;
ENetPeer *ipv6_peer = nullptr;
if (has_ipv6) {
ipv6_peer = enet_host_connect(ipv6_host, &ipv6_address, NUM_CHANNELS, 0);
} else if (has_ipv4) {
ipv4_peer = enet_host_connect(host, &ipv4_address, NUM_CHANNELS, 0);
}
TbClockMSec connection_start = LbTimerClock();
TbClockMSec holepunch_stage_start = connection_start;
TbClockMSec holepunch_deadline = connection_start + TIMEOUT_CONNECT_HOLEPUNCH;
TbClockMSec connection_deadline = connection_start + TIMEOUT_CONNECT_HOLEPUNCH
+ (has_ipv6 ? TIMEOUT_CONNECT_DIRECT_IPV6 : 0)
+ (has_ipv4 ? TIMEOUT_CONNECT_DIRECT_IPV4 : 0);
TbClockMSec ipv4_delay_end = LbTimerClock() + HAPPY_EYEBALLS_DELAY_MS;
ENetEvent enet_event;
while (LbTimerClock() < holepunch_deadline) {
if (has_ipv4 && ipv4_peer == nullptr && LbTimerClock() >= ipv4_delay_end) {
ipv4_peer = enet_host_connect(host, &ipv4_address, NUM_CHANNELS, 0);
}
if (ipv6_peer && enet_host_service(ipv6_host, &enet_event, 0) > 0 && enet_event.type == ENET_EVENT_TYPE_CONNECT) {
LbNetLog("Join: TIMEOUT_CONNECT_HOLEPUNCH took %d ms (connected)\n", (int)(LbTimerClock() - holepunch_stage_start));
return finish_join(ipv6_host, ipv6_peer, host, nullptr, "matchmaking server", "IPv6");
}
if (ipv4_peer && enet_host_service(host, &enet_event, 0) > 0 && enet_event.type == ENET_EVENT_TYPE_CONNECT) {
LbNetLog("Join: TIMEOUT_CONNECT_HOLEPUNCH took %d ms (connected)\n", (int)(LbTimerClock() - holepunch_stage_start));
if (ipv6_peer)
LbNetLog("Join: IPv4 connected first, continuing over IPv4.\n");
return finish_join(host, ipv4_peer, ipv6_host, ipv6_peer, "matchmaking server", "IPv4");
}
if (ipv6_peer) holepunch_punch_to(ipv6_host, &ipv6_address);
if (ipv4_peer) holepunch_punch_to(host, &ipv4_address);
TbClockMSec remaining = holepunch_deadline - LbTimerClock();
enet_uint32 wait_ms = (enet_uint32)min((TbClockMSec)HOLEPUNCH_CONNECT_DELAY_MS, remaining);
if (has_ipv4 && ipv4_peer == nullptr) {
TbClockMSec time_to_ipv4 = ipv4_delay_end - LbTimerClock();
if (time_to_ipv4 > 0)
wait_ms = (enet_uint32)min((TbClockMSec)wait_ms, time_to_ipv4);
}
SDL_Delay(wait_ms);
display_attempting_to_join_message((int)((connection_deadline - LbTimerClock()) / 1000));
if (attempting_to_join_cancel_requested()) {
LbNetLog("Join: cancelled by user during hole-punch\n");
cleanup_join_host(ipv6_host, ipv6_peer);
host_destroy();
return Lb_FAIL;
}
}
LbNetLog("Join: TIMEOUT_CONNECT_HOLEPUNCH took %d ms (timed out)\n", (int)(LbTimerClock() - holepunch_stage_start));
cleanup_join_host(ipv6_host, ipv6_peer);
host_destroy();
return join_direct_fallback(&punch_addresses, connection_deadline);
}
TbError bf_enet_join(const char *session, void *)
{
ENetAddress connect_address;
TbClockMSec join_start_ms = LbTimerClock();
if (strncmp(join_lobby_id, "LAN:", 4) == 0) {
LbNetLog("Join: connecting via LAN\n");
char lan_peer_address[MATCHMAKING_IP_MAX];
snprintf(lan_peer_address, sizeof(lan_peer_address), "%s", join_lobby_id + 4);
join_lobby_id[0] = '\0';
char *port_separator = strrchr(lan_peer_address, ':');
if (!port_separator)
return Lb_FAIL;
*port_separator = '\0';
int lan_game_port = atoi(port_separator + 1);
if (enet_address_set_host(&connect_address, ENET_ADDRESS_TYPE_IPV4, lan_peer_address) < 0) {
LbNetLog("Join: failed to resolve LAN peer address %s\n", lan_peer_address);
return Lb_FAIL;
}
connect_address.port = (enet_uint16)lan_game_port;
if (create_join_host(ENET_ADDRESS_TYPE_IPV4) != Lb_OK)
return Lb_FAIL;
} else if (join_lobby_id[0] != '\0') {
return join_via_holepunch(join_start_ms);
} else {
return join_direct_session(session, LbTimerClock() + TIMEOUT_CONNECT_DIRECT_IPV4, TIMEOUT_CONNECT_DIRECT_IPV4, "direct connect");
}
return connect_to_current_join_host(&connect_address, "LAN", LbTimerClock() + TIMEOUT_CONNECT_DIRECT_IPV4, TIMEOUT_CONNECT_DIRECT_IPV4);
}
/*
* @returns -1 if error, +1 if there is a packet, 0 if timeoout or no events
*/
int bf_enet_read_event(NetNewUserCallback new_user, uint timeout)
{
if (!host)
return -1;
ENetEvent enet_event;
NetUserId user_id;
int service_result = enet_host_service(host, &enet_event, timeout);
if (service_result == 0)
return 0;
if (service_result < 0)
{
NETDBG(1, "enet_host -> %d", service_result);
return service_result;
}
switch (enet_event.type)
{
case ENET_EVENT_TYPE_CONNECT:
LbNetLog("ENet: incoming connection accepted\n");
if (new_user(&user_id)) {
enet_peer_timeout(enet_event.peer, PEER_TIMEOUT_LIMIT, PEER_TIMEOUT_MIN_MS, PEER_TIMEOUT_MAX_MS);
enet_event.peer->data = reinterpret_cast<void *>(user_id);
} else {
LbNetLog("ENet: rejecting peer, no user slot available\n");
enet_peer_disconnect_now(enet_event.peer, 0);
}
break;
case ENET_EVENT_TYPE_DISCONNECT:
case ENET_EVENT_TYPE_DISCONNECT_TIMEOUT: {
if (client_peer && client_peer == enet_event.peer) {
user_id = SERVER_ID;
} else {
user_id = NetUserId(reinterpret_cast<ptrdiff_t>(enet_event.peer->data));
}
const char *disconnect_reason = "timed out";
if (enet_event.type == ENET_EVENT_TYPE_DISCONNECT)
disconnect_reason = "disconnected (clean)";
destroy_incoming_queue(user_id);
LbNetLog("ENet: peer %d %s\n", (int)user_id, disconnect_reason);
g_drop_callback(user_id, NETDROP_ERROR);
break;
}
case ENET_EVENT_TYPE_RECEIVE: {
user_id = SERVER_ID;
if (!client_peer) {
user_id = NetUserId(reinterpret_cast<ptrdiff_t>(enet_event.peer->data));
}
enqueue_incoming_packet(enet_event.packet, user_id);
return 1;
}
case ENET_EVENT_TYPE_NONE:
break;
}
return 0;
}
/**
* Checks for new connections.
* @param new_user Call back if a new user has connected.
*/
void bf_enet_update(NetNewUserCallback new_user)
{
if (new_user == nullptr) {
new_user = not_expected_user;
}
int packets_read = 0;
const int MAX_PACKETS_PER_UPDATE = 100;
while (packets_read < MAX_PACKETS_PER_UPDATE && bf_enet_read_event(new_user, 0))
{
packets_read++;
}
}
/**
* Sends a message buffer to a certain user.
* @param destination Destination user.
* @param buffer
* @param size Must be > 0
*/
void bf_enet_sendmsg_single(NetUserId destination, const char *buffer, size_t size)
{
ENetPacket *packet = enet_packet_create(buffer, size, ENET_PACKET_FLAG_RELIABLE);
if (client_peer) // Just send to server
{
enet_peer_send(client_peer, ENET_CHANNEL_RELIABLE, packet);
}
else
{
for (ENetPeer *currentPeer = host->peers; currentPeer < &host->peers[host -> peerCount]; ++currentPeer)
{
if (currentPeer->state != ENET_PEER_STATE_CONNECTED)
continue;
if (NetUserId(reinterpret_cast<ptrdiff_t>(currentPeer->data)) == destination)
{
enet_peer_send(currentPeer, ENET_CHANNEL_RELIABLE, packet);
}
}
}
enet_host_flush(host);
}
/**
* Sends a message buffer to a certain user using unsequenced delivery.
* @param destination Destination user.
* @param buffer
* @param size Must be > 0
*/
void bf_enet_sendmsg_single_unsequenced(NetUserId destination, const char *buffer, size_t size)
{
ENetPacket *packet = enet_packet_create(buffer, size, ENET_PACKET_FLAG_UNSEQUENCED);
if (client_peer) // Just send to server
{
enet_peer_send(client_peer, ENET_CHANNEL_UNSEQUENCED, packet);
}
else
{
for (ENetPeer *currentPeer = host->peers; currentPeer < &host->peers[host -> peerCount]; ++currentPeer)
{
if (currentPeer->state != ENET_PEER_STATE_CONNECTED)
continue;
if (NetUserId(reinterpret_cast<ptrdiff_t>(currentPeer->data)) == destination)
{
enet_peer_send(currentPeer, ENET_CHANNEL_UNSEQUENCED, packet);
}
}
}
enet_host_flush(host);
}
/**
* Sends a message buffer to all remote users.
* @param buffer
* @param size Must be > 0
*/
void bf_enet_sendmsg_all(const char *buffer, size_t size)
{
ENetPacket *packet = enet_packet_create(buffer, size, ENET_PACKET_FLAG_RELIABLE);
enet_host_broadcast(host, ENET_CHANNEL_RELIABLE, packet);
enet_host_flush(host);
}
TbBool not_expected_user(NetUserId *)
{
ERRORLOG("Unexpected connected user\n");
fprintf(stderr, "Unexpected connected user\n");
return false;
}
bool wait_for_incoming_packet(NetUserId source, unsigned timeout)
{
if (oldest_packet[source] != nullptr) {
return true;
}
TbClockMSec start = LbTimerClock();
while (true)
{
unsigned wait_ms = 0;
if (timeout > 0)
{
TbClockMSec elapsed = LbTimerClock() - start;
if (elapsed >= timeout) {
return false;
}
wait_ms = (unsigned)(timeout - elapsed);
}
NetNewUserCallback new_user_callback;
if (!client_peer) {
new_user_callback = OnNewUser;
} else {
new_user_callback = not_expected_user;
}
if (bf_enet_read_event(new_user_callback, wait_ms) <= 0) {
return false;
}
if (oldest_packet[source] != nullptr) {
return true;
}
if (timeout == 0) {
return false;
}
}
}
/**
* Reads and removes the oldest queued message from a user.
* @param source The source user.
* @param buffer Output buffer for the received message.
* @param max_size Maximum number of bytes copied into the buffer.
* @return Number of bytes copied, or 0 if no message is queued.
*/
size_t bf_enet_readmsg(NetUserId source, char *buffer, size_t max_size)
{
if (oldest_packet[source] == nullptr) {
if (!wait_for_incoming_packet(source, 0)) {
return 0;
}
}
ENetPacket *packet = oldest_packet[source];
oldest_packet[source] = static_cast<ENetPacket *>(oldest_packet[source]->userData);
if (oldest_packet[source] == nullptr) {
newest_packet[source] = nullptr;
}
incoming_queue_size--;
size_t copy_size = min(packet->dataLength, max_size);
memcpy(buffer, packet->data, copy_size);
enet_packet_destroy(packet);
return copy_size;
}
/**
* Asks if a message has finished reception and get be read through readmsg.
* May block under some circumstances but shouldn't unless it can be presumed
* a whole message is on the way.
* TODO NET this definition is due to how SDL Net handles sockets.. see if it can
* be improved - ideally this function shouldn't block at all
* @param source The source user.
* @param timeout If non-zero, this method will wait this number of milliseconds
* for a message to arrive before returning.
* @return The size of the message waiting if there is a message, otherwise 0.
*/
size_t bf_enet_msgready(NetUserId source, unsigned timeout)
{
if (!wait_for_incoming_packet(source, timeout)) {
return 0;
}
return oldest_packet[source]->dataLength;
}
/**
* Disconnects a user.
* @param id User to be dropped.
*/
void bf_enet_drop_user(NetUserId id)
{
LbNetLog("ENet: dropping user %d\n", (int)id);
destroy_incoming_queue(id);
if (host) {
for (ENetPeer *peer = host->peers; peer < &host->peers[host->peerCount]; peer += 1) {
if (peer->state == ENET_PEER_STATE_CONNECTED && NetUserId(reinterpret_cast<ptrdiff_t>(peer->data)) == id) {
enet_peer_disconnect_now(peer, 0);
break;
}
}
}
if (g_drop_callback != nullptr) {
g_drop_callback(id, NETDROP_MANUAL);
}
}
}
static bool IsPeerConnected(const ENetPeer *peer) {
return peer && peer->state == ENET_PEER_STATE_CONNECTED;
}
static bool IsLocalPeer(NetUserId id) {
return id == SERVER_ID || id == my_player_number;
}
unsigned long GetPing(NetUserId id) {
const bool requesting_local_peer = IsLocalPeer(id);
if (IsPeerConnected(client_peer)) {
if (!requesting_local_peer) {
return 0;
}
enet_uint32 value = client_peer->roundTripTime;
if (value == 0) {
value = client_peer->lastRoundTripTime;
}
return static_cast<unsigned long>(value);
}
if (!host) {
return 0;
}
unsigned long best_value = 0;
for (size_t peer_index = 0; peer_index < host->peerCount; ++peer_index) {
ENetPeer *peer = &host->peers[peer_index];
if (!IsPeerConnected(peer)) {
continue;
}
enet_uint32 peer_round_trip = peer->roundTripTime;
if (peer_round_trip == 0) {
peer_round_trip = peer->lastRoundTripTime;
}
unsigned long value = static_cast<unsigned long>(peer_round_trip);
if (!requesting_local_peer) {
NetUserId peer_id = NetUserId(reinterpret_cast<ptrdiff_t>(peer->data));
if (peer_id == id) {
return value;
}
continue;
}
if (value > best_value) {
best_value = value;
}
}
if (requesting_local_peer) {
return best_value;
}
return 0;
}
unsigned int GetPacketLoss(NetUserId id) {
const bool requesting_local_peer = IsLocalPeer(id);
if (IsPeerConnected(client_peer)) {
if (!requesting_local_peer) {
return 0;
}
enet_uint32 value = client_peer->packetLoss;
unsigned int percent = static_cast<unsigned int>((static_cast<unsigned long long>(value) * 100ULL) / ENET_PEER_PACKET_LOSS_SCALE);
return percent;
}
if (!host) {
return 0;
}
unsigned int best_value = 0;
for (size_t peer_index = 0; peer_index < host->peerCount; ++peer_index) {
ENetPeer *peer = &host->peers[peer_index];
if (!IsPeerConnected(peer)) {
continue;
}
enet_uint32 peer_packet_loss = peer->packetLoss;
unsigned int value = static_cast<unsigned int>((static_cast<unsigned long long>(peer_packet_loss) * 100ULL) / ENET_PEER_PACKET_LOSS_SCALE);
if (!requesting_local_peer) {
NetUserId peer_id = NetUserId(reinterpret_cast<ptrdiff_t>(peer->data));
if (peer_id == id) {
return value;
}
continue;
}
if (value > best_value) {
best_value = value;
}
}
if (requesting_local_peer) {
return best_value;
}
return 0;
}
unsigned int GetClientDataInTransit() {
if (IsPeerConnected(client_peer)) {
return client_peer->reliableDataInTransit;
}
if (!host) {
return 0;
}
unsigned int result = 0;
for (size_t peer_index = 0; peer_index < host->peerCount; ++peer_index) {
ENetPeer *peer = &host->peers[peer_index];
if (!IsPeerConnected(peer)) {
continue;
}
if (peer->reliableDataInTransit > result) {
result = peer->reliableDataInTransit;
}
}
return result;
}
unsigned int GetClientPacketsLost() {
if (IsPeerConnected(client_peer)) {
return static_cast<unsigned int>(client_peer->packetsLost);
}
if (!host) {
return 0;
}
unsigned long long total = 0;
for (size_t peer_index = 0; peer_index < host->peerCount; ++peer_index) {
ENetPeer *peer = &host->peers[peer_index];
if (!IsPeerConnected(peer)) {
continue;
}
total += static_cast<unsigned long long>(peer->packetsLost);
if (total > UINT_MAX) {
return UINT_MAX;
}
}
return static_cast<unsigned int>(total);
}
unsigned int GetUploadRateBytesPerSecond()
{
if (!host) {
return 0;
}
return sample_transfer_bytes_per_second(&upload_rate_tracker, &host->totalSentData);
}
unsigned int GetDownloadRateBytesPerSecond()
{
if (!host) {
return 0;
}
return sample_transfer_bytes_per_second(&download_rate_tracker, &host->totalReceivedData);
}
uint16_t enet_get_bound_ipv6_port(void)
{
if (!host_is_dual_stack || !host) {
return 0;
}
return host->address.port;
}
void enet_matchmaking_host_update(void)
{
if (!host)
return;
static ENetAddress pending_ipv4;
static ENetAddress pending_ipv6;
static int has_pending_ipv4 = 0;
static int has_pending_ipv6 = 0;
static TbClockMSec next_punch_time = 0;
PunchAddresses punch_addresses;
int new_punch = 0;
if (matchmaking_poll_punch(&punch_addresses)) {
new_punch = 1;
has_pending_ipv4 = resolve_punch_address(punch_addresses.ipv4, ENET_ADDRESS_TYPE_IPV4, punch_addresses.ipv4_port, &pending_ipv4);
has_pending_ipv6 = host_is_dual_stack && resolve_punch_address(punch_addresses.ipv6, ENET_ADDRESS_TYPE_IPV6, punch_addresses.ipv6_port, &pending_ipv6);
next_punch_time = 0;
if (has_pending_ipv4 || has_pending_ipv6)
LbNetLog("Host: received punch ipv4=%s ipv6=%s ipv4_port=%d ipv6_port=%d\n", punch_addresses.ipv4, punch_addresses.ipv6, punch_addresses.ipv4_port, punch_addresses.ipv6_port);
if (!has_pending_ipv6 && punch_addresses.ipv6[0] != '\0')
LbNetLog("Host: IPv6 punch skipped (host is not dual-stack)\n");
}
if (!has_pending_ipv4 && !has_pending_ipv6) {
next_punch_time = 0;
return;
}
if (!new_punch) {
for (ENetPeer *peer = host->peers; peer < &host->peers[host->peerCount]; peer++) {
if (peer->state == ENET_PEER_STATE_CONNECTED)
return;
}
}
TbClockMSec now = LbTimerClock();
if (!new_punch && now < next_punch_time)
return;
if (has_pending_ipv6)
holepunch_punch_to(host, &pending_ipv6);
if (has_pending_ipv4)
holepunch_punch_to(host, &pending_ipv4);
next_punch_time = now + HOLEPUNCH_CONNECT_DELAY_MS;
}
struct NetSP *InitEnetSP()
{