From 7033851e42d1412c34c4022f6a8dd1632c64586e Mon Sep 17 00:00:00 2001 From: ofernander Date: Sun, 12 Apr 2026 18:40:01 -0700 Subject: feat: add username reg pattern matching to blacklist group Adds a field to that accepts a list of regular expressions matched against usernames. --- src/slskd/Core/Options.cs | 16 ++++++++++++++++ src/slskd/Users/UserService.cs | 17 +++++++++++++++++ 2 files changed, 33 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7b38143e..dda1b7b5 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1149,6 +1149,14 @@ namespace slskd /// public string[] Members { get; init; } = Array.Empty(); + /// + /// Gets the list of regular expression patterns matched against usernames. + /// Any username matching one or more patterns will be blacklisted. + /// Follows the same case sensitivity rules as other user-defined regular expressions + /// (case insensitive by default; controlled by the flags.case_sensitive_regex option). + /// + public string[] Patterns { get; init; } = Array.Empty(); + /// /// Gets the list of group CIDRs. /// @@ -1163,6 +1171,14 @@ namespace slskd { var results = new List(); + foreach (var pattern in Patterns ?? Array.Empty()) + { + if (!pattern.IsValidRegex()) + { + results.Add(new ValidationResult($"Blacklist username pattern '{pattern}' is not a valid regular expression")); + } + } + foreach (var cidr in Cidrs ?? Array.Empty()) { try diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index d8b24f4d..31c1e540 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -38,6 +38,7 @@ namespace slskd.Users using System.Collections.Generic; using System.Linq; using System.Net; + using System.Text.RegularExpressions; using System.Threading.Tasks; using NetTools; using Serilog; @@ -291,6 +292,8 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { + if (username is null) return false; + var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; if (blacklist.Members.Contains(username)) @@ -298,6 +301,20 @@ namespace slskd.Users return true; } + // check username patterns (regex). respects the same case sensitivity flag used by other + // user-defined regular expressions throughout the application. + if (blacklist.Patterns.Length > 0) + { + var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx + ? RegexOptions.None + : RegexOptions.IgnoreCase; + + if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) + { + 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?) -- cgit v1.2.3 From 795a78e441e28988bed629a0dc61874f760b43cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Apr 2026 22:03:16 -0500 Subject: compile blacklist patterns --- src/slskd/Users/UserService.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 31c1e540..73bf1118 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -138,6 +138,7 @@ namespace slskd.Users private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); + private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; /// /// Gets or sets the internal cache of User data. @@ -433,6 +434,18 @@ namespace slskd.Users } } + 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(); + LastOptionsHash = optionsHash; } -- cgit v1.2.3 From 73634ad0b54d486cc278c4950583754ad77aac00 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 19:28:35 -0500 Subject: consistent options --- src/slskd/Core/Options.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index dda1b7b5..fcc65c3b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1151,9 +1151,6 @@ namespace slskd /// /// Gets the list of regular expression patterns matched against usernames. - /// Any username matching one or more patterns will be blacklisted. - /// Follows the same case sensitivity rules as other user-defined regular expressions - /// (case insensitive by default; controlled by the flags.case_sensitive_regex option). /// public string[] Patterns { get; init; } = Array.Empty(); @@ -1175,7 +1172,7 @@ namespace slskd { if (!pattern.IsValidRegex()) { - results.Add(new ValidationResult($"Blacklist username pattern '{pattern}' is not a valid regular expression")); + results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression")); } } -- cgit v1.2.3 From d2a71a7340c5caf7923824910f112be5b169378d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 19:30:06 -0500 Subject: wip, wtf is going on here --- src/slskd/Users/UserService.cs | 60 +++++++++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 73bf1118..0eb541e0 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -34,12 +34,14 @@ 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 NetTools; using Serilog; using Soulseek; @@ -139,6 +141,7 @@ namespace slskd.Users private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; + private MemoryCache GetGroupCache { get; } = new MemoryCache(new MemoryCacheOptions() { }); /// /// Gets or sets the internal cache of User data. @@ -171,33 +174,49 @@ namespace slskd.Users /// The group for the specified username. public string GetGroup(string username) { + if (GetGroupCache.TryGetValue(username, out var cached)) + { + return cached; + } + else + { + var group = GetGroupInternal(username); + + GetGroupCache.Set(username, group, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); + + return group; + } + // note: this is an extremely hot path; keep the work done to an absolute minimum. - if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) + string GetGroupInternal(string username) { - if (IsBlacklisted(user.Username)) + if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) { - return Application.BlacklistedGroup; - } + if (IsBlacklisted(user.Username)) + { + return Application.BlacklistedGroup; + } - if (user.Status?.IsPrivileged ?? false) - { - return Application.PrivilegedGroup; - } + if (user.Status?.IsPrivileged ?? false) + { + return Application.PrivilegedGroup; + } - if (user.Group != null) - { - return user.Group; - } + if (user.Group != null) + { + return user.Group; + } - var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; + var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; - if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) - { - return Application.LeecherGroup; + if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) + { + return Application.LeecherGroup; + } } - } - return Application.DefaultGroup; + return Application.DefaultGroup; + } } /// @@ -293,7 +312,10 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { - if (username is null) return false; + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username)); + } var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; -- cgit v1.2.3 From ee041dc6c810982393745df7502c1630876bca6b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 20:59:03 -0500 Subject: clarify purpose of group --- src/slskd/Users/Types/User.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') 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 /// /// Gets the user's configured group. /// + /// + /// This is the group under which the username appears in config, *not* the group derived at runtime. + /// public string Group { get; init; } /// -- cgit v1.2.3 From d49b11b2e74f872ef79a3966bac22601191ba773 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 22:17:23 -0500 Subject: add a memory cache for blacklist decisions, recompile patterns and invalidate cache on config change --- src/slskd/Users/UserService.cs | 97 ++++++++++++++++++++++++++---------------- 1 file changed, 60 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 73bf1118..9a29e567 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -34,12 +34,14 @@ 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 NetTools; using Serilog; using Soulseek; @@ -139,6 +141,8 @@ namespace slskd.Users private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; + private MemoryCache BlacklistDecisionCache { get; } = + new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); /// /// Gets or sets the internal cache of User data. @@ -293,44 +297,59 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { - if (username is null) return false; + ArgumentNullException.ThrowIfNull(username); - var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; - - if (blacklist.Members.Contains(username)) + if (BlacklistDecisionCache.TryGetValue(username, out var u)) { - return true; + return u; } - // check username patterns (regex). respects the same case sensitivity flag used by other - // user-defined regular expressions throughout the application. - if (blacklist.Patterns.Length > 0) + var b = IsBlacklistedInternal(username, ipAddress); + + BlacklistDecisionCache.Set(username, b, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); + + return b; + + bool IsBlacklistedInternal(string username, IPAddress iPAddress = null) { - var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx - ? RegexOptions.None - : RegexOptions.IgnoreCase; + // first, check to see if the name appears explicitly in the config + var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; - if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) + if (blacklist.Members.Contains(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 username patterns (regex). respects the same case sensitivity flag used by other + // user-defined regular expressions throughout the application. + if (blacklist.Patterns.Length > 0) + { + var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx + ? RegexOptions.None + : RegexOptions.IgnoreCase; - // check the managed blacklist loaded from a third party blacklist file - if (ipAddress is not null && Blacklist.Contains(ipAddress)) - { - return true; - } + if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) + { + return true; + } + } - return false; + // 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; + } } /// @@ -434,21 +453,22 @@ namespace slskd.Users } } - var regexOptions = RegexOptions.Compiled; - - if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx) - { - regexOptions |= RegexOptions.IgnoreCase; - } + LastOptionsHash = optionsHash; + } - CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns - .Select(f => new Regex(f, regexOptions)) - .ToList() - .AsReadOnly(); + // recompile blacklist patterns, regardless of whether they changed (this cheap to do) + var regexOptions = RegexOptions.Compiled; - LastOptionsHash = optionsHash; + 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. @@ -494,6 +514,9 @@ namespace slskd.Users LastBlacklistOptionsHash = blacklistOptionsHash; } + + // invalidate cached blacklist decisions + BlacklistDecisionCache.Clear(); } private void Reset() -- cgit v1.2.3 From a379b400b62c7c29fb3ace854b2d8acfdeeee26e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:46:50 -0500 Subject: check compiled patterns --- src/slskd/Users/UserService.cs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 469680cf..ee117855 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -319,18 +319,10 @@ namespace slskd.Users return true; } - // check username patterns (regex). respects the same case sensitivity flag used by other - // user-defined regular expressions throughout the application. - if (blacklist.Patterns.Length > 0) + // check to see if the username matches any patterns + if (CompiledBlacklistPatterns.Any(pattern => pattern.IsMatch(username))) { - var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx - ? RegexOptions.None - : RegexOptions.IgnoreCase; - - if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) - { - return true; - } + return true; } // check the user-curated list of blacklisted CIDRs that exists along with the list of -- cgit v1.2.3 From 13e8d31658fbe9083bb44bc0666983fa988af0ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:47:48 -0500 Subject: add cache for IsBlacklisted --- src/slskd/Users/IUserService.cs | 3 ++- src/slskd/Users/UserService.cs | 39 ++++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 10 deletions(-) (limited to 'src') 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 /// /// The username to check. /// The IPAddress to check, if available. + /// A value indicating whether to compute blacklisted status on a cache miss. /// A value indicating whether the specified user and/or IP are blacklisted. - bool IsBlacklisted(string username, IPAddress ipAddress = null); + bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true); /// /// Retrieves a value indicating whether the specified peer is privileged. diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index ee117855..0a620992 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -88,15 +88,20 @@ namespace slskd.Users /// /// /// + /// public UserService( ISoulseekClient soulseekClient, - IOptionsMonitor optionsMonitor) + IOptionsMonitor optionsMonitor, + ISystemClock systemClock) { Client = soulseekClient; OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); + InjectedClock = 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. @@ -141,8 +146,8 @@ namespace slskd.Users private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; - private MemoryCache BlacklistDecisionCache { get; } = - new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); + private ISystemClock InjectedClock { get; } + private MemoryCache BlacklistDecisionCache { get; } /// /// Gets or sets the internal cache of User data. @@ -291,23 +296,39 @@ namespace slskd.Users /// /// Gets a value indicating whether the specified and/or are blacklisted. /// + /// + /// 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). + /// /// The username to check. /// The IPAddress to check, if available. + /// A value indicating whether to compute blacklisted status on a cache miss. /// A value indicating whether the specified user and/or IP are blacklisted. - public bool IsBlacklisted(string username, IPAddress ipAddress = null) + public bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true) { ArgumentNullException.ThrowIfNull(username); - if (BlacklistDecisionCache.TryGetValue(username, out var u)) + if (BlacklistDecisionCache.TryGetValue(username, out var cached)) { - return u; + return cached; + } + + // 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 false; } - var b = IsBlacklistedInternal(username, ipAddress); + var blacklisted = IsBlacklistedInternal(username, ipAddress); - BlacklistDecisionCache.Set(username, b, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); + BlacklistDecisionCache.Set(username, blacklisted, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }); - return b; + return blacklisted; bool IsBlacklistedInternal(string username, IPAddress iPAddress = null) { -- cgit v1.2.3 From 0e79985655abcbf10380f60fd50da46c47d8af88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:48:15 -0500 Subject: document GetGroup, remove check of IsBlacklisted within --- src/slskd/Users/UserService.cs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 0a620992..95892753 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -42,6 +42,7 @@ namespace slskd.Users using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; + using Microsoft.Extensions.Internal; using NetTools; using Serilog; using Soulseek; @@ -173,30 +174,45 @@ namespace slskd.Users private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); /// - /// Gets the name of the group for the specified . + /// Gets the name of the group for the specified from cached data. /// - /// The group name is fetched from cached data, and lookups should always be fast. + /// + /// + /// Excludes the 'blacklisted' group for performance; use to guard network operations instead. + /// + /// + /// 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. + /// + /// /// The username of the peer. /// The group for the specified username. public string GetGroup(string username) { + // 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) -- cgit v1.2.3 From c6f3bcb5da8d9a075789b1136cf46bb1ad86835d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:48:42 -0500 Subject: use only cached blacklist status pre-search --- src/slskd/Application.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a8a7883a..b25713ef 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1651,7 +1651,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; } -- cgit v1.2.3 From b7e5f00ce9a9d5f44b956e4f1a70f84fc1b2bea8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:48:56 -0500 Subject: add obsolete flag to BlacklistedGroup --- src/slskd/Application.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b25713ef..6112198c 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -94,6 +94,7 @@ namespace slskd /// /// The name of the blacklisted user group. /// + [Obsolete("use IsBlacklisted instead")] public const string BlacklistedGroup = "blacklisted"; private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; -- cgit v1.2.3 From afdeba219343136d89e6414e0983a5937e272eb4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 22:17:53 -0500 Subject: make cache set more legible --- src/slskd/Users/UserService.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 95892753..4354a0eb 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -342,7 +342,14 @@ namespace slskd.Users var blacklisted = IsBlacklistedInternal(username, ipAddress); - BlacklistDecisionCache.Set(username, blacklisted, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }); + BlacklistDecisionCache.Set( + key: username, + value: blacklisted, + options: new MemoryCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), + Size = 1, + }); return blacklisted; -- cgit v1.2.3 From 5a47b87e6c03cd093ce07274479d5c1dcd7aa2b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 17:54:58 -0500 Subject: blacklisted users appear offline --- .../API/Controllers/ConversationsController.cs | 10 +++++++++ src/slskd/Users/API/Controllers/UsersController.cs | 25 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) (limited to 'src') 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; /// /// Conversations. @@ -56,19 +57,23 @@ namespace slskd.Messaging.API /// /// /// + /// /// public ConversationsController( IStateMonitor applicationStateMonitor, IMessagingService messagingService, + IUserService userService, IOptionsSnapshot optionsSnapshot) { ApplicationStateMonitor = applicationStateMonitor; Messages = messagingService; + Users = userService; OptionsSnapshot = optionsSnapshot; } private IStateMonitor ApplicationStateMonitor { get; } private IMessagingService Messages { get; } + private IUserService Users { get; } private IOptionsSnapshot OptionsSnapshot { get; } /// @@ -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/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); -- cgit v1.2.3 From 2ac28fe1e35f17d12c6e1c2b09d4b7cb90c8d591 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 17:59:31 -0500 Subject: don't try to download from blacklisted users --- .../Transfers/API/Controllers/TransfersController.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') 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; /// /// Transfers. @@ -58,17 +60,21 @@ namespace slskd.Transfers.API /// Initializes a new instance of the class. /// /// + /// /// public TransfersController( ITransferService transferService, + IUserService userService, IOptionsSnapshot 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 OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); @@ -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(); -- cgit v1.2.3 From 1b420744ef3942785de2a1bc72a0ff2e8734b5d2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 18:02:04 -0500 Subject: don't send place in queue to blacklisted users --- src/slskd/Application.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6112198c..814e01a3 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1381,6 +1381,12 @@ namespace slskd private Task 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(null); + } + try { var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); -- cgit v1.2.3 From 3d9bc65bf535a3c4dab440e91587495afba648e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 18:28:52 -0500 Subject: fix ISystemClock --- src/slskd/Users/UserService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 4354a0eb..3ce827c8 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -93,14 +93,14 @@ namespace slskd.Users public UserService( ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, - ISystemClock systemClock) + ISystemClock systemClock = null) { Client = soulseekClient; OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); - InjectedClock = systemClock; + 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 -- cgit v1.2.3