aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--bin/lint8
-rw-r--r--bin/test121
-rw-r--r--src/slskd/Application.cs18
-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
-rw-r--r--src/slskd/Events/API/EventsController.cs49
-rw-r--r--src/slskd/Events/EventBus.cs9
-rw-r--r--src/slskd/Files/FileService.cs8
-rw-r--r--src/slskd/Integrations/Scripts/ScriptService.cs13
-rw-r--r--src/slskd/Program.cs16
-rw-r--r--src/slskd/Search/SearchService.cs7
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs10
-rw-r--r--src/slskd/Shares/ShareService.cs10
-rw-r--r--src/slskd/Telemetry/API/MetricsController.cs14
-rw-r--r--src/slskd/Telemetry/API/MetricsHub.cs2
-rw-r--r--src/slskd/Telemetry/API/ReportsController.cs16
-rw-r--r--src/slskd/Telemetry/PrometheusService.cs5
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs47
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs4
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs15
-rw-r--r--src/slskd/Users/UserService.cs6
-rw-r--r--src/web/src/components/App.jsx2
-rw-r--r--src/web/src/components/Browse/Browse.jsx9
-rw-r--r--src/web/src/components/Chat/Chat.jsx9
-rw-r--r--src/web/src/components/Rooms/RoomJoinModal.jsx2
-rw-r--r--src/web/src/components/Rooms/Rooms.jsx22
-rw-r--r--src/web/src/components/Search/Response.jsx5
-rw-r--r--src/web/src/components/Search/Searches.jsx16
-rw-r--r--src/web/src/components/Shared/CodeEditor.jsx2
-rw-r--r--src/web/src/components/System/Data/index.jsx12
-rw-r--r--src/web/src/components/System/Events/index.jsx27
-rw-r--r--src/web/src/components/System/Files/Explorer.jsx27
-rw-r--r--src/web/src/components/System/Info/index.jsx3
-rw-r--r--src/web/src/components/System/Logs/Live.jsx5
-rw-r--r--src/web/src/components/System/Options/EditModal.jsx9
-rw-r--r--src/web/src/components/System/Shares/ContentsModal.jsx11
-rw-r--r--src/web/src/components/Transfers/TransferGroup.jsx34
-rw-r--r--src/web/src/components/Transfers/Transfers.jsx2
-rw-r--r--src/web/src/components/Users/User.jsx4
-rw-r--r--src/web/src/components/Users/Users.jsx12
-rw-r--r--src/web/src/lib/api.js2
-rw-r--r--src/web/src/lib/options.js4
-rw-r--r--src/web/src/lib/session.js2
-rw-r--r--tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs204
-rw-r--r--tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs190
51 files changed, 940 insertions, 241 deletions
diff --git a/bin/lint b/bin/lint
index ffb49b35..e31fd7b6 100644
--- a/bin/lint
+++ b/bin/lint
@@ -28,3 +28,11 @@ else
echo $'\n🛠️ dotnet format --verbosity normal\n'
dotnet format --verbosity normal
fi
+
+if [ "$fix" == false ]; then
+ echo $'\n🛠️ npm run lint\n'
+ (cd src/web && npm run lint)
+else
+ echo $'\n🛠️ npm run lint:fix\n'
+ (cd src/web && npm run lint:fix)
+fi
diff --git a/bin/test b/bin/test
new file mode 100644
index 00000000..1c4ccb6d
--- /dev/null
+++ b/bin/test
@@ -0,0 +1,121 @@
+#!/usr/bin/env bash
+set -e
+set -o pipefail
+
+affected=false
+from=""
+unit=false
+integration=false
+web=false
+
+while test $# -gt 0; do
+ case "$1" in
+ -h|--help)
+ echo ''
+ echo 'usage: test [options]'
+ echo ''
+ echo 'options:'
+ echo '-h, --help show help'
+ echo '--unit run only unit tests'
+ echo '--integration run only integration tests'
+ echo '--dotnet run only unit and integration tests'
+ echo '--web run only frontend tests'
+ echo '--all run unit, integration, and frontend tests'
+ echo '--affected run only tests for projects affected by changes (uses dotnet-affected)'
+ echo '--from REF branch or commit to compare against when using --affected. defaults to HEAD'
+ echo ''
+ echo 'with no options, only unit tests are run.'
+ echo ''
+ echo 'examples:'
+ echo ' test'
+ echo ' test --all'
+ echo ' test --web'
+ echo ' test --affected --from master'
+ echo ''
+ exit 0
+ ;;
+ --unit)
+ unit=true
+ shift
+ ;;
+ --integration)
+ integration=true
+ shift
+ ;;
+ --dotnet)
+ unit=true
+ integration=true
+ shift
+ ;;
+ --web)
+ web=true
+ shift
+ ;;
+ --all)
+ unit=true
+ integration=true
+ web=true
+ shift
+ ;;
+ --affected)
+ affected=true
+ shift
+ ;;
+ --from)
+ shift
+ from=$1
+ shift
+ ;;
+ *)
+ echo "error: unknown option '$1'"
+ exit 1
+ ;;
+ esac
+done
+
+if [ "$unit" == false ] && [ "$integration" == false ] && [ "$web" == false ]; then
+ unit=true
+fi
+
+if [ "$unit" == true ] || [ "$integration" == true ]; then
+ pattern=""
+
+ if [ "$unit" == true ]; then
+ pattern="Tests\.Unit\.csproj$"
+ fi
+
+ if [ "$integration" == true ]; then
+ pattern="${pattern:+$pattern|}Tests\.Integration\.csproj$"
+ fi
+
+ if [ "$affected" == true ]; then
+ args=(--format text --dry-run)
+
+ if [ -n "$from" ]; then
+ args+=(--from "$from")
+ fi
+
+ echo $'\n🔍 dotnet tool run dotnet-affected --' "${args[@]}" $'\n'
+
+ dotnet tool restore > /dev/null
+ projects=$(dotnet tool run dotnet-affected -- "${args[@]}" | tr -d '\r' | grep -E '\.csproj$' | grep -E "$pattern" || true)
+ else
+ projects=$(find tests -name '*.csproj' | grep -E "$pattern" || true)
+ fi
+
+ if [ -z "$projects" ]; then
+ echo $'\n🤷 no test projects to run\n'
+ else
+ while IFS= read -r project; do
+ echo $'\n\t🧪 dotnet test' "$project" $'\n'
+ dotnet test "$project"
+ done <<< "$projects"
+ fi
+fi
+
+if [ "$web" == true ]; then
+ echo $'\n\t🧪 npm run test-unattended\n'
+ (cd src/web && npm run test-unattended)
+fi
+
+echo $'\n\t🎉 tests passed!\n'
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index e055fcd8..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<PosixSignalRegistration> PosixSignals { get; } = [];
private ISoulseekClient Client { get; set; }
private FileService Files { get; }
@@ -741,7 +742,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.
@@ -1439,7 +1440,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<int?>(null);
}
@@ -1565,8 +1566,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();
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>
diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs
index 5381f513..2f3f3573 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)
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>(T data)
where T : Event
{
+ // we look up the list of subscribers using T, and then cast the callback to Func<T, Task>, 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
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;
}
/// <summary>
diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs
index 33ef0b9b..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();
@@ -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;
}
@@ -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);
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 372dc998..879f76b7 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -535,7 +535,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
@@ -1178,12 +1178,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;
@@ -1299,7 +1301,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('"'),
@@ -1331,11 +1333,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);
}
};
}
diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs
index 208e8f9d..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<SearchResponse> responses = new();
+ // responses arrive concurrently from many connections, so this must be thread safe
+ ConcurrentQueue<SearchResponse> 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,
@@ -377,7 +378,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);
diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs
index 64d703bd..4e328717 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();
}
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 _))
{
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
/// </summary>
private List<Regex> 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),
];
/// <summary>
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<IMetricsHub>
{
public MetricsHub(MetricsService metricsService)
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<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ if (!Enum.TryParse<TransferDirection>(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<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ if (!Enum.TryParse<TransferDirection>(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<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ if (!Enum.TryParse<TransferDirection>(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<LeaderboardSortBy>(sortBy, out var parsedSortBy))
+ if (!Enum.TryParse<LeaderboardSortBy>(sortBy, out var parsedSortBy) || !Enum.IsDefined(parsedSortBy))
{
return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}");
}
- if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder))
+ if (!Enum.TryParse<SortOrder>(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<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ if (!Enum.TryParse<TransferDirection>(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>(sortOrder, out var parsedSortOrder))
+ if (!Enum.TryParse<SortOrder>(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<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection))
{
return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
}
diff --git a/src/slskd/Telemetry/PrometheusService.cs b/src/slskd/Telemetry/PrometheusService.cs
index 9c1e46c5..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;
@@ -137,7 +138,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"))
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index cb9423bc..5a5fe699 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);
@@ -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.Last();
+ }
+
// 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;
@@ -1070,6 +1076,7 @@ namespace slskd.Transfers.Downloads
{
OperationCanceledException => TransferStates.Cancelled,
TimeoutException => TransferStates.TimedOut,
+ TransferRejectedException => TransferStates.Rejected,
_ => TransferStates.Errored,
};
}
@@ -1221,20 +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;
- }
-
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
-
Telemetry.Metrics.Update(() =>
{
if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State))
@@ -1254,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);
}
@@ -1553,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);
@@ -1569,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);
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index 9aff5195..3ad27e63 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).
/// </summary>
/// <param name="transfer">The Transfer to complete.</param>
- /// <returns>A value indicating whether a problem was encountered.</return>
+ /// <returns>A value indicating whether a problem was encountered.</returns>
/// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
bool TryComplete(Transfer transfer);
@@ -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();
}
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);
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index 51b47d5b..046a87e5 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -452,7 +452,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 } });
}
}
@@ -572,7 +572,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 });
}
@@ -580,7 +580,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 });
}
}
diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx
index 2d2713c4..091cc2f8 100644
--- a/src/web/src/components/App.jsx
+++ b/src/web/src/components/App.jsx
@@ -127,7 +127,7 @@ const ModeSpecificConnectButton = ({
color = 'yellow';
}
- if (server?.isConnecting || server?.IsLoggingIn) {
+ if (server?.isConnecting || server?.isLoggingIn) {
icon = 'sync alternate loading';
color = 'green';
}
diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx
index 44e6b2dd..c6107bd5 100644
--- a/src/web/src/components/Browse/Browse.jsx
+++ b/src/web/src/components/Browse/Browse.jsx
@@ -251,8 +251,13 @@ class Browse extends Component {
return;
}
- const response = await users.getBrowseStatus({ username });
- this.setState({ browseStatus: response.data });
+ try {
+ const response = await users.getBrowseStatus({ username });
+ this.setState({ browseStatus: response.data });
+ } catch {
+ // status is not available until the first progress update, and is removed shortly after completion;
+ // this runs on an interval, so just try again next time
+ }
};
getDirectoryTree = ({ directories, separator }) => {
diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx
index 9224fb30..4fcb44ed 100644
--- a/src/web/src/components/Chat/Chat.jsx
+++ b/src/web/src/components/Chat/Chat.jsx
@@ -60,7 +60,13 @@ class Chat extends Component {
this.setState(
{
active: sessionStorage.getItem(activeChatKey) || '',
- interval: window.setInterval(this.fetchConversations, 5_000),
+ interval: window.setInterval(async () => {
+ try {
+ await this.fetchConversations();
+ } catch (error) {
+ console.error(error);
+ }
+ }, 5_000),
},
async () => {
await this.fetchConversations();
@@ -113,7 +119,6 @@ class Chat extends Component {
// check to see if the active chat is still active
// this will happen whenever a chat is closed/removed
if (activeConversation) {
- console.log('active?', activeConversation);
// *before* fetching messages, ack any unacked messages
// for the active chat
if (activeConversation.hasUnAcknowledgedMessages === true) {
diff --git a/src/web/src/components/Rooms/RoomJoinModal.jsx b/src/web/src/components/Rooms/RoomJoinModal.jsx
index 5a6cf0c2..dd3c7178 100644
--- a/src/web/src/components/Rooms/RoomJoinModal.jsx
+++ b/src/web/src/components/Rooms/RoomJoinModal.jsx
@@ -25,7 +25,7 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
const getAvailableRooms = async () => {
setLoading(true);
const availableResult = await rooms.getAvailable();
- setAvailable(availableResult);
+ setAvailable(availableResult ?? []);
setLoading(false);
};
diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx
index f6bdb685..87fe51be 100644
--- a/src/web/src/components/Rooms/Rooms.jsx
+++ b/src/web/src/components/Rooms/Rooms.jsx
@@ -1,4 +1,4 @@
-import { activeRoomKey } from '../../config';
+import { activeRoomKey, urlBase } from '../../config';
import * as rooms from '../../lib/rooms';
import PlaceholderSegment from '../Shared/PlaceholderSegment';
import RoomMenu from './RoomMenu';
@@ -81,8 +81,20 @@ class Rooms extends Component {
{
active: sessionStorage.getItem(activeRoomKey) || '',
intervals: {
- messages: window.setInterval(this.fetchActiveRoom, 1_000),
- rooms: window.setInterval(this.fetchJoinedRooms, 500),
+ messages: window.setInterval(async () => {
+ try {
+ await this.fetchActiveRoom();
+ } catch (error) {
+ console.error(error);
+ }
+ }, 1_000),
+ rooms: window.setInterval(async () => {
+ try {
+ await this.fetchJoinedRooms();
+ } catch (error) {
+ console.error(error);
+ }
+ }, 500),
},
},
async () => {
@@ -248,13 +260,13 @@ class Rooms extends Component {
};
handleUserProfile = () => {
- this.props.history.push('/users', {
+ this.props.history.push(`${urlBase}/users`, {
user: this.state.contextMenu.message.username,
});
};
handleBrowseShares = () => {
- this.props.history.push('/browse', {
+ this.props.history.push(`${urlBase}/browse`, {
user: this.state.contextMenu.message.username,
});
};
diff --git a/src/web/src/components/Search/Response.jsx b/src/web/src/components/Search/Response.jsx
index 567b80a3..a17df823 100644
--- a/src/web/src/components/Search/Response.jsx
+++ b/src/web/src/components/Search/Response.jsx
@@ -254,8 +254,9 @@ class Response extends Component {
size="large"
/>
<Label>
- {downloadError.data +
- ` (HTTP ${downloadError.status} ${downloadError.statusText})`}
+ {downloadError?.data
+ ? `${downloadError.data} (HTTP ${downloadError.status} ${downloadError.statusText})`
+ : 'Download failed'}
</Label>
</span>
)}
diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx
index d50462ba..9306867c 100644
--- a/src/web/src/components/Search/Searches.jsx
+++ b/src/web/src/components/Search/Searches.jsx
@@ -145,9 +145,11 @@ const Searches = ({ server } = {}) => {
});
setRemoving(false);
- } catch (error_) {
- console.error(error_);
- toast.error(error?.response?.data ?? error?.message ?? error);
+ } catch (removeError) {
+ console.error(removeError);
+ toast.error(
+ removeError?.response?.data ?? removeError?.message ?? removeError,
+ );
setRemoving(false);
}
};
@@ -218,24 +220,24 @@ const Searches = ({ server } = {}) => {
action={
<>
<Button
- disabled={creating || !server.isConnected}
+ disabled={creating || !server?.isConnected}
icon="plus"
onClick={create}
/>
<Button
- disabled={creating || !server.isConnected}
+ disabled={creating || !server?.isConnected}
icon="search"
onClick={() => create({ navigate: true })}
/>
</>
}
className="search-input"
- disabled={creating || !server.isConnected}
+ disabled={creating || !server?.isConnected}
input={
<input
data-lpignore="true"
placeholder={
- server.isConnected
+ server?.isConnected
? 'Search phrase'
: 'Connect to server to perform a search'
}
diff --git a/src/web/src/components/Shared/CodeEditor.jsx b/src/web/src/components/Shared/CodeEditor.jsx
index 8780bc31..b82683de 100644
--- a/src/web/src/components/Shared/CodeEditor.jsx
+++ b/src/web/src/components/Shared/CodeEditor.jsx
@@ -8,8 +8,6 @@ import CodeMirror from '@uiw/react-codemirror';
import React from 'react';
const CodeEditor = ({ onChange = () => {}, theme, value, ...rest }) => {
- console.log(defaultHighlightStyle);
-
return (
<CodeMirror
extensions={[
diff --git a/src/web/src/components/System/Data/index.jsx b/src/web/src/components/System/Data/index.jsx
index 8b6a99eb..2424ea87 100644
--- a/src/web/src/components/System/Data/index.jsx
+++ b/src/web/src/components/System/Data/index.jsx
@@ -5,9 +5,15 @@ import { Button, Divider, Header, Icon } from 'semantic-ui-react';
const clear = async ({ direction, setState }) => {
setState(true);
- await clearCompleted({ direction });
- setState(false);
- toast.success(`Completed ${direction}s cleared!`);
+
+ try {
+ await clearCompleted({ direction });
+ toast.success(`Completed ${direction}s cleared!`);
+ } catch (error) {
+ toast.error(error?.response?.data ?? error?.message ?? error);
+ } finally {
+ setState(false);
+ }
};
const Data = () => {
diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx
index 7f708908..b0549259 100644
--- a/src/web/src/components/System/Events/index.jsx
+++ b/src/web/src/components/System/Events/index.jsx
@@ -17,18 +17,27 @@ const Events = () => {
const fetch = async () => {
setLoading(true);
- const { events: items, totalCount } = await list({
- limit: PER_PAGE,
- offset: (page - 1) * PER_PAGE,
- });
+ try {
+ const { events: items, totalCount } = await list({
+ limit: PER_PAGE,
+ offset: (page - 1) * PER_PAGE,
+ });
- const tp = Math.ceil(totalCount / PER_PAGE);
+ const tp = Math.ceil(totalCount / PER_PAGE);
- setEvents(items);
- setTotalPages(Number.isNaN(tp) ? 0 : tp);
- setLoading(false);
+ setEvents(items);
+ setTotalPages(Number.isNaN(tp) ? 0 : tp);
- return items;
+ return items;
+ } catch (error) {
+ console.error(error);
+ setEvents([]);
+ setTotalPages(0);
+
+ return [];
+ } finally {
+ setLoading(false);
+ }
};
const paginationChanged = ({ activePage }) => {
diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx
index ca0bdba1..a4f0bbbe 100644
--- a/src/web/src/components/System/Files/Explorer.jsx
+++ b/src/web/src/components/System/Files/Explorer.jsx
@@ -9,6 +9,7 @@ const FileRow = ({
length,
modifiedAt,
name,
+ onDeleted,
remoteFileManagement,
root,
subdirectory,
@@ -34,7 +35,7 @@ const FileRow = ({
path: `${subdirectory.join('/')}/${fullName}`,
root,
});
- fetch();
+ onDeleted();
},
},
]}
@@ -66,6 +67,7 @@ const DirectoryRow = ({
modifiedAt,
name,
onClick = () => {},
+ onDeleted,
remoteFileManagement,
root,
subdirectory,
@@ -94,7 +96,7 @@ const DirectoryRow = ({
path: `${subdirectory.join('/')}/${fullName}`,
root,
});
- fetch();
+ onDeleted();
},
},
]}
@@ -131,12 +133,19 @@ const Explorer = ({ remoteFileManagement, root }) => {
const fetch = async () => {
setLoading(true);
- const directoryResult = await list({
- root,
- subdirectory: subdirectory.join('/'),
- });
- setDirectory(directoryResult);
- setLoading(false);
+
+ try {
+ const directoryResult = await list({
+ root,
+ subdirectory: subdirectory.join('/'),
+ });
+ setDirectory(directoryResult);
+ } catch (error) {
+ console.error(error);
+ setDirectory({ directories: [], files: [] });
+ } finally {
+ setLoading(false);
+ }
};
useEffect(() => {
@@ -281,6 +290,7 @@ const Explorer = ({ remoteFileManagement, root }) => {
<DirectoryRow
key={d.name}
onClick={() => select({ path: d.name })}
+ onDeleted={fetch}
remoteFileManagement={remoteFileManagement}
root={root}
subdirectory={subdirectory}
@@ -290,6 +300,7 @@ const Explorer = ({ remoteFileManagement, root }) => {
{sortedFiles?.map((f) => (
<FileRow
key={f.name}
+ onDeleted={fetch}
remoteFileManagement={remoteFileManagement}
root={root}
subdirectory={subdirectory}
diff --git a/src/web/src/components/System/Info/index.jsx b/src/web/src/components/System/Info/index.jsx
index 8672b5df..016b683f 100644
--- a/src/web/src/components/System/Info/index.jsx
+++ b/src/web/src/components/System/Info/index.jsx
@@ -42,8 +42,9 @@ const Info = ({ state, theme }) => {
mediaQuery="(max-width: 686px)"
onClick={() =>
window.open(
- `http://www.slsknet.org/qtlogin.php?username=${state?.user?.username}`,
+ `http://www.slsknet.org/qtlogin.php?username=${encodeURIComponent(state?.user?.username ?? '')}`,
'_blank',
+ 'noopener,noreferrer',
)
}
>
diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx
index 2699a2e3..c572b2f9 100644
--- a/src/web/src/components/System/Logs/Live.jsx
+++ b/src/web/src/components/System/Logs/Live.jsx
@@ -20,6 +20,7 @@ class Live extends Component {
componentDidMount() {
const logsHub = createLogsHubConnection();
+ this.logsHub = logsHub;
logsHub.on('buffer', (buffer) => {
this.setState({
@@ -44,6 +45,10 @@ class Live extends Component {
logsHub.start();
}
+ componentWillUnmount() {
+ this.logsHub?.stop();
+ }
+
nextId = 0;
withId = (log) => ({ ...log, id: this.nextId++ });
diff --git a/src/web/src/components/System/Options/EditModal.jsx b/src/web/src/components/System/Options/EditModal.jsx
index 6fc2af69..0727b83e 100644
--- a/src/web/src/components/System/Options/EditModal.jsx
+++ b/src/web/src/components/System/Options/EditModal.jsx
@@ -43,6 +43,7 @@ const EditModal = ({ onClose, open, theme }) => {
const validate = async (newYaml) => {
const response = await validateYaml({ yaml: newYaml });
setYamlError(response);
+ return response;
};
const update = async (newYaml) => {
@@ -51,14 +52,16 @@ const EditModal = ({ onClose, open, theme }) => {
};
const save = async (newYaml) => {
- await validate(newYaml);
+ const validationError = await validate(newYaml);
- if (!yamlError) {
+ if (!validationError) {
try {
await updateYaml({ yaml: newYaml });
onClose();
} catch (nextUpdateError) {
- setUpdateError(nextUpdateError.response.data);
+ setUpdateError(
+ nextUpdateError?.response?.data ?? nextUpdateError?.message,
+ );
}
}
};
diff --git a/src/web/src/components/System/Shares/ContentsModal.jsx b/src/web/src/components/System/Shares/ContentsModal.jsx
index 5399bcf2..36d1d79d 100644
--- a/src/web/src/components/System/Shares/ContentsModal.jsx
+++ b/src/web/src/components/System/Shares/ContentsModal.jsx
@@ -13,7 +13,16 @@ const ContentsModal = ({ onClose, share, theme }) => {
const fetch = async () => {
setLoading(true);
- const result = await browse({ id });
+ let result;
+
+ try {
+ result = await browse({ id });
+ } catch (error) {
+ console.error(error);
+ setContents(error?.response?.data ?? error?.message ?? String(error));
+ setLoading(false);
+ return;
+ }
const directories = result.map((directory) => {
const lines = [directory.name.replace(remotePath, localPath)];
diff --git a/src/web/src/components/Transfers/TransferGroup.jsx b/src/web/src/components/Transfers/TransferGroup.jsx
index 12354362..f150459a 100644
--- a/src/web/src/components/Transfers/TransferGroup.jsx
+++ b/src/web/src/components/Transfers/TransferGroup.jsx
@@ -42,7 +42,7 @@ class TransferGroup extends Component {
.map((s) =>
user.directories
.find((d) => d.directory === s.directory)
- .files.find((f) => f.filename === s.filename),
+ ?.files?.find((f) => f.filename === s.filename),
)
.filter((s) => s !== undefined);
};
@@ -65,21 +65,29 @@ class TransferGroup extends Component {
};
cancelAll = async (direction, username, selected) => {
- await Promise.all(
- selected.map((file) =>
- transfers.cancel({ direction, id: file.id, username }),
- ),
- );
+ try {
+ await Promise.all(
+ selected.map((file) =>
+ transfers.cancel({ direction, id: file.id, username }),
+ ),
+ );
+ } catch (error) {
+ console.error(error);
+ }
};
removeAll = async (direction, username, selected) => {
- await Promise.all(
- selected.map((file) =>
- transfers
- .cancel({ direction, id: file.id, remove: true, username })
- .then(() => this.removeFileSelection(file)),
- ),
- );
+ try {
+ await Promise.all(
+ selected.map((file) =>
+ transfers
+ .cancel({ direction, id: file.id, remove: true, username })
+ .then(() => this.removeFileSelection(file)),
+ ),
+ );
+ } catch (error) {
+ console.error(error);
+ }
};
handleRetry = async (file) => {
diff --git a/src/web/src/components/Transfers/Transfers.jsx b/src/web/src/components/Transfers/Transfers.jsx
index f43ed1ae..025de9e2 100644
--- a/src/web/src/components/Transfers/Transfers.jsx
+++ b/src/web/src/components/Transfers/Transfers.jsx
@@ -17,7 +17,7 @@ const Transfers = ({ direction, server }) => {
const fetch = async () => {
try {
const response = await transfersLibrary.getAll({ direction });
- setTransfers(response);
+ setTransfers(response ?? []);
} catch (error) {
console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);
diff --git a/src/web/src/components/Users/User.jsx b/src/web/src/components/Users/User.jsx
index 0e392122..457c095b 100644
--- a/src/web/src/components/Users/User.jsx
+++ b/src/web/src/components/Users/User.jsx
@@ -33,6 +33,7 @@ const FreeUploadSlot = ({ hasFreeUploadSlot }) => (
const User = ({
address,
description,
+ hasFreeUploadSlot,
hasPicture,
picture,
port,
@@ -57,7 +58,8 @@ const User = ({
{username}
</Item.Header>
<Item.Meta>
- Free Upload Slot: <FreeUploadSlot hasFreeUploadSlot />, Total Upload
+ Free Upload Slot:{' '}
+ <FreeUploadSlot hasFreeUploadSlot={hasFreeUploadSlot} />, Total Upload
Slots: {uploadSlots}, Queue Length: {queueLength}, IP Address: {address}
, Port: {port}
</Item.Meta>
diff --git a/src/web/src/components/Users/Users.jsx b/src/web/src/components/Users/Users.jsx
index 55dc1047..fd9c3c6c 100644
--- a/src/web/src/components/Users/Users.jsx
+++ b/src/web/src/components/Users/Users.jsx
@@ -3,7 +3,7 @@ import { activeUserInfoKey } from '../../config';
import * as users from '../../lib/users';
import PlaceholderSegment from '../Shared/PlaceholderSegment';
import User from './User';
-import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Icon, Input, Item, Loader, Segment } from 'semantic-ui-react';
@@ -37,20 +37,20 @@ const Users = () => {
const keyUp = (event) => (event.key === 'Escape' ? clear() : '');
- useLayoutEffect(() => {
- document.removeEventListener('keyup', keyUp, false);
- }, []); // eslint-disable-line react-hooks/exhaustive-deps
-
useEffect(() => {
document.addEventListener('keyup', keyUp, false);
const storedUsername =
location.state?.user || localStorage.getItem(activeUserInfoKey);
- if (storedUsername !== undefined) {
+ if (storedUsername) {
setSelectedUsername(storedUsername);
setInputText(storedUsername);
}
+
+ return () => {
+ document.removeEventListener('keyup', keyUp, false);
+ };
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js
index 9506a0da..74602d63 100644
--- a/src/web/src/lib/api.js
+++ b/src/web/src/lib/api.js
@@ -26,7 +26,7 @@ api.interceptors.response.use(
},
(error) => {
if (
- error.response.status === 401 &&
+ error.response?.status === 401 &&
!['/session', '/server', '/application'].includes(
error.response.config.url,
)
diff --git a/src/web/src/lib/options.js b/src/web/src/lib/options.js
index 1c3c55c5..891d0ee2 100644
--- a/src/web/src/lib/options.js
+++ b/src/web/src/lib/options.js
@@ -17,9 +17,9 @@ export const getYamlLocation = async () => {
};
export const validateYaml = async ({ yaml }) => {
- return (await api.post('/options/yaml/validate', yaml)).data;
+ return (await api.post('/options/yaml/validate', JSON.stringify(yaml))).data;
};
export const updateYaml = async ({ yaml }) => {
- return (await api.put('/options/yaml', yaml)).data;
+ return (await api.put('/options/yaml', JSON.stringify(yaml))).data;
};
diff --git a/src/web/src/lib/session.js b/src/web/src/lib/session.js
index 014b131c..cf6966c6 100644
--- a/src/web/src/lib/session.js
+++ b/src/web/src/lib/session.js
@@ -36,7 +36,7 @@ export const check = async () => {
await api.get('/session');
return true;
} catch (error) {
- if (error.response.status === 401) {
+ if (error.response?.status === 401) {
console.error('session error; not logged in or session has expired');
logout();
return false;
diff --git a/tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs b/tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs
new file mode 100644
index 00000000..640bca0e
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs
@@ -0,0 +1,204 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Middleware;
+
+public class HTMLInjectionMiddlewareTests
+{
+ private const string Html = "<html><body>hello</body></html>";
+ private const string Injection = "<script>window.urlBase=\"/slskd\"</script>";
+ private static readonly string[] ExcludedRoutes = ["/api", "/swagger"];
+
+ [Theory]
+ [InlineData("text/html")]
+ [InlineData("TEXT/HTML")]
+ [InlineData("application/xhtml+xml")]
+ [InlineData("application/xml")]
+ [InlineData("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")]
+ [InlineData("application/xml;q=0.9")]
+ [InlineData("application/json, text/html")]
+ public async Task InvokeAsync_Injects_When_Accept_Is_Injectable(string accept)
+ {
+ var (context, body) = CreateContext(path: "/", accept: accept);
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html + Injection, Read(body));
+ }
+
+ [Theory]
+ [InlineData("application/json")]
+ [InlineData("*/*")]
+ [InlineData("")]
+ public async Task InvokeAsync_Does_Not_Inject_When_Accept_Is_Not_Injectable(string accept)
+ {
+ var (context, body) = CreateContext(path: "/", accept: accept);
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData("text/html")]
+ [InlineData("text/html; charset=utf-8")]
+ [InlineData("TEXT/HTML;charset=UTF-8")]
+ [InlineData("application/xhtml+xml")]
+ public async Task InvokeAsync_Injects_When_Response_Content_Type_Is_Injectable(string contentType)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, contentType));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html + Injection, Read(body));
+ }
+
+ [Theory]
+ [InlineData("application/json")]
+ [InlineData("text/plain; charset=utf-8")]
+ [InlineData(null)]
+ public async Task InvokeAsync_Does_Not_Inject_When_Response_Content_Type_Is_Not_Injectable(string contentType)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond("{\"foo\":\"bar\"}", contentType));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal("{\"foo\":\"bar\"}", Read(body));
+ }
+
+ [Theory]
+ [InlineData("/api")]
+ [InlineData("/api/v0/application")]
+ [InlineData("/swagger")]
+ [InlineData("/swagger/index.html")]
+ public async Task InvokeAsync_Does_Not_Inject_Excluded_Routes(string path)
+ {
+ var (context, body) = CreateContext(path: path, accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData("/")]
+ [InlineData("/searches")]
+ [InlineData("/system/info")]
+ public async Task InvokeAsync_Injects_Non_Excluded_Routes(string path)
+ {
+ var (context, body) = CreateContext(path: path, accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html + Injection, Read(body));
+ }
+
+ [Theory]
+ [InlineData("POST")]
+ [InlineData("PUT")]
+ [InlineData("HEAD")]
+ public async Task InvokeAsync_Does_Not_Inject_Non_GET_Requests(string method)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html", method: method);
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData(404)]
+ [InlineData(500)]
+ public async Task InvokeAsync_Does_Not_Inject_Non_200_Responses(int statusCode)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html", statusCode));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(statusCode, context.Response.StatusCode);
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Fact]
+ public async Task InvokeAsync_Removes_Content_Length_And_Retains_Other_Headers()
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(async ctx =>
+ {
+ ctx.Response.Headers["X-Test"] = "value";
+ ctx.Response.ContentLength = Html.Length;
+ await Respond(Html, "text/html")(ctx);
+ });
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Null(context.Response.ContentLength);
+ Assert.Equal("value", context.Response.Headers["X-Test"]);
+ Assert.Equal("text/html", context.Response.ContentType);
+ Assert.Equal(Html + Injection, Read(body));
+ }
+
+ [Fact]
+ public async Task InvokeAsync_Restores_Original_Body_Stream_When_Downstream_Throws()
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(_ => throw new InvalidOperationException("boom"));
+
+ var ex = await Record.ExceptionAsync(() => middleware.InvokeAsync(context));
+
+ Assert.IsType<InvalidOperationException>(ex);
+ Assert.Same(body, context.Response.Body);
+ }
+
+ [Fact]
+ public async Task InvokeAsync_Restores_Original_Body_Stream_When_Successful()
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Same(body, context.Response.Body);
+ }
+
+ private static HTMLInjectionMiddleware CreateMiddleware(RequestDelegate next)
+ => new(next, Injection, ExcludedRoutes);
+
+ private static RequestDelegate Respond(string content, string contentType, int statusCode = 200)
+ => async ctx =>
+ {
+ ctx.Response.StatusCode = statusCode;
+ ctx.Response.ContentType = contentType;
+ await ctx.Response.WriteAsync(content);
+ };
+
+ private static (HttpContext Context, MemoryStream Body) CreateContext(string path, string accept, string method = "GET")
+ {
+ var body = new MemoryStream();
+ var context = new DefaultHttpContext();
+
+ context.Request.Method = method;
+ context.Request.Path = path;
+ context.Request.Headers.Accept = accept;
+ context.Response.Body = body;
+
+ return (context, body);
+ }
+
+ private static string Read(MemoryStream stream)
+ {
+ stream.Seek(0, SeekOrigin.Begin);
+ return new StreamReader(stream).ReadToEnd();
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs b/tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs
new file mode 100644
index 00000000..203b9e0e
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs
@@ -0,0 +1,190 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Middleware;
+
+public class HTMLRewriteMiddlewareTests
+{
+ // the same patterns and replacements used in Program.cs, with a url base of /slskd
+ private const string StaticPattern = "((\\.)?\\/static)";
+ private const string StaticReplacement = "/slskd/static";
+ private const string Html = "<html><script src=\"./static/js/main.js\"></script><link href=\"/static/css/main.css\"></html>";
+ private const string RewrittenHtml = "<html><script src=\"/slskd/static/js/main.js\"></script><link href=\"/slskd/static/css/main.css\"></html>";
+
+ [Theory]
+ [InlineData("text/html")]
+ [InlineData("TEXT/HTML")]
+ [InlineData("application/xhtml+xml")]
+ [InlineData("application/xml")]
+ [InlineData("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")]
+ [InlineData("application/xml;q=0.9")]
+ [InlineData("application/json, text/html")]
+ public async Task InvokeAsync_Rewrites_When_Accept_Is_Rewriteable(string accept)
+ {
+ var (context, body) = CreateContext(path: "/", accept: accept);
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(RewrittenHtml, Read(body));
+ }
+
+ [Theory]
+ [InlineData("application/json")]
+ [InlineData("*/*")]
+ [InlineData("")]
+ public async Task InvokeAsync_Does_Not_Rewrite_When_Accept_Is_Not_Rewriteable(string accept)
+ {
+ var (context, body) = CreateContext(path: "/", accept: accept);
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData("text/html")]
+ [InlineData("text/html; charset=utf-8")]
+ [InlineData("TEXT/HTML;charset=UTF-8")]
+ [InlineData("application/xhtml+xml")]
+ public async Task InvokeAsync_Rewrites_When_Response_Content_Type_Is_Rewriteable(string contentType)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, contentType));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(RewrittenHtml, Read(body));
+ }
+
+ [Theory]
+ [InlineData("application/javascript")]
+ [InlineData("text/css; charset=utf-8")]
+ [InlineData(null)]
+ public async Task InvokeAsync_Does_Not_Rewrite_When_Response_Content_Type_Is_Not_Rewriteable(string contentType)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, contentType));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData("/api")]
+ [InlineData("/api/v0/application")]
+ public async Task InvokeAsync_Does_Not_Rewrite_API_Routes(string path)
+ {
+ var (context, body) = CreateContext(path: path, accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData("POST")]
+ [InlineData("PUT")]
+ [InlineData("HEAD")]
+ public async Task InvokeAsync_Does_Not_Rewrite_Non_GET_Requests(string method)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html", method: method);
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Theory]
+ [InlineData(404)]
+ [InlineData(500)]
+ public async Task InvokeAsync_Does_Not_Rewrite_Non_200_Responses(int statusCode)
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html", statusCode));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Equal(statusCode, context.Response.StatusCode);
+ Assert.Equal(Html, Read(body));
+ }
+
+ [Fact]
+ public async Task InvokeAsync_Removes_Content_Length_And_Retains_Other_Headers()
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(async ctx =>
+ {
+ ctx.Response.Headers["X-Test"] = "value";
+ ctx.Response.ContentLength = Html.Length;
+ await Respond(Html, "text/html")(ctx);
+ });
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Null(context.Response.ContentLength);
+ Assert.Equal("value", context.Response.Headers["X-Test"]);
+ Assert.Equal("text/html", context.Response.ContentType);
+ Assert.Equal(RewrittenHtml, Read(body));
+ }
+
+ [Fact]
+ public async Task InvokeAsync_Restores_Original_Body_Stream_When_Downstream_Throws()
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(_ => throw new InvalidOperationException("boom"));
+
+ var ex = await Record.ExceptionAsync(() => middleware.InvokeAsync(context));
+
+ Assert.IsType<InvalidOperationException>(ex);
+ Assert.Same(body, context.Response.Body);
+ }
+
+ [Fact]
+ public async Task InvokeAsync_Restores_Original_Body_Stream_When_Successful()
+ {
+ var (context, body) = CreateContext(path: "/", accept: "text/html");
+ var middleware = CreateMiddleware(Respond(Html, "text/html"));
+
+ await middleware.InvokeAsync(context);
+
+ Assert.Same(body, context.Response.Body);
+ }
+
+ private static HTMLRewriteMiddleware CreateMiddleware(RequestDelegate next)
+ => new(next, StaticPattern, StaticReplacement);
+
+ private static RequestDelegate Respond(string content, string contentType, int statusCode = 200)
+ => async ctx =>
+ {
+ ctx.Response.StatusCode = statusCode;
+ ctx.Response.ContentType = contentType;
+ await ctx.Response.WriteAsync(content);
+ };
+
+ private static (HttpContext Context, MemoryStream Body) CreateContext(string path, string accept, string method = "GET")
+ {
+ var body = new MemoryStream();
+ var context = new DefaultHttpContext();
+
+ context.Request.Method = method;
+ context.Request.Path = path;
+ context.Request.Headers.Accept = accept;
+ context.Response.Body = body;
+
+ return (context, body);
+ }
+
+ private static string Read(MemoryStream stream)
+ {
+ stream.Seek(0, SeekOrigin.Begin);
+ return new StreamReader(stream).ReadToEnd();
+ }
+}