ensure commands are not displayed/usable for unsupported games

This commit is contained in:
RaidMax 2022-06-17 13:11:44 -05:00
parent 4322e8d882
commit 55bccc7d3d
3 changed files with 125 additions and 107 deletions

View File

@ -154,10 +154,10 @@ namespace IW4MAdmin
{ {
if (E.IsBlocking) if (E.IsBlocking)
{ {
await E.Origin?.Lock(); await E.Origin.Lock();
} }
bool canExecuteCommand = true; var canExecuteCommand = true;
try try
{ {
@ -166,30 +166,30 @@ namespace IW4MAdmin
return; return;
} }
Command C = null; Command command = null;
if (E.Type == GameEvent.EventType.Command) if (E.Type == GameEvent.EventType.Command)
{ {
try try
{ {
C = await SharedLibraryCore.Commands.CommandProcessing.ValidateCommand(E, Manager.GetApplicationSettings().Configuration(), _commandConfiguration); command = await SharedLibraryCore.Commands.CommandProcessing.ValidateCommand(E, Manager.GetApplicationSettings().Configuration(), _commandConfiguration);
} }
catch (CommandException e) catch (CommandException e)
{ {
ServerLogger.LogWarning(e, "Error validating command from event {@event}", ServerLogger.LogWarning(e, "Error validating command from event {@Event}",
new { E.Type, E.Data, E.Message, E.Subtype, E.IsRemote, E.CorrelationId }); new { E.Type, E.Data, E.Message, E.Subtype, E.IsRemote, E.CorrelationId });
E.FailReason = GameEvent.EventFailReason.Invalid; E.FailReason = GameEvent.EventFailReason.Invalid;
} }
if (C != null) if (command != null)
{ {
E.Extra = C; E.Extra = command;
} }
} }
try try
{ {
var loginPlugin = Manager.Plugins.FirstOrDefault(_plugin => _plugin.Name == "Login"); var loginPlugin = Manager.Plugins.FirstOrDefault(plugin => plugin.Name == "Login");
if (loginPlugin != null) if (loginPlugin != null)
{ {
@ -204,15 +204,15 @@ namespace IW4MAdmin
} }
// hack: this prevents commands from getting executing that 'shouldn't' be // hack: this prevents commands from getting executing that 'shouldn't' be
if (E.Type == GameEvent.EventType.Command && E.Extra is Command command && if (E.Type == GameEvent.EventType.Command && E.Extra is Command cmd &&
(canExecuteCommand || E.Origin?.Level == Permission.Console)) (canExecuteCommand || E.Origin?.Level == Permission.Console))
{ {
ServerLogger.LogInformation("Executing command {comamnd} for {client}", command.Name, E.Origin.ToString()); ServerLogger.LogInformation("Executing command {Command} for {Client}", cmd.Name, E.Origin.ToString());
await command.ExecuteAsync(E); await cmd.ExecuteAsync(E);
} }
var pluginTasks = Manager.Plugins var pluginTasks = Manager.Plugins
.Where(_plugin => _plugin.Name != "Login") .Where(plugin => plugin.Name != "Login")
.Select(async plugin => await CreatePluginTask(plugin, E)); .Select(async plugin => await CreatePluginTask(plugin, E));
await Task.WhenAll(pluginTasks); await Task.WhenAll(pluginTasks);

View File

@ -11,163 +11,180 @@ namespace SharedLibraryCore.Commands
{ {
public class CommandProcessing public class CommandProcessing
{ {
public static async Task<Command> ValidateCommand(GameEvent E, ApplicationConfiguration appConfig, public static async Task<Command> ValidateCommand(GameEvent gameEvent, ApplicationConfiguration appConfig,
CommandConfiguration commandConfig) CommandConfiguration commandConfig)
{ {
var loc = Utilities.CurrentLocalization.LocalizationIndex; var loc = Utilities.CurrentLocalization.LocalizationIndex;
var Manager = E.Owner.Manager; var manager = gameEvent.Owner.Manager;
var isBroadcast = E.Data.StartsWith(appConfig.BroadcastCommandPrefix); var isBroadcast = gameEvent.Data.StartsWith(appConfig.BroadcastCommandPrefix);
var prefixLength = isBroadcast ? appConfig.BroadcastCommandPrefix.Length : appConfig.CommandPrefix.Length; var prefixLength = isBroadcast ? appConfig.BroadcastCommandPrefix.Length : appConfig.CommandPrefix.Length;
var CommandString = E.Data.Substring(prefixLength, E.Data.Length - prefixLength).Split(' ')[0]; var commandString =
E.Message = E.Data; gameEvent.Data.Substring(prefixLength, gameEvent.Data.Length - prefixLength).Split(' ')[0];
gameEvent.Message = gameEvent.Data;
Command C = null; Command matchedCommand = null;
foreach (Command cmd in Manager.GetCommands() foreach (var availableCommand in manager.GetCommands()
.Where(c => c.Name != null)) .Where(c => c.Name != null))
if (cmd.Name.Equals(CommandString, StringComparison.OrdinalIgnoreCase) ||
(cmd.Alias ?? "").Equals(CommandString, StringComparison.OrdinalIgnoreCase))
{ {
C = cmd; if ((availableCommand.SupportedGames?.Any() ?? false) &&
!availableCommand.SupportedGames.Contains(gameEvent.Owner.GameName))
{
continue;
} }
if (C == null) if (availableCommand.Name.Equals(commandString, StringComparison.OrdinalIgnoreCase) ||
(availableCommand.Alias ?? "").Equals(commandString, StringComparison.OrdinalIgnoreCase))
{ {
E.Origin.Tell(loc["COMMAND_UNKNOWN"]); matchedCommand = (Command)availableCommand;
throw new CommandException($"{E.Origin} entered unknown command \"{CommandString}\""); }
} }
C.IsBroadcast = isBroadcast; if (matchedCommand == null)
var allowImpersonation = commandConfig?.Commands?.ContainsKey(C.GetType().Name) ?? false
? commandConfig.Commands[C.GetType().Name].AllowImpersonation
: C.AllowImpersonation;
if (!allowImpersonation && E.ImpersonationOrigin != null)
{ {
E.ImpersonationOrigin.Tell(loc["COMMANDS_RUN_AS_FAIL"]); gameEvent.Origin.Tell(loc["COMMAND_UNKNOWN"]);
throw new CommandException($"Command {C.Name} cannot be run as another client"); throw new CommandException($"{gameEvent.Origin} entered unknown command \"{commandString}\"");
} }
E.Data = E.Data.RemoveWords(1); matchedCommand.IsBroadcast = isBroadcast;
var Args = E.Data.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var allowImpersonation = commandConfig?.Commands?.ContainsKey(matchedCommand.GetType().Name) ?? false
? commandConfig.Commands[matchedCommand.GetType().Name].AllowImpersonation
: matchedCommand.AllowImpersonation;
if (!allowImpersonation && gameEvent.ImpersonationOrigin != null)
{
gameEvent.ImpersonationOrigin.Tell(loc["COMMANDS_RUN_AS_FAIL"]);
throw new CommandException($"Command {matchedCommand.Name} cannot be run as another client");
}
gameEvent.Data = gameEvent.Data.RemoveWords(1);
var args = gameEvent.Data.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// todo: the code below can be cleaned up // todo: the code below can be cleaned up
if (gameEvent.Origin.Level < matchedCommand.Permission)
if (E.Origin.Level < C.Permission)
{ {
E.Origin.Tell(loc["COMMAND_NOACCESS"]); gameEvent.Origin.Tell(loc["COMMAND_NOACCESS"]);
throw new CommandException($"{E.Origin} does not have access to \"{C.Name}\""); throw new CommandException($"{gameEvent.Origin} does not have access to \"{matchedCommand.Name}\"");
} }
if (Args.Length < C.RequiredArgumentCount) if (args.Length < matchedCommand.RequiredArgumentCount)
{ {
E.Origin.Tell(loc["COMMAND_MISSINGARGS"]); gameEvent.Origin.Tell(loc["COMMAND_MISSINGARGS"]);
E.Origin.Tell(C.Syntax); gameEvent.Origin.Tell(matchedCommand.Syntax);
throw new CommandException($"{E.Origin} did not supply enough arguments for \"{C.Name}\""); throw new CommandException(
$"{gameEvent.Origin} did not supply enough arguments for \"{matchedCommand.Name}\"");
} }
if (C.RequiresTarget) if (matchedCommand.RequiresTarget)
{ {
if (Args.Length > 0) if (args.Length > 0)
{ {
if (!int.TryParse(Args[0], out var cNum)) if (!int.TryParse(args[0], out var cNum))
{ {
cNum = -1; cNum = -1;
} }
if (Args[0][0] == '@') // user specifying target by database ID if (args[0][0] == '@') // user specifying target by database ID
{ {
int.TryParse(Args[0].Substring(1, Args[0].Length - 1), out var dbID); int.TryParse(args[0].Substring(1, args[0].Length - 1), out var dbID);
var found = await Manager.GetClientService().Get(dbID); var found = await manager.GetClientService().Get(dbID);
if (found != null) if (found != null)
{ {
found = Manager.FindActiveClient(found); found = manager.FindActiveClient(found);
E.Target = found; gameEvent.Target = found;
E.Target.CurrentServer = found.CurrentServer ?? E.Owner; gameEvent.Target.CurrentServer = found.CurrentServer ?? gameEvent.Owner;
E.Data = string.Join(" ", Args.Skip(1)); gameEvent.Data = string.Join(" ", args.Skip(1));
} }
} }
else if (Args[0].Length < 3 && cNum > -1 && cNum < E.Owner.MaxClients else if (args[0].Length < 3 && cNum > -1 && cNum < gameEvent.Owner.MaxClients
) // user specifying target by client num ) // user specifying target by client num
{ {
if (E.Owner.Clients[cNum] != null) if (gameEvent.Owner.Clients[cNum] != null)
{ {
E.Target = E.Owner.Clients[cNum]; gameEvent.Target = gameEvent.Owner.Clients[cNum];
E.Data = string.Join(" ", Args.Skip(1)); gameEvent.Data = string.Join(" ", args.Skip(1));
} }
} }
} }
List<EFClient> matchingPlayers; List<EFClient> matchingPlayers;
if (E.Target == null && C.RequiresTarget) // Find active player including quotes (multiple words) if (gameEvent.Target == null &&
matchedCommand.RequiresTarget) // Find active player including quotes (multiple words)
{ {
matchingPlayers = E.Owner.GetClientByName(E.Data); matchingPlayers = gameEvent.Owner.GetClientByName(gameEvent.Data);
if (matchingPlayers.Count > 1) if (matchingPlayers.Count > 1)
{ {
E.Origin.Tell(loc["COMMAND_TARGET_MULTI"]); gameEvent.Origin.Tell(loc["COMMAND_TARGET_MULTI"]);
throw new CommandException($"{E.Origin} had multiple players found for {C.Name}"); throw new CommandException(
$"{gameEvent.Origin} had multiple players found for {matchedCommand.Name}");
} }
if (matchingPlayers.Count == 1) if (matchingPlayers.Count == 1)
{ {
E.Target = matchingPlayers.First(); gameEvent.Target = matchingPlayers.First();
var escapedName = Regex.Escape(E.Target.CleanedName); var escapedName = Regex.Escape(gameEvent.Target.CleanedName);
var reg = new Regex($"(\"{escapedName}\")|({escapedName})", RegexOptions.IgnoreCase); var reg = new Regex($"(\"{escapedName}\")|({escapedName})", RegexOptions.IgnoreCase);
E.Data = reg.Replace(E.Data, "", 1).Trim(); gameEvent.Data = reg.Replace(gameEvent.Data, "", 1).Trim();
if (E.Data.Length == 0 && C.RequiredArgumentCount > 1) if (gameEvent.Data.Length == 0 && matchedCommand.RequiredArgumentCount > 1)
{ {
E.Origin.Tell(loc["COMMAND_MISSINGARGS"]); gameEvent.Origin.Tell(loc["COMMAND_MISSINGARGS"]);
E.Origin.Tell(C.Syntax); gameEvent.Origin.Tell(matchedCommand.Syntax);
throw new CommandException($"{E.Origin} did not supply enough arguments for \"{C.Name}\""); throw new CommandException(
$"{gameEvent.Origin} did not supply enough arguments for \"{matchedCommand.Name}\"");
} }
} }
} }
if (E.Target == null && C.RequiresTarget && Args.Length > 0) // Find active player as single word if (gameEvent.Target == null && matchedCommand.RequiresTarget &&
args.Length > 0) // Find active player as single word
{ {
matchingPlayers = E.Owner.GetClientByName(Args[0]); matchingPlayers = gameEvent.Owner.GetClientByName(args[0]);
if (matchingPlayers.Count > 1) if (matchingPlayers.Count > 1)
{ {
E.Origin.Tell(loc["COMMAND_TARGET_MULTI"]); gameEvent.Origin.Tell(loc["COMMAND_TARGET_MULTI"]);
foreach (var p in matchingPlayers) foreach (var p in matchingPlayers)
E.Origin.Tell($"[(Color::Yellow){p.ClientNumber}(Color::White)] {p.Name}"); gameEvent.Origin.Tell($"[(Color::Yellow){p.ClientNumber}(Color::White)] {p.Name}");
throw new CommandException($"{E.Origin} had multiple players found for {C.Name}"); throw new CommandException(
$"{gameEvent.Origin} had multiple players found for {matchedCommand.Name}");
} }
if (matchingPlayers.Count == 1) if (matchingPlayers.Count == 1)
{ {
E.Target = matchingPlayers.First(); gameEvent.Target = matchingPlayers.First();
var escapedName = Regex.Escape(E.Target.CleanedName); var escapedName = Regex.Escape(gameEvent.Target.CleanedName);
var escapedArg = Regex.Escape(Args[0]); var escapedArg = Regex.Escape(args[0]);
var reg = new Regex($"({escapedName})|({escapedArg})", RegexOptions.IgnoreCase); var reg = new Regex($"({escapedName})|({escapedArg})", RegexOptions.IgnoreCase);
E.Data = reg.Replace(E.Data, "", 1).Trim(); gameEvent.Data = reg.Replace(gameEvent.Data, "", 1).Trim();
if ((E.Data.Trim() == E.Target.CleanedName.ToLower().Trim() || if ((gameEvent.Data.Trim() == gameEvent.Target.CleanedName.ToLower().Trim() ||
E.Data == string.Empty) && gameEvent.Data == string.Empty) &&
C.RequiresTarget) matchedCommand.RequiresTarget)
{ {
E.Origin.Tell(loc["COMMAND_MISSINGARGS"]); gameEvent.Origin.Tell(loc["COMMAND_MISSINGARGS"]);
E.Origin.Tell(C.Syntax); gameEvent.Origin.Tell(matchedCommand.Syntax);
throw new CommandException($"{E.Origin} did not supply enough arguments for \"{C.Name}\""); throw new CommandException(
$"{gameEvent.Origin} did not supply enough arguments for \"{matchedCommand.Name}\"");
} }
} }
} }
if (E.Target == null && C.RequiresTarget) if (gameEvent.Target == null && matchedCommand.RequiresTarget)
{ {
E.Origin.Tell(loc["COMMAND_TARGET_NOTFOUND"]); gameEvent.Origin.Tell(loc["COMMAND_TARGET_NOTFOUND"]);
throw new CommandException($"{E.Origin} specified invalid player for \"{C.Name}\""); throw new CommandException(
$"{gameEvent.Origin} specified invalid player for \"{matchedCommand.Name}\"");
} }
} }
E.Data = E.Data.Trim(); gameEvent.Data = gameEvent.Data.Trim();
return C; return matchedCommand;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using Newtonsoft.Json; using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using static Data.Models.Client.EFClient; using static Data.Models.Client.EFClient;
using static SharedLibraryCore.Server; using static SharedLibraryCore.Server;
@ -35,6 +36,6 @@ namespace SharedLibraryCore.Configuration
/// Specifies the games supporting the functionality of the command /// Specifies the games supporting the functionality of the command
/// </summary> /// </summary>
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))] [JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public Game[] SupportedGames { get; set; } = new Game[0]; public Game[] SupportedGames { get; set; } = Array.Empty<Game>();
} }
} }