aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorArtur <5359825+sethidden@users.noreply.github.com>2024-05-30 09:27:41 +0000
committerGitHub <noreply@github.com>2024-05-30 09:27:41 +0000
commita783e181982dd8c435bb51345a8528a65a4304ac (patch)
tree236c9b7bc40ca09cf3f40878a9beb1dea292a20d /src
parent02bf77158d3bf3dcb6919a9bd0637bf040644c26 (diff)
parentb33449b0282d7f466be22570c26e9e3c982b888a (diff)
downloadslskd-a783e181982dd8c435bb51345a8528a65a4304ac.tar.gz
Merge branch 'slskd:master' into master
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs66
-rw-r--r--src/slskd/Common/Validation/FileExistsAttribute.cs30
-rw-r--r--src/slskd/Core/Blacklist.cs341
-rw-r--r--src/slskd/Core/ConnectionWatchdog.cs49
-rw-r--r--src/slskd/Core/Options.cs132
-rw-r--r--src/slskd/Files/API/FilesController.cs4
-rw-r--r--src/slskd/Files/FileExtensions.cs62
-rw-r--r--src/slskd/Files/FileService.cs152
-rw-r--r--src/slskd/Files/IFileService.cs74
-rw-r--r--src/slskd/Files/Types/CreateFileOptions.cs31
-rw-r--r--src/slskd/Program.cs10
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs71
-rw-r--r--src/slskd/Users/UserService.cs124
-rw-r--r--src/web/package-lock.json44
14 files changed, 953 insertions, 237 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 7f703eaa..f92b4647 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 =>
- {
- 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,
@@ -453,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();
}
}
}
@@ -477,6 +464,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);
+
+ 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.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
+ }
+ 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)
{
@@ -801,7 +819,7 @@ namespace slskd
else
{
Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message);
- ConnectionWatchdog.Start();
+ ConnectionWatchdog.Restart();
}
}
@@ -1290,16 +1308,8 @@ namespace slskd
inactivityTimeout: connection.Timeout.Inactivity,
proxyOptions: proxyPatch);
- var configureKeepAlive = new Action<Socket>(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,
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
/// </summary>
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}'");
+ }
+ }
}
}
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
+}
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<Options> optionsSnapshot)
{
Files = fileService;
OptionsSnapshot = optionsSnapshot;
}
- private IFileService Files { get; }
+ private FileService Files { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<FilesController>();
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 file="FileExtensions.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.Files;
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+/// <summary>
+/// Extension methods related to <see cref="Files"/>.
+/// </summary>
+public static class FileExtensions
+{
+ /// <summary>
+ /// Converts the specified <paramref name="permissions"/> string into an instance of <see cref="UnixFileMode"/>.
+ /// </summary>
+ /// <param name="permissions">A 3 or 4 character string consisting of only 0-7, matching a Unix file permission (e.g. one used with 'chmod').</param>
+ /// <returns>The converted UnixFileMode.</returns>
+ /// <exception cref="ArgumentException">Thrown if the specified <paramref name="permissions"/> string is null or consists of only whitespace.</exception>
+ /// <exception cref="ArgumentOutOfRangeException">Thrown if the specified <paramref name="permissions"/> are not a 3 or 4 character string consisting of only 0-7.</exception>
+ 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
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index c820220f..0d193d73 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,25 +30,25 @@ namespace slskd.Files
/// <summary>
/// Manages files on disk.
/// </summary>
- public class FileService : IFileService
+ public class FileService
{
/// <summary>
/// Initializes a new instance of the <see cref="FileService"/> class.
/// </summary>
public FileService(
- IOptionsSnapshot<Options> optionsSnapshot)
+ IOptionsMonitor<Options> optionsMonitor)
{
- OptionsSnapshot = optionsSnapshot;
+ OptionsMonitor = optionsMonitor;
}
private IEnumerable<string> 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<FileService>();
- private IOptionsSnapshot<Options> OptionsSnapshot { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
/// <summary>
/// Deletes the specified <paramref name="directories"/>.
@@ -66,7 +65,7 @@ namespace slskd.Files
/// </exception>
/// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception>
/// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception>
- public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories)
+ public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories)
{
if (directories.Any(directory => Path.GetFullPath(directory) != directory))
{
@@ -129,7 +128,7 @@ namespace slskd.Files
/// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception>
/// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception>
/// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception>
- public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files)
+ public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files)
{
if (files.Any(file => Path.GetFullPath(file) != file))
{
@@ -182,7 +181,7 @@ namespace slskd.Files
/// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception>
/// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception>
/// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception>
- public async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
+ public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
{
if (Path.GetFullPath(directory) != directory)
{
@@ -237,5 +236,138 @@ namespace slskd.Files
}
});
}
+
+ /// <summary>
+ /// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>,
+ /// returning a <see cref="Stream"/> with which the contents of the file can be written.
+ /// </summary>
+ /// <remarks>
+ /// 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.
+ /// </remarks>
+ /// <param name="filename">The fully qualified filename.</param>
+ /// <param name="options">An optional patch for the underlying <see cref="FileStreamOptions"/>.</param>
+ /// <returns>A Stream with which the contents of the file can be written.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception>
+ /// <exception cref="IOException">Thrown if the underlying file or Stream can't be created for some reason.</exception>
+ 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())
+ {
+ 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.
+ if (options?.UnixCreateMode != null || !string.IsNullOrWhiteSpace(appOption))
+ {
+ streamOptions.UnixCreateMode = options?.UnixCreateMode ?? appOption?.ToUnixFileMode();
+ Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode);
+ }
+ }
+
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Moves the specified fully qualified, localized, <paramref name="sourceFilename"/> to the specified fully qualified, localized,
+ /// <paramref name="destinationDirectory"/>.
+ /// </summary>
+ /// <remarks>
+ /// If the destination file already exists and the <paramref name="overwrite"/> option is not set, the destination filename will
+ /// be modified to include the current time to avoid the collision while preserving both files.
+ /// </remarks>
+ /// <param name="sourceFilename">The fully qualified filename of the file to move.</param>
+ /// <param name="destinationDirectory">The fully qualified directory to which to move the source file.</param>
+ /// <param name="overwrite">An optional value indicating whether the destination file should be overwritten if it already exists.</param>
+ /// <param name="deleteSourceDirectoryIfEmptyAfterMove">
+ /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move.
+ /// </param>
+ /// <returns>The fully qualified filename of the resulting file.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if either of the specified file or directories are null or contain only whitespace.</exception>
+ /// <exception cref="FileNotFoundException">Thrown if the specified <paramref name="sourceFilename"/> does not exist.</exception>
+ /// <exception cref="IOException">Thrown if the file can't be moved, or the <paramref name="deleteSourceDirectoryIfEmptyAfterMove"/> option is set and the operation fails.</exception>
+ public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false)
+ {
+ 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 destinationFilename = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilename));
+
+ Log.Debug("Attempting to move {Source} to {Destination}", sourceFilename, destinationFilename);
+
+ if (!overwrite && File.Exists(destinationFilename))
+ {
+ 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))
+ {
+ destinationFilename = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}";
+ }
+ }
+
+ try
+ {
+ 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 (deleteSourceDirectoryIfEmptyAfterMove && !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(sourceFilename)}: {ex.Message}", ex);
+ }
+ }
}
} \ No newline at end of file
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 file="IFileService.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.Files
-{
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Security;
- using System.Threading.Tasks;
- using OneOf;
-
- /// <summary>
- /// Manages files on disk.
- /// </summary>
- public interface IFileService
- {
- /// <summary>
- /// Deletes the specified <paramref name="directories"/>.
- /// </summary>
- /// <remarks>
- /// 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.
- /// </remarks>
- /// <param name="directories">The directories to delete.</param>
- /// <returns>The operation context.</returns>
- /// <exception cref="ArgumentException">Thrown if any of the specified directories have a relative path.</exception>
- /// <exception cref="ArgumentException">
- /// Thrown if any of the directories is an exact match for an application-controlled directory.
- /// </exception>
- /// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception>
- /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception>
- Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories);
-
- /// <summary>
- /// Deletes the specified <paramref name="files"/>.
- /// </summary>
- /// <remarks>
- /// 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.
- /// </remarks>
- /// <param name="files">The list of files to delete.</param>
- /// <returns>The operation context.</returns>
- /// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception>
- /// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception>
- /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception>
- Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files);
-
- /// <summary>
- /// Lists the contents in the specified <paramref name="directory"/>, optionally applying the specified <paramref name="enumerationOptions"/>.
- /// </summary>
- /// <param name="directory">The directory from which to start the listing.</param>
- /// <param name="enumerationOptions">Optional enumeration options to apply.</param>
- /// <returns>The list of found contents.</returns>
- /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception>
- /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception>
- /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception>
- Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null);
- }
-} \ No newline at end of file
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 file="CreateFileOptions.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.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
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index d7f6caca..27cbfc6f 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -242,6 +242,12 @@ namespace slskd
private static bool ShowVersion { get; set; }
/// <summary>
+ /// Panic.
+ /// </summary>
+ /// <param name="code">An optional exit code.</param>
+ public static void Exit(int code = 1) => Environment.Exit(code);
+
+ /// <summary>
/// Entrypoint.
/// </summary>
/// <param name="args">Command line arguments.</param>
@@ -576,13 +582,15 @@ namespace slskd
services.AddTransient<IShareRepositoryFactory, SqliteShareRepositoryFactory>();
services.AddSingleton<ISearchService, SearchService>();
+
services.AddSingleton<IUserService, UserService>();
+
services.AddSingleton<IRoomService, RoomService>();
services.AddSingleton<ITransferService, TransferService>();
services.AddSingleton<IDownloadService, DownloadService>();
services.AddSingleton<IUploadService, UploadService>();
- services.AddTransient<IFileService, FileService>();
+ services.AddSingleton<FileService>();
services.AddSingleton<IRelayService, RelayService>();
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 57a78a1f..32903bf9 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -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;
@@ -120,12 +120,14 @@ namespace slskd.Transfers.Downloads
IOptionsMonitor<Options> optionsMonitor,
ISoulseekClient soulseekClient,
IDbContextFactory<TransfersDbContext> 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<TransfersDbContext> ContextFactory { get; }
private IFTPService FTP { get; }
+ private FileService Files { get; }
private IRelayService Relay { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
@@ -285,7 +288,18 @@ 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 = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode)
+ ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
+ : null,
+ })),
size: file.Size,
startOffset: 0,
token: null,
@@ -304,7 +318,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: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)),
+ overwrite: false,
+ deleteSourceDirectoryIfEmptyAfterMove: true);
Log.Debug("Moved file to {Destination}", finalFilename);
@@ -587,52 +605,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);
- }
-
- return new FileStream(localFilename, FileMode.Create);
- }
-
- 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;
- }
}
} \ No newline at end of file
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index 5b15b671..e278ccc7 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -1,4 +1,4 @@
-// <copyright file="UserService.cs" company="slskd Team">
+// <copyright file="UserService.cs" company="slskd Team">
// 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);
@@ -110,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<UserService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private Blacklist Blacklist { get; } = new Blacklist();
/// <summary>
/// Gets or sets the internal cache of User data.
@@ -273,11 +283,20 @@ namespace slskd.Users
return true;
}
+ // check the user-curated list of blacklisted CIDRs that exists along with the list of
+ // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a
+ // blacklist supplied by a third party (but might?)
if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
{
return true;
}
+ // check the managed blacklist loaded from a third party blacklist file
+ if (ipAddress is not null && Blacklist.Contains(ipAddress))
+ {
+ return true;
+ }
+
return false;
}
@@ -347,45 +366,86 @@ namespace slskd.Users
{
var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson());
- 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))
+ if (optionsHash != LastOptionsHash || force)
{
- 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;
+ 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);
+ }
+ });
+ }
+
+ LastBlacklistOptionsHash = blacklistOptionsHash;
+ }
}
private void Reset()
@@ -410,4 +470,4 @@ namespace slskd.Users
updateValueFactory: (key, user) => user with { Username = username, Status = status });
}
}
-} \ No newline at end of file
+}
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index f4022f3b..eb8b7fda 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -6296,13 +6296,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",
@@ -6310,7 +6310,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"
},
@@ -7060,9 +7060,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"
@@ -8060,9 +8060,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"
@@ -10340,17 +10340,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",
@@ -17146,9 +17146,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",
@@ -20412,9 +20412,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",