From 70520ee0e09526cd86a4bdf6573cbc6f3af717da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:10:50 -0500 Subject: add our own OperatingSystem enum because why not at this point --- src/slskd/Common/Compute.cs | 18 ++++------------ src/slskd/Common/OperatingSystem.cs | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 14 deletions(-) create mode 100644 src/slskd/Common/OperatingSystem.cs (limited to 'src') 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/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs new file mode 100644 index 00000000..97c205a6 --- /dev/null +++ b/src/slskd/Common/OperatingSystem.cs @@ -0,0 +1,42 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd; + +public enum OperatingSystem +{ + None = 0, + Current = 1, + Linux = 2, + Windows = 3, + Any = 4, +} \ No newline at end of file -- cgit v1.2.3 From 48f9412b8e9be15b36a2bd7335d6b7a8a0448421 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:17:24 -0500 Subject: so dumb --- src/slskd/Common/OperatingSystem.cs | 7 ++-- .../Common/Validation/AbsolutePathAttribute.cs | 39 +++++++++++++++++----- .../Common/Validation/RelativePathAttribute.cs | 39 ++++++++++++++++++---- 3 files changed, 67 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs index 97c205a6..0c3dae2c 100644 --- a/src/slskd/Common/OperatingSystem.cs +++ b/src/slskd/Common/OperatingSystem.cs @@ -35,8 +35,9 @@ namespace slskd; public enum OperatingSystem { None = 0, - Current = 1, - Linux = 2, - Windows = 3, + 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..9393e524 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; /// /// Validates that the specified path is absolute. /// 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,31 @@ namespace slskd.Validation { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path, os: OS)) + // 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: Injected)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path."); + } + + return ValidationResult.Success; + } + + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathAbsolute(path, os: 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..755ea311 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,30 +33,55 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// /// Validates that the specified path is relative. /// 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)) + // 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)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } -- cgit v1.2.3 From c0212d05af5a9ec22ff5c89a24ea4d5761a48482 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:17:49 -0500 Subject: pass os in attributes --- src/slskd/Core/Options.cs | 8 ++++---- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f2a78247..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] + [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] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -1072,7 +1072,7 @@ namespace slskd /// /// Gets the destination subdirectory for the files in the batch. /// - [RelativePath] + [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] + [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 /// /// The destination directory for the files, relative to the configured download directory. /// - [RelativePath] + [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } -- cgit v1.2.3 From 31a9b5918d49650564c4b59c8ae95a16412bef9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:18:03 -0500 Subject: use OperatingSystem instead of the other thing --- src/slskd/Common/FileSafety.cs | 55 +++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 25 deletions(-) (limited to 'src') 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; /// @@ -85,7 +84,7 @@ public static class FileSafety /// The combined path. /// Thrown if the root, list of segments, or one or more segments is null. /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. - 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 /// The path to check. /// An optional operating system override, for testing. /// True if the path is absolute, false otherwise. - 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 /// The path to check. /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. - public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); /// /// Returns the filename from the specified , properly @@ -224,7 +228,7 @@ public static class FileSafety /// An optional value indicating that invalid characters should not be replaced. /// An optional operating system override, for testing. /// The extracted filename. - 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 /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - 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 /// The path to convert. /// An optional operating system override, for testing. /// The converted path. - 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 /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized filename. - 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 /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized path segment. - 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 /// /// The path. /// The character to substitute for invalid characters. - /// An optional value indicating whether to keep the path's root, if present. + /// An optional value indicating whether to strip the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - 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 /// The path to strip. /// An optional operating system override, for testing. /// The path with the root stripped, if one was present. - public static string StripPathRoot(string path, OSPlatform? os = null) + public static string StripPathRoot(string path, OperatingSystem? os = null) { if (path is null) { -- cgit v1.2.3 From 389ef5a3f0069df2a2560a32da8804cda78be16b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:18:46 -0500 Subject: now we have to disambiguate OperatingSystem --- src/slskd/Application.cs | 2 +- src/slskd/Common/Dumper.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') 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/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"; } -- cgit v1.2.3 From 9a08d5029880c2be008685990f0c83f221ec0e75 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:19:21 -0500 Subject: specify replacement explicitly --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 }); -- cgit v1.2.3