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 --- src/slskd/Core/Options.cs | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) (limited to 'src/slskd/Core') 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 a77a2d48c22b2287d8ad9125e0f9fa68f45def8b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:39:20 -0500 Subject: remove deprecated common extensions --- src/slskd/Common/CommonExtensions.cs | 28 +--------------------- src/slskd/Core/Options.cs | 8 +++---- src/slskd/Relay/RelayClient.cs | 2 +- .../Common/FileSafety/LocalizePathTests.cs | 6 ++--- 4 files changed, 9 insertions(+), 35 deletions(-) (limited to 'src/slskd/Core') 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 64db0b76b4a7f3242887d81b18414b8983a0d888 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:15:53 -0500 Subject: rename 'conflict' option to 'exists' --- config/slskd.example.yml | 2 +- src/slskd/Core/Options.cs | 6 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ---------------------- .../Transfers/Types/DestinationExistsStrategy.cs | 49 ++++++++++++++++++++++ 5 files changed, 55 insertions(+), 55 deletions(-) delete mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 src/slskd/Transfers/Types/DestinationExistsStrategy.cs (limited to 'src/slskd/Core') 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