public void ClientJoined(S server, Connection newConn) { var defaults = new GameRules.PlayerSettings(); var client = new Session.Client() { Index = newConn.PlayerIndex, Color1 = defaults.Color1, Color2 = defaults.Color2, Name = defaults.Name, Country = "random", State = Session.ClientState.NotReady, SpawnPoint = 0, Team = 0, Slot = ChooseFreeSlot(server), }; var slotData = server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == client.Slot ); if (slotData != null) SyncClientToPlayerReference(client, server.Map.Players[slotData.MapPlayer]); server.lobbyInfo.Clients.Add(client); Log.Write("server", "Client {0}: Accepted connection from {1}", newConn.PlayerIndex, newConn.socket.RemoteEndPoint); server.SendChat(newConn, "has joined the game."); server.SyncLobbyInfo(); }
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]); 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], Race = "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} Developer Cheats." .F(client.Name, server.LobbyInfo.GlobalSettings.AllowCheats ? "allowed" : "disallowed")); 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} Shroud." .F(client.Name, server.LobbyInfo.GlobalSettings.Shroud ? "enabled" : "disabled")); 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"].Traits.WithInterface <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); } }, { "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); } }, { "race", 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 race changes if (server.LobbyInfo.Slots[targetClient.Slot].LockRace) { return(true); } targetClient.Race = 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)); }
static bool Map(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 map."); return(true); } var lastMap = server.LobbyInfo.GlobalSettings.Map; Action <MapPreview> selectMap = map => { lock (server.LobbyInfo) { // Make sure the map hasn't changed in the meantime if (server.LobbyInfo.GlobalSettings.Map != lastMap) { return; } server.LobbyInfo.GlobalSettings.Map = map.Uid; var oldSlots = server.LobbyInfo.Slots.Keys.ToArray(); server.Map = server.ModData.MapCache[server.LobbyInfo.GlobalSettings.Map]; server.LobbyInfo.Slots = server.Map.Players.Players .Select(p => MakeSlotFromPlayerReference(p.Value)) .Where(ss => ss != null) .ToDictionary(ss => ss.PlayerReference, ss => ss); LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); // Reset client states var selectableFactions = server.Map.Rules.Actors["world"].TraitInfos <FactionInfo>() .Where(f => f.Selectable) .Select(f => f.InternalName) .ToList(); foreach (var c in server.LobbyInfo.Clients) { c.State = Session.ClientState.Invalid; if (!selectableFactions.Contains(c.Faction)) { c.Faction = "Random"; } } // Reassign players into new slots based on their old slots: // - Observers remain as observers // - Players who now lack a slot are made observers // - Bots who now lack a slot are dropped // - Bots who are not defined in the map rules are dropped var botTypes = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Type); var slots = server.LobbyInfo.Slots.Keys.ToArray(); var i = 0; foreach (var os in oldSlots) { var c = server.LobbyInfo.ClientInSlot(os); if (c == null) { continue; } c.SpawnPoint = 0; c.Slot = i < slots.Length ? slots[i++] : null; if (c.Slot != null) { // Remove Bot from slot if slot forbids bots if (c.Bot != null && (!server.Map.Players.Players[c.Slot].AllowBots || !botTypes.Contains(c.Bot))) { server.LobbyInfo.Clients.Remove(c); } S.SyncClientToPlayerReference(c, server.Map.Players.Players[c.Slot]); } else if (c.Bot != null) { server.LobbyInfo.Clients.Remove(c); } else { c.Color = Color.White; } } // Validate if color is allowed and get an alternative if it isn't foreach (var c in server.LobbyInfo.Clients) { if (c.Slot != null && !server.LobbyInfo.Slots[c.Slot].LockColor) { c.Color = c.PreferredColor = SanitizePlayerColor(server, c.Color, c.Index, conn); } } server.LobbyInfo.DisabledSpawnPoints.Clear(); server.SyncLobbyInfo(); server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); if (server.Map.DefinesUnsafeCustomRules) { server.SendMessage("This map contains custom rules. Game experience may change."); } if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer) { server.SendMessage(server.TwoHumansRequiredText); } else if (server.Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { server.SendMessage("Bots have been disabled on this map."); } var briefing = MissionBriefingOrDefault(server); if (briefing != null) { server.SendMessage(briefing); } } }; Action queryFailed = () => server.SendOrderTo(conn, "Message", "Map was not found on server."); var m = server.ModData.MapCache[s]; if (m.Status == MapStatus.Available || m.Status == MapStatus.DownloadAvailable) { selectMap(m); } else if (server.Settings.QueryMapRepository) { server.SendOrderTo(conn, "Message", "Searching for map on the Resource Center..."); var mapRepository = server.ModData.Manifest.Get <WebServices>().MapRepository; server.ModData.MapCache.QueryRemoteMapDetails(mapRepository, new[] { s }, selectMap, queryFailed); } else { queryFailed(); } return(true); } }
public static void SetupReadyWidget(Widget parent, Session.Slot s, Session.Client c) { parent.Get <ImageWidget>("STATUS_IMAGE").IsVisible = () => c.IsReady || c.Bot != null; }
public static void SetupTeamWidget(Widget parent, Session.Slot s, Session.Client c) { parent.Get <LabelWidget>("TEAM").GetText = () => (c.Team == 0) ? "-" : c.Team.ToString(); }
public static void SetupNameWidget(Widget parent, Session.Slot s, Session.Client c) { var name = parent.Get <LabelWidget>("NAME"); name.GetText = () => c.Name; }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client { Name = OpenRA.Settings.SanitizedPlayerName(handshake.Client.Name), IpAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.PreferredColor, Color = handshake.Client.Color, Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin) }; if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); } else { client.Color = HSLColor.FromRGB(255, 255, 255); } if (ModData.Manifest.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Metadata.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } // Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); newConn.Validated = true; var clientPing = new Session.ClientPing { Index = client.Index }; LobbyInfo.ClientPings.Add(clientPing); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); Log.Write("server", "{0} ({1}) has joined the game.", client.Name, newConn.Socket.RemoteEndPoint); if (LobbyInfo.NonBotClients.Count() > 1) { SendMessage("{0} has joined the game.".F(client.Name)); } // Send initial ping SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); if (Dedicated) { var motdFile = Platform.ResolvePath(Platform.SupportDirPrefix, "motd.txt"); if (!File.Exists(motdFile)) { File.WriteAllText(motdFile, "Welcome, have fun and good luck!"); } var motd = File.ReadAllText(motdFile); if (!string.IsNullOrEmpty(motd)) { SendOrderTo(newConn, "Message", motd); } } if (Map.DefinesUnsafeCustomRules) { SendOrderTo(newConn, "Message", "This map contains custom rules. Game experience may change."); } if (!LobbyInfo.GlobalSettings.EnableSingleplayer) { SendOrderTo(newConn, "Message", TwoHumansRequiredText); } else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { SendOrderTo(newConn, "Message", "Bots have been disabled on this map."); } if (handshake.Mod == "{DEV_VERSION}") { SendMessage("{0} is running an unversioned development build, ".F(client.Name) + "and may desynchronize the game state if they have incompatible rules."); } } catch (Exception ex) { Log.Write("server", "Dropping connection {0} because an error occurred:", newConn.Socket.RemoteEndPoint); Log.Write("server", ex.ToString()); DropClient(newConn); } }
public static void ProcessOrder(OrderManager orderManager, World world, int clientId, Order order) { if (world != null) { if (!world.WorldActor.TraitsImplementing<IValidateOrder>().All(vo => vo.OrderValidation(orderManager, world, clientId, order))) return; } switch (order.OrderString) { case "Chat": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { var player = world != null ? world.FindPlayerByClient(client) : null; var suffix = (player != null && player.WinState == WinState.Lost) ? " (Dead)" : ""; Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + suffix, order.TargetString); } else Game.AddChatLine(Color.White, "(player {0})".F(clientId), order.TargetString); break; } case "Disconnected": /* reports that the target player disconnected */ { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { client.State = Session.ClientState.Disconnected; } break; } case "TeamChat": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { if (world == null) { if (client.Team == orderManager.LocalClient.Team) Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + " (Team)", order.TargetString); } else { var player = world.FindPlayerByClient(client); var display = player != null && (world.LocalPlayer != null && player.Stances[world.LocalPlayer] == Stance.Ally || player.WinState == WinState.Lost); if (display) { var suffix = (player != null && player.WinState == WinState.Lost) ? " (Dead)" : " (Team)"; Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + suffix, order.TargetString); } } } break; } case "StartGame": { Game.AddChatLine(Color.White, "Server", "The game has started."); Game.StartGame(orderManager.LobbyInfo.GlobalSettings.Map); break; } case "HandshakeRequest": { var request = HandshakeRequest.Deserialize(order.TargetString); // Check that the map exists on the client if (!Game.modData.AvailableMaps.ContainsKey(request.Map)) throw new InvalidOperationException("Missing map {0}".F(request.Map)); var info = new Session.Client() { Name = Game.Settings.Player.Name, ColorRamp = Game.Settings.Player.ColorRamp, Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady }; var localMods = orderManager.LobbyInfo.GlobalSettings.Mods.Select(m => "{0}@{1}".F(m,Mod.AllMods[m].Version)).ToArray(); var response = new HandshakeResponse() { Client = info, Mods = localMods, Password = "******" }; orderManager.IssueOrder(Order.HandshakeResponse(response.Serialize())); break; } case "ServerError": orderManager.ServerError = order.TargetString; break; case "SyncInfo": { orderManager.LobbyInfo = Session.Deserialize(order.TargetString); if (orderManager.FramesAhead != orderManager.LobbyInfo.GlobalSettings.OrderLatency && !orderManager.GameStarted) { orderManager.FramesAhead = orderManager.LobbyInfo.GlobalSettings.OrderLatency; Game.Debug( "Order lag is now {0} frames.".F(orderManager.LobbyInfo.GlobalSettings.OrderLatency)); } Game.SyncLobbyInfo(); break; } case "SetStance": { if (Game.orderManager.LobbyInfo.GlobalSettings.LockTeams) return; var targetPlayer = order.Player.World.players[order.TargetLocation.X]; var newStance = (Stance)order.TargetLocation.Y; SetPlayerStance(world, order.Player, targetPlayer, newStance); Game.Debug("{0} has set diplomatic stance vs {1} to {2}".F( order.Player.PlayerName, targetPlayer.PlayerName, newStance)); // automatically declare war reciprocally if (newStance == Stance.Enemy && targetPlayer.Stances[order.Player] == Stance.Ally) { SetPlayerStance(world, targetPlayer, order.Player, newStance); Game.Debug("{0} has reciprocated",targetPlayer.PlayerName); } break; } default: { if( !order.IsImmediate ) { var self = order.Subject; var health = self.TraitOrDefault<Health>(); if( health == null || !health.IsDead ) foreach( var t in self.TraitsImplementing<IResolveOrder>() ) t.ResolveOrder( self, order ); } break; } } }
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 Player(World world, Session.Client client, PlayerReference pr) { World = world; InternalName = pr.Name; PlayerReference = pr; inMissionMap = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector); // Real player or host-created bot if (client != null) { ClientIndex = client.Index; Color = client.Color; if (client.Bot != null) { var botInfo = world.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().First(b => b.Type == client.Bot); var botsOfSameType = world.LobbyInfo.Clients.Where(c => c.Bot == client.Bot).ToArray(); PlayerName = botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1); } else { PlayerName = client.Name; } BotType = client.Bot; Faction = ChooseFaction(world, client.Faction, !pr.LockFaction); DisplayFaction = ChooseDisplayFaction(world, client.Faction); } else { // Map player ClientIndex = 0; // Owned by the host (TODO: fix this) Color = pr.Color; PlayerName = pr.Name; NonCombatant = pr.NonCombatant; Playable = pr.Playable; Spectating = pr.Spectating; BotType = pr.Bot; Faction = ChooseFaction(world, pr.Faction, false); DisplayFaction = ChooseDisplayFaction(world, pr.Faction); } if (!Spectating) { PlayerMask = new LongBitSet <PlayerBitMask>(InternalName); } var playerActorType = world.Type == WorldType.Editor ? "EditorPlayer" : "Player"; PlayerActor = world.CreateActor(playerActorType, new TypeDictionary { new OwnerInit(this) }); Shroud = PlayerActor.Trait <Shroud>(); FrozenActorLayer = PlayerActor.TraitOrDefault <FrozenActorLayer>(); // Enable the bot logic on the host IsBot = BotType != null; if (IsBot && Game.IsHost) { var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType); if (logic == null) { Log.Write("debug", "Invalid bot type: {0}", BotType); } else { logic.Activate(this); } } stanceColors.Self = ChromeMetrics.Get <Color>("PlayerStanceColorSelf"); stanceColors.Allies = ChromeMetrics.Get <Color>("PlayerStanceColorAllies"); stanceColors.Enemies = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies"); stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals"); unlockRenderPlayer = PlayerActor.TraitsImplementing <IUnlocksRenderPlayer>().ToArray(); }
public static void ProcessOrder(OrderManager orderManager, World world, int clientId, Order order) { if (world != null) { if (!world.WorldActor.TraitsImplementing<IValidateOrder>().All(vo => vo.OrderValidation(orderManager, world, clientId, order))) return; } switch (order.OrderString) { case "Chat": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { var player = world != null ? world.FindPlayerByClient(client) : null; var suffix = (player != null && player.WinState == WinState.Lost) ? " (Dead)" : ""; suffix = client.IsObserver ? " (Spectator)" : suffix; Game.AddChatLine(client.Color.RGB, client.Name + suffix, order.TargetString); } else Game.AddChatLine(Color.White, "(player {0})".F(clientId), order.TargetString); break; } case "Message": // Server message Game.AddChatLine(Color.White, "Server", order.TargetString); break; case "Disconnected": /* reports that the target player disconnected */ { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) client.State = Session.ClientState.Disconnected; break; } case "TeamChat": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { if (world == null) { if (orderManager.LocalClient != null && client.Team == orderManager.LocalClient.Team) Game.AddChatLine(client.Color.RGB, client.Name + " (Team)", order.TargetString); } else { var player = world.FindPlayerByClient(client); if (player == null) return; if (world.LocalPlayer != null && player.Stances[world.LocalPlayer] == Stance.Ally || player.WinState == WinState.Lost) { var suffix = player.WinState == WinState.Lost ? " (Dead)" : " (Team)"; Game.AddChatLine(client.Color.RGB, client.Name + suffix, order.TargetString); } } } break; } case "StartGame": { Game.AddChatLine(Color.White, "Server", "The game has started."); Game.StartGame(orderManager.LobbyInfo.GlobalSettings.Map, false); break; } case "PauseGame": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { var pause = order.TargetString == "Pause"; if (orderManager.world.Paused != pause && !world.LobbyInfo.IsSinglePlayer) { var pausetext = "The game is {0} by {1}".F(pause ? "paused" : "un-paused", client.Name); Game.AddChatLine(Color.White, "", pausetext); } orderManager.world.Paused = pause; orderManager.world.PredictedPaused = pause; } break; } case "HandshakeRequest": { // TODO: Switch to the server's mod if we have it // Otherwise send the handshake with our current settings and let the server reject us var mod = Game.modData.Manifest.Mod; var info = new Session.Client() { Name = Game.Settings.Player.Name, PreferredColor = Game.Settings.Player.Color, Color = Game.Settings.Player.Color, Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid }; var response = new HandshakeResponse() { Client = info, Mod = mod.Id, Version = mod.Version, Password = orderManager.Password }; orderManager.IssueOrder(Order.HandshakeResponse(response.Serialize())); break; } case "ServerError": { orderManager.ServerError = order.TargetString; orderManager.AuthenticationFailed = false; break; } case "AuthenticationError": { orderManager.ServerError = order.TargetString; orderManager.AuthenticationFailed = true; break; } case "SyncInfo": { orderManager.LobbyInfo = Session.Deserialize(order.TargetString); SetOrderLag(orderManager); Game.SyncLobbyInfo(); break; } case "SyncLobbyClients": { var clients = new List<Session.Client>(); var nodes = MiniYaml.FromString(order.TargetString); foreach (var node in nodes) { var strings = node.Key.Split('@'); if (strings[0] == "Client") clients.Add(Session.Client.Deserialize(node.Value)); } orderManager.LobbyInfo.Clients = clients; Game.SyncLobbyInfo(); break; } case "SyncLobbySlots": { var slots = new Dictionary<string, Session.Slot>(); var nodes = MiniYaml.FromString(order.TargetString); foreach (var node in nodes) { var strings = node.Key.Split('@'); if (strings[0] == "Slot") { var slot = Session.Slot.Deserialize(node.Value); slots.Add(slot.PlayerReference, slot); } } orderManager.LobbyInfo.Slots = slots; Game.SyncLobbyInfo(); break; } case "SyncLobbyGlobalSettings": { var nodes = MiniYaml.FromString(order.TargetString); foreach (var node in nodes) { var strings = node.Key.Split('@'); if (strings[0] == "GlobalSettings") orderManager.LobbyInfo.GlobalSettings = Session.Global.Deserialize(node.Value); } SetOrderLag(orderManager); Game.SyncLobbyInfo(); break; } case "SyncClientPings": { var pings = new List<Session.ClientPing>(); var nodes = MiniYaml.FromString(order.TargetString); foreach (var node in nodes) { var strings = node.Key.Split('@'); if (strings[0] == "ClientPing") pings.Add(Session.ClientPing.Deserialize(node.Value)); } orderManager.LobbyInfo.ClientPings = pings; break; } case "SetStance": { if (!Game.orderManager.LobbyInfo.GlobalSettings.FragileAlliances) return; var targetPlayer = order.Player.World.Players.FirstOrDefault(p => p.InternalName == order.TargetString); var newStance = (Stance)order.TargetLocation.X; SetPlayerStance(world, order.Player, targetPlayer, newStance); Game.Debug("{0} has set diplomatic stance vs {1} to {2}".F( order.Player.PlayerName, targetPlayer.PlayerName, newStance)); // automatically declare war reciprocally if (newStance == Stance.Enemy && targetPlayer.Stances[order.Player] == Stance.Ally) { SetPlayerStance(world, targetPlayer, order.Player, newStance); Game.Debug("{0} has reciprocated",targetPlayer.PlayerName); } break; } case "Ping": { orderManager.IssueOrder(Order.Pong(order.TargetString)); break; } default: { if (!order.IsImmediate) { var self = order.Subject; var health = self.TraitOrDefault<Health>(); if (health == null || !health.IsDead) foreach (var t in self.TraitsImplementing<IResolveOrder>()) t.ResolveOrder(self, order); } break; } } }
public static void SetupEditableSlotWidget(LobbyLogic logic, Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager) { var slot = parent.Get <DropDownButtonWidget>("SLOT_OPTIONS"); slot.IsVisible = () => true; slot.IsDisabled = () => orderManager.LocalClient.IsReady; slot.GetText = () => c != null ? c.Name : s.Closed ? "Closed" : "Open"; slot.OnMouseDown = _ => ShowSlotDropDown(logic, slot, s, c, orderManager); // Ensure Name selector (if present) is hidden var name = parent.GetOrNull("NAME"); if (name != null) { name.IsVisible = () => false; } }
public void Bind(OrderManager orderManager, WorldRenderer worldRenderer, Session.Client client) { this.orderManager = orderManager; this.worldRenderer = worldRenderer; this.client = client; }
public AnonymousProfileTooltipLogic(Widget widget, OrderManager orderManager, Session.Client client) { var address = LobbyUtils.GetExternalIP(client, orderManager); var cachedDescriptiveIP = address ?? "Unknown IP"; var nameLabel = widget.Get <LabelWidget>("NAME"); var nameFont = Game.Renderer.Fonts[nameLabel.Font]; widget.Bounds.Width = nameFont.Measure(nameLabel.Text).X + 2 * nameLabel.Bounds.Left; var ipLabel = widget.Get <LabelWidget>("IP"); ipLabel.GetText = () => cachedDescriptiveIP; var locationLabel = widget.Get <LabelWidget>("LOCATION"); var cachedCountryLookup = GeoIP.LookupCountry(address); locationLabel.GetText = () => cachedCountryLookup; if (client.IsAdmin) { var adminLabel = widget.Get("GAME_ADMIN"); adminLabel.IsVisible = () => client.IsAdmin; widget.Bounds.Height += adminLabel.Bounds.Height; } }
public RegisteredProfileTooltipLogic(Widget widget, WorldRenderer worldRenderer, ModData modData, Session.Client client) { playerDatabase = modData.Manifest.Get <PlayerDatabase>(); var header = widget.Get("HEADER"); var badgeContainer = widget.Get("BADGES_CONTAINER"); var badgeSeparator = badgeContainer.GetOrNull("SEPARATOR"); var profileHeader = header.Get("PROFILE_HEADER"); var messageHeader = header.Get("MESSAGE_HEADER"); var message = messageHeader.Get <LabelWidget>("MESSAGE"); var messageFont = Game.Renderer.Fonts[message.Font]; profileHeader.IsVisible = () => profileLoaded; messageHeader.IsVisible = () => !profileLoaded; var profileWidth = 0; var messageText = "Loading player profile..."; var messageWidth = messageFont.Measure(messageText).X + 2 * message.Bounds.Left; Action <DownloadDataCompletedEventArgs> onQueryComplete = i => { try { if (i.Error == null) { var yaml = MiniYaml.FromString(Encoding.UTF8.GetString(i.Result)).First(); if (yaml.Key == "Player") { profile = FieldLoader.Load <PlayerProfile>(yaml.Value); Game.RunAfterTick(() => { var nameLabel = profileHeader.Get <LabelWidget>("PROFILE_NAME"); var nameFont = Game.Renderer.Fonts[nameLabel.Font]; var rankLabel = profileHeader.Get <LabelWidget>("PROFILE_RANK"); var rankFont = Game.Renderer.Fonts[rankLabel.Font]; var adminContainer = profileHeader.Get("GAME_ADMIN"); var adminLabel = adminContainer.Get <LabelWidget>("LABEL"); var adminFont = Game.Renderer.Fonts[adminLabel.Font]; var headerSizeOffset = profileHeader.Bounds.Height - messageHeader.Bounds.Height; nameLabel.GetText = () => profile.ProfileName; rankLabel.GetText = () => profile.ProfileRank; profileWidth = Math.Max(profileWidth, nameFont.Measure(profile.ProfileName).X + 2 * nameLabel.Bounds.Left); profileWidth = Math.Max(profileWidth, rankFont.Measure(profile.ProfileRank).X + 2 * rankLabel.Bounds.Left); header.Bounds.Height += headerSizeOffset; badgeContainer.Bounds.Y += header.Bounds.Height; if (client.IsAdmin) { profileWidth = Math.Max(profileWidth, adminFont.Measure(adminLabel.Text).X + 2 * adminLabel.Bounds.Left); adminContainer.IsVisible = () => true; profileHeader.Bounds.Height += adminLabel.Bounds.Height; header.Bounds.Height += adminLabel.Bounds.Height; badgeContainer.Bounds.Y += adminLabel.Bounds.Height; } Func <int, int> negotiateWidth = badgeWidth => { profileWidth = Math.Min(Math.Max(badgeWidth, profileWidth), widget.Bounds.Width); return(profileWidth); }; if (profile.Badges.Any()) { var badges = Ui.LoadWidget("PLAYER_PROFILE_BADGES_INSERT", badgeContainer, new WidgetArgs() { { "worldRenderer", worldRenderer }, { "profile", profile }, { "negotiateWidth", negotiateWidth } }); if (badges.Bounds.Height > 0) { badgeContainer.Bounds.Height = badges.Bounds.Height; badgeContainer.IsVisible = () => true; } } profileWidth = Math.Min(profileWidth, widget.Bounds.Width); header.Bounds.Width = widget.Bounds.Width = badgeContainer.Bounds.Width = profileWidth; widget.Bounds.Height = header.Bounds.Height + badgeContainer.Bounds.Height; if (badgeSeparator != null) { badgeSeparator.Bounds.Width = profileWidth - 2 * badgeSeparator.Bounds.X; } profileLoaded = true; }); } } } catch (Exception e) { Log.Write("debug", "Failed to parse player data result with exception: {0}", e); } finally { if (profile == null) { messageText = "Failed to load player profile."; messageWidth = messageFont.Measure(messageText).X + 2 * message.Bounds.Left; header.Bounds.Width = widget.Bounds.Width = messageWidth; } } }; message.GetText = () => messageText; header.Bounds.Height += messageHeader.Bounds.Height; header.Bounds.Width = widget.Bounds.Width = messageWidth; widget.Bounds.Height = header.Bounds.Height; badgeContainer.Visible = false; new Download(playerDatabase.Profile + client.Fingerprint, _ => { }, onQueryComplete); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); var client = new Session.Client() { Name = handshake.Client.Name, IpAddress = ((IPEndPoint)newConn.socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = lobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.Color, Color = handshake.Client.Color, Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, IsAdmin = !lobbyInfo.Clients.Any(c1 => c1.IsAdmin) }; if (client.Slot != null) SyncClientToPlayerReference(client, Map.Players[client.Slot]); else client.Color = HSLColor.FromRGB(255, 255, 255); // Check that the client has compatible mods var mods = handshake.Mods; var validMod = mods.All(m => m.Contains('@')) && //valid format mods.Count() == Game.CurrentMods.Count() && //same number mods.Select(m => Pair.New(m.Split('@')[0], m.Split('@')[1])).All(kv => Game.CurrentMods.ContainsKey(kv.First)); if (!validMod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Your mods don't match the server"); DropClient(newConn); return; } var validVersion = mods.Select(m => Pair.New(m.Split('@')[0], m.Split('@')[1])).All( kv => kv.Second == Game.CurrentMods[kv.First].Version); if (!validVersion && !lobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Not running the same version."); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You are {0} from the server.".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } // Promote connection to a valid client preConns.Remove(newConn); conns.Add(newConn); lobbyInfo.Clients.Add(client); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.socket.RemoteEndPoint); foreach (var t in ServerTraits.WithInterface<IClientJoined>()) t.ClientJoined(this, newConn); SyncLobbyInfo(); SendMessage("{0} has joined the server.".F(client.Name)); // Send initial ping SendOrderTo(newConn, "Ping", Environment.TickCount.ToString()); if (File.Exists("{0}motd_{1}.txt".F(Platform.SupportDir, lobbyInfo.GlobalSettings.Mods[0]))) { var motd = System.IO.File.ReadAllText("{0}motd_{1}.txt".F(Platform.SupportDir, lobbyInfo.GlobalSettings.Mods[0])); SendOrderTo(newConn, "Message", motd); } if (mods.Any(m => m.Contains("{DEV_VERSION}"))) SendMessage("{0} is running an unversioned development build, ".F(client.Name) + "and may desynchronize the game state if they have incompatible rules."); SetOrderLag(); } catch (Exception) { DropClient(newConn); } }
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 static void SetupEditableStartCashWidget(Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager, WorldRenderer worldRenderer, Dictionary <string, LobbyFaction> factions) { var name = parent.Get <TextFieldWidget>("STARTCASH"); LobbyFaction fact = factions[c.Faction]; name.IsVisible = () => true; name.IsDisabled = () => orderManager.LocalClient.IsReady; //name.Text = c.StartCash.ToString(); if (c.StartCash == 0) { c.StartCash = fact.StartCash; //orderManager.IssueOrder(Order.Command("startcash " + name.Text)); } name.Text = c.StartCash.ToString(); var escPressed = false; name.OnLoseFocus = () => { if (escPressed) { escPressed = false; return; } name.Text = name.Text.Trim(); if (name.Text.Length == 0) { name.Text = c.StartCash.ToString(); } else if (name.Text != c.StartCash.ToString()) { //name.Text = Settings.SanitizedPlayerName(name.Text); //добавить позже проверку на валидность orderManager.IssueOrder(Order.Command("startcash " + name.Text)); //Game.Settings.Player. = name.Text; //Game.Settings.Save(); } }; name.OnEnterKey = () => { name.YieldKeyboardFocus(); return(true); }; name.OnEscKey = () => { name.Text = c.StartCash.ToString(); escPressed = true; name.YieldKeyboardFocus(); return(true); }; SetupProfileWidget(name, c, orderManager, worldRenderer); //HideChildWidget(parent, "SLOT_OPTIONS"); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client { Name = EW.Settings.SanitizedPlayerName(handshake.Client.Name), IpAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.PreferredColor, Color = handshake.Client.Color, Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, IsAdmin = !LobbyInfo.Clients.Any(cl => cl.IsAdmin) }; if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); } else { client.Color = HSLColor.FromRGB(255, 255, 255); } if (ModData.Manifest.Id != handshake.Mod) { SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Metadata.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } //Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } //Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); newConn.Validated = true; var clientPing = new Session.ClientPing { Index = client.Index }; LobbyInfo.ClientPings.Add(clientPing); foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); if (LobbyInfo.NonBotClients.Count() > 1) { SendMessage("{0} has joined the game".F(client.Name)); } SendOrderTo(newConn, "Ping", WarGame.RunTime.ToString(CultureInfo.InvariantCulture)); if (Dedicated) { } if (Map.DefinesUnsafeCustomRules) { SendOrderTo(newConn, "Message", "This map contains custom rules.Game experience may change."); } if (!LobbyInfo.GlobalSettings.EnableSinglePlayer) { SendOrderTo(newConn, "Message", TwoHumansRequiredText); } else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { SendOrderTo(newConn, "Message", "Bots have been disabled on this map"); } } catch (Exception ex) { DropClient(newConn); } }
public bool InterpretCommand(Server server, Connection conn, Session.Client client, string cmd) { Console.WriteLine("Server received command from player {1}: {0}", cmd, conn.PlayerIndex); return(false); }
public bool InterpretCommand(S server, EW.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; 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.NonBotPlayers.Count() < 2) { server.SendOrderTo(conn, "Message", server.TwoHumansRequiredText); return(true); } server.StartGame(); 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)) { return(false); } // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client"); return(true); } var botType = parts[2]; var botInfo = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().FirstOrDefault(b => b.Type == botType); if (botInfo == null) { server.SendOrderTo(conn, "Message", "Invalid bot type."); return(true); } slot.Closed = false; if (bot == null) { //Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botInfo.Name, Bot = botType, Slot = parts[0], Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex, }; // Pick a random color for the bot var validator = server.ModData.Manifest.Get <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 = botInfo.Name; 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 => { 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; } var botTypes = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Type); var slots = server.LobbyInfo.Slots.Keys.ToArray(); var i = 0; foreach (var os in oldSlots) { var c = server.LobbyInfo.ClientInSlot(os); if (c == null) { continue; } c.SpawnPoint = 0; c.Slot = i < slots.Length?slots[i++]:null; if (c.Slot != null) { if (c.Bot != null && (!server.Map.Players.Players[c.Slot].AllowBots || !botTypes.Contains(c.Bot))) { server.LobbyInfo.Clients.Remove(c); } S.SyncClientToPlayerReference(c, server.Map.Players.Players[c.Slot]); } else if (c.Bot != null) { server.LobbyInfo.Clients.Remove(c); } } foreach (var c in server.LobbyInfo.Clients) { if (c.Slot != null && !server.LobbyInfo.Slots[c.Slot].LockColor) { c.Color = c.PreferredColor = SanitizePlayerColor(server, c.Color, c.Index, conn); } } server.SyncLobbyInfo(); server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); if (!server.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) { } else { queryFailed(); } 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 Player(World world, Session.Client client, PlayerReference pr, MersenneTwister playerRandom) { World = world; InternalName = pr.Name; PlayerReference = pr; inMissionMap = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector); // Real player or host-created bot if (client != null) { ClientIndex = client.Index; Color = client.Color; PlayerName = ResolvePlayerName(client, world.LobbyInfo.Clients, world.Map.Rules.Actors[SystemActors.Player].TraitInfos <IBotInfo>()); BotType = client.Bot; Faction = ResolveFaction(world, client.Faction, playerRandom, !pr.LockFaction); DisplayFaction = ResolveDisplayFaction(world, client.Faction); var assignSpawnPoints = world.WorldActor.TraitOrDefault <IAssignSpawnPoints>(); HomeLocation = assignSpawnPoints?.AssignHomeLocation(world, client, playerRandom) ?? pr.HomeLocation; SpawnPoint = assignSpawnPoints?.SpawnPointForPlayer(this) ?? client.SpawnPoint; DisplaySpawnPoint = client.SpawnPoint; Handicap = client.Handicap; } else { // Map player ClientIndex = world.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin)?.Index ?? 0; // Owned by the host (TODO: fix this) Color = pr.Color; PlayerName = pr.Name; NonCombatant = pr.NonCombatant; Playable = pr.Playable; spectating = pr.Spectating; BotType = pr.Bot; Faction = ResolveFaction(world, pr.Faction, playerRandom, false); DisplayFaction = ResolveDisplayFaction(world, pr.Faction); HomeLocation = pr.HomeLocation; SpawnPoint = DisplaySpawnPoint = 0; Handicap = pr.Handicap; } if (!spectating) { PlayerMask = new LongBitSet <PlayerBitMask>(InternalName); } // Set this property before running any Created callbacks on the player actor IsBot = BotType != null; // Special case handling is required for the Player actor: // Since Actor.Created would be called before PlayerActor is assigned here // querying player traits in INotifyCreated.Created would crash. // Therefore assign the uninitialized actor and run the Created callbacks // by calling Initialize ourselves. var playerActorType = world.Type == WorldType.Editor ? SystemActors.EditorPlayer : SystemActors.Player; PlayerActor = new Actor(world, playerActorType.ToString(), new TypeDictionary { new OwnerInit(this) }); PlayerActor.Initialize(true); Shroud = PlayerActor.Trait <Shroud>(); FrozenActorLayer = PlayerActor.TraitOrDefault <FrozenActorLayer>(); // Enable the bot logic on the host if (IsBot && Game.IsHost) { var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType); if (logic == null) { Log.Write("debug", "Invalid bot type: {0}", BotType); } else { logic.Activate(this); } } stanceColors.Self = ChromeMetrics.Get <Color>("PlayerStanceColorSelf"); stanceColors.Allies = ChromeMetrics.Get <Color>("PlayerStanceColorAllies"); stanceColors.Enemies = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies"); stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals"); unlockRenderPlayer = PlayerActor.TraitsImplementing <IUnlocksRenderPlayer>().ToArray(); notifyDisconnected = PlayerActor.TraitsImplementing <INotifyPlayerDisconnected>().ToArray(); }
public static void SetupColorWidget(Widget parent, Session.Slot s, Session.Client c) { var color = parent.Get <ColorBlockWidget>("COLORBLOCK"); color.GetColor = () => c.Color.RGB; }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client() { Name = handshake.Client.Name, IpAddress = ((IPEndPoint)newConn.socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.Color, Color = handshake.Client.Color, Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin) }; if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players[client.Slot]); } else { client.Color = HSLColor.FromRGB(255, 255, 255); } if (ModData.Manifest.Mod.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Mod.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } // Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); var clientPing = new Session.ClientPing(); clientPing.Index = client.Index; LobbyInfo.ClientPings.Add(clientPing); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.socket.RemoteEndPoint); foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); SendMessage("{0} has joined the game.".F(client.Name)); // Send initial ping SendOrderTo(newConn, "Ping", Game.RunTime.ToString()); if (Settings.Dedicated) { var motdFile = Platform.ResolvePath("^", "motd.txt"); if (!File.Exists(motdFile)) { System.IO.File.WriteAllText(motdFile, "Welcome, have fun and good luck!"); } var motd = System.IO.File.ReadAllText(motdFile); if (!string.IsNullOrEmpty(motd)) { SendOrderTo(newConn, "Message", motd); } } if (handshake.Mod == "{DEV_VERSION}") { SendMessage("{0} is running an unversioned development build, ".F(client.Name) + "and may desynchronize the game state if they have incompatible rules."); } SetOrderLag(); } catch (Exception) { DropClient(newConn); } }
public static void SetupSpawnWidget(Widget parent, Session.Slot s, Session.Client c) { parent.Get <LabelWidget>("SPAWN").GetText = () => (c.SpawnPoint == 0) ? "-" : Convert.ToChar('A' - 1 + c.SpawnPoint).ToString(); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var ipAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address; var client = new Session.Client { Name = OpenRA.Settings.SanitizedPlayerName(handshake.Client.Name), IPAddress = ipAddress.ToString(), AnonymizedIPAddress = Type != ServerType.Local && Settings.ShareAnonymizedIPs ? Session.AnonymizeIP(ipAddress) : null, Location = GeoIP.LookupCountry(ipAddress), Index = newConn.PlayerIndex, PreferredColor = handshake.Client.PreferredColor, Color = handshake.Client.Color, Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, }; if (ModData.Manifest.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Metadata.Version != handshake.Version) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } if (handshake.OrdersProtocol != ProtocolVersion.Orders) { Log.Write("server", "Rejected connection from {0}; incompatible Orders protocol version {1}.", newConn.Socket.RemoteEndPoint, handshake.OrdersProtocol); SendOrderTo(newConn, "ServerError", "Server is running an incompatible protocol"); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IPAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IPAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } Action completeConnection = () => { client.Slot = LobbyInfo.FirstEmptySlot(); client.IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin); if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); } else { client.Color = Color.White; } // Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); newConn.Validated = true; var clientPing = new Session.ClientPing { Index = client.Index }; LobbyInfo.ClientPings.Add(clientPing); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); if (client.Fingerprint != null) { Log.Write("server", "Client {0}: Player fingerprint is {1}.", newConn.PlayerIndex, client.Fingerprint); } foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); Log.Write("server", "{0} ({1}) has joined the game.", client.Name, newConn.Socket.RemoteEndPoint); // Report to all other players SendMessage("{0} has joined the game.".F(client.Name), newConn); // Send initial ping SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); if (Type == ServerType.Dedicated) { var motdFile = Platform.ResolvePath(Platform.SupportDirPrefix, "motd.txt"); if (!File.Exists(motdFile)) { File.WriteAllText(motdFile, "Welcome, have fun and good luck!"); } var motd = File.ReadAllText(motdFile); if (!string.IsNullOrEmpty(motd)) { SendOrderTo(newConn, "Message", motd); } } if (Map.DefinesUnsafeCustomRules) { SendOrderTo(newConn, "Message", "This map contains custom rules. Game experience may change."); } if (!LobbyInfo.GlobalSettings.EnableSingleplayer) { SendOrderTo(newConn, "Message", TwoHumansRequiredText); } else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { SendOrderTo(newConn, "Message", "Bots have been disabled on this map."); } }; if (Type == ServerType.Local) { // Local servers can only be joined by the local client, so we can trust their identity without validation client.Fingerprint = handshake.Fingerprint; completeConnection(); } else if (!string.IsNullOrEmpty(handshake.Fingerprint) && !string.IsNullOrEmpty(handshake.AuthSignature)) { waitingForAuthenticationCallback++; Action <DownloadDataCompletedEventArgs> onQueryComplete = i => { PlayerProfile profile = null; if (i.Error == null) { try { var yaml = MiniYaml.FromString(Encoding.UTF8.GetString(i.Result)).First(); if (yaml.Key == "Player") { profile = FieldLoader.Load <PlayerProfile>(yaml.Value); var publicKey = Encoding.ASCII.GetString(Convert.FromBase64String(profile.PublicKey)); var parameters = CryptoUtil.DecodePEMPublicKey(publicKey); if (!profile.KeyRevoked && CryptoUtil.VerifySignature(parameters, newConn.AuthToken, handshake.AuthSignature)) { client.Fingerprint = handshake.Fingerprint; Log.Write("server", "{0} authenticated as {1} (UID {2})", newConn.Socket.RemoteEndPoint, profile.ProfileName, profile.ProfileID); } else if (profile.KeyRevoked) { profile = null; Log.Write("server", "{0} failed to authenticate as {1} (key revoked)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint); } else { profile = null; Log.Write("server", "{0} failed to authenticate as {1} (signature verification failed)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint); } } else { Log.Write("server", "{0} failed to authenticate as {1} (invalid server response: `{2}` is not `Player`)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint, yaml.Key); } } catch (Exception ex) { Log.Write("server", "{0} failed to authenticate as {1} (exception occurred)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint); Log.Write("server", ex.ToString()); } } else { Log.Write("server", "{0} failed to authenticate as {1} (server error: `{2}`)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint, i.Error); } delayedActions.Add(() => { var notAuthenticated = Type == ServerType.Dedicated && profile == null && (Settings.RequireAuthentication || Settings.ProfileIDWhitelist.Any()); var blacklisted = Type == ServerType.Dedicated && profile != null && Settings.ProfileIDBlacklist.Contains(profile.ProfileID); var notWhitelisted = Type == ServerType.Dedicated && Settings.ProfileIDWhitelist.Any() && (profile == null || !Settings.ProfileIDWhitelist.Contains(profile.ProfileID)); if (notAuthenticated) { Log.Write("server", "Rejected connection from {0}; Not authenticated.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server requires players to have an OpenRA forum account"); DropClient(newConn); } else if (blacklisted || notWhitelisted) { if (blacklisted) { Log.Write("server", "Rejected connection from {0}; In server blacklist.", newConn.Socket.RemoteEndPoint); } else { Log.Write("server", "Rejected connection from {0}; Not in server whitelist.", newConn.Socket.RemoteEndPoint); } SendOrderTo(newConn, "ServerError", "You do not have permission to join this server"); DropClient(newConn); } else { completeConnection(); } waitingForAuthenticationCallback--; }, 0); }; new Download(playerDatabase.Profile + handshake.Fingerprint, _ => { }, onQueryComplete); } else { if (Type == ServerType.Dedicated && (Settings.RequireAuthentication || Settings.ProfileIDWhitelist.Any())) { Log.Write("server", "Rejected connection from {0}; Not authenticated.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server requires players to have an OpenRA forum account"); DropClient(newConn); } else { completeConnection(); } } } catch (Exception ex) { Log.Write("server", "Dropping connection {0} because an error occurred:", newConn.Socket.RemoteEndPoint); Log.Write("server", ex.ToString()); DropClient(newConn); } }
static bool SlotBot(S server, Connection conn, Session.Client client, string s) { lock (server.LobbyInfo) { 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]); if (!Exts.TryParseIntegerInvariant(parts[1], out var controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return(false); } // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); return(true); } var botType = parts[2]; var botInfo = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>() .FirstOrDefault(b => b.Type == botType); if (botInfo == null) { server.SendOrderTo(conn, "Message", "Invalid bot type."); return(true); } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botInfo.Name, Bot = botType, Slot = parts[0], Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex }; // Pick a random color for the bot var validator = server.ModData.Manifest.Get <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) .Concat(server.Map.Players.Players.Values.Select(p => p.Color)); bot.Color = bot.PreferredColor = validator.RandomPresetColor(server.Random, terrainColors, playerColors); server.LobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botInfo.Name; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players.Players[parts[0]]); server.SyncLobbyClients(); server.SyncLobbySlots(); return(true); } }
void InterpretServerOrder(Connection conn, Order o) { // Only accept handshake responses from unvalidated clients // Anything else may be an attempt to exploit the server if (!conn.Validated) { if (o.OrderString == "HandshakeResponse") { ValidateClient(conn, o.TargetString); } else { Log.Write("server", "Rejected connection from {0}; Order `{1}` is not a `HandshakeResponse`.", conn.Socket.RemoteEndPoint, o.OrderString); DropClient(conn); } return; } switch (o.OrderString) { case "Command": { var handledBy = serverTraits.WithInterface <IInterpretCommand>() .FirstOrDefault(t => t.InterpretCommand(this, conn, GetClient(conn), o.TargetString)); if (handledBy == null) { Log.Write("server", "Unknown server command: {0}", o.TargetString); SendOrderTo(conn, "Message", "Unknown server command: {0}".F(o.TargetString)); } break; } case "Chat": DispatchOrdersToClients(conn, 0, o.Serialize()); break; case "Pong": { long pingSent; if (!OpenRA.Exts.TryParseInt64Invariant(o.TargetString, out pingSent)) { Log.Write("server", "Invalid order pong payload: {0}", o.TargetString); break; } var client = GetClient(conn); if (client == null) { return; } var pingFromClient = LobbyInfo.PingFromClient(client); if (pingFromClient == null) { return; } var history = pingFromClient.LatencyHistory.ToList(); history.Add(Game.RunTime - pingSent); // Cap ping history at 5 values (25 seconds) if (history.Count > 5) { history.RemoveRange(0, history.Count - 5); } pingFromClient.Latency = history.Sum() / history.Count; pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2; pingFromClient.LatencyHistory = history.ToArray(); SyncClientPing(); break; } case "GameSaveTraitData": { if (GameSave != null) { var data = MiniYaml.FromString(o.TargetString)[0]; GameSave.AddTraitData(int.Parse(data.Key), data.Value); } break; } case "CreateGameSave": { if (GameSave != null) { // Sanitize potentially malicious input var filename = o.TargetString; var invalidIndex = -1; var invalidChars = Path.GetInvalidFileNameChars(); while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1) { filename = filename.Remove(invalidIndex, 1); } var baseSavePath = Platform.ResolvePath( Platform.SupportDirPrefix, "Saves", ModData.Manifest.Id, ModData.Manifest.Metadata.Version); if (!Directory.Exists(baseSavePath)) { Directory.CreateDirectory(baseSavePath); } GameSave.Save(Path.Combine(baseSavePath, filename)); DispatchOrdersToClients(null, 0, Order.FromTargetString("GameSaved", filename, true).Serialize()); } break; } case "LoadGameSave": { if (Type == ServerType.Dedicated || State >= ServerState.GameStarted) { break; } // Sanitize potentially malicious input var filename = o.TargetString; var invalidIndex = -1; var invalidChars = Path.GetInvalidFileNameChars(); while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1) { filename = filename.Remove(invalidIndex, 1); } var savePath = Platform.ResolvePath( Platform.SupportDirPrefix, "Saves", ModData.Manifest.Id, ModData.Manifest.Metadata.Version, filename); GameSave = new GameSave(savePath); LobbyInfo.GlobalSettings = GameSave.GlobalSettings; LobbyInfo.Slots = GameSave.Slots; // Reassign clients to slots // - Bot ordering is preserved // - Humans are assigned on a first-come-first-serve basis // - Leftover humans become spectators // Start by removing all bots and assigning all players as spectators foreach (var c in LobbyInfo.Clients) { if (c.Bot != null) { LobbyInfo.Clients.Remove(c); var ping = LobbyInfo.PingFromClient(c); if (ping != null) { LobbyInfo.ClientPings.Remove(ping); } } else { c.Slot = null; } } // Rebuild/remap the saved client state // TODO: Multiplayer saves should leave all humans as spectators so they can manually pick slots var adminClientIndex = LobbyInfo.Clients.First(c => c.IsAdmin).Index; foreach (var kv in GameSave.SlotClients) { if (kv.Value.Bot != null) { var bot = new Session.Client() { Index = ChooseFreePlayerIndex(), State = Session.ClientState.NotReady, BotControllerClientIndex = adminClientIndex }; kv.Value.ApplyTo(bot); LobbyInfo.Clients.Add(bot); } else { // This will throw if the server doesn't have enough human clients to fill all player slots // See TODO above - this isn't a problem in practice because MP saves won't use this var client = LobbyInfo.Clients.First(c => c.Slot == null); kv.Value.ApplyTo(client); } } SyncLobbyInfo(); SyncLobbyClients(); SyncClientPing(); break; } } }
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.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(' '); if (split.Length < 2 || !options.TryGetValue(split[0], out var option) || !option.Values.ContainsKey(split[1])) { server.SendOrderTo(conn, "Message", "Invalid configuration command."); return(true); } if (option.IsLocked) { server.SendOrderTo(conn, "Message", "{0} cannot be changed.".F(option.Name)); return(true); } var oo = server.LobbyInfo.GlobalSettings.LobbyOptions[option.Id]; if (oo.Value == split[1]) { return(true); } oo.Value = oo.PreferredValue = split[1]; if (option.Id == "gamespeed") { var speed = server.ModData.Manifest.Get <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])); foreach (var c in server.LobbyInfo.Clients) { c.State = Session.ClientState.NotReady; } server.SyncLobbyClients(); 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.NonBotPlayers.Count() < 2) { 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.Team = 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); } // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); return(true); } var botType = parts[2]; var botInfo = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>() .FirstOrDefault(b => b.Type == botType); if (botInfo == null) { server.SendOrderTo(conn, "Message", "Invalid bot type."); return(true); } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botInfo.Name, Bot = botType, Slot = parts[0], Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex }; // Pick a random color for the bot var validator = server.ModData.Manifest.Get <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 = botInfo.Name; 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 botTypes = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Type); var slots = server.LobbyInfo.Slots.Keys.ToArray(); var i = 0; foreach (var os in oldSlots) { var c = server.LobbyInfo.ClientInSlot(os); if (c == null) { continue; } c.SpawnPoint = 0; c.Slot = i < slots.Length ? slots[i++] : null; if (c.Slot != null) { // Remove Bot from slot if slot forbids bots if (c.Bot != null && (!server.Map.Players.Players[c.Slot].AllowBots || !botTypes.Contains(c.Bot))) { server.LobbyInfo.Clients.Remove(c); } S.SyncClientToPlayerReference(c, server.Map.Players.Players[c.Slot]); } else if (c.Bot != null) { server.LobbyInfo.Clients.Remove(c); } } // Validate if color is allowed and get an alternative if it isn't foreach (var c in server.LobbyInfo.Clients) { if (c.Slot != null && !server.LobbyInfo.Slots[c.Slot].LockColor) { c.Color = c.PreferredColor = SanitizePlayerColor(server, c.Color, c.Index, conn); } } server.SyncLobbyInfo(); server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); if (server.Map.DefinesUnsafeCustomRules) { server.SendMessage("This map contains custom rules. Game experience may change."); } if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer) { server.SendMessage(server.TwoHumansRequiredText); } else if (server.Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { server.SendMessage("Bots have been disabled on this map."); } var briefing = MissionBriefingOrDefault(server); if (briefing != null) { server.SendMessage(briefing); } }; Action queryFailed = () => server.SendOrderTo(conn, "Message", "Map was not found on server."); var m = server.ModData.MapCache[s]; if (m.Status == MapStatus.Available || m.Status == MapStatus.DownloadAvailable) { selectMap(m); } else if (server.Settings.QueryMapRepository) { server.SendOrderTo(conn, "Message", "Searching for map on the Resource Center..."); var mapRepository = server.ModData.Manifest.Get <WebServices>().MapRepository; server.ModData.MapCache.QueryRemoteMapDetails(mapRepository, 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.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); } }, { "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)); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client() { Name = handshake.Client.Name, IpAddress = ((IPEndPoint)newConn.socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.Color, Color = handshake.Client.Color, Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin) }; if (client.Slot != null) SyncClientToPlayerReference(client, Map.Players[client.Slot]); else client.Color = HSLColor.FromRGB(255, 255, 255); if (ModData.Manifest.Mod.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Mod.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } // Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.socket.RemoteEndPoint); foreach (var t in serverTraits.WithInterface<IClientJoined>()) t.ClientJoined(this, newConn); SyncLobbyInfo(); SendMessage("{0} has joined the server.".F(client.Name)); // Send initial ping SendOrderTo(newConn, "Ping", Environment.TickCount.ToString()); var motdPath = Path.Combine(Platform.SupportDir, "motd_{0}.txt".F(ModData.Manifest.Mod.Id)); if (File.Exists(motdPath)) { var motd = System.IO.File.ReadAllText(motdPath); SendOrderTo(newConn, "Message", motd); } if (handshake.Mod == "{DEV_VERSION}") SendMessage("{0} is running an unversioned development build, ".F(client.Name) + "and may desynchronize the game state if they have incompatible rules."); SetOrderLag(); } catch (Exception) { DropClient(newConn); } }
public Player(World world, Session.Client client, PlayerReference pr) { World = world; InternalName = pr.Name; PlayerReference = pr; inMissionMap = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector); // Real player or host-created bot if (client != null) { ClientIndex = client.Index; Color = client.Color; if (client.Bot != null) { var botInfo = world.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().First(b => b.Type == client.Bot); var botsOfSameType = world.LobbyInfo.Clients.Where(c => c.Bot == client.Bot).ToArray(); PlayerName = botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1); } else { PlayerName = client.Name; } BotType = client.Bot; Faction = ChooseFaction(world, client.Faction, !pr.LockFaction); DisplayFaction = ChooseDisplayFaction(world, client.Faction); } else { // Map player ClientIndex = 0; // Owned by the host (TODO: fix this) Color = pr.Color; PlayerName = pr.Name; NonCombatant = pr.NonCombatant; Playable = pr.Playable; Spectating = pr.Spectating; BotType = pr.Bot; Faction = ChooseFaction(world, pr.Faction, false); DisplayFaction = ChooseDisplayFaction(world, pr.Faction); } if (!Spectating) { PlayerMask = new LongBitSet <PlayerBitMask>(InternalName); } // Set this property before running any Created callbacks on the player actor IsBot = BotType != null; // Special case handling is required for the Player actor: // Since Actor.Created would be called before PlayerActor is assigned here // querying player traits in INotifyCreated.Created would crash. // Therefore assign the uninitialized actor and run the Created callbacks // by calling Initialize ourselves. var playerActorType = world.Type == WorldType.Editor ? EditorPlayerActorType : PlayerActorType; PlayerActor = new Actor(world, playerActorType, new TypeDictionary { new OwnerInit(this) }); PlayerActor.Initialize(true); Shroud = PlayerActor.Trait <Shroud>(); FrozenActorLayer = PlayerActor.TraitOrDefault <FrozenActorLayer>(); // Enable the bot logic on the host if (IsBot && Game.IsHost) { var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType); if (logic == null) { Log.Write("debug", "Invalid bot type: {0}", BotType); } else { logic.Activate(this); } } stanceColors.Self = ChromeMetrics.Get <Color>("PlayerStanceColorSelf"); stanceColors.Allies = ChromeMetrics.Get <Color>("PlayerStanceColorAllies"); stanceColors.Enemies = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies"); stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals"); unlockRenderPlayer = PlayerActor.TraitsImplementing <IUnlocksRenderPlayer>().ToArray(); }
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 LatencyTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, OrderManager orderManager, Session.Client client) { var latencyPrefix = widget.Get <LabelWidget>("LATENCY_PREFIX"); var latencyPrefixFont = Game.Renderer.Fonts[latencyPrefix.Font]; var latency = widget.Get <LabelWidget>("LATENCY"); var latencyFont = Game.Renderer.Fonts[latency.Font]; var rightMargin = widget.Bounds.Width; latency.Bounds.X = latencyPrefix.Bounds.X + latencyPrefixFont.Measure(latencyPrefix.Text + " ").X; widget.IsVisible = () => client != null; tooltipContainer.BeforeRender = () => { if (widget.IsVisible()) { widget.Bounds.Width = latency.Bounds.X + latencyFont.Measure(latency.GetText()).X + rightMargin; } }; var ping = orderManager.LobbyInfo.PingFromClient(client); latency.GetText = () => LobbyUtils.LatencyDescription(ping); latency.GetColor = () => LobbyUtils.LatencyColor(ping); }
int IAssignSpawnPointsInfo.AssignSpawnPoint(object stateObject, Session lobbyInfo, Session.Client client, MersenneTwister playerRandom) { var state = (AssignSpawnLocationsState)stateObject; var separateTeamSpawns = lobbyInfo.GlobalSettings.OptionOrDefault("separateteamspawns", SeparateTeamSpawnsCheckboxEnabled); if (client.SpawnPoint > 0 && client.SpawnPoint <= state.SpawnLocations.Length) { return(client.SpawnPoint); } var spawnPoint = state.OccupiedSpawnPoints.Count == 0 || !separateTeamSpawns ? state.AvailableSpawnPoints.Random(playerRandom) : state.AvailableSpawnPoints // pick the most distant spawnpoint from everyone else .Select(s => (Cell: state.SpawnLocations[s - 1], Index: s)) .MaxBy(s => state.OccupiedSpawnPoints.Sum(kv => (state.SpawnLocations[kv.Key - 1] - s.Cell).LengthSquared)).Index; state.AvailableSpawnPoints.Remove(spawnPoint); state.OccupiedSpawnPoints.Add(spawnPoint, client); return(spawnPoint); }
public static void SetupEditableHandicapWidget(Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager) { var dropdown = parent.Get <DropDownButtonWidget>("HANDICAP_DROPDOWN"); dropdown.IsVisible = () => true; dropdown.IsDisabled = () => s.LockHandicap || orderManager.LocalClient.IsReady; dropdown.OnMouseDown = _ => ShowHandicapDropDown(dropdown, c, orderManager); var handicapLabel = new CachedTransform <int, string>(h => $"{h}%"); dropdown.GetText = () => handicapLabel.Update(c.Handicap); HideChildWidget(parent, "HANDICAP"); }
public static void ProcessOrder(OrderManager orderManager, World world, int clientId, Order order) { if (world != null) { if (!world.WorldActor.TraitsImplementing<IValidateOrder>().All(vo => vo.OrderValidation(orderManager, world, clientId, order))) return; } switch (order.OrderString) { case "Chat": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { var player = world != null ? world.FindPlayerByClient(client) : null; var suffix = (player != null && player.WinState == WinState.Lost) ? " (Dead)" : ""; suffix = client.IsObserver ? " (Spectator)" : suffix; Game.AddChatLine(client.Color.RGB, client.Name + suffix, order.TargetString); } else Game.AddChatLine(Color.White, "(player {0})".F(clientId), order.TargetString); break; } case "Message": // Server message Game.AddChatLine(Color.White, "Server", order.TargetString); break; case "Disconnected": /* reports that the target player disconnected */ { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) client.State = Session.ClientState.Disconnected; break; } case "TeamChat": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { if (world == null) { if (orderManager.LocalClient != null && client.Team == orderManager.LocalClient.Team) Game.AddChatLine(client.Color.RGB, client.Name + " (Team)", order.TargetString); } else { var player = world.FindPlayerByClient(client); if (player == null) return; if (world.LocalPlayer != null && player.Stances[world.LocalPlayer] == Stance.Ally || player.WinState == WinState.Lost) { var suffix = player.WinState == WinState.Lost ? " (Dead)" : " (Team)"; Game.AddChatLine(client.Color.RGB, client.Name + suffix, order.TargetString); } } } break; } case "StartGame": { Game.AddChatLine(Color.White, "Server", "The game has started."); Game.StartGame(orderManager.LobbyInfo.GlobalSettings.Map, false); break; } case "PauseGame": { var client = orderManager.LobbyInfo.ClientWithIndex(clientId); if (client != null) { var pause = order.TargetString == "Pause"; if (orderManager.world.Paused != pause && !world.LobbyInfo.IsSinglePlayer) { var pausetext = "The game is {0} by {1}".F(pause ? "paused" : "un-paused", client.Name); Game.AddChatLine(Color.White, "", pausetext); } orderManager.world.Paused = pause; orderManager.world.PredictedPaused = pause; } break; } case "HandshakeRequest": { var request = HandshakeRequest.Deserialize(order.TargetString); var localMods = orderManager.LobbyInfo.GlobalSettings.Mods.Select(m => "{0}@{1}".F(m,Mod.AllMods[m].Version)).ToArray(); // Check if mods match if (localMods.FirstOrDefault().ToString().Split('@')[0] != request.Mods.FirstOrDefault().ToString().Split('@')[0]) throw new InvalidOperationException("Server's mod ({0}) and yours ({1}) don't match".F(localMods.FirstOrDefault().ToString().Split('@')[0], request.Mods.FirstOrDefault().ToString().Split('@')[0])); // Check that the map exists on the client if (!Game.modData.AvailableMaps.ContainsKey(request.Map)) { if (Game.Settings.Game.AllowDownloading) Game.DownloadMap(request.Map); else throw new InvalidOperationException("Missing map {0}".F(request.Map)); } var info = new Session.Client() { Name = Game.Settings.Player.Name, PreferredColor = Game.Settings.Player.Color, Color = Game.Settings.Player.Color, Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady }; var response = new HandshakeResponse() { Client = info, Mods = localMods, Password = "******" }; orderManager.IssueOrder(Order.HandshakeResponse(response.Serialize())); break; } case "ServerError": { orderManager.ServerError = order.TargetString; break; } case "SyncInfo": { orderManager.LobbyInfo = Session.Deserialize(order.TargetString); if (orderManager.FramesAhead != orderManager.LobbyInfo.GlobalSettings.OrderLatency && !orderManager.GameStarted) { orderManager.FramesAhead = orderManager.LobbyInfo.GlobalSettings.OrderLatency; Game.Debug("Order lag is now {0} frames.".F(orderManager.LobbyInfo.GlobalSettings.OrderLatency)); } Game.SyncLobbyInfo(); break; } case "SetStance": { if (!Game.orderManager.LobbyInfo.GlobalSettings.FragileAlliances) return; var targetPlayer = order.Player.World.Players.FirstOrDefault(p => p.InternalName == order.TargetString); var newStance = (Stance)order.TargetLocation.X; SetPlayerStance(world, order.Player, targetPlayer, newStance); Game.Debug("{0} has set diplomatic stance vs {1} to {2}".F( order.Player.PlayerName, targetPlayer.PlayerName, newStance)); // automatically declare war reciprocally if (newStance == Stance.Enemy && targetPlayer.Stances[order.Player] == Stance.Ally) { SetPlayerStance(world, targetPlayer, order.Player, newStance); Game.Debug("{0} has reciprocated",targetPlayer.PlayerName); } break; } case "Ping": { orderManager.IssueOrder(Order.Pong(order.TargetString)); break; } default: { if (!order.IsImmediate) { var self = order.Subject; var health = self.TraitOrDefault<Health>(); if (health == null || !health.IsDead) foreach (var t in self.TraitsImplementing<IResolveOrder>()) t.ResolveOrder(self, order); } break; } } }
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 (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; 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); } 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); } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyInfo(); return(true); } }, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } int teams; if (!int.TryParse(s, out teams)) { server.SendOrderTo(conn, "Message", "Number of teams could not be parsed: {0}".F(s)); return(true); } teams = teams.Clamp(2, 8); var players = server.lobbyInfo.Slots .Select(slot => server.lobbyInfo.Clients.SingleOrDefault(c => c.Slot == slot.Key)) .Where(c => c != null && !server.lobbyInfo.Slots[c.Slot].LockTeam).ToArray(); if (players.Length < 2) { server.SendOrderTo(conn, "Message", "Not enough players to assign teams"); return(true); } if (teams > players.Length) { server.SendOrderTo(conn, "Message", "Too many teams for the number of players"); return(true); } var teamSizes = new int[players.Length]; for (var i = 0; i < players.Length; i++) { teamSizes[i % teams]++; } var playerIndex = 0; for (var team = 1; team <= teams; team++) { for (var teamPlayerIndex = 0; teamPlayerIndex < teamSizes[team - 1]; playerIndex++, teamPlayerIndex++) { var cl = players[playerIndex]; if (cl.Bot == null) { cl.State = Session.ClientState.NotReady; } cl.Team = team; } } server.SyncLobbyInfo(); return(true); } }, { "crates", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } bool.TryParse(s, out server.lobbyInfo.GlobalSettings.Crates); server.SyncLobbyInfo(); return(true); } }, { "difficulty", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if ((server.Map.Difficulties == null && s != null) || (server.Map.Difficulties != null && !server.Map.Difficulties.Contains(s))) { server.SendOrderTo(conn, "Message", "Unsupported difficulty selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported difficulties: {0}".F(server.Map.Difficulties.JoinWith(","))); return(true); } server.lobbyInfo.GlobalSettings.Difficulty = s; server.SyncLobbyInfo(); return(true); } }, { "kick", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "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.SendOrderTo(conn, "Message", "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.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); } // 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)); }