public SendOrderTo ( Connection conn, string order, string data ) : void | ||
conn | Connection | |
order | string | |
data | string | |
Résultat | void |
static bool MakeSpectator(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { 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); } }
static bool StartGame(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { 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); } }
static bool Spawn(S server, Connection conn, Session.Client client, string s) { 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); } // 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) { 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); } }
static bool Faction(S server, Connection conn, Session.Client client, string s) { 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); } // Map has disabled faction changes if (server.LobbyInfo.Slots[targetClient.Slot].LockFaction) { return(true); } var factions = server.Map.Rules.Actors["world"].TraitInfos <FactionInfo>() .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); } }
static bool MakeAdmin(S server, Connection conn, Session.Client client, string s) { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only admins can transfer admin to another player."); return(true); } int newAdminId; Exts.TryParseIntegerInvariant(s, out 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; 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 Kick(S server, Connection conn, Session.Client client, string s) { 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); } int kickClientID; Exts.TryParseIntegerInvariant(split[0], out 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 tempBan; bool.TryParse(split[1], out 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 Option(S server, Connection conn, Session.Client client, string s) { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the configuration."); return(true); } var allOptions = server.Map.Rules.Actors["player"].TraitInfos <ILobbyOptions>() .Concat(server.Map.Rules.Actors["world"].TraitInfos <ILobbyOptions>()) .SelectMany(t => t.LobbyOptions(server.Map.Rules)); // Overwrite keys with duplicate ids var options = new Dictionary <string, LobbyOption>(); foreach (var o in allOptions) { options[o.Id] = o; } var split = s.Split(' '); LobbyOption option; if (split.Length < 2 || !options.TryGetValue(split[0], out 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 <GameSpeeds>().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])); return(true); }
static bool Option(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the configuration."); return(true); } var allOptions = server.Map.PlayerActorInfo.TraitInfos <ILobbyOptions>() .Concat(server.Map.WorldActorInfo.TraitInfos <ILobbyOptions>()) .SelectMany(t => t.LobbyOptions(server.Map)); // Overwrite keys with duplicate ids var options = new Dictionary <string, LobbyOption>(); 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", $"{option.Name} cannot be changed."); return(true); } var oo = server.LobbyInfo.GlobalSettings.LobbyOptions[option.Id]; if (oo.Value == split[1]) { return(true); } oo.Value = oo.PreferredValue = split[1]; 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); } }
public void ClientJoined(OpenRA.Server.Server server, Connection conn) { if (server.LobbyInfo.ClientWithIndex(conn.PlayerIndex).IsAdmin) { return; } var defaults = new Session.Global(); FieldLoader.Load(defaults, Game.modData.Manifest.LobbyDefaults); if (server.LobbyInfo.GlobalSettings.FragileAlliances != defaults.FragileAlliances) { server.SendOrderTo(conn, "Message", "Diplomacy Changes: {0}".F(server.LobbyInfo.GlobalSettings.FragileAlliances)); } if (server.LobbyInfo.GlobalSettings.AllowCheats != defaults.AllowCheats) { server.SendOrderTo(conn, "Message", "Allow Cheats: {0}".F(server.LobbyInfo.GlobalSettings.AllowCheats)); } if (server.LobbyInfo.GlobalSettings.Shroud != defaults.Shroud) { server.SendOrderTo(conn, "Message", "Shroud: {0}".F(server.LobbyInfo.GlobalSettings.Shroud)); } if (server.LobbyInfo.GlobalSettings.Fog != defaults.Fog) { server.SendOrderTo(conn, "Message", "Fog of war: {0}".F(server.LobbyInfo.GlobalSettings.Fog)); } if (server.LobbyInfo.GlobalSettings.Crates != defaults.Crates) { server.SendOrderTo(conn, "Message", "Crates Appear: {0}".F(server.LobbyInfo.GlobalSettings.Crates)); } if (server.LobbyInfo.GlobalSettings.AllyBuildRadius != defaults.AllyBuildRadius) { server.SendOrderTo(conn, "Message", "Build off Ally ConYards: {0}".F(server.LobbyInfo.GlobalSettings.AllyBuildRadius)); } if (server.LobbyInfo.GlobalSettings.StartingUnitsClass != defaults.StartingUnitsClass) { var startUnitsInfo = server.Map.Rules.Actors["world"].Traits.WithInterface <MPStartUnitsInfo>(); var selectedClass = startUnitsInfo.Where(u => u.Class == server.LobbyInfo.GlobalSettings.StartingUnitsClass).Select(u => u.ClassName).FirstOrDefault(); var className = selectedClass != null ? selectedClass : server.LobbyInfo.GlobalSettings.StartingUnitsClass; server.SendOrderTo(conn, "Message", "Starting Units: {0}".F(className)); } if (server.LobbyInfo.GlobalSettings.StartingCash != defaults.StartingCash) { server.SendOrderTo(conn, "Message", "Starting Cash: ${0}".F(server.LobbyInfo.GlobalSettings.StartingCash)); } if (server.LobbyInfo.GlobalSettings.TechLevel != defaults.TechLevel) { server.SendOrderTo(conn, "Message", "Tech Level: {0}".F(server.LobbyInfo.GlobalSettings.TechLevel)); } }
public static bool ValidatePlayerNewColor(S server, Color askedColor, int playerIndex, out Color forbiddenColor, Connection connectionToEcho = null) { // Validate color against the current map tileset var tileset = server.Map.Rules.TileSets[server.Map.Tileset]; var forbiddenColors = tileset.TerrainInfo.Select(terrainInfo => terrainInfo.Color); if (!ValidateColorAgainstForbidden(askedColor, forbiddenColors, out forbiddenColor)) { if (connectionToEcho != null) { server.SendOrderTo(connectionToEcho, "Message", "Color was too similar to the terrain, and has been adjusted."); } return(false); } // Validate color against other clients var playerColors = server.LobbyInfo.Clients .Where(c => c.Index != playerIndex) .ToDictionary(c => c.Color.RGB, c => c.Name); if (!ValidateColorAgainstForbidden(askedColor, playerColors.Keys, out forbiddenColor)) { if (connectionToEcho != null) { var client = playerColors[forbiddenColor]; server.SendOrderTo(connectionToEcho, "Message", "Color was too similar to {0}, and has been adjusted.".F(client)); } return(false); } var mapPlayerColors = server.Map.Players.Values .Select(p => p.ColorRamp.RGB); if (!ValidateColorAgainstForbidden(askedColor, mapPlayerColors, out forbiddenColor)) { if (connectionToEcho != null) { server.SendOrderTo(connectionToEcho, "Message", "Color was too similar to a non-combatant player, and has been adjusted."); } return(false); } // Color is valid forbiddenColor = default(Color); return(true); }
static bool AssignTeams(S server, Connection conn, Session.Client client, string s) { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return(true); } int teamCount; if (!Exts.TryParseIntegerInvariant(s, out 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); }
public static bool ValidateCommand(S server, Connection conn, Session.Client client, string cmd) { 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 static bool ValidateCommand(S server, Connection conn, Session.Client client, string cmd) { 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 void ClientJoined(OpenRA.Server.Server server, Connection conn) { lock (server.LobbyInfo) { 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 <ILobbyOptions>() .Concat(server.Map.Rules.Actors["world"].TraitInfos <ILobbyOptions>()) .SelectMany(t => t.LobbyOptions(server.Map.Rules)) .ToDictionary(o => o.Id, o => o); foreach (var kv in server.LobbyInfo.GlobalSettings.LobbyOptions) { if (!defaults.LobbyOptions.TryGetValue(kv.Key, out var def) || kv.Value.Value != def.Value) { if (options.TryGetValue(kv.Key, out var option)) { server.SendOrderTo(conn, "Message", option.Name + ": " + option.Values[kv.Value.Value]); } } } } }
static bool SlotClose(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { 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(); } 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); } }
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 <ILobbyOptions>() .Concat(server.Map.Rules.Actors["world"].TraitInfos <ILobbyOptions>()) .SelectMany(t => t.LobbyOptions(server.Map.Rules)); var optionNames = new Dictionary <string, string>(); foreach (var o in options) { optionNames[o.Id] = o.Name; } foreach (var kv in server.LobbyInfo.GlobalSettings.LobbyOptions) { Session.LobbyOptionState def; string optionName; if (!defaults.LobbyOptions.TryGetValue(kv.Key, out def) || kv.Value.Value != def.Value) { if (optionNames.TryGetValue(kv.Key, out optionName)) { server.SendOrderTo(conn, "Message", optionName + ": " + kv.Value.Value); } } } }
public void Tick(S server) { if ((Environment.TickCount - lastPing > PingInterval) || isInitialPing) { isInitialPing = false; lastPing = Environment.TickCount; foreach (var p in server.Conns) server.SendOrderTo(p, "Ping", Environment.TickCount.ToString()); } }
static bool SyncLobby(S server, Connection conn, Session.Client client, string s) { 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); }
public void Tick(S server) { if ((Environment.TickCount - lastPing > PingInterval) || isInitialPing) { isInitialPing = false; lastPing = Environment.TickCount; foreach (var p in server.Conns) { server.SendOrderTo(p, "Ping", Environment.TickCount.ToString()); } } }
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 { server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); return(true); } }
static bool MakeAdmin(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { 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); } }
static bool ClearPlayerSpawn(S server, Connection conn, Session.Client client, string s) { var spawnPoint = Exts.ParseIntegerInvariant(s); if (spawnPoint == 0) { return(true); } var existingClient = server.LobbyInfo.Clients.FirstOrDefault(cc => cc.SpawnPoint == spawnPoint); if (client != existingClient && !client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only admins can clear spawn points."); return(true); } // Clearing a selected spawn point removes the player if (existingClient != null) { // Prevent a map-defined lock spawn from being affected if (existingClient.Slot != null && server.LobbyInfo.Slots[existingClient.Slot].LockSpawn) { return(true); } existingClient.SpawnPoint = 0; if (existingClient.State == Session.ClientState.Ready) { existingClient.State = Session.ClientState.NotReady; } server.SyncLobbyClients(); return(true); } // Clearing an empty spawn point prevents it from being selected // Clearing a disabled spawn restores it for use if (!server.LobbyInfo.DisabledSpawnPoints.Contains(spawnPoint)) { server.LobbyInfo.DisabledSpawnPoints.Add(spawnPoint); } else { server.LobbyInfo.DisabledSpawnPoints.Remove(spawnPoint); } server.SyncLobbyInfo(); return(true); }
public static bool ValidateCommand(S server, Connection conn, Session.Client client, string cmd) { 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. ({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); } }
static bool ValidateSlotCommand(S server, Connection conn, Session.Client client, string arg, bool requiresHost) { 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; } return true; }
static bool ValidateSlotCommand(S server, Connection conn, Session.Client client, string arg, bool requiresHost) { 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); } return(true); }
static bool State(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { if (!Enum <Session.ClientState> .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); } }
static HSLColor SanitizePlayerColor(S server, HSLColor askedColor, int playerIndex, Connection connectionToEcho = null) { var validator = server.ModData.Manifest.Get <ColorValidator>(); var askColor = askedColor; Action <string> onError = message => { if (connectionToEcho != null) { server.SendOrderTo(connectionToEcho, "Message", message); } }; 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.RGB) .Concat(server.Map.Players.Players.Values.Select(p => p.Color.RGB)).ToList(); return(validator.MakeValid(askColor.RGB, server.Random, terrainColors, playerColors, onError)); }
public void ClientJoined(S server, Connection conn) { 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); } // 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); } }
public void Tick(S server) { if ((Game.RunTime - lastPing > PingInterval) || isInitialPing) { isInitialPing = false; lastPing = Game.RunTime; foreach (var c in server.Conns.ToList()) { if (c.TimeSinceLastResponse < ConnTimeout) { server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); if (!c.TimeoutMessageShown && c.TimeSinceLastResponse > PingInterval * 2) { server.SendMessage(server.GetClient(c).Name + " is experiencing connection problems."); c.TimeoutMessageShown = true; } } else { server.SendMessage(server.GetClient(c).Name + " has been dropped after timing out."); server.DropClient(c, -1); } } } if (Game.RunTime - lastConnReport > ConnReportInterval) { lastConnReport = Game.RunTime; var timeouts = server.Conns .Where(c => c.TimeSinceLastResponse > ConnReportInterval && c.TimeSinceLastResponse < ConnTimeout) .OrderBy(c => c.TimeSinceLastResponse); foreach (var c in timeouts) { server.SendMessage("{0} will be dropped in {1} seconds.".F( server.GetClient(c).Name, (ConnTimeout - c.TimeSinceLastResponse) / 1000)); } } }
static Color SanitizePlayerColor(S server, Color askedColor, int playerIndex, Connection connectionToEcho = null) { lock (server.LobbyInfo) { var colorManager = server.ModData.DefaultRules.Actors[SystemActors.World].TraitInfo <ColorPickerManagerInfo>(); var askColor = askedColor; Action <string> onError = message => { if (connectionToEcho != null) { server.SendOrderTo(connectionToEcho, "Message", message); } }; var terrainColors = server.ModData.DefaultTerrainInfo[server.Map.TileSet].RestrictedPlayerColors; 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(colorManager.MakeValid(askColor, server.Random, terrainColors, playerColors, onError)); } }
public void Tick(S server) { if ((Game.RunTime - lastPing > PingInterval) || isInitialPing) { isInitialPing = false; lastPing = Game.RunTime; foreach (var c in server.Conns.ToList()) { if (c.TimeSinceLastResponse < ConnTimeout) { server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); if (!c.TimeoutMessageShown && c.TimeSinceLastResponse > PingInterval * 2) { server.SendMessage(server.GetClient(c).Name + " is experiencing connection problems."); c.TimeoutMessageShown = true; } } else { server.SendMessage(server.GetClient(c).Name + " has been dropped after timing out."); server.DropClient(c, -1); } } } if (Game.RunTime - lastConnReport > ConnReportInterval) { lastConnReport = Game.RunTime; var timeouts = server.Conns .Where(c => c.TimeSinceLastResponse > ConnReportInterval && c.TimeSinceLastResponse < ConnTimeout) .OrderBy(c => c.TimeSinceLastResponse); foreach (var c in timeouts) server.SendMessage("{0} will be dropped in {1} seconds.".F( server.GetClient(c).Name, (ConnTimeout - c.TimeSinceLastResponse) / 1000)); } }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (server == null || conn == null || client == null || !ValidateCommand(server, conn, client, cmd)) return false; var dict = new Dictionary<string, Func<string, bool>> { { "state", s => { var state = Session.ClientState.Invalid; if (!Enum<Session.ClientState>.TryParse(s, false, out 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; } }, { "startgame", s => { 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; } server.StartGame(); return true; } }, { "slot", s => { 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; client.Slot = s; S.SyncClientToPlayerReference(client, server.MapPlayers.Players[s]); var validatedColor = ColorValidator.ValidatePlayerColorAndGetAlternative(server, client.Color, client.Index, conn); client.PreferredColor = client.Color = validatedColor; server.SyncLobbyClients(); CheckAutoStart(server); return true; } }, { "allow_spectators", s => { if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) { server.SyncLobbyGlobalSettings(); return true; } else { server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); return true; } } }, { "spectate", s => { if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) { client.Slot = null; client.SpawnPoint = 0; client.Color = HSLColor.FromRGB(255, 255, 255); server.SyncLobbyClients(); return true; } else return false; } }, { "slot_close", 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) { 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; } }, { "slot_open", 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; } }, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 3) { 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]); int controllerClientIndex; if (!Exts.TryParseIntegerInvariant(parts[1], out controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return false; } var botType = parts.Skip(2).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); return true; } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, Bot = botType, Slot = parts[0], Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex }; // Pick a random color for the bot HSLColor botColor; do { var hue = (byte)server.Random.Next(255); var sat = (byte)server.Random.Next(255); var lum = (byte)server.Random.Next(51, 255); botColor = new HSLColor(hue, sat, lum); } while (!ColorValidator.ValidatePlayerNewColor(server, botColor.RGB, bot.Index)); bot.Color = bot.PreferredColor = botColor; server.LobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.MapPlayers.Players[parts[0]]); server.SyncLobbyClients(); server.SyncLobbySlots(); return true; } }, { "map", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the map."); return true; } if (server.ModData.MapCache[s].Status != MapStatus.Available) { server.SendOrderTo(conn, "Message", "Map was not found on server."); return true; } server.LobbyInfo.GlobalSettings.Map = s; var oldSlots = server.LobbyInfo.Slots.Keys.ToArray(); LoadMap(server); SetDefaultDifficulty(server); // Reset client states foreach (var c in server.LobbyInfo.Clients) c.State = Session.ClientState.Invalid; // 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 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.MapPlayers.Players[c.Slot].AllowBots) server.LobbyInfo.Clients.Remove(c); S.SyncClientToPlayerReference(c, server.MapPlayers.Players[c.Slot]); } else if (c.Bot != null) server.LobbyInfo.Clients.Remove(c); } foreach (var c in server.LobbyInfo.Clients) { // Validate if color is allowed and get an alternative it it isn't c.Color = c.PreferredColor = ColorValidator.ValidatePlayerColorAndGetAlternative(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.RuleDefinitions.Any()) server.SendMessage("This map contains custom rules. Game experience may change."); return true; } }, { "fragilealliance", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.FragileAlliances.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled alliance configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.FragileAlliances); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Diplomacy Changes." .F(client.Name, server.LobbyInfo.GlobalSettings.FragileAlliances ? "enabled" : "disabled")); return true; } }, { "allowcheats", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.Cheats.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled cheat configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} the Debug Menu." .F(client.Name, server.LobbyInfo.GlobalSettings.AllowCheats ? "enabled" : "disabled")); return true; } }, { "shroud", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.Shroud.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled shroud configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Shroud); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Explored map." .F(client.Name, server.LobbyInfo.GlobalSettings.Shroud ? "disabled" : "enabled")); return true; } }, { "fog", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.Fog.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled fog configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Fog); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Fog of War." .F(client.Name, server.LobbyInfo.GlobalSettings.Fog ? "enabled" : "disabled")); return true; } }, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } int teamCount; if (!Exts.TryParseIntegerInvariant(s, out 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; } }, { "crates", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.Crates.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled crate configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Crates); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Crates." .F(client.Name, server.LobbyInfo.GlobalSettings.Crates ? "enabled" : "disabled")); return true; } }, { "creeps", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.Creeps.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled Creeps spawning configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Creeps); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Creeps spawning." .F(client.Name, server.LobbyInfo.GlobalSettings.Creeps ? "enabled" : "disabled")); return true; } }, { "allybuildradius", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.AllyBuildRadius.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled ally build radius configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllyBuildRadius); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Build off Allies' ConYards." .F(client.Name, server.LobbyInfo.GlobalSettings.AllyBuildRadius ? "enabled" : "disabled")); return true; } }, { "difficulty", s => { if (!server.Map.Options.Difficulties.Any()) return true; if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (s != null && !server.Map.Options.Difficulties.Contains(s)) { server.SendOrderTo(conn, "Message", "Unsupported difficulty selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported difficulties: {0}".F(server.Map.Options.Difficulties.JoinWith(","))); return true; } server.LobbyInfo.GlobalSettings.Difficulty = s; server.SyncLobbyGlobalSettings(); server.SendMessage("{0} changed difficulty to {1}.".F(client.Name, s)); return true; } }, { "startingunits", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (!server.Map.Options.ConfigurableStartingUnits) { server.SendOrderTo(conn, "Message", "Map has disabled start unit configuration."); return true; } var startUnitsInfo = server.Map.Rules.Actors["world"].TraitInfos<MPStartUnitsInfo>(); var selectedClass = startUnitsInfo.Where(u => u.Class == s).Select(u => u.ClassName).FirstOrDefault(); var className = selectedClass != null ? selectedClass : s; server.LobbyInfo.GlobalSettings.StartingUnitsClass = s; server.SyncLobbyGlobalSettings(); server.SendMessage("{0} changed Starting Units to {1}.".F(client.Name, className)); return true; } }, { "startingcash", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.StartingCash.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled cash configuration."); return true; } server.LobbyInfo.GlobalSettings.StartingCash = Exts.ParseIntegerInvariant(s); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} changed Starting Cash to ${1}.".F(client.Name, s)); return true; } }, { "techlevel", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.TechLevel != null) { server.SendOrderTo(conn, "Message", "Map has disabled Tech configuration."); return true; } server.LobbyInfo.GlobalSettings.TechLevel = s; server.SyncLobbyInfo(); server.SendMessage("{0} changed Tech Level to {1}.".F(client.Name, s)); return true; } }, { "gamespeed", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var gameSpeeds = Game.ModData.Manifest.Get<GameSpeeds>(); GameSpeed speed; if (!gameSpeeds.Speeds.TryGetValue(s, out speed)) { server.SendOrderTo(conn, "Message", "Invalid game speed selected."); return true; } server.LobbyInfo.GlobalSettings.GameSpeedType = s; server.LobbyInfo.GlobalSettings.Timestep = speed.Timestep; server.LobbyInfo.GlobalSettings.OrderLatency = server.LobbyInfo.IsSinglePlayer ? 1 : speed.OrderLatency; server.SyncLobbyInfo(); server.SendMessage("{0} changed Game Speed to {1}.".F(client.Name, speed.Name)); return true; } }, { "kick", s => { 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; } int kickClientID; Exts.TryParseIntegerInvariant(split[0], out kickClientID); var kickConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickClientID); if (kickConn == null) { server.SendOrderTo(conn, "Message", "Noone in that slot."); return true; } var kickClient = server.GetClient(kickConn); 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 tempBan; bool.TryParse(split[1], out 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; } }, { "name", s => { var sanitizedName = OpenRA.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; } }, { "faction", 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; targetClient.Faction = parts[1]; server.SyncLobbyClients(); return true; } }, { "team", 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; int team; if (!Exts.TryParseIntegerInvariant(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s); return false; } targetClient.Team = team; server.SyncLobbyClients(); return true; } }, { "spawn", 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; int spawnPoint; if (!Exts.TryParseIntegerInvariant(parts[1], out spawnPoint) || spawnPoint < 0 || spawnPoint > server.Map.SpawnPoints.Value.Length) { 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; } targetClient.SpawnPoint = spawnPoint; server.SyncLobbyClients(); return true; } }, { "color", 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; // Spectator or map has disabled color changes if (targetClient.Slot == null || server.LobbyInfo.Slots[targetClient.Slot].LockColor) return true; var newHslColor = FieldLoader.GetValue<HSLColor>("(value)", parts[1]); // Validate if color is allowed and get an alternative it it isn't var altHslColor = ColorValidator.ValidatePlayerColorAndGetAlternative(server, newHslColor, targetClient.Index, conn); targetClient.Color = altHslColor; // Only update player's preferred color if new color is valid if (newHslColor == altHslColor) targetClient.PreferredColor = altHslColor; server.SyncLobbyClients(); return true; } }, { "shortgame", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } if (server.Map.Options.ShortGame.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled short game configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.ShortGame); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Short Game." .F(client.Name, server.LobbyInfo.GlobalSettings.ShortGame ? "enabled" : "disabled")); return true; } } }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func<string, bool> a; if (!dict.TryGetValue(cmdName, out a)) return false; return a(cmdValue); }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (!ValidateCommand(server, conn, client, cmd)) return false; var dict = new Dictionary<string, Func<string, bool>> { { "ready", s => { // if we're downloading, we can't ready up. if (client.State == Session.ClientState.NotReady) client.State = Session.ClientState.Ready; else if (client.State == Session.ClientState.Ready) client.State = Session.ClientState.NotReady; Log.Write("server", "Player @{0} is {1}", conn.socket.RemoteEndPoint, client.State); server.SyncLobbyInfo(); CheckAutoStart(server, conn, client); return true; }}, { "startgame", s => { 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; } server.StartGame(); return true; }}, { "slot", s => { 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; client.Slot = s; S.SyncClientToPlayerReference(client, server.Map.Players[s]); server.SyncLobbyInfo(); CheckAutoStart(server, conn, client); return true; }}, { "spectate", s => { client.Slot = null; client.SpawnPoint = 0; client.Color = HSLColor.FromRGB(255, 255, 255); server.SyncLobbyInfo(); return true; }}, { "slot_close", 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) { if (occupant.Bot != null) server.lobbyInfo.Clients.Remove(occupant); 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.SyncLobbyInfo(); return true; }}, { "slot_open", s => { if (!ValidateSlotCommand( server, conn, client, s, true )) return false; var slot = server.lobbyInfo.Slots[s]; slot.Closed = false; // 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.SyncLobbyInfo(); return true; }}, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 3) { 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]); int controllerClientIndex; if (!int.TryParse(parts[1], out controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return false; } var botType = parts.Skip(2).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client"); return true; } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, Bot = botType, Slot = parts[0], Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex }; // pick a random color for the bot var hue = (byte)server.Random.Next(255); var sat = (byte)server.Random.Next(255); var lum = (byte)server.Random.Next(51,255); bot.Color = bot.PreferredColor = new HSLColor(hue, sat, lum); server.lobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players[parts[0]]); server.SyncLobbyInfo(); return true; }}, { "map", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the map"); return true; } if (!server.ModData.AvailableMaps.ContainsKey(s)) { server.SendOrderTo(conn, "Message", "Map not found"); return true; } server.lobbyInfo.GlobalSettings.Map = s; var oldSlots = server.lobbyInfo.Slots.Keys.ToArray(); LoadMap(server); SetDefaultDifficulty(server); // 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 var slots = server.lobbyInfo.Slots.Keys.ToArray(); int i = 0; foreach (var os in oldSlots) { var c = server.lobbyInfo.ClientInSlot(os); if (c == null) continue; c.SpawnPoint = 0; c.State = Session.ClientState.NotReady; 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[c.Slot].AllowBots) server.lobbyInfo.Clients.Remove(c); S.SyncClientToPlayerReference(c, server.Map.Players[c.Slot]); } else if (c.Bot != null) server.lobbyInfo.Clients.Remove(c); } server.SyncLobbyInfo(); return true; }}, { "fragilealliance", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.FragileAlliances.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled alliance configuration"); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.FragileAlliances); server.SyncLobbyInfo(); return true; }}, { "allowcheats", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.Cheats.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled cheat configuration"); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyInfo(); return true; }}, { "shroud", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.Shroud.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled shroud configuration"); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.Shroud); server.SyncLobbyInfo(); return true; }}, { "fog", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.Fog.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled fog configuration"); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.Fog); server.SyncLobbyInfo(); return true; }}, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } int teamCount; if (!int.TryParse(s, out 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 players = server.lobbyInfo.Slots .Select(slot => server.lobbyInfo.ClientInSlot(slot.Key)) .Where(c => c != null && !server.lobbyInfo.Slots[c.Slot].LockTeam); var assigned = 0; var playerCount = players.Count(); foreach (var player in players) { // 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 / playerCount + 1; } server.SyncLobbyInfo(); return true; }}, { "crates", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.Crates.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled crate configuration"); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.Crates); server.SyncLobbyInfo(); return true; }}, { "allybuildradius", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.AllyBuildRadius.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled ally build radius configuration"); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.AllyBuildRadius); server.SyncLobbyInfo(); return true; }}, { "difficulty", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (s != null && !server.Map.Options.Difficulties.Contains(s)) { server.SendOrderTo(conn, "Message", "Unsupported difficulty selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported difficulties: {0}".F(server.Map.Options.Difficulties.JoinWith(","))); return true; } server.lobbyInfo.GlobalSettings.Difficulty = s; server.SyncLobbyInfo(); return true; }}, { "startingunits", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (!server.Map.Options.ConfigurableStartingUnits) { server.SendOrderTo(conn, "Message", "Map has disabled start unit configuration"); return true; } server.lobbyInfo.GlobalSettings.StartingUnitsClass = s; server.SyncLobbyInfo(); return true; }}, { "startingcash", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return true; } if (server.Map.Options.StartingCash.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled cash configuration"); return true; } server.lobbyInfo.GlobalSettings.StartingCash = int.Parse(s); server.SyncLobbyInfo(); return true; }}, { "kick", s => { 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; } int kickClientID; int.TryParse(split[0], out kickClientID); var kickConn = server.conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickClientID); if (kickConn == null) { server.SendOrderTo(conn, "Message", "Noone in that slot."); return true; } var kickConnIP = server.GetClient(kickConn).IpAddress; Log.Write("server", "Kicking client {0} as requested", kickClientID); server.SendOrderTo(kickConn, "ServerError", "You have been kicked from the server"); server.DropClient(kickConn); bool tempBan; bool.TryParse(split[1], out tempBan); if (tempBan) { Log.Write("server", "Temporarily banning client {0} ({1}) as requested", kickClientID, kickConnIP); server.TempBans.Add(kickConnIP); } server.SyncLobbyInfo(); return true; }}, { "name", s => { Log.Write("server", "Player@{0} is now known as {1}", conn.socket.RemoteEndPoint, s); client.Name = s; server.SyncLobbyInfo(); return true; }}, { "race", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) return true; // Map has disabled race changes if (server.lobbyInfo.Slots[targetClient.Slot].LockRace) return true; targetClient.Country = parts[1]; server.SyncLobbyInfo(); return true; }}, { "team", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(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; int team; if (!int.TryParse(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s ); return false; } targetClient.Team = team; server.SyncLobbyInfo(); return true; }}, { "spawn", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(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; int spawnPoint; if (!int.TryParse(parts[1], out spawnPoint) || spawnPoint < 0 || spawnPoint > server.Map.GetSpawnPoints().Length) { 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 can't be at the same spawn point as another player"); return true; } targetClient.SpawnPoint = spawnPoint; server.SyncLobbyInfo(); return true; }}, { "color", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(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; var ci = parts[1].Split(',').Select(cc => int.Parse(cc)).ToArray(); targetClient.Color = targetClient.PreferredColor = new HSLColor((byte)ci[0], (byte)ci[1], (byte)ci[2]); server.SyncLobbyInfo(); return true; }} }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func<string, bool> a; if (!dict.TryGetValue(cmdName, out a)) return false; return a(cmdValue); }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (!ValidateCommand(server, conn, client, cmd)) return false; var dict = new Dictionary<string, Func<string, bool>> { { "ready", s => { // if we're downloading, we can't ready up. if (client.State == Session.ClientState.NotReady) client.State = Session.ClientState.Ready; else if (client.State == Session.ClientState.Ready) client.State = Session.ClientState.NotReady; Log.Write("server", "Player @{0} is {1}", conn.socket.RemoteEndPoint, client.State); server.SyncLobbyInfo(); if (server.conns.Count > 0 && server.conns.All(c => server.GetClient(c).State == Session.ClientState.Ready)) InterpretCommand(server, conn, client, "startgame"); return true; }}, { "startgame", s => { server.StartGame(); return true; }}, { "lag", s => { int lag; if (!int.TryParse(s, out lag)) { Log.Write("server", "Invalid order lag: {0}", s); return false; } Log.Write("server", "Order lag is now {0} frames.", lag); server.lobbyInfo.GlobalSettings.OrderLatency = lag; server.SyncLobbyInfo(); return true; }}, { "slot", s => { 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; client.Slot = s; S.SyncClientToPlayerReference(client, server.Map.Players[s]); server.SyncLobbyInfo(); return true; }}, { "spectate", s => { client.Slot = null; client.SpawnPoint = 0; server.SyncLobbyInfo(); return true; }}, { "slot_close", 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) { if (occupant.Bot != null) server.lobbyInfo.Clients.Remove(occupant); 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.SyncLobbyInfo(); return true; }}, { "slot_open", s => { if (!ValidateSlotCommand( server, conn, client, s, true )) return false; var slot = server.lobbyInfo.Slots[s]; slot.Closed = false; // 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.SyncLobbyInfo(); return true; }}, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 2) { server.SendChatTo( conn, "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]); var botType = parts.Skip(1).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendChatTo( conn, "Can't add bots to a slot with another client" ); return true; } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, Bot = botType, Slot = parts[0], Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady }; // pick a random color for the bot var hue = (byte)server.Random.Next(255); var sat = (byte)server.Random.Next(255); var lum = (byte)server.Random.Next(51,255); bot.ColorRamp = new ColorRamp(hue, sat, lum, 10); server.lobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players[parts[0]]); server.SyncLobbyInfo(); return true; }}, { "map", s => { if (!client.IsAdmin) { server.SendChatTo( conn, "Only the host can change the map" ); return true; } server.lobbyInfo.GlobalSettings.Map = s; var oldSlots = server.lobbyInfo.Slots.Keys.ToArray(); LoadMap(server); // 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 var slots = server.lobbyInfo.Slots.Keys.ToArray(); int i = 0; foreach (var os in oldSlots) { var c = server.lobbyInfo.ClientInSlot(os); if (c == null) continue; c.SpawnPoint = 0; c.State = Session.ClientState.NotReady; c.Slot = i < slots.Length ? slots[i++] : null; if (c.Slot != null) S.SyncClientToPlayerReference(c, server.Map.Players[c.Slot]); else if (c.Bot != null) server.lobbyInfo.Clients.Remove(c); } server.SyncLobbyInfo(); return true; }}, { "lockteams", s => { if (!client.IsAdmin) { server.SendChatTo( conn, "Only the host can set that option" ); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.LockTeams); server.SyncLobbyInfo(); return true; }}, { "allowcheats", s => { if (!client.IsAdmin) { server.SendChatTo( conn, "Only the host can set that option" ); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyInfo(); return true; }}, { "kick", s => { if (!client.IsAdmin) { server.SendChatTo( conn, "Only the host can kick players" ); return true; } int clientID; int.TryParse( s, out clientID ); var connToKick = server.conns.SingleOrDefault( c => server.GetClient(c) != null && server.GetClient(c).Index == clientID); if (connToKick == null) { server.SendChatTo( conn, "Noone in that slot." ); return true; } server.SendOrderTo(connToKick, "ServerError", "You have been kicked from the server"); server.DropClient(connToKick); server.SyncLobbyInfo(); return true; }}, { "name", s => { Log.Write("server", "Player@{0} is now known as {1}", conn.socket.RemoteEndPoint, s); client.Name = s; server.SyncLobbyInfo(); return true; }}, { "race", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) return true; // Map has disabled race changes if (server.lobbyInfo.Slots[targetClient.Slot].LockRace) return true; targetClient.Country = parts[1]; server.SyncLobbyInfo(); return true; }}, { "team", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(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; int team; if (!int.TryParse(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s ); return false; } targetClient.Team = team; server.SyncLobbyInfo(); return true; }}, { "spawn", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(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; int spawnPoint; if (!int.TryParse(parts[1], out spawnPoint) || spawnPoint < 0 || spawnPoint > server.Map.GetSpawnPoints().Length) { 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.SendChatTo( conn, "You can't be at the same spawn point as another player" ); return true; } targetClient.SpawnPoint = spawnPoint; server.SyncLobbyInfo(); return true; }}, { "color", s => { var parts = s.Split(' '); var targetClient = server.lobbyInfo.ClientWithIndex(int.Parse(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) return true; // Map has disabled color changes if (targetClient.Slot != null && server.lobbyInfo.Slots[targetClient.Slot].LockColor) return true; var ci = parts[1].Split(',').Select(cc => int.Parse(cc)).ToArray(); targetClient.ColorRamp = new ColorRamp((byte)ci[0], (byte)ci[1], (byte)ci[2], (byte)ci[3]); server.SyncLobbyInfo(); return true; }} }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func<string,bool> a; if (!dict.TryGetValue(cmdName, out a)) return false; return a(cmdValue); }
public static bool ValidatePlayerNewColor(S server, Color askedColor, int playerIndex, out Color forbiddenColor, Connection connectionToEcho = null) { // Validate color against the current map tileset var tileset = server.Map.Rules.TileSets[server.Map.Tileset]; var forbiddenColors = tileset.TerrainInfo.Select(terrainInfo => terrainInfo.Color); if (!ValidateColorAgainstForbidden(askedColor, forbiddenColors, out forbiddenColor)) { if (connectionToEcho != null) server.SendOrderTo(connectionToEcho, "Message", "Color was too similar to the terrain, and has been adjusted."); return false; } // Validate color against other clients var playerColors = server.LobbyInfo.Clients.Where(c => c.Index != playerIndex).Select(c => c.Color.RGB); if (!ValidateColorAgainstForbidden(askedColor, playerColors, out forbiddenColor)) { if (connectionToEcho != null) server.SendOrderTo(connectionToEcho, "Message", "Color was too similar to another player's color, and has been adjusted."); return false; } var mapPlayerColors = server.MapPlayers.Players.Values.Select(p => p.ColorRamp.RGB); if (!ValidateColorAgainstForbidden(askedColor, mapPlayerColors, out forbiddenColor)) { if (connectionToEcho != null) server.SendOrderTo(connectionToEcho, "Message", "Color was too similar to a non-combatant player, and has been adjusted."); return false; } // Color is valid forbiddenColor = default(Color); return true; }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (server == null || conn == null || client == null || !ValidateCommand(server, conn, client, cmd)) { return(false); } var dict = new Dictionary <string, Func <string, bool> > { { "state", s => { var state = Session.ClientState.Invalid; if (!Enum <Session.ClientState> .TryParse(s, false, out 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); } }, { "startgame", s => { 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.Clients.Where(c => c.Bot == null && c.Slot != null).Count() == 1) { server.SendOrderTo(conn, "Message", server.TwoHumansRequiredText); return(true); } server.StartGame(); return(true); } }, { "slot", s => { 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); } }, { "allow_spectators", s => { if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) { server.SyncLobbyGlobalSettings(); return(true); } else { server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); return(true); } } }, { "spectate", s => { if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) { client.Slot = null; client.SpawnPoint = 0; client.Color = HSLColor.FromRGB(255, 255, 255); server.SyncLobbyClients(); CheckAutoStart(server); return(true); } else { return(false); } } }, { "slot_close", 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) { 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); } }, { "slot_open", 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); } }, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 3) { 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]); int controllerClientIndex; if (!Exts.TryParseIntegerInvariant(parts[1], out controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return(false); } var botType = parts.Skip(2).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); return(true); } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, 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 <ColorValidator>(); 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.RGB) .Concat(server.Map.Players.Players.Values.Select(p => p.Color.RGB)); bot.Color = bot.PreferredColor = validator.RandomValidColor(server.Random, terrainColors, playerColors); server.LobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players.Players[parts[0]]); server.SyncLobbyClients(); server.SyncLobbySlots(); return(true); } }, { "map", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the map."); return(true); } var lastMap = server.LobbyInfo.GlobalSettings.Map; Action <MapPreview> 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 foreach (var c in server.LobbyInfo.Clients) { c.State = Session.ClientState.Invalid; } // 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 botNames = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Name); 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 || !botNames.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); } } // Validate if color is allowed and get an alternative if it isn't foreach (var c in server.LobbyInfo.Clients) { if (c.Slot == null || (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..."); server.ModData.MapCache.QueryRemoteMapDetails(new[] { s }, selectMap, queryFailed); } else { queryFailed(); } return(true); } }, { "option", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the configuration."); return(true); } var allOptions = server.Map.Rules.Actors["player"].TraitInfos <ILobbyOptions>() .Concat(server.Map.Rules.Actors["world"].TraitInfos <ILobbyOptions>()) .SelectMany(t => t.LobbyOptions(server.Map.Rules)); // Overwrite keys with duplicate ids var options = new Dictionary <string, LobbyOption>(); foreach (var o in allOptions) { options[o.Id] = o; } var split = s.Split(' '); LobbyOption option; if (split.Length < 2 || !options.TryGetValue(split[0], out option) || !option.Values.ContainsKey(split[1])) { server.SendOrderTo(conn, "Message", "Invalid configuration command."); return(true); } if (option.Locked) { 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 <GameSpeeds>().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])); return(true); } }, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return(true); } int teamCount; if (!Exts.TryParseIntegerInvariant(s, out 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); } }, { "kick", s => { 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); } int kickClientID; Exts.TryParseIntegerInvariant(split[0], out 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); 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 tempBan; bool.TryParse(split[1], out 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); } }, { "name", s => { 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); } }, { "faction", 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 <FactionInfo>() .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); } }, { "team", 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); } int team; if (!Exts.TryParseIntegerInvariant(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s); return(false); } targetClient.Team = team; server.SyncLobbyClients(); return(true); } }, { "spawn", 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); } int spawnPoint; if (!Exts.TryParseIntegerInvariant(parts[1], out spawnPoint) || spawnPoint <0 || spawnPoint> server.Map.SpawnPoints.Length) { 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); } }, { "color", 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); } // 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 <HSLColor>("(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); } }, { "sync_lobby", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set lobby info"); return(true); } var lobbyInfo = Session.Deserialize(s); if (lobbyInfo == null) { server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent"); return(true); } server.LobbyInfo = lobbyInfo; server.SyncLobbyInfo(); return(true); } } }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func <string, bool> a; if (!dict.TryGetValue(cmdName, out a)) { return(false); } return(a(cmdValue)); }
public void Tick(S server) { if ((Game.RunTime - lastPing > PingInterval) || isInitialPing) { isInitialPing = false; lastPing = Game.RunTime; // Ignore client timeout in singleplayer games to make debugging easier if (server.LobbyInfo.NonBotClients.Count() < 2 && !server.Dedicated) { foreach (var c in server.Conns.ToList()) { server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); } } else { foreach (var c in server.Conns.ToList()) { if (c == null || c.Socket == null) { continue; } var client = server.GetClient(c); if (client == null) { server.DropClient(c); server.SendMessage("A player has been dropped after timing out."); continue; } if (c.TimeSinceLastResponse < ConnTimeout) { server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); if (!c.TimeoutMessageShown && c.TimeSinceLastResponse > PingInterval * 2) { server.SendMessage(client.Name + " is experiencing connection problems."); c.TimeoutMessageShown = true; } } else { server.SendMessage(client.Name + " has been dropped after timing out."); server.DropClient(c); } } if (Game.RunTime - lastConnReport > ConnReportInterval) { lastConnReport = Game.RunTime; var timeouts = server.Conns .Where(c => c.TimeSinceLastResponse > ConnReportInterval && c.TimeSinceLastResponse < ConnTimeout) .OrderBy(c => c.TimeSinceLastResponse); foreach (var c in timeouts) { if (c == null || c.Socket == null) { continue; } var client = server.GetClient(c); if (client != null) { server.SendMessage("{0} will be dropped in {1} seconds.".F(client.Name, (ConnTimeout - c.TimeSinceLastResponse) / 1000)); } } } } } }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (server == null || conn == null || client == null || !ValidateCommand(server, conn, client, cmd)) return false; var dict = new Dictionary<string, Func<string, bool>> { { "state", s => { var state = Session.ClientState.Invalid; if (!Enum<Session.ClientState>.TryParse(s, false, out 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; } }, { "startgame", s => { 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.Settings.DisableSinglePlayer && server.LobbyInfo.Clients.Where(c => c.Bot == null && c.Slot != null).Count() == 1) { server.SendOrderTo(conn, "Message", "Unable to start the game until another player joins."); return true; } server.StartGame(); return true; } }, { "slot", s => { 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; } }, { "allow_spectators", s => { if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) { server.SyncLobbyGlobalSettings(); return true; } else { server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); return true; } } }, { "spectate", s => { if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) { client.Slot = null; client.SpawnPoint = 0; client.Color = HSLColor.FromRGB(255, 255, 255); server.SyncLobbyClients(); return true; } else return false; } }, { "slot_close", 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) { 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; } }, { "slot_open", 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; } }, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 3) { 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]); int controllerClientIndex; if (!Exts.TryParseIntegerInvariant(parts[1], out controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return false; } var botType = parts.Skip(2).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); return true; } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, 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<ColorValidator>(); 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.RGB) .Concat(server.Map.Players.Players.Values.Select(p => p.Color.RGB)); bot.Color = bot.PreferredColor = validator.RandomValidColor(server.Random, terrainColors, playerColors); server.LobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players.Players[parts[0]]); server.SyncLobbyClients(); server.SyncLobbySlots(); return true; } }, { "map", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the map."); return true; } var lastMap = server.LobbyInfo.GlobalSettings.Map; Action<MapPreview> 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.LobbyInfo.GlobalSettings, server.Map.Rules); // Reset client states foreach (var c in server.LobbyInfo.Clients) c.State = Session.ClientState.Invalid; // 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 botNames = server.Map.Rules.Actors["player"].TraitInfos<IBotInfo>().Select(t => t.Name); 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 || !botNames.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); } // Validate if color is allowed and get an alternative if it isn't foreach (var c in server.LobbyInfo.Clients) if (c.Slot == null || (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.Settings.DisableSinglePlayer) server.SendMessage("Singleplayer games have been disabled on this server."); 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."); }; 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..."); server.ModData.MapCache.QueryRemoteMapDetails(new[] { s }, selectMap, queryFailed); } else queryFailed(); return true; } }, { "allowcheats", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var devMode = server.Map.Rules.Actors["player"].TraitInfo<DeveloperModeInfo>(); if (devMode.Locked) { server.SendOrderTo(conn, "Message", "Map has disabled cheat configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} the Debug Menu." .F(client.Name, server.LobbyInfo.GlobalSettings.AllowCheats ? "enabled" : "disabled")); return true; } }, { "shroud", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var shroud = server.Map.Rules.Actors["player"].TraitInfo<ShroudInfo>(); if (shroud.ExploredMapLocked) { server.SendOrderTo(conn, "Message", "Map has disabled shroud configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Shroud); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Explored map." .F(client.Name, server.LobbyInfo.GlobalSettings.Shroud ? "disabled" : "enabled")); return true; } }, { "fog", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var shroud = server.Map.Rules.Actors["player"].TraitInfo<ShroudInfo>(); if (shroud.FogLocked) { server.SendOrderTo(conn, "Message", "Map has disabled fog configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Fog); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Fog of War." .F(client.Name, server.LobbyInfo.GlobalSettings.Fog ? "enabled" : "disabled")); return true; } }, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } int teamCount; if (!Exts.TryParseIntegerInvariant(s, out 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; } }, { "crates", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var crateSpawner = server.Map.Rules.Actors["world"].TraitInfoOrDefault<CrateSpawnerInfo>(); if (crateSpawner == null || crateSpawner.Locked) { server.SendOrderTo(conn, "Message", "Map has disabled crate configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Crates); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Crates." .F(client.Name, server.LobbyInfo.GlobalSettings.Crates ? "enabled" : "disabled")); return true; } }, { "creeps", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var mapCreeps = server.Map.Rules.Actors["world"].TraitInfoOrDefault<MapCreepsInfo>(); if (mapCreeps == null || mapCreeps.Locked) { server.SendOrderTo(conn, "Message", "Map has disabled Creeps spawning configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Creeps); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Creeps spawning." .F(client.Name, server.LobbyInfo.GlobalSettings.Creeps ? "enabled" : "disabled")); return true; } }, { "allybuildradius", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var mapBuildRadius = server.Map.Rules.Actors["world"].TraitInfoOrDefault<MapBuildRadiusInfo>(); if (mapBuildRadius == null || mapBuildRadius.AllyBuildRadiusLocked) { server.SendOrderTo(conn, "Message", "Map has disabled ally build radius configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllyBuildRadius); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Build off Allies' ConYards." .F(client.Name, server.LobbyInfo.GlobalSettings.AllyBuildRadius ? "enabled" : "disabled")); return true; } }, { "difficulty", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var mapOptions = server.Map.Rules.Actors["world"].TraitInfo<MapOptionsInfo>(); if (mapOptions.DifficultyLocked || !mapOptions.Difficulties.Any()) { server.SendOrderTo(conn, "Message", "Map has disabled difficulty configuration."); return true; } if (s != null && !mapOptions.Difficulties.Contains(s)) { server.SendOrderTo(conn, "Message", "Invalid difficulty selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported values: {0}".F(mapOptions.Difficulties.JoinWith(", "))); return true; } server.LobbyInfo.GlobalSettings.Difficulty = s; server.SyncLobbyGlobalSettings(); server.SendMessage("{0} changed difficulty to {1}.".F(client.Name, s)); return true; } }, { "startingunits", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var startingUnits = server.Map.Rules.Actors["world"].TraitInfoOrDefault<SpawnMPUnitsInfo>(); if (startingUnits == null || startingUnits.Locked) { server.SendOrderTo(conn, "Message", "Map has disabled start unit configuration."); return true; } var startUnitsInfo = server.Map.Rules.Actors["world"].TraitInfos<MPStartUnitsInfo>(); var selectedClass = startUnitsInfo.Where(u => u.Class == s).FirstOrDefault(); if (selectedClass == null) { server.SendOrderTo(conn, "Message", "Invalid starting units option selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported values: {0}".F(startUnitsInfo.Select(su => su.ClassName).JoinWith(", "))); return true; } server.LobbyInfo.GlobalSettings.StartingUnitsClass = selectedClass.Class; server.SyncLobbyGlobalSettings(); server.SendMessage("{0} changed Starting Units to {1}.".F(client.Name, selectedClass.ClassName)); return true; } }, { "startingcash", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var playerResources = server.Map.Rules.Actors["player"].TraitInfo<PlayerResourcesInfo>(); if (playerResources.DefaultCashLocked) { server.SendOrderTo(conn, "Message", "Map has disabled cash configuration."); return true; } var startingCashOptions = playerResources.SelectableCash; var requestedCash = Exts.ParseIntegerInvariant(s); if (!startingCashOptions.Contains(requestedCash)) { server.SendOrderTo(conn, "Message", "Invalid starting cash value selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported values: {0}".F(startingCashOptions.JoinWith(", "))); return true; } server.LobbyInfo.GlobalSettings.StartingCash = requestedCash; server.SyncLobbyGlobalSettings(); server.SendMessage("{0} changed Starting Cash to ${1}.".F(client.Name, requestedCash)); return true; } }, { "techlevel", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var mapOptions = server.Map.Rules.Actors["world"].TraitInfo<MapOptionsInfo>(); if (mapOptions.TechLevelLocked) { server.SendOrderTo(conn, "Message", "Map has disabled Tech configuration."); return true; } var techlevels = server.Map.Rules.Actors["player"].TraitInfos<ProvidesTechPrerequisiteInfo>().Select(t => t.Name); if (!techlevels.Contains(s)) { server.SendOrderTo(conn, "Message", "Invalid tech level selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported values: {0}".F(techlevels.JoinWith(", "))); return true; } server.LobbyInfo.GlobalSettings.TechLevel = s; server.SyncLobbyInfo(); server.SendMessage("{0} changed Tech Level to {1}.".F(client.Name, s)); return true; } }, { "gamespeed", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var gameSpeeds = server.ModData.Manifest.Get<GameSpeeds>(); GameSpeed speed; if (!gameSpeeds.Speeds.TryGetValue(s, out speed)) { server.SendOrderTo(conn, "Message", "Invalid game speed selected."); return true; } server.LobbyInfo.GlobalSettings.GameSpeedType = s; server.LobbyInfo.GlobalSettings.Timestep = speed.Timestep; server.LobbyInfo.GlobalSettings.OrderLatency = server.LobbyInfo.IsSinglePlayer ? 1 : speed.OrderLatency; server.SyncLobbyInfo(); server.SendMessage("{0} changed Game Speed to {1}.".F(client.Name, speed.Name)); return true; } }, { "kick", s => { 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; } int kickClientID; Exts.TryParseIntegerInvariant(split[0], out 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); 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 tempBan; bool.TryParse(split[1], out 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; } }, { "name", s => { 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; } }, { "faction", 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<FactionInfo>() .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; } }, { "team", 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; int team; if (!Exts.TryParseIntegerInvariant(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s); return false; } targetClient.Team = team; server.SyncLobbyClients(); return true; } }, { "spawn", 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; int spawnPoint; if (!Exts.TryParseIntegerInvariant(parts[1], out spawnPoint) || spawnPoint < 0 || spawnPoint > server.Map.SpawnPoints.Length) { 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; } }, { "color", 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; // 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<HSLColor>("(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; } }, { "shortgame", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return true; } var mapOptions = server.Map.Rules.Actors["world"].TraitInfo<MapOptionsInfo>(); if (mapOptions.ShortGameLocked) { server.SendOrderTo(conn, "Message", "Map has disabled short game configuration."); return true; } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.ShortGame); server.SyncLobbyGlobalSettings(); server.SendMessage("{0} {1} Short Game." .F(client.Name, server.LobbyInfo.GlobalSettings.ShortGame ? "enabled" : "disabled")); return true; } }, { "sync_lobby", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set lobby info"); return true; } var lobbyInfo = Session.Deserialize(s); if (lobbyInfo == null) { server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent"); return true; } server.LobbyInfo = lobbyInfo; server.SyncLobbyInfo(); return true; } } }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func<string, bool> a; if (!dict.TryGetValue(cmdName, out a)) return false; return a(cmdValue); }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (server.GameStarted) { server.SendChatTo(conn, "Cannot change state when game started. ({0})".F(cmd)); return false; } else if (client.State == Session.ClientState.Ready && !(cmd == "ready" || cmd == "startgame")) { server.SendChatTo(conn, "Cannot change state when marked as ready."); return false; } var dict = new Dictionary<string, Func<string, bool>> { { "ready", s => { // if we're downloading, we can't ready up. if (client.State == Session.ClientState.NotReady) client.State = Session.ClientState.Ready; else if (client.State == Session.ClientState.Ready) client.State = Session.ClientState.NotReady; Log.Write("server", "Player @{0} is {1}", conn.socket.RemoteEndPoint, client.State); server.SyncLobbyInfo(); if (server.conns.Count > 0 && server.conns.All(c => server.GetClient(c).State == Session.ClientState.Ready)) InterpretCommand(server, conn, client, "startgame"); return true; }}, { "startgame", s => { server.StartGame(); return true; }}, { "lag", s => { int lag; if (!int.TryParse(s, out lag)) { Log.Write("server", "Invalid order lag: {0}", s); return false; } Log.Write("server", "Order lag is now {0} frames.", lag); server.lobbyInfo.GlobalSettings.OrderLatency = lag; server.SyncLobbyInfo(); return true; }}, { "spectator", s => { var slotData = server.lobbyInfo.Slots.Where(ax => ax.Spectator && !server.lobbyInfo.Clients.Any(l => l.Slot == ax.Index)).FirstOrDefault(); if (slotData == null) return true; client.Slot = slotData.Index; S.SyncClientToPlayerReference(client, slotData.MapPlayer != null ? server.Map.Players[slotData.MapPlayer] : null); server.SyncLobbyInfo(); return true; }}, { "slot", s => { int slot; if (!int.TryParse(s, out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; } var slotData = server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot ); if (slotData == null || slotData.Closed || slotData.Bot != null || server.lobbyInfo.Clients.Any( c => c.Slot == slot )) return false; client.Slot = slot; S.SyncClientToPlayerReference(client, slotData.MapPlayer != null ? server.Map.Players[slotData.MapPlayer] : null); server.SyncLobbyInfo(); return true; }}, { "slot_close", s => { int slot; if (!int.TryParse(s, out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; } var slotData = server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot ); if (slotData == null) return false; if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can alter slots" ); return true; } slotData.Closed = true; slotData.Bot = null; /* kick any player that's in the slot */ var occupant = server.lobbyInfo.Clients.FirstOrDefault( c => c.Slot == slotData.Index ); if (occupant != null) { 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.SyncLobbyInfo(); return true; }}, { "slot_open", s => { int slot; if (!int.TryParse(s, out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; } var slotData = server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot ); if (slotData == null) return false; if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can alter slots" ); return true; } slotData.Closed = false; slotData.Bot = null; server.SyncLobbyInfo(); return true; }}, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 2) { server.SendChatTo( conn, "Malformed slot_bot command" ); return true; } int slot; if (!int.TryParse(parts[0], out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; } var slotData = server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot ); if (slotData == null) return false; if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can alter slots" ); return true; } slotData.Closed = false; slotData.Bot = string.Join(" ", parts.Skip(1).ToArray() ); server.SyncLobbyInfo(); return true; }}, { "map", s => { if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can change the map" ); return true; } server.lobbyInfo.GlobalSettings.Map = s; LoadMap(server); foreach(var c in server.lobbyInfo.Clients) { c.SpawnPoint = 0; var slotData = server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == c.Slot ); if (slotData != null && slotData.MapPlayer != null) S.SyncClientToPlayerReference(c, server.Map.Players[slotData.MapPlayer]); c.State = Session.ClientState.NotReady; } server.SyncLobbyInfo(); return true; }}, { "lockteams", s => { if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can set that option" ); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.LockTeams); server.SyncLobbyInfo(); return true; }}, { "allowcheats", s => { if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can set that option" ); return true; } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyInfo(); return true; }}, { "kick", s => { if (conn.PlayerIndex != 0) { server.SendChatTo( conn, "Only the host can kick players" ); return true; } int slot; int.TryParse( s, out slot ); var connToKick = server.conns.SingleOrDefault( c => server.GetClient(c) != null && server.GetClient(c).Slot == slot); if (connToKick == null) { server.SendChatTo( conn, "Noone in that slot." ); return true; } server.SendOrderTo(connToKick, "ServerError", "You have been kicked from the server"); server.DropClient(connToKick); server.SyncLobbyInfo(); return true; }}, }; var cmdName = cmd.Split(' ').First(); var cmdValue = string.Join(" ", cmd.Split(' ').Skip(1).ToArray()); Func<string,bool> a; if (!dict.TryGetValue(cmdName, out a)) return false; return a(cmdValue); }
static HSLColor SanitizePlayerColor(S server, HSLColor askedColor, int playerIndex, Connection connectionToEcho = null) { var validator = server.ModData.Manifest.Get<ColorValidator>(); var askColor = askedColor; Action<string> onError = message => { if (connectionToEcho != null) server.SendOrderTo(connectionToEcho, "Message", message); }; 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.RGB) .Concat(server.Map.Players.Players.Values.Select(p => p.Color.RGB)).ToList(); return validator.MakeValid(askColor.RGB, server.Random, terrainColors, playerColors, onError); }
public void Tick(S server) { if ((Game.RunTime - lastPing > PingInterval) || isInitialPing) { isInitialPing = false; lastPing = Game.RunTime; // Ignore client timeout in singleplayer games to make debugging easier if (server.LobbyInfo.IsSinglePlayer && !server.Settings.Dedicated) foreach (var c in server.Conns.ToList()) server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); else { foreach (var c in server.Conns.ToList()) { if (c == null || c.Socket == null) continue; var client = server.GetClient(c); if (client == null) { server.DropClient(c, -1); server.SendMessage("A player has been dropped after timing out."); continue; } if (c.TimeSinceLastResponse < ConnTimeout) { server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); if (!c.TimeoutMessageShown && c.TimeSinceLastResponse > PingInterval * 2) { server.SendMessage(client.Name + " is experiencing connection problems."); c.TimeoutMessageShown = true; } } else { server.SendMessage(client.Name + " has been dropped after timing out."); server.DropClient(c, -1); } } if (Game.RunTime - lastConnReport > ConnReportInterval) { lastConnReport = Game.RunTime; var timeouts = server.Conns .Where(c => c.TimeSinceLastResponse > ConnReportInterval && c.TimeSinceLastResponse < ConnTimeout) .OrderBy(c => c.TimeSinceLastResponse); foreach (var c in timeouts) { if (c == null || c.Socket == null) continue; var client = server.GetClient(c); if (client != null) server.SendMessage("{0} will be dropped in {1} seconds.".F(client.Name, (ConnTimeout - c.TimeSinceLastResponse) / 1000)); } } } } }
public void Tick(S server) { if (queue.TryDequeue(out var line)) { // Do your line processing logic here, on the server thread. Console.WriteLine("You typed: {0}", line); if (line == "exit") { // Console.WriteLine("OK, shutting down!"); Console.WriteLine("This command is disabled"); // server.Shutdown(); } if (line == "ads") { var adFile = Path.Combine(Platform.SupportDir, "mrads.txt"); if (!File.Exists(adFile)) { File.WriteAllText(adFile, "[MR] Welcome to our server. Good luck, have fun!"); } if (File.Exists(adFile)) { var xlines = File.ReadAllLines(adFile); var lineStr = xlines.Random(server.Random); server.SendMessage(lineStr); } } if (line == "testmsg") { var testmsg = string.Format("Hello this is a message from the console!"); Console.WriteLine("Sending Test Message to game"); server.SendMessage(testmsg); } if (line == "help") { Console.WriteLine("Available commands: say, psay, status, kick, tban, admin, deladmin, ads, help. Type help commandName for more information."); } if (line.StartsWith("say ")) { var smsg = line.Remove(0, 4); string.Format(smsg); Console.WriteLine(smsg); server.SendMessage("[MR] {0}".F(smsg)); } if (line == "help psay") { Console.WriteLine("Syntax: psay userID 'message here'"); Console.WriteLine("WARNING: Private messages are unencrypted, and may be saved to replay files. Use with caution"); } if (line.StartsWith("psay ") && line.Length > 7) { var smsg = line.Remove(0, 5); int index = smsg.IndexOf('\''); if (index >= 0) { // Console.WriteLine("Index was greater than 0"); int msgUID = Int32.Parse(smsg.Substring(0, index)); var msgConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == msgUID); if (msgConn != null) { // Console.WriteLine("msgConn was not null"); smsg = smsg.Remove(0, index - 1); Match match = Regex.Match(smsg, @"'([^']*)"); if (match.Success) { var msgClient = server.GetClient(msgConn); server.SendOrderTo(msgConn, "Message", "[MR] Private Msg: {0}".F(match.Groups[1].Value)); Console.WriteLine("[MR] PMsg to {0}: {1}", msgClient.Name, match.Groups[1].Value); } } } } if (line.StartsWith("map ") && server.State != ServerState.GameStarted) { // lock(server.LobbyInfo) // { var mapID = line.Remove(0, 4); string.Format(mapID); // server.Map = server.ModData.MapCache[mapID];; // LobbyCommands.LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); Console.WriteLine("Changed map to {0}", mapID); server.SendMessage("[MR] Changed map to {0}".F(mapID)); // } } if (line == "help kick") { Console.WriteLine("Syntax: kick UserID"); } if (line.StartsWith("kick ")) { var aUID = line.Remove(0, 5); int kickUID; int.TryParse(aUID, out kickUID); var kickConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickUID); if (kickConn != null) { var kickClient = server.GetClient(kickConn); Console.WriteLine("Kicking CID {0} - {1}", kickUID.ToString(), kickClient.Name); server.SendMessage("[MR] Kicking CID {0} - {1}".F(kickUID.ToString(), kickClient.Name)); server.SendOrderTo(kickConn, "ServerError", "You were kicked by the console."); server.DropClient(kickConn); if (server.State != ServerState.GameStarted) { server.SyncLobbyClients(); server.SyncLobbySlots(); } } } if (line.StartsWith("tban ")) { var aUID = line.Remove(0, 5); int banUID; int.TryParse(aUID, out banUID); var banConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == banUID); if (banConn != null) { var banClient = server.GetClient(banConn); server.SendOrderTo(banConn, "ServerError", "You were temp banned by the console."); server.TempBans.Add(banClient.IPAddress); server.DropClient(banConn); Console.WriteLine("Tempbanning CID {0} - {1}", banUID.ToString(), banClient.Name); server.SendMessage("[MR] Tempbanning CID {0} - {1}".F(banUID.ToString(), banClient.Name)); if (server.State != ServerState.GameStarted) { server.SyncLobbyClients(); server.SyncLobbySlots(); } } } if (line.StartsWith("ipban ")) { string aIPstr = line.Remove(0, 5); Regex validIpV4AddressRegex = new Regex(@"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", RegexOptions.IgnoreCase); if (!string.IsNullOrWhiteSpace(aIPstr)) { bool flag = validIpV4AddressRegex.IsMatch(aIPstr.Trim()); if (flag) { server.TempBans.Add(aIPstr.Trim()); Console.WriteLine("TempIP Ban {0}", aIPstr.Trim()); Log.Write("server", "TempIP Ban {0}", aIPstr.Trim()); } else { Console.WriteLine("{0} is not a valid IP", aIPstr.ToString()); } } } if (line == "banlist") { foreach (var item in server.TempBans) { Console.WriteLine(item); } } if (line.StartsWith("admin ")) { var aUID = line.Remove(0, 6); int adminUID; int.TryParse(aUID, out adminUID); var adminConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == adminUID); if (adminConn != null) { var adminClient = server.GetClient(adminConn); adminClient.IsAdmin = true; Console.WriteLine("Setting Admin {0} - {1}]", adminUID.ToString(), adminClient.Name); server.SendMessage("[MR] Setting Admin {0} - {1}".F(adminUID.ToString(), adminClient.Name)); server.SendOrderTo(adminConn, "Message", "You have been set as an admin by the console"); if (server.State != ServerState.GameStarted) { server.SyncLobbyClients(); server.SyncLobbySlots(); } } } if (line.StartsWith("deladmin ")) { var aUID = line.Remove(0, 9); int adminUID; int.TryParse(aUID, out adminUID); var adminConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == adminUID); if (adminConn != null) { var adminClient = server.GetClient(adminConn); adminClient.IsAdmin = false; Console.WriteLine("Removing Admin {0} - {1}]", adminUID.ToString(), adminClient.Name); server.SendMessage("[MR] Removing Admin {0} - {1}".F(adminUID.ToString(), adminClient.Name)); server.SendOrderTo(adminConn, "Message", "Your admin status was revoked by the console"); if (server.State != ServerState.GameStarted) { server.SyncLobbyClients(); server.SyncLobbySlots(); } } } if (line == "status") { Console.WriteLine(string.Format("CurMap: {0} \n", server.Map.Title)); Console.WriteLine(string.Format("MapHash: {0} \n", server.LobbyInfo.GlobalSettings.Map)); Console.WriteLine(string.Format("CurConnections: {0} \n", server.LobbyInfo.Clients.Count())); Console.WriteLine(string.Format("MapMaxPlayers: {0} \n", server.LobbyInfo.Slots.Count())); Console.WriteLine(string.Format("GameState: {0} \n", server.State.ToString())); var testbuffer = server.Conns.ToArray(); foreach (var item in testbuffer) { var clientIdT = server.GetClient(item); // make the temporary array the client ID Console.WriteLine(string.Format("ID: {0} IP: {1} TEAM: {2} SPEC: {3}, NAME: {4} \n", clientIdT.Index.ToString(), clientIdT.IPAddress.ToString(), clientIdT.Team.ToString(), clientIdT.IsObserver.ToString(), clientIdT.Name.ToString())); } } } }
public void ClientJoined(S server, Connection conn) { 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); // 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); }