diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-03-02 20:48:11 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-03-02 20:48:11 -0600 |
| commit | 57092492292b2d809dee463d8c5edc1dcdec286e (patch) | |
| tree | 411f633cbb40e5a2c2c8159c17de1a768ab8ca0c /src/slskd | |
| parent | 71fe0a4a578fdd9f0945923eb655ddf2a546f1db (diff) | |
| parent | 4de21d94899605accdba680eeff95b8dc38b59e2 (diff) | |
| download | slskd-57092492292b2d809dee463d8c5edc1dcdec286e.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/serialize-javascript-6.0.2
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Core/Options.cs | 61 | ||||
| -rw-r--r-- | src/slskd/Integrations/Scripts/ScriptService.cs | 125 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 7 |
3 files changed, 157 insertions, 36 deletions
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index ff9cc407..266d04aa 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2107,14 +2107,10 @@ namespace slskd public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { - var results = new List<ValidationResult>(); - if (!Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { - results.Add(new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)")); + yield return new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)"); } - - return results; } } @@ -2161,9 +2157,58 @@ namespace slskd /// <summary> /// Gets the shell script to invoke. /// </summary> - [StringLength(int.MaxValue, MinimumLength = 1)] - [NotNullOrWhiteSpace] - public string Run { get; init; } + public ScriptRunOptions Run { get; init; } = new ScriptRunOptions(); + } + + /// <summary> + /// Script run options. + /// </summary> + public class ScriptRunOptions : IValidatableObject + { + /// <summary> + /// Gets the shell command to run. + /// </summary> + public string Command { get; init; } + + /// <summary> + /// Gets the executable to start. + /// </summary> + public string Executable { get; init; } + + /// <summary> + /// Gets the arguments to pass to the executable. + /// </summary> + /// <remarks> + /// Mutually exclusive with <see cref="Arglist"/>. + /// </remarks> + public string Args { get; init; } + + /// <summary> + /// Gets the list of arguments to pass to the executable. + /// </summary> + /// <remarks> + /// Mutually exclusive with <see cref="Args"/>. + /// </remarks> + public string[] Arglist { get; init; } = null; + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var cmdIsSet = !string.IsNullOrWhiteSpace(Command); + var exeIsSet = !string.IsNullOrWhiteSpace(Executable); + + if ((cmdIsSet && exeIsSet) || (!cmdIsSet && !exeIsSet)) + { + yield return new ValidationResult($"One and only one of the fields {nameof(Command)} or {nameof(Executable)} may be specified for a single script. If you intend to use the system shell, omit 'executable'. If you intend to use an executable other than the system shell, omit 'command' and specify either 'args' or 'args_list'."); + } + + var argsIsSet = !string.IsNullOrWhiteSpace(Args); + var argsListIsSet = Arglist is not null; + + if (argsIsSet && argsListIsSet) + { + yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(Arglist)} may be specified for a single script. Specify 'args' if you intend to construct a single quoted string yourself, and specify 'args_list' if you'd like slskd to handle quoting for you."); + } + } } /// <summary> diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 227f2fb1..05769a6d 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -39,12 +39,31 @@ public class ScriptService Events.Subscribe<Event>(nameof(ScriptService), HandleEvent); + if (OperatingSystem.IsWindows()) + { + DefaultExecutable = "cmd.exe"; + DefaultCommandPrefix = "/c"; + } + else + { + DefaultExecutable = Environment.GetEnvironmentVariable("SHELL"); + DefaultCommandPrefix = "-c"; + + if (string.IsNullOrEmpty(DefaultExecutable)) + { + Log.Warning("Unable to determine default script executable ($SHELL is missing or blank); any user-defined scripts that do not specify an executable will fail"); + } + } + + Log.Information("Set default script executable to '{DefaultExecutable}'", DefaultExecutable); Log.Debug("{Service} initialized", nameof(ScriptService)); } private ILogger Log { get; } = Serilog.Log.ForContext<ScriptService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private EventBus Events { get; } + private string DefaultExecutable { get; } + private string DefaultCommandPrefix { get; } private async Task HandleEvent(Event data) { @@ -64,44 +83,92 @@ public class ScriptService _ = Task.Run(() => { Process process = default; + var processId = Guid.NewGuid(); + // there are three 'modes' that we can use to execute a script, which are detailed below. + // the mode is negotiated based on the script config, and we rely on the validation in Options + // to enforce mututal exclusivity and prevent a user from supplying an invalid config try { var run = script.Value.Run; + var executable = run.Executable ?? DefaultExecutable; - // split the string into at most 2 parts, leaving part [0] the executable and part [1] the rest of the string, but possibly null - var parts = run.Split(" ", count: 2, options: StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.RemoveEmptyEntries); - - var executable = parts[0]; - string args = default; - - if (parts.Length > 1) + if (string.IsNullOrEmpty(executable)) { - args = parts[1].Replace("$DATA", data.ToJson()); + Log.Warning("Script '{Script}' will not be run: unable to determine script executable. Update the script configuration, or set your operating system's SHELL envar."); + return; } - Log.Debug("Running script '{Script}': {Run}", script.Key, run); - var sw = Stopwatch.StartNew(); - - process = new Process() + if (!string.IsNullOrEmpty(run.Command)) { - StartInfo = new ProcessStartInfo(fileName: executable) + // 'command' mode takes precedence over 'executable' mode + // run the system shell and ensure the specified command is prefixed with the correct flag + // this is designed to be the 'pit of success' for this feature that will work for most users, + // who most likely have not read the docs and expect this to work like a command line. + // users are on the hook for properly (and safely) quoting arguments + Log.Debug("Running script '{Script}' in 'command mode'", script.Key); + + process = new Process() { - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - RedirectStandardInput = true, - }, - }; - - process.Start(); - - if (args is not null) + StartInfo = new ProcessStartInfo(fileName: executable) + { + WorkingDirectory = Program.ScriptDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} \"{run.Command.Trim('"')}\"", + }, + }; + } + else if (run.Arglist is not null) { - process.StandardInput.WriteLine(args); + // 'args list' mode takes precedence over 'args' mode + // the supplied list of args will be passed to the constructor of ProcessStartInfo, which is + // curiously the only way to pass a list of args (instead of a string). if no executable has been + // specified, the system shell is used. this mode is for maximalists who know what they are doing + // and want granular control + Log.Debug("Running script '{Script}' in 'args list mode'", script.Key); + + process = new Process() + { + StartInfo = new ProcessStartInfo( + fileName: executable, + arguments: run.Arglist) + { + WorkingDirectory = Program.ScriptDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }, + }; + } + else + { + // 'args' mode is the default mode + // run the specified executable, or if not specified, the system shell. pass the args string + // (which may be empty or null) to ProcessStartInfo + Log.Debug("Running script '{Script}' in 'args mode'", script.Key); + process = new Process() + { + StartInfo = new ProcessStartInfo(fileName: executable) + { + WorkingDirectory = Program.ScriptDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + Arguments = run.Args, + }, + }; } - process.StandardInput.WriteLine("exit"); + Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.Arglist ?? []), processId); + var sw = Stopwatch.StartNew(); + + process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = data.ToJson(); + process.Start(); process.WaitForExit(); sw.Stop(); @@ -116,21 +183,23 @@ public class ScriptService var result = process.StandardOutput.ReadToEnd(); var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); - Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output}", script.Key, sw.ElapsedMilliseconds, resultAsLines); + Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output} (id: {ProcessId})", script.Key, sw.ElapsedMilliseconds, resultAsLines, processId); } catch (Exception ex) { - Log.Warning(ex, "Failed to run script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message); + Log.Warning("Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId); + Log.Debug(ex, "Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId); } finally { try { process?.Close(); + process?.Dispose(); } catch (Exception ex) { - Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message); + Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId); } } }); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 49b01516..b7fa47d2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -208,6 +208,11 @@ namespace slskd public static string LogDirectory { get; private set; } = null; /// <summary> + /// Gets the path where user-defined scripts are stored. + /// </summary> + public static string ScriptDirectory { get; private set; } = null; + + /// <summary> /// Gets a buffer containing the last few log events. /// </summary> public static ConcurrentFixedSizeQueue<LogRecord> LogBuffer { get; } = new ConcurrentFixedSizeQueue<LogRecord>(size: 100); @@ -332,6 +337,7 @@ namespace slskd AppDirectory ??= DefaultAppDirectory; DataDirectory = Path.Combine(AppDirectory, "data"); LogDirectory = Path.Combine(AppDirectory, "logs"); + ScriptDirectory = Path.Combine(AppDirectory, "scripts"); DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads"); @@ -347,6 +353,7 @@ namespace slskd { VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DataDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(ScriptDirectory, createIfMissing: true, verifyWriteable: false); VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true); } |
