aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-05-31 21:17:39 -0500
committerJP Dillingham <jp@dillingham.me>2026-05-31 21:17:39 -0500
commita19fcd796c3acd497388daa0e38f5fa37bf511ee (patch)
tree9cff5b7e687da2bf5819164887edf7ae39adc4bb /src
parent845da6c1c95ed18ec88c93a48f0a04c539f28bc3 (diff)
parent9c8a0cdbb1bf86c1d313919b37446b22a353c7c3 (diff)
downloadslskd-a19fcd796c3acd497388daa0e38f5fa37bf511ee.tar.gz
Merge branch 'destination' of github.com:slskd/slskd into destination
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/CommonExtensions.cs28
-rw-r--r--src/slskd/Common/FileSafety.cs184
-rw-r--r--src/slskd/Core/Options.cs35
-rw-r--r--src/slskd/Relay/RelayClient.cs2
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs58
-rw-r--r--src/slskd/Transfers/Types/DestinationExistsStrategy.cs49
6 files changed, 285 insertions, 71 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
@@ -410,16 +410,6 @@ namespace slskd
}
/// <summary>
- /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar).
- /// </summary>
- /// <param name="path">The path to convert.</param>
- /// <returns>The converted path.</returns>
- public static string LocalizePath(this string path)
- {
- return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
- }
-
- /// <summary>
/// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
@@ -455,7 +445,7 @@ namespace slskd
}
// normalize path separators
- var localizedRemoteFilename = remoteFilename.LocalizePath();
+ var localizedRemoteFilename = FileSafety.LocalizePath(remoteFilename);
var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar);
@@ -471,22 +461,6 @@ namespace slskd
}
/// <summary>
- /// Replaces any path traversal segments in the specified <paramref name="path"/> with the specified
- /// <paramref name="replacement"/>.
- /// </summary>
- /// <param name="path">The path to sanitize.</param>
- /// <param name="replacement">The string with which to replace path traversal segments.</param>
- /// <returns>The sanitized path.</returns>
- 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));
- }
-
- /// <summary>
/// Converts a ModelStateDictionary into a human-readable format.
/// </summary>
/// <param name="dictionary">The ModelStateDictionary to format.</param>
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs
index 06fd340d..650c082b 100644
--- a/src/slskd/Common/FileSafety.cs
+++ b/src/slskd/Common/FileSafety.cs
@@ -43,7 +43,6 @@ using System.Text.RegularExpressions;
/// </summary>
public static class FileSafety
{
-
/// <summary>
/// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc).
/// </summary>
@@ -63,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
/// <summary>
/// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or
@@ -131,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
@@ -218,15 +217,113 @@ public static class FileSafety
public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os);
/// <summary>
+ /// Returns the filename from the specified <paramref name="path"/>, properly
+ /// handling both forward and backslashes and removing invalid characters.
+ /// </summary>
+ /// <param name="path">The path from which to extract the filename.</param>
+ /// <param name="sanitize">An optional value indicating that invalid characters should not be replaced.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The extracted filename.</returns>
+ public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null)
+ {
+ if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\'))
+ {
+ return null;
+ }
+
+ if (StripPathRoot(path, os) == string.Empty)
+ {
+ return null;
+ }
+
+ var localPath = LocalizePath(path, os);
+ var segments = localPath.Split('/', '\\');
+
+ return segments
+ .TakeLast(1)
+ .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)
+ .Single();
+ }
+
+ /// <summary>
+ /// Returns the full directory name from the specified <paramref name="path"/>, properly handling both
+ /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing
+ /// each of the remaining segments.
+ /// </summary>
+ /// <param name="path">The path from which to extract the directory name.</param>
+ /// <param name="retainRoot">An optional value indicating whether to keep the path's root, if present.</param>
+ /// <param name="sanitize">An optional value indicating that path segments should not be sanitized.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The directory name.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the specified path is null.</exception>
+ public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null)
+ {
+ 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 leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count();
+
+ 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);
+
+ // were given a root; C:\, //server, @@abcde
+ if (unrooted is null or "")
+ {
+ return null;
+ }
+
+ if (!retainRoot)
+ {
+ local = unrooted;
+ }
+
+ // 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 ? SanitizePathSegment(s, os: os) : s));
+
+ if (retainRoot)
+ {
+ return new string(sep, leadingSlashCount) + newPath;
+ }
+
+ return newPath;
+ }
+
+ /// <summary>
/// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar).
/// </summary>
/// <param name="path">The path to convert.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The converted path.</returns>
- public static string LocalizePath(this string path, OSPlatform? os = null)
+ public static string LocalizePath(string path, OSPlatform? os = null)
{
os ??= Compute.OSPlatform();
-
var sep = os.Value == OSPlatform.Windows ? '\\' : '/';
return path.Replace('\\', sep).Replace('/', sep);
@@ -235,7 +332,7 @@ public static class FileSafety
/// <summary>
/// Sanitizes the specified <paramref name="filename"/> (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 <paramref name="replacement"/>.
+ /// replacing any invalid characters with the specified <paramref name="replacement"/>.
/// </summary>
/// <param name="filename">The filename (or string intended to be used as/part of one).</param>
/// <param name="replacement">The character to substitute for invalid characters.</param>
@@ -272,35 +369,90 @@ public static class FileSafety
}
/// <summary>
+ /// Sanitizes the specified <paramref name="segment"/> 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
+ /// <paramref name="replacement"/>.
+ /// </summary>
+ /// <param name="segment">The path segment.</param>
+ /// <param name="replacement">The character to substitute for invalid characters.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The sanitized path segment.</returns>
+ 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;
+ }
+
+ /// <summary>
/// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system
/// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with
/// the specified <paramref name="replacement"/>, and by dropping any path traversal segments.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="replacement">The character to substitute for invalid characters.</param>
+ /// <param name="retainRoot">An optional value indicating whether to keep the path's root, if present.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The sanitized path.</returns>
- 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)
+ if (!retainRoot)
+ {
+ // strip C:\ or //server, if present (regardless of slash variant, etc)
+ path = StripPathRoot(path);
+ }
+
+ // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings
+ var segments = path
+ .Split('/', '\\')
+ .Where(s => s is not "")
+ .Select(s => SanitizePathSegment(s, replacement, os));
+
+ return string.Join(sep, segments);
+ }
+
+ /// <summary>
+ /// Removes the root of the specified <paramref name="path"/>, 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).
+ /// </summary>
+ /// <param name="path">The path to strip.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The path with the root stripped, if one was present.</returns>
+ 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);
- // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings
- var segments = path
- .Split(sep)
- .Select(s => SanitizeFilename(s, replacement, os))
- .Select(s => s is "." or ".." ? replacement.ToString() : s);
-
- return string.Join(sep, segments);
+ return path;
}
} \ No newline at end of file
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 298ea2c0..4e7dca7b 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -832,22 +832,22 @@ namespace slskd
var directories = Directories ?? Enumerable.Empty<string>();
- 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.")));
@@ -1069,26 +1069,39 @@ namespace slskd
/// </summary>
public class DestinationOptions
{
+ /// <summary>
+ /// Gets the destination subdirectory for the files in the batch.
+ /// </summary>
[RelativePath]
[NonTraversingPath]
[String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}";
- [Enum(typeof(DestinationConflictStrategy))]
- public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant();
+ /// <summary>
+ /// Gets the strategy for handling existing files on disk.
+ /// </summary>
+ [Enum(typeof(DestinationExistsStrategy))]
+ public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant();
+ /// <summary>
+ /// Gets the permissions to apply to downloaded files and directories.
+ /// </summary>
[Validate]
public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions();
+ /// <summary>
+ /// Download destination permission options.
+ /// </summary>
public class DestinationPermissionsOptions : IValidatableObject
{
- public string Mode { get; init; }
-
/// <summary>
- /// Extended validation.
+ /// Gets the permissions to apply to newly created files.
/// </summary>
- /// <param name="validationContext"></param>
- /// <returns></returns>
+ /// <remarks>
+ /// Applicable to non-Windows operating systems, only.
+ /// </remarks>
+ public string Mode { get; init; }
+
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
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/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index af7a4699..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();
@@ -818,7 +820,7 @@ namespace slskd.Transfers.Downloads
search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString();
search_text = FileSafety.SanitizeFilename(
- filename: search?.SearchText ?? "unknown_search_text",
+ filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText,
replacement: '_');
}
catch (Exception ex)
@@ -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,14 +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)));
+ /*
+ 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:
+
+ <incomplete directory>/<username>/<full path to file on remote client>/<filename>
+
+ 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;
@@ -1320,7 +1346,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<DestinationConflictStrategy>();
+ var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum<DestinationExistsStrategy>();
Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory);
@@ -1328,7 +1354,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/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 file="DestinationExistsStrategy.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ 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
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Strategy for handling downloaded files when the destination file already exists.
+/// </summary>
+public enum DestinationExistsStrategy
+{
+ /// <summary>
+ /// Rename the new file by appending something to the file name.
+ /// </summary>
+ Rename = 0,
+
+ /// <summary>
+ /// Overwrite the existing file.
+ /// </summary>
+ Overwrite = 1,
+} \ No newline at end of file