From 7140111857675a5c6f43de3eac262e1683ec0b46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 5 Sep 2026 19:02:11 -0500 Subject: use EnumerateFiles when pruning --- src/slskd/Application.cs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 475e4288..8de4fe53 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1257,28 +1257,39 @@ namespace slskd RecurseSubdirectories = true, }; - var files = System.IO.Directory.GetFiles(directory, "*", options) - .Select(filename => Files.ResolveFileInfo(filename)) - .Where(file => file.LastAccessTimeUtc <= DateTime.UtcNow.AddMinutes(-age.Value)); - - Log.Debug("Found {Count} files of need of pruning", files.Count()); + var fileInfo = new DirectoryInfo(directory) + .EnumerateFiles("*", options) + .Where(file => + { + try + { + return file.LastWriteTimeUtc <= DateTime.UtcNow.AddMinutes(-age.Value); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to access file {File} during pruning: {Message}", file.Name, ex.Message); + return false; + } + }); - int errors = 0; + int errorCount = 0; + int fileCount = 0; - foreach (var file in files) + foreach (var file in fileInfo) { try { file.Delete(); + fileCount++; } catch (Exception ex) { - errors++; + errorCount++; Log.Warning(ex, "Failed to prune file {File}: {Message}", file, ex.Message); } } - Log.Debug("Pruning complete. Deleted: {Deleted}, Errors: {Errors}", files.Count() - errors, errors); + Log.Debug("Pruning complete. Deleted: {Deleted}, Errors: {Errors}", fileCount, errorCount); } catch (Exception ex) { -- cgit v1.2.3 From fbeb97958bafe339b470f41db2780d2db505427f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Sep 2026 14:03:08 -0500 Subject: add an overload of ResolveFileInfo accepting a FileInfo instance --- src/slskd/Files/FileService.cs | 87 +++++++++++++++++++++++++----------------- 1 file changed, 53 insertions(+), 34 deletions(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 62d17f20..8450ba48 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -67,42 +67,19 @@ namespace slskd.Files private IOptionsMonitor OptionsMonitor { get; } /// - /// Resolves an instance of for the specified , following + /// Resolves an instance of for the specified , following /// any symlinks that may be present to their final target. A non-null return value is guaranteed. /// - /// The fully qualified filename for which to resolve the FileInfo instance. + /// The FileInfo instance for which to follow symlinks. /// The resolved FileInfo instance. - /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the specified FileInfo is null. /// Thrown if the specified or linked file is restricted. /// Thrown if the specified or linked file can't be resolved for some reason. - public virtual FileInfo ResolveFileInfo(string filename) + public virtual FileInfo ResolveFileInfo(FileInfo info) { - ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); - - if (Path.GetFullPath(filename) != filename) - { - throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); - } - - if (FileSafety.ContainsTraversalSegments(filename)) - { - Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); - throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename)); - } - - FileInfo info; - - try - { - info = new FileInfo(filename); - } - catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) - { - throw new UnauthorizedException($"Access to the file '{filename}' was denied: {ex.Message}", ex); - } - catch (Exception ex) + if (info is null) { - throw new IOException($"Failed to access file '{filename}': {ex.Message}", ex); + throw new ArgumentException("The specified FileInfo is null", nameof(info)); } // if the above didn't throw we are guaranteed a valid instance of FileInfo regardless of whether @@ -130,23 +107,65 @@ namespace slskd.Files } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) { - throw new UnauthorizedException($"Access to the linked file '{filename}->{info.LinkTarget}' was denied: {ex.Message}", ex); + throw new UnauthorizedException($"Access to the linked file '{info.Name}->{info.LinkTarget}' was denied: {ex.Message}", ex); } catch (Exception ex) { - Log.Error(ex, "Failed to resolve FileInfo for linked file '{File}->{Link}': {Message}", filename, info.LinkTarget, ex.Message); - throw new IOException($"Failed to resolve FileInfo for linked file '{filename}->{info.LinkTarget}': {ex.Message}", ex); + Log.Error(ex, "Failed to resolve FileInfo for linked file '{File}->{Link}': {Message}", info.Name, info.LinkTarget, ex.Message); + throw new IOException($"Failed to resolve FileInfo for linked file '{info.Name}->{info.LinkTarget}': {ex.Message}", ex); } if (info is null) { - Log.Error("Resolved FileInfo for linked file '{File}->{Link}' was unexpectedly null", filename, info.LinkTarget); - throw new IOException($"An unexpected error was encountered while resolving FileInfo for linked file '{filename}->{info.LinkTarget}'"); + Log.Error("Resolved FileInfo for linked file '{File}->{Link}' was unexpectedly null", info.Name, info.LinkTarget); + throw new IOException($"An unexpected error was encountered while resolving FileInfo for linked file '{info.Name}->{info.LinkTarget}'"); } return info; } + /// + /// Resolves an instance of for the specified , following + /// any symlinks that may be present to their final target. A non-null return value is guaranteed. + /// + /// The fully qualified filename for which to resolve the FileInfo instance. + /// The resolved FileInfo instance. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the specified or linked file is restricted. + /// Thrown if the specified or linked file can't be resolved for some reason. + public virtual FileInfo ResolveFileInfo(string filename) + { + ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + if (Path.GetFullPath(filename) != filename) + { + throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); + } + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename)); + } + + FileInfo info; + + try + { + info = new FileInfo(filename); + } + catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) + { + throw new UnauthorizedException($"Access to the file '{filename}' was denied: {ex.Message}", ex); + } + catch (Exception ex) + { + throw new IOException($"Failed to access file '{filename}': {ex.Message}", ex); + } + + return ResolveFileInfo(info); + } + /// /// Deletes the specified . /// -- cgit v1.2.3 From f1771147eb2a217ff0992c343abb6019b60f4234 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Sep 2026 14:04:18 -0500 Subject: ensure share paths omit trailing slashes --- src/slskd/Shares/Types/Share.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs index eef8989d..5b16ccf0 100644 --- a/src/slskd/Shares/Types/Share.cs +++ b/src/slskd/Shares/Types/Share.cs @@ -71,6 +71,7 @@ namespace slskd.Shares /// public Share(string share) { + share = share.TrimEnd('/', '\\'); Raw = share; IsExcluded = share.StartsWith('-') || share.StartsWith('!'); -- cgit v1.2.3 From f70236b507fb54eff2460d056fcbfbee33a5a5d5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Sep 2026 12:04:21 -0500 Subject: add IsRootDirectoryOf and IsSubDirectoryOf to FileSafety --- src/slskd/Common/FileSafety.cs | 55 +++++ .../Common/FileSafety/IsRootDirectoryOfTests.cs | 245 +++++++++++++++++++++ .../Common/FileSafety/IsSubDirectoryOfTests.cs | 215 ++++++++++++++++++ 3 files changed, 515 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 6a6dea22..cb7991d2 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -232,6 +232,61 @@ public static class FileSafety /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); + /// + /// Indicates whether the specified is a subdirectory within (or is) the . + /// + /// The potential root path. + /// The path to check. + /// An optional operating system override, for testing. + /// A value indicating whether the specified path is a subdirectory of (or is) the root. + /// Thrown if the specified root is null, empty, or consists of only whitespace. + /// Thrown if the specified root or subdirectories are not absolute or contain traversal segments. + public static bool IsRootDirectoryOf(string root, string subDirectory, OperatingSystem? os = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(root); + + if (!IsPathAbsolute(root, os)) + { + throw new ArgumentException("Specified root path must be absolute"); + } + + if (ContainsTraversalSegments(root)) + { + throw new ArgumentException("Specified root path contains traversal segments"); + } + + if (!IsPathAbsolute(subDirectory, os)) + { + throw new ArgumentException("Specified subdirectory path must be absolute"); + } + + if (ContainsTraversalSegments(subDirectory)) + { + throw new ArgumentException("Specified subdirectory path contains traversal segments"); + } + + var stringComparison = StringComparison.Ordinal; + + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) + { + stringComparison = StringComparison.OrdinalIgnoreCase; + } + + return subDirectory.TrimEnd('/', '\\').Equals(root.TrimEnd('/', '\\'), stringComparison) || + subDirectory.StartsWith(root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar, stringComparison); + } + + /// + /// Indicates whether the specified is the parent path of (or is) the . + /// + /// The potential subdirectory. + /// The path to check. + /// An optional operating system override, for testing. + /// A value indicating whether the specified path is the parent of (or is) the subdirectory. + /// Thrown if the specified root is null, empty, or consists of only whitespace. + /// Thrown if the specified root or subdirectories are not absolute or contain traversal segments. + public static bool IsSubDirectoryOf(string subDirectory, string root, OperatingSystem? os = null) => IsRootDirectoryOf(root, subDirectory, os); + /// /// Returns the filename from the specified , properly /// handling both forward and backslashes and removing invalid characters. diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs new file mode 100644 index 00000000..f035f703 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs @@ -0,0 +1,245 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class IsRootDirectoryOfTests + { + [Fact] + public void Root_Null_Throws_ArgumentNullException() + { + string root = null; + + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo")); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Root_Empty_Or_Whitespace_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo")); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + public class Windows + { + [Theory] + [InlineData("foo")] + [InlineData("foo\\bar")] + [InlineData("foo/bar")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("C:\\foo\\..")] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + [InlineData("C:\\..")] + [InlineData("\\\\foo\\..")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo\\bar")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("C:\\foo", subdirectory, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("C:\\foo\\..")] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("C:\\foo", subdirectory, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("C:\\foo", "C:\\foo")] + [InlineData("C:\\FOO", "C:\\foo")] + [InlineData("C:\\foo", "C:\\FOO")] + [InlineData("\\\\foo\\bar", "\\\\foo\\bar")] + [InlineData("\\\\FOO\\bar", "\\\\foo\\BAR")] + public void Equal_Paths_Are_A_Case_Insensitive_Match(string root, string subdirectory) + { + Assert.True(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Windows)); + } + + // the character joining root and subdirectory is always the runtime OS separator + // (Path.DirectorySeparatorChar) regardless of the `os` override passed to force + // Windows-style absolute-path and case-sensitivity rules, so the expected result + // is computed from the actual runtime separator rather than hardcoded - this keeps + // the case correct on whichever OS the suite runs on, while still exercising both + // slash styles, mixed styles, drive letters, and UNC-style roots via inline data. + [Theory] + [InlineData("C:\\foo", "C:\\foo\\bar", '\\')] + [InlineData("C:\\foo", "C:\\foo/bar", '/')] + [InlineData("C:/foo", "C:/foo/bar", '/')] + [InlineData("C:/foo", "C:/foo\\bar", '\\')] + [InlineData("\\\\foo\\bar", "\\\\foo\\bar\\baz", '\\')] + [InlineData("\\\\foo\\bar", "\\\\foo\\bar/baz", '/')] + [InlineData("C:\\foo\\", "C:\\foo\\bar", '\\')] + [InlineData("C:\\foo/", "C:\\foo\\bar", '\\')] + public void Subdirectory_Match_Depends_On_Native_Separator_At_The_Boundary(string root, string subdirectory, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Windows)); + } + + [Theory] + [InlineData("C:\\foo", "C:\\foobar")] + [InlineData("C:\\foo\\bar", "C:\\foo")] + [InlineData("C:\\foo", "C:\\bar")] + [InlineData("C:\\foo\\bar", "C:\\foo\\baz")] + [InlineData("C:\\foo", "D:\\foo\\bar")] + [InlineData("\\\\foo\\bar", "\\\\foo\\barbaz")] + public void Non_Subdirectory_Returns_False(string root, string subdirectory) + { + Assert.False(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Windows)); + } + + [Fact] + public void StartsWith_Check_Is_Case_Insensitive() + { + var subdirectory = "C:\\FOO" + Path.DirectorySeparatorChar + "bar"; + + Assert.True(FileSafety.IsRootDirectoryOf("C:\\foo", subdirectory, OperatingSystem.Windows)); + } + } + + public class Linux + { + [Theory] + [InlineData("foo")] + [InlineData("foo/bar")] + [InlineData("foo\\bar")] + [InlineData("C:\\foo")] + [InlineData("\\\\foo\\bar")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("/foo/..")] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + [InlineData("/..")] + [InlineData("//foo/..")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo/bar")] + [InlineData("C:\\foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("/foo", subdirectory, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("/foo/..")] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("/foo", subdirectory, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("/foo", "/foo")] + [InlineData("//foo/bar", "//foo/bar")] + public void Equal_Paths_Match(string root, string subdirectory) + { + Assert.True(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Linux)); + } + + [Fact] + public void Equal_Paths_Different_Case_Do_Not_Match() + { + Assert.False(FileSafety.IsRootDirectoryOf("/FOO", "/foo", OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foo", "/foo/bar", '/')] + [InlineData("/foo", "/foo\\bar", '\\')] + [InlineData("//foo/bar", "//foo/bar/baz", '/')] + [InlineData("//foo/bar", "//foo/bar\\baz", '\\')] + [InlineData("/foo/", "/foo/bar", '/')] + [InlineData("/foo\\", "/foo/bar", '/')] + public void Subdirectory_Match_Depends_On_Native_Separator_At_The_Boundary(string root, string subdirectory, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foo", "/foobar")] + [InlineData("/foo/bar", "/foo")] + [InlineData("/foo", "/bar")] + [InlineData("/foo/bar", "/foo/baz")] + public void Non_Subdirectory_Returns_False(string root, string subdirectory) + { + Assert.False(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Linux)); + } + + [Fact] + public void StartsWith_Check_Is_Case_Sensitive() + { + var subdirectory = "/FOO" + Path.DirectorySeparatorChar + "bar"; + + Assert.False(FileSafety.IsRootDirectoryOf("/foo", subdirectory, OperatingSystem.Linux)); + } + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs new file mode 100644 index 00000000..2f5fe8ee --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs @@ -0,0 +1,215 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class IsSubDirectoryOfTests + { + // IsSubDirectoryOf(subdirectory, root) forwards to IsRootDirectoryOf(root, subdirectory), + // so `root` (the second parameter here) lands on IsRootDirectoryOf's first parameter and + // is the one validated with ArgumentNullException.ThrowIfNullOrWhiteSpace. + [Fact] + public void Root_Null_Throws_ArgumentNullException() + { + string root = null; + + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo", root)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Root_Empty_Or_Whitespace_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo", root)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + // subdirectory (the first parameter here) is never null-checked directly; it only fails + // the "must be absolute" check, so null/empty/whitespace all throw plain ArgumentException. + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Subdirectory_Null_Empty_Or_Whitespace_Throws_ArgumentException_Not_ArgumentNullException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + public class Windows + { + [Theory] + [InlineData("foo")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo\\bar", root, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("C:\\foo\\..")] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo\\bar", root, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("C:\\foo", "C:\\foo")] + [InlineData("C:\\FOO", "C:\\foo")] + [InlineData("C:\\foo", "C:\\FOO")] + public void Equal_Paths_Are_A_Case_Insensitive_Match(string subdirectory, string root) + { + Assert.True(FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Windows)); + } + + [Theory] + [InlineData("C:\\foo\\bar", "C:\\foo", '\\')] + [InlineData("C:\\foo/bar", "C:\\foo", '/')] + [InlineData("\\\\foo\\bar\\baz", "\\\\foo\\bar", '\\')] + [InlineData("\\\\foo\\bar/baz", "\\\\foo\\bar", '/')] + [InlineData("C:\\foo\\bar", "C:\\foo\\", '\\')] + public void Match_Depends_On_Native_Separator_At_The_Boundary(string subdirectory, string root, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Windows)); + } + + [Theory] + [InlineData("C:\\foobar", "C:\\foo")] + [InlineData("C:\\foo", "C:\\foo\\bar")] + [InlineData("C:\\bar", "C:\\foo")] + [InlineData("C:\\foo\\baz", "C:\\foo\\bar")] + public void Not_A_Child_Of_Root_Returns_False(string subdirectory, string root) + { + Assert.False(FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Windows)); + } + } + + public class Linux + { + [Theory] + [InlineData("foo")] + [InlineData("C:\\foo")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("/foo/bar", root, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("C:\\foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("/foo/bar", root, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Fact] + public void Equal_Paths_Match() + { + Assert.True(FileSafety.IsSubDirectoryOf("/foo", "/foo", OperatingSystem.Linux)); + } + + [Fact] + public void Equal_Paths_Different_Case_Do_Not_Match() + { + Assert.False(FileSafety.IsSubDirectoryOf("/FOO", "/foo", OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foo/bar", "/foo", '/')] + [InlineData("/foo\\bar", "/foo", '\\')] + [InlineData("//foo/bar/baz", "//foo/bar", '/')] + [InlineData("//foo/bar\\baz", "//foo/bar", '\\')] + public void Match_Depends_On_Native_Separator_At_The_Boundary(string subdirectory, string root, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foobar", "/foo")] + [InlineData("/foo", "/foo/bar")] + [InlineData("/bar", "/foo")] + [InlineData("/foo/baz", "/foo/bar")] + public void Not_A_Child_Of_Root_Returns_False(string subdirectory, string root) + { + Assert.False(FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Linux)); + } + } + } +} -- cgit v1.2.3 From 4fbd0d2a01c2cd225a0ecfb2b1dc4db47154923a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Sep 2026 12:06:37 -0500 Subject: add stripped down IsSubDirectoryOf inline in scanner --- src/slskd/Shares/ShareScanner.cs | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 7c93d437..e763438f 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -199,20 +199,14 @@ namespace slskd.Shares Log.Information("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; - // derive a list of all directories from all shares. skip hidden and system directories, as well as anything that - // can't be accessed due to security restrictions. it's necessary to enumerate these directories up front so we - // can deduplicate directories and apply exclusions - var unmaskedDirectories = Shares - .SelectMany(share => - { - try - { - var directories = System.IO.Directory.GetDirectories(share.LocalPath, "*", new EnumerationOptions() - { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, - IgnoreInaccessible = true, - RecurseSubdirectories = true, - }); + // note: there's a safer version of this in the FileSafety class that checks for traversal and navigates + // case sensitivity for different operating systems. this version is stripped down for speed, and because + // we're not dealing with untrusted data + static bool IsSubDirectoryOf(string subDirectory, string root, StringComparison stringComparison = StringComparison.OrdinalIgnoreCase) + { + return subDirectory.TrimEnd('/', '\\').Equals(root.TrimEnd('/', '\\'), stringComparison) || // subdirectory literally is the root + subDirectory.StartsWith(root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar, stringComparison); + } return directories.Where(directory => !filters.Any(filter => filter.IsMatch(directory))); } -- cgit v1.2.3 From 72385ba35cced320c7c0aba58d31c65784f505e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Sep 2026 12:06:59 -0500 Subject: refactor directory discovery logic to reduce memory overhead --- src/slskd/Shares/ShareScanner.cs | 69 +++++++++++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 15 deletions(-) diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index e763438f..4ce7ebb3 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -208,25 +208,64 @@ namespace slskd.Shares subDirectory.StartsWith(root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar, stringComparison); } - return directories.Where(directory => !filters.Any(filter => filter.IsMatch(directory))); - } - catch (Exception ex) + /* + derive a list of all subdirectories to scan by enumerating the subdirectories within each configured + share recursively, omitting any directory that matches a filter or that exists within an excluded share + + we don't enumerate excluded shares because 1) the exclusion is a subdirectory of another share and it + will be enumerated once already or 2) the exclusion is not a subdirectory of another share and we don't + want to enumerate its directories just to remove them all. this is probably obvious and kind of a worthless comment + */ + var unmaskedDirectories = new HashSet(StringComparer.OrdinalIgnoreCase); + var excludedDirectories = new HashSet(StringComparer.OrdinalIgnoreCase); + + var excludedPaths = Shares.Where(s => s.IsExcluded).Select(s => s.LocalPath).ToHashSet(); + + foreach (var share in Shares) + { + if (share.IsExcluded) + { + continue; + } + + try + { + var directories = Directory.EnumerateDirectories(share.LocalPath, "*", new EnumerationOptions() { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint, + IgnoreInaccessible = true, + RecurseSubdirectories = true, + }); - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + unmaskedDirectories.Add(share.LocalPath); - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + foreach (var directory in directories) + { + if (excludedPaths.Any(excludedPath => IsSubDirectoryOf(subDirectory: directory, root: excludedPath))) + { + excludedDirectories.Add(directory); + Log.Debug("Excluding directory {Directory} because it is a subdirectory of an excluded share", directory); + continue; + } + + if (filters.Any(f => f.IsMatch(directory))) + { + excludedDirectories.Add(directory); + Log.Debug("Excluding directory {Directory} because it matches one or more share filters", directory); + continue; + } + + unmaskedDirectories.Add(directory); + } + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + } + } - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Information("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count }); + Log.Information("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; var current = 0; -- cgit v1.2.3 From d5ee2dc6dbb01a9f5aaf98c3cfcd545d600e6f32 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Sep 2026 12:08:25 -0500 Subject: fix share resolution from directory --- src/slskd/Shares/ShareScanner.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 4ce7ebb3..a49003f4 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -286,6 +286,15 @@ namespace slskd.Shares foreach (var id in Enumerable.Range(0, WorkerCount)) { + // set up a function to reliably resolve the Share given a directory; users can define nested shares, + // so we need to sort to ensure the deepest-nested share is selected first + var sortedShares = Shares.OrderByDescending(s => s.LocalPath.Length); + + Share ResolveShareFromDirectory(string directory) + { + return sortedShares.First(share => IsSubDirectoryOf(subDirectory: directory, root: share.LocalPath)); + } + workers.Add(new ChannelReader( channel: channel, cancellationToken: cancellationToken, @@ -296,7 +305,7 @@ namespace slskd.Shares var addedFiles = 0; var filteredFiles = 0; - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + var share = ResolveShareFromDirectory(directory); repository.InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek(), timestamp); -- cgit v1.2.3 From 5d33e56bc35aa809b98bdf98e0b13e6c0dd04541 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Sep 2026 12:09:00 -0500 Subject: refactor file enumeration to reduce disk i/o --- src/slskd/Shares/ShareScanner.cs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index a49003f4..063dc0e4 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -315,29 +315,29 @@ namespace slskd.Shares { // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything // that can't be accessed due to security restrictions - var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() + var newFileInfos = new DirectoryInfo(directory).EnumerateFiles("*", new EnumerationOptions() { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint, IgnoreInaccessible = true, RecurseSubdirectories = false, }); - addedFiles = newFiles.Length; - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var originalFilename in newFiles) + foreach (var info in newFileInfos) { - var info = Files.ResolveFileInfo(originalFilename); - var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek()); - - if (filters.Any(filter => filter.IsMatch(originalFilename))) + if (filters.Any(filter => filter.IsMatch(info.FullName))) { filteredFiles++; continue; } - repository.InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp); + var file = SoulseekFileFactory.Create( + filename: info.FullName, + maskedFilename: info.FullName.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek()); + + repository.InsertFile(maskedFilename: file.Filename, originalFilename: info.FullName, touchedAt: info.LastWriteTimeUtc, file, timestamp); + addedFiles++; } } catch (Exception ex) -- cgit v1.2.3 From 032e31e2aa04a9d5a0ee2a3ebeb120a63e720854 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Sep 2026 12:19:04 -0500 Subject: move share resolution out of the loop --- src/slskd/Shares/ShareScanner.cs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 063dc0e4..af0b2181 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -272,6 +272,18 @@ namespace slskd.Shares var cached = 0; var filtered = 0; + // set up a function to reliably resolve the Share given a directory; users can define nested shares, + // so we need to sort to ensure the deepest-nested share is selected first + var sortedShares = Shares + .Where(s => !s.IsExcluded) + .OrderByDescending(s => s.LocalPath.Length) + .ToList(); + + Share ResolveShareFromDirectory(string directory) + { + return sortedShares.First(share => IsSubDirectoryOf(subDirectory: directory, root: share.LocalPath)); + } + // set up a channel to fan out for directory scanning var channel = Channel.CreateBounded(new BoundedChannelOptions(1000) { @@ -286,15 +298,6 @@ namespace slskd.Shares foreach (var id in Enumerable.Range(0, WorkerCount)) { - // set up a function to reliably resolve the Share given a directory; users can define nested shares, - // so we need to sort to ensure the deepest-nested share is selected first - var sortedShares = Shares.OrderByDescending(s => s.LocalPath.Length); - - Share ResolveShareFromDirectory(string directory) - { - return sortedShares.First(share => IsSubDirectoryOf(subDirectory: directory, root: share.LocalPath)); - } - workers.Add(new ChannelReader( channel: channel, cancellationToken: cancellationToken, -- cgit v1.2.3 From 5699bcf9fde961105b917350b720803c869566f2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Sep 2026 19:34:13 -0500 Subject: update counts in log message --- src/slskd/Shares/ShareScanner.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index af0b2181..84ea80e3 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -388,7 +388,7 @@ namespace slskd.Shares await Task.WhenAll(workers.Select(w => w.Completed)); Log.Debug("All workers finished"); - Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); + Log.Information("Scan found {Files} files, cached {Cached}, and filtered {Filtered} in {Elapsed}ms", cached + filtered, cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; var deletedFiles = repository.PruneFiles(olderThanTimestamp: timestamp); -- cgit v1.2.3