-
Notifications
You must be signed in to change notification settings - Fork 269
/
cute_net.h
12370 lines (10385 loc) · 397 KB
/
cute_net.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
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
cute_net.h - v1.03
To create implementation (the function definitions)
#define CUTE_NET_IMPLEMENTATION
in *one* C/CPP file (translation unit) that includes this file
SUMMARY
Cute net provides you a way to securely connect clients to servers, and
implements all the machinery for sending both reliable-in-order and
fire-and-forget (UDP style) packets. This is great for many kinds of games,
ranging from games who just want TCP-style packets (such as a turn-based
RPG), to fast paced platformer or fighting games.
FEATURES
* Reliable-in-order packets. These are packets that will be resent if they
aren't received, and will be received in the same order they are sent.
* Fire-and-forget packets. These are basic UDP packets, useful for sending
temporal info like transforms for quick updates. They are not resent if
lost, and can arrive out of order.
* Client and server abstractions.
* State of the art connect tokens for security.
* Support for large packets (fragmentation and reassembly).
* Bandwidth stats (incoming/outgoing kbps, packet loss).
TODO FEATURES
* Bandwidth throttling
* TCP-only mode (for web builds via emscripten)
* Channel support (for reliable packet stalling mitigation)
* Loopback clients for server
* Memory stats query for server
CROSS PLATFORM
Works on almost any platform. The main limitation is initialization of
cryptographically secure random numbers, as implemented by libhydrogen.
But, it should work pretty much everywhere. You can find the platforms
supported via ctrl + f "#error Unsupported platform (libhydrogen)." without
quotes. The platforms APIs are (yes, this covers Mac, iOS, Windows, Android
and Linux):
* riot
* mbedtls
* unix
* wasi
* windows
* NRF
* particle
* ESP
* AVR
Please note emscripten (and browsers) are not supported, as Cute Net uses
the UDP transport layer, not TCP.
LIMITATIONS
Cute net does not implement some high level multiplayer features, such as
interpolation, rollback, or other similar features. Cute net is merely to
setup secure connections between clients and servers, and facilitate
packets through the connection.
This is a pretty big library with a lot of code. It's doing a lot under the
hood, including cryptography, book-keeping, and dealing with the UDP layer.
However, it's very small for what it's doing!
There is no HTTPS support, so distributing connect tokens is *out of scope*
of this library. If you want an out-of-the-box solution for making HTTPS
calls to a game server, you can try out the higher level library Cute
Framework (https://github.com/RandyGaul/cute_framework).
SPECIAL THANKS
Special thanks to Glenn Fiedler for his online resources, especially his
netcode.io (https://github.com/networkprotocol/netcode).
Special thanks to Frank Denis for providing the cryptography AEAD primitive
within his libhydrogen (https://github.com/jedisct1/libhydrogen).
Special thanks to Mattias Gustavsson for his rnd and hashtable implementations
(https://github.com/mattiasgustavsson/libs).
Revision history:
1.00 (04/22/2022) Initial release.
1.01 (07/22/2022) Fixed an old find + replace bug that caused packets to fail
decryption across different platforms/compilers.
1.02 (11/12/2022) Fixed a bug where sequence buffers would desync when sending
too many reliable packets all at once.
* Implemented stats queries (packet loss, round-trip-time, etc.)
* Return proper error if packets of size 0 are sent.
* Renamed cn_error_t to cn_result_t.
* Fixed a bug where reliable sequence numbers were incremented
at the wrong time, causing a desynchronization and connection
drop.
1.03 (03/27/2023) Fixed an issue where sometimes a sequence buffer would mark an
an entry as free before actually free'ing it, inevitably causing
a double free. Also added a new function cn_server_set_public_ip,
useful for testing servers behind a NAT: WARNING -- not recommended
for shipping due to compromised security!!!
*/
/*
DOCUMENTATION
Clients use connect tokens to connect to game servers. This only allows clients
who authenticate themselves to connect and play on your game servers, granting
completel control over who can or cannot play. This is important as dedicated
game servers are typically fairly expensive to run, and usually only players who
have paid for the game are able to obtain connect tokens.
You will have to distribute connect tokens to clients. The recommendation is to
setup a web service to provide a REST API, like a simple HTTP server. The client
can send an HTTP request, and the server responds with a connect token.
The client then reads the connect token, which contains a list of game servers
to try and connect to along with other needed security info. Here's a diagram
describing the process.
+-----------+
| Web |
| Service |
+-----------+
^ |
| | +-----------+ +-----------+
REST Call | Dedicated | | Dedicated |
returns a | Server 1 | | Server 2 |
Connect Token +-----------+ +-----------+
| | ^ ^
| v | |
+--------+ *connect token packet* -> | if fail, try next -> |
| Client |-------------------------------+--------------------------+----------> ... Token timeout!
+--------+
Once you get a connect token make a call to `cn_client_connect`.
The function `cn_generate_connect_token` can be used to generate connect tokens for the web service to distribute.
The web service distributes connect tokens. Cute net does not provide an implementation
of a web service because there are many different good solutions out there already. The
goal is to only respond and provide connect tokens to clients who have authenticated
themselves over a secure connection with the web service, such as through HTTPS. For
example: this is how cute net can be used to filter out players who have no purchased the
game or signed up with an account.
EXAMPLES
Here is a full example of a client and server, where the client sends a string to the
server to print to the console.
Client example: https://github.com/RandyGaul/cute_headers/tree/master/examples_cute_net/client
Server example: https://github.com/RandyGaul/cute_headers/tree/master/examples_cute_net/server
UNIT TESTS
You may enable building the unit tests with CUTE_NET_TESTS. Simply call
cn_run_tests(-1, false);
to run all of the unit tests. The first parameter is the test number to run,
while the second paramater is for a "soak" test (run the tests in an in-
finite loop).
You will see a bunch of colored text printed to the console about each test
and whether or not each test passed or failed.
CUSTOMIZATION
There are a number of macros to override c-runtime functions. Simply define
your own version of these macros before including this header when you setup
the implementation with CUTE_NET_IMPLEMENTATION.
CN_ALLOC
CN_FREE
CN_MEMCPY
CN_MEMSET
CN_ASSERT
CN_STRNCPY
CN_STRLEN
CN_STRNCMP
CN_MEMCMP
CN_SNPRINTF
CN_FPRINTF
CN_PRINTF
You can disable IPv6 support by defining CUTE_NET_NO_IPV6 like so.
#define CUTE_NET_NO_IPV6
#define CUTE_NET_IMPLEMENTATION
#include <cute_net.h>
You may override the number of max clients on a server via CN_SERVER_MAX_CLIENTS.
The memory per client is a constant factor, and not too much. From rough back of the
envelope math it was estimated to easily support 2k+ players on a single machine.
BUGS AND CRASHES
This header is quite new and it takes time to test all code; There may be bugs
here and there, so please open up an issue on github if you have any questions
or need help!
https://github.com/RandyGaul/cute_headers/issues
*/
#ifndef CN_NET_H
#define CN_NET_H
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
typedef struct cn_result_t cn_result_t;
typedef struct cn_client_t cn_client_t;
typedef struct cn_server_t cn_server_t;
typedef struct cn_endpoint_t cn_endpoint_t;
typedef struct cn_crypto_key_t { uint8_t key[32]; } cn_crypto_key_t;
typedef struct cn_crypto_sign_public_t { uint8_t key[32]; } cn_crypto_sign_public_t;
typedef struct cn_crypto_sign_secret_t { uint8_t key[64]; } cn_crypto_sign_secret_t;
typedef struct cn_crypto_signature_t { uint8_t bytes[64]; } cn_crypto_signature_t;
#ifdef __cplusplus
# define CN_INLINE inline
#else
# define CN_INLINE static inline
#endif
//--------------------------------------------------------------------------------------------------
// ENDPOINT
typedef enum cn_address_type_t
{
CN_ADDRESS_TYPE_NONE,
CN_ADDRESS_TYPE_IPV4,
#ifndef CUTE_NET_NO_IPV6
CN_ADDRESS_TYPE_IPV6
#endif
} cn_address_type_t;
struct cn_endpoint_t
{
cn_address_type_t type;
uint16_t port;
union
{
uint8_t ipv4[4];
#ifndef CUTE_NET_NO_IPV6
uint16_t ipv6[8];
#endif
} u;
};
int cn_endpoint_init(cn_endpoint_t* endpoint, const char* address_and_port_string);
void cn_endpoint_to_string(cn_endpoint_t endpoint, char* buffer, int buffer_size);
int cn_endpoint_equals(cn_endpoint_t a, cn_endpoint_t b);
//--------------------------------------------------------------------------------------------------
// CONNECT TOKEN
#define CN_CONNECT_TOKEN_SIZE 1114
#define CN_CONNECT_TOKEN_USER_DATA_SIZE 256
/**
* Generates a cryptography key in a cryptographically secure way.
*/
cn_crypto_key_t cn_crypto_generate_key();
/**
* Fills a buffer in a cryptographically secure way (i.e. a slow way).
*/
void cn_crypto_random_bytes(void* data, int byte_count);
/**
* Generates a cryptographically secure keypair, used for facilitating connect tokens.
*/
void cn_crypto_sign_keygen(cn_crypto_sign_public_t* public_key, cn_crypto_sign_secret_t* secret_key);
/**
* Generates a connect token, useable by clients to authenticate and securely connect to
* a server. You can use this function whenever a validated client wants to join your game servers.
*
* It's recommended to setup a web service specifically for allowing players to authenticate
* themselves (login). Once authenticated, the webservice can call this function and hand
* the connect token to the client. The client can then read the public section of the
* connect token and see the `address_list` of servers to try and connect to. The client then
* sends the connect token to one of these servers to start the connection handshake. If the
* handshake completes successfully, the client will connect to the server.
*
* The connect token is protected by an AEAD primitive (https://en.wikipedia.org/wiki/Authenticated_encryption),
* which means the token cannot be modified or forged as long as the `shared_secret_key` is
* not leaked. In the event your secret key is accidentally leaked, you can always roll a
* new one and distribute it to your webservice and game servers.
*/
cn_result_t cn_generate_connect_token(
uint64_t application_id, // A unique number to identify your game, can be whatever value you like.
// This must be the same number as in `cn_client_create` and `cn_server_create`.
uint64_t creation_timestamp, // A unix timestamp of the current time.
const cn_crypto_key_t* client_to_server_key, // A unique key for this connect token for the client to encrypt packets, and server to
// decrypt packets. This can be generated with `cn_crypto_generate_key` on your web service.
const cn_crypto_key_t* server_to_client_key, // A unique key for this connect token for the server to encrypt packets, and the client to
// decrypt packets. This can be generated with `cn_crypto_generate_key` on your web service.
uint64_t expiration_timestamp, // A unix timestamp for when this connect token expires and becomes invalid.
uint32_t handshake_timeout, // The number of seconds the connection will stay alive during the handshake process before
// the client and server reject the handshake process as failed.
int address_count, // Must be from 1 to 32 (inclusive). The number of addresses in `address_list`.
const char** address_list, // A list of game servers the client can try connecting to, of length `address_count`.
uint64_t client_id, // The unique client identifier.
const uint8_t* user_data, // Optional buffer of data of `CN_CONNECT_TOKEN_USER_DATA_SIZE` (256) bytes. Can be NULL.
const cn_crypto_sign_secret_t* shared_secret_key, // Only your webservice and game servers know this key.
uint8_t* token_ptr_out // Pointer to your buffer, should be `CN_CONNECT_TOKEN_SIZE` bytes large.
);
//--------------------------------------------------------------------------------------------------
// CLIENT
cn_client_t* cn_client_create(
uint16_t port, // Port for opening a UDP socket.
uint64_t application_id, // A unique number to identify your game, can be whatever value you like.
// This must be the same number as in `cn_server_create`.
bool use_ipv6 /* = false */, // Whether or not the socket should turn on ipv6. Some users will not have
// ipv6 enabled, so this defaults to false.
void* user_allocator_context /* = NULL */ // Used for custom allocators, this can be set to NULL.
);
void cn_client_destroy(cn_client_t* client);
/**
* The client will make an attempt to connect to all servers listed in the connect token, one after
* another. If no server can be connected to the client's state will be set to an error state. Call
* `cn_client_state_get` to get the client's state. Once `cn_client_connect` is called then successive calls to
* `cn_client_update` is expected, where `cn_client_update` will perform the connection handshake and make
* connection attempts to your servers.
*/
cn_result_t cn_client_connect(cn_client_t* client, const uint8_t* connect_token);
void cn_client_disconnect(cn_client_t* client);
/**
* You should call this one per game loop after calling `cn_client_connect`.
*/
void cn_client_update(cn_client_t* client, double dt, uint64_t current_time);
/**
* Returns a packet from the server if one is available. You must free this packet when you're done by
* calling `cn_client_free_packet`.
*/
bool cn_client_pop_packet(cn_client_t* client, void** packet, int* size, bool* was_sent_reliably /* = NULL */);
void cn_client_free_packet(cn_client_t* client, void* packet);
/**
* Sends a packet to the server. If the packet size is too large (over 1k bytes) it will be split up
* and sent in smaller chunks.
*
* `send_reliably` as true means the packet will be sent reliably an in-order relative to other
* reliable packets. Under packet loss the packet will continually be sent until an acknowledgement
* from the server is received. False means to send a typical UDP packet, with no special mechanisms
* regarding packet loss.
*
* Reliable packets are significantly more expensive than unreliable packets, so try to send any data
* that can be lost due to packet loss as an unreliable packet. Of course, some packets are required
* to be sent, and so reliable is appropriate. As an optimization some kinds of data, such as frequent
* transform updates, can be sent unreliably.
*
* Will return an error result if the packet cannot be queued up for some reason. This typically means
* you are sending way too much data to the other end and need to slow down.
*
* IMPORTANT NOTE -- If you send reliable packets you _MUST_ be sending packets both to the server
* and to the client. Two-way communication is required. If you only send reliable
* packets one-way, it will never hear back from the other end whether or not those
* packets safely arrived, and you will stall the connection. It's recommended to
* constantly send packets back and forth each game tick. Each packet can confirm
* 32 other packets, so as a rule of thumb make sure you are sending at least one
* packet for every 16 received.
*/
cn_result_t cn_client_send(cn_client_t* client, const void* packet, int size, bool send_reliably);
typedef enum cn_client_state_t
{
CN_CLIENT_STATE_CONNECT_TOKEN_EXPIRED = -6,
CN_CLIENT_STATE_INVALID_CONNECT_TOKEN = -5,
CN_CLIENT_STATE_CONNECTION_TIMED_OUT = -4,
CN_CLIENT_STATE_CHALLENGE_RESPONSE_TIMED_OUT = -3,
CN_CLIENT_STATE_CONNECTION_REQUEST_TIMED_OUT = -2,
CN_CLIENT_STATE_CONNECTION_DENIED = -1,
CN_CLIENT_STATE_DISCONNECTED = 0,
CN_CLIENT_STATE_SENDING_CONNECTION_REQUEST = 1,
CN_CLIENT_STATE_SENDING_CHALLENGE_RESPONSE = 2,
CN_CLIENT_STATE_CONNECTED = 3,
} cn_client_state_t;
cn_client_state_t cn_client_state_get(const cn_client_t* client);
const char* cn_client_state_string(cn_client_state_t state);
void cn_client_enable_network_simulator(cn_client_t* client, double latency, double jitter, double drop_chance, double duplicate_chance);
float cn_client_get_packet_loss_estimate(cn_client_t* client);
float cn_client_get_rtt_estimate(cn_client_t* client);
float cn_client_get_incoming_kbps_estimate(cn_client_t* client);
float cn_client_get_outgoing_kbps_estimate(cn_client_t* client);
//--------------------------------------------------------------------------------------------------
// SERVER
// Override this macro as seen fit.
#ifndef CN_SERVER_MAX_CLIENTS
# define CN_SERVER_MAX_CLIENTS 32
#endif
typedef struct cn_server_config_t
{
uint64_t application_id; // A unique number to identify your game, can be whatever value you like.
// This must be the same number as in `cn_client_make`.
int max_incoming_bytes_per_second; // Not implemented yet.
int max_outgoing_bytes_per_second; // Not implemented yet.
int connection_timeout; // The number of seconds before consider a connection as timed out when not
// receiving any packets on the connection.
double resend_rate; // The number of seconds to wait before resending a packet that has not been
// acknowledge as received by a client.
cn_crypto_sign_public_t public_key; // The public part of your public key cryptography used for connect tokens.
// This can be safely shared with your players publicly.
cn_crypto_sign_secret_t secret_key; // The secret part of your public key cryptography used for connect tokens.
// This must never be shared publicly and remain a complete secret only know to your servers.
void* user_allocator_context;
} cn_server_config_t;
CN_INLINE cn_server_config_t cn_server_config_defaults(void)
{
cn_server_config_t config;
config.application_id = 0;
config.max_incoming_bytes_per_second = 0;
config.max_outgoing_bytes_per_second = 0;
config.connection_timeout = 10;
config.resend_rate = 0.1f;
return config;
}
cn_server_t* cn_server_create(cn_server_config_t config);
void cn_server_destroy(cn_server_t* server);
/**
* Starts up the server, ready to receive new client connections.
*
* Please note that not all users will be able to access an ipv6 server address, so it might
* be good to also provide a way to connect through ipv4.
*/
cn_result_t cn_server_start(cn_server_t* server, const char* address_and_port);
void cn_server_stop(cn_server_t* server);
typedef enum cn_server_event_type_t
{
CN_SERVER_EVENT_TYPE_NEW_CONNECTION, // A new incoming connection.
CN_SERVER_EVENT_TYPE_DISCONNECTED, // A disconnecting client.
CN_SERVER_EVENT_TYPE_PAYLOAD_PACKET, // An incoming packet from a client.
} cn_server_event_type_t;
typedef struct cn_server_event_t
{
cn_server_event_type_t type;
union
{
struct
{
int client_index; // An index representing this particular client.
uint64_t client_id; // A unique identifier for this particular client, as read from the connect token.
cn_endpoint_t endpoint; // The address and port of the incoming connection.
} new_connection;
struct
{
int client_index; // An index representing this particular client.
} disconnected;
struct
{
int client_index; // An index representing this particular client.
void* data; // Pointer to the packet's payload data. Send this back to `cn_server_free_packet` when done.
int size; // Size of the packet at the data pointer.
} payload_packet;
} u;
} cn_server_event_t;
/**
* Server events notify of when a client connects/disconnects, or has sent a payload packet.
* You must free the payload packets with `cn_server_free_packet` when done.
*/
bool cn_server_pop_event(cn_server_t* server, cn_server_event_t* event);
void cn_server_free_packet(cn_server_t* server, int client_index, void* data);
void cn_server_update(cn_server_t* server, double dt, uint64_t current_time);
void cn_server_disconnect_client(cn_server_t* server, int client_index, bool notify_client /* = true */);
/**
* Sends a packet to the client. If the packet size is too large (over 1k bytes) it will be split up
* and sent in smaller chunks.
*
* `send_reliably` as true means the packet will be sent reliably an in-order relative to other
* reliable packets. Under packet loss the packet will continually be sent until an acknowledgement
* from the client is received. False means to send a typical UDP packet, with no special mechanisms
* regarding packet loss.
*
* Reliable packets are significantly more expensive than unreliable packets, so try to send any data
* that can be lost due to packet loss as an unreliable packet. Of course, some packets are required
* to be sent, and so reliable is appropriate. As an optimization some kinds of data, such as frequent
* transform updates, can be sent unreliably.
*
* Will return an error result if the packet cannot be queued up for some reason. This typically means
* you are sending way too much data to the other end and need to slow down.
*
* IMPORTANT NOTE -- If you send reliable packets you _MUST_ be sending packets both to the server
* and to the client. Two-way communication is required. If you only send reliable
* packets one-way, it will never hear back from the other end whether or not those
* packets safely arrived, and you will stall the connection. It's recommended to
* constantly send packets back and forth each game tick. Each packet can confirm
* 32 other packets, so as a rule of thumb make sure you are sending at least one
* packet for every 16 received.
*/
cn_result_t cn_server_send(cn_server_t* server, const void* packet, int size, int client_index, bool send_reliably);
bool cn_server_is_client_connected(cn_server_t* server, int client_index);
/**
* WARNING -- For test/dev builds only!
*
* If your server runs in the cloud with a public ip (highly recommended) this function is not at all necessary. However,
* for testing purposes a lot of developers want to start out with port forwarding on their personal machine. Unfortunately
* routers nowadays will likely act as your public IP. The connect token a client uses must use the router's IP address. As
* the token is opened up by the server the server will notice it's local IP (something like 192.168.1.3) will not match the
* the server's public ip listed in the connect token, causing a disconnect.
*
* Instead you may specify the server to match against it's *local IP*, instead of the public IP. This of course compromises
* the entire security design, but it's a great way to get going before learning how to setup a proper dedicated server with
* a real public IP address.
*
* For some more info/context you can see the original GitHub issue on this topic: https://github.com/RandyGaul/cute_headers/issues/344
*/
void cn_server_set_public_ip(cn_server_t* server, const char* address_and_port);
void cn_server_enable_network_simulator(cn_server_t* server, double latency, double jitter, double drop_chance, double duplicate_chance);
float cn_server_get_packet_loss_estimate(cn_server_t* server, int client_index);
float cn_server_get_rtt_estimate(cn_server_t* server, int client_index);
float cn_server_get_incoming_kbps_estimate(cn_server_t* server, int client_index);
float cn_server_get_outgoing_kbps_estimate(cn_server_t* server, int client_index);
//--------------------------------------------------------------------------------------------------
// ERROR
#define CN_ERROR_SUCCESS (0)
#define CN_ERROR_FAILURE (-1)
struct cn_result_t
{
int code;
const char* details;
};
CN_INLINE bool cn_is_error(cn_result_t result) { return result.code == CN_ERROR_FAILURE; }
CN_INLINE cn_result_t cn_error_failure(const char* details) { cn_result_t result; result.code = CN_ERROR_FAILURE; result.details = details; return result; }
CN_INLINE cn_result_t cn_error_success(void) { cn_result_t result; result.code = CN_ERROR_SUCCESS; result.details = NULL; return result; }
#define CN_RETURN_IF_ERROR(x) do { cn_result_t result = (x); if (cn_is_error(result)) return result; } while (0)
#endif // CN_NET_H
#ifndef CN_NET_INTERNAL_H
#define CN_NET_INTERNAL_H
#define CN_CRYPTO_HEADER_BYTES ((int)(20 + 16))
#define CN_KB 1024
#define CN_MB (CN_KB * CN_KB)
#endif // CN_NET_INTERNAL_H
#ifdef CUTE_NET_IMPLEMENTATION
#ifndef CUTE_NET_IMPLEMENTATION_ONCE
#define CUTE_NET_IMPLEMENTATION_ONCE
#if defined(_WIN32)
# define CN_WINDOWS 1
#elif defined(__linux__) || defined(__unix__) && !defined(__APPLE__) && !defined(__EMSCRIPTEN__)
# define CN_LINUX 1
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
# define CN_IOS 1
# elif TARGET_OS_MAC
# define CN_MACOSX 1
# else
# error "Unknown Apple platform"
# endif
#elif defined(__ANDROID__)
# define CN_ANDROID 1
#elif defined(__EMSCRIPTEN__)
# error Emscripten is not supported, as Cute Net uses the UDP transport layer.
#endif
#if !defined(CN_ALLOC)
#include <stdlib.h>
#define CN_ALLOC(size, ctx) malloc(size)
#define CN_FREE(mem, ctx) free(mem)
#endif
#if !defined(CN_MEMCPY)
#include <string.h>
#define CN_MEMCPY memcpy
#endif
#if !defined(CN_MEMSET)
#include <string.h>
#define CN_MEMSET memset
#endif
#if !defined(CN_ASSERT)
#include <assert.h>
#define CN_ASSERT assert
#endif
#ifndef CN_STRNCPY
# include <string.h>
# define CN_STRNCPY strncpy
#endif
#ifndef CN_STRLEN
# include <string.h>
# define CN_STRLEN strlen
#endif
#ifndef CN_STRNCMP
# include <string.h>
# define CN_STRNCMP strncmp
#endif
#ifndef CN_MEMCMP
# include <string.h>
# define CN_MEMCMP memcmp
#endif
#ifndef CN_SNPRINTF
# include <stdio.h>
# define CN_SNPRINTF snprintf
#endif
#ifndef CN_FPRINTF
# include <stdio.h>
# define CN_FPRINTF fprintf
#endif
#ifndef CN_PRINTF
# define CN_PRINTF(...)
#endif
//--------------------------------------------------------------------------------------------------
// Embedded libhydrogen packed up from a python script.
// See https://github.com/jedisct1/libhydrogen for the original source.
#ifndef hydrogen_H
#define hydrogen_H
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wlong-long"
#endif
extern "C" {
#endif
#if defined(__clang__) || defined(__GNUC__)
#define _hydro_attr_(X) __attribute__(X)
#else
#define _hydro_attr_(X)
#endif
#define _hydro_attr_deprecated_ _hydro_attr_((deprecated))
#define _hydro_attr_malloc_ _hydro_attr_((malloc))
#define _hydro_attr_noinline_ _hydro_attr_((noinline))
#define _hydro_attr_noreturn_ _hydro_attr_((noreturn))
#define _hydro_attr_warn_unused_result_ _hydro_attr_((warn_unused_result))
#define _hydro_attr_weak_ _hydro_attr_((weak))
#if defined(__INTEL_COMPILER) || (defined(_MSC_VER) && !defined(__clang__))
#define _hydro_attr_aligned_(X) __declspec(align(X))
#elif defined(__clang__) || defined(__GNUC__)
#define _hydro_attr_aligned_(X) _hydro_attr_((aligned(X)))
#else
#define _hydro_attr_aligned_(X)
#endif
#define HYDRO_VERSION_MAJOR 1
#define HYDRO_VERSION_MINOR 0
int hydro_init(void);
/* ---------------- */
#define hydro_random_SEEDBYTES 32
uint32_t hydro_random_u32(void);
uint32_t hydro_random_uniform(const uint32_t upper_bound);
void hydro_random_buf(void *out, size_t out_len);
void hydro_random_buf_deterministic(void *out, size_t out_len,
const uint8_t seed[hydro_random_SEEDBYTES]);
void hydro_random_ratchet(void);
void hydro_random_reseed(void);
/* ---------------- */
#define hydro_hash_BYTES 32
#define hydro_hash_BYTES_MAX 65535
#define hydro_hash_BYTES_MIN 16
#define hydro_hash_CONTEXTBYTES 8
#define hydro_hash_KEYBYTES 32
typedef struct hydro_hash_state {
uint32_t state[12];
uint8_t buf_off;
uint8_t align[3];
} hydro_hash_state;
void hydro_hash_keygen(uint8_t key[hydro_hash_KEYBYTES]);
int hydro_hash_init(hydro_hash_state *state, const char ctx[hydro_hash_CONTEXTBYTES],
const uint8_t key[hydro_hash_KEYBYTES]);
int hydro_hash_update(hydro_hash_state *state, const void *in_, size_t in_len);
int hydro_hash_final(hydro_hash_state *state, uint8_t *out, size_t out_len);
int hydro_hash_hash(uint8_t *out, size_t out_len, const void *in_, size_t in_len,
const char ctx[hydro_hash_CONTEXTBYTES],
const uint8_t key[hydro_hash_KEYBYTES]);
/* ---------------- */
#define hydro_secretbox_CONTEXTBYTES 8
#define hydro_secretbox_HEADERBYTES (20 + 16)
#define hydro_secretbox_KEYBYTES 32
#define hydro_secretbox_PROBEBYTES 16
void hydro_secretbox_keygen(uint8_t key[hydro_secretbox_KEYBYTES]);
int hydro_secretbox_encrypt(uint8_t *c, const void *m_, size_t mlen, uint64_t msg_id,
const char ctx[hydro_secretbox_CONTEXTBYTES],
const uint8_t key[hydro_secretbox_KEYBYTES]);
int hydro_secretbox_decrypt(void *m_, const uint8_t *c, size_t clen, uint64_t msg_id,
const char ctx[hydro_secretbox_CONTEXTBYTES],
const uint8_t key[hydro_secretbox_KEYBYTES])
_hydro_attr_warn_unused_result_;
void hydro_secretbox_probe_create(uint8_t probe[hydro_secretbox_PROBEBYTES], const uint8_t *c,
size_t c_len, const char ctx[hydro_secretbox_CONTEXTBYTES],
const uint8_t key[hydro_secretbox_KEYBYTES]);
int hydro_secretbox_probe_verify(const uint8_t probe[hydro_secretbox_PROBEBYTES], const uint8_t *c,
size_t c_len, const char ctx[hydro_secretbox_CONTEXTBYTES],
const uint8_t key[hydro_secretbox_KEYBYTES])
_hydro_attr_warn_unused_result_;
/* ---------------- */
#define hydro_kdf_CONTEXTBYTES 8
#define hydro_kdf_KEYBYTES 32
#define hydro_kdf_BYTES_MAX 65535
#define hydro_kdf_BYTES_MIN 16
void hydro_kdf_keygen(uint8_t key[hydro_kdf_KEYBYTES]);
int hydro_kdf_derive_from_key(uint8_t *subkey, size_t subkey_len, uint64_t subkey_id,
const char ctx[hydro_kdf_CONTEXTBYTES],
const uint8_t key[hydro_kdf_KEYBYTES]);
/* ---------------- */
#define hydro_sign_BYTES 64
#define hydro_sign_CONTEXTBYTES 8
#define hydro_sign_PUBLICKEYBYTES 32
#define hydro_sign_SECRETKEYBYTES 64
#define hydro_sign_SEEDBYTES 32
typedef struct hydro_sign_state {
hydro_hash_state hash_st;
} hydro_sign_state;
typedef struct hydro_sign_keypair {
uint8_t pk[hydro_sign_PUBLICKEYBYTES];
uint8_t sk[hydro_sign_SECRETKEYBYTES];
} hydro_sign_keypair;
void hydro_sign_keygen(hydro_sign_keypair *kp);
void hydro_sign_keygen_deterministic(hydro_sign_keypair *kp,
const uint8_t seed[hydro_sign_SEEDBYTES]);
int hydro_sign_init(hydro_sign_state *state, const char ctx[hydro_sign_CONTEXTBYTES]);
int hydro_sign_update(hydro_sign_state *state, const void *m_, size_t mlen);
int hydro_sign_final_create(hydro_sign_state *state, uint8_t csig[hydro_sign_BYTES],
const uint8_t sk[hydro_sign_SECRETKEYBYTES]);
int hydro_sign_final_verify(hydro_sign_state *state, const uint8_t csig[hydro_sign_BYTES],
const uint8_t pk[hydro_sign_PUBLICKEYBYTES])
_hydro_attr_warn_unused_result_;
int hydro_sign_create(uint8_t csig[hydro_sign_BYTES], const void *m_, size_t mlen,
const char ctx[hydro_sign_CONTEXTBYTES],
const uint8_t sk[hydro_sign_SECRETKEYBYTES]);
int hydro_sign_verify(const uint8_t csig[hydro_sign_BYTES], const void *m_, size_t mlen,
const char ctx[hydro_sign_CONTEXTBYTES],
const uint8_t pk[hydro_sign_PUBLICKEYBYTES]) _hydro_attr_warn_unused_result_;
/* ---------------- */
#define hydro_kx_SESSIONKEYBYTES 32
#define hydro_kx_PUBLICKEYBYTES 32
#define hydro_kx_SECRETKEYBYTES 32
#define hydro_kx_PSKBYTES 32
#define hydro_kx_SEEDBYTES 32
typedef struct hydro_kx_keypair {
uint8_t pk[hydro_kx_PUBLICKEYBYTES];
uint8_t sk[hydro_kx_SECRETKEYBYTES];
} hydro_kx_keypair;
typedef struct hydro_kx_session_keypair {
uint8_t rx[hydro_kx_SESSIONKEYBYTES];
uint8_t tx[hydro_kx_SESSIONKEYBYTES];
} hydro_kx_session_keypair;
typedef struct hydro_kx_state {
hydro_kx_keypair eph_kp;
hydro_hash_state h_st;
} hydro_kx_state;
void hydro_kx_keygen(hydro_kx_keypair *static_kp);
void hydro_kx_keygen_deterministic(hydro_kx_keypair *static_kp,
const uint8_t seed[hydro_kx_SEEDBYTES]);
/* NOISE_N */
#define hydro_kx_N_PACKET1BYTES (32 + 16)
int hydro_kx_n_1(hydro_kx_session_keypair *kp, uint8_t packet1[hydro_kx_N_PACKET1BYTES],
const uint8_t psk[hydro_kx_PSKBYTES],
const uint8_t peer_static_pk[hydro_kx_PUBLICKEYBYTES]);
int hydro_kx_n_2(hydro_kx_session_keypair *kp, const uint8_t packet1[hydro_kx_N_PACKET1BYTES],
const uint8_t psk[hydro_kx_PSKBYTES], const hydro_kx_keypair *static_kp);
/* NOISE_KK */
#define hydro_kx_KK_PACKET1BYTES (32 + 16)
#define hydro_kx_KK_PACKET2BYTES (32 + 16)
int hydro_kx_kk_1(hydro_kx_state *state, uint8_t packet1[hydro_kx_KK_PACKET1BYTES],
const uint8_t peer_static_pk[hydro_kx_PUBLICKEYBYTES],
const hydro_kx_keypair *static_kp);
int hydro_kx_kk_2(hydro_kx_session_keypair *kp, uint8_t packet2[hydro_kx_KK_PACKET2BYTES],
const uint8_t packet1[hydro_kx_KK_PACKET1BYTES],
const uint8_t peer_static_pk[hydro_kx_PUBLICKEYBYTES],
const hydro_kx_keypair *static_kp);
int hydro_kx_kk_3(hydro_kx_state *state, hydro_kx_session_keypair *kp,
const uint8_t packet2[hydro_kx_KK_PACKET2BYTES],
const hydro_kx_keypair *static_kp);
/* NOISE_XX */
#define hydro_kx_XX_PACKET1BYTES (32 + 16)
#define hydro_kx_XX_PACKET2BYTES (32 + 32 + 16 + 16)
#define hydro_kx_XX_PACKET3BYTES (32 + 16 + 16)
int hydro_kx_xx_1(hydro_kx_state *state, uint8_t packet1[hydro_kx_XX_PACKET1BYTES],
const uint8_t psk[hydro_kx_PSKBYTES]);
int hydro_kx_xx_2(hydro_kx_state *state, uint8_t packet2[hydro_kx_XX_PACKET2BYTES],
const uint8_t packet1[hydro_kx_XX_PACKET1BYTES],
const uint8_t psk[hydro_kx_PSKBYTES], const hydro_kx_keypair *static_kp);
int hydro_kx_xx_3(hydro_kx_state *state, hydro_kx_session_keypair *kp,
uint8_t packet3[hydro_kx_XX_PACKET3BYTES],
uint8_t peer_static_pk[hydro_kx_PUBLICKEYBYTES],
const uint8_t packet2[hydro_kx_XX_PACKET2BYTES],
const uint8_t psk[hydro_kx_PSKBYTES], const hydro_kx_keypair *static_kp);
int hydro_kx_xx_4(hydro_kx_state *state, hydro_kx_session_keypair *kp,
uint8_t peer_static_pk[hydro_kx_PUBLICKEYBYTES],
const uint8_t packet3[hydro_kx_XX_PACKET3BYTES],
const uint8_t psk[hydro_kx_PSKBYTES]);
/* NOISE_NK */
#define hydro_kx_NK_PACKET1BYTES (32 + 16)
#define hydro_kx_NK_PACKET2BYTES (32 + 16)
int hydro_kx_nk_1(hydro_kx_state *state, uint8_t packet1[hydro_kx_NK_PACKET1BYTES],
const uint8_t psk[hydro_kx_PSKBYTES],
const uint8_t peer_static_pk[hydro_kx_PUBLICKEYBYTES]);
int hydro_kx_nk_2(hydro_kx_session_keypair *kp, uint8_t packet2[hydro_kx_NK_PACKET2BYTES],
const uint8_t packet1[hydro_kx_NK_PACKET1BYTES],
const uint8_t psk[hydro_kx_PSKBYTES], const hydro_kx_keypair *static_kp);
int hydro_kx_nk_3(hydro_kx_state *state, hydro_kx_session_keypair *kp,
const uint8_t packet2[hydro_kx_NK_PACKET2BYTES]);
/* ---------------- */
#define hydro_pwhash_CONTEXTBYTES 8
#define hydro_pwhash_MASTERKEYBYTES 32
#define hydro_pwhash_STOREDBYTES 128
void hydro_pwhash_keygen(uint8_t master_key[hydro_pwhash_MASTERKEYBYTES]);
int hydro_pwhash_deterministic(uint8_t *h, size_t h_len, const char *passwd, size_t passwd_len,
const char ctx[hydro_pwhash_CONTEXTBYTES],
const uint8_t master_key[hydro_pwhash_MASTERKEYBYTES],
uint64_t opslimit, size_t memlimit, uint8_t threads);
int hydro_pwhash_create(uint8_t stored[hydro_pwhash_STOREDBYTES], const char *passwd,
size_t passwd_len, const uint8_t master_key[hydro_pwhash_MASTERKEYBYTES],
uint64_t opslimit, size_t memlimit, uint8_t threads);
int hydro_pwhash_verify(const uint8_t stored[hydro_pwhash_STOREDBYTES], const char *passwd,
size_t passwd_len, const uint8_t master_key[hydro_pwhash_MASTERKEYBYTES],
uint64_t opslimit_max, size_t memlimit_max, uint8_t threads_max);
int hydro_pwhash_derive_static_key(uint8_t *static_key, size_t static_key_len,
const uint8_t stored[hydro_pwhash_STOREDBYTES],
const char *passwd, size_t passwd_len,
const char ctx[hydro_pwhash_CONTEXTBYTES],
const uint8_t master_key[hydro_pwhash_MASTERKEYBYTES],
uint64_t opslimit_max, size_t memlimit_max, uint8_t threads_max);
int hydro_pwhash_reencrypt(uint8_t stored[hydro_pwhash_STOREDBYTES],
const uint8_t master_key[hydro_pwhash_MASTERKEYBYTES],
const uint8_t new_master_key[hydro_pwhash_MASTERKEYBYTES]);
int hydro_pwhash_upgrade(uint8_t stored[hydro_pwhash_STOREDBYTES],
const uint8_t master_key[hydro_pwhash_MASTERKEYBYTES], uint64_t opslimit,
size_t memlimit, uint8_t threads);
/* ---------------- */
void hydro_memzero(void *pnt, size_t len);
void hydro_increment(uint8_t *n, size_t len);
bool hydro_equal(const void *b1_, const void *b2_, size_t len);
int hydro_compare(const uint8_t *b1_, const uint8_t *b2_, size_t len);
char *hydro_bin2hex(char *hex, size_t hex_maxlen, const uint8_t *bin, size_t bin_len);
int hydro_hex2bin(uint8_t *bin, size_t bin_maxlen, const char *hex, size_t hex_len,
const char *ignore, const char **hex_end_p);
int hydro_pad(unsigned char *buf, size_t unpadded_buflen, size_t blocksize, size_t max_buflen);
int hydro_unpad(const unsigned char *buf, size_t padded_buflen, size_t blocksize);
/* ---------------- */
#define HYDRO_HWTYPE_ATMEGA328 1
#ifndef HYDRO_HWTYPE
#ifdef __AVR__
#define HYDRO_HWTYPE HYDRO_HWTYPE_ATMEGA328
#endif
#endif
#ifdef __cplusplus
}