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(-) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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 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 (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(+) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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 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(+) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(+) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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