-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetcode.cs
More file actions
4468 lines (3737 loc) · 190 KB
/
netcode.cs
File metadata and controls
4468 lines (3737 loc) · 190 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
netcode.io reference implementation
Copyright © 2017 - 2019, The Network Protocol Company, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Crypto.Tls;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace networkprotocol
{
#region netcode_h
public static partial class netcode
{
public const int CONNECT_TOKEN_BYTES = 2048;
public const int KEY_BYTES = 32;
public const int MAC_BYTES = 16;
public const int USER_DATA_BYTES = 256;
public const int MAX_SERVERS_PER_CONNECT = 32;
public const int CLIENT_STATE_CONNECT_TOKEN_EXPIRED = -6;
public const int CLIENT_STATE_INVALID_CONNECT_TOKEN = -5;
public const int CLIENT_STATE_CONNECTION_TIMED_OUT = -4;
public const int CLIENT_STATE_CONNECTION_RESPONSE_TIMED_OUT = -3;
public const int CLIENT_STATE_CONNECTION_REQUEST_TIMED_OUT = -2;
public const int CLIENT_STATE_CONNECTION_DENIED = -1;
public const int CLIENT_STATE_DISCONNECTED = 0;
public const int CLIENT_STATE_SENDING_CONNECTION_REQUEST = 1;
public const int CLIENT_STATE_SENDING_CONNECTION_RESPONSE = 2;
public const int CLIENT_STATE_CONNECTED = 3;
public const int MAX_CLIENTS = 256;
public const int MAX_PACKET_SIZE = 1200;
public const int LOG_LEVEL_NONE = 0;
public const int LOG_LEVEL_ERROR = 1;
public const int LOG_LEVEL_INFO = 2;
public const int LOG_LEVEL_DEBUG = 3;
public const int OK = 1;
public const int ERROR = 0;
public const int ADDRESS_NONE = 0;
public const int ADDRESS_IPV4 = 1;
public const int ADDRESS_IPV6 = 2;
}
public class netcode_address_t
{
public IPAddress data;
public ushort port;
public byte type;
}
public class netcode_client_config_t
{
public object allocator_context;
public Func<object, ulong, object> allocate_function;
public Action<object, object> free_function;
public netcode_network_simulator_t network_simulator;
public object callback_context;
public Action<object, int, int> state_change_callback;
public Action<object, int, byte[], int, ulong> send_loopback_packet_callback;
public bool override_send_and_receive;
public Action<object, netcode_address_t, byte[], int> send_packet_override;
public Func<object, netcode_address_t, byte[], int, int> receive_packet_override;
}
public class netcode_server_config_t
{
public ulong protocol_id;
public byte[] private_key = new byte[netcode.KEY_BYTES];
public object allocator_context;
public Func<object, ulong, object> allocate_function;
public Action<object, object> free_function;
public netcode_network_simulator_t network_simulator;
public object callback_context;
public Action<object, int, int> connect_disconnect_callback;
public Action<object, int, byte[], int, ulong> send_loopback_packet_callback;
public bool override_send_and_receive;
public Action<object, netcode_address_t, byte[], int> send_packet_override;
public Func<object, netcode_address_t, byte[], int, int> receive_packet_override;
}
#endregion
public static partial class netcode
{
#region defines
internal const int SOCKET_IPV6 = 1;
internal const int SOCKET_IPV4 = 2;
internal const int CONNECT_TOKEN_NONCE_BYTES = 24;
internal const int CONNECT_TOKEN_PRIVATE_BYTES = 1024;
internal const int CHALLENGE_TOKEN_BYTES = 300;
internal const int VERSION_INFO_BYTES = 13;
internal const int MAX_PACKET_BYTES = 1300;
internal const int MAX_PAYLOAD_BYTES = 1200;
internal const int MAX_ADDRESS_STRING_LENGTH = 256;
internal const int PACKET_QUEUE_SIZE = 256;
internal const int REPLAY_PROTECTION_BUFFER_SIZE = 256;
internal const int CLIENT_MAX_RECEIVE_PACKETS = 64;
internal const int SERVER_MAX_RECEIVE_PACKETS = 64 * MAX_CLIENTS;
internal const int CLIENT_SOCKET_SNDBUF_SIZE = 256 * 1024;
internal const int CLIENT_SOCKET_RCVBUF_SIZE = 256 * 1024;
internal const int SERVER_SOCKET_SNDBUF_SIZE = 4 * 1024 * 1024;
internal const int SERVER_SOCKET_RCVBUF_SIZE = 4 * 1024 * 1024;
internal static byte[] VERSION_INFO = Encoding.ASCII.GetBytes("NETCODE 1.02\0");
internal const float PACKET_SEND_RATE = 10.0f;
internal const int NUM_DISCONNECT_PACKETS = 10;
[DebuggerStepThrough, Conditional("DEBUG")]
public static void assert(bool condition)
{
if (!condition)
{
var stackFrame = new StackTrace().GetFrame(1);
assert_function?.Invoke("n/a", stackFrame.GetMethod().Name, stackFrame.GetFileName(), stackFrame.GetFileLineNumber());
Environment.Exit(1);
}
}
#endregion
#region assert / logging
static void default_assert_handler(string condition, string function, string file, int line)
{
Console.Write($"assert failed: ( {condition} ), function {function}, file {file}, line {line}\n");
Debugger.Break();
Environment.Exit(1);
}
static int log_level_ = 0;
static Action<string> printf_function =
x => Console.Write(x);
public static Action<string, string, string, int> assert_function = default_assert_handler;
public static void log_level(int level) =>
log_level_ = level;
public static void set_printf_function(Action<string> function)
{
assert(function != null);
printf_function = function;
}
public static void set_assert_function(Action<string, string, string, int> function) =>
assert_function = function;
#if !NETCODE_ENABLE_LOGGING
static void printf(int level, string format)
{
if (level > log_level_) return;
printf_function(format);
}
#else
static void printf(int level, string format) { }
#endif
static object default_allocate_function(object context, ulong bytes) => null;
static void default_free_function(object context, object pointer) { }
#endregion
#region netcode_address_t
public static int parse_address(string address_string, out netcode_address_t address)
{
assert(address_string != null);
address = new netcode_address_t(); //: assert(address != null);
// first try to parse the string as an IPv6 address:
// 1. if the first character is '[' then it's probably an ipv6 in form "[addr6]:portnum"
// 2. otherwise try to parse as a raw IPv6 address using inet_pton
int base_index;
var address_string_length = address_string.Length;
if (address_string_length > 0 && address_string[0] == '[')
{
base_index = address_string_length - 1;
for (var i = 0; i < 6; ++i) // note: no need to search past 6 characters as ":65535" is longest possible port value
{
var index = base_index - i;
if (index < 3)
return ERROR;
if (address_string[index] == ':')
{
string value;
address.port = (ushort)((value = address_string.Substring(index + 1)).Length > 0 ? int.Parse(value) : 0);
address_string = address_string.Substring(0, index - 1);
}
}
address_string = address_string.Substring(1);
}
if (IPAddress.TryParse(address_string, out var ipaddress) && ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
{
address.type = ADDRESS_IPV6;
address.data = ipaddress;
return OK;
}
// otherwise it's probably an IPv4 address:
// 1. look for ":portnum", if found save the portnum and strip it out
// 2. parse remaining ipv4 address via inet_pton
address_string_length = address_string.Length;
base_index = address_string_length - 1;
for (var i = 0; i < 6; ++i)
{
int index = base_index - i;
if (index < 0)
break;
if (address_string[index] == ':')
{
string value;
address.port = (ushort)((value = address_string.Substring(index + 1)).Length > 0 ? int.Parse(value) : 0);
address_string = address_string.Substring(0, index);
}
}
if (IPAddress.TryParse(address_string, out ipaddress) && ipaddress.AddressFamily == AddressFamily.InterNetwork)
{
address.type = ADDRESS_IPV4;
address.data = ipaddress;
return OK;
}
return ERROR;
}
public static string address_to_string(netcode_address_t address)
{
assert(address != null);
if (address.type == ADDRESS_IPV6) return $"[{address.data}]{(address.port != 0 ? $":{address.port}" : null)}";
else if (address.type == ADDRESS_IPV4) return $"{address.data}{(address.port != 0 ? $":{address.port}" : null)}";
else return "NONE";
}
public static bool address_equal(netcode_address_t a, netcode_address_t b)
{
assert(a != null);
assert(b != null);
return a.type == b.type &&
a.port == b.port &&
Enumerable.SequenceEqual(a.data.GetAddressBytes(), b.data.GetAddressBytes());
}
#endregion
#region netcode_t
internal struct netcode_t
{
public bool initialized;
}
static netcode_t netcode_;
public static int init()
{
assert(!netcode_.initialized);
netcode_.initialized = true;
return OK;
}
public static void term()
{
assert(netcode_.initialized);
netcode_.initialized = false;
}
#endregion
#region socket_t
internal class socket_t
{
public netcode_address_t address = new netcode_address_t();
public Socket handle;
}
internal class socket_holder_t
{
public socket_t ipv4;
public socket_t ipv6;
}
const int SOCKET_ERROR_NONE = 0;
const int SOCKET_ERROR_CREATE_FAILED = 1;
const int SOCKET_ERROR_SET_NON_BLOCKING_FAILED = 2;
const int SOCKET_ERROR_SOCKOPT_IPV6_ONLY_FAILED = 3;
const int SOCKET_ERROR_SOCKOPT_RCVBUF_FAILED = 4;
const int SOCKET_ERROR_SOCKOPT_SNDBUF_FAILED = 5;
const int SOCKET_ERROR_BIND_FAILED = 6;
const int SOCKET_ERROR_GET_SOCKNAME_FAILED = 8;
static void socket_destroy(ref socket_t socket)
{
assert(socket != null);
assert(netcode_.initialized);
if (socket.handle != null)
socket.handle.Close();
socket = null;
}
static int socket_create(ref socket_t s, netcode_address_t address, int send_buffer_size, int receive_buffer_size)
{
assert(s != null);
assert(address != null);
assert(netcode_.initialized);
assert(address.type != ADDRESS_NONE);
s.address = address;
// create socket
try { s.handle = new Socket((address.type == ADDRESS_IPV6) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); }
catch
{
printf(LOG_LEVEL_ERROR, "error: failed to create socket\n");
return SOCKET_ERROR_CREATE_FAILED;
}
// force IPv6 only if necessary
if (address.type == ADDRESS_IPV6)
{
try { s.handle.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, true); }
catch
{
printf(LOG_LEVEL_ERROR, "error: failed to set socket ipv6 only\n");
socket_destroy(ref s);
return SOCKET_ERROR_SOCKOPT_IPV6_ONLY_FAILED;
}
}
// increase socket send and receive buffer sizes
try { s.handle.SendBufferSize = send_buffer_size; }
catch
{
printf(LOG_LEVEL_ERROR, "error: failed to set socket send buffer size\n");
socket_destroy(ref s);
return SOCKET_ERROR_SOCKOPT_SNDBUF_FAILED;
}
try { s.handle.ReceiveBufferSize = receive_buffer_size; }
catch
{
printf(LOG_LEVEL_ERROR, "error: failed to set socket receive buffer size\n");
socket_destroy(ref s);
return SOCKET_ERROR_SOCKOPT_RCVBUF_FAILED;
}
// bind to port
var endpoint = new IPEndPoint(address.data, address.port);
try { s.handle.Bind(endpoint); }
catch
{
printf(LOG_LEVEL_ERROR, "error: failed to bind socket\n");
socket_destroy(ref s);
return SOCKET_ERROR_BIND_FAILED;
}
// if bound to port 0 find the actual port we got
if (address.port == 0)
{
if (s.handle.LocalEndPoint == null)
{
printf(LOG_LEVEL_ERROR, "error: failed to get socket port\n");
socket_destroy(ref s);
return SOCKET_ERROR_GET_SOCKNAME_FAILED;
}
s.address.port = (ushort)((IPEndPoint)s.handle.LocalEndPoint).Port;
}
// set non-blocking io
try { s.handle.Blocking = false; }
catch
{
socket_destroy(ref s);
return SOCKET_ERROR_SET_NON_BLOCKING_FAILED;
}
return SOCKET_ERROR_NONE;
}
static void socket_send_packet(socket_t socket, netcode_address_t to, byte[] packet_data, int packet_bytes)
{
assert(socket != null);
assert(socket.handle != null);
assert(to != null);
assert(to.type == ADDRESS_IPV6 || to.type == ADDRESS_IPV4);
assert(packet_data != null);
assert(packet_bytes > 0);
var socket_address = new IPEndPoint(to.data, to.port);
try { socket.handle.SendTo(packet_data, packet_bytes, SocketFlags.None, socket_address); }
catch (SocketException) { }
}
static int socket_receive_packet(socket_t socket, netcode_address_t from, byte[] packet_data, int max_packet_size)
{
assert(socket != null);
assert(socket.handle != null);
assert(from != null);
assert(packet_data != null);
assert(max_packet_size > 0);
if (socket.handle.Available == 0)
return 0;
var sockaddr_from = (EndPoint)new IPEndPoint(socket.address.type == ADDRESS_IPV4 ? IPAddress.Any : IPAddress.IPv6Any, 0);
int result;
try { result = socket.handle.ReceiveFrom(packet_data, 0, max_packet_size, SocketFlags.None, ref sockaddr_from); }
catch (SocketException e)
{
var error = e.SocketErrorCode;
if (error == SocketError.WouldBlock || error == SocketError.ConnectionReset)
return 0;
printf(LOG_LEVEL_ERROR, $"error: recvfrom failed with error {error}\n");
return 0;
}
if (result <= 0)
{
printf(LOG_LEVEL_ERROR, "error: recvfrom failed with error {}\n");
return 0;
}
var endpoint = (IPEndPoint)sockaddr_from;
if (endpoint.AddressFamily == AddressFamily.InterNetworkV6)
{
from.type = ADDRESS_IPV6;
from.data = endpoint.Address;
from.port = (ushort)endpoint.Port;
}
else if (endpoint.AddressFamily == AddressFamily.InterNetwork)
{
from.type = ADDRESS_IPV4;
from.data = endpoint.Address;
from.port = (ushort)endpoint.Port;
}
else
{
assert(false);
return 0;
}
assert(result >= 0);
var bytes_read = result;
return bytes_read;
}
#endregion
#region binary serdes
internal static void write_uint8(byte[] b, ref int p, byte value)
{
b[p] = value;
++p;
}
internal static void write_uint16(byte[] b, ref int p, ushort value)
{
b[p] = (byte)value;
b[p + 1] = (byte)(value >> 8);
p += 2;
}
internal static void write_uint32(byte[] b, ref int p, uint value)
{
b[p] = (byte)value;
b[p + 1] = (byte)(value >> 8);
b[p + 2] = (byte)(value >> 0x10);
b[p + 3] = (byte)(value >> 0x18);
p += 4;
}
internal static void write_uint64(byte[] b, ref int p, ulong value)
{
b[p + 0] = (byte)value;
b[p + 1] = (byte)(value >> 8);
b[p + 2] = (byte)(value >> 0x10);
b[p + 3] = (byte)(value >> 0x18);
b[p + 4] = (byte)(value >> 0x20);
b[p + 5] = (byte)(value >> 0x28);
b[p + 6] = (byte)(value >> 0x30);
b[p + 7] = (byte)(value >> 0x38);
p += 8;
}
internal static void write_bytes(byte[] b, ref int p, byte[] byte_array, int num_bytes)
{
int i;
for (i = 0; i < num_bytes; ++i)
write_uint8(b, ref p, byte_array[i]);
}
internal static byte read_uint8(byte[] b, ref int p)
{
var value = b[p];
++p;
return value;
}
internal static ushort read_uint16(byte[] b, ref int p)
{
var value = (ushort)(b[p] | (b[p + 1] << 8));
p += 2;
return value;
}
internal static uint read_uint32(byte[] b, ref int p)
{
var value = (uint)(b[p] | (b[p + 1] << 8) | (b[p + 2] << 0x10) | (b[p + 3] << 0x18));
p += 4;
return value;
}
internal static ulong read_uint64(byte[] b, ref int p)
{
var num = (uint)(b[p] | (b[p + 1] << 8) | (b[p + 2] << 0x10) | (b[p + 3] << 0x18));
var num2 = (uint)(b[p + 4] | (b[p + 5] << 8) | (b[p + 6] << 0x10) | (b[p + 7] << 0x18));
var value = ((ulong)num2 << 0x20) | num;
p += 8;
return value;
}
internal static byte[] read_bytes(byte[] b, ref int p, byte[] byte_array, int num_bytes)
{
int i;
for (i = 0; i < num_bytes; ++i)
byte_array[i] = read_uint8(b, ref p);
return byte_array;
}
#endregion
#region generate / encrypt
readonly static RNGCryptoServiceProvider rngCrypto = new RNGCryptoServiceProvider();
static void generate_key(byte[] key) { assert(key != null); rngCrypto.GetBytes(key); }
static void generate_nonce(byte[] nonce) { assert(nonce != null); rngCrypto.GetBytes(nonce); }
public static void random_bytes(ref ulong data, int bytes) { var v = new byte[bytes]; random_bytes(v, bytes); data = BitConverter.ToUInt64(v, 0); }
public static void random_bytes(byte[] data, int bytes) { assert(data != null); assert(bytes > 0); assert(bytes == data.Length); rngCrypto.GetBytes(data); } //: randombytes_buf(data, bytes);
static int encrypt_aead_bignonce(
byte[] message, int p, ulong message_length,
byte[] additional, ulong additional_length,
byte[] nonce,
byte[] key)
{
var result = Crypto_aead.CurrentThread.Encrypt(true,
message, p, out var encrypted_length,
message, message_length,
additional, additional_length,
null, nonce, key);
if (result != 0)
return ERROR;
assert(encrypted_length == message_length + MAC_BYTES);
return OK;
}
static int decrypt_aead_bignonce(
byte[] message, int p, ulong message_length,
byte[] additional, ulong additional_length,
byte[] nonce,
byte[] key)
{
var result = Crypto_aead.CurrentThread.Decrypt(true,
message, p, out var decrypted_length,
null,
message, message_length,
additional, additional_length,
nonce, key);
if (result != 0)
return ERROR;
assert(decrypted_length == message_length - MAC_BYTES);
return OK;
}
static int encrypt_aead(
byte[] message, int p, ulong message_length,
byte[] additional, ulong additional_length,
byte[] nonce,
byte[] key)
{
var result = Crypto_aead.CurrentThread.Encrypt(false,
message, p, out var encrypted_length,
message, message_length,
additional, additional_length,
null, nonce, key);
if (result != 0)
return ERROR;
assert(encrypted_length == message_length + MAC_BYTES);
return OK;
}
static int decrypt_aead(
byte[] message, int p, ulong message_length,
byte[] additional, ulong additional_length,
byte[] nonce,
byte[] key)
{
var result = Crypto_aead.CurrentThread.Decrypt(false,
message, p, out var decrypted_length,
null,
message, message_length,
additional, additional_length,
nonce, key);
if (result != 0)
return ERROR;
assert(decrypted_length == message_length - MAC_BYTES);
return OK;
}
#endregion
#region connect_token_private
internal class connect_token_private_t
{
public ulong client_id;
public int timeout_seconds;
public int num_server_addresses;
public netcode_address_t[] server_addresses = BufferEx.NewT<netcode_address_t>(MAX_SERVERS_PER_CONNECT);
public byte[] client_to_server_key = new byte[KEY_BYTES];
public byte[] server_to_client_key = new byte[KEY_BYTES];
public byte[] user_data = new byte[USER_DATA_BYTES];
}
static void generate_connect_token_private(
connect_token_private_t connect_token,
ulong client_id,
int timeout_seconds,
int num_server_addresses,
netcode_address_t[] server_addresses,
byte[] user_data)
{
assert(connect_token != null);
assert(num_server_addresses > 0);
assert(num_server_addresses <= MAX_SERVERS_PER_CONNECT);
assert(server_addresses != null);
assert(user_data != null);
connect_token.client_id = client_id;
connect_token.timeout_seconds = timeout_seconds;
connect_token.num_server_addresses = num_server_addresses;
for (var i = 0; i < num_server_addresses; ++i)
BufferEx.Copy(ref connect_token.server_addresses[i], server_addresses[i]);
generate_key(connect_token.client_to_server_key);
generate_key(connect_token.server_to_client_key);
if (user_data != null)
BufferEx.Copy(connect_token.user_data, user_data, USER_DATA_BYTES);
else
BufferEx.Set(connect_token.user_data, 0, USER_DATA_BYTES);
}
static void write_connect_token_private(
connect_token_private_t connect_token,
byte[] buffer, int buffer_length)
{
assert(connect_token != null);
assert(connect_token.num_server_addresses > 0);
assert(connect_token.num_server_addresses <= MAX_SERVERS_PER_CONNECT);
assert(buffer != null);
assert(buffer_length >= CONNECT_TOKEN_PRIVATE_BYTES);
var p = 0;
write_uint64(buffer, ref p, connect_token.client_id);
write_uint32(buffer, ref p, (uint)connect_token.timeout_seconds);
write_uint32(buffer, ref p, (uint)connect_token.num_server_addresses);
for (var i = 0; i < connect_token.num_server_addresses; ++i)
// todo: should really have a function to write an address
if (connect_token.server_addresses[i].type == ADDRESS_IPV4)
{
write_uint8(buffer, ref p, ADDRESS_IPV4);
write_bytes(buffer, ref p, connect_token.server_addresses[i].data.GetAddressBytes(), 4);
write_uint16(buffer, ref p, connect_token.server_addresses[i].port);
}
else if (connect_token.server_addresses[i].type == ADDRESS_IPV6)
{
write_uint8(buffer, ref p, ADDRESS_IPV6);
write_bytes(buffer, ref p, connect_token.server_addresses[i].data.GetAddressBytes(), 16);
write_uint16(buffer, ref p, connect_token.server_addresses[i].port);
}
else assert(false);
write_bytes(buffer, ref p, connect_token.client_to_server_key, KEY_BYTES);
write_bytes(buffer, ref p, connect_token.server_to_client_key, KEY_BYTES);
write_bytes(buffer, ref p, connect_token.user_data, USER_DATA_BYTES);
assert(p <= CONNECT_TOKEN_PRIVATE_BYTES - MAC_BYTES);
BufferEx.SetWithOffset(buffer, p, 0, CONNECT_TOKEN_PRIVATE_BYTES - p);
}
static int encrypt_connect_token_private(
byte[] buffer, int p,
int buffer_length,
byte[] version_info,
ulong protocol_id,
ulong expire_timestamp,
byte[] nonce,
byte[] key)
{
assert(buffer != null);
assert(buffer_length == CONNECT_TOKEN_PRIVATE_BYTES);
assert(key != null);
var additional_data = new byte[VERSION_INFO_BYTES + 8 + 8];
{
var p2 = 0;
write_bytes(additional_data, ref p2, version_info, VERSION_INFO_BYTES);
write_uint64(additional_data, ref p2, protocol_id);
write_uint64(additional_data, ref p2, expire_timestamp);
}
return encrypt_aead_bignonce(buffer, p, CONNECT_TOKEN_PRIVATE_BYTES - MAC_BYTES, additional_data, (ulong)additional_data.Length, nonce, key);
}
static int decrypt_connect_token_private(
byte[] buffer, int p,
int buffer_length,
byte[] version_info,
ulong protocol_id,
ulong expire_timestamp,
byte[] nonce,
byte[] key)
{
assert(buffer != null);
assert(buffer_length == CONNECT_TOKEN_PRIVATE_BYTES);
assert(key != null);
var additional_data = new byte[VERSION_INFO_BYTES + 8 + 8];
{
var p2 = 0;
write_bytes(additional_data, ref p2, version_info, VERSION_INFO_BYTES);
write_uint64(additional_data, ref p2, protocol_id);
write_uint64(additional_data, ref p2, expire_timestamp);
}
return decrypt_aead_bignonce(buffer, p, CONNECT_TOKEN_PRIVATE_BYTES, additional_data, (ulong)additional_data.Length, nonce, key);
}
static int read_connect_token_private(
byte[] buffer, int buffer_length, connect_token_private_t connect_token)
{
assert(buffer != null);
assert(connect_token != null);
if (buffer_length < CONNECT_TOKEN_PRIVATE_BYTES)
return ERROR;
var p = 0;
connect_token.client_id = read_uint64(buffer, ref p);
connect_token.timeout_seconds = (int)read_uint32(buffer, ref p);
connect_token.num_server_addresses = (int)read_uint32(buffer, ref p);
if (connect_token.num_server_addresses <= 0)
return ERROR;
if (connect_token.num_server_addresses > MAX_SERVERS_PER_CONNECT)
return ERROR;
int i;
for (i = 0; i < connect_token.num_server_addresses; ++i)
{
// todo: should really have a function to read an address
connect_token.server_addresses[i].type = read_uint8(buffer, ref p);
if (connect_token.server_addresses[i].type == ADDRESS_IPV4)
{
var buf = new byte[4];
connect_token.server_addresses[i].data = new IPAddress(read_bytes(buffer, ref p, buf, 4));
connect_token.server_addresses[i].port = read_uint16(buffer, ref p);
}
else if (connect_token.server_addresses[i].type == ADDRESS_IPV6)
{
var buf = new byte[16];
connect_token.server_addresses[i].data = new IPAddress(read_bytes(buffer, ref p, buf, 16));
connect_token.server_addresses[i].port = read_uint16(buffer, ref p);
}
else return ERROR;
}
read_bytes(buffer, ref p, connect_token.client_to_server_key, KEY_BYTES);
read_bytes(buffer, ref p, connect_token.server_to_client_key, KEY_BYTES);
read_bytes(buffer, ref p, connect_token.user_data, USER_DATA_BYTES);
return OK;
}
#endregion
#region challenge_token_t
internal class challenge_token_t
{
public ulong client_id;
public byte[] user_data = new byte[USER_DATA_BYTES];
}
static void write_challenge_token(challenge_token_t challenge_token, byte[] buffer, int buffer_length)
{
assert(challenge_token != null);
assert(buffer != null);
assert(buffer_length >= CHALLENGE_TOKEN_BYTES);
BufferEx.Set(buffer, 0, CHALLENGE_TOKEN_BYTES);
var p = 0;
write_uint64(buffer, ref p, challenge_token.client_id);
write_bytes(buffer, ref p, challenge_token.user_data, USER_DATA_BYTES);
assert(p <= CHALLENGE_TOKEN_BYTES - MAC_BYTES);
}
static int encrypt_challenge_token(byte[] buffer, int p, int buffer_length, ulong sequence, byte[] key)
{
assert(buffer != null);
assert(buffer_length >= CHALLENGE_TOKEN_BYTES);
assert(key != null);
var nonce = new byte[12];
{
var p2 = 0;
write_uint32(nonce, ref p2, 0);
write_uint64(nonce, ref p2, sequence);
}
return encrypt_aead(buffer, p, CHALLENGE_TOKEN_BYTES - MAC_BYTES, null, 0, nonce, key);
}
static int decrypt_challenge_token(byte[] buffer, int p, int buffer_length, ulong sequence, byte[] key)
{
assert(buffer != null);
assert(buffer_length >= CHALLENGE_TOKEN_BYTES);
assert(key != null);
var nonce = new byte[12];
{
var p2 = 0;
write_uint32(nonce, ref p2, 0);
write_uint64(nonce, ref p2, sequence);
}
return decrypt_aead(buffer, p, CHALLENGE_TOKEN_BYTES, null, 0, nonce, key);
}
static int read_challenge_token(byte[] buffer, int buffer_length, challenge_token_t challenge_token)
{
assert(buffer != null);
assert(challenge_token != null);
if (buffer_length < CHALLENGE_TOKEN_BYTES)
return ERROR;
var p = 0;
challenge_token.client_id = read_uint64(buffer, ref p);
read_bytes(buffer, ref p, challenge_token.user_data, USER_DATA_BYTES);
assert(p == 8 + USER_DATA_BYTES);
return OK;
}
#endregion
#region challenge_token_t
const int CONNECTION_REQUEST_PACKET = 0;
const int CONNECTION_DENIED_PACKET = 1;
const int CONNECTION_CHALLENGE_PACKET = 2;
const int CONNECTION_RESPONSE_PACKET = 3;
const int CONNECTION_KEEP_ALIVE_PACKET = 4;
const int CONNECTION_PAYLOAD_PACKET = 5;
const int CONNECTION_DISCONNECT_PACKET = 6;
const int CONNECTION_NUM_PACKETS = 7;
internal class base_request_packet_t
{
public byte packet_type;
}
internal class connection_request_packet_t : base_request_packet_t
{
public byte[] version_info = new byte[VERSION_INFO_BYTES];
public ulong protocol_id;
public ulong connect_token_expire_timestamp;
public byte[] connect_token_nonce = new byte[CONNECT_TOKEN_NONCE_BYTES];
public byte[] connect_token_data = new byte[CONNECT_TOKEN_PRIVATE_BYTES];
}
internal class connection_denied_packet_t : base_request_packet_t
{
}
internal class connection_challenge_packet_t : base_request_packet_t
{
public ulong challenge_token_sequence;
public byte[] challenge_token_data = new byte[CHALLENGE_TOKEN_BYTES];
}
internal class connection_response_packet_t : base_request_packet_t
{
public ulong challenge_token_sequence;
public byte[] challenge_token_data = new byte[CHALLENGE_TOKEN_BYTES];
}
internal class connection_keep_alive_packet_t : base_request_packet_t
{
public int client_index;
public int max_clients;
}
internal class connection_payload_packet_t : base_request_packet_t
{
public ulong payload_bytes;
public byte[] payload_data;
}
internal class connection_disconnect_packet_t : base_request_packet_t
{
}
static connection_payload_packet_t create_payload_packet(int payload_bytes, object allocator_context, Func<object, ulong, object> allocate_function)
{
assert(payload_bytes >= 0);
assert(payload_bytes <= MAX_PAYLOAD_BYTES);
if (allocate_function == null)
allocate_function = default_allocate_function;
var packet = new connection_payload_packet_t { payload_data = new byte[payload_bytes] };
if (packet == null)
return null;
packet.packet_type = CONNECTION_PAYLOAD_PACKET;
packet.payload_bytes = (ulong)payload_bytes;
return packet;
}
internal class context_t
{
public byte[] write_packet_key = new byte[KEY_BYTES];
public byte[] read_packet_key = new byte[KEY_BYTES];
}
static int sequence_number_bytes_required(ulong sequence)
{
int i;
var mask = 0xFF00000000000000UL;
for (i = 0; i < 7; ++i)
{
if ((sequence & mask) != 0)
break;