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(-) 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 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(-) 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(-) 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(-) 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(+) 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 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 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 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(+) 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(-) 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 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(-) 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(-) 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(-) 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(-) 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(-) 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 cde3a504186aee5302d80e0ced3bef1949ec18fb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:55:21 -0500 Subject: tweaks --- .../Common/FileSafety/GetFileNameSafelyTests.cs | 54 ++++++++++++++-------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs index a25da89b..1f71dc76 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using Xunit; namespace slskd.Tests.Unit.Common; @@ -7,19 +8,19 @@ public partial class FileSafetyTests public class GetFileNameSafelyTests { [Fact] - public void Throws_Given_Null() + public void Returns_Null_Given_Null() { - var ex = Record.Exception(() => FileSafety.GetFileNameSafely(null)); + var result = FileSafety.GetFileNameSafely(null); - Assert.NotNull(ex); + Assert.Null(result); } [Fact] - public void Returns_Empty_Given_Empty() + public void Returns_Null_Given_Empty() { var result = FileSafety.GetFileNameSafely(""); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] @@ -33,22 +34,23 @@ public partial class FileSafetyTests [InlineData("foo//")] [InlineData("C:\\foo//bar\\")] [InlineData("C:/foo\\bar/")] - public void Returns_Empty_Given_Path_Ending_In_Separator(string input) + public void Returns_Null_Given_Path_Ending_In_Separator(string input) { var result = FileSafety.GetFileNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] - [InlineData("//server", "server")] - [InlineData("\\\\server", "server")] - public void Returns_LastSegment_Given_UncRoot(string input, string expected) + [InlineData("//server")] + [InlineData("\\\\server")] + [InlineData("C:")] + [InlineData("@@abcde")] + public void Returns_Null_Given_Just_Rooted_Path(string input) { - // StripPathRoot is not called; the last segment of the localized + split path is returned var result = FileSafety.GetFileNameSafely(input); - Assert.Equal(expected, result); + Assert.Null(result); } [Theory] @@ -69,26 +71,42 @@ public partial class FileSafetyTests } [Fact] - public void Sanitize_True_Replaces_InvalidCharacters() + public void Sanitize_True_Replaces_InvalidCharacters_On_Windows() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters_On_Linux() { - var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: true, os: OSPlatform.Linux); Assert.Equal("file_name.flac", result); } [Fact] - public void Sanitize_False_Preserves_InvalidCharacters() + public void Sanitize_False_Preserves_InvalidCharacters_On_Windows() { - var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false); + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false, os: OSPlatform.Windows); Assert.Equal("file:name.flac", result); } + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_On_Linux() + { + var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: false, os: OSPlatform.Linux); + + Assert.Equal("file\0name.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); + var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac", os: OSPlatform.Windows); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); Assert.Equal(resultExplicit, resultDefault); } -- 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(-) 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(-) 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 9c8a0cdbb1bf86c1d313919b37446b22a353c7c3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 19:21:49 -0500 Subject: more tests --- .../FileSafety/GetDirectoryNameSafelyTests.cs | 97 ++++++++++++++++++++-- 1 file changed, 90 insertions(+), 7 deletions(-) diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index 07e4d485..ff64e90d 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -23,6 +23,21 @@ public partial class FileSafetyTests Assert.Null(result); } + [Theory] + [InlineData("\\")] + [InlineData("\\\\")] + [InlineData("\\\\\\")] + [InlineData("/")] + [InlineData("//")] + [InlineData("///")] + [InlineData("/\\/\\\\//////\\")] + public void Returns_Null_Given_Only_Slashes(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Null(result); + } + [Theory] [InlineData("foo")] [InlineData("foo.bar")] @@ -34,13 +49,13 @@ public partial class FileSafetyTests } [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 + [InlineData("C:")] + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("/")] + [InlineData("\\")] + [InlineData("//server")] + [InlineData("\\\\server")] public void Returns_Null_Given_Root(string input) { var result = FileSafety.GetDirectoryNameSafely(input); @@ -48,6 +63,62 @@ public partial class FileSafetyTests Assert.Null(result); } + [Theory] + [InlineData("C:\\file.txt")] + [InlineData("C:/file.txt")] + [InlineData("//server/file.txt")] + [InlineData("\\\\server\\file.txt")] + [InlineData("@@abcde/file.txt")] + [InlineData("@@abcde\\file.txt")] + public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_False_Linux(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OSPlatform.Linux); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:\\file.txt")] + [InlineData("C:/file.txt")] + [InlineData("//server/file.txt")] + [InlineData("\\\\server\\file.txt")] + [InlineData("@@abcde/file.txt")] + [InlineData("@@abcde\\file.txt")] + public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_False_Windows(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OSPlatform.Windows); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:\\file.txt", "C:")] + [InlineData("C:/file.txt", "C:")] + [InlineData("//server/file.txt", "//server")] + [InlineData("\\\\server\\file.txt", "//server")] + [InlineData("@@abcde/file.txt", "@@abcde")] + [InlineData("@@abcde\\file.txt", "@@abcde")] + public void Returns_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\file.txt", "C_")] + [InlineData("C:/file.txt", "C_")] + [InlineData("//server/file.txt", "\\\\server")] + [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) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + [Fact] public void Sanitizes_Path_When_Sanitize_True() { @@ -101,6 +172,8 @@ public partial class FileSafetyTests [InlineData("C:\\foo.txt", null)] [InlineData("//server/share/song.flac", "share")] [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("/abs\0olute/path", "abs_olute")] + [InlineData("\\abs\0olute\\path", "abs_olute")] [InlineData("@@abcde\\foo\\bar", "foo")] public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Linux(string input, string expected) { @@ -118,6 +191,8 @@ public partial class FileSafetyTests [InlineData("C:\\foo.txt", null)] [InlineData("//server/share/song.flac", "share")] [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("/abs\0olute/path", "abs_olute")] + [InlineData("\\abs\0olute\\path", "abs_olute")] [InlineData("@@abcde\\foo\\bar", "foo")] public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Windows(string input, string expected) { @@ -134,6 +209,8 @@ public partial class FileSafetyTests [InlineData("C:\\Music\\Artist\\song.flac", "C_\\Music\\Artist")] [InlineData("//server/share/song.flac", "\\\\server\\share")] [InlineData("\\\\server\\share\\song.flac", "\\\\server\\share")] + [InlineData("/absolute/path", "\\absolute")] + [InlineData("\\absolute\\path", "\\absolute")] [InlineData("@@abcde\\foo\\bar", "@@abcde\\foo")] public void Retains_Path_Root_When_RetainRoot_True_Windows(string input, string expected) { @@ -150,6 +227,8 @@ public partial class FileSafetyTests [InlineData("C:\\Music\\Artist\\song.flac", "C:/Music/Artist")] [InlineData("//server/share/song.flac", "//server/share")] [InlineData("\\\\server\\share\\song.flac", "//server/share")] + [InlineData("/absolute/path", "/absolute")] + [InlineData("\\absolute\\path", "/absolute")] [InlineData("@@abcde\\foo\\bar", "@@abcde/foo")] public void Retains_Path_Root_When_RetainRoot_True_Linux(string input, string expected) { @@ -163,6 +242,8 @@ public partial class FileSafetyTests [InlineData("C:/Music/song.flac", "C:\\Music")] [InlineData("//server/share/song.flac", "\\\\server\\share")] [InlineData("\\\\serv?er\\share\\song.flac", "\\\\serv?er\\share")] + [InlineData("/abs\0olute/path", "\\abs\0olute")] + [InlineData("\\abs\0olute\\path", "\\abs\0olute")] [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) @@ -177,6 +258,8 @@ public partial class FileSafetyTests [InlineData("C:/Music/song.flac", "C:/Music")] [InlineData("//server/share/song.flac", "//server/share")] [InlineData("\\\\serv?er\\share\\song.flac", "//serv?er/share")] + [InlineData("/abs\0olute/path", "/abs\0olute")] + [InlineData("\\abs\0olute\\path", "/abs\0olute")] [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) -- cgit v1.2.3