-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuvkcp.c
More file actions
1911 lines (1667 loc) · 69.4 KB
/
uvkcp.c
File metadata and controls
1911 lines (1667 loc) · 69.4 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
//////////////////////////////////////////////////////
// KCP interfaces implementation
// Copyright 2020, tom zhou<appnet.link@gmail.com>
//////////////////////////////////////////////////////
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include "kcp/ikcp.h"
#include "uvkcp.h"
void kcp__stream_io(uv_poll_t *handle, int status, int events);
// Forward declarations for TCP handshake callbacks
static void tcp_connection_cb(uv_stream_t *server, int status);
static void tcp_handshake_read_cb(uv_stream_t *tcp_client, ssize_t nread, const uv_buf_t *buf);
static void tcp_handshake_write_cb(uv_write_t *req, int status);
static void tcp_client_handshake_write_cb(uv_write_t *req, int status);
static void tcp_client_handshake_read_cb(uv_stream_t *tcp_client, ssize_t nread, const uv_buf_t *buf);
static void tcp_connect_cb(uv_connect_t *req, int status);
// Forward declarations for conversation registry functions
static void init_conv_registry(kcp_context_t *ctx);
static int add_conv_to_registry(kcp_context_t *ctx, uint32_t conv_id, uvkcp_t *handle);
static int remove_conv_from_registry(kcp_context_t *ctx, uint32_t conv_id);
static void cleanup_conv_registry(kcp_context_t *ctx);
static int conv_exists_in_registry(kcp_context_t *ctx, uint32_t conv_id);
void kcp__interval_cb(uv_timer_t *timer)
{
kcp_context_t *ctx = (kcp_context_t *)timer->data;
if (!ctx || !ctx->kcp)
{
return;
}
IUINT32 current = uv_now(ctx->loop);
// Update KCP state - this will flush any pending output
ikcp_update(ctx->kcp, current);
// Use ikcp_check to determine the optimal next update time
IUINT32 next_update = ikcp_check(ctx->kcp, current);
IUINT32 delay = (next_update > current) ? (next_update - current) : 1;
// Ensure minimum delay of 1ms and maximum of 50ms for faster response
// For high-performance mode, use even tighter bounds
if (delay < 1) delay = 1;
if (delay > 50) delay = 50;
// High-performance optimization: reduce maximum delay for low-latency scenarios
// This provides faster response times at the cost of slightly higher CPU usage
if (ctx->high_performance_mode && delay > 10 && ctx->is_connected && ctx->kcp->state == 0) {
delay = 10; // Force much faster updates in high-performance mode
} else if (delay > 25 && ctx->is_connected && ctx->kcp->state == 0) {
delay = 25; // Force faster updates when connected and in normal state
}
// Restart timer with adaptive interval
uv_timer_start(&ctx->timer_handle, kcp__interval_cb, delay, 0);
ctx->timer_active = 1;
}
// KCP debug logging callback
static void kcp_writelog(const char *log, ikcpcb *kcp, void *user)
{
#ifdef UVKCP_DEBUG
UVKCP_LOG("[KCP DEBUG] %s", log);
#endif
}
// KCP output function - sends data over UDP
static int kcp_output(const char *buf, int len, ikcpcb *kcp, void *user)
{
kcp_context_t *ctx = (kcp_context_t *)user;
if (ctx->udp_fd == -1)
{
return -1;
}
// Try to send immediately
ssize_t sent = sendto(ctx->udp_fd, buf, len, 0,
(struct sockaddr *)&ctx->peer_addr,
ctx->peer_addr_len);
if (sent < 0)
{
// If EAGAIN/EWOULDBLOCK, we need to ensure writable event monitoring
// KCP will handle retransmission, but we need to make sure the socket
// is being monitored for writable events so we can flush pending data
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// Find the uvkcp_t handle that contains this KCP context
// Since uvkcp_t inherits from uv_poll_t, we need to search for it
// For now, we'll rely on the KCP timer to retry later
// In a more sophisticated implementation, we would track the association
// between KCP contexts and their uvkcp_t handles
return -1;
}
return -1;
}
// Log UDP send details
if (ctx->peer_addr.ss_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)&ctx->peer_addr;
char ip_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr_in->sin_addr, ip_str, sizeof(ip_str));
UVKCP_LOG("kcp_output: Sent %zd bytes to %s:%d", sent, ip_str, ntohs(addr_in->sin_port));
}
else if (ctx->peer_addr.ss_family == AF_INET6)
{
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)&ctx->peer_addr;
char ip_str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &addr_in6->sin6_addr, ip_str, sizeof(ip_str));
UVKCP_LOG("kcp_output: Sent %zd bytes to [%s]:%d", sent, ip_str, ntohs(addr_in6->sin6_port));
}
// Track statistics
ctx->pktSentTotal++;
ctx->bytesSentTotal += sent;
// KCP expects 0 on success, not the number of bytes sent
return 0;
}
// Initialize KCP handle
int uvkcp_init(uv_loop_t *loop, uvkcp_t *handle)
{
UVKCP_LOG_FUNC("Initializing KCP handle");
static int _initialized = 0;
if (!_initialized)
{
// KCP library initialization if needed
_initialized = 1;
UVKCP_LOG("KCP library initialized");
}
// Initialize stream
kcp__stream_init(loop, handle);
// Allocate KCP context
kcp_context_t *ctx = (kcp_context_t *)malloc(sizeof(kcp_context_t));
if (!ctx)
{
UVKCP_LOG_ERROR("Failed to allocate KCP context");
return UV_ENOMEM;
}
memset(ctx, 0, sizeof(kcp_context_t));
ctx->loop = loop;
ctx->udp_fd = -1;
ctx->is_connected = 0;
ctx->is_listening = 0;
ctx->timer_active = 0;
ctx->backlog = 0;
ctx->connection_cb = NULL;
memset(&ctx->server_addr, 0, sizeof(ctx->server_addr));
ctx->server_addr_len = 0;
ctx->next_conv = 1;
ctx->pending_connect_req = NULL;
// Initialize statistics
ctx->pktSentTotal = 0;
ctx->pktRecvTotal = 0;
ctx->pktSndLossTotal = 0;
ctx->pktRcvLossTotal = 0;
ctx->pktRetransTotal = 0;
ctx->bytesSentTotal = 0;
ctx->bytesRecvTotal = 0;
ctx->lastUpdateTime = 0;
// Initialize performance optimization flags
ctx->high_performance_mode = 0; // Default to balanced mode
// Initialize performance monitoring
ctx->perf_cb = NULL;
ctx->perf_interval = 0;
memset(&ctx->perf_timer, 0, sizeof(ctx->perf_timer));
// Initialize conversation registry
ctx->conv_registry = NULL;
// Initialize timer handle for interval-based KCP updates
if (uv_timer_init(loop, &ctx->timer_handle) < 0)
{
UVKCP_LOG_ERROR("Failed to initialize timer");
free(ctx);
return UV_ENOMEM;
}
ctx->timer_handle.data = ctx;
ctx->update_interval = 10; // Default 10ms interval for KCP updates (legacy, now adaptive)
// Store context in handle
handle->kcp_ctx = ctx;
UVKCP_LOG("KCP handle initialized successfully");
return 0;
}
// Open KCP handle with existing UDP socket
int uvkcp_open(uvkcp_t *handle, uv_os_sock_t sock)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx)
{
return UV_EINVAL;
}
ctx->udp_fd = sock;
// KCP instance creation deferred until TCP handshake completes
// TCP handshake required to exchange conversation ID and peer address
ctx->kcp = NULL;
UVKCP_LOG("KCP handle opened, TCP handshake required for connection");
return kcp__stream_open(handle, sock, 0); // No flags until connected
}
// Bind KCP to address
int uvkcp_bind(uvkcp_t *handle, const struct sockaddr *addr, int reuseaddr, int reuseable)
{
UVKCP_LOG_FUNC("Binding KCP handle");
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx)
{
UVKCP_LOG_ERROR("Invalid KCP context");
return UV_EINVAL;
}
// Initialize TCP server for handshake
if (uv_tcp_init(ctx->loop, &ctx->tcp_server) < 0)
{
UVKCP_LOG_ERROR("Failed to initialize TCP server");
return UV_ENOMEM;
}
ctx->tcp_server.data = handle;
// Set TCP socket options
if (reuseaddr)
{
// Set SO_REUSEADDR on TCP socket
uv_tcp_t *tcp = &ctx->tcp_server;
if (uv_tcp_keepalive(tcp, 1, 60) != 0)
{
UVKCP_LOG("Failed to set TCP keepalive");
}
UVKCP_LOG("Set SO_REUSEADDR on TCP handshake socket");
}
// Bind TCP server to the specified address
if (uv_tcp_bind(&ctx->tcp_server, addr, 0) < 0)
{
UVKCP_LOG_ERROR("Failed to bind TCP server");
uv_close((uv_handle_t *)&ctx->tcp_server, NULL);
return uv_translate_sys_error(errno);
}
// Store the server address for later use
memcpy(&ctx->server_addr, addr, sizeof(ctx->server_addr));
ctx->server_addr_len = (addr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
// Log the TCP port we're binding to
if (addr->sa_family == AF_INET) {
UVKCP_LOG("KCP handle bound to TCP4 handshake socket on port %d, ready for listening", ntohs(((struct sockaddr_in *)addr)->sin_port));
} else if (addr->sa_family == AF_INET6) {
UVKCP_LOG("KCP handle bound to TCP6 handshake socket on port %d, ready for listening", ntohs(((struct sockaddr_in6 *)addr)->sin6_port));
}
// UDP socket will be created later for each client connection
ctx->udp_fd = -1;
return 0;
}
// Connect to remote address
int uvkcp_connect(uvkcp_connect_t *req, uvkcp_t *handle, const struct sockaddr *addr, uvkcp_connect_cb cb)
{
UVKCP_LOG_FUNC("Connecting KCP handle");
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx)
{
UVKCP_LOG_ERROR("Invalid KCP context");
return UV_EINVAL;
}
// Setup connection request
req->handle = handle;
req->cb = cb;
handle->connect_req = req;
// Always use TCP handshake for KCP connection
UVKCP_LOG("Using TCP handshake for KCP connection");
// Store the connect request for later use
ctx->pending_connect_req = req;
// Store the server address for use in TCP connect callback
memcpy(&ctx->server_addr, addr, sizeof(ctx->server_addr));
ctx->server_addr_len = (addr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
// Initialize TCP client for handshake
if (uv_tcp_init(ctx->loop, &ctx->tcp_client) < 0)
{
UVKCP_LOG_ERROR("Failed to initialize TCP client");
return UV_ENOMEM;
}
ctx->tcp_client.data = ctx;
// Connect to TCP server for handshake
uv_connect_t *tcp_connect_req = malloc(sizeof(uv_connect_t));
if (!tcp_connect_req)
{
UVKCP_LOG_ERROR("Failed to allocate TCP connect request");
return UV_ENOMEM;
}
tcp_connect_req->data = ctx;
int r = uv_tcp_connect(tcp_connect_req, &ctx->tcp_client, addr, tcp_connect_cb);
if (r != 0)
{
UVKCP_LOG_ERROR("Failed to connect to TCP server: %d", r);
free(tcp_connect_req);
return r;
}
UVKCP_LOG("TCP handshake initiated");
return 0;
}
// Listen for incoming connections
int uvkcp_listen(uvkcp_t *stream, int backlog, uvkcp_connection_cb cb)
{
kcp_context_t *ctx = (kcp_context_t *)stream->kcp_ctx;
if (!ctx)
{
return UV_EINVAL;
}
if (ctx->is_connected)
{
UVKCP_LOG_ERROR("KCP handle already connected, cannot listen");
return UV_EISCONN;
}
// Check if TCP server is already bound
if (ctx->tcp_server.loop == NULL)
{
UVKCP_LOG_ERROR("KCP handle not bound to TCP socket, call uvkcp_bind first");
return UV_EINVAL;
}
stream->connection_cb = cb;
ctx->connection_cb = cb;
ctx->backlog = backlog;
ctx->is_listening = 1;
// Start listening on the already-bound TCP server
UVKCP_LOG("Starting TCP server for KCP handshake");
// Start listening on TCP server
int r = uv_listen((uv_stream_t *)&ctx->tcp_server, backlog, tcp_connection_cb);
if (r != 0)
{
UVKCP_LOG_ERROR("Failed to listen on TCP server: %d", r);
return r;
}
UVKCP_LOG("KCP server listening on TCP handshake socket, backlog=%d", backlog);
return 0;
}
// Close KCP handle
int uvkcp_close(uvkcp_t *handle, uv_close_cb close_cb)
{
UVKCP_LOG_FUNC("Closing KCP handle");
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx)
{
UVKCP_LOG_ERROR("Invalid KCP context");
return UV_EINVAL;
}
// Set closing flag
handle->flags |= UVKCP_FLAG_CLOSING;
// Stop timers
if (ctx->timer_active)
{
UVKCP_LOG("Stopping KCP interval timer");
uv_timer_stop(&ctx->timer_handle);
ctx->timer_active = 0;
}
// Stop performance monitoring timer
if (ctx->perf_interval > 0)
{
UVKCP_LOG("Stopping performance monitoring timer");
uv_timer_stop(&ctx->perf_timer);
uv_close((uv_handle_t *)&ctx->perf_timer, NULL);
}
// Cleanup KCP
if (ctx->kcp)
{
// Remove conversation ID from registry if this is a client connection
if (ctx->is_connected && !ctx->is_listening && ctx->server_ctx)
{
// Get conversation ID from KCP instance
uint32_t conv_id = ctx->kcp->conv;
UVKCP_LOG("Removing conversation ID %u from registry", conv_id);
remove_conv_from_registry(ctx->server_ctx, conv_id);
}
UVKCP_LOG("Releasing KCP instance");
ikcp_release(ctx->kcp);
ctx->kcp = NULL;
}
// Close TCP connections for handshake based on context
UVKCP_LOG("Closing TCP connections");
// For server contexts, close TCP server stream only
if (ctx->is_listening) {
UVKCP_LOG("Closing TCP server stream for server context");
uv_close((uv_handle_t *)&ctx->tcp_server, NULL);
}
// For client contexts, TCP client is already closed during handshake
// No need to close it again in uvkcp_close
// Close UDP socket
if (ctx->udp_fd != -1)
{
UVKCP_LOG("Closing UDP socket fd=%d", ctx->udp_fd);
close(ctx->udp_fd);
ctx->udp_fd = -1;
}
// Clean up conversation registry for server contexts
if (ctx->is_listening)
{
UVKCP_LOG("Cleaning up conversation registry");
cleanup_conv_registry(ctx);
}
// Stop polling
UVKCP_LOG("Stopping poll handle");
uv_poll_stop((uv_poll_t *)handle);
// Free context
UVKCP_LOG("Freeing KCP context");
free(ctx);
handle->kcp_ctx = NULL;
// Call stream destroy
UVKCP_LOG("Destroying KCP stream");
kcp__stream_destroy(handle);
// Set closed flag
handle->flags |= UVKCP_FLAG_CLOSED;
handle->flags &= ~UVKCP_FLAG_CLOSING;
// Call close callback if provided
if (close_cb)
{
UVKCP_LOG("Calling close callback");
close_cb((uv_handle_t *)handle);
}
UVKCP_LOG("KCP handle closed successfully");
return 0;
}
// Set KCP nodelay option
int uvkcp_nodelay(uvkcp_t *handle, int enable, int interval, int resend, int nc)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx || !ctx->kcp)
{
return UV_EINVAL;
}
ikcp_nodelay(ctx->kcp, enable, interval, resend, nc);
return 0;
}
// Set KCP window size
int uvkcp_wndsize(uvkcp_t *handle, int sndwnd, int rcvwnd)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx || !ctx->kcp)
{
return UV_EINVAL;
}
ikcp_wndsize(ctx->kcp, sndwnd, rcvwnd);
return 0;
}
// Set KCP MTU
int uvkcp_setmtu(uvkcp_t *handle, int mtu)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx || !ctx->kcp)
{
return UV_EINVAL;
}
ikcp_setmtu(ctx->kcp, mtu);
return 0;
}
// Translate KCP error to libuv error
int uvkcp_translate_kcp_error(void)
{
// KCP doesn't have detailed error codes, return generic error
return UV_EIO;
}
// Stub implementations for missing functions
int uvkcp_keepalive(uvkcp_t *handle, int enable, unsigned int delay)
{
// KCP doesn't support keepalive in the same way as TCP
return 0;
}
int uvkcp_getsockname(const uvkcp_t *handle, struct sockaddr *name, int *namelen)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx || ctx->udp_fd == -1)
{
return UV_EINVAL;
}
socklen_t len = *namelen;
if (getsockname(ctx->udp_fd, name, &len) < 0)
{
return uv_translate_sys_error(errno);
}
*namelen = len;
return 0;
}
int uvkcp_getpeername(const uvkcp_t *handle, struct sockaddr *name, int *namelen)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx || !ctx->is_connected)
{
return UV_ENOTCONN;
}
socklen_t len = *namelen;
if (len > ctx->peer_addr_len)
{
len = ctx->peer_addr_len;
}
memcpy(name, &ctx->peer_addr, len);
*namelen = len;
return 0;
}
int uvkcp_getperf(uvkcp_t *handle, uvkcp_netperf_t *perf, int clear)
{
kcp_context_t *ctx = (kcp_context_t *)handle->kcp_ctx;
if (!ctx || !ctx->kcp)
{
return UV_EINVAL;
}
// Get basic KCP statistics
memset(perf, 0, sizeof(uvkcp_netperf_t));
// Fill in actual statistics from context
perf->msTimeStamp = uv_now(ctx->loop);
perf->pktSentTotal = ctx->pktSentTotal;
perf->pktRecvTotal = ctx->pktRecvTotal;
perf->pktSndLossTotal = ctx->pktSndLossTotal;
perf->pktRcvLossTotal = ctx->pktRcvLossTotal;
perf->pktRetransTotal = ctx->pktRetransTotal;
perf->pktSentACKTotal = 0; // KCP handles ACKs internally
perf->pktRecvACKTotal = 0; // KCP handles ACKs internally
perf->pktSentNAKTotal = 0; // KCP doesn't use NAK
perf->pktRecvNAKTotal = 0; // KCP doesn't use NAK
perf->usSndDurationTotal = 0; // Not tracked currently
// Calculate rates (simplified)
IUINT32 current = uv_now(ctx->loop);
IUINT32 timeDiff = current - ctx->lastUpdateTime;
if (timeDiff > 0)
{
double timeSec = timeDiff / 1000.0;
if (timeSec > 0)
{
perf->mbpsSendRate = (ctx->bytesSentTotal * 8.0) / (timeSec * 1000000.0);
perf->mbpsRecvRate = (ctx->bytesRecvTotal * 8.0) / (timeSec * 1000000.0);
}
}
// Enhanced KCP statistics from ikcp structure
if (ctx->kcp) {
perf->pktFlowWindow = ctx->kcp->rcv_wnd;
perf->pktCongestionWindow = ctx->kcp->cwnd;
perf->pktFlightSize = ctx->kcp->snd_nxt - ctx->kcp->snd_una;
perf->msRTT = ctx->kcp->rx_rttval;
// Note: KCP doesn't expose buffer size/count directly, using queue counts as approximation
perf->byteAvailSndBuf = 0; // Not directly available from KCP
perf->byteAvailRcvBuf = 0; // Not directly available from KCP
// Calculate bandwidth estimation based on KCP state
if (perf->msRTT > 0) {
perf->mbpsBandwidth = (perf->pktCongestionWindow * ctx->kcp->mtu * 8.0) / (perf->msRTT / 1000.0) / 1000000.0;
}
}
// Update last update time
ctx->lastUpdateTime = current;
// Clear statistics if requested
if (clear)
{
ctx->pktSentTotal = 0;
ctx->pktRecvTotal = 0;
ctx->pktSndLossTotal = 0;
ctx->pktRcvLossTotal = 0;
ctx->pktRetransTotal = 0;
ctx->bytesSentTotal = 0;
ctx->bytesRecvTotal = 0;
}
return 0;
}
// Server/Client style KCP implementation with TCP handshake
// Simple conversation registry entry
struct conv_registry_entry_s
{
uint32_t conv_id;
uvkcp_t *handle;
struct conv_registry_entry_s *next;
};
typedef struct conv_registry_entry_s conv_registry_entry_t;
// Simple hash table for conversation ID registry
#define CONV_REGISTRY_SIZE 256
// Initialize conversation registry
static void init_conv_registry(kcp_context_t *ctx)
{
if (ctx->conv_registry == NULL)
{
ctx->conv_registry = calloc(CONV_REGISTRY_SIZE, sizeof(conv_registry_entry_t *));
}
}
// Hash function for conversation ID
static unsigned int conv_hash(uint32_t conv_id)
{
return conv_id % CONV_REGISTRY_SIZE;
}
// Add conversation ID to registry
static int add_conv_to_registry(kcp_context_t *ctx, uint32_t conv_id, uvkcp_t *handle)
{
if (!ctx->conv_registry)
{
init_conv_registry(ctx);
}
unsigned int hash = conv_hash(conv_id);
conv_registry_entry_t **bucket = (conv_registry_entry_t **)ctx->conv_registry + hash;
// Check for existing entry
conv_registry_entry_t *entry = *bucket;
while (entry)
{
if (entry->conv_id == conv_id)
{
UVKCP_LOG_ERROR("Conversation ID %u already exists in registry", conv_id);
return -1; // Conflict detected
}
entry = entry->next;
}
// Add new entry
entry = malloc(sizeof(conv_registry_entry_t));
if (!entry)
{
UVKCP_LOG_ERROR("Failed to allocate conversation registry entry for conv %u", conv_id);
return -1;
}
entry->conv_id = conv_id;
entry->handle = handle;
entry->next = *bucket;
*bucket = entry;
UVKCP_LOG("Registered conversation ID %u in registry", conv_id);
return 0;
}
// Remove conversation ID from registry
static int remove_conv_from_registry(kcp_context_t *ctx, uint32_t conv_id)
{
if (!ctx->conv_registry)
{
UVKCP_LOG_ERROR("Cannot remove conversation ID %u - registry not initialized", conv_id);
return -1;
}
unsigned int hash = conv_hash(conv_id);
conv_registry_entry_t **bucket = (conv_registry_entry_t **)ctx->conv_registry + hash;
conv_registry_entry_t *prev = NULL;
conv_registry_entry_t *entry = *bucket;
while (entry)
{
if (entry->conv_id == conv_id)
{
if (prev)
{
prev->next = entry->next;
}
else
{
*bucket = entry->next;
}
free(entry);
UVKCP_LOG("Removed conversation ID %u from registry", conv_id);
return 0;
}
prev = entry;
entry = entry->next;
}
UVKCP_LOG_ERROR("Conversation ID %u not found in registry", conv_id);
return -1; // Not found
}
// Clean up entire conversation registry
static void cleanup_conv_registry(kcp_context_t *ctx)
{
if (!ctx->conv_registry)
{
UVKCP_LOG("No conversation registry to clean up");
return;
}
int i;
for (i = 0; i < CONV_REGISTRY_SIZE; i++)
{
conv_registry_entry_t **bucket = (conv_registry_entry_t **)ctx->conv_registry + i;
conv_registry_entry_t *entry = *bucket;
while (entry)
{
conv_registry_entry_t *next = entry->next;
free(entry);
entry = next;
}
*bucket = NULL;
}
free(ctx->conv_registry);
ctx->conv_registry = NULL;
UVKCP_LOG("Cleaned up conversation registry with %d entries", total_entries);
}
// Check if conversation ID exists in registry
static int conv_exists_in_registry(kcp_context_t *ctx, uint32_t conv_id)
{
if (!ctx->conv_registry)
{
return 0;
}
unsigned int hash = conv_hash(conv_id);
conv_registry_entry_t *bucket = *((conv_registry_entry_t **)ctx->conv_registry + hash);
while (bucket)
{
if (bucket->conv_id == conv_id)
{
return 1;
}
bucket = bucket->next;
}
return 0;
}
// Helper function to generate random conversation ID with conflict detection
static uint32_t generate_conv_id(kcp_context_t *ctx)
{
// Use instance-specific base to avoid conflicts between server instances
if (ctx->base_conv == 0)
{
ctx->base_conv = (uint32_t)rand() | 0x10000000; // Ensure non-zero and high bit set
UVKCP_LOG("Initialized conversation ID base: %u", ctx->base_conv);
}
// Generate conversation ID with conflict detection
uint32_t conv;
int attempts = 100; // Prevent infinite loop
int conflicts = 0;
do
{
conv = ctx->base_conv + ctx->next_conv;
ctx->next_conv++;
// Wrap around if needed (avoid 0 which is reserved for handshake requests)
if (ctx->next_conv > 0x0FFFFFFF)
{
ctx->next_conv = 1;
ctx->base_conv = (uint32_t)rand() | 0x10000000;
UVKCP_LOG("Wrapped conversation ID counter, new base: %u", ctx->base_conv);
}
if (conv_exists_in_registry(ctx, conv))
{
conflicts++;
UVKCP_LOG("Conversation ID conflict detected: %u (attempt %d)", conv, attempts);
}
attempts--;
} while (conv_exists_in_registry(ctx, conv) && attempts > 0);
if (attempts <= 0)
{
// Fallback: use timestamp-based ID with more entropy
conv = (uint32_t)uv_now(ctx->loop) ^ (uint32_t)rand() ^ (uint32_t)((uintptr_t)ctx);
UVKCP_LOG("Used fallback conversation ID: %u (after %d conflicts)", conv, conflicts);
}
else if (conflicts > 0)
{
UVKCP_LOG("Generated conversation ID: %u (resolved %d conflicts)", conv, conflicts);
}
else
{
UVKCP_LOG("Generated conversation ID: %u", conv);
}
return conv;
}
// Helper function to get current timestamp
static uint32_t get_timestamp(void)
{
return (uint32_t)(uv_now(uv_default_loop()) / 1000);
}
// Helper function to generate random nonce
static uint32_t generate_nonce(void)
{
return (uint32_t)rand();
}
// Helper function to set socket to non-blocking mode
static int set_socket_nonblocking(int sock)
{
int flags = fcntl(sock, F_GETFL, 0);
if (flags == -1)
{
UVKCP_LOG_ERROR("Failed to get socket flags: %s", strerror(errno));
return -1;
}
if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)
{
UVKCP_LOG_ERROR("Failed to set socket non-blocking: %s", strerror(errno));
return -1;
}
UVKCP_LOG("Set socket %d to non-blocking mode", sock);
return 0;
}
// Simple alloc function for TCP handshake
static void echo_alloc(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
{
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
// Structure to store TCP client and its address
struct tcp_client_info_s {
uv_tcp_t tcp_client;
struct sockaddr_storage client_addr;
socklen_t client_addr_len;
};
typedef struct tcp_client_info_s tcp_client_info_t;
// TCP connection callback for server
static void tcp_connection_cb(uv_stream_t *server, int status)
{
if (status != 0)
{
UVKCP_LOG_ERROR("TCP connection error: %d", status);
return;
}
uvkcp_t *kcp_server = (uvkcp_t *)server->data;
kcp_context_t *server_ctx = (kcp_context_t *)kcp_server->kcp_ctx;
tcp_client_info_t *client_info = malloc(sizeof(tcp_client_info_t));
if (!client_info)
{
UVKCP_LOG_ERROR("Failed to allocate TCP client info");
return;
}
if (uv_tcp_init(server_ctx->loop, &client_info->tcp_client) < 0)
{
UVKCP_LOG_ERROR("Failed to initialize TCP client");
free(client_info);
return;
}
// Store the KCP server in the TCP client data
client_info->tcp_client.data = kcp_server;
if (uv_accept(server, (uv_stream_t *)&client_info->tcp_client) == 0)
{
UVKCP_LOG("Accepted TCP connection for KCP handshake");
// Get the client's TCP address
client_info->client_addr_len = sizeof(client_info->client_addr);
int addr_len = (int)client_info->client_addr_len;
int r = uv_tcp_getpeername(&client_info->tcp_client,
(struct sockaddr *)&client_info->client_addr,
&addr_len);
client_info->client_addr_len = (socklen_t)addr_len;
if (r == 0)
{
if (client_info->client_addr.ss_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)&client_info->client_addr;
char ip_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr_in->sin_addr, ip_str, sizeof(ip_str));
UVKCP_LOG("Client TCP address: %s:%d", ip_str, ntohs(addr_in->sin_port));
}
else if (client_info->client_addr.ss_family == AF_INET6)
{
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)&client_info->client_addr;
char ip_str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &addr_in6->sin6_addr, ip_str, sizeof(ip_str));
UVKCP_LOG("Client TCP address: [%s]:%d", ip_str, ntohs(addr_in6->sin6_port));
}
}
else
{
UVKCP_LOG_ERROR("Failed to get client TCP address: %d", r);
}
// Start reading handshake request
uv_read_start((uv_stream_t *)&client_info->tcp_client,
(uv_alloc_cb)echo_alloc,
tcp_handshake_read_cb);
}
else
{
UVKCP_LOG_ERROR("Failed to accept TCP connection");
uv_close((uv_handle_t *)&client_info->tcp_client, NULL);
free(client_info);
}
}
// TCP read callback for handshake
static void tcp_handshake_read_cb(uv_stream_t *tcp_client, ssize_t nread, const uv_buf_t *buf)
{
if (nread < 0)
{
UVKCP_LOG_ERROR("TCP handshake read error: %zd", nread);
free(buf->base);
uv_close((uv_handle_t *)tcp_client, NULL);
return;
}
if (nread == sizeof(kcp_handshake_t))
{
kcp_handshake_t *handshake = (kcp_handshake_t *)buf->base;
uvkcp_t *kcp_server = (uvkcp_t *)tcp_client->data;
kcp_context_t *server_ctx = (kcp_context_t *)kcp_server->kcp_ctx;
// Process handshake request
UVKCP_LOG("Received KCP handshake request: conv=%u, addr_family=%d, udp_port=%d",
ntohl(handshake->conv), handshake->addr_family, ntohs(handshake->udp_port));