From b39b8606219bd3957b28310b2a4b42f2f8ce3f21 Mon Sep 17 00:00:00 2001 From: Graham Sutherland Date: Fri, 26 Jan 2024 22:25:14 +0000 Subject: Added blacklist file support to the options. Add a new option that allows the user to specify a blacklist file containing CIDRs, e.g. from a blacklist publisher. Introduce a cache for the IPAddressRange objects representing blacklisted CIDRs, to avoid re-parsing them on every call, since the blacklist files may be large. --- src/slskd/Core/Options.cs | 50 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3727b89d..49603872 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -927,11 +927,30 @@ namespace slskd /// public string[] Members { get; init; } = Array.Empty(); + /// + /// A pre-parsed cache of IPAddressRange objects describing all blacklisted ranges. + /// + private List BlacklistedCIDRs = new List(); + /// /// Gets the list of group CIDRs. /// public string[] Cidrs { get; init; } = Array.Empty(); + /// + /// Gets the CIDR blacklist file path. + /// + public string BlacklistFile { get; init; } = string.Empty; + + /// + /// Gets address ranges for all blacklisted CIDRs defined by the configuration file and the blacklist file. + /// + /// An IEnumerable of IPAddressRange objects describing the blacklisted CIDRs. + public IEnumerable GetBlacklistedCIDRs() + { + return BlacklistedCIDRs; + } + /// /// Extended validation. /// @@ -940,12 +959,13 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); + var cache = new List(); foreach (var cidr in Cidrs) { try { - _ = IPAddressRange.Parse(cidr); + cache.Add(IPAddressRange.Parse(cidr)); } catch (Exception ex) { @@ -953,6 +973,32 @@ namespace slskd } } + // if a blacklist file is specified, process it too. + if (!string.IsNullOrEmpty(BlacklistFile)) + { + try + { + var lines = System.IO.File.ReadAllLines(BlacklistFile).Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith("#")); + foreach (var cidr in lines) + { + try + { + cache.Add(IPAddressRange.Parse(cidr)); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"CIDR {cidr} in blacklist file is invalid: {ex.Message}")); + } + } + } + catch (Exception ex) + { + results.Add(new ValidationResult($"CIDR blacklist file {BlacklistFile} could not be loaded: {ex.Message}")); + } + } + + BlacklistedCIDRs = cache.Distinct().ToList(); + return results; } } @@ -2066,4 +2112,4 @@ namespace slskd } } } -} \ No newline at end of file +} -- cgit v1.2.3 From 0b194f1922f1eedf0e4cf7d9dce59b47e7f5389a Mon Sep 17 00:00:00 2001 From: Graham Sutherland Date: Fri, 26 Jan 2024 22:28:14 +0000 Subject: Update IsBlacklisted to use the new GetBlacklistedCIDRs function. This ensures that blacklisted CIDRs from both the config file and the blacklist file are considered. --- src/slskd/Users/UserService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 5b15b671..324e3743 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -273,7 +273,7 @@ namespace slskd.Users return true; } - if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) + if (ipAddress is not null && blacklist.GetBlacklistedCIDRs().Any(range => range.Contains(ipAddress))) { return true; } @@ -410,4 +410,4 @@ namespace slskd.Users updateValueFactory: (key, user) => user with { Username = username, Status = status }); } } -} \ No newline at end of file +} -- cgit v1.2.3 From 106e318d896c521b90b27f438bf7225ffd276b8b Mon Sep 17 00:00:00 2001 From: Graham Sutherland Date: Fri, 26 Jan 2024 22:33:26 +0000 Subject: Document blacklistfile --- docs/config.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index 15a4c817..f46f581f 100644 --- a/docs/config.md +++ b/docs/config.md @@ -359,7 +359,7 @@ Blacklisted users are prevented from: - Retrieving directory contents - Enqueueing downloads -Users can be blacklisted by adding their username to the `members` list. Additionally, users can be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. +Users can be blacklisted by adding their username to the `members` list. Users can also be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. In addition, an external blacklist file containing CIDRs can be specified using `blacklistfile`, with each CIDR on its own line. Empty lines and lines starting with `#` are ignored. Users added to the blacklist will be blocked from enqueueing any new files. Any existing active or queued transfers will need to be cancelled manually. @@ -371,6 +371,7 @@ groups: - cidrs: - + blacklistfile: 'D:\blacklist.txt' ``` ## User Defined Groups -- cgit v1.2.3 From 01eb8baea79339ac7683d1a8b0078427e3be5c75 Mon Sep 17 00:00:00 2001 From: Graham Sutherland Date: Fri, 26 Jan 2024 22:34:33 +0000 Subject: Update slskd.example.yml with blacklistfile option --- config/slskd.example.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index eb0ffce0..c7bf4851 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -93,6 +93,7 @@ # - # cidrs: # - +# blacklistfile: # user_defined: # my_buddies: # upload: -- cgit v1.2.3 From b4728e523d8c32de44922f1e8219b898fa8207e2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 17:29:31 -0500 Subject: add FileAccess to FileExists attribute, test files for access --- src/slskd/Common/Validation/FileExistsAttribute.cs | 30 ++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index c1b3fd15..762cd6b3 100644 --- a/src/slskd/Common/Validation/FileExistsAttribute.cs +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -25,15 +25,41 @@ namespace slskd.Validation /// public class FileExistsAttribute : ValidationAttribute { + public FileExistsAttribute() + { + } + + public FileExistsAttribute(FileAccess fileAccess) + { + FileAccess = fileAccess; + } + + private FileAccess? FileAccess { get; } = null; + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { var file = Path.GetFullPath(value?.ToString()); - if (!string.IsNullOrEmpty(file) && !File.Exists(file)) + if (!string.IsNullOrEmpty(file)) { - return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + if (!File.Exists(file)) + { + return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + } + + if (FileAccess is not null) + { + try + { + File.Open(file, FileMode.Open, FileAccess.Value).Dispose(); + } + catch (IOException) + { + return new ValidationResult($"The {validationContext.DisplayName} field specifies a file '{file}' that cannot be opened for required access '{FileAccess}'"); + } + } } } -- cgit v1.2.3 From fcf5cae9457f01c624e2ac98032cb82973e90888 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 17:33:26 -0500 Subject: rename blacklistfile to file --- config/slskd.example.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 34e1f7fb..39e2d084 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -108,7 +108,7 @@ # - # cidrs: # - -# blacklistfile: +# file: # user_defined: # my_buddies: # upload: -- cgit v1.2.3 From fcde0fb58aa3a4e8aa7fc268c286842de39a9bb5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 17:34:05 -0500 Subject: ensure blacklist file exists and can be read --- src/slskd/Core/Options.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index add3953a..e0ee1aa4 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -994,16 +994,8 @@ namespace slskd /// /// Gets the CIDR blacklist file path. /// - public string BlacklistFile { get; init; } = string.Empty; - - /// - /// Gets address ranges for all blacklisted CIDRs defined by the configuration file and the blacklist file. - /// - /// An IEnumerable of IPAddressRange objects describing the blacklisted CIDRs. - public IEnumerable GetBlacklistedCIDRs() - { - return BlacklistedCIDRs; - } + [FileExists(FileAccess.Read)] + public string File { get; init; } /// /// Extended validation. -- cgit v1.2.3 From 46db12ccfec443341d0a64888e7601667d0b6f0d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 17:34:27 -0500 Subject: remove i/o --- src/slskd/Core/Options.cs | 34 ++-------------------------------- 1 file changed, 2 insertions(+), 32 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e0ee1aa4..c38cf85e 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -24,6 +24,7 @@ namespace slskd using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; + using System.IO; using System.Linq; using System.Text.Json.Serialization; using System.Text.RegularExpressions; @@ -981,11 +982,6 @@ namespace slskd /// public string[] Members { get; init; } = Array.Empty(); - /// - /// A pre-parsed cache of IPAddressRange objects describing all blacklisted ranges. - /// - private List BlacklistedCIDRs = new List(); - /// /// Gets the list of group CIDRs. /// @@ -1019,32 +1015,6 @@ namespace slskd } } - // if a blacklist file is specified, process it too. - if (!string.IsNullOrEmpty(BlacklistFile)) - { - try - { - var lines = System.IO.File.ReadAllLines(BlacklistFile).Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith("#")); - foreach (var cidr in lines) - { - try - { - cache.Add(IPAddressRange.Parse(cidr)); - } - catch (Exception ex) - { - results.Add(new ValidationResult($"CIDR {cidr} in blacklist file is invalid: {ex.Message}")); - } - } - } - catch (Exception ex) - { - results.Add(new ValidationResult($"CIDR blacklist file {BlacklistFile} could not be loaded: {ex.Message}")); - } - } - - BlacklistedCIDRs = cache.Distinct().ToList(); - return results; } } @@ -1883,7 +1853,7 @@ namespace slskd [Argument(default, "https-cert-pfx")] [EnvironmentVariable("HTTPS_CERT_PFX")] [Description("path to X509 certificate .pfx")] - [FileExists] + [FileExists(FileAccess.Read)] [RequiresRestart] public string Pfx { get; init; } -- cgit v1.2.3 From 6abd8142a4b526b562bf1fde2c9fde2164a820cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 18:23:32 -0500 Subject: stub Blacklist --- src/slskd/Users/Blacklist.cs | 73 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/slskd/Users/Blacklist.cs diff --git a/src/slskd/Users/Blacklist.cs b/src/slskd/Users/Blacklist.cs new file mode 100644 index 00000000..de8b567b --- /dev/null +++ b/src/slskd/Users/Blacklist.cs @@ -0,0 +1,73 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd.Users; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; + +/// +/// A managed blacklist for CIDRs. +/// +public class Blacklist +{ + private Dictionary Cache { get; } + + public void Load(string filename) + { + // todo: + // _stream_ contents of file into a ConcurrentDictionary> + // load that dictionary into the Cache + // enjoy + } + + public bool Contains(IPAddress ip) + { + int first = ip.GetAddressBytes()[0]; + + if (!Cache.TryGetValue(first, out (uint, uint)[] cidrs)) + { + return false; + } + + var ipAsUint32 = ToUint32(ip); + + foreach (var cidr in cidrs) + { + if (ipAsUint32 >= cidr.Item1 && ipAsUint32 <= cidr.Item2) + { + return true; + } + } + + return false; + } + + private uint ToUint32(IPAddress ip) + { + byte[] bytes = ip.GetAddressBytes(); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(bytes); + } + + return BitConverter.ToUInt32(bytes, 0); + } +} \ No newline at end of file -- cgit v1.2.3 From d275223aa4afc588bd0731363c58fa3583b8ff36 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 18:24:44 -0500 Subject: move blacklist to core --- src/slskd/Core/Blacklist.cs | 73 ++++++++++++++++++++++++++++++++++++++++++++ src/slskd/Users/Blacklist.cs | 73 -------------------------------------------- 2 files changed, 73 insertions(+), 73 deletions(-) create mode 100644 src/slskd/Core/Blacklist.cs delete mode 100644 src/slskd/Users/Blacklist.cs diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs new file mode 100644 index 00000000..86232d73 --- /dev/null +++ b/src/slskd/Core/Blacklist.cs @@ -0,0 +1,73 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; + +/// +/// A managed blacklist for CIDRs. +/// +public class Blacklist +{ + private Dictionary Cache { get; } + + public void Load(string filename) + { + // todo: + // _stream_ contents of file into a ConcurrentDictionary> + // load that dictionary into the Cache + // enjoy + } + + public bool Contains(IPAddress ip) + { + int first = ip.GetAddressBytes()[0]; + + if (!Cache.TryGetValue(first, out (uint, uint)[] cidrs)) + { + return false; + } + + var ipAsUint32 = ToUint32(ip); + + foreach (var cidr in cidrs) + { + if (ipAsUint32 >= cidr.Item1 && ipAsUint32 <= cidr.Item2) + { + return true; + } + } + + return false; + } + + private uint ToUint32(IPAddress ip) + { + byte[] bytes = ip.GetAddressBytes(); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(bytes); + } + + return BitConverter.ToUInt32(bytes, 0); + } +} \ No newline at end of file diff --git a/src/slskd/Users/Blacklist.cs b/src/slskd/Users/Blacklist.cs deleted file mode 100644 index de8b567b..00000000 --- a/src/slskd/Users/Blacklist.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// 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, either version 3 of the License, or -// (at your option) any later version. -// -// 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/. -// - -namespace slskd.Users; - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Net; - -/// -/// A managed blacklist for CIDRs. -/// -public class Blacklist -{ - private Dictionary Cache { get; } - - public void Load(string filename) - { - // todo: - // _stream_ contents of file into a ConcurrentDictionary> - // load that dictionary into the Cache - // enjoy - } - - public bool Contains(IPAddress ip) - { - int first = ip.GetAddressBytes()[0]; - - if (!Cache.TryGetValue(first, out (uint, uint)[] cidrs)) - { - return false; - } - - var ipAsUint32 = ToUint32(ip); - - foreach (var cidr in cidrs) - { - if (ipAsUint32 >= cidr.Item1 && ipAsUint32 <= cidr.Item2) - { - return true; - } - } - - return false; - } - - private uint ToUint32(IPAddress ip) - { - byte[] bytes = ip.GetAddressBytes(); - - if (BitConverter.IsLittleEndian) - { - Array.Reverse(bytes); - } - - return BitConverter.ToUInt32(bytes, 0); - } -} \ No newline at end of file -- cgit v1.2.3 From be948dcb6989039c6d9fdb805ed44d921a097f7a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 18:25:00 -0500 Subject: move blacklist config to root --- config/slskd.example.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 39e2d084..f4839e6d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -108,7 +108,6 @@ # - # cidrs: # - -# file: # user_defined: # my_buddies: # upload: @@ -121,6 +120,9 @@ # members: # - alice # - bob +# blacklist: +# enabled: true +# file: # filters: # search: # request: -- cgit v1.2.3 From 522974041e4c07050d8cb13b8ca3e65f8dd8060a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 18:25:10 -0500 Subject: add todo --- src/slskd/Users/UserService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 324e3743..7a7de43a 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -273,7 +273,8 @@ namespace slskd.Users return true; } - if (ipAddress is not null && blacklist.GetBlacklistedCIDRs().Any(range => range.Contains(ipAddress))) + // todo: substitute this with a call to the managed blacklist + if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) { return true; } -- cgit v1.2.3 From a841cda6cae75e216259e32231c500a6397238d6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 Mar 2024 23:03:50 -0500 Subject: implement blacklist --- src/slskd/Core/Blacklist.cs | 211 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 204 insertions(+), 7 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 86232d73..b91c9384 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -20,34 +20,188 @@ namespace slskd; using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.IO; using System.Net; +using System.Threading.Tasks; +using NetTools; +using Serilog; + +/// +/// Blacklist file formats. +/// +public enum BlacklistFormat +{ + /// + /// Automatically detect format based on contents. + /// + AutoDetect, + + /// + /// CIDR format. . + /// + /// + /// + /// 1.2.4.0/24 + /// 1.2.8.0/24 + /// 1.9.96.105/32 + /// + /// + CIDR, + + /// + /// P2P format. . + /// + /// + /// + /// China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + /// China Internet Information Center (CNNIC):1.2.8.0-1.2.8.255 + /// Botnet on Telekom Malaysia:1.9.96.105-1.9.96.105 + /// + /// + P2P, + + /// + /// DAT format. . + /// + /// + /// + /// 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + /// 001.002.008.000 - 001.002.008.255 , 000 , China Internet Information Center (CNNIC) + /// 001.009.096.105 - 001.009.096.105 , 000 , Botnet on Telekom Malaysia + /// + /// + DAT, +} /// /// A managed blacklist for CIDRs. /// public class Blacklist { - private Dictionary Cache { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); + private ConcurrentDictionary Cache { get; } = new(); - public void Load(string filename) + /// + /// Loads the contents of the specified into the Blacklist. + /// + /// + /// The existing Blacklist contents are replaced atomically. + /// + /// The fully qualified path to the file to load. + /// The optional blacklist file format. + /// The operation context. + /// + /// Thrown if any of the lines in the file do not match the specified or auto-detected . + /// + /// + /// Thrown if the specified is and the format could not be detected. + /// + public virtual async Task Load(string filename, BlacklistFormat format = BlacklistFormat.AutoDetect) { - // todo: - // _stream_ contents of file into a ConcurrentDictionary> - // load that dictionary into the Cache - // enjoy + if (format == BlacklistFormat.AutoDetect) + { + Log.Debug("Attempting to auto-detect blacklist fomat from contents..."); + format = await AutoDetectBlacklistFormat(filename); // FormatException + Log.Debug("Detected blacklist format {Format}", format); + } + + using var reader = new StreamReader(filename, options: new FileStreamOptions + { + Access = FileAccess.Read, + Mode = FileMode.Open, + Share = FileShare.Read, + BufferSize = 8192, + }); + + var dict = new ConcurrentDictionary>(); + string line = default; + int lineNumber = 0; + + while ((line = await reader.ReadLineAsync()) != null) + { + lineNumber++; + + if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) + { + continue; + } + + IPAddressRange cidr = default; + + /* + parse CIDR from string using specified or detected format + note: we should never get this far without format being one of CIDR, P2P, DAT + */ + + // CIDR format: 1.2.4.0/24 + if (format == BlacklistFormat.CIDR && !IPAddressRange.TryParse(line, out cidr)) + { + throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); + } + + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + else if (format == BlacklistFormat.P2P && !IPAddressRange.TryParse(line.Split(':')[1], out cidr)) + { + throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); + } + + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + else if (format == BlacklistFormat.DAT && !IPAddressRange.TryParse(line.Split(",")[0], out cidr)) + { + throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); + } + + // grab the first octet of the first and last addresses in the range + var first = int.Parse(cidr.Begin.ToString().Split('.')[0]); + var last = int.Parse(cidr.End.ToString().Split('.')[0]); + + var entry = (ToUint32(cidr.Begin), ToUint32(cidr.End)); + + // CIDRs with a mask of /7 and lower span multiple octets, so we must add these CIDRs to the list for each octet + for (int i = 0; i <= last - first; i++) + { + dict.AddOrUpdate( + key: first + i, // first octet + addValueFactory: (_) => new List<(uint, uint)> { entry }, // if we haven't seen this octet yet, initialize the list + updateValueFactory: (_, list) => + { + list.Add(entry); // if we've seen it already, append + return list; + }); + } + } + + // copy working dictionary to cache, converting List<> to array to increase access speed + foreach (var key in dict.Keys) + { + Cache.AddOrUpdate( + key, + addValueFactory: (_) => dict[key].ToArray(), + updateValueFactory: (_, _) => dict[key].ToArray()); + } } - public bool Contains(IPAddress ip) + /// + /// Returns a value indicating whether the specified is contained witin the blacklist. + /// + /// The IP address to check. + /// A value indicating whether the specified IP is contained within the blacklist. + public virtual bool Contains(IPAddress ip) { + // grab the first octet int first = ip.GetAddressBytes()[0]; + // check to see if *any* CIDRs covering this offset are in the blacklist + // best case scenario for performance if not, roughly O(1) if (!Cache.TryGetValue(first, out (uint, uint)[] cidrs)) { return false; } + // conver the entire IP to a uint var ipAsUint32 = ToUint32(ip); + // check the list for this octet sequentially until the first match foreach (var cidr in cidrs) { if (ipAsUint32 >= cidr.Item1 && ipAsUint32 <= cidr.Item2) @@ -56,9 +210,52 @@ public class Blacklist } } + // not in the list + // worst case scenario for performance, O(n) where n = list length return false; } + private async Task AutoDetectBlacklistFormat(string filename) + { + using var reader = new StreamReader(filename, options: new FileStreamOptions + { + Access = FileAccess.Read, + Mode = FileMode.Open, + Share = FileShare.Read, + BufferSize = 512, + }); + + string line = default; + + while ((line = await reader.ReadLineAsync()) != null) + { + if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) + { + continue; + } + + // CIDR format: 1.2.4.0/24 + if (IPAddressRange.TryParse(line, out _)) + { + return BlacklistFormat.CIDR; + } + + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + if (IPAddressRange.TryParse(line.Split(':')[1], out _)) + { + return BlacklistFormat.P2P; + } + + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + if (IPAddressRange.TryParse(line.Split(",")[0], out _)) + { + return BlacklistFormat.DAT; + } + } + + throw new FormatException($"Failed to auto-detect blacklist format. Only CIDR, P2P and DAT formats are supported"); + } + private uint ToUint32(IPAddress ip) { byte[] bytes = ip.GetAddressBytes(); -- cgit v1.2.3 From 0c6b0f5ab6a70512170e01a850f8da5971f7a7a1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 23 Mar 2024 06:53:08 +0000 Subject: Bump webpack-dev-middleware from 5.3.3 to 5.3.4 in /src/web Bumps [webpack-dev-middleware](https://github.com/webpack/webpack-dev-middleware) from 5.3.3 to 5.3.4. - [Release notes](https://github.com/webpack/webpack-dev-middleware/releases) - [Changelog](https://github.com/webpack/webpack-dev-middleware/blob/v5.3.4/CHANGELOG.md) - [Commits](https://github.com/webpack/webpack-dev-middleware/compare/v5.3.3...v5.3.4) --- updated-dependencies: - dependency-name: webpack-dev-middleware dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 4c670d54..5973cd6e 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -20413,9 +20413,9 @@ } }, "node_modules/webpack-dev-middleware": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.3.tgz", - "integrity": "sha512-hj5CYrY0bZLB+eTO+x/j67Pkrquiy7kWepMHmUMoPsmcUaeEnQJqFzHJOyxgWlq746/wUuA64p9ta34Kyb01pA==", + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.4.tgz", + "integrity": "sha512-BVdTqhhs+0IfoeAf7EoH5WE+exCmqGerHfDM0IL096Px60Tq2Mn9MAbnaGUe6HiMa41KMCYF19gyzZmBcq/o4Q==", "dev": true, "dependencies": { "colorette": "^2.0.10", -- cgit v1.2.3 From 18c514d1f45b4d83066a17d73c21ce27938f325b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 29 Mar 2024 03:19:32 +0000 Subject: Bump express from 4.18.2 to 4.19.2 in /src/web Bumps [express](https://github.com/expressjs/express) from 4.18.2 to 4.19.2. - [Release notes](https://github.com/expressjs/express/releases) - [Changelog](https://github.com/expressjs/express/blob/master/History.md) - [Commits](https://github.com/expressjs/express/compare/4.18.2...4.19.2) --- updated-dependencies: - dependency-name: express dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 4c670d54..a1d5efec 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -6297,13 +6297,13 @@ "dev": true }, "node_modules/body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", "dev": true, "dependencies": { "bytes": "3.1.2", - "content-type": "~1.0.4", + "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", @@ -6311,7 +6311,7 @@ "iconv-lite": "0.4.24", "on-finished": "2.4.1", "qs": "6.11.0", - "raw-body": "2.5.1", + "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" }, @@ -7061,9 +7061,9 @@ "dev": true }, "node_modules/cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", "dev": true, "engines": { "node": ">= 0.6" @@ -10341,17 +10341,17 @@ } }, "node_modules/express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", "dev": true, "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.1", + "body-parser": "1.20.2", "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.5.0", + "cookie": "0.6.0", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", @@ -17147,9 +17147,9 @@ } }, "node_modules/raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", "dev": true, "dependencies": { "bytes": "3.1.2", -- cgit v1.2.3 From 65b9904ac817a001aafcc9b0db6e5d21bb99958e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Mar 2024 17:29:31 -0500 Subject: add FileAccess to FileExists attribute, test files for access --- src/slskd/Common/Validation/FileExistsAttribute.cs | 30 ++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index c1b3fd15..762cd6b3 100644 --- a/src/slskd/Common/Validation/FileExistsAttribute.cs +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -25,15 +25,41 @@ namespace slskd.Validation /// public class FileExistsAttribute : ValidationAttribute { + public FileExistsAttribute() + { + } + + public FileExistsAttribute(FileAccess fileAccess) + { + FileAccess = fileAccess; + } + + private FileAccess? FileAccess { get; } = null; + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { var file = Path.GetFullPath(value?.ToString()); - if (!string.IsNullOrEmpty(file) && !File.Exists(file)) + if (!string.IsNullOrEmpty(file)) { - return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + if (!File.Exists(file)) + { + return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + } + + if (FileAccess is not null) + { + try + { + File.Open(file, FileMode.Open, FileAccess.Value).Dispose(); + } + catch (IOException) + { + return new ValidationResult($"The {validationContext.DisplayName} field specifies a file '{file}' that cannot be opened for required access '{FileAccess}'"); + } + } } } -- cgit v1.2.3 From 01a60e7f7eb25010dd35c1b3751906296d4e8733 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Apr 2024 17:59:40 -0500 Subject: guard against malformed lines --- src/slskd/Core/Blacklist.cs | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index b91c9384..1f55e1ba 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -133,20 +133,27 @@ public class Blacklist note: we should never get this far without format being one of CIDR, P2P, DAT */ - // CIDR format: 1.2.4.0/24 - if (format == BlacklistFormat.CIDR && !IPAddressRange.TryParse(line, out cidr)) + try { - throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); + // CIDR format: 1.2.4.0/24 + if (format == BlacklistFormat.CIDR && !IPAddressRange.TryParse(line, out cidr)) + { + throw new Exception(); + } + + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + else if (format == BlacklistFormat.P2P && !IPAddressRange.TryParse(line.Split(':')[1], out cidr)) + { + throw new Exception(); + } + + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + else if (format == BlacklistFormat.DAT && !IPAddressRange.TryParse(line.Split(",")[0], out cidr)) + { + throw new Exception(); + } } - - // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 - else if (format == BlacklistFormat.P2P && !IPAddressRange.TryParse(line.Split(':')[1], out cidr)) - { - throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); - } - - // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) - else if (format == BlacklistFormat.DAT && !IPAddressRange.TryParse(line.Split(",")[0], out cidr)) + catch { throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); } -- cgit v1.2.3 From 40443e3c576418f98ddbe0f616be55359cb74dcb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Apr 2024 17:59:51 -0500 Subject: bumpless (re)loading --- src/slskd/Core/Blacklist.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 1f55e1ba..907fd9ba 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -79,7 +79,7 @@ public enum BlacklistFormat public class Blacklist { private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private ConcurrentDictionary Cache { get; } = new(); + private ConcurrentDictionary Cache { get; set; } = new(); /// /// Loads the contents of the specified into the Blacklist. @@ -101,7 +101,7 @@ public class Blacklist if (format == BlacklistFormat.AutoDetect) { Log.Debug("Attempting to auto-detect blacklist fomat from contents..."); - format = await AutoDetectBlacklistFormat(filename); // FormatException + format = await AutoDetectBlacklistFormat(filename); // FormatException if unsuccessful Log.Debug("Detected blacklist format {Format}", format); } @@ -110,7 +110,7 @@ public class Blacklist Access = FileAccess.Read, Mode = FileMode.Open, Share = FileShare.Read, - BufferSize = 8192, + BufferSize = 262144, // 256kib, assumes most blacklists will be > 1mb }); var dict = new ConcurrentDictionary>(); @@ -178,14 +178,19 @@ public class Blacklist } } - // copy working dictionary to cache, converting List<> to array to increase access speed + // copy working dictionary to a temporary cache, converting List<> to array to increase access speed + var tempCache = new ConcurrentDictionary(); + foreach (var key in dict.Keys) { - Cache.AddOrUpdate( + tempCache.AddOrUpdate( key, addValueFactory: (_) => dict[key].ToArray(), updateValueFactory: (_, _) => dict[key].ToArray()); } + + // swap the temporary cache for the "real" cache, enabling a bumpless update + Cache = tempCache; } /// @@ -229,11 +234,11 @@ public class Blacklist Access = FileAccess.Read, Mode = FileMode.Open, Share = FileShare.Read, - BufferSize = 512, }); string line = default; + // read the first non-empty, non-commented line from the file while ((line = await reader.ReadLineAsync()) != null) { if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) -- cgit v1.2.3 From 0ddd0626002c9ff15deffe91b78d3d5eae51d5ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Apr 2024 18:20:29 -0500 Subject: sort values --- src/slskd/Core/Blacklist.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 907fd9ba..d7a680aa 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -21,6 +21,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Net; using System.Threading.Tasks; using NetTools; @@ -178,15 +179,14 @@ public class Blacklist } } - // copy working dictionary to a temporary cache, converting List<> to array to increase access speed + // copy working dictionary to a temporary cache to: + // * convert List<> to array to increase access speed + // * sort arrays by first IP to enable binary search var tempCache = new ConcurrentDictionary(); foreach (var key in dict.Keys) { - tempCache.AddOrUpdate( - key, - addValueFactory: (_) => dict[key].ToArray(), - updateValueFactory: (_, _) => dict[key].ToArray()); + tempCache[key] = dict[key].OrderBy(x => x.First).ToArray(); } // swap the temporary cache for the "real" cache, enabling a bumpless update -- cgit v1.2.3 From 8815f5042ca19cb082e966497d088ca9b3d79f28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 17:42:49 -0500 Subject: make format detection public --- src/slskd/Core/Blacklist.cs | 107 +++++++++++++++++++++++++++----------------- 1 file changed, 66 insertions(+), 41 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index d7a680aa..dc8a9162 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -82,6 +82,72 @@ public class Blacklist private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Cache { get; set; } = new(); + /// + /// Examines the contents of the specified and attempts to determine the format. + /// + /// The fully qualified path to the file to examine. + /// The detected format. + /// Thrown if the specified filename can't be accessed. + /// Thrown if the format can't be determined. + public static async Task DetectFormat(string filename) + { + using var reader = new StreamReader(filename, options: new FileStreamOptions + { + Access = FileAccess.Read, + Mode = FileMode.Open, + Share = FileShare.Read, + }); + + string line = default; + + // read the first non-empty, non-commented line from the file + while ((line = await reader.ReadLineAsync()) != null) + { + if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) + { + continue; + } + + try + { + // CIDR format: 1.2.4.0/24 + if (IPAddressRange.TryParse(line, out _)) + { + return BlacklistFormat.CIDR; + } + } + catch + { + } + + try + { + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + if (IPAddressRange.TryParse(line.Split(':')[1], out _)) + { + return BlacklistFormat.P2P; + } + } + catch + { + } + + try + { + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + if (IPAddressRange.TryParse(line.Split(",")[0], out _)) + { + return BlacklistFormat.DAT; + } + } + catch + { + } + } + + throw new FormatException($"Failed to auto-detect blacklist format. Only CIDR, P2P and DAT formats are supported"); + } + /// /// Loads the contents of the specified into the Blacklist. /// @@ -227,47 +293,6 @@ public class Blacklist return false; } - private async Task AutoDetectBlacklistFormat(string filename) - { - using var reader = new StreamReader(filename, options: new FileStreamOptions - { - Access = FileAccess.Read, - Mode = FileMode.Open, - Share = FileShare.Read, - }); - - string line = default; - - // read the first non-empty, non-commented line from the file - while ((line = await reader.ReadLineAsync()) != null) - { - if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) - { - continue; - } - - // CIDR format: 1.2.4.0/24 - if (IPAddressRange.TryParse(line, out _)) - { - return BlacklistFormat.CIDR; - } - - // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 - if (IPAddressRange.TryParse(line.Split(':')[1], out _)) - { - return BlacklistFormat.P2P; - } - - // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) - if (IPAddressRange.TryParse(line.Split(",")[0], out _)) - { - return BlacklistFormat.DAT; - } - } - - throw new FormatException($"Failed to auto-detect blacklist format. Only CIDR, P2P and DAT formats are supported"); - } - private uint ToUint32(IPAddress ip) { byte[] bytes = ip.GetAddressBytes(); -- cgit v1.2.3 From d157f72d4640c1c94f279a2f2377bb97d7c76c3e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 17:46:15 -0500 Subject: include format failure reason --- src/slskd/Core/Blacklist.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index dc8a9162..5242a797 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -220,9 +220,9 @@ public class Blacklist throw new Exception(); } } - catch + catch (Exception ex) { - throw new FormatException($"Failed to parse blacklist line {lineNumber} '{line}' (expected {format} format)"); + throw new FormatException($"Failed to parse {format} blacklist line {lineNumber} '{line}': {ex.Message}"); } // grab the first octet of the first and last addresses in the range -- cgit v1.2.3 From e228e3717eddf1168657437187fb1c41ebf1c197 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 17:46:35 -0500 Subject: strip leading zeros from DAT entries --- src/slskd/Core/Blacklist.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 5242a797..3d9805d0 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -215,9 +215,24 @@ public class Blacklist } // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) - else if (format == BlacklistFormat.DAT && !IPAddressRange.TryParse(line.Split(",")[0], out cidr)) + else if (format == BlacklistFormat.DAT) { - throw new Exception(); + // the IPAddressRange library doesn't like leading zeros, so we have to remove them + static string TrimLeadingZerosFromEachOctet(string ip) + => string.Join('.', ip.Split('.').Select(octet => octet == "000" ? "0" : octet.TrimStart('0'))); + + // 001.002.004.000-001.002.004.255 + var range = line.Split(",")[0] + .Replace(" ", string.Empty); + + // [1.2.4.0, 1.2.4.255] + var ips = range.Split("-") + .Select(TrimLeadingZerosFromEachOctet); + + if (!IPAddressRange.TryParse(string.Join('-', ips), out cidr)) + { + throw new Exception(); + } } } catch (Exception ex) -- cgit v1.2.3 From b760b7ba6f9200b3f7295c19230b19041d10be21 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 17:48:15 -0500 Subject: expose total count --- src/slskd/Core/Blacklist.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 3d9805d0..9f49c022 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -79,6 +79,11 @@ public enum BlacklistFormat /// public class Blacklist { + /// + /// Gets the total number of loaded CIDRs. + /// + public long Count => Cache.Sum(kvp => kvp.Value.Length); + private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Cache { get; set; } = new(); -- cgit v1.2.3 From 0c1aedd8eebb591aeadc9bdcd1ccf351ab47c77a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 17:48:31 -0500 Subject: docs --- src/slskd/Core/Blacklist.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 9f49c022..857b9002 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -162,6 +162,7 @@ public class Blacklist /// The fully qualified path to the file to load. /// The optional blacklist file format. /// The operation context. + /// Thrown if the specified filename can't be accessed. /// /// Thrown if any of the lines in the file do not match the specified or auto-detected . /// @@ -173,7 +174,7 @@ public class Blacklist if (format == BlacklistFormat.AutoDetect) { Log.Debug("Attempting to auto-detect blacklist fomat from contents..."); - format = await AutoDetectBlacklistFormat(filename); // FormatException if unsuccessful + format = await DetectFormat(filename); // FormatException if unsuccessful Log.Debug("Detected blacklist format {Format}", format); } @@ -267,7 +268,7 @@ public class Blacklist // copy working dictionary to a temporary cache to: // * convert List<> to array to increase access speed - // * sort arrays by first IP to enable binary search + // * sort arrays by first IP to enable binary search (future?) var tempCache = new ConcurrentDictionary(); foreach (var key in dict.Keys) -- cgit v1.2.3 From 605e15e3e72b6210f3f43939cb3b4d2c704ad590 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 17:48:50 -0500 Subject: add blacklist tests --- tests/slskd.Tests.Unit/Common/BlacklistTests.cs | 74 +++++++++++++++++++++++++ tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt | 7 +++ tests/slskd.Tests.Unit/Data/Blacklist/dat.txt | 7 +++ tests/slskd.Tests.Unit/Data/Blacklist/empty.txt | 13 +++++ tests/slskd.Tests.Unit/Data/Blacklist/junk.txt | 3 + tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt | 7 +++ tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj | 18 ++++++ 7 files changed, 129 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/BlacklistTests.cs create mode 100644 tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt create mode 100644 tests/slskd.Tests.Unit/Data/Blacklist/dat.txt create mode 100644 tests/slskd.Tests.Unit/Data/Blacklist/empty.txt create mode 100644 tests/slskd.Tests.Unit/Data/Blacklist/junk.txt create mode 100644 tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt diff --git a/tests/slskd.Tests.Unit/Common/BlacklistTests.cs b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs new file mode 100644 index 00000000..71f67dd4 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public class BlacklistTests +{ + [Theory] + [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] + [InlineData("Data/Blacklist/dat.txt", BlacklistFormat.DAT)] + [InlineData("Data/Blacklist/p2p.txt", BlacklistFormat.P2P)] + public async Task DetectFormat_Detects(string filename, BlacklistFormat expected) + { + var result = await Blacklist.DetectFormat(filename); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Data/Blacklist/junk.txt", typeof(FormatException))] + [InlineData("Data/Blacklist/empty.txt", typeof(FormatException))] + [InlineData("Data/does.not.exist.txt", typeof(IOException))] + public async Task DetectFormat_Throws(string filename, Type exType) + { + var ex = await Record.ExceptionAsync(() => Blacklist.DetectFormat(filename)); + + Assert.NotNull(ex); + Assert.IsAssignableFrom(exType, ex); + } + + [Theory] + [InlineData("Data/Blacklist/junk.txt", BlacklistFormat.CIDR, typeof(FormatException))] + [InlineData("Data/does.not.exist.txt", BlacklistFormat.DAT, typeof(IOException))] + public async Task Load_throws(string filename, BlacklistFormat format, Type exType) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename, format)); + + Assert.NotNull(ex); + Assert.IsAssignableFrom(exType, ex); + } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] + [InlineData("Data/Blacklist/dat.txt", BlacklistFormat.DAT)] + [InlineData("Data/Blacklist/p2p.txt", BlacklistFormat.P2P)] + public async Task Load_Loads(string filename, BlacklistFormat format) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename, format)); + + Assert.Null(ex); + + // the test files are assumed to all contain 5 entries + Assert.Equal(5, bl.Count); + } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt")] + [InlineData("Data/Blacklist/dat.txt")] + [InlineData("Data/Blacklist/p2p.txt")] + public async Task Load_AutoDetects_And_Loads(string filename) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename)); + + Assert.Null(ex); + + // the test files are assumed to all contain 5 entries + Assert.Equal(5, bl.Count); + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt b/tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt new file mode 100644 index 00000000..850a2074 --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt @@ -0,0 +1,7 @@ +# here's a comment + +1.2.4.0/24 +1.2.8.0/24 +1.9.96.105/32 +1.9.102.251/32 +1.9.106.186/32 \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/dat.txt b/tests/slskd.Tests.Unit/Data/Blacklist/dat.txt new file mode 100644 index 00000000..9386a98f --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/dat.txt @@ -0,0 +1,7 @@ +# here's a comment + +001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) +001.002.008.000 - 001.002.008.255 , 000 , China Internet Information Center (CNNIC) +001.009.096.105 - 001.009.096.105 , 000 , Botnet on Telekom Malaysia +001.009.102.251 - 001.009.102.251 , 000 , Botnet on Telekom Malaysia +001.009.106.186 - 001.009.106.186 , 000 , Botnet on Telekom Malaysia \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/empty.txt b/tests/slskd.Tests.Unit/Data/Blacklist/empty.txt new file mode 100644 index 00000000..a50080e3 --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/empty.txt @@ -0,0 +1,13 @@ +# only a comment and some blank lines + + + + + + + + + + + +# end \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/junk.txt b/tests/slskd.Tests.Unit/Data/Blacklist/junk.txt new file mode 100644 index 00000000..b42f309e --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/junk.txt @@ -0,0 +1,3 @@ +{ + "foo": "bar" +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt b/tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt new file mode 100644 index 00000000..fb18aa83 --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt @@ -0,0 +1,7 @@ +# here's a comment + +China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 +China Internet Information Center (CNNIC):1.2.8.0-1.2.8.255 +Botnet on Telekom Malaysia:1.9.96.105-1.9.96.105 +Botnet on Telekom Malaysia:1.9.102.251-1.9.102.251 +Botnet on Telekom Malaysia:1.9.106.186-1.9.106.186 \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj index 127e0c1d..04b18bb7 100644 --- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj +++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj @@ -25,4 +25,22 @@ + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + -- cgit v1.2.3 From 4388d31bf151c07e9805ec0ba77232eded375385 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Apr 2024 18:29:31 -0500 Subject: add tests for Contains() --- tests/slskd.Tests.Unit/Common/BlacklistTests.cs | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/slskd.Tests.Unit/Common/BlacklistTests.cs b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs index 71f67dd4..efe76921 100644 --- a/tests/slskd.Tests.Unit/Common/BlacklistTests.cs +++ b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Net; using System.Threading.Tasks; using Xunit; @@ -7,6 +9,25 @@ namespace slskd.Tests.Unit.Common; public class BlacklistTests { + private List<(string, bool)> IPs = new List<(string, bool)>() + { + ("1.2.4.0", true), + ("1.2.4.128", true), + ("1.2.4.255", true), + ("1.2.8.0", true), + ("1.2.8.128", true), + ("1.2.8.255", true), + ("1.9.96.104", false), + ("1.9.96.105", true), + ("1.9.102.250", false), + ("1.9.102.251", true), + ("1.9.106.186", true), + ("1.9.106.187", false), + ("192.168.1.1", false), + ("4.4.4.4", false), + ("123.234.111.123", false), + }; + [Theory] [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] [InlineData("Data/Blacklist/dat.txt", BlacklistFormat.DAT)] @@ -71,4 +92,22 @@ public class BlacklistTests // the test files are assumed to all contain 5 entries Assert.Equal(5, bl.Count); } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt")] + [InlineData("Data/Blacklist/dat.txt")] + [InlineData("Data/Blacklist/p2p.txt")] + public async Task CIDR_Contains(string filename) + { + var bl = new Blacklist(); + await bl.Load(filename); + + foreach (var ip in IPs) + { + if (bl.Contains(IPAddress.Parse(ip.Item1)) != ip.Item2) + { + throw new Exception($"Expected contains for {ip.Item1} to be {ip.Item2} but it wasn't"); + } + } + } } \ No newline at end of file -- cgit v1.2.3 From 8191c984c52e886c3fba40c7fdcc48f9382abf46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:11:03 -0500 Subject: add Exit() --- src/slskd/Program.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d7f6caca..918ca828 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -241,6 +241,12 @@ namespace slskd [Argument('v', "version", "display version information")] private static bool ShowVersion { get; set; } + /// + /// Panic. + /// + /// An optional exit code. + public static void Exit(int code = 1) => Environment.Exit(code); + /// /// Entrypoint. /// @@ -576,7 +582,9 @@ namespace slskd services.AddTransient(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From c9c01ad332a22cb190810f437d1bc17306a9982d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:11:22 -0500 Subject: add Clear() --- src/slskd/Core/Blacklist.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 857b9002..f9504c52 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -153,6 +153,11 @@ public class Blacklist throw new FormatException($"Failed to auto-detect blacklist format. Only CIDR, P2P and DAT formats are supported"); } + /// + /// Clears the contents of the Blacklist. + /// + public virtual void Clear() => Cache.Clear(); + /// /// Loads the contents of the specified into the Blacklist. /// -- cgit v1.2.3 From d92a201c953efab7229b8c6f489001ce99b0b597 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:14:01 -0500 Subject: add test for Clear() --- tests/slskd.Tests.Unit/Common/BlacklistTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/slskd.Tests.Unit/Common/BlacklistTests.cs b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs index efe76921..9f21dde8 100644 --- a/tests/slskd.Tests.Unit/Common/BlacklistTests.cs +++ b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs @@ -78,6 +78,23 @@ public class BlacklistTests Assert.Equal(5, bl.Count); } + [Theory] + [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] + public async Task Load_Then_Clear(string filename, BlacklistFormat format) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename, format)); + + Assert.Null(ex); + + // the test files are assumed to all contain 5 entries + Assert.Equal(5, bl.Count); + + bl.Clear(); + + Assert.Equal(0, bl.Count); + } + [Theory] [InlineData("Data/Blacklist/cidr.txt")] [InlineData("Data/Blacklist/dat.txt")] -- cgit v1.2.3 From fabfad8e17222514c14ca540c3b0a9911e816f29 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:14:15 -0500 Subject: add Blacklist options --- src/slskd/Core/Options.cs | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index c38cf85e..e99eb85f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -234,6 +234,12 @@ namespace slskd [Validate] public GroupsOptions Groups { get; init; } = new GroupsOptions(); + /// + /// Gets blacklist options. + /// + [Validate] + public BlacklistOptions Blacklist { get; init; } = new BlacklistOptions(); + /// /// Gets filter options. /// @@ -987,12 +993,6 @@ namespace slskd /// public string[] Cidrs { get; init; } = Array.Empty(); - /// - /// Gets the CIDR blacklist file path. - /// - [FileExists(FileAccess.Read)] - public string File { get; init; } - /// /// Extended validation. /// @@ -1106,6 +1106,27 @@ namespace slskd public bool Swagger { get; init; } = false; } + public class BlacklistOptions + { + /// + /// Gets a value indicating whether blacklist file support should be enabled. + /// + [Argument(default, "enable-blacklist")] + [EnvironmentVariable("BLACKLIST")] + [Description("enable blacklist file support")] + [RequiresRestart] + public bool Enabled { get; init; } + + /// + /// Gets the path to the blacklist file. + /// + [Argument(default, "blacklist-file")] + [EnvironmentVariable("BLACKLIST_FILE")] + [Description("path to blacklist file")] + [FileExists(FileAccess.Read)] + public string File { get; init; } + } + /// /// Filter options. /// -- cgit v1.2.3 From 4e2386deebe1bc5ede1d51aa29c126fc0f694c90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:14:36 -0500 Subject: add docs to events --- src/slskd/Users/UserService.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 7a7de43a..757d9333 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -91,8 +91,16 @@ namespace slskd.Users _ = GetStatisticsAsync(userStatus.Username); }; - Client.Connected += (_, _) => Reset(); + // it's important for us to force a reconfig at login to discard any users that were previously tracked + // specific scenario being; up and running for some time, offline for some time (days?), reconnect, are users still online? have stats changed? + // to avoid needing to go through and exhaustively check each user in the tracking dictionary, just delete it and let it be built back up + // any user we are downloading from will be tracked again when pending downloads are re-requested Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); + + // working hand-in-hand with the forced reconfig on login, reset clears everything upon connect; clearing the way + // for the reconfig at login to rebuild it. i think. yeah, that sounds right. we don't ever want Configure() to reset anything + // so the connect is distinctly different from reconfig at login. + Client.Connected += (_, _) => Reset(); Client.PrivilegedUserListReceived += (_, list) => Client_PrivilegedUserListReceived(list); Configure(OptionsMonitor.CurrentValue); -- cgit v1.2.3 From 0691977ea44fdccf46d752560b669cddf72e080b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:15:09 -0500 Subject: add a check for Blacklist --- src/slskd/Users/UserService.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 757d9333..2f718c7c 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -281,12 +281,20 @@ namespace slskd.Users return true; } - // todo: substitute this with a call to the managed blacklist + // 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; } -- cgit v1.2.3 From 0cf8603c69176f194bb61f764e2f66a3c40e4e0f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:15:50 -0500 Subject: invert reconfig expression --- src/slskd/Users/UserService.cs | 58 ++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 2f718c7c..4b702933 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -364,45 +364,43 @@ namespace slskd.Users { var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); - if (optionsHash == LastOptionsHash && !force) + if (optionsHash != LastOptionsHash || force) { - 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 - var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); - var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); - var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); - - // clear the configured group for anyone that was removed from config, or that was added transiently - foreach (var username in usernamesRemoved) - { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Username = username }, - updateValueFactory: (key, user) => user with { Username = username, Group = null }); - } - - // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the - // operation is complete. - foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) - { - foreach (var username in group.Value.Members) + // 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); + + // clear the configured group for anyone that was removed from config, or that was added transiently + foreach (var username in usernamesRemoved) { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Username = username, Group = group.Key }, - updateValueFactory: (key, user) => user with { Username = username, Group = group.Key }); + addValue: new User() { Username = username }, + updateValueFactory: (key, user) => user with { Username = username, Group = null }); + } - if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) + // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the + // operation is complete. + foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) + { + foreach (var username in group.Value.Members) { - _ = WatchAsync(username); + UserDictionary.AddOrUpdate( + 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); + } } } - } - LastOptionsHash = optionsHash; + LastOptionsHash = optionsHash; + } } private void Reset() -- cgit v1.2.3 From 23f82bd69dfb80a517cf5d324f5e972456c20606 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Apr 2024 18:28:27 -0500 Subject: blacklist reconfig logic --- src/slskd/Users/UserService.cs | 45 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 4b702933..61ad66a6 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -118,8 +118,10 @@ namespace slskd.Users private ISoulseekClient Client { get; } private string LastOptionsHash { get; set; } + private string LastBlacklistOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } + private Blacklist Blacklist { get; } = new Blacklist(); /// /// Gets or sets the internal cache of User data. @@ -401,6 +403,47 @@ namespace slskd.Users LastOptionsHash = optionsHash; } + + var blacklistOptionsHash = Compute.Sha1Hash(options.Blacklist.ToJson()); + + // there's no forced re-config of the blacklist; either the config changed or it didn't. + // if the underlying file changed, users can toggle the blacklist off and on or restart + // the application. these sorts of blacklists should be relatively static (i think) + if (blacklistOptionsHash != LastBlacklistOptionsHash) + { + Log.Debug("Blacklist options changed: {JSON}", options.Blacklist.ToJson()); + + if (!options.Blacklist.Enabled) + { + Log.Debug("Blacklist disabled; clearing contents"); + Blacklist.Clear(); + Log.Information("Blacklist disabled"); + } + else + { + // the option validation logic should have ensured the file format could be auto-detected and that the file + // contained no formatting errors. this should only fail on transient I/O errors. + _ = Task.Run(() => Blacklist.Load(options.Blacklist.File, BlacklistFormat.AutoDetect)) + .ContinueWith(task => + { + // if the task faulted, the load of the file failed, and the user isn't getting the + // intended protection from the blacklist. in this case we can: + // 1) log an error and continue, potentially against the desires of the user + // 2) kill the application and force the user to deal with the cause + // a user taking advantage of the blacklist feature would absolutely want to know if it wasn't working, + // so we're taking door #2. + if (task.IsFaulted) + { + Log.Fatal(task.Exception, "Fatal error loading blacklist from file {File}: {Message}", options.Blacklist.File, task.Exception?.Message); + Program.Exit(1); + } + else + { + Log.Information("Blacklist updated with {Count} CIDRs from file {File}", Blacklist.Count, options.Blacklist.File); + } + }); + } + } } private void Reset() -- cgit v1.2.3 From 10b70fd2d4d11089e60331bded941d6306f2dd25 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 17:17:05 -0500 Subject: tweak exception message --- src/slskd/Core/Blacklist.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index f9504c52..730fb9ca 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -150,7 +150,7 @@ public class Blacklist } } - throw new FormatException($"Failed to auto-detect blacklist format. Only CIDR, P2P and DAT formats are supported"); + throw new FormatException($"Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported"); } /// -- cgit v1.2.3 From 50d7bd6ffea49909a4679d09242f405fa6c32fe4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 18:41:08 -0500 Subject: use more resilient splitting --- src/slskd/Core/Blacklist.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 730fb9ca..c46e5d25 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -222,7 +222,7 @@ public class Blacklist // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 else if (format == BlacklistFormat.P2P && !IPAddressRange.TryParse(line.Split(':')[1], out cidr)) { - throw new Exception(); + cidr = IPAddressRange.Parse(line.Split(':').Last()); } // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) @@ -233,8 +233,7 @@ public class Blacklist => string.Join('.', ip.Split('.').Select(octet => octet == "000" ? "0" : octet.TrimStart('0'))); // 001.002.004.000-001.002.004.255 - var range = line.Split(",")[0] - .Replace(" ", string.Empty); + var range = line.Split(",").First().Replace(" ", string.Empty); // [1.2.4.0, 1.2.4.255] var ips = range.Split("-") -- cgit v1.2.3 From 163ac3ddcf38a568ed34679a76760c3e923ef9be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 18:41:28 -0500 Subject: better error messages --- src/slskd/Core/Blacklist.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index c46e5d25..4a47b8a8 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -214,13 +214,13 @@ public class Blacklist try { // CIDR format: 1.2.4.0/24 - if (format == BlacklistFormat.CIDR && !IPAddressRange.TryParse(line, out cidr)) + if (format == BlacklistFormat.CIDR) { - throw new Exception(); + cidr = IPAddressRange.Parse(line); } // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 - else if (format == BlacklistFormat.P2P && !IPAddressRange.TryParse(line.Split(':')[1], out cidr)) + else if (format == BlacklistFormat.P2P) { cidr = IPAddressRange.Parse(line.Split(':').Last()); } @@ -239,10 +239,7 @@ public class Blacklist var ips = range.Split("-") .Select(TrimLeadingZerosFromEachOctet); - if (!IPAddressRange.TryParse(string.Join('-', ips), out cidr)) - { - throw new Exception(); - } + cidr = IPAddressRange.Parse(string.Join('-', ips)); } } catch (Exception ex) -- cgit v1.2.3 From 2460cf84334f77be9515c1674a3d710a34479bc9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 18:42:05 -0500 Subject: deduplicate entries --- src/slskd/Core/Blacklist.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 4a47b8a8..7b1a46c6 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -268,13 +268,17 @@ public class Blacklist } // copy working dictionary to a temporary cache to: - // * convert List<> to array to increase access speed + // * deduplicate entries // * sort arrays by first IP to enable binary search (future?) + // * convert List<> to array to increase access speed var tempCache = new ConcurrentDictionary(); foreach (var key in dict.Keys) { - tempCache[key] = dict[key].OrderBy(x => x.First).ToArray(); + tempCache[key] = dict[key] + .Distinct() + .OrderBy(x => x.First) + .ToArray(); } // swap the temporary cache for the "real" cache, enabling a bumpless update -- cgit v1.2.3 From 8c2802cdda09238818b04f51643183c74818b98f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 18:42:25 -0500 Subject: benchmark load --- src/slskd/Core/Blacklist.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 7b1a46c6..56414ad6 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -20,6 +20,7 @@ namespace slskd; using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using System.Net; @@ -183,6 +184,10 @@ public class Blacklist Log.Debug("Detected blacklist format {Format}", format); } + var sw = new Stopwatch(); + sw.Start(); + Log.Debug("Loading blacklist"); + using var reader = new StreamReader(filename, options: new FileStreamOptions { Access = FileAccess.Read, @@ -283,6 +288,9 @@ public class Blacklist // swap the temporary cache for the "real" cache, enabling a bumpless update Cache = tempCache; + + sw.Stop(); + Log.Debug("Blacklist loaded in {Duration}ms", sw.ElapsedMilliseconds); } /// -- cgit v1.2.3 From 6126fd7508c7ebb503ec29db81eb9e7e17170b71 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 18:44:04 -0500 Subject: add validation for blacklist format --- src/slskd/Core/Options.cs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e99eb85f..afc9b07f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1106,7 +1106,10 @@ namespace slskd public bool Swagger { get; init; } = false; } - public class BlacklistOptions + /// + /// Blacklist options. + /// + public class BlacklistOptions : IValidatableObject { /// /// Gets a value indicating whether blacklist file support should be enabled. @@ -1125,6 +1128,36 @@ namespace slskd [Description("path to blacklist file")] [FileExists(FileAccess.Read)] public string File { get; init; } + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (!Enabled) + { + return results; + } + + // loading/validating the entire list will be costly on low spec systems + // just make sure that we can detect a valid format and leave it at that + // if there's a problem with any of the entries, the load will fail and + // kill the application + try + { + _ = slskd.Blacklist.DetectFormat(File); + } + catch (FormatException ex) + { + results.Add(new ValidationResult(ex.Message)); + } + + return results; + } } /// -- cgit v1.2.3 From 5013879d30e0091decbadfc38360117873238518 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Apr 2024 19:06:21 -0500 Subject: capture blacklist option hash --- src/slskd/Users/UserService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 61ad66a6..e278ccc7 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -443,6 +443,8 @@ namespace slskd.Users } }); } + + LastBlacklistOptionsHash = blacklistOptionsHash; } } -- cgit v1.2.3 From 28372896b8dae9fd20b48a2a6bc8e077e91e18ea Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Apr 2024 17:25:20 -0500 Subject: revert cidr cache --- src/slskd/Core/Options.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index afc9b07f..0ede272d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1001,13 +1001,12 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); - var cache = new List(); foreach (var cidr in Cidrs ?? Array.Empty()) { try { - cache.Add(IPAddressRange.Parse(cidr)); + _ = IPAddressRange.Parse(cidr); } catch (Exception ex) { -- cgit v1.2.3 From 0f79d9f8fd07690e5e3757c1be6f23e1c205dd86 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Apr 2024 18:02:15 -0500 Subject: make validation work --- src/slskd/Core/Blacklist.cs | 2 +- src/slskd/Core/Options.cs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 56414ad6..76f0b37f 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -151,7 +151,7 @@ public class Blacklist } } - throw new FormatException($"Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported"); + throw new FormatException("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported"); } /// diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 0ede272d..81dc09f6 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1148,11 +1148,12 @@ namespace slskd // kill the application try { - _ = slskd.Blacklist.DetectFormat(File); + // async not supported here, .Result is all we have + _ = slskd.Blacklist.DetectFormat(File).Result; } - catch (FormatException ex) + catch { - results.Add(new ValidationResult(ex.Message)); + results.Add(new ValidationResult("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported")); } return results; -- cgit v1.2.3 From ae877bfc0c028de9e1ea6b297c69a7e686ec382d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 2 May 2024 11:10:31 +0000 Subject: Bump ejs from 3.1.9 to 3.1.10 in /src/web Bumps [ejs](https://github.com/mde/ejs) from 3.1.9 to 3.1.10. - [Release notes](https://github.com/mde/ejs/releases) - [Commits](https://github.com/mde/ejs/compare/v3.1.9...v3.1.10) --- updated-dependencies: - dependency-name: ejs dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 3419b628..90d5e9fe 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -8061,9 +8061,9 @@ "dev": true }, "node_modules/ejs": { - "version": "3.1.9", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.9.tgz", - "integrity": "sha512-rC+QVNMJWv+MtPgkt0y+0rVEIdbtxVADApW9JXrUVlzHetgcyczP/E7DJmWJ4fJCZF2cPcBk0laWO9ZHMG3DmQ==", + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", "dev": true, "dependencies": { "jake": "^10.8.5" -- cgit v1.2.3 From 2a5c671499ac7bb542d7373464ac4a57465d971d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 May 2024 13:34:37 -0500 Subject: document the managed blacklist --- docs/config.md | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/docs/config.md b/docs/config.md index 265b3fd2..f81fe8c0 100644 --- a/docs/config.md +++ b/docs/config.md @@ -415,7 +415,7 @@ groups: failures: 30 ``` -## Blacklist +## User Blacklist A fourth built-in group, `blacklisted`, is used to disallow other users from various activities. @@ -425,10 +425,12 @@ Blacklisted users are prevented from: - Retrieving directory contents - Enqueueing downloads -Users can be blacklisted by adding their username to the `members` list. Users can also be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. In addition, an external blacklist file containing CIDRs can be specified using `blacklistfile`, with each CIDR on its own line. Empty lines and lines starting with `#` are ignored. +Users can be blacklisted by adding their username to the `members` list. Additionally, users can be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. Users added to the blacklist will be blocked from enqueueing any new files. Any existing active or queued transfers will need to be cancelled manually. +A managed blacklist file may also be used to achieve the same effects. Read more about this in the [Managed Blacklist](#managed-blacklist) section below. + **YAML** ```yaml groups: @@ -437,7 +439,6 @@ groups: - cidrs: - - blacklistfile: 'D:\blacklist.txt' ``` ## User Defined Groups @@ -505,6 +506,27 @@ groups: - bob ``` +## Managed Blacklist + +A managed blacklist (also called a blocklist) can be specified to disallow interaction with known undesireable actors. Users whose IP address metches an entry on this list are functionally the same as users added to the [User Blacklist](#user-blacklist) described above and are disallowed any interactions with shares or files. + +Blacklists/blocklists designed for use with other P2P applications (such as BitTorrent) are supported; specifically the P2P, DAT, and CIDR formats. + +When enabled, the specified file is validated by reading the first few lines of the file to automatically detect the format. If the file doesn't exist, can't be read, the format can't be detected, or if it contains any lines that don't match the format, the application will exit. Similarly, if the file changes while the application is running and there's an issue, the application will exit. + +Note that the contents of the blacklist are stored in memory to ensure performance, and this will increase the amount of memory used, potentially significantly if the blacklist is large. + +| Command-Line | Environment Variable | Description | +| -------------------- | -------------------- | ------------------------------ | +| `--enable-blacklist` | `BLACKLIST` | Enable the managed blacklist | +| `--blacklist-file` | `BLACKLIST_FILE` | The path to the blacklist file | + +```yaml +blacklist: + enabled: true + file: +``` + # Chat Rooms and Private Messaging ## Auto-Joining Rooms @@ -515,7 +537,6 @@ The list can be specified via command line (e.g. --rooms --rooms Additionally, when the client is disconnected, any rooms that were joined at the time of the disconnect are rejoined upon reconnect, as long as the app hasn't been restarted in between. - | Command-Line | Environment Variable | Description | | ------------- | ---------------------| ----------------------------------------| | `--rooms` | `ROOMS` | A list of chat rooms to join on startup | -- cgit v1.2.3 From 0da8e151297fd2ea123e0e59b7928171b2006d9e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 8 May 2024 22:00:54 -0500 Subject: add example file perm config --- config/slskd.example.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f4839e6d..f3871b5a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -35,6 +35,8 @@ # directories: # incomplete: ~ # downloads: ~ +# files: +# permissions: 655 # shares: # directories: # - ~ -- cgit v1.2.3 From 25245ca526b436b00b2150c02e0eb946df548e93 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 8 May 2024 22:44:52 -0500 Subject: stub options --- src/slskd/Core/Options.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 81dc09f6..3fef8a94 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -209,6 +209,12 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); + /// + /// Gets file options. + /// + [Validate] + public FilesOptions Files { get; init; } = new FilesOptions(); + /// /// Gets directory options. /// @@ -602,6 +608,33 @@ namespace slskd } } + /// + /// File options. + /// + public class FilesOptions : IValidatableObject + { + public string Permissions { get; init; } + public string Umask { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var regEx = new Regex("[0-7]{3}", RegexOptions.Compiled); + var results = new List(); + + if (!string.IsNullOrEmpty(Permissions) && !regEx.IsMatch(Permissions)) + { + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); + } + + if (!string.IsNullOrEmpty(Umask) && !regEx.IsMatch(Umask)) + { + results.Add(new ValidationResult($"Field {nameof(Umask)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); + } + + return results; + } + } + /// /// Directory options. /// -- cgit v1.2.3 From a30d5fb6d9fb3ce582f62b58af0d36dccb906869 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 May 2024 22:30:01 -0500 Subject: tweak example --- config/slskd.example.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f3871b5a..3d79f05d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,11 +32,11 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: # cidr: 0.0.0.0/0,::/0 +# files: +# permissions: 644 # directories: # incomplete: ~ # downloads: ~ -# files: -# permissions: 655 # shares: # directories: # - ~ -- cgit v1.2.3 From 6f652112800cc3de11c1ce0eaca3162b2179d02b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 May 2024 22:30:17 -0500 Subject: docs, remove umask --- src/slskd/Core/Options.cs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3fef8a94..81e73403 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -613,22 +613,30 @@ namespace slskd /// public class FilesOptions : IValidatableObject { - public string Permissions { get; init; } - public string Umask { get; init; } + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + [Argument(default, "file-permissions")] + [EnvironmentVariable("FILE_PERMISSIONS")] + [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] + public string Permissions { get; init; } = "644"; + /// + /// Extended validation. + /// + /// + /// public IEnumerable Validate(ValidationContext validationContext) { var regEx = new Regex("[0-7]{3}", RegexOptions.Compiled); var results = new List(); - if (!string.IsNullOrEmpty(Permissions) && !regEx.IsMatch(Permissions)) - { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); - } - - if (!string.IsNullOrEmpty(Umask) && !regEx.IsMatch(Umask)) + if (!regEx.IsMatch(Permissions)) { - results.Add(new ValidationResult($"Field {nameof(Umask)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (chmod syntax, 000-777, inclusive)")); } return results; -- cgit v1.2.3 From 28c2c7cbe76b215c605e1b510cee34270596cf27 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 13:19:36 -0500 Subject: stub creation logic --- src/slskd/Transfers/Downloads/DownloadService.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 57a78a1f..a8269b49 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -598,7 +598,18 @@ namespace slskd.Transfers.Downloads Directory.CreateDirectory(path); } - return new FileStream(localFilename, FileMode.Create); + var options = new FileStreamOptions + { + Mode = FileMode.Create, + Access = FileAccess.Write, + }; + + if (!OperatingSystem.IsWindows()) + { + options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; + } + + return new FileStream(localFilename, options); } private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) -- cgit v1.2.3 From 9a005447ef2f6726b2139b0ae4d99cf566ef365b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 15:57:05 -0500 Subject: simplify file service --- src/slskd/Files/API/FilesController.cs | 4 +- src/slskd/Files/FileService.cs | 9 ++- src/slskd/Files/IFileService.cs | 74 ------------------------ src/slskd/Program.cs | 2 +- tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 2 +- 5 files changed, 8 insertions(+), 83 deletions(-) delete mode 100644 src/slskd/Files/IFileService.cs diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index b99af658..1ced3e63 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -39,14 +39,14 @@ namespace slskd.Files.API public class FilesController : ControllerBase { public FilesController( - IFileService fileService, + FileService fileService, IOptionsSnapshot optionsSnapshot) { Files = fileService; OptionsSnapshot = optionsSnapshot; } - private IFileService Files { get; } + private FileService Files { get; } private IOptionsSnapshot OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c820220f..ee8271b1 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -23,7 +23,6 @@ namespace slskd.Files using System.Collections.Generic; using System.IO; using System.Linq; - using System.Security; using System.Threading.Tasks; using OneOf; using Serilog; @@ -31,7 +30,7 @@ namespace slskd.Files /// /// Manages files on disk. /// - public class FileService : IFileService + public class FileService { /// /// Initializes a new instance of the class. @@ -66,7 +65,7 @@ namespace slskd.Files /// /// Thrown if a specified directory does not exist. /// Thrown if a specified directory is restricted. - public async Task>> DeleteDirectoriesAsync(params string[] directories) + public virtual async Task>> DeleteDirectoriesAsync(params string[] directories) { if (directories.Any(directory => Path.GetFullPath(directory) != directory)) { @@ -129,7 +128,7 @@ namespace slskd.Files /// Thrown if any of the specified files have a relative path. /// Thrown if a specified file does not exist. /// Thrown if a specified file is restricted. - public async Task>> DeleteFilesAsync(params string[] files) + public virtual async Task>> DeleteFilesAsync(params string[] files) { if (files.Any(file => Path.GetFullPath(file) != file)) { @@ -182,7 +181,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public async Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { if (Path.GetFullPath(directory) != directory) { diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs deleted file mode 100644 index 89d4ce76..00000000 --- a/src/slskd/Files/IFileService.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// 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, either version 3 of the License, or -// (at your option) any later version. -// -// 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/. -// - -namespace slskd.Files -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Security; - using System.Threading.Tasks; - using OneOf; - - /// - /// Manages files on disk. - /// - public interface IFileService - { - /// - /// Deletes the specified . - /// - /// - /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are - /// contained in the result, and are not thrown. - /// - /// The directories to delete. - /// The operation context. - /// Thrown if any of the specified directories have a relative path. - /// - /// Thrown if any of the directories is an exact match for an application-controlled directory. - /// - /// Thrown if a specified directory does not exist. - /// Thrown if a specified directory is restricted. - Task>> DeleteDirectoriesAsync(params string[] directories); - - /// - /// Deletes the specified . - /// - /// - /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are - /// contained in the result, and are not thrown. - /// - /// The list of files to delete. - /// The operation context. - /// Thrown if any of the specified files have a relative path. - /// Thrown if a specified file does not exist. - /// Thrown if a specified file is restricted. - Task>> DeleteFilesAsync(params string[] files); - - /// - /// Lists the contents in the specified , optionally applying the specified . - /// - /// The directory from which to start the listing. - /// Optional enumeration options to apply. - /// The list of found contents. - /// Thrown if the specified directory has a relative path. - /// Thrown if the specified directory does not exist. - /// Thrown if the specified root directory is restricted. - Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null); - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 918ca828..545a80ab 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -590,7 +590,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.AddSingleton(); diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index 7c9931ab..917d1a43 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -29,7 +29,7 @@ namespace slskd.Tests.Unit.Files private Mock> OptionsSnapshotMock { get; init; } private string Temp { get; init; } - private IFileService FileService { get; init; } + private FileService FileService { get; init; } [Fact] public async Task ListContentsAsync_Throws_ArgumentException_Given_Relative_Path() -- cgit v1.2.3 From f54a5ec419bdbcddcaea760c984df7cc47005905 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:11:26 -0500 Subject: rough in create/move --- src/slskd/Files/FileService.cs | 120 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index ee8271b1..67488491 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -236,5 +236,125 @@ namespace slskd.Files } }); } + + /// + /// Creates a new file with the specified fully qualified and the optional , + /// returning a with which the contents of the file can be written. + /// + /// + /// Reasonable defaults, including the Unix permissions from app configuration, have been applied. Be sure to review the defaults + /// for each new use case and ensure they are appropriate. + /// + /// The fully qualified filename. + /// An optional patch for the underlying . + /// A Stream with which the contents of the file can be written. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the underlying file or Stream can't be created for some reason. + public virtual Stream CreateFile(string filename, CreateFileOptions options = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + var path = Path.GetDirectoryName(filename); + + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + var streamOptions = new FileStreamOptions + { + Access = options?.Access ?? FileAccess.Write, + BufferSize = options?.BufferSize ?? 4096, // framework default + Mode = options?.Mode ?? FileMode.Create, // overwrite + Options = options?.Options ?? FileOptions.None, // synchronous I/O + PreallocationSize = options?.PreallocationSize ?? 0, + Share = options?.Share ?? FileShare.None, // exclusive access + }; + + // attempting to use UnixCreateMode on Windows raises an Exception + // we *MUST* check the OS and skip this on Windows + if (!OperatingSystem.IsWindows()) + { + streamOptions.UnixCreateMode = options?.UnixCreateMode ?? UnixFileMode.None; // todo: substitute default from options + } + + try + { + return new FileStream(filename, streamOptions); + } + catch (Exception ex) + { + // the operation above can throw quite a few exceptions, all granular variations of + // IOException. to make handling downstream easier, wrap them all up and re-throw. + throw new IOException($"Failed to create file {Path.GetFileName(filename)}: {ex.Message}", ex); + } + } + + /// + /// Moves the specified fully qualified, localized, to the specified fully qualified, localized, + /// . + /// + /// + /// If the destination file already exists and the option is not set, the destination filename will + /// be modified to include the current time to avoid the collision while preserving both files. + /// + /// The fully qualified filename of the file to move. + /// The fully qualified directory to which to move the source file. + /// An optional value indicating whether the destination file should be overwritten if it already exists. + /// + /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. + /// + /// The fully qualified filename of the resulting file. + /// Thrown if either of the specified file or directories are null or contain only whitespace. + /// Thrown if the specified does not exist. + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = true) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); + ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); + + if (!File.Exists(sourceFilename)) + { + throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); + } + + if (!Directory.Exists(destinationDirectory)) + { + Directory.CreateDirectory(destinationDirectory); + } + + var filename = Path.GetFileName(sourceFilename); // without directory + var destinationFilename = Path.Combine(destinationDirectory, filename); + + if (!overwrite && File.Exists(destinationFilename)) + { + string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); + string extension = Path.GetExtension(filename); + + while (File.Exists(destinationFilename)) + { + string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; + destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); + } + } + + try + { + File.Move(sourceFilename, destinationFilename, overwrite: overwrite); + + // if the parent directory is empty after the move, delete it + if (deleteEmptiedParentDirectory && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + + return destinationFilename; + } + catch (Exception ex) + { + // the operation above can throw quite a few exceptions, all granular variations of + // IOException. to make handling downstream easier, wrap them all up and re-throw. + throw new IOException($"Failed to move file {Path.GetFileName(filename)}: {ex.Message}", ex); + } + } } } \ No newline at end of file -- cgit v1.2.3 From 3ddbba90fbbe67e2ca6f2d58a09c578efefa8f3d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:13:08 -0500 Subject: docs, default delete to false --- src/slskd/Files/FileService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 67488491..c3da7621 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -307,7 +307,8 @@ namespace slskd.Files /// The fully qualified filename of the resulting file. /// Thrown if either of the specified file or directories are null or contain only whitespace. /// Thrown if the specified does not exist. - public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = true) + /// Thrown if the file can't be moved, or the option is set and the operation fails. + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = false) { ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); -- cgit v1.2.3 From 7fe5b89ad8a211d0e1be1bd10a477ad9f7db51f2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:13:18 -0500 Subject: add CreateFileOptions --- src/slskd/Files/Types/CreateFileOptions.cs | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/slskd/Files/Types/CreateFileOptions.cs diff --git a/src/slskd/Files/Types/CreateFileOptions.cs b/src/slskd/Files/Types/CreateFileOptions.cs new file mode 100644 index 00000000..26d6e7d4 --- /dev/null +++ b/src/slskd/Files/Types/CreateFileOptions.cs @@ -0,0 +1,31 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd.Files; + +using System.IO; + +public record CreateFileOptions +{ + public FileAccess? Access { get; init; } + public int? BufferSize { get; init; } + public FileMode? Mode { get; init; } + public FileOptions? Options { get; init; } + public long? PreallocationSize { get; init; } + public FileShare? Share { get; init; } + public UnixFileMode? UnixCreateMode { get; init; } +} \ No newline at end of file -- cgit v1.2.3 From 2c8a0d34b4bc89a0f51cdd0e5667cc4fa8ee5424 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:15:13 -0500 Subject: temporarily comment old create/move --- src/slskd/Transfers/Downloads/DownloadService.cs | 116 +++++++++++------------ 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a8269b49..bf036e48 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -588,62 +588,62 @@ namespace slskd.Transfers.Downloads context.SaveChanges(); } - private static Stream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - var path = Path.GetDirectoryName(localFilename); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - var options = new FileStreamOptions - { - Mode = FileMode.Create, - Access = FileAccess.Write, - }; - - if (!OperatingSystem.IsWindows()) - { - options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; - } - - return new FileStream(localFilename, options); - } - - private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) - { - var sourceFilename = filename.ToLocalFilename(sourceDirectory); - var destinationFilename = filename.ToLocalFilename(destinationDirectory); - - var destinationPath = Path.GetDirectoryName(destinationFilename); - - if (!Directory.Exists(destinationPath)) - { - Directory.CreateDirectory(destinationPath); - } - - if (File.Exists(destinationFilename)) - { - string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); - string extension = Path.GetExtension(filename); - - while (File.Exists(destinationFilename)) - { - string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; - destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); - } - } - - File.Move(sourceFilename, destinationFilename, overwrite: true); - - if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) - { - Directory.Delete(Path.GetDirectoryName(sourceFilename)); - } - - return destinationFilename; - } + // private static Stream GetLocalFileStream(string remoteFilename, string saveDirectory) + // { + // var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); + // var path = Path.GetDirectoryName(localFilename); + + // if (!Directory.Exists(path)) + // { + // Directory.CreateDirectory(path); + // } + + // var options = new FileStreamOptions + // { + // Mode = FileMode.Create, + // Access = FileAccess.Write, + // }; + + // if (!OperatingSystem.IsWindows()) + // { + // options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; + // } + + // return new FileStream(localFilename, options); + // } + + // private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) + // { + // var sourceFilename = filename.ToLocalFilename(baseDirectory: sourceDirectory); + // var destinationFilename = filename.ToLocalFilename(baseDirectory: destinationDirectory); + + // var destinationPath = Path.GetDirectoryName(destinationFilename); + + // if (!Directory.Exists(destinationPath)) + // { + // Directory.CreateDirectory(destinationPath); + // } + + // if (File.Exists(destinationFilename)) + // { + // string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); + // string extension = Path.GetExtension(filename); + + // while (File.Exists(destinationFilename)) + // { + // string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; + // destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); + // } + // } + + // File.Move(sourceFilename, destinationFilename, overwrite: true); + + // if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + // { + // Directory.Delete(Path.GetDirectoryName(sourceFilename)); + // } + + // return destinationFilename; + // } } } \ No newline at end of file -- cgit v1.2.3 From e0874640202c2a978685bdc8c19e05ce049b081b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:15:40 -0500 Subject: inject FileService --- src/slskd/Transfers/Downloads/DownloadService.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf036e48..41fb45ee 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -120,12 +120,14 @@ namespace slskd.Transfers.Downloads IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory contextFactory, + FileService fileService, IRelayService relayService, IFTPService ftpClient) { Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; + Files = fileService; FTP = ftpClient; Relay = relayService; } @@ -134,6 +136,7 @@ namespace slskd.Transfers.Downloads private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private IFTPService FTP { get; } + private FileService Files { get; } private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } -- cgit v1.2.3 From 45907e3a8547bdfe59e6e829aec91af934c5367e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:16:09 -0500 Subject: use FileService --- src/slskd/Transfers/Downloads/DownloadService.cs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 41fb45ee..8ec7def2 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -23,13 +23,13 @@ namespace slskd.Transfers.Downloads using System; using System.Collections.Concurrent; using System.Collections.Generic; - using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; @@ -288,7 +288,16 @@ namespace slskd.Transfers.Downloads var completedTransfer = await Client.DownloadAsync( username: username, remoteFilename: file.Filename, - outputStreamFactory: () => Task.FromResult(GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete)), + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + 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 = System.IO.UnixFileMode.None, // todo: replace with options + })), size: file.Size, startOffset: 0, token: null, @@ -307,7 +316,11 @@ namespace slskd.Transfers.Downloads // this would be the ideal place to hook in a generic post-download task processor for now, we'll // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could // argue both ways for that being the correct behavior. revisit this later. - var finalFilename = MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); + var finalFilename = Files.MoveFile( + sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: OptionsMonitor.CurrentValue.Directories.Downloads, + overwrite: false, + deleteEmptiedParentDirectory: true); Log.Debug("Moved file to {Destination}", finalFilename); -- cgit v1.2.3 From e4c20ae1a67dc6d03db6f3a6f6e8eac1c612d3f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:27:45 -0500 Subject: make FileService singleton --- src/slskd/Files/FileService.cs | 10 +++++----- src/slskd/Program.cs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c3da7621..18bf72d1 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -36,19 +36,19 @@ namespace slskd.Files /// Initializes a new instance of the class. /// public FileService( - IOptionsSnapshot optionsSnapshot) + IOptionsMonitor optionsMonitor) { - OptionsSnapshot = optionsSnapshot; + OptionsMonitor = optionsMonitor; } private IEnumerable AllowedDirectories => new[] { - Path.GetFullPath(OptionsSnapshot.Value.Directories.Downloads), - Path.GetFullPath(OptionsSnapshot.Value.Directories.Incomplete), + Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), + Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), }; private ILogger Log { get; } = Serilog.Log.ForContext(); - private IOptionsSnapshot OptionsSnapshot { get; } + private IOptionsMonitor OptionsMonitor { get; } /// /// Deletes the specified . diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 545a80ab..27cbfc6f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -590,7 +590,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddTransient(); + services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From dbccaefb3c50ae67f671c91f88d088972d6a7f57 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 15:29:07 -0500 Subject: preserve remote directory --- src/slskd/Files/FileService.cs | 26 ++++++++++++++---------- src/slskd/Transfers/Downloads/DownloadService.cs | 6 +++--- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 18bf72d1..e5ce63f9 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -301,14 +301,14 @@ namespace slskd.Files /// The fully qualified filename of the file to move. /// The fully qualified directory to which to move the source file. /// An optional value indicating whether the destination file should be overwritten if it already exists. - /// + /// /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. /// /// The fully qualified filename of the resulting file. /// Thrown if either of the specified file or directories are null or contain only whitespace. /// Thrown if the specified does not exist. - /// Thrown if the file can't be moved, or the option is set and the operation fails. - public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = false) + /// Thrown if the file can't be moved, or the option is set and the operation fails. + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) { ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); @@ -323,18 +323,20 @@ namespace slskd.Files Directory.CreateDirectory(destinationDirectory); } - var filename = Path.GetFileName(sourceFilename); // without directory - var destinationFilename = Path.Combine(destinationDirectory, filename); + var destinationFilename = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilename)); + + Log.Debug("Attempting to move {Source} to {Destination}", sourceFilename, destinationFilename); if (!overwrite && File.Exists(destinationFilename)) { - string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); - string extension = Path.GetExtension(filename); + Log.Debug("Destination file {Destination} exists, and overwite option is not set; attempting to generate new filename", destinationFilename); + + string extensionlessFilename = Path.Combine(Path.GetDirectoryName(destinationFilename), Path.GetFileNameWithoutExtension(sourceFilename)); + string extension = Path.GetExtension(sourceFilename); while (File.Exists(destinationFilename)) { - string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; - destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); + destinationFilename = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; } } @@ -342,8 +344,10 @@ namespace slskd.Files { File.Move(sourceFilename, destinationFilename, overwrite: overwrite); + Log.Debug("Successfully moved {Source} to {Destination}", sourceFilename, destinationFilename); + // if the parent directory is empty after the move, delete it - if (deleteEmptiedParentDirectory && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) { Directory.Delete(Path.GetDirectoryName(sourceFilename)); } @@ -354,7 +358,7 @@ namespace slskd.Files { // the operation above can throw quite a few exceptions, all granular variations of // IOException. to make handling downstream easier, wrap them all up and re-throw. - throw new IOException($"Failed to move file {Path.GetFileName(filename)}: {ex.Message}", ex); + throw new IOException($"Failed to move file {Path.GetFileName(sourceFilename)}: {ex.Message}", ex); } } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8ec7def2..90d40b22 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -318,9 +318,9 @@ namespace slskd.Transfers.Downloads // argue both ways for that being the correct behavior. revisit this later. var finalFilename = Files.MoveFile( sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: OptionsMonitor.CurrentValue.Directories.Downloads, + destinationDirectory: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)), overwrite: false, - deleteEmptiedParentDirectory: true); + deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file to {Destination}", finalFilename); -- cgit v1.2.3 From 91133c53779c19590586139231537a2ef3df1da0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 15:29:20 -0500 Subject: remove deprecated code --- src/slskd/Transfers/Downloads/DownloadService.cs | 60 +----------------------- 1 file changed, 1 insertion(+), 59 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 90d40b22..8d06fcec 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -603,63 +603,5 @@ namespace slskd.Transfers.Downloads context.Update(transfer); context.SaveChanges(); } - - // private static Stream GetLocalFileStream(string remoteFilename, string saveDirectory) - // { - // var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - // var path = Path.GetDirectoryName(localFilename); - - // if (!Directory.Exists(path)) - // { - // Directory.CreateDirectory(path); - // } - - // var options = new FileStreamOptions - // { - // Mode = FileMode.Create, - // Access = FileAccess.Write, - // }; - - // if (!OperatingSystem.IsWindows()) - // { - // options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; - // } - - // return new FileStream(localFilename, options); - // } - - // private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) - // { - // var sourceFilename = filename.ToLocalFilename(baseDirectory: sourceDirectory); - // var destinationFilename = filename.ToLocalFilename(baseDirectory: destinationDirectory); - - // var destinationPath = Path.GetDirectoryName(destinationFilename); - - // if (!Directory.Exists(destinationPath)) - // { - // Directory.CreateDirectory(destinationPath); - // } - - // if (File.Exists(destinationFilename)) - // { - // string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); - // string extension = Path.GetExtension(filename); - - // while (File.Exists(destinationFilename)) - // { - // string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; - // destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); - // } - // } - - // File.Move(sourceFilename, destinationFilename, overwrite: true); - - // if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) - // { - // Directory.Delete(Path.GetDirectoryName(sourceFilename)); - // } - - // return destinationFilename; - // } } } \ No newline at end of file -- cgit v1.2.3 From 9db3b39cf1f606f80fb15872aa5a8a7e9ff0baad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 17:58:22 -0500 Subject: allow 4 character perms --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 81e73403..37b333ba 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -631,7 +631,7 @@ namespace slskd /// public IEnumerable Validate(ValidationContext validationContext) { - var regEx = new Regex("[0-7]{3}", RegexOptions.Compiled); + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); var results = new List(); if (!regEx.IsMatch(Permissions)) -- cgit v1.2.3 From cb17718d1e072bd41d014f22f4804ff48f82996e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:02:06 -0500 Subject: add extension ToUnixFileMode --- src/slskd/Files/FileExtensions.cs | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/slskd/Files/FileExtensions.cs diff --git a/src/slskd/Files/FileExtensions.cs b/src/slskd/Files/FileExtensions.cs new file mode 100644 index 00000000..4aa7a648 --- /dev/null +++ b/src/slskd/Files/FileExtensions.cs @@ -0,0 +1,62 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd.Files; + +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +/// +/// Extension methods related to . +/// +public static class FileExtensions +{ + /// + /// Converts the specified string into an instance of . + /// + /// A 3 or 4 character string consisting of only 0-7, matching a Unix file permission (e.g. one used with 'chmod'). + /// The converted UnixFileMode. + /// Thrown if the specified string is null or consists of only whitespace. + /// Thrown if the specified are not a 3 or 4 character string consisting of only 0-7. + public static UnixFileMode ToUnixFileMode(this string permissions) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(permissions, nameof(permissions)); + + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(permissions)) + { + throw new ArgumentOutOfRangeException($"The provided permissions are not a valid, expected 0-7 repeated 3 or 4 times (provided: {permissions})"); + } + + var opts = permissions + .Select(x => int.Parse(x.ToString())) + .Reverse() + .ToArray(); + + int mode = 0; + + for (var i = 0; i < opts.Length; i++) + { + mode |= opts[i] << (i * 3); + } + + return (UnixFileMode)mode; + } +} \ No newline at end of file -- cgit v1.2.3 From ce69e9b95349d71c05ff53eebcd92ad01ab431a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:02:36 -0500 Subject: add ToUnixFileMode tests --- .../slskd.Tests.Unit/Files/FileExtensionsTests.cs | 71 ++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs diff --git a/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs b/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs new file mode 100644 index 00000000..c270bb31 --- /dev/null +++ b/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using slskd.Files; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +public class FileExtensionsTests +{ + [Theory] + [InlineData("0000", UnixFileMode.None)] + [InlineData("0100", UnixFileMode.UserExecute)] + [InlineData("0200", UnixFileMode.UserWrite)] + [InlineData("0300", UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [InlineData("0400", UnixFileMode.UserRead)] + [InlineData("0500", UnixFileMode.UserRead | UnixFileMode.UserExecute)] + [InlineData("0600", UnixFileMode.UserRead | UnixFileMode.UserWrite)] + [InlineData("0700", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [InlineData("0010", UnixFileMode.GroupExecute)] + [InlineData("0020", UnixFileMode.GroupWrite)] + [InlineData("0030", UnixFileMode.GroupWrite | UnixFileMode.GroupExecute)] + [InlineData("0040", UnixFileMode.GroupRead)] + [InlineData("0050", UnixFileMode.GroupRead | UnixFileMode.GroupExecute)] + [InlineData("0060", UnixFileMode.GroupRead | UnixFileMode.GroupWrite)] + [InlineData("0070", UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute)] + [InlineData("0001", UnixFileMode.OtherExecute)] + [InlineData("0002", UnixFileMode.OtherWrite)] + [InlineData("0003", UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)] + [InlineData("0004", UnixFileMode.OtherRead)] + [InlineData("0005", UnixFileMode.OtherRead | UnixFileMode.OtherExecute)] + [InlineData("0006", UnixFileMode.OtherRead | UnixFileMode.OtherWrite)] + [InlineData("0007", UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)] + [InlineData("0644", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead)] + [InlineData("0777", UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite | UnixFileMode.GroupRead | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite | UnixFileMode.OtherRead)] + [InlineData("1000", UnixFileMode.StickyBit)] + [InlineData("2000", UnixFileMode.SetGroup)] + [InlineData("3000", UnixFileMode.SetGroup | UnixFileMode.StickyBit)] + [InlineData("4000", UnixFileMode.SetUser)] + [InlineData("5000", UnixFileMode.SetUser | UnixFileMode.StickyBit)] + [InlineData("6000", UnixFileMode.SetUser | UnixFileMode.SetGroup)] + [InlineData("7000", UnixFileMode.SetUser | UnixFileMode.SetGroup | UnixFileMode.StickyBit)] + [InlineData("7777", UnixFileMode.SetUser | UnixFileMode.SetGroup | UnixFileMode.StickyBit | UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite | UnixFileMode.GroupRead | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite | UnixFileMode.OtherRead)] + public void ToUnixFileMode_Works_As_Expected(string permissions, UnixFileMode expected) + { + var result = permissions.ToUnixFileMode(); + + Assert.Equal(expected, result); + } + + [Fact] + public void ToUinixFileMode_Throws_ArgumentException_Given_Empty() + { + var ex = Record.Exception(() => "".ToUnixFileMode()); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("0")] + [InlineData("00")] + [InlineData("00000")] + [InlineData("foo bar baz")] + public void ToUinixFileMode_Throws_ArgumentOutOfRangeException_Given_Bad_String(string str) + { + var ex = Record.Exception(() => str.ToUnixFileMode()); + + Assert.NotNull(ex); + Assert.IsType(ex); + } +} \ No newline at end of file -- cgit v1.2.3 From 4f17a9558688d172c2c01400cadeed855a536778 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:02:42 -0500 Subject: fix FileServiceTests --- tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index 917d1a43..6c3d1d73 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -13,13 +13,13 @@ namespace slskd.Tests.Unit.Files { public FileServiceTests() { - OptionsSnapshotMock = new Mock>(); + OptionsMonitorMock = new Mock>(); Temp = Path.Combine(Path.GetTempPath(), $"slskd.test.{Guid.NewGuid()}"); Directory.CreateDirectory(Temp); FileService = new FileService( - optionsSnapshot: OptionsSnapshotMock.Object); + optionsMonitor: OptionsMonitorMock.Object); } public void Dispose() @@ -27,7 +27,7 @@ namespace slskd.Tests.Unit.Files Directory.Delete(Temp, recursive: true); } - private Mock> OptionsSnapshotMock { get; init; } + private Mock> OptionsMonitorMock { get; init; } private string Temp { get; init; } private FileService FileService { get; init; } @@ -44,7 +44,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_UnauthorizedException_Given_Disallowed_Directory() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -62,7 +62,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_NotFoundException_Given_NonExistent_Directory() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -90,7 +90,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task DeleteDirectoriesAsync_Throws_ArgumentException_Given_Disallowed_Path() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -118,7 +118,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task DeleteFilesAsync_Throws_ArgumentException_Given_Disallowed_Path() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { -- cgit v1.2.3 From c00096d90e14d391272919c102eda702a0a2b35a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:09:42 -0500 Subject: use configured permissions when creating files --- src/slskd/Files/FileService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index e5ce63f9..af8f4111 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -275,7 +275,9 @@ namespace slskd.Files // we *MUST* check the OS and skip this on Windows if (!OperatingSystem.IsWindows()) { - streamOptions.UnixCreateMode = options?.UnixCreateMode ?? UnixFileMode.None; // todo: substitute default from options + streamOptions.UnixCreateMode = options?.UnixCreateMode + ?? OptionsMonitor.CurrentValue.Files.Permissions?.ToUnixFileMode() + ?? UnixFileMode.None; } try -- cgit v1.2.3 From ac66a8f6fbe9d49d4ed1f6cc8808ee75f92e62d0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 22:30:59 -0500 Subject: add log --- src/slskd/Files/FileService.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index af8f4111..91dadba6 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -278,6 +278,8 @@ namespace slskd.Files streamOptions.UnixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Files.Permissions?.ToUnixFileMode() ?? UnixFileMode.None; + + Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); } try -- cgit v1.2.3 From ad43047f4f57a26d0ab5225f22b2a78ab491a12c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 22:31:10 -0500 Subject: send correct perms --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8d06fcec..f848928f 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,7 +296,7 @@ namespace slskd.Transfers.Downloads 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 = System.IO.UnixFileMode.None, // todo: replace with options + UnixCreateMode = OptionsMonitor.CurrentValue.Files.Permissions.ToUnixFileMode(), })), size: file.Size, startOffset: 0, -- cgit v1.2.3 From d221780782481d931daa11b04e14229accceee6d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 May 2024 18:27:32 -0500 Subject: move config under Global --- config/slskd.example.yml | 4 +- src/slskd/Core/Options.cs | 82 ++++++++++++------------ src/slskd/Files/FileService.cs | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 4 files changed, 45 insertions(+), 45 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 3d79f05d..7dedebd6 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,8 +32,6 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: # cidr: 0.0.0.0/0,::/0 -# files: -# permissions: 644 # directories: # incomplete: ~ # downloads: ~ @@ -69,6 +67,8 @@ # download: # slots: 500 # speed_limit: 1000 +# file: +# permissions: 644 # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 37b333ba..e67be138 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -209,12 +209,6 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); - /// - /// Gets file options. - /// - [Validate] - public FilesOptions Files { get; init; } = new FilesOptions(); - /// /// Gets directory options. /// @@ -608,41 +602,6 @@ namespace slskd } } - /// - /// File options. - /// - public class FilesOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly created files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - [Argument(default, "file-permissions")] - [EnvironmentVariable("FILE_PERMISSIONS")] - [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] - public string Permissions { get; init; } = "644"; - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); - var results = new List(); - - if (!regEx.IsMatch(Permissions)) - { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (chmod syntax, 000-777, inclusive)")); - } - - return results; - } - } - /// /// Directory options. /// @@ -894,6 +853,47 @@ namespace slskd [Description("the total download speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; + + /// + /// Gets downloaded file options. + /// + [Validate] + public GlobalDownloadFileOptions File { get; init; } = new GlobalDownloadFileOptions(); + } + + /// + /// File options. + /// + public class GlobalDownloadFileOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly downloaded files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + [Argument(default, "downloaded-file-permissions")] + [EnvironmentVariable("DOWNLOADED_FILE_PERMISSIONS")] + [Description("the permissions to apply to newly downloaded files (chmod syntax, non-Windows only)")] + public string Permissions { get; init; } = "644"; + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + var results = new List(); + + if (!regEx.IsMatch(Permissions)) + { + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } + + return results; + } } } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 91dadba6..3bcdd04f 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -276,7 +276,7 @@ namespace slskd.Files if (!OperatingSystem.IsWindows()) { streamOptions.UnixCreateMode = options?.UnixCreateMode - ?? OptionsMonitor.CurrentValue.Files.Permissions?.ToUnixFileMode() + ?? OptionsMonitor.CurrentValue.Global.Download.File.Permissions?.ToUnixFileMode() ?? UnixFileMode.None; Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f848928f..e6410691 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,7 +296,7 @@ namespace slskd.Transfers.Downloads 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 = OptionsMonitor.CurrentValue.Files.Permissions.ToUnixFileMode(), + UnixCreateMode = OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode(), })), size: file.Size, startOffset: 0, -- cgit v1.2.3 From 2e278a5f0651ac70324557c12e0388fd1de3159d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 May 2024 18:53:04 -0500 Subject: add permissions to docs --- docs/config.md | 53 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 15 deletions(-) diff --git a/docs/config.md b/docs/config.md index f81fe8c0..9e08e8c4 100644 --- a/docs/config.md +++ b/docs/config.md @@ -272,11 +272,39 @@ relay: downloads: false ``` -# Limits and User Groups +# Upload/Download Configuration, Limits and User Groups -## Global Slot and Speed Limits +## Downloads -Global slot and speed behave as a hard limit, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. +A hard limit for download slots can be set to limit the number of concurrent downloads. Upon reaching the limit, additional downloads will be queued locally (and thus a remote queue position will not be obtained). There is no slot limit by default. + +A download speed limit can be set to limit the total amount of network bandwidth consumed by downloads. When configured, this bandwidth is split among all active downloads. There is no speed limit by default. + +A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. + +Unix file permissions can be configured and applied to newly downloaded files. The permission syntax is the same as the syntax used by the [chmod](https://en.wikipedia.org/wiki/Chmod) utility, accepting a numeric string of 3 or 4 numbers, each from 0 to 7. Unix file permissions are only applied when the application is running on a unix-like operating system (effectively, everything except Windows). The default permissions are 644, translating to read/write permissions for the owner (the user under which the application runs), read only for the owner's group, and read only for all other users. + +| Command-Line | Environment Variable | Description | +| ------------------------------- | ------------------------------------| ----------------------------------------------------------- | +| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | +| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | +| `--downloaded-file-permissions` | `SLSKD_DOWNLOADED_FILE_PERMISSIONS` | The Unix file permissions to be applied to downloaded files | + +#### **YAML** +```yaml +global: + download: + slots: 500 + speed_limit: 1000 # kibibytes + file: + permissions: 644 +``` + +## Uploads + +### Global Slot and Speed Limits + +Global upload slot and speed limits behave as hard limits, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. @@ -284,8 +312,6 @@ A change to slot limits requires an application restart to take effect, while sp | ------------------------ | ---------------------------- | ------------------------------------------------ | | `--upload-slots` | `SLSKD_UPLOAD_SLOTS` | The limit for the total number of upload slots | | `--upload-speed-limit` | `SLSKD_UPLOAD_SPEED_LIMIT` | The total upload speed limit, in kibibytes | -| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | -| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | #### **YAML** ```yaml @@ -293,12 +319,9 @@ global: upload: slots: 20 speed_limit: 1000 # kibibytes - download: - slots: 500 - speed_limit: 1000 ``` -## Global Upload Limits +### Global Upload Limits Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. @@ -327,7 +350,7 @@ global: failures: 1000 ``` -## Groups +### Groups User groups are used to control upload slots, speed limits, and queue behavior on a per-user basis. @@ -362,7 +385,7 @@ limits: failures: 1000 ``` -## Built-In Groups +### Built-In Groups The `default` built-in group contains all users who have not been explicitly added to a user-defined group, are not privileged, and haven't been identified as leechers. @@ -415,7 +438,7 @@ groups: failures: 30 ``` -## User Blacklist +### User Blacklist A fourth built-in group, `blacklisted`, is used to disallow other users from various activities. @@ -441,7 +464,7 @@ groups: - ``` -## User Defined Groups +### User Defined Groups In the group configuration, any number of user-defined groups can be added under the `user_defined` key. @@ -467,7 +490,7 @@ groups: - alice ``` -## Example +### Example In the following example: @@ -506,7 +529,7 @@ groups: - bob ``` -## Managed Blacklist +# Managed Blacklist A managed blacklist (also called a blocklist) can be specified to disallow interaction with known undesireable actors. Users whose IP address metches an entry on this list are functionally the same as users added to the [User Blacklist](#user-blacklist) described above and are disallowed any interactions with shares or files. -- cgit v1.2.3 From 57b0a10b294d89659fba11ba616b1afdefd82d5e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 May 2024 14:07:41 -0500 Subject: add SLSKD_UMASK --- Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 9ffcc2a1..07278892 100644 --- a/Dockerfile +++ b/Dockerfile @@ -63,6 +63,7 @@ ENV DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \ DOTNET_gcConcurrent=1 \ DOTNET_GCHeapHardLimit=1F400000 \ DOTNET_GCConserveMemory=9 \ + SLSKD_UMASK=0022 \ SLSKD_HTTP_PORT=5030 \ SLSKD_HTTPS_PORT=5031 \ SLSKD_SLSK_LISTEN_PORT=50300 \ @@ -87,4 +88,7 @@ LABEL org.opencontainers.image.title=slskd \ WORKDIR /slskd COPY --from=publish /slskd/dist/${TARGETPLATFORM} . -ENTRYPOINT ["/usr/bin/tini", "--", "./slskd"] +RUN echo "umask \$SLSKD_UMASK && ./slskd" > start.sh \ + && chmod +x start.sh + +ENTRYPOINT ["/usr/bin/tini", "--", "./start.sh"] -- cgit v1.2.3 From 65337c147088318961e58c549a90ab79dfa51b44 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 May 2024 14:18:50 -0500 Subject: default file permissions to nothing (use umask) --- src/slskd/Core/Options.cs | 12 ++++++++---- src/slskd/Files/FileService.cs | 12 ++++++++---- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +++- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e67be138..e7462848 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -875,7 +875,7 @@ namespace slskd [Argument(default, "downloaded-file-permissions")] [EnvironmentVariable("DOWNLOADED_FILE_PERMISSIONS")] [Description("the permissions to apply to newly downloaded files (chmod syntax, non-Windows only)")] - public string Permissions { get; init; } = "644"; + public string Permissions { get; init; } /// /// Extended validation. @@ -884,12 +884,16 @@ namespace slskd /// public IEnumerable Validate(ValidationContext validationContext) { - var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); var results = new List(); - if (!regEx.IsMatch(Permissions)) + if (!string.IsNullOrEmpty(Permissions)) { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(Permissions)) + { + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } } return results; diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 3bcdd04f..d9aa9dc3 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -275,11 +275,15 @@ namespace slskd.Files // we *MUST* check the OS and skip this on Windows if (!OperatingSystem.IsWindows()) { - streamOptions.UnixCreateMode = options?.UnixCreateMode - ?? OptionsMonitor.CurrentValue.Global.Download.File.Permissions?.ToUnixFileMode() - ?? UnixFileMode.None; + var appOption = OptionsMonitor.CurrentValue.Global.Download.File.Permissions; - Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); + // if options haven't been passed in and none have been set in app config, omit this + // so that the application's umask will be applied, saving users the hassle of setting it twice. + if (options?.UnixCreateMode != null || !string.IsNullOrWhiteSpace(appOption)) + { + streamOptions.UnixCreateMode = options?.UnixCreateMode ?? appOption?.ToUnixFileMode(); + Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); + } } try diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e6410691..bdd7ebed 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,7 +296,9 @@ namespace slskd.Transfers.Downloads 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 = OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode(), + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Global.Download.File.Permissions) + ? OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode() + : null, })), size: file.Size, startOffset: 0, -- cgit v1.2.3 From 79cd6c0033631b33e9508b7c10e48b9edfafe21d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 May 2024 21:40:47 -0500 Subject: move options once again --- src/slskd/Core/Options.cs | 102 +++++++++++++---------- src/slskd/Files/FileService.cs | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +- 3 files changed, 60 insertions(+), 48 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e7462848..f2419c83 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -209,6 +209,12 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); + /// + /// Gets permission options. + /// + [Validate] + public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + /// /// Gets directory options. /// @@ -602,6 +608,57 @@ namespace slskd } } + /// + /// Permission options. + /// + public class PermissionsOptions + { + /// + /// Gets file permission options. + /// + [Validate] + public FileOptions File { get; init; } = new FileOptions(); + + /// + /// File permission options. + /// + public class FileOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + [Argument(default, "file-permission-mode")] + [EnvironmentVariable("FILE_PERMISSION_MODE")] + [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] + public string Mode { get; init; } + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (!string.IsNullOrEmpty(Mode)) + { + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(Mode)) + { + results.Add(new ValidationResult($"Field {nameof(Mode)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } + } + + return results; + } + } + } + /// /// Directory options. /// @@ -853,51 +910,6 @@ namespace slskd [Description("the total download speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; - - /// - /// Gets downloaded file options. - /// - [Validate] - public GlobalDownloadFileOptions File { get; init; } = new GlobalDownloadFileOptions(); - } - - /// - /// File options. - /// - public class GlobalDownloadFileOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly downloaded files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - [Argument(default, "downloaded-file-permissions")] - [EnvironmentVariable("DOWNLOADED_FILE_PERMISSIONS")] - [Description("the permissions to apply to newly downloaded files (chmod syntax, non-Windows only)")] - public string Permissions { get; init; } - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (!string.IsNullOrEmpty(Permissions)) - { - var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); - - if (!regEx.IsMatch(Permissions)) - { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); - } - } - - return results; - } } } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index d9aa9dc3..0d193d73 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -275,7 +275,7 @@ namespace slskd.Files // we *MUST* check the OS and skip this on Windows if (!OperatingSystem.IsWindows()) { - var appOption = OptionsMonitor.CurrentValue.Global.Download.File.Permissions; + var appOption = OptionsMonitor.CurrentValue.Permissions.File.Mode; // if options haven't been passed in and none have been set in app config, omit this // so that the application's umask will be applied, saving users the hassle of setting it twice. diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bdd7ebed..32903bf9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,8 +296,8 @@ namespace slskd.Transfers.Downloads 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 = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Global.Download.File.Permissions) - ? OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode() + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null, })), size: file.Size, -- cgit v1.2.3 From 4f50d184c8923d975e5930a66a6385683823ef77 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 May 2024 20:32:46 -0500 Subject: update example --- config/slskd.example.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7dedebd6..f1e1b4ab 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,6 +32,9 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: # cidr: 0.0.0.0/0,::/0 +# permissions: +# file: +# mode: ~ # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask # directories: # incomplete: ~ # downloads: ~ @@ -67,8 +70,6 @@ # download: # slots: 500 # speed_limit: 1000 -# file: -# permissions: 644 # groups: # default: # upload: -- cgit v1.2.3 From 29faa7d07a11862fd4fb51a84df98c9a53d70625 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 May 2024 20:38:18 -0500 Subject: revert docs --- docs/config.md | 55 ++++++++++++++++--------------------------------------- 1 file changed, 16 insertions(+), 39 deletions(-) diff --git a/docs/config.md b/docs/config.md index 9e08e8c4..bed6d2d6 100644 --- a/docs/config.md +++ b/docs/config.md @@ -272,39 +272,11 @@ relay: downloads: false ``` -# Upload/Download Configuration, Limits and User Groups +# Limits and User Groups -## Downloads +## Global Slot and Speed Limits -A hard limit for download slots can be set to limit the number of concurrent downloads. Upon reaching the limit, additional downloads will be queued locally (and thus a remote queue position will not be obtained). There is no slot limit by default. - -A download speed limit can be set to limit the total amount of network bandwidth consumed by downloads. When configured, this bandwidth is split among all active downloads. There is no speed limit by default. - -A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. - -Unix file permissions can be configured and applied to newly downloaded files. The permission syntax is the same as the syntax used by the [chmod](https://en.wikipedia.org/wiki/Chmod) utility, accepting a numeric string of 3 or 4 numbers, each from 0 to 7. Unix file permissions are only applied when the application is running on a unix-like operating system (effectively, everything except Windows). The default permissions are 644, translating to read/write permissions for the owner (the user under which the application runs), read only for the owner's group, and read only for all other users. - -| Command-Line | Environment Variable | Description | -| ------------------------------- | ------------------------------------| ----------------------------------------------------------- | -| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | -| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | -| `--downloaded-file-permissions` | `SLSKD_DOWNLOADED_FILE_PERMISSIONS` | The Unix file permissions to be applied to downloaded files | - -#### **YAML** -```yaml -global: - download: - slots: 500 - speed_limit: 1000 # kibibytes - file: - permissions: 644 -``` - -## Uploads - -### Global Slot and Speed Limits - -Global upload slot and speed limits behave as hard limits, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. +Global slot and speed behave as a hard limit, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. @@ -312,6 +284,8 @@ A change to slot limits requires an application restart to take effect, while sp | ------------------------ | ---------------------------- | ------------------------------------------------ | | `--upload-slots` | `SLSKD_UPLOAD_SLOTS` | The limit for the total number of upload slots | | `--upload-speed-limit` | `SLSKD_UPLOAD_SPEED_LIMIT` | The total upload speed limit, in kibibytes | +| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | +| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | #### **YAML** ```yaml @@ -319,9 +293,12 @@ global: upload: slots: 20 speed_limit: 1000 # kibibytes + download: + slots: 500 + speed_limit: 1000 ``` -### Global Upload Limits +## Global Upload Limits Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. @@ -350,7 +327,7 @@ global: failures: 1000 ``` -### Groups +## Groups User groups are used to control upload slots, speed limits, and queue behavior on a per-user basis. @@ -385,7 +362,7 @@ limits: failures: 1000 ``` -### Built-In Groups +## Built-In Groups The `default` built-in group contains all users who have not been explicitly added to a user-defined group, are not privileged, and haven't been identified as leechers. @@ -438,7 +415,7 @@ groups: failures: 30 ``` -### User Blacklist +## User Blacklist A fourth built-in group, `blacklisted`, is used to disallow other users from various activities. @@ -464,7 +441,7 @@ groups: - ``` -### User Defined Groups +## User Defined Groups In the group configuration, any number of user-defined groups can be added under the `user_defined` key. @@ -490,7 +467,7 @@ groups: - alice ``` -### Example +## Example In the following example: @@ -529,7 +506,7 @@ groups: - bob ``` -# Managed Blacklist +## Managed Blacklist A managed blacklist (also called a blocklist) can be specified to disallow interaction with known undesireable actors. Users whose IP address metches an entry on this list are functionally the same as users added to the [User Blacklist](#user-blacklist) described above and are disallowed any interactions with shares or files. @@ -1113,4 +1090,4 @@ The application can be run in "command mode", causing it to execute a command an | `-h\|--help` | Display available command-line arguments | | `-e\|--envars` | Display available environment variables | | `-g\|--generate-cert` | Generate an X509 certificate and password for HTTPS | -| `-k\|--generate-secret ` | Generate a random secret of the specified length | +| `-k\|--generate-secret ` | Generate a random secret of the specified length | \ No newline at end of file -- cgit v1.2.3 From f7fefd065aec5ba3a9b4e679e36a5997924ec591 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 May 2024 22:49:41 -0500 Subject: docs --- docs/config.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index bed6d2d6..5c4eb2bb 100644 --- a/docs/config.md +++ b/docs/config.md @@ -73,6 +73,30 @@ If an attacker were to gain access to the application and retrieve the YAML file remote_configuration: false ``` +# Permissions + +On [Unix-like](https://en.wikipedia.org/wiki/Unix-like) operating systems, slskd creates downloaded files with permissions dictated by the [umask](https://en.wikipedia.org/wiki/Umask) of the process, usually 022, which translates to a file mode of 644; read/write for the owner and read for the group and all others. + +Users wishing to create files with different permissions can change the umask value before launching the application (e.g. `umask 000 & ./slskd`), and the file mode will be changed accordingly. + +When running within a docker container the environment variable `SLSKD_UMASK` can be used to change the umask for the process within the container, and this will in turn change the resulting file mode on a mounted volume. + +Users can optionally configure alternative permissions for files by setting the file permission mode option. It's not possible to supersede the configured umask value; setting a mode of 777, for example, will have no effect with a umask of 022. + +These options have no effect on Windows. + +| Command-Line | Environment Variable | Description | +| ------------------------ | -----------------------------| -------------------------------------------------------------------------------- | +| n/a | `SLSKD_UMASK` | When running within the slskd Docker container, the umask for the process | +| `--file-permission-mode` | `SLSKD_FILE_PERMISSION_MODE` | The permissions to apply to newly created files (chmod syntax, non-Windows only) | + +#### **YAML** +```yaml +permissions: + file: + mode: 644 # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask +``` + # Application Directory Configuration The application directory configuration option determines the location of the YAML file, the default locations of the download and incomplete directories, and the location of application working data, such as logs and SQLite databases. @@ -1090,4 +1114,4 @@ The application can be run in "command mode", causing it to execute a command an | `-h\|--help` | Display available command-line arguments | | `-e\|--envars` | Display available environment variables | | `-g\|--generate-cert` | Generate an X509 certificate and password for HTTPS | -| `-k\|--generate-secret ` | Generate a random secret of the specified length | \ No newline at end of file +| `-k\|--generate-secret ` | Generate a random secret of the specified length | -- cgit v1.2.3 From e153974f378b0d81b84c834d6c8006ddd83eda76 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 May 2024 17:33:46 -0500 Subject: add flag for legacy windows keepalive --- config/slskd.example.yml | 1 + src/slskd/Core/Options.cs | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f1e1b4ab..2552e081 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -14,6 +14,7 @@ # experimental: false # volatile: false # case_sensitive_reg_ex: false +# legacy_windows_tcp_keepalive: false # relay: # enabled: false # mode: controller # controller (default), agent, or debug (for local development) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f2419c83..1b049ae1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -425,6 +425,15 @@ namespace slskd [Description("user-defined regular expressions are case sensitive")] [RequiresRestart] public bool CaseSensitiveRegEx { get; init; } = false; + + /// + /// Gets a value indicating whether to use legacy TCP keepalive options, for Windows + /// versions prior to Windows 10, version 1709 (and associated Server SKUs). + /// + [Argument(default, "legacy-windows-tcp-keepalive")] + [EnvironmentVariable("LEGACY_WINDOWS_TCP_KEEPALIVE")] + [Description("use a legacy TCP keepalive strategy for older Windows versions")] + public bool LegacyWindowsTcpKeepalive { get; init; } = false; } /// -- cgit v1.2.3 From 8ed18de869eb0da04ce07d29665e654991410ce6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 May 2024 17:37:56 -0500 Subject: refactor keepalive config --- src/slskd/Application.cs | 56 +++++++++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 7f703eaa..3269f6f3 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -348,16 +348,9 @@ namespace slskd inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, proxyOptions: proxyOptions); - var configureKeepAlive = new Action(socket => - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity / 1000); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity / 1000); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3); - }); - - var serverOptions = connectionOptions.With(configureSocketAction: configureKeepAlive); - var distributedOptions = connectionOptions.With(configureSocketAction: configureKeepAlive); + // os-specific keepalive is configured for long-lived connections for the server and distributed parent/children + var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection)); + var distributedOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection)); var transferOptions = connectionOptions.With( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, @@ -477,6 +470,37 @@ namespace slskd return Task.CompletedTask; } + private void ConfigureSocketKeepAlive(Socket socket, Options.SoulseekOptions.ConnectionOptions options) + { + /* + os-specific keepalive is configured for long-lived connections for the server and distributed parent/children + there may be legitimate reasons for these connections to go idle, and for that reason we can't use an inactivity watchdog + to determine when they are dead. + + the intent, assuming the inactivity option is set to 15 seconds, is to send a keepalive probe after 15 seconds of inactivity, + and then again every 15 seconds until a total of 3 unanswered probes are sent, after which the socket will disconnect. + */ + try + { + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3); // TCP_KEEPCNT + + if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) + { + return; + } + + // the following will throw an exception on operating systems prior to Windows 10, version 1709 (and whatever Server SKU that corresponds to) + // see: https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, options.Timeout.Inactivity / 1000); // TCP_KEEPIDLE + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, options.Timeout.Inactivity / 1000); // TCP_KEEPINTVL + } + catch (SocketException ex) + { + Log.Warning("Failed to configure connection keepalive settings: \"{Message}\". Performance is degraded. Set the configuration flag \"Legacy Windows TCP Keepalive\" to avoid this.", ex.Message); + } + } + // todo: consider moving this somewhere else; it's pretty long and complicated private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { @@ -1290,16 +1314,8 @@ namespace slskd inactivityTimeout: connection.Timeout.Inactivity, proxyOptions: proxyPatch); - var configureKeepAlive = new Action(socket => - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, connection.Timeout.Inactivity / 1000); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, connection.Timeout.Inactivity / 1000); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3); - }); - - serverPatch = connectionPatch.With(configureSocketAction: configureKeepAlive); - distributedPatch = connectionPatch.With(configureSocketAction: configureKeepAlive); + serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection)); + distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection)); transferPatch = connectionPatch.With( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, -- cgit v1.2.3 From 1748a75cfd10008ebf46144c61d8f884625c6726 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 May 2024 18:19:01 -0500 Subject: docs for keepalive --- docs/config.md | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/docs/config.md b/docs/config.md index 5c4eb2bb..87fb916b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1072,20 +1072,21 @@ feature: Several additional feature flags are provided to change the application's runtime behavior, which is helpful during development. Available feature flags are: -| Flag | Environment Variable | Description | -| ------------------------ | ---------------------------- | ---------------------------------------------------------------- | -| `-d\|--debug` | `SLSKD_DEBUG` | Run the application in debug mode. Produces verbose log output. | -| `--experimental` | `SLSKD_EXPERIMENTAL` | Run the application in experimental mode. YMMV. | -| `-n\|--no-logo` | `SLSKD_NO_LOGO` | Don't show the application logo on startup | -| `-x\|--no-start` | `SLSKD_NO_START` | Bootstrap the application, but don't start | -| `--no-config-watch` | `SLSKD_NO_CONFIG_WATCH` | Don't watch the configuration file for changes | -| `--no-connect` | `SLSKD_NO_CONNECT` | Start the application, but don't connect to the server | -| `--no-share-scan` | `SLSKD_NO_SHARE_SCAN` | Don't perform a scan of shared directories on startup | -| `--force-share-scan` | `SLSKD_FORCE_SHARE_SCAN` | Force a scan of shared directories on startup | -| `--no-version-check` | `SLSKD_NO_VERSION_CHECK` | Don't perform a version check on startup | -| `--log-sql` | `SLSKD_LOG_SQL` | Log SQL queries generated by Entity Framework | -| `--volatile` | `SLSKD_VOLATILE` | Use volatile data storage (all data will be lost at shutdown) | -| `--case-sensitive-regex` | `SLSKD_CASE_SENSITIVE_REGEX` | User-defined regular expressions are case sensitive | +| Flag | Environment Variable | Description | +| -------------------------------- | ------------------------------------ | ---------------------------------------------------------------- | +| `-d\|--debug` | `SLSKD_DEBUG` | Run the application in debug mode. Produces verbose log output. | +| `--experimental` | `SLSKD_EXPERIMENTAL` | Run the application in experimental mode. YMMV. | +| `-n\|--no-logo` | `SLSKD_NO_LOGO` | Don't show the application logo on startup | +| `-x\|--no-start` | `SLSKD_NO_START` | Bootstrap the application, but don't start | +| `--no-config-watch` | `SLSKD_NO_CONFIG_WATCH` | Don't watch the configuration file for changes | +| `--no-connect` | `SLSKD_NO_CONNECT` | Start the application, but don't connect to the server | +| `--no-share-scan` | `SLSKD_NO_SHARE_SCAN` | Don't perform a scan of shared directories on startup | +| `--force-share-scan` | `SLSKD_FORCE_SHARE_SCAN` | Force a scan of shared directories on startup | +| `--no-version-check` | `SLSKD_NO_VERSION_CHECK` | Don't perform a version check on startup | +| `--log-sql` | `SLSKD_LOG_SQL` | Log SQL queries generated by Entity Framework | +| `--volatile` | `SLSKD_VOLATILE` | Use volatile data storage (all data will be lost at shutdown) | +| `--case-sensitive-regex` | `SLSKD_CASE_SENSITIVE_REGEX` | User-defined regular expressions are case sensitive | +| `--legacy-windows-tcp-keepalive` | `SLSKD_LEGACY_WINDOWS_TCP_KEEPALIVE` | Use a legacy TCP keepalive strategy for older Windows versions | #### **YAML** ```yaml @@ -1102,6 +1103,7 @@ flags: experimental: false volatile: false case_sensitive_reg_ex: false + legacy_windows_tcp_keepalive: false ``` # Commands -- cgit v1.2.3 From befac9735c93e4b5efb13472c8fdd96e4f234524 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 May 2024 18:26:50 -0500 Subject: i guess TCP_KEEPCNT is broke too --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 3269f6f3..0ad8c800 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -483,7 +483,6 @@ namespace slskd try { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3); // TCP_KEEPCNT if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) { @@ -492,6 +491,7 @@ namespace slskd // the following will throw an exception on operating systems prior to Windows 10, version 1709 (and whatever Server SKU that corresponds to) // see: https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3); // TCP_KEEPCNT socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, options.Timeout.Inactivity / 1000); // TCP_KEEPIDLE socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, options.Timeout.Inactivity / 1000); // TCP_KEEPINTVL } -- cgit v1.2.3 From 400cf795c01184ed28471a0b0e91bda07be8411c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 May 2024 19:05:51 -0500 Subject: add ability to use ConnectionWatchdog to make initial connection --- src/slskd/Core/ConnectionWatchdog.cs | 49 +++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 19e2d47c..4ffc58e0 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -36,11 +36,17 @@ namespace slskd bool IsEnabled { get; } /// - /// Starts monitoring the server connection. + /// Initializes the watchdog and makes the initial connection to the server. /// - /// This should be called when the connection is disconnected. + /// This should be called at application startup. void Start(); + /// + /// Starts monitoring the server connection following a disconnect. + /// + /// This should be called when the connection is disconnected. + void Restart(); + /// /// Stops monitoring the server connection. /// @@ -102,14 +108,24 @@ namespace slskd GC.SuppressFinalize(this); } + /// + /// Initializes the watchdog and makes the initial connection to the server. + /// + /// This should be called at application startup. + public void Start() + { + WatchdogTimer.Enabled = true; + _ = AttemptReconnect(attempts: 0); + } + /// /// Starts monitoring the server connection. /// /// This should be called when the connection is disconnected. - public void Start() + public void Restart() { WatchdogTimer.Enabled = true; - _ = AttemptReconnect(); + _ = AttemptReconnect(attempts: 1); } /// @@ -135,7 +151,7 @@ namespace slskd } } - private async Task AttemptReconnect() + private async Task AttemptReconnect(int attempts = 1) { if (await SyncRoot.WaitAsync(0)) { @@ -146,19 +162,24 @@ namespace slskd return; } - var attempts = 1; - while (true) { - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: attempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + if (attempts > 0) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); - Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); - await Task.Delay(delay + jitter); + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before attempting to reconnect"); + await Task.Delay(delay + jitter); - Log.Information("Attempting to reconnect (#{Attempts})...", attempts); + Log.Information("Attempting to reconnect to the Soulseek server (#{Attempts})...", attempts); + } + else + { + Log.Information("Attempting to connect to the Soulseek server..."); + } try { -- cgit v1.2.3 From 3901f5df412d53f273a4939b69838468d5f1989b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 May 2024 19:06:30 -0500 Subject: use ConnectionWatchdog to make initial connection --- src/slskd/Application.cs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 0ad8c800..f92b4647 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -446,13 +446,7 @@ namespace slskd } else { - var opt = OptionsAtStartup.Soulseek; - - await Client.ConnectAsync( - address: opt.Address, - port: opt.Port, - username: opt.Username, - password: opt.Password).ConfigureAwait(false); + ConnectionWatchdog.Start(); } } } @@ -825,7 +819,7 @@ namespace slskd else { Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - ConnectionWatchdog.Start(); + ConnectionWatchdog.Restart(); } } -- cgit v1.2.3