forked from mas-bandwidth/netcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
netcode.c
executable file
·8958 lines (6886 loc) · 327 KB
/
netcode.c
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
/*
netcode.io reference implementation
Copyright © 2017 - 2020, The Network Protocol Company, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "netcode.h"
#include <stdlib.h>
#include <memory.h>
#include <stdio.h>
#include <stdarg.h>
#include <inttypes.h>
#include <math.h>
#include <time.h>
#ifdef _MSC_VER
#define SODIUM_STATIC
#pragma warning(disable:4996)
#endif // #ifdef _MSC_VER
#include <sodium.h>
#define NETCODE_SOCKET_IPV6 1
#define NETCODE_SOCKET_IPV4 2
#define NETCODE_CONNECT_TOKEN_NONCE_BYTES 24
#define NETCODE_CONNECT_TOKEN_PRIVATE_BYTES 1024
#define NETCODE_CHALLENGE_TOKEN_BYTES 300
#define NETCODE_VERSION_INFO_BYTES 13
#define NETCODE_MAX_PACKET_BYTES 1300
#define NETCODE_MAX_PAYLOAD_BYTES 1200
#define NETCODE_MAX_ADDRESS_STRING_LENGTH 256
#define NETCODE_PACKET_QUEUE_SIZE 256
#define NETCODE_REPLAY_PROTECTION_BUFFER_SIZE 256
#define NETCODE_CLIENT_MAX_RECEIVE_PACKETS 64
#define NETCODE_SERVER_MAX_RECEIVE_PACKETS ( 64 * NETCODE_MAX_CLIENTS )
#define NETCODE_CLIENT_SOCKET_SNDBUF_SIZE ( 256 * 1024 )
#define NETCODE_CLIENT_SOCKET_RCVBUF_SIZE ( 256 * 1024 )
#define NETCODE_SERVER_SOCKET_SNDBUF_SIZE ( 4 * 1024 * 1024 )
#define NETCODE_SERVER_SOCKET_RCVBUF_SIZE ( 4 * 1024 * 1024 )
#define NETCODE_VERSION_INFO ( (uint8_t*) "NETCODE 1.02" )
#define NETCODE_PACKET_SEND_RATE 10.0
#define NETCODE_NUM_DISCONNECT_PACKETS 10
#ifndef NETCODE_ENABLE_TESTS
#define NETCODE_ENABLE_TESTS 0
#endif // #ifndef NETCODE_ENABLE_TESTS
#ifndef NETCODE_ENABLE_LOGGING
#define NETCODE_ENABLE_LOGGING 1
#endif // #ifndef NETCODE_ENABLE_LOGGING
// ------------------------------------------------------------------
static void netcode_default_assert_handler( NETCODE_CONST char * condition, NETCODE_CONST char * function, NETCODE_CONST char * file, int line )
{
printf( "assert failed: ( %s ), function %s, file %s, line %d\n", condition, function, file, line );
#if defined( __GNUC__ )
__builtin_trap();
#elif defined( _MSC_VER )
__debugbreak();
#endif
exit( 1 );
}
static int log_level = 0;
static int (*printf_function)( NETCODE_CONST char *, ... ) = ( int (*)( NETCODE_CONST char *, ... ) ) printf;
void (*netcode_assert_function)( NETCODE_CONST char *, NETCODE_CONST char *, NETCODE_CONST char * file, int line ) = netcode_default_assert_handler;
void netcode_log_level( int level )
{
log_level = level;
}
void netcode_set_printf_function( int (*function)( NETCODE_CONST char *, ... ) )
{
netcode_assert( function );
printf_function = function;
}
void netcode_set_assert_function( void (*function)( NETCODE_CONST char *, NETCODE_CONST char *, NETCODE_CONST char * file, int line ) )
{
netcode_assert_function = function;
}
#if NETCODE_ENABLE_LOGGING
void netcode_printf( int level, NETCODE_CONST char * format, ... )
{
if ( level > log_level )
return;
va_list args;
va_start( args, format );
char buffer[4*1024];
vsprintf( buffer, format, args );
printf_function( "%s", buffer );
va_end( args );
}
#else // #if NETCODE_ENABLE_LOGGING
void netcode_printf( int level, NETCODE_CONST char * format, ... )
{
(void) level;
(void) format;
}
#endif // #if NETCODE_ENABLE_LOGGING
void * netcode_default_allocate_function( void * context, uint64_t bytes )
{
(void) context;
return malloc( bytes );
}
void netcode_default_free_function( void * context, void * pointer )
{
(void) context;
free( pointer );
}
// ------------------------------------------------------------------
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
#define NOMINMAX
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#include <ws2tcpip.h>
#include <ws2ipdef.h>
#include <iphlpapi.h>
#pragma comment( lib, "WS2_32.lib" )
#pragma comment( lib, "IPHLPAPI.lib" )
#ifdef SetPort
#undef SetPort
#endif // #ifdef SetPort
#include <iphlpapi.h>
#pragma comment( lib, "IPHLPAPI.lib" )
#elif NETCODE_PLATFORM == NETCODE_PLATFORM_MAC || NETCODE_PLATFORM == NETCODE_PLATFORM_UNIX
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#else
#error netcode.io - unknown platform!
#endif
// ----------------------------------------------------------------
#ifdef __MINGW32__
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
{
if ( af == AF_INET )
{
struct sockaddr_in in;
memset(&in, 0, sizeof(in));
in.sin_family = AF_INET;
memcpy(&in.sin_addr, src, sizeof(struct in_addr));
getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
return dst;
}
else if ( af == AF_INET6 )
{
struct sockaddr_in6 in;
memset(&in, 0, sizeof(in));
in.sin6_family = AF_INET6;
memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
return dst;
}
return NULL;
}
#define NS_INADDRSZ 4
#define NS_IN6ADDRSZ 16
#define NS_INT16SZ 2
int inet_pton4(const char *src, char *dst)
{
uint8_t tmp[NS_INADDRSZ], *tp;
int saw_digit = 0;
int octets = 0;
*(tp = tmp) = 0;
int ch;
while ((ch = *src++) != '\0')
{
if ( ch >= '0' && ch <= '9' )
{
uint32_t n = *tp * 10 + (ch - '0');
if ( saw_digit && *tp == 0 )
return 0;
if ( n > 255 )
return 0;
*tp = n;
if ( !saw_digit )
{
if ( ++octets > 4 )
return 0;
saw_digit = 1;
}
}
else if ( ch == '.' && saw_digit )
{
if ( octets == 4 )
return 0;
*++tp = 0;
saw_digit = 0;
}
else
return 0;
}
if ( octets < 4 )
return 0;
memcpy(dst, tmp, NS_INADDRSZ);
return 1;
}
int inet_pton6(const char *src, char *dst)
{
static const char xdigits[] = "0123456789abcdef";
uint8_t tmp[NS_IN6ADDRSZ];
uint8_t *tp = (uint8_t*) memset(tmp, '\0', NS_IN6ADDRSZ);
uint8_t *endp = tp + NS_IN6ADDRSZ;
uint8_t *colonp = NULL;
// Leading :: requires some special handling
if ( *src == ':' )
{
if ( *++src != ':' )
return 0;
}
const char *curtok = src;
int saw_xdigit = 0;
uint32_t val = 0;
int ch;
while ( (ch = tolower(*src++)) != '\0' )
{
const char *pch = strchr(xdigits, ch);
if ( pch != NULL )
{
val <<= 4;
val |= (pch - xdigits);
if ( val > 0xffff )
return 0;
saw_xdigit = 1;
continue;
}
if ( ch == ':' )
{
curtok = src;
if ( !saw_xdigit )
{
if ( colonp )
return 0;
colonp = tp;
continue;
}
else if ( *src == '\0' )
{
return 0;
}
if ( tp + NS_INT16SZ > endp )
return 0;
*tp++ = (uint8_t) (val >> 8) & 0xff;
*tp++ = (uint8_t) val & 0xff;
saw_xdigit = 0;
val = 0;
continue;
}
if ( ch == '.' && ((tp + NS_INADDRSZ) <= endp) && inet_pton4(curtok, (char*) tp) > 0 )
{
tp += NS_INADDRSZ;
saw_xdigit = 0;
break;
}
return 0;
}
if ( saw_xdigit )
{
if ( tp + NS_INT16SZ > endp )
return 0;
*tp++ = (uint8_t) (val >> 8) & 0xff;
*tp++ = (uint8_t) val & 0xff;
}
if ( colonp != NULL )
{
const int n = tp - colonp;
if ( tp == endp )
return 0;
for (int i = 1; i <= n; i++)
{
endp[-i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if ( tp != endp )
return 0;
memcpy(dst, tmp, NS_IN6ADDRSZ);
return 1;
}
int inet_pton(int af, const char *src, void *dst)
{
switch ( af )
{
case AF_INET:
return inet_pton4(src, (char *) dst);
case AF_INET6:
return inet_pton6(src, (char *) dst);
default:
return -1;
}
}
#endif
// ----------------------------------------------------------------
int netcode_parse_address( NETCODE_CONST char * address_string_in, struct netcode_address_t * address )
{
netcode_assert( address_string_in );
netcode_assert( address );
memset( address, 0, sizeof( struct netcode_address_t ) );
// first try to parse the string as an IPv6 address:
// 1. if the first character is '[' then it's probably an ipv6 in form "[addr6]:portnum"
// 2. otherwise try to parse as a raw IPv6 address using inet_pton
#define NETCODE_ADDRESS_BUFFER_SAFETY 32
char buffer[NETCODE_MAX_ADDRESS_STRING_LENGTH + NETCODE_ADDRESS_BUFFER_SAFETY*2];
char * address_string = buffer + NETCODE_ADDRESS_BUFFER_SAFETY;
strncpy( address_string, address_string_in, NETCODE_MAX_ADDRESS_STRING_LENGTH - 1 );
address_string[NETCODE_MAX_ADDRESS_STRING_LENGTH-1] = '\0';
int address_string_length = (int) strlen( address_string );
if ( address_string[0] == '[' )
{
int base_index = address_string_length - 1;
int i;
for ( i = 0; i < 6; ++i ) // note: no need to search past 6 characters as ":65535" is longest possible port value
{
int index = base_index - i;
if ( index < 3 )
return NETCODE_ERROR;
if ( address_string[index] == ':' )
{
address->port = (uint16_t) ( atoi( &address_string[index + 1] ) );
address_string[index-1] = '\0';
}
}
address_string += 1;
}
struct in6_addr sockaddr6;
if ( inet_pton( AF_INET6, address_string, &sockaddr6 ) == 1 )
{
address->type = NETCODE_ADDRESS_IPV6;
int i;
for ( i = 0; i < 8; ++i )
{
address->data.ipv6[i] = ntohs( ( (uint16_t*) &sockaddr6 ) [i] );
}
return NETCODE_OK;
}
// otherwise it's probably an IPv4 address:
// 1. look for ":portnum", if found save the portnum and strip it out
// 2. parse remaining ipv4 address via inet_pton
address_string_length = (int) strlen( address_string );
int base_index = address_string_length - 1;
int i;
for ( i = 0; i < 6; ++i )
{
int index = base_index - i;
if ( index < 0 )
break;
if ( address_string[index] == ':' )
{
address->port = (uint16_t) atoi( &address_string[index+1] );
address_string[index] = '\0';
}
}
struct sockaddr_in sockaddr4;
if ( inet_pton( AF_INET, address_string, &sockaddr4.sin_addr ) == 1 )
{
address->type = NETCODE_ADDRESS_IPV4;
address->data.ipv4[3] = (uint8_t) ( ( sockaddr4.sin_addr.s_addr & 0xFF000000 ) >> 24 );
address->data.ipv4[2] = (uint8_t) ( ( sockaddr4.sin_addr.s_addr & 0x00FF0000 ) >> 16 );
address->data.ipv4[1] = (uint8_t) ( ( sockaddr4.sin_addr.s_addr & 0x0000FF00 ) >> 8 );
address->data.ipv4[0] = (uint8_t) ( ( sockaddr4.sin_addr.s_addr & 0x000000FF ) );
return NETCODE_OK;
}
return NETCODE_ERROR;
}
char * netcode_address_to_string( struct netcode_address_t * address, char * buffer )
{
netcode_assert( address );
netcode_assert( buffer );
if ( address->type == NETCODE_ADDRESS_IPV6 )
{
if ( address->port == 0 )
{
uint16_t ipv6_network_order[8];
int i;
for ( i = 0; i < 8; ++i )
ipv6_network_order[i] = htons( address->data.ipv6[i] );
inet_ntop( AF_INET6, (void*) ipv6_network_order, buffer, NETCODE_MAX_ADDRESS_STRING_LENGTH );
return buffer;
}
else
{
char address_string[INET6_ADDRSTRLEN];
uint16_t ipv6_network_order[8];
int i;
for ( i = 0; i < 8; ++i )
ipv6_network_order[i] = htons( address->data.ipv6[i] );
inet_ntop( AF_INET6, (void*) ipv6_network_order, address_string, INET6_ADDRSTRLEN );
snprintf( buffer, NETCODE_MAX_ADDRESS_STRING_LENGTH, "[%s]:%d", address_string, address->port );
return buffer;
}
}
else if ( address->type == NETCODE_ADDRESS_IPV4 )
{
if ( address->port != 0 )
{
snprintf( buffer, NETCODE_MAX_ADDRESS_STRING_LENGTH, "%d.%d.%d.%d:%d",
address->data.ipv4[0],
address->data.ipv4[1],
address->data.ipv4[2],
address->data.ipv4[3],
address->port );
}
else
{
snprintf( buffer, NETCODE_MAX_ADDRESS_STRING_LENGTH, "%d.%d.%d.%d",
address->data.ipv4[0],
address->data.ipv4[1],
address->data.ipv4[2],
address->data.ipv4[3] );
}
return buffer;
}
else
{
snprintf( buffer, NETCODE_MAX_ADDRESS_STRING_LENGTH, "%s", "NONE" );
return buffer;
}
}
int netcode_address_equal( struct netcode_address_t * a, struct netcode_address_t * b )
{
netcode_assert( a );
netcode_assert( b );
if ( a->type != b->type )
return 0;
if ( a->port != b->port )
return 0;
if ( a->type == NETCODE_ADDRESS_IPV4 )
{
int i;
for ( i = 0; i < 4; ++i )
{
if ( a->data.ipv4[i] != b->data.ipv4[i] )
return 0;
}
}
else if ( a->type == NETCODE_ADDRESS_IPV6 )
{
int i;
for ( i = 0; i < 8; ++i )
{
if ( a->data.ipv6[i] != b->data.ipv6[i] )
return 0;
}
}
else
{
return 0;
}
return 1;
}
// ----------------------------------------------------------------
struct netcode_t
{
int initialized;
};
static struct netcode_t netcode;
int netcode_init()
{
netcode_assert( !netcode.initialized );
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
WSADATA WsaData;
if ( WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR )
return NETCODE_ERROR;
#endif // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
if ( sodium_init() == -1 )
return NETCODE_ERROR;
netcode.initialized = 1;
return NETCODE_OK;
}
void netcode_term()
{
netcode_assert( netcode.initialized );
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
WSACleanup();
#endif // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
netcode.initialized = 0;
}
// ----------------------------------------------------------------
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
typedef uint64_t netcode_socket_handle_t;
#else // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
typedef int netcode_socket_handle_t;
#endif // #if NETCODE_PLATFORM == NETCODe_PLATFORM_WINDOWS
struct netcode_socket_t
{
struct netcode_address_t address;
netcode_socket_handle_t handle;
};
struct netcode_socket_holder_t
{
struct netcode_socket_t ipv4;
struct netcode_socket_t ipv6;
};
#define NETCODE_SOCKET_ERROR_NONE 0
#define NETCODE_SOCKET_ERROR_CREATE_FAILED 1
#define NETCODE_SOCKET_ERROR_SET_NON_BLOCKING_FAILED 2
#define NETCODE_SOCKET_ERROR_SOCKOPT_IPV6_ONLY_FAILED 3
#define NETCODE_SOCKET_ERROR_SOCKOPT_RCVBUF_FAILED 4
#define NETCODE_SOCKET_ERROR_SOCKOPT_SNDBUF_FAILED 5
#define NETCODE_SOCKET_ERROR_BIND_IPV4_FAILED 6
#define NETCODE_SOCKET_ERROR_BIND_IPV6_FAILED 7
#define NETCODE_SOCKET_ERROR_GET_SOCKNAME_IPV4_FAILED 8
#define NETCODE_SOCKET_ERROR_GET_SOCKNAME_IPV6_FAILED 7
void netcode_socket_destroy( struct netcode_socket_t * socket )
{
netcode_assert( socket );
netcode_assert( netcode.initialized );
if ( socket->handle != 0 )
{
#if NETCODE_PLATFORM == NETCODE_PLATFORM_MAC || NETCODE_PLATFORM == NETCODE_PLATFORM_UNIX
close( socket->handle );
#elif NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
closesocket( socket->handle );
#else
#error unsupported platform
#endif
socket->handle = 0;
}
}
int netcode_socket_set_ttl( struct netcode_socket_t * s, int ttl )
{
return setsockopt(s->handle, IPPROTO_IP, IP_TTL, (const char*)(&ttl), sizeof(ttl));
}
int netcode_socket_get_ttl(struct netcode_socket_t * s)
{
int ttl;
socklen_t len = sizeof(ttl);
int result = getsockopt(s->handle, IPPROTO_IP, IP_TTL, (char*)(&ttl), &len);
(void)result;
netcode_assert(0 == result);
return ttl;
}
int netcode_socket_create( struct netcode_socket_t * s, struct netcode_address_t * address, int send_buffer_size, int receive_buffer_size )
{
netcode_assert( s );
netcode_assert( address );
netcode_assert( netcode.initialized );
netcode_assert( address->type != NETCODE_ADDRESS_NONE );
s->address = *address;
// create socket
s->handle = socket( ( address->type == NETCODE_ADDRESS_IPV6 ) ? AF_INET6 : AF_INET, SOCK_DGRAM, IPPROTO_UDP );
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
if ( s->handle == INVALID_SOCKET )
#else // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
if ( s->handle <= 0 )
#endif // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to create socket\n" );
return NETCODE_SOCKET_ERROR_CREATE_FAILED;
}
// force IPv6 only if necessary
if ( address->type == NETCODE_ADDRESS_IPV6 )
{
int yes = 1;
if ( setsockopt( s->handle, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&yes, sizeof(yes) ) != 0 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to set socket ipv6 only\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_SOCKOPT_IPV6_ONLY_FAILED;
}
}
// increase socket send and receive buffer sizes
if ( setsockopt( s->handle, SOL_SOCKET, SO_SNDBUF, (char*)&send_buffer_size, sizeof(int) ) != 0 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to set socket send buffer size\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_SOCKOPT_SNDBUF_FAILED;
}
if ( setsockopt( s->handle, SOL_SOCKET, SO_RCVBUF, (char*)&receive_buffer_size, sizeof(int) ) != 0 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to set socket receive buffer size\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_SOCKOPT_RCVBUF_FAILED;
}
// bind to port
if ( address->type == NETCODE_ADDRESS_IPV6 )
{
struct sockaddr_in6 socket_address;
memset( &socket_address, 0, sizeof( struct sockaddr_in6 ) );
socket_address.sin6_family = AF_INET6;
int i;
for ( i = 0; i < 8; ++i )
{
( (uint16_t*) &socket_address.sin6_addr ) [i] = htons( address->data.ipv6[i] );
}
socket_address.sin6_port = htons( address->port );
if ( bind( s->handle, (struct sockaddr*) &socket_address, sizeof( socket_address ) ) < 0 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to bind socket (ipv6)\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_BIND_IPV6_FAILED;
}
}
else
{
struct sockaddr_in socket_address;
memset( &socket_address, 0, sizeof( socket_address ) );
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = ( ( (uint32_t) address->data.ipv4[0] ) ) |
( ( (uint32_t) address->data.ipv4[1] ) << 8 ) |
( ( (uint32_t) address->data.ipv4[2] ) << 16 ) |
( ( (uint32_t) address->data.ipv4[3] ) << 24 );
socket_address.sin_port = htons( address->port );
if ( bind( s->handle, (struct sockaddr*) &socket_address, sizeof( socket_address ) ) < 0 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to bind socket (ipv4)\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_BIND_IPV4_FAILED;
}
}
// if bound to port 0 find the actual port we got
if ( address->port == 0 )
{
if ( address->type == NETCODE_ADDRESS_IPV6 )
{
struct sockaddr_in6 sin;
socklen_t len = sizeof( sin );
if ( getsockname( s->handle, (struct sockaddr*)&sin, &len ) == -1 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to get socket port (ipv6)\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_GET_SOCKNAME_IPV6_FAILED;
}
s->address.port = ntohs( sin.sin6_port );
}
else
{
struct sockaddr_in sin;
socklen_t len = sizeof( sin );
if ( getsockname( s->handle, (struct sockaddr*)&sin, &len ) == -1 )
{
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: failed to get socket port (ipv4)\n" );
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_GET_SOCKNAME_IPV4_FAILED;
}
s->address.port = ntohs( sin.sin_port );
}
}
// set non-blocking io
#if NETCODE_PLATFORM == NETCODE_PLATFORM_MAC || NETCODE_PLATFORM == NETCODE_PLATFORM_UNIX
int non_blocking = 1;
if ( fcntl( s->handle, F_SETFL, O_NONBLOCK, non_blocking ) == -1 )
{
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_SET_NON_BLOCKING_FAILED;
}
#elif NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
DWORD nonBlocking = 1;
if ( ioctlsocket( s->handle, FIONBIO, &nonBlocking ) != 0 )
{
netcode_socket_destroy( s );
return NETCODE_SOCKET_ERROR_SET_NON_BLOCKING_FAILED;
}
#else
#error unsupported platform
#endif
return NETCODE_SOCKET_ERROR_NONE;
}
void netcode_socket_send_packet( struct netcode_socket_t * socket, struct netcode_address_t * to, void * packet_data, int packet_bytes )
{
netcode_assert( socket );
netcode_assert( socket->handle != 0 );
netcode_assert( to );
netcode_assert( to->type == NETCODE_ADDRESS_IPV6 || to->type == NETCODE_ADDRESS_IPV4 );
netcode_assert( packet_data );
netcode_assert( packet_bytes > 0 );
if ( to->type == NETCODE_ADDRESS_IPV6 )
{
struct sockaddr_in6 socket_address;
memset( &socket_address, 0, sizeof( socket_address ) );
socket_address.sin6_family = AF_INET6;
int i;
for ( i = 0; i < 8; ++i )
{
( (uint16_t*) &socket_address.sin6_addr ) [i] = htons( to->data.ipv6[i] );
}
socket_address.sin6_port = htons( to->port );
int result = sendto( socket->handle, (char*) packet_data, packet_bytes, 0, (struct sockaddr*) &socket_address, sizeof( struct sockaddr_in6 ) );
(void) result;
}
else if ( to->type == NETCODE_ADDRESS_IPV4 )
{
struct sockaddr_in socket_address;
memset( &socket_address, 0, sizeof( socket_address ) );
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = ( ( (uint32_t) to->data.ipv4[0] ) ) |
( ( (uint32_t) to->data.ipv4[1] ) << 8 ) |
( ( (uint32_t) to->data.ipv4[2] ) << 16 ) |
( ( (uint32_t) to->data.ipv4[3] ) << 24 );
socket_address.sin_port = htons( to->port );
int result = sendto( socket->handle, (NETCODE_CONST char*) packet_data, packet_bytes, 0, (struct sockaddr*) &socket_address, sizeof( struct sockaddr_in ) );
(void) result;
}
}
int netcode_socket_receive_packet( struct netcode_socket_t * socket, struct netcode_address_t * from, void * packet_data, int max_packet_size )
{
netcode_assert( socket );
netcode_assert( socket->handle != 0 );
netcode_assert( from );
netcode_assert( packet_data );
netcode_assert( max_packet_size > 0 );
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
typedef int socklen_t;
#endif // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
struct sockaddr_storage sockaddr_from;
socklen_t from_length = sizeof( sockaddr_from );
int result = recvfrom( socket->handle, (char*) packet_data, max_packet_size, 0, (struct sockaddr*) &sockaddr_from, &from_length );
#if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
if ( result == SOCKET_ERROR )
{
int error = WSAGetLastError();
if ( error == WSAEWOULDBLOCK || error == WSAECONNRESET )
return 0;
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: recvfrom failed with error %d\n", error );
return 0;
}
#else // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
if ( result <= 0 )
{
if ( errno == EAGAIN )
return 0;
netcode_printf( NETCODE_LOG_LEVEL_ERROR, "error: recvfrom failed with error %d\n", errno );
return 0;
}
#endif // #if NETCODE_PLATFORM == NETCODE_PLATFORM_WINDOWS
if ( sockaddr_from.ss_family == AF_INET6 )
{
struct sockaddr_in6 * addr_ipv6 = (struct sockaddr_in6*) &sockaddr_from;
from->type = NETCODE_ADDRESS_IPV6;
int i;
for ( i = 0; i < 8; ++i )
{
from->data.ipv6[i] = ntohs( ( (uint16_t*) &addr_ipv6->sin6_addr ) [i] );
}
from->port = ntohs( addr_ipv6->sin6_port );
}
else if ( sockaddr_from.ss_family == AF_INET )
{
struct sockaddr_in * addr_ipv4 = (struct sockaddr_in*) &sockaddr_from;
from->type = NETCODE_ADDRESS_IPV4;
from->data.ipv4[0] = (uint8_t) ( ( addr_ipv4->sin_addr.s_addr & 0x000000FF ) );
from->data.ipv4[1] = (uint8_t) ( ( addr_ipv4->sin_addr.s_addr & 0x0000FF00 ) >> 8 );
from->data.ipv4[2] = (uint8_t) ( ( addr_ipv4->sin_addr.s_addr & 0x00FF0000 ) >> 16 );
from->data.ipv4[3] = (uint8_t) ( ( addr_ipv4->sin_addr.s_addr & 0xFF000000 ) >> 24 );
from->port = ntohs( addr_ipv4->sin_port );
}
else
{
netcode_assert( 0 );
return 0;
}
netcode_assert( result >= 0 );
int bytes_read = result;
return bytes_read;
}
// ----------------------------------------------------------------
void netcode_write_uint8( uint8_t ** p, uint8_t value )
{
**p = value;
++(*p);
}
void netcode_write_uint16( uint8_t ** p, uint16_t value )
{
(*p)[0] = value & 0xFF;
(*p)[1] = value >> 8;
*p += 2;
}
void netcode_write_uint32( uint8_t ** p, uint32_t value )
{
(*p)[0] = value & 0xFF;
(*p)[1] = ( value >> 8 ) & 0xFF;
(*p)[2] = ( value >> 16 ) & 0xFF;
(*p)[3] = value >> 24;
*p += 4;
}
void netcode_write_uint64( uint8_t ** p, uint64_t value )
{
(*p)[0] = value & 0xFF;
(*p)[1] = ( value >> 8 ) & 0xFF;
(*p)[2] = ( value >> 16 ) & 0xFF;
(*p)[3] = ( value >> 24 ) & 0xFF;
(*p)[4] = ( value >> 32 ) & 0xFF;
(*p)[5] = ( value >> 40 ) & 0xFF;
(*p)[6] = ( value >> 48 ) & 0xFF;
(*p)[7] = value >> 56;
*p += 8;
}
void netcode_write_bytes( uint8_t ** p, uint8_t * byte_array, int num_bytes )
{
int i;
for ( i = 0; i < num_bytes; ++i )
{
netcode_write_uint8( p, byte_array[i] );
}
}
uint8_t netcode_read_uint8( uint8_t ** p )
{
uint8_t value = **p;
++(*p);
return value;
}
uint16_t netcode_read_uint16( uint8_t ** p )
{
uint16_t value;
value = (*p)[0];
value |= ( ( (uint16_t)( (*p)[1] ) ) << 8 );
*p += 2;
return value;
}
uint32_t netcode_read_uint32( uint8_t ** p )
{
uint32_t value;
value = (*p)[0];
value |= ( ( (uint32_t)( (*p)[1] ) ) << 8 );
value |= ( ( (uint32_t)( (*p)[2] ) ) << 16 );
value |= ( ( (uint32_t)( (*p)[3] ) ) << 24 );
*p += 4;
return value;
}
uint64_t netcode_read_uint64( uint8_t ** p )
{
uint64_t value;
value = (*p)[0];
value |= ( ( (uint64_t)( (*p)[1] ) ) << 8 );
value |= ( ( (uint64_t)( (*p)[2] ) ) << 16 );
value |= ( ( (uint64_t)( (*p)[3] ) ) << 24 );
value |= ( ( (uint64_t)( (*p)[4] ) ) << 32 );
value |= ( ( (uint64_t)( (*p)[5] ) ) << 40 );
value |= ( ( (uint64_t)( (*p)[6] ) ) << 48 );
value |= ( ( (uint64_t)( (*p)[7] ) ) << 56 );
*p += 8;
return value;
}