aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-04-27 20:36:53 -0500
committerGitHub <noreply@github.com>2026-04-27 20:36:53 -0500
commit8c611f627b1859a1d9963388fb40f7dfeaeda652 (patch)
tree6564d337d0fe73a3c2f93b601e3e782e42f964c1 /src
parentcb4d254099cf846f918214c2be07341d93d90900 (diff)
parent2b97e3ef7f65b57c3cbe2f3298aef4f856a47985 (diff)
downloadslskd-8c611f627b1859a1d9963388fb40f7dfeaeda652.tar.gz
Merge branch 'master' into docker-volume
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs13
-rw-r--r--src/slskd/Common/CommonExtensions.cs27
-rw-r--r--src/slskd/Common/Retry.cs15
-rw-r--r--src/slskd/Core/Options.cs50
-rw-r--r--src/slskd/Messaging/API/Controllers/ConversationsController.cs10
-rw-r--r--src/slskd/Program.cs10
-rw-r--r--src/slskd/Relay/API/Hubs/RelayHub.cs42
-rw-r--r--src/slskd/Relay/RelayClient.cs9
-rw-r--r--src/slskd/Telemetry/ReportsService.cs3
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs18
-rw-r--r--src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs57
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs122
-rw-r--r--src/slskd/Transfers/Extensions.cs1
-rw-r--r--src/slskd/Transfers/Types/RetryIncompleteStrategy.cs49
-rw-r--r--src/slskd/Users/API/Controllers/UsersController.cs25
-rw-r--r--src/slskd/Users/IUserService.cs3
-rw-r--r--src/slskd/Users/Types/User.cs3
-rw-r--r--src/slskd/Users/UserService.cs134
-rw-r--r--src/web/package-lock.json6
-rw-r--r--src/web/src/components/Transfers/TransferDetails.jsx2
-rw-r--r--src/web/src/components/Transfers/TransferList.jsx4
21 files changed, 523 insertions, 80 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index a8a7883a..e36a5539 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -94,6 +94,7 @@ namespace slskd
/// <summary>
/// The name of the blacklisted user group.
/// </summary>
+ [Obsolete("use IsBlacklisted instead")]
public const string BlacklistedGroup = "blacklisted";
private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down";
@@ -1380,6 +1381,12 @@ namespace slskd
private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename)
{
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
+ return Task.FromResult<int?>(null);
+ }
+
try
{
var place = Transfers.Uploads.Queue.EstimatePosition(username, filename);
@@ -1452,7 +1459,7 @@ namespace slskd
foreach (var (property, fqn, left, right) in diff)
{
- static bool HasAttribute<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T));
+ static bool HasAttribute<T>(PropertyInfo property) => property?.CustomAttributes.Any(a => a.AttributeType == typeof(T)) ?? false;
var requiresRestart = HasAttribute<RequiresRestartAttribute>(property);
var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property);
@@ -1651,7 +1658,9 @@ namespace slskd
var sw = new Stopwatch();
sw.Start();
- if (Users.IsBlacklisted(username))
+ // opportunistically try and avoid performing the search if we have a cached blacklisted value, otherwise
+ // hold off on computing it and filling the cache until we have the user's IP
+ if (Users.IsBlacklisted(username, bypassCache: false))
{
return null;
}
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 88e6d3c8..77db91ef 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -111,20 +111,41 @@ namespace slskd
/// <returns>A list of differences between the two objects.</returns>
public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null)
{
- if (left?.GetType() != right?.GetType())
+ if (left is null || right is null)
{
- throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}");
+ if (left is null == right is null)
+ {
+ return [];
+ }
+
+ return [(null, parentFqn ?? string.Empty, left, right)];
+ }
+
+ if (left.GetType() != right.GetType())
+ {
+ throw new InvalidCastException($"Unable to diff types {left.GetType()} and {right.GetType()}");
}
var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>();
- foreach (var prop in left?.GetType().GetProperties())
+ foreach (var prop in left.GetType().GetProperties())
{
var leftVal = prop.GetValue(left);
var rightVal = prop.GetValue(right);
var propType = prop.PropertyType;
var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name);
+ if (leftVal is null || rightVal is null)
+ {
+ if (leftVal is null == rightVal is null)
+ {
+ continue;
+ }
+
+ differences.Add((prop, fqn, leftVal, rightVal));
+ continue;
+ }
+
if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
{
if (leftVal.ToJson() != rightVal.ToJson())
diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs
index 53aa59db..a14d2def 100644
--- a/src/slskd/Common/Retry.cs
+++ b/src/slskd/Common/Retry.cs
@@ -52,6 +52,7 @@ namespace slskd
/// <param name="maxAttempts">The maximum number of retry attempts.</param>
/// <param name="baseDelayInMilliseconds">The base delay in milliseconds.</param>
/// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param>
+ /// <param name="exceptionHistoryLimit">The maximum number of Exceptions to keep in history.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The execution context.</returns>
public static async Task Do(
@@ -62,13 +63,14 @@ namespace slskd
int maxAttempts = 3,
int baseDelayInMilliseconds = 1000,
int maxDelayInMilliseconds = int.MaxValue,
+ int exceptionHistoryLimit = 5,
CancellationToken cancellationToken = default)
{
await Do<object>(async () =>
{
await task();
return Task.FromResult<object>(null);
- }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken);
+ }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, exceptionHistoryLimit, cancellationToken);
}
/// <summary>
@@ -81,6 +83,7 @@ namespace slskd
/// <param name="maxAttempts">The maximum number of retry attempts.</param>
/// <param name="baseDelayInMilliseconds">The base delay in milliseconds.</param>
/// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param>
+ /// <param name="exceptionHistoryLimit">The maximum number of Exceptions to keep in history.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <typeparam name="T">The Type of the logic return value.</typeparam>
/// <returns>The execution context.</returns>
@@ -92,11 +95,12 @@ namespace slskd
int maxAttempts = 3,
int baseDelayInMilliseconds = 1000,
int maxDelayInMilliseconds = int.MaxValue,
+ int exceptionHistoryLimit = 5,
CancellationToken cancellationToken = default)
{
isRetryable ??= (_, _) => true;
- var exceptions = new List<Exception>();
+ var exceptions = new Queue<Exception>();
for (int attempts = 0; attempts < maxAttempts; attempts++)
{
@@ -119,7 +123,12 @@ namespace slskd
}
catch (Exception ex)
{
- exceptions.Add(ex);
+ exceptions.Enqueue(ex);
+
+ if (exceptions.Count > exceptionHistoryLimit)
+ {
+ exceptions.Dequeue();
+ }
try
{
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 7b38143e..8cc369af 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -50,6 +50,7 @@ namespace slskd
using slskd.Events;
using slskd.Relay;
using slskd.Shares;
+ using slskd.Transfers;
using slskd.Validation;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
@@ -1010,6 +1011,42 @@ namespace slskd
[Description("the total download speed limit")]
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
+
+ /// <summary>
+ /// Gets download retry options.
+ /// </summary>
+ [Validate]
+ public RetryOptions Retry { get; init; } = new RetryOptions();
+
+ /// <summary>
+ /// Download retry options.
+ /// </summary>
+ public class RetryOptions
+ {
+ /// <summary>
+ /// Gets the maximum number of times to retry a failed transfer.
+ /// </summary>
+ [Range(1, int.MaxValue)]
+ public int Attempts { get; init; } = 3;
+
+ /// <summary>
+ /// Gets the base time to wait between retry attempts, in milliseconds.
+ /// </summary>
+ [Range(1000, int.MaxValue)]
+ public int Delay { get; init; } = 5000;
+
+ /// <summary>
+ /// Gets the maximum time to wait between retry attempts, in milliseconds.
+ /// </summary>
+ [Range(30_000, int.MaxValue)]
+ public int MaxDelay { get; init; } = 60_000;
+
+ /// <summary>
+ /// Gets the strategy for handling incomplete files upon retry.
+ /// </summary>
+ [Enum(typeof(RetryIncompleteStrategy))]
+ public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant();
+ }
}
/// <summary>
@@ -1150,6 +1187,11 @@ namespace slskd
public string[] Members { get; init; } = Array.Empty<string>();
/// <summary>
+ /// Gets the list of regular expression patterns matched against usernames.
+ /// </summary>
+ public string[] Patterns { get; init; } = Array.Empty<string>();
+
+ /// <summary>
/// Gets the list of group CIDRs.
/// </summary>
public string[] Cidrs { get; init; } = Array.Empty<string>();
@@ -1163,6 +1205,14 @@ namespace slskd
{
var results = new List<ValidationResult>();
+ foreach (var pattern in Patterns ?? Array.Empty<string>())
+ {
+ if (!pattern.IsValidRegex())
+ {
+ results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression"));
+ }
+ }
+
foreach (var cidr in Cidrs ?? Array.Empty<string>())
{
try
diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs
index c60d0c2f..7ed0a92c 100644
--- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs
+++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs
@@ -40,6 +40,7 @@ namespace slskd.Messaging.API
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+ using slskd.Users;
/// <summary>
/// Conversations.
@@ -56,19 +57,23 @@ namespace slskd.Messaging.API
/// </summary>
/// <param name="applicationStateMonitor"></param>
/// <param name="messagingService"></param>
+ /// <param name="userService"></param>
/// <param name="optionsSnapshot"></param>
public ConversationsController(
IStateMonitor<State> applicationStateMonitor,
IMessagingService messagingService,
+ IUserService userService,
IOptionsSnapshot<Options> optionsSnapshot)
{
ApplicationStateMonitor = applicationStateMonitor;
Messages = messagingService;
+ Users = userService;
OptionsSnapshot = optionsSnapshot;
}
private IStateMonitor<State> ApplicationStateMonitor { get; }
private IMessagingService Messages { get; }
+ private IUserService Users { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
/// <summary>
@@ -264,6 +269,11 @@ namespace slskd.Messaging.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return StatusCode(200);
+ }
+
if (string.IsNullOrEmpty(message))
{
return BadRequest();
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 25077de7..42f43918 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -706,11 +706,11 @@ namespace slskd
new SoulseekClient(
minorVersion: NetworkMinorVersion,
options: new SoulseekClientOptions(
- maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots,
- maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots,
- minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(),
- maximumConcurrentSearches: 2,
- raiseEventsAsynchronously: true)));
+ maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots,
+ maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots,
+ minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(),
+ maximumConcurrentSearches: 2,
+ raiseEventsAsynchronously: true)));
// add the core application service to DI as well as a hosted service so that other services can
// access instance methods
diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs
index 53e2830f..8430164c 100644
--- a/src/slskd/Relay/API/Hubs/RelayHub.cs
+++ b/src/slskd/Relay/API/Hubs/RelayHub.cs
@@ -109,7 +109,6 @@ namespace slskd.Relay
private IOptionsMonitor<Options> OptionsMonitor { get; }
private OptionsAtStartup OptionsAtStartup { get; }
private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>();
- private IPAddress RemoteIpAddress => Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress;
/// <summary>
/// Executed when a new connection is established.
@@ -119,13 +118,13 @@ namespace slskd.Relay
{
if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode))
{
- Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, RemoteIpAddress);
+ Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, GetRemoteIPAddress());
Context.Abort();
}
var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId);
- Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, RemoteIpAddress, token);
+ Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, GetRemoteIPAddress(), token);
await Clients.Caller.Challenge(token);
}
@@ -138,7 +137,7 @@ namespace slskd.Relay
{
if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record))
{
- Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, RemoteIpAddress);
+ Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress());
Relay.TryDeregisterAgent(record.Agent.Name, out _);
}
@@ -170,23 +169,25 @@ namespace slskd.Relay
return false;
}
+ var remoteIP = GetRemoteIPAddress();
+
if (!TryGetAgentConfig(agent, out var agentOptions))
{
- Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, RemoteIpAddress);
+ Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, remoteIP);
throw new UnauthorizedAccessException();
}
if (!agentOptions.Cidr.Split(',')
.Select(cidr => IPAddressRange.Parse(cidr))
- .Any(range => range.Contains(RemoteIpAddress)))
+ .Any(range => range.Contains(remoteIP)))
{
- Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, RemoteIpAddress, agentOptions.Cidr);
+ Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, remoteIP, agentOptions.Cidr);
throw new UnauthorizedAccessException();
}
if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse))
{
- Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, RemoteIpAddress);
+ Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, remoteIP);
Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case!
throw new UnauthorizedAccessException();
}
@@ -208,12 +209,12 @@ namespace slskd.Relay
if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record))
{
// this can happen if the agent attempts to upload before logging in
- Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, RemoteIpAddress);
+ Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, GetRemoteIPAddress());
throw new UnauthorizedAccessException();
}
var token = Relay.GenerateShareUploadToken(record.Agent.Name);
- Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, RemoteIpAddress, token);
+ Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, GetRemoteIPAddress(), token);
return token;
}
@@ -227,11 +228,11 @@ namespace slskd.Relay
{
if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record))
{
- Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, RemoteIpAddress);
+ Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, GetRemoteIPAddress());
throw new UnauthorizedAccessException();
}
- Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, RemoteIpAddress, id, exception.Message);
+ Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, GetRemoteIPAddress(), id, exception.Message);
Relay.NotifyFileStreamException(record.Agent.Name, id, exception);
}
@@ -247,13 +248,26 @@ namespace slskd.Relay
{
if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record))
{
- Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, RemoteIpAddress);
+ Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, GetRemoteIPAddress());
throw new UnauthorizedAccessException();
}
- Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, RemoteIpAddress, id, exists, length);
+ Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress(), id, exists, length);
Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length));
}
+
+ private IPAddress GetRemoteIPAddress()
+ {
+ var ip = Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress;
+
+ // looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4
+ if (ip.IsIPv4MappedToIPv6)
+ {
+ ip = ip.MapToIPv4();
+ }
+
+ return ip;
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index 6fb2f360..9aec7b00 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -362,11 +362,6 @@ namespace slskd.Relay
LoggedInTaskCompletionSource.TrySetResult();
}
- catch (UnauthorizedAccessException)
- {
- await HubConnection.StopAsync();
- Log.Error("Relay controller authentication failed. Check configuration.");
- }
catch (Exception ex)
{
Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message);
@@ -532,6 +527,8 @@ namespace slskd.Relay
Log.Information("Uploading shares...");
await UploadSharesAsync();
+
+ Log.Information("Shares uploaded. Ready to relay files.");
}
catch (Exception ex)
{
@@ -542,8 +539,6 @@ namespace slskd.Relay
await StopAsync();
_ = StartAsync();
}
-
- Log.Information("Shares uploaded. Ready to relay files.");
}
private Task HubConnection_Reconnecting(Exception arg)
diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs
index cab4e406..ae2d1129 100644
--- a/src/slskd/Telemetry/ReportsService.cs
+++ b/src/slskd/Telemetry/ReportsService.cs
@@ -38,6 +38,7 @@ using System.Linq;
using Dapper;
using Microsoft.Data.Sqlite;
using Serilog;
+using slskd.Transfers;
using Soulseek;
/// <summary>
@@ -99,6 +100,7 @@ public class ReportsService
FROM Transfers
WHERE EndedAt IS NOT NULL
AND EndedAt BETWEEN @Start AND @End
+ AND State IN ({string.Join(", ", TransferStateCategories.Completed.Select(s => (int)s))})
{(direction is not null ? "AND Direction = @Direction" : string.Empty)}
{(username is not null ? "AND Username = @Username" : string.Empty)}
GROUP BY Direction, StateDescription
@@ -186,6 +188,7 @@ public class ReportsService
FROM Transfers
WHERE EndedAt IS NOT NULL
AND EndedAt BETWEEN @Start AND @End
+ AND State IN ({string.Join(", ", TransferStateCategories.Completed.Select(s => (int)s))})
{(direction is not null ? "AND Direction = @Direction" : string.Empty)}
{(username is not null ? "AND Username = @Username" : string.Empty)}
GROUP BY Interval, Direction, StateDescription
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 2ffd50d4..494ee722 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -44,6 +44,8 @@ namespace slskd.Transfers.API
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Serilog;
+ using slskd.Users;
+ using Soulseek;
/// <summary>
/// Transfers.
@@ -58,17 +60,21 @@ namespace slskd.Transfers.API
/// Initializes a new instance of the <see cref="TransfersController"/> class.
/// </summary>
/// <param name="optionsSnapshot"></param>
+ /// <param name="userService"></param>
/// <param name="transferService"></param>
public TransfersController(
ITransferService transferService,
+ IUserService userService,
IOptionsSnapshot<Options> optionsSnapshot)
{
Transfers = transferService;
+ Users = userService;
OptionsSnapshot = optionsSnapshot;
}
private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2);
private ITransferService Transfers { get; }
+ private IUserService Users { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>();
@@ -253,6 +259,13 @@ namespace slskd.Transfers.API
try
{
+ var endpoint = await Users.GetIPEndPointAsync(username);
+
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ throw new UserOfflineException($"User {username} appears to be offline");
+ }
+
var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)));
return StatusCode(201, new { Enqueued = enqueued, Failed = failed });
@@ -382,6 +395,11 @@ namespace slskd.Transfers.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
if (!Guid.TryParse(id, out var guid))
{
return BadRequest();
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
new file mode 100644
index 00000000..ce3331ca
--- /dev/null
+++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
@@ -0,0 +1,57 @@
+// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+
+namespace slskd.Transfers.API;
+
+public record EnqueueDownloadBatchRequest
+{
+ public Guid? BatchId { get; init; }
+ public Guid? SearchId { get; init; }
+
+ [Required]
+ [StringLength(500, MinimumLength = 1)]
+ public string Username { get; init; }
+ public List<EnqueueDownloadBatchItem> Files { get; init; } = [];
+}
+
+public record EnqueueDownloadBatchItem
+{
+ [Required]
+ public string Filename { get; set; }
+
+ [Range(0, int.MaxValue)]
+ public long Size { get; set; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index c8e10fe6..d4d8004a 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -937,6 +937,7 @@ namespace slskd.Transfers.Downloads
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None);
cancellationToken = cts.Token;
+ var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry;
var updateSyncRoot = new SemaphoreSlim(1, 1);
try
@@ -967,6 +968,16 @@ 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 (transfer.Attempts < retryOptions.Attempts)
+ {
+ transfer.State &= ~TransferStates.Completed; // remove the Completed flag
+ }
+
// todo: broadcast
SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken);
}
@@ -1017,26 +1028,79 @@ namespace slskd.Transfers.Downloads
? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
: null;
+ // if the transfer has an associated batch id, store the incomplete file in a directory of the same name
+ // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file)
+ var incompleteFilename = transfer.Filename.ToLocalFilename(
+ baseDirectory: System.IO.Path.Combine(
+ OptionsMonitor.CurrentValue.Directories.Incomplete,
+ transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty));
+
Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username);
+ transfer.Attempts = 1;
+ SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
+
+ var completedTransfer = await Retry.Do(() =>
+ {
+ var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename);
+ var incompleteStrategy = retryOptions.Incomplete.ToEnum<RetryIncompleteStrategy>();
+
+ var shouldResume = false;
+ var startOffset = 0L;
- var completedTransfer = await Client.DownloadAsync(
- username: transfer.Username,
- remoteFilename: transfer.Filename,
- outputStreamFactory: () => Task.FromResult(
- Files.CreateFile(
- filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
- options: new CreateFileOptions
+ if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0)
+ {
+ if (incompleteStrategy == RetryIncompleteStrategy.Resume)
+ {
+ shouldResume = true;
+ startOffset = incompleteFileInfo.Length;
+ Log.Information("Resuming download of {Filename} from user {Username} at offset {Offet}", transfer.Filename, transfer.Username, incompleteFileInfo.Length);
+ }
+ else
{
- Access = System.IO.FileAccess.Write,
- Mode = System.IO.FileMode.Create, // overwrites file if it exists
- Share = System.IO.FileShare.None, // exclusive access for the duration of the download
- UnixCreateMode = unixFileMode,
- })),
- size: transfer.Size,
- startOffset: 0,
- token: null,
- cancellationToken: cancellationToken,
- options: topts);
+ Log.Information("Overwriting partial download of {Length} bytes for download of {Filename} from user {Username} at offset {Offet}", incompleteFileInfo.Length, transfer.Filename, transfer.Username);
+ }
+ }
+
+ return Client.DownloadAsync(
+ username: transfer.Username,
+ remoteFilename: transfer.Filename,
+ outputStreamFactory: () => Task.FromResult(
+ Files.CreateFile(
+ filename: incompleteFilename,
+ options: new CreateFileOptions
+ {
+ Access = System.IO.FileAccess.Write,
+ Mode = shouldResume ? System.IO.FileMode.Append : System.IO.FileMode.Create,
+ Share = System.IO.FileShare.None, // exclusive access for the duration of the download
+ UnixCreateMode = unixFileMode,
+ })),
+ size: transfer.Size,
+ startOffset: startOffset,
+ token: null,
+ cancellationToken: cancellationToken,
+ options: topts);
+ },
+ isRetryable: (attempts, ex) =>
+ ex is not OperationCanceledException
+ && ex is not TransferRejectedException
+ && ex is not DuplicateTransferException
+ && ex is not TransferSizeMismatchException,
+ onRetry: (attempts, delay) =>
+ {
+ Log.Information("Waiting about {Delay} second(s) to retry attempt #{Attempt} to download {Filename} from user {Username} in {Delay}ms", (int)Math.Ceiling((double)delay / 1000), attempts, transfer.Filename, transfer.Username);
+
+ transfer.Attempts = attempts;
+ transfer.State = TransferStates.Queued | TransferStates.Locally;
+ SynchronizedUpdate(transfer, updateSyncRoot);
+ },
+ onFailure: (attempts, ex) =>
+ {
+ Log.Warning("Failed attempt #{Attempts} to download {Filename} from user {Username}: {Message}", attempts, transfer.Filename, transfer.Username, ex.Message);
+ },
+ maxAttempts: retryOptions.Attempts,
+ baseDelayInMilliseconds: retryOptions.Delay,
+ maxDelayInMilliseconds: retryOptions.MaxDelay,
+ cancellationToken: cancellationToken);
Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username);
@@ -1053,8 +1117,28 @@ namespace slskd.Transfers.Downloads
Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete);
- // move the file from incomplete to complete
- var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads));
+ /*
+ move the file from incomplete to complete
+
+ users have a lot of strong opinions about this!
+ */
+ string destinationDirectory;
+
+ if (transfer.BatchId is not null)
+ {
+ // if the transfer has an associated batch id, then:
+ // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext
+ destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString());
+ }
+ else
+ {
+ // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so:
+ // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext
+ // this is "legacy" behavior that will be familiar to most Soulseek users
+ destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads));
+ }
+
+ Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory);
var finalFilename = Files.MoveFile(
sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs
index 1c5ff4b5..48179ff2 100644
--- a/src/slskd/Transfers/Extensions.cs
+++ b/src/slskd/Transfers/Extensions.cs
@@ -53,6 +53,7 @@ namespace slskd.Transfers
BytesTransferred = t.BytesTransferred,
AverageSpeed = t.AverageSpeed,
Exception = t.Exception?.Message,
+ Attempts = transfer.Attempts,
};
}
}
diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs
new file mode 100644
index 00000000..9ac8d8e2
--- /dev/null
+++ b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs
@@ -0,0 +1,49 @@
+// <copyright file="RetryIncompleteStrategy.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Strategy for retrying incomplete files.
+/// </summary>
+public enum RetryIncompleteStrategy
+{
+ /// <summary>
+ /// Overwrite the existing file.
+ /// </summary>
+ Overwrite = 0,
+
+ /// <summary>
+ /// Resume the transfer using the size of the incomplete file as the initial offset.
+ /// </summary>
+ Resume = 1,
+} \ No newline at end of file
diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs
index 2a6f535f..8029b5e0 100644
--- a/src/slskd/Users/API/Controllers/UsersController.cs
+++ b/src/slskd/Users/API/Controllers/UsersController.cs
@@ -93,6 +93,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var endpoint = await Users.GetIPEndPointAsync(username);
@@ -120,6 +125,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var result = await Client.BrowseAsync(username);
@@ -184,6 +194,11 @@ namespace slskd.Users.API
return BadRequest();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var result = await Client.GetDirectoryContentsAsync(username, request.Directory);
@@ -214,6 +229,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var response = await Users.GetInfoAsync(username);
@@ -241,6 +261,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var response = await Users.GetStatusAsync(username);
diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs
index f2cfa5f1..28bb6459 100644
--- a/src/slskd/Users/IUserService.cs
+++ b/src/slskd/Users/IUserService.cs
@@ -144,8 +144,9 @@ namespace slskd.Users
/// </summary>
/// <param name="username">The username to check.</param>
/// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <param name="bypassCache">A value indicating whether to compute blacklisted status on a cache miss.</param>
/// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
- bool IsBlacklisted(string username, IPAddress ipAddress = null);
+ bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true);
/// <summary>
/// Retrieves a value indicating whether the specified peer is privileged.
diff --git a/src/slskd/Users/Types/User.cs b/src/slskd/Users/Types/User.cs
index 7297d747..473bedfb 100644
--- a/src/slskd/Users/Types/User.cs
+++ b/src/slskd/Users/Types/User.cs
@@ -42,6 +42,9 @@ namespace slskd.Users
/// <summary>
/// Gets the user's configured group.
/// </summary>
+ /// <remarks>
+ /// This is the group under which the username appears in config, *not* the group derived at runtime.
+ /// </remarks>
public string Group { get; init; }
/// <summary>
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index d8b24f4d..3ce827c8 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -34,11 +34,15 @@ using Microsoft.Extensions.Options;
namespace slskd.Users
{
+ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
+ using System.Text.RegularExpressions;
using System.Threading.Tasks;
+ using Microsoft.Extensions.Caching.Memory;
+ using Microsoft.Extensions.Internal;
using NetTools;
using Serilog;
using Soulseek;
@@ -85,15 +89,20 @@ namespace slskd.Users
/// </summary>
/// <param name="soulseekClient"></param>
/// <param name="optionsMonitor"></param>
+ /// <param name="systemClock"></param>
public UserService(
ISoulseekClient soulseekClient,
- IOptionsMonitor<Options> optionsMonitor)
+ IOptionsMonitor<Options> optionsMonitor,
+ ISystemClock systemClock = null)
{
Client = soulseekClient;
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
+ InjectedClock = systemClock ?? new SystemClock();
+ BlacklistDecisionCache = new MemoryCache(new MemoryCacheOptions { Clock = InjectedClock, ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 });
+
// updates may be sent unsolicited from the server, so update when we get them. binding these events will cause
// multiple redundant round trips when initially watching a user or when explicitly requesting via
// GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
@@ -137,6 +146,9 @@ namespace slskd.Users
private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
private Blacklist Blacklist { get; } = new Blacklist();
+ private IReadOnlyCollection<Regex> CompiledBlacklistPatterns { get; set; } = [];
+ private ISystemClock InjectedClock { get; }
+ private MemoryCache BlacklistDecisionCache { get; }
/// <summary>
/// Gets or sets the internal cache of User data.
@@ -162,31 +174,45 @@ namespace slskd.Users
private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>();
/// <summary>
- /// Gets the name of the group for the specified <paramref name="username"/>.
+ /// Gets the name of the group for the specified <paramref name="username"/> from cached data.
/// </summary>
- /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks>
+ /// <remarks>
+ /// <para>
+ /// Excludes the 'blacklisted' group for performance; use <see cref="IsBlacklisted"/> to guard network operations instead.
+ /// </para>
+ /// <para>
+ /// This is an extremely hot path, and the value returned may be approximated or incorrect in the case of a
+ /// cache miss in order to provide low latency values.
+ /// </para>
+ /// </remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The group for the specified username.</returns>
public string GetGroup(string username)
{
- // note: this is an extremely hot path; keep the work done to an absolute minimum.
+ // users end up in this dictionary for a few reasons, including but maybe not limited to:
+ // * they show up in the user defined group list somewhere
+ // * the server told us they have privileges when we logged in
+ // * we 'watched' them
+ // * we fetched statistics or status for them
+ // if we handle any of their data they'll probably wind up here. if they show up in the config,
+ // their Group property will be set. otherwise we must resolve their group dynamically.
if (UserDictionary.TryGetValue(username ?? string.Empty, out var user))
{
- if (IsBlacklisted(user.Username))
- {
- return Application.BlacklistedGroup;
- }
-
+ // privileged users trump everything, and we resolve their group accordingly regardless of all other factors
if (user.Status?.IsPrivileged ?? false)
{
return Application.PrivilegedGroup;
}
+ // if the user isn't privileged and the user has put their username in any user defined group, that's
+ // their group. they aren't subjected to leecher checks.
if (user.Group != null)
{
return user.Group;
}
+ // check to see if they are a leecher. they may be in the dictionary because we checked their stats.
+ // if we don't have their stats we don't have enough info to make the call, group is inconclusive so fall through
var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds;
if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories)
@@ -286,33 +312,79 @@ namespace slskd.Users
/// <summary>
/// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted.
/// </summary>
+ /// <remarks>
+ /// This method may be taxing if the user has defined a blacklist file or large number of patterns. Call it to 'guard'
+ /// actions at the network level (with the exception of search results where latency is sensitive), but don't
+ /// use it to check once the user is 'in' the system (e.g. don't call this in the upload governor or queue logic).
+ /// </remarks>
/// <param name="username">The username to check.</param>
/// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <param name="bypassCache">A value indicating whether to compute blacklisted status on a cache miss.</param>
/// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
- public bool IsBlacklisted(string username, IPAddress ipAddress = null)
+ public bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true)
{
- var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted;
+ ArgumentNullException.ThrowIfNull(username);
- if (blacklist.Members.Contains(username))
+ if (BlacklistDecisionCache.TryGetValue<bool>(username, out var cached))
{
- return true;
+ return cached;
}
- // check the user-curated list of blacklisted CIDRs that exists along with the list of
- // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a
- // blacklist supplied by a third party (but might?)
- if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
+ // if we have a cache miss and the caller has specified bypassCache = false, assume that a cache miss
+ // means that the user is not blacklisted. we will only specify bypassCache = false when we're checking
+ // in a hot path, which at the time of this writing is only when determining whether to search shares for a
+ // request. we will check again before sending the results with bypassCache = true, and we should always
+ // follow this pattern when using bypassCache = false (specifically, check again before sending something)
+ if (!bypassCache)
{
- return true;
+ return false;
}
- // check the managed blacklist loaded from a third party blacklist file
- if (ipAddress is not null && Blacklist.Contains(ipAddress))
+ var blacklisted = IsBlacklistedInternal(username, ipAddress);
+
+ BlacklistDecisionCache.Set(
+ key: username,
+ value: blacklisted,
+ options: new MemoryCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
+ Size = 1,
+ });
+
+ return blacklisted;
+
+ bool IsBlacklistedInternal(string username, IPAddress iPAddress = null)
{
- return true;
- }
+ // first, check to see if the name appears explicitly in the config
+ var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted;
- return false;
+ if (blacklist.Members.Contains(username))
+ {
+ return true;
+ }
+
+ // check to see if the username matches any patterns
+ if (CompiledBlacklistPatterns.Any(pattern => pattern.IsMatch(username)))
+ {
+ return true;
+ }
+
+ // check the user-curated list of blacklisted CIDRs that exists along with the list of
+ // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a
+ // blacklist supplied by a third party (but might?)
+ if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
+ {
+ return true;
+ }
+
+ // check the managed blacklist loaded from a third party blacklist file
+ if (ipAddress is not null && Blacklist.Contains(ipAddress))
+ {
+ return true;
+ }
+
+ return false;
+ }
}
/// <summary>
@@ -419,6 +491,19 @@ namespace slskd.Users
LastOptionsHash = optionsHash;
}
+ // recompile blacklist patterns, regardless of whether they changed (this cheap to do)
+ var regexOptions = RegexOptions.Compiled;
+
+ if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx)
+ {
+ regexOptions |= RegexOptions.IgnoreCase;
+ }
+
+ CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns
+ .Select(f => new Regex(f, regexOptions))
+ .ToList()
+ .AsReadOnly();
+
var blacklistOptionsHash = Compute.Sha1Hash(options.Blacklist.ToJson());
// there's no forced re-config of the blacklist; either the config changed or it didn't.
@@ -464,6 +549,9 @@ namespace slskd.Users
LastBlacklistOptionsHash = blacklistOptionsHash;
}
+
+ // invalidate cached blacklist decisions
+ BlacklistDecisionCache.Clear();
}
private void Reset()
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index f309d9af..22d9c714 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -10906,9 +10906,9 @@
"license": "ISC"
},
"node_modules/follow-redirects": {
- "version": "1.15.11",
- "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
- "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
+ "version": "1.16.0",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
+ "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",
"funding": [
{
"type": "individual",
diff --git a/src/web/src/components/Transfers/TransferDetails.jsx b/src/web/src/components/Transfers/TransferDetails.jsx
index 256ddcac..2ec890e9 100644
--- a/src/web/src/components/Transfers/TransferDetails.jsx
+++ b/src/web/src/components/Transfers/TransferDetails.jsx
@@ -79,6 +79,8 @@ const TransferDetails = ({ file }) => {
'elapsedTime',
'percentComplete',
'remainingTime',
+ 'attempts',
+ 'exception',
];
return (
diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx
index 4bd1e14e..42e58933 100644
--- a/src/web/src/components/Transfers/TransferList.jsx
+++ b/src/web/src/components/Transfers/TransferList.jsx
@@ -163,6 +163,9 @@ class TransferList extends Component {
padding: 7,
}}
{...getColor(f.state)}
+ {...(!getColor(f.state).color && f.attempts > 1
+ ? { color: 'yellow' }
+ : {})}
active={f.direction === 'Upload'}
onClick={() => this.handleClick(f)}
>
@@ -176,6 +179,7 @@ class TransferList extends Component {
)}
{f.state}
{f.placeInQueue ? ` (#${f.placeInQueue})` : ''}
+ {f.attempts > 1 ? ` (Retry #${f.attempts})` : ''}
</Button>
)}
</Table.Cell>