From f0b7b48eb6a6b6dcb9e19d693403f70bda1bba32 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Feb 2025 17:47:03 -0600 Subject: add regex --- src/slskd/Integrations/Scripts/ScriptService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 227f2fb1..5e6d23d6 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -45,6 +45,7 @@ public class ScriptService private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus Events { get; } + private Regex LeadingQuotedString => new("(\"[^\"]*\"){0,1}(.*)", RegexOptions.Singleline | RegexOptions.Compiled); private async Task HandleEvent(Event data) { -- cgit v1.2.3 From ba85ca83c1ca1a394a938497019404a11ecbf5bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Feb 2025 17:49:18 -0600 Subject: might as well try and dispose while we're here --- src/slskd/Integrations/Scripts/ScriptService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 5e6d23d6..a6ddb251 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -128,6 +128,7 @@ public class ScriptService try { process?.Close(); + process?.Dispose(); } catch (Exception ex) { -- cgit v1.2.3 From ddd0dbff4604d484fb058197539879208b281a3e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Feb 2025 17:50:05 -0600 Subject: support quoted executable strings --- src/slskd/Integrations/Scripts/ScriptService.cs | 26 ++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index a6ddb251..d4eb0bb1 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -69,16 +69,28 @@ public class ScriptService try { var run = script.Value.Run; - - // 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 executable = default; string args = default; - if (parts.Length > 1) + // determine whether the executable is wrapped in quotes, and if so, set the executable to the + // text contained within. the regex contains two capturing groups; the initial quoted string, and + // everything that comes after. if both groups capture something, we were given a quoted string to start + // otherwise no quotes were used, and we should use the first word as the executable + var matches = LeadingQuotedString.Matches(run); + + if (matches.Count == 2) { - args = parts[1].Replace("$DATA", data.ToJson()); + executable = matches[0].Value; + args = matches[1].Value; + } + else + { + // didn't start with a quoted string, so just 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); + + executable = parts[0]; + args = parts.Length > 1 ? parts[1] : null; } Log.Debug("Running script '{Script}': {Run}", script.Key, run); -- cgit v1.2.3 From 83bfe9e3b2999c4c34becd4868f7195b1cc84b1c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Feb 2025 17:51:57 -0600 Subject: log process id --- src/slskd/Integrations/Scripts/ScriptService.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index d4eb0bb1..2c1bc66d 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -65,6 +65,7 @@ public class ScriptService _ = Task.Run(() => { Process process = default; + var processId = Guid.NewGuid(); try { @@ -93,7 +94,7 @@ public class ScriptService args = parts.Length > 1 ? parts[1] : null; } - Log.Debug("Running script '{Script}': {Run}", script.Key, run); + Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, args, processId); var sw = Stopwatch.StartNew(); process = new Process() @@ -129,11 +130,11 @@ 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(ex, "Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId); } finally { @@ -144,7 +145,7 @@ public class ScriptService } 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); } } }); -- cgit v1.2.3 From c91439be2900c2a9d3401592b3417b63a4a497b8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Feb 2025 17:52:08 -0600 Subject: rework process params --- src/slskd/Integrations/Scripts/ScriptService.cs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 2c1bc66d..28c8db77 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -102,21 +102,17 @@ public class ScriptService StartInfo = new ProcessStartInfo(fileName: executable) { UseShellExecute = false, + CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, - RedirectStandardInput = true, + Arguments = args, }, }; + process.StartInfo.Environment.Clear(); + process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = data.ToJson(); process.Start(); - if (args is not null) - { - process.StandardInput.WriteLine(args); - } - - process.StandardInput.WriteLine("exit"); - process.WaitForExit(); sw.Stop(); -- cgit v1.2.3 From 7dd7c6be0fa2adc640a8c68a80d9d2d25b097577 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:37:14 -0600 Subject: add ScriptDirectory --- src/slskd/Program.cs | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') 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 @@ -207,6 +207,11 @@ namespace slskd /// public static string LogDirectory { get; private set; } = null; + /// + /// Gets the path where user-defined scripts are stored. + /// + public static string ScriptDirectory { get; private set; } = null; + /// /// Gets a buffer containing the last few log events. /// @@ -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); } -- cgit v1.2.3 From 13a315c9e858255ce773a4501c0c6c223e6f21f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:37:32 -0600 Subject: simplify webhook validation --- src/slskd/Core/Options.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index ff9cc407..9f539311 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2107,14 +2107,10 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { - var results = new List(); - 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; } } -- cgit v1.2.3 From 94d46b3eb94c3f846b84afe9e58c651b8c63616d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:37:53 -0600 Subject: split script Run into Executable and Command, ensure at least one specified --- src/slskd/Core/Options.cs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 9f539311..183fcbe5 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2157,9 +2157,31 @@ namespace slskd /// /// Gets the shell script to invoke. /// - [StringLength(int.MaxValue, MinimumLength = 1)] - [NotNullOrWhiteSpace] - public string Run { get; init; } + public ScriptRunOptions Run { get; init; } = new ScriptRunOptions(); + } + + /// + /// Script run options. + /// + public class ScriptRunOptions : IValidatableObject + { + /// + /// Gets the executable to start. + /// + public string Executable { get; init; } + + /// + /// Gets the command to run. + /// + public string Command { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + if (string.IsNullOrWhiteSpace(Executable) && string.IsNullOrWhiteSpace(Command)) + { + yield return new ValidationResult($"At least one of the {nameof(Executable)} and {nameof(Command)} fields must be specified"); + } + } } /// -- cgit v1.2.3 From e6d927beabe38eef8d184ccdf5f914026a272255 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:38:36 -0600 Subject: set DefaultExecutable --- src/slskd/Integrations/Scripts/ScriptService.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 28c8db77..b3092a56 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -39,13 +39,28 @@ public class ScriptService Events.Subscribe(nameof(ScriptService), HandleEvent); + if (OperatingSystem.IsWindows()) + { + DefaultExecutable = "cmd.exe"; + } + else + { + DefaultExecutable = Environment.GetEnvironmentVariable("SHELL"); + + 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(); private IOptionsMonitor OptionsMonitor { get; } private EventBus Events { get; } - private Regex LeadingQuotedString => new("(\"[^\"]*\"){0,1}(.*)", RegexOptions.Singleline | RegexOptions.Compiled); + private string DefaultExecutable { get; } private async Task HandleEvent(Event data) { -- cgit v1.2.3 From 6620aaf1bd072b8e86adc0a1541109cb51506e28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:39:05 -0600 Subject: fall back to DefaultExecutable if none specified --- src/slskd/Integrations/Scripts/ScriptService.cs | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index b3092a56..0c3bf5b6 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -85,28 +85,12 @@ public class ScriptService try { var run = script.Value.Run; - string executable = default; - string args = default; + string executable = run.Executable ?? DefaultExecutable; + string args = run.Command; - // determine whether the executable is wrapped in quotes, and if so, set the executable to the - // text contained within. the regex contains two capturing groups; the initial quoted string, and - // everything that comes after. if both groups capture something, we were given a quoted string to start - // otherwise no quotes were used, and we should use the first word as the executable - var matches = LeadingQuotedString.Matches(run); - - if (matches.Count == 2) - { - executable = matches[0].Value; - args = matches[1].Value; - } - else + if (string.IsNullOrEmpty(executable)) { - // didn't start with a quoted string, so just 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); - - executable = parts[0]; - args = parts.Length > 1 ? parts[1] : null; + 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."); } Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, args, processId); -- cgit v1.2.3 From 780c100d37a36f290abfd1357d10c50253a7644b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:39:20 -0600 Subject: set working directory --- src/slskd/Integrations/Scripts/ScriptService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 0c3bf5b6..99771d89 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -98,8 +98,9 @@ public class ScriptService process = new Process() { - StartInfo = new ProcessStartInfo(fileName: executable) + StartInfo = new ProcessStartInfo(executable ?? DefaultExecutable) { + WorkingDirectory = Program.ScriptDirectory, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, -- cgit v1.2.3 From 8fdfc74c403f00425d2b56dd39bdc2d1e1a5fd18 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Feb 2025 17:42:05 -0600 Subject: don't try to run if no executable --- src/slskd/Integrations/Scripts/ScriptService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 99771d89..1a010a80 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -91,6 +91,7 @@ public class ScriptService if (string.IsNullOrEmpty(executable)) { 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}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, args, processId); -- cgit v1.2.3 From c21b459f7dcc9c55260e5b3036a64083eeced140 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 17 Feb 2025 14:15:12 -0600 Subject: document options --- src/slskd/Core/Options.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 183fcbe5..6f8e5682 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2165,21 +2165,29 @@ namespace slskd /// public class ScriptRunOptions : IValidatableObject { + /// + /// Gets the shell command to run. + /// + public string Command { get; init; } + /// /// Gets the executable to start. /// public string Executable { get; init; } /// - /// Gets the command to run. + /// Gets the arguments to pass to the executable. /// - public string Command { get; init; } + public string Args { get; init; } public IEnumerable Validate(ValidationContext validationContext) { - if (string.IsNullOrWhiteSpace(Executable) && string.IsNullOrWhiteSpace(Command)) + var cmdIsSet = !string.IsNullOrWhiteSpace(Command); + var exeIsSet = !string.IsNullOrWhiteSpace(Executable); + + if ((cmdIsSet && exeIsSet) || (!cmdIsSet && !exeIsSet)) { - yield return new ValidationResult($"At least one of the {nameof(Executable)} and {nameof(Command)} fields must be specified"); + yield return new ValidationResult($"One and only one of the fields {nameof(Command)} or {nameof(Executable)} may be specified for a single script"); } } } -- cgit v1.2.3 From 03265e1a8429adfb0d087f87570aa46dcaa15075 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 17 Feb 2025 14:15:34 -0600 Subject: add DefaultCommandPrefix --- src/slskd/Integrations/Scripts/ScriptService.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 1a010a80..091ea05d 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -42,10 +42,12 @@ public class ScriptService if (OperatingSystem.IsWindows()) { DefaultExecutable = "cmd.exe"; + DefaultCommandPrefix = "/c"; } else { DefaultExecutable = Environment.GetEnvironmentVariable("SHELL"); + DefaultCommandPrefix = "-c"; if (string.IsNullOrEmpty(DefaultExecutable)) { @@ -61,6 +63,7 @@ public class ScriptService private IOptionsMonitor OptionsMonitor { get; } private EventBus Events { get; } private string DefaultExecutable { get; } + private string DefaultCommandPrefix { get; } private async Task HandleEvent(Event data) { -- cgit v1.2.3 From 97b7e5cbf0bf717fedc1d52f1a2a6e1a462f87f4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 17 Feb 2025 14:16:08 -0600 Subject: negotiate exe and args --- src/slskd/Integrations/Scripts/ScriptService.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 091ea05d..48b7484a 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -88,8 +88,21 @@ public class ScriptService try { var run = script.Value.Run; - string executable = run.Executable ?? DefaultExecutable; - string args = run.Command; + string executable = default; + string args = default; + + // 'command mode' takes precedence over 'executable' mode + // run the system shell and ensure the specified command is prefixed with the correct flag + if (!string.IsNullOrEmpty(run.Command)) + { + executable = DefaultExecutable; + args = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} {run.Command}"; + } + else + { + executable = run.Executable ?? DefaultExecutable; + args = run.Args; + } if (string.IsNullOrEmpty(executable)) { -- cgit v1.2.3 From 8c443b2fe6240c8f666f4781b1b21579ff8523b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Feb 2025 16:46:17 -0600 Subject: add ArgsList --- src/slskd/Core/Options.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6f8e5682..440cd8a4 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2178,8 +2178,19 @@ namespace slskd /// /// Gets the arguments to pass to the executable. /// + /// + /// Mutually exclusive with . + /// public string Args { get; init; } + /// + /// Gets the list of arguments to pass to the executable. + /// + /// + /// Mutually exclusive with . + /// + public string[] ArgsList { get; init; } = null; + public IEnumerable Validate(ValidationContext validationContext) { var cmdIsSet = !string.IsNullOrWhiteSpace(Command); @@ -2189,6 +2200,14 @@ namespace slskd { yield return new ValidationResult($"One and only one of the fields {nameof(Command)} or {nameof(Executable)} may be specified for a single script"); } + + var argsIsSet = !string.IsNullOrWhiteSpace(Args); + var argsListIsSet = ArgsList is not null; + + if (argsIsSet && argsListIsSet) + { + yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(ArgsList)} may be specified for a single script"); + } } } -- cgit v1.2.3 From f435c1e2e58c16cf33098bab4f946bb7fa0c30be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Feb 2025 17:00:01 -0600 Subject: adjust validation messages --- src/slskd/Core/Options.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 440cd8a4..5c9c756c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2198,7 +2198,7 @@ namespace slskd 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"); + 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); @@ -2206,7 +2206,7 @@ namespace slskd if (argsIsSet && argsListIsSet) { - yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(ArgsList)} may be specified for a single script"); + yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(ArgsList)} 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."); } } } -- cgit v1.2.3 From 3d48f846bc90d299fa2bf0d22d868aada4ad00ff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Feb 2025 17:14:42 -0600 Subject: codify running modes --- src/slskd/Integrations/Scripts/ScriptService.cs | 91 +++++++++++++++++-------- 1 file changed, 63 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 48b7484a..6c289832 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -85,48 +85,83 @@ public class ScriptService 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; - string executable = default; - string args = default; + var executable = run.Executable ?? DefaultExecutable; + + if (string.IsNullOrEmpty(executable)) + { + 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; + } - // 'command mode' takes precedence over 'executable' mode - // run the system shell and ensure the specified command is prefixed with the correct flag if (!string.IsNullOrEmpty(run.Command)) { - executable = DefaultExecutable; - args = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} {run.Command}"; + // '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 + process = new Process() + { + 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}", + }, + }; } - else + else if (run.ArgsList is not null) { - executable = run.Executable ?? DefaultExecutable; - args = run.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 + process = new Process() + { + StartInfo = new ProcessStartInfo( + fileName: executable, + arguments: run.ArgsList) + { + WorkingDirectory = Program.ScriptDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }, + }; } - - if (string.IsNullOrEmpty(executable)) + else { - 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; + // '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 + process = new Process() + { + StartInfo = new ProcessStartInfo(fileName: executable) + { + WorkingDirectory = Program.ScriptDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + Arguments = run.Args, + }, + }; } - Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, args, processId); + Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.ArgsList), processId); var sw = Stopwatch.StartNew(); - process = new Process() - { - StartInfo = new ProcessStartInfo(executable ?? DefaultExecutable) - { - WorkingDirectory = Program.ScriptDirectory, - UseShellExecute = false, - CreateNoWindow = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - Arguments = args, - }, - }; - - process.StartInfo.Environment.Clear(); process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = data.ToJson(); process.Start(); -- cgit v1.2.3 From e22f14e9d12d4bb53d3b802b7bbd5a445e2afbed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 25 Feb 2025 22:02:02 -0600 Subject: quote command --- src/slskd/Integrations/Scripts/ScriptService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 6c289832..0d789a91 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -115,7 +115,7 @@ public class ScriptService CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, - Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} {run.Command}", + Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} \"{run.Command}\"", }, }; } -- cgit v1.2.3 From a39936fe06d623967f68dc0f154c487657106dc3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 25 Feb 2025 22:02:13 -0600 Subject: fix null ref --- src/slskd/Integrations/Scripts/ScriptService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 0d789a91..d4e90d7e 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -159,7 +159,7 @@ public class ScriptService }; } - Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.ArgsList), processId); + Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.ArgsList ?? []), processId); var sw = Stopwatch.StartNew(); process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = data.ToJson(); -- cgit v1.2.3 From bc622aab1f445d27a323daa3a64a25c27fa73307 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 Feb 2025 22:12:55 -0600 Subject: add logs to indicate mode --- src/slskd/Integrations/Scripts/ScriptService.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index d4e90d7e..3a05df04 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -106,6 +106,8 @@ public class ScriptService // 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() { StartInfo = new ProcessStartInfo(fileName: executable) @@ -126,6 +128,8 @@ public class ScriptService // 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( @@ -145,6 +149,7 @@ public class ScriptService // '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) -- cgit v1.2.3 From d56505cb9528ef5b950c9a2e0ed99555ed23e201 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 1 Mar 2025 18:10:55 -0600 Subject: ArgsList -> Arglist --- src/slskd/Core/Options.cs | 8 ++++---- src/slskd/Integrations/Scripts/ScriptService.cs | 9 +++++---- 2 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 5c9c756c..266d04aa 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2179,7 +2179,7 @@ namespace slskd /// Gets the arguments to pass to the executable. /// /// - /// Mutually exclusive with . + /// Mutually exclusive with . /// public string Args { get; init; } @@ -2189,7 +2189,7 @@ namespace slskd /// /// Mutually exclusive with . /// - public string[] ArgsList { get; init; } = null; + public string[] Arglist { get; init; } = null; public IEnumerable Validate(ValidationContext validationContext) { @@ -2202,11 +2202,11 @@ namespace slskd } var argsIsSet = !string.IsNullOrWhiteSpace(Args); - var argsListIsSet = ArgsList is not null; + var argsListIsSet = Arglist is not null; if (argsIsSet && argsListIsSet) { - yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(ArgsList)} 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."); + 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."); } } } diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 3a05df04..dacead33 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -121,7 +121,7 @@ public class ScriptService }, }; } - else if (run.ArgsList is not null) + else if (run.Arglist is not null) { // 'args list' mode takes precedence over 'args' mode // the supplied list of args will be passed to the constructor of ProcessStartInfo, which is @@ -134,7 +134,7 @@ public class ScriptService { StartInfo = new ProcessStartInfo( fileName: executable, - arguments: run.ArgsList) + arguments: run.Arglist) { WorkingDirectory = Program.ScriptDirectory, UseShellExecute = false, @@ -164,7 +164,7 @@ public class ScriptService }; } - Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.ArgsList ?? []), processId); + 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(); @@ -187,7 +187,8 @@ public class ScriptService } catch (Exception ex) { - Log.Warning(ex, "Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId); + 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 { -- cgit v1.2.3 From 9c50ae8b5d6e9b6de3d2a3fa26ed6317f50c4433 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 1 Mar 2025 18:50:37 -0600 Subject: fix issue with quoted commands --- src/slskd/Integrations/Scripts/ScriptService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index dacead33..05769a6d 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -117,7 +117,7 @@ public class ScriptService CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, - Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} \"{run.Command}\"", + Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} \"{run.Command.Trim('"')}\"", }, }; } -- cgit v1.2.3