aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2024-01-20 11:15:23 -0600
committerGitHub <noreply@github.com>2024-01-20 11:15:23 -0600
commit9c0a10048e34106fdf744cb2351da6a5b6f6223d (patch)
tree609f0f7c6645fc1f6bf05c1c413b881f8dd1971a /src
parent8bfce5d955aeea9a95ee76a5eecd5fa77454425a (diff)
parent84acaed78564bed6c251de7b0d94bea43fecc7dc (diff)
downloadslskd-9c0a10048e34106fdf744cb2351da6a5b6f6223d.tar.gz
Merge pull request #1035 from slskd/quotas
Add configurable limits for number (and size) of queued files, daily and weekly completions
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs227
-rw-r--r--src/slskd/Common/Authentication/ApiKeyAuthentication.cs2
-rw-r--r--src/slskd/Core/Options.cs77
-rw-r--r--src/slskd/Relay/RelayClient.cs8
-rw-r--r--src/slskd/Relay/RelayService.cs2
-rw-r--r--src/slskd/Shares/IShareRepository.cs4
-rw-r--r--src/slskd/Shares/IShareService.cs4
-rw-r--r--src/slskd/Shares/ShareService.cs10
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs13
-rw-r--r--src/slskd/Shares/Types/Share.cs2
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs9
-rw-r--r--src/slskd/Transfers/Types/Transfer.cs7
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs82
-rw-r--r--src/slskd/Users/IUserService.cs62
-rw-r--r--src/slskd/Users/UserService.cs215
-rw-r--r--src/slskd/slskd.csproj4
16 files changed, 594 insertions, 134 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 5c926644..70d726ab 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -36,7 +36,6 @@ namespace slskd
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Hosting;
- using NetTools;
using Serilog;
using Serilog.Events;
using slskd.Configuration;
@@ -47,6 +46,7 @@ namespace slskd
using slskd.Search;
using slskd.Shares;
using slskd.Transfers;
+ using slskd.Transfers.API;
using slskd.Users;
using Soulseek;
using Soulseek.Diagnostics;
@@ -62,17 +62,22 @@ namespace slskd
/// <summary>
/// The name of the default user group.
/// </summary>
- public static readonly string DefaultGroup = "default";
+ public const string DefaultGroup = "default";
/// <summary>
/// The name of the privileged user group.
/// </summary>
- public static readonly string PrivilegedGroup = "privileged";
+ public const string PrivilegedGroup = "privileged";
/// <summary>
/// The name of the leecher user group.
/// </summary>
- public static readonly string LeecherGroup = "leechers";
+ public const string LeecherGroup = "leechers";
+
+ /// <summary>
+ /// The name of the blacklisted user group.
+ /// </summary>
+ public const string BlacklistedGroup = "blacklisted";
private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down";
@@ -290,7 +295,7 @@ namespace slskd
// records to be updated if the application has started to shut down so that we can do this cleanup and properly
// disposition them as having failed due to an application shutdown, instead of some random exception thrown while
// things are being disposed.
- var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)
+ var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed), includeRemoved: false)
.Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434
.ToList();
@@ -383,7 +388,7 @@ namespace slskd
await Client.ReconfigureOptionsAsync(patch);
Log.Debug("Client configured");
- Log.Information("Listening for incoming connections son {IP}:{Port}", OptionsAtStartup.Soulseek.ListenIpAddress, OptionsAtStartup.Soulseek.ListenPort);
+ Log.Information("Listening for incoming connections on {IP}:{Port}", OptionsAtStartup.Soulseek.ListenIpAddress, OptionsAtStartup.Soulseek.ListenPort);
if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled)
{
@@ -470,15 +475,175 @@ namespace slskd
return Task.CompletedTask;
}
- private Task EnqueueDownload(string username, IPEndPoint endpoint, string filename)
+ private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename)
{
- if (IsBlacklisted(username, endpoint.Address))
+ if (Users.IsBlacklisted(username, endpoint.Address))
{
Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
- return Task.FromException(new DownloadEnqueueException($"File not shared."));
+ throw new DownloadEnqueueException("File not shared.");
+ }
+
+ // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
+ // it helps, too, that this will tell us whether the file is even shared.
+ (string Host, string Filename, long Size) resolved;
+
+ try
+ {
+ resolved = await Shares.ResolveFileAsync(filename);
+ }
+ catch (NotFoundException)
+ {
+ throw new DownloadEnqueueException("File not shared.");
}
- return Transfers.Uploads.EnqueueAsync(username, filename);
+ // get the user's group. this will be the name of the user's group, if they have been added to a
+ // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted'
+ var group = await Users.GetOrFetchGroupAsync(username);
+
+ // privileged users aren't subject to limits (for now)
+ // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited"
+ // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level
+ // of control, but i'd need to figure out a lower bound
+ if (string.Equals(group, PrivilegedGroup))
+ {
+ Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename);
+ await Transfers.Uploads.EnqueueAsync(username, filename);
+ return;
+ }
+
+ // resolve the limits for this user's group. there's no 'fallthrough' here, if limits for a group
+ // are unset, then that group is unlimited.
+ Options.GroupsOptions.LimitsOptions limits;
+
+ if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions))
+ {
+ limits = userDefinedOptions.Limits;
+ }
+ else
+ {
+ limits = group switch
+ {
+ DefaultGroup => Options.Groups.Default.Limits,
+ LeecherGroup => Options.Groups.Leechers.Limits,
+ _ => Options.Groups.Default.Limits,
+ };
+ }
+
+ bool IsNull(Options.GroupsOptions.LimitsExtendedOptions l) => l is null || (l?.Files is null && l?.Megabytes is null);
+
+ // if no limits are set, we're good to go; just enqueue the file.
+ if (limits is null || (IsNull(limits.Daily) && IsNull(limits.Weekly) && IsNull(limits.Queued)))
+ {
+ Log.Debug("Limits bypassed for {Username} and {File}; no limits are set", username, filename);
+ await Transfers.Uploads.EnqueueAsync(username, filename);
+ return;
+ }
+
+ var sw = new Stopwatch();
+ sw.Start();
+
+ /*
+ * 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.
+ * the strategy here is to summarize all uploads:
+ * 1) belonging to this user
+ * 2) that were started within the time period
+ * 3) that did not end due to an error (state includes errored, exception column is set)
+ */
+ (bool Files, bool Megabytes) OverLimits((int Files, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, long size)
+ {
+ var files = false;
+ var megabytes = false;
+ var byteLimit = (options?.Megabytes ?? 0) * 1000 * 1000;
+
+ if (options?.Megabytes is not null && (stats.Bytes + size) > byteLimit)
+ {
+ Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimit);
+ megabytes = true;
+ }
+
+ if (options?.Files is not null && (stats.Files + 1) > options.Files)
+ {
+ Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, options.Files);
+ files = true;
+ }
+
+ return (files, megabytes);
+ }
+
+ // start with the queue, since that should contain the fewest files and should be the least expensive to check
+ // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
+ // for terminal transfers.
+ if (!IsNull(limits.Queued))
+ {
+ var queued = Transfers.Uploads.Summarize(
+ expression: t => t.Username == username && t.EndedAt == null);
+
+ Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds);
+
+ var over = OverLimits(queued, limits!.Queued, resolved.Size);
+
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} queued");
+ }
+ }
+
+ // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum
+ // transfers that 'count' for the weekly limit are uploads that:
+ // * started within the last week
+ // * which have or have not ended (assuming queued files will complete)
+ // * that were not errored
+ if (!IsNull(limits.Weekly))
+ {
+ var erroredState = TransferStates.Completed | TransferStates.Errored;
+ var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
+ var weekly = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && !t.State.HasFlag(erroredState)
+ && t.Exception == null);
+
+ Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds);
+
+ var over = OverLimits(weekly, limits!.Weekly, resolved.Size);
+
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week");
+ }
+ }
+
+ // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead
+ // of the previous 7.
+ if (!IsNull(limits.Daily))
+ {
+ var erroredState = TransferStates.Completed | TransferStates.Errored;
+ var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
+ var daily = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && !t.State.HasFlag(erroredState)
+ && t.Exception == null);
+
+ Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds);
+
+ var over = OverLimits(daily, limits!.Daily, resolved.Size);
+
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today");
+ }
+ }
+
+ sw.Stop();
+ Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds);
+
+ await Transfers.Uploads.EnqueueAsync(username, filename);
}
/// <summary>
@@ -491,7 +656,7 @@ namespace slskd
{
Metrics.Browse.RequestsReceived.Inc(1);
- if (IsBlacklisted(username, endpoint.Address))
+ if (Users.IsBlacklisted(username, endpoint.Address))
{
Log.Information("Returned empty browse listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
return new BrowseResponse();
@@ -954,7 +1119,7 @@ namespace slskd
/// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns>
private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory)
{
- if (IsBlacklisted(username, endpoint.Address))
+ if (Users.IsBlacklisted(username, endpoint.Address))
{
Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
return new Soulseek.Directory(directory);
@@ -1151,7 +1316,7 @@ namespace slskd
{
Metrics.Search.RequestsReceived.Inc(1);
- if (IsBlacklisted(username))
+ if (Users.IsBlacklisted(username))
{
Log.Information("Returned empty search response for blacklisted user {Username}", username);
return new SearchResponse(username, token, hasFreeUploadSlot: false, uploadSpeed: 0, queueLength: int.MaxValue, fileList: Enumerable.Empty<Soulseek.File>());
@@ -1186,6 +1351,9 @@ namespace slskd
// make sure our average speed (as reported by the server) is reasonably up to date
await RefreshUserStatistics();
+ // note: the following uses cached user data to determine group, so if the user's data
+ // isn't cached they may get a forecast based on the wrong group. this is a hot path though,
+ // and we don't want to incur the massive penalties that would caching data for each request.
var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username);
Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText);
@@ -1344,11 +1512,23 @@ namespace slskd
/// <param name="username">The username of the requesting user.</param>
/// <param name="endpoint">The IP endpoint of the requesting user.</param>
/// <returns>A Task resolving the UserInfo instance.</returns>
- private Task<UserInfo> UserInfoResolver(string username, IPEndPoint endpoint)
+ private async Task<UserInfo> UserInfoResolver(string username, IPEndPoint endpoint)
{
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ return new UserInfo(
+ description: Options.Soulseek.Description,
+ uploadSlots: 0,
+ queueLength: int.MaxValue,
+ hasFreeUploadSlot: false);
+ }
+
try
{
- var groupName = Users.GetGroup(username);
+ // note: users must first be watched or cached for leech and privilege detection to work.
+ // we are deliberately skipping it here; if the username is watched
+ // leech detection works and they get accurate info, if not, they won't
+ var groupName = await Users.GetOrFetchGroupAsync(username);
var group = Transfers.Uploads.Queue.GetGroupInfo(groupName);
// forecast the position at which this user would enter the queue if they were to request
@@ -1366,7 +1546,7 @@ namespace slskd
queueLength: forecastedPosition,
hasFreeUploadSlot: forecastedPosition == 0);
- return Task.FromResult(info);
+ return info;
}
catch (Exception ex)
{
@@ -1374,20 +1554,5 @@ namespace slskd
throw;
}
}
-
- private bool IsBlacklisted(string username, IPAddress ipAddress = null)
- {
- if (Options.Groups.Blacklisted.Members.Contains(username))
- {
- return true;
- }
-
- if (ipAddress is not null && Options.Groups.Blacklisted.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
- {
- return true;
- }
-
- return false;
- }
}
}
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
index 7c6c9235..b27c4c05 100644
--- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
+++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
@@ -96,7 +96,9 @@ namespace slskd.Authentication
/// <summary>
/// API key authentication options.
/// </summary>
+#pragma warning disable S2094 // Classes should not be empty
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
+#pragma warning restore S2094 // Classes should not be empty
{
}
}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 94f8618d..c1f4d558 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -682,7 +682,9 @@ namespace slskd
return (share, matches[0].Groups[2].Value, matches[0].Groups[3].Value);
}
+#pragma warning disable S3878 // Arrays should not be created for params parameters
return (share, share.Split(new[] { '/', '\\' }).Last(), share);
+#pragma warning restore S3878 // Arrays should not be created for params parameters
}
var digestedShared = directories
@@ -882,15 +884,28 @@ namespace slskd
}
/// <summary>
- /// Built in user group options.
+ /// Options that are common to all groups.
/// </summary>
- public class BuiltInOptions
+ public class GroupOptions
{
/// <summary>
/// Gets upload options.
/// </summary>
[Validate]
public UploadOptions Upload { get; init; } = new UploadOptions();
+
+ /// <summary>
+ /// Gets limit options.
+ /// </summary>
+ [Validate]
+ public LimitsOptions Limits { get; init; } = new LimitsOptions();
+ }
+
+ /// <summary>
+ /// Built in user group options.
+ /// </summary>
+ public class BuiltInOptions : GroupOptions
+ {
}
/// <summary>
@@ -936,19 +951,13 @@ namespace slskd
/// <summary>
/// Built in leecher group options.
/// </summary>
- public class LeecherOptions
+ public class LeecherOptions : GroupOptions
{
/// <summary>
/// Gets leecher threshold options.
/// </summary>
[Validate]
public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions();
-
- /// <summary>
- /// Gets upload options.
- /// </summary>
- [Validate]
- public UploadOptions Upload { get; init; } = new UploadOptions();
}
/// <summary>
@@ -972,15 +981,9 @@ namespace slskd
/// <summary>
/// User defined user group options.
/// </summary>
- public class UserDefinedOptions
+ public class UserDefinedOptions : GroupOptions
{
/// <summary>
- /// Gets upload options.
- /// </summary>
- [Validate]
- public UploadOptions Upload { get; init; } = new UploadOptions();
-
- /// <summary>
/// Gets the list of group member usernames.
/// </summary>
public string[] Members { get; init; } = Array.Empty<string>();
@@ -1015,6 +1018,48 @@ namespace slskd
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
}
+
+ /// <summary>
+ /// Upload limit options.
+ /// </summary>
+ public class LimitsOptions
+ {
+ /// <summary>
+ /// Gets limits for queued transfers.
+ /// </summary>
+ [Validate]
+ public LimitsExtendedOptions Queued { get; init; } = new LimitsExtendedOptions();
+
+ /// <summary>
+ /// Gets daily limits for transfers.
+ /// </summary>
+ [Validate]
+ public LimitsExtendedOptions Daily { get; init; } = new LimitsExtendedOptions();
+
+ /// <summary>
+ /// Gets weekly limits for transfers.
+ /// </summary>
+ [Validate]
+ public LimitsExtendedOptions Weekly { get; init; } = new LimitsExtendedOptions();
+ }
+
+ /// <summary>
+ /// Extended limit options.
+ /// </summary>
+ public class LimitsExtendedOptions
+ {
+ /// <summary>
+ /// Gets the limit for number of files.
+ /// </summary>
+ [Range(1, int.MaxValue)]
+ public int? Files { get; init; } = null;
+
+ /// <summary>
+ /// Gets the limit for number of megabytes.
+ /// </summary>
+ [Range(1, int.MaxValue)]
+ public int? Megabytes { get; init; } = null;
+ }
}
/// <summary>
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index f3880c97..e7a1cc76 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -259,7 +259,9 @@ namespace slskd.Relay
{
if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors)
{
+#pragma warning disable S4830 // Enable server certificate validation on this SSL/TLS connection
clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true;
+#pragma warning restore S4830 // Enable server certificate validation on this SSL/TLS connection
}
return message;
@@ -304,7 +306,9 @@ namespace slskd.Relay
client = new HttpClient(new HttpClientHandler()
{
ClientCertificateOptions = ClientCertificateOption.Manual,
+#pragma warning disable S4830 // Enable server certificate validation on this SSL/TLS connection
ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
+#pragma warning restore S4830 // Enable server certificate validation on this SSL/TLS connection
});
}
else
@@ -354,7 +358,7 @@ namespace slskd.Relay
try
{
- var (_, localFilename) = await Shares.ResolveFileAsync(filename);
+ var (_, localFilename, _) = await Shares.ResolveFileAsync(filename);
var localFileInfo = new FileInfo(localFilename);
@@ -375,7 +379,7 @@ namespace slskd.Relay
try
{
- var (_, localFilename) = await Shares.ResolveFileAsync(filename);
+ var (_, localFilename, _) = await Shares.ResolveFileAsync(filename);
var localFileInfo = new FileInfo(localFilename);
diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs
index 6cbbb0a2..d3f35693 100644
--- a/src/slskd/Relay/RelayService.cs
+++ b/src/slskd/Relay/RelayService.cs
@@ -624,7 +624,7 @@ namespace slskd.Relay
// ensure filename is relative to the local download directory and make sure it doesn't start with a slash
filename = filename
.ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty)
- .TrimStart(new[] { '/', '\\' });
+ .TrimStart('/', '\\');
async Task Notify((string ConnectionId, Agent Agent) record)
{
diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs
index 41b0fe32..c721fa40 100644
--- a/src/slskd/Shares/IShareRepository.cs
+++ b/src/slskd/Shares/IShareRepository.cs
@@ -74,11 +74,11 @@ namespace slskd.Shares
void EnableKeepalive(bool enable);
/// <summary>
- /// Finds the filename of the file matching the specified <paramref name="maskedFilename"/>.
+ /// Finds the filename and length of the file matching the specified <paramref name="maskedFilename"/>.
/// </summary>
/// <param name="maskedFilename">The fully qualified remote path of the file.</param>
/// <returns>The filename, if found.</returns>
- string FindFilename(string maskedFilename);
+ (string Filename, long Size) FindFileInfo(string maskedFilename);
/// <summary>
/// Finds and returns the most recent scan record.
diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs
index 7e1352e9..7db9671b 100644
--- a/src/slskd/Shares/IShareService.cs
+++ b/src/slskd/Shares/IShareService.cs
@@ -88,7 +88,7 @@ namespace slskd.Shares
void RequestScan();
/// <summary>
- /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a
+ /// Resolves the local filename and size of the specified <paramref name="remoteFilename"/>, if the mask is associated with a
/// configured share.
/// </summary>
/// <param name="remoteFilename">The fully qualified filename to resolve.</param>
@@ -96,7 +96,7 @@ namespace slskd.Shares
/// <exception cref="NotFoundException">
/// Thrown when the specified remote filename can not be associated with a configured share.
/// </exception>
- Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename);
+ Task<(string Host, string Filename, long Size)> ResolveFileAsync(string remoteFilename);
/// <summary>
/// Scans the configured shares on the local host.
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index 97867cde..4f409705 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -267,9 +267,9 @@ namespace slskd.Shares
/// <exception cref="NotFoundException">
/// Thrown when the specified remote filename can not be associated with a configured share.
/// </exception>
- public Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename)
+ public Task<(string Host, string Filename, long Size)> ResolveFileAsync(string remoteFilename)
{
- string resolvedFilename = Local.Repository.FindFilename(remoteFilename);
+ var (resolvedFilename, size) = Local.Repository.FindFileInfo(remoteFilename);
// when we're debugging the relay (running as both controller and agent on the same instance)
// always resolve files from remote hosts, ignoring local. this is a crappy hack, but it is the
@@ -281,7 +281,7 @@ namespace slskd.Shares
else if (!string.IsNullOrEmpty(resolvedFilename))
{
Log.Debug("Resolved remote file to {ResolvedFilename} on local host", resolvedFilename);
- return Task.FromResult((Program.LocalHostName, resolvedFilename));
+ return Task.FromResult((Program.LocalHostName, resolvedFilename, size));
}
else
{
@@ -292,12 +292,12 @@ namespace slskd.Shares
// this is the slow, dumb way to do this, but it's plenty fast in this context.
foreach (var host in HostDictionary.Values)
{
- resolvedFilename = host.Repository.FindFilename(remoteFilename);
+ (resolvedFilename, size) = host.Repository.FindFileInfo(remoteFilename);
if (!string.IsNullOrEmpty(resolvedFilename))
{
Log.Debug("Resolved remote file to {ResolvedFilename} on host {Host}", remoteFilename, host.Host.Name);
- return Task.FromResult((host.Host.Name, resolvedFilename));
+ return Task.FromResult((host.Host.Name, resolvedFilename, size));
}
Log.Debug("Failed to resolve remote file on host {Host}", host.Host.Name);
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index 57a76177..882ede74 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -210,10 +210,10 @@ namespace slskd.Shares
/// </summary>
/// <param name="maskedFilename">The fully qualified remote path of the file.</param>
/// <returns>The filename, if found.</returns>
- public string FindFilename(string maskedFilename)
+ public (string Filename, long Size) FindFileInfo(string maskedFilename)
{
using var conn = GetConnection();
- using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn);
+ using var cmd = new SqliteCommand("SELECT originalFilename, size FROM files WHERE maskedFilename = @maskedFilename;", conn);
cmd.Parameters.AddWithValue("maskedFilename", maskedFilename);
var reader = cmd.ExecuteReader();
@@ -221,12 +221,13 @@ namespace slskd.Shares
if (!reader.Read())
{
Log.Warning("Failed to resolve shared file {Filename}", maskedFilename);
- return null;
+ return default;
}
- var resolved = reader.GetString(0);
- Log.Debug($"Resolved requested shared file {maskedFilename} to {resolved}");
- return resolved;
+ var filename = (string)reader["originalFilename"];
+ var size = (long)reader["size"];
+ Log.Debug($"Resolved requested shared file {maskedFilename} to {filename} ({size} bytes)");
+ return (filename, size);
}
/// <summary>
diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs
index d60998f6..2911cf83 100644
--- a/src/slskd/Shares/Types/Share.cs
+++ b/src/slskd/Shares/Types/Share.cs
@@ -76,7 +76,9 @@ namespace slskd.Shares
}
else
{
+#pragma warning disable S3878 // Arrays should not be created for params parameters
Alias = share.Split(new[] { '/', '\\' }).Last();
+#pragma warning restore S3878 // Arrays should not be created for params parameters
LocalPath = share;
}
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index aea815af..ad984a4c 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -180,8 +180,9 @@ namespace slskd.Transfers.API
return Forbid();
}
+ // get all the transfers that aren't removed
var transfers = Transfers.Uploads
- .List() // https://github.com/dotnet/efcore/issues/10434
+ .List(t => true, includeRemoved: false) // https://github.com/dotnet/efcore/issues/10434
.Where(t => t.State.HasFlag(Soulseek.TransferStates.Completed));
foreach (var id in transfers.Select(t => t.Id))
@@ -373,7 +374,9 @@ namespace slskd.Transfers.API
return Forbid();
}
- var uploads = Transfers.Uploads.List(includeRemoved: includeRemoved);
+ // todo: refactor this so it doesn't return the world. start and end time params
+ // should be required. consider pagination.
+ var uploads = Transfers.Uploads.List(t => true, includeRemoved: includeRemoved);
var response = uploads.GroupBy(t => t.Username).Select(grouping => new UserResponse()
{
@@ -405,7 +408,7 @@ namespace slskd.Transfers.API
return Forbid();
}
- var uploads = Transfers.Uploads.List(d => d.Username == username);
+ var uploads = Transfers.Uploads.List(d => d.Username == username, includeRemoved: false);
if (!uploads.Any())
{
diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs
index c55826d4..1797adcd 100644
--- a/src/slskd/Transfers/Types/Transfer.cs
+++ b/src/slskd/Transfers/Types/Transfer.cs
@@ -37,6 +37,13 @@ namespace slskd.Transfers
public DateTime RequestedAt { get; set; }
public DateTime? EnqueuedAt { get; set; }
public DateTime? StartedAt { get; set; }
+
+ /// <summary>
+ /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress.
+ /// </summary>
+ /// <remarks>
+ /// Guaranteed to be set for transfers in a terminal state.
+ /// </remarks>
public DateTime? EndedAt { get; set; }
public long BytesTransferred { get; set; }
public double AverageSpeed { get; set; }
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 04e6a431..55b6b39a 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -72,12 +72,22 @@ namespace slskd.Transfers.Uploads
Transfer Find(Expression<Func<Transfer, bool>> expression);
/// <summary>
+ /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
+ /// consider caching.
+ /// </summary>
+ /// <param name="expression">The expression used to select uploads for summarization.</param>
+ /// <returns>
+ /// The generated summary, including the number of files and total size in bytes.
+ /// </returns>
+ (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression);
+
+ /// <summary>
/// Returns a list of all uploads matching the optional <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An optional expression used to match uploads.</param>
- /// <param name="includeRemoved">Optionally include uploads that have been removed previously.</param>
+ /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param>
/// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns>
- List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);
+ List<Transfer> List(Expression<Func<Transfer, bool>> expression, bool includeRemoved);
/// <summary>
/// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
@@ -146,10 +156,10 @@ namespace slskd.Transfers.Uploads
private ISoulseekClient Client { get; set; }
private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<UploadService>();
- private IShareService Shares { get; set; }
- private IUserService Users { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; }
private IRelayService Relay { get; }
+ private IShareService Shares { get; set; }
+ private IUserService Users { get; set; }
/// <summary>
/// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
@@ -187,20 +197,21 @@ namespace slskd.Transfers.Uploads
{
string host = default;
string localFilename = default;
+ long resolvedFileLength = default;
long localFileLength = default;
Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename);
try
{
- (host, localFilename) = await Shares.ResolveFileAsync(filename);
+ (host, localFilename, resolvedFileLength) = await Shares.ResolveFileAsync(filename);
Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename);
if (host == Program.LocalHostName)
{
- // if it's local, do a quick check to see if it exists to spare the caller from
- // queueing up if the transfer is doomed to fail. for remote files, take a leap of faith.
+ // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is
+ // doomed to fail. for remote files, take a leap of faith.
var info = new FileInfo(localFilename);
if (!info.Exists)
@@ -232,8 +243,15 @@ namespace slskd.Transfers.Uploads
Log.Information("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host);
+ if (localFileLength != resolvedFileLength)
+ {
+ // todo: should we fail the transfer? the file changed on disk since the last scan. i guess not? since the caller doesn't provide a size
+ Shares.RequestScan();
+ Log.Warning("Resolved size for {Remote} of {Resolved} doesn't match actual size {Actual}", filename, resolvedFileLength, localFileLength);
+ }
+
// find existing records for this username and file that haven't been removed from the UI
- var existingRecords = List(t => t.Username == username && t.Filename == localFilename && !t.Removed);
+ var existingRecords = List(t => t.Username == username && t.Filename == localFilename, includeRemoved: false);
// check whether any of these records is in a non-complete state and bail out if so
if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed)))
@@ -360,8 +378,8 @@ namespace slskd.Transfers.Uploads
transfer = transfer.WithSoulseekTransfer(completedTransfer);
}
- // explicitly dispose the rate limiter to prevent updates from it
- // beyond this point, which may overwrite the final state
+ // explicitly dispose the rate limiter to prevent updates from it beyond this point, which may overwrite the
+ // final state
rateLimiter.Dispose();
// todo: broadcast
@@ -425,12 +443,52 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
+ /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
+ /// consider caching.
+ /// </summary>
+ /// <param name="expression">The expression used to select uploads for summarization.</param>
+ /// <returns>
+ /// The generated summary, including the number of files and total size in bytes.
+ /// </returns>
+ public (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression)
+ {
+ expression ??= t => true;
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ var query = context.Transfers
+ .AsNoTracking()
+ .Where(t => t.Direction == TransferDirection.Upload)
+ .Where(expression)
+ .GroupBy(t => true) // https://stackoverflow.com/a/25489456
+ .Select(t => new
+ {
+ Files = t.Count(),
+ Bytes = t.Sum(x => x.Size),
+ });
+
+ Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString());
+
+ var stats = query.FirstOrDefault();
+
+ return (stats?.Files ?? 0, stats?.Bytes ?? 0);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to list uploads: {Message}", ex.Message);
+ throw;
+ }
+ }
+
+ /// <summary>
/// Returns a list of all uploads matching the optional <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An optional expression used to match uploads.</param>
- /// <param name="includeRemoved">Optionally include uploads that have been removed previously.</param>
+ /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param>
/// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns>
- public List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false)
+ public List<Transfer> List(Expression<Func<Transfer, bool>> expression, bool includeRemoved)
{
expression ??= t => true;
diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs
index 88090f9f..75afd442 100644
--- a/src/slskd/Users/IUserService.cs
+++ b/src/slskd/Users/IUserService.cs
@@ -24,6 +24,38 @@ namespace slskd.Users
/// <summary>
/// Provides information and operations for network peers.
/// </summary>
+ /// <remarks>
+ /// <para>
+ /// This class maintains a UserDictionary that acts as a non-expiring cache of information
+ /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc)
+ /// and, if they are a member of a user-defined group, their group.
+ /// </para>
+ /// <para>
+ /// This class also maintains a WatchedUsernamesDictionary to keep track of which usernames have been
+ /// "watched" server side and for which we will therefore receive events when their status changes.
+ /// </para>
+ /// <para>
+ /// If a user's information is in the UserDictionary, it's because we requested it at some point. If that user
+ /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so.
+ /// </para>
+ /// <para>
+ /// The data in the UserDictionary can continue to grow until -- unlikely -- it contains a record for every
+ /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly
+ /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having
+ /// a user's data when it is needed (for queue positioning, speed limits, etc).
+ /// </para>
+ /// <para>
+ /// The <see cref="GetGroup(string)"/> method acts on cached data _only_. This method should be called within hot paths,
+ /// such as a transfer governor or from the upload queue. We care more that it is fast than if it is stale. If no data for the
+ /// requested user is cached, that user is assumed to be in the default group.
+ /// </para>
+ /// <para>
+ /// The <see cref="GetOrFetchGroupAsync(string, bool)"/> method is similar to <see cref="GetGroup(string)"/>, except that if
+ /// the requested user is not cached, it will fetch the user's data and cache it before returning. This method accepts an optional
+ /// parameter that can be used to force a "refresh" of the requested user's data, useful for times when we want the latest data,
+ /// and can afford to wait for it.
+ /// </para>
+ /// </remarks>
public interface IUserService
{
/// <summary>
@@ -39,6 +71,7 @@ namespace slskd.Users
/// <summary>
/// Gets the name of the group for the specified <paramref name="username"/>.
/// </summary>
+ /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The group for the specified username.</returns>
string GetGroup(string username);
@@ -58,7 +91,26 @@ namespace slskd.Users
Task<IPEndPoint> GetIPEndPointAsync(string username);
/// <summary>
- /// Retrieves the current <see cref="Status"/> of a peer.
+ /// Gets the name of the group for the specified <paramref name="username"/>, or, if the user's information isn't
+ /// cached, fetches and caches the user's information from the server, then returns the group.
+ /// </summary>
+ /// <remarks>The fetch of fresh data can be forced by specifying <paramref name="forceFetch"/> = true.</remarks>
+ /// <param name="username">The username of the peer.</param>
+ /// <param name="forceFetch">
+ /// A value determining whether the user's information should be fetched from the server, regardless of local cache.
+ /// </param>
+ /// <returns>The group for the specified username.</returns>
+ Task<string> GetOrFetchGroupAsync(string username, bool forceFetch = false);
+
+ /// <summary>
+ /// Retrieves the current <see cref="Statistics"/> of a peer, and caches the result.
+ /// </summary>
+ /// <param name="username">The username of the peer.</param>
+ /// <returns>The retrieved statistics.</returns>
+ Task<Statistics> GetStatisticsAsync(string username);
+
+ /// <summary>
+ /// Retrieves the current <see cref="Status"/> of a peer, and caches the result.
/// </summary>
/// <param name="username">The username of the peer.</param>
/// <returns>The retrieved status.</returns>
@@ -73,6 +125,14 @@ namespace slskd.Users
Task GrantPrivilegesAsync(string username, int days);
/// <summary>
+ /// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted.
+ /// </summary>
+ /// <param name="username">The username to check.</param>
+ /// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
+ bool IsBlacklisted(string username, IPAddress ipAddress = null);
+
+ /// <summary>
/// Retrieves a value indicating whether the specified peer is privileged.
/// </summary>
/// <param name="username">The username of the peer.</param>
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index 95fed12d..5b15b671 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -24,35 +24,64 @@ namespace slskd.Users
using System.Linq;
using System.Net;
using System.Threading.Tasks;
+ using NetTools;
using Serilog;
using Soulseek;
/// <summary>
/// Provides information and operations for network peers.
/// </summary>
+ /// <remarks>
+ /// <para>
+ /// This class maintains a <see cref="UserDictionary"/> that acts as a non-expiring cache of information
+ /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc)
+ /// and, if they are a member of a user-defined group, their group.
+ /// </para>
+ /// <para>
+ /// This class also maintains a <see cref="WatchedUsernamesDictionary"/> to keep track of which usernames have been
+ /// "watched" server side and for which we will therefore receive events when their status changes.
+ /// </para>
+ /// <para>
+ /// If a user's information is in the <see cref="UserDictionary"/>, it's because we requested it at some point. If that user
+ /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so.
+ /// </para>
+ /// <para>
+ /// The data in the <see cref="UserDictionary"/> can continue to grow until -- unlikely -- it contains a record for every
+ /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly
+ /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having
+ /// a user's data when it is needed (for queue positioning, speed limits, etc).
+ /// </para>
+ /// <para>
+ /// The <see cref="GetGroup(string)"/> method acts on cached data _only_. This method should be called within hot paths,
+ /// such as a transfer governor or from the upload queue. We care more that it is fast than if it is stale. If no data for the
+ /// requested user is cached, that user is assumed to be in the default group.
+ /// </para>
+ /// <para>
+ /// The <see cref="GetOrFetchGroupAsync(string, bool)"/> method is similar to <see cref="GetGroup(string)"/>, except that if
+ /// the requested user is not cached, it will fetch the user's data and cache it before returning. This method accepts an optional
+ /// parameter that can be used to force a "refresh" of the requested user's data, useful for times when we want the latest data,
+ /// and can afford to wait for it.
+ /// </para>
+ /// </remarks>
public class UserService : IUserService
{
/// <summary>
/// Initializes a new instance of the <see cref="UserService"/> class.
/// </summary>
/// <param name="soulseekClient"></param>
- /// <param name="stateMutator"></param>
/// <param name="optionsMonitor"></param>
public UserService(
ISoulseekClient soulseekClient,
- IStateMutator<State> stateMutator,
IOptionsMonitor<Options> optionsMonitor)
{
Client = soulseekClient;
- StateMutator = stateMutator;
-
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
- // 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.
+ // 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.
Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics());
Client.UserStatusChanged += (sender, userStatus) =>
{
@@ -64,6 +93,7 @@ namespace slskd.Users
Client.Connected += (_, _) => Reset();
Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true);
+ Client.PrivilegedUserListReceived += (_, list) => Client_PrivilegedUserListReceived(list);
Configure(OptionsMonitor.CurrentValue);
}
@@ -82,13 +112,34 @@ namespace slskd.Users
private string LastOptionsHash { get; set; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
- private IStateMutator<State> StateMutator { get; }
+
+ /// <summary>
+ /// Gets or sets the internal cache of User data.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// This method retrieves the requested user's information from a dictionary, and is therefore a 'get'. This
+ /// information is needed to control who can do what, who is subject to what limits, how to control the upload
+ /// queue, and how to govern speeds. The logic in this method is the 'hottest' in the application and *must*
+ /// remain very simple and _fast_.
+ /// </para>
+ /// <para>
+ /// If this method is called for a user who has not previously been cached, it will return the default group,
+ /// meaning leech, privilege, and user defined group discrimination will not work. For this reason it is critical
+ /// that user information is retrieved and cached upon first interaction with that user.
+ /// </para>
+ /// <para>
+ /// Uploads can be cached indefinitely, and for that reason the user data cache must be filled indefinitely;
+ /// meaning there is no invalidation and that user data will accrue for the lifetime of the application (instance).
+ /// </para>
+ /// </remarks>
private ConcurrentDictionary<string, User> UserDictionary { get; set; } = new ConcurrentDictionary<string, User>();
private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>();
/// <summary>
/// Gets the name of the group for the specified <paramref name="username"/>.
/// </summary>
+ /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The group for the specified username.</returns>
public string GetGroup(string username)
@@ -96,6 +147,11 @@ namespace slskd.Users
// note: this is an extremely hot path; keep the work done to an absolute minimum.
if (UserDictionary.TryGetValue(username ?? string.Empty, out var user))
{
+ if (IsBlacklisted(user.Username))
+ {
+ return Application.BlacklistedGroup;
+ }
+
if (user.Status?.IsPrivileged ?? false)
{
return Application.PrivilegedGroup;
@@ -139,7 +195,32 @@ namespace slskd.Users
}
/// <summary>
- /// Retrieves the current <see cref="Statistics"/> of a peer.
+ /// Gets the name of the group for the specified <paramref name="username"/>, or, if the user's information isn't
+ /// cached, fetches and caches the user's information from the server, then returns the group.
+ /// </summary>
+ /// <remarks>The fetch of fresh data can be forced by specifying <paramref name="forceFetch"/> = true.</remarks>
+ /// <param name="username">The username of the peer.</param>
+ /// <param name="forceFetch">
+ /// A value determining whether the user's information should be fetched from the server, regardless of local cache.
+ /// </param>
+ /// <returns>The group for the specified username.</returns>
+ public async Task<string> GetOrFetchGroupAsync(string username, bool forceFetch = false)
+ {
+ if (!UserDictionary.ContainsKey(username) || forceFetch)
+ {
+ // ensure the record will exist
+ UserDictionary.TryAdd(username, new User { Username = username });
+
+ // try to populate the user's info
+ await GetStatisticsAsync(username);
+ await GetStatusAsync(username);
+ }
+
+ return GetGroup(username);
+ }
+
+ /// <summary>
+ /// Retrieves the current <see cref="Statistics"/> of a peer, and caches the result.
/// </summary>
/// <param name="username">The username of the peer.</param>
/// <returns>The retrieved statistics.</returns>
@@ -154,7 +235,7 @@ namespace slskd.Users
}
/// <summary>
- /// Retrieves the current <see cref="Status"/> of a peer.
+ /// Retrieves the current <see cref="Status"/> of a peer, and caches the result.
/// </summary>
/// <param name="username">The username of the peer.</param>
/// <returns>The retrieved status.</returns>
@@ -178,6 +259,29 @@ namespace slskd.Users
=> Client.GrantUserPrivilegesAsync(username, days);
/// <summary>
+ /// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted.
+ /// </summary>
+ /// <param name="username">The username to check.</param>
+ /// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
+ public bool IsBlacklisted(string username, IPAddress ipAddress = null)
+ {
+ var blacklist = OptionsMonitor.CurrentValue.Groups.Blacklisted;
+
+ if (blacklist.Members.Contains(username))
+ {
+ return true;
+ }
+
+ if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
/// Retrieves a value indicating whether the specified peer is privileged.
/// </summary>
/// <param name="username">The username of the peer.</param>
@@ -198,48 +302,45 @@ namespace slskd.Users
/// <summary>
/// Adds the specified username to the server-side user list.
/// </summary>
+ /// <remarks>
+ /// <para>Idempotent; if a user is already watched, subsequent calls will only update their status and statistics.</para>
+ /// <para>
+ /// Any user we want to track in any way needs to be watched so that their statistics and status are updated
+ /// properly via server side events. This seems extreme and wasteful, but the only alternative is to periodically
+ /// spam the server for the information instead of letting the server spam the client when things change.
+ /// </para>
+ /// </remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The operation context.</returns>
public async Task WatchAsync(string username)
{
+ // watch the user, server side
await Client.AddUserAsync(username);
- WatchedUsernamesDictionary.TryAdd(username, true);
+ UserDictionary.TryAdd(username, new User { Username = username });
Log.Information("Added user {Username} to watch list", username);
- // the server does not automatically send status and statistics information
- // when watching a user initially. explicitly fetch both, so that the user has been
- // watched and all information populated when this method returns.
+ // the server does not automatically send status and statistics information when watching a user initially. explicitly
+ // fetch both, so that the user has been watched and all information populated when this method returns.
await GetStatusAsync(username);
await GetStatisticsAsync(username);
- }
-
- private void UpdateStatistics(string username, Statistics statistics)
- {
- UserDictionary.AddOrUpdate(
- key: username,
- addValue: new User() { Statistics = statistics },
- updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics });
-
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
- }
- private void UpdateStatus(string username, Status status)
- {
- UserDictionary.AddOrUpdate(
- key: username,
- addValue: new User() { Status = status },
- updateValueFactory: (key, user) => user with { Username = username, Status = status });
-
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ // delay the add until last, so that IsWatched won't return true until stats and status are populated. this may result
+ // in several unecessary calls to WatchAsync (if someone is checking IsWatched() and WatchAsync()ing if false), but we
+ // can be sure that if IsWatched() is true, we have valid stats and status. if we can't ensure this, the application
+ // will have non-deterministic behavior when it makes decisions about user groups, limits, governance etc.
+ WatchedUsernamesDictionary.TryAdd(username, true);
}
- private void Reset()
+ private void Client_PrivilegedUserListReceived(IEnumerable<string> list)
{
- WatchedUsernamesDictionary.Clear();
- UserDictionary.Clear();
-
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ foreach (var username in list)
+ {
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Status = new Status { IsPrivileged = true } },
+ updateValueFactory: (key, user) => user with { Username = username, Status = user.Status with { IsPrivileged = true } });
+ }
}
private void Configure(Options options, bool force = false)
@@ -251,8 +352,8 @@ namespace slskd.Users
return;
}
- // get a list of tracked names that haven't been explicitly added to any group, including
- // those that were previlously configured but have now been removed
+ // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously
+ // configured but have now been removed
var usernamesBeforeUpdate = UserDictionary.Keys.ToList();
var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members);
var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate);
@@ -276,25 +377,37 @@ namespace slskd.Users
key: username,
addValue: new User() { Username = username, Group = group.Key },
updateValueFactory: (key, user) => user with { Username = username, Group = group.Key });
+
+ if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn))
+ {
+ _ = WatchAsync(username);
+ }
}
}
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ LastOptionsHash = optionsHash;
+ }
- WatchAllUsers();
+ private void Reset()
+ {
+ WatchedUsernamesDictionary.Clear();
+ UserDictionary.Clear();
+ }
- LastOptionsHash = optionsHash;
+ private void UpdateStatistics(string username, Statistics statistics)
+ {
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Statistics = statistics },
+ updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics });
}
- private void WatchAllUsers()
+ private void UpdateStatus(string username, Status status)
{
- if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn))
- {
- foreach (var username in UserDictionary.Keys.ToList())
- {
- _ = WatchAsync(username);
- }
- }
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Status = status },
+ updateValueFactory: (key, user) => user with { Username = username, Status = status });
}
}
} \ No newline at end of file
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 2c66f3fb..b2146d5e 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -17,11 +17,11 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
- <NoWarn>1701;1702;1591</NoWarn>
+ <NoWarn>1701;1702;1591;S1133;S2094;S1135</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
- <NoWarn>1591</NoWarn>
+ <NoWarn>1591;S1133;S2094;S1135</NoWarn>
</PropertyGroup>
<ItemGroup>