aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-11-07 23:16:26 -0600
committerGitHub <noreply@github.com>2026-11-07 23:16:26 -0600
commitcefdcd02e28b1f02f546002fdd475de4fa03e839 (patch)
tree95bb26f4ed7b60e3739bcd884966a19be1e9ee07 /src/slskd/Common
parent2b827344d11e7490b323defa898264cadbdb6089 (diff)
parentdbc308d5e408a2e194a0c70a8fc7592f776aaf11 (diff)
downloadslskd-cefdcd02e28b1f02f546002fdd475de4fa03e839.tar.gz
Merge pull request #1913 from slskd/bugs
Fix a random assortment of bugs
Diffstat (limited to 'src/slskd/Common')
-rw-r--r--src/slskd/Common/CommonExtensions.cs6
-rw-r--r--src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs87
-rw-r--r--src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs74
-rw-r--r--src/slskd/Common/RateLimiter.cs6
-rw-r--r--src/slskd/Common/Validation/EnumAttribute.cs4
-rw-r--r--src/slskd/Common/Validation/FileExistsAttribute.cs3
-rw-r--r--src/slskd/Common/Validation/StringAttribute.cs2
-rw-r--r--src/slskd/Common/WaitKey.cs6
8 files changed, 115 insertions, 73 deletions
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
/// </summary>
public static class CommonExtensions
{
+ private static readonly JsonSerializerOptions DefaultJsonSerializerOptions = GetJsonSerializerOptions();
+
/// <summary>
/// Times this Task out after the specified TimeSpan.
/// </summary>
@@ -358,7 +360,7 @@ namespace slskd
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <returns>A string containing the serialized object.</returns>
- public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions());
+ public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, DefaultJsonSerializerOptions);
/// <summary>
/// Serializes this object to yaml.
@@ -481,7 +483,7 @@ namespace slskd
/// <typeparam name="T">The type to which to deserialize the string.</typeparam>
/// <param name="str">The string to deserialize.</param>
/// <returns>The new object deserialized from the string.</returns>
- public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, GetJsonSerializerOptions());
+ public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, DefaultJsonSerializerOptions);
/// <summary>
/// Applies the standard json serializer options to the specified instance.
diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
index 68900267..18851c0d 100644
--- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
+++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
@@ -54,7 +54,7 @@ namespace slskd
/// <returns></returns>
public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html, IEnumerable<string> excludedRoutes)
{
- return builder.UseMiddleware<HTMLInjectionMiddleware>(html);
+ return builder.UseMiddleware<HTMLInjectionMiddleware>(html, excludedRoutes);
}
}
@@ -87,9 +87,13 @@ namespace slskd
/// <returns></returns>
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();
@@ -106,46 +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();
-
- var headers = context.Response.Headers
- .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
- .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase));
+ await Next.Invoke(context);
- context.Response.Clear();
-
- 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 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);
+
+ if (!isInjectableResponseType)
+ {
+ await context.Response.WriteAsync(body);
+ }
+ else
+ {
+ await context.Response.WriteAsync(body + HTML);
+ }
}
- // 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);
- }
+ // 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
{
diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
index e91a2352..0c8a8fb2 100644
--- a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
+++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
@@ -87,9 +87,13 @@ namespace slskd
/// <returns></returns>
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();
@@ -106,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
{
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
{
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")}.");
}
diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs
index c4d97a7c..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;
@@ -71,7 +72,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}'");
}
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;
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);
}
/// <summary>
@@ -93,7 +93,7 @@ namespace slskd
/// <returns>A value indicating whether the specified WaitKey is equal to this instance.</returns>
public bool Equals(WaitKey other)
{
- return Token == other.Token;
+ return other is not null && Token == other.Token;
}
/// <summary>