aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2024-03-18 23:03:50 -0500
committerJP Dillingham <jp@dillingham.me>2024-03-18 23:03:50 -0500
commita841cda6cae75e216259e32231c500a6397238d6 (patch)
treeab45153aaaab98ec100a2268291e82f6044c5592 /src
parent522974041e4c07050d8cb13b8ca3e65f8dd8060a (diff)
downloadslskd-a841cda6cae75e216259e32231c500a6397238d6.tar.gz
implement blacklist
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Core/Blacklist.cs211
1 files 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;
+
+/// <summary>
+/// Blacklist file formats.
+/// </summary>
+public enum BlacklistFormat
+{
+ /// <summary>
+ /// Automatically detect format based on contents.
+ /// </summary>
+ AutoDetect,
+
+ /// <summary>
+ /// CIDR format. <see href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing"/>.
+ /// </summary>
+ /// <example>
+ /// <code>
+ /// 1.2.4.0/24
+ /// 1.2.8.0/24
+ /// 1.9.96.105/32
+ /// </code>
+ /// </example>
+ CIDR,
+
+ /// <summary>
+ /// P2P format. <see href="https://sourceforge.net/p/peerguardian/wiki/dev-blocklist-format-p2p/"/>.
+ /// </summary>
+ /// <example>
+ /// <code>
+ /// 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
+ /// </code>
+ /// </example>
+ P2P,
+
+ /// <summary>
+ /// DAT format. <see href="https://sourceforge.net/p/peerguardian/wiki/dev-blocklist-format-dat/"/>.
+ /// </summary>
+ /// <example>
+ /// <code>
+ /// 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
+ /// </code>
+ /// </example>
+ DAT,
+}
/// <summary>
/// A managed blacklist for CIDRs.
/// </summary>
public class Blacklist
{
- private Dictionary<int, (uint First, uint Last)[]> Cache { get; }
+ private ILogger Log { get; set; } = Serilog.Log.ForContext<Blacklist>();
+ private ConcurrentDictionary<int, (uint First, uint Last)[]> Cache { get; } = new();
- public void Load(string filename)
+ /// <summary>
+ /// Loads the contents of the specified <paramref name="filename"/> into the Blacklist.
+ /// </summary>
+ /// <remarks>
+ /// The existing Blacklist contents are replaced atomically.
+ /// </remarks>
+ /// <param name="filename">The fully qualified path to the file to load.</param>
+ /// <param name="format">The optional blacklist file format.</param>
+ /// <returns>The operation context.</returns>
+ /// <exception cref="FormatException">
+ /// Thrown if any of the lines in the file do not match the specified or auto-detected <paramref name="format"/>.
+ /// </exception>
+ /// <exception cref="FormatException">
+ /// Thrown if the specified <paramref name="format"/> is <see cref="BlacklistFormat.AutoDetect"/> and the format could not be detected.
+ /// </exception>
+ public virtual async Task Load(string filename, BlacklistFormat format = BlacklistFormat.AutoDetect)
{
- // todo:
- // _stream_ contents of file into a ConcurrentDictionary<int, List<>>
- // 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<int, List<(uint First, uint Last)>>();
+ 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)
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="ip"/> is contained witin the blacklist.
+ /// </summary>
+ /// <param name="ip">The IP address to check.</param>
+ /// <returns>A value indicating whether the specified IP is contained within the blacklist.</returns>
+ 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<BlacklistFormat> 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();