-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjavelin.c
824 lines (737 loc) · 30.6 KB
/
javelin.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
#define _POSIX_C_SOURCE 200809L
#include "javelin.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#include <sys/types.h>
#endif
#ifndef VERBOSE
#define VERBOSE 0
#endif
enum JavelinError javelinWriteCharArray( struct JavelinMessageBlock* block, const char* buffer, const size_t length )
{
if ( length >= (1 << 16) ) {
return JAVELIN_ERROR_CHAR_ARRAY_TOO_LONG;
}
if ( block->size + sizeof (javelin_u16) + length > JAVELIN_MAX_MESSAGE_SIZE ) {
return JAVELIN_ERROR_MESSAGE_FULL;
}
javelinWriteU16( block, (javelin_u16)length );
memcpy( &block->payload[block->size], buffer, length );
block->size += sizeof (javelin_u16) + length;
return JAVELIN_ERROR_OK;
}
static void writeBufferU8( javelin_u8* buffer, size_t* offset, const javelin_u8 value )
{
buffer[(*offset)++] = value;
}
enum JavelinError javelinWriteU8( struct JavelinMessageBlock* block, const javelin_u8 value )
{
if ( block->size + sizeof (javelin_u8) > JAVELIN_MAX_MESSAGE_SIZE ) {
return JAVELIN_ERROR_MESSAGE_FULL;
}
writeBufferU8( block->payload, &block->size, value );
return JAVELIN_ERROR_OK;
}
static void writeBufferU16( javelin_u8* buffer, size_t* offset, const javelin_u16 value )
{
buffer[(*offset)++] = value & 0xff;
buffer[(*offset)++] = (value >> 8) & 0xff;
}
enum JavelinError javelinWriteU16( struct JavelinMessageBlock* block, const javelin_u16 value )
{
if ( block->size + sizeof (javelin_u16) > JAVELIN_MAX_MESSAGE_SIZE ) {
return JAVELIN_ERROR_MESSAGE_FULL;
}
writeBufferU16( block->payload, &block->size, value );
return JAVELIN_ERROR_OK;
}
enum JavelinError javelinWriteS16( struct JavelinMessageBlock* block, const javelin_s16 value )
{
return javelinWriteU16( block, (javelin_u16)value );
}
static void writeBufferU32( javelin_u8* buffer, size_t* offset, const javelin_u32 value )
{
buffer[(*offset)++] = value & 0xff;
buffer[(*offset)++] = (value >> 8) & 0xff;
buffer[(*offset)++] = (value >> 16) & 0xff;
buffer[(*offset)++] = (value >> 24) & 0xff;
}
enum JavelinError javelinWriteU32( struct JavelinMessageBlock* block, const javelin_u32 value )
{
if ( block->size + sizeof (javelin_u32) > JAVELIN_MAX_MESSAGE_SIZE ) {
return JAVELIN_ERROR_MESSAGE_FULL;
}
writeBufferU32( block->payload, &block->size, value );
return JAVELIN_ERROR_OK;
}
enum JavelinError javelinWriteS32( struct JavelinMessageBlock* block, const javelin_s32 value )
{
return javelinWriteU32( block, (javelin_u32)value );
}
static void writeBufferU64( javelin_u8* buffer, size_t* offset, const javelin_u64 value )
{
buffer[(*offset)++] = value & 0xff;
buffer[(*offset)++] = (value >> 8) & 0xff;
buffer[(*offset)++] = (value >> 16) & 0xff;
buffer[(*offset)++] = (value >> 24) & 0xff;
buffer[(*offset)++] = (value >> 32) & 0xff;
buffer[(*offset)++] = (value >> 40) & 0xff;
buffer[(*offset)++] = (value >> 48) & 0xff;
buffer[(*offset)++] = (value >> 56) & 0xff;
}
enum JavelinError javelinWriteU64( struct JavelinMessageBlock* block, const javelin_u64 value )
{
if ( block->size + sizeof (javelin_u64) > JAVELIN_MAX_MESSAGE_SIZE ) {
return JAVELIN_ERROR_MESSAGE_FULL;
}
writeBufferU64( block->payload, &block->size, value );
return JAVELIN_ERROR_OK;
}
enum JavelinError javelinWriteS64( struct JavelinMessageBlock* block, const javelin_s64 value )
{
return javelinWriteU64( block, (javelin_u64)value );
}
size_t javelinReadCharArray( struct JavelinMessageBlock* block, char* buffer, const size_t bufferSize )
{
if ( block->incomingReadOffset > block->size ) {
return 0;
}
const size_t length = javelinReadU16( block );
if ( block->incomingReadOffset + length > block->size ) {
return 0;
}
const size_t copyCount = length < bufferSize ? bufferSize : length;
memcpy( buffer, &block->payload[block->incomingReadOffset], copyCount );
block->incomingReadOffset += copyCount;
return length;
}
static javelin_u8 readBufferU8( const javelin_u8* buffer, size_t* offset )
{
const javelin_u8 v = buffer[(*offset)++];
return v;
}
javelin_u8 javelinReadU8( struct JavelinMessageBlock* block )
{
if ( block->incomingReadOffset + sizeof (javelin_u8) > block->size ) {
return 0;
}
return readBufferU8( block->payload, &block->incomingReadOffset );
}
static javelin_u16 readBufferU16( const javelin_u8* buffer, size_t* offset )
{
const javelin_u8 v1 = buffer[(*offset)++];
const javelin_u8 v2 = buffer[(*offset)++];
return ((javelin_u16)v1) | ((javelin_u16)v2 << 8);
}
javelin_u16 javelinReadU16( struct JavelinMessageBlock* block )
{
if ( block->incomingReadOffset + sizeof (javelin_u16) > block->size ) {
return 0;
}
return readBufferU16( block->payload, &block->incomingReadOffset );
}
javelin_s16 javelinReadS16( struct JavelinMessageBlock* block )
{
const javelin_u16 value = javelinReadU16( block );
if ( value < ((javelin_u16)1 << 15) ) {
return (javelin_s16)value;
}
return -(javelin_s16)(-value);
}
static javelin_u32 readBufferU32( const javelin_u8* buffer, size_t* offset )
{
const javelin_u8 v1 = buffer[(*offset)++];
const javelin_u8 v2 = buffer[(*offset)++];
const javelin_u8 v3 = buffer[(*offset)++];
const javelin_u8 v4 = buffer[(*offset)++];
return ((javelin_u32)v1) | ((javelin_u32)v2 << 8) | ((javelin_u32)v3 << 16) | ((javelin_u32)v4 << 24);
}
javelin_u32 javelinReadU32( struct JavelinMessageBlock* block )
{
if ( block->incomingReadOffset + sizeof (javelin_u32) > block->size ) {
return 0;
}
return readBufferU32( block->payload, &block->incomingReadOffset );
}
javelin_s32 javelinReadS32( struct JavelinMessageBlock* block )
{
javelin_u32 value = javelinReadU32( block );
if ( value < ((javelin_u32)1 << 31) ) {
return (javelin_s32)value;
}
return -(javelin_s32)(-value);
}
static javelin_u64 readBufferU64( const javelin_u8* buffer, size_t* offset )
{
const javelin_u8 v1 = buffer[(*offset)++];
const javelin_u8 v2 = buffer[(*offset)++];
const javelin_u8 v3 = buffer[(*offset)++];
const javelin_u8 v4 = buffer[(*offset)++];
const javelin_u8 v5 = buffer[(*offset)++];
const javelin_u8 v6 = buffer[(*offset)++];
const javelin_u8 v7 = buffer[(*offset)++];
const javelin_u8 v8 = buffer[(*offset)++];
return ((javelin_u64)v1) | ((javelin_u64)v2 << 8) | ((javelin_u64)v3 << 16) | ((javelin_u64)v4 << 24) | ((javelin_u64)v5 << 32) | ((javelin_u64)v6 << 40) | ((javelin_u64)v7 << 48) | ((javelin_u64)v8 << 56);
}
javelin_u64 javelinReadU64( struct JavelinMessageBlock* block )
{
if ( block->incomingReadOffset + sizeof (javelin_u64) > block->size ) {
return 0;
}
return readBufferU64( block->payload, &block->incomingReadOffset );
}
javelin_s64 javelinReadS64( struct JavelinMessageBlock* block )
{
javelin_u64 value = javelinReadU64( block );
if ( value < ((javelin_u64)1 << 63) ) {
return (javelin_s64)value;
}
return -(javelin_s64)(-value);
}
static javelin_u64 getCurrentTime( void )
{
struct timespec ts;
timespec_get( &ts, TIME_UTC );
return ((javelin_u64)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000));
}
enum JavelinError javelinCreate( struct JavelinState* state, const char* address, const javelin_u16 port, const javelin_u32 maxConnections, javelin_u32 (*randomGenerator)( void ) )
{
static_assert( JAVELIN_MAX_PACKET_SIZE > sizeof (struct JavelinPacketHeader) + sizeof (javelin_u16) + sizeof (javelin_u16) + JAVELIN_MAX_MESSAGE_SIZE, "Max message size is too large to fit in a packet" );
static_assert( (JAVELIN_MAX_MESSAGES & (JAVELIN_MAX_MESSAGES - 1)) == 0, "Max number of messages must be a power of two" );
if ( randomGenerator == NULL ) {
return JAVELIN_ERROR_RANDOM_GENERATOR_REQUIRED;
}
memset( state, 0, sizeof (struct JavelinState) );
#ifdef _WIN32
WSADATA wsaData;
int wsaResult = WSAStartup( MAKEWORD(1,1), &wsaData );
if ( wsaResult != 0 ) {
return JAVELIN_ERROR_WINSOCK;
}
if ( LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1 ) {
WSACleanup();
return JAVELIN_ERROR_WINSOCK;
}
#endif
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ( address == NULL ) {
hints.ai_flags = AI_PASSIVE;
}
char portString[10];
snprintf( portString, sizeof (portString), "%i", port );
struct addrinfo* addrResults;
int aiStatus = getaddrinfo( address, portString, &hints, &addrResults );
if ( aiStatus != 0 ) {
return JAVELIN_ERROR_GETADDRINFO;
}
struct addrinfo* addr;
for ( addr = addrResults; addr != NULL; addr = addr->ai_next ) {
state->socket = socket( addr->ai_family, addr->ai_socktype, addr->ai_protocol );
if ( state->socket == -1 ) {
continue;
}
int bindResult = bind( state->socket, addr->ai_addr, addr->ai_addrlen );
if ( bindResult == -1 ) {
// TODO: close socket cross-platform
continue;
}
if ( addr->ai_family == AF_INET ) {
memcpy( &state->address, addr->ai_addr, sizeof (struct sockaddr_in) );
}
else {
memcpy( &state->address, addr->ai_addr, sizeof (struct sockaddr_in6) );
int v6Only = 0;
setsockopt( state->socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6Only, sizeof (v6Only) );
}
#ifdef _WIN32
DWORD nonBlocking = 1;
int nbResult = ioctlsocket( state->socket, FIONBIO, &nonBlocking );
if ( nbResult != 0 ) {
return JAVELIN_ERROR_WINSOCK;
}
#else
fcntl( state->socket, F_SETFL, O_NONBLOCK );
#endif
break;
}
if ( addr == NULL ) {
return JAVELIN_ERROR_SOCKET;
}
freeaddrinfo( addrResults );
state->connectionLimit = maxConnections > 0 ? maxConnections : 1;
state->connectionSlots = (struct JavelinConnection*)malloc( sizeof (struct JavelinConnection) * state->connectionLimit );
if ( state->connectionSlots == 0 ) {
return JAVELIN_ERROR_MEMORY;
}
memset( state->connectionSlots, 0, sizeof (struct JavelinConnection) * state->connectionLimit );
state->randomGenerator = randomGenerator;
return JAVELIN_ERROR_OK;
}
void javelinDestroy( struct JavelinState* state )
{
if ( state->socket != 0 ) {
#ifdef _WIN32
closesocket( state->socket );
#else
close( state->socket );
#endif
}
state->socket = 0;
free( state->connectionSlots );
#ifdef _WIN32
WSACleanup();
#endif
}
static bool isSaltGood( struct JavelinConnection* connection, javelin_u32 salt )
{
return connection->remoteSalt != 0 && (salt ^ connection->localSalt) == connection->remoteSalt;
}
static javelin_u32 calculateSalt( struct JavelinConnection* connection )
{
return connection->localSalt ^ connection->remoteSalt;
}
static void writePacketHeader( struct JavelinState* state, enum JavelinPacketType type, javelin_u32 ackId, javelin_u32 salt )
{
state->outgoingPacketSize = 0;
writeBufferU8( state->outgoingPacketBuffer, &state->outgoingPacketSize, type );
writeBufferU16( state->outgoingPacketBuffer, &state->outgoingPacketSize, ackId );
writeBufferU32( state->outgoingPacketBuffer, &state->outgoingPacketSize, salt );
}
static void sendPacket( struct JavelinState* state, struct sockaddr_storage* address )
{
int result = sendto( state->socket, state->outgoingPacketBuffer, state->outgoingPacketSize, 0, (struct sockaddr*)address, sizeof (struct sockaddr_storage) );
if ( result < 0 ) {
// TODO: Do we care about this error? Count errors towards a forced disconnect?
if ( VERBOSE ) printf( "net: sendto error: %i\n", errno );
}
}
enum JavelinError javelinConnect( struct JavelinState* state, const char* address, const javelin_u16 port )
{
if ( address == NULL || port == 0 ) {
return JAVELIN_ERROR_INVALID_ADDRESS;
}
struct JavelinConnection* connection = NULL;
for ( size_t i = 0; i < state->connectionLimit; i++ ) {
if ( state->connectionSlots[i].isActive ) {
continue;
}
connection = &state->connectionSlots[i];
memset( connection, 0, sizeof (struct JavelinConnection) );
connection->slot = i;
break;
}
if ( connection == NULL ) {
return JAVELIN_ERROR_CONNECTION_LIMIT;
}
char portString[10];
snprintf( portString, sizeof (portString), "%i", port );
struct addrinfo hints = {0};
hints.ai_family = state->address.ss_family;
hints.ai_socktype = SOCK_DGRAM;
struct addrinfo* addr;
int aiStatus = getaddrinfo( address, portString, &hints, &addr );
if ( aiStatus != 0 || addr == NULL ) {
return JAVELIN_ERROR_GETADDRINFO;
}
if ( addr->ai_family == AF_INET ) {
memcpy( &connection->address, addr->ai_addr, sizeof (struct sockaddr_in) );
}
else {
memcpy( &connection->address, addr->ai_addr, sizeof (struct sockaddr_in6) );
}
javelin_u64 currentTimeMs = getCurrentTime();
connection->isActive = true;
connection->connectionState = JAVELIN_CONNECTIONSTATE_CONNECTING;
connection->retryTime = JAVELIN_DEFAULT_RETRY_TIME_MS;
connection->localSalt = state->randomGenerator();
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_REQUEST\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_REQUEST, 0, connection->localSalt );
sendPacket( state, &connection->address );
connection->lastSendTime = currentTimeMs;
connection->lastReceiveTime = currentTimeMs;
freeaddrinfo( addr );
return JAVELIN_ERROR_OK;
}
void javelinDisconnect( struct JavelinState* state )
{
// TODO: Consider whether we need to use this on the server side to disconnect all clients
struct JavelinConnection* connection = NULL;
for ( size_t i = 0; i < state->connectionLimit; i++ ) {
if ( !state->connectionSlots[i].isActive ) {
continue;
}
connection = &state->connectionSlots[i];
break;
}
if ( connection == NULL ) {
return;
}
connection->connectionState = JAVELIN_CONNECTIONSTATE_DISCONNECTING;
// TODO: decide when we're fully disconnected
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_DISCONNECT\n" );
writePacketHeader( state, JAVELIN_PACKET_DISCONNECT, 0, calculateSalt( connection ) );
sendPacket( state, &connection->address );
}
static bool isSameConnection( struct sockaddr_storage* first, struct sockaddr_storage* second )
{
if ( first->ss_family != second->ss_family ) {
return false;
}
if ( first->ss_family == AF_INET ) {
struct sockaddr_in* first4 = (struct sockaddr_in*)first;
struct sockaddr_in* second4 = (struct sockaddr_in*)second;
if ( second4->sin_addr.s_addr == first4->sin_addr.s_addr && second4->sin_port == first4->sin_port ) {
return true;
}
}
else if ( first->ss_family == AF_INET6 ) {
struct sockaddr_in6* first6 = (struct sockaddr_in6*)first;
struct sockaddr_in6* second6 = (struct sockaddr_in6*)second;
if ( memcmp( second6->sin6_addr.s6_addr, first6->sin6_addr.s6_addr, 16 ) == 0 && second6->sin6_port == first6->sin6_port ) {
return true;
}
}
return false;
}
static bool idIsGreater( const javelin_u32 first, javelin_u32 second )
{
return ((first > second) && (first - second <= (1 << 15))) ||
((first < second) && (second - first > (1 << 15)));
}
bool javelinProcess( struct JavelinState* state, struct JavelinEvent* outEvent )
{
javelin_u64 currentTimeMs = getCurrentTime();
// TODO: add unreliable message buffer
// TODO: add bandwidth tracking to adjust packet size or number sent
for ( size_t slot = 0; slot < state->connectionLimit; slot++ ) {
struct JavelinConnection* connection = &state->connectionSlots[slot];
if ( !connection->isActive ) {
continue;
}
if ( connection->outgoingLastIdSent == connection->outgoingLastIdAcknowledged ) {
continue;
}
size_t messageIndex = (connection->outgoingLastIdAcknowledged + 1) % JAVELIN_MAX_MESSAGES;
size_t lastIndex = (connection->outgoingLastIdSent + 1) % JAVELIN_MAX_MESSAGES;
while ( messageIndex != lastIndex ) {
writePacketHeader( state, JAVELIN_PACKET_DATA, connection->incomingLastIdProcessed, calculateSalt( connection ) );
bool messagesToSend = false;
while ( messageIndex != lastIndex ) {
struct JavelinMessageBlock* block = &connection->outgoingMessageBuffer[messageIndex];
if ( state->outgoingPacketSize + sizeof (javelin_u16) + sizeof (javelin_u16) + block->size > JAVELIN_MAX_PACKET_SIZE ) {
break;
}
if ( block->outgoingLastSendTime == 0 || (currentTimeMs - block->outgoingLastSendTime) > connection->retryTime ) {
if ( VERBOSE ) printf( "net: queuing message to send: id = %i, size = %zu\n", block->messageId, block->size );
// message header
writeBufferU16( state->outgoingPacketBuffer, &state->outgoingPacketSize, block->messageId );
writeBufferU16( state->outgoingPacketBuffer, &state->outgoingPacketSize, block->size );
memcpy( &state->outgoingPacketBuffer[state->outgoingPacketSize], block->payload, block->size );
state->outgoingPacketSize += block->size;
block->outgoingLastSendTime = currentTimeMs;
messagesToSend = true;
}
messageIndex = (messageIndex + 1) % JAVELIN_MAX_MESSAGES;
}
if ( messagesToSend ) {
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_DATA\n" );
sendPacket( state, &connection->address );
connection->lastSendTime = currentTimeMs;
}
}
}
// Scan all connections for connection packets to resend
for ( size_t slot = 0; slot < state->connectionLimit; slot++ ) {
struct JavelinConnection* connection = &state->connectionSlots[slot];
if ( !connection->isActive ) {
continue;
}
if ( currentTimeMs - connection->lastSendTime < connection->retryTime ) {
continue;
}
if ( connection->connectionState == JAVELIN_CONNECTIONSTATE_CONNECTING ) {
if ( connection->remoteSalt == 0 ) {
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_REQUEST\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_REQUEST, 0, connection->localSalt );
sendPacket( state, &connection->address );
connection->lastSendTime = currentTimeMs;
}
else {
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE, 0, calculateSalt( connection ) );
sendPacket( state, &connection->address );
connection->lastSendTime = currentTimeMs;
}
}
}
// Scan all connections and pendingConnections for timeouts
size_t pendingConnectionIndex = 0;
while ( pendingConnectionIndex < state->pendingConnectionCount ) {
struct JavelinPendingConnection* pendingConnection = &state->pendingConnectionSlots[pendingConnectionIndex];
if ( currentTimeMs - pendingConnection->lastReceiveTime >= JAVELIN_CONNECTION_TIMEOUT_MS ) {
if ( VERBOSE ) printf( "net: pending connection timeout: %zu\n", pendingConnectionIndex );
*pendingConnection = state->pendingConnectionSlots[--state->pendingConnectionCount];
}
else {
pendingConnectionIndex++;
}
}
for ( size_t slot = 0; slot < state->connectionLimit; slot++ ) {
struct JavelinConnection* connection = &state->connectionSlots[slot];
if ( !connection->isActive ) {
continue;
}
if ( currentTimeMs - connection->lastReceiveTime >= JAVELIN_CONNECTION_TIMEOUT_MS ) {
if ( VERBOSE ) printf( "connection timeout for slot %zu\n", slot );
connection->isActive = false;
connection->connectionState = JAVELIN_CONNECTIONSTATE_DISCONNECTED;
outEvent->connection = connection;
outEvent->type = JAVELIN_EVENT_DISCONNECT;
return true;
}
else if ( currentTimeMs - connection->lastSendTime >= connection->retryTime && connection->connectionState == JAVELIN_CONNECTIONSTATE_CONNECTED ) {
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_PING (%i)\n", connection->incomingLastIdProcessed );
writePacketHeader( state, JAVELIN_PACKET_PING, connection->incomingLastIdProcessed, calculateSalt( connection ) );
sendPacket( state, &connection->address );
connection->lastSendTime = currentTimeMs;
}
}
// Keep reading packets until we have a message to return
while ( true ) {
struct JavelinConnection* lastPacketConnection = &state->connectionSlots[state->incomingLastPacketSlot];
const javelin_u32 nextIndex = (lastPacketConnection->incomingLastIdProcessed + 1) & 0xffff;
const javelin_u32 messageIndex = nextIndex % JAVELIN_MAX_MESSAGES;
if ( lastPacketConnection->incomingMessageBuffer[messageIndex].messageId == nextIndex ) {
if ( VERBOSE ) printf( "returning queued message %u\n", lastPacketConnection->incomingMessageBuffer[messageIndex].messageId );
outEvent->connection = lastPacketConnection;
outEvent->type = JAVELIN_EVENT_DATA;
outEvent->message = &lastPacketConnection->incomingMessageBuffer[messageIndex];
lastPacketConnection->incomingLastIdProcessed = nextIndex;
return true;
}
struct sockaddr_storage fromAddress;
int fromLength = sizeof (fromAddress);
javelin_u8 packetBuffer[JAVELIN_MAX_PACKET_SIZE];
int receivedLength = recvfrom( state->socket, packetBuffer, JAVELIN_MAX_PACKET_SIZE, 0, (struct sockaddr*)&fromAddress, (socklen_t*)&fromLength );
if ( receivedLength <= 0 ) {
if ( receivedLength == -1 && errno != EAGAIN && errno != EWOULDBLOCK ) {
// TODO: Do we care about this error? Count errors towards a forced disconnect?
if ( VERBOSE ) printf( "net: recvfrom error: %i\n", errno );
}
return false;
}
size_t readOffset = 0;
struct JavelinPacketHeader packetHeader;
packetHeader.type = readBufferU8( packetBuffer, &readOffset );
packetHeader.ackMessageId = readBufferU16( packetBuffer, &readOffset );
packetHeader.salt = readBufferU32( packetBuffer, &readOffset );
struct JavelinConnection* packetConnection = NULL;
for ( size_t slot = 0; slot < state->connectionLimit; slot++ ) {
struct JavelinConnection* connection = &state->connectionSlots[slot];
if ( !connection->isActive ) {
continue;
}
if ( isSameConnection( &fromAddress, &connection->address ) ) {
packetConnection = connection;
state->incomingLastPacketSlot = slot;
break;
}
}
if ( packetConnection == NULL ) {
struct JavelinPendingConnection* pendingConnection = NULL;
for ( size_t slot = 0; slot < state->pendingConnectionCount; slot++ ) {
struct JavelinPendingConnection* connection = &state->pendingConnectionSlots[slot];
if ( connection->connectionState == JAVELIN_CONNECTIONSTATE_NONE ) {
continue;
}
if ( isSameConnection( &fromAddress, &connection->address ) ) {
pendingConnection = connection;
break;
}
}
if ( pendingConnection == NULL ) {
if ( state->pendingConnectionCount == JAVELIN_MAX_PENDING_CONNECTIONS ) {
if ( VERBOSE ) printf( "net: server full: %i = %i\n", state->pendingConnectionCount, JAVELIN_MAX_PENDING_CONNECTIONS );
writePacketHeader( state, JAVELIN_PACKET_SERVER_FULL, 0, packetHeader.salt );
sendPacket( state, &fromAddress );
continue; // next packet, no room for another connection attempt
}
if ( VERBOSE ) printf( "net: new pending slot: %i\n", state->pendingConnectionCount );
pendingConnection = &state->pendingConnectionSlots[state->pendingConnectionCount++];
memset( pendingConnection, 0, sizeof (struct JavelinPendingConnection) );
pendingConnection->address = fromAddress;
pendingConnection->connectionState = JAVELIN_CONNECTIONSTATE_NONE;
pendingConnection->localSalt = state->randomGenerator();
}
pendingConnection->lastReceiveTime = currentTimeMs;
if ( packetHeader.type == JAVELIN_PACKET_CONNECT_REQUEST ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_CONNECT_REQUEST\n" );
if ( packetHeader.salt != 0 ) {
pendingConnection->remoteSalt = packetHeader.salt;
pendingConnection->connectionState = JAVELIN_CONNECTIONSTATE_CONNECTING;
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_CHALLENGE\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_CHALLENGE, 0, pendingConnection->remoteSalt );
writeBufferU32( state->outgoingPacketBuffer, &state->outgoingPacketSize, pendingConnection->localSalt );
sendPacket( state, &pendingConnection->address );
pendingConnection->lastSendTime = currentTimeMs;
}
}
else if ( packetHeader.type == JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE && pendingConnection->connectionState == JAVELIN_CONNECTIONSTATE_CONNECTING ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE\n" );
if ( (packetHeader.salt ^ pendingConnection->remoteSalt) != pendingConnection->localSalt ) {
if ( VERBOSE ) printf( "net: bad salt\n" );
continue; // next packet
}
javelin_s32 availableSlot = -1;
for ( size_t slot = 0; slot < state->connectionLimit; slot++ ) {
struct JavelinConnection* connection = &state->connectionSlots[slot];
if ( !connection->isActive ) {
availableSlot = slot;
break;
}
}
if ( availableSlot == -1 ) {
// TODO: send "server full" packet
if ( VERBOSE ) printf( "net: server full\n" );
*pendingConnection = state->pendingConnectionSlots[--state->pendingConnectionCount];
continue; // next packet
}
struct JavelinConnection* connection = &state->connectionSlots[availableSlot];
memset( connection, 0, sizeof (struct JavelinConnection) );
connection->isActive = true;
connection->slot = availableSlot;
connection->address = pendingConnection->address;
connection->connectionState = JAVELIN_CONNECTIONSTATE_CONNECTED;
connection->localSalt = pendingConnection->localSalt;
connection->remoteSalt = pendingConnection->remoteSalt;
connection->retryTime = JAVELIN_DEFAULT_RETRY_TIME_MS;
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_ACCEPT\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_ACCEPT, 0, calculateSalt( connection ) );
sendPacket( state, &connection->address );
connection->lastSendTime = currentTimeMs;
connection->lastReceiveTime = currentTimeMs;
outEvent->connection = connection;
outEvent->type = JAVELIN_EVENT_CONNECT;
return true;
}
continue; // next packet
}
packetConnection->lastReceiveTime = currentTimeMs;
if ( idIsGreater( packetHeader.ackMessageId, packetConnection->outgoingLastIdAcknowledged ) ) {
packetConnection->outgoingLastIdAcknowledged = packetHeader.ackMessageId;
if ( VERBOSE ) printf( "net: acknowledged up to %u\n", packetConnection->outgoingLastIdAcknowledged );
}
if ( packetConnection->connectionState == JAVELIN_CONNECTIONSTATE_CONNECTING ) {
if ( packetHeader.type == JAVELIN_PACKET_CONNECT_CHALLENGE ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_CONNECT_CHALLENGE\n" );
if ( packetHeader.salt == packetConnection->localSalt ) {
packetConnection->remoteSalt = readBufferU32( packetBuffer, &readOffset );
if ( packetConnection->remoteSalt != 0 ) {
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE, 0, calculateSalt( packetConnection ) );
sendPacket( state, &packetConnection->address );
packetConnection->lastSendTime = currentTimeMs;
}
}
}
else if ( packetHeader.type == JAVELIN_PACKET_CONNECT_ACCEPT && isSaltGood( packetConnection, packetHeader.salt ) ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_CONNECT_ACCEPT\n" );
packetConnection->connectionState = JAVELIN_CONNECTIONSTATE_CONNECTED;
outEvent->connection = packetConnection;
outEvent->type = JAVELIN_EVENT_CONNECT;
return true;
}
else if ( packetHeader.type == JAVELIN_PACKET_CONNECT_REJECT && isSaltGood( packetConnection, packetHeader.salt ) ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_CONNECT_REJECT\n" );
packetConnection->connectionState = JAVELIN_CONNECTIONSTATE_DISCONNECTED;
outEvent->connection = packetConnection;
outEvent->type = JAVELIN_EVENT_DISCONNECT;
return true;
}
}
else if ( packetConnection->connectionState == JAVELIN_CONNECTIONSTATE_CONNECTED && isSaltGood( packetConnection, packetHeader.salt ) ) {
if ( packetHeader.type == JAVELIN_PACKET_DATA ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_DATA\n" );
while ( readOffset < (size_t)receivedLength ) {
// message header
const javelin_u16 id = readBufferU16( packetBuffer, &readOffset );
const javelin_u32 size = readBufferU16( packetBuffer, &readOffset );
if ( VERBOSE ) printf( " received message: id = %i, size = %i\n", id, size );
if ( readOffset + size > (size_t)receivedLength ) {
// If reported size is bad, ignore the rest of the packet
if ( VERBOSE ) printf( " reported size %zu larger than %u, aborting packet\n", readOffset + size, receivedLength );
break;
}
if ( id - packetConnection->incomingLastIdProcessed < JAVELIN_MAX_MESSAGES ) {
if ( VERBOSE ) printf( " storing message %u (to slot %u)\n", id, id % JAVELIN_MAX_MESSAGES );
struct JavelinMessageBlock* block = &packetConnection->incomingMessageBuffer[id % JAVELIN_MAX_MESSAGES];
block->messageId = id;
block->incomingReadOffset = 0;
block->size = size;
memcpy( block->payload, &packetBuffer[readOffset], size );
}
else {
if ( VERBOSE ) printf( " ignoring message %u (too old)\n", id );
}
readOffset += size;
}
}
else if ( packetHeader.type == JAVELIN_PACKET_PING ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_PING\n" );
// nothing
}
else if ( packetHeader.type == JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_CONNECT_CHALLENGE_RESPONSE\n" );
// We think the client is already connected, but they may not have received the accept packet
if ( VERBOSE ) printf( "net: Send packet: JAVELIN_PACKET_CONNECT_ACCEPT\n" );
writePacketHeader( state, JAVELIN_PACKET_CONNECT_ACCEPT, 0, calculateSalt( packetConnection ) );
sendPacket( state, &packetConnection->address );
packetConnection->lastSendTime = currentTimeMs;
}
else if ( packetHeader.type == JAVELIN_PACKET_DISCONNECT ) {
if ( VERBOSE ) printf( "net: Received JAVELIN_PACKET_DISCONNECT\n" );
packetConnection->isActive = false;
packetConnection->connectionState = JAVELIN_CONNECTIONSTATE_DISCONNECTED;
outEvent->connection = packetConnection;
outEvent->type = JAVELIN_EVENT_DISCONNECT;
return true;
}
}
}
return false;
}
struct JavelinMessageBlock javelinCreateMessage( void )
{
// .size field must be initialized to zero before writing to a message
return (struct JavelinMessageBlock) { 0 };
}
enum JavelinError javelinQueueMessage( struct JavelinConnection* connection, struct JavelinMessageBlock* block )
{
if ( block->size == 0 || block->size > JAVELIN_MAX_MESSAGE_SIZE ) {
if ( VERBOSE ) printf( "net: Unable to queue message: invalid\n" );
return JAVELIN_ERROR_INVALID_MESSAGE;
}
if ( (connection->outgoingLastIdSent - connection->outgoingLastIdAcknowledged) >= JAVELIN_MAX_MESSAGES ) {
if ( VERBOSE ) printf( "net: Unable to queue message: buffer full\n" );
return JAVELIN_ERROR_MESSAGE_BUFFER_FULL;
}
const javelin_u32 messageIndex = (connection->outgoingLastIdSent + 1) % JAVELIN_MAX_MESSAGES;
struct JavelinMessageBlock* outgoingBlock = &connection->outgoingMessageBuffer[messageIndex];
memcpy( outgoingBlock->payload, block->payload, block->size );
outgoingBlock->size = block->size;
outgoingBlock->messageId = ++connection->outgoingLastIdSent & 0xffff;
outgoingBlock->outgoingLastSendTime = 0;
if ( VERBOSE ) printf( "net: message queued as %i\n", outgoingBlock->messageId );
return JAVELIN_ERROR_OK;
}