From 0672553a0711253239c90e9b7c58b1cf56d94908 Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Sun, 20 Sep 2020 12:54:03 +0100 Subject: [PATCH] Lock Server.LobbyInfo to prevent races with callback threads. --- OpenRA.Game/Server/Server.cs | 669 ++++---- .../ServerTraits/LobbyCommands.cs | 1482 +++++++++-------- .../ServerTraits/LobbySettingsNotification.cs | 39 +- .../ServerTraits/PlayerPinger.cs | 6 +- 4 files changed, 1156 insertions(+), 1040 deletions(-) diff --git a/OpenRA.Game/Server/Server.cs b/OpenRA.Game/Server/Server.cs index ee9ae373c5..4392e72ef8 100644 --- a/OpenRA.Game/Server/Server.cs +++ b/OpenRA.Game/Server/Server.cs @@ -431,69 +431,72 @@ namespace OpenRA.Server Action completeConnection = () => { - client.Slot = LobbyInfo.FirstEmptySlot(); - client.IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin); - - if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) + lock (LobbyInfo) { - SendOrderTo(newConn, "ServerError", "The game is full"); - DropClient(newConn); - return; + client.Slot = LobbyInfo.FirstEmptySlot(); + client.IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin); + + if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) + { + SendOrderTo(newConn, "ServerError", "The game is 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 + PreConns.Remove(newConn); + Conns.Add(newConn); + LobbyInfo.Clients.Add(client); + newConn.Validated = true; + + var clientPing = new Session.ClientPing { Index = client.Index }; + LobbyInfo.ClientPings.Add(clientPing); + + Log.Write("server", "Client {0}: Accepted connection from {1}.", + newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); + + if (client.Fingerprint != null) + Log.Write("server", "Client {0}: Player fingerprint is {1}.", + newConn.PlayerIndex, client.Fingerprint); + + foreach (var t in serverTraits.WithInterface()) + t.ClientJoined(this, newConn); + + SyncLobbyInfo(); + + Log.Write("server", "{0} ({1}) has joined the game.", + client.Name, newConn.Socket.RemoteEndPoint); + + // Report to all other players + SendMessage("{0} has joined the game.".F(client.Name), newConn); + + // Send initial ping + SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); + + if (Type == ServerType.Dedicated) + { + var motdFile = Platform.ResolvePath(Platform.SupportDirPrefix, "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 (Map.DefinesUnsafeCustomRules) + SendOrderTo(newConn, "Message", "This map contains custom rules. Game experience may change."); + + if (!LobbyInfo.GlobalSettings.EnableSingleplayer) + SendOrderTo(newConn, "Message", TwoHumansRequiredText); + else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) + SendOrderTo(newConn, "Message", "Bots have been disabled on this map."); } - - if (client.Slot != null) - SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); - else - client.Color = Color.White; - - // Promote connection to a valid client - PreConns.Remove(newConn); - Conns.Add(newConn); - LobbyInfo.Clients.Add(client); - newConn.Validated = true; - - var clientPing = new Session.ClientPing { Index = client.Index }; - LobbyInfo.ClientPings.Add(clientPing); - - Log.Write("server", "Client {0}: Accepted connection from {1}.", - newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); - - if (client.Fingerprint != null) - Log.Write("server", "Client {0}: Player fingerprint is {1}.", - newConn.PlayerIndex, client.Fingerprint); - - foreach (var t in serverTraits.WithInterface()) - t.ClientJoined(this, newConn); - - SyncLobbyInfo(); - - Log.Write("server", "{0} ({1}) has joined the game.", - client.Name, newConn.Socket.RemoteEndPoint); - - // Report to all other players - SendMessage("{0} has joined the game.".F(client.Name), newConn); - - // Send initial ping - SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); - - if (Type == ServerType.Dedicated) - { - var motdFile = Platform.ResolvePath(Platform.SupportDirPrefix, "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 (Map.DefinesUnsafeCustomRules) - SendOrderTo(newConn, "Message", "This map contains custom rules. Game experience may change."); - - if (!LobbyInfo.GlobalSettings.EnableSingleplayer) - SendOrderTo(newConn, "Message", TwoHumansRequiredText); - else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) - SendOrderTo(newConn, "Message", "Bots have been disabled on this map."); }; if (Type == ServerType.Local) @@ -676,89 +679,119 @@ namespace OpenRA.Server void InterpretServerOrder(Connection conn, Order o) { - // Only accept handshake responses from unvalidated clients - // Anything else may be an attempt to exploit the server - if (!conn.Validated) + lock (LobbyInfo) { - if (o.OrderString == "HandshakeResponse") - ValidateClient(conn, o.TargetString); - else + // Only accept handshake responses from unvalidated clients + // Anything else may be an attempt to exploit the server + if (!conn.Validated) { - Log.Write("server", "Rejected connection from {0}; Order `{1}` is not a `HandshakeResponse`.", - conn.Socket.RemoteEndPoint, o.OrderString); - - DropClient(conn); - } - - return; - } - - switch (o.OrderString) - { - case "Command": + if (o.OrderString == "HandshakeResponse") + ValidateClient(conn, o.TargetString); + else { - var handledBy = serverTraits.WithInterface() - .FirstOrDefault(t => t.InterpretCommand(this, conn, GetClient(conn), o.TargetString)); + Log.Write("server", "Rejected connection from {0}; Order `{1}` is not a `HandshakeResponse`.", + conn.Socket.RemoteEndPoint, o.OrderString); - if (handledBy == null) - { - Log.Write("server", "Unknown server command: {0}", o.TargetString); - SendOrderTo(conn, "Message", "Unknown server command: {0}".F(o.TargetString)); - } - - break; + DropClient(conn); } - case "Chat": - DispatchOrdersToClients(conn, 0, o.Serialize()); - break; - case "Pong": - { - if (!OpenRA.Exts.TryParseInt64Invariant(o.TargetString, out var pingSent)) + return; + } + + switch (o.OrderString) + { + case "Command": { - Log.Write("server", "Invalid order pong payload: {0}", o.TargetString); + var handledBy = serverTraits.WithInterface() + .FirstOrDefault(t => t.InterpretCommand(this, conn, GetClient(conn), o.TargetString)); + + if (handledBy == null) + { + Log.Write("server", "Unknown server command: {0}", o.TargetString); + SendOrderTo(conn, "Message", "Unknown server command: {0}".F(o.TargetString)); + } + break; } - var client = GetClient(conn); - if (client == null) - return; - - var pingFromClient = LobbyInfo.PingFromClient(client); - if (pingFromClient == null) - return; - - var history = pingFromClient.LatencyHistory.ToList(); - history.Add(Game.RunTime - pingSent); - - // Cap ping history at 5 values (25 seconds) - if (history.Count > 5) - history.RemoveRange(0, history.Count - 5); - - pingFromClient.Latency = history.Sum() / history.Count; - pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2; - pingFromClient.LatencyHistory = history.ToArray(); - - SyncClientPing(); - + case "Chat": + DispatchOrdersToClients(conn, 0, o.Serialize()); break; - } - - case "GameSaveTraitData": - { - if (GameSave != null) + case "Pong": { - var data = MiniYaml.FromString(o.TargetString)[0]; - GameSave.AddTraitData(int.Parse(data.Key), data.Value); + if (!OpenRA.Exts.TryParseInt64Invariant(o.TargetString, out var pingSent)) + { + Log.Write("server", "Invalid order pong payload: {0}", o.TargetString); + break; + } + + var client = GetClient(conn); + if (client == null) + return; + + var pingFromClient = LobbyInfo.PingFromClient(client); + if (pingFromClient == null) + return; + + var history = pingFromClient.LatencyHistory.ToList(); + history.Add(Game.RunTime - pingSent); + + // Cap ping history at 5 values (25 seconds) + if (history.Count > 5) + history.RemoveRange(0, history.Count - 5); + + pingFromClient.Latency = history.Sum() / history.Count; + pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2; + pingFromClient.LatencyHistory = history.ToArray(); + + SyncClientPing(); + + break; } - break; - } - - case "CreateGameSave": - { - if (GameSave != null) + case "GameSaveTraitData": { + if (GameSave != null) + { + var data = MiniYaml.FromString(o.TargetString)[0]; + GameSave.AddTraitData(int.Parse(data.Key), data.Value); + } + + break; + } + + case "CreateGameSave": + { + if (GameSave != null) + { + // Sanitize potentially malicious input + var filename = o.TargetString; + var invalidIndex = -1; + var invalidChars = Path.GetInvalidFileNameChars(); + while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1) + filename = filename.Remove(invalidIndex, 1); + + var baseSavePath = Platform.ResolvePath( + Platform.SupportDirPrefix, + "Saves", + ModData.Manifest.Id, + ModData.Manifest.Metadata.Version); + + if (!Directory.Exists(baseSavePath)) + Directory.CreateDirectory(baseSavePath); + + GameSave.Save(Path.Combine(baseSavePath, filename)); + DispatchOrdersToClients(null, 0, Order.FromTargetString("GameSaved", filename, true).Serialize()); + } + + break; + } + + case "LoadGameSave": + { + if (Type == ServerType.Dedicated || State >= ServerState.GameStarted) + break; + // Sanitize potentially malicious input var filename = o.TargetString; var invalidIndex = -1; @@ -766,96 +799,69 @@ namespace OpenRA.Server while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1) filename = filename.Remove(invalidIndex, 1); - var baseSavePath = Platform.ResolvePath( + var savePath = Platform.ResolvePath( Platform.SupportDirPrefix, "Saves", ModData.Manifest.Id, - ModData.Manifest.Metadata.Version); + ModData.Manifest.Metadata.Version, + filename); - if (!Directory.Exists(baseSavePath)) - Directory.CreateDirectory(baseSavePath); + GameSave = new GameSave(savePath); + LobbyInfo.GlobalSettings = GameSave.GlobalSettings; + LobbyInfo.Slots = GameSave.Slots; - GameSave.Save(Path.Combine(baseSavePath, filename)); - DispatchOrdersToClients(null, 0, Order.FromTargetString("GameSaved", filename, true).Serialize()); - } + // Reassign clients to slots + // - Bot ordering is preserved + // - Humans are assigned on a first-come-first-serve basis + // - Leftover humans become spectators - break; - } - - case "LoadGameSave": - { - if (Type == ServerType.Dedicated || State >= ServerState.GameStarted) - break; - - // Sanitize potentially malicious input - var filename = o.TargetString; - var invalidIndex = -1; - var invalidChars = Path.GetInvalidFileNameChars(); - while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1) - filename = filename.Remove(invalidIndex, 1); - - var savePath = Platform.ResolvePath( - Platform.SupportDirPrefix, - "Saves", - ModData.Manifest.Id, - ModData.Manifest.Metadata.Version, - filename); - - GameSave = new GameSave(savePath); - LobbyInfo.GlobalSettings = GameSave.GlobalSettings; - LobbyInfo.Slots = GameSave.Slots; - - // Reassign clients to slots - // - Bot ordering is preserved - // - Humans are assigned on a first-come-first-serve basis - // - Leftover humans become spectators - - // Start by removing all bots and assigning all players as spectators - foreach (var c in LobbyInfo.Clients) - { - if (c.Bot != null) + // Start by removing all bots and assigning all players as spectators + foreach (var c in LobbyInfo.Clients) { - LobbyInfo.Clients.Remove(c); - var ping = LobbyInfo.PingFromClient(c); - if (ping != null) - LobbyInfo.ClientPings.Remove(ping); - } - else - c.Slot = null; - } - - // Rebuild/remap the saved client state - // TODO: Multiplayer saves should leave all humans as spectators so they can manually pick slots - var adminClientIndex = LobbyInfo.Clients.First(c => c.IsAdmin).Index; - foreach (var kv in GameSave.SlotClients) - { - if (kv.Value.Bot != null) - { - var bot = new Session.Client() + if (c.Bot != null) { - Index = ChooseFreePlayerIndex(), - State = Session.ClientState.NotReady, - BotControllerClientIndex = adminClientIndex - }; - - kv.Value.ApplyTo(bot); - LobbyInfo.Clients.Add(bot); + LobbyInfo.Clients.Remove(c); + var ping = LobbyInfo.PingFromClient(c); + if (ping != null) + LobbyInfo.ClientPings.Remove(ping); + } + else + c.Slot = null; } - else + + // Rebuild/remap the saved client state + // TODO: Multiplayer saves should leave all humans as spectators so they can manually pick slots + var adminClientIndex = LobbyInfo.Clients.First(c => c.IsAdmin).Index; + foreach (var kv in GameSave.SlotClients) { - // This will throw if the server doesn't have enough human clients to fill all player slots - // See TODO above - this isn't a problem in practice because MP saves won't use this - var client = LobbyInfo.Clients.First(c => c.Slot == null); - kv.Value.ApplyTo(client); + if (kv.Value.Bot != null) + { + var bot = new Session.Client() + { + Index = ChooseFreePlayerIndex(), + State = Session.ClientState.NotReady, + BotControllerClientIndex = adminClientIndex + }; + + kv.Value.ApplyTo(bot); + LobbyInfo.Clients.Add(bot); + } + else + { + // This will throw if the server doesn't have enough human clients to fill all player slots + // See TODO above - this isn't a problem in practice because MP saves won't use this + var client = LobbyInfo.Clients.First(c => c.Slot == null); + kv.Value.ApplyTo(client); + } } + + SyncLobbyInfo(); + SyncLobbyClients(); + SyncClientPing(); + + break; } - - SyncLobbyInfo(); - SyncLobbyClients(); - SyncClientPing(); - - break; - } + } } } @@ -866,54 +872,57 @@ namespace OpenRA.Server public void DropClient(Connection toDrop) { - if (!PreConns.Remove(toDrop)) + lock (LobbyInfo) { - Conns.Remove(toDrop); - - var dropClient = LobbyInfo.Clients.FirstOrDefault(c1 => c1.Index == toDrop.PlayerIndex); - if (dropClient == null) - return; - - var suffix = ""; - if (State == ServerState.GameStarted) - suffix = dropClient.IsObserver ? " (Spectator)" : dropClient.Team != 0 ? " (Team {0})".F(dropClient.Team) : ""; - SendMessage("{0}{1} has disconnected.".F(dropClient.Name, suffix)); - - // Send disconnected order, even if still in the lobby - DispatchOrdersToClients(toDrop, 0, Order.FromTargetString("Disconnected", "", true).Serialize()); - - LobbyInfo.Clients.RemoveAll(c => c.Index == toDrop.PlayerIndex); - LobbyInfo.ClientPings.RemoveAll(p => p.Index == toDrop.PlayerIndex); - - // Client was the server admin - // TODO: Reassign admin for game in progress via an order - if (Type == ServerType.Dedicated && dropClient.IsAdmin && State == ServerState.WaitingPlayers) + if (!PreConns.Remove(toDrop)) { - // Remove any bots controlled by the admin - LobbyInfo.Clients.RemoveAll(c => c.Bot != null && c.BotControllerClientIndex == toDrop.PlayerIndex); + Conns.Remove(toDrop); - var nextAdmin = LobbyInfo.Clients.Where(c1 => c1.Bot == null) - .MinByOrDefault(c => c.Index); + var dropClient = LobbyInfo.Clients.FirstOrDefault(c1 => c1.Index == toDrop.PlayerIndex); + if (dropClient == null) + return; - if (nextAdmin != null) + var suffix = ""; + if (State == ServerState.GameStarted) + suffix = dropClient.IsObserver ? " (Spectator)" : dropClient.Team != 0 ? " (Team {0})".F(dropClient.Team) : ""; + SendMessage("{0}{1} has disconnected.".F(dropClient.Name, suffix)); + + // Send disconnected order, even if still in the lobby + DispatchOrdersToClients(toDrop, 0, Order.FromTargetString("Disconnected", "", true).Serialize()); + + LobbyInfo.Clients.RemoveAll(c => c.Index == toDrop.PlayerIndex); + LobbyInfo.ClientPings.RemoveAll(p => p.Index == toDrop.PlayerIndex); + + // Client was the server admin + // TODO: Reassign admin for game in progress via an order + if (Type == ServerType.Dedicated && dropClient.IsAdmin && State == ServerState.WaitingPlayers) { - nextAdmin.IsAdmin = true; - SendMessage("{0} is now the admin.".F(nextAdmin.Name)); + // Remove any bots controlled by the admin + LobbyInfo.Clients.RemoveAll(c => c.Bot != null && c.BotControllerClientIndex == toDrop.PlayerIndex); + + var nextAdmin = LobbyInfo.Clients.Where(c1 => c1.Bot == null) + .MinByOrDefault(c => c.Index); + + if (nextAdmin != null) + { + nextAdmin.IsAdmin = true; + SendMessage("{0} is now the admin.".F(nextAdmin.Name)); + } } + + DispatchOrders(toDrop, toDrop.MostRecentFrame, new[] { (byte)OrderType.Disconnect }); + + // All clients have left: clean up + if (!Conns.Any()) + foreach (var t in serverTraits.WithInterface()) + t.ServerEmpty(this); + + if (Conns.Any() || Type == ServerType.Dedicated) + SyncLobbyClients(); + + if (Type != ServerType.Dedicated && dropClient.IsAdmin) + Shutdown(); } - - DispatchOrders(toDrop, toDrop.MostRecentFrame, new[] { (byte)OrderType.Disconnect }); - - // All clients have left: clean up - if (!Conns.Any()) - foreach (var t in serverTraits.WithInterface()) - t.ServerEmpty(this); - - if (Conns.Any() || Type == ServerType.Dedicated) - SyncLobbyClients(); - - if (Type != ServerType.Dedicated && dropClient.IsAdmin) - Shutdown(); } try @@ -925,11 +934,14 @@ namespace OpenRA.Server public void SyncLobbyInfo() { - if (State == ServerState.WaitingPlayers) // Don't do this while the game is running, it breaks things! - DispatchOrders(null, 0, Order.FromTargetString("SyncInfo", LobbyInfo.Serialize(), true).Serialize()); + lock (LobbyInfo) + { + if (State == ServerState.WaitingPlayers) // Don't do this while the game is running, it breaks things! + DispatchOrders(null, 0, Order.FromTargetString("SyncInfo", LobbyInfo.Serialize(), true).Serialize()); - foreach (var t in serverTraits.WithInterface()) - t.LobbyInfoSynced(this); + foreach (var t in serverTraits.WithInterface()) + t.LobbyInfoSynced(this); + } } public void SyncLobbyClients() @@ -937,13 +949,16 @@ namespace OpenRA.Server if (State != ServerState.WaitingPlayers) return; - // TODO: Only need to sync the specific client that has changed to avoid conflicts! - var clientData = LobbyInfo.Clients.Select(client => client.Serialize()).ToList(); + lock (LobbyInfo) + { + // TODO: Only need to sync the specific client that has changed to avoid conflicts! + var clientData = LobbyInfo.Clients.Select(client => client.Serialize()).ToList(); - DispatchOrders(null, 0, Order.FromTargetString("SyncLobbyClients", clientData.WriteToString(), true).Serialize()); + DispatchOrders(null, 0, Order.FromTargetString("SyncLobbyClients", clientData.WriteToString(), true).Serialize()); - foreach (var t in serverTraits.WithInterface()) - t.LobbyInfoSynced(this); + foreach (var t in serverTraits.WithInterface()) + t.LobbyInfoSynced(this); + } } public void SyncLobbySlots() @@ -951,13 +966,16 @@ namespace OpenRA.Server if (State != ServerState.WaitingPlayers) return; - // TODO: Don't sync all the slots if just one changed! - var slotData = LobbyInfo.Slots.Select(slot => slot.Value.Serialize()).ToList(); + lock (LobbyInfo) + { + // TODO: Don't sync all the slots if just one changed! + var slotData = LobbyInfo.Slots.Select(slot => slot.Value.Serialize()).ToList(); - DispatchOrders(null, 0, Order.FromTargetString("SyncLobbySlots", slotData.WriteToString(), true).Serialize()); + DispatchOrders(null, 0, Order.FromTargetString("SyncLobbySlots", slotData.WriteToString(), true).Serialize()); - foreach (var t in serverTraits.WithInterface()) - t.LobbyInfoSynced(this); + foreach (var t in serverTraits.WithInterface()) + t.LobbyInfoSynced(this); + } } public void SyncLobbyGlobalSettings() @@ -965,86 +983,95 @@ namespace OpenRA.Server if (State != ServerState.WaitingPlayers) return; - var sessionData = new List { LobbyInfo.GlobalSettings.Serialize() }; + lock (LobbyInfo) + { + var sessionData = new List { LobbyInfo.GlobalSettings.Serialize() }; - DispatchOrders(null, 0, Order.FromTargetString("SyncLobbyGlobalSettings", sessionData.WriteToString(), true).Serialize()); + DispatchOrders(null, 0, Order.FromTargetString("SyncLobbyGlobalSettings", sessionData.WriteToString(), true).Serialize()); - foreach (var t in serverTraits.WithInterface()) - t.LobbyInfoSynced(this); + foreach (var t in serverTraits.WithInterface()) + t.LobbyInfoSynced(this); + } } public void SyncClientPing() { - // TODO: Split this further into per client ping orders - var clientPings = LobbyInfo.ClientPings.Select(ping => ping.Serialize()).ToList(); + lock (LobbyInfo) + { + // TODO: Split this further into per client ping orders + var clientPings = LobbyInfo.ClientPings.Select(ping => ping.Serialize()).ToList(); - // Note that syncing pings doesn't trigger INotifySyncLobbyInfo - DispatchOrders(null, 0, Order.FromTargetString("SyncClientPings", clientPings.WriteToString(), true).Serialize()); + // Note that syncing pings doesn't trigger INotifySyncLobbyInfo + DispatchOrders(null, 0, Order.FromTargetString("SyncClientPings", clientPings.WriteToString(), true).Serialize()); + } } public void StartGame() { - foreach (var listener in listeners) - listener.Stop(); - - Console.WriteLine("[{0}] Game started", DateTime.Now.ToString(Settings.TimestampFormat)); - - // Drop any unvalidated clients - foreach (var c in PreConns.ToArray()) - DropClient(c); - - // Drop any players who are not ready - foreach (var c in Conns.Where(c => GetClient(c).IsInvalid).ToArray()) + lock (LobbyInfo) { - SendOrderTo(c, "ServerError", "You have been kicked from the server!"); - DropClient(c); - } + foreach (var listener in listeners) + listener.Stop(); - // HACK: Turn down the latency if there is only one real player - if (LobbyInfo.NonBotClients.Count() == 1) - LobbyInfo.GlobalSettings.OrderLatency = 1; + Console.WriteLine("[{0}] Game started", DateTime.Now.ToString(Settings.TimestampFormat)); - // Enable game saves for singleplayer missions only - // TODO: Enable for multiplayer (non-dedicated servers only) once the lobby UI has been created - LobbyInfo.GlobalSettings.GameSavesEnabled = Type != ServerType.Dedicated && LobbyInfo.NonBotClients.Count() == 1; + // Drop any unvalidated clients + foreach (var c in PreConns.ToArray()) + DropClient(c); - SyncLobbyInfo(); - State = ServerState.GameStarted; - - foreach (var c in Conns) - foreach (var d in Conns) - DispatchOrdersToClient(c, d.PlayerIndex, int.MaxValue, new[] { (byte)OrderType.Disconnect }); - - if (GameSave == null && LobbyInfo.GlobalSettings.GameSavesEnabled) - GameSave = new GameSave(); - - var startGameData = ""; - if (GameSave != null) - { - GameSave.StartGame(LobbyInfo, Map); - if (GameSave.LastOrdersFrame >= 0) + // Drop any players who are not ready + foreach (var c in Conns.Where(c => GetClient(c).IsInvalid).ToArray()) { - startGameData = new List() - { - new MiniYamlNode("SaveLastOrdersFrame", GameSave.LastOrdersFrame.ToString()), - new MiniYamlNode("SaveSyncFrame", GameSave.LastSyncFrame.ToString()) - }.WriteToString(); + SendOrderTo(c, "ServerError", "You have been kicked from the server!"); + DropClient(c); } - } - DispatchOrders(null, 0, - Order.FromTargetString("StartGame", startGameData, true).Serialize()); + // HACK: Turn down the latency if there is only one real player + if (LobbyInfo.NonBotClients.Count() == 1) + LobbyInfo.GlobalSettings.OrderLatency = 1; - foreach (var t in serverTraits.WithInterface()) - t.GameStarted(this); + // Enable game saves for singleplayer missions only + // TODO: Enable for multiplayer (non-dedicated servers only) once the lobby UI has been created + LobbyInfo.GlobalSettings.GameSavesEnabled = Type != ServerType.Dedicated && LobbyInfo.NonBotClients.Count() == 1; - if (GameSave != null && GameSave.LastOrdersFrame >= 0) - { - GameSave.ParseOrders(LobbyInfo, (frame, client, data) => + SyncLobbyInfo(); + State = ServerState.GameStarted; + + foreach (var c in Conns) + foreach (var d in Conns) + DispatchOrdersToClient(c, d.PlayerIndex, int.MaxValue, new[] { (byte)OrderType.Disconnect }); + + if (GameSave == null && LobbyInfo.GlobalSettings.GameSavesEnabled) + GameSave = new GameSave(); + + var startGameData = ""; + if (GameSave != null) { - foreach (var c in Conns) - DispatchOrdersToClient(c, client, frame, data); - }); + GameSave.StartGame(LobbyInfo, Map); + if (GameSave.LastOrdersFrame >= 0) + { + startGameData = new List() + { + new MiniYamlNode("SaveLastOrdersFrame", GameSave.LastOrdersFrame.ToString()), + new MiniYamlNode("SaveSyncFrame", GameSave.LastSyncFrame.ToString()) + }.WriteToString(); + } + } + + DispatchOrders(null, 0, + Order.FromTargetString("StartGame", startGameData, true).Serialize()); + + foreach (var t in serverTraits.WithInterface()) + t.GameStarted(this); + + if (GameSave != null && GameSave.LastOrdersFrame >= 0) + { + GameSave.ParseOrders(LobbyInfo, (frame, client, data) => + { + foreach (var c in Conns) + DispatchOrdersToClient(c, client, frame, data); + }); + } } } diff --git a/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs b/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs index b9575a3906..4f8a1a9638 100644 --- a/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs +++ b/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs @@ -49,39 +49,45 @@ namespace OpenRA.Mods.Common.Server static bool ValidateSlotCommand(S server, Connection conn, Session.Client client, string arg, bool requiresHost) { - if (!server.LobbyInfo.Slots.ContainsKey(arg)) + lock (server.LobbyInfo) { - Log.Write("server", "Invalid slot: {0}", arg); - return false; - } + if (!server.LobbyInfo.Slots.ContainsKey(arg)) + { + Log.Write("server", "Invalid slot: {0}", arg); + return false; + } - if (requiresHost && !client.IsAdmin) - { - server.SendOrderTo(conn, "Message", "Only the host can do that."); - return false; - } + if (requiresHost && !client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can do that."); + return false; + } - return true; + return true; + } } public static bool ValidateCommand(S server, Connection conn, Session.Client client, string cmd) { - // Kick command is always valid for the host - if (cmd.StartsWith("kick ")) + lock (server.LobbyInfo) + { + // Kick command is always valid for the host + if (cmd.StartsWith("kick ")) + return true; + + if (server.State == ServerState.GameStarted) + { + server.SendOrderTo(conn, "Message", "Cannot change state when game started. ({0})".F(cmd)); + return false; + } + else if (client.State == Session.ClientState.Ready && !(cmd.StartsWith("state") || cmd == "startgame")) + { + server.SendOrderTo(conn, "Message", "Cannot change state when marked as ready."); + return false; + } + return true; - - if (server.State == ServerState.GameStarted) - { - server.SendOrderTo(conn, "Message", "Cannot change state when game started. ({0})".F(cmd)); - return false; } - else if (client.State == Session.ClientState.Ready && !(cmd.StartsWith("state") || cmd == "startgame")) - { - server.SendOrderTo(conn, "Message", "Cannot change state when marked as ready."); - return false; - } - - return true; } public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) @@ -100,143 +106,200 @@ namespace OpenRA.Mods.Common.Server static void CheckAutoStart(S server) { - var nonBotPlayers = server.LobbyInfo.NonBotPlayers; + lock (server.LobbyInfo) + { + var nonBotPlayers = server.LobbyInfo.NonBotPlayers; - // Are all players and admin (could be spectating) ready? - if (nonBotPlayers.Any(c => c.State != Session.ClientState.Ready) || - server.LobbyInfo.Clients.First(c => c.IsAdmin).State != Session.ClientState.Ready) - return; + // Are all players and admin (could be spectating) ready? + if (nonBotPlayers.Any(c => c.State != Session.ClientState.Ready) || + server.LobbyInfo.Clients.First(c => c.IsAdmin).State != Session.ClientState.Ready) + return; - // Does server have at least 2 human players? - if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer && nonBotPlayers.Count() < 2) - return; + // Does server have at least 2 human players? + if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer && nonBotPlayers.Count() < 2) + return; - // Are the map conditions satisfied? - if (server.LobbyInfo.Slots.Any(sl => sl.Value.Required && server.LobbyInfo.ClientInSlot(sl.Key) == null)) - return; + // Are the map conditions satisfied? + if (server.LobbyInfo.Slots.Any(sl => sl.Value.Required && server.LobbyInfo.ClientInSlot(sl.Key) == null)) + return; - server.StartGame(); + server.StartGame(); + } } static bool State(S server, Connection conn, Session.Client client, string s) { - var state = Session.ClientState.Invalid; - if (!Enum.TryParse(s, false, out state)) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Malformed state command"); + if (!Enum.TryParse(s, false, out var state)) + { + server.SendOrderTo(conn, "Message", "Malformed state command"); + return true; + } + + client.State = state; + Log.Write("server", "Player @{0} is {1}", conn.Socket.RemoteEndPoint, client.State); + + server.SyncLobbyClients(); + CheckAutoStart(server); + return true; } - - client.State = state; - - Log.Write("server", "Player @{0} is {1}", - conn.Socket.RemoteEndPoint, client.State); - - server.SyncLobbyClients(); - - CheckAutoStart(server); - - return true; } static bool StartGame(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can start the game."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can start the game."); + return true; + } + + if (server.LobbyInfo.Slots.Any(sl => sl.Value.Required && + server.LobbyInfo.ClientInSlot(sl.Key) == null)) + { + server.SendOrderTo(conn, "Message", "Unable to start the game until required slots are full."); + return true; + } + + if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer && server.LobbyInfo.NonBotPlayers.Count() < 2) + { + server.SendOrderTo(conn, "Message", server.TwoHumansRequiredText); + return true; + } + + server.StartGame(); + return true; } - - if (server.LobbyInfo.Slots.Any(sl => sl.Value.Required && - server.LobbyInfo.ClientInSlot(sl.Key) == null)) - { - server.SendOrderTo(conn, "Message", "Unable to start the game until required slots are full."); - return true; - } - - if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer && server.LobbyInfo.NonBotPlayers.Count() < 2) - { - server.SendOrderTo(conn, "Message", server.TwoHumansRequiredText); - return true; - } - - server.StartGame(); - return true; } static bool Slot(S server, Connection conn, Session.Client client, string s) { - if (!server.LobbyInfo.Slots.ContainsKey(s)) + lock (server.LobbyInfo) { - Log.Write("server", "Invalid slot: {0}", s); - return false; + if (!server.LobbyInfo.Slots.ContainsKey(s)) + { + Log.Write("server", "Invalid slot: {0}", s); + return false; + } + + var slot = server.LobbyInfo.Slots[s]; + + if (slot.Closed || server.LobbyInfo.ClientInSlot(s) != null) + return false; + + // If the previous slot had a locked spawn then we must not carry that to the new slot + var oldSlot = client.Slot != null ? server.LobbyInfo.Slots[client.Slot] : null; + if (oldSlot != null && oldSlot.LockSpawn) + client.SpawnPoint = 0; + + client.Slot = s; + S.SyncClientToPlayerReference(client, server.Map.Players.Players[s]); + + if (!slot.LockColor) + client.PreferredColor = client.Color = SanitizePlayerColor(server, client.Color, client.Index, conn); + + server.SyncLobbyClients(); + CheckAutoStart(server); + + return true; } - - var slot = server.LobbyInfo.Slots[s]; - - if (slot.Closed || server.LobbyInfo.ClientInSlot(s) != null) - return false; - - // If the previous slot had a locked spawn then we must not carry that to the new slot - var oldSlot = client.Slot != null ? server.LobbyInfo.Slots[client.Slot] : null; - if (oldSlot != null && oldSlot.LockSpawn) - client.SpawnPoint = 0; - - client.Slot = s; - S.SyncClientToPlayerReference(client, server.Map.Players.Players[s]); - - if (!slot.LockColor) - client.PreferredColor = client.Color = SanitizePlayerColor(server, client.Color, client.Index, conn); - - server.SyncLobbyClients(); - CheckAutoStart(server); - - return true; } static bool AllowSpectators(S server, Connection conn, Session.Client client, string s) { - if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) - { - server.SyncLobbyGlobalSettings(); - return true; - } - else + lock (server.LobbyInfo) { + if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) + { + server.SyncLobbyGlobalSettings(); + return true; + } + server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); + return true; } } static bool Specate(S server, Connection conn, Session.Client client, string s) { - if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) + lock (server.LobbyInfo) { - client.Slot = null; - client.SpawnPoint = 0; - client.Team = 0; - client.Color = Color.White; - server.SyncLobbyClients(); - CheckAutoStart(server); - return true; - } - else + if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) + { + client.Slot = null; + client.SpawnPoint = 0; + client.Team = 0; + client.Color = Color.White; + server.SyncLobbyClients(); + CheckAutoStart(server); + return true; + } + return false; + } } static bool SlotClose(S server, Connection conn, Session.Client client, string s) { - if (!ValidateSlotCommand(server, conn, client, s, true)) - return false; - - // kick any player that's in the slot - var occupant = server.LobbyInfo.ClientInSlot(s); - if (occupant != null) + lock (server.LobbyInfo) { - if (occupant.Bot != null) + if (!ValidateSlotCommand(server, conn, client, s, true)) + return false; + + // kick any player that's in the slot + var occupant = server.LobbyInfo.ClientInSlot(s); + if (occupant != null) + { + if (occupant.Bot != null) + { + server.LobbyInfo.Clients.Remove(occupant); + server.SyncLobbyClients(); + var ping = server.LobbyInfo.PingFromClient(occupant); + if (ping != null) + { + server.LobbyInfo.ClientPings.Remove(ping); + server.SyncClientPing(); + } + } + else + { + var occupantConn = server.Conns.FirstOrDefault(c => c.PlayerIndex == occupant.Index); + if (occupantConn != null) + { + server.SendOrderTo(occupantConn, "ServerError", "Your slot was closed by the host."); + server.DropClient(occupantConn); + } + } + } + + server.LobbyInfo.Slots[s].Closed = true; + server.SyncLobbySlots(); + + return true; + } + } + + static bool SlotOpen(S server, Connection conn, Session.Client client, string s) + { + lock (server.LobbyInfo) + { + if (!ValidateSlotCommand(server, conn, client, s, true)) + return false; + + var slot = server.LobbyInfo.Slots[s]; + slot.Closed = false; + server.SyncLobbySlots(); + + // Slot may have a bot in it + var occupant = server.LobbyInfo.ClientInSlot(s); + if (occupant != null && occupant.Bot != null) { server.LobbyInfo.Clients.Remove(occupant); - server.SyncLobbyClients(); var ping = server.LobbyInfo.PingFromClient(occupant); if (ping != null) { @@ -244,635 +307,642 @@ namespace OpenRA.Mods.Common.Server server.SyncClientPing(); } } - else - { - var occupantConn = server.Conns.FirstOrDefault(c => c.PlayerIndex == occupant.Index); - if (occupantConn != null) - { - server.SendOrderTo(occupantConn, "ServerError", "Your slot was closed by the host."); - server.DropClient(occupantConn); - } - } + + server.SyncLobbyClients(); + + return true; } - - server.LobbyInfo.Slots[s].Closed = true; - server.SyncLobbySlots(); - - return true; - } - - static bool SlotOpen(S server, Connection conn, Session.Client client, string s) - { - if (!ValidateSlotCommand(server, conn, client, s, true)) - return false; - - var slot = server.LobbyInfo.Slots[s]; - slot.Closed = false; - server.SyncLobbySlots(); - - // Slot may have a bot in it - var occupant = server.LobbyInfo.ClientInSlot(s); - if (occupant != null && occupant.Bot != null) - { - server.LobbyInfo.Clients.Remove(occupant); - var ping = server.LobbyInfo.PingFromClient(occupant); - if (ping != null) - { - server.LobbyInfo.ClientPings.Remove(ping); - server.SyncClientPing(); - } - } - - server.SyncLobbyClients(); - - return true; } static bool SlotBot(S server, Connection conn, Session.Client client, string s) { - var parts = s.Split(' '); - - if (parts.Length < 3) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Malformed slot_bot command"); - return true; - } - - if (!ValidateSlotCommand(server, conn, client, parts[0], true)) - return false; - - var slot = server.LobbyInfo.Slots[parts[0]]; - var bot = server.LobbyInfo.ClientInSlot(parts[0]); - if (!Exts.TryParseIntegerInvariant(parts[1], out var controllerClientIndex)) - { - Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); - return false; - } - - // Invalid slot - if (bot != null && bot.Bot == null) - { - server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); - return true; - } - - var botType = parts[2]; - var botInfo = server.Map.Rules.Actors["player"].TraitInfos() - .FirstOrDefault(b => b.Type == botType); - - if (botInfo == null) - { - server.SendOrderTo(conn, "Message", "Invalid bot type."); - return true; - } - - slot.Closed = false; - if (bot == null) - { - // Create a new bot - bot = new Session.Client() + var parts = s.Split(' '); + if (parts.Length < 3) { - Index = server.ChooseFreePlayerIndex(), - Name = botInfo.Name, - Bot = botType, - Slot = parts[0], - Faction = "Random", - SpawnPoint = 0, - Team = 0, - State = Session.ClientState.NotReady, - BotControllerClientIndex = controllerClientIndex - }; + server.SendOrderTo(conn, "Message", "Malformed slot_bot command"); + return true; + } - // Pick a random color for the bot - var validator = server.ModData.Manifest.Get(); - var tileset = server.Map.Rules.TileSet; - var terrainColors = tileset.TerrainInfo.Where(ti => ti.RestrictPlayerColor).Select(ti => ti.Color); - var playerColors = server.LobbyInfo.Clients.Select(c => c.Color) - .Concat(server.Map.Players.Players.Values.Select(p => p.Color)); - bot.Color = bot.PreferredColor = validator.RandomPresetColor(server.Random, terrainColors, playerColors); + if (!ValidateSlotCommand(server, conn, client, parts[0], true)) + return false; - server.LobbyInfo.Clients.Add(bot); + var slot = server.LobbyInfo.Slots[parts[0]]; + var bot = server.LobbyInfo.ClientInSlot(parts[0]); + if (!Exts.TryParseIntegerInvariant(parts[1], out var controllerClientIndex)) + { + Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); + return false; + } + + // Invalid slot + if (bot != null && bot.Bot == null) + { + server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); + return true; + } + + var botType = parts[2]; + var botInfo = server.Map.Rules.Actors["player"].TraitInfos() + .FirstOrDefault(b => b.Type == botType); + + if (botInfo == null) + { + server.SendOrderTo(conn, "Message", "Invalid bot type."); + return true; + } + + slot.Closed = false; + if (bot == null) + { + // Create a new bot + bot = new Session.Client() + { + Index = server.ChooseFreePlayerIndex(), + Name = botInfo.Name, + Bot = botType, + Slot = parts[0], + Faction = "Random", + SpawnPoint = 0, + Team = 0, + State = Session.ClientState.NotReady, + BotControllerClientIndex = controllerClientIndex + }; + + // Pick a random color for the bot + var validator = server.ModData.Manifest.Get(); + var tileset = server.Map.Rules.TileSet; + var terrainColors = tileset.TerrainInfo.Where(ti => ti.RestrictPlayerColor).Select(ti => ti.Color); + var playerColors = server.LobbyInfo.Clients.Select(c => c.Color) + .Concat(server.Map.Players.Players.Values.Select(p => p.Color)); + bot.Color = bot.PreferredColor = validator.RandomPresetColor(server.Random, terrainColors, playerColors); + + server.LobbyInfo.Clients.Add(bot); + } + else + { + // Change the type of the existing bot + bot.Name = botInfo.Name; + bot.Bot = botType; + } + + S.SyncClientToPlayerReference(bot, server.Map.Players.Players[parts[0]]); + server.SyncLobbyClients(); + server.SyncLobbySlots(); + + return true; } - else - { - // Change the type of the existing bot - bot.Name = botInfo.Name; - bot.Bot = botType; - } - - S.SyncClientToPlayerReference(bot, server.Map.Players.Players[parts[0]]); - server.SyncLobbyClients(); - server.SyncLobbySlots(); - - return true; } static bool Map(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can change the map."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can change the map."); + return true; + } + + var lastMap = server.LobbyInfo.GlobalSettings.Map; + Action selectMap = map => + { + lock (server.LobbyInfo) + { + // Make sure the map hasn't changed in the meantime + if (server.LobbyInfo.GlobalSettings.Map != lastMap) + return; + + server.LobbyInfo.GlobalSettings.Map = map.Uid; + + var oldSlots = server.LobbyInfo.Slots.Keys.ToArray(); + server.Map = server.ModData.MapCache[server.LobbyInfo.GlobalSettings.Map]; + + server.LobbyInfo.Slots = server.Map.Players.Players + .Select(p => MakeSlotFromPlayerReference(p.Value)) + .Where(ss => ss != null) + .ToDictionary(ss => ss.PlayerReference, ss => ss); + + LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); + + // Reset client states + var selectableFactions = server.Map.Rules.Actors["world"].TraitInfos() + .Where(f => f.Selectable) + .Select(f => f.InternalName) + .ToList(); + + foreach (var c in server.LobbyInfo.Clients) + { + c.State = Session.ClientState.Invalid; + if (!selectableFactions.Contains(c.Faction)) + c.Faction = "Random"; + } + + // Reassign players into new slots based on their old slots: + // - Observers remain as observers + // - Players who now lack a slot are made observers + // - Bots who now lack a slot are dropped + // - Bots who are not defined in the map rules are dropped + var botTypes = server.Map.Rules.Actors["player"].TraitInfos().Select(t => t.Type); + var slots = server.LobbyInfo.Slots.Keys.ToArray(); + var i = 0; + foreach (var os in oldSlots) + { + var c = server.LobbyInfo.ClientInSlot(os); + if (c == null) + continue; + + c.SpawnPoint = 0; + c.Slot = i < slots.Length ? slots[i++] : null; + if (c.Slot != null) + { + // Remove Bot from slot if slot forbids bots + if (c.Bot != null && (!server.Map.Players.Players[c.Slot].AllowBots || !botTypes.Contains(c.Bot))) + server.LobbyInfo.Clients.Remove(c); + S.SyncClientToPlayerReference(c, server.Map.Players.Players[c.Slot]); + } + else if (c.Bot != null) + server.LobbyInfo.Clients.Remove(c); + else + c.Color = Color.White; + } + + // Validate if color is allowed and get an alternative if it isn't + foreach (var c in server.LobbyInfo.Clients) + if (c.Slot != null && !server.LobbyInfo.Slots[c.Slot].LockColor) + c.Color = c.PreferredColor = SanitizePlayerColor(server, c.Color, c.Index, conn); + + server.SyncLobbyInfo(); + + server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); + + if (server.Map.DefinesUnsafeCustomRules) + server.SendMessage("This map contains custom rules. Game experience may change."); + + if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer) + server.SendMessage(server.TwoHumansRequiredText); + else if (server.Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) + server.SendMessage("Bots have been disabled on this map."); + + var briefing = MissionBriefingOrDefault(server); + if (briefing != null) + server.SendMessage(briefing); + } + }; + + Action queryFailed = () => server.SendOrderTo(conn, "Message", "Map was not found on server."); + + var m = server.ModData.MapCache[s]; + if (m.Status == MapStatus.Available || m.Status == MapStatus.DownloadAvailable) + selectMap(m); + else if (server.Settings.QueryMapRepository) + { + server.SendOrderTo(conn, "Message", "Searching for map on the Resource Center..."); + var mapRepository = server.ModData.Manifest.Get().MapRepository; + server.ModData.MapCache.QueryRemoteMapDetails(mapRepository, new[] { s }, selectMap, queryFailed); + } + else + queryFailed(); + return true; } - - var lastMap = server.LobbyInfo.GlobalSettings.Map; - Action selectMap = map => - { - // Make sure the map hasn't changed in the meantime - if (server.LobbyInfo.GlobalSettings.Map != lastMap) - return; - - server.LobbyInfo.GlobalSettings.Map = map.Uid; - - var oldSlots = server.LobbyInfo.Slots.Keys.ToArray(); - server.Map = server.ModData.MapCache[server.LobbyInfo.GlobalSettings.Map]; - - server.LobbyInfo.Slots = server.Map.Players.Players - .Select(p => MakeSlotFromPlayerReference(p.Value)) - .Where(ss => ss != null) - .ToDictionary(ss => ss.PlayerReference, ss => ss); - - LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); - - // Reset client states - var selectableFactions = server.Map.Rules.Actors["world"].TraitInfos() - .Where(f => f.Selectable) - .Select(f => f.InternalName) - .ToList(); - - foreach (var c in server.LobbyInfo.Clients) - { - c.State = Session.ClientState.Invalid; - if (!selectableFactions.Contains(c.Faction)) - c.Faction = "Random"; - } - - // Reassign players into new slots based on their old slots: - // - Observers remain as observers - // - Players who now lack a slot are made observers - // - Bots who now lack a slot are dropped - // - Bots who are not defined in the map rules are dropped - var botTypes = server.Map.Rules.Actors["player"].TraitInfos().Select(t => t.Type); - var slots = server.LobbyInfo.Slots.Keys.ToArray(); - var i = 0; - foreach (var os in oldSlots) - { - var c = server.LobbyInfo.ClientInSlot(os); - if (c == null) - continue; - - c.SpawnPoint = 0; - c.Slot = i < slots.Length ? slots[i++] : null; - if (c.Slot != null) - { - // Remove Bot from slot if slot forbids bots - if (c.Bot != null && (!server.Map.Players.Players[c.Slot].AllowBots || !botTypes.Contains(c.Bot))) - server.LobbyInfo.Clients.Remove(c); - S.SyncClientToPlayerReference(c, server.Map.Players.Players[c.Slot]); - } - else if (c.Bot != null) - server.LobbyInfo.Clients.Remove(c); - else - c.Color = Color.White; - } - - // Validate if color is allowed and get an alternative if it isn't - foreach (var c in server.LobbyInfo.Clients) - if (c.Slot != null && !server.LobbyInfo.Slots[c.Slot].LockColor) - c.Color = c.PreferredColor = SanitizePlayerColor(server, c.Color, c.Index, conn); - - server.SyncLobbyInfo(); - - server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); - - if (server.Map.DefinesUnsafeCustomRules) - server.SendMessage("This map contains custom rules. Game experience may change."); - - if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer) - server.SendMessage(server.TwoHumansRequiredText); - else if (server.Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) - server.SendMessage("Bots have been disabled on this map."); - - var briefing = MissionBriefingOrDefault(server); - if (briefing != null) - server.SendMessage(briefing); - }; - - Action queryFailed = () => - server.SendOrderTo(conn, "Message", "Map was not found on server."); - - var m = server.ModData.MapCache[s]; - if (m.Status == MapStatus.Available || m.Status == MapStatus.DownloadAvailable) - selectMap(m); - else if (server.Settings.QueryMapRepository) - { - server.SendOrderTo(conn, "Message", "Searching for map on the Resource Center..."); - var mapRepository = server.ModData.Manifest.Get().MapRepository; - server.ModData.MapCache.QueryRemoteMapDetails(mapRepository, new[] { s }, selectMap, queryFailed); - } - else - queryFailed(); - - return true; } static bool Option(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can change the configuration."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can change the configuration."); + return true; + } + + var allOptions = server.Map.Rules.Actors["player"].TraitInfos() + .Concat(server.Map.Rules.Actors["world"].TraitInfos()) + .SelectMany(t => t.LobbyOptions(server.Map.Rules)); + + // Overwrite keys with duplicate ids + var options = new Dictionary(); + foreach (var o in allOptions) + options[o.Id] = o; + + var split = s.Split(' '); + if (split.Length < 2 || !options.TryGetValue(split[0], out var option) || + !option.Values.ContainsKey(split[1])) + { + server.SendOrderTo(conn, "Message", "Invalid configuration command."); + return true; + } + + if (option.IsLocked) + { + server.SendOrderTo(conn, "Message", "{0} cannot be changed.".F(option.Name)); + return true; + } + + var oo = server.LobbyInfo.GlobalSettings.LobbyOptions[option.Id]; + if (oo.Value == split[1]) + return true; + + oo.Value = oo.PreferredValue = split[1]; + + if (option.Id == "gamespeed") + { + var speed = server.ModData.Manifest.Get().Speeds[oo.Value]; + server.LobbyInfo.GlobalSettings.Timestep = speed.Timestep; + server.LobbyInfo.GlobalSettings.OrderLatency = speed.OrderLatency; + } + + server.SyncLobbyGlobalSettings(); + server.SendMessage(option.ValueChangedMessage(client.Name, split[1])); + + foreach (var c in server.LobbyInfo.Clients) + c.State = Session.ClientState.NotReady; + + server.SyncLobbyClients(); + return true; } - - var allOptions = server.Map.Rules.Actors["player"].TraitInfos() - .Concat(server.Map.Rules.Actors["world"].TraitInfos()) - .SelectMany(t => t.LobbyOptions(server.Map.Rules)); - - // Overwrite keys with duplicate ids - var options = new Dictionary(); - foreach (var o in allOptions) - options[o.Id] = o; - - var split = s.Split(' '); - if (split.Length < 2 || !options.TryGetValue(split[0], out var option) || - !option.Values.ContainsKey(split[1])) - { - server.SendOrderTo(conn, "Message", "Invalid configuration command."); - return true; - } - - if (option.IsLocked) - { - server.SendOrderTo(conn, "Message", "{0} cannot be changed.".F(option.Name)); - return true; - } - - var oo = server.LobbyInfo.GlobalSettings.LobbyOptions[option.Id]; - if (oo.Value == split[1]) - return true; - - oo.Value = oo.PreferredValue = split[1]; - - if (option.Id == "gamespeed") - { - var speed = server.ModData.Manifest.Get().Speeds[oo.Value]; - server.LobbyInfo.GlobalSettings.Timestep = speed.Timestep; - server.LobbyInfo.GlobalSettings.OrderLatency = speed.OrderLatency; - } - - server.SyncLobbyGlobalSettings(); - server.SendMessage(option.ValueChangedMessage(client.Name, split[1])); - - foreach (var c in server.LobbyInfo.Clients) - c.State = Session.ClientState.NotReady; - - server.SyncLobbyClients(); - - return true; } static bool AssignTeams(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can set that option."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can set that option."); + return true; + } + + if (!Exts.TryParseIntegerInvariant(s, out var teamCount)) + { + server.SendOrderTo(conn, "Message", "Number of teams could not be parsed: {0}".F(s)); + return true; + } + + var maxTeams = (server.LobbyInfo.Clients.Count(c => c.Slot != null) + 1) / 2; + teamCount = teamCount.Clamp(0, maxTeams); + var clients = server.LobbyInfo.Slots + .Select(slot => server.LobbyInfo.ClientInSlot(slot.Key)) + .Where(c => c != null && !server.LobbyInfo.Slots[c.Slot].LockTeam); + + var assigned = 0; + var clientCount = clients.Count(); + foreach (var player in clients) + { + // Free for all + if (teamCount == 0) + player.Team = 0; + + // Humans vs Bots + else if (teamCount == 1) + player.Team = player.Bot == null ? 1 : 2; + else + player.Team = assigned++ * teamCount / clientCount + 1; + } + + server.SyncLobbyClients(); + return true; } - - if (!Exts.TryParseIntegerInvariant(s, out var teamCount)) - { - server.SendOrderTo(conn, "Message", "Number of teams could not be parsed: {0}".F(s)); - return true; - } - - var maxTeams = (server.LobbyInfo.Clients.Count(c => c.Slot != null) + 1) / 2; - teamCount = teamCount.Clamp(0, maxTeams); - var clients = server.LobbyInfo.Slots - .Select(slot => server.LobbyInfo.ClientInSlot(slot.Key)) - .Where(c => c != null && !server.LobbyInfo.Slots[c.Slot].LockTeam); - - var assigned = 0; - var clientCount = clients.Count(); - foreach (var player in clients) - { - // Free for all - if (teamCount == 0) - player.Team = 0; - - // Humans vs Bots - else if (teamCount == 1) - player.Team = player.Bot == null ? 1 : 2; - else - player.Team = assigned++ * teamCount / clientCount + 1; - } - - server.SyncLobbyClients(); - - return true; } static bool Kick(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can kick players."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can kick players."); + return true; + } + + var split = s.Split(' '); + if (split.Length < 2) + { + server.SendOrderTo(conn, "Message", "Malformed kick command"); + return true; + } + + Exts.TryParseIntegerInvariant(split[0], out var kickClientID); + + var kickConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickClientID); + if (kickConn == null) + { + server.SendOrderTo(conn, "Message", "No-one in that slot."); + return true; + } + + var kickClient = server.GetClient(kickConn); + if (server.State == ServerState.GameStarted && !kickClient.IsObserver) + { + server.SendOrderTo(conn, "Message", "Only spectators can be kicked after the game has started."); + return true; + } + + Log.Write("server", "Kicking client {0}.", kickClientID); + server.SendMessage("{0} kicked {1} from the server.".F(client.Name, kickClient.Name)); + server.SendOrderTo(kickConn, "ServerError", "You have been kicked from the server."); + server.DropClient(kickConn); + + bool.TryParse(split[1], out var tempBan); + if (tempBan) + { + Log.Write("server", "Temporarily banning client {0} ({1}).", kickClientID, kickClient.IPAddress); + server.SendMessage("{0} temporarily banned {1} from the server.".F(client.Name, kickClient.Name)); + server.TempBans.Add(kickClient.IPAddress); + } + + server.SyncLobbyClients(); + server.SyncLobbySlots(); + return true; } - - var split = s.Split(' '); - if (split.Length < 2) - { - server.SendOrderTo(conn, "Message", "Malformed kick command"); - return true; - } - - Exts.TryParseIntegerInvariant(split[0], out var kickClientID); - - var kickConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickClientID); - if (kickConn == null) - { - server.SendOrderTo(conn, "Message", "No-one in that slot."); - return true; - } - - var kickClient = server.GetClient(kickConn); - if (server.State == ServerState.GameStarted && !kickClient.IsObserver) - { - server.SendOrderTo(conn, "Message", "Only spectators can be kicked after the game has started."); - return true; - } - - Log.Write("server", "Kicking client {0}.", kickClientID); - server.SendMessage("{0} kicked {1} from the server.".F(client.Name, kickClient.Name)); - server.SendOrderTo(kickConn, "ServerError", "You have been kicked from the server."); - server.DropClient(kickConn); - - bool.TryParse(split[1], out var tempBan); - - if (tempBan) - { - Log.Write("server", "Temporarily banning client {0} ({1}).", kickClientID, kickClient.IPAddress); - server.SendMessage("{0} temporarily banned {1} from the server.".F(client.Name, kickClient.Name)); - server.TempBans.Add(kickClient.IPAddress); - } - - server.SyncLobbyClients(); - server.SyncLobbySlots(); - - return true; } static bool MakeAdmin(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only admins can transfer admin to another player."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only admins can transfer admin to another player."); + return true; + } + + Exts.TryParseIntegerInvariant(s, out var newAdminId); + var newAdminConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == newAdminId); + + if (newAdminConn == null) + { + server.SendOrderTo(conn, "Message", "No-one in that slot."); + return true; + } + + var newAdminClient = server.GetClient(newAdminConn); + client.IsAdmin = false; + newAdminClient.IsAdmin = true; + + var bots = server.LobbyInfo.Slots + .Select(slot => server.LobbyInfo.ClientInSlot(slot.Key)) + .Where(c => c != null && c.Bot != null); + foreach (var b in bots) + b.BotControllerClientIndex = newAdminId; + + server.SendMessage("{0} is now the admin.".F(newAdminClient.Name)); + Log.Write("server", "{0} is now the admin.".F(newAdminClient.Name)); + server.SyncLobbyClients(); + return true; } - - Exts.TryParseIntegerInvariant(s, out var newAdminId); - var newAdminConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == newAdminId); - - if (newAdminConn == null) - { - server.SendOrderTo(conn, "Message", "No-one in that slot."); - return true; - } - - var newAdminClient = server.GetClient(newAdminConn); - client.IsAdmin = false; - newAdminClient.IsAdmin = true; - - var bots = server.LobbyInfo.Slots - .Select(slot => server.LobbyInfo.ClientInSlot(slot.Key)) - .Where(c => c != null && c.Bot != null); - foreach (var b in bots) - b.BotControllerClientIndex = newAdminId; - - server.SendMessage("{0} is now the admin.".F(newAdminClient.Name)); - Log.Write("server", "{0} is now the admin.".F(newAdminClient.Name)); - server.SyncLobbyClients(); - - return true; } static bool MakeSpectator(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can move players to spectators."); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can move players to spectators."); + return true; + } + + Exts.TryParseIntegerInvariant(s, out var targetId); + var targetConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == targetId); + + if (targetConn == null) + { + server.SendOrderTo(conn, "Message", "No-one in that slot."); + return true; + } + + var targetClient = server.GetClient(targetConn); + targetClient.Slot = null; + targetClient.SpawnPoint = 0; + targetClient.Team = 0; + targetClient.Color = Color.White; + targetClient.State = Session.ClientState.NotReady; + server.SendMessage("{0} moved {1} to spectators.".F(client.Name, targetClient.Name)); + Log.Write("server", "{0} moved {1} to spectators.".F(client.Name, targetClient.Name)); + server.SyncLobbyClients(); + CheckAutoStart(server); + return true; } - - Exts.TryParseIntegerInvariant(s, out var targetId); - var targetConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == targetId); - - if (targetConn == null) - { - server.SendOrderTo(conn, "Message", "No-one in that slot."); - return true; - } - - var targetClient = server.GetClient(targetConn); - targetClient.Slot = null; - targetClient.SpawnPoint = 0; - targetClient.Team = 0; - targetClient.Color = Color.White; - targetClient.State = Session.ClientState.NotReady; - server.SendMessage("{0} moved {1} to spectators.".F(client.Name, targetClient.Name)); - Log.Write("server", "{0} moved {1} to spectators.".F(client.Name, targetClient.Name)); - server.SyncLobbyClients(); - CheckAutoStart(server); - - return true; } static bool Name(S server, Connection conn, Session.Client client, string s) { - var sanitizedName = Settings.SanitizedPlayerName(s); - if (sanitizedName == client.Name) + lock (server.LobbyInfo) + { + var sanitizedName = Settings.SanitizedPlayerName(s); + if (sanitizedName == client.Name) + return true; + + Log.Write("server", "Player@{0} is now known as {1}.", conn.Socket.RemoteEndPoint, sanitizedName); + server.SendMessage("{0} is now known as {1}.".F(client.Name, sanitizedName)); + client.Name = sanitizedName; + server.SyncLobbyClients(); + return true; - - Log.Write("server", "Player@{0} is now known as {1}.", conn.Socket.RemoteEndPoint, sanitizedName); - server.SendMessage("{0} is now known as {1}.".F(client.Name, sanitizedName)); - client.Name = sanitizedName; - server.SyncLobbyClients(); - - return true; + } } static bool Faction(S server, Connection conn, Session.Client client, string s) { - var parts = s.Split(' '); - var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); - - // Only the host can change other client's info - if (targetClient.Index != client.Index && !client.IsAdmin) - return true; - - // Map has disabled faction changes - if (server.LobbyInfo.Slots[targetClient.Slot].LockFaction) - return true; - - var factions = server.Map.Rules.Actors["world"].TraitInfos() - .Where(f => f.Selectable).Select(f => f.InternalName); - - if (!factions.Contains(parts[1])) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Invalid faction selected: {0}".F(parts[1])); - server.SendOrderTo(conn, "Message", "Supported values: {0}".F(factions.JoinWith(", "))); + var parts = s.Split(' '); + var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); + + // Only the host can change other client's info + if (targetClient.Index != client.Index && !client.IsAdmin) + return true; + + // Map has disabled faction changes + if (server.LobbyInfo.Slots[targetClient.Slot].LockFaction) + return true; + + var factions = server.Map.Rules.Actors["world"].TraitInfos() + .Where(f => f.Selectable).Select(f => f.InternalName); + + if (!factions.Contains(parts[1])) + { + server.SendOrderTo(conn, "Message", "Invalid faction selected: {0}".F(parts[1])); + server.SendOrderTo(conn, "Message", "Supported values: {0}".F(factions.JoinWith(", "))); + return true; + } + + targetClient.Faction = parts[1]; + server.SyncLobbyClients(); + return true; } - - targetClient.Faction = parts[1]; - server.SyncLobbyClients(); - - return true; } static bool Team(S server, Connection conn, Session.Client client, string s) { - var parts = s.Split(' '); - var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); - - // Only the host can change other client's info - if (targetClient.Index != client.Index && !client.IsAdmin) - return true; - - // Map has disabled team changes - if (server.LobbyInfo.Slots[targetClient.Slot].LockTeam) - return true; - - if (!Exts.TryParseIntegerInvariant(parts[1], out var team)) + lock (server.LobbyInfo) { - Log.Write("server", "Invalid team: {0}", s); - return false; + var parts = s.Split(' '); + var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); + + // Only the host can change other client's info + if (targetClient.Index != client.Index && !client.IsAdmin) + return true; + + // Map has disabled team changes + if (server.LobbyInfo.Slots[targetClient.Slot].LockTeam) + return true; + + if (!Exts.TryParseIntegerInvariant(parts[1], out var team)) + { + Log.Write("server", "Invalid team: {0}", s); + return false; + } + + targetClient.Team = team; + server.SyncLobbyClients(); + + return true; } - - targetClient.Team = team; - server.SyncLobbyClients(); - - return true; } static bool Spawn(S server, Connection conn, Session.Client client, string s) { - var parts = s.Split(' '); - var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); - - // Only the host can change other client's info - if (targetClient.Index != client.Index && !client.IsAdmin) - return true; - - // Spectators don't need a spawnpoint - if (targetClient.Slot == null) - return true; - - // Map has disabled spawn changes - if (server.LobbyInfo.Slots[targetClient.Slot].LockSpawn) - return true; - - if (!Exts.TryParseIntegerInvariant(parts[1], out var spawnPoint) - || spawnPoint < 0 || spawnPoint > server.Map.SpawnPoints.Length) + lock (server.LobbyInfo) { - Log.Write("server", "Invalid spawn point: {0}", parts[1]); - return true; - } + var parts = s.Split(' '); + var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); - if (server.LobbyInfo.Clients.Where(cc => cc != client).Any(cc => (cc.SpawnPoint == spawnPoint) && (cc.SpawnPoint != 0))) - { - server.SendOrderTo(conn, "Message", "You cannot occupy the same spawn point as another player."); - return true; - } + // Only the host can change other client's info + if (targetClient.Index != client.Index && !client.IsAdmin) + return true; - // Check if any other slot has locked the requested spawn - if (spawnPoint > 0) - { - var spawnLockedByAnotherSlot = server.LobbyInfo.Slots.Where(ss => ss.Value.LockSpawn).Any(ss => + // Spectators don't need a spawnpoint + if (targetClient.Slot == null) + return true; + + // Map has disabled spawn changes + if (server.LobbyInfo.Slots[targetClient.Slot].LockSpawn) + return true; + + if (!Exts.TryParseIntegerInvariant(parts[1], out var spawnPoint) + || spawnPoint < 0 || spawnPoint > server.Map.SpawnPoints.Length) { - var pr = PlayerReferenceForSlot(server, ss.Value); - return pr != null && pr.Spawn == spawnPoint; - }); - - if (spawnLockedByAnotherSlot) - { - server.SendOrderTo(conn, "Message", "The spawn point is locked to another player slot."); + Log.Write("server", "Invalid spawn point: {0}", parts[1]); return true; } + + if (server.LobbyInfo.Clients.Where(cc => cc != client).Any(cc => (cc.SpawnPoint == spawnPoint) && (cc.SpawnPoint != 0))) + { + server.SendOrderTo(conn, "Message", "You cannot occupy the same spawn point as another player."); + return true; + } + + // Check if any other slot has locked the requested spawn + if (spawnPoint > 0) + { + var spawnLockedByAnotherSlot = server.LobbyInfo.Slots.Where(ss => ss.Value.LockSpawn).Any(ss => + { + var pr = PlayerReferenceForSlot(server, ss.Value); + return pr != null && pr.Spawn == spawnPoint; + }); + + if (spawnLockedByAnotherSlot) + { + server.SendOrderTo(conn, "Message", "The spawn point is locked to another player slot."); + return true; + } + } + + targetClient.SpawnPoint = spawnPoint; + server.SyncLobbyClients(); + + return true; } - - targetClient.SpawnPoint = spawnPoint; - server.SyncLobbyClients(); - - return true; } static bool PlayerColor(S server, Connection conn, Session.Client client, string s) { - var parts = s.Split(' '); - var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); + lock (server.LobbyInfo) + { + var parts = s.Split(' '); + var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); + + // Only the host can change other client's info + if (targetClient.Index != client.Index && !client.IsAdmin) + return true; + + // Spectator or map has disabled color changes + if (targetClient.Slot == null || server.LobbyInfo.Slots[targetClient.Slot].LockColor) + return true; + + // Validate if color is allowed and get an alternative it isn't + var newColor = FieldLoader.GetValue("(value)", parts[1]); + targetClient.Color = SanitizePlayerColor(server, newColor, targetClient.Index, conn); + + // Only update player's preferred color if new color is valid + if (newColor == targetClient.Color) + targetClient.PreferredColor = targetClient.Color; + + server.SyncLobbyClients(); - // Only the host can change other client's info - if (targetClient.Index != client.Index && !client.IsAdmin) return true; - - // Spectator or map has disabled color changes - if (targetClient.Slot == null || server.LobbyInfo.Slots[targetClient.Slot].LockColor) - return true; - - // Validate if color is allowed and get an alternative it isn't - var newColor = FieldLoader.GetValue("(value)", parts[1]); - targetClient.Color = SanitizePlayerColor(server, newColor, targetClient.Index, conn); - - // Only update player's preferred color if new color is valid - if (newColor == targetClient.Color) - targetClient.PreferredColor = targetClient.Color; - - server.SyncLobbyClients(); - - return true; + } } static bool SyncLobby(S server, Connection conn, Session.Client client, string s) { - if (!client.IsAdmin) + lock (server.LobbyInfo) { - server.SendOrderTo(conn, "Message", "Only the host can set lobby info"); + if (!client.IsAdmin) + { + server.SendOrderTo(conn, "Message", "Only the host can set lobby info"); + return true; + } + + try + { + server.LobbyInfo = Session.Deserialize(s); + server.SyncLobbyInfo(); + } + catch (Exception) + { + server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent"); + } + return true; } - - try - { - server.LobbyInfo = Session.Deserialize(s); - server.SyncLobbyInfo(); - } - catch (Exception) - { - server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent"); - } - - return true; } public void ServerStarted(S server) { - // Remote maps are not supported for the initial map - var uid = server.LobbyInfo.GlobalSettings.Map; - server.Map = server.ModData.MapCache[uid]; - if (server.Map.Status != MapStatus.Available) - throw new InvalidOperationException("Map {0} not found".F(uid)); + lock (server.LobbyInfo) + { + // Remote maps are not supported for the initial map + var uid = server.LobbyInfo.GlobalSettings.Map; + server.Map = server.ModData.MapCache[uid]; + if (server.Map.Status != MapStatus.Available) + throw new InvalidOperationException("Map {0} not found".F(uid)); - server.LobbyInfo.Slots = server.Map.Players.Players - .Select(p => MakeSlotFromPlayerReference(p.Value)) - .Where(s => s != null) - .ToDictionary(s => s.PlayerReference, s => s); + server.LobbyInfo.Slots = server.Map.Players.Players + .Select(p => MakeSlotFromPlayerReference(p.Value)) + .Where(s => s != null) + .ToDictionary(s => s.PlayerReference, s => s); - LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); + LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); + } } static Session.Slot MakeSlotFromPlayerReference(PlayerReference pr) { - if (!pr.Playable) return null; + if (!pr.Playable) + return null; + return new Session.Slot { PlayerReference = pr.Name, @@ -888,61 +958,67 @@ namespace OpenRA.Mods.Common.Server public static void LoadMapSettings(S server, Session.Global gs, Ruleset rules) { - var options = rules.Actors["player"].TraitInfos() - .Concat(rules.Actors["world"].TraitInfos()) - .SelectMany(t => t.LobbyOptions(rules)); - - foreach (var o in options) + lock (server.LobbyInfo) { - var value = o.DefaultValue; - var preferredValue = o.DefaultValue; - if (gs.LobbyOptions.TryGetValue(o.Id, out var state)) + var options = rules.Actors["player"].TraitInfos() + .Concat(rules.Actors["world"].TraitInfos()) + .SelectMany(t => t.LobbyOptions(rules)); + + foreach (var o in options) { - // Propagate old state on map change - if (!o.IsLocked) + var value = o.DefaultValue; + var preferredValue = o.DefaultValue; + if (gs.LobbyOptions.TryGetValue(o.Id, out var state)) { - if (o.Values.Keys.Contains(state.PreferredValue)) - value = state.PreferredValue; - else if (o.Values.Keys.Contains(state.Value)) - value = state.Value; + // Propagate old state on map change + if (!o.IsLocked) + { + if (o.Values.Keys.Contains(state.PreferredValue)) + value = state.PreferredValue; + else if (o.Values.Keys.Contains(state.Value)) + value = state.Value; + } + + preferredValue = state.PreferredValue; } + else + state = new Session.LobbyOptionState(); - preferredValue = state.PreferredValue; - } - else - state = new Session.LobbyOptionState(); + state.IsLocked = o.IsLocked; + state.Value = value; + state.PreferredValue = preferredValue; + gs.LobbyOptions[o.Id] = state; - state.IsLocked = o.IsLocked; - state.Value = value; - state.PreferredValue = preferredValue; - gs.LobbyOptions[o.Id] = state; - - if (o.Id == "gamespeed") - { - var speed = server.ModData.Manifest.Get().Speeds[value]; - gs.Timestep = speed.Timestep; - gs.OrderLatency = speed.OrderLatency; + if (o.Id == "gamespeed") + { + var speed = server.ModData.Manifest.Get().Speeds[value]; + gs.Timestep = speed.Timestep; + gs.OrderLatency = speed.OrderLatency; + } } } } static Color SanitizePlayerColor(S server, Color askedColor, int playerIndex, Connection connectionToEcho = null) { - var validator = server.ModData.Manifest.Get(); - var askColor = askedColor; - - Action onError = message => + lock (server.LobbyInfo) { - if (connectionToEcho != null) - server.SendOrderTo(connectionToEcho, "Message", message); - }; + var validator = server.ModData.Manifest.Get(); + var askColor = askedColor; - var tileset = server.Map.Rules.TileSet; - var terrainColors = tileset.TerrainInfo.Where(ti => ti.RestrictPlayerColor).Select(ti => ti.Color).ToList(); - var playerColors = server.LobbyInfo.Clients.Where(c => c.Index != playerIndex).Select(c => c.Color) - .Concat(server.Map.Players.Players.Values.Select(p => p.Color)).ToList(); + Action onError = message => + { + if (connectionToEcho != null) + server.SendOrderTo(connectionToEcho, "Message", message); + }; - return validator.MakeValid(askColor, server.Random, terrainColors, playerColors, onError); + var tileset = server.Map.Rules.TileSet; + var terrainColors = tileset.TerrainInfo.Where(ti => ti.RestrictPlayerColor).Select(ti => ti.Color).ToList(); + var playerColors = server.LobbyInfo.Clients.Where(c => c.Index != playerIndex).Select(c => c.Color) + .Concat(server.Map.Players.Players.Values.Select(p => p.Color)).ToList(); + + return validator.MakeValid(askColor, server.Random, terrainColors, playerColors, onError); + } } static string MissionBriefingOrDefault(S server) @@ -956,33 +1032,39 @@ namespace OpenRA.Mods.Common.Server public void ClientJoined(S server, Connection conn) { - var client = server.GetClient(conn); + lock (server.LobbyInfo) + { + var client = server.GetClient(conn); - // Validate whether color is allowed and get an alternative if it isn't - if (client.Slot != null && !server.LobbyInfo.Slots[client.Slot].LockColor) - client.Color = SanitizePlayerColor(server, client.Color, client.Index); + // Validate whether color is allowed and get an alternative if it isn't + if (client.Slot != null && !server.LobbyInfo.Slots[client.Slot].LockColor) + client.Color = SanitizePlayerColor(server, client.Color, client.Index); - // Report any custom map details - // HACK: this isn't the best place for this to live, but if we move it somewhere else - // then we need a larger hack to hook the map change event. - var briefing = MissionBriefingOrDefault(server); - if (briefing != null) - server.SendOrderTo(conn, "Message", briefing); + // Report any custom map details + // HACK: this isn't the best place for this to live, but if we move it somewhere else + // then we need a larger hack to hook the map change event. + var briefing = MissionBriefingOrDefault(server); + if (briefing != null) + server.SendOrderTo(conn, "Message", briefing); + } } void INotifyServerEmpty.ServerEmpty(S server) { - // Expire any temporary bans - server.TempBans.Clear(); + lock (server.LobbyInfo) + { + // Expire any temporary bans + server.TempBans.Clear(); - // Re-enable spectators - server.LobbyInfo.GlobalSettings.AllowSpectators = true; + // Re-enable spectators + server.LobbyInfo.GlobalSettings.AllowSpectators = true; - // Reset player slots - server.LobbyInfo.Slots = server.Map.Players.Players - .Select(p => MakeSlotFromPlayerReference(p.Value)) - .Where(ss => ss != null) - .ToDictionary(ss => ss.PlayerReference, ss => ss); + // Reset player slots + server.LobbyInfo.Slots = server.Map.Players.Players + .Select(p => MakeSlotFromPlayerReference(p.Value)) + .Where(ss => ss != null) + .ToDictionary(ss => ss.PlayerReference, ss => ss); + } } public static PlayerReference PlayerReferenceForSlot(S server, Session.Slot slot) diff --git a/OpenRA.Mods.Common/ServerTraits/LobbySettingsNotification.cs b/OpenRA.Mods.Common/ServerTraits/LobbySettingsNotification.cs index 24503edc61..89ab371095 100644 --- a/OpenRA.Mods.Common/ServerTraits/LobbySettingsNotification.cs +++ b/OpenRA.Mods.Common/ServerTraits/LobbySettingsNotification.cs @@ -21,25 +21,28 @@ namespace OpenRA.Mods.Common.Server { public void ClientJoined(OpenRA.Server.Server server, Connection conn) { - if (server.LobbyInfo.ClientWithIndex(conn.PlayerIndex).IsAdmin) - return; - - var defaults = new Session.Global(); - LobbyCommands.LoadMapSettings(server, defaults, server.Map.Rules); - - var options = server.Map.Rules.Actors["player"].TraitInfos() - .Concat(server.Map.Rules.Actors["world"].TraitInfos()) - .SelectMany(t => t.LobbyOptions(server.Map.Rules)); - - var optionNames = new Dictionary(); - foreach (var o in options) - optionNames[o.Id] = o.Name; - - foreach (var kv in server.LobbyInfo.GlobalSettings.LobbyOptions) + lock (server.LobbyInfo) { - if (!defaults.LobbyOptions.TryGetValue(kv.Key, out var def) || kv.Value.Value != def.Value) - if (optionNames.TryGetValue(kv.Key, out var optionName)) - server.SendOrderTo(conn, "Message", optionName + ": " + kv.Value.Value); + if (server.LobbyInfo.ClientWithIndex(conn.PlayerIndex).IsAdmin) + return; + + var defaults = new Session.Global(); + LobbyCommands.LoadMapSettings(server, defaults, server.Map.Rules); + + var options = server.Map.Rules.Actors["player"].TraitInfos() + .Concat(server.Map.Rules.Actors["world"].TraitInfos()) + .SelectMany(t => t.LobbyOptions(server.Map.Rules)); + + var optionNames = new Dictionary(); + foreach (var o in options) + optionNames[o.Id] = o.Name; + + foreach (var kv in server.LobbyInfo.GlobalSettings.LobbyOptions) + { + if (!defaults.LobbyOptions.TryGetValue(kv.Key, out var def) || kv.Value.Value != def.Value) + if (optionNames.TryGetValue(kv.Key, out var optionName)) + server.SendOrderTo(conn, "Message", optionName + ": " + kv.Value.Value); + } } } } diff --git a/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs b/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs index 1193df9c31..4a49280d93 100644 --- a/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs +++ b/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs @@ -36,7 +36,11 @@ namespace OpenRA.Mods.Common.Server lastPing = Game.RunTime; // Ignore client timeout in singleplayer games to make debugging easier - if (server.LobbyInfo.NonBotClients.Count() < 2 && server.Type != ServerType.Dedicated) + var nonBotClientCount = 0; + lock (server.LobbyInfo) + nonBotClientCount = server.LobbyInfo.NonBotClients.Count(); + + if (nonBotClientCount < 2 && server.Type != ServerType.Dedicated) foreach (var c in server.Conns.ToList()) server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); else