forked from RandyGaul/cute_headers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinynet.h
1722 lines (1481 loc) · 47.8 KB
/
tinynet.h
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
/*
tinynet.h - v0.0
*/
/*
docs, blah
*/
// TODO
// make asserts compile out in release
// audit the asserts and add in release mode if statements
#if !defined( TINYNET_H )
#define TN_WINDOWS 1
#define TN_MAC 2
#define TN_UNIX 3
#if defined( _WIN32 )
#define TN_PLATFORM TN_WINDOWS
#elif defined( __APPLE__ )
#define TN_PLATFORM TN_MAC
#else
#define TN_PLATFORM TN_UNIX
#endif
const char* g_tnErrorReason;
#define TN_RELIABLE_BYTE_COUNT 256
#define TN_RELIABLE_WORD_COUNT (TN_RELIABLE_BYTE_COUNT / sizeof( uint32_t ))
// clang is a bitch and aggressively deletes *(int*) = 0
#if TN_PLATFORM == TN_MAC && defined( __clang__ )
#define TN_ASSERT_INTERNAL __builtin_trap( )
#else
#define TN_ASSERT_INTERNAL *(int*)0 = 0
#endif
#define TN_CHECK( X, Y ) do { if ( !(X) ) { g_tnErrorReason = Y; return 0; } } while ( 0 )
#define TN_ASSERT( X ) do { if ( !(X) ) TN_ASSERT_INTERNAL; } while ( 0 )
#define TN_ALIGN( X, Y ) ((((size_t)X) + ((Y) - 1)) & ~((Y) - 1))
#define TN_MAX_ADDRESS_LEN 256
#define TN_PROTOCOL_ID 0xC883FC1D
#define TN_MTU 1200
#define TN_MTU_WORDCOUNT (TN_MTU / sizeof( uint32_t ))
#define TN_PACKET_TYPE_BYTES 4
#define TN_CRC_BYTES 4
#define TN_PACKET_DATA_MAX_SIZE 1024
#define TN_MIN( a, b ) ((a) < (b) ? a : b)
#define TN_MAX( a, b ) ((a) > (b) ? a : b)
#define TN_INT16_MAX ((uint16_t)32768)
#define TN_UINT16_MAX ((uint16_t)~0)
// TODO: create macros to detect platform and setup as necessary
#define TN_BIG_ENDIAN 0
#if TN_BIG_ENDIAN
#define tnEndian( a ) a = tnSWAP_INTERNAL( a )
#else
#define tnEndian( a ) a
#endif
#if TN_PLATFORM == TN_WINDOWS
#define NOMINMAX
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS FUCK_YOU
#define snprintf _snprintf
#include <winsock2.h> // socket
#include <ws2tcpip.h> // WSA stuff
#pragma comment( lib, "ws2_32.lib" )
#elif TN_PLATFORM == TN_MAC || TN_PLATFORM == TN_UNIX
#include <sys/socket.h> // socket
#include <fcntl.h> // fcntl
#include <arpa/inet.h> // inet_pton
#include <unistd.h> // close
#include <errno.h>
#endif
// TODO
// add in preprocessor stuff to use stb_sprintf
#include <stdio.h> // printf (debug only), sprintf
#include <stdint.h>
#include <string.h> // memcpy, memset
#include <stdlib.h> // atoi
#if 1
#define TN_DEBUG_PRINT( ... ) printf( __VA_ARGS__ )
#else
#define TN_DEBUG_PRINT( ... )
#endif
uint16_t tnSWAP_INTERNAL( uint16_t a )
{
return ((a & 0x00FF) << 8)
| ((a & 0xFF00) >> 8);
}
int16_t tnSWAP_INTERNAL( int16_t a )
{
return ((a & 0x00FF) << 8)
| ((a & 0xFF00) >> 8);
}
uint32_t tnSWAP_INTERNAL( uint32_t a )
{
return ((a & 0x000000FF) << 24)
| ((a & 0x0000FF00) << 8)
| ((a & 0x00FF0000) >> 8)
| ((a & 0xFF000000) >> 24);
}
int32_t tnSWAP_INTERNAL( int32_t a )
{
return ((a & 0x000000FF) << 24)
| ((a & 0x0000FF00) << 8)
| ((a & 0x00FF0000) >> 8)
| ((a & 0xFF000000) >> 24);
}
union tnU32F32
{
uint32_t uval;
float fval;
};
union tnU64F64
{
uint64_t uval;
double fval;
};
float tnSWAP_INTERNAL( float a )
{
tnU32F32 u;
u.fval = a;
u.uval = tnSWAP_INTERNAL( u.uval );
return u.fval;
}
uint32_t tnPopCount( uint32_t x )
{
uint32_t a = x - ((x >> 1) & 0x55555555);
uint32_t b = (((a >> 2) & 0x33333333) + (a & 0x33333333));
uint32_t c = (((b >> 4) + b) & 0x0f0f0f0f);
uint32_t d = c + (c >> 8);
uint32_t e = d + (d >> 16);
uint32_t f = e & 0x0000003f;
return f;
}
uint32_t tnLog2( uint32_t x )
{
uint32_t a = x | ( x >> 1 );
uint32_t b = a | ( a >> 2 );
uint32_t c = b | ( b >> 4 );
uint32_t d = c | ( c >> 8 );
uint32_t e = d | ( d >> 16 );
uint32_t f = e >> 1;
return tnPopCount( f );
}
uint32_t tnBitsRequired( uint32_t min, uint32_t max )
{
return (min == max) ? 0 : tnLog2( max - min ) + 1;
}
struct tnBuffer
{
uint64_t bits;
uint32_t count;
uint32_t* words;
uint32_t word_index;
int32_t bits_left;
int32_t bits_total;
};
tnBuffer tnMakeBuffer( uint32_t* words, uint32_t word_count )
{
tnBuffer buffer;
buffer.bits = 0;
buffer.count = 0;
buffer.words = words;
buffer.word_index = 0;
buffer.bits_left = word_count * sizeof( uint32_t ) * 8;
buffer.bits_total = buffer.bits_left;
return buffer;
}
size_t tnSize( tnBuffer* buffer )
{
return TN_ALIGN( buffer->bits_total - buffer->bits_left, 32 ) / 8;
}
int tnWouldOverflow( tnBuffer* buffer, uint32_t num_bits )
{
return buffer->bits_left - (int32_t)num_bits < 0;
}
uint32_t tnReadBits_internal( tnBuffer* buffer, uint32_t num_bits_to_read )
{
TN_ASSERT( num_bits_to_read <= 32 );
TN_ASSERT( num_bits_to_read > 0 );
TN_ASSERT( buffer->bits_left > 0 );
TN_ASSERT( buffer->count <= 64 );
TN_ASSERT( !tnWouldOverflow( buffer, num_bits_to_read ) );
if ( buffer->count < num_bits_to_read )
{
buffer->bits |= (uint64_t)(tnEndian( buffer->words[ buffer->word_index ] )) << buffer->count;
buffer->count += 32;
buffer->word_index += 1;
}
TN_ASSERT( buffer->count >= num_bits_to_read );
uint32_t bits = buffer->bits & (((uint64_t)1 << num_bits_to_read) - 1);
buffer->bits >>= num_bits_to_read;
buffer->count -= num_bits_to_read;
buffer->bits_left -= num_bits_to_read;
return bits;
}
void tnWriteBits( tnBuffer* buffer, uint32_t value, uint32_t num_bits_to_write )
{
TN_ASSERT( buffer );
TN_ASSERT( num_bits_to_write <= 32 );
TN_ASSERT( buffer->bits_left > 0 );
TN_ASSERT( buffer->count <= 32 );
TN_ASSERT( !tnWouldOverflow( buffer, num_bits_to_write ) );
buffer->bits |= (uint64_t)(value & (((uint64_t)1 << num_bits_to_write) - 1)) << buffer->count;
buffer->count += num_bits_to_write;
buffer->bits_left -= num_bits_to_write;
if ( buffer->count >= 32 )
{
buffer->words[ buffer->word_index ] = tnEndian( (uint32_t)(buffer->bits & ((uint32_t)~0)) );
buffer->bits >>= 32;
buffer->count -= 32;
buffer->word_index += 1;
}
}
void tnFlush( tnBuffer* buffer )
{
TN_ASSERT( buffer->count <= 32 );
if ( buffer->count )
{
buffer->words[ buffer->word_index ] = tnEndian( (uint32_t)(buffer->bits & ((uint32_t)~0)) );
}
}
static const uint32_t g_CRC32[ 256 ] = {
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,
0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,
0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,
0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,
0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,
0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,
0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,
0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,
0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,
0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,
0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,
0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,
0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D
};
uint32_t tnCRC32( const void* memory, size_t bytes, uint32_t crc32 )
{
uint8_t* buffer = (uint8_t*)memory;
crc32 = ~crc32;
for ( size_t i = 0; i < bytes; ++i )
crc32 = (crc32 >> 8) ^ g_CRC32[ (crc32 ^ buffer[ i ]) & 0xFF ];
return ~crc32;
}
enum tnAddressType
{
TN_ADDRESS_NONE,
TN_ADDRESS_IPV4,
TN_ADDRESS_IPV6
};
struct tnAddress
{
tnAddressType type;
uint16_t port;
union
{
uint32_t ipv4;
uint16_t ipv6[ 8 ];
};
};
tnAddress tnMakeAddress( uint32_t address, int16_t port )
{
tnAddress addr;
addr.type = TN_ADDRESS_IPV4;
addr.port = port;
addr.ipv4 = htonl( address );
return addr;
}
tnAddress tnMakeAddress( int16_t port )
{
tnAddress addr;
addr.type = TN_ADDRESS_IPV4;
addr.port = port;
addr.ipv4 = htonl( INADDR_ANY );
return addr;
}
tnAddress tnMakeAddress( uint8_t a, uint8_t b, uint8_t c, uint8_t d, int16_t port )
{
uint32_t ipv4 = (uint32_t)a | (uint32_t)b << 8 | (uint32_t)c << 16 | (uint32_t)d << 24;
return tnMakeAddress( ipv4, port );
}
tnAddress tnMakeAddress( sockaddr_storage* sockaddr )
{
TN_ASSERT( sockaddr );
tnAddress addr;
switch ( sockaddr->ss_family )
{
case AF_INET:
{
sockaddr_in* addr_ipv4 = (sockaddr_in*)sockaddr;
addr.type = TN_ADDRESS_IPV4;
addr.port = ntohs( addr_ipv4->sin_port );
addr.ipv4 = addr_ipv4->sin_addr.s_addr;
} break;
case AF_INET6:
{
sockaddr_in6* addr_ipv6 = (sockaddr_in6*)sockaddr;
addr.type = TN_ADDRESS_IPV6;
addr.port = ntohs( addr_ipv6->sin6_port );
memcpy( addr.ipv6, &addr_ipv6->sin6_addr, 16 );
} break;
default: TN_ASSERT( 0 );
}
return addr;
}
tnAddress tnMakeAddress( const char* string )
{
TN_ASSERT( string );
char memory[ TN_MAX_ADDRESS_LEN ];
strncpy( memory, string, TN_MAX_ADDRESS_LEN - 1 );
memory[ TN_MAX_ADDRESS_LEN - 1 ] = 0;
char* buffer = memory;
tnAddress address;
address.type = TN_ADDRESS_NONE;
address.port = 0;
// ipv6 first
// handle [address]:port format first
// then try inet_pton
if ( *buffer == '[' )
{
buffer += 1;
char* search = buffer;
char c;
while ( (c = *search++) )
{
if ( c == ']' )
{
if ( *search == ':' )
{
address.port = (uint16_t)atoi( search + 1 );
search[ -1 ] = 0;
break;
}
}
}
}
in6_addr sockaddr6;
if ( inet_pton( AF_INET6, buffer, &sockaddr6 ) == 1 )
{
memcpy( address.ipv6, &sockaddr6, 16 );
address.type = TN_ADDRESS_IPV6;
return address;
}
// now try ipv4
// first handle format of "address:port"
// then try inet_pton
char* search = buffer;
char c;
while ( (c = *search++) )
{
if ( c == ':' )
{
address.port = (uint16_t)atoi( search );
search[ -1 ] = 0;
break;
}
}
sockaddr_in sockaddr4;
if ( inet_pton( AF_INET, buffer, &sockaddr4.sin_addr ) == 1 )
{
address.type = TN_ADDRESS_IPV4;
address.ipv4 = sockaddr4.sin_addr.s_addr;
return address;
}
return address;
}
void tnAddressString( tnAddress address, char* buffer, int max_buffer_bytes )
{
switch ( address.type )
{
case TN_ADDRESS_IPV4:
{
uint8_t a = address.ipv4 & 0xFF;
uint8_t b = (address.ipv4 >> 8) & 0xFF;
uint8_t c = (address.ipv4 >> 16) & 0xFF;
uint8_t d = (address.ipv4 >> 24) & 0xFF;
if ( address.port ) snprintf( buffer, max_buffer_bytes, "%d.%d.%d.%d:%d", a, b, c, d, address.port );
else snprintf( buffer, max_buffer_bytes, "%d.%d.%d.%d", a, b, c, d );
} break;
case TN_ADDRESS_IPV6:
{
if ( address.port )
{
char inet6_addrstr[ INET6_ADDRSTRLEN ];
inet_ntop( AF_INET6, (void*)address.ipv6, inet6_addrstr, INET6_ADDRSTRLEN );
snprintf( buffer, max_buffer_bytes, "[%s]:%d", inet6_addrstr, address.port );
}
else inet_ntop( AF_INET6, (void*)address.ipv6, buffer, max_buffer_bytes );
} break;
default: TN_ASSERT( 0 );
}
}
int tnAddressEqu( tnAddress a, tnAddress b )
{
if ( a.type != b.type ) return 0;
if ( a.port != b.port ) return 0;
switch ( a.type )
{
case TN_ADDRESS_IPV4: if ( a.ipv4 != b.ipv4 ) return 0; break;
case TN_ADDRESS_IPV6: if ( memcmp( a.ipv6, b.ipv6, sizeof( a.ipv6 ) ) ) return 0; break;
default: TN_ASSERT( 0 );
}
return 1;
}
#if TN_PLATFORM == TN_WINDOWS
typedef SOCKET tnSocketHandle;
#else
typedef int tnSocketHandle;
#endif
enum tnSocketError
{
TN_SOCKET_ERROR_NONE,
TN_SOCKET_ERROR_MAKE_FAILED,
TN_SOCKET_ERROR_SET_NON_BLOCKING_FAILED,
TN_SOCKET_ERROR_SETSOCKOPT_IPV6_ONLY_FAILED,
TN_SOCKET_ERROR_SETSOCKOPT_RCVBUF_FAILED,
TN_SOCKET_ERROR_SETSOCKOPT_SNDBUF_FAILED,
TN_SOCKET_ERROR_BIND_IPV4_FAILED,
TN_SOCKET_ERROR_BIND_IPV6_FAILED,
TN_SOCKET_ERROR_GETSOCKNAME_IPV4_FAILED,
TN_SOCKET_ERROR_GETSOCKNAME_IPV6_FAILED
};
struct tnSocket
{
tnSocketHandle handle;
tnAddress address;
tnSocketError error_code;
};
tnSocket tnMakeSocket( tnAddress address, int buffer_size )
{
tnSocket socket;
socket.error_code = TN_SOCKET_ERROR_NONE;
socket.handle = ::socket( address.type == TN_ADDRESS_IPV6 ? AF_INET6 : AF_INET, SOCK_DGRAM, IPPROTO_UDP );
#if TN_PLATFORM == TN_WINDOWS
if ( socket.handle == INVALID_SOCKET )
#else
if ( socket.handle <= 0 )
#endif
{
socket.error_code = TN_SOCKET_ERROR_MAKE_FAILED;
return socket;
}
// allow users to enforce ipv6 only
// see: https://msdn.microsoft.com/en-us/library/windows/desktop/ms738574(v=vs.85).aspx
if ( address.type == TN_ADDRESS_IPV6 )
{
int enable = 1;
if ( setsockopt( socket.handle, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enable, sizeof( enable ) ) )
{
socket.error_code = TN_SOCKET_ERROR_SETSOCKOPT_IPV6_ONLY_FAILED;
return socket;
}
}
// set socket send/recieve buffer sizes to our chosen size
if ( setsockopt( socket.handle, SOL_SOCKET, SO_RCVBUF, (char*)&buffer_size, sizeof( int ) ) )
{
socket.error_code = TN_SOCKET_ERROR_SETSOCKOPT_RCVBUF_FAILED;
return socket;
}
if ( setsockopt( socket.handle, SOL_SOCKET, SO_SNDBUF, (char*)&buffer_size, sizeof( int ) ) )
{
socket.error_code = TN_SOCKET_ERROR_SETSOCKOPT_SNDBUF_FAILED;
return socket;
}
// bind port
switch ( address.type )
{
case TN_ADDRESS_IPV4:
{
sockaddr_in sock_address;
sock_address.sin_family = AF_INET;
sock_address.sin_addr.s_addr = address.ipv4;
sock_address.sin_port = htons( address.port );
if ( bind( socket.handle, (const sockaddr*)&sock_address, sizeof( sock_address ) ) < 0 )
{
socket.error_code = TN_SOCKET_ERROR_BIND_IPV4_FAILED;
return socket;
}
} break;
case TN_ADDRESS_IPV6:
{
sockaddr_in6 sock_address;
memset( &sock_address, 0, sizeof( sockaddr_in6 ) );
sock_address.sin6_family = AF_INET6;
memcpy( &sock_address.sin6_addr, address.ipv6, sizeof( sock_address.sin6_addr ) );
sock_address.sin6_port = htons( address.port );
if ( bind( socket.handle, (const sockaddr*)&sock_address, sizeof( sock_address ) ) < 0 )
{
socket.error_code = TN_SOCKET_ERROR_BIND_IPV6_FAILED;
return socket;
}
} break;
default: TN_ASSERT( 0 );
}
// handle auto-picked ports
if ( !address.port )
{
if ( address.type == TN_ADDRESS_IPV6 )
{
struct sockaddr_in6 sin;
socklen_t len = sizeof( sin );
if ( getsockname( socket.handle, (struct sockaddr*)&sin, &len ) == -1 )
{
socket.error_code = TN_SOCKET_ERROR_GETSOCKNAME_IPV6_FAILED;
return socket;
}
address.port = ntohs( sin.sin6_port );
}
else
{
struct sockaddr_in sin;
socklen_t len = sizeof( sin );
if ( getsockname( socket.handle, (struct sockaddr*)&sin, &len ) == -1 )
{
socket.error_code = TN_SOCKET_ERROR_GETSOCKNAME_IPV4_FAILED;
return socket;
}
address.port = ntohs( sin.sin_port );
}
}
socket.address = address;
// set non-blocking io
#if TN_PLATFORM == TN_MAC || TN_PLATFORM == TN_UNIX
int nonBlocking = 1;
if ( fcntl( socket.handle, F_SETFL, O_NONBLOCK, nonBlocking ) == -1 )
{
socket.error_code = TN_SOCKET_ERROR_SET_NON_BLOCKING_FAILED;
return socket;
}
#elif TN_PLATFORM == TN_WINDOWS
DWORD nonBlocking = 1;
if ( ioctlsocket( socket.handle, FIONBIO, &nonBlocking ) != 0 )
{
socket.error_code = TN_SOCKET_ERROR_SET_NON_BLOCKING_FAILED;
return socket;
}
#endif
return socket;
}
void tnCloseSocket( tnSocket* socket )
{
if ( socket->handle )
{
#if TN_PLATFORM == TN_MAC || TN_PLATFORM == TN_UNIX
close( socket->handle );
#elif TN_PLATFORM == TN_WINDOWS
closesocket( socket->handle );
#endif
socket->handle = 0;
}
}
typedef void (*tnWrite)( tnBuffer* buffer, void* data );
typedef int (*tnRead)( tnBuffer* buffer, void* data );
typedef int (*tnMeasure)( );
struct tnVTABLE
{
tnWrite Write;
tnRead Read;
tnMeasure Measure;
int runtime_size;
};
struct tnSimPacket
{
int size;
float delay;
struct tnTransport* transport;
tnSimPacket* next;
uint32_t words[ TN_MTU_WORDCOUNT ];
};
struct tnNetSim
{
int latency;
int jitter;
int drop;
int corruption;
int duplicates;
int duplicates_min;
int duplicates_max;
int pool_size;
tnSimPacket* packets;
tnSimPacket* free_list;
tnSimPacket* live_packets;
};
struct tnNetSimDef
{
int latency; // milliseconds, delay before sending packets
int jitter; // milliseconds, random value/sign from 0-jitter
int drop; // percent chance, 0-100, of dropping an outgoing packet
int corruption; // percent chance, 0-100, of corrupting outgoing packets
int duplicates; // percent chance, 0-100, of duplicating outgoing packets
int duplicates_min; // min of range of duplicate packet count
int duplicates_max; // max of range of duplicate packet count
int pool_size; // num of entries for internal pool to buffer outgoing packets
};
// OPTIMIZE
// Can remove this? Modify sequence buffer to handle NO DATA somehow
// perhaps return (void*)1 if sequence exists, keep data pointer 0
struct tnIncomingPacketData
{
};
#define TN_MAX_RELIABLES 64
#define TN_MAX_RELIABLES_BITS_REQUIRED 7
struct tnOutgoingPacketData
{
int acked;
int send_time_milliseconds;
int count;
uint16_t ids[ TN_MAX_RELIABLES ];
};
struct tnReliableData
{
int user_type;
uint32_t data[ TN_RELIABLE_WORD_COUNT ];
};
#define TN_SEQUENCE_BUFFER_SIZE 1024
struct tnSequenceBuffer
{
uint16_t sequence;
uint32_t buffer[ TN_SEQUENCE_BUFFER_SIZE ];
int stride;
char* data;
};
void tnMakeSequenceBuffer( tnSequenceBuffer* buffer, int stride )
{
TN_ASSERT( stride >= 0 );
TN_ASSERT( stride < TN_SEQUENCE_BUFFER_SIZE );
buffer->sequence = 0;
buffer->data = (char*)malloc( stride * TN_SEQUENCE_BUFFER_SIZE );
buffer->stride = stride;
TN_ASSERT( buffer->data );
memset( buffer->data, 0, stride * TN_SEQUENCE_BUFFER_SIZE );
for ( int i = 0; i < TN_SEQUENCE_BUFFER_SIZE; ++i ) buffer->buffer[ i ] = ~0;
}
void tnFreeSequenceBuffer( tnSequenceBuffer* seq_buf )
{
free( seq_buf->data );
memset( seq_buf, 0, sizeof( tnSequenceBuffer ) );
}
void* tnGetSequenceData( tnSequenceBuffer* seq_buf, uint16_t sequence )
{
int index = sequence % TN_SEQUENCE_BUFFER_SIZE;
if ( seq_buf->buffer[ index ] == sequence ) return seq_buf->data + index * seq_buf->stride;
else return 0;
}
int tnSequenceExists( tnSequenceBuffer* seq_buf, uint16_t sequence )
{
int index = sequence % TN_SEQUENCE_BUFFER_SIZE;
return seq_buf->buffer[ index ] != ~0;
}
void tnSequenceRemove( tnSequenceBuffer* seq_buf, uint16_t sequence )
{
int index = sequence % TN_SEQUENCE_BUFFER_SIZE;
seq_buf->buffer[ index ] = ~0;
}
int tnMoreRecent( uint16_t a, uint16_t b )
{
int yes = (a > b) && (a - b <= TN_INT16_MAX);
int yes_wrap = (a < b) && (b - a > TN_INT16_MAX);
return yes || yes_wrap;
}
int tnLessRecent( uint16_t a, uint16_t b )
{
return tnMoreRecent( b, a );
}
void tnClearEntries( uint32_t* seq, int a, int b )
{
if ( b < a ) b += TN_UINT16_MAX;
for ( int i = a; i <= b; ++i ) seq[ i % TN_SEQUENCE_BUFFER_SIZE ] = ~0;
}
void* tnInsertSequence( tnSequenceBuffer* seq_buf, uint16_t sequence )
{
if ( tnMoreRecent( sequence + 1, seq_buf->sequence ) )
{
tnClearEntries( seq_buf->buffer, seq_buf->sequence, sequence );
seq_buf->sequence = sequence + 1;
}
else if ( tnMoreRecent( seq_buf->sequence - TN_SEQUENCE_BUFFER_SIZE, sequence ) ) return 0;
int index = sequence % TN_SEQUENCE_BUFFER_SIZE;
seq_buf->buffer[ index ] = sequence;
return seq_buf->data + index * seq_buf->stride;
}
void tnMakeAck( tnSequenceBuffer* seq, uint16_t* ack, uint32_t* ack_bits )
{
uint16_t local = seq->sequence - 1;
*ack = local;
uint32_t bits = 0;
for ( int i = 0; i < 32; ++i )
{
uint16_t sequence = local - (uint16_t)i;
if ( tnGetSequenceData( seq, sequence ) ) bits |= (1 << i);
}
*ack_bits = bits;
}
struct tnContext
{
float dt;
int time_monotonic_milliseconds;
int rtt;
int vtable_count;
tnVTABLE* vtables;
int use_sim;
tnNetSim sim;
};
int tnPing( tnContext* ctx )
{
int rtt = ctx->rtt;
/*int fuzz = (int)(ctx->dt * 1500.0f + 0.5f);
if ( ctx->use_sim ) fuzz += (int)(ctx->dt * 1000.0f + 0.5f);
if ( rtt - fuzz > 0 ) rtt = rtt - fuzz;
if ( rtt < 4 ) rtt = 4;*/
return rtt;
}
tnVTABLE* tnGetTable( tnContext* ctx, int user_type )
{
TN_ASSERT( user_type >= 0 );
TN_ASSERT( user_type < ctx->vtable_count );
return ctx->vtables + user_type;
}
struct tnTransport
{
const char* debug_name;
tnContext* ctx;
tnSocket socket;
tnAddress to;
tnSequenceBuffer incoming;
tnSequenceBuffer outgoing;
uint16_t reliable_next_incoming;
uint16_t reliable_oldest_unacked;
tnSequenceBuffer reliable_incoming;
tnSequenceBuffer reliable_outgoing;
int has_packet;
uint32_t words[ TN_MTU_WORDCOUNT ];
};
void tnMakeTransport( tnTransport* transport, tnContext* ctx, tnSocket socket, tnAddress to, const char* debug_name )
{
transport->debug_name = debug_name;
transport->ctx = ctx;
transport->socket = socket;
transport->to = to;
transport->has_packet = 0;
tnMakeSequenceBuffer( &transport->incoming, sizeof( tnIncomingPacketData ) );
tnMakeSequenceBuffer( &transport->outgoing, sizeof( tnOutgoingPacketData ) );
transport->reliable_next_incoming = 0;
transport->reliable_oldest_unacked = 0;
tnMakeSequenceBuffer( &transport->reliable_incoming, sizeof( tnReliableData ) );
tnMakeSequenceBuffer( &transport->reliable_outgoing, sizeof( tnReliableData ) );
}
void tnFreeTransport( tnTransport* transport )
{
tnFreeSequenceBuffer( &transport->incoming );
tnFreeSequenceBuffer( &transport->outgoing );
tnFreeSequenceBuffer( &transport->reliable_incoming );
tnFreeSequenceBuffer( &transport->reliable_outgoing );
memset( transport, 0, sizeof( tnTransport ) );
}
void tnAssertTransport( tnTransport* transport )
{
TN_ASSERT( transport );
TN_ASSERT( transport->ctx );
}
void tnWriteStub_internal( tnBuffer* buffer, void* data ) { (void)buffer; (void)data; }
int tnReadStub_internal( tnBuffer* buffer, void* data ) { (void)buffer; (void)data; return 1; }
int tnMeasureStub_internal( ) { return 0; }
int tnRegister( tnContext* ctx, int type_index, tnWrite write, tnRead read, tnMeasure measure, int runtime_size )
{
TN_CHECK( type_index != 0, "tnRegister abort: zero for type_index is reserved for internal use." );
TN_CHECK( type_index > 0, "tnRegister abort: type_index invalid value." );
TN_CHECK( type_index < ctx->vtable_count, "tnRegister abort: type_index invalid value." );
tnVTABLE table = { write, read, measure, runtime_size };
ctx->vtables[ type_index ] = table;
return 1;
}
tnContext* tnInit( int num_packet_types )
{
#if TN_PLATFORM == PLATFORM_WINDOWS
WSADATA WsaData;
WSAStartup( MAKEWORD( 2, 2 ), &WsaData );
#endif
int req = tnBitsRequired( 0, num_packet_types );
TN_CHECK( req < TN_PACKET_TYPE_BYTES * 8, "Please make TN_PACKET_TYPE_NUM_BITS larger." );
tnContext* ctx = (tnContext*)malloc( sizeof( tnContext ) );
ctx->dt = 0;
ctx->rtt = 0;
ctx->time_monotonic_milliseconds = 0;
ctx->vtable_count = num_packet_types;
ctx->vtables = (tnVTABLE*)calloc( 1, sizeof( tnVTABLE ) * num_packet_types );
ctx->use_sim = 0;
tnVTABLE stub = { tnWriteStub_internal, tnReadStub_internal, tnMeasureStub_internal, 0 };
ctx->vtables[ 0 ] = stub;
return ctx;
}
void tnShutdown( tnContext* ctx )
{
#if TN_PLATFORM == PLATFORM_WINDOWS
WSACleanup( );
#endif
free( ctx->vtables );
if ( ctx->use_sim ) free( ctx->sim.packets );
free( ctx );
}
enum tnPacketType_internal
{
TN_PACKET_TYPE_NONE,
TN_PACKET_TYPE_UNRELIABLE, // packet contained no reliable data
TN_PACKET_TYPE_RELIABLE, // packet contained some reliable data
TN_PACKET_TYPE_SLICE, // packet was a chunk slice
TN_PACKET_TYPE_COUNT,
};
// TODO: use this to compress packet header bytes?
#define TN_PACKET_TYPE_BITS_REQUIRED 3
void tnAddNetSim( tnContext* ctx, tnNetSimDef* def )
{
TN_ASSERT( ctx );
tnNetSim* sim = &ctx->sim;
sim->latency = def->latency;
sim->jitter = def->jitter;
sim->drop = def->drop;
sim->corruption = def->corruption;
sim->duplicates = def->duplicates;
sim->duplicates_min = def->duplicates_min;
sim->duplicates_max = def->duplicates_max;
sim->pool_size = def->pool_size;
TN_ASSERT( sim->duplicates_min <= sim->duplicates_max );
TN_ASSERT( sim->duplicates_min >= 0 );
TN_ASSERT( sim->duplicates_max >= 0 );
ctx->use_sim = 1;
sim->packets = (tnSimPacket*)malloc( sizeof( tnSimPacket ) * sim->pool_size );
sim->free_list = sim->packets;
for ( int i = 0; i < sim->pool_size - 1; ++i )
sim->free_list[ i ].next = sim->free_list + i + 1;
sim->free_list[ sim->pool_size - 1 ].next = 0;
sim->live_packets = 0;
}
int tnRandomInt( int a, int b )
{
return a + rand( ) % (b - a + 1);
}
float tnRandomFloat( float a, float b )
{
float x = (float)rand( );
x /= (float)RAND_MAX;
return (b - a) * x + a;
}
int tnSendData_internal( tnSocket socket, tnAddress to, void* data, int bytes );
void tnFlushNetSim( tnContext* ctx )
{
TN_ASSERT( ctx );
TN_ASSERT( ctx->use_sim );
tnNetSim* sim = &ctx->sim;
tnTransport* transport;
int dup, corrupt, drop_chance;
tnSimPacket** ptr = &sim->live_packets;