diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-06-04 07:48:47 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2026-06-04 07:48:47 -0500 |
| commit | 7e0bc2227cc8593b65e3acd587cbc783e561ca6a (patch) | |
| tree | d3646d726ac543320a7513387c0342c57809bcda /src/slskd | |
| parent | 78561f600754241efdf06c0fcee5ffdbdccda1b6 (diff) | |
| parent | 9a08d5029880c2be008685990f0c83f221ec0e75 (diff) | |
| download | slskd-7e0bc2227cc8593b65e3acd587cbc783e561ca6a.tar.gz | |
Merge branch 'destination' of github.com:slskd/slskd into destination
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Application.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Common/Compute.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Common/Dumper.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Common/FileSafety.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Common/OperatingSystem.cs | 43 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/AbsolutePathAttribute.cs | 53 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/RelativePathAttribute.cs | 40 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 2 |
10 files changed, 143 insertions, 88 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/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..b72d3749 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,7 +102,7 @@ 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(); + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); foreach (var segment in segments) { @@ -170,15 +169,18 @@ 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()) + Console.WriteLine($"IsPathAbsolute? path: {path}, os: {os}, iswindows? {System.OperatingSystem.IsWindows()}"); + + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { + Console.WriteLine("Windows!"); // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows if (path.Length >= 3 @@ -198,6 +200,8 @@ public static class FileSafety return false; } + Console.WriteLine("Linux!"); + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / if (path.StartsWith('/')) { @@ -214,7 +218,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 +228,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 +260,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 +275,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 +326,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 +348,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 +360,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 +392,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); @@ -418,10 +422,10 @@ public static class FileSafety /// </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="stripRoot">An optional value indicating whether to strip 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 = '_', bool stripRoot = false, OperatingSystem? os = null) { if (path is null) { @@ -430,13 +434,13 @@ 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 ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (!retainRoot) + if (stripRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) path = StripPathRoot(path, os); @@ -450,9 +454,10 @@ public static class FileSafety var newPath = string.Join(sep, segments); - if (retainRoot) + if (!stripRoot) { - // leading slashes are stripped of leading slashes by Split() so we must add them back + // leading slashes are stripped by Split() so we must add them back, + // unless we intended to strip the root return new string(sep, leadingSlashCount) + newPath; } @@ -467,7 +472,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/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 8ee486c5..9393e524 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,26 +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(bool platformAgnostic = false) + public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current) { - PlatformAgnostic = platformAgnostic; - } + 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(bool platformAgnostic = false, OSPlatform? os = null) - { - PlatformAgnostic = platformAgnostic; OS = os; } - public OSPlatform? OS { get; } - public bool PlatformAgnostic { get; } + public OperatingSystem? OS { get; } + private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -60,34 +58,31 @@ namespace slskd.Validation { var path = value.ToString(); - if (OS.HasValue) + // this property can only be set via reflection in a unit test; this is here only to make this testable + if (Injected.HasValue) { - if (!FileSafety.IsPathAbsolute(path, os: OS)) + if (!FileSafety.IsPathAbsolute(path, os: Injected)) { - 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."); } + + return ValidationResult.Success; } - else + + if (OS == OperatingSystem.Current) { - if (!PlatformAgnostic) + if (!FileSafety.IsPathAbsolute(path, os: Compute.OperatingSystem())) { - if (!FileSafety.IsPathAbsolute(path, os: OS)) // this OS - { - 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 the current operating system."); } - else - { - if (!FileSafety.IsPathAbsolute(path, os: OSPlatform.Linux)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); - } - if (!FileSafety.IsPathAbsolute(path, os: OSPlatform.Windows)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); - } - } + 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."); } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index a3a3d435..62185a42 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,25 +33,25 @@ 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(bool platformAgnostic = false) + public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current) { - PlatformAgnostic = platformAgnostic; - } + 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 bool PlatformAgnostic { get; } + public OperatingSystem OS { get; } + + private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -59,7 +59,29 @@ namespace slskd.Validation { var path = value.ToString(); - if (OS.HasValue) + // this property can only be set via reflection in a unit test; this is here only to make this testable + if (Injected.HasValue) + { + if (!FileSafety.IsPathRelative(path, os: Injected)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); + } + + return ValidationResult.Success; + } + + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathRelative(path, os: Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any; + if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { // this can only be exercised via unit tests; OSPlatform can't be passeed as an attribute argument // so, this takes precedent over PlatformAgnostic diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 9ad1a626..e76f5d2f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -765,7 +765,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] - [AbsolutePath(platformAgnostic: true)] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -777,7 +777,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] - [AbsolutePath(platformAgnostic: true)] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -1072,7 +1072,7 @@ namespace slskd /// <summary> /// Gets the destination subdirectory for the files in the batch. /// </summary> - [RelativePath(platformAgnostic: true)] + [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; @@ -2046,7 +2046,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsolutePath(platformAgnostic: false)] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index e569df30..fe34bfec 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -106,7 +106,7 @@ 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; } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9e240a7e..84753547 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -865,7 +865,7 @@ namespace slskd.Transfers.Downloads return match.Value; }); - destination = FileSafety.SanitizePath(destination); + destination = FileSafety.SanitizePath(destination, replacement: '_', stripRoot: false); 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 }); |
