From 2950b16e08e4c18edb03bba299baef1faf7cb6f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Jan 2025 20:25:59 -0600 Subject: clean up dangling searches at startup --- src/slskd/Application.cs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 05f62902..82429b5f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -312,7 +312,7 @@ namespace slskd // disposition them as having failed due to an application shutdown, instead of some random exception thrown while // things are being disposed. var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed), includeRemoved: false) - .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 + .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 .ToList(); foreach (var upload in activeUploads) @@ -324,7 +324,7 @@ namespace slskd } var activeDownloads = Transfers.Downloads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed) - .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 + .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 .ToList(); foreach (var download in activeDownloads) @@ -335,6 +335,26 @@ namespace slskd Transfers.Downloads.Update(download); } + /* + search records can be left 'dangling' as well. responses are held in memory and saved to the database + when the search is complete, so when a search 'dangles' all responses have been lost. to avoid discrepancies, + we need to zero the response and file counts as well as set the state and EndedAt. + */ + var activeSearches = (await Search.ListAsync(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed))) + .Where(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed)) // https://github.com/slskd/slskd/issues/1280 + .ToList(); + + foreach (var search in activeSearches) + { + Log.Debug("Cleaning up dangling search {Query}", search.SearchText); + search.Responses = []; + search.ResponseCount = 0; + search.FileCount = 0; + search.LockedFileCount = 0; + search.State = SearchStates.Completed | SearchStates.TimedOut; + search.EndedAt = DateTime.UtcNow; + } + // save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in. // we need to check the database before we re-request to make sure the user didn't remove them from the UI while // the application was running, but before it was logged in. so just save the ids. -- cgit v1.2.3 From 71d8c3d233458fde02d7b169380ad347aaf88342 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Jan 2025 20:40:12 -0600 Subject: add a public Update() method, refactor to use it internally --- src/slskd/Search/SearchService.cs | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 809647b2..f91714f5 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -64,6 +64,15 @@ namespace slskd.Search /// The list of searches matching the specified expression, or all searches if no expression is specified. Task> ListAsync(Expression> expression = null); + /// + /// Updates the specified . + /// + /// + /// Round-trips the database; use accordingly. + /// + /// The search to update. + void Update(Search search); + /// /// Performs a search for the specified and . /// @@ -191,6 +200,17 @@ namespace slskd.Search .ToListAsync(); } + /// + /// Updates the specified . + /// + /// The search to update. + public void Update(Search search) + { + using var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); + } + /// /// Performs a search for the specified and . /// @@ -223,20 +243,13 @@ namespace slskd.Search List responses = new(); - void UpdateAndSaveChanges(Search search) - { - using var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); - } - options ??= new SearchOptions(); options = options.WithActions( stateChanged: (args) => { search = search.WithSoulseekSearch(args.Search); SearchHub.BroadcastUpdateAsync(search); - UpdateAndSaveChanges(search); + Update(search); }, responseReceived: (args) => rateLimiter.Invoke(() => { @@ -250,7 +263,7 @@ namespace slskd.Search // note that we're not actually doing anything with the response here, that's happening in the // response handler. we're only updating counts here. SearchHub.BroadcastUpdateAsync(search); - UpdateAndSaveChanges(search); + Update(search); })); var soulseekSearchTask = Client.SearchAsync( @@ -278,7 +291,7 @@ namespace slskd.Search search.EndedAt = DateTime.UtcNow; search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); - UpdateAndSaveChanges(search); + Update(search); // zero responses before broadcasting, as we don't want to blast this // data out over the SignalR socket -- cgit v1.2.3 From 301890c323e2248a97c7340d403288d2e6cc4d35 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Jan 2025 20:42:45 -0600 Subject: log when cleaning starts, save updated search --- src/slskd/Application.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 82429b5f..8453386b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -307,6 +307,8 @@ namespace slskd { Log.Information("Application started"); + Log.Debug("Cleaning up any dangling records"); + // if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these // records to be updated if the application has started to shut down so that we can do this cleanup and properly // disposition them as having failed due to an application shutdown, instead of some random exception thrown while @@ -346,13 +348,15 @@ namespace slskd foreach (var search in activeSearches) { - Log.Debug("Cleaning up dangling search {Query}", search.SearchText); + Log.Debug("Cleaning up dangling search {Query} started {StartedAt}", search.SearchText, search.StartedAt); search.Responses = []; search.ResponseCount = 0; search.FileCount = 0; search.LockedFileCount = 0; search.State = SearchStates.Completed | SearchStates.TimedOut; search.EndedAt = DateTime.UtcNow; + + Search.Update(search); } // save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in. -- cgit v1.2.3 From f87d9e7d0da78c4a5016ff16dc26c6b51a6e2cbd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Jan 2025 08:27:27 -0600 Subject: set EndedAt when cleaning up dangling transfers --- src/slskd/Application.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 8453386b..4a2141e9 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -321,6 +321,7 @@ namespace slskd { Log.Debug("Cleaning up dangling upload {Filename} to {Username}", upload.Filename, upload.Username); upload.State = TransferStates.Completed | TransferStates.Errored; + upload.EndedAt = DateTime.UtcNow; upload.Exception = ApplicationShutdownTransferExceptionMessage; Transfers.Uploads.Update(upload); } @@ -333,6 +334,7 @@ namespace slskd { Log.Debug("Cleaning up dangling download {Filename} from {Username}", download.Filename, download.Username); download.State = TransferStates.Completed | TransferStates.Errored; + download.EndedAt = DateTime.UtcNow; download.Exception = ApplicationShutdownTransferExceptionMessage; Transfers.Downloads.Update(download); } -- cgit v1.2.3 From f3b79d3b4e4c79f77f5a9f87f06304ba1222dd12 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Jan 2025 08:35:59 -0600 Subject: consider transfers with no EndedAt to be dangling, including removed transfers --- src/slskd/Application.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 4a2141e9..791cf245 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -313,8 +313,8 @@ namespace slskd // records to be updated if the application has started to shut down so that we can do this cleanup and properly // disposition them as having failed due to an application shutdown, instead of some random exception thrown while // things are being disposed. - var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed), includeRemoved: false) - .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 + var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true) + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 .ToList(); foreach (var upload in activeUploads) @@ -326,8 +326,8 @@ namespace slskd Transfers.Uploads.Update(upload); } - var activeDownloads = Transfers.Downloads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed) - .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 + var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true) + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 .ToList(); foreach (var download in activeDownloads) -- cgit v1.2.3 From bd292cf918c5ae0472fd397123ade86f318f709f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Jan 2025 22:01:33 -0600 Subject: fix search record if it fails --- src/slskd/Search/SearchService.cs | 62 ++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index f91714f5..7f5597b4 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -266,7 +266,9 @@ namespace slskd.Search Update(search); })); - var soulseekSearchTask = Client.SearchAsync( + try + { + var soulseekSearchTask = Client.SearchAsync( query, responseHandler: (response) => responses.Add(response), scope, @@ -274,35 +276,47 @@ namespace slskd.Search options, cancellationToken: cancellationTokenSource.Token); - _ = Task.Run(async () => - { - try - { - var soulseekSearch = await soulseekSearchTask; - search = search.WithSoulseekSearch(soulseekSearch); - } - finally + _ = Task.Run(async () => { - rateLimiter.Dispose(); - CancellationTokens.TryRemove(id, out _); - try { - search.EndedAt = DateTime.UtcNow; - search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); - - Update(search); - - // zero responses before broadcasting, as we don't want to blast this - // data out over the SignalR socket - await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + var soulseekSearch = await soulseekSearchTask; + search = search.WithSoulseekSearch(soulseekSearch); } - catch (Exception ex) + finally { - Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); + rateLimiter.Dispose(); + CancellationTokens.TryRemove(id, out _); + + try + { + search.EndedAt = DateTime.UtcNow; + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); + + Update(search); + + // zero responses before broadcasting, as we don't want to blast this + // data out over the SignalR socket + await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); + } } - } - }); + }); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); + + search.State = SearchStates.Completed | SearchStates.Errored; + search.EndedAt = search.StartedAt; + context.Update(search); + context.SaveChanges(); + + throw; + } await SearchHub.BroadcastCreateAsync(search); -- cgit v1.2.3 From fa0b0a322a6d7be193400873e9fee4d9b91306d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 09:04:31 -0600 Subject: broadcast search created as soon as it is created --- src/slskd/Search/SearchService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 7f5597b4..c4c1003b 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -241,6 +241,8 @@ namespace slskd.Search context.Add(search); context.SaveChanges(); + await SearchHub.BroadcastCreateAsync(search); + List responses = new(); options ??= new SearchOptions(); -- cgit v1.2.3 From b9ac9709e597eb565faad43dc25757873502b31f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 09:05:22 -0600 Subject: docs/indentation --- src/slskd/Search/SearchService.cs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index c4c1003b..a4b59453 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -270,14 +270,19 @@ namespace slskd.Search try { + // initiate the search. this can throw at invocation if there's a problem with + // the client state (e.g. disconnected) or a problem with the search (e.g. no terms) var soulseekSearchTask = Client.SearchAsync( - query, - responseHandler: (response) => responses.Add(response), - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - + query, + responseHandler: (response) => responses.Add(response), + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + // seach looks ok so far; let the rest of the logic run asynchronously + // on a background thread. this logic needs to clean up after itself and + // update the search record to accurately reflect the final state _ = Task.Run(async () => { try -- cgit v1.2.3 From 09a1767fb3abd3614716faa5863c26641a1aa9b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 09:05:40 -0600 Subject: docs --- src/slskd/Search/SearchService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index a4b59453..b3487e1f 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -308,6 +308,7 @@ namespace slskd.Search } catch (Exception ex) { + // record will be left 'hanging' and will need to be cleaned up at the next boot Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); } } -- cgit v1.2.3 From 43abc568fecca208385db6a8c61c534dcc4b051a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 20:37:13 -0600 Subject: tweak sequencing of broadcasts, ensure state is set properly --- src/slskd/Search/SearchService.cs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index b3487e1f..b4864918 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -228,6 +228,8 @@ namespace slskd.Search var rateLimiter = new RateLimiter(250); + // initialize the search record, save it to the database, and broadcast the creation + // we do this so the UI has some feedback to show to the user that we've gotten their request var search = new Search() { SearchText = query.SearchText, @@ -243,6 +245,8 @@ namespace slskd.Search await SearchHub.BroadcastCreateAsync(search); + // initialize the list of responses that we'll use to accumulate them + // populated by the responseHandler we pass to SearchAsync List responses = new(); options ??= new SearchOptions(); @@ -290,6 +294,11 @@ namespace slskd.Search var soulseekSearch = await soulseekSearchTask; search = search.WithSoulseekSearch(soulseekSearch); } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); + search.State = SearchStates.Completed | SearchStates.Errored; + } finally { rateLimiter.Dispose(); @@ -308,27 +317,30 @@ namespace slskd.Search } catch (Exception ex) { - // record will be left 'hanging' and will need to be cleaned up at the next boot + // record may be left 'hanging' and will need to be cleaned up at the next boot Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); } } }); + + await SearchHub.BroadcastUpdateAsync(search); + + return search; } catch (Exception ex) { + // we'll end up here if the initial call throws for an ArgumentException, InvalidOperationException if + // the app isn't connected, and a few other straightforward issues that arise before even requesting the search Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); search.State = SearchStates.Completed | SearchStates.Errored; search.EndedAt = search.StartedAt; - context.Update(search); - context.SaveChanges(); + Update(search); + + await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); throw; } - - await SearchHub.BroadcastCreateAsync(search); - - return search; } /// -- cgit v1.2.3 From bfda68c3aef85a9b98f346f683f75472a4f423b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 20:37:39 -0600 Subject: improve logging --- src/slskd/Search/API/Controllers/SearchesController.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src') diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index d6d96bbe..58e1fe37 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -24,6 +24,7 @@ namespace slskd.Search.API using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; @@ -50,6 +51,7 @@ namespace slskd.Search.API private ISearchService Searches { get; } private IOptionsSnapshot OptionsSnapshot { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); /// /// Performs a search for the specified . @@ -83,12 +85,19 @@ namespace slskd.Search.API } catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); return BadRequest(ex.Message); } catch (InvalidOperationException ex) { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); return Conflict(ex.Message); } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return StatusCode(500, ex.Message); + } return Ok(search); } -- cgit v1.2.3 From daa6baca2e28b480889f7db721d5e1fbbc422723 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 20:39:58 -0600 Subject: stub create handler --- src/web/src/components/Search/Searches.jsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx index 471f833d..362ec4fd 100644 --- a/src/web/src/components/Search/Searches.jsx +++ b/src/web/src/components/Search/Searches.jsx @@ -72,7 +72,9 @@ const Searches = ({ server } = {}) => { }); }); - searchHub.on('create', () => {}); + searchHub.on('create', (search) => { + console.log('search', search); + }); searchHub.onreconnecting((connectionError) => onConnectionError(connectionError?.message ?? 'Disconnected'), -- cgit v1.2.3 From 32e0b716b7cc90b727bb2901b00ad0f41234410d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Jan 2025 22:15:55 -0600 Subject: update UI when 'create' is received --- src/web/src/components/Search/Searches.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx index 362ec4fd..d50462ba 100644 --- a/src/web/src/components/Search/Searches.jsx +++ b/src/web/src/components/Search/Searches.jsx @@ -73,7 +73,7 @@ const Searches = ({ server } = {}) => { }); searchHub.on('create', (search) => { - console.log('search', search); + onUpdate((old) => ({ ...old, [search.id]: search })); }); searchHub.onreconnecting((connectionError) => -- cgit v1.2.3 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 71fe0a4a578fdd9f0945923eb655ddf2a546f1db Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 23 Feb 2025 19:39:31 +0000 Subject: Bump serialize-javascript from 6.0.1 to 6.0.2 in /src/web Bumps [serialize-javascript](https://github.com/yahoo/serialize-javascript) from 6.0.1 to 6.0.2. - [Release notes](https://github.com/yahoo/serialize-javascript/releases) - [Commits](https://github.com/yahoo/serialize-javascript/compare/v6.0.1...v6.0.2) --- updated-dependencies: - dependency-name: serialize-javascript dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 912ea6e9..a61bca8f 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -18432,10 +18432,11 @@ "dev": true }, "node_modules/serialize-javascript": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.1.tgz", - "integrity": "sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "randombytes": "^2.1.0" } -- 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