From 65178904483e4496c1140bee11b2fd4d79da121f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 May 2026 18:19:42 -0500 Subject: add ReplacePathTraversalSegments --- src/slskd/Common/CommonExtensions.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 5ff3e519..ce1b5afb 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -471,7 +471,7 @@ namespace slskd } /// - /// Replaces any occurrence of an invalid filename character with the specified . + /// Replaces any occurrence of an invalid filename character with the specified . /// /// The path to sanitize. /// The character with which to replace invalid characters. @@ -488,6 +488,22 @@ namespace slskd return sanitized; } + /// + /// Replaces any path traversal segments in the specified with the specified + /// . + /// + /// The path to sanitize. + /// The string with which to replace path traversal segments. + /// The sanitized path. + public static string ReplacePathTraversalSegments(this string path, string replacement = "_") + { + return string.Join(Path.DirectorySeparatorChar, + path + .LocalizePath() + .Split(Path.DirectorySeparatorChar) + .Select(s => s is "." or ".." ? replacement : s)); + } + /// /// Converts a ModelStateDictionary into a human-readable format. /// -- cgit v1.2.3 From def6a3a05f02a53b814821ab6b9692e89c2df693 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:18:06 -0500 Subject: add sanitize functions to FileSafety --- src/slskd/Common/FileSafety.cs | 106 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f67af8d5..aae14a25 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -36,12 +36,34 @@ using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; /// /// Utility functions to help safely work with paths from untrusted sources. /// public static class FileSafety { + + /// + /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). + /// + public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/']; + + /// + /// Invalid filename characters on Windows. + /// + public static readonly char[] InvalidFileNameCharactersOnWindows = + [ + '\"', '<', '>', '|', '\0', + (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, + (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, + (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, + (char)31, ':', '*', '?', '\\', '/', + ]; + + private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ + private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + /// /// An alternative to that disallows rooted segments in the second or /// subsequent position, and disallows segments containing path traversal characters "." and "..". @@ -193,4 +215,88 @@ public static class FileSafety /// 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); + + /// + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// + /// The path to convert. + /// An optional operating system override, for testing. + /// The converted path. + public static string LocalizePath(this string path, OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + return path.Replace('\\', sep).Replace('/', sep); + } + + /// + /// Sanitizes the specified (or string intended to be used as or as part of a filename) + /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and + /// and replacing any invalid characters with the specified . + /// + /// The filename (or string intended to be used as/part of one). + /// 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) + { + if (replacement is '/' or '\\') + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); + } + + os ??= Compute.OSPlatform(); + + var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + + if (characters.Contains(replacement)) + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}"); + } + + var sanitized = filename; + + foreach (var c in characters) + { + sanitized = sanitized.Replace(c, replacement); + } + + // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames + // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath() + return sanitized + .Replace('/', replacement) + .Replace('\\', replacement); + } + + /// + /// Sanitizes the specified 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 , and by dropping any path traversal segments. + /// + /// The path. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path. + public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + // flip slashes the correct way + path = path.LocalizePath(os); + + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + var segments = path + .Split(sep) + .Select(s => SanitizeFilename(s, replacement, os)) + .Select(s => s is "." or ".." ? replacement.ToString() : s); + + return string.Join(sep, segments); + } } \ No newline at end of file -- cgit v1.2.3 From 002a2295241bbbc3e823bc1aa18d64651a10ce74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:18:27 -0500 Subject: add compute.OSPlatform() --- src/slskd/Common/Compute.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 8d7c1ceb..dc565806 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -33,6 +33,7 @@ namespace slskd { using System; + using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; @@ -64,5 +65,25 @@ namespace slskd using var sha256 = SHA256.Create(); return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } + + public static OSPlatform OSPlatform() + { + if (OperatingSystem.IsWindows()) + { + return System.Runtime.InteropServices.OSPlatform.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; + } } } \ No newline at end of file -- cgit v1.2.3 From e711d6ad8b52e7ee6454b20bce0fcdbe12aaae91 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:25:10 -0500 Subject: add ExternalId to batch options --- src/slskd/Transfers/Types/BatchOptions.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') 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. /// public string Destination { get; init; } + + /// + /// Gets an optional external ID for the batch. + /// + public string ExternalId { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 89f2a6e19745f22a8f003556b743cbe87ec67cc8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:43:50 -0500 Subject: strip soulseek qt prefixes too --- src/slskd/Common/FileSafety.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index aae14a25..06fd340d 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -63,6 +63,7 @@ public static class FileSafety private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix /// /// An alternative to that disallows rooted segments in the second or @@ -291,6 +292,9 @@ public static class FileSafety path = DriveRootRegex.Replace(path, string.Empty); path = UncRootRegex.Replace(path, string.Empty); + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split(sep) -- cgit v1.2.3 From f785cdc0a88069f04e62a6dc968504d3fa8fd49b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:56:49 -0500 Subject: add missing ExternalId to DTO --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index c1b7d725..e569df30 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -110,4 +110,9 @@ public record EnqueueDownloadBatchOptions [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } + + /// + /// An optional external ID for the batch. + /// + public string ExternalId { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 65ab127c1b85b5c7023324a2c22b782d07f01f26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:58:48 -0500 Subject: remove deprecated extension method --- src/slskd/Common/CommonExtensions.cs | 24 +--- .../ReplaceInvalidFileNameCharactersTests.cs | 144 --------------------- 2 files changed, 3 insertions(+), 165 deletions(-) delete mode 100644 tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index ce1b5afb..4b327a1b 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -461,33 +461,15 @@ namespace slskd if (parts.Length == 1) { - return parts.First().ReplaceInvalidFileNameCharacters(); + return FileSafety.SanitizeFilename(parts.First()); } - var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); + var file = FileSafety.SanitizeFilename(parts.Last()); + var directory = FileSafety.SanitizeFilename(parts.Reverse().Skip(1).Take(1).Single()); return FileSafety.CombineSafely(directory, file); } - /// - /// Replaces any occurrence of an invalid filename character with the specified . - /// - /// The path to sanitize. - /// The character with which to replace invalid characters. - /// The sanitized path. - 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; - } - /// /// Replaces any path traversal segments in the specified with the specified /// . diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs deleted file mode 100644 index eff24587..00000000 --- a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -namespace slskd.Tests.Unit.Common.Extensions -{ - using System; - using System.IO; - using System.Linq; - using Xunit; - - public class ReplaceInvalidFileNameCharactersTests - { - [Fact] - public void Throws_NullReferenceException_Given_Null() - { - string path = null; - Assert.Throws(() => path.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Returns_Empty_String_Given_Empty_Input() - { - Assert.Equal(string.Empty, string.Empty.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Returns_Input_Unchanged_When_No_Invalid_Characters_Present() - { - var valid = "valid_filename.ext"; - Assert.Equal(valid, valid.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Preserves_Valid_Characters() - { - // Common valid filename chars that must not be touched - var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._- "; - Assert.Equal(valid, valid.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Default_Replacement_Character_Is_Underscore() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"a{c}b".ReplaceInvalidFileNameCharacters(); - Assert.Equal("a_b", result); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_With_Default_Replacement() - { - // Each invalid char is tested individually so failures identify the exact offending char - Assert.All(Path.GetInvalidFileNameChars(), c => - { - var result = $"prefix{c}suffix".ReplaceInvalidFileNameCharacters(); - Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced"); - Assert.Equal("prefix_suffix", result); - }); - } - - [Fact] - public void Replaces_All_Invalid_Filename_Characters_Simultaneously() - { - var invalidChars = Path.GetInvalidFileNameChars(); - var allInvalid = new string(invalidChars); - var result = allInvalid.ReplaceInvalidFileNameCharacters(); - - Assert.All(invalidChars, c => - Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} remained after sanitization")); - } - - [Fact] - public void Result_Contains_Only_Replacement_Character_When_All_Input_Characters_Are_Invalid() - { - var invalidChars = Path.GetInvalidFileNameChars(); - var allInvalid = new string(invalidChars); - var result = allInvalid.ReplaceInvalidFileNameCharacters(); - - Assert.Equal(new string('_', invalidChars.Length), result); - } - - [Fact] - public void Uses_Custom_Replacement_Character() - { - char replacement = '-'; - - Assert.All(Path.GetInvalidFileNameChars(), c => - { - var result = $"a{c}b".ReplaceInvalidFileNameCharacters(replacement); - Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced"); - Assert.Equal("a-b", result); - }); - } - - [Fact] - public void Replaces_Consecutive_Invalid_Characters() - { - var chars = Path.GetInvalidFileNameChars(); - if (chars.Length < 2) - { - return; - } - - var input = $"a{chars[0]}{chars[1]}b"; - var result = input.ReplaceInvalidFileNameCharacters(); - - Assert.Equal("a__b", result); - } - - [Fact] - public void Replaces_Invalid_Character_At_Start_Of_String() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"{c}filename.ext".ReplaceInvalidFileNameCharacters(); - Assert.Equal("_filename.ext", result); - } - - [Fact] - public void Replaces_Invalid_Character_At_End_Of_String() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"filename.ext{c}".ReplaceInvalidFileNameCharacters(); - Assert.Equal("filename.ext_", result); - } - - [Fact] - public void Result_Contains_No_Invalid_Filename_Characters() - { - var invalidChars = Path.GetInvalidFileNameChars(); - var input = "valid" + new string(invalidChars) + "also_valid"; - var result = input.ReplaceInvalidFileNameCharacters(); - - Assert.All(invalidChars, c => - Assert.False(result.Contains(c), $"Character U+{(int)c:X4} remained after sanitization")); - } - - [Fact] - public void Valid_Characters_Surrounding_Invalid_Characters_Are_Preserved() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"before{c}after".ReplaceInvalidFileNameCharacters(); - - Assert.StartsWith("before", result); - Assert.EndsWith("after", result); - } - } -} -- cgit v1.2.3 From 953733c42b4f7556a8619c32da1ef897a0027ae9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:59:07 -0500 Subject: use new SanitizeFilename --- src/slskd/Relay/API/Controllers/RelayController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 { -- cgit v1.2.3 From 845da6c1c95ed18ec88c93a48f0a04c539f28bc3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:59:45 -0500 Subject: wip --- config/slskd.example.yml | 7 +- src/slskd/Core/Options.cs | 50 ++ src/slskd/Transfers/Downloads/DownloadService.cs | 205 ++++++++- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ++ .../DownloadService/DeriveDestinationTests.cs | 512 +++++++++++++++++++++ 5 files changed, 802 insertions(+), 21 deletions(-) create mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 367d8e4d..d295b964 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -39,7 +39,7 @@ # cidr: 0.0.0.0/0,::/0 # permissions: # file: -# mode: ~ # chmod syntax, e.g. 644, 777. not for Windows. +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # directories: # incomplete: ~ # downloads: ~ @@ -78,6 +78,11 @@ # attempts: 3 # delay: 5000 # initial time between retries, in milliseconds # max_delay: 60000 # maximum time between retries, in milliseconds +# destination: +# subdirectory: {SOURCE_DIRECTORY} +# conflict: rename # 'overwrite' or 'rename' +# permissions: +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index bac86ea2..298ea2c0 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1028,6 +1028,12 @@ namespace slskd [Validate] public RetryOptions Retry { get; init; } = new RetryOptions(); + /// + /// Gets download destination options. + /// + [Validate] + public DestinationOptions Destination { get; init; } = new DestinationOptions(); + /// /// Download retry options. /// @@ -1057,6 +1063,50 @@ namespace slskd [Enum(typeof(RetryPartialStrategy))] public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } + + /// + /// Download destination options. + /// + public class DestinationOptions + { + [RelativePath] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; + + [Enum(typeof(DestinationConflictStrategy))] + public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant(); + + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + public class DestinationPermissionsOptions : IValidatableObject + { + public string Mode { get; init; } + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + } } /// diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 013e6a7a..af7a4699 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; /// /// Manages downloads. @@ -67,6 +70,26 @@ namespace slskd.Transfers.Downloads /// void AddOrSupersede(Transfer transfer); + /// + /// Derives the destination subdirectory for the specified based on user and batch + /// configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the specified download doesn't exist. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + Task DeriveDestination(Transfer transfer); + /// /// Enqueues the requested list of . /// @@ -165,6 +188,7 @@ namespace slskd.Transfers.Downloads { public DownloadService( IBatchService batchService, + ISearchService searchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory 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 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(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -707,6 +734,144 @@ namespace slskd.Transfers.Downloads } } + /// + /// Derives the destination subdirectory for the specified based on user and + /// batch configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + public async Task DeriveDestination(Transfer transfer) + { + 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' + source_path = (Path.GetDirectoryName(filename) ?? string.Empty).TrimEnd('/', '\\'); + + // name of the remote parent directory, so using the example above, 'Baz' + source_directory = (Path.GetFileName(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: search?.SearchText ?? "unknown_search_text", + replacement: '_'); + } + catch (Exception ex) + { + Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message); + throw; + } + + var args = new Dictionary( + 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, + }; + + // 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; + + // 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); + + Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", Path.GetFileName(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})", Path.GetFileName(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; + } + /// /// Returns a list of all downloads matching the optional . /// @@ -1045,14 +1210,18 @@ 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 + // 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. if the remote file + // changes size between attempts, Soulseek.NET's DownloadAsync() will throw, so the only real risk is + // in a case where the file contents have changed but the size remains. the resulting file will be + // corrupted in that case. users that are concerned about this (extremely unlikely) case should + // configure slskd to always overwrite partial files. var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); + baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, FileSafety.SanitizeFilename(transfer.Username))); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1140,22 +1309,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 conflictStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Conflict.ToEnum(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1163,7 +1328,7 @@ namespace slskd.Transfers.Downloads sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: false, + overwrite: conflictStrategy == DestinationConflictStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); 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 (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.Transfers; + +/// +/// Strategy for handling downloaded files with conflicting names. +/// +public enum DestinationConflictStrategy +{ + /// + /// Rename the new file by appending something. + /// + Rename = 0, + + /// + /// Overwrite the existing file. + /// + Overwrite = 1, +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs new file mode 100644 index 00000000..cd8060ef --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -0,0 +1,512 @@ +namespace slskd.Tests.Unit.Transfers.Downloads; + +using System; +using System.IO; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Moq; +using slskd.Search; +using slskd.Transfers; +using slskd.Transfers.Downloads; +using Xunit; + +public partial class DownloadServiceTests +{ + public class DeriveDestination + { + [Fact] + public async Task Explicit_Destination_Takes_Precedence_Over_Subdirectory_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("explicit-dir", result); + } + + [Fact] + public async Task Explicit_Destination_Tokens_Are_Not_Expanded() + { + // explicit destination is sanitized but not token-substituted + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "{SOURCE_USERNAME}" } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("{SOURCE_USERNAME}", result); + } + + [Fact] + public async Task Explicit_Destination_Is_Always_Relative() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "/etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Explicit_Destination_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "../../../etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Explicit_Destination_Null_Byte_Replaced() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "down\0loads" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("down_loads", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Is_Substituted() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive() + { + var (service, _) = GetFixture("{source_username}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Theory] + [InlineData("al\\..\\ice")] + [InlineData("al/../ice")] + [InlineData("al\\../ice")] + [InlineData("al/..\\ice")] + public async Task SOURCE_USERNAME_Traversal_Segment_Periods_Remains_After_Replacing_Slashes_With_Underscore(string username) + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_.._ice", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename() + { + var (service, _) = GetFixture("{SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal(Path.Combine("@alice", "Music", "album"), result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("{SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory() + { + var (service, _) = GetFixture("{SOURCE_PATH}-{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("@alice-@alice", result); + } + + [Fact] + public async Task BATCH_ID_Is_Substituted_When_Batch_Exists() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId }; + var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(batchId.ToString(), result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("{BATCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_Batch_Id_Is_Empty_Guid() + { + var batch = new Batch { Id = Guid.Empty }; + var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = Guid.Empty }); + + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Substituted_When_Batch_Has_External_Id() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "my-ext-id" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("my-ext-id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Null() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Whitespace() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo/bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Backslash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\\bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Null_Byte_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\0bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(searchId.ToString(), result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_No_Batch() + { + // no batch → SearchId is never consulted + var (service, _) = GetFixture("{SEARCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_ID_Is_Empty_Guid() + { + var searchId = Guid.Empty; + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo bar baz" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo bar baz", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_No_Search() + { + var (service, _) = GetFixture("{SEARCH_TEXT}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo/bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Backlash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\\bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task Batch_With_Null_Options_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = null }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Batch_With_Whitespace_Destination_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}/downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Backslash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}\\downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Output_Is_Always_Relative() + { + var (service, _) = GetFixture("/etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Pattern_Traversal_Segments_Do_Not_Survive() + { + var (service, _) = GetFixture("../../../etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Username_Containing_Traversal_Is_Safe() + { + // exact '..' in username must not produce a traversal segment in the final output + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + } + + private static (DownloadService service, Mocks mocks) GetFixture( + string subdirectory = "{SOURCE_USERNAME}", + Batch batch = null, + Search search = null) + { + var mocks = new Mocks(subdirectory, batch, search); + var service = new DownloadService( + mocks.BatchService.Object, + mocks.SearchService.Object, + mocks.OptionsMonitor, + null, + new Mock>().Object, + null, + null, + null, + null); + return (service, mocks); + } + + private class Mocks + { + public Mocks(string subdirectory = null, Batch batch = null, Search search = null) + { + OptionsMonitor = new TestOptionsMonitor(new Options + { + Transfers = new Options.TransfersOptions + { + Download = new Options.TransfersOptions.GlobalDownloadOptions + { + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Subdirectory = subdirectory + } + } + } + }); + + BatchService.Setup(b => b.FindAsync(It.IsAny>>())) + .ReturnsAsync(batch); + SearchService.Setup(s => s.FindAsync(It.IsAny>>(), It.IsAny())) + .ReturnsAsync(search); + } + + public Mock BatchService { get; } = new(); + public Mock SearchService { get; } = new(); + public TestOptionsMonitor OptionsMonitor { get; } + } +} -- cgit v1.2.3 From 34005f37c03e878c2a3286ca0223f921a66a5671 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 May 2026 19:10:37 -0500 Subject: tests --- src/slskd/Common/FileSafety.cs | 1 - .../Common/FileSafety/LocalizePathTests.cs | 16 ++++++++++++++- .../Common/FileSafety/SanitizeFilenameTests.cs | 24 ++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 06fd340d..dc27a8b4 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -43,7 +43,6 @@ using System.Text.RegularExpressions; /// public static class FileSafety { - /// /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). /// diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index ed3e692f..2df3e18f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -10,8 +10,15 @@ public partial class FileSafetyTests [Theory] [InlineData("foo/bar", "foo/bar")] [InlineData("foo\\bar", "foo/bar")] + [InlineData("foo/bar/baz", "foo/bar/baz")] [InlineData("foo\\bar/baz", "foo/bar/baz")] [InlineData("foo\\\\bar", "foo//bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde/foo/bar/")] + [InlineData("@@abcde/foo/bar/", "@@abcde/foo/bar/")] + [InlineData("\\\\server\\foo\\", "//server/foo/")] + [InlineData("//server/foo/", "//server/foo/")] + [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] + [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] public void Linux_NormalizesToForwardSlash(string input, string expected) { @@ -24,7 +31,14 @@ public partial class FileSafetyTests [InlineData("foo/bar", "foo\\bar")] [InlineData("foo\\bar", "foo\\bar")] [InlineData("foo/bar/baz", "foo\\bar\\baz")] + [InlineData("foo\\bar/baz", "foo\\bar\\baz")] [InlineData("foo//bar", "foo\\\\bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde\\foo\\bar\\")] + [InlineData("@@abcde/foo/bar/", "@@abcde\\foo\\bar\\")] + [InlineData("\\\\server\\foo\\", "\\\\server\\foo\\")] + [InlineData("//server/foo/", "\\\\server\\foo\\")] + [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] + [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] public void Windows_NormalizesToBackslash(string input, string expected) { @@ -38,7 +52,7 @@ public partial class FileSafetyTests { var result = "foo/bar".LocalizePath(); - Assert.NotNull(result); + Assert.False(string.IsNullOrEmpty(result)); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 285fdffd..34e969d4 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -85,6 +85,18 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C:_Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Linux_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + [Fact] public void Linux_Uses_Custom_Replacement() { @@ -109,6 +121,18 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C__Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Windows_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + [Fact] public void Windows_Replaces_ControlCharacters() { -- cgit v1.2.3 From 0e4af54cebd4adba3ef32d57f8dbc3920ad28228 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 May 2026 19:27:08 -0500 Subject: tests, strategy enum --- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ++ .../DownloadService/DeriveDestinationTests.cs | 610 +++++++++++++++++++++ 2 files changed, 659 insertions(+) create mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs (limited to 'src') 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 (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.Transfers; + +/// +/// Strategy for handling downloaded files with conflicting names. +/// +public enum DestinationConflictStrategy +{ + /// + /// Rename the new file by appending something. + /// + Rename = 0, + + /// + /// Overwrite the existing file. + /// + Overwrite = 1, +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs new file mode 100644 index 00000000..4da05b24 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -0,0 +1,610 @@ +namespace slskd.Tests.Unit.Transfers.Downloads; + +using System; +using System.IO; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Moq; +using slskd.Search; +using slskd.Transfers; +using slskd.Transfers.Downloads; +using Xunit; + +public partial class DownloadServiceTests +{ + public class DeriveDestination + { + [Fact] + public async Task Explicit_Destination_Takes_Precedence_Over_Subdirectory_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("explicit-dir", result); + } + + [Fact] + public async Task Explicit_Destination_Tokens_Are_Not_Expanded() + { + // explicit destination is sanitized but not token-substituted + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "{SOURCE_USERNAME}" } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("{SOURCE_USERNAME}", result); + } + + [Fact] + public async Task Explicit_Destination_Is_Always_Relative() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "/etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Explicit_Destination_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "../../../etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Explicit_Destination_Null_Byte_Replaced() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "down\0loads" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("down_loads", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Is_Substituted() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive() + { + var (service, _) = GetFixture("{source_username}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Theory] + [InlineData("al\\..\\ice")] + [InlineData("al/../ice")] + [InlineData("al\\../ice")] + [InlineData("al/..\\ice")] + public async Task SOURCE_USERNAME_Traversal_Segment_Periods_Remains_After_Replacing_Slashes_With_Underscore(string username) + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_.._ice", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename() + { + var (service, _) = GetFixture("{SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal(Path.Combine("@alice", "Music", "album"), result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("{SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory() + { + var (service, _) = GetFixture("{SOURCE_PATH}-{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("@alice-@alice", result); + } + + [Fact] + public async Task BATCH_ID_Is_Substituted_When_Batch_Exists() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId }; + var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(batchId.ToString(), result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("{BATCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_Batch_Id_Is_Empty_Guid() + { + var batch = new Batch { Id = Guid.Empty }; + var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = Guid.Empty }); + + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Substituted_When_Batch_Has_External_Id() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "my-ext-id" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("my-ext-id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Null() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Whitespace() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo/bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Backslash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\\bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Null_Byte_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\0bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(searchId.ToString(), result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_No_Batch() + { + // no batch → SearchId is never consulted + var (service, _) = GetFixture("{SEARCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_ID_Is_Empty_Guid() + { + var searchId = Guid.Empty; + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo bar baz" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo bar baz", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_No_Search() + { + var (service, _) = GetFixture("{SEARCH_TEXT}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo/bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Backlash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\\bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task Batch_With_Null_Options_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = null }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Batch_With_Whitespace_Destination_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}/downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Backslash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}\\downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Output_Is_Always_Relative() + { + var (service, _) = GetFixture("/etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Pattern_Traversal_Segments_Do_Not_Survive() + { + var (service, _) = GetFixture("../../../etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Username_Containing_Traversal_Is_Safe() + { + // exact '..' in username must not produce a traversal segment in the final output + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task SEARCH_TEXT_Null_Byte_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\0bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() + { + // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() + { + // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = " " }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Traversal_Segments_Do_Not_Survive() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "../evil" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Empty_String() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "../evil" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + } + + private static (DownloadService service, Mocks mocks) GetFixture( + string subdirectory = "{SOURCE_USERNAME}", + Batch batch = null, + Search search = null) + { + var mocks = new Mocks(subdirectory, batch, search); + var service = new DownloadService( + mocks.BatchService.Object, + mocks.SearchService.Object, + mocks.OptionsMonitor, + null, + new Mock>().Object, + null, + null, + null, + null); + return (service, mocks); + } + + private class Mocks + { + public Mocks(string subdirectory = null, Batch batch = null, Search search = null) + { + OptionsMonitor = new TestOptionsMonitor(new Options + { + Transfers = new Options.TransfersOptions + { + Download = new Options.TransfersOptions.GlobalDownloadOptions + { + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Subdirectory = subdirectory + } + } + } + }); + + BatchService.Setup(b => b.FindAsync(It.IsAny>>())) + .ReturnsAsync(batch); + SearchService.Setup(s => s.FindAsync(It.IsAny>>(), It.IsAny())) + .ReturnsAsync(search); + } + + public Mock BatchService { get; } = new(); + public Mock SearchService { get; } = new(); + public TestOptionsMonitor OptionsMonitor { get; } + } +} -- cgit v1.2.3 From 040a31783e874c88e0cd35859253e29e33830ecf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 May 2026 19:08:58 -0500 Subject: add destination options --- config/slskd.example.yml | 7 +++++- src/slskd/Core/Options.cs | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 367d8e4d..d295b964 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -39,7 +39,7 @@ # cidr: 0.0.0.0/0,::/0 # permissions: # file: -# mode: ~ # chmod syntax, e.g. 644, 777. not for Windows. +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # directories: # incomplete: ~ # downloads: ~ @@ -78,6 +78,11 @@ # attempts: 3 # delay: 5000 # initial time between retries, in milliseconds # max_delay: 60000 # maximum time between retries, in milliseconds +# destination: +# subdirectory: {SOURCE_DIRECTORY} +# conflict: rename # 'overwrite' or 'rename' +# permissions: +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index bac86ea2..8123404e 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1028,6 +1028,12 @@ namespace slskd [Validate] public RetryOptions Retry { get; init; } = new RetryOptions(); + /// + /// Gets download destination options. + /// + [Validate] + public DestinationOptions Destination { get; init; } = new DestinationOptions(); + /// /// Download retry options. /// @@ -1057,6 +1063,63 @@ namespace slskd [Enum(typeof(RetryPartialStrategy))] public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } + + /// + /// Download destination options. + /// + public class DestinationOptions + { + /// + /// Gets the destination subdirectory for the files in the batch. + /// + [RelativePath] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; + + /// + /// Gets the strategy for handling conflicting filenames on disk. + /// + [Enum(typeof(DestinationConflictStrategy))] + public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant(); + + /// + /// Gets the permissions to apply to downloaded files and directories. + /// + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + /// + /// Download destination permission options. + /// + public class DestinationPermissionsOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + public string Mode { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + } } /// -- cgit v1.2.3 From 648ef46c787b0ebc96ae205a8b39b3cf5067dad2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 May 2026 19:11:13 -0500 Subject: implement subdirectory derivation --- src/slskd/Transfers/Downloads/DownloadService.cs | 208 ++++++++++++++++++++--- 1 file changed, 188 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 013e6a7a..b2435669 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; /// /// Manages downloads. @@ -67,6 +70,26 @@ namespace slskd.Transfers.Downloads /// void AddOrSupersede(Transfer transfer); + /// + /// Derives the destination subdirectory for the specified based on user and batch + /// configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the specified download doesn't exist. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + Task DeriveDestination(Transfer transfer); + /// /// Enqueues the requested list of . /// @@ -165,6 +188,7 @@ namespace slskd.Transfers.Downloads { public DownloadService( IBatchService batchService, + ISearchService searchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory 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 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(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -707,6 +734,144 @@ namespace slskd.Transfers.Downloads } } + /// + /// Derives the destination subdirectory for the specified based on user and + /// batch configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + public async Task DeriveDestination(Transfer transfer) + { + 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' + source_path = (Path.GetDirectoryName(filename) ?? string.Empty).TrimEnd('/', '\\'); + + // name of the remote parent directory, so using the example above, 'Baz' + source_directory = (Path.GetFileName(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( + 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, + }; + + // 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; + + // 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); + + Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", Path.GetFileName(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})", Path.GetFileName(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; + } + /// /// Returns a list of all downloads matching the optional . /// @@ -1045,14 +1210,21 @@ 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 + // 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. if the remote file + // changes size between attempts, Soulseek.NET's DownloadAsync() will throw, so the only real risk is + // in a case where the file contents have changed but the size remains. the resulting file will be + // corrupted in that case. users that are concerned about this (extremely unlikely) case should + // configure slskd to always overwrite partial files. var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); + baseDirectory: FileSafety.CombineSafely( + OptionsMonitor.CurrentValue.Directories.Incomplete, + FileSafety.SanitizeFilename(transfer.Username), + FileSafety.SanitizePath(transfer.Filename))); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1140,22 +1312,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 conflictStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Conflict.ToEnum(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1163,7 +1331,7 @@ namespace slskd.Transfers.Downloads sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: false, + overwrite: conflictStrategy == DestinationConflictStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); -- cgit v1.2.3 From a77a2d48c22b2287d8ad9125e0f9fa68f45def8b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:39:20 -0500 Subject: remove deprecated common extensions --- src/slskd/Common/CommonExtensions.cs | 28 +--------------------- src/slskd/Core/Options.cs | 8 +++---- src/slskd/Relay/RelayClient.cs | 2 +- .../Common/FileSafety/LocalizePathTests.cs | 6 ++--- 4 files changed, 9 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 4b327a1b..c37c1550 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -409,16 +409,6 @@ namespace slskd return path.Replace('/', '\\'); } - /// - /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). - /// - /// The path to convert. - /// The converted path. - public static string LocalizePath(this string path) - { - return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); - } - /// /// , but for paths normalized to use backslashes. /// @@ -455,7 +445,7 @@ namespace slskd } // normalize path separators - var localizedRemoteFilename = remoteFilename.LocalizePath(); + var localizedRemoteFilename = FileSafety.LocalizePath(remoteFilename); var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); @@ -470,22 +460,6 @@ namespace slskd return FileSafety.CombineSafely(directory, file); } - /// - /// Replaces any path traversal segments in the specified with the specified - /// . - /// - /// The path to sanitize. - /// The string with which to replace path traversal segments. - /// The sanitized path. - public static string ReplacePathTraversalSegments(this string path, string replacement = "_") - { - return string.Join(Path.DirectorySeparatorChar, - path - .LocalizePath() - .Split(Path.DirectorySeparatorChar) - .Select(s => s is "." or ".." ? replacement : s)); - } - /// /// Converts a ModelStateDictionary into a human-readable format. /// diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8123404e..6600cf76 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -832,22 +832,22 @@ namespace slskd var directories = Directories ?? Enumerable.Empty(); - 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."))); 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/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index 2df3e18f..160f2a72 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -22,7 +22,7 @@ public partial class FileSafetyTests [InlineData("", "")] public void Linux_NormalizesToForwardSlash(string input, string expected) { - var result = input.LocalizePath(OSPlatform.Linux); + var result = FileSafety.LocalizePath(input, OSPlatform.Linux); Assert.Equal(expected, result); } @@ -42,7 +42,7 @@ public partial class FileSafetyTests [InlineData("", "")] public void Windows_NormalizesToBackslash(string input, string expected) { - var result = input.LocalizePath(OSPlatform.Windows); + var result = FileSafety.LocalizePath(input, OSPlatform.Windows); Assert.Equal(expected, result); } @@ -50,7 +50,7 @@ public partial class FileSafetyTests [Fact] public void NullOs_UsesPlatformDefault_DoesNotThrow() { - var result = "foo/bar".LocalizePath(); + var result = FileSafety.LocalizePath("foo/bar"); Assert.False(string.IsNullOrEmpty(result)); } -- cgit v1.2.3 From ebf7c753f385c558cc1442609eaa17d2eb32e6da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:40:13 -0500 Subject: add get filename/directory name safely methods, overload sanitizefilename with sanitizePathRoot --- src/slskd/Common/FileSafety.cs | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index dc27a8b4..93a91faa 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -216,6 +216,54 @@ public static class FileSafety /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + /// + /// Returns the filename from the specified , properly + /// handling both forward and backslashes and removing invalid characters. + /// + /// The path from which to extract the filename. + /// An optional value indicating that invalid characters should not be replaced. + /// An optional operating system override, for testing. + /// The extracted filename. + /// Thrown if the specified path is null. + public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + { + ArgumentNullException.ThrowIfNull(path); + + return LocalizePath(path, os) + .Split(Path.DirectorySeparatorChar) + .TakeLast(1) + .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) + .Single(); + } + + /// + /// Returns the full directory name from the specified , properly handling both + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments and sanitizing + /// each of the remaining segments. + /// + /// The path from which to extract the directory name. + /// An optional value indicating that root segments should not be stripped. + /// An optional value indicating that path segments should not be sanitized. + /// An optional operating system override, for testing. + /// The directory name. + /// Thrown if the specified path is null. + public static string GetDirectoryNameSafely(string path, bool stripRoot = true, bool sanitize = true, OSPlatform? os = null) + { + ArgumentNullException.ThrowIfNull(path); + + var local = LocalizePath(path, os: os); + + if (stripRoot) + { + local = StripPathRoot(local); + } + + return string.Join(Path.DirectorySeparatorChar, local + .Split(Path.DirectorySeparatorChar) + .SkipLast(1) + .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); + } + /// /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). /// @@ -270,6 +318,21 @@ public static class FileSafety .Replace('\\', replacement); } + /// + /// Sanitizes the specified to make it suitable and safe on the local operating + /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified + /// . + /// + /// + /// This is an overload for that exists to improve understanding of intent at the + /// call site. + /// + /// The path segment. + /// 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) => SanitizeFilename(segment, replacement, os); + /// /// Sanitizes the specified 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 -- cgit v1.2.3 From 062d282403cc03c3fdd4101742647be6a83d0329 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:40:29 -0500 Subject: extract StripPathRoot --- src/slskd/Common/FileSafety.cs | 23 ++++ .../Common/FileSafety/StripPathRootTests.cs | 150 +++++++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 93a91faa..a175ebbd 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -365,4 +365,27 @@ public static class FileSafety return string.Join(sep, segments); } + + /// + /// Removes the root of the specified , including Window's drive prefix (e.g. C:\), + /// UNC paths on any OS (e.g. \\server on Windows, //server on Linux), and drops the hashed prefix added by + /// Soulseek Qt to hide the path on disk (e.g. @@abcde). + /// + /// 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) + { + // flip slashes the correct way + path = LocalizePath(path, os); + + // strip C:\ or //server, if present (regardless of slash variant) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + + return path; + } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs new file mode 100644 index 00000000..f3638c9e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -0,0 +1,150 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class StripPathRootTests + { + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.StripPathRoot("foo/bar"); + + Assert.NotNull(result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music/Artist")] + [InlineData("C:/Music/Artist", "Music/Artist")] + [InlineData("D:\\path\\to\\file", "path/to/file")] + [InlineData("Z:\\", "")] + [InlineData("Z:/", "")] + [InlineData("Z:", "")] // bare drive letter, no separator + [InlineData("c:\\Music", "Music")] // lowercase drive letter + [InlineData("A:/single", "single")] + public void Linux_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music\\Artist")] + [InlineData("C:/Music/Artist", "Music\\Artist")] + [InlineData("D:\\path\\to\\file", "path\\to\\file")] + [InlineData("Z:\\", "")] + [InlineData("Z:", "")] + [InlineData("c:\\Music", "Music")] + public void Windows_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "share/Music")] + [InlineData("//server/Music", "Music")] + [InlineData("//192.168.1.1/share/folder", "share/folder")] + [InlineData("//server", "")] // no path after server + public void Linux_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "share\\Music")] + [InlineData("\\\\server\\Music", "Music")] + [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] + [InlineData("\\\\server", "")] // no path after server + public void Windows_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "Music/Artist")] + [InlineData("@@abcdefgh/Music", "Music")] + [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] + public void Linux_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "Music\\Artist")] + [InlineData("@@abcdefgh\\Music", "Music")] + [InlineData("@@abcde/Music/Artist", "Music\\Artist")] + public void Windows_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abc/Music")] // only 3 alphanumeric chars — does not match + [InlineData("@@abcd/Music")] // only 4 — does not match + public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.StartsWith("@@", result); + } + + [Theory] + [InlineData("Music/Artist", "Music/Artist")] + [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("", "")] + [InlineData("foo", "foo")] + public void Linux_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Music\\Artist", "Music\\Artist")] + [InlineData("Artist\\Album\\song.flac", "Artist\\Album\\song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("foo", "foo")] + public void Windows_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/home/user/Music", "/home/user/Music")] + [InlineData("/Music", "/Music")] + [InlineData("/single", "/single")] + public void Linux_ReturnsUnchanged_Given_Single_ForwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\Music", "\\Music")] + [InlineData("\\home\\user", "\\home\\user")] + public void Windows_ReturnsUnchanged_Given_Single_BackwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} -- cgit v1.2.3 From 012b429f11d6c0247fa90a74c0367a112d45a84c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:00:35 -0500 Subject: add SanitizePathSegment --- src/slskd/Common/FileSafety.cs | 27 ++++-- .../Common/FileSafety/SanitizePathSegmentTests.cs | 99 ++++++++++++++++++++++ 2 files changed, 121 insertions(+), 5 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a175ebbd..7e8c3516 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,15 +323,32 @@ public static class FileSafety /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified /// . /// - /// - /// This is an overload for that exists to improve understanding of intent at the - /// call site. - /// /// The path segment. /// 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) => SanitizeFilename(segment, replacement, os); + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + { + var sanitized = SanitizeFilename(segment, replacement, os); + + // is is possible for the result of sanitization to produce path traversal strings, + // which would result in traversal when combined (or throw an error because of CombineSafely) + // this can happen either because the segment is already periods, or because the replacement + // character is a period and the input one or two invalid characters. + // if this happens we follow the principle of least surprise and return an empty string + // avoid using a period for replacement (don't let users choose) and we won't have this problem + if (sanitized is "." or "..") + { + if (replacement is '.') + { + return string.Empty; + } + + return replacement.ToString(); + } + + return sanitized; + } /// /// Sanitizes the specified to make it suitable and safe on the local operating system diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs new file mode 100644 index 00000000..72e6a21b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -0,0 +1,99 @@ +using System; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class SanitizePathSegmentTests + { + [Theory] + [InlineData('/')] + [InlineData('\\')] + public void Throws_Given_Slash_As_Replacement(char replacement) + { + var ex = Record.Exception(() => FileSafety.SanitizePathSegment("segment", replacement)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid in filenames", ex.Message); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Replaces_Traversal_Segments_With_Replacement(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal("_", s); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Returns_Empty_String_When_Replacement_Is_Period_And_Result_Would_Be_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '.'); + + Assert.Equal("", s); + } + + [Theory] + [InlineData("a.")] + [InlineData("..b")] + [InlineData("c..d")] + public void Preserves_Periods_In_Segment_If_Not_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal(input, s); + } + + [Fact] + public void Respects_Replacement_Character() + { + var s = FileSafety.SanitizePathSegment("???", replacement: '!'); + + Assert.Equal("!!!", s); + } + + [Theory] + [InlineData("clean", "clean")] + [InlineData("Artist - Album", "Artist - Album")] + [InlineData("Ünïcödé", "Ünïcödé")] + [InlineData("пользователь", "пользователь")] + public void Linux_ReturnsUnchanged_Given_Safe_Segment(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("has/slash", "has_slash")] + [InlineData("has\\backslash", "has_backslash")] + [InlineData("has/both\\types", "has_both_types")] + public void Linux_Replaces_Slashes(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("file:name", "file_name")] + [InlineData("file*name", "file_name")] + [InlineData("file?name", "file_name")] + [InlineData("file\"name", "file_name")] + [InlineData("file/name", "file_name")] + [InlineData("file\\name", "file_name")] + public void Windows_Replaces_InvalidCharacters(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} -- cgit v1.2.3 From 64db0b76b4a7f3242887d81b18414b8983a0d888 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:15:53 -0500 Subject: rename 'conflict' option to 'exists' --- config/slskd.example.yml | 2 +- src/slskd/Core/Options.cs | 6 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ---------------------- .../Transfers/Types/DestinationExistsStrategy.cs | 49 ++++++++++++++++++++++ 5 files changed, 55 insertions(+), 55 deletions(-) delete mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 src/slskd/Transfers/Types/DestinationExistsStrategy.cs (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index d295b964..b66879e3 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -80,7 +80,7 @@ # max_delay: 60000 # maximum time between retries, in milliseconds # destination: # subdirectory: {SOURCE_DIRECTORY} -# conflict: rename # 'overwrite' or 'rename' +# exists: rename # 'overwrite' or 'rename' # permissions: # mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6600cf76..4e7dca7b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1078,10 +1078,10 @@ namespace slskd public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; /// - /// Gets the strategy for handling conflicting filenames on disk. + /// Gets the strategy for handling existing files on disk. /// - [Enum(typeof(DestinationConflictStrategy))] - public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant(); + [Enum(typeof(DestinationExistsStrategy))] + public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); /// /// Gets the permissions to apply to downloaded files and directories. diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index b2435669..d09bb71b 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1323,7 +1323,7 @@ namespace slskd.Transfers.Downloads var subdirectory = await DeriveDestination(transfer); var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory); - var conflictStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Conflict.ToEnum(); + var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1331,7 +1331,7 @@ namespace slskd.Transfers.Downloads sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: conflictStrategy == DestinationConflictStrategy.Overwrite, + overwrite: existsStrategy == DestinationExistsStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); diff --git a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs deleted file mode 100644 index 27281a2d..00000000 --- a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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.Transfers; - -/// -/// Strategy for handling downloaded files with conflicting names. -/// -public enum DestinationConflictStrategy -{ - /// - /// Rename the new file by appending something. - /// - Rename = 0, - - /// - /// Overwrite the existing file. - /// - 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 (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.Transfers; + +/// +/// Strategy for handling downloaded files when the destination file already exists. +/// +public enum DestinationExistsStrategy +{ + /// + /// Rename the new file by appending something to the file name. + /// + Rename = 0, + + /// + /// Overwrite the existing file. + /// + Overwrite = 1, +} \ No newline at end of file -- cgit v1.2.3 From ba3d4690e132a966567db40c8b778c5ed3922833 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:24:27 -0500 Subject: paths ending in a slash don't have a file --- src/slskd/Common/FileSafety.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 7e8c3516..6c1ce8b6 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -229,6 +229,11 @@ public static class FileSafety { ArgumentNullException.ThrowIfNull(path); + if (path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } + return LocalizePath(path, os) .Split(Path.DirectorySeparatorChar) .TakeLast(1) -- cgit v1.2.3 From b52215184538991dfe1012c1017437edeb2e7b70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:24:50 -0500 Subject: remove the option to strip the root when getting directory --- src/slskd/Common/FileSafety.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 6c1ce8b6..acbe273b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -247,22 +247,16 @@ public static class FileSafety /// each of the remaining segments. /// /// The path from which to extract the directory name. - /// An optional value indicating that root segments should not be stripped. /// An optional value indicating that path segments should not be sanitized. /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool stripRoot = true, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool sanitize = true, OSPlatform? os = null) { ArgumentNullException.ThrowIfNull(path); var local = LocalizePath(path, os: os); - if (stripRoot) - { - local = StripPathRoot(local); - } - return string.Join(Path.DirectorySeparatorChar, local .Split(Path.DirectorySeparatorChar) .SkipLast(1) -- cgit v1.2.3 From 957dd89b04e941a17efb76dbfa439a2a0f5157ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:34:27 -0500 Subject: more tests, make root stripping optional --- src/slskd/Common/FileSafety.cs | 22 +++-- .../FileSafety/GetDirectoryNameSafelyTests.cs | 90 ++++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 96 ++++++++++++++++++++++ .../Common/FileSafety/SanitizePathTests.cs | 30 +++---- 4 files changed, 214 insertions(+), 24 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index acbe273b..dcdaa00a 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -269,7 +269,7 @@ public static class FileSafety /// The path to convert. /// An optional operating system override, for testing. /// The converted path. - public static string LocalizePath(this string path, OSPlatform? os = null) + public static string LocalizePath(string path, OSPlatform? os = null) { os ??= Compute.OSPlatform(); @@ -281,7 +281,7 @@ public static class FileSafety /// /// Sanitizes the specified (or string intended to be used as or as part of a filename) /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and - /// and replacing any invalid characters with the specified . + /// replacing any invalid characters with the specified . /// /// The filename (or string intended to be used as/part of one). /// The character to substitute for invalid characters. @@ -356,22 +356,26 @@ 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 operating system override, for testing. /// The sanitized path. - public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) { os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; // flip slashes the correct way - path = path.LocalizePath(os); + path = LocalizePath(path, os); - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = DriveRootRegex.Replace(path, string.Empty); - path = UncRootRegex.Replace(path, string.Empty); + if (!retainRoot) + { + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); - // strip @@abcde prefixes used by SoulseekQt to obscure paths - path = SoulseekQtRootRegex.Replace(path, string.Empty); + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs new file mode 100644 index 00000000..fd78fcaa --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -0,0 +1,90 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetDirectoryNameSafelyTests + { + [Fact] + public void Throws_Given_Null() + { + var ex = Record.Exception(() => FileSafety.GetDirectoryNameSafely(null)); + + Assert.NotNull(ex); + } + + [Fact] + public void Returns_Empty_Given_Empty() + { + var result = FileSafety.GetDirectoryNameSafely(""); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo.bar")] + public void Returns_Empty_Given_Bare_File(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("C:")] // bare drive letter — StripPathRoot removes it, nothing left + [InlineData("C:\\")] // drive root with trailing backslash + [InlineData("C:/")] // drive root with trailing forward slash + [InlineData("/")] // Unix-style root — no double-slash, not stripped; splits to ["", ""] + [InlineData("\\")] // single backslash root + [InlineData("//server")] // UNC root — StripPathRoot removes server, nothing left + [InlineData("\\\\server")] // UNC root, backslashes + public void Returns_Empty_Given_Root(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "Music\\Artist")] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + public void Returns_Directory_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters_In_Segments() + { + var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + + Assert.Equal("Music_\\Artist", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_In_Segments() + { + var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: false); + + Assert.Equal("Music*\\Artist", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac"); + var resultExplicit = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs new file mode 100644 index 00000000..a25da89b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -0,0 +1,96 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetFileNameSafelyTests + { + [Fact] + public void Throws_Given_Null() + { + var ex = Record.Exception(() => FileSafety.GetFileNameSafely(null)); + + Assert.NotNull(ex); + } + + [Fact] + public void Returns_Empty_Given_Empty() + { + var result = FileSafety.GetFileNameSafely(""); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("\\")] + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("//")] + [InlineData("\\\\")] + [InlineData("foo\\")] + [InlineData("foo//")] + [InlineData("C:\\foo//bar\\")] + [InlineData("C:/foo\\bar/")] + public void Returns_Empty_Given_Path_Ending_In_Separator(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("//server", "server")] + [InlineData("\\\\server", "server")] + public void Returns_LastSegment_Given_UncRoot(string input, string expected) + { + // StripPathRoot is not called; the last segment of the localized + split path is returned + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo", "foo")] + [InlineData("foo.bar", "foo.bar")] + [InlineData("foo\\bar", "bar")] + [InlineData("foo/bar", "bar")] + [InlineData("C:\\Music\\song.flac", "song.flac")] + [InlineData("C:/Music/song.flac", "song.flac")] + [InlineData("Music\\Artist\\song.flac", "song.flac")] + [InlineData("//server/share/song.flac", "song.flac")] + [InlineData("\\\\server\\share\\song.flac", "song.flac")] + public void Returns_Filename_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false); + + Assert.Equal("file:name.flac", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac"); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index ea5b8538..2f712334 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -10,7 +10,7 @@ public partial class FileSafetyTests [Fact] public void NullOs_UsesPlatformDefault_DoesNotThrow() { - var result = "foo/bar".SanitizePath(); + var result = FileSafety.SanitizePath("foo/bar"); Assert.NotNull(result); } @@ -22,7 +22,7 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/пользователь", "Ünïcödé/пользователь")] public void Linux_NormalizesSlashes(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -33,7 +33,7 @@ public partial class FileSafetyTests [InlineData("Artist/Album/song.flac", "Artist\\Album\\song.flac")] public void Windows_NormalizesSlashes(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -45,7 +45,7 @@ public partial class FileSafetyTests [InlineData("Z:\\", "")] public void Windows_Strips_DriveRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -56,7 +56,7 @@ public partial class FileSafetyTests [InlineData("D:\\path", "path")] public void Linux_Strips_DriveRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -67,7 +67,7 @@ public partial class FileSafetyTests [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] public void Windows_Strips_UncRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -78,7 +78,7 @@ public partial class FileSafetyTests [InlineData("//192.168.1.1/share/folder", "share/folder")] public void Linux_Strips_UncRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -89,7 +89,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] public void Linux_Strips_SoulseekQtPrefix(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -100,7 +100,7 @@ public partial class FileSafetyTests [InlineData("@@abcde/Music/Artist", "Music\\Artist")] public void Windows_Strips_SoulseekQtPrefix(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -110,7 +110,7 @@ public partial class FileSafetyTests [InlineData("@@abcd/Music")] // only 4 — does not match public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.StartsWith("@@", result); } @@ -124,7 +124,7 @@ public partial class FileSafetyTests [InlineData("foo/.", "foo/_")] public void Linux_Replaces_TraversalSegments(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -135,7 +135,7 @@ public partial class FileSafetyTests [InlineData("..\\etc", "_\\etc")] public void Windows_Replaces_TraversalSegments(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -143,7 +143,7 @@ public partial class FileSafetyTests [Fact] public void Linux_Replaces_InvalidFilenameChars_In_Segments() { - var result = "seg\0ment/file\0name".SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OSPlatform.Linux); Assert.Equal("seg_ment/file_name", result); } @@ -151,7 +151,7 @@ public partial class FileSafetyTests [Fact] public void Windows_Replaces_InvalidFilenameChars_In_Segments() { - var result = "seg*ment\\file:name".SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OSPlatform.Windows); Assert.Equal("seg_ment\\file_name", result); } @@ -159,7 +159,7 @@ public partial class FileSafetyTests [Fact] public void Uses_Custom_Replacement() { - var result = "foo/../bar".SanitizePath(replacement: '-', os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OSPlatform.Linux); Assert.Equal("foo/-/bar", result); } -- cgit v1.2.3 From bebeb114426e717596b1cf485e358eae65cb08e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:35:15 -0500 Subject: use full sanitized path for incomplete files --- src/slskd/Transfers/Downloads/DownloadService.cs | 55 +++++++++++++++++------- 1 file changed, 39 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d09bb71b..ee7f2efd 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -802,11 +802,13 @@ namespace slskd.Transfers.Downloads var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_'); - // full remote path, e.g. '@abcd\Foo\Bar\Baz\Qux.ext' => '@abcd\Foo\Bar\Baz' - source_path = (Path.GetDirectoryName(filename) ?? string.Empty).TrimEnd('/', '\\'); + // 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) ?? string.Empty).TrimEnd('/', '\\'); // name of the remote parent directory, so using the example above, 'Baz' - source_directory = (Path.GetFileName(source_path) ?? string.Empty).TrimEnd('/', '\\'); + source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString(); @@ -859,13 +861,13 @@ namespace slskd.Transfers.Downloads destination = FileSafety.SanitizePath(destination); - Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", Path.GetFileName(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); + 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})", Path.GetFileName(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); + 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."); } @@ -1214,17 +1216,38 @@ namespace slskd.Transfers.Downloads ? 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. if the remote file - // changes size between attempts, Soulseek.NET's DownloadAsync() will throw, so the only real risk is - // in a case where the file contents have changed but the size remains. the resulting file will be - // corrupted in that case. users that are concerned about this (extremely unlikely) case should - // configure slskd to always overwrite partial files. - var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely( - OptionsMonitor.CurrentValue.Directories.Incomplete, - FileSafety.SanitizeFilename(transfer.Username), - FileSafety.SanitizePath(transfer.Filename))); + /* + 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: + + /// + + 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); + + var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); + + Log.Warning("Incomplete file for {Filename} from {Username} will be: {Filename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; -- cgit v1.2.3 From 3003f80c16af1d551b9d6e484c566c7d69c061a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:52:50 -0500 Subject: make slskqt regex slash optional --- src/slskd/Common/FileSafety.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index dcdaa00a..479f7834 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -62,7 +62,7 @@ public static class FileSafety private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants - private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]?", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix /// /// An alternative to that disallows rooted segments in the second or -- cgit v1.2.3 From 058b02ea093f4d7867441d055bef2b857eb98dd0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:54:01 -0500 Subject: always split by both slashes --- src/slskd/Common/FileSafety.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 479f7834..ebd9a69c 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -130,7 +130,7 @@ public static class FileSafety } } - var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); + var parts = segment.Split('\\', '/'); // ensure the segments we're combining don't contain traversal segments "." or ".." // untrusted input could use this to "break out" of the root directory and access sensitive areas @@ -234,8 +234,7 @@ public static class FileSafety return null; } - return LocalizePath(path, os) - .Split(Path.DirectorySeparatorChar) + var segments = localPath.Split('/', '\\'); .TakeLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) .Single(); @@ -258,7 +257,7 @@ public static class FileSafety var local = LocalizePath(path, os: os); return string.Join(Path.DirectorySeparatorChar, local - .Split(Path.DirectorySeparatorChar) + .Split('/', '\\') .SkipLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); } @@ -379,7 +378,7 @@ public static class FileSafety // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path - .Split(sep) + .Split('/', '\\') .Select(s => SanitizeFilename(s, replacement, os)) .Select(s => s is "." or ".." ? replacement.ToString() : s); -- cgit v1.2.3 From 2926ef6ee1c9151d72ae9ab5d713630b299224ed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:54:32 -0500 Subject: use method instead of inline --- src/slskd/Common/FileSafety.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index ebd9a69c..011a7a70 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -369,11 +369,7 @@ public static class FileSafety if (!retainRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) - path = DriveRootRegex.Replace(path, string.Empty); - path = UncRootRegex.Replace(path, string.Empty); - - // strip @@abcde prefixes used by SoulseekQt to obscure paths - path = SoulseekQtRootRegex.Replace(path, string.Empty); + path = StripPathRoot(path); } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings -- cgit v1.2.3 From 3e52de31aad47a3a333c64ef1b68f8abcf726fe8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:55:07 -0500 Subject: fix GetFileNameSafely test cases --- src/slskd/Common/FileSafety.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 011a7a70..9c8fac74 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -224,17 +224,22 @@ 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. - /// Thrown if the specified path is null. public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) { - ArgumentNullException.ThrowIfNull(path); + if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } - if (path.EndsWith('/') || path.EndsWith('\\')) + if (StripPathRoot(path, os) == string.Empty) { return null; } + var localPath = LocalizePath(path, os); var segments = localPath.Split('/', '\\'); + + return segments .TakeLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) .Single(); @@ -254,7 +259,7 @@ public static class FileSafety { ArgumentNullException.ThrowIfNull(path); - var local = LocalizePath(path, os: os); + var local = LocalizePath(path, os); return string.Join(Path.DirectorySeparatorChar, local .Split('/', '\\') -- cgit v1.2.3 From 046c60b817144b46d82c4311d166e6ba78062a90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 17:48:57 -0500 Subject: i want to be done with this --- src/slskd/Common/FileSafety.cs | 60 ++++++-- .../Common/FileSafety/CombineSafelyTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 151 +++++++++++++++++---- .../Common/FileSafety/SanitizePathSegmentTests.cs | 2 +- 4 files changed, 180 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 9c8fac74..1fff4b08 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -241,7 +241,7 @@ public static class FileSafety return segments .TakeLast(1) - .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s) .Single(); } @@ -251,20 +251,63 @@ public static class FileSafety /// each of the remaining segments. /// /// The path from which to extract the directory name. + /// An optional value indicating whether to keep the path's root, if present. /// An optional value indicating that path segments should not be sanitized. /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) { - ArgumentNullException.ThrowIfNull(path); + if (path is null or "") + { + return null; + } + + // a plain string is assumed to be a file. matches the behavior of the BCL method + if (!path.Contains('/') && !path.Contains('\\')) + { + return null; + } + + var isUNC = path.StartsWith("//") || path.StartsWith("\\\\"); + + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + var local = LocalizePath(path, os) + .TrimEnd('/', '\\'); // treat file-less paths the same as files + + var unrooted = StripPathRoot(local, os); - var local = LocalizePath(path, os); + // were given a root; C:\, //server, @@abcde + if (unrooted is null or "") + { + return null; + } + + if (!retainRoot) + { + local = unrooted; + } - return string.Join(Path.DirectorySeparatorChar, local + // strip empty segments + var segments = local .Split('/', '\\') + .Where(s => s is not "") + .ToArray(); + + // we were given all slashes, a file in the root, or some other case where + // only a file or subdirectory remains; no parent directory + if (segments.Length <= 1) + { + return null; + } + + var newPath = string.Join(sep, segments .SkipLast(1) - .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); + + return (retainRoot && isUNC) ? $"{sep}{sep}{newPath}" : newPath; } /// @@ -276,7 +319,6 @@ public static class FileSafety public static string LocalizePath(string path, OSPlatform? os = null) { os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); @@ -380,8 +422,8 @@ public static class FileSafety // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split('/', '\\') - .Select(s => SanitizeFilename(s, replacement, os)) - .Select(s => s is "." or ".." ? replacement.ToString() : s); + .Where(s => s is not "") + .Select(s => SanitizePathSegment(s, replacement, os)); return string.Join(sep, segments); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 2d496c4b..0ffa0129 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -103,6 +103,9 @@ public partial class FileSafetyTests [InlineData("用户/音乐")] [InlineData("ユーザー/音楽")] [InlineData("사용자/음악")] + [InlineData("foo\\bar\\baz\\qux\\deeply\\nested")] + [InlineData("foo/bar/baz/qux/deeply/nested")] + [InlineData("foo/bar\\baz/qux\\deeply/nested")] public void Combines_Safe_Segments(string segment) { var result = FileSafety.CombineSafely(Base, segment); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index fd78fcaa..07e4d485 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using Xunit; namespace slskd.Tests.Unit.Common; @@ -7,29 +8,29 @@ public partial class FileSafetyTests public class GetDirectoryNameSafelyTests { [Fact] - public void Throws_Given_Null() + public void Returns_Null_Given_Null() { - var ex = Record.Exception(() => FileSafety.GetDirectoryNameSafely(null)); + var result = FileSafety.GetDirectoryNameSafely(null); - Assert.NotNull(ex); + Assert.Null(result); } [Fact] - public void Returns_Empty_Given_Empty() + public void Returns_Null_Given_Empty() { var result = FileSafety.GetDirectoryNameSafely(""); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] [InlineData("foo")] [InlineData("foo.bar")] - public void Returns_Empty_Given_Bare_File(string input) + public void Returns_Null_Given_Bare_File(string input) { var result = FileSafety.GetDirectoryNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] @@ -40,51 +41,149 @@ public partial class FileSafetyTests [InlineData("\\")] // single backslash root [InlineData("//server")] // UNC root — StripPathRoot removes server, nothing left [InlineData("\\\\server")] // UNC root, backslashes - public void Returns_Empty_Given_Root(string input) + public void Returns_Null_Given_Root(string input) { var result = FileSafety.GetDirectoryNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); + } + + [Fact] + public void Sanitizes_Path_When_Sanitize_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: true); + + Assert.DoesNotContain('\0', result); + } + + [Fact] + public void Does_Not_Sanitize_Path_When_Sanitize_False() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: false); + + Assert.Contains('\0', result); + } + + [Fact] + public void Sanitize_Defaults_To_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz"); + + Assert.DoesNotContain('\0', result); } [Theory] - [InlineData("foo\\bar", "foo")] + [InlineData("\\foo\\\\bar\\\\baz", "foo\\bar")] + [InlineData("/foo//bar//baz", "foo\\bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\foo\\\\bar\\\\baz", "foo/bar")] + [InlineData("/foo//bar//baz", "foo/bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] [InlineData("C:\\Music\\song.flac", "Music")] [InlineData("C:/Music/song.flac", "Music")] - [InlineData("C:\\Music\\Artist\\song.flac", "Music\\Artist")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic/Artist")] + [InlineData("C:\\foo.txt", null)] [InlineData("//server/share/song.flac", "share")] [InlineData("\\\\server\\share\\song.flac", "share")] - public void Returns_Directory_Given_Path_With_File(string input, string expected) + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); Assert.Equal(expected, result); } - [Fact] - public void Sanitize_True_Replaces_InvalidCharacters_In_Segments() + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic\\Artist")] + [InlineData("C:\\foo.txt", null)] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); - Assert.Equal("Music_\\Artist", result); + Assert.Equal(expected, result); } - [Fact] - public void Sanitize_False_Preserves_InvalidCharacters_In_Segments() + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C_\\Music")] + [InlineData("C:/Music/song.flac", "C_\\Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C_\\Music\\Artist")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\server\\share\\song.flac", "\\\\server\\share")] + [InlineData("@@abcde\\foo\\bar", "@@abcde\\foo")] + public void Retains_Path_Root_When_RetainRoot_True_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: false); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); - Assert.Equal("Music*\\Artist", result); + Assert.Equal(expected, result); } - [Fact] - public void Default_Sanitize_Is_True() + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C:/Music")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C:/Music/Artist")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\server\\share\\song.flac", "//server/share")] + [InlineData("@@abcde\\foo\\bar", "@@abcde/foo")] + public void Retains_Path_Root_When_RetainRoot_True_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:\\Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:\\Music")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\serv?er\\share\\song.flac", "\\\\serv?er\\share")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde\\fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde\\fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Windows(string input, string expected) { - var resultDefault = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac"); - var resultExplicit = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Windows); - Assert.Equal(resultExplicit, resultDefault); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:/Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\serv?er\\share\\song.flac", "//serv?er/share")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde/fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde/fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 72e6a21b..27dcf925 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -54,7 +54,7 @@ public partial class FileSafetyTests [Fact] public void Respects_Replacement_Character() { - var s = FileSafety.SanitizePathSegment("???", replacement: '!'); + var s = FileSafety.SanitizePathSegment("\0\0\0", replacement: '!'); Assert.Equal("!!!", s); } -- cgit v1.2.3 From cc5d80202e6f5973a0ce1bbdb30635392aa07ada Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 19:15:08 -0500 Subject: tweak root handling --- src/slskd/Common/FileSafety.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1fff4b08..650c082b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -247,7 +247,7 @@ public static class FileSafety /// /// Returns the full directory name from the specified , properly handling both - /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments and sanitizing + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing /// each of the remaining segments. /// /// The path from which to extract the directory name. @@ -269,7 +269,7 @@ public static class FileSafety return null; } - var isUNC = path.StartsWith("//") || path.StartsWith("\\\\"); + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -307,7 +307,12 @@ public static class FileSafety .SkipLast(1) .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); - return (retainRoot && isUNC) ? $"{sep}{sep}{newPath}" : newPath; + if (retainRoot) + { + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; } /// -- cgit v1.2.3 From 18ecfac2d8dc2b5c768cc7cc2dc61fa23259417c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 22:37:56 -0500 Subject: short circuit if a user has configured the root shortcut --- src/slskd/Transfers/Downloads/DownloadService.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ee7f2efd..48c29b19 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -753,6 +753,16 @@ namespace slskd.Transfers.Downloads /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. public async Task 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; @@ -841,10 +851,6 @@ namespace slskd.Transfers.Downloads ["SEARCH_TEXT"] = search_text, }; - // 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; - // 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( @@ -1247,7 +1253,7 @@ namespace slskd.Transfers.Downloads var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); - Log.Warning("Incomplete file for {Filename} from {Username} will be: {Filename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); + 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; -- cgit v1.2.3 From 7239327610f020dcb9028a845709c79a5567869d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jun 2026 18:33:17 -0500 Subject: gracefully handle nulls --- src/slskd/Common/FileSafety.cs | 22 +++++++++++++++++++++- .../FileSafety/GetDirectoryNameSafelyTests.cs | 2 +- .../Common/FileSafety/LocalizePathTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizeFilenameTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizePathTests.cs | 9 +++++++++ .../Common/FileSafety/StripPathRootTests.cs | 8 ++++++++ 7 files changed, 63 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 650c082b..9819209f 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,6 +323,11 @@ public static class FileSafety /// The converted path. public static string LocalizePath(string path, OSPlatform? os = null) { + if (path is null) + { + return null; + } + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -340,6 +345,11 @@ public static class FileSafety /// The sanitized filename. public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) { + if (filename is null) + { + return null; + } + if (replacement is '/' or '\\') { throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); @@ -412,6 +422,11 @@ public static class FileSafety /// The sanitized path. public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) { + if (path is null) + { + return null; + } + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -421,7 +436,7 @@ public static class FileSafety if (!retainRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path); + path = StripPathRoot(path, os); } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings @@ -443,6 +458,11 @@ public static class FileSafety /// The path with the root stripped, if one was present. public static string StripPathRoot(string path, OSPlatform? os = null) { + if (path is null) + { + return null; + } + // flip slashes the correct way path = LocalizePath(path, os); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index ff64e90d..3d89e9f5 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -112,7 +112,7 @@ public partial class FileSafetyTests [InlineData("\\\\server\\file.txt", "\\\\server")] [InlineData("@@abcde/file.txt", "@@abcde")] [InlineData("@@abcde\\file.txt", "@@abcde")] - public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) + public void Returns_Sanitized_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) { var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index 160f2a72..0b3eb81e 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -54,5 +54,13 @@ public partial class FileSafetyTests Assert.False(string.IsNullOrEmpty(result)); } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.LocalizePath(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 34e969d4..c0334d9b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -152,5 +152,13 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizeFilename(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 27dcf925..d322179b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -95,5 +95,13 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizePathSegment(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 2f712334..92a9e62c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -163,5 +163,14 @@ public partial class FileSafetyTests Assert.Equal("foo/-/bar", result); } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.SanitizePath(null); + + Assert.Null(result); + } + } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index f3638c9e..1ec2021d 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -15,6 +15,14 @@ public partial class FileSafetyTests Assert.NotNull(result); } + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.StripPathRoot(null); + + Assert.Null(result); + } + [Theory] [InlineData("C:\\Music\\Artist", "Music/Artist")] [InlineData("C:/Music/Artist", "Music/Artist")] -- cgit v1.2.3 From 16271c5f89dd6b8a5af4690fc2813285ce797dad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jun 2026 18:43:16 -0500 Subject: add leading slashes back when SanitizePath and retainRoot = true --- src/slskd/Common/FileSafety.cs | 13 ++- .../Common/FileSafety/SanitizePathTests.cs | 93 ++++++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 9819209f..5a5d964e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -309,6 +309,7 @@ public static class FileSafety if (retainRoot) { + // leading slashes are stripped of leading slashes by Split() so we must add them back return new string(sep, leadingSlashCount) + newPath; } @@ -427,6 +428,8 @@ public static class FileSafety return null; } + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -445,7 +448,15 @@ public static class FileSafety .Where(s => s is not "") .Select(s => SanitizePathSegment(s, replacement, os)); - return string.Join(sep, segments); + 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; } /// diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 92a9e62c..f36e53de 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -1,3 +1,4 @@ +using System; using System.Runtime.InteropServices; using Xunit; @@ -172,5 +173,97 @@ public partial class FileSafetyTests Assert.Null(result); } + // --- retainRoot: true --- + // These verify that SanitizePath honours retainRoot. The UNC and single-slash absolute + // cases are EXPECTED TO FAIL: SanitizePath filters empty segments produced by splitting on + // leading slashes, so "//server/share" becomes "server/share" — the root is silently lost. + // Drive-letter and @@-prefix cases pass because they produce no empty segments. + + + [Theory] + [InlineData("C:/Music/Artist", "C:/Music/Artist")] + [InlineData("C:\\Music\\Artist", "C:/Music/Artist")] + public void Linux_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "C_\\Music\\Artist")] + [InlineData("C:/Music/Artist", "C_\\Music\\Artist")] + public void Windows_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "@@abcde/Music/Artist")] + [InlineData("@@abcde\\Music\\Artist", "@@abcde/Music/Artist")] + public void Linux_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "@@abcde\\Music\\Artist")] + [InlineData("@@abcde/Music/Artist", "@@abcde\\Music\\Artist")] + public void Windows_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "//server/share/Music")] + [InlineData("//server/Music", "//server/Music")] + [InlineData("\\\\server\\share\\Music", "//server/share/Music")] + [InlineData("\\\\server\\Music", "//server/Music")] + public void Linux_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/absolute/Music", "/absolute/Music")] + [InlineData("/single", "/single")] + [InlineData("\\absolute\\Music", "/absolute/Music")] + [InlineData("\\single", "/single")] + public void Linux_RetainsAbsoluteRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "\\\\server\\share\\Music")] + [InlineData("\\\\server\\Music", "\\\\server\\Music")] + [InlineData("//server/share/Music", "\\\\server\\share\\Music")] + [InlineData("//server/Music", "\\\\server\\Music")] + public void Windows_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\absolute\\Music", "\\absolute\\Music")] + [InlineData("/absolute/Music", "\\absolute\\Music")] + public void Windows_RetainsDriveRelativeRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } } } -- cgit v1.2.3 From 0a30f1080595a877d8c4b30f796e7055302de2cc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 08:53:45 -0500 Subject: remove deprecated extension methods --- src/slskd/Common/CommonExtensions.cs | 46 ------ .../Extensions/ToLocalRelativeFilenameTests.cs | 160 --------------------- 2 files changed, 206 deletions(-) delete mode 100644 tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index c37c1550..95721163 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -381,21 +381,6 @@ namespace slskd .Build() .Deserialize(str); - /// - /// Converts a fully qualified remote filename to a local filename based in the provided - /// , 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). - /// - /// The fully qualified remote filename to convert. - /// The base directory for the local filename. - /// The converted filename. - [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()); - } - /// /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// @@ -429,37 +414,6 @@ namespace slskd return path.Split('\\').TakeLast(1).First(); } - /// - /// 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). - /// - /// The fully qualified remote filename to convert. - /// The converted filename. - [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 = FileSafety.LocalizePath(remoteFilename); - - var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); - - if (parts.Length == 1) - { - return FileSafety.SanitizeFilename(parts.First()); - } - - var file = FileSafety.SanitizeFilename(parts.Last()); - var directory = FileSafety.SanitizeFilename(parts.Reverse().Skip(1).Take(1).Single()); - - return FileSafety.CombineSafely(directory, file); - } - /// /// Converts a ModelStateDictionary into a human-readable format. /// diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs deleted file mode 100644 index 78539142..00000000 --- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs +++ /dev/null @@ -1,160 +0,0 @@ -namespace slskd.Tests.Unit.Common.Extensions -{ - using System; - using System.IO; - using System.Linq; - using Xunit; - - public class ToLocalRelativeFilenameTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("\t")] - public void Throws_ArgumentException_Given_Bad_Remote_Filename(string filename) - { - var ex = Record.Exception(() => filename.ToLocalRelativeFilename()); - - Assert.NotNull(ex); - Assert.IsType(ex); - } - - [Fact] - public void Returns_Last_Directory_And_Filename_From_Deep_Path() - { - var expected = "path" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"deeply\nested\path\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Returns_Just_Filename_If_No_Directory_Given() - { - Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Replaces_Invalid_Characters_In_Filename() - { - // Exclude backslash and forward slash — they act as segment separators in the input - // and would cause the dirty string to be split rather than treated as a filename. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - var dirtyName = new string(invalidChars); - var result = $@"a\b\{dirtyName}".ToLocalRelativeFilename(); - var filename = Path.GetFileName(result); - - Assert.All(invalidChars, c => - Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename")); - } - - [Fact] - public void Replaces_Invalid_Characters_In_Directory() - { - // Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so the full - // GetInvalidFileNameChars() set applies (excluding path separators, which split the input). - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - var dirtyName = new string(invalidChars); - var result = $@"a\{dirtyName}\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - - Assert.All(invalidChars, c => - Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory")); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_Individually() - { - // Tests each invalid filename char in isolation so that failures identify the exact - // offending character rather than only reporting that something in a concatenated - // string was not replaced. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\b\prefix{c}suffix.ext".ToLocalRelativeFilename(); - var filename = Path.GetFileName(result); - Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename"); - }); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_In_Directory_Individually() - { - // Tests each invalid filename char in the directory segment in isolation so that - // failures identify the exact offending character. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory"); - }); - } - - [Fact] - public void Returns_Last_Directory_And_Filename_From_Two_Segment_Path() - { - var expected = "dir" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"dir\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Handles_Forward_Slash_As_Segment_Separator() - { - // LocalizePath normalizes '/' to Path.DirectorySeparatorChar before splitting, - // so forward-slash paths must produce the same result as backslash paths. - var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; - Assert.Equal(expected, "a/b/c.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Handles_Mixed_Slash_Separators() - { - var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; - Assert.Equal(expected, @"a/b\c.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Preserves_Spaces_In_Filename() - { - // Spaces are valid in file names and must survive sanitization. - var expected = "dir" + Path.DirectorySeparatorChar + "file name.ext"; - Assert.Equal(expected, @"root\dir\file name.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Preserves_Spaces_In_Directory() - { - var expected = "my dir" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"root\my dir\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Directory_Segment_Contains_No_Characters_Invalid_For_Directory_Names() - { - // All GetInvalidFileNameChars() (minus separators) must be absent from the directory - // segment. Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so - // the full filename-invalid set applies. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - Assert.False(directory.Contains(c), $"Character U+{(int)c:X4} is invalid for directory names but was not replaced"); - }); - } - } -} \ No newline at end of file -- cgit v1.2.3 From c89de5d4bcb56202a6879d752a685a7fc81d2920 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 08:57:19 -0500 Subject: temporarily back out destination permissions --- config/slskd.example.yml | 2 -- src/slskd/Core/Options.cs | 37 ------------------------ src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- 3 files changed, 2 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index b66879e3..f616cd8a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -81,8 +81,6 @@ # destination: # subdirectory: {SOURCE_DIRECTORY} # exists: rename # 'overwrite' or 'rename' -# permissions: -# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 4e7dca7b..f2a78247 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1082,43 +1082,6 @@ namespace slskd /// [Enum(typeof(DestinationExistsStrategy))] public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); - - /// - /// Gets the permissions to apply to downloaded files and directories. - /// - [Validate] - public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); - - /// - /// Download destination permission options. - /// - public class DestinationPermissionsOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly created files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - public string Mode { get; init; } - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - 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; - } - } } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 48c29b19..85de28b0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1218,8 +1218,8 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode) - ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode() + UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; /* -- cgit v1.2.3 From e479f3a213d13cb8b165237a594bcb86b7462606 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 10:05:45 -0500 Subject: add informational log --- 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 85de28b0..9e240a7e 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1363,7 +1363,7 @@ namespace slskd.Transfers.Downloads 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) { -- cgit v1.2.3 From 78561f600754241efdf06c0fcee5ffdbdccda1b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 18:56:06 -0500 Subject: wip --- .../Common/Validation/AbsolutePathAttribute.cs | 36 +++++++++++++++++++--- .../Common/Validation/RelativePathAttribute.cs | 36 ++++++++++++++++++++-- src/slskd/Core/Options.cs | 8 ++--- 3 files changed, 69 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index eb1c9069..8ee486c5 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -40,16 +40,19 @@ namespace slskd.Validation /// public class AbsolutePathAttribute : ValidationAttribute { - public AbsolutePathAttribute() + public AbsolutePathAttribute(bool platformAgnostic = false) { + PlatformAgnostic = platformAgnostic; } - public AbsolutePathAttribute(OSPlatform? os = null) + public AbsolutePathAttribute(bool platformAgnostic = false, OSPlatform? os = null) { + PlatformAgnostic = platformAgnostic; OS = os; } public OSPlatform? OS { get; } + public bool PlatformAgnostic { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -57,9 +60,34 @@ namespace slskd.Validation { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path, os: OS)) + if (OS.HasValue) { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + if (!FileSafety.IsPathAbsolute(path, os: OS)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + } + else + { + if (!PlatformAgnostic) + { + if (!FileSafety.IsPathAbsolute(path, os: OS)) // this OS + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + } + 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."); + } + } } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f465ba98..a3a3d435 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -40,8 +40,9 @@ namespace slskd.Validation /// public class RelativePathAttribute : ValidationAttribute { - public RelativePathAttribute() + public RelativePathAttribute(bool platformAgnostic = false) { + PlatformAgnostic = platformAgnostic; } public RelativePathAttribute(OSPlatform? os = null) @@ -50,15 +51,44 @@ namespace slskd.Validation } public OSPlatform? OS { get; } + public bool PlatformAgnostic { 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.HasValue) + { + // this can only be exercised via unit tests; OSPlatform can't be passeed as an attribute argument + // so, this takes precedent over PlatformAgnostic + if (!FileSafety.IsPathRelative(path, os: OS)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + } + else { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + if (!PlatformAgnostic) + { + if (!FileSafety.IsPathRelative(path, os: null)) // this OS + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + } + else + { + if (!FileSafety.IsPathRelative(path, os: OSPlatform.Linux)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + + if (!FileSafety.IsPathRelative(path, os: OSPlatform.Windows)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + } } } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f2a78247..9ad1a626 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(platformAgnostic: true)] [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(platformAgnostic: true)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -1072,7 +1072,7 @@ namespace slskd /// /// Gets the destination subdirectory for the files in the batch. /// - [RelativePath] + [RelativePath(platformAgnostic: true)] [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(platformAgnostic: false)] [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } -- cgit v1.2.3 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 From e5d362836ce8892487864170abdc31fc032989c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 08:07:48 -0500 Subject: fix junk --- src/slskd/Common/FileSafety.cs | 5 ---- .../Common/Validation/RelativePathAttribute.cs | 31 ++-------------------- 2 files changed, 2 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index b72d3749..a07de6d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -176,11 +176,8 @@ public static class FileSafety return false; } - 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 @@ -200,8 +197,6 @@ 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('/')) { diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 62185a42..1bdbd4fb 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -83,38 +83,11 @@ namespace slskd.Validation // 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 - if (!FileSafety.IsPathRelative(path, os: OS)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } - else - { - if (!PlatformAgnostic) - { - if (!FileSafety.IsPathRelative(path, os: null)) // this OS - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } - else - { - if (!FileSafety.IsPathRelative(path, os: OSPlatform.Linux)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - - if (!FileSafety.IsPathRelative(path, os: OSPlatform.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."); } } return ValidationResult.Success; } } -} +} \ No newline at end of file -- cgit v1.2.3 From 483e37f64def66cecb01a8c471d35e2937178960 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 18:07:07 -0500 Subject: change how property injection impacts path validation --- src/slskd/Common/Validation/AbsolutePathAttribute.cs | 13 +------------ src/slskd/Common/Validation/RelativePathAttribute.cs | 13 +------------ 2 files changed, 2 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 9393e524..f2615315 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -58,20 +58,9 @@ namespace slskd.Validation { var path = value.ToString(); - // 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())) + 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."); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 1bdbd4fb..f691d4e5 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -59,20 +59,9 @@ namespace slskd.Validation { var path = value.ToString(); - // 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())) + if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } -- cgit v1.2.3 From fec423393232bc3b9b3a8b40ebeafb489c871e65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:24:26 -0500 Subject: don't strip roots or restore slashes --- src/slskd/Common/FileSafety.cs | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a07de6d1..73dd4b40 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -412,35 +412,26 @@ public static class FileSafety /// /// Sanitizes the specified 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 , and by dropping any path traversal segments. + /// by converting to the correct slashes, replacing any invalid characters with the specified + /// , and by dropping any path traversal segments. /// /// The path. /// The character to substitute for invalid characters. - /// 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 stripRoot = false, OperatingSystem? 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.OperatingSystem(); var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (stripRoot) - { - // 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 var segments = path .Split('/', '\\') @@ -449,13 +440,6 @@ public static class FileSafety var newPath = string.Join(sep, segments); - if (!stripRoot) - { - // 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; - } - return newPath; } -- cgit v1.2.3 From 40913d2f6d2b6bd6ef41e4531c6dc62da1fe2b5d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:24:43 -0500 Subject: remove deprecated arg --- 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 84753547..0f7805ba 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, replacement: '_', stripRoot: false); + 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 }); -- cgit v1.2.3 From ee41b93605a380480a5f7d826e7ae0602cd52de1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:52:37 -0500 Subject: wip --- src/slskd/Common/FileSafety.cs | 6 +- .../Common/FileSafety/CombineSafelyTests.cs | 38 +++++++++++ .../FileSafety/ContainsTraversalSegmentsTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 79 ++++++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 32 +++++++++ .../Common/FileSafety/IsPathTests.cs | 3 + .../Common/FileSafety/LocalizePathTests.cs | 4 ++ .../Common/FileSafety/SanitizeFilenameTests.cs | 16 +++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 1 + .../Common/FileSafety/SanitizePathTests.cs | 36 ++++++++++ .../Common/FileSafety/StripPathRootTests.cs | 18 +++++ 11 files changed, 234 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 73dd4b40..bf81da0e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -432,11 +432,13 @@ public static class FileSafety // flip slashes the correct way path = LocalizePath(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); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index ee5a69d8..c3b69b12 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -218,6 +218,44 @@ public partial class FileSafetyTests } } + [Fact] + public void Returns_Root_Given_Single_Empty_Segment() + { + var result = FileSafety.CombineSafely(Base, ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Returns_Root_Given_All_Empty_Segments() + { + var result = FileSafety.CombineSafely(Base, "", ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Handles_Root_With_Trailing_Separator() + { + var rootWithTrailing = Base + Path.DirectorySeparatorChar; + var result = FileSafety.CombineSafely(rootWithTrailing, "foo"); + + Assert.StartsWith(ExpectedStartsWith, result); + Assert.EndsWith("foo", result); + } + + [Theory] + [InlineData("./foo")] + [InlineData("../bar")] + [InlineData("foo/../bar")] + public void Throws_ArgumentException_Given_TraversingRoot_With_Os_Override(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root, OperatingSystem.Linux, "segment")); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + [Theory] // Bare traversal [InlineData("..")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs index 205c87c2..f0b1a394 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -106,6 +106,9 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/..hidden")] [InlineData("пользователь/...dir")] [InlineData("用户/..名前")] + // Segments that look like traversal but have surrounding whitespace — not exact matches + [InlineData(" . ")] + [InlineData(" .. ")] public void Path_DoesNotContainTraversal(string path) { Assert.False(FileSafety.ContainsTraversalSegments(path)); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index 3ac48efd..eaeaa29f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -45,6 +45,14 @@ public partial class FileSafetyTests Assert.Null(result); } + [Fact] + public void Returns_Null_Given_Whitespace_Only() + { + var result = FileSafety.GetDirectoryNameSafely(" "); + + Assert.Null(result); + } + [Theory] [InlineData("foo")] [InlineData("foo.bar")] @@ -192,6 +200,77 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo/bar")] + public void Treats_Trailing_Slash_As_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo\\bar")] + public void Treats_Trailing_Slash_As_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o/bar", "fo\0o")] + [InlineData("C:/Mu\0sic/song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo\0o")] + [InlineData("C:\\Mu\0sic\\song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo/../bar/file.txt", "foo/../bar")] + [InlineData("../etc/file.txt", "../etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\..\\bar\\file.txt", "foo\\..\\bar")] + [InlineData("..\\etc\\file.txt", "..\\etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcd/foo/bar/file.txt")] + public void Short_Qt_Prefix_Treated_As_Segment_Linux(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.StartsWith("@@abcd", result); + } + [Theory] [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs index 2af5321e..59ba2b54 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -138,6 +138,38 @@ public partial class FileSafetyTests Assert.Equal(input, result); } + [Theory] + [InlineData("foo/.")] + [InlineData("foo/..")] + [InlineData("foo\\..")] + public void Sanitize_True_Replaces_Traversal_As_Last_Path_Segment(string input) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: true); + + Assert.Equal("_", result); + } + + [Theory] + [InlineData("foo/.", ".")] + [InlineData("foo/..", "..")] + [InlineData("foo\\..", "..")] + public void Sanitize_False_Preserves_Traversal_As_Last_Path_Segment(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: false); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo//bar.flac", "bar.flac")] + [InlineData("foo\\\\bar.flac", "bar.flac")] + public void Returns_Filename_Given_Double_Separator(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + [Theory] [InlineData("@@abcde/song.flac", "song.flac")] [InlineData("@@abcde\\song.flac", "song.flac")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs index df81c8e2..771a1ea0 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -22,6 +22,9 @@ public partial class FileSafetyTests [InlineData("C:\\Users\\Ünïcödé\\Music")] [InlineData("C:\\Users\\пользователь\\Музыка")] [InlineData("C:\\Users\\用户\\音乐")] + // lowercase drive letters + [InlineData("c:\\Music")] + [InlineData("a:/path")] // UNC paths (\\ prefix) [InlineData("\\\\server\\share")] [InlineData("\\\\server\\share\\folder")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index a6909438..f0fc196c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -20,6 +20,8 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] + [InlineData("/", "/")] + [InlineData("\\", "/")] public void Linux_NormalizesToForwardSlash(string input, string expected) { var result = FileSafety.LocalizePath(input, OperatingSystem.Linux); @@ -40,6 +42,8 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] + [InlineData("/", "\\")] + [InlineData("\\", "\\")] public void Windows_NormalizesToBackslash(string input, string expected) { var result = FileSafety.LocalizePath(input, OperatingSystem.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 8985edd4..c53b95fc 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -153,6 +153,22 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Fact] + public void Linux_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file\0name", '.', OperatingSystem.Linux); + + Assert.Equal("file.name", result); + } + + [Fact] + public void Windows_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file*name", '.', OperatingSystem.Windows); + + Assert.Equal("file.name", result); + } + [Fact] public void Returns_Null_Given_Null() { diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 82a583c0..230c9a89 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -123,6 +123,7 @@ public partial class FileSafetyTests [Theory] [InlineData("*")] [InlineData("*?")] + [InlineData("*.")] // one invalid char + one period → ".." public void Windows_Returns_EmptyString_When_Period_Replacement_Produces_Traversal(string input) { var result = FileSafety.SanitizePathSegment(input, replacement: '.', os: OperatingSystem.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 12ebdefa..61233e44 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -129,5 +129,41 @@ public partial class FileSafetyTests Assert.False(result.StartsWith('/') || result.StartsWith('\\')); } + + [Fact] + public void Linux_NeverReturns_LeadingSlash_When_First_Segment_Sanitizes_To_Empty() + { + // '\0' replaced with '.' produces "." — SanitizePathSegment converts that to "" + // joining ["", "foo"] with '/' would yield "/foo" without a guard + var result = FileSafety.SanitizePath("\0/foo", replacement: '.', os: OperatingSystem.Linux); + + Assert.False(result.StartsWith('/') || result.StartsWith('\\')); + } + + [Theory] + [InlineData("../..")] + [InlineData("./.")] + public void Linux_Replaces_All_Traversal_Segments(string input) + { + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); + + Assert.Equal("_/_", result); + } + + [Fact] + public void Linux_Handles_SoulseekQt_Prefixed_Path() + { + var result = FileSafety.SanitizePath("@@abcde/foo/bar", os: OperatingSystem.Linux); + + Assert.Equal("@@abcde/foo/bar", result); + } + + [Fact] + public void Windows_Sanitizes_Colon_In_Drive_Like_Segment() + { + var result = FileSafety.SanitizePath("C:/Music/song.flac", os: OperatingSystem.Windows); + + Assert.Equal("C_\\Music\\song.flac", result); + } } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index 469f5335..d547843b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -121,6 +121,24 @@ public partial class FileSafetyTests Assert.StartsWith("@@", result); } + [Fact] + public void Linux_Strips_Bare_SoulseekQtPrefix_Returning_Empty() + { + var result = FileSafety.StripPathRoot("@@abcde", OperatingSystem.Linux); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("//")] + public void Linux_ReturnsUnchanged_Given_Slash_Only_Path(string input) + { + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); + + Assert.Equal(input, result); + } + [Theory] [InlineData("Music/Artist", "Music/Artist")] [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] -- cgit v1.2.3 From 62134e78472a51ef0becff9c0850f635933ab506 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:16:57 -0500 Subject: stop using any Path.* method, because they are all fucked up and untestable --- src/slskd/Common/FileSafety.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index bf81da0e..1634ca7a 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,15 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } + root = LocalizePath(root, os).TrimEnd('/').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) { @@ -139,11 +147,17 @@ public static class FileSafety } } - var combined = Path.Combine(root, Path.Combine(segments)); + segments = [.. segments + .Where(s => !string.IsNullOrEmpty(s)) + .Select(s => LocalizePath(s))]; + + var combined = string.Join(sep, [root, .. segments]); // 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))) + var expectedPrefix = root + sep; + + if (combined != root && !combined.StartsWith(expectedPrefix)) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } -- cgit v1.2.3 From 5ed58b906b98c0f1b06147ed4db18c9bc2f1ffdf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:18:18 -0500 Subject: small tweaks --- src/slskd/Common/FileSafety.cs | 14 ++++++---- .../Common/Validation/AbsolutePathAttribute.cs | 2 +- .../Common/Validation/RelativePathAttribute.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Common/FileSafety/CombineSafelyTests.cs | 32 +++------------------- .../Validation/RelativePathAttributeTests.cs | 2 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- .../DownloadService/DeriveDestinationTests.cs | 2 -- 8 files changed, 19 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1634ca7a..bf8302d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + root = root.TrimEnd('/').TrimEnd('\\'); if (segments.Length == 0) { @@ -148,16 +148,18 @@ public static class FileSafety } segments = [.. segments - .Where(s => !string.IsNullOrEmpty(s)) - .Select(s => LocalizePath(s))]; + .Where(s => !string.IsNullOrEmpty(s))]; var combined = string.Join(sep, [root, .. segments]); + if (combined.TrimEnd('/').TrimEnd('\\') == root.TrimEnd('/').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 - var expectedPrefix = root + sep; - - if (combined != root && !combined.StartsWith(expectedPrefix)) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index f2615315..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,7 +49,7 @@ namespace slskd.Validation OS = os; } - public OperatingSystem? OS { get; } + public OperatingSystem OS { get; } private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f691d4e5..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -63,7 +63,7 @@ namespace slskd.Validation { if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); } return ValidationResult.Success; @@ -72,7 +72,7 @@ namespace slskd.Validation // 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."); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0f7805ba..ad91ba2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -815,7 +815,7 @@ namespace slskd.Transfers.Downloads // 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) ?? string.Empty).TrimEnd('/', '\\'); + 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('/', '\\'); @@ -1249,7 +1249,7 @@ namespace slskd.Transfers.Downloads 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); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index c3b69b12..e40ce743 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -169,21 +169,9 @@ public partial class FileSafetyTests [InlineData("C:relative")] public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -201,21 +189,9 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/\\Music", result); } [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 8d1c16b3..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -130,7 +130,7 @@ public class RelativePathAttributeTests // Note: the implementation uses the same message for Current as for Any/All. // "on all operating systems" is misleading here since Current only validates // against the current (or injected) OS. - Assert.Equal("The Field field must be a relative path on all operating systems.", msg); + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); } [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 4d4e4969..370a722d 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -285,7 +285,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Equal("The Destination field must be a relative path on all operating systems.", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index 4da05b24..f35ff452 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -499,7 +499,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; @@ -513,7 +512,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; -- cgit v1.2.3 From 12cf9ad6b33ae29e9e7caea20b205fadd45798bf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:18:18 -0500 Subject: small tweaks --- src/slskd/Common/FileSafety.cs | 14 ++++++---- .../Common/Validation/AbsolutePathAttribute.cs | 2 +- .../Common/Validation/RelativePathAttribute.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Common/FileSafety/CombineSafelyTests.cs | 32 +++------------------- .../Validation/RelativePathAttributeTests.cs | 2 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 4 +-- .../DownloadService/DeriveDestinationTests.cs | 2 -- 8 files changed, 20 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1634ca7a..bf8302d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + root = root.TrimEnd('/').TrimEnd('\\'); if (segments.Length == 0) { @@ -148,16 +148,18 @@ public static class FileSafety } segments = [.. segments - .Where(s => !string.IsNullOrEmpty(s)) - .Select(s => LocalizePath(s))]; + .Where(s => !string.IsNullOrEmpty(s))]; var combined = string.Join(sep, [root, .. segments]); + if (combined.TrimEnd('/').TrimEnd('\\') == root.TrimEnd('/').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 - var expectedPrefix = root + sep; - - if (combined != root && !combined.StartsWith(expectedPrefix)) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index f2615315..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,7 +49,7 @@ namespace slskd.Validation OS = os; } - public OperatingSystem? OS { get; } + public OperatingSystem OS { get; } private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f691d4e5..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -63,7 +63,7 @@ namespace slskd.Validation { if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); } return ValidationResult.Success; @@ -72,7 +72,7 @@ namespace slskd.Validation // 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."); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0f7805ba..ad91ba2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -815,7 +815,7 @@ namespace slskd.Transfers.Downloads // 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) ?? string.Empty).TrimEnd('/', '\\'); + 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('/', '\\'); @@ -1249,7 +1249,7 @@ namespace slskd.Transfers.Downloads 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); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index c3b69b12..e40ce743 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -169,21 +169,9 @@ public partial class FileSafetyTests [InlineData("C:relative")] public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -201,21 +189,9 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/\\Music", result); } [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 8d1c16b3..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -130,7 +130,7 @@ public class RelativePathAttributeTests // Note: the implementation uses the same message for Current as for Any/All. // "on all operating systems" is misleading here since Current only validates // against the current (or injected) OS. - Assert.Equal("The Field field must be a relative path on all operating systems.", msg); + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); } [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 4d4e4969..f608467b 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -285,7 +285,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } @@ -300,7 +300,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index 4da05b24..f35ff452 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -499,7 +499,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; @@ -513,7 +512,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; -- cgit v1.2.3 From d35ac4573e2ac5817af3a2b9a6025d41959b9caf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 10:43:22 -0500 Subject: require dollar sign prefix for values to eliminate the need for single quotes --- config/slskd.example.yml | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- .../DownloadService/DeriveDestinationTests.cs | 98 +++++++++++----------- 3 files changed, 51 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f616cd8a..46ef6ec1 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -79,7 +79,7 @@ # delay: 5000 # initial time between retries, in milliseconds # max_delay: 60000 # maximum time between retries, in milliseconds # destination: -# subdirectory: {SOURCE_DIRECTORY} +# subdirectory: ${SOURCE_DIRECTORY} # options: SOURCE_USERNAME, SOURCE_PATH, SOURCE_DIRECTORY, BATCH_ID, BATCH_EXTERNAL_ID, SEARCH_ID, SEARCH_TEXT # exists: rename # 'overwrite' or 'rename' # groups: # default: diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ad91ba2c..c6892fc4 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -243,7 +243,7 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } - private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index f35ff452..fcf3c45a 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -20,7 +20,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("explicit-dir", result); @@ -31,11 +31,11 @@ public partial class DownloadServiceTests { // explicit destination is sanitized but not token-substituted var batchId = Guid.NewGuid(); - var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "{SOURCE_USERNAME}" } }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "${SOURCE_USERNAME}" } }; + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); - Assert.Equal("{SOURCE_USERNAME}", result); + Assert.Equal("${SOURCE_USERNAME}", result); } [Fact] @@ -74,7 +74,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Is_Substituted() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("alice", result); @@ -83,7 +83,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive() { - var (service, _) = GetFixture("{source_username}"); + var (service, _) = GetFixture("${source_username}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("alice", result); @@ -92,7 +92,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" }); Assert.Equal("al_ice", result); @@ -101,7 +101,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" }); Assert.Equal("al_ice", result); @@ -110,7 +110,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" }); Assert.Equal("al_ice", result); @@ -123,7 +123,7 @@ public partial class DownloadServiceTests [InlineData("al/..\\ice")] public async Task SOURCE_USERNAME_Traversal_Segment_Periods_Remains_After_Replacing_Slashes_With_Underscore(string username) { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" }); Assert.Equal("al_.._ice", result); @@ -132,7 +132,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash() { - var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); Assert.Equal("album", result); @@ -141,7 +141,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash() { - var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" }); Assert.Equal("album", result); @@ -150,7 +150,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root() { - var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); Assert.Equal(string.Empty, result); @@ -159,7 +159,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename() { - var (service, _) = GetFixture("{SOURCE_PATH}"); + var (service, _) = GetFixture("${SOURCE_PATH}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); Assert.Equal(Path.Combine("@alice", "Music", "album"), result); @@ -168,7 +168,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root() { - var (service, _) = GetFixture("{SOURCE_PATH}"); + var (service, _) = GetFixture("${SOURCE_PATH}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); Assert.Equal(string.Empty, result); @@ -177,7 +177,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory() { - var (service, _) = GetFixture("{SOURCE_PATH}-{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_PATH}-${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("@alice-@alice", result); @@ -188,7 +188,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId }; - var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal(batchId.ToString(), result); @@ -197,7 +197,7 @@ public partial class DownloadServiceTests [Fact] public async Task BATCH_ID_Is_Fallback_When_No_Batch() { - var (service, _) = GetFixture("{BATCH_ID}"); + var (service, _) = GetFixture("${BATCH_ID}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_batch_id", result); } @@ -206,7 +206,7 @@ public partial class DownloadServiceTests public async Task BATCH_ID_Is_Fallback_When_Batch_Id_Is_Empty_Guid() { var batch = new Batch { Id = Guid.Empty }; - var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = Guid.Empty }); Assert.Equal("unknown_batch_id", result); @@ -217,7 +217,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "my-ext-id" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("my-ext-id", result); @@ -226,7 +226,7 @@ public partial class DownloadServiceTests [Fact] public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch() { - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}"); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_batch_external_id", result); @@ -237,7 +237,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_batch_external_id", result); @@ -248,7 +248,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_batch_external_id", result); @@ -259,7 +259,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo/bar" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo_bar", result); @@ -270,7 +270,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\\bar" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo_bar", result); @@ -281,7 +281,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\0bar" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo_bar", result); @@ -294,7 +294,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "some query" }; - var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal(searchId.ToString(), result); @@ -304,7 +304,7 @@ public partial class DownloadServiceTests public async Task SEARCH_ID_Is_Fallback_When_No_Batch() { // no batch → SearchId is never consulted - var (service, _) = GetFixture("{SEARCH_ID}"); + var (service, _) = GetFixture("${SEARCH_ID}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_search_id", result); @@ -315,7 +315,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = null }; - var (service, _) = GetFixture("{SEARCH_ID}", batch: batch); + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_id", result); @@ -326,7 +326,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; - var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: null); + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: null); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_id", result); @@ -339,7 +339,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "some query" }; - var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_id", result); @@ -352,7 +352,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "foo bar baz" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo bar baz", result); @@ -361,7 +361,7 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_No_Search() { - var (service, _) = GetFixture("{SEARCH_TEXT}"); + var (service, _) = GetFixture("${SEARCH_TEXT}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_search_text", result); @@ -374,7 +374,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "foo/bar" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo_bar", result); @@ -387,7 +387,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "foo\\bar" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo_bar", result); @@ -398,7 +398,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = null }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("alice", result); @@ -409,7 +409,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("alice", result); @@ -418,7 +418,7 @@ public partial class DownloadServiceTests [Fact] public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output() { - var (service, _) = GetFixture("{SOURCE_USERNAME}/downloads"); + var (service, _) = GetFixture("${SOURCE_USERNAME}/downloads"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal(Path.Combine("alice", "downloads"), result); @@ -427,7 +427,7 @@ public partial class DownloadServiceTests [Fact] public async Task Pattern_Backslash_Separator_Preserved_In_Output() { - var (service, _) = GetFixture("{SOURCE_USERNAME}\\downloads"); + var (service, _) = GetFixture("${SOURCE_USERNAME}\\downloads"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal(Path.Combine("alice", "downloads"), result); @@ -455,7 +455,7 @@ public partial class DownloadServiceTests public async Task Username_Containing_Traversal_Is_Safe() { // exact '..' in username must not produce a traversal segment in the final output - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" }); Assert.False(FileSafety.ContainsTraversalSegments(result)); @@ -468,7 +468,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "foo\0bar" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("foo_bar", result); @@ -479,7 +479,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: null); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: null); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -490,7 +490,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = null }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -503,7 +503,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -516,7 +516,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = " " }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -529,7 +529,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "../evil" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.False(FileSafety.ContainsTraversalSegments(result)); @@ -540,7 +540,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_batch_external_id", result); @@ -551,7 +551,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "../evil" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.False(FileSafety.ContainsTraversalSegments(result)); @@ -559,7 +559,7 @@ public partial class DownloadServiceTests } private static (DownloadService service, Mocks mocks) GetFixture( - string subdirectory = "{SOURCE_USERNAME}", + string subdirectory = "${SOURCE_USERNAME}", Batch batch = null, Search search = null) { -- cgit v1.2.3 From 3740aaf2d59add87b87a88864ed459a94b925f5e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:47:26 -0500 Subject: add permissions to download.destination --- config/slskd.example.yml | 2 ++ src/slskd/Core/Options.cs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 46ef6ec1..475ac65a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -81,6 +81,8 @@ # destination: # subdirectory: ${SOURCE_DIRECTORY} # options: SOURCE_USERNAME, SOURCE_PATH, SOURCE_DIRECTORY, BATCH_ID, BATCH_EXTERNAL_ID, SEARCH_ID, SEARCH_TEXT # exists: rename # 'overwrite' or 'rename' +# permissions: +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e76f5d2f..6436a6d2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1082,6 +1082,43 @@ namespace slskd /// [Enum(typeof(DestinationExistsStrategy))] public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); + + /// + /// Gets the permissions to apply to downloaded files and directories. + /// + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + /// + /// Download destination permission options. + /// + public class DestinationPermissionsOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + public string Mode { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } } } -- cgit v1.2.3 From d2f1a0ca65b77cff7b5841df1bbaf3e3342c6df0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:49:09 -0500 Subject: deprecate old permissions and add a validation error to flag it --- src/slskd/Core/Options.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6436a6d2..7fb70fbb 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(); - /// - /// Gets permission options. - /// - [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; /// /// 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; -- cgit v1.2.3 From c1d14e53eab549922f02ae1adb811b2f5a7ec331 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:50:01 -0500 Subject: add missing $ --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e76f5d2f..29d37806 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1075,7 +1075,7 @@ namespace slskd [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] - public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; + public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}"; /// /// Gets the strategy for handling existing files on disk. -- cgit v1.2.3 From c1dd8157a683e2fb816ff0c5d06056cc0ac1e17a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:59:22 -0500 Subject: run chmod on directories --- src/slskd/Files/FileService.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src') 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 { -- cgit v1.2.3 From 0a5274bdeb39d8aa67161ff28382c2bab626f446 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 19:40:21 -0500 Subject: bump dependencies --- src/slskd/slskd.csproj | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'src') 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 @@ - - + + - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + - + - - - - - - - - + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + -- cgit v1.2.3 From ee655d70335939746a7c16f3bd9686c5e4cd2a88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 19:42:08 -0500 Subject: update ref --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c6892fc4..7c794e55 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1218,8 +1218,8 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - 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; /* -- cgit v1.2.3 From 596e6b9ee5a90384ee9c170986a9384fcd3e9f8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 22:18:57 -0500 Subject: update imports --- src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs | 2 +- src/slskd/Program.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') 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; /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d4baf276..22ad585a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -62,7 +62,7 @@ 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; -- cgit v1.2.3 From 69360f579b1c0679a34263290af475bba8c4060d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 22:19:13 -0500 Subject: update loki config --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 22ad585a..9b7cd75e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -67,6 +67,7 @@ namespace slskd 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; @@ -1236,7 +1237,7 @@ namespace slskd 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}")) + textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))) .WriteTo.Sink(new DelegatingSink(logEvent => { string message = default; -- cgit v1.2.3 From e71eade0131b16c01f77637088c1e44ee07b3af6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 22:40:41 -0500 Subject: conditional config of loki --- src/slskd/Program.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9b7cd75e..39c0d2ac 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1235,9 +1235,15 @@ namespace slskd retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), - config => config.GrafanaLoki( - OptionsAtStartup.Logger.Loki ?? string.Empty, - textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))) + config => + { + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) + { + config.GrafanaLoki( + OptionsAtStartup.Logger.Loki, + textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")); + } + }) .WriteTo.Sink(new DelegatingSink(logEvent => { string message = default; -- cgit v1.2.3 From 0145a4d87ebe474aba82e2ad136eb9f5d652cc12 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jun 2026 13:50:21 -0500 Subject: use the default message formatter for Loki (previous format prevented capture of properties) --- src/slskd/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 39c0d2ac..9a2914ea 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1008,6 +1008,7 @@ namespace slskd services.AddSwaggerGen(options => { options.DescribeAllParametersInCamelCase(); + options.CustomSchemaIds(type => type.FullName); options.SwaggerDoc("v0", new OpenApiInfo { Version = "v0", @@ -1217,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) @@ -1239,9 +1241,7 @@ namespace slskd { if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - config.GrafanaLoki( - OptionsAtStartup.Logger.Loki, - textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")); + config.GrafanaLoki(OptionsAtStartup.Logger.Loki); } }) .WriteTo.Sink(new DelegatingSink(logEvent => -- cgit v1.2.3