From 48c41217c3c6a884c52e30341f1c39bdabceb0f7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Oct 2026 20:24:25 -0500 Subject: set policy for metrics --- src/slskd/Telemetry/API/MetricsHub.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs index 5dcd4ecc..b6920ef0 100644 --- a/src/slskd/Telemetry/API/MetricsHub.cs +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -42,7 +42,7 @@ public interface IMetricsHub Task Update(object metrics); } -[Authorize] +[Authorize(Policy = AuthPolicy.Any)] public class MetricsHub : Hub { public MetricsHub(MetricsService metricsService) -- cgit v1.2.3 From e4788aed713769aeade0e2ce8a05c75e3986fe8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Oct 2026 20:25:23 -0500 Subject: dispose ephemeral share repositories --- src/slskd/Shares/ShareService.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 054561bf..40603892 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -391,7 +391,11 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)); + using (var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)) + { + Local.Repository.BackupTo(backupRepository); + } + Log.Debug("Shared file cache database backup complete"); Log.Debug("Recomputing share statistics..."); @@ -443,7 +447,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); + using var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { @@ -471,7 +475,7 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); + using var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { -- cgit v1.2.3 From 4b3bc19e6411ea16bf2c6bfe50468ca92034b287 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Oct 2026 22:02:47 -0500 Subject: don't cancel search tasks; can cause 'hanging' --- src/slskd/Search/SearchService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 208e8f9d..4051eeab 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -377,7 +377,7 @@ namespace slskd.Search rateLimiter.Dispose(); CancellationTokens.TryRemove(id, out _); } - }, cancellationToken: cancellationTokenSource.Token); + }); // broadcast and return the _newly created_ search; it will continue to be updated in the background await SearchHub.BroadcastUpdateAsync(search); -- cgit v1.2.3 From c7984d965f4d2d323091d5b87e558ca57a7e1011 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Oct 2026 22:03:15 -0500 Subject: use a thread safe collection for responses --- src/slskd/Search/SearchService.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 4051eeab..8b107084 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -271,7 +271,8 @@ namespace slskd.Search // initialize the list of responses that we'll use to accumulate them // populated by the responseHandler we pass to SearchAsync - List responses = new(); + // responses arrive concurrently from many connections, so this must be thread safe + ConcurrentQueue responses = new(); options ??= new SearchOptions(); options = options.WithActions( @@ -308,7 +309,7 @@ namespace slskd.Search // 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), + responseHandler: (response) => responses.Enqueue(response), scope, token, options, -- cgit v1.2.3 From 151594c755354d0425f2e55069b7386ebf81a563 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Oct 2026 22:12:51 -0500 Subject: extra check if value is a number --- src/slskd/Common/Validation/EnumAttribute.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Validation/EnumAttribute.cs b/src/slskd/Common/Validation/EnumAttribute.cs index fc077bb6..cdbaccda 100644 --- a/src/slskd/Common/Validation/EnumAttribute.cs +++ b/src/slskd/Common/Validation/EnumAttribute.cs @@ -60,14 +60,14 @@ namespace slskd.Validation return new ValidationResult($"The {validationContext.DisplayName} field contains one or more null or empty values"); } - if (array.Any(x => !Enum.TryParse(TargetType, x, IgnoreCase, out _))) + if (array.Any(x => !Enum.TryParse(TargetType, x, IgnoreCase, out var parsed) || !Enum.IsDefined(TargetType, parsed))) { return new ValidationResult($"The elements in the {validationContext.DisplayName} field must all be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); } } else { - if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + if (value != null && (!Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out var parsed) || !Enum.IsDefined(TargetType, parsed))) { return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); } -- cgit v1.2.3 From 06a7849bd93108a4f96427e26007494da276382b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Oct 2026 22:14:44 -0500 Subject: fix missing arg in log --- src/slskd/Integrations/Scripts/ScriptService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 33ef0b9b..8fb0f74d 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -123,7 +123,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."); + 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.", script.Key); return; } -- cgit v1.2.3 From 3e61fd10d693a45c520b7436097919bc68eface0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 09:53:21 -0500 Subject: cache default serializer options --- src/slskd/Common/CommonExtensions.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 95721163..47e4aee1 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -53,6 +53,8 @@ namespace slskd /// public static class CommonExtensions { + private static readonly JsonSerializerOptions DefaultJsonSerializerOptions = GetJsonSerializerOptions(); + /// /// Times this Task out after the specified TimeSpan. /// @@ -358,7 +360,7 @@ namespace slskd /// /// The object to serialize. /// A string containing the serialized object. - public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions()); + public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, DefaultJsonSerializerOptions); /// /// Serializes this object to yaml. @@ -481,7 +483,7 @@ namespace slskd /// The type to which to deserialize the string. /// The string to deserialize. /// The new object deserialized from the string. - public static T FromJson(this string str) => JsonSerializer.Deserialize(str, GetJsonSerializerOptions()); + public static T FromJson(this string str) => JsonSerializer.Deserialize(str, DefaultJsonSerializerOptions); /// /// Applies the standard json serializer options to the specified instance. -- cgit v1.2.3 From ed922f1963148db85f256066c0c55cb5f308c2d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 10:27:57 -0500 Subject: fix bug resolving links --- src/slskd/Files/FileService.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 70bfc293..7cce5198 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -103,9 +103,11 @@ namespace slskd.Files // we should only get this far if: // 1) the given file exists and // 2) it is a symlink, meaning this line _SHOULD_ be guaranteed to return an instance of FileInfo. + FileInfo resolved; + try { - info = (FileInfo)info.ResolveLinkTarget(returnFinalTarget: true); + resolved = (FileInfo)info.ResolveLinkTarget(returnFinalTarget: true); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) { @@ -117,13 +119,13 @@ namespace slskd.Files throw new IOException($"Failed to resolve FileInfo for linked file '{info.Name}->{info.LinkTarget}': {ex.Message}", ex); } - if (info is null) + if (resolved is null) { Log.Error("Resolved FileInfo for linked file '{File}->{Link}' was unexpectedly null", info.Name, info.LinkTarget); throw new IOException($"An unexpected error was encountered while resolving FileInfo for linked file '{info.Name}->{info.LinkTarget}'"); } - return info; + return resolved; } /// -- cgit v1.2.3 From e14c0a6b31d801118949408e12feae6bd43ea6da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 10:57:58 -0500 Subject: improve behavior when kicking off scan --- src/slskd/Shares/API/Controllers/SharesController.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 76ec4643..1ce1f88e 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -153,15 +153,13 @@ namespace slskd.Shares.API [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { - try + if (Shares.StateMonitor.CurrentValue.Scanning) { - _ = Shares.ScanAsync(); - } - catch (ShareScanInProgressException) - { - return Conflict("A share scan is already in progress."); + return Conflict("A share scan is already in progress"); } + _ = Shares.ScanAsync(); + return Ok(); } -- cgit v1.2.3 From e8f3b105f91cdc64a6b27f807b61a84badf17f3d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:24:46 -0500 Subject: check parsed enums --- src/slskd/Telemetry/API/ReportsController.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index ccb45daf..02b962e1 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -104,7 +104,7 @@ public class ReportsController : ControllerBase if (!string.IsNullOrWhiteSpace(direction)) { - if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -205,7 +205,7 @@ public class ReportsController : ControllerBase if (!string.IsNullOrWhiteSpace(direction)) { - if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -263,7 +263,7 @@ public class ReportsController : ControllerBase return BadRequest("Direction is required"); } - if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -276,12 +276,12 @@ public class ReportsController : ControllerBase return BadRequest("End time must be later than start time"); } - if (!Enum.TryParse(sortBy, out var parsedSortBy)) + if (!Enum.TryParse(sortBy, out var parsedSortBy) || !Enum.IsDefined(parsedSortBy)) { return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}"); } - if (!Enum.TryParse(sortOrder, out var parsedSortOrder)) + if (!Enum.TryParse(sortOrder, out var parsedSortOrder) || !Enum.IsDefined(parsedSortOrder)) { return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}"); } @@ -425,7 +425,7 @@ public class ReportsController : ControllerBase return BadRequest("Direction is required"); } - if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -438,7 +438,7 @@ public class ReportsController : ControllerBase return BadRequest("End time must be later than start time"); } - if (!Enum.TryParse(sortOrder, out var parsedSortOrder)) + if (!Enum.TryParse(sortOrder, out var parsedSortOrder) || !Enum.IsDefined(parsedSortOrder)) { return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}"); } @@ -502,7 +502,7 @@ public class ReportsController : ControllerBase return BadRequest("Direction is required"); } - if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } -- cgit v1.2.3 From 6f05ff65e10b8eac8d676d3c69ff1bed1a5b69cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:30:11 -0500 Subject: make wait key operators null-safe --- src/slskd/Common/WaitKey.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/WaitKey.cs b/src/slskd/Common/WaitKey.cs index af71af7a..3306103d 100644 --- a/src/slskd/Common/WaitKey.cs +++ b/src/slskd/Common/WaitKey.cs @@ -61,12 +61,12 @@ namespace slskd public static bool operator !=(WaitKey lhs, WaitKey rhs) { - return !lhs.Equals(rhs); + return !(lhs == rhs); } public static bool operator ==(WaitKey lhs, WaitKey rhs) { - return lhs.Equals(rhs); + return lhs is null ? rhs is null : lhs.Equals(rhs); } /// @@ -93,7 +93,7 @@ namespace slskd /// A value indicating whether the specified WaitKey is equal to this instance. public bool Equals(WaitKey other) { - return Token == other.Token; + return other is not null && Token == other.Token; } /// -- cgit v1.2.3 From d1c2e879d159f0e20a218a58348be436116134e9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:36:38 -0500 Subject: avoid a race in rate limiter --- src/slskd/Common/RateLimiter.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs index ac34ed5d..7229441f 100644 --- a/src/slskd/Common/RateLimiter.cs +++ b/src/slskd/Common/RateLimiter.cs @@ -97,6 +97,7 @@ namespace slskd return; } + // previously staged action is lost, intentionally Staged = action; } @@ -131,8 +132,11 @@ namespace slskd { try { - Staged?.Invoke(); + // capture the staged action before nulling it to avoid + // a race where another action might slip in between the invoke and null + var staged = Staged; Staged = null; + staged?.Invoke(); } finally { -- cgit v1.2.3 From 404643e58ca7210b1f499e0e4b2f2c04676d1017 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:37:01 -0500 Subject: fix validation message --- src/slskd/Common/Validation/StringAttribute.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs index bb323ba2..d656a047 100644 --- a/src/slskd/Common/Validation/StringAttribute.cs +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -90,7 +90,7 @@ namespace slskd.Validation if (Pattern is not null && Pattern.IsMatch(val)) { - return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}"); + return new ValidationResult($"The {validationContext.DisplayName} field must not match the regular expression {Pattern.ToJson()}"); } return ValidationResult.Success; -- cgit v1.2.3 From 9a4d777f43f93fcb5aabcb2ea7b437a1c39f0f0e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:37:36 -0500 Subject: better error trapping --- src/slskd/Common/Validation/FileExistsAttribute.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index c4d97a7c..4343dec9 100644 --- a/src/slskd/Common/Validation/FileExistsAttribute.cs +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -71,7 +71,7 @@ namespace slskd.Validation using var fs = File.Open(file, FileMode.Open, FileAccess.Value); fs.Close(); } - catch (IOException) + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { return new ValidationResult($"The {validationContext.DisplayName} field specifies a file '{file}' that cannot be opened for required access '{FileAccess}'"); } -- cgit v1.2.3 From 07d3a08a1d28020f7630de04b2ff0b16969f6c5e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:37:49 -0500 Subject: missed using --- src/slskd/Common/Validation/FileExistsAttribute.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd') diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index 4343dec9..6fc50f63 100644 --- a/src/slskd/Common/Validation/FileExistsAttribute.cs +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -32,6 +32,7 @@ namespace slskd.Validation { + using System; using System.ComponentModel.DataAnnotations; using System.IO; -- cgit v1.2.3 From 93a5f51a030d0500a7d11069d38205e697314699 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:56:54 -0500 Subject: fix rewrite middleware --- src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs index e91a2352..542e2a6c 100644 --- a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs @@ -87,9 +87,13 @@ namespace slskd /// public async Task InvokeAsync(HttpContext context) { + // accept types can have some metadata after the type, separated by a semicolon. example: + // text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 context.Request.Headers.TryGetValue("accept", out var accept); - var requestedTypes = accept.ToString().Split(','); - var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + // split by comma, then drop the semicolon and everything after it (if present) for that type + var requestedTypes = accept.ToString().Split(',').Select(type => type.Split(';')[0].Trim()); + var injectableTypes = new[] { "text/html", "application/xhtml+xml", "application/xml" }; var isRewriteableType = requestedTypes .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) .Any(); -- cgit v1.2.3 From 79ee67b09c7d0f45ac586c7375ed329f238b93f7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 19:59:03 -0500 Subject: fix injection middleware --- src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index 68900267..f14307c8 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -54,7 +54,7 @@ namespace slskd /// public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html, IEnumerable excludedRoutes) { - return builder.UseMiddleware(html); + return builder.UseMiddleware(html, excludedRoutes); } } @@ -87,9 +87,13 @@ namespace slskd /// public async Task InvokeAsync(HttpContext context) { + // accept types can have some metadata after the type, separated by a semicolon. example: + // text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 context.Request.Headers.TryGetValue("accept", out var accept); - var requestedTypes = accept.ToString().Split(','); - var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + // split by comma, then drop the semicolon and everything after it (if present) for that type + var requestedTypes = accept.ToString().Split(',').Select(type => type.Split(';')[0].Trim()); + var injectableTypes = new[] { "text/html", "application/xhtml+xml", "application/xml" }; var isInjectableType = requestedTypes .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) .Any(); -- cgit v1.2.3 From dad997da75fbccdad4988cea9ce9147f72b493a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 20:04:59 -0500 Subject: drop junk after the semicolon --- src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index f14307c8..4f3a743b 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -130,18 +130,9 @@ namespace slskd context.Response.Headers.Add(header); } - // check the response content type to make sure it's still injectable. the server might return something other - // than what was requested. if it's no longer injectable, don't inject. - var isInjectableResponseType = injectableTypes.Any(injectableType => context.Response.Headers.ContentType.Contains(injectableType)); - if (!isInjectableResponseType) - { - await context.Response.WriteAsync(body); - } - else - { - await context.Response.WriteAsync(body + HTML); - } - } + // drop the semicolon and everything after it (e.g. '; charset=utf-8') before comparing + var responseType = context.Response.ContentType?.Split(';')[0].Trim(); + var isInjectableResponseType = injectableTypes.Contains(responseType, StringComparer.InvariantCultureIgnoreCase); // rewind the stream we injected to the beginning, then replay the data to the // original stream -- cgit v1.2.3 From be0bc671c057babfd953300066806e5f79a6ce0e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 20:08:21 -0500 Subject: ensure exception can be returned if injection throws --- .../Common/Middleware/HTMLInjectionMiddleware.cs | 60 ++++++++++++++-------- 1 file changed, 39 insertions(+), 21 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index 4f3a743b..18851c0d 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -110,37 +110,55 @@ namespace slskd var stream = new MemoryStream(); context.Response.Body = stream; - await Next.Invoke(context); - - if (context.Response.StatusCode == 200) + try { - // something downstream responded with a 200, meaning there's data in the body - // we need to read it, so we can reset then play it back with the modified HTML - context.Response.Body.Seek(0, SeekOrigin.Begin); - var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + await Next.Invoke(context); - var headers = context.Response.Headers - .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) - .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); + if (context.Response.StatusCode == 200) + { + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the modified HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); - context.Response.Clear(); + var headers = context.Response.Headers + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); - foreach (var header in headers) - { - context.Response.Headers.Add(header); - } + context.Response.Clear(); + + foreach (var header in headers) + { + context.Response.Headers.Add(header); + } + // check the response content type to make sure it's still injectable. the server might return something other + // than what was requested. if it's no longer injectable, don't inject. // drop the semicolon and everything after it (e.g. '; charset=utf-8') before comparing var responseType = context.Response.ContentType?.Split(';')[0].Trim(); var isInjectableResponseType = injectableTypes.Contains(responseType, StringComparer.InvariantCultureIgnoreCase); - // rewind the stream we injected to the beginning, then replay the data to the - // original stream - stream.Seek(0, SeekOrigin.Begin); - await stream.CopyToAsync(originalStream); + if (!isInjectableResponseType) + { + await context.Response.WriteAsync(body); + } + else + { + await context.Response.WriteAsync(body + HTML); + } + } - // swap the original stream back in - context.Response.Body = originalStream; + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + } + finally + { + // swap the original stream back in, even if something downstream threw, so that + // upstream middleware (e.g. the exception handler) can write to the response + context.Response.Body = originalStream; + } } else { -- cgit v1.2.3 From 4633465c8f35edea49a4c6ebb3df00334969d553 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 20:09:42 -0500 Subject: handle infinity? --- src/slskd/Telemetry/PrometheusService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Telemetry/PrometheusService.cs b/src/slskd/Telemetry/PrometheusService.cs index 9c1e46c5..f4467074 100644 --- a/src/slskd/Telemetry/PrometheusService.cs +++ b/src/slskd/Telemetry/PrometheusService.cs @@ -137,7 +137,9 @@ public class PrometheusService var groups = match.Groups; var sampleName = groups[1].Value; var sampleLabels = groups[2].Value; - var sampleValue = double.Parse(groups[3].Value); + + // the exposition format is culture invariant, and uses '+Inf'/'-Inf' which .NET doesn't recognize + var sampleValue = double.Parse(groups[3].Value.Replace("Inf", "Infinity"), NumberStyles.Float, CultureInfo.InvariantCulture); var labels = ParseLabels(sampleLabels); if (type.Equals("counter") || type.Equals("gauge")) -- cgit v1.2.3 From 89a36d7b8fdadbf9f9905c6681d975b70fd0c6c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 20:09:59 -0500 Subject: globalization was a mistake --- src/slskd/Telemetry/PrometheusService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd') diff --git a/src/slskd/Telemetry/PrometheusService.cs b/src/slskd/Telemetry/PrometheusService.cs index f4467074..a26c8283 100644 --- a/src/slskd/Telemetry/PrometheusService.cs +++ b/src/slskd/Telemetry/PrometheusService.cs @@ -34,6 +34,7 @@ namespace slskd.Telemetry; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; -- cgit v1.2.3 From 70e99d376373a235186d6069728b90c5f43ede23 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 20:53:31 -0500 Subject: make rewrite resilent --- .../Common/Middleware/HTMLRewriteMiddleware.cs | 66 ++++++++++++++-------- 1 file changed, 42 insertions(+), 24 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs index 542e2a6c..0c8a8fb2 100644 --- a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs @@ -110,36 +110,54 @@ namespace slskd var stream = new MemoryStream(); context.Response.Body = stream; - await Next.Invoke(context); - - if (context.Response.StatusCode == 200) + try { - // something downstream responded with a 200, meaning there's data in the body - // we need to read it, so we can reset then play it back with the modified HTML - context.Response.Body.Seek(0, SeekOrigin.Begin); - var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); - - var headers = context.Response.Headers - .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) - .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); - - context.Response.Clear(); + await Next.Invoke(context); - foreach (var header in headers) + if (context.Response.StatusCode == 200) { - context.Response.Headers.Add(header); + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the modified HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + var headers = context.Response.Headers + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); + + context.Response.Clear(); + + foreach (var header in headers) + { + context.Response.Headers.Add(header); + } + + // check the response content type to make sure it's still rewriteable. the server might return something other + // than what was requested. if it's no longer rewriteable, don't rewrite. + // drop the semicolon and everything after it (e.g. '; charset=utf-8') before comparing + var responseType = context.Response.ContentType?.Split(';')[0].Trim(); + var isRewriteableResponseType = injectableTypes.Contains(responseType, StringComparer.InvariantCultureIgnoreCase); + if (!isRewriteableResponseType) + { + await context.Response.WriteAsync(body); + } + else + { + await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement)); + } } - await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement)); + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + } + finally + { + // swap the original stream back in, even if something downstream threw, so that + // upstream middleware (e.g. the exception handler) can write to the response + context.Response.Body = originalStream; } - - // rewind the stream we injected to the beginning, then replay the data to the - // original stream - stream.Seek(0, SeekOrigin.Begin); - await stream.CopyToAsync(originalStream); - - // swap the original stream back in - context.Response.Body = originalStream; } else { -- cgit v1.2.3 From f15ea30dcc444c049e7c25ff1dfe644dad36ab83 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 22:05:58 -0500 Subject: anchor kpi regexes --- src/slskd/Telemetry/API/MetricsController.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Telemetry/API/MetricsController.cs b/src/slskd/Telemetry/API/MetricsController.cs index 1f0efee1..7954bd22 100644 --- a/src/slskd/Telemetry/API/MetricsController.cs +++ b/src/slskd/Telemetry/API/MetricsController.cs @@ -79,13 +79,13 @@ public class MetricsController : ControllerBase /// private List KpiRegexes { get; } = [ - new Regex("slskd_.*", RegexOptions.Compiled), - new Regex("node_(?!cpu)", RegexOptions.Compiled), - new Regex("process_.*", RegexOptions.Compiled), - new Regex("dotnet_total_memory_bytes", RegexOptions.Compiled), - new Regex("system_runtime_[cpu_usage|working_set|alloc_total]", RegexOptions.Compiled), - new Regex("system_net_sockets.*", RegexOptions.Compiled), - new Regex("microsoft_aspnetcore_server_kestrel_[current|total]_connections", RegexOptions.Compiled), + new Regex("^slskd_.*", RegexOptions.Compiled), + new Regex("^node_(?!cpu)", RegexOptions.Compiled), + new Regex("^process_.*", RegexOptions.Compiled), + new Regex("^dotnet_total_memory_bytes", RegexOptions.Compiled), + new Regex("^system_runtime_(cpu_usage|working_set|alloc_total)", RegexOptions.Compiled), + new Regex("^system_net_sockets.*", RegexOptions.Compiled), + new Regex("^microsoft_aspnetcore_server_kestrel_(current|total)_connections", RegexOptions.Compiled), ]; /// -- cgit v1.2.3 From 98aec8ab30b29ad15f1b740bd3a615a772c6367c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 22:06:33 -0500 Subject: fix log --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e055fcd8..982a828d 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1439,7 +1439,7 @@ namespace slskd { if (Users.IsBlacklisted(username, endpoint.Address)) { - Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); + Log.Information("Returned no place in queue for blacklisted user {Username} ({IP})", username, endpoint.Address); return Task.FromResult(null); } -- cgit v1.2.3 From 9f2487f7767931ece68621830ee76441eed9a57c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 22:07:19 -0500 Subject: apply regex options when patching --- src/slskd/Application.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 982a828d..69676406 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1565,8 +1565,15 @@ namespace slskd if (PreviousOptions.Filters.Search.Request.Except(newOptions.Filters.Search.Request).Any() || newOptions.Filters.Search.Request.Except(PreviousOptions.Filters.Search.Request).Any()) { + var regexOptions = RegexOptions.Compiled; + + if (!Flags.CaseSensitiveRegEx) + { + regexOptions |= RegexOptions.IgnoreCase; + } + CompiledSearchRequestFilters = newOptions.Filters.Search.Request - .Select(f => new Regex(f, RegexOptions.Compiled)) + .Select(f => new Regex(f, regexOptions)) .ToList() .AsReadOnly(); -- cgit v1.2.3 From 20951bf6fded64b82211aeb03aa26a72151585bd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Oct 2026 22:07:52 -0500 Subject: coalesece some things --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 69676406..075495a7 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -741,7 +741,7 @@ namespace slskd } bool IsNull(Options.TransfersOptions.LimitsOptions.Limits lim, Options.TransfersOptions.LimitsOptions.Limits global) - => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null); + => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim?.Failures ?? global?.Failures) is null); /* * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. -- cgit v1.2.3 From 87146ea6c1bb39e5c760cc758a7433471a9df95e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Oct 2026 08:33:18 -0500 Subject: improve metrics auth --- src/slskd/Program.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e236886b..e40113e1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1168,12 +1168,14 @@ namespace slskd if (!options.Authentication.Disabled) { var auth = context.Request.Headers["Authorization"].FirstOrDefault(); - var providedCreds = auth?.Split(' ').Last(); + var providedCreds = auth?.Split(' ').Last() ?? string.Empty; var validCreds = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{options.Authentication.Username}:{options.Authentication.Password}")); + // use paranoid FixedTimeEquals to protect against time attacks if (string.IsNullOrEmpty(auth) || - !auth.StartsWith("Basic", StringComparison.InvariantCultureIgnoreCase) || - !string.Equals(providedCreds, validCreds, StringComparison.InvariantCultureIgnoreCase)) + !auth.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase) || + string.IsNullOrEmpty(providedCreds) || + !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(providedCreds), Encoding.UTF8.GetBytes(validCreds))) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return; -- cgit v1.2.3 From 648e98b324917681e17195cd6e411ea846a2996c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Oct 2026 09:12:01 -0500 Subject: fix a few logging bugs --- src/slskd/Program.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e40113e1..1865453f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -525,7 +525,7 @@ namespace slskd if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); + Log.Information("Forwarding logs to Grafana Loki"); } // bootstrap the ASP.NET application @@ -1291,7 +1291,7 @@ namespace slskd var record = new LogRecord() { Timestamp = logEvent.Timestamp.LocalDateTime, - Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'), + Context = logEvent.Properties.TryGetValue("SourceContext", out var sourceContext) ? sourceContext.ToString().TrimStart('"').TrimEnd('"') : null, SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null, Level = logEvent.Level.ToString(), Message = message.TrimStart('"').TrimEnd('"'), @@ -1323,11 +1323,11 @@ namespace slskd if (e.IsTerminating) { - Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating); + Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", exception?.Message); } else { - Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message); + Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception?.Message); } }; } -- cgit v1.2.3 From fe97cb3fcbfaf66374ea09527672a9444d3ef1da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Oct 2026 17:12:56 -0500 Subject: attach stderr and stdout before waiting for exit --- src/slskd/Integrations/Scripts/ScriptService.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 8fb0f74d..f3f0efde 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -108,7 +108,7 @@ public class ScriptService foreach (var script in scriptsTriggeredByThisEventType) { - _ = Task.Run(() => + _ = Task.Run(async () => { Process process = default; var processId = Guid.NewGuid(); @@ -202,17 +202,20 @@ public class ScriptService process.Start(); - process.WaitForExit(); + var errorTask = process.StandardError.ReadToEndAsync(); + var outputTask = process.StandardOutput.ReadToEndAsync(); + + await process.WaitForExitAsync(); sw.Stop(); - var error = process.StandardError.ReadToEnd(); + var error = await errorTask; if (!string.IsNullOrEmpty(error)) { throw new Exception($"STDERR: {Regex.Replace(error, @"\r\n?|\n", " ", RegexOptions.Compiled)}"); } - var result = process.StandardOutput.ReadToEnd(); + var result = await outputTask; var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output} (id: {ProcessId})", script.Key, sw.ElapsedMilliseconds, resultAsLines, processId); -- cgit v1.2.3 From 5b1ecbde01591fef7928992adced759ba75249d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 18:46:53 -0500 Subject: prevent event bus malfunction with Event type --- src/slskd/Events/EventBus.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index 0c9b8e57..72f797ff 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -88,6 +88,15 @@ public class EventBus public virtual void Raise(T data) where T : Event { + // we look up the list of subscribers using T, and then cast the callback to Func, and this breaks when + // T is Event rather than the derived type. the fix for this involves wrapping the callbacks with another delegate + // that performs the proper cast (or just rethinking this approach entirely), so we're just going to throw + // at run-time instead, which the smallest amount of functional testing will surface + if (typeof(T) == typeof(Event)) + { + throw new ArgumentException($"Raise can not be called with a type argument of type Event because the bus can't properly source the list of subscribers. Supply the derived Event Type when calling"); + } + Log.Debug("Handling {Type}: {Data}", typeof(T), data); // save the event to the database before broadcasting to consumers -- cgit v1.2.3 From 6e082e57998e1e3e72ef44c45a36b312ff903263 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 18:47:17 -0500 Subject: raise derived event types to avoid lookup issue --- src/slskd/Events/API/EventsController.cs | 49 +++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 11 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index e031498c..603d07d5 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -148,18 +148,45 @@ public class EventsController : ControllerBase { var d = disambiguator; - Event @event = eventType switch + Event @event; + + // each event must be raised using its concrete type so that the correct subscribers are invoked + switch (eventType) { - EventType.DownloadFileComplete => new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }, - EventType.DownloadDirectoryComplete => new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" }, - EventType.UploadFileComplete => new UploadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }, - EventType.PrivateMessageReceived => new PrivateMessageReceivedEvent { Message = new PrivateMessage { Id = 42, Timestamp = DateTime.UtcNow, Username = $"{d}username", Message = $"{d}message" } }, - EventType.RoomMessageReceived => new RoomMessageReceivedEvent { Message = new RoomMessage { RoomName = $"{d}room", Username = $"{d}username", Message = $"{d}message" } }, - EventType.Noop => new NoopEvent(), - _ => throw new SlskdException($"Event type {eventType} is an enum member but is not handled. Please submit an issue on GitHub."), - }; - - EventBus.Raise(@event); + case EventType.DownloadFileComplete: + var downloadFileComplete = new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }; + EventBus.Raise(downloadFileComplete); + @event = downloadFileComplete; + break; + case EventType.DownloadDirectoryComplete: + var downloadDirectoryComplete = new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" }; + EventBus.Raise(downloadDirectoryComplete); + @event = downloadDirectoryComplete; + break; + case EventType.UploadFileComplete: + var uploadFileComplete = new UploadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }; + EventBus.Raise(uploadFileComplete); + @event = uploadFileComplete; + break; + case EventType.PrivateMessageReceived: + var privateMessageReceived = new PrivateMessageReceivedEvent { Message = new PrivateMessage { Id = 42, Timestamp = DateTime.UtcNow, Username = $"{d}username", Message = $"{d}message" } }; + EventBus.Raise(privateMessageReceived); + @event = privateMessageReceived; + break; + case EventType.RoomMessageReceived: + var roomMessageReceived = new RoomMessageReceivedEvent { Message = new RoomMessage { RoomName = $"{d}room", Username = $"{d}username", Message = $"{d}message" } }; + EventBus.Raise(roomMessageReceived); + @event = roomMessageReceived; + break; + case EventType.Noop: + var noop = new NoopEvent(); + EventBus.Raise(noop); + @event = noop; + break; + default: + throw new SlskdException($"Event type {eventType} is an enum member but is not handled. Please submit an issue on GitHub."); + } + return StatusCode(201, @event); } catch (Exception ex) -- cgit v1.2.3 From 901f05d95785df8f2eb240988a5ec5ad99cb5c86 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 18:49:45 -0500 Subject: retain signal registrations to avoid deregistration --- src/slskd/Application.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 075495a7..461a5fef 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -134,13 +134,13 @@ namespace slskd foreach (var signal in new[] { PosixSignal.SIGINT, PosixSignal.SIGQUIT, PosixSignal.SIGTERM }) { - PosixSignalRegistration.Create(signal, context => + PosixSignals.Add(PosixSignalRegistration.Create(signal, context => { ShuttingDown = true; Program.MasterCancellationTokenSource.Cancel(); Log.Fatal("Received {Signal}", signal); Environment.Exit(1); - }); + })); } OptionsAtStartup = optionsAtStartup; @@ -237,6 +237,7 @@ namespace slskd public static bool IsShuttingDown => Environment.HasShutdownStarted || ShuttingDown; private static bool ShuttingDown { get; set; } = false; + private static List PosixSignals { get; } = []; private ISoulseekClient Client { get; set; } private FileService Files { get; } -- cgit v1.2.3 From bda7ae6c3eca4cf5d2298733c7ee0e3b24d5d1d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 19:05:17 -0500 Subject: docs --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 9aff5195..4bddeba3 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -70,7 +70,7 @@ namespace slskd.Transfers.Uploads /// (such as the upload not being tracked currently). /// /// The Transfer to complete. - /// A value indicating whether a problem was encountered. + /// A value indicating whether a problem was encountered. /// Thrown if the specified Transfer is null. bool TryComplete(Transfer transfer); -- cgit v1.2.3 From e7371f41100fc56eec503fec28c129ea9317a7b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 19:05:44 -0500 Subject: missing param in log --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 4bddeba3..3ad27e63 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -235,7 +235,7 @@ namespace slskd.Transfers.Uploads // todo: deprecate this with improved cancellation handling; it shouldn't be needed if (!upload.TaskCompletionSource.Task.IsCompleted) { - Log.Debug("Upload {File} for {User} was removed without being completed, so it has been cancelled", Path.GetFileName(upload.Filename)); + Log.Debug("Upload {File} for {User} was removed without being completed, so it has been cancelled", Path.GetFileName(upload.Filename), upload.Username); upload.TaskCompletionSource.TrySetCanceled(); } -- cgit v1.2.3 From c33fd207076d63242f8d0be112051967ddf891db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 19:06:32 -0500 Subject: set User property of user dict items --- src/slskd/Users/UserService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 3ce827c8..09d70d2e 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -444,7 +444,7 @@ namespace slskd.Users { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Status = new Status { IsPrivileged = true } }, + addValue: new User() { Username = username, Status = new Status { IsPrivileged = true } }, updateValueFactory: (key, user) => user with { Username = username, Status = user.Status with { IsPrivileged = true } }); } } @@ -564,7 +564,7 @@ namespace slskd.Users { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Statistics = statistics }, + addValue: new User() { Username = username, Statistics = statistics }, updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); } @@ -572,7 +572,7 @@ namespace slskd.Users { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Status = status }, + addValue: new User() { Username = username, Status = status }, updateValueFactory: (key, user) => user with { Username = username, Status = status }); } } -- cgit v1.2.3 From 053e68f5ca0acf8e3f0ec914b4136a22a4a1b6db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 19:07:01 -0500 Subject: don't return place in queue for uploads --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index cb9423bc..c9095dd5 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -722,9 +722,9 @@ namespace slskd.Transfers.Downloads var transfer = context.Transfers.Find(id); - if (transfer == default) + if (transfer == default || transfer.Direction != TransferDirection.Download) { - throw new NotFoundException($"No download matching id ${id}"); + throw new NotFoundException($"No download matching id {id}"); } var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); -- cgit v1.2.3 From 48dc932c5fad4bb01933eedc5355f5e0c2433ec9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 19:07:50 -0500 Subject: take last exception when finalizing --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c9095dd5..d847f79c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1059,6 +1059,12 @@ namespace slskd.Transfers.Downloads t.EndedAt ??= DateTime.UtcNow; + // Retry.Do() wraps failures in an AggregateException; use the most recent so that the state reflects what happened + if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count > 0) + { + exception = aggregate.InnerExceptions[^1]; + } + // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking // exceptions in a database. when we encounter one of these, drop the first segment. var m = exception.Message; -- cgit v1.2.3 From 47c0c9fccbe976c1d1f8f71c6b0bfd45bceda1a4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Oct 2026 19:09:43 -0500 Subject: set state to Rejected when rejected --- src/slskd/Transfers/Downloads/DownloadService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d847f79c..35359d2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1076,6 +1076,7 @@ namespace slskd.Transfers.Downloads { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, + TransferRejectedException => TransferStates.Rejected, _ => TransferStates.Errored, }; } -- cgit v1.2.3 From 73373e2ce4b0939bdc621d60d434d5e0954586ed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Oct 2026 17:44:31 -0500 Subject: fix errant double-copy of transfer properties in download state handler --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 35359d2c..c211c628 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1240,8 +1240,6 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Queued | TransferStates.Locally; } - transfer = transfer.WithSoulseekTransfer(args.Transfer); - Telemetry.Metrics.Update(() => { if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) -- cgit v1.2.3 From 0e50c8fa4c35118f334b2252ae692debb9b11400 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Oct 2026 18:42:29 -0500 Subject: swap .Last() for [^1] --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c211c628..02613756 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1062,7 +1062,7 @@ namespace slskd.Transfers.Downloads // Retry.Do() wraps failures in an AggregateException; use the most recent so that the state reflects what happened if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count > 0) { - exception = aggregate.InnerExceptions[^1]; + exception = aggregate.InnerExceptions.Last(); } // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking -- cgit v1.2.3 From a3474b1ffb078f150bcd3ca0e44adca6ac293750 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Oct 2026 18:44:25 -0500 Subject: improve order of updates to transfer records when failing --- src/slskd/Transfers/Downloads/DownloadService.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 02613756..33bec3ee 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1558,11 +1558,10 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); @@ -1574,11 +1573,10 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); -- cgit v1.2.3 From 9cc83bcbb8cc81e035e62fb1f636dcbf77ea7d19 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Oct 2026 19:22:23 -0500 Subject: improve update order when failing uploads --- src/slskd/Transfers/Uploads/UploadService.cs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 35bb9468..05251ecf 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -516,11 +516,10 @@ namespace slskd.Transfers.Uploads { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); @@ -532,11 +531,10 @@ namespace slskd.Transfers.Uploads { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); @@ -548,11 +546,10 @@ namespace slskd.Transfers.Uploads { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); -- cgit v1.2.3 From 95836a29adfc10ecf65fc41b6ef16368df8846e5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Nov 2026 16:25:33 -0600 Subject: move change of state pending retry to where it won't skew metrics or history --- src/slskd/Transfers/Downloads/DownloadService.cs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 33bec3ee..5a5fe699 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1228,18 +1228,6 @@ namespace slskd.Transfers.Downloads transfer.EnqueuedAt ??= DateTime.UtcNow; } - // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer - // *might* still have remaining retry attempts. leave this non-committal for now, and allow - // the final update after all retry attempts have been exhausted to add it. - // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all - // retries is to look for this flag - if (args.Transfer.State.HasFlag(TransferStates.Completed) - && !args.Transfer.State.HasFlag(TransferStates.Succeeded) - && transfer.Attempts < retryOptions.Attempts) - { - transfer.State = TransferStates.Queued | TransferStates.Locally; - } - Telemetry.Metrics.Update(() => { if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) @@ -1259,6 +1247,18 @@ namespace slskd.Transfers.Downloads stateHistory.Add(transfer.State); + // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer + // *might* still have remaining retry attempts. leave this non-committal for now, and allow + // the final update after all retry attempts have been exhausted to add it. + // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all + // retries is to look for this flag + if (args.Transfer.State.HasFlag(TransferStates.Completed) + && !args.Transfer.State.HasFlag(TransferStates.Succeeded) + && transfer.Attempts < retryOptions.Attempts) + { + transfer.State = TransferStates.Queued | TransferStates.Locally; + } + // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } -- cgit v1.2.3