forked from GlaireDaggers/Netcode.IO.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cs
More file actions
1074 lines (863 loc) · 30 KB
/
Copy pathServer.cs
File metadata and controls
1074 lines (863 loc) · 30 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
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Org.BouncyCastle.Crypto.TlsExt;
using NetcodeIO.NET.Utils;
using NetcodeIO.NET.Utils.IO;
using NetcodeIO.NET.Internal;
namespace NetcodeIO.NET;
/// <summary>
/// Represents a remote client connected to a server
/// </summary>
public class RemoteClient
{
/// <summary>
/// The unique ID of the client as assigned by the token server
/// </summary>
public ulong ClientID;
/// <summary>
/// The index as assigned by the server
/// </summary>
public uint ClientIndex;
/// <summary>
/// The remote endpoint of the client
/// </summary>
public EndPoint RemoteEndpoint;
/// <summary>
/// 256 bytes of arbitrary user data
/// </summary>
public byte[] UserData;
internal bool Connected;
internal bool Confirmed;
internal NetcodeReplayProtection replayProtection;
internal Server server;
internal double lastResponseTime;
internal int timeoutSeconds;
public RemoteClient(Server server)
{
this.server = server;
}
/// <summary>
/// Send a payload to this client
/// </summary>
public void SendPayload(byte[] payload, int payloadSize)
{
server.SendPayload(this, payload, payloadSize);
}
internal void Touch(double time)
{
lastResponseTime = time;
}
}
/// <summary>
/// Event handler for when a client connects to the server
/// </summary>
public delegate void RemoteClientConnectedEventHandler(RemoteClient client);
/// <summary>
/// Event handler for when a client disconnects from the server
/// </summary>
public delegate void RemoteClientDisconnectedEventHandler(RemoteClient client);
/// <summary>
/// Event handler for when payload packets are received from a connected client
/// </summary>
public delegate void RemoteClientMessageReceivedEventHandler(RemoteClient sender, byte[] payload, int payloadSize);
/// <summary>
/// Event handler for when the server writes a log message
/// </summary>
public delegate void ServerLogEventHandler(string message, NetcodeLogLevel logLevel);
/// <summary>
/// Class for starting a Netcode.IO server and accepting connections from remote clients
/// </summary>
public sealed class Server
{
#region embedded types
private struct usedConnectToken
{
public byte[] mac;
public EndPoint endpoint;
public double time;
}
#endregion
#region Public fields/properties
/// <summary>
/// Event triggered when a remote client connects
/// </summary>
public event RemoteClientConnectedEventHandler OnClientConnected;
/// <summary>
/// Event triggered when a remote client disconnects
/// </summary>
public event RemoteClientDisconnectedEventHandler OnClientDisconnected;
/// <summary>
/// Event triggered when a payload is received from a remote client
/// </summary>
public event RemoteClientMessageReceivedEventHandler OnClientMessageReceived;
/// <summary>
/// Event triggered when the server logs a message
/// </summary>
public event ServerLogEventHandler OnLogMessage;
/// <summary>
/// Log level for messages
/// </summary>
public NetcodeLogLevel LogLevel = NetcodeLogLevel.Error;
/// <summary>
/// Gets the port this server is listening on (or -1 if not listening)
/// </summary>
public int Port
{
get
{
if (listenSocket == null)
return -1;
return listenSocket.BoundPort;
}
}
/// <summary>
/// Gets or sets the internal tickrate of the server in ticks per second. Value must be between 1 and 1000.
/// </summary>
public int Tickrate
{
get { return tickrate; }
set
{
if (value < 1 || value > 1000) throw new ArgumentOutOfRangeException();
tickrate = value;
}
}
/// <summary>
/// Gets the current number of connected clients
/// </summary>
public int NumConnectedClients
{
get
{
int connectedClients = 0;
for (int i = 0; i < clientSlots.Length; i++)
if (clientSlots[i] != null && clientSlots[i].Confirmed) connectedClients++;
return connectedClients;
}
}
#endregion
#region Private fields
internal bool debugIgnoreConnectionRequest = false;
internal bool debugIgnoreChallengeResponse = false;
private ISocketContext listenSocket;
private IPEndPoint listenEndpoint;
private IPEndPoint externalEndpoint;
private bool isRunning = false;
private ulong protocolID;
private RemoteClient[] clientSlots;
private int maxSlots;
private usedConnectToken[] connectTokenHistory;
private int maxConnectTokenEntries;
private ulong nextSequenceNumber = 0;
private ulong nextChallengeSequenceNumber = 0;
private byte[] privateKey;
private byte[] challengeKey;
private EncryptionManager encryptionManager;
private int tickrate;
internal double time;
private bool disposed = false;
#endregion
public Server(int maxSlots, string address, int port, ulong protocolID, byte[] privateKey) :
this(maxSlots, address, address, port, protocolID, privateKey)
{
}
public Server(int maxSlots, string address, string externalAddress, int port, ulong protocolID, byte[] privateKey)
{
this.tickrate = 60;
this.maxSlots = maxSlots;
this.maxConnectTokenEntries = this.maxSlots * 8;
this.connectTokenHistory = new usedConnectToken[this.maxConnectTokenEntries];
initConnectTokenHistory();
this.clientSlots = new RemoteClient[maxSlots];
this.encryptionManager = new EncryptionManager(maxSlots);
this.listenEndpoint = new IPEndPoint(IPAddress.Parse(address), port);
this.externalEndpoint = new IPEndPoint(IPAddress.Parse(externalAddress), port);
if (this.listenEndpoint.AddressFamily == AddressFamily.InterNetwork)
this.listenSocket = new UDPSocketContext(AddressFamily.InterNetwork);
else
this.listenSocket = new UDPSocketContext(AddressFamily.InterNetworkV6);
this.protocolID = protocolID;
this.privateKey = privateKey;
// generate a random challenge key
this.challengeKey = new byte[32];
KeyUtils.GenerateKey(this.challengeKey);
}
internal Server(ISocketContext socketContext, int maxSlots, string address, int port, ulong protocolID, byte[] privateKey)
{
this.tickrate = 60;
this.maxSlots = maxSlots;
this.maxConnectTokenEntries = this.maxSlots * 8;
this.connectTokenHistory = new usedConnectToken[this.maxConnectTokenEntries];
initConnectTokenHistory();
this.clientSlots = new RemoteClient[maxSlots];
this.encryptionManager = new EncryptionManager(maxSlots);
this.listenEndpoint = new IPEndPoint(IPAddress.Parse(address), port);
this.listenSocket = socketContext;
this.protocolID = protocolID;
this.privateKey = privateKey;
// generate a random challenge key
this.challengeKey = new byte[32];
KeyUtils.GenerateKey(this.challengeKey);
}
#region Public Methods
/// <summary>
/// Start the server and listen for incoming connections
/// </summary>
public void Start()
{
Start(true);
}
internal void Start(bool autoTick)
{
if (disposed) throw new InvalidOperationException("Can't restart disposed server, please create a new server");
resetConnectTokenHistory();
this.listenSocket.Bind(this.listenEndpoint);
isRunning = true;
if (autoTick)
{
this.time = DateTime.Now.GetTotalSeconds();
ThreadPool.QueueUserWorkItem(serverTick);
}
}
/// <summary>
/// Stop the server and disconnect any clients
/// </summary>
public void Stop()
{
disposed = true;
disconnectAll();
isRunning = false;
this.listenSocket.Close();
if (OnClientConnected != null)
{
foreach (var receiver in OnClientConnected.GetInvocationList())
OnClientConnected -= (RemoteClientConnectedEventHandler)receiver;
}
if (OnClientDisconnected != null)
{
foreach (var receiver in OnClientDisconnected.GetInvocationList())
OnClientDisconnected -= (RemoteClientDisconnectedEventHandler)receiver;
}
if (OnClientMessageReceived != null)
{
foreach (var receiver in OnClientMessageReceived.GetInvocationList())
OnClientMessageReceived -= (RemoteClientMessageReceivedEventHandler)receiver;
}
if (OnLogMessage != null)
{
foreach (var receiver in OnLogMessage.GetInvocationList())
OnLogMessage -= (ServerLogEventHandler)receiver;
}
}
/// <summary>
/// Send a payload to the remote client
/// </summary>
public void SendPayload(RemoteClient client, byte[] payload, int payloadSize)
{
sendPayloadToClient(client, payload, payloadSize);
}
/// <summary>
/// Disconnect the remote client
/// </summary>
public void Disconnect(RemoteClient client)
{
disconnectClient(client);
}
#endregion
#region Core
double keepAlive = 0.0;
internal void Tick(double time)
{
this.listenSocket.Pump();
double dt = time - this.time;
this.time = time;
// 초당 10회 클라이언트에는 keep alive 를 보낸다
keepAlive += dt;
while (keepAlive >= 0.1)
{
keepAlive -= 0.1;
for (int i = 0; i < clientSlots.Length; i++)
{
if (clientSlots[i] != null)
{
sendKeepAlive(clientSlots[i]);
}
}
}
// 시간 초과 초 동안 응답하지 않은 클라이언트의 연결을 끊는다
for (int i = 0; i < clientSlots.Length; i++)
{
if (clientSlots[i] == null)
{
continue;
}
double timeRemaining = time - clientSlots[i].lastResponseTime;
// timeout < 0 disables timeouts
if (clientSlots[i].timeoutSeconds >= 0 &&
(time - clientSlots[i].lastResponseTime) >= clientSlots[i].timeoutSeconds)
{
if (OnClientDisconnected != null)
{
OnClientDisconnected(clientSlots[i]);
}
log("Client {0} timed out", NetcodeLogLevel.Debug, clientSlots[i].RemoteEndpoint.ToString());
disconnectClient(clientSlots[i]);
}
}
// process datagram queue
Datagram packet;
while (listenSocket != null && listenSocket.Read(out packet))
{
processDatagram(packet.payload, packet.payloadSize, packet.sender);
packet.Release();
}
}
private void serverTick(Object stateInfo)
{
while (isRunning)
{
Tick(DateTime.Now.GetTotalSeconds());
// sleep until next tick
double tickLength = 1.0 / tickrate;
Thread.Sleep((int)(tickLength * 1000));
}
}
// process a received datagram
private void processDatagram(byte[] payload, int size, EndPoint sender)
{
using (var reader = ByteArrayReaderWriter.Get(payload))
{
NetcodePacketHeader packetHeader = new NetcodePacketHeader();
packetHeader.Read(reader);
if (packetHeader.PacketType == NetcodePacketType.ConnectionRequest)
{
if (!debugIgnoreConnectionRequest)
processConnectionRequest(reader, size, sender);
}
else
{
switch (packetHeader.PacketType)
{
case NetcodePacketType.ChallengeResponse:
if (!debugIgnoreChallengeResponse)
processConnectionResponse(reader, packetHeader, size, sender);
break;
case NetcodePacketType.ConnectionKeepAlive:
processConnectionKeepAlive(reader, packetHeader, size, sender);
break;
case NetcodePacketType.ConnectionPayload:
processConnectionPayload(reader, packetHeader, size, sender);
break;
case NetcodePacketType.ConnectionDisconnect:
processConnectionDisconnect(reader, packetHeader, size, sender);
break;
}
}
}
}
#endregion
#region Receive Packet Methods
// check the packet against the client's replay protection, returning true if packet was replayed, false otherwise
private bool checkReplay(NetcodePacketHeader header, EndPoint sender)
{
var cryptIdx = encryptionManager.FindEncryptionMapping(sender, time);
if (cryptIdx == -1) {
log("Replay protection failed to find encryption mapping", NetcodeLogLevel.Debug);
return true;
}
var clientIndex = encryptionManager.GetClientID(cryptIdx);
var client = clientSlots[clientIndex];
if (client == null) {
log("Replay protection failed to find client", NetcodeLogLevel.Debug);
return true;
}
return client.replayProtection.AlreadyReceived(header.SequenceNumber);
}
// process an incoming disconnect message
private void processConnectionDisconnect(ByteArrayReaderWriter reader, NetcodePacketHeader header, int size, EndPoint sender)
{
if (checkReplay(header, sender))
{
return;
}
// encryption mapping was not registered, so don't bother
int cryptIdx = encryptionManager.FindEncryptionMapping(sender, time);
if (cryptIdx == -1)
{
log("No crytpo key for sender", NetcodeLogLevel.Debug);
return;
}
var decryptKey = encryptionManager.GetReceiveKey(cryptIdx);
var disconnectPacket = new NetcodeDisconnectPacket() { Header = header };
if (!disconnectPacket.Read(reader, size - (int)reader.ReadPosition, decryptKey, protocolID))
return;
// locate the client by endpoint and free their slot
var clientIndex = encryptionManager.GetClientID(cryptIdx);
var client = clientSlots[clientIndex];
if (client == null) return;
clientSlots[clientIndex] = null;
// remove encryption mapping
encryptionManager.RemoveEncryptionMapping(sender, time);
// make sure all other clients still have their encryption mappings
foreach (RemoteClient otherClient in clientSlots) {
if (otherClient == null) continue;
if (encryptionManager.FindEncryptionMapping(otherClient.RemoteEndpoint, time) == -1)
log("Encryption mapping removed wrong mapping!", NetcodeLogLevel.Debug);
}
// trigger client disconnect callback
if (OnClientDisconnected != null)
OnClientDisconnected(client);
log("Client {0} disconnected", NetcodeLogLevel.Info, client.RemoteEndpoint);
}
// process an incoming payload
private void processConnectionPayload(ByteArrayReaderWriter reader, NetcodePacketHeader header, int size, EndPoint sender)
{
if (checkReplay(header, sender))
{
return;
}
// encryption mapping was not registered, so don't bother
int cryptIdx = encryptionManager.FindEncryptionMapping(sender, time);
if (cryptIdx == -1)
{
log("No crytpo key for sender", NetcodeLogLevel.Debug);
return;
}
// grab the decryption key and decrypt the packet
var decryptKey = encryptionManager.GetReceiveKey(cryptIdx);
var payloadPacket = new NetcodePayloadPacket() { Header = header };
if (!payloadPacket.Read(reader, size - (int)reader.ReadPosition, decryptKey, protocolID))
return;
var clientIndex = encryptionManager.GetClientID(cryptIdx);
var client = clientSlots[clientIndex];
// trigger callback
if (OnClientMessageReceived != null)
OnClientMessageReceived(client, payloadPacket.Payload, payloadPacket.Length);
payloadPacket.Release();
}
// process an incoming connection keep alive packet
private void processConnectionKeepAlive(ByteArrayReaderWriter reader, NetcodePacketHeader header, int size, EndPoint sender)
{
if (checkReplay(header, sender))
{
log("Detected replay in keep-alive", NetcodeLogLevel.Debug);
return;
}
// encryption mapping was not registered, so don't bother
int cryptIdx = encryptionManager.FindEncryptionMapping(sender, time);
if (cryptIdx == -1)
{
log("No crytpo key for sender", NetcodeLogLevel.Debug);
return;
}
// grab the decryption key and decrypt the packet
var decryptKey = encryptionManager.GetReceiveKey(cryptIdx);
var keepAlivePacket = new NetcodeKeepAlivePacket() { Header = header };
if (!keepAlivePacket.Read(reader, size - (int)reader.ReadPosition, decryptKey, protocolID))
{
log("Failed to decrypt", NetcodeLogLevel.Debug);
return;
}
if (keepAlivePacket.ClientIndex >= maxSlots)
{
log("Invalid client index", NetcodeLogLevel.Debug);
return;
}
var client = this.clientSlots[(int)keepAlivePacket.ClientIndex];
if (client == null) {
log("Failed to find client for endpoint", NetcodeLogLevel.Debug);
return;
}
if (!client.RemoteEndpoint.Equals(sender))
{
log("Client does not match sender", NetcodeLogLevel.Debug);
return;
}
if (!client.Confirmed)
{
// trigger callback
if (OnClientConnected != null)
OnClientConnected(client);
log("Client {0} connected", NetcodeLogLevel.Info, client.RemoteEndpoint);
}
client.Confirmed = true;
client.Touch(time);
int idx = encryptionManager.FindEncryptionMapping(client.RemoteEndpoint, time);
encryptionManager.Touch(idx, client.RemoteEndpoint, time);
}
// process an incoming connection response packet
private void processConnectionResponse(ByteArrayReaderWriter reader, NetcodePacketHeader header, int size, EndPoint sender)
{
log("Got connection response", NetcodeLogLevel.Debug);
// encryption mapping was not registered, so don't bother
int cryptIdx = encryptionManager.FindEncryptionMapping(sender, time);
if (cryptIdx == -1)
{
log("No crytpo key for sender", NetcodeLogLevel.Debug);
return;
}
// grab the decryption key and decrypt the packet
var decryptKey = encryptionManager.GetReceiveKey(cryptIdx);
var connectionResponsePacket = new NetcodeConnectionChallengeResponsePacket() { Header = header };
if (!connectionResponsePacket.Read(reader, size - (int)reader.ReadPosition, decryptKey, protocolID))
{
log("Failed to decrypt packet", NetcodeLogLevel.Debug);
return;
}
var challengeToken = new NetcodeChallengeToken();
if (!challengeToken.Read(connectionResponsePacket.ChallengeTokenBytes, connectionResponsePacket.ChallengeTokenSequence, challengeKey))
{
log("Failed to read challenge token", NetcodeLogLevel.Debug);
connectionResponsePacket.Release();
return;
}
// if a client from packet source IP / port is already connected, ignore the packet
if (clientSlots.Any(x => x != null && x.RemoteEndpoint.Equals(sender)))
{
log("Client {0} already connected", NetcodeLogLevel.Debug, sender.ToString());
return;
}
// if a client with the same id is already connected, ignore the packet
if (clientSlots.Any(x => x != null && x.ClientID == challengeToken.ClientID))
{
log("Client ID {0} already connected", NetcodeLogLevel.Debug, challengeToken.ClientID);
return;
}
// if the server is full, deny the connection
int nextSlot = getFreeClientSlot();
if (nextSlot == -1)
{
log("Server full, denying connection", NetcodeLogLevel.Info);
denyConnection(sender, encryptionManager.GetSendKey(cryptIdx));
return;
}
// assign the endpoint and client ID to a free client slot and set connected to true
RemoteClient client = new RemoteClient(this);
client.ClientID = challengeToken.ClientID;
client.RemoteEndpoint = sender;
client.Connected = true;
client.replayProtection = new NetcodeReplayProtection();
// assign timeout to client
client.timeoutSeconds = encryptionManager.GetTimeoutSeconds(cryptIdx);
// assign client to a free slot
client.ClientIndex = (uint)nextSlot;
this.clientSlots[nextSlot] = client;
encryptionManager.SetClientID(cryptIdx, client.ClientIndex);
// copy user data so application can make use of it, and set confirmed to false
client.UserData = challengeToken.UserData;
client.Confirmed = false;
client.Touch(time);
// respond with a connection keep alive packet
sendKeepAlive(client);
}
// process an incoming connection request packet
private void processConnectionRequest(ByteArrayReaderWriter reader, int size, EndPoint sender)
{
log("Got connection request", NetcodeLogLevel.Debug);
var connectionRequestPacket = new NetcodeConnectionRequestPacket();
if (!connectionRequestPacket.Read(reader, size - (int)reader.ReadPosition, protocolID))
{
log("Failed to read request", NetcodeLogLevel.Debug);
return;
}
// expiration timestamp should be greater than current timestamp
if (connectionRequestPacket.Expiration <= (ulong)Math.Truncate(time))
{
log("Connect token expired", NetcodeLogLevel.Debug);
connectionRequestPacket.Release();
return;
}
var privateConnectToken = new NetcodePrivateConnectToken();
if (!privateConnectToken.Read(connectionRequestPacket.ConnectTokenBytes, privateKey, protocolID, connectionRequestPacket.Expiration, connectionRequestPacket.TokenSequenceNum))
{
log("Failed to read private token", NetcodeLogLevel.Debug);
connectionRequestPacket.Release();
return;
}
// if this server's public IP is not in the list of endpoints, packet is not valid
bool serverAddressInEndpoints = privateConnectToken.ConnectServers.Any(x => x.Endpoint.CompareEndpoint(this.externalEndpoint, this.Port));
if (!serverAddressInEndpoints)
{
log("Server address not listen in token", NetcodeLogLevel.Debug);
return;
}
// if a client from packet source IP / port is already connected, ignore the packet
if (clientSlots.Any(x => x != null && x.RemoteEndpoint.Equals(sender)))
{
log("Client {0} already connected", NetcodeLogLevel.Debug, sender.ToString());
return;
}
// if a client with the same id as the connect token is already connected, ignore the packet
if (clientSlots.Any(x => x != null && x.ClientID == privateConnectToken.ClientID))
{
log("Client ID {0} already connected", NetcodeLogLevel.Debug, privateConnectToken.ClientID);
return;
}
// if the connect token has already been used by a different endpoint, ignore the packet
// otherwise, add the token hmac and endpoint to the used token history
// compares the last 16 bytes (token mac)
byte[] token_mac = BufferPool.GetBuffer(Defines.MAC_SIZE);
System.Array.Copy(connectionRequestPacket.ConnectTokenBytes, Defines.NETCODE_CONNECT_TOKEN_PRIVATE_BYTES - Defines.MAC_SIZE, token_mac, 0, Defines.MAC_SIZE);
if (!findOrAddConnectToken(sender, token_mac, time))
{
log("Token already used", NetcodeLogLevel.Debug);
BufferPool.ReturnBuffer(token_mac);
return;
}
BufferPool.ReturnBuffer(token_mac);
// if we have no slots, we need to respond with a connection denied packet
var nextSlot = getFreeClientSlot();
if (nextSlot == -1)
{
denyConnection(sender, privateConnectToken.ServerToClientKey);
log("Server is full, denying connection", NetcodeLogLevel.Info);
return;
}
// add encryption mapping for this endpoint as well as timeout
// packets received from this endpoint are to be decrypted with the client-to-server key
// packets sent to this endpoint are to be encrypted with the server-to-client key
// if no messages are received within timeout from this endpoint, it is disconnected (unless timeout is negative)
if (!encryptionManager.AddEncryptionMapping(sender,
privateConnectToken.ServerToClientKey,
privateConnectToken.ClientToServerKey,
time,
time + 30,
privateConnectToken.TimeoutSeconds,
0))
{
log("Failed to add encryption mapping", NetcodeLogLevel.Error);
return;
}
// finally, send a connection challenge packet
sendConnectionChallenge(privateConnectToken, sender);
}
#endregion
#region Send Packet Methods
// disconnect all clients
private void disconnectAll()
{
for (int i = 0; i < clientSlots.Length; i++)
{
if (clientSlots[i] != null)
disconnectClient(clientSlots[i]);
}
}
// sends a disconnect packet to the client
private void disconnectClient(RemoteClient client)
{
for (int i = 0; i < clientSlots.Length; i++)
{
if (clientSlots[i] == client)
{
clientSlots[i] = null;
break;
}
}
var cryptIdx = encryptionManager.FindEncryptionMapping(client.RemoteEndpoint, time);
if (cryptIdx == -1)
{
return;
}
var cryptKey = encryptionManager.GetSendKey(cryptIdx);
for (int i = 0; i < Defines.NUM_DISCONNECT_PACKETS; i++)
{
serializePacket(new NetcodePacketHeader() { PacketType = NetcodePacketType.ConnectionDisconnect }, (writer) =>
{
}, client.RemoteEndpoint, cryptKey);
}
}
// sends a connection denied packet to the endpoint
private void denyConnection(EndPoint endpoint, byte[] cryptKey)
{
if (cryptKey == null)
{
var cryptIdx = encryptionManager.FindEncryptionMapping(endpoint, time);
if (cryptIdx == -1) return;
cryptKey = encryptionManager.GetSendKey(cryptIdx);
}
serializePacket(new NetcodePacketHeader() { PacketType = NetcodePacketType.ConnectionDenied }, (writer) =>
{
}, endpoint, cryptKey);
}
// send a payload to a client
private void sendPayloadToClient(RemoteClient client, byte[] payload, int payloadSize)
{
// if the client isn't confirmed, send a keep-alive packet before this packet
if (!client.Confirmed)
sendKeepAlive(client);
var cryptIdx = encryptionManager.FindEncryptionMapping(client.RemoteEndpoint, time);
if (cryptIdx == -1) return;
var cryptKey = encryptionManager.GetSendKey(cryptIdx);
serializePacket(new NetcodePacketHeader() { PacketType = NetcodePacketType.ConnectionPayload }, (writer) =>
{
writer.WriteBuffer(payload, payloadSize);
}, client.RemoteEndpoint, cryptKey);
}
// send a keep-alive packet to the client
private void sendKeepAlive(RemoteClient client)
{
var packet = new NetcodeKeepAlivePacket() { ClientIndex = client.ClientIndex, MaxSlots = (uint)this.maxSlots };
var cryptIdx = encryptionManager.FindEncryptionMapping(client.RemoteEndpoint, time);
if (cryptIdx == -1) return;
var cryptKey = encryptionManager.GetSendKey(cryptIdx);
serializePacket(new NetcodePacketHeader() { PacketType = NetcodePacketType.ConnectionKeepAlive }, (writer) =>
{
packet.Write(writer);
}, client.RemoteEndpoint, cryptKey);
}
// sends a connection challenge packet to the endpoint
private void sendConnectionChallenge(NetcodePrivateConnectToken connectToken, EndPoint endpoint)
{
log("Sending connection challenge", NetcodeLogLevel.Debug);
var challengeToken = new NetcodeChallengeToken();
challengeToken.ClientID = connectToken.ClientID;
challengeToken.UserData = connectToken.UserData;
ulong challengeSequence = nextChallengeSequenceNumber++;
byte[] tokenBytes = BufferPool.GetBuffer(300);
using (var tokenWriter = ByteArrayReaderWriter.Get(tokenBytes))
challengeToken.Write(tokenWriter);
byte[] encryptedToken = BufferPool.GetBuffer(300);
int encryptedTokenBytes;
try
{
encryptedTokenBytes = PacketIO.EncryptChallengeToken(challengeSequence, tokenBytes, challengeKey, encryptedToken);
}
catch
{
BufferPool.ReturnBuffer(tokenBytes);
BufferPool.ReturnBuffer(encryptedToken);
return;
}
var challengePacket = new NetcodeConnectionChallengeResponsePacket();
challengePacket.ChallengeTokenSequence = challengeSequence;
challengePacket.ChallengeTokenBytes = encryptedToken;
var cryptIdx = encryptionManager.FindEncryptionMapping(endpoint, time);
if (cryptIdx == -1) return;
var cryptKey = encryptionManager.GetSendKey(cryptIdx);
serializePacket(new NetcodePacketHeader() { PacketType = NetcodePacketType.ConnectionChallenge }, (writer) =>
{
challengePacket.Write(writer);
}, endpoint, cryptKey);
BufferPool.ReturnBuffer(tokenBytes);
BufferPool.ReturnBuffer(encryptedToken);
}
// encrypts a packet and sends it to the endpoint
private void sendPacketToClient(NetcodePacketHeader packetHeader, byte[] packetData, int packetDataLen, EndPoint endpoint, byte[] key)
{
// assign a sequence number to this packet
packetHeader.SequenceNumber = this.nextSequenceNumber++;
// encrypt packet data
byte[] encryptedPacketBuffer = BufferPool.GetBuffer(2048);
int encryptedBytes = PacketIO.EncryptPacketData(packetHeader, protocolID, packetData, packetDataLen, key, encryptedPacketBuffer);
int packetLen = 0;
// write packet to byte array
var packetBuffer = BufferPool.GetBuffer(2048);
using (var packetWriter = ByteArrayReaderWriter.Get(packetBuffer))
{
packetHeader.Write(packetWriter);
packetWriter.WriteBuffer(encryptedPacketBuffer, encryptedBytes);
packetLen = (int)packetWriter.WritePosition;
}
// send packet
listenSocket.SendTo(packetBuffer, packetLen, endpoint);
BufferPool.ReturnBuffer(packetBuffer);
BufferPool.ReturnBuffer(encryptedPacketBuffer);
}
private void serializePacket(NetcodePacketHeader packetHeader, Action<ByteArrayReaderWriter> write, EndPoint endpoint, byte[] key)
{
byte[] tempPacket = BufferPool.GetBuffer(2048);
int writeLen = 0;
using (var writer = ByteArrayReaderWriter.Get(tempPacket))
{
write(writer);
writeLen = (int)writer.WritePosition;
}
sendPacketToClient(packetHeader, tempPacket, writeLen, endpoint, key);
BufferPool.ReturnBuffer(tempPacket);
}
#endregion
#region Misc Util Methods
// find or add a connect token entry
// intentional constant time worst case search
private bool findOrAddConnectToken(EndPoint address, byte[] mac, double time)
{
int matchingTokenIndex = -1;
int oldestTokenIndex = -1;
double oldestTokenTime = 0.0;
for (int i = 0; i < connectTokenHistory.Length; i++)
{
var token = connectTokenHistory[i];
if (MiscUtils.CompareHMACConstantTime(token.mac, mac))
matchingTokenIndex = i;
if (oldestTokenIndex == -1 || token.time < oldestTokenTime)
{
oldestTokenTime = token.time;
oldestTokenIndex = i;
}