diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-06-07 18:46:25 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2026-06-07 18:46:25 -0500 |
| commit | 294fcabd3928b420a4dfbd7ddd0dc38ada523165 (patch) | |
| tree | bcc92e42c71f2a9b67f7750c5ecd0a396b5897e5 /src | |
| parent | 60bc0c0c2ea6d9c80a7f091f022567b1d5e3240a (diff) | |
| parent | 8e152ed6eccd5650179f2875eef4aa21243c8c15 (diff) | |
| download | slskd-294fcabd3928b420a4dfbd7ddd0dc38ada523165.tar.gz | |
Merge remote-tracking branch 'origin/master' into reports
Diffstat (limited to 'src')
48 files changed, 2847 insertions, 641 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e36a5539..2b9a1f93 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -551,7 +551,7 @@ namespace slskd { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) + if (System.OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) { return; } @@ -572,6 +572,14 @@ namespace slskd { Metrics.Enqueue.RequestsReceived.Inc(1); + // it shouldn't be possible for us to be sharing any such files, as share paths are required to be absolute and rooted + // if someone is requesting a file like this, something is either really wrong, or they are a bad actor + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt from user {Username} to enqueue a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, filename); + throw new DownloadEnqueueException("File not shared."); + } + /* circuit breaker/failsafe: @@ -1413,6 +1421,14 @@ namespace slskd /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> private async Task<IEnumerable<Soulseek.Directory>> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { + // we shouldn't be sharing any files with these segments because shares are required to be absolute and rooted + // if we see this, something has either gone really wrong, or someone is trying something funny + if (FileSafety.ContainsTraversalSegments(directory)) + { + Log.Warning("Suspicious attempt from user {Username} to list a directory containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, directory); + return []; + } + if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 77db91ef..95721163 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -382,20 +382,6 @@ namespace slskd .Deserialize<T>(str); /// <summary> - /// Converts a fully qualified remote filename to a local filename based in the provided - /// <paramref name="baseDirectory"/>, swapping directory characters for those specific to the local OS, removing any - /// characters that are invalid for the local OS, and making the path relative to the remote store (including the - /// filename and the parent folder). - /// </summary> - /// <param name="remoteFilename">The fully qualified remote filename to convert.</param> - /// <param name="baseDirectory">The base directory for the local filename.</param> - /// <returns>The converted filename.</returns> - public static string ToLocalFilename(this string remoteFilename, string baseDirectory) - { - return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename()); - } - - /// <summary> /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// </summary> /// <remarks> @@ -409,16 +395,6 @@ namespace slskd } /// <summary> - /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). - /// </summary> - /// <param name="path">The path to convert.</param> - /// <returns>The converted path.</returns> - public static string LocalizePath(this string path) - { - return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); - } - - /// <summary> /// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes. /// </summary> /// <param name="path"></param> @@ -439,54 +415,6 @@ namespace slskd } /// <summary> - /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific - /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the - /// remote store (including the filename and the parent folder). - /// </summary> - /// <param name="remoteFilename">The fully qualified remote filename to convert.</param> - /// <returns>The converted filename.</returns> - public static string ToLocalRelativeFilename(this string remoteFilename) - { - if (string.IsNullOrWhiteSpace(remoteFilename)) - { - throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename)); - } - - // normalize path separators - var localizedRemoteFilename = remoteFilename.LocalizePath(); - - var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); - - if (parts.Length == 1) - { - return parts.First().ReplaceInvalidFileNameCharacters(); - } - - var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); - - return Path.Combine(directory, file); - } - - /// <summary> - /// Replaces any occurrence of an invalid filename character with the specified <see paramref="replacement"/>. - /// </summary> - /// <param name="path">The path to sanitize.</param> - /// <param name="replacement">The character with which to replace invalid characters.</param> - /// <returns>The sanitized path.</returns> - public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_') - { - var sanitized = path; - - foreach (var c in Path.GetInvalidFileNameChars()) - { - sanitized = sanitized.Replace(c, replacement); - } - - return sanitized; - } - - /// <summary> /// Converts a ModelStateDictionary into a human-readable format. /// </summary> /// <param name="dictionary">The ModelStateDictionary to format.</param> @@ -555,9 +483,17 @@ namespace slskd /// <returns>The new object deserialized from the string.</returns> public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, GetJsonSerializerOptions()); - private static JsonSerializerOptions GetJsonSerializerOptions() + /// <summary> + /// Applies the standard json serializer options to the specified instance. + /// </summary> + /// <param name="opt">The instance.</param> + /// <returns>The instances with the standard options applied.</returns> + public static JsonSerializerOptions WithStandardOptions(this JsonSerializerOptions opt) + => GetJsonSerializerOptions(opt); + + private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions opt = null) { - var options = new JsonSerializerOptions(); + var options = opt ?? new JsonSerializerOptions(); options.Converters.Add(new IPAddressConverter()); options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new KnownUnsupportedTypeConverter()); diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 8d7c1ceb..d235a87c 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -33,6 +33,7 @@ namespace slskd { using System; + using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; @@ -64,5 +65,15 @@ namespace slskd using var sha256 = SHA256.Create(); return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } + + public static OperatingSystem OperatingSystem() + { + if (System.OperatingSystem.IsWindows()) + { + return slskd.OperatingSystem.Windows; + } + + return slskd.OperatingSystem.Linux; + } } }
\ No newline at end of file diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs index bed224cf..b003decf 100644 --- a/src/slskd/Common/Cryptography/X509.cs +++ b/src/slskd/Common/Cryptography/X509.cs @@ -64,7 +64,7 @@ namespace slskd.Cryptography new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(36500))); - return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags); + return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags); } /// <summary> @@ -80,7 +80,7 @@ namespace slskd.Cryptography try { - _ = new X509Certificate2(fileName, password); + _ = X509CertificateLoader.LoadPkcs12FromFile(fileName, password); return true; } catch (Exception ex) diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs index f4367e61..27304873 100644 --- a/src/slskd/Common/Dumper.cs +++ b/src/slskd/Common/Dumper.cs @@ -84,7 +84,7 @@ namespace slskd await Download(url, BinFile); - if (!OperatingSystem.IsWindows()) + if (!System.OperatingSystem.IsWindows()) { await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\""); } @@ -139,15 +139,15 @@ namespace slskd string os = default; // seems like there should be a way to just retrieve this, but there is not as of .NET 6 - if (OperatingSystem.IsLinux()) + if (System.OperatingSystem.IsLinux()) { os = "linux"; } - else if (OperatingSystem.IsWindows()) + else if (System.OperatingSystem.IsWindows()) { os = "win"; } - else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD()) + else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD()) { os = "osx"; } diff --git a/src/slskd/Common/Exceptions/ConflictException.cs b/src/slskd/Common/Exceptions/ConflictException.cs new file mode 100644 index 00000000..c58708d0 --- /dev/null +++ b/src/slskd/Common/Exceptions/ConflictException.cs @@ -0,0 +1,75 @@ +// <copyright file="ConflictException.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// <summary> + /// Represents errors that originate due to duplication. + /// </summary> + [ExcludeFromCodeCoverage] + public class ConflictException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="ConflictException"/> class. + /// </summary> + public ConflictException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ConflictException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public ConflictException(string message, Exception innerException) + : base(message, innerException) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/DuplicateException.cs b/src/slskd/Common/Exceptions/DuplicateException.cs new file mode 100644 index 00000000..da603d87 --- /dev/null +++ b/src/slskd/Common/Exceptions/DuplicateException.cs @@ -0,0 +1,75 @@ +// <copyright file="DuplicateException.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// <summary> + /// Represents errors that originate due to duplication. + /// </summary> + [ExcludeFromCodeCoverage] + public class DuplicateException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="DuplicateException"/> class. + /// </summary> + public DuplicateException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public DuplicateException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public DuplicateException(string message, Exception innerException) + : base(message, innerException) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs new file mode 100644 index 00000000..6a6dea22 --- /dev/null +++ b/src/slskd/Common/FileSafety.cs @@ -0,0 +1,492 @@ +// <copyright file="FileSafety.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd; + +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +/// <summary> +/// Utility functions to help safely work with paths from untrusted sources. +/// </summary> +public static class FileSafety +{ + /// <summary> + /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). + /// </summary> + public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/']; + + /// <summary> + /// Invalid filename characters on Windows. + /// </summary> + public static readonly char[] InvalidFileNameCharactersOnWindows = + [ + '\"', '<', '>', '|', '\0', + (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, + (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, + (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, + (char)31, ':', '*', '?', '\\', '/', + ]; + + private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ + private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]?", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix + + /// <summary> + /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// </summary> + /// <param name="root">The root directory.</param> + /// <param name="segments">The segments to append.</param> + /// <returns>The combined path.</returns> + /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception> + /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception> + public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments); + + /// <summary> + /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// </summary> + /// <param name="root">The root directory.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <param name="segments">The segments to append.</param> + /// <returns>The combined path.</returns> + /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception> + /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception> + public static string CombineSafely(string root, OperatingSystem? os, params string[] segments) + { + // ensure no inputs are null. matches the behavior of Path.Combine() + if (string.IsNullOrWhiteSpace(root)) + { + throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace"); + } + + if (ContainsTraversalSegments(root)) + { + throw new ArgumentException("Specified root directory contains path traversal segments", nameof(root)); + } + + if (segments is null || segments.Any(s => s is null)) + { + throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); + } + + root = root.TrimEnd('/', '\\'); + + if (segments.Length == 0) + { + return root; + } + + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); + var sep = isWindows ? '\\' : '/'; + + foreach (var segment in segments) + { + // disallow any segments that: + // windows: are drive letter (C:\) or UNC path (\\) + // linux: begin with a forward slash (any number, covering both local and UNC paths) + if (IsPathAbsolute(segment, os)) + { + throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'"); + } + + if (isWindows) + { + if (segment.Contains(':')) + { + throw new ArgumentException($"Colons are not permitted in segments: '{segment}'"); + } + + // on Windows, a segment beginning with a slash is considered 'drive rooted' and something like + // "\foo" translates to "C:\foo" when passed to Path.Combine() + if (segment.StartsWith('\\') || segment.StartsWith('/')) + { + throw new ArgumentException($"Drive-relative segments or those containing leading slashes are not permitted in segments: '{segment}'"); + } + } + + var parts = segment.Split('\\', '/'); + + // ensure the segments we're combining don't contain traversal segments "." or ".." + // untrusted input could use this to "break out" of the root directory and access sensitive areas + // this covers cases where the entire segment is . or .., or foo\..\bar, or \.. or ..\ or \..\ + if (parts.Any(s => s is "." or "..")) + { + throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'"); + } + } + + segments = [.. segments + .Where(s => !string.IsNullOrEmpty(s))]; + + var combined = string.Join(sep, [root, .. segments]); + + if (combined.TrimEnd('/', '\\') == root.TrimEnd('/', '\\')) + { + return combined; + } + + // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting + // path is actually rooted in the root we provided; if not the input was successful in traversal + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) + { + throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); + } + + return combined; + } + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="path"/> contains path traversal segments. + /// </summary> + /// <param name="path">The path to check.</param> + /// <returns>True if one or more segments is present, false otherwise.</returns> + public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted) on the current + /// operating system. + /// </summary> + /// <remarks> + /// This is necessary because the base library is opaque and untestable in a cross-platform way, so we are + /// implementing the nuclear option and doing it ourselves. + /// </remarks> + /// <param name="path">The path to check.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>True if the path is absolute, false otherwise.</returns> + public static bool IsPathAbsolute(string path, OperatingSystem? os = null) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) + { + // Windows drive-letter path: X:\ or X:/ + // X:foo is relative on windows + if (path.Length >= 3 + && char.IsAsciiLetter(path[0]) + && path[1] == ':' + && (path[2] == '\\' || path[2] == '/')) + { + return true; + } + + // UNC path \\server\share + if (path.StartsWith("\\\\")) + { + return true; + } + + return false; + } + + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / + if (path.StartsWith('/')) + { + return true; + } + + return false; + } + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="path"/> is relative on the current + /// operating system. + /// </summary> + /// <param name="path">The path to check.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>True if the path is relative, false otherwise.</returns> + public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); + + /// <summary> + /// Returns the filename from the specified <paramref name="path"/>, properly + /// handling both forward and backslashes and removing invalid characters. + /// </summary> + /// <param name="path">The path from which to extract the filename.</param> + /// <param name="sanitize">An optional value indicating that invalid characters should not be replaced.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The extracted filename.</returns> + public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null) + { + if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } + + if (StripPathRoot(path, os) == string.Empty) + { + return null; + } + + var localPath = LocalizePath(path, os); + var segments = localPath.Split('/', '\\'); + + return segments + .TakeLast(1) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s) + .Single(); + } + + /// <summary> + /// Returns the full directory name from the specified <paramref name="path"/>, properly handling both + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing + /// each of the remaining segments. + /// </summary> + /// <param name="path">The path from which to extract the directory name.</param> + /// <param name="retainRoot">An optional value indicating whether to keep the path's root, if present.</param> + /// <param name="sanitize">An optional value indicating that path segments should not be sanitized.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The directory name.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified path is null.</exception> + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null) + { + if (path is null or "") + { + return null; + } + + // a plain string is assumed to be a file. matches the behavior of the BCL method + if (!path.Contains('/') && !path.Contains('\\')) + { + return null; + } + + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); + + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; + + var local = LocalizePath(path, os) + .TrimEnd('/', '\\'); // treat file-less paths the same as files + + var unrooted = StripPathRoot(local, os); + + // were given a root; C:\, //server, @@abcde + if (unrooted is null or "") + { + return null; + } + + if (!retainRoot) + { + local = unrooted; + } + + // strip empty segments + var segments = local + .Split('/', '\\') + .Where(s => s is not "") + .ToArray(); + + // we were given all slashes, a file in the root, or some other case where + // only a file or subdirectory remains; no parent directory + if (segments.Length <= 1) + { + return null; + } + + var newPath = string.Join(sep, segments + .SkipLast(1) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); + + if (retainRoot) + { + // leading slashes are stripped of leading slashes by Split() so we must add them back + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; + } + + /// <summary> + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// </summary> + /// <param name="path">The path to convert.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The converted path.</returns> + public static string LocalizePath(string path, OperatingSystem? os = null) + { + if (path is null) + { + return null; + } + + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; + + return path.Replace('\\', sep).Replace('/', sep); + } + + /// <summary> + /// Sanitizes the specified <paramref name="filename"/> (or string intended to be used as or as part of a filename) + /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and + /// replacing any invalid characters with the specified <paramref name="replacement"/>. + /// </summary> + /// <param name="filename">The filename (or string intended to be used as/part of one).</param> + /// <param name="replacement">The character to substitute for invalid characters.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The sanitized filename.</returns> + public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null) + { + if (filename is null) + { + return null; + } + + if (replacement is '/' or '\\') + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); + } + + os ??= Compute.OperatingSystem(); + + var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + + if (characters.Contains(replacement)) + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}"); + } + + var sanitized = filename; + + foreach (var c in characters) + { + sanitized = sanitized.Replace(c, replacement); + } + + // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames + // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath() + return sanitized + .Replace('/', replacement) + .Replace('\\', replacement); + } + + /// <summary> + /// Sanitizes the specified <paramref name="segment"/> to make it suitable and safe on the local operating + /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified + /// <paramref name="replacement"/>. + /// </summary> + /// <param name="segment">The path segment.</param> + /// <param name="replacement">The character to substitute for invalid characters.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The sanitized path segment.</returns> + public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null) + { + var sanitized = SanitizeFilename(segment, replacement, os); + + // is is possible for the result of sanitization to produce path traversal strings, + // which would result in traversal when combined (or throw an error because of CombineSafely) + // this can happen either because the segment is already periods, or because the replacement + // character is a period and the input one or two invalid characters. + // if this happens we follow the principle of least surprise and return an empty string + // avoid using a period for replacement (don't let users choose) and we won't have this problem + if (sanitized is "." or "..") + { + if (replacement is '.') + { + return string.Empty; + } + + return replacement.ToString(); + } + + return sanitized; + } + + /// <summary> + /// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system + /// by converting to the correct slashes, replacing any invalid characters with the specified + /// <paramref name="replacement"/>, and by dropping any path traversal segments. + /// </summary> + /// <param name="path">The path.</param> + /// <param name="replacement">The character to substitute for invalid characters.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The sanitized path.</returns> + public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null) + { + if (path is null) + { + return null; + } + + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; + + // flip slashes the correct way + path = LocalizePath(path, os); + + // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings, + // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement) + var segments = path + .Split('/', '\\') + .Where(s => s is not "") + .Select(s => SanitizePathSegment(s, replacement, os)) + .Where(s => s is not ""); + + var newPath = string.Join(sep, segments); + + return newPath; + } + + /// <summary> + /// Removes the root of the specified <paramref name="path"/>, including Window's drive prefix (e.g. C:\), + /// UNC paths on any OS (e.g. \\server on Windows, //server on Linux), and drops the hashed prefix added by + /// Soulseek Qt to hide the path on disk (e.g. @@abcde). + /// </summary> + /// <param name="path">The path to strip.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>The path with the root stripped, if one was present.</returns> + public static string StripPathRoot(string path, OperatingSystem? os = null) + { + if (path is null) + { + return null; + } + + // flip slashes the correct way + path = LocalizePath(path, os); + + // strip C:\ or //server, if present (regardless of slash variant) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + + return path; + } +}
\ No newline at end of file diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs index a7e7e0dc..760f7ba9 100644 --- a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs +++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs @@ -36,7 +36,7 @@ using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; -using Microsoft.OpenApi.Models; +using Microsoft.OpenApi; using Swashbuckle.AspNetCore.SwaggerGen; /// <summary> diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs new file mode 100644 index 00000000..0c3dae2c --- /dev/null +++ b/src/slskd/Common/OperatingSystem.cs @@ -0,0 +1,43 @@ +// <copyright file="OperatingSystem.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd; + +public enum OperatingSystem +{ + None = 0, + Linux = 1, + Windows = 2, + Current = 3, + Any = 4, + All = 5, +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs new file mode 100644 index 00000000..217a4eea --- /dev/null +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -0,0 +1,81 @@ +// <copyright file="AbsolutePathAttribute.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// <summary> + /// Validates that the specified path is absolute. + /// </summary> + public class AbsolutePathAttribute : ValidationAttribute + { + public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current) + { + if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All) + { + throw new System.ArgumentException("OperatingSystem argument for AbsolutePathAttribute must be one of: Current, Any, All", nameof(os)); + } + + OS = os; + } + + public OperatingSystem OS { get; } + private OperatingSystem? Injected { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null && value is string str && !string.IsNullOrEmpty(str)) + { + var path = value.ToString(); + + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathAbsolute(path, os: Injected ?? Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any + if (!FileSafety.IsPathAbsolute(path, os: OperatingSystem.Linux) || !FileSafety.IsPathAbsolute(path, os: OperatingSystem.Windows)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems."); + } + } + + return ValidationResult.Success; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs new file mode 100644 index 00000000..7c04f1f9 --- /dev/null +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -0,0 +1,81 @@ +// <copyright file="GuidAttribute.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Validation +{ + using System; + + using System.ComponentModel.DataAnnotations; + + /// <summary> + /// Validates that the value is a valid Guid. + /// </summary> + public class GuidAttribute : ValidationAttribute + { + public GuidAttribute(bool allowEmpty = false) + { + AllowEmpty = allowEmpty; + } + + public bool AllowEmpty { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value is null) + { + return ValidationResult.Success; + } + + if (value is Guid guid) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + if (value is string str && Guid.TryParse(str, out guid)) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID"); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs index 8f87e479..1e2616bd 100644 --- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs +++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs @@ -1,4 +1,4 @@ -// <copyright file="AbsoluteFilePathAttribute.cs" company="JP Dillingham"> +// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ @@ -33,22 +33,21 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.IO; /// <summary> - /// Validates that the specified path is absolute. + /// Validates that the specified path does not contain traversal segments '.' or '..'. /// </summary> - public class AbsoluteFilePathAttribute : ValidationAttribute + public class NonTraversingPathAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { - var filePath = value.ToString(); + var path = value.ToString(); - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) + if (FileSafety.ContainsTraversalSegments(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs new file mode 100644 index 00000000..ea2b627b --- /dev/null +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -0,0 +1,82 @@ +// <copyright file="RelativePathAttribute.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// <summary> + /// Validates that the specified path is relative. + /// </summary> + public class RelativePathAttribute : ValidationAttribute + { + public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current) + { + if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All) + { + throw new System.ArgumentException("OperatingSystem argument for RelativePathAttribute must be one of: Current, Any, All", nameof(os)); + } + + OS = os; + } + + public OperatingSystem OS { get; } + + private OperatingSystem? Injected { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null && value is string str && !string.IsNullOrEmpty(str)) + { + var path = value.ToString(); + + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any; + if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + } + } + + return ValidationResult.Success; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs new file mode 100644 index 00000000..bb323ba2 --- /dev/null +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -0,0 +1,99 @@ +// <copyright file="StringAttribute.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.Linq; + using System.Text.RegularExpressions; + + /// <summary> + /// Validates that the value is not null or whitespace. + /// </summary> + public class StringAttribute : ValidationAttribute + { + public bool AllowNull { get; set; } = true; + public bool AllowEmpty { get; set; } = true; + public bool AllowWhiteSpace { get; set; } = true; + public char[] DisallowedCharacters { get; set; } = []; + public int MinimumLength { get; set; } = 0; + public int MaximumLength { get; set; } = int.MaxValue; + public Regex Pattern { get; set; } = null; + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + var val = (string)value; + + if (val is null) + { + if (!AllowNull) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + } + else + { + return ValidationResult.Success; + } + } + + if (!AllowEmpty && val is "") + { + return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character"); + } + + // check this after empty to avoid overlap + if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c))) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace"); + } + + if (val.Length < MinimumLength || val.Length > MaximumLength) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters"); + } + + var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + + if (Pattern is not null && Pattern.IsMatch(val)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}"); + } + + return ValidationResult.Success; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs index 6c5810c5..1a155f18 100644 --- a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs @@ -69,7 +69,10 @@ public class Z2025_04_01_TransferStateMigration : IMigration var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; +#pragma warning disable CS0618 // Type or member is obsolete return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); +#pragma warning restore CS0618 // Type or member is obsolete + } public void Apply() diff --git a/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs new file mode 100644 index 00000000..4fb25b1f --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs @@ -0,0 +1,101 @@ +// <copyright file="Z2026_04_30_DropTransferStartOffsetMigration.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// <summary> +/// Updates the Transfers table to drop the unused StartOffset column. +/// </summary> +public class Z2026_04_30_DropTransferStartOffsetMigration : IMigration +{ + public Z2026_04_30_DropTransferStartOffsetMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext<Z2026_04_30_DropTransferStartOffsetMigration>(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + + var columns = schema["Transfers"]; + + if (columns.Any(c => c.Name == "StartOffset")) + { + return true; + } + + return false; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_04_30_DropTransferStartOffsetMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Dropping StartOffset column from the Transfers table..."); + + Exec("ALTER TABLE Transfers DROP COLUMN StartOffset;"); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs new file mode 100644 index 00000000..9b373f71 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -0,0 +1,108 @@ +// <copyright file="Z2026_05_06_AddBatchesTableMigration.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Migrations; + +using System; +using Microsoft.Data.Sqlite; +using Serilog; + +/// <summary> +/// Creates the Batches table in the Transfers database. +/// </summary> +public class Z2026_05_06_AddBatchesTableMigration : IMigration +{ + public Z2026_05_06_AddBatchesTableMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext<Z2026_05_06_AddBatchesTableMigration>(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + + if (schema.ContainsKey("Batches")) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_05_06_AddBatchesTableMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Creating the Batches table..."); + + Exec(@" + CREATE TABLE Batches ( + Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY, + SearchId TEXT, + Username TEXT, + Direction INTEGER NOT NULL, + CreatedAt TEXT NOT NULL, + Options TEXT + );"); + + Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);"); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 7289b070..d53d7c8c 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -60,6 +60,8 @@ public class Migrator { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) }, + { nameof(Z2026_04_30_DropTransferStartOffsetMigration), new Z2026_04_30_DropTransferStartOffsetMigration(connectionStrings: Databases) }, + { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) }, }; } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8cc369af..d1062a2c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -235,11 +235,8 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); - /// <summary> - /// Gets permission options. - /// </summary> - [Validate] - public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + [Obsolete("temporary sentinel to warn users about breaking change. use Transfers.Download.Destination.Permissions instead.")] + public object Permissions { get; init; } = null; /// <summary> /// Gets directory options. @@ -364,6 +361,11 @@ namespace slskd { results.Add(new ValidationResult("The 'integration' key has been renamed to 'integrations'. Add an 's' to the end of the key to remove this error (no other changes were made)")); } + + if (Permissions is not null) + { + results.Add(new ValidationResult("The 'permissions' keys have been moved under a new 'destination' key under transfers -> download, and the behavior has changed. See https://github.com/slskd/slskd/pull/1756 for details")); + } #pragma warning restore CS0618 // Type or member is obsolete return results; @@ -704,57 +706,6 @@ 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 @@ -765,6 +716,8 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] + [AbsolutePath(OperatingSystem.Current)] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -775,6 +728,8 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] + [AbsolutePath(OperatingSystem.Current)] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -828,22 +783,28 @@ namespace slskd var directories = Directories ?? Enumerable.Empty<string>(); - bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); + bool IsBlankPath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])$"); directories?.Where(share => IsBlankPath(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} does not specify a path"))); - bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); + bool IsRootMount(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])/$"); directories?.Where(share => IsRootMount(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); // starts with '/', 'X:', or '\\' - bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); + bool IsAbsolutePath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. + // which is resolved by some OS and will cause weird, unintended side effects + bool ContainsTraversalSegments(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + directories?.Where(share => ContainsTraversalSegments(share)).ToList() + .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); + (string Raw, string Alias, string Path) Digest(string share) { - var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); + var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$"); if (matches.Any()) { @@ -1019,6 +980,12 @@ namespace slskd public RetryOptions Retry { get; init; } = new RetryOptions(); /// <summary> + /// Gets download destination options. + /// </summary> + [Validate] + public DestinationOptions Destination { get; init; } = new DestinationOptions(); + + /// <summary> /// Download retry options. /// </summary> public class RetryOptions @@ -1042,10 +1009,67 @@ namespace slskd public int MaxDelay { get; init; } = 60_000; /// <summary> - /// Gets the strategy for handling incomplete files upon retry. + /// Gets the strategy for handling partial files upon retry. + /// </summary> + [Enum(typeof(RetryPartialStrategy))] + public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); + } + + /// <summary> + /// Download destination options. + /// </summary> + public class DestinationOptions + { + /// <summary> + /// Gets the destination subdirectory for the files in the batch. + /// </summary> + [RelativePath(OperatingSystem.All)] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}"; + + /// <summary> + /// Gets the strategy for handling existing files on disk. + /// </summary> + [Enum(typeof(DestinationExistsStrategy))] + public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); + + /// <summary> + /// Gets the permissions to apply to downloaded files and directories. + /// </summary> + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + /// <summary> + /// Download destination permission options. /// </summary> - [Enum(typeof(RetryIncompleteStrategy))] - public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant(); + public class DestinationPermissionsOptions : IValidatableObject + { + /// <summary> + /// Gets the permissions to apply to newly created files. + /// </summary> + /// <remarks> + /// Applicable to non-Windows operating systems, only. + /// </remarks> + public string Mode { get; init; } + + 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; + } + } } } @@ -2010,7 +2034,8 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsoluteFilePath] + [AbsolutePath(OperatingSystem.Current)] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 575619d5..62d17f20 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -79,6 +79,17 @@ namespace slskd.Files { ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + if (Path.GetFullPath(filename) != filename) + { + throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); + } + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename)); + } + FileInfo info; try @@ -153,18 +164,29 @@ namespace slskd.Files /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception> public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories) { + if (directories is null or [] || directories.Any(directory => string.IsNullOrEmpty(directory))) + { + throw new ArgumentException("One or more directories are null or empty"); + } + if (directories.Any(directory => Path.GetFullPath(directory) != directory)) { throw new ArgumentException("Only absolute paths may be specified", nameof(directories)); } + if (directories.Any(directory => FileSafety.ContainsTraversalSegments(directory))) + { + Log.Warning("Suspicious attempt to delete a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directories: {Directories}", string.Join(", ", directories)); + throw new ArgumentException("Directories containing traversal segments are not allowed", nameof(directories)); + } + if (directories.Any(directory => AllowedDirectories.Contains(directory))) { throw new ArgumentException("Deletion of application-controlled directory roots is not supported"); } // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' - bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed)); + bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed); // if any of the resolved directory paths aren't rooted in one of the allowed directories, forbid the entire request if (!directories.All(directory => IsAllowed(directory))) @@ -216,13 +238,24 @@ namespace slskd.Files /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception> public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files) { + if (files is null or [] || files.Any(file => string.IsNullOrWhiteSpace(file))) + { + throw new ArgumentException("One or more files are null or empty", nameof(files)); + } + if (files.Any(file => Path.GetFullPath(file) != file)) { throw new ArgumentException("Only absolute paths may be specified", nameof(files)); } + if (files.Any(file => FileSafety.ContainsTraversalSegments(file))) + { + Log.Warning("Suspicious attempt to delete a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file(s): {File}", string.Join(", ", files)); + throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(files)); + } + // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' - bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed)); + bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed); // if any of the resolved file paths aren't rooted in one of the allowed directories, forbid the entire request if (!files.All(file => IsAllowed(file))) @@ -269,15 +302,23 @@ namespace slskd.Files /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { + ArgumentException.ThrowIfNullOrWhiteSpace(directory); + if (Path.GetFullPath(directory) != directory) { throw new ArgumentException("Only absolute paths may be specified", nameof(directory)); } + if (FileSafety.ContainsTraversalSegments(directory)) + { + Log.Warning("Suspicious attempt to list a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directory: {Directory}", directory); + throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(directory)); + } + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' - if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed))) + if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed + Path.DirectorySeparatorChar) || directory == allowed)) { - throw new UnauthorizedException($"Only application-controlled directories can be deleted"); + throw new UnauthorizedException($"Only application-controlled directories can be listed"); } if (!Directory.Exists(directory)) @@ -340,15 +381,23 @@ namespace slskd.Files { ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to create a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed"); + } + var path = Path.GetDirectoryName(filename); - UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); + UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode(); if (!Directory.Exists(path)) { if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue) { - Directory.CreateDirectory(path, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag()); + var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag(); + Directory.CreateDirectory(path, unixCreateMode: mode); + File.SetUnixFileMode(path, mode: mode); } else { @@ -411,18 +460,26 @@ namespace slskd.Files ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); + if (FileSafety.ContainsTraversalSegments(sourceFilename) || FileSafety.ContainsTraversalSegments(destinationDirectory)) + { + Log.Warning("Suspicious attempt to move a file with either a source filename or destination directory name containing unsafe path segments (one or more of path traversal characters '.' and '..'). Source: {Source}, Destination: {Destination}", sourceFilename, destinationDirectory); + throw new ArgumentException("Filenames and directories containing traversal segments are not allowed"); + } + if (!File.Exists(sourceFilename)) { throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); } - UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); + UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode(); if (!Directory.Exists(destinationDirectory)) { if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue) { - Directory.CreateDirectory(destinationDirectory, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag()); + var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag(); + Directory.CreateDirectory(destinationDirectory, unixCreateMode: mode); + File.SetUnixFileMode(destinationDirectory, mode: mode); } else { diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index 8c270d6a..597a34f3 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -109,7 +109,7 @@ namespace slskd.Integrations.FTP private async Task AttemptUploadAsync(string filename) { var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); - var remotePath = FtpOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + var remotePath = FtpOptions.RemotePath.TrimEnd('/', '\\'); var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; var existsMode = FtpOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 49a1c260..b6710fdd 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -62,11 +62,12 @@ namespace slskd using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; using Microsoft.IdentityModel.Tokens; - using Microsoft.OpenApi.Models; + using Microsoft.OpenApi; using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; using Serilog; using Serilog.Events; + using Serilog.Formatting.Display; using Serilog.Sinks.Grafana.Loki; using Serilog.Sinks.SystemConsole.Themes; using slskd.Authentication; @@ -780,6 +781,7 @@ namespace slskd services.AddSingleton<TransferService>(); services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); + services.AddSingleton<IBatchService, BatchService>(); services.AddSingleton<FileService>(); services.AddSingleton<IRelayService, RelayService>(); @@ -1006,6 +1008,7 @@ namespace slskd services.AddSwaggerGen(options => { options.DescribeAllParametersInCamelCase(); + options.CustomSchemaIds(type => type.FullName); options.SwaggerDoc("v0", new OpenApiInfo { Version = "v0", @@ -1215,6 +1218,7 @@ namespace slskd .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Authentication.ApiKeyAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning) // bump this down to Information to show SQL + .Enrich.WithProperty("App", AppName) .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) @@ -1233,9 +1237,13 @@ namespace slskd retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), - config => config.GrafanaLoki( - OptionsAtStartup.Logger.Loki ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + config => + { + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) + { + config.GrafanaLoki(OptionsAtStartup.Logger.Loki); + } + }) .WriteTo.Sink(new DelegatingSink(logEvent => { string message = default; diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 0d2ef9c5..ddb8d0b0 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -149,6 +149,14 @@ namespace slskd.Relay return BadRequest(); } + // check the path; the caller has a valid API key but we haven't validated the credential yet, so this is worth + // doing here instead of relying on the CombineSafely() backstop + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to download a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + return BadRequest(); + } + Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // note: the token remains valid after the validation attempt, unlike most other endpoints. @@ -159,7 +167,12 @@ namespace slskd.Relay return Unauthorized(); } - var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); + // if we get this far, the caller has supplied a valid credential and filename, meaning the request + // to download is being made in response to the controller signaling the agent that a download had completed. + // it's not possible for the client to download arbitrary files; credentials are computed from a token, and + // this token is cached in the controller, so only file downloads that the controller solicited are possible + // still, for the abundance of caution, use the CombineSafely method in case the filename has traversal segments + var sourceFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename); Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename); @@ -225,6 +238,14 @@ namespace slskd.Relay throw new ArgumentException("Upload filename is null or empty"); } + // use an abundance of caution; the caller has a valid API key but we haven't validated the credential yet + // this is a really unlikely attack vector and it wouldn't do anything, but we're taking a hard stance on input validation + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to upload a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + return BadRequest(); + } + if (stream == null || !stream.CanRead) { throw new ArgumentException("Unable to obtain stream from request"); @@ -323,8 +344,8 @@ namespace slskd.Relay return Unauthorized(); } - Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); - var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_{agentName}_{Path.GetRandomFileName()}.db"); + Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); + var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{FileSafety.SanitizeFilename(agentName)}_{Path.GetRandomFileName()}.db"); try { diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 9aec7b00..5c5f9d38 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -273,7 +273,7 @@ namespace slskd.Relay StartCancellationTokenSource?.Cancel(); HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder => + .WithUrl($"{options.Relay.Controller.Address.TrimEnd('/')}/hub/relay", builder => { builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey); builder.HttpMessageHandlerFactory = (message) => @@ -338,7 +338,7 @@ namespace slskd.Relay } client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue); - client.BaseAddress = new(options.Address); + client.BaseAddress = new(options.Address.TrimEnd('/')); return client; } @@ -370,6 +370,12 @@ namespace slskd.Relay private async Task HandleFileInfoRequest(string filename, Guid id) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); + } + Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); try @@ -387,8 +393,14 @@ namespace slskd.Relay } } - private Task HandleFileUploadRequest(string filename, long startOffset, Guid token) + private async Task HandleFileUploadRequest(string filename, long startOffset, Guid token) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); + } + _ = Task.Run(async () => { Log.Information("Relay controller requested file {Filename} with ID {Id}", filename, token); @@ -442,33 +454,37 @@ namespace slskd.Relay await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); } }); - - return Task.CompletedTask; } - private Task HandleNotifyFileDownloadCompleted(string filename, Guid token) + private async Task HandleNotifyFileDownloadCompleted(string filename, Guid token) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to solicit a file download containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + return; + } + if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads) { - return Task.CompletedTask; + return; } Log.Information("Relay controller sent a download notification for {Filename} ({Token})", filename, token); _ = Task.Run(async () => { - var destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); + var destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename); if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug) { // if we're debugging, we're referencing the same file for both the controller and agent which will lead to an // access violation. prefix the destination file to avoid this. - destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); + destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); } // if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the // local OS or we're going to get funny results when we go to write the file - destinationFile = destinationFile.LocalizePath(); + destinationFile = FileSafety.LocalizePath(destinationFile); await Retry.Do(task: async () => { @@ -498,8 +514,6 @@ namespace slskd.Relay Log.Information("File {Filename} successfully downloaded to {Destination}", filename, destinationFile); }); - - return Task.CompletedTask; } private Task HubConnection_Closed(Exception arg) @@ -579,7 +593,7 @@ namespace slskd.Relay return; } - var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); + var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); try { diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a1dde4eb..054561bf 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -188,7 +188,9 @@ namespace slskd.Shares directories.TryAdd(directory, new Directory(directory)); } - var files = repositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true)); + var files = repositories.SelectMany(r => r.ListFiles( + parentDirectory: prefix, + includeFullPath: true)); // includes the full *masked* filename; directory and file name and extension. not the local filename. var groups = files .GroupBy(file => file.Filename.GetNormalizedDirectoryName()) @@ -280,7 +282,7 @@ namespace slskd.Shares /// <returns>The contents of the directory.</returns> public Task<Directory> ListDirectoryAsync(string directory) { - var files = AllRepositories.SelectMany(r => r.ListFiles(directory)); + var files = AllRepositories.SelectMany(r => r.ListFiles(directory, includeFullPath: false)); return Task.FromResult(new Directory(directory, files)); } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index b6c5fc9d..ed594209 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -418,7 +418,7 @@ namespace slskd.Shares while (reader.Read()) { - var filename = reader.GetString(0); + var maskedFilename = reader.GetString(0); var code = reader.GetInt32(1); var size = reader.GetInt64(2); var extension = reader.GetString(3); @@ -426,9 +426,9 @@ namespace slskd.Shares var attributeList = attributeJson.FromJson<List<FileAttribute>>(); - filename = includeFullPath ? filename : filename.GetNormalizedFileName(); + maskedFilename = includeFullPath ? maskedFilename : maskedFilename.GetNormalizedFileName(); - var file = new Soulseek.File(code, filename, size, extension, attributeList); + var file = new Soulseek.File(code, maskedFilename, size, extension, attributeList); results.Add(file); } diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 494ee722..3191e3a8 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -42,6 +42,7 @@ namespace slskd.Transfers.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Users; @@ -217,7 +218,7 @@ namespace slskd.Transfers.API } /// <summary> - /// Enqueues the specified download. + /// (Obsolete) Enqueues the specified download. /// </summary> /// <param name="username">The username of the download source.</param> /// <param name="requests">The list of download requests.</param> @@ -225,6 +226,7 @@ namespace slskd.Transfers.API /// <response code="201">The download was successfully enqueued.</response> /// <response code="403">The download was rejected.</response> /// <response code="500">An unexpected error was encountered.</response> + [Obsolete("Will be phased out in future versions; use batches")] [HttpPost("downloads/{username}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] @@ -249,7 +251,12 @@ namespace slskd.Transfers.API if (requests.Any(r => r is null)) { - return BadRequest("One or more records in the request are null"); + return BadRequest("One or more files in the request are null"); + } + + if (requests.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + { + return BadRequest("One or more files in the request contain a dangerous path traversal segment"); } if (!DownloadRequestLimiter.Wait(0)) @@ -282,6 +289,155 @@ namespace slskd.Transfers.API } /// <summary> + /// Enqueues a batch of downloads. + /// </summary> + /// <param name="request">The batch details.</param> + /// <returns></returns> + /// <response code="201">All downloads were successfully enqueued.</response> + /// <response code="200">The request succeeded, but all downloads failed to be enqueued.</response> + /// <response code="207">Some downloads were successfully enqueued, while some failed.</response> + /// <response code="400">Bad request.</response> + /// <response code="403">The request was forbidden.</response> + /// <response code="409">A batch with the same ID already exists.</response> + /// <response code="429">Request throttled.</response> + /// <response code="500">An unexpected error was encountered.</response> + [HttpPost("downloads/batches")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)] + [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] + public async Task<IActionResult> EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetReadableString()); + } + + if (request.Files.Any(r => r is null)) + { + return BadRequest("One or more files in the request are null"); + } + + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + { + return BadRequest("Two or more files in the request are repeated"); + } + + Guid? batchId; + Guid? searchId; + + try + { + batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id); + searchId = string.IsNullOrWhiteSpace(request.SearchId) ? null : Guid.Parse(request.SearchId); + } + catch (Exception ex) + { + Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message); + return BadRequest("One or more provided identifiers is not a valid GUID/UUID"); + } + + batchId ??= Guid.NewGuid(); + + if (!DownloadRequestLimiter.Wait(0)) + { + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); + } + + try + { + var endpoint = await Users.GetIPEndPointAsync(request.Username); + + if (Users.IsBlacklisted(request.Username, endpoint.Address)) + { + throw new UserOfflineException($"User {request.Username} appears to be offline"); + } + + // throws DuplicateException if a record already exists + await Transfers.Downloads.Batches.CreateAsync(new() + { + Id = batchId.Value, + SearchId = searchId, + Username = request.Username, + Options = new() + { + Destination = request.Options.Destination, + }, + }); + + // Transfer records will have been inserted before this returns, unless they were rejected + // because they were already in progress, in which case they will show up in 'failed'. or maybe they + // failed with an error. either way this complicates the return code + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync( + username: request.Username, + files: request.Files.Select(r => (r.Filename, r.Size.Value)), + batchId: batchId); + + if (failed.Count > 0) + { + Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed); + } + + // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) + // failed transfers MAY or MAY NOT have an associated database record. if they do, it should have been + // properly finalized and marked as a failure + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); + + var response = new QueueDownloadBatchResponse + { + Batch = batch, + Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(), + }; + + // basically a no-op, but we did create the batch record (and it's useless, but it's there) + // there's nothing to process asynchronously, so we'll return 200. 204 makes more sense to me, + // but it doesn't allow a body and without it the caller will never know the id unless they supplied it + if (response.Failures.Count == request.Files.Count) + { + return StatusCode(StatusCodes.Status200OK, response); + } + + // if at least one (but not all) failed, we're in a weird state so send the most appropriate status code + // along with the batch and list of failures; the caller will have to pick through it and decide what to do + if (response.Failures.Count > 0) + { + return StatusCode(StatusCodes.Status207MultiStatus, response); + } + + // everything passed and we are now (or will eventually be) downloading asynchronously + return StatusCode(StatusCodes.Status201Created, response); + } + catch (UserOfflineException ex) + { + return StatusCode(StatusCodes.Status404NotFound, ex.Message); + } + catch (DuplicateException ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id); + return Conflict($"A batch with ID {batchId} already exists"); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username} (batch Id: {BatchId}): {Message}", request.Files.Count, request.Username, batchId, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + finally + { + DownloadRequestLimiter.Release(); + } + } + + /// <summary> /// Gets all downloads. /// </summary> /// <returns></returns> @@ -313,6 +469,47 @@ namespace slskd.Transfers.API } /// <summary> + /// Gets the specified batch and associated transfers. + /// </summary> + /// <param name="id">The id of the batch.</param> + /// <returns></returns> + /// <response code="400">The specified id is not valid.</response> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified batch was not found.</response> + [HttpGet("downloads/batches/{id}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(200)] + public async Task<IActionResult> Get([FromRoute, Required] string id) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest($"The specified id {id} is not a valid GUID/UUID"); + } + + try + { + var found = await Transfers.Downloads.Batches.FindAsync(b => b.Id == guid); + + if (found is null) + { + return NotFound(); + } + + return Ok(found); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get batch with ID {Id}: {Message}", guid, ex.Message); + return StatusCode(500, ex.Message); + } + } + + /// <summary> /// Gets all downloads for the specified username. /// </summary> /// <param name="username"></param> @@ -351,7 +548,7 @@ namespace slskd.Transfers.API [HttpGet("downloads/{username}/{id}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { @@ -386,7 +583,7 @@ namespace slskd.Transfers.API /// <response code="404">The specified download was not found.</response> [HttpGet("downloads/{username}/{id}/position")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs new file mode 100644 index 00000000..fe34bfec --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -0,0 +1,118 @@ +// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using slskd.Validation; + +namespace slskd.Transfers.API; + +/// <summary> +/// Enqueue a batch of downloads. +/// </summary> +public record QueueDownloadBatchRequest +{ + /// <summary> + /// The ID of the Batch. + /// </summary> + /// <remarks> + /// If not supplied, one will be randomly generated. + /// </remarks> + [Guid] + public string Id { get; init; } + + /// <summary> + /// The ID of the associated Search, if applicable. + /// </summary> + [Guid] + public string SearchId { get; init; } + + /// <summary> + /// The username of the user from which to download. + /// </summary> + [Required] + [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] + public string Username { get; init; } + + /// <summary> + /// The list of files to download. + /// </summary> + [Required] + [MinLength(1)] + public IReadOnlyCollection<EnqueueDownloadBatchItem> Files { get; init; } = []; + + /// <summary> + /// Options for the Batch. + /// </summary> + public EnqueueDownloadBatchOptions Options { get; init; } = new(); +} + +/// <summary> +/// An item in a download batch. +/// </summary> +public record EnqueueDownloadBatchItem +{ + /// <summary> + /// The name of the file. + /// </summary> + [Required] + [NotNullOrWhiteSpace] + [NonTraversingPath] + public string Filename { get; init; } + + /// <summary> + /// The file size. + /// </summary> + [Required] + [Range(0, long.MaxValue)] + public long? Size { get; init; } +} + +/// <summary> +/// Download batch options. +/// </summary> +public record EnqueueDownloadBatchOptions +{ + /// <summary> + /// The destination directory for the files, relative to the configured download directory. + /// </summary> + [RelativePath(OperatingSystem.All)] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Destination { get; init; } + + /// <summary> + /// An optional external ID for the batch. + /// </summary> + public string ExternalId { get; init; } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs index ce3331ca..84b570bc 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs @@ -1,4 +1,4 @@ -// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham"> +// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ @@ -30,28 +30,18 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> -using System; using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; namespace slskd.Transfers.API; -public record EnqueueDownloadBatchRequest +public record QueueDownloadBatchResponse { - public Guid? BatchId { get; init; } - public Guid? SearchId { get; init; } - - [Required] - [StringLength(500, MinimumLength = 1)] - public string Username { get; init; } - public List<EnqueueDownloadBatchItem> Files { get; init; } = []; + public Batch Batch { get; init; } + public IReadOnlyCollection<QueueDownloadBatchResponseFailure> Failures { get; init; } = []; } -public record EnqueueDownloadBatchItem +public record QueueDownloadBatchResponseFailure { - [Required] - public string Filename { get; set; } - - [Range(0, int.MaxValue)] - public long Size { get; set; } -}
\ No newline at end of file + public string Filename { get; init; } + public string Message { get; init; } +} diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs deleted file mode 100644 index 949f15d4..00000000 --- a/src/slskd/Transfers/API/DTO/Transfer.cs +++ /dev/null @@ -1,169 +0,0 @@ -// <copyright file="Transfer.cs" company="JP Dillingham"> -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ Copyright (c) JP Dillingham. -// │ -// │ 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, version 3. -// │ -// │ 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/. -// │ -// │ This program is distributed with Additional Terms pursuant to Section 7 -// │ of the AGPLv3. See the LICENSE file in the root directory of this -// │ project for the complete terms and conditions. -// │ -// │ https://slskd.org -// │ -// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ -// │ SPDX-FileCopyrightText: JP Dillingham -// │ SPDX-License-Identifier: AGPL-3.0-only -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// </copyright> - -namespace slskd.Transfers.API -{ - using System; - using System.Net; - using Soulseek; - - /// <summary> - /// A single file transfer. - /// </summary> - public class Transfer - { - /// <summary> - /// Gets the current average transfer speed. - /// </summary> - public double AverageSpeed { get; set; } - - /// <summary> - /// Gets the number of remaining bytes to be transferred. - /// </summary> - public long BytesRemaining { get; set; } - - /// <summary> - /// Gets the total number of bytes transferred. - /// </summary> - public long BytesTransferred { get; set; } - - /// <summary> - /// Gets the transfer direction. - /// </summary> - public TransferDirection Direction { get; set; } - - /// <summary> - /// Gets the current duration of the transfer, if it has been started. - /// </summary> - public double? ElapsedTime { get; set; } - - /// <summary> - /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state. - /// </summary> - public DateTime? EndTime { get; set; } - - /// <summary> - /// Gets the filename of the file to be transferred. - /// </summary> - public string Filename { get; set; } - - /// <summary> - /// Gets the transfer id. - /// </summary> - public string Id => Compute.Sha1Hash(Filename); - - /// <summary> - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// </summary> - public IPEndPoint IPEndPoint { get; set; } - - /// <summary> - /// Gets the current progress in percent. - /// </summary> - public double PercentComplete { get; set; } - - /// <summary> - /// Gets the current place in queue, if it has been fetched. - /// </summary> - public int? PlaceInQueue { get; set; } - - /// <summary> - /// Gets the projected remaining duration of the transfer. - /// </summary> - public double? RemainingTime { get; set; } - - /// <summary> - /// Gets the remote unique token for the transfer. - /// </summary> - public int? RemoteToken { get; set; } - - /// <summary> - /// Gets the size of the file to be transferred, in bytes. - /// </summary> - public long Size { get; set; } - - /// <summary> - /// Gets the starting offset of the transfer, in bytes. - /// </summary> - public long StartOffset { get; set; } - - /// <summary> - /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state. - /// </summary> - public DateTime? StartTime { get; set; } - - /// <summary> - /// Gets the state of the transfer. - /// </summary> - public TransferStates State { get; set; } - - /// <summary> - /// Gets the unique token for the transfer. - /// </summary> - public int Token { get; set; } - - /// <summary> - /// Gets the username of the peer to or from which the file is to be transferred. - /// </summary> - public string Username { get; set; } - - /// <summary> - /// Gets the Exception that caused the failure of the transfer, if applicable. - /// </summary> - public string Exception { get; set; } - - public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) - { - return new Transfer() - { - AverageSpeed = transfer.AverageSpeed, - BytesRemaining = transfer.BytesRemaining, - BytesTransferred = transfer.BytesTransferred, - Direction = transfer.Direction, - ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, - EndTime = transfer.EndTime, - Filename = transfer.Filename, - IPEndPoint = transfer.IPEndPoint, - PercentComplete = transfer.PercentComplete, - RemainingTime = transfer.RemainingTime?.TotalMilliseconds, - RemoteToken = transfer.RemoteToken, - Size = transfer.Size, - StartOffset = transfer.StartOffset, - StartTime = transfer.StartTime, - State = transfer.State, - Token = transfer.Token, - Username = transfer.Username, - Exception = transfer.Exception?.Message, - }; - } - } -}
\ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs new file mode 100644 index 00000000..7ea9a70a --- /dev/null +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -0,0 +1,140 @@ +// <copyright file="BatchService.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers.Downloads; + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Serilog; + +/// <summary> +/// Manages transfer batches. +/// </summary> +public interface IBatchService +{ + /// <summary> + /// Creates a new batch record. + /// </summary> + /// <param name="batch">The batch to create.</param> + /// <returns>The created batch.</returns> + Task<Batch> CreateAsync(Batch batch); + + /// <summary> + /// Finds a single batch matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match batches.</param> + /// <returns>The found batch, or default if not found.</returns> + /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception> + Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression); +} + +/// <summary> +/// Manages transfer batches. +/// </summary> +public class BatchService : IBatchService +{ + /// <summary> + /// Initializes a new instance of the <see cref="BatchService"/> class. + /// </summary> + /// <param name="contextFactory">The database context factory to use.</param> + public BatchService(IDbContextFactory<TransfersDbContext> contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory<TransfersDbContext> ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<BatchService>(); + + /// <summary> + /// Creates a new batch record. + /// </summary> + /// <param name="batch">The batch to create.</param> + /// <returns>The created batch.</returns> + public async Task<Batch> CreateAsync(Batch batch) + { + if (batch == default) + { + throw new ArgumentNullException(nameof(batch)); + } + + if (batch.Id == Guid.Empty) + { + throw new ArgumentOutOfRangeException(nameof(batch.Id), message: $"Batch ID may not be an empty uuid ({Guid.Empty})"); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + + context.Batches.Add(batch); + + await context.SaveChangesAsync(); + + return batch; + } + catch (DbUpdateException ex) when (ex.InnerException is SqliteException { SqliteErrorCode: 19 }) + { + throw new DuplicateException($"A Batch with ID {batch.Id} already exists."); + } + catch (Exception ex) + { + Log.Error("Failed to create Batch: {Message}", ex.Message); + throw; + } + } + + /// <summary> + /// Finds a single batch matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match batches.</param> + /// <returns>The found batch, or default if not found.</returns> + /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception> + public async Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + return await context.Batches + .AsNoTracking() + .Include(b => b.Transfers) + .Where(expression) + .SingleOrDefaultAsync(); + } +} diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d4d8004a..7c794e55 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -38,9 +38,11 @@ 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.Net; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -49,6 +51,7 @@ namespace slskd.Transfers.Downloads using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; + using slskd.Search; /// <summary> /// Manages downloads. @@ -56,6 +59,11 @@ namespace slskd.Transfers.Downloads public interface IDownloadService { /// <summary> + /// Gets download batch service. + /// </summary> + IBatchService Batches { get; } + + /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> /// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks> @@ -63,6 +71,26 @@ namespace slskd.Transfers.Downloads void AddOrSupersede(Transfer transfer); /// <summary> + /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and batch + /// configuration. + /// </summary> + /// <remarks> + /// <para> + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop. + /// </para> + /// <para> + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact. + /// </para> + /// </remarks> + /// <param name="transfer">The transfer.</param> + /// <returns>The derived destination directory.</returns> + /// <exception cref="NotFoundException">Thrown if the specified download doesn't exist.</exception> + /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception> + Task<string> DeriveDestination(Transfer transfer); + + /// <summary> /// Enqueues the requested list of <paramref name="files"/>. /// </summary> /// <remarks> @@ -71,12 +99,13 @@ namespace slskd.Transfers.Downloads /// </remarks> /// <param name="username">The username of remote user.</param> /// <param name="files">The list of files to enqueue.</param> + /// <param name="batchId">The optional batch id for the transfers.</param> /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception> /// <exception cref="ArgumentException">Thrown when no files are requested.</exception> /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception> - Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); + Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// <summary> /// Finds a single download matching the specified <paramref name="expression"/>. @@ -158,6 +187,8 @@ namespace slskd.Transfers.Downloads public class DownloadService : IDownloadService { public DownloadService( + IBatchService batchService, + ISearchService searchService, IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory<TransfersDbContext> contextFactory, @@ -166,6 +197,8 @@ namespace slskd.Transfers.Downloads IFTPService ftpClient, EventBus eventBus) { + Batches = batchService; + Searches = searchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -178,6 +211,11 @@ namespace slskd.Transfers.Downloads } /// <summary> + /// Gets download batch service. + /// </summary> + public IBatchService Batches { get; } + + /// <summary> /// These tokens give users the ability to cancel transfers via the UI (or API). /// /// The lifecycle is: @@ -200,10 +238,12 @@ namespace slskd.Transfers.Downloads private IDbContextFactory<TransfersDbContext> ContextFactory { get; } private IFTPService FTP { get; } private FileService Files { get; } + private ISearchService Searches { get; } private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private EventBus EventBus { get; } + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// <summary> /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -249,12 +289,13 @@ namespace slskd.Transfers.Downloads /// </summary> /// <param name="username">The username of the remote user.</param> /// <param name="files">The list of files to enqueue.</param> + /// <param name="batchId">The optional batch id for the transfers.</param> /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception> /// <exception cref="ArgumentException">Thrown when no files are requested.</exception> /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception> - public async Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) + public async Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -273,6 +314,11 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("At least one filename is null or empty", nameof(files)); } + if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename))) + { + throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files)); + } + if (fileList.Count != fileList.Distinct().Count()) { throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); @@ -306,7 +352,7 @@ namespace slskd.Transfers.Downloads } List<Transfer> enqueued = []; - List<string> failed = []; + List<(string Filename, string Message)> failed = []; SemaphoreSlim userSemaphore; Task userSemaphoreWaitTask; @@ -404,7 +450,7 @@ namespace slskd.Transfers.Downloads if (existingInProgressRecord is not null) { Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id); - failed.Add(file.Filename); + failed.Add((file.Filename, "Skipped: Already in progress")); continue; } @@ -416,7 +462,7 @@ namespace slskd.Transfers.Downloads if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false) { Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username); - failed.Add(file.Filename); + failed.Add((file.Filename, "Skipped: Already in progress")); continue; } @@ -431,11 +477,11 @@ namespace slskd.Transfers.Downloads var transfer = new Transfer() { Id = transferId, + BatchId = batchId, Username = username, Direction = TransferDirection.Download, Filename = file.Filename, // important! use the remote filename Size = file.Size, - StartOffset = 0, // todo: maybe implement resumeable downloads? RequestedAt = DateTime.UtcNow, State = TransferStates.Queued | TransferStates.Locally, }; @@ -607,7 +653,7 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); TryFail(transferId, exception: ex); - failed.Add(file.Filename); + failed.Add((file.Filename, $"Error: {ex.Message}")); if (CancellationTokens.TryRemove(transferId, out var cts)) { @@ -689,6 +735,152 @@ namespace slskd.Transfers.Downloads } /// <summary> + /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and + /// batch configuration. + /// </summary> + /// <remarks> + /// <para> + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop. + /// </para> + /// <para> + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact. + /// </para> + /// </remarks> + /// <param name="transfer">The transfer.</param> + /// <returns>The derived destination directory.</returns> + /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception> + public async Task<string> DeriveDestination(Transfer transfer) + { + // validation should ensure this is a relative path and that it contains no traversal segments + // we accept any type of slash in the pattern and convert it to the correct variant for the local OS + var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory; + + // users can enter '{}' if they want the files to go directly into the root of the downloads directory + if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase)) + { + return string.Empty; + } + + string source_username; + string source_path; + string source_directory; + string batch_id; + string batch_external_id; + string search_id; + string search_text; + + /* + fetch/extract/derive and sanitize each of the values we're going to replace + + when flow leaves this block we can expect that all of the string values + defined above have a value that can be safely substituted for its placeholder + */ + try + { + Batch batch = null; + + if (transfer.BatchId is not null) + { + batch = await Batches.FindAsync(b => b.Id == transfer.BatchId); + } + + // destination supplied with the batch enqueue request takes precedence over all; return early + if (!string.IsNullOrWhiteSpace(batch?.Options?.Destination)) + { + var explicitDestination = FileSafety.SanitizePath(batch.Options.Destination, replacement: '_'); + + // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are + // properly sanitizing user input both via the API and in the logic above + if (FileSafety.IsPathAbsolute(explicitDestination) || FileSafety.ContainsTraversalSegments(explicitDestination)) + { + throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub."); + } + + return explicitDestination; + } + + Search search = null; + + if (batch?.SearchId is not null) + { + search = await Searches.FindAsync(s => s.Id == batch.SearchId); + } + + source_username = FileSafety.SanitizeFilename(transfer.Username, replacement: '_'); + + var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_'); + + // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' + // retains the path root, if there is one (Soulseek NS does this), which may not be what + // people want, so possibly revisit and add StripPathRoot() + source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\'); + + // name of the remote parent directory, so using the example above, 'Baz' + source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); + + batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString(); + + // the external id can be any string (it is supplied via API call) so we have to sanitize it just like the destination, + // except we don't want to allow it to tack on directories; that's not what it is for and it could be unintended + batch_external_id = FileSafety.SanitizeFilename( + filename: string.IsNullOrWhiteSpace(batch?.Options?.ExternalId) ? "unknown_batch_external_id" : batch.Options.ExternalId, + replacement: '_'); + + search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString(); + search_text = FileSafety.SanitizeFilename( + filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText, + replacement: '_'); + } + catch (Exception ex) + { + Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message); + throw; + } + + var args = new Dictionary<string, string>( + StringComparer.OrdinalIgnoreCase) // important! + { + ["SOURCE_USERNAME"] = source_username, + ["SOURCE_PATH"] = source_path, + ["SOURCE_DIRECTORY"] = source_directory, + ["BATCH_ID"] = batch_id, + ["BATCH_EXTERNAL_ID"] = batch_external_id, + ["SEARCH_ID"] = search_id, + ["SEARCH_TEXT"] = search_text, + }; + + // use Regex.Replace here because it makes one pass; if we chained .Replace() calls the output from one could + // cascade into others and produce unintended results + var destination = SubdirectoryPatternTokenRegex.Replace( + input: pattern, + evaluator: match => + { + if (args.TryGetValue(match.Groups[1].Value, out var value)) + { + return value; + } + + return match.Value; + }); + + destination = FileSafety.SanitizePath(destination, replacement: '_'); + + Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); + + // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are + // properly sanitizing the final output to strip leading slashes and replace traversal segments + if (FileSafety.IsPathAbsolute(destination) || FileSafety.ContainsTraversalSegments(destination)) + { + Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); + throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub."); + } + + return destination; + } + + /// <summary> /// Returns a list of all downloads matching the optional <paramref name="expression"/>. /// </summary> /// <param name="expression">An optional expression used to match downloads.</param> @@ -973,9 +1165,11 @@ namespace slskd.Transfers.Downloads // the final update after all retry attempts have been exhausted to add it. // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all // retries is to look for this flag - if (transfer.Attempts < retryOptions.Attempts) + if (args.Transfer.State.HasFlag(TransferStates.Completed) + && !args.Transfer.State.HasFlag(TransferStates.Succeeded) + && transfer.Attempts < retryOptions.Attempts) { - transfer.State &= ~TransferStates.Completed; // remove the Completed flag + transfer.State = TransferStates.Queued | TransferStates.Locally; } // todo: broadcast @@ -1024,16 +1218,42 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode) + ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode() : null; - // if the transfer has an associated batch id, store the incomplete file in a directory of the same name - // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file) - var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: System.IO.Path.Combine( - OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); + /* + store incomplete files under a username subdirectory to prevent collisions between users and to make + it safe to resume partial downloads without risking picking up an unrelated file. + + we're going to store the file as: + + <incomplete directory>/<username>/<full path to file on remote client>/<filename> + + so, a remote file 'C:\Music\Public_Domain\Foo\Bar\Baz.ext' from user 'FooBar' becomes: + + linux: incomplete/C:/FooBar/Music/Public_Domain/Foo/Bar/Baz.ext + windows: incomplete\C_\FooBar\Music\Public_Domain\Foo\Bar\Baz.ext + + slashes are normalized to the current OS and any invalid characters are replaced with an underscore, _. + this mitigates the risk of an improper partial resume to a great extent. + + if the remote file changes size between attempts, Soulseek.NET's DownloadAsync() will throw because + the size we send originates from the original file, and there will be a mismatch. + + the only remaining risk is in a case where the file contents have changed but the size remains the same. + the resulting file will be corrupted in that case, and there's nothing we can really do about it. users + that are concerned about this (extremely unlikely) case should configure slskd to always overwrite + partial files. + */ + var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; + var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); + var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; + + var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); + + Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1042,14 +1262,14 @@ namespace slskd.Transfers.Downloads var completedTransfer = await Retry.Do(() => { var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename); - var incompleteStrategy = retryOptions.Incomplete.ToEnum<RetryIncompleteStrategy>(); + var incompleteStrategy = retryOptions.Partial.ToEnum<RetryPartialStrategy>(); var shouldResume = false; var startOffset = 0L; if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0) { - if (incompleteStrategy == RetryIncompleteStrategy.Resume) + if (incompleteStrategy == RetryPartialStrategy.Resume) { shouldResume = true; startOffset = incompleteFileInfo.Length; @@ -1121,33 +1341,29 @@ namespace slskd.Transfers.Downloads move the file from incomplete to complete users have a lot of strong opinions about this! + + the destination is always rooted in the configured download directory. we derive the subdirectory + for this file based on either the Destination property defined for the Batch that contains this transfer, + or by applying replacements to the user's configured Destination.Subdirectory string. + + what we get back will be a relative path (or perhaps an empty string if that's what the user wanted) + that has sanitized and checked for safety against traversal */ - string destinationDirectory; + var subdirectory = await DeriveDestination(transfer); + var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory); - if (transfer.BatchId is not null) - { - // if the transfer has an associated batch id, then: - // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext - destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); - } - else - { - // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so: - // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext - // this is "legacy" behavior that will be familiar to most Soulseek users - destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - } + var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum<DestinationExistsStrategy>(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); var finalFilename = Files.MoveFile( - sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: false, + overwrite: existsStrategy == DestinationExistsStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); - Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); + Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename); if (OptionsMonitor.CurrentValue.Relay.Enabled) { diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index 48179ff2..3180dbd9 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -44,7 +44,6 @@ namespace slskd.Transfers Direction = transfer.Direction, Filename = transfer.Filename, Size = transfer.Size, - StartOffset = t.StartOffset, State = t.State, RequestedAt = transfer.RequestedAt, EnqueuedAt = transfer.EnqueuedAt, diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index be312e8e..b25e7663 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -33,6 +33,7 @@ namespace slskd.Transfers { using System; + using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -43,16 +44,23 @@ namespace slskd.Transfers { } + public DbSet<Batch> Batches { get; set; } public DbSet<Transfer> Transfers { get; set; } public override int SaveChanges(bool acceptAllChangesOnSuccess) { // this is absolutely NOT IDEAL and will accellerate the move away from EF + // we have to do this to store both the integer and the string value in the database + // well, we don't *HAVE* to, but storing the string allows external apps to understand transfer history + // and not need to work out the flags. storing the integer allows us to use bitwise operations in queries, + // which is the main driver for this. foreach (var entry in ChangeTracker.Entries<Transfer>()) { if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { +#pragma warning disable CS0618 // Type or member is obsolete entry.Entity.StateDescription = entry.Entity.State.ToString(); +#pragma warning restore CS0618 // Type or member is obsolete } } @@ -61,6 +69,12 @@ namespace slskd.Transfers protected override void OnModelCreating(ModelBuilder modelBuilder) { + ConfigureTransfers(modelBuilder); + ConfigureBatches(modelBuilder); + } + + private void ConfigureTransfers(ModelBuilder modelBuilder) + { modelBuilder .Entity<Transfer>() .Property(e => e.StartedAt) @@ -114,5 +128,34 @@ namespace slskd.Transfers .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); } + + private void ConfigureBatches(ModelBuilder modelBuilder) + { + modelBuilder + .Entity<Batch>() + .Property(e => e.CreatedAt) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder + .Entity<Batch>() + .HasMany(b => b.Transfers) + .WithOne() + .HasForeignKey(t => t.BatchId) + .IsRequired(false) + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder + .Entity<Batch>() + .Property(b => b.Options) + .HasConversion( + convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()), + convertFromProviderExpression: v => JsonSerializer.Deserialize<BatchOptions>(v, new JsonSerializerOptions().WithStandardOptions())) + .HasColumnType("TEXT"); + + modelBuilder + .Entity<Batch>() + .HasIndex(b => b.SearchId) + .HasDatabaseName("IDX_Batches_SearchId"); + } } } diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs new file mode 100644 index 00000000..a0d71bef --- /dev/null +++ b/src/slskd/Transfers/Types/Batch.cs @@ -0,0 +1,118 @@ +// <copyright file="Batch.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers; + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Soulseek; + +/// <summary> +/// <para> +/// A Transfer Batch is a lightweight association between a number of related Transfer +/// records and optionally the associated Search the Transfers are intended to fulfil. +/// </para> +/// <para> +/// Transfers may be enqueued in a Batch, and a caller that enqueued a Batch may use the +/// available API(s) to determine whether all of the Transfers within the Batch are complete, +/// but otherwise a Batch serves no functional purpose within the application. +/// </para> +/// </summary> +public record Batch +{ + /// <summary> + /// Gets the associated <see cref="slskd.Search.Search.Id"/>, if one was specified when the + /// Batch was enqueued. + /// </summary> + public Guid? SearchId { get; init; } = null; + + /// <summary> + /// Gets the unique identifier for the Batch. + /// </summary> + [Key] + public Guid Id { get; init; } + + /// <summary> + /// Gets the username associated with the Batch. + /// </summary> + public string Username { get; init; } + + /// <summary> + /// Gets the Batch direction (Upload, Download). + /// </summary> + /// <remarks> + /// We don't have, and likely will never be able to implement, upload batches, + /// nor are they of any particular use. + /// </remarks> + public TransferDirection Direction { get; init; } = TransferDirection.Download; + + /// <summary> + /// Gets the time at which the Batch was created. + /// </summary> + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; + + /// <summary> + /// Gets the Transfer records associated with the batch. + /// </summary> + public ICollection<Transfer> Transfers { get; init; } = null; + + /// <summary> + /// Gets the options for the batch. + /// </summary> + public BatchOptions Options { get; init; } + + /* + future: [NotMapped] properties that aggregate values from the associated Transfer records. + there's no use for these now, but if we ever decide to leverage Batch records for anything + but determining whether a Search has been fulfilled, allowing a user to override a download directory, + or to handle an event when a batch is completed, we can add them and figure out how persistence should work. + + file count and size are also not included because of the transfer deduplication that takes place during + the enqueue; if a batch is created and some or all of the files within are already in progress, they are + dropped and no new transfer records are created. this would create data inconsistency, and for no reason (for now) + + loading Transfers and doing aggregation in memory (if fetching 1 batch) or querying and aggregating Transfer + records in SQL and then updating a list of Batch records in memory (if fetching a list) technically works, + but is unlikely to perform well, especially as data grows, and ESPECIALLY when excliding 'Removed' Batches + from results (as this must be aggregated on the fly for each batch.. forever) + + my thinking (and reason for punting on this for now); add the interesting properties (Removed, BytesTransferred, + AverageSpeed, etc) to this class as nullable, and don't set a value until all of the associated Transfer + records have been finalized, then update the columns. when fetching batches we can deduce that any Batch + record missing those properties is still in progress, and we can aggregate the data on the fly. for historical + records that have completed, the data is all in the database and is quick to query. + + this can sit until/if we have further use for Batch records, i want to get this out and don't want to sit + and go back and forth trying to speculate on how this might need to work in the future. + */ +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs new file mode 100644 index 00000000..2ea22997 --- /dev/null +++ b/src/slskd/Transfers/Types/BatchOptions.cs @@ -0,0 +1,53 @@ +// <copyright file="BatchOptions.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers; + +/// <summary> +/// Options for <see cref="Batch"/>es. +/// </summary> +public record BatchOptions +{ + /// <summary> + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. + /// </summary> + /// <remarks> + /// If specified, takes precedence over other configured placement rules. + /// </remarks> + public string Destination { get; init; } + + /// <summary> + /// Gets an optional external ID for the batch. + /// </summary> + public string ExternalId { get; init; } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs new file mode 100644 index 00000000..27281a2d --- /dev/null +++ b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs @@ -0,0 +1,49 @@ +// <copyright file="DestinationConflictStrategy.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers; + +/// <summary> +/// Strategy for handling downloaded files with conflicting names. +/// </summary> +public enum DestinationConflictStrategy +{ + /// <summary> + /// Rename the new file by appending something. + /// </summary> + Rename = 0, + + /// <summary> + /// Overwrite the existing file. + /// </summary> + Overwrite = 1, +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/DestinationExistsStrategy.cs b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs new file mode 100644 index 00000000..18837563 --- /dev/null +++ b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs @@ -0,0 +1,49 @@ +// <copyright file="DestinationExistsStrategy.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers; + +/// <summary> +/// Strategy for handling downloaded files when the destination file already exists. +/// </summary> +public enum DestinationExistsStrategy +{ + /// <summary> + /// Rename the new file by appending something to the file name. + /// </summary> + Rename = 0, + + /// <summary> + /// Overwrite the existing file. + /// </summary> + Overwrite = 1, +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryPartialStrategy.cs index 9ac8d8e2..20868913 100644 --- a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs +++ b/src/slskd/Transfers/Types/RetryPartialStrategy.cs @@ -1,4 +1,4 @@ -// <copyright file="RetryIncompleteStrategy.cs" company="JP Dillingham"> +// <copyright file="RetryPartialStrategy.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ @@ -33,9 +33,9 @@ namespace slskd.Transfers; /// <summary> -/// Strategy for retrying incomplete files. +/// Strategy for retrying partial files. /// </summary> -public enum RetryIncompleteStrategy +public enum RetryPartialStrategy { /// <summary> /// Overwrite the existing file. @@ -43,7 +43,7 @@ public enum RetryIncompleteStrategy Overwrite = 0, /// <summary> - /// Resume the transfer using the size of the incomplete file as the initial offset. + /// Resume the transfer using the size of the partial file as the initial offset. /// </summary> Resume = 1, }
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 93a23380..d33a5efc 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -30,72 +30,146 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> -namespace slskd.Transfers +namespace slskd.Transfers; + +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using Soulseek; + +/// <summary> +/// A file Transfer between network peers. +/// </summary> +public class Transfer { - using System; - using System.ComponentModel.DataAnnotations; - using System.ComponentModel.DataAnnotations.Schema; - using System.Text.Json.Serialization; - using Soulseek; - - public class Transfer - { - public Guid? BatchId { get; init; } = null; - - [Key] - public Guid Id { get; init; } - public string Username { get; init; } - public TransferDirection Direction { get; init; } - - /// <summary> - /// Gets the remote filename. - /// </summary> - public string Filename { get; init; } - public long Size { get; set; } - public long StartOffset { get; init; } - - public TransferStates State { get; set; } = TransferStates.None; - - /// <summary> - /// Gets the string representation of the transfer <see cref="State"/>. - /// </summary> - /// <remarks> - /// This is a hack to get the string into the database. *DO NOT* use this property in code - /// and especially **DO NOT** set the value. The getter and setter can't be protected because - /// EF Core needs them to be public. - /// </remarks> - public string StateDescription { get; set; } - public DateTime RequestedAt { get; set; } - public DateTime? EnqueuedAt { get; set; } - public DateTime? StartedAt { get; set; } - - /// <summary> - /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress. - /// </summary> - /// <remarks> - /// Guaranteed to be set for transfers in a terminal state. - /// </remarks> - public DateTime? EndedAt { get; set; } - public long BytesTransferred { get; set; } - public double AverageSpeed { get; set; } - - public int? PlaceInQueue { get; set; } - public string Exception { get; set; } - - public int Attempts { get; set; } = 0; - - public DateTime? NextAttemptAt { get; set; } = null; - - [JsonIgnore] - public bool Removed { get; set; } - - [NotMapped] - public long BytesRemaining => Size - BytesTransferred; - [NotMapped] - public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; - [NotMapped] - public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; - [NotMapped] - public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed); - } + /// <summary> + /// Gets the associated <see cref="Batch.Id"/>, if one was specified when the Transfer was created. + /// </summary> + public Guid? BatchId { get; init; } = null; + + /// <summary> + /// Gets the unique identifier for the Transfer. + /// </summary> + [Key] + public Guid Id { get; init; } + + /// <summary> + /// Gets the remote username associated with the Transfer. + /// </summary> + public string Username { get; init; } + + /// <summary> + /// Gets the Transfer direction (Upload, Download). + /// </summary> + public TransferDirection Direction { get; init; } + + /// <summary> + /// Gets the remote filename of the file. + /// </summary> + /// <remarks> + /// Exactly as it appeared in the originating Search, Browse, or file directory contents response. + /// </remarks> + public string Filename { get; init; } + + /// <summary> + /// Gets or sets the remote size of the file. + /// </summary> + public long Size { get; set; } + + /// <summary> + /// Gets or sets the state of the Transfer. + /// </summary> + public TransferStates State { get; set; } = TransferStates.None; + + /// <summary> + /// Gets or sets the string representation of the transfer <see cref="State"/>. + /// </summary> + /// <remarks> + /// This is a hack to get the string into the database. *DO NOT* use this property in code + /// and especially **DO NOT** set the value. The getter and setter can't be protected because + /// EF Core needs them to be public. + /// </remarks> + [Obsolete("Use State isntead; this is a hack for EF")] + [JsonIgnore] + public string StateDescription { get; set; } + + /// <summary> + /// Gets or sets the time at which the Transfer was requested from the remote peer. + /// </summary> + public DateTime RequestedAt { get; set; } + + /// <summary> + /// Gets or sets the time at which the Transfer was enqueued, or null if the Transfer has not yet been enqueued. + /// </summary> + /// <remarks> + /// For downloads, this is the time at which the remote peer responded to our enqueue request. For uploads this + /// is the time at which the transfer was made available for scheduling by the upload queue, after we have + /// responded to the remote peer's request to enqueue. + /// </remarks> + public DateTime? EnqueuedAt { get; set; } + + /// <summary> + /// Gets or sets the time at which the Transfer connection was established and data transfer began, or null if the + /// Transfer has not yet been started. + /// </summary> + public DateTime? StartedAt { get; set; } + + /// <summary> + /// Gets or sets the time at which the Transfer ended, or null if the Transfer has not yet started or is still in progress. + /// </summary> + /// <remarks> + /// Guaranteed to be set for transfers in a terminal state. + /// </remarks> + public DateTime? EndedAt { get; set; } + + /// <summary> + /// Gets or sets the number of bytes transferred. + /// </summary> + public long BytesTransferred { get; set; } + + /// <summary> + /// Gets or sets the average speed of the Transfer over the duration. + /// </summary> + public double AverageSpeed { get; set; } + + /// <summary> + /// Gets or sets the current place in line in the remote peer's queue, if place has been requested. + /// </summary> + /// <remarks> + /// May be wildly innacurate to the point of uselessness. + /// </remarks> + public int? PlaceInQueue { get; set; } + + /// <summary> + /// Gets or sets the associated Exception, if the Transfer did not end successfully, or null if it did. + /// </summary> + public string Exception { get; set; } + + /// <summary> + /// Gets or sets the number of attempts. Incremented each time the Transfer is retried. + /// </summary> + /// <remarks> + /// Applicable to downloads only. + /// </remarks> + public int Attempts { get; set; } = 0; + + /// <summary> + /// Gets or sets the time at which the next retry attempt will be made, if applicable. + /// </summary> + public DateTime? NextAttemptAt { get; set; } = null; + + /// <summary> + /// Gets or sets a value indicating whether the Transfer has been removed from the UI. + /// </summary> + public bool Removed { get; set; } + + [NotMapped] + public long BytesRemaining => Size - BytesTransferred; + [NotMapped] + public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; + [NotMapped] + public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + [NotMapped] + public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed); }
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 603c669a..333ae525 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -111,6 +111,7 @@ public static class TransferStateCategories /// </list> /// </summary> public static readonly HashSet<TransferStates> Queued = [ + TransferStates.Requested, // optimistically assume that we will be allowed to enqueue TransferStates.Queued, // 2, in case of some sort of a malfunction or regression TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050 TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098 diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index ebc6c4c6..894f739b 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -101,16 +101,6 @@ namespace slskd.Transfers.Uploads Transfer Find(Expression<Func<Transfer, bool>> expression); /// <summary> - /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive; - /// consider caching. - /// </summary> - /// <param name="expression">The expression used to select uploads for summarization.</param> - /// <returns> - /// The generated summary, including the number of files and total size in bytes. - /// </returns> - (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression); - - /// <summary> /// Gets upload statistics for the specified <paramref name="username"/>. /// </summary> /// <param name="username">The username of the user.</param> @@ -678,7 +668,6 @@ namespace slskd.Transfers.Uploads Direction = TransferDirection.Upload, Filename = filename, // important! use the remote filename Size = localFileLength, - StartOffset = 0, // potentially updated later during handshaking RequestedAt = DateTime.UtcNow, State = TransferStates.Queued | TransferStates.Locally, }; @@ -777,51 +766,12 @@ namespace slskd.Transfers.Uploads return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) - .Where(expression).FirstOrDefault(); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to find upload: {Message}", ex.Message); - throw; - } - } - - /// <summary> - /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive; - /// consider caching. - /// </summary> - /// <param name="expression">The expression used to select uploads for summarization.</param> - /// <returns> - /// The generated summary, including the number of files and total size in bytes. - /// </returns> - public (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression) - { - expression ??= t => true; - - try - { - using var context = ContextFactory.CreateDbContext(); - - var query = context.Transfers - .AsNoTracking() - .Where(t => t.Direction == TransferDirection.Upload) .Where(expression) - .GroupBy(t => true) // https://stackoverflow.com/a/25489456: The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group. - .Select(t => new - { - Files = t.Count(), - Bytes = t.Sum(x => x.Size), - }); - - Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString()); - - var stats = query.FirstOrDefault(); - - return (stats?.Files ?? 0, stats?.Bytes ?? 0); + .SingleOrDefault(); } catch (Exception ex) { - Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + Log.Error(ex, "Failed to find upload: {Message}", ex.Message); throw; } } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index cf825701..cb6a7d83 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -43,41 +43,41 @@ </Target> <ItemGroup> - <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" /> - <PackageReference Include="Dapper" Version="2.1.66" /> + <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" /> + <PackageReference Include="Dapper" Version="2.1.79" /> <PackageReference Include="FluentFTP" Version="49.0.2" /> - <PackageReference Include="IPAddressRange" Version="6.0.0" /> - <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" /> - <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.6" /> - <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0"> + <PackageReference Include="IPAddressRange" Version="6.3.0" /> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" /> + <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" /> + <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.300"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.6" /> - <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="8.0.6" /> + <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.8" /> + <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.8" /> <PackageReference Include="OneOf" Version="3.0.271" /> <PackageReference Include="prometheus-net" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore.HealthChecks" Version="8.2.1" /> - <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.0" /> + <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.1" /> <PackageReference Include="prometheus-net.SystemMetrics" Version="3.1.0" /> - <PackageReference Include="Serilog" Version="3.1.1" /> - <PackageReference Include="Serilog.AspNetCore" Version="8.0.1" /> - <PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" /> - <PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" /> - <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> - <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" /> - <PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" /> - <PackageReference Include="Soulseek" Version="10.0.0" /> + <PackageReference Include="Serilog" Version="4.3.1" /> + <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" /> + <PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" /> + <PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" /> + <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" /> + <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="9.0.0" /> + <PackageReference Include="Serilog.Sinks.Http" Version="9.2.1" /> + <PackageReference Include="Soulseek" Version="10.0.1" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> + <PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.1" /> <PackageReference Include="TagLibSharp" Version="2.3.0" /> <PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" /> <PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" /> - <PackageReference Include="YamlDotNet" Version="15.3.0" /> + <PackageReference Include="YamlDotNet" Version="18.0.0" /> </ItemGroup> </Project> diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js index 0c36e3ed..81d1001c 100644 --- a/src/web/.eslintrc.js +++ b/src/web/.eslintrc.js @@ -5,6 +5,7 @@ const overrides = { 'no-eq-null': 'off', // noisy 'react/forbid-component-props': 'off', // noisy 'react/prop-types': 'off', // noisy + 'canonical/sort-keys': 'off', // noisy 'unicorn/no-array-reduce': 'off', // noisy }; diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 22d9c714..e64bc38d 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -14304,13 +14304,14 @@ } }, "node_modules/launch-editor": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.6.0.tgz", - "integrity": "sha512-JpDCcQnyAAzZZaZ7vEiSqL690w7dAEyLao+KC96zBplnYbJS7TYNjvM3M7y3dGz+v7aIsJk3hllWuc0kWAjyRQ==", + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz", + "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==", "dev": true, + "license": "MIT", "dependencies": { - "picocolors": "^1.0.0", - "shell-quote": "^1.7.3" + "picocolors": "^1.1.1", + "shell-quote": "^1.8.4" } }, "node_modules/less": { @@ -18840,10 +18841,14 @@ } }, "node_modules/shell-quote": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz", - "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==", + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz", + "integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==", "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 23619bd1..39dd1a44 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -20,8 +20,35 @@ const initialState = { conversations: {}, interval: undefined, loading: false, + message: '', }; +const ChatMessageHistory = React.memo( + ({ formatTimestamp, messages, selfUsername }) => { + return ( + <> + {messages.map((message) => ( + <List.Content + className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`} + key={`${message.timestamp}+${message.message}`} + > + <span className="chat-message-time"> + {formatTimestamp(message.timestamp)} + </span> + <span className="chat-message-name"> + {message.direction === 'Out' ? selfUsername : message.username}: + </span> + <span className="chat-message-message">{message.message}</span> + </List.Content> + ))} + <List.Content id="chat-history-scroll-anchor" /> + </> + ); + }, +); + +ChatMessageHistory.displayName = 'ChatMessageHistory'; + class Chat extends Component { constructor(props) { super(props); @@ -62,6 +89,13 @@ class Chat extends Component { // fetch all of the active conversations (but no messages) let conversations = await chat.getAll(); + // the username '..' breaks nearly everything in slskd because it's a path traversal + // sequence and no API endpoints that expect usernames in the path work + // rather than letting this sit broken, i'm making the choice to filter it out + // eslint-disable-next-line no-warning-comments + // todo: remove this filter when the API can handle '..' + conversations = conversations.filter((f) => f.username !== '..'); + // turn into a map, keyed by username // if there are no active conversations, set to an empty map if (conversations.length === 0) { @@ -106,21 +140,15 @@ class Chat extends Component { await chat.acknowledge({ username }); }; - sendMessage = async (username, message) => { - if (!username || !message || username === '') return; - await chat.send({ message, username }); - }; - sendReply = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; + const { active, message } = this.state; if (!this.validInput()) { return; } - await this.sendMessage(active, message); - this.messageRef.current.value = ''; + await chat.send({ username: active, message }); + this.setState({ message: '' }); // force a refresh to append the message // we could probably do this in the browser but we can be lazy @@ -129,12 +157,7 @@ class Chat extends Component { validInput = () => (this.state.active || '').length > 0 && - ( - (this.messageRef && - this.messageRef.current && - this.messageRef.current.value) || - '' - ).length > 0; + (this.state.message || '').length > 0; focusInput = () => { this.messageRef.current.focus(); @@ -154,10 +177,11 @@ class Chat extends Component { selectConversation = (username) => { this.setState( - { + (previousState) => ({ active: username, loading: true, - }, + message: previousState.active === username ? previousState.message : '', + }), async () => { const { active, conversations } = this.state; @@ -180,6 +204,12 @@ class Chat extends Component { } catch { // no-op } + + try { + this.messageRef.current.focus(); + } catch { + // no-op + } }, ); }, @@ -260,26 +290,11 @@ class Chat extends Component { <Segment className="chat-history"> <Ref innerRef={this.listRef}> <List> - {messages.map((message) => ( - <List.Content - className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`} - key={`${message.timestamp}+${message.message}`} - > - <span className="chat-message-time"> - {this.formatTimestamp(message.timestamp)} - </span> - <span className="chat-message-name"> - {message.direction === 'Out' - ? user.username - : message.username} - :{' '} - </span> - <span className="chat-message-message"> - {message.message} - </span> - </List.Content> - ))} - <List.Content id="chat-history-scroll-anchor" /> + <ChatMessageHistory + formatTimestamp={this.formatTimestamp} + messages={messages} + selfUsername={user.username} + /> </List> </Ref> </Segment> @@ -294,7 +309,7 @@ class Chat extends Component { name="send" /> ), - onClick: this.sendMessage, + onClick: this.sendReply, }} fluid input={ @@ -302,7 +317,11 @@ class Chat extends Component { autoComplete="off" data-lpignore="true" id="chat-message-input" + onChange={(event) => + this.setState({ message: event.target.value }) + } type="text" + value={this.state.message} /> } onKeyUp={(event) => diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 0f2e4382..f6bdb685 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -32,12 +32,43 @@ const initialState = { }, joined: [], loading: false, + message: '', room: { messages: [], users: [], }, }; +const RoomMessageHistory = React.memo( + ({ formatTimestamp, messages, onHandleContextMenu }) => { + return ( + <> + {messages.map((message) => ( + <div + key={`${message.timestamp}+${message.message}`} + onContextMenu={(clickEvent) => + onHandleContextMenu(clickEvent, message) + } + > + <List.Content + className={`room-message ${message.self ? 'room-message-self' : ''}`} + > + <span className="room-message-time"> + {formatTimestamp(message.timestamp)} + </span> + <span className="room-message-name">{message.username}: </span> + <span className="room-message-message">{message.message}</span> + </List.Content> + </div> + ))} + <List.Content id="room-history-scroll-anchor" /> + </> + ); + }, +); + +RoomMessageHistory.displayName = 'RoomMessageHistory'; + class Rooms extends Component { constructor(props) { super(props); @@ -114,11 +145,12 @@ class Rooms extends Component { selectRoom = async (roomName) => { this.setState( - { + (previousState) => ({ active: roomName, loading: true, + message: previousState.active === roomName ? previousState.message : '', room: initialState.room, - }, + }), async () => { const { active } = this.state; @@ -131,6 +163,12 @@ class Rooms extends Component { } catch { // no-op } + + try { + this.messageRef.current.focus(); + } catch { + // no-op + } }); }, ); @@ -150,12 +188,7 @@ class Rooms extends Component { validInput = () => (this.state.active || '').length > 0 && - ( - (this.messageRef && - this.messageRef.current && - this.messageRef.current.value) || - '' - ).length > 0; + (this.state.message || '').length > 0; focusInput = () => { this.messageRef.current.focus(); @@ -174,15 +207,14 @@ class Rooms extends Component { }; sendMessage = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; + const { active, message } = this.state; if (!this.validInput()) { return; } await rooms.sendMessage({ message, roomName: active }); - this.messageRef.current.value = ''; + this.setState({ message: '' }); }; handleContextMenu = (clickEvent, message) => { @@ -207,8 +239,12 @@ class Rooms extends Component { }; handleReply = () => { - this.messageRef.current.value = `[${this.state.contextMenu.message.username}] ${this.state.contextMenu.message.message} --> `; - this.focusInput(); + this.setState( + (previousState) => ({ + message: `[${previousState.contextMenu.message.username}] ${previousState.contextMenu.message.message} --> `, + }), + () => this.focusInput(), + ); }; handleUserProfile = () => { @@ -319,29 +355,11 @@ class Rooms extends Component { <Segment className="room-history"> <Ref innerRef={this.listRef}> <List> - {room.messages.map((message) => ( - <div - key={`${message.timestamp}+${message.message}`} - onContextMenu={(clickEvent) => - this.handleContextMenu(clickEvent, message) - } - > - <List.Content - className={`room-message ${message.self ? 'room-message-self' : ''}`} - > - <span className="room-message-time"> - {this.formatTimestamp(message.timestamp)} - </span> - <span className="room-message-name"> - {message.username}:{' '} - </span> - <span className="room-message-message"> - {message.message} - </span> - </List.Content> - </div> - ))} - <List.Content id="room-history-scroll-anchor" /> + <RoomMessageHistory + formatTimestamp={this.formatTimestamp} + messages={room.messages} + onHandleContextMenu={this.handleContextMenu} + /> </List> </Ref> </Segment> @@ -364,7 +382,11 @@ class Rooms extends Component { autoComplete="off" data-lpignore="true" id="room-message-input" + onChange={(event) => + this.setState({ message: event.target.value }) + } type="text" + value={this.state.message} /> } onKeyUp={(event) => |
