diff options
| author | Artur <5359825+sethidden@users.noreply.github.com> | 2024-05-30 09:27:41 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-30 09:27:41 +0000 |
| commit | a783e181982dd8c435bb51345a8528a65a4304ac (patch) | |
| tree | 236c9b7bc40ca09cf3f40878a9beb1dea292a20d /src/slskd/Core | |
| parent | 02bf77158d3bf3dcb6919a9bd0637bf040644c26 (diff) | |
| parent | b33449b0282d7f466be22570c26e9e3c982b888a (diff) | |
| download | slskd-a783e181982dd8c435bb51345a8528a65a4304ac.tar.gz | |
Merge branch 'slskd:master' into master
Diffstat (limited to 'src/slskd/Core')
| -rw-r--r-- | src/slskd/Core/Blacklist.cs | 341 | ||||
| -rw-r--r-- | src/slskd/Core/ConnectionWatchdog.cs | 49 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 132 |
3 files changed, 506 insertions, 16 deletions
diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs new file mode 100644 index 00000000..76f0b37f --- /dev/null +++ b/src/slskd/Core/Blacklist.cs @@ -0,0 +1,341 @@ +// <copyright file="Blacklist.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +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 +{ + /// <summary> + /// Gets the total number of loaded CIDRs. + /// </summary> + public long Count => Cache.Sum(kvp => kvp.Value.Length); + + private ILogger Log { get; set; } = Serilog.Log.ForContext<Blacklist>(); + private ConcurrentDictionary<int, (uint First, uint Last)[]> Cache { get; set; } = new(); + + /// <summary> + /// Examines the contents of the specified <paramref name="filename"/> and attempts to determine the format. + /// </summary> + /// <param name="filename">The fully qualified path to the file to examine.</param> + /// <returns>The detected format.</returns> + /// <exception cref="IOException">Thrown if the specified filename can't be accessed.</exception> + /// <exception cref="FormatException">Thrown if the format can't be determined.</exception> + public static async Task<BlacklistFormat> 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 detect blacklist format. Only CIDR, P2P and DAT formats are supported"); + } + + /// <summary> + /// Clears the contents of the Blacklist. + /// </summary> + public virtual void Clear() => Cache.Clear(); + + /// <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="IOException">Thrown if the specified filename can't be accessed.</exception> + /// <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) + { + if (format == BlacklistFormat.AutoDetect) + { + Log.Debug("Attempting to auto-detect blacklist fomat from contents..."); + format = await DetectFormat(filename); // FormatException if unsuccessful + 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, + Mode = FileMode.Open, + Share = FileShare.Read, + BufferSize = 262144, // 256kib, assumes most blacklists will be > 1mb + }); + + 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 + */ + + try + { + // CIDR format: 1.2.4.0/24 + if (format == BlacklistFormat.CIDR) + { + cidr = IPAddressRange.Parse(line); + } + + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + else if (format == BlacklistFormat.P2P) + { + cidr = IPAddressRange.Parse(line.Split(':').Last()); + } + + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + else if (format == BlacklistFormat.DAT) + { + // 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(",").First().Replace(" ", string.Empty); + + // [1.2.4.0, 1.2.4.255] + var ips = range.Split("-") + .Select(TrimLeadingZerosFromEachOctet); + + cidr = IPAddressRange.Parse(string.Join('-', ips)); + } + } + catch (Exception ex) + { + 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 + 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 a temporary cache to: + // * deduplicate entries + // * sort arrays by first IP to enable binary search (future?) + // * convert List<> to array to increase access speed + var tempCache = new ConcurrentDictionary<int, (uint First, uint Last)[]>(); + + foreach (var key in dict.Keys) + { + tempCache[key] = dict[key] + .Distinct() + .OrderBy(x => x.First) + .ToArray(); + } + + // 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); + } + + /// <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) + { + return true; + } + } + + // not in the list + // worst case scenario for performance, O(n) where n = list length + 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/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,12 +36,18 @@ namespace slskd bool IsEnabled { get; } /// <summary> - /// Starts monitoring the server connection. + /// Initializes the watchdog and makes the initial connection to the server. /// </summary> - /// <remarks>This should be called when the connection is disconnected.</remarks> + /// <remarks>This should be called at application startup.</remarks> void Start(); /// <summary> + /// Starts monitoring the server connection following a disconnect. + /// </summary> + /// <remarks>This should be called when the connection is disconnected.</remarks> + void Restart(); + + /// <summary> /// Stops monitoring the server connection. /// </summary> /// <remarks>This should be called when the application is reasonably certain that the connection is connected.</remarks> @@ -103,13 +109,23 @@ namespace slskd } /// <summary> + /// Initializes the watchdog and makes the initial connection to the server. + /// </summary> + /// <remarks>This should be called at application startup.</remarks> + public void Start() + { + WatchdogTimer.Enabled = true; + _ = AttemptReconnect(attempts: 0); + } + + /// <summary> /// Starts monitoring the server connection. /// </summary> /// <remarks>This should be called when the connection is disconnected.</remarks> - public void Start() + public void Restart() { WatchdogTimer.Enabled = true; - _ = AttemptReconnect(); + _ = AttemptReconnect(attempts: 1); } /// <summary> @@ -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 { diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cfe78eb1..1b049ae1 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; @@ -209,6 +210,12 @@ namespace slskd public RelayOptions Relay { get; init; } = new RelayOptions(); /// <summary> + /// Gets permission options. + /// </summary> + [Validate] + public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + + /// <summary> /// Gets directory options. /// </summary> [Validate] @@ -234,6 +241,12 @@ namespace slskd public GroupsOptions Groups { get; init; } = new GroupsOptions(); /// <summary> + /// Gets blacklist options. + /// </summary> + [Validate] + public BlacklistOptions Blacklist { get; init; } = new BlacklistOptions(); + + /// <summary> /// Gets filter options. /// </summary> [Validate] @@ -412,6 +425,15 @@ namespace slskd [Description("user-defined regular expressions are case sensitive")] [RequiresRestart] public bool CaseSensitiveRegEx { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether to use legacy TCP keepalive options, for Windows + /// versions prior to Windows 10, version 1709 (and associated Server SKUs). + /// </summary> + [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; } /// <summary> @@ -596,6 +618,57 @@ namespace slskd } /// <summary> + /// Permission options. + /// </summary> + public class PermissionsOptions + { + /// <summary> + /// Gets file permission options. + /// </summary> + [Validate] + public FileOptions File { get; init; } = new FileOptions(); + + /// <summary> + /// File permission options. + /// </summary> + public class FileOptions : IValidatableObject + { + /// <summary> + /// Gets the permissions to apply to newly created files. + /// </summary> + /// <remarks> + /// Applicable to non-Windows operating systems, only. + /// </remarks> + [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; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + 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; + } + } + } + + /// <summary> /// Directory options. /// </summary> public class DirectoriesOptions @@ -1099,6 +1172,61 @@ namespace slskd } /// <summary> + /// Blacklist options. + /// </summary> + public class BlacklistOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether blacklist file support should be enabled. + /// </summary> + [Argument(default, "enable-blacklist")] + [EnvironmentVariable("BLACKLIST")] + [Description("enable blacklist file support")] + [RequiresRestart] + public bool Enabled { get; init; } + + /// <summary> + /// Gets the path to the blacklist file. + /// </summary> + [Argument(default, "blacklist-file")] + [EnvironmentVariable("BLACKLIST_FILE")] + [Description("path to blacklist file")] + [FileExists(FileAccess.Read)] + public string File { get; init; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + 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 + { + // async not supported here, .Result is all we have + _ = slskd.Blacklist.DetectFormat(File).Result; + } + catch + { + results.Add(new ValidationResult("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported")); + } + + return results; + } + } + + /// <summary> /// Filter options. /// </summary> public class FiltersOptions @@ -1845,7 +1973,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; } @@ -2078,4 +2206,4 @@ namespace slskd } } } -}
\ No newline at end of file +} |
