diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-31 21:17:39 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2026-05-31 21:17:39 -0500 |
| commit | a19fcd796c3acd497388daa0e38f5fa37bf511ee (patch) | |
| tree | 9cff5b7e687da2bf5819164887edf7ae39adc4bb | |
| parent | 845da6c1c95ed18ec88c93a48f0a04c539f28bc3 (diff) | |
| parent | 9c8a0cdbb1bf86c1d313919b37446b22a353c7c3 (diff) | |
| download | slskd-a19fcd796c3acd497388daa0e38f5fa37bf511ee.tar.gz | |
Merge branch 'destination' of github.com:slskd/slskd into destination
16 files changed, 1079 insertions, 91 deletions
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/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 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 new file mode 100644 index 00000000..ff64e90d --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -0,0 +1,272 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetDirectoryNameSafelyTests + { + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.GetDirectoryNameSafely(null); + + Assert.Null(result); + } + + [Fact] + public void Returns_Null_Given_Empty() + { + var result = FileSafety.GetDirectoryNameSafely(""); + + 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")] + public void Returns_Null_Given_Bare_File(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [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); + + 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() + { + 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\\\\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:\\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("/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) + { + 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:\\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("/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) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [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("/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) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [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("/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) + { + 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("/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) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Windows); + + 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("/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) + { + 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/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs new file mode 100644 index 00000000..1f71dc76 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -0,0 +1,114 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetFileNameSafelyTests + { + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.GetFileNameSafely(null); + + Assert.Null(result); + } + + [Fact] + public void Returns_Null_Given_Empty() + { + var result = FileSafety.GetFileNameSafely(""); + + Assert.Null(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_Null_Given_Path_Ending_In_Separator(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [InlineData("//server")] + [InlineData("\\\\server")] + [InlineData("C:")] + [InlineData("@@abcde")] + public void Returns_Null_Given_Just_Rooted_Path(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Null(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_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\0name.flac", sanitize: true, os: OSPlatform.Linux); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_On_Windows() + { + 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", os: OSPlatform.Windows); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index ed3e692f..160f2a72 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -10,12 +10,19 @@ 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) { - var result = input.LocalizePath(OSPlatform.Linux); + var result = FileSafety.LocalizePath(input, OSPlatform.Linux); Assert.Equal(expected, result); } @@ -24,11 +31,18 @@ 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) { - var result = input.LocalizePath(OSPlatform.Windows); + var result = FileSafety.LocalizePath(input, OSPlatform.Windows); Assert.Equal(expected, result); } @@ -36,9 +50,9 @@ public partial class FileSafetyTests [Fact] public void NullOs_UsesPlatformDefault_DoesNotThrow() { - var result = "foo/bar".LocalizePath(); + var result = FileSafety.LocalizePath("foo/bar"); - 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() { 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..27dcf925 --- /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<ArgumentException>(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("\0\0\0", 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); + } + } +} 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); } 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); + } + } +} diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index cd8060ef..4da05b24 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -460,6 +460,104 @@ public partial class DownloadServiceTests 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( |
