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/Common') 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 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/Common') 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 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/Common') 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/Common') 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/Common') 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/Common') 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/Common') 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/Common') 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/Common') 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/Common') 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/Common') 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 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/Common') 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