-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Server.cs
1549 lines (1278 loc) · 45.7 KB
/
Server.cs
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
#region Copyright & License Information
/*
* Copyright (c) The OpenRA Developers and Contributors
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenRA;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Primitives;
using OpenRA.Support;
using OpenRA.Traits;
namespace OpenRA.Server
{
public enum ServerState
{
WaitingPlayers = 1,
GameStarted = 2,
ShuttingDown = 3
}
public enum ServerType
{
Local = 0,
Skirmish = 1,
Multiplayer = 2,
Dedicated = 3
}
public sealed class Server
{
[TranslationReference]
const string CustomRules = "notification-custom-rules";
[TranslationReference]
const string BotsDisabled = "notification-map-bots-disabled";
[TranslationReference]
const string TwoHumansRequired = "notification-two-humans-required";
[TranslationReference]
const string ErrorGameStarted = "notification-error-game-started";
[TranslationReference]
const string RequiresPassword = "notification-requires-password";
[TranslationReference]
const string IncorrectPassword = "notification-incorrect-password";
[TranslationReference]
const string IncompatibleMod = "notification-incompatible-mod";
[TranslationReference]
const string IncompatibleVersion = "notification-incompatible-version";
[TranslationReference]
const string IncompatibleProtocol = "notification-incompatible-protocol";
[TranslationReference]
const string Banned = "notification-you-were-banned";
[TranslationReference]
const string TempBanned = "notification-you-were-temp-banned";
[TranslationReference]
const string Full = "notification-game-full";
[TranslationReference("player")]
const string Joined = "notification-joined";
[TranslationReference]
const string RequiresAuthentication = "notification-requires-authentication";
[TranslationReference]
const string NoPermission = "notification-no-permission-to-join";
[TranslationReference("command")]
const string UnknownServerCommand = "notification-unknown-server-command";
[TranslationReference("player")]
const string LobbyDisconnected = "notification-lobby-disconnected";
[TranslationReference("player")]
const string PlayerDisconnected = "notification-player-disconnected";
[TranslationReference("player", "team")]
const string PlayerTeamDisconnected = "notification-team-player-disconnected";
[TranslationReference("player")]
const string ObserverDisconnected = "notification-observer-disconnected";
[TranslationReference("player")]
const string NewAdmin = "notification-new-admin";
[TranslationReference]
const string YouWereKicked = "notification-you-were-kicked";
[TranslationReference]
const string GameStarted = "notification-game-started";
public readonly MersenneTwister Random = new();
public readonly ServerType Type;
public bool IsMultiplayer => Type == ServerType.Dedicated || Type == ServerType.Multiplayer;
public readonly List<Connection> Conns = new();
public Session LobbyInfo;
public ServerSettings Settings;
public ModData ModData;
public List<string> TempBans = new();
// Managed by LobbyCommands
public MapPreview Map;
public readonly MapStatusCache MapStatusCache;
public GameSave GameSave;
public HashSet<string> MapPool;
// Default to the next frame for ServerType.Local - MP servers take the value from the selected GameSpeed.
public int OrderLatency = 1;
readonly int randomSeed;
readonly List<TcpListener> listeners = new();
readonly TypeDictionary serverTraits = new();
readonly PlayerDatabase playerDatabase;
OrderBuffer orderBuffer;
volatile ServerState internalState = ServerState.WaitingPlayers;
readonly BlockingCollection<IServerEvent> events = new();
ReplayRecorder recorder;
GameInformation gameInfo;
readonly List<GameInformation.Player> worldPlayers = new();
readonly Stopwatch pingUpdated = Stopwatch.StartNew();
public readonly VoteKickTracker VoteKickTracker;
readonly PlayerMessageTracker playerMessageTracker;
public ServerState State
{
get => internalState;
set => internalState = value;
}
public static void SyncClientToPlayerReference(Session.Client c, PlayerReference pr)
{
if (pr == null)
return;
if (pr.LockFaction)
c.Faction = pr.Faction;
if (pr.LockSpawn)
c.SpawnPoint = pr.Spawn;
if (pr.LockTeam)
c.Team = pr.Team;
if (pr.LockHandicap)
c.Handicap = pr.Handicap;
c.Color = pr.LockColor ? pr.Color : c.PreferredColor;
}
public void Shutdown()
{
State = ServerState.ShuttingDown;
}
public void EndGame()
{
foreach (var t in serverTraits.WithInterface<IEndGame>())
t.GameEnded(this);
recorder?.Dispose();
recorder = null;
}
// Craft a fake handshake request/response because that's the
// only way to expose the Version and OrdersProtocol.
public void RecordFakeHandshake()
{
var request = new HandshakeRequest
{
Mod = ModData.Manifest.Id,
Version = ModData.Manifest.Metadata.Version,
};
recorder.ReceiveFrame(0, 0, new Order("HandshakeRequest", null, false)
{
Type = OrderType.Handshake,
IsImmediate = true,
TargetString = request.Serialize(),
}.Serialize());
var response = new HandshakeResponse()
{
Mod = ModData.Manifest.Id,
Version = ModData.Manifest.Metadata.Version,
OrdersProtocol = ProtocolVersion.Orders,
Client = new Session.Client(),
};
recorder.ReceiveFrame(0, 0, new Order("HandshakeResponse", null, false)
{
Type = OrderType.Handshake,
IsImmediate = true,
TargetString = response.Serialize(),
}.Serialize());
}
void MapStatusChanged(string uid, Session.MapStatus status)
{
lock (LobbyInfo)
{
if (LobbyInfo.GlobalSettings.Map == uid)
LobbyInfo.GlobalSettings.MapStatus = status;
SyncLobbyInfo();
}
}
public Server(List<IPEndPoint> endpoints, ServerSettings settings, ModData modData, ServerType type)
{
Log.AddChannel("server", "server.log", true);
SocketException lastException = null;
foreach (var endpoint in endpoints)
{
var listener = new TcpListener(endpoint);
try
{
try
{
listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 1);
}
catch (Exception ex) when (ex is SocketException || ex is ArgumentException)
{
Log.Write("server", $"Failed to set socket option on {endpoint}: {ex.Message}");
}
listener.Start();
listeners.Add(listener);
new Thread(() =>
{
while (true)
{
if (State != ServerState.WaitingPlayers)
{
listener.Stop();
return;
}
// Use a 1s timeout so we can stop listening once the game starts
if (listener.Server.Poll(1000000, SelectMode.SelectRead))
{
try
{
events.Add(new ConnectionConnectEvent(listener.AcceptSocket()));
}
catch (Exception)
{
// Ignore the exception that may be generated if the connection
// drops while we are trying to connect
}
}
}
})
{ Name = $"Connection listener ({listener.LocalEndpoint})", IsBackground = true }.Start();
}
catch (SocketException ex)
{
lastException = ex;
Log.Write("server", $"Failed to listen on {endpoint}: {ex.Message}");
}
}
if (listeners.Count == 0)
throw lastException;
Type = type;
Settings = settings;
Settings.Name = Game.Settings.SanitizedServerName(Settings.Name);
ModData = modData;
playerDatabase = modData.Manifest.Get<PlayerDatabase>();
randomSeed = (int)DateTime.Now.ToBinary();
if (IsMultiplayer && settings.EnableGeoIP)
GeoIP.Initialize();
if (IsMultiplayer)
Nat.TryForwardPort(Settings.ListenPort, Settings.ListenPort);
foreach (var trait in modData.Manifest.ServerTraits)
serverTraits.Add(modData.ObjectCreator.CreateObject<ServerTrait>(trait));
serverTraits.TrimExcess();
MapStatusCache = new MapStatusCache(modData, MapStatusChanged, type == ServerType.Dedicated && settings.EnableLintChecks);
playerMessageTracker = new PlayerMessageTracker(this, DispatchOrdersToClient, SendLocalizedMessageTo);
VoteKickTracker = new VoteKickTracker(this);
LobbyInfo = new Session
{
GlobalSettings =
{
RandomSeed = randomSeed,
ServerName = settings.Name,
EnableSingleplayer = settings.EnableSingleplayer || Type != ServerType.Dedicated,
EnableSyncReports = settings.EnableSyncReports,
GameUid = Guid.NewGuid().ToString(),
Dedicated = Type == ServerType.Dedicated
}
};
if (Settings.RecordReplays && Type == ServerType.Dedicated)
{
recorder = new ReplayRecorder(() => Game.TimestampedFilename(extra: "-Server"));
// We only need one handshake to initialize the replay.
// Add it now, then ignore the redundant handshakes from each client
RecordFakeHandshake();
}
new Thread(_ =>
{
// Note: at least one of these is required to set the initial LobbyInfo.Map and MapStatus
foreach (var t in serverTraits.WithInterface<INotifyServerStart>())
t.ServerStarted(this);
Log.Write("server", $"Initial mod: {ModData.Manifest.Id}");
Log.Write("server", $"Initial map: {LobbyInfo.GlobalSettings.Map}");
while (true)
{
if (State != ServerState.ShuttingDown)
{
if (events.TryTake(out var e, 1000))
e.Invoke(this);
// PERF: Dedicated servers need to drain the action queue to remove references blocking the GC from cleaning up disposed objects.
if (Type == ServerType.Dedicated)
Game.PerformDelayedActions();
foreach (var t in serverTraits.WithInterface<ITick>())
t.Tick(this);
if (State == ServerState.GameStarted)
{
foreach (var (playerIndex, scale) in orderBuffer.GetTickScales())
{
var frame = CreateTickScaleFrame(scale);
var con = Conns.SingleOrDefault(c => c.PlayerIndex == playerIndex);
if (con != null && con.Validated)
DispatchFrameToClient(con, playerIndex, frame);
}
}
}
if (State == ServerState.ShuttingDown)
{
EndGame();
if (IsMultiplayer)
Nat.TryRemovePortForward();
break;
}
}
foreach (var t in serverTraits.WithInterface<INotifyServerShutdown>())
t.ServerShutdown(this);
// Make sure to immediately close connections after the server is shutdown, we don't want to keep clients waiting
foreach (var c in Conns)
c.Dispose();
Conns.Clear();
})
{ IsBackground = true }.Start();
}
int nextPlayerIndex;
public int ChooseFreePlayerIndex()
{
return nextPlayerIndex++;
}
internal void OnConnectionPacket(Connection conn, int frame, byte[] data)
{
events.Add(new ConnectionPacketEvent(conn, frame, data));
}
internal void OnConnectionPing(Connection conn, int[] pingHistory, byte queueLength)
{
events.Add(new ConnectionPingEvent(conn, pingHistory, queueLength));
}
internal void OnConnectionDisconnect(Connection conn)
{
events.Add(new ConnectionDisconnectEvent(conn));
}
void AcceptConnection(Socket socket)
{
if (State != ServerState.WaitingPlayers)
return;
// Validate player identity by asking them to sign a random blob of data
// which we can then verify against the player public key database
var token = Convert.ToBase64String(OpenRA.Exts.MakeArray(256, _ => (byte)Random.Next()));
var newConn = new Connection(this, socket, token);
try
{
// Send handshake and client index.
var ms = new MemoryStream(8);
ms.Write(ProtocolVersion.Handshake);
ms.Write(newConn.PlayerIndex);
newConn.TrySendData(ms.ToArray());
// Dispatch a handshake order
var request = new HandshakeRequest
{
Mod = ModData.Manifest.Id,
Version = ModData.Manifest.Metadata.Version,
AuthToken = token
};
DispatchOrdersToClient(newConn, 0, 0, new Order("HandshakeRequest", null, false)
{
Type = OrderType.Handshake,
IsImmediate = true,
TargetString = request.Serialize()
}.Serialize());
}
catch (Exception e)
{
Log.Write("server", $"Handshake for client {newConn.EndPoint} failed: {e}");
}
Conns.Add(newConn);
}
void ValidateClient(Connection newConn, string data, string name)
{
try
{
if (State == ServerState.GameStarted)
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; game is already started.");
SendOrderTo(newConn, "ServerError", ErrorGameStarted);
DropClient(newConn);
return;
}
var handshake = HandshakeResponse.Deserialize(data, name);
if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password)
{
var message = string.IsNullOrEmpty(handshake.Password) ? RequiresPassword : IncorrectPassword;
SendOrderTo(newConn, "AuthenticationError", message);
DropClient(newConn);
return;
}
var ipAddress = ((IPEndPoint)newConn.EndPoint).Address;
var client = new Session.Client
{
Name = OpenRA.Settings.SanitizedPlayerName(handshake.Client.Name),
IPAddress = ipAddress.ToString(),
AnonymizedIPAddress = IsMultiplayer && Settings.ShareAnonymizedIPs ? Session.AnonymizeIP(ipAddress) : null,
Location = GeoIP.LookupCountry(ipAddress),
Index = newConn.PlayerIndex,
PreferredColor = handshake.Client.PreferredColor,
Color = handshake.Client.Color,
Faction = "Random",
SpawnPoint = 0,
Team = 0,
Handicap = 0,
State = Session.ClientState.Invalid,
};
if (ModData.Manifest.Id != handshake.Mod)
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; mods do not match.");
SendOrderTo(newConn, "ServerError", IncompatibleMod);
DropClient(newConn);
return;
}
if (ModData.Manifest.Metadata.Version != handshake.Version)
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; Not running the same version.");
SendOrderTo(newConn, "ServerError", IncompatibleVersion);
DropClient(newConn);
return;
}
if (handshake.OrdersProtocol != ProtocolVersion.Orders)
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; incompatible Orders protocol version {handshake.OrdersProtocol}.");
SendOrderTo(newConn, "ServerError", IncompatibleProtocol);
DropClient(newConn);
return;
}
// Check if IP is banned
var bans = Settings.Ban.Union(TempBans);
if (bans.Contains(client.IPAddress))
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; Banned.");
var message = Settings.Ban.Contains(client.IPAddress) ? Banned : TempBanned;
SendOrderTo(newConn, "ServerError", message);
DropClient(newConn);
return;
}
void CompleteConnection()
{
lock (LobbyInfo)
{
client.Slot = LobbyInfo.FirstEmptySlot();
client.IsAdmin = !LobbyInfo.Clients.Any(c => c.IsAdmin);
if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators)
{
SendOrderTo(newConn, "ServerError", Full);
DropClient(newConn);
return;
}
if (client.Slot != null)
SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]);
else
client.Color = Color.White;
// Promote connection to a valid client
LobbyInfo.Clients.Add(client);
newConn.Validated = true;
// Disable chat UI to stop the client sending messages that we know we will reject
if (!client.IsAdmin && Settings.FloodLimitJoinCooldown > 0)
playerMessageTracker.DisableChatUI(newConn, Settings.FloodLimitJoinCooldown);
Log.Write("server", $"Client {newConn.PlayerIndex}: Accepted connection from {newConn.EndPoint}.");
if (client.Fingerprint != null)
Log.Write("server", $"Client {newConn.PlayerIndex}: Player fingerprint is {client.Fingerprint}.");
foreach (var t in serverTraits.WithInterface<IClientJoined>())
t.ClientJoined(this, newConn);
SyncLobbyInfo();
Log.Write("server", $"{client.Name} ({newConn.EndPoint}) has joined the game.");
SendLocalizedMessage(Joined, Translation.Arguments("player", client.Name));
if (Type == ServerType.Dedicated)
{
var motdFile = Path.Combine(Platform.SupportDir, "motd.txt");
if (!File.Exists(motdFile))
File.WriteAllText(motdFile, "Welcome, have fun and good luck!");
var motd = File.ReadAllText(motdFile);
if (!string.IsNullOrEmpty(motd))
SendOrderTo(newConn, "Message", motd);
}
if ((LobbyInfo.GlobalSettings.MapStatus & Session.MapStatus.UnsafeCustomRules) != 0)
SendLocalizedMessageTo(newConn, CustomRules);
if (!LobbyInfo.GlobalSettings.EnableSingleplayer)
SendLocalizedMessageTo(newConn, TwoHumansRequired);
else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots))
SendLocalizedMessageTo(newConn, BotsDisabled);
}
}
if (!IsMultiplayer)
{
// Local servers can only be joined by the local client, so we can trust their identity without validation
client.Fingerprint = handshake.Fingerprint;
CompleteConnection();
}
else if (!string.IsNullOrEmpty(handshake.Fingerprint) && !string.IsNullOrEmpty(handshake.AuthSignature))
{
Task.Run(async () =>
{
PlayerProfile profile = null;
try
{
var httpClient = HttpClientFactory.Create();
var url = playerDatabase.Profile + handshake.Fingerprint;
var httpResponseMessage = await httpClient.GetAsync(url);
var result = await httpResponseMessage.Content.ReadAsStreamAsync();
var yaml = MiniYaml.FromStream(result, url).First();
if (yaml.Key == "Player")
{
profile = FieldLoader.Load<PlayerProfile>(yaml.Value);
var publicKey = Encoding.ASCII.GetString(Convert.FromBase64String(profile.PublicKey));
var parameters = CryptoUtil.DecodePEMPublicKey(publicKey);
if (!profile.KeyRevoked && CryptoUtil.VerifySignature(parameters, newConn.AuthToken, handshake.AuthSignature))
{
client.Fingerprint = handshake.Fingerprint;
Log.Write("server", $"{newConn.EndPoint} authenticated as {profile.ProfileName} (UID {profile.ProfileID})");
}
else if (profile.KeyRevoked)
{
profile = null;
Log.Write("server", $"{newConn.EndPoint} failed to authenticate as {handshake.Fingerprint} (key revoked)");
}
else
{
profile = null;
Log.Write("server", $"{newConn.EndPoint} failed to authenticate as {handshake.Fingerprint} (signature verification failed)");
}
}
else
Log.Write("server", $"{newConn.EndPoint} failed to authenticate as {handshake.Fingerprint} (invalid server response: `{yaml.Key}` is not `Player`)");
}
catch (Exception ex)
{
Log.Write("server", $"{newConn.EndPoint} failed to authenticate as {handshake.Fingerprint} (exception occurred)");
Log.Write("server", ex.ToString());
}
events.Add(new CallbackEvent(() =>
{
var notAuthenticated = Type == ServerType.Dedicated && profile == null && (Settings.RequireAuthentication || Settings.ProfileIDWhitelist.Length > 0);
var blacklisted = Type == ServerType.Dedicated && profile != null && Settings.ProfileIDBlacklist.Contains(profile.ProfileID);
var notWhitelisted = Type == ServerType.Dedicated && Settings.ProfileIDWhitelist.Length > 0 &&
(profile == null || !Settings.ProfileIDWhitelist.Contains(profile.ProfileID));
if (notAuthenticated)
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; Not authenticated.");
SendOrderTo(newConn, "ServerError", RequiresAuthentication);
DropClient(newConn);
}
else if (blacklisted || notWhitelisted)
{
if (blacklisted)
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; In server blacklist.");
else
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; Not in server whitelist.");
SendOrderTo(newConn, "ServerError", NoPermission);
DropClient(newConn);
}
else
CompleteConnection();
}));
});
}
else
{
if (Type == ServerType.Dedicated && (Settings.RequireAuthentication || Settings.ProfileIDWhitelist.Length > 0))
{
Log.Write("server", $"Rejected connection from {newConn.EndPoint}; Not authenticated.");
SendOrderTo(newConn, "ServerError", RequiresAuthentication);
DropClient(newConn);
}
else
CompleteConnection();
}
}
catch (Exception ex)
{
Log.Write("server", $"Dropping connection {newConn.EndPoint} because an error occurred:");
Log.Write("server", ex.ToString());
DropClient(newConn);
}
}
static byte[] CreateFrame(int client, int frame, byte[] data)
{
var ms = new MemoryStream(data.Length + 12);
ms.Write(data.Length + 4);
ms.Write(client);
ms.Write(frame);
ms.Write(data);
return ms.GetBuffer();
}
static byte[] CreateAckFrame(int frame, byte count)
{
var ms = new MemoryStream(14);
ms.Write(6);
ms.Write(0);
ms.Write(frame);
ms.WriteByte((byte)OrderType.Ack);
ms.WriteByte(count);
return ms.GetBuffer();
}
static byte[] CreateTickScaleFrame(float scale)
{
var ms = new MemoryStream(17);
ms.Write(9);
ms.Write(0);
ms.Write(0);
ms.WriteByte((byte)OrderType.TickScale);
ms.Write(scale);
return ms.GetBuffer();
}
void DispatchOrdersToClient(Connection c, int client, int frame, byte[] data)
{
DispatchFrameToClient(c, client, CreateFrame(client, frame, data));
}
void DispatchFrameToClient(Connection c, int client, byte[] frameData)
{
if (!c.TrySendData(frameData))
{
DropClient(c);
Log.Write("server", $"Dropping client {client.ToString(CultureInfo.InvariantCulture)} because dispatching orders failed!");
}
}
bool AnyUndefinedWinStates()
{
var lastTeam = -1;
var remainingPlayers = gameInfo.Players.Where(p => p.Outcome == WinState.Undefined);
foreach (var player in remainingPlayers)
{
if (lastTeam >= 0 && (player.Team != lastTeam || player.Team == 0))
return true;
lastTeam = player.Team;
}
return false;
}
void SetPlayerDefeat(int playerIndex)
{
var defeatedPlayer = worldPlayers[playerIndex];
if (defeatedPlayer == null || defeatedPlayer.Outcome != WinState.Undefined)
return;
defeatedPlayer.Outcome = WinState.Lost;
defeatedPlayer.OutcomeTimestampUtc = DateTime.UtcNow;
// Set remaining players as winners if only one side remains
if (!AnyUndefinedWinStates())
{
var now = DateTime.UtcNow;
var remainingPlayers = gameInfo.Players.Where(p => p.Outcome == WinState.Undefined);
foreach (var winner in remainingPlayers)
{
winner.Outcome = WinState.Won;
winner.OutcomeTimestampUtc = now;
}
}
}
void OutOfSync(int frame)
{
Log.Write("server", $"Out of sync detected at frame {frame}, cancel replay recording");
// Make sure the written file is not valid
// TODO: storing a serverside replay on desync would be extremely useful
if (recorder != null)
{
recorder.Metadata = null;
recorder.Dispose();
}
// Stop the recording
recorder = null;
}
readonly Dictionary<int, byte[]> syncForFrame = new();
int lastDefeatStateFrame;
ulong lastDefeatState;
void HandleSyncOrder(int frame, byte[] packet)
{
if (syncForFrame.TryGetValue(frame, out var existingSync))
{
if (packet.Length != existingSync.Length)
{
OutOfSync(frame);
return;
}
for (var i = 0; i < packet.Length; i++)
{
if (packet[i] != existingSync[i])
{
OutOfSync(frame);
return;
}
}
}
else
{
// Update player losses based on the new defeat state.
// Do this once for the first player, the check above
// guarantees a desync if any other player disagrees.
var playerDefeatState = BitConverter.ToUInt64(packet, 1 + 4);
if (frame > lastDefeatStateFrame && lastDefeatState != playerDefeatState)
{
var newDefeats = playerDefeatState & ~lastDefeatState;
for (var i = 0; i < worldPlayers.Count; i++)
if ((newDefeats & (1UL << i)) != 0)
SetPlayerDefeat(i);
lastDefeatState = playerDefeatState;
lastDefeatStateFrame = frame;
}
syncForFrame.Add(frame, packet);
}
}
public void DispatchOrdersToClients(Connection conn, int frame, byte[] data)
{
var from = conn.PlayerIndex;
var frameData = CreateFrame(from, frame, data);
foreach (var c in Conns.ToList())
if (c != conn && c.Validated)
DispatchFrameToClient(c, from, frameData);
RecordOrder(frame, data, from);
}
void RecordOrder(int frame, byte[] data, int from)
{
recorder?.ReceiveFrame(from, frame, data);
if (data.Length > 0 && data[0] == (byte)OrderType.SyncHash)
{
if (data.Length == Order.SyncHashOrderLength)
HandleSyncOrder(frame, data);
else
Log.Write("server", $"Dropped sync order with length {data.Length} from client {from}. Expected length {Order.SyncHashOrderLength}.");
}
}
public void DispatchServerOrdersToClients(Order order)
{
DispatchServerOrdersToClients(order.Serialize());
}
public void DispatchServerOrdersToClients(byte[] data, int frame = 0)
{
const int From = 0;
var frameData = CreateFrame(From, frame, data);
foreach (var c in Conns.ToList())
if (c.Validated)
DispatchFrameToClient(c, From, frameData);
RecordOrder(frame, data, From);
}
public void ReceiveOrders(Connection conn, int frame, byte[] data)
{
// Make sure we don't accidentally forward on orders from clients who we have just dropped
if (!Conns.Contains(conn))
return;
if (frame == 0)
InterpretServerOrders(conn, data);
else
{
// Non-immediate orders must be projected into the future so that all players can
// apply them on the same world tick. We can do this directly when forwarding the
// packet on to other clients, but sending the same data back to the client that
// sent it just to update the frame number would be wasteful. We instead send them
// a separate Ack packet that tells them to apply the order from a locally stored queue.
// TODO: Replace static latency with a dynamic order buffering system
if (data.Length == 0 || data[0] != (byte)OrderType.SyncHash)
{
frame += OrderLatency;
DispatchFrameToClient(conn, conn.PlayerIndex, CreateAckFrame(frame, 1));
orderBuffer.AddOrderTimestamp(conn.PlayerIndex);
// Track the last frame for each client so the disconnect handling can write
// an EndOfOrders marker with the correct frame number.
// TODO: This should be handled by the order buffering system too
conn.LastOrdersFrame = frame;
}
DispatchOrdersToClients(conn, frame, data);
}
GameSave?.DispatchOrders(conn, frame, data);
}
void InterpretServerOrders(Connection conn, byte[] data)
{
var ms = new MemoryStream(data);
var br = new BinaryReader(ms);
try
{
while (ms.Position < ms.Length)
{
var o = Order.Deserialize(null, br);
if (o != null)
InterpretServerOrder(conn, o);
}
}
catch (EndOfStreamException) { }
catch (NotImplementedException) { }
}
public void SendOrderTo(Connection conn, string order, string data)
{
DispatchOrdersToClient(conn, 0, 0, Order.FromTargetString(order, data, true).Serialize());
}
public void SendMessage(string text)
{
DispatchServerOrdersToClients(Order.FromTargetString("Message", text, true));
if (Type == ServerType.Dedicated)
WriteLineWithTimeStamp(text);
}
public void SendLocalizedMessage(string key, Dictionary<string, object> arguments = null)
{
var text = LocalizedMessage.Serialize(key, arguments);
DispatchServerOrdersToClients(Order.FromTargetString("LocalizedMessage", text, true));
if (Type == ServerType.Dedicated)
WriteLineWithTimeStamp(TranslationProvider.GetString(key, arguments));
}
public void SendLocalizedMessageTo(Connection conn, string key, Dictionary<string, object> arguments = null)
{
var text = LocalizedMessage.Serialize(key, arguments);
DispatchOrdersToClient(conn, 0, 0, Order.FromTargetString("LocalizedMessage", text, true).Serialize());
}
void WriteLineWithTimeStamp(string line)
{
Console.WriteLine($"[{DateTime.Now.ToString(Settings.TimestampFormat, CultureInfo.CurrentCulture)}] {line}");
}
void InterpretServerOrder(Connection conn, Order o)
{
lock (LobbyInfo)
{
// Only accept handshake responses from unvalidated clients
// Anything else may be an attempt to exploit the server
if (!conn.Validated)
{
if (o.OrderString == "HandshakeResponse")
ValidateClient(conn, o.TargetString, o.OrderString);
else
{
Log.Write("server", $"Rejected connection from {conn.EndPoint}; Order `{o.OrderString}` is not a `HandshakeResponse`.");
DropClient(conn);
}
return;
}
switch (o.OrderString)
{
case "Command":
{
if (!InterpretCommand(o.TargetString, conn))
{
Log.Write("server", $"Unknown server command: {o.TargetString}");