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/slskd/Common/CommonExtensions.cs') 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 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/slskd/Common/CommonExtensions.cs') 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 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/slskd/Common/CommonExtensions.cs') 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 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/slskd/Common/CommonExtensions.cs') 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