diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-06-07 14:45:04 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-06-07 14:45:04 -0500 |
| commit | b747b68ba0ba777be578e73bd1328fbde940e436 (patch) | |
| tree | 160d23aeb8707dc04f81bb52e81913c1b77bb2a4 /src | |
| parent | e06999e5eec1616d93b34ffbab0eade617d1aaf6 (diff) | |
| parent | 2d069bbf1f71f38e1286e27d45c24b478feb11ac (diff) | |
| download | slskd-b747b68ba0ba777be578e73bd1328fbde940e436.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/launch-editor-2.14.1
Diffstat (limited to 'src')
21 files changed, 591 insertions, 222 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e3d212f7..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; } diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 5ff3e519..95721163 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -382,21 +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> - [Obsolete("Find something more intelligent to do instead of this")] - public static string ToLocalFilename(this string remoteFilename, string baseDirectory) - { - return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename()); - } - - /// <summary> /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// </summary> /// <remarks> @@ -410,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> @@ -440,55 +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> - [Obsolete("Find something more intelligent to do instead of this")] - 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 FileSafety.CombineSafely(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> diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index dc565806..d235a87c 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -66,24 +66,14 @@ namespace slskd return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } - public static OSPlatform OSPlatform() + public static OperatingSystem OperatingSystem() { - if (OperatingSystem.IsWindows()) + if (System.OperatingSystem.IsWindows()) { - return System.Runtime.InteropServices.OSPlatform.Windows; + return slskd.OperatingSystem.Windows; } - if (OperatingSystem.IsMacOS()) - { - return System.Runtime.InteropServices.OSPlatform.OSX; - } - - if (OperatingSystem.IsFreeBSD()) - { - return System.Runtime.InteropServices.OSPlatform.FreeBSD; - } - - return System.Runtime.InteropServices.OSPlatform.Linux; + return slskd.OperatingSystem.Linux; } } }
\ No newline at end of file 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/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 5a5d964e..6a6dea22 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -35,7 +35,6 @@ namespace slskd; using System; using System.IO; using System.Linq; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; /// <summary> @@ -85,7 +84,7 @@ public static class FileSafety /// <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, OSPlatform? os, params string[] segments) + 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)) @@ -103,13 +102,21 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows(); + 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) { - // if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment - // and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc" - // not what we want! + // 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}'"); @@ -134,17 +141,26 @@ public static class FileSafety // 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}'"); } } - var combined = Path.Combine(root, Path.Combine(segments)); + 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 (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } @@ -170,14 +186,14 @@ public static class FileSafety /// <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, OSPlatform? os = null) + public static bool IsPathAbsolute(string path, OperatingSystem? os = null) { if (string.IsNullOrEmpty(path)) { return false; } - if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows()) + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows @@ -214,7 +230,7 @@ public static class FileSafety /// <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, OSPlatform? os = null) => !IsPathAbsolute(path, os); + public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); /// <summary> /// Returns the filename from the specified <paramref name="path"/>, properly @@ -224,7 +240,7 @@ public static class FileSafety /// <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, OSPlatform? os = null) + public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) { @@ -256,7 +272,7 @@ public static class FileSafety /// <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, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "") { @@ -271,8 +287,8 @@ public static class FileSafety var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; var local = LocalizePath(path, os) .TrimEnd('/', '\\'); // treat file-less paths the same as files @@ -322,15 +338,15 @@ public static class FileSafety /// <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, OSPlatform? os = null) + public static string LocalizePath(string path, OperatingSystem? os = null) { if (path is null) { return null; } - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); } @@ -344,7 +360,7 @@ public static class FileSafety /// <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 = '_', OSPlatform? os = null) + public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null) { if (filename is null) { @@ -356,9 +372,9 @@ public static class FileSafety throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); } - os ??= Compute.OSPlatform(); + os ??= Compute.OperatingSystem(); - var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; if (characters.Contains(replacement)) { @@ -388,7 +404,7 @@ public static class FileSafety /// <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 = '_', OSPlatform? os = null) + public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null) { var sanitized = SanitizeFilename(segment, replacement, os); @@ -413,49 +429,36 @@ public static class FileSafety /// <summary> /// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system - /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with - /// the specified <paramref name="replacement"/>, and by dropping any path traversal segments. + /// 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="retainRoot">An optional value indicating whether to keep the path's root, if present.</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 = '_', bool retainRoot = false, OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null) { if (path is null) { return null; } - var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (!retainRoot) - { - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path, os); - } - - // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + // 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)); + .Select(s => SanitizePathSegment(s, replacement, os)) + .Where(s => s is not ""); var newPath = string.Join(sep, segments); - 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; } @@ -467,7 +470,7 @@ public static class FileSafety /// <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, OSPlatform? os = null) + public static string StripPathRoot(string path, OperatingSystem? os = null) { if (path is null) { 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 index eb1c9069..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,23 +33,24 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// <summary> /// Validates that the specified path is absolute. /// </summary> public class AbsolutePathAttribute : ValidationAttribute { - public AbsolutePathAttribute() + 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)); + } - public AbsolutePathAttribute(OSPlatform? os = null) - { OS = os; } - public OSPlatform? OS { get; } + public OperatingSystem OS { get; } + private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -57,9 +58,20 @@ namespace slskd.Validation { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path, os: OS)) + 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 file path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems."); } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f465ba98..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,36 +33,50 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// <summary> /// Validates that the specified path is relative. /// </summary> public class RelativePathAttribute : ValidationAttribute { - public RelativePathAttribute() + 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)); + } - public RelativePathAttribute(OSPlatform? os = null) - { OS = os; } - public OSPlatform? OS { get; } + 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 (!FileSafety.IsPathRelative(path, os: OS)) + 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."); + 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/Core/Options.cs b/src/slskd/Core/Options.cs index bac86ea2..f35a56df 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; @@ -765,7 +767,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -777,7 +779,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -832,22 +834,22 @@ 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(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + 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."))); @@ -1029,6 +1031,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 @@ -1057,6 +1065,63 @@ namespace slskd [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> + 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; + } + } + } } /// <summary> @@ -2020,7 +2085,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsolutePath] + [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 3b304d99..62d17f20 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -389,13 +389,15 @@ namespace slskd.Files 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 { @@ -469,13 +471,15 @@ namespace slskd.Files 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 d4baf276..9a2914ea 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; @@ -1007,6 +1008,7 @@ namespace slskd services.AddSwaggerGen(options => { options.DescribeAllParametersInCamelCase(); + options.CustomSchemaIds(type => type.FullName); options.SwaggerDoc("v0", new OpenApiInfo { Version = "v0", @@ -1216,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) @@ -1234,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 fdc6dbe6..ddb8d0b0 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -345,7 +345,7 @@ namespace slskd.Relay } Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); - var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{agentName.ReplaceInvalidFileNameCharacters()}_{Path.GetRandomFileName()}.db"); + 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 974ca71e..5c5f9d38 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -484,7 +484,7 @@ namespace slskd.Relay // 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 () => { diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index c1b7d725..fe34bfec 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -106,8 +106,13 @@ public record EnqueueDownloadBatchOptions /// <summary> /// The destination directory for the files, relative to the configured download directory. /// </summary> - [RelativePath] + [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/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 013e6a7a..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. @@ -68,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> @@ -165,6 +188,7 @@ namespace slskd.Transfers.Downloads { public DownloadService( IBatchService batchService, + ISearchService searchService, IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory<TransfersDbContext> contextFactory, @@ -174,6 +198,7 @@ namespace slskd.Transfers.Downloads EventBus eventBus) { Batches = batchService; + Searches = searchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -213,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 @@ -708,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> @@ -1045,14 +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; - // 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 - var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); + /* + 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; @@ -1140,22 +1341,18 @@ 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 = FileSafety.CombineSafely(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); @@ -1163,10 +1360,10 @@ namespace slskd.Transfers.Downloads 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/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs index 6bacef8c..2ea22997 100644 --- a/src/slskd/Transfers/Types/BatchOptions.cs +++ b/src/slskd/Transfers/Types/BatchOptions.cs @@ -45,4 +45,9 @@ public record BatchOptions /// 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/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> |
