aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-06-07 18:46:25 -0500
committerJP Dillingham <jp@dillingham.me>2026-06-07 18:46:25 -0500
commit294fcabd3928b420a4dfbd7ddd0dc38ada523165 (patch)
treebcc92e42c71f2a9b67f7750c5ecd0a396b5897e5
parent60bc0c0c2ea6d9c80a7f091f022567b1d5e3240a (diff)
parent8e152ed6eccd5650179f2875eef4aa21243c8c15 (diff)
downloadslskd-294fcabd3928b420a4dfbd7ddd0dc38ada523165.tar.gz
Merge remote-tracking branch 'origin/master' into reports
-rw-r--r--FORKING.md2
-rwxr-xr-xbin/build4
-rw-r--r--bin/cover4
-rw-r--r--bin/lint4
-rwxr-xr-xbin/publish4
-rwxr-xr-xbin/run4
-rwxr-xr-xbin/watch4
-rw-r--r--config/slskd.example.yml9
-rw-r--r--docs/config.md37
-rw-r--r--src/slskd/Application.cs18
-rw-r--r--src/slskd/Common/CommonExtensions.cs84
-rw-r--r--src/slskd/Common/Compute.cs11
-rw-r--r--src/slskd/Common/Cryptography/X509.cs4
-rw-r--r--src/slskd/Common/Dumper.cs8
-rw-r--r--src/slskd/Common/Exceptions/ConflictException.cs75
-rw-r--r--src/slskd/Common/Exceptions/DuplicateException.cs75
-rw-r--r--src/slskd/Common/FileSafety.cs492
-rw-r--r--src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs2
-rw-r--r--src/slskd/Common/OperatingSystem.cs43
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs81
-rw-r--r--src/slskd/Common/Validation/GuidAttribute.cs81
-rw-r--r--src/slskd/Common/Validation/NonTraversingPathAttribute.cs (renamed from src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs)15
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs82
-rw-r--r--src/slskd/Common/Validation/StringAttribute.cs99
-rw-r--r--src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs3
-rw-r--r--src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs101
-rw-r--r--src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs108
-rw-r--r--src/slskd/Core/Data/Migrator.cs2
-rw-r--r--src/slskd/Core/Options.cs153
-rw-r--r--src/slskd/Files/FileService.cs73
-rw-r--r--src/slskd/Integrations/FTP/FTPService.cs2
-rw-r--r--src/slskd/Program.cs16
-rw-r--r--src/slskd/Relay/API/Controllers/RelayController.cs27
-rw-r--r--src/slskd/Relay/RelayClient.cs40
-rw-r--r--src/slskd/Shares/ShareService.cs6
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs6
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs205
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs118
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (renamed from src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs)26
-rw-r--r--src/slskd/Transfers/API/DTO/Transfer.cs169
-rw-r--r--src/slskd/Transfers/Downloads/BatchService.cs140
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs288
-rw-r--r--src/slskd/Transfers/Extensions.cs1
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs43
-rw-r--r--src/slskd/Transfers/Types/Batch.cs118
-rw-r--r--src/slskd/Transfers/Types/BatchOptions.cs53
-rw-r--r--src/slskd/Transfers/Types/DestinationConflictStrategy.cs49
-rw-r--r--src/slskd/Transfers/Types/DestinationExistsStrategy.cs49
-rw-r--r--src/slskd/Transfers/Types/RetryPartialStrategy.cs (renamed from src/slskd/Transfers/Types/RetryIncompleteStrategy.cs)8
-rw-r--r--src/slskd/Transfers/Types/Transfer.cs208
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs1
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs54
-rw-r--r--src/slskd/slskd.csproj40
-rw-r--r--src/web/.eslintrc.js1
-rw-r--r--src/web/package-lock.json21
-rw-r--r--src/web/src/components/Chat/Chat.jsx95
-rw-r--r--src/web/src/components/Rooms/Rooms.jsx94
-rw-r--r--tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs53
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs263
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs117
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs380
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs195
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs135
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs70
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs188
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs142
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs169
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs188
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs319
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs106
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs94
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs317
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs422
-rw-r--r--tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs40
-rw-r--r--tests/slskd.Tests.Unit/Files/FileServiceTests.cs72
-rw-r--r--tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs321
-rw-r--r--tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs608
-rw-r--r--tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj8
78 files changed, 7023 insertions, 744 deletions
diff --git a/FORKING.md b/FORKING.md
index 5b76f580..6b9aaa28 100644
--- a/FORKING.md
+++ b/FORKING.md
@@ -6,7 +6,7 @@ The requirements exist for two reasons, and both are about the people who use th
The first is to make sure users always know they are using software licensed under the AGPL. That matters because the AGPL gives users meaningful rights: the right to know that the source code exists, the right to access it, and the right to understand what they are running. Those rights only mean something if users are actually informed of them. Requiring that the full LICENSE be included with every distribution, and that license notices be preserved everywhere they appear, ensures that no user ever ends up with a copy of this software that hides or obscures the terms under which it was released.
-The second is to make sure users understand who made the software they are using. They should be able to tell where it came from, who maintains it, what has been changed and by whom, and whether it is the original project or a fork. A user who installs a fork deserves to know it is a fork. The requirements around naming, branding, source file headers, and identification notices all serve this goal. They are not intended to discourage forking โ€” they are intended to make sure that anyone who uses a fork has an accurate picture of what they have.
+The second is to make sure users understand who made the software they are using. They should be able to tell where it came from, who maintains it, what has been changed and by whom, and whether it is the original project or a fork. A user who installs a fork deserves to know it is a fork. The requirements around naming, branding, source file headers, and identification notices all serve this goal. They are not intended to discourage forking, they are intended to make sure that anyone who uses a fork has an accurate picture of what they have.
Read the LICENSE in full. This document is a plain-language guide, not a substitute for it.
diff --git a/bin/build b/bin/build
index ab469a32..8283bf25 100755
--- a/bin/build
+++ b/bin/build
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/usr/bin/env bash
set -e
web_only=false
@@ -97,4 +97,4 @@ else
fi
fi
-echo $'\n\t๐ŸŽ‰ build succeded!\n' \ No newline at end of file
+echo $'\n\t๐ŸŽ‰ build succeded!\n'
diff --git a/bin/cover b/bin/cover
index 93b364aa..e270f951 100644
--- a/bin/cover
+++ b/bin/cover
@@ -1,8 +1,8 @@
-#!/bin/bash
+#!/usr/bin/env bash
set -e
echo $'\n\t๐Ÿงช dotnet test -p:CollectCoverage=true -p:CoverletOutputFormat=lcov -p:CoverletOutput=TestResults/lcov.info\n'
dotnet test -p:CollectCoverage=true -p:CoverletOutputFormat=lcov -p:CoverletOutput=TestResults/lcov.info
-echo $'\n\t๐ŸŽ‰ coverage collection succeded!\n' \ No newline at end of file
+echo $'\n\t๐ŸŽ‰ coverage collection succeded!\n'
diff --git a/bin/lint b/bin/lint
index 4daf9c42..ffb49b35 100644
--- a/bin/lint
+++ b/bin/lint
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/usr/bin/env bash
set -e
fix=false
@@ -27,4 +27,4 @@ if [ "$fix" == false ]; then
else
echo $'\n๐Ÿ› ๏ธ dotnet format --verbosity normal\n'
dotnet format --verbosity normal
-fi \ No newline at end of file
+fi
diff --git a/bin/publish b/bin/publish
index 512fb9f6..406e7461 100755
--- a/bin/publish
+++ b/bin/publish
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/usr/bin/env bash
set -e
prebuild=true
@@ -111,4 +111,4 @@ echo $'\n\t๐Ÿ“ '$(pwd)$'\n'
echo $'\n\t๐Ÿ“ฆ artifacts:\n'
ls -la .
-echo $'\n\t๐ŸŽ‰ publish succeeded!\n' \ No newline at end of file
+echo $'\n\t๐ŸŽ‰ publish succeeded!\n'
diff --git a/bin/run b/bin/run
index f57a88a5..7f7ccf48 100755
--- a/bin/run
+++ b/bin/run
@@ -1,3 +1,3 @@
-#!/bin/bash
+#!/usr/bin/env bash
-dotnet run --project src/slskd/slskd.csproj \ No newline at end of file
+dotnet run --project src/slskd/slskd.csproj
diff --git a/bin/watch b/bin/watch
index 0605b83f..8adb3b39 100755
--- a/bin/watch
+++ b/bin/watch
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/usr/bin/env bash
if [ "$1" == "--web" ]; then
cd src/web
@@ -6,4 +6,4 @@ if [ "$1" == "--web" ]; then
npm start
else
dotnet watch --project src/slskd/slskd.csproj run
-fi \ No newline at end of file
+fi
diff --git a/config/slskd.example.yml b/config/slskd.example.yml
index e68baae2..475ac65a 100644
--- a/config/slskd.example.yml
+++ b/config/slskd.example.yml
@@ -39,7 +39,7 @@
# cidr: 0.0.0.0/0,::/0
# permissions:
# file:
-# mode: ~ # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask
+# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows.
# directories:
# incomplete: ~
# downloads: ~
@@ -74,10 +74,15 @@
# slots: 500
# speed_limit: 1000
# retry:
-# incomplete: resume # 'overwrite' or 'resume'
+# partial: resume # 'overwrite' or 'resume'
# attempts: 3
# delay: 5000 # initial time between retries, in milliseconds
# max_delay: 60000 # maximum time between retries, in milliseconds
+# destination:
+# subdirectory: ${SOURCE_DIRECTORY} # options: SOURCE_USERNAME, SOURCE_PATH, SOURCE_DIRECTORY, BATCH_ID, BATCH_EXTERNAL_ID, SEARCH_ID, SEARCH_TEXT
+# exists: rename # 'overwrite' or 'rename'
+# permissions:
+# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows.
# groups:
# default:
# upload:
diff --git a/docs/config.md b/docs/config.md
index 14f1ae24..c8a8fca2 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -117,21 +117,11 @@ Users wishing to create files with different permissions can change the umask va
When running within a docker container the environment variable `SLSKD_UMASK` can be used to change the umask for the process within the container, and this will in turn change the resulting file mode on a mounted volume.
-Users can optionally configure alternative permissions for files by setting the file permission mode option. It's not possible to supersede the configured umask value; setting a mode of 777, for example, will have no effect with a umask of 022.
-
-These options have no effect on Windows.
+This option has no effect on Windows.
| Command-Line | Environment Variable | Description |
| ------------------------ | -----------------------------| -------------------------------------------------------------------------------- |
| n/a | `SLSKD_UMASK` | When running within the slskd Docker container, the umask for the process |
-| `--file-permission-mode` | `SLSKD_FILE_PERMISSION_MODE` | The permissions to apply to newly created files (chmod syntax, non-Windows only) |
-
-#### **YAML**
-```yaml
-permissions:
- file:
- mode: 644 # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask
-```
# Application Directory Configuration
@@ -362,19 +352,40 @@ transfers:
Failed downloads can be retried automatically up to the configured number of attempts. If an attempt fails initially, the application delays the second attempt by the configured delay, and an exponential backoff is used to compute the delay for all subsequent events, up to the configured maximum delay.
-By default, partial downloads are resumed based on the size of the incomplete file. Users can choose to always overwrite files if they wish.
+By default, partial downloads are resumed based on the size of the file on disk. Users can choose to always overwrite files if they wish.
+
+Incomplete files are stored in subdirectories including the remote user's username and the name of the containing directory on the remote user's PC, which minimizes (but does not completely eliminate!) the risk that a partial file is resumed incorrectly. Choosing to always overwrite files eliminates this risk but is less efficient and it increases the risk that the file will fail to fully transfer successfully.
**YAML**
```yaml
transfers:
download:
retry:
- incomplete: resume # 'overwrite' or 'resume'
+ partial: resume # 'overwrite' or 'resume'
attempts: 3
delay: 5000 # initial time between retries, in milliseconds
max_delay: 60000 # maximum time between retries, in milliseconds
```
+## Destination
+
+### Permissions
+
+On [Unix-like](https://en.wikipedia.org/wiki/Unix-like) operating systems, downloaded files will be created according to the [umask](https://en.wikipedia.org/wiki/Umask) of the process (see [Permissions](#permissions) for more info).
+
+Users can optionally configure alternative permissions by setting the permission mode option which, when enabled, effectively causes slskd to `chmod` files and directories with the configured mode immediately after creation.
+
+This option has no effect on Windows.
+
+#### **YAML**
+```yaml
+transfers:
+ download:
+ destination:
+ permissions:
+ mode: 644 # chmod syntax, e.g. 644, 777. has no effect on Windows
+```
+
## Global Upload Limits
Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set.
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index e36a5539..2b9a1f93 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -551,7 +551,7 @@ namespace slskd
{
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
- if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive)
+ if (System.OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive)
{
return;
}
@@ -572,6 +572,14 @@ namespace slskd
{
Metrics.Enqueue.RequestsReceived.Inc(1);
+ // it shouldn't be possible for us to be sharing any such files, as share paths are required to be absolute and rooted
+ // if someone is requesting a file like this, something is either really wrong, or they are a bad actor
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt from user {Username} to enqueue a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, filename);
+ throw new DownloadEnqueueException("File not shared.");
+ }
+
/*
circuit breaker/failsafe:
@@ -1413,6 +1421,14 @@ namespace slskd
/// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns>
private async Task<IEnumerable<Soulseek.Directory>> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory)
{
+ // we shouldn't be sharing any files with these segments because shares are required to be absolute and rooted
+ // if we see this, something has either gone really wrong, or someone is trying something funny
+ if (FileSafety.ContainsTraversalSegments(directory))
+ {
+ Log.Warning("Suspicious attempt from user {Username} to list a directory containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, directory);
+ return [];
+ }
+
if (Users.IsBlacklisted(username, endpoint.Address))
{
Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 77db91ef..95721163 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -382,20 +382,6 @@ namespace slskd
.Deserialize<T>(str);
/// <summary>
- /// Converts a fully qualified remote filename to a local filename based in the provided
- /// <paramref name="baseDirectory"/>, swapping directory characters for those specific to the local OS, removing any
- /// characters that are invalid for the local OS, and making the path relative to the remote store (including the
- /// filename and the parent folder).
- /// </summary>
- /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
- /// <param name="baseDirectory">The base directory for the local filename.</param>
- /// <returns>The converted filename.</returns>
- public static string ToLocalFilename(this string remoteFilename, string baseDirectory)
- {
- return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename());
- }
-
- /// <summary>
/// Converts the given path to the normalized format (normalizes path separators to backslashes).
/// </summary>
/// <remarks>
@@ -409,16 +395,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>
@@ -439,54 +415,6 @@ namespace slskd
}
/// <summary>
- /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific
- /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the
- /// remote store (including the filename and the parent folder).
- /// </summary>
- /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
- /// <returns>The converted filename.</returns>
- public static string ToLocalRelativeFilename(this string remoteFilename)
- {
- if (string.IsNullOrWhiteSpace(remoteFilename))
- {
- throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename));
- }
-
- // normalize path separators
- var localizedRemoteFilename = remoteFilename.LocalizePath();
-
- var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar);
-
- if (parts.Length == 1)
- {
- return parts.First().ReplaceInvalidFileNameCharacters();
- }
-
- var file = parts.Last().ReplaceInvalidFileNameCharacters();
- var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters();
-
- return Path.Combine(directory, file);
- }
-
- /// <summary>
- /// Replaces any occurrence of an invalid filename character with the specified <see paramref="replacement"/>.
- /// </summary>
- /// <param name="path">The path to sanitize.</param>
- /// <param name="replacement">The character with which to replace invalid characters.</param>
- /// <returns>The sanitized path.</returns>
- public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_')
- {
- var sanitized = path;
-
- foreach (var c in Path.GetInvalidFileNameChars())
- {
- sanitized = sanitized.Replace(c, replacement);
- }
-
- return sanitized;
- }
-
- /// <summary>
/// Converts a ModelStateDictionary into a human-readable format.
/// </summary>
/// <param name="dictionary">The ModelStateDictionary to format.</param>
@@ -555,9 +483,17 @@ namespace slskd
/// <returns>The new object deserialized from the string.</returns>
public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, GetJsonSerializerOptions());
- private static JsonSerializerOptions GetJsonSerializerOptions()
+ /// <summary>
+ /// Applies the standard json serializer options to the specified instance.
+ /// </summary>
+ /// <param name="opt">The instance.</param>
+ /// <returns>The instances with the standard options applied.</returns>
+ public static JsonSerializerOptions WithStandardOptions(this JsonSerializerOptions opt)
+ => GetJsonSerializerOptions(opt);
+
+ private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions opt = null)
{
- var options = new JsonSerializerOptions();
+ var options = opt ?? new JsonSerializerOptions();
options.Converters.Add(new IPAddressConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new KnownUnsupportedTypeConverter());
diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs
index 8d7c1ceb..d235a87c 100644
--- a/src/slskd/Common/Compute.cs
+++ b/src/slskd/Common/Compute.cs
@@ -33,6 +33,7 @@
namespace slskd
{
using System;
+ using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
@@ -64,5 +65,15 @@ namespace slskd
using var sha256 = SHA256.Create();
return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
}
+
+ public static OperatingSystem OperatingSystem()
+ {
+ if (System.OperatingSystem.IsWindows())
+ {
+ return slskd.OperatingSystem.Windows;
+ }
+
+ return slskd.OperatingSystem.Linux;
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs
index bed224cf..b003decf 100644
--- a/src/slskd/Common/Cryptography/X509.cs
+++ b/src/slskd/Common/Cryptography/X509.cs
@@ -64,7 +64,7 @@ namespace slskd.Cryptography
new DateTimeOffset(DateTime.UtcNow.AddDays(-1)),
new DateTimeOffset(DateTime.UtcNow.AddDays(36500)));
- return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
+ return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
}
/// <summary>
@@ -80,7 +80,7 @@ namespace slskd.Cryptography
try
{
- _ = new X509Certificate2(fileName, password);
+ _ = X509CertificateLoader.LoadPkcs12FromFile(fileName, password);
return true;
}
catch (Exception ex)
diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs
index f4367e61..27304873 100644
--- a/src/slskd/Common/Dumper.cs
+++ b/src/slskd/Common/Dumper.cs
@@ -84,7 +84,7 @@ namespace slskd
await Download(url, BinFile);
- if (!OperatingSystem.IsWindows())
+ if (!System.OperatingSystem.IsWindows())
{
await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\"");
}
@@ -139,15 +139,15 @@ namespace slskd
string os = default;
// seems like there should be a way to just retrieve this, but there is not as of .NET 6
- if (OperatingSystem.IsLinux())
+ if (System.OperatingSystem.IsLinux())
{
os = "linux";
}
- else if (OperatingSystem.IsWindows())
+ else if (System.OperatingSystem.IsWindows())
{
os = "win";
}
- else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
+ else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD())
{
os = "osx";
}
diff --git a/src/slskd/Common/Exceptions/ConflictException.cs b/src/slskd/Common/Exceptions/ConflictException.cs
new file mode 100644
index 00000000..c58708d0
--- /dev/null
+++ b/src/slskd/Common/Exceptions/ConflictException.cs
@@ -0,0 +1,75 @@
+// <copyright file="ConflictException.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
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+
+ /// <summary>
+ /// Represents errors that originate due to duplication.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ public class ConflictException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConflictException"/> class.
+ /// </summary>
+ public ConflictException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public ConflictException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public ConflictException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Exceptions/DuplicateException.cs b/src/slskd/Common/Exceptions/DuplicateException.cs
new file mode 100644
index 00000000..da603d87
--- /dev/null
+++ b/src/slskd/Common/Exceptions/DuplicateException.cs
@@ -0,0 +1,75 @@
+// <copyright file="DuplicateException.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
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+
+ /// <summary>
+ /// Represents errors that originate due to duplication.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ public class DuplicateException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DuplicateException"/> class.
+ /// </summary>
+ public DuplicateException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public DuplicateException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public DuplicateException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs
new file mode 100644
index 00000000..6a6dea22
--- /dev/null
+++ b/src/slskd/Common/FileSafety.cs
@@ -0,0 +1,492 @@
+// <copyright file="FileSafety.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;
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+/// <summary>
+/// Utility functions to help safely work with paths from untrusted sources.
+/// </summary>
+public static class FileSafety
+{
+ /// <summary>
+ /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc).
+ /// </summary>
+ public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/'];
+
+ /// <summary>
+ /// Invalid filename characters on Windows.
+ /// </summary>
+ public static readonly char[] InvalidFileNameCharactersOnWindows =
+ [
+ '\"', '<', '>', '|', '\0',
+ (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
+ (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
+ (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
+ (char)31, ':', '*', '?', '\\', '/',
+ ];
+
+ 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
+
+ /// <summary>
+ /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or
+ /// subsequent position, and disallows segments containing path traversal characters "." and "..".
+ /// </summary>
+ /// <param name="root">The root directory.</param>
+ /// <param name="segments">The segments to append.</param>
+ /// <returns>The combined path.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception>
+ /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception>
+ public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments);
+
+ /// <summary>
+ /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or
+ /// subsequent position, and disallows segments containing path traversal characters "." and "..".
+ /// </summary>
+ /// <param name="root">The root directory.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <param name="segments">The segments to append.</param>
+ /// <returns>The combined path.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception>
+ /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception>
+ public static string CombineSafely(string root, OperatingSystem? os, params string[] segments)
+ {
+ // ensure no inputs are null. matches the behavior of Path.Combine()
+ if (string.IsNullOrWhiteSpace(root))
+ {
+ throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace");
+ }
+
+ if (ContainsTraversalSegments(root))
+ {
+ throw new ArgumentException("Specified root directory contains path traversal segments", nameof(root));
+ }
+
+ if (segments is null || segments.Any(s => s is null))
+ {
+ throw new ArgumentNullException(nameof(segments), $"One or more segments is null");
+ }
+
+ root = root.TrimEnd('/', '\\');
+
+ if (segments.Length == 0)
+ {
+ return root;
+ }
+
+ var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows();
+ var sep = isWindows ? '\\' : '/';
+
+ foreach (var segment in segments)
+ {
+ // disallow any segments that:
+ // windows: are drive letter (C:\) or UNC path (\\)
+ // linux: begin with a forward slash (any number, covering both local and UNC paths)
+ if (IsPathAbsolute(segment, os))
+ {
+ throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'");
+ }
+
+ if (isWindows)
+ {
+ if (segment.Contains(':'))
+ {
+ throw new ArgumentException($"Colons are not permitted in segments: '{segment}'");
+ }
+
+ // on Windows, a segment beginning with a slash is considered 'drive rooted' and something like
+ // "\foo" translates to "C:\foo" when passed to Path.Combine()
+ if (segment.StartsWith('\\') || segment.StartsWith('/'))
+ {
+ throw new ArgumentException($"Drive-relative segments or those containing leading slashes are not permitted in segments: '{segment}'");
+ }
+ }
+
+ 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
+ // this covers cases where the entire segment is . or .., or foo\..\bar, or \.. or ..\ or \..\
+ if (parts.Any(s => s is "." or ".."))
+ {
+ throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'");
+ }
+ }
+
+ segments = [.. segments
+ .Where(s => !string.IsNullOrEmpty(s))];
+
+ var combined = string.Join(sep, [root, .. segments]);
+
+ if (combined.TrimEnd('/', '\\') == root.TrimEnd('/', '\\'))
+ {
+ return combined;
+ }
+
+ // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting
+ // path is actually rooted in the root we provided; if not the input was successful in traversal
+ if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\"))
+ {
+ throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed");
+ }
+
+ return combined;
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/> contains path traversal segments.
+ /// </summary>
+ /// <param name="path">The path to check.</param>
+ /// <returns>True if one or more segments is present, false otherwise.</returns>
+ public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false;
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted) on the current
+ /// operating system.
+ /// </summary>
+ /// <remarks>
+ /// This is necessary because the base library is opaque and untestable in a cross-platform way, so we are
+ /// implementing the nuclear option and doing it ourselves.
+ /// </remarks>
+ /// <param name="path">The path to check.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>True if the path is absolute, false otherwise.</returns>
+ public static bool IsPathAbsolute(string path, OperatingSystem? os = null)
+ {
+ if (string.IsNullOrEmpty(path))
+ {
+ return false;
+ }
+
+ if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows())
+ {
+ // Windows drive-letter path: X:\ or X:/
+ // X:foo is relative on windows
+ if (path.Length >= 3
+ && char.IsAsciiLetter(path[0])
+ && path[1] == ':'
+ && (path[2] == '\\' || path[2] == '/'))
+ {
+ return true;
+ }
+
+ // UNC path \\server\share
+ if (path.StartsWith("\\\\"))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with /
+ if (path.StartsWith('/'))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/> is relative on the current
+ /// operating system.
+ /// </summary>
+ /// <param name="path">The path to check.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>True if the path is relative, false otherwise.</returns>
+ public static bool IsPathRelative(string path, OperatingSystem? 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, OperatingSystem? 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, OperatingSystem? 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.OperatingSystem();
+ var sep = os.Value == OperatingSystem.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)
+ {
+ // leading slashes are stripped of leading slashes by Split() so we must add them back
+ 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(string path, OperatingSystem? os = null)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
+
+ return path.Replace('\\', sep).Replace('/', sep);
+ }
+
+ /// <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
+ /// 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>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The sanitized filename.</returns>
+ public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null)
+ {
+ if (filename is null)
+ {
+ return null;
+ }
+
+ if (replacement is '/' or '\\')
+ {
+ throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames");
+ }
+
+ os ??= Compute.OperatingSystem();
+
+ var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix;
+
+ if (characters.Contains(replacement))
+ {
+ throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}");
+ }
+
+ var sanitized = filename;
+
+ foreach (var c in characters)
+ {
+ sanitized = sanitized.Replace(c, replacement);
+ }
+
+ // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames
+ // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath()
+ return sanitized
+ .Replace('/', replacement)
+ .Replace('\\', replacement);
+ }
+
+ /// <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 = '_', OperatingSystem? 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, 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="os">An optional operating system override, for testing.</param>
+ /// <returns>The sanitized path.</returns>
+ public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
+
+ // flip slashes the correct way
+ path = LocalizePath(path, os);
+
+ // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings,
+ // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement)
+ var segments = path
+ .Split('/', '\\')
+ .Where(s => s is not "")
+ .Select(s => SanitizePathSegment(s, replacement, os))
+ .Where(s => s is not "");
+
+ var newPath = string.Join(sep, segments);
+
+ return newPath;
+ }
+
+ /// <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, OperatingSystem? os = null)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ // flip slashes the correct way
+ path = LocalizePath(path, os);
+
+ // strip C:\ or //server, if present (regardless of slash variant)
+ path = DriveRootRegex.Replace(path, string.Empty);
+ path = UncRootRegex.Replace(path, string.Empty);
+
+ // strip @@abcde prefixes used by SoulseekQt to obscure paths
+ path = SoulseekQtRootRegex.Replace(path, string.Empty);
+
+ return path;
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
index a7e7e0dc..760f7ba9 100644
--- a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
+++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
@@ -36,7 +36,7 @@ using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
-using Microsoft.OpenApi.Models;
+using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
/// <summary>
diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs
new file mode 100644
index 00000000..0c3dae2c
--- /dev/null
+++ b/src/slskd/Common/OperatingSystem.cs
@@ -0,0 +1,43 @@
+// <copyright file="OperatingSystem.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;
+
+public enum OperatingSystem
+{
+ None = 0,
+ Linux = 1,
+ Windows = 2,
+ Current = 3,
+ Any = 4,
+ All = 5,
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
new file mode 100644
index 00000000..217a4eea
--- /dev/null
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -0,0 +1,81 @@
+// <copyright file="AbsolutePathAttribute.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.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the specified path is absolute.
+ /// </summary>
+ public class AbsolutePathAttribute : ValidationAttribute
+ {
+ public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current)
+ {
+ if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All)
+ {
+ throw new System.ArgumentException("OperatingSystem argument for AbsolutePathAttribute must be one of: Current, Any, All", nameof(os));
+ }
+
+ OS = os;
+ }
+
+ public OperatingSystem OS { get; }
+ private OperatingSystem? Injected { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
+ {
+ var path = value.ToString();
+
+ if (OS == OperatingSystem.Current)
+ {
+ if (!FileSafety.IsPathAbsolute(path, os: Injected ?? Compute.OperatingSystem()))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system.");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ // OS == OperatingSystem.All or .Any
+ if (!FileSafety.IsPathAbsolute(path, os: OperatingSystem.Linux) || !FileSafety.IsPathAbsolute(path, os: OperatingSystem.Windows))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems.");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs
new file mode 100644
index 00000000..7c04f1f9
--- /dev/null
+++ b/src/slskd/Common/Validation/GuidAttribute.cs
@@ -0,0 +1,81 @@
+// <copyright file="GuidAttribute.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.Validation
+{
+ using System;
+
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the value is a valid Guid.
+ /// </summary>
+ public class GuidAttribute : ValidationAttribute
+ {
+ public GuidAttribute(bool allowEmpty = false)
+ {
+ AllowEmpty = allowEmpty;
+ }
+
+ public bool AllowEmpty { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value is null)
+ {
+ return ValidationResult.Success;
+ }
+
+ if (value is Guid guid)
+ {
+ if (!AllowEmpty && guid == Guid.Empty)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ if (value is string str && Guid.TryParse(str, out guid))
+ {
+ if (!AllowEmpty && guid == Guid.Empty)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID");
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
index 8f87e479..1e2616bd 100644
--- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs
+++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
@@ -1,4 +1,4 @@
-// <copyright file="AbsoluteFilePathAttribute.cs" company="JP Dillingham">
+// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham">
// โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„
// โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆ
// โ–ˆ__ --โ–ˆ โ–ˆ__ --โ–ˆ โ—„โ–ˆ - โ–ˆ
@@ -33,22 +33,21 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.IO;
/// <summary>
- /// Validates that the specified path is absolute.
+ /// Validates that the specified path does not contain traversal segments '.' or '..'.
/// </summary>
- public class AbsoluteFilePathAttribute : ValidationAttribute
+ public class NonTraversingPathAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
- if (value != null)
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
- var filePath = value.ToString();
+ var path = value.ToString();
- if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath))
+ if (FileSafety.ContainsTraversalSegments(path))
{
- return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path.");
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
}
}
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
new file mode 100644
index 00000000..ea2b627b
--- /dev/null
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -0,0 +1,82 @@
+// <copyright file="RelativePathAttribute.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.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the specified path is relative.
+ /// </summary>
+ public class RelativePathAttribute : ValidationAttribute
+ {
+ public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current)
+ {
+ if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All)
+ {
+ throw new System.ArgumentException("OperatingSystem argument for RelativePathAttribute must be one of: Current, Any, All", nameof(os));
+ }
+
+ OS = os;
+ }
+
+ public OperatingSystem OS { get; }
+
+ private OperatingSystem? Injected { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
+ {
+ var path = value.ToString();
+
+ if (OS == OperatingSystem.Current)
+ {
+ if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem()))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system.");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ // OS == OperatingSystem.All or .Any;
+ if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems.");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs
new file mode 100644
index 00000000..bb323ba2
--- /dev/null
+++ b/src/slskd/Common/Validation/StringAttribute.cs
@@ -0,0 +1,99 @@
+// <copyright file="StringAttribute.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.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+
+ /// <summary>
+ /// Validates that the value is not null or whitespace.
+ /// </summary>
+ public class StringAttribute : ValidationAttribute
+ {
+ public bool AllowNull { get; set; } = true;
+ public bool AllowEmpty { get; set; } = true;
+ public bool AllowWhiteSpace { get; set; } = true;
+ public char[] DisallowedCharacters { get; set; } = [];
+ public int MinimumLength { get; set; } = 0;
+ public int MaximumLength { get; set; } = int.MaxValue;
+ public Regex Pattern { get; set; } = null;
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ var val = (string)value;
+
+ if (val is null)
+ {
+ if (!AllowNull)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not be null");
+ }
+ else
+ {
+ return ValidationResult.Success;
+ }
+ }
+
+ if (!AllowEmpty && val is "")
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character");
+ }
+
+ // check this after empty to avoid overlap
+ if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c)))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace");
+ }
+
+ if (val.Length < MinimumLength || val.Length > MaximumLength)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters");
+ }
+
+ var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)));
+
+ if (invalid.Any())
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ }
+
+ if (Pattern is not null && Pattern.IsMatch(val))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}");
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs
index 6c5810c5..1a155f18 100644
--- a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs
+++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs
@@ -69,7 +69,10 @@ public class Z2025_04_01_TransferStateMigration : IMigration
var schema = SchemaInspector.GetDatabaseSchema(ConnectionString);
var txfers = schema["Transfers"];
+#pragma warning disable CS0618 // Type or member is obsolete
return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription));
+#pragma warning restore CS0618 // Type or member is obsolete
+
}
public void Apply()
diff --git a/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs
new file mode 100644
index 00000000..4fb25b1f
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs
@@ -0,0 +1,101 @@
+// <copyright file="Z2026_04_30_DropTransferStartOffsetMigration.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.Migrations;
+
+using System;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// Updates the Transfers table to drop the unused StartOffset column.
+/// </summary>
+public class Z2026_04_30_DropTransferStartOffsetMigration : IMigration
+{
+ public Z2026_04_30_DropTransferStartOffsetMigration(ConnectionStringDictionary connectionStrings)
+ {
+ ConnectionString = connectionStrings[Database.Transfers];
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z2026_04_30_DropTransferStartOffsetMigration>();
+ private string ConnectionString { get; }
+
+ public bool NeedsToBeApplied()
+ {
+ var schema = SchemaInspector.GetDatabaseSchema(ConnectionString);
+
+ var columns = schema["Transfers"];
+
+ if (columns.Any(c => c.Name == "StartOffset"))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ public void Apply()
+ {
+ if (!NeedsToBeApplied())
+ {
+ Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_04_30_DropTransferStartOffsetMigration));
+ return;
+ }
+
+ using var connection = new SqliteConnection(ConnectionString);
+ connection.Open();
+
+ using var transaction = connection.BeginTransaction();
+
+ try
+ {
+ void Exec(string sql)
+ {
+ using var command = new SqliteCommand(sql, connection, transaction);
+ command.ExecuteNonQuery();
+ }
+
+ Log.Information("> Dropping StartOffset column from the Transfers table...");
+
+ Exec("ALTER TABLE Transfers DROP COLUMN StartOffset;");
+
+ transaction.Commit();
+ Log.Information("> Done!");
+ }
+ catch (Exception)
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs
new file mode 100644
index 00000000..9b373f71
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs
@@ -0,0 +1,108 @@
+// <copyright file="Z2026_05_06_AddBatchesTableMigration.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.Migrations;
+
+using System;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// Creates the Batches table in the Transfers database.
+/// </summary>
+public class Z2026_05_06_AddBatchesTableMigration : IMigration
+{
+ public Z2026_05_06_AddBatchesTableMigration(ConnectionStringDictionary connectionStrings)
+ {
+ ConnectionString = connectionStrings[Database.Transfers];
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z2026_05_06_AddBatchesTableMigration>();
+ private string ConnectionString { get; }
+
+ public bool NeedsToBeApplied()
+ {
+ var schema = SchemaInspector.GetDatabaseSchema(ConnectionString);
+
+ if (schema.ContainsKey("Batches"))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ public void Apply()
+ {
+ if (!NeedsToBeApplied())
+ {
+ Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_05_06_AddBatchesTableMigration));
+ return;
+ }
+
+ using var connection = new SqliteConnection(ConnectionString);
+ connection.Open();
+
+ using var transaction = connection.BeginTransaction();
+
+ try
+ {
+ void Exec(string sql)
+ {
+ using var command = new SqliteCommand(sql, connection, transaction);
+ command.ExecuteNonQuery();
+ }
+
+ Log.Information("> Creating the Batches table...");
+
+ Exec(@"
+ CREATE TABLE Batches (
+ Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY,
+ SearchId TEXT,
+ Username TEXT,
+ Direction INTEGER NOT NULL,
+ CreatedAt TEXT NOT NULL,
+ Options TEXT
+ );");
+
+ Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);");
+
+ transaction.Commit();
+ Log.Information("> Done!");
+ }
+ catch (Exception)
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs
index 7289b070..d53d7c8c 100644
--- a/src/slskd/Core/Data/Migrator.cs
+++ b/src/slskd/Core/Data/Migrator.cs
@@ -60,6 +60,8 @@ public class Migrator
{ nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) },
{ nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) },
{ nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) },
+ { nameof(Z2026_04_30_DropTransferStartOffsetMigration), new Z2026_04_30_DropTransferStartOffsetMigration(connectionStrings: Databases) },
+ { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) },
};
}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 8cc369af..d1062a2c 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -235,11 +235,8 @@ namespace slskd
[Validate]
public RelayOptions Relay { get; init; } = new RelayOptions();
- /// <summary>
- /// Gets permission options.
- /// </summary>
- [Validate]
- public PermissionsOptions Permissions { get; init; } = new PermissionsOptions();
+ [Obsolete("temporary sentinel to warn users about breaking change. use Transfers.Download.Destination.Permissions instead.")]
+ public object Permissions { get; init; } = null;
/// <summary>
/// Gets directory options.
@@ -364,6 +361,11 @@ namespace slskd
{
results.Add(new ValidationResult("The 'integration' key has been renamed to 'integrations'. Add an 's' to the end of the key to remove this error (no other changes were made)"));
}
+
+ if (Permissions is not null)
+ {
+ results.Add(new ValidationResult("The 'permissions' keys have been moved under a new 'destination' key under transfers -> download, and the behavior has changed. See https://github.com/slskd/slskd/pull/1756 for details"));
+ }
#pragma warning restore CS0618 // Type or member is obsolete
return results;
@@ -704,57 +706,6 @@ namespace slskd
}
/// <summary>
- /// Permission options.
- /// </summary>
- public class PermissionsOptions
- {
- /// <summary>
- /// Gets file permission options.
- /// </summary>
- [Validate]
- public FileOptions File { get; init; } = new FileOptions();
-
- /// <summary>
- /// File permission options.
- /// </summary>
- public class FileOptions : IValidatableObject
- {
- /// <summary>
- /// Gets the permissions to apply to newly created files.
- /// </summary>
- /// <remarks>
- /// Applicable to non-Windows operating systems, only.
- /// </remarks>
- [Argument(default, "file-permission-mode")]
- [EnvironmentVariable("FILE_PERMISSION_MODE")]
- [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")]
- public string Mode { get; init; }
-
- /// <summary>
- /// Extended validation.
- /// </summary>
- /// <param name="validationContext"></param>
- /// <returns></returns>
- public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
- {
- var results = new List<ValidationResult>();
-
- 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;
- }
- }
- }
-
- /// <summary>
/// Directory options.
/// </summary>
public class DirectoriesOptions
@@ -765,6 +716,8 @@ namespace slskd
[Argument(default, "incomplete")]
[EnvironmentVariable("INCOMPLETE_DIR")]
[Description("path where incomplete downloads are saved")]
+ [AbsolutePath(OperatingSystem.Current)]
+ [NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory;
@@ -775,6 +728,8 @@ namespace slskd
[Argument('o', "downloads")]
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
+ [AbsolutePath(OperatingSystem.Current)]
+ [NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Downloads { get; init; } = Program.DefaultDownloadsDirectory;
@@ -828,22 +783,28 @@ 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(FileSafety.LocalizePath(share), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$");
+ directories?.Where(share => ContainsTraversalSegments(share)).ToList()
+ .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment.")));
+
(string Raw, string Alias, string Path) Digest(string share)
{
- var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$");
+ var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$");
if (matches.Any())
{
@@ -1019,6 +980,12 @@ namespace slskd
public RetryOptions Retry { get; init; } = new RetryOptions();
/// <summary>
+ /// Gets download destination options.
+ /// </summary>
+ [Validate]
+ public DestinationOptions Destination { get; init; } = new DestinationOptions();
+
+ /// <summary>
/// Download retry options.
/// </summary>
public class RetryOptions
@@ -1042,10 +1009,67 @@ namespace slskd
public int MaxDelay { get; init; } = 60_000;
/// <summary>
- /// Gets the strategy for handling incomplete files upon retry.
+ /// Gets the strategy for handling partial files upon retry.
+ /// </summary>
+ [Enum(typeof(RetryPartialStrategy))]
+ public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant();
+ }
+
+ /// <summary>
+ /// Download destination options.
+ /// </summary>
+ public class DestinationOptions
+ {
+ /// <summary>
+ /// Gets the destination subdirectory for the files in the batch.
+ /// </summary>
+ [RelativePath(OperatingSystem.All)]
+ [NonTraversingPath]
+ [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
+ public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}";
+
+ /// <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>
- [Enum(typeof(RetryIncompleteStrategy))]
- public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant();
+ public class DestinationPermissionsOptions : IValidatableObject
+ {
+ /// <summary>
+ /// Gets the permissions to apply to newly created files.
+ /// </summary>
+ /// <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>();
+
+ 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;
+ }
+ }
}
}
@@ -2010,7 +2034,8 @@ namespace slskd
[Argument(default, "http-socket")]
[EnvironmentVariable("HTTP_SOCKET")]
[Description("HTTP listen unix domain socket (UDS) path for web UI")]
- [AbsoluteFilePath]
+ [AbsolutePath(OperatingSystem.Current)]
+ [NonTraversingPath]
[RequiresRestart]
public string Socket { get; init; }
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index 575619d5..62d17f20 100644
--- a/src/slskd/Files/FileService.cs
+++ b/src/slskd/Files/FileService.cs
@@ -79,6 +79,17 @@ namespace slskd.Files
{
ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename));
+ if (Path.GetFullPath(filename) != filename)
+ {
+ throw new ArgumentException("Only absolute paths may be specified", nameof(filename));
+ }
+
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename);
+ throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename));
+ }
+
FileInfo info;
try
@@ -153,18 +164,29 @@ namespace slskd.Files
/// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception>
public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories)
{
+ if (directories is null or [] || directories.Any(directory => string.IsNullOrEmpty(directory)))
+ {
+ throw new ArgumentException("One or more directories are null or empty");
+ }
+
if (directories.Any(directory => Path.GetFullPath(directory) != directory))
{
throw new ArgumentException("Only absolute paths may be specified", nameof(directories));
}
+ if (directories.Any(directory => FileSafety.ContainsTraversalSegments(directory)))
+ {
+ Log.Warning("Suspicious attempt to delete a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directories: {Directories}", string.Join(", ", directories));
+ throw new ArgumentException("Directories containing traversal segments are not allowed", nameof(directories));
+ }
+
if (directories.Any(directory => AllowedDirectories.Contains(directory)))
{
throw new ArgumentException("Deletion of application-controlled directory roots is not supported");
}
// important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..'
- bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed));
+ bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed);
// if any of the resolved directory paths aren't rooted in one of the allowed directories, forbid the entire request
if (!directories.All(directory => IsAllowed(directory)))
@@ -216,13 +238,24 @@ namespace slskd.Files
/// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception>
public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files)
{
+ if (files is null or [] || files.Any(file => string.IsNullOrWhiteSpace(file)))
+ {
+ throw new ArgumentException("One or more files are null or empty", nameof(files));
+ }
+
if (files.Any(file => Path.GetFullPath(file) != file))
{
throw new ArgumentException("Only absolute paths may be specified", nameof(files));
}
+ if (files.Any(file => FileSafety.ContainsTraversalSegments(file)))
+ {
+ Log.Warning("Suspicious attempt to delete a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file(s): {File}", string.Join(", ", files));
+ throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(files));
+ }
+
// important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..'
- bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed));
+ bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed);
// if any of the resolved file paths aren't rooted in one of the allowed directories, forbid the entire request
if (!files.All(file => IsAllowed(file)))
@@ -269,15 +302,23 @@ namespace slskd.Files
/// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception>
public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
{
+ ArgumentException.ThrowIfNullOrWhiteSpace(directory);
+
if (Path.GetFullPath(directory) != directory)
{
throw new ArgumentException("Only absolute paths may be specified", nameof(directory));
}
+ if (FileSafety.ContainsTraversalSegments(directory))
+ {
+ Log.Warning("Suspicious attempt to list a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directory: {Directory}", directory);
+ throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(directory));
+ }
+
// important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..'
- if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed)))
+ if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed + Path.DirectorySeparatorChar) || directory == allowed))
{
- throw new UnauthorizedException($"Only application-controlled directories can be deleted");
+ throw new UnauthorizedException($"Only application-controlled directories can be listed");
}
if (!Directory.Exists(directory))
@@ -340,15 +381,23 @@ namespace slskd.Files
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename));
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to create a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename);
+ throw new ArgumentException("Filenames containing traversal segments are not allowed");
+ }
+
var path = Path.GetDirectoryName(filename);
- UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode();
+ UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode();
if (!Directory.Exists(path))
{
if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue)
{
- Directory.CreateDirectory(path, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag());
+ var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag();
+ Directory.CreateDirectory(path, unixCreateMode: mode);
+ File.SetUnixFileMode(path, mode: mode);
}
else
{
@@ -411,18 +460,26 @@ namespace slskd.Files
ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename));
ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory));
+ if (FileSafety.ContainsTraversalSegments(sourceFilename) || FileSafety.ContainsTraversalSegments(destinationDirectory))
+ {
+ Log.Warning("Suspicious attempt to move a file with either a source filename or destination directory name containing unsafe path segments (one or more of path traversal characters '.' and '..'). Source: {Source}, Destination: {Destination}", sourceFilename, destinationDirectory);
+ throw new ArgumentException("Filenames and directories containing traversal segments are not allowed");
+ }
+
if (!File.Exists(sourceFilename))
{
throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename);
}
- UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode();
+ UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode();
if (!Directory.Exists(destinationDirectory))
{
if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue)
{
- Directory.CreateDirectory(destinationDirectory, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag());
+ var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag();
+ Directory.CreateDirectory(destinationDirectory, unixCreateMode: mode);
+ File.SetUnixFileMode(destinationDirectory, mode: mode);
}
else
{
diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs
index 8c270d6a..597a34f3 100644
--- a/src/slskd/Integrations/FTP/FTPService.cs
+++ b/src/slskd/Integrations/FTP/FTPService.cs
@@ -109,7 +109,7 @@ namespace slskd.Integrations.FTP
private async Task AttemptUploadAsync(string filename)
{
var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename);
- var remotePath = FtpOptions.RemotePath.TrimEnd('/').TrimEnd('\\');
+ var remotePath = FtpOptions.RemotePath.TrimEnd('/', '\\');
var remoteFilename = $"{remotePath}/{fileAndParentDirectory}";
var existsMode = FtpOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip;
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 49a1c260..b6710fdd 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -62,11 +62,12 @@ namespace slskd
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Physical;
using Microsoft.IdentityModel.Tokens;
- using Microsoft.OpenApi.Models;
+ using Microsoft.OpenApi;
using Prometheus.DotNetRuntime;
using Prometheus.SystemMetrics;
using Serilog;
using Serilog.Events;
+ using Serilog.Formatting.Display;
using Serilog.Sinks.Grafana.Loki;
using Serilog.Sinks.SystemConsole.Themes;
using slskd.Authentication;
@@ -780,6 +781,7 @@ namespace slskd
services.AddSingleton<TransferService>();
services.AddSingleton<IDownloadService, DownloadService>();
services.AddSingleton<IUploadService, UploadService>();
+ services.AddSingleton<IBatchService, BatchService>();
services.AddSingleton<FileService>();
services.AddSingleton<IRelayService, RelayService>();
@@ -1006,6 +1008,7 @@ namespace slskd
services.AddSwaggerGen(options =>
{
options.DescribeAllParametersInCamelCase();
+ options.CustomSchemaIds(type => type.FullName);
options.SwaggerDoc("v0", new OpenApiInfo
{
Version = "v0",
@@ -1215,6 +1218,7 @@ namespace slskd
.MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning)
.MinimumLevel.Override("slskd.Authentication.ApiKeyAuthenticationHandler", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning) // bump this down to Information to show SQL
+ .Enrich.WithProperty("App", AppName)
.Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName)
.Enrich.WithProperty("InvocationId", InvocationId)
.Enrich.WithProperty("ProcessId", ProcessId)
@@ -1233,9 +1237,13 @@ namespace slskd
retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs))))
.WriteTo.Conditional(
e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
- config => config.GrafanaLoki(
- OptionsAtStartup.Logger.Loki ?? string.Empty,
- outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
+ config =>
+ {
+ if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki))
+ {
+ config.GrafanaLoki(OptionsAtStartup.Logger.Loki);
+ }
+ })
.WriteTo.Sink(new DelegatingSink(logEvent =>
{
string message = default;
diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs
index 0d2ef9c5..ddb8d0b0 100644
--- a/src/slskd/Relay/API/Controllers/RelayController.cs
+++ b/src/slskd/Relay/API/Controllers/RelayController.cs
@@ -149,6 +149,14 @@ namespace slskd.Relay
return BadRequest();
}
+ // check the path; the caller has a valid API key but we haven't validated the credential yet, so this is worth
+ // doing here instead of relying on the CombineSafely() backstop
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to download a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ return BadRequest();
+ }
+
Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName);
// note: the token remains valid after the validation attempt, unlike most other endpoints.
@@ -159,7 +167,12 @@ namespace slskd.Relay
return Unauthorized();
}
- var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
+ // if we get this far, the caller has supplied a valid credential and filename, meaning the request
+ // to download is being made in response to the controller signaling the agent that a download had completed.
+ // it's not possible for the client to download arbitrary files; credentials are computed from a token, and
+ // this token is cached in the controller, so only file downloads that the controller solicited are possible
+ // still, for the abundance of caution, use the CombineSafely method in case the filename has traversal segments
+ var sourceFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename);
@@ -225,6 +238,14 @@ namespace slskd.Relay
throw new ArgumentException("Upload filename is null or empty");
}
+ // use an abundance of caution; the caller has a valid API key but we haven't validated the credential yet
+ // this is a really unlikely attack vector and it wouldn't do anything, but we're taking a hard stance on input validation
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to upload a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ return BadRequest();
+ }
+
if (stream == null || !stream.CanRead)
{
throw new ArgumentException("Unable to obtain stream from request");
@@ -323,8 +344,8 @@ namespace slskd.Relay
return Unauthorized();
}
- Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
- var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_{agentName}_{Path.GetRandomFileName()}.db");
+ Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName));
+ var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{FileSafety.SanitizeFilename(agentName)}_{Path.GetRandomFileName()}.db");
try
{
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index 9aec7b00..5c5f9d38 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -273,7 +273,7 @@ namespace slskd.Relay
StartCancellationTokenSource?.Cancel();
HubConnection = new HubConnectionBuilder()
- .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder =>
+ .WithUrl($"{options.Relay.Controller.Address.TrimEnd('/')}/hub/relay", builder =>
{
builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey);
builder.HttpMessageHandlerFactory = (message) =>
@@ -338,7 +338,7 @@ namespace slskd.Relay
}
client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue);
- client.BaseAddress = new(options.Address);
+ client.BaseAddress = new(options.Address.TrimEnd('/'));
return client;
}
@@ -370,6 +370,12 @@ namespace slskd.Relay
private async Task HandleFileInfoRequest(string filename, Guid id)
{
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0);
+ }
+
Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id);
try
@@ -387,8 +393,14 @@ namespace slskd.Relay
}
}
- private Task HandleFileUploadRequest(string filename, long startOffset, Guid token)
+ private async Task HandleFileUploadRequest(string filename, long startOffset, Guid token)
{
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token);
+ }
+
_ = Task.Run(async () =>
{
Log.Information("Relay controller requested file {Filename} with ID {Id}", filename, token);
@@ -442,33 +454,37 @@ namespace slskd.Relay
await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token);
}
});
-
- return Task.CompletedTask;
}
- private Task HandleNotifyFileDownloadCompleted(string filename, Guid token)
+ private async Task HandleNotifyFileDownloadCompleted(string filename, Guid token)
{
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to solicit a file download containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ return;
+ }
+
if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads)
{
- return Task.CompletedTask;
+ return;
}
Log.Information("Relay controller sent a download notification for {Filename} ({Token})", filename, token);
_ = Task.Run(async () =>
{
- var destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
+ var destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
{
// if we're debugging, we're referencing the same file for both the controller and agent which will lead to an
// access violation. prefix the destination file to avoid this.
- destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed");
+ destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed");
}
// 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 () =>
{
@@ -498,8 +514,6 @@ namespace slskd.Relay
Log.Information("File {Filename} successfully downloaded to {Destination}", filename, destinationFile);
});
-
- return Task.CompletedTask;
}
private Task HubConnection_Closed(Exception arg)
@@ -579,7 +593,7 @@ namespace slskd.Relay
return;
}
- var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
+ var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
try
{
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index a1dde4eb..054561bf 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -188,7 +188,9 @@ namespace slskd.Shares
directories.TryAdd(directory, new Directory(directory));
}
- var files = repositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true));
+ var files = repositories.SelectMany(r => r.ListFiles(
+ parentDirectory: prefix,
+ includeFullPath: true)); // includes the full *masked* filename; directory and file name and extension. not the local filename.
var groups = files
.GroupBy(file => file.Filename.GetNormalizedDirectoryName())
@@ -280,7 +282,7 @@ namespace slskd.Shares
/// <returns>The contents of the directory.</returns>
public Task<Directory> ListDirectoryAsync(string directory)
{
- var files = AllRepositories.SelectMany(r => r.ListFiles(directory));
+ var files = AllRepositories.SelectMany(r => r.ListFiles(directory, includeFullPath: false));
return Task.FromResult(new Directory(directory, files));
}
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index b6c5fc9d..ed594209 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -418,7 +418,7 @@ namespace slskd.Shares
while (reader.Read())
{
- var filename = reader.GetString(0);
+ var maskedFilename = reader.GetString(0);
var code = reader.GetInt32(1);
var size = reader.GetInt64(2);
var extension = reader.GetString(3);
@@ -426,9 +426,9 @@ namespace slskd.Shares
var attributeList = attributeJson.FromJson<List<FileAttribute>>();
- filename = includeFullPath ? filename : filename.GetNormalizedFileName();
+ maskedFilename = includeFullPath ? maskedFilename : maskedFilename.GetNormalizedFileName();
- var file = new Soulseek.File(code, filename, size, extension, attributeList);
+ var file = new Soulseek.File(code, maskedFilename, size, extension, attributeList);
results.Add(file);
}
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 494ee722..3191e3a8 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -42,6 +42,7 @@ namespace slskd.Transfers.API
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using slskd.Users;
@@ -217,7 +218,7 @@ namespace slskd.Transfers.API
}
/// <summary>
- /// Enqueues the specified download.
+ /// (Obsolete) Enqueues the specified download.
/// </summary>
/// <param name="username">The username of the download source.</param>
/// <param name="requests">The list of download requests.</param>
@@ -225,6 +226,7 @@ namespace slskd.Transfers.API
/// <response code="201">The download was successfully enqueued.</response>
/// <response code="403">The download was rejected.</response>
/// <response code="500">An unexpected error was encountered.</response>
+ [Obsolete("Will be phased out in future versions; use batches")]
[HttpPost("downloads/{username}")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(201)]
@@ -249,7 +251,12 @@ namespace slskd.Transfers.API
if (requests.Any(r => r is null))
{
- return BadRequest("One or more records in the request are null");
+ return BadRequest("One or more files in the request are null");
+ }
+
+ if (requests.Any(r => FileSafety.ContainsTraversalSegments(r.Filename)))
+ {
+ return BadRequest("One or more files in the request contain a dangerous path traversal segment");
}
if (!DownloadRequestLimiter.Wait(0))
@@ -282,6 +289,155 @@ namespace slskd.Transfers.API
}
/// <summary>
+ /// Enqueues a batch of downloads.
+ /// </summary>
+ /// <param name="request">The batch details.</param>
+ /// <returns></returns>
+ /// <response code="201">All downloads were successfully enqueued.</response>
+ /// <response code="200">The request succeeded, but all downloads failed to be enqueued.</response>
+ /// <response code="207">Some downloads were successfully enqueued, while some failed.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="403">The request was forbidden.</response>
+ /// <response code="409">A batch with the same ID already exists.</response>
+ /// <response code="429">Request throttled.</response>
+ /// <response code="500">An unexpected error was encountered.</response>
+ [HttpPost("downloads/batches")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
+ public async Task<IActionResult> EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request)
+ {
+ if (Program.IsRelayAgent)
+ {
+ return Forbid();
+ }
+
+ if (!ModelState.IsValid)
+ {
+ return BadRequest(ModelState.GetReadableString());
+ }
+
+ if (request.Files.Any(r => r is null))
+ {
+ return BadRequest("One or more files in the request are null");
+ }
+
+ if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count)
+ {
+ return BadRequest("Two or more files in the request are repeated");
+ }
+
+ Guid? batchId;
+ Guid? searchId;
+
+ try
+ {
+ batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id);
+ searchId = string.IsNullOrWhiteSpace(request.SearchId) ? null : Guid.Parse(request.SearchId);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message);
+ return BadRequest("One or more provided identifiers is not a valid GUID/UUID");
+ }
+
+ batchId ??= Guid.NewGuid();
+
+ if (!DownloadRequestLimiter.Wait(0))
+ {
+ return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes");
+ }
+
+ try
+ {
+ var endpoint = await Users.GetIPEndPointAsync(request.Username);
+
+ if (Users.IsBlacklisted(request.Username, endpoint.Address))
+ {
+ throw new UserOfflineException($"User {request.Username} appears to be offline");
+ }
+
+ // throws DuplicateException if a record already exists
+ await Transfers.Downloads.Batches.CreateAsync(new()
+ {
+ Id = batchId.Value,
+ SearchId = searchId,
+ Username = request.Username,
+ Options = new()
+ {
+ Destination = request.Options.Destination,
+ },
+ });
+
+ // Transfer records will have been inserted before this returns, unless they were rejected
+ // because they were already in progress, in which case they will show up in 'failed'. or maybe they
+ // failed with an error. either way this complicates the return code
+ var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(
+ username: request.Username,
+ files: request.Files.Select(r => (r.Filename, r.Size.Value)),
+ batchId: batchId);
+
+ if (failed.Count > 0)
+ {
+ Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed);
+ }
+
+ // the returned batch will have whatever Transfers were successfully inserted attached (via Include())
+ // failed transfers MAY or MAY NOT have an associated database record. if they do, it should have been
+ // properly finalized and marked as a failure
+ var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId);
+
+ var response = new QueueDownloadBatchResponse
+ {
+ Batch = batch,
+ Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(),
+ };
+
+ // basically a no-op, but we did create the batch record (and it's useless, but it's there)
+ // there's nothing to process asynchronously, so we'll return 200. 204 makes more sense to me,
+ // but it doesn't allow a body and without it the caller will never know the id unless they supplied it
+ if (response.Failures.Count == request.Files.Count)
+ {
+ return StatusCode(StatusCodes.Status200OK, response);
+ }
+
+ // if at least one (but not all) failed, we're in a weird state so send the most appropriate status code
+ // along with the batch and list of failures; the caller will have to pick through it and decide what to do
+ if (response.Failures.Count > 0)
+ {
+ return StatusCode(StatusCodes.Status207MultiStatus, response);
+ }
+
+ // everything passed and we are now (or will eventually be) downloading asynchronously
+ return StatusCode(StatusCodes.Status201Created, response);
+ }
+ catch (UserOfflineException ex)
+ {
+ return StatusCode(StatusCodes.Status404NotFound, ex.Message);
+ }
+ catch (DuplicateException ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id);
+ return Conflict($"A batch with ID {batchId} already exists");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username} (batch Id: {BatchId}): {Message}", request.Files.Count, request.Username, batchId, ex.Message);
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ finally
+ {
+ DownloadRequestLimiter.Release();
+ }
+ }
+
+ /// <summary>
/// Gets all downloads.
/// </summary>
/// <returns></returns>
@@ -313,6 +469,47 @@ namespace slskd.Transfers.API
}
/// <summary>
+ /// Gets the specified batch and associated transfers.
+ /// </summary>
+ /// <param name="id">The id of the batch.</param>
+ /// <returns></returns>
+ /// <response code="400">The specified id is not valid.</response>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified batch was not found.</response>
+ [HttpGet("downloads/batches/{id}")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(200)]
+ public async Task<IActionResult> Get([FromRoute, Required] string id)
+ {
+ if (Program.IsRelayAgent)
+ {
+ return Forbid();
+ }
+
+ if (!Guid.TryParse(id, out var guid))
+ {
+ return BadRequest($"The specified id {id} is not a valid GUID/UUID");
+ }
+
+ try
+ {
+ var found = await Transfers.Downloads.Batches.FindAsync(b => b.Id == guid);
+
+ if (found is null)
+ {
+ return NotFound();
+ }
+
+ return Ok(found);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to get batch with ID {Id}: {Message}", guid, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
/// Gets all downloads for the specified username.
/// </summary>
/// <param name="username"></param>
@@ -351,7 +548,7 @@ namespace slskd.Transfers.API
[HttpGet("downloads/{username}/{id}")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(API.Transfer), 200)]
+ [ProducesResponseType(typeof(Transfer), 200)]
[ProducesResponseType(404)]
public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id)
{
@@ -386,7 +583,7 @@ namespace slskd.Transfers.API
/// <response code="404">The specified download was not found.</response>
[HttpGet("downloads/{username}/{id}/position")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(API.Transfer), 200)]
+ [ProducesResponseType(typeof(Transfer), 200)]
[ProducesResponseType(404)]
public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id)
{
diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs
new file mode 100644
index 00000000..fe34bfec
--- /dev/null
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs
@@ -0,0 +1,118 @@
+// <copyright file="QueueDownloadBatchRequest.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>
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+
+namespace slskd.Transfers.API;
+
+/// <summary>
+/// Enqueue a batch of downloads.
+/// </summary>
+public record QueueDownloadBatchRequest
+{
+ /// <summary>
+ /// The ID of the Batch.
+ /// </summary>
+ /// <remarks>
+ /// If not supplied, one will be randomly generated.
+ /// </remarks>
+ [Guid]
+ public string Id { get; init; }
+
+ /// <summary>
+ /// The ID of the associated Search, if applicable.
+ /// </summary>
+ [Guid]
+ public string SearchId { get; init; }
+
+ /// <summary>
+ /// The username of the user from which to download.
+ /// </summary>
+ [Required]
+ [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)]
+ public string Username { get; init; }
+
+ /// <summary>
+ /// The list of files to download.
+ /// </summary>
+ [Required]
+ [MinLength(1)]
+ public IReadOnlyCollection<EnqueueDownloadBatchItem> Files { get; init; } = [];
+
+ /// <summary>
+ /// Options for the Batch.
+ /// </summary>
+ public EnqueueDownloadBatchOptions Options { get; init; } = new();
+}
+
+/// <summary>
+/// An item in a download batch.
+/// </summary>
+public record EnqueueDownloadBatchItem
+{
+ /// <summary>
+ /// The name of the file.
+ /// </summary>
+ [Required]
+ [NotNullOrWhiteSpace]
+ [NonTraversingPath]
+ public string Filename { get; init; }
+
+ /// <summary>
+ /// The file size.
+ /// </summary>
+ [Required]
+ [Range(0, long.MaxValue)]
+ public long? Size { get; init; }
+}
+
+/// <summary>
+/// Download batch options.
+/// </summary>
+public record EnqueueDownloadBatchOptions
+{
+ /// <summary>
+ /// The destination directory for the files, relative to the configured download directory.
+ /// </summary>
+ [RelativePath(OperatingSystem.All)]
+ [NonTraversingPath]
+ [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
+ public string Destination { get; init; }
+
+ /// <summary>
+ /// An optional external ID for the batch.
+ /// </summary>
+ public string ExternalId { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs
index ce3331ca..84b570bc 100644
--- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs
@@ -1,4 +1,4 @@
-// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham">
+// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham">
// โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„
// โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆ
// โ–ˆ__ --โ–ˆ โ–ˆ__ --โ–ˆ โ—„โ–ˆ - โ–ˆ
@@ -30,28 +30,18 @@
// โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ถโ”€โ”€โ”€โ”€ โ”€ โ”€โ”€โ”€ โ”€ โ”€โ”€ โ”€โ”€โ”ˆ โ”ˆ
// </copyright>
-using System;
using System.Collections.Generic;
-using System.ComponentModel.DataAnnotations;
namespace slskd.Transfers.API;
-public record EnqueueDownloadBatchRequest
+public record QueueDownloadBatchResponse
{
- public Guid? BatchId { get; init; }
- public Guid? SearchId { get; init; }
-
- [Required]
- [StringLength(500, MinimumLength = 1)]
- public string Username { get; init; }
- public List<EnqueueDownloadBatchItem> Files { get; init; } = [];
+ public Batch Batch { get; init; }
+ public IReadOnlyCollection<QueueDownloadBatchResponseFailure> Failures { get; init; } = [];
}
-public record EnqueueDownloadBatchItem
+public record QueueDownloadBatchResponseFailure
{
- [Required]
- public string Filename { get; set; }
-
- [Range(0, int.MaxValue)]
- public long Size { get; set; }
-} \ No newline at end of file
+ public string Filename { get; init; }
+ public string Message { get; init; }
+}
diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs
deleted file mode 100644
index 949f15d4..00000000
--- a/src/slskd/Transfers/API/DTO/Transfer.cs
+++ /dev/null
@@ -1,169 +0,0 @@
-// <copyright file="Transfer.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.API
-{
- using System;
- using System.Net;
- using Soulseek;
-
- /// <summary>
- /// A single file transfer.
- /// </summary>
- public class Transfer
- {
- /// <summary>
- /// Gets the current average transfer speed.
- /// </summary>
- public double AverageSpeed { get; set; }
-
- /// <summary>
- /// Gets the number of remaining bytes to be transferred.
- /// </summary>
- public long BytesRemaining { get; set; }
-
- /// <summary>
- /// Gets the total number of bytes transferred.
- /// </summary>
- public long BytesTransferred { get; set; }
-
- /// <summary>
- /// Gets the transfer direction.
- /// </summary>
- public TransferDirection Direction { get; set; }
-
- /// <summary>
- /// Gets the current duration of the transfer, if it has been started.
- /// </summary>
- public double? ElapsedTime { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state.
- /// </summary>
- public DateTime? EndTime { get; set; }
-
- /// <summary>
- /// Gets the filename of the file to be transferred.
- /// </summary>
- public string Filename { get; set; }
-
- /// <summary>
- /// Gets the transfer id.
- /// </summary>
- public string Id => Compute.Sha1Hash(Filename);
-
- /// <summary>
- /// Gets the ip endpoint of the remote transfer connection, if one has been established.
- /// </summary>
- public IPEndPoint IPEndPoint { get; set; }
-
- /// <summary>
- /// Gets the current progress in percent.
- /// </summary>
- public double PercentComplete { get; set; }
-
- /// <summary>
- /// Gets the current place in queue, if it has been fetched.
- /// </summary>
- public int? PlaceInQueue { get; set; }
-
- /// <summary>
- /// Gets the projected remaining duration of the transfer.
- /// </summary>
- public double? RemainingTime { get; set; }
-
- /// <summary>
- /// Gets the remote unique token for the transfer.
- /// </summary>
- public int? RemoteToken { get; set; }
-
- /// <summary>
- /// Gets the size of the file to be transferred, in bytes.
- /// </summary>
- public long Size { get; set; }
-
- /// <summary>
- /// Gets the starting offset of the transfer, in bytes.
- /// </summary>
- public long StartOffset { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state.
- /// </summary>
- public DateTime? StartTime { get; set; }
-
- /// <summary>
- /// Gets the state of the transfer.
- /// </summary>
- public TransferStates State { get; set; }
-
- /// <summary>
- /// Gets the unique token for the transfer.
- /// </summary>
- public int Token { get; set; }
-
- /// <summary>
- /// Gets the username of the peer to or from which the file is to be transferred.
- /// </summary>
- public string Username { get; set; }
-
- /// <summary>
- /// Gets the Exception that caused the failure of the transfer, if applicable.
- /// </summary>
- public string Exception { get; set; }
-
- public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer)
- {
- return new Transfer()
- {
- AverageSpeed = transfer.AverageSpeed,
- BytesRemaining = transfer.BytesRemaining,
- BytesTransferred = transfer.BytesTransferred,
- Direction = transfer.Direction,
- ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds,
- EndTime = transfer.EndTime,
- Filename = transfer.Filename,
- IPEndPoint = transfer.IPEndPoint,
- PercentComplete = transfer.PercentComplete,
- RemainingTime = transfer.RemainingTime?.TotalMilliseconds,
- RemoteToken = transfer.RemoteToken,
- Size = transfer.Size,
- StartOffset = transfer.StartOffset,
- StartTime = transfer.StartTime,
- State = transfer.State,
- Token = transfer.Token,
- Username = transfer.Username,
- Exception = transfer.Exception?.Message,
- };
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs
new file mode 100644
index 00000000..7ea9a70a
--- /dev/null
+++ b/src/slskd/Transfers/Downloads/BatchService.cs
@@ -0,0 +1,140 @@
+// <copyright file="BatchService.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.Downloads;
+
+using System;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Threading.Tasks;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
+using Serilog;
+
+/// <summary>
+/// Manages transfer batches.
+/// </summary>
+public interface IBatchService
+{
+ /// <summary>
+ /// Creates a new batch record.
+ /// </summary>
+ /// <param name="batch">The batch to create.</param>
+ /// <returns>The created batch.</returns>
+ Task<Batch> CreateAsync(Batch batch);
+
+ /// <summary>
+ /// Finds a single batch matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match batches.</param>
+ /// <returns>The found batch, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception>
+ Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression);
+}
+
+/// <summary>
+/// Manages transfer batches.
+/// </summary>
+public class BatchService : IBatchService
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BatchService"/> class.
+ /// </summary>
+ /// <param name="contextFactory">The database context factory to use.</param>
+ public BatchService(IDbContextFactory<TransfersDbContext> contextFactory)
+ {
+ ContextFactory = contextFactory;
+ }
+
+ private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<BatchService>();
+
+ /// <summary>
+ /// Creates a new batch record.
+ /// </summary>
+ /// <param name="batch">The batch to create.</param>
+ /// <returns>The created batch.</returns>
+ public async Task<Batch> CreateAsync(Batch batch)
+ {
+ if (batch == default)
+ {
+ throw new ArgumentNullException(nameof(batch));
+ }
+
+ if (batch.Id == Guid.Empty)
+ {
+ throw new ArgumentOutOfRangeException(nameof(batch.Id), message: $"Batch ID may not be an empty uuid ({Guid.Empty})");
+ }
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ context.Batches.Add(batch);
+
+ await context.SaveChangesAsync();
+
+ return batch;
+ }
+ catch (DbUpdateException ex) when (ex.InnerException is SqliteException { SqliteErrorCode: 19 })
+ {
+ throw new DuplicateException($"A Batch with ID {batch.Id} already exists.");
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Failed to create Batch: {Message}", ex.Message);
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Finds a single batch matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match batches.</param>
+ /// <returns>The found batch, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception>
+ public async Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression)
+ {
+ if (expression == default)
+ {
+ throw new ArgumentException("An expression must be supplied.", nameof(expression));
+ }
+
+ using var context = ContextFactory.CreateDbContext();
+
+ return await context.Batches
+ .AsNoTracking()
+ .Include(b => b.Transfers)
+ .Where(expression)
+ .SingleOrDefaultAsync();
+ }
+}
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index d4d8004a..7c794e55 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -38,9 +38,11 @@ namespace slskd.Transfers.Downloads
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+ using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
+ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
@@ -49,6 +51,7 @@ namespace slskd.Transfers.Downloads
using slskd.Files;
using slskd.Integrations.FTP;
using slskd.Relay;
+ using slskd.Search;
/// <summary>
/// Manages downloads.
@@ -56,6 +59,11 @@ namespace slskd.Transfers.Downloads
public interface IDownloadService
{
/// <summary>
+ /// Gets download batch service.
+ /// </summary>
+ IBatchService Batches { get; }
+
+ /// <summary>
/// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
/// </summary>
/// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks>
@@ -63,6 +71,26 @@ namespace slskd.Transfers.Downloads
void AddOrSupersede(Transfer transfer);
/// <summary>
+ /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and batch
+ /// configuration.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
+ /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop.
+ /// </para>
+ /// <para>
+ /// Empty segments may be present in the output, which more closely aligns with user intent. The
+ /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact.
+ /// </para>
+ /// </remarks>
+ /// <param name="transfer">The transfer.</param>
+ /// <returns>The derived destination directory.</returns>
+ /// <exception cref="NotFoundException">Thrown if the specified download doesn't exist.</exception>
+ /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception>
+ Task<string> DeriveDestination(Transfer transfer);
+
+ /// <summary>
/// Enqueues the requested list of <paramref name="files"/>.
/// </summary>
/// <remarks>
@@ -71,12 +99,13 @@ namespace slskd.Transfers.Downloads
/// </remarks>
/// <param name="username">The username of remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="batchId">The optional batch id for the transfers.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default);
+ Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default);
/// <summary>
/// Finds a single download matching the specified <paramref name="expression"/>.
@@ -158,6 +187,8 @@ namespace slskd.Transfers.Downloads
public class DownloadService : IDownloadService
{
public DownloadService(
+ IBatchService batchService,
+ ISearchService searchService,
IOptionsMonitor<Options> optionsMonitor,
ISoulseekClient soulseekClient,
IDbContextFactory<TransfersDbContext> contextFactory,
@@ -166,6 +197,8 @@ namespace slskd.Transfers.Downloads
IFTPService ftpClient,
EventBus eventBus)
{
+ Batches = batchService;
+ Searches = searchService;
Client = soulseekClient;
OptionsMonitor = optionsMonitor;
ContextFactory = contextFactory;
@@ -178,6 +211,11 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
+ /// Gets download batch service.
+ /// </summary>
+ public IBatchService Batches { get; }
+
+ /// <summary>
/// These tokens give users the ability to cancel transfers via the UI (or API).
///
/// The lifecycle is:
@@ -200,10 +238,12 @@ namespace slskd.Transfers.Downloads
private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
private IFTPService FTP { get; }
private FileService Files { get; }
+ private ISearchService Searches { get; }
private IRelayService Relay { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
private EventBus EventBus { get; }
+ private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they
@@ -249,12 +289,13 @@ namespace slskd.Transfers.Downloads
/// </summary>
/// <param name="username">The username of the remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="batchId">The optional batch id for the transfers.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- public async Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
+ public async Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
@@ -273,6 +314,11 @@ namespace slskd.Transfers.Downloads
throw new ArgumentException("At least one filename is null or empty", nameof(files));
}
+ if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename)))
+ {
+ throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files));
+ }
+
if (fileList.Count != fileList.Distinct().Count())
{
throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
@@ -306,7 +352,7 @@ namespace slskd.Transfers.Downloads
}
List<Transfer> enqueued = [];
- List<string> failed = [];
+ List<(string Filename, string Message)> failed = [];
SemaphoreSlim userSemaphore;
Task userSemaphoreWaitTask;
@@ -404,7 +450,7 @@ namespace slskd.Transfers.Downloads
if (existingInProgressRecord is not null)
{
Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
@@ -416,7 +462,7 @@ namespace slskd.Transfers.Downloads
if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false)
{
Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
@@ -431,11 +477,11 @@ namespace slskd.Transfers.Downloads
var transfer = new Transfer()
{
Id = transferId,
+ BatchId = batchId,
Username = username,
Direction = TransferDirection.Download,
Filename = file.Filename, // important! use the remote filename
Size = file.Size,
- StartOffset = 0, // todo: maybe implement resumeable downloads?
RequestedAt = DateTime.UtcNow,
State = TransferStates.Queued | TransferStates.Locally,
};
@@ -607,7 +653,7 @@ namespace slskd.Transfers.Downloads
{
Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
TryFail(transferId, exception: ex);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, $"Error: {ex.Message}"));
if (CancellationTokens.TryRemove(transferId, out var cts))
{
@@ -689,6 +735,152 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
+ /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and
+ /// batch configuration.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
+ /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop.
+ /// </para>
+ /// <para>
+ /// Empty segments may be present in the output, which more closely aligns with user intent. The
+ /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact.
+ /// </para>
+ /// </remarks>
+ /// <param name="transfer">The transfer.</param>
+ /// <returns>The derived destination directory.</returns>
+ /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception>
+ public async Task<string> DeriveDestination(Transfer transfer)
+ {
+ // validation should ensure this is a relative path and that it contains no traversal segments
+ // we accept any type of slash in the pattern and convert it to the correct variant for the local OS
+ var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory;
+
+ // users can enter '{}' if they want the files to go directly into the root of the downloads directory
+ if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase))
+ {
+ return string.Empty;
+ }
+
+ string source_username;
+ string source_path;
+ string source_directory;
+ string batch_id;
+ string batch_external_id;
+ string search_id;
+ string search_text;
+
+ /*
+ fetch/extract/derive and sanitize each of the values we're going to replace
+
+ when flow leaves this block we can expect that all of the string values
+ defined above have a value that can be safely substituted for its placeholder
+ */
+ try
+ {
+ Batch batch = null;
+
+ if (transfer.BatchId is not null)
+ {
+ batch = await Batches.FindAsync(b => b.Id == transfer.BatchId);
+ }
+
+ // destination supplied with the batch enqueue request takes precedence over all; return early
+ if (!string.IsNullOrWhiteSpace(batch?.Options?.Destination))
+ {
+ var explicitDestination = FileSafety.SanitizePath(batch.Options.Destination, replacement: '_');
+
+ // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
+ // properly sanitizing user input both via the API and in the logic above
+ if (FileSafety.IsPathAbsolute(explicitDestination) || FileSafety.ContainsTraversalSegments(explicitDestination))
+ {
+ throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub.");
+ }
+
+ return explicitDestination;
+ }
+
+ Search search = null;
+
+ if (batch?.SearchId is not null)
+ {
+ search = await Searches.FindAsync(s => s.Id == batch.SearchId);
+ }
+
+ source_username = FileSafety.SanitizeFilename(transfer.Username, replacement: '_');
+
+ var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_');
+
+ // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz'
+ // 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, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\');
+
+ // name of the remote parent directory, so using the example above, 'Baz'
+ source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\');
+
+ batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString();
+
+ // the external id can be any string (it is supplied via API call) so we have to sanitize it just like the destination,
+ // except we don't want to allow it to tack on directories; that's not what it is for and it could be unintended
+ batch_external_id = FileSafety.SanitizeFilename(
+ filename: string.IsNullOrWhiteSpace(batch?.Options?.ExternalId) ? "unknown_batch_external_id" : batch.Options.ExternalId,
+ replacement: '_');
+
+ search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString();
+ search_text = FileSafety.SanitizeFilename(
+ filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText,
+ replacement: '_');
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message);
+ throw;
+ }
+
+ var args = new Dictionary<string, string>(
+ StringComparer.OrdinalIgnoreCase) // important!
+ {
+ ["SOURCE_USERNAME"] = source_username,
+ ["SOURCE_PATH"] = source_path,
+ ["SOURCE_DIRECTORY"] = source_directory,
+ ["BATCH_ID"] = batch_id,
+ ["BATCH_EXTERNAL_ID"] = batch_external_id,
+ ["SEARCH_ID"] = search_id,
+ ["SEARCH_TEXT"] = search_text,
+ };
+
+ // use Regex.Replace here because it makes one pass; if we chained .Replace() calls the output from one could
+ // cascade into others and produce unintended results
+ var destination = SubdirectoryPatternTokenRegex.Replace(
+ input: pattern,
+ evaluator: match =>
+ {
+ if (args.TryGetValue(match.Groups[1].Value, out var value))
+ {
+ return value;
+ }
+
+ return match.Value;
+ });
+
+ destination = FileSafety.SanitizePath(destination, replacement: '_');
+
+ 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})", 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.");
+ }
+
+ return destination;
+ }
+
+ /// <summary>
/// Returns a list of all downloads matching the optional <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An optional expression used to match downloads.</param>
@@ -973,9 +1165,11 @@ namespace slskd.Transfers.Downloads
// the final update after all retry attempts have been exhausted to add it.
// this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all
// retries is to look for this flag
- if (transfer.Attempts < retryOptions.Attempts)
+ if (args.Transfer.State.HasFlag(TransferStates.Completed)
+ && !args.Transfer.State.HasFlag(TransferStates.Succeeded)
+ && transfer.Attempts < retryOptions.Attempts)
{
- transfer.State &= ~TransferStates.Completed; // remove the Completed flag
+ transfer.State = TransferStates.Queued | TransferStates.Locally;
}
// todo: broadcast
@@ -1024,16 +1218,42 @@ namespace slskd.Transfers.Downloads
}),
disposeOutputStreamOnCompletion: true);
- System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode)
- ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
+ UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode)
+ ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode()
: null;
- // if the transfer has an associated batch id, store the incomplete file in a directory of the same name
- // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file)
- var incompleteFilename = transfer.Filename.ToLocalFilename(
- baseDirectory: System.IO.Path.Combine(
- OptionsMonitor.CurrentValue.Directories.Incomplete,
- transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty));
+ /*
+ 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) ?? string.Empty;
+
+ var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename);
+
+ Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename);
Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username);
transfer.Attempts = 1;
@@ -1042,14 +1262,14 @@ namespace slskd.Transfers.Downloads
var completedTransfer = await Retry.Do(() =>
{
var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename);
- var incompleteStrategy = retryOptions.Incomplete.ToEnum<RetryIncompleteStrategy>();
+ var incompleteStrategy = retryOptions.Partial.ToEnum<RetryPartialStrategy>();
var shouldResume = false;
var startOffset = 0L;
if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0)
{
- if (incompleteStrategy == RetryIncompleteStrategy.Resume)
+ if (incompleteStrategy == RetryPartialStrategy.Resume)
{
shouldResume = true;
startOffset = incompleteFileInfo.Length;
@@ -1121,33 +1341,29 @@ namespace slskd.Transfers.Downloads
move the file from incomplete to complete
users have a lot of strong opinions about this!
+
+ the destination is always rooted in the configured download directory. we derive the subdirectory
+ for this file based on either the Destination property defined for the Batch that contains this transfer,
+ or by applying replacements to the user's configured Destination.Subdirectory string.
+
+ what we get back will be a relative path (or perhaps an empty string if that's what the user wanted)
+ that has sanitized and checked for safety against traversal
*/
- string destinationDirectory;
+ var subdirectory = await DeriveDestination(transfer);
+ var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory);
- if (transfer.BatchId is not null)
- {
- // if the transfer has an associated batch id, then:
- // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext
- destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString());
- }
- else
- {
- // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so:
- // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext
- // this is "legacy" behavior that will be familiar to most Soulseek users
- destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads));
- }
+ var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum<DestinationExistsStrategy>();
Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory);
var finalFilename = Files.MoveFile(
- sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
+ sourceFilename: incompleteFilename,
destinationDirectory: destinationDirectory,
unixFileMode: unixFileMode,
- overwrite: false,
+ overwrite: existsStrategy == DestinationExistsStrategy.Overwrite,
deleteSourceDirectoryIfEmptyAfterMove: true);
- Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename);
+ Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename);
if (OptionsMonitor.CurrentValue.Relay.Enabled)
{
diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs
index 48179ff2..3180dbd9 100644
--- a/src/slskd/Transfers/Extensions.cs
+++ b/src/slskd/Transfers/Extensions.cs
@@ -44,7 +44,6 @@ namespace slskd.Transfers
Direction = transfer.Direction,
Filename = transfer.Filename,
Size = transfer.Size,
- StartOffset = t.StartOffset,
State = t.State,
RequestedAt = transfer.RequestedAt,
EnqueuedAt = transfer.EnqueuedAt,
diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index be312e8e..b25e7663 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -33,6 +33,7 @@
namespace slskd.Transfers
{
using System;
+ using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
@@ -43,16 +44,23 @@ namespace slskd.Transfers
{
}
+ public DbSet<Batch> Batches { get; set; }
public DbSet<Transfer> Transfers { get; set; }
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
// this is absolutely NOT IDEAL and will accellerate the move away from EF
+ // we have to do this to store both the integer and the string value in the database
+ // well, we don't *HAVE* to, but storing the string allows external apps to understand transfer history
+ // and not need to work out the flags. storing the integer allows us to use bitwise operations in queries,
+ // which is the main driver for this.
foreach (var entry in ChangeTracker.Entries<Transfer>())
{
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
+#pragma warning disable CS0618 // Type or member is obsolete
entry.Entity.StateDescription = entry.Entity.State.ToString();
+#pragma warning restore CS0618 // Type or member is obsolete
}
}
@@ -61,6 +69,12 @@ namespace slskd.Transfers
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
+ ConfigureTransfers(modelBuilder);
+ ConfigureBatches(modelBuilder);
+ }
+
+ private void ConfigureTransfers(ModelBuilder modelBuilder)
+ {
modelBuilder
.Entity<Transfer>()
.Property(e => e.StartedAt)
@@ -114,5 +128,34 @@ namespace slskd.Transfers
.HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size })
.HasDatabaseName("IDX_Transfers_UserUploadStatistics");
}
+
+ private void ConfigureBatches(ModelBuilder modelBuilder)
+ {
+ modelBuilder
+ .Entity<Batch>()
+ .Property(e => e.CreatedAt)
+ .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
+
+ modelBuilder
+ .Entity<Batch>()
+ .HasMany(b => b.Transfers)
+ .WithOne()
+ .HasForeignKey(t => t.BatchId)
+ .IsRequired(false)
+ .OnDelete(DeleteBehavior.Cascade);
+
+ modelBuilder
+ .Entity<Batch>()
+ .Property(b => b.Options)
+ .HasConversion(
+ convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()),
+ convertFromProviderExpression: v => JsonSerializer.Deserialize<BatchOptions>(v, new JsonSerializerOptions().WithStandardOptions()))
+ .HasColumnType("TEXT");
+
+ modelBuilder
+ .Entity<Batch>()
+ .HasIndex(b => b.SearchId)
+ .HasDatabaseName("IDX_Batches_SearchId");
+ }
}
}
diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs
new file mode 100644
index 00000000..a0d71bef
--- /dev/null
+++ b/src/slskd/Transfers/Types/Batch.cs
@@ -0,0 +1,118 @@
+// <copyright file="Batch.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;
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Soulseek;
+
+/// <summary>
+/// <para>
+/// A Transfer Batch is a lightweight association between a number of related Transfer
+/// records and optionally the associated Search the Transfers are intended to fulfil.
+/// </para>
+/// <para>
+/// Transfers may be enqueued in a Batch, and a caller that enqueued a Batch may use the
+/// available API(s) to determine whether all of the Transfers within the Batch are complete,
+/// but otherwise a Batch serves no functional purpose within the application.
+/// </para>
+/// </summary>
+public record Batch
+{
+ /// <summary>
+ /// Gets the associated <see cref="slskd.Search.Search.Id"/>, if one was specified when the
+ /// Batch was enqueued.
+ /// </summary>
+ public Guid? SearchId { get; init; } = null;
+
+ /// <summary>
+ /// Gets the unique identifier for the Batch.
+ /// </summary>
+ [Key]
+ public Guid Id { get; init; }
+
+ /// <summary>
+ /// Gets the username associated with the Batch.
+ /// </summary>
+ public string Username { get; init; }
+
+ /// <summary>
+ /// Gets the Batch direction (Upload, Download).
+ /// </summary>
+ /// <remarks>
+ /// We don't have, and likely will never be able to implement, upload batches,
+ /// nor are they of any particular use.
+ /// </remarks>
+ public TransferDirection Direction { get; init; } = TransferDirection.Download;
+
+ /// <summary>
+ /// Gets the time at which the Batch was created.
+ /// </summary>
+ public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
+
+ /// <summary>
+ /// Gets the Transfer records associated with the batch.
+ /// </summary>
+ public ICollection<Transfer> Transfers { get; init; } = null;
+
+ /// <summary>
+ /// Gets the options for the batch.
+ /// </summary>
+ public BatchOptions Options { get; init; }
+
+ /*
+ future: [NotMapped] properties that aggregate values from the associated Transfer records.
+ there's no use for these now, but if we ever decide to leverage Batch records for anything
+ but determining whether a Search has been fulfilled, allowing a user to override a download directory,
+ or to handle an event when a batch is completed, we can add them and figure out how persistence should work.
+
+ file count and size are also not included because of the transfer deduplication that takes place during
+ the enqueue; if a batch is created and some or all of the files within are already in progress, they are
+ dropped and no new transfer records are created. this would create data inconsistency, and for no reason (for now)
+
+ loading Transfers and doing aggregation in memory (if fetching 1 batch) or querying and aggregating Transfer
+ records in SQL and then updating a list of Batch records in memory (if fetching a list) technically works,
+ but is unlikely to perform well, especially as data grows, and ESPECIALLY when excliding 'Removed' Batches
+ from results (as this must be aggregated on the fly for each batch.. forever)
+
+ my thinking (and reason for punting on this for now); add the interesting properties (Removed, BytesTransferred,
+ AverageSpeed, etc) to this class as nullable, and don't set a value until all of the associated Transfer
+ records have been finalized, then update the columns. when fetching batches we can deduce that any Batch
+ record missing those properties is still in progress, and we can aggregate the data on the fly. for historical
+ records that have completed, the data is all in the database and is quick to query.
+
+ this can sit until/if we have further use for Batch records, i want to get this out and don't want to sit
+ and go back and forth trying to speculate on how this might need to work in the future.
+ */
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs
new file mode 100644
index 00000000..2ea22997
--- /dev/null
+++ b/src/slskd/Transfers/Types/BatchOptions.cs
@@ -0,0 +1,53 @@
+// <copyright file="BatchOptions.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>
+/// Options for <see cref="Batch"/>es.
+/// </summary>
+public record BatchOptions
+{
+ /// <summary>
+ /// Gets the optional destination directory for the files in the Batch, relative to the configured
+ /// download directory.
+ /// </summary>
+ /// <remarks>
+ /// If specified, takes precedence over other configured placement rules.
+ /// </remarks>
+ public string Destination { get; init; }
+
+ /// <summary>
+ /// Gets an optional external ID for the batch.
+ /// </summary>
+ public string ExternalId { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs
new file mode 100644
index 00000000..27281a2d
--- /dev/null
+++ b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs
@@ -0,0 +1,49 @@
+// <copyright file="DestinationConflictStrategy.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 with conflicting names.
+/// </summary>
+public enum DestinationConflictStrategy
+{
+ /// <summary>
+ /// Rename the new file by appending something.
+ /// </summary>
+ Rename = 0,
+
+ /// <summary>
+ /// Overwrite the existing file.
+ /// </summary>
+ 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 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/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryPartialStrategy.cs
index 9ac8d8e2..20868913 100644
--- a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs
+++ b/src/slskd/Transfers/Types/RetryPartialStrategy.cs
@@ -1,4 +1,4 @@
-// <copyright file="RetryIncompleteStrategy.cs" company="JP Dillingham">
+// <copyright file="RetryPartialStrategy.cs" company="JP Dillingham">
// โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„
// โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆ
// โ–ˆ__ --โ–ˆ โ–ˆ__ --โ–ˆ โ—„โ–ˆ - โ–ˆ
@@ -33,9 +33,9 @@
namespace slskd.Transfers;
/// <summary>
-/// Strategy for retrying incomplete files.
+/// Strategy for retrying partial files.
/// </summary>
-public enum RetryIncompleteStrategy
+public enum RetryPartialStrategy
{
/// <summary>
/// Overwrite the existing file.
@@ -43,7 +43,7 @@ public enum RetryIncompleteStrategy
Overwrite = 0,
/// <summary>
- /// Resume the transfer using the size of the incomplete file as the initial offset.
+ /// Resume the transfer using the size of the partial file as the initial offset.
/// </summary>
Resume = 1,
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs
index 93a23380..d33a5efc 100644
--- a/src/slskd/Transfers/Types/Transfer.cs
+++ b/src/slskd/Transfers/Types/Transfer.cs
@@ -30,72 +30,146 @@
// โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ถโ”€โ”€โ”€โ”€ โ”€ โ”€โ”€โ”€ โ”€ โ”€โ”€ โ”€โ”€โ”ˆ โ”ˆ
// </copyright>
-namespace slskd.Transfers
+namespace slskd.Transfers;
+
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Text.Json.Serialization;
+using Soulseek;
+
+/// <summary>
+/// A file Transfer between network peers.
+/// </summary>
+public class Transfer
{
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text.Json.Serialization;
- using Soulseek;
-
- public class Transfer
- {
- public Guid? BatchId { get; init; } = null;
-
- [Key]
- public Guid Id { get; init; }
- public string Username { get; init; }
- public TransferDirection Direction { get; init; }
-
- /// <summary>
- /// Gets the remote filename.
- /// </summary>
- public string Filename { get; init; }
- public long Size { get; set; }
- public long StartOffset { get; init; }
-
- public TransferStates State { get; set; } = TransferStates.None;
-
- /// <summary>
- /// Gets the string representation of the transfer <see cref="State"/>.
- /// </summary>
- /// <remarks>
- /// This is a hack to get the string into the database. *DO NOT* use this property in code
- /// and especially **DO NOT** set the value. The getter and setter can't be protected because
- /// EF Core needs them to be public.
- /// </remarks>
- public string StateDescription { get; set; }
- public DateTime RequestedAt { get; set; }
- public DateTime? EnqueuedAt { get; set; }
- public DateTime? StartedAt { get; set; }
-
- /// <summary>
- /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress.
- /// </summary>
- /// <remarks>
- /// Guaranteed to be set for transfers in a terminal state.
- /// </remarks>
- public DateTime? EndedAt { get; set; }
- public long BytesTransferred { get; set; }
- public double AverageSpeed { get; set; }
-
- public int? PlaceInQueue { get; set; }
- public string Exception { get; set; }
-
- public int Attempts { get; set; } = 0;
-
- public DateTime? NextAttemptAt { get; set; } = null;
-
- [JsonIgnore]
- public bool Removed { get; set; }
-
- [NotMapped]
- public long BytesRemaining => Size - BytesTransferred;
- [NotMapped]
- public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value;
- [NotMapped]
- public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100;
- [NotMapped]
- public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed);
- }
+ /// <summary>
+ /// Gets the associated <see cref="Batch.Id"/>, if one was specified when the Transfer was created.
+ /// </summary>
+ public Guid? BatchId { get; init; } = null;
+
+ /// <summary>
+ /// Gets the unique identifier for the Transfer.
+ /// </summary>
+ [Key]
+ public Guid Id { get; init; }
+
+ /// <summary>
+ /// Gets the remote username associated with the Transfer.
+ /// </summary>
+ public string Username { get; init; }
+
+ /// <summary>
+ /// Gets the Transfer direction (Upload, Download).
+ /// </summary>
+ public TransferDirection Direction { get; init; }
+
+ /// <summary>
+ /// Gets the remote filename of the file.
+ /// </summary>
+ /// <remarks>
+ /// Exactly as it appeared in the originating Search, Browse, or file directory contents response.
+ /// </remarks>
+ public string Filename { get; init; }
+
+ /// <summary>
+ /// Gets or sets the remote size of the file.
+ /// </summary>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the state of the Transfer.
+ /// </summary>
+ public TransferStates State { get; set; } = TransferStates.None;
+
+ /// <summary>
+ /// Gets or sets the string representation of the transfer <see cref="State"/>.
+ /// </summary>
+ /// <remarks>
+ /// This is a hack to get the string into the database. *DO NOT* use this property in code
+ /// and especially **DO NOT** set the value. The getter and setter can't be protected because
+ /// EF Core needs them to be public.
+ /// </remarks>
+ [Obsolete("Use State isntead; this is a hack for EF")]
+ [JsonIgnore]
+ public string StateDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer was requested from the remote peer.
+ /// </summary>
+ public DateTime RequestedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer was enqueued, or null if the Transfer has not yet been enqueued.
+ /// </summary>
+ /// <remarks>
+ /// For downloads, this is the time at which the remote peer responded to our enqueue request. For uploads this
+ /// is the time at which the transfer was made available for scheduling by the upload queue, after we have
+ /// responded to the remote peer's request to enqueue.
+ /// </remarks>
+ public DateTime? EnqueuedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer connection was established and data transfer began, or null if the
+ /// Transfer has not yet been started.
+ /// </summary>
+ public DateTime? StartedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer ended, or null if the Transfer has not yet started or is still in progress.
+ /// </summary>
+ /// <remarks>
+ /// Guaranteed to be set for transfers in a terminal state.
+ /// </remarks>
+ public DateTime? EndedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of bytes transferred.
+ /// </summary>
+ public long BytesTransferred { get; set; }
+
+ /// <summary>
+ /// Gets or sets the average speed of the Transfer over the duration.
+ /// </summary>
+ public double AverageSpeed { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current place in line in the remote peer's queue, if place has been requested.
+ /// </summary>
+ /// <remarks>
+ /// May be wildly innacurate to the point of uselessness.
+ /// </remarks>
+ public int? PlaceInQueue { get; set; }
+
+ /// <summary>
+ /// Gets or sets the associated Exception, if the Transfer did not end successfully, or null if it did.
+ /// </summary>
+ public string Exception { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of attempts. Incremented each time the Transfer is retried.
+ /// </summary>
+ /// <remarks>
+ /// Applicable to downloads only.
+ /// </remarks>
+ public int Attempts { get; set; } = 0;
+
+ /// <summary>
+ /// Gets or sets the time at which the next retry attempt will be made, if applicable.
+ /// </summary>
+ public DateTime? NextAttemptAt { get; set; } = null;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the Transfer has been removed from the UI.
+ /// </summary>
+ public bool Removed { get; set; }
+
+ [NotMapped]
+ public long BytesRemaining => Size - BytesTransferred;
+ [NotMapped]
+ public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value;
+ [NotMapped]
+ public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100;
+ [NotMapped]
+ public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed);
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs
index 603c669a..333ae525 100644
--- a/src/slskd/Transfers/Types/TransferStateCategories.cs
+++ b/src/slskd/Transfers/Types/TransferStateCategories.cs
@@ -111,6 +111,7 @@ public static class TransferStateCategories
/// </list>
/// </summary>
public static readonly HashSet<TransferStates> Queued = [
+ TransferStates.Requested, // optimistically assume that we will be allowed to enqueue
TransferStates.Queued, // 2, in case of some sort of a malfunction or regression
TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050
TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index ebc6c4c6..894f739b 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -101,16 +101,6 @@ namespace slskd.Transfers.Uploads
Transfer Find(Expression<Func<Transfer, bool>> expression);
/// <summary>
- /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
- /// consider caching.
- /// </summary>
- /// <param name="expression">The expression used to select uploads for summarization.</param>
- /// <returns>
- /// The generated summary, including the number of files and total size in bytes.
- /// </returns>
- (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression);
-
- /// <summary>
/// Gets upload statistics for the specified <paramref name="username"/>.
/// </summary>
/// <param name="username">The username of the user.</param>
@@ -678,7 +668,6 @@ namespace slskd.Transfers.Uploads
Direction = TransferDirection.Upload,
Filename = filename, // important! use the remote filename
Size = localFileLength,
- StartOffset = 0, // potentially updated later during handshaking
RequestedAt = DateTime.UtcNow,
State = TransferStates.Queued | TransferStates.Locally,
};
@@ -777,51 +766,12 @@ namespace slskd.Transfers.Uploads
return context.Transfers
.AsNoTracking()
.Where(t => t.Direction == TransferDirection.Upload)
- .Where(expression).FirstOrDefault();
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
- throw;
- }
- }
-
- /// <summary>
- /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
- /// consider caching.
- /// </summary>
- /// <param name="expression">The expression used to select uploads for summarization.</param>
- /// <returns>
- /// The generated summary, including the number of files and total size in bytes.
- /// </returns>
- public (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression)
- {
- expression ??= t => true;
-
- try
- {
- using var context = ContextFactory.CreateDbContext();
-
- var query = context.Transfers
- .AsNoTracking()
- .Where(t => t.Direction == TransferDirection.Upload)
.Where(expression)
- .GroupBy(t => true) // https://stackoverflow.com/a/25489456: The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group.
- .Select(t => new
- {
- Files = t.Count(),
- Bytes = t.Sum(x => x.Size),
- });
-
- Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString());
-
- var stats = query.FirstOrDefault();
-
- return (stats?.Files ?? 0, stats?.Bytes ?? 0);
+ .SingleOrDefault();
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to list uploads: {Message}", ex.Message);
+ Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
throw;
}
}
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index cf825701..cb6a7d83 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -43,41 +43,41 @@
</Target>
<ItemGroup>
- <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
- <PackageReference Include="Dapper" Version="2.1.66" />
+ <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" />
+ <PackageReference Include="Dapper" Version="2.1.79" />
<PackageReference Include="FluentFTP" Version="49.0.2" />
- <PackageReference Include="IPAddressRange" Version="6.0.0" />
- <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" />
- <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.6" />
- <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0">
+ <PackageReference Include="IPAddressRange" Version="6.3.0" />
+ <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
+ <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" />
+ <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.300">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
- <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.6" />
- <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
- <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="8.0.6" />
+ <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.8" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.8" />
<PackageReference Include="OneOf" Version="3.0.271" />
<PackageReference Include="prometheus-net" Version="8.2.1" />
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" />
<PackageReference Include="prometheus-net.AspNetCore.HealthChecks" Version="8.2.1" />
- <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.0" />
+ <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.1" />
<PackageReference Include="prometheus-net.SystemMetrics" Version="3.1.0" />
- <PackageReference Include="Serilog" Version="3.1.1" />
- <PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
- <PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
- <PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
- <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
- <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" />
- <PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" />
- <PackageReference Include="Soulseek" Version="10.0.0" />
+ <PackageReference Include="Serilog" Version="4.3.1" />
+ <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
+ <PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" />
+ <PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
+ <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
+ <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="9.0.0" />
+ <PackageReference Include="Serilog.Sinks.Http" Version="9.2.1" />
+ <PackageReference Include="Soulseek" Version="10.0.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
- <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.1" />
<PackageReference Include="TagLibSharp" Version="2.3.0" />
<PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" />
<PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" />
- <PackageReference Include="YamlDotNet" Version="15.3.0" />
+ <PackageReference Include="YamlDotNet" Version="18.0.0" />
</ItemGroup>
</Project>
diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js
index 0c36e3ed..81d1001c 100644
--- a/src/web/.eslintrc.js
+++ b/src/web/.eslintrc.js
@@ -5,6 +5,7 @@ const overrides = {
'no-eq-null': 'off', // noisy
'react/forbid-component-props': 'off', // noisy
'react/prop-types': 'off', // noisy
+ 'canonical/sort-keys': 'off', // noisy
'unicorn/no-array-reduce': 'off', // noisy
};
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 22d9c714..e64bc38d 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -14304,13 +14304,14 @@
}
},
"node_modules/launch-editor": {
- "version": "2.6.0",
- "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.6.0.tgz",
- "integrity": "sha512-JpDCcQnyAAzZZaZ7vEiSqL690w7dAEyLao+KC96zBplnYbJS7TYNjvM3M7y3dGz+v7aIsJk3hllWuc0kWAjyRQ==",
+ "version": "2.14.1",
+ "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz",
+ "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==",
"dev": true,
+ "license": "MIT",
"dependencies": {
- "picocolors": "^1.0.0",
- "shell-quote": "^1.7.3"
+ "picocolors": "^1.1.1",
+ "shell-quote": "^1.8.4"
}
},
"node_modules/less": {
@@ -18840,10 +18841,14 @@
}
},
"node_modules/shell-quote": {
- "version": "1.8.1",
- "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz",
- "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==",
+ "version": "1.8.4",
+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz",
+ "integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==",
"dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx
index 23619bd1..39dd1a44 100644
--- a/src/web/src/components/Chat/Chat.jsx
+++ b/src/web/src/components/Chat/Chat.jsx
@@ -20,8 +20,35 @@ const initialState = {
conversations: {},
interval: undefined,
loading: false,
+ message: '',
};
+const ChatMessageHistory = React.memo(
+ ({ formatTimestamp, messages, selfUsername }) => {
+ return (
+ <>
+ {messages.map((message) => (
+ <List.Content
+ className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`}
+ key={`${message.timestamp}+${message.message}`}
+ >
+ <span className="chat-message-time">
+ {formatTimestamp(message.timestamp)}
+ </span>
+ <span className="chat-message-name">
+ {message.direction === 'Out' ? selfUsername : message.username}:
+ </span>
+ <span className="chat-message-message">{message.message}</span>
+ </List.Content>
+ ))}
+ <List.Content id="chat-history-scroll-anchor" />
+ </>
+ );
+ },
+);
+
+ChatMessageHistory.displayName = 'ChatMessageHistory';
+
class Chat extends Component {
constructor(props) {
super(props);
@@ -62,6 +89,13 @@ class Chat extends Component {
// fetch all of the active conversations (but no messages)
let conversations = await chat.getAll();
+ // the username '..' breaks nearly everything in slskd because it's a path traversal
+ // sequence and no API endpoints that expect usernames in the path work
+ // rather than letting this sit broken, i'm making the choice to filter it out
+ // eslint-disable-next-line no-warning-comments
+ // todo: remove this filter when the API can handle '..'
+ conversations = conversations.filter((f) => f.username !== '..');
+
// turn into a map, keyed by username
// if there are no active conversations, set to an empty map
if (conversations.length === 0) {
@@ -106,21 +140,15 @@ class Chat extends Component {
await chat.acknowledge({ username });
};
- sendMessage = async (username, message) => {
- if (!username || !message || username === '') return;
- await chat.send({ message, username });
- };
-
sendReply = async () => {
- const { active } = this.state;
- const message = this.messageRef.current.value;
+ const { active, message } = this.state;
if (!this.validInput()) {
return;
}
- await this.sendMessage(active, message);
- this.messageRef.current.value = '';
+ await chat.send({ username: active, message });
+ this.setState({ message: '' });
// force a refresh to append the message
// we could probably do this in the browser but we can be lazy
@@ -129,12 +157,7 @@ class Chat extends Component {
validInput = () =>
(this.state.active || '').length > 0 &&
- (
- (this.messageRef &&
- this.messageRef.current &&
- this.messageRef.current.value) ||
- ''
- ).length > 0;
+ (this.state.message || '').length > 0;
focusInput = () => {
this.messageRef.current.focus();
@@ -154,10 +177,11 @@ class Chat extends Component {
selectConversation = (username) => {
this.setState(
- {
+ (previousState) => ({
active: username,
loading: true,
- },
+ message: previousState.active === username ? previousState.message : '',
+ }),
async () => {
const { active, conversations } = this.state;
@@ -180,6 +204,12 @@ class Chat extends Component {
} catch {
// no-op
}
+
+ try {
+ this.messageRef.current.focus();
+ } catch {
+ // no-op
+ }
},
);
},
@@ -260,26 +290,11 @@ class Chat extends Component {
<Segment className="chat-history">
<Ref innerRef={this.listRef}>
<List>
- {messages.map((message) => (
- <List.Content
- className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`}
- key={`${message.timestamp}+${message.message}`}
- >
- <span className="chat-message-time">
- {this.formatTimestamp(message.timestamp)}
- </span>
- <span className="chat-message-name">
- {message.direction === 'Out'
- ? user.username
- : message.username}
- :{' '}
- </span>
- <span className="chat-message-message">
- {message.message}
- </span>
- </List.Content>
- ))}
- <List.Content id="chat-history-scroll-anchor" />
+ <ChatMessageHistory
+ formatTimestamp={this.formatTimestamp}
+ messages={messages}
+ selfUsername={user.username}
+ />
</List>
</Ref>
</Segment>
@@ -294,7 +309,7 @@ class Chat extends Component {
name="send"
/>
),
- onClick: this.sendMessage,
+ onClick: this.sendReply,
}}
fluid
input={
@@ -302,7 +317,11 @@ class Chat extends Component {
autoComplete="off"
data-lpignore="true"
id="chat-message-input"
+ onChange={(event) =>
+ this.setState({ message: event.target.value })
+ }
type="text"
+ value={this.state.message}
/>
}
onKeyUp={(event) =>
diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx
index 0f2e4382..f6bdb685 100644
--- a/src/web/src/components/Rooms/Rooms.jsx
+++ b/src/web/src/components/Rooms/Rooms.jsx
@@ -32,12 +32,43 @@ const initialState = {
},
joined: [],
loading: false,
+ message: '',
room: {
messages: [],
users: [],
},
};
+const RoomMessageHistory = React.memo(
+ ({ formatTimestamp, messages, onHandleContextMenu }) => {
+ return (
+ <>
+ {messages.map((message) => (
+ <div
+ key={`${message.timestamp}+${message.message}`}
+ onContextMenu={(clickEvent) =>
+ onHandleContextMenu(clickEvent, message)
+ }
+ >
+ <List.Content
+ className={`room-message ${message.self ? 'room-message-self' : ''}`}
+ >
+ <span className="room-message-time">
+ {formatTimestamp(message.timestamp)}
+ </span>
+ <span className="room-message-name">{message.username}: </span>
+ <span className="room-message-message">{message.message}</span>
+ </List.Content>
+ </div>
+ ))}
+ <List.Content id="room-history-scroll-anchor" />
+ </>
+ );
+ },
+);
+
+RoomMessageHistory.displayName = 'RoomMessageHistory';
+
class Rooms extends Component {
constructor(props) {
super(props);
@@ -114,11 +145,12 @@ class Rooms extends Component {
selectRoom = async (roomName) => {
this.setState(
- {
+ (previousState) => ({
active: roomName,
loading: true,
+ message: previousState.active === roomName ? previousState.message : '',
room: initialState.room,
- },
+ }),
async () => {
const { active } = this.state;
@@ -131,6 +163,12 @@ class Rooms extends Component {
} catch {
// no-op
}
+
+ try {
+ this.messageRef.current.focus();
+ } catch {
+ // no-op
+ }
});
},
);
@@ -150,12 +188,7 @@ class Rooms extends Component {
validInput = () =>
(this.state.active || '').length > 0 &&
- (
- (this.messageRef &&
- this.messageRef.current &&
- this.messageRef.current.value) ||
- ''
- ).length > 0;
+ (this.state.message || '').length > 0;
focusInput = () => {
this.messageRef.current.focus();
@@ -174,15 +207,14 @@ class Rooms extends Component {
};
sendMessage = async () => {
- const { active } = this.state;
- const message = this.messageRef.current.value;
+ const { active, message } = this.state;
if (!this.validInput()) {
return;
}
await rooms.sendMessage({ message, roomName: active });
- this.messageRef.current.value = '';
+ this.setState({ message: '' });
};
handleContextMenu = (clickEvent, message) => {
@@ -207,8 +239,12 @@ class Rooms extends Component {
};
handleReply = () => {
- this.messageRef.current.value = `[${this.state.contextMenu.message.username}] ${this.state.contextMenu.message.message} --> `;
- this.focusInput();
+ this.setState(
+ (previousState) => ({
+ message: `[${previousState.contextMenu.message.username}] ${previousState.contextMenu.message.message} --> `,
+ }),
+ () => this.focusInput(),
+ );
};
handleUserProfile = () => {
@@ -319,29 +355,11 @@ class Rooms extends Component {
<Segment className="room-history">
<Ref innerRef={this.listRef}>
<List>
- {room.messages.map((message) => (
- <div
- key={`${message.timestamp}+${message.message}`}
- onContextMenu={(clickEvent) =>
- this.handleContextMenu(clickEvent, message)
- }
- >
- <List.Content
- className={`room-message ${message.self ? 'room-message-self' : ''}`}
- >
- <span className="room-message-time">
- {this.formatTimestamp(message.timestamp)}
- </span>
- <span className="room-message-name">
- {message.username}:{' '}
- </span>
- <span className="room-message-message">
- {message.message}
- </span>
- </List.Content>
- </div>
- ))}
- <List.Content id="room-history-scroll-anchor" />
+ <RoomMessageHistory
+ formatTimestamp={this.formatTimestamp}
+ messages={room.messages}
+ onHandleContextMenu={this.handleContextMenu}
+ />
</List>
</Ref>
</Segment>
@@ -364,7 +382,11 @@ class Rooms extends Component {
autoComplete="off"
data-lpignore="true"
id="room-message-input"
+ onChange={(event) =>
+ this.setState({ message: event.target.value })
+ }
type="text"
+ value={this.state.message}
/>
}
onKeyUp={(event) =>
diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs
deleted file mode 100644
index 1012ddfa..00000000
--- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-namespace slskd.Tests.Unit.Common.Extensions
-{
- using System;
- using Xunit;
-
- public class ToLocalRelativeFilenameTests
- {
- [Theory]
- [InlineData(null)]
- [InlineData("")]
- [InlineData("\t")]
- public void Throws_ArgumentException_Given_Bad_Remote_Filename(string filename)
- {
- var ex = Record.Exception(() => filename.ToLocalRelativeFilename());
-
- Assert.NotNull(ex);
- Assert.IsType<ArgumentException>(ex);
- }
-
- [Fact]
- public void Returns_Localized_Filename_And_Parent_Directory()
- {
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- {
- Assert.Equal(@"path\file.ext", "deeply/nested/path/file.ext".ToLocalRelativeFilename());
- }
- else
- {
- Assert.Equal(@"path/file.ext", @"C:\deeply\nested\path\file.ext".ToLocalRelativeFilename());
- }
-
- }
-
- [Fact]
- public void Returns_Just_File_If_Only_File_Given()
- {
- Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename());
- }
-
- [Fact]
- public void Removes_Invalid_Characters_From_Path_And_Filename()
- {
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- {
- Assert.Equal(@"p_a_t_h\fi_le.ext", @"p?a|t<h/fi>le.ext".ToLocalRelativeFilename());
- }
- else
- {
- Assert.Equal(@"_", $"{'\0'}".ToLocalRelativeFilename());
- }
- }
- }
-}
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs
new file mode 100644
index 00000000..ceba3b86
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs
@@ -0,0 +1,263 @@
+using System;
+using System.IO;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common;
+
+public partial class FileSafetyTests
+{
+ public class CombineSafelyTests
+ {
+ public static string Base = System.OperatingSystem.IsWindows() ? "C:\\base" : "/base";
+ public static string ExpectedStartsWith = Base + Path.DirectorySeparatorChar;
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ public void Throws_ArgumentNullException_Given_NullOrWhiteSpaceRoot(string root)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(root));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentNullException>(ex);
+ }
+
+ [Theory]
+ [InlineData(".")]
+ [InlineData("..")]
+ [InlineData("./foo")]
+ [InlineData("../bar")]
+ [InlineData("foo/../bar")]
+ [InlineData("foo\\..\\bar")]
+ public void Throws_ArgumentException_Given_TraversingRoot(string root)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(root));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ }
+
+ [Fact]
+ public void Returns_Root_Given_No_Segments()
+ {
+ var result = FileSafety.CombineSafely(Base);
+
+ Assert.StartsWith(ExpectedStartsWith.TrimEnd(Path.DirectorySeparatorChar), result);
+ }
+
+ [Fact]
+ public void Drops_Empty_Segments()
+ {
+ var result = FileSafety.CombineSafely(Base, string.Empty, "foo", string.Empty, "bar");
+
+ Assert.StartsWith(ExpectedStartsWith, result);
+ Assert.EndsWith(Path.Combine("foo", "bar"), result);
+ }
+
+ [Fact]
+ public void Throws_Given_Null_Segment()
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(Base, "foo", null, "bar"));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentNullException>(ex);
+ }
+
+ [Fact]
+ public void Throws_Given_Null_Segments()
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(Base, segments: null));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentNullException>(ex);
+ }
+
+ [Fact]
+ public void SingleSegment_ReturnsBaseAndSegment()
+ {
+ var result = FileSafety.CombineSafely(Base, "subdir");
+
+ Assert.Equal(Path.Combine(Base, "subdir"), result);
+ }
+
+ [Fact]
+ public void MultipleSegments_CombinesAll()
+ {
+ var result = FileSafety.CombineSafely(Base, "sub", "dir", "file.flac");
+
+ Assert.Equal(Path.Combine(Base, "sub", "dir", "file.flac"), result);
+ Assert.StartsWith(ExpectedStartsWith, result);
+ }
+
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("sub//dir")]
+ [InlineData("sub\\\\dir")]
+ [InlineData("My Artist")]
+ [InlineData("Artist.Name")]
+ [InlineData("...dir")]
+ [InlineData("..hidden")]
+ [InlineData(".hidden")]
+ [InlineData("dir/..dir")]
+ [InlineData("รœnรฏcรถdรฉ")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/ะœัƒะทั‹ะบะฐ")]
+ [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);
+
+ Assert.Equal(Path.Combine(Base, segment), result);
+ Assert.StartsWith(ExpectedStartsWith, result);
+ }
+
+ [Theory]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ public void Throws_ArgumentException_Given_AbsolutePath_On_Unix(string segment)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment));
+
+ Assert.NotNull(ex);
+ Assert.Contains("Absolute", ex.Message);
+ }
+
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("\\\\server\\share")]
+ public void Throws_ArgumentException_Given_AbsolutePath_On_Windows(string segment)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Windows, segment));
+
+ Assert.NotNull(ex);
+ Assert.Contains("Absolute", ex.Message);
+ }
+
+ [Theory]
+ [InlineData("foo:bar")]
+ [InlineData("C:relative")]
+ [InlineData("sub/foo:bar")]
+ [InlineData("sub/foo/bar:qux")]
+ public void Throws_ArgumentException_Given_Colon_In_Segment_On_Windows(string segment)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Windows, segment));
+
+ Assert.NotNull(ex);
+ Assert.Contains("Colon", ex.Message);
+ }
+
+ [Theory]
+ [InlineData("foo:bar")]
+ [InlineData("sub/foo:bar")]
+ [InlineData("sub/foo/bar:qux")]
+ public void Accepts_Colon_In_Segment_On_Linux(string segment)
+ {
+ var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment));
+
+ Assert.Null(result);
+ }
+
+ [Theory]
+ [InlineData("C:relative")]
+ public void Accepts_Colon_In_Segment_On_Linux_When_Running_On_Windows(string segment)
+ {
+ var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment);
+
+ Assert.Equal($"{Base}/C:relative", result);
+ }
+
+ [Theory]
+ [InlineData("/Music")]
+ [InlineData("\\Music")]
+ public void Throws_ArgumentException_Given_Leading_Slash_In_Segment_On_Windows(string segment)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Windows, segment));
+
+ Assert.NotNull(ex);
+ Assert.Contains("Drive-relative", ex.Message);
+ }
+
+ [Theory]
+ [InlineData("\\Music")]
+ public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment)
+ {
+ var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment);
+
+ Assert.Equal($"{Base}/\\Music", result);
+ }
+
+ [Fact]
+ public void Returns_Root_Given_Single_Empty_Segment()
+ {
+ var result = FileSafety.CombineSafely(Base, "");
+
+ Assert.Equal(Base, result);
+ }
+
+ [Fact]
+ public void Returns_Root_Given_All_Empty_Segments()
+ {
+ var result = FileSafety.CombineSafely(Base, "", "");
+
+ Assert.Equal(Base, result);
+ }
+
+ [Fact]
+ public void Handles_Root_With_Trailing_Separator()
+ {
+ var rootWithTrailing = Base + Path.DirectorySeparatorChar;
+ var result = FileSafety.CombineSafely(rootWithTrailing, "foo");
+
+ Assert.StartsWith(ExpectedStartsWith, result);
+ Assert.EndsWith("foo", result);
+ }
+
+ [Theory]
+ [InlineData("./foo")]
+ [InlineData("../bar")]
+ [InlineData("foo/../bar")]
+ public void Throws_ArgumentException_Given_TraversingRoot_With_Os_Override(string root)
+ {
+ var ex = Record.Exception(() => FileSafety.CombineSafely(root, OperatingSystem.Linux, "segment"));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ }
+
+ [Theory]
+ // Bare traversal
+ [InlineData("..")]
+ [InlineData(".")]
+ // Traversal as first component
+ [InlineData("../escape")]
+ [InlineData("./dir")]
+ // Traversal in middle
+ [InlineData("sub/../escape")]
+ [InlineData("sub/./dir")]
+ // Traversal at end
+ [InlineData("sub/..")]
+ [InlineData("sub/.")]
+ // Double traversal
+ [InlineData("sub/../../escape")]
+ [InlineData("a/b/c/../../..")]
+ // Via backslash
+ [InlineData("sub\\..")]
+ [InlineData("sub\\.")]
+ [InlineData("sub\\..\\escape")]
+ public void Throws_ArgumentException_Given_Traversing_Segment(string segment)
+ {
+ var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment));
+
+ Assert.NotNull(ex);
+ Assert.Contains("traversal", ex.Message);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs
new file mode 100644
index 00000000..f0b1a394
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs
@@ -0,0 +1,117 @@
+using Xunit;
+
+namespace slskd.Tests.Unit.Common;
+
+public partial class FileSafetyTests
+{
+ public class ContainsTraversalSegmentTests
+ {
+ [Theory]
+ // Bare traversal segments
+ [InlineData("..")]
+ [InlineData(".")]
+ // Traversal as first component โ€” forward slash
+ [InlineData("../escape")]
+ [InlineData("./dir")]
+ // Traversal at end โ€” forward slash
+ [InlineData("sub/..")]
+ [InlineData("sub/.")]
+ // Traversal in middle โ€” forward slash
+ [InlineData("sub/../escape")]
+ [InlineData("sub/./dir")]
+ // Double traversal โ€” forward slash
+ [InlineData("sub/../../escape")]
+ [InlineData("a/b/c/../../..")]
+ // Traversal via backslash
+ [InlineData("sub\\..")]
+ [InlineData("sub\\.")]
+ [InlineData("sub\\..\\escape")]
+ [InlineData("sub\\.\\dir")]
+ // Mixed separators
+ [InlineData("sub/..\\escape")]
+ [InlineData("sub\\./../escape")]
+ // Unicode path components mixed with forward-slash traversal
+ [InlineData("รœnรฏcรถdรฉ/../escape")]
+ [InlineData("รœnรฏcรถdรฉ/./escape")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/../etc")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/./etc")]
+ [InlineData("็”จๆˆท/../escape")]
+ [InlineData("ใƒฆใƒผใ‚ถใƒผ/../../escape")]
+ [InlineData("์‚ฌ์šฉ์ž/../escape")]
+ [InlineData("ู…ุณุชุฎุฏู…/../escape")]
+ [InlineData("ฯ‡ฯฮฎฯƒฯ„ฮทฯ‚/../ฮผฮฟฯ…ฯƒฮนฮบฮฎ")]
+ [InlineData("ืžืฉืชืžืฉ/../ืžื•ื–ื™ืงื”")]
+ // Unicode path components mixed with backslash traversal
+ [InlineData("็”จๆˆท\\..\\escape")]
+ [InlineData("ใƒฆใƒผใ‚ถใƒผ\\..\\escape")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ\\..\\ะœัƒะทั‹ะบะฐ")]
+ // Traversal between two valid Unicode segments
+ [InlineData("รœnรฏcรถdรฉ/../ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ")]
+ [InlineData("็”จๆˆท/music/../escape")]
+ // Traversal at end after unicode
+ [InlineData("รœnรฏcรถdรฉ/..")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/..")]
+ [InlineData("็”จๆˆท\\..")]
+ public void Path_ContainsTraversal(string path)
+ {
+ Assert.True(FileSafety.ContainsTraversalSegments(path));
+ }
+
+ [Theory]
+ // Simple names โ€” no separators, no dots
+ [InlineData("subdir")]
+ [InlineData("file.flac")]
+ [InlineData("My Artist")]
+ [InlineData("Artist.Name")]
+ // Dotfile and dot-prefixed names โ€” not exactly . or ..
+ [InlineData(".hidden")]
+ [InlineData("..hidden")]
+ [InlineData("...")]
+ [InlineData("...dir")]
+ // Segments that start with .. but are not exactly ..
+ [InlineData("dir/..dir")]
+ [InlineData("dir/...")]
+ // Forward-slash paths โ€” no traversal
+ [InlineData("sub/dir")]
+ [InlineData("Artist/Album")]
+ [InlineData("Artist/Album/Song.flac")]
+ // Backslash paths โ€” no traversal
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("Artist\\Album\\Song.flac")]
+ // Mixed separators โ€” no traversal
+ [InlineData("Artist/Album\\Song.flac")]
+ // Double separators โ€” empty segment is not . or ..
+ [InlineData("sub//dir")]
+ [InlineData("sub\\\\dir")]
+ // Null and empty string โ€” both return false without throwing
+ [InlineData(null)]
+ [InlineData("")]
+ // Unicode โ€” no traversal, forward slash
+ [InlineData("รœnรฏcรถdรฉ")]
+ [InlineData("รœnรฏcรถdรฉ/ร€rtรฏst/ร€lbรผm")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/ะœัƒะทั‹ะบะฐ")]
+ [InlineData("็”จๆˆท/้Ÿณไน/ไธ“่พ‘")]
+ [InlineData("ใƒฆใƒผใ‚ถใƒผ/้Ÿณๆฅฝ/ใ‚ขใƒซใƒใƒ ")]
+ [InlineData("์‚ฌ์šฉ์ž/์Œ์•…/์•จ๋ฒ”")]
+ [InlineData("ู…ุณุชุฎุฏู…/ู…ูˆุณูŠู‚ู‰")]
+ [InlineData("ฯ‡ฯฮฎฯƒฯ„ฮทฯ‚/ฮผฮฟฯ…ฯƒฮนฮบฮฎ")]
+ [InlineData("ืžืฉืชืžืฉ/ืžื•ื–ื™ืงื”")]
+ // Unicode โ€” no traversal, backslash
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ\\ะœัƒะทั‹ะบะฐ\\ะะปัŒะฑะพะผ")]
+ [InlineData("็”จๆˆท\\้Ÿณไน\\ไธ“่พ‘")]
+ [InlineData("ใƒฆใƒผใ‚ถใƒผ\\้Ÿณๆฅฝ\\ใ‚ขใƒซใƒใƒ ")]
+ [InlineData("์‚ฌ์šฉ์ž\\์Œ์•…\\์•จ๋ฒ”")]
+ // Unicode names that start with dots โ€” not traversal
+ [InlineData("รœnรฏcรถdรฉ/..hidden")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/...dir")]
+ [InlineData("็”จๆˆท/..ๅๅ‰")]
+ // Segments that look like traversal but have surrounding whitespace โ€” not exact matches
+ [InlineData(" . ")]
+ [InlineData(" .. ")]
+ public void Path_DoesNotContainTraversal(string path)
+ {
+ Assert.False(FileSafety.ContainsTraversalSegments(path));
+ }
+ }
+} \ No newline at end of file
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..eaeaa29f
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs
@@ -0,0 +1,380 @@
+namespace slskd.Tests.Unit.Common;
+
+using Xunit;
+
+public partial class FileSafetyTests
+{
+ public class GetDirectoryNameSafelyTests
+ {
+ [Fact]
+ public void NullOs_UsesPlatformDefault_DoesNotThrow()
+ {
+ var result = FileSafety.GetDirectoryNameSafely("foo/bar");
+
+ Assert.Equal("foo", result);
+ }
+
+ [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);
+ }
+
+ [Fact]
+ public void Returns_Null_Given_Whitespace_Only()
+ {
+ var result = FileSafety.GetDirectoryNameSafely(" ");
+
+ 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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.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_Sanitized_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OperatingSystem.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: OperatingSystem.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: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo/../bar/file.txt", "foo/_/bar")]
+ [InlineData("../bar/file.txt", "_/bar")]
+ [InlineData("a/./b/file.txt", "a/_/b")]
+ public void Sanitizes_Traversal_Segments_In_Directory_Linux(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo\\..\\bar\\file.txt", "foo\\_\\bar")]
+ [InlineData("..\\bar\\file.txt", "_\\bar")]
+ [InlineData("a\\.\\b\\file.txt", "a\\_\\b")]
+ public void Sanitizes_Traversal_Segments_In_Directory_Windows(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("Artist/Album/", "Artist")]
+ [InlineData("Artist\\Album\\", "Artist")]
+ [InlineData("foo/bar/baz/", "foo/bar")]
+ public void Treats_Trailing_Slash_As_Directory_Linux(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("Artist/Album/", "Artist")]
+ [InlineData("Artist\\Album\\", "Artist")]
+ [InlineData("foo/bar/baz/", "foo\\bar")]
+ public void Treats_Trailing_Slash_As_Directory_Windows(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("fo\0o/bar", "fo\0o")]
+ [InlineData("C:/Mu\0sic/song.flac", "Mu\0sic")]
+ public void Returns_Unrooted_Unsanitized_Directory_Linux(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("fo\0o\\bar", "fo\0o")]
+ [InlineData("C:\\Mu\0sic\\song.flac", "Mu\0sic")]
+ public void Returns_Unrooted_Unsanitized_Directory_Windows(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo/../bar/file.txt", "foo/../bar")]
+ [InlineData("../etc/file.txt", "../etc")]
+ public void Preserves_Traversal_Segments_When_Sanitize_False_Linux(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo\\..\\bar\\file.txt", "foo\\..\\bar")]
+ [InlineData("..\\etc\\file.txt", "..\\etc")]
+ public void Preserves_Traversal_Segments_When_Sanitize_False_Windows(string input, string expected)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("@@abcd/foo/bar/file.txt")]
+ public void Short_Qt_Prefix_Treated_As_Segment_Linux(string input)
+ {
+ var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux);
+
+ Assert.StartsWith("@@abcd", 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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+ }
+} \ No newline at end of file
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..59ba2b54
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs
@@ -0,0 +1,195 @@
+namespace slskd.Tests.Unit.Common;
+
+using Xunit;
+
+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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.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: OperatingSystem.Linux);
+
+ Assert.Equal("file\0name.flac", result);
+ }
+
+ [Fact]
+ public void Default_Sanitize_Is_True()
+ {
+ var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac", os: OperatingSystem.Windows);
+ var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OperatingSystem.Windows);
+
+ Assert.Equal(resultExplicit, resultDefault);
+ }
+
+ [Fact]
+ public void NullOs_UsesPlatformDefault_DoesNotThrow()
+ {
+ var result = FileSafety.GetFileNameSafely("Music/song.flac");
+
+ Assert.Equal("song.flac", result);
+ }
+
+ [Theory]
+ [InlineData(".")]
+ [InlineData("..")]
+ public void Sanitize_True_Replaces_BareTraversalFilename(string input)
+ {
+ var result = FileSafety.GetFileNameSafely(input, sanitize: true);
+
+ Assert.Equal("_", result);
+ }
+
+ [Theory]
+ [InlineData(".")]
+ [InlineData("..")]
+ public void Sanitize_False_Preserves_BareTraversalFilename(string input)
+ {
+ var result = FileSafety.GetFileNameSafely(input, sanitize: false);
+
+ Assert.Equal(input, result);
+ }
+
+ [Theory]
+ [InlineData("foo/.")]
+ [InlineData("foo/..")]
+ [InlineData("foo\\..")]
+ public void Sanitize_True_Replaces_Traversal_As_Last_Path_Segment(string input)
+ {
+ var result = FileSafety.GetFileNameSafely(input, sanitize: true);
+
+ Assert.Equal("_", result);
+ }
+
+ [Theory]
+ [InlineData("foo/.", ".")]
+ [InlineData("foo/..", "..")]
+ [InlineData("foo\\..", "..")]
+ public void Sanitize_False_Preserves_Traversal_As_Last_Path_Segment(string input, string expected)
+ {
+ var result = FileSafety.GetFileNameSafely(input, sanitize: false);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo//bar.flac", "bar.flac")]
+ [InlineData("foo\\\\bar.flac", "bar.flac")]
+ public void Returns_Filename_Given_Double_Separator(string input, string expected)
+ {
+ var result = FileSafety.GetFileNameSafely(input);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("@@abcde/song.flac", "song.flac")]
+ [InlineData("@@abcde\\song.flac", "song.flac")]
+ [InlineData("@@abcdefgh/Music/song.flac", "song.flac")]
+ public void Returns_Filename_Given_SoulseekQt_Prefixed_Path_Linux(string input, string expected)
+ {
+ var result = FileSafety.GetFileNameSafely(input, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("@@abcde\\song.flac", "song.flac")]
+ [InlineData("@@abcde/song.flac", "song.flac")]
+ [InlineData("@@abcdefgh\\Music\\song.flac", "song.flac")]
+ public void Returns_Filename_Given_SoulseekQt_Prefixed_Path_Windows(string input, string expected)
+ {
+ var result = FileSafety.GetFileNameSafely(input, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs
new file mode 100644
index 00000000..771a1ea0
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs
@@ -0,0 +1,135 @@
+namespace slskd.Tests.Unit.Common;
+
+using Xunit;
+
+public partial class FileSafetyTests
+{
+ public class IsPathTests
+ {
+ public class Windows
+ {
+ public class Absolute
+ {
+ [Theory]
+ // drive-letter paths (X:\ or X:/)
+ [InlineData("C:\\")]
+ [InlineData("C:/")]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\Music\\Artist\\Album")]
+ [InlineData("D:\\path")]
+ [InlineData("Z:\\downloads")]
+ [InlineData("C:\\Users\\รœnรฏcรถdรฉ\\Music")]
+ [InlineData("C:\\Users\\ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ\\ะœัƒะทั‹ะบะฐ")]
+ [InlineData("C:\\Users\\็”จๆˆท\\้Ÿณไน")]
+ // lowercase drive letters
+ [InlineData("c:\\Music")]
+ [InlineData("a:/path")]
+ // UNC paths (\\ prefix)
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\\\server\\share\\folder")]
+ [InlineData("\\\\server\\share\\My Music")]
+ [InlineData("\\\\192.168.1.1\\share")]
+ [InlineData("\\\\server\\รœnรฏcรถdรฉ")]
+ [InlineData("\\\\server\\share\\ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ")]
+ [InlineData("\\\\server\\share\\็”จๆˆท\\้Ÿณไน")]
+ [InlineData("\\\\server")]
+ public void IsAbsolute_NotRelative(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path, OperatingSystem.Windows));
+ Assert.False(FileSafety.IsPathRelative(path, OperatingSystem.Windows));
+ }
+ }
+
+ public class Relative
+ {
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("Artist/Album/Song")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData(".hidden")]
+ [InlineData("..hidden")]
+ [InlineData("...dir")]
+ [InlineData("../escape")]
+ [InlineData("./dir")]
+ [InlineData("..")]
+ [InlineData(".")]
+ [InlineData("รœnรฏcรถdรฉ")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/ะœัƒะทั‹ะบะฐ")]
+ [InlineData("/Music")]
+ [InlineData("\\Music")]
+ [InlineData("/home/user")]
+ [InlineData("//server/share")]
+ [InlineData("//server")]
+ [InlineData("C:")]
+ [InlineData("C:Music")]
+ [InlineData("D:path")]
+ public void IsRelative_NotAbsolute(string path)
+ {
+ Assert.False(FileSafety.IsPathAbsolute(path, OperatingSystem.Windows));
+ Assert.True(FileSafety.IsPathRelative(path, OperatingSystem.Windows));
+ }
+ }
+ }
+
+ public class Linux
+ {
+ public class Absolute
+ {
+ [Theory]
+ [InlineData("/")]
+ [InlineData("/home")]
+ [InlineData("/home/user/Music")]
+ [InlineData("/home/user/My Music")]
+ [InlineData("/etc/hosts")]
+ [InlineData("/tmp")]
+ [InlineData("/home/รœnรฏcรถdรฉ")]
+ [InlineData("/home/ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/ะœัƒะทั‹ะบะฐ")]
+ [InlineData("/home/็”จๆˆท/้Ÿณไน")]
+ [InlineData("/home/ใƒฆใƒผใ‚ถใƒผ/้Ÿณๆฅฝ")]
+ [InlineData("/home/์‚ฌ์šฉ์ž/์Œ์•…")]
+ [InlineData("//server/share")]
+ [InlineData("//server/share/folder")]
+ [InlineData("//192.168.1.1/share")]
+ public void IsAbsolute_NotRelative(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path, OperatingSystem.Linux));
+ Assert.False(FileSafety.IsPathRelative(path, OperatingSystem.Linux));
+ }
+ }
+
+ public class Relative
+ {
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("music.flac")]
+ [InlineData(".hidden")]
+ [InlineData("../escape")]
+ [InlineData("./dir")]
+ [InlineData("..")]
+ [InlineData(".")]
+ [InlineData("รœnรฏcรถdรฉ")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/ะœัƒะทั‹ะบะฐ")]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\Music")]
+ public void IsRelative_NotAbsolute(string path)
+ {
+ Assert.False(FileSafety.IsPathAbsolute(path, OperatingSystem.Linux));
+ Assert.True(FileSafety.IsPathRelative(path, OperatingSystem.Linux));
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs
new file mode 100644
index 00000000..f0fc196c
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs
@@ -0,0 +1,70 @@
+using System.Runtime.InteropServices;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common;
+
+public partial class FileSafetyTests
+{
+ public class LocalizePathTests
+ {
+ [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("", "")]
+ [InlineData("/", "/")]
+ [InlineData("\\", "/")]
+ public void Linux_NormalizesToForwardSlash(string input, string expected)
+ {
+ var result = FileSafety.LocalizePath(input, OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [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("", "")]
+ [InlineData("/", "\\")]
+ [InlineData("\\", "\\")]
+ public void Windows_NormalizesToBackslash(string input, string expected)
+ {
+ var result = FileSafety.LocalizePath(input, OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void NullOs_UsesPlatformDefault_DoesNotThrow()
+ {
+ var result = FileSafety.LocalizePath("foo/bar");
+
+ Assert.False(string.IsNullOrEmpty(result));
+ }
+
+ [Fact]
+ public void Returns_Null_Given_Null_Path()
+ {
+ var result = FileSafety.LocalizePath(null);
+
+ Assert.Null(result);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs
new file mode 100644
index 00000000..c53b95fc
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs
@@ -0,0 +1,188 @@
+using System;
+using System.Runtime.InteropServices;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common;
+
+public partial class FileSafetyTests
+{
+ public class SanitizeFilenameTests
+ {
+ [Theory]
+ [InlineData('/')]
+ [InlineData('\\')]
+ public void Throws_Given_Slash_As_Replacement(char replacement)
+ {
+ var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", replacement));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ Assert.Contains("invalid in filenames", ex.Message);
+ }
+
+ [Fact]
+ public void Throws_Given_OsInvalid_Replacement_On_Unix()
+ {
+ // '\0' is invalid on Unix but not caught by the slash guard
+ var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '\0', OperatingSystem.Linux));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ Assert.Contains("invalid on", ex.Message);
+ }
+
+ [Fact]
+ public void Throws_Given_OsInvalid_Replacement_On_Windows()
+ {
+ // '*' is invalid on Windows but not caught by the slash guard
+ var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '*', OperatingSystem.Windows));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ Assert.Contains("invalid on", ex.Message);
+ }
+
+ [Fact]
+ public void NullOs_UsesPlatformDefault_DoesNotThrow()
+ {
+ var result = FileSafety.SanitizeFilename("safe_file.flac");
+
+ Assert.NotNull(result);
+ }
+
+ [Theory]
+ [InlineData("clean", "clean")]
+ [InlineData("file.flac", "file.flac")]
+ [InlineData("My Artist - My Album", "My Artist - My Album")]
+ [InlineData("รœnรฏcรถdรฉ", "รœnรฏcรถdรฉ")]
+ [InlineData("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ", "ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ")]
+ public void Linux_ReturnsUnchanged_Given_Safe_Filename(string input, string expected)
+ {
+ var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("file\0name", "file_name")]
+ [InlineData("\0leading", "_leading")]
+ [InlineData("trailing\0", "trailing_")]
+ public void Linux_Replaces_NullByte(string input, string expected)
+ {
+ var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.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.SanitizeFilename(input, '_', OperatingSystem.Linux);
+
+ 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, '_', OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void Linux_Uses_Custom_Replacement()
+ {
+ var result = FileSafety.SanitizeFilename("has/slash", '-', OperatingSystem.Linux);
+
+ Assert.Equal("has-slash", 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")]
+ [InlineData("file\\name", "file_name")]
+ [InlineData("file/name", "file_name")]
+ public void Windows_Replaces_InvalidCharacters(string input, string expected)
+ {
+ var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows);
+
+ 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, '_', OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void Windows_Replaces_ControlCharacters()
+ {
+ var input = "file\x01\x1fname";
+ var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows);
+
+ Assert.Equal("file__name", result);
+ }
+
+ [Theory]
+ [InlineData("clean", "clean")]
+ [InlineData("file.flac", "file.flac")]
+ [InlineData("My Artist", "My Artist")]
+ public void Windows_ReturnsUnchanged_Given_Safe_Filename(string input, string expected)
+ {
+ var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void Linux_Accepts_Period_As_Replacement()
+ {
+ var result = FileSafety.SanitizeFilename("file\0name", '.', OperatingSystem.Linux);
+
+ Assert.Equal("file.name", result);
+ }
+
+ [Fact]
+ public void Windows_Accepts_Period_As_Replacement()
+ {
+ var result = FileSafety.SanitizeFilename("file*name", '.', OperatingSystem.Windows);
+
+ Assert.Equal("file.name", result);
+ }
+
+ [Fact]
+ public void Returns_Null_Given_Null()
+ {
+ var result = FileSafety.SanitizeFilename(null);
+
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public void Returns_EmptyString_Given_EmptyString()
+ {
+ var result = FileSafety.SanitizeFilename(string.Empty);
+
+ Assert.Equal(string.Empty, result);
+ }
+ }
+} \ No newline at end of file
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..230c9a89
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs
@@ -0,0 +1,142 @@
+using System;
+
+namespace slskd.Tests.Unit.Common;
+
+using Xunit;
+
+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, '_', OperatingSystem.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, '_', OperatingSystem.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, '_', OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void Returns_Null_Given_Null()
+ {
+ var result = FileSafety.SanitizePathSegment(null);
+
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public void Returns_EmptyString_Given_EmptyString()
+ {
+ var result = FileSafety.SanitizePathSegment(string.Empty);
+
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Fact]
+ public void NullOs_UsesPlatformDefault_DoesNotThrow()
+ {
+ var result = FileSafety.SanitizePathSegment("safe_segment");
+
+ Assert.NotNull(result);
+ }
+
+ [Theory]
+ [InlineData("*")]
+ [InlineData("*?")]
+ [InlineData("*.")] // one invalid char + one period โ†’ ".."
+ public void Windows_Returns_EmptyString_When_Period_Replacement_Produces_Traversal(string input)
+ {
+ var result = FileSafety.SanitizePathSegment(input, replacement: '.', os: OperatingSystem.Windows);
+
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Fact]
+ public void Linux_Returns_EmptyString_When_Period_Replacement_Produces_Traversal()
+ {
+ var result = FileSafety.SanitizePathSegment("\0", replacement: '.', os: OperatingSystem.Linux);
+
+ Assert.Equal(string.Empty, result);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs
new file mode 100644
index 00000000..61233e44
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs
@@ -0,0 +1,169 @@
+namespace slskd.Tests.Unit.Common;
+
+using Xunit;
+
+public partial class FileSafetyTests
+{
+ public class SanitizePathTests
+ {
+ [Fact]
+ public void NullOs_UsesPlatformDefault_DoesNotThrow()
+ {
+ var result = FileSafety.SanitizePath("foo/bar");
+
+ Assert.NotNull(result);
+ }
+
+ [Theory]
+ [InlineData("foo/bar", "foo/bar")]
+ [InlineData("foo\\bar", "foo/bar")]
+ [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")]
+ [InlineData("รœnรฏcรถdรฉ/ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ", "รœnรฏcรถdรฉ/ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ")]
+ [InlineData("foo//bar", "foo/bar")]
+ [InlineData("foo\\\\bar", "foo/bar")]
+ public void Linux_NormalizesSlashes(string input, string expected)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo/bar", "foo\\bar")]
+ [InlineData("foo\\bar", "foo\\bar")]
+ [InlineData("Artist/Album/song.flac", "Artist\\Album\\song.flac")]
+ [InlineData("foo//bar", "foo\\bar")]
+ [InlineData("foo\\\\bar", "foo\\bar")]
+ public void Windows_NormalizesSlashes(string input, string expected)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo/../bar", "foo/_/bar")]
+ [InlineData("foo/./bar", "foo/_/bar")]
+ [InlineData("../etc", "_/etc")]
+ [InlineData("./tmp", "_/tmp")]
+ [InlineData("foo/..", "foo/_")]
+ [InlineData("foo/.", "foo/_")]
+ public void Linux_Replaces_TraversalSegments(string input, string expected)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [InlineData("foo\\..\\bar", "foo\\_\\bar")]
+ [InlineData("foo\\.\\bar", "foo\\_\\bar")]
+ [InlineData("..\\etc", "_\\etc")]
+ public void Windows_Replaces_TraversalSegments(string input, string expected)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void Linux_Replaces_InvalidFilenameChars_In_Segments()
+ {
+ var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OperatingSystem.Linux);
+
+ Assert.Equal("seg_ment/file_name", result);
+ }
+
+ [Fact]
+ public void Windows_Replaces_InvalidFilenameChars_In_Segments()
+ {
+ var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OperatingSystem.Windows);
+
+ Assert.Equal("seg_ment\\file_name", result);
+ }
+
+ [Fact]
+ public void Uses_Custom_Replacement()
+ {
+ var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OperatingSystem.Linux);
+
+ Assert.Equal("foo/-/bar", result);
+ }
+
+ [Fact]
+ public void Returns_Null_Given_Null_Path()
+ {
+ var result = FileSafety.SanitizePath(null);
+
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public void Returns_EmptyString_Given_EmptyString()
+ {
+ var result = FileSafety.SanitizePath(string.Empty);
+
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Theory]
+ [InlineData("/foo/bar")]
+ [InlineData("//foo/bar")]
+ [InlineData("\\foo\\bar")]
+ [InlineData("\\\\foo\\bar")]
+ public void Linux_NeverReturns_LeadingSlash(string input)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux);
+
+ Assert.False(result.StartsWith('/') || result.StartsWith('\\'));
+ }
+
+ [Theory]
+ [InlineData("/foo/bar")]
+ [InlineData("//foo/bar")]
+ [InlineData("\\foo\\bar")]
+ [InlineData("\\\\foo\\bar")]
+ public void Windows_NeverReturns_LeadingSlash(string input)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Windows);
+
+ Assert.False(result.StartsWith('/') || result.StartsWith('\\'));
+ }
+
+ [Fact]
+ public void Linux_NeverReturns_LeadingSlash_When_First_Segment_Sanitizes_To_Empty()
+ {
+ // '\0' replaced with '.' produces "." โ€” SanitizePathSegment converts that to ""
+ // joining ["", "foo"] with '/' would yield "/foo" without a guard
+ var result = FileSafety.SanitizePath("\0/foo", replacement: '.', os: OperatingSystem.Linux);
+
+ Assert.False(result.StartsWith('/') || result.StartsWith('\\'));
+ }
+
+ [Theory]
+ [InlineData("../..")]
+ [InlineData("./.")]
+ public void Linux_Replaces_All_Traversal_Segments(string input)
+ {
+ var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux);
+
+ Assert.Equal("_/_", result);
+ }
+
+ [Fact]
+ public void Linux_Handles_SoulseekQt_Prefixed_Path()
+ {
+ var result = FileSafety.SanitizePath("@@abcde/foo/bar", os: OperatingSystem.Linux);
+
+ Assert.Equal("@@abcde/foo/bar", result);
+ }
+
+ [Fact]
+ public void Windows_Sanitizes_Colon_In_Drive_Like_Segment()
+ {
+ var result = FileSafety.SanitizePath("C:/Music/song.flac", os: OperatingSystem.Windows);
+
+ Assert.Equal("C_\\Music\\song.flac", result);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs
new file mode 100644
index 00000000..d547843b
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs
@@ -0,0 +1,188 @@
+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);
+ }
+
+ [Fact]
+ public void Returns_Null_Given_Null_Path()
+ {
+ var result = FileSafety.StripPathRoot(null);
+
+ Assert.Null(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, OperatingSystem.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, OperatingSystem.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, OperatingSystem.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, OperatingSystem.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", "")]
+ public void Windows_Strips_ForwardSlash_UncRoot(string input, string expected)
+ {
+ var result = FileSafety.StripPathRoot(input, OperatingSystem.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, OperatingSystem.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, OperatingSystem.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, OperatingSystem.Linux);
+
+ Assert.StartsWith("@@", result);
+ }
+
+ [Fact]
+ public void Linux_Strips_Bare_SoulseekQtPrefix_Returning_Empty()
+ {
+ var result = FileSafety.StripPathRoot("@@abcde", OperatingSystem.Linux);
+
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Theory]
+ [InlineData("/")]
+ [InlineData("//")]
+ public void Linux_ReturnsUnchanged_Given_Slash_Only_Path(string input)
+ {
+ var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux);
+
+ Assert.Equal(input, 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, OperatingSystem.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, OperatingSystem.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, OperatingSystem.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, OperatingSystem.Windows);
+
+ Assert.Equal(expected, result);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
new file mode 100644
index 00000000..beaecd9c
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
@@ -0,0 +1,319 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Reflection;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class AbsolutePathAttributeTests
+{
+ private static AbsolutePathAttribute CreateAttribute(OperatingSystem os, OperatingSystem? injected = null)
+ {
+ var attr = new AbsolutePathAttribute(os);
+
+ if (injected.HasValue)
+ {
+ var field = typeof(AbsolutePathAttribute)
+ .GetField("<Injected>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
+ field.SetValue(attr, injected.Value);
+ }
+
+ return attr;
+ }
+
+ private static (bool IsValid, string ErrorMessage) Validate(string value, OperatingSystem os, OperatingSystem? injected = null)
+ {
+ var attr = CreateAttribute(os, injected);
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attr.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ public class Constructor
+ {
+ [Fact]
+ public void AcceptsCurrentOsValue()
+ {
+ var ex = Record.Exception(() => _ = new AbsolutePathAttribute(OperatingSystem.Current));
+
+ Assert.Null(ex);
+ }
+
+ [Fact]
+ public void AcceptsAnyOsValue()
+ {
+ var ex = Record.Exception(() => _ = new AbsolutePathAttribute(OperatingSystem.Any));
+
+ Assert.Null(ex);
+ }
+
+ [Fact]
+ public void AcceptsAllOsValue()
+ {
+ var ex = Record.Exception(() => _ = new AbsolutePathAttribute(OperatingSystem.All));
+
+ Assert.Null(ex);
+ }
+
+ [Fact]
+ public void ThrowsForWindowsOsValue()
+ {
+ Assert.Throws<ArgumentException>(() => new AbsolutePathAttribute(OperatingSystem.Windows));
+ }
+
+ [Fact]
+ public void ThrowsForLinuxOsValue()
+ {
+ Assert.Throws<ArgumentException>(() => new AbsolutePathAttribute(OperatingSystem.Linux));
+ }
+
+ [Fact]
+ public void ThrowsForNoneOsValue()
+ {
+ Assert.Throws<ArgumentException>(() => new AbsolutePathAttribute(OperatingSystem.None));
+ }
+ }
+
+ public class NullOrEmpty
+ {
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForCurrentWithWindowsInjected(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForCurrentWithLinuxInjected(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForAny(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForAll(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.True(isValid);
+ }
+ }
+
+ // Current mode: validates using only the injected (or actual current) OS
+ public class Current
+ {
+ public class WithWindowsInjected
+ {
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\Music\\Artist\\Album")]
+ [InlineData("C:\\")]
+ [InlineData("Z:\\")]
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\\\server\\share\\folder")]
+ [InlineData("\\\\192.168.1.1\\share")]
+ [InlineData("\\\\server")] // bare UNC (server only, no share) โ€” StartsWith("\\") โ†’ absolute
+ public void AbsolutePaths_Pass(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ [InlineData("...dir")]
+ [InlineData("\\Music")] // drive-relative on Windows, not absolute
+ [InlineData("/Music")] // same
+ [InlineData("/home/user")] // same โ€” leading slash without drive letter is not absolute on Windows
+ [InlineData("//server/share")] // forward-slash UNC is not recognized as absolute on Windows
+ [InlineData("C:")]
+ [InlineData("C:Music")]
+ public void NonAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.False(isValid);
+ }
+ }
+
+ public class WithLinuxInjected
+ {
+ [Theory]
+ [InlineData("/")]
+ [InlineData("/home")]
+ [InlineData("/home/user")]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ [InlineData("//192.168.1.1/share")]
+ public void AbsolutePaths_Pass(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ [InlineData("...dir")]
+ [InlineData("C:\\Music")] // backslash paths are relative on Linux
+ [InlineData("C:/Music")] // starts with 'C', not '/' โ€” relative on Linux
+ [InlineData("\\\\server\\share")] // backslash UNC is relative on Linux
+ [InlineData("\\")]
+ [InlineData("\\home")]
+ public void NonAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux);
+ Assert.False(isValid);
+ }
+ }
+ }
+
+ public class ErrorMessages
+ {
+ [Fact]
+ public void Current_Message_MentionsCurrentOperatingSystem()
+ {
+ var (_, msg) = Validate("relative/path", OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.Contains("current operating system", msg);
+ }
+
+ [Fact]
+ public void Current_Message_IncludesFieldName()
+ {
+ var (_, msg) = Validate("relative/path", OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.Contains("Field", msg);
+ }
+
+ [Fact]
+ public void AnyAll_Message_MentionsAllOperatingSystems()
+ {
+ var (_, msg) = Validate("/home/user", OperatingSystem.Any);
+ Assert.Contains("all operating systems", msg);
+ }
+ }
+
+ // Any and All use identical logic: path must be absolute on both Windows and Linux.
+ // No common path satisfies this โ€” Windows uses drive letters or \\ UNC, Linux uses /,
+ // and no single path form is recognized as absolute by both detection rules.
+ public class Any
+ {
+ [Fact]
+ public void UsesAndLogic_NoPathCanEverPass_BecauseLinuxAndWindowsAbsoluteFormsAreIncompatible()
+ {
+ // If Any used OR-logic ("absolute on at least one OS"), a Linux-absolute path would pass.
+ // Any actually requires absolute on ALL checked OSes (AND-logic), identical to All.
+ // No path form satisfies both: Linux requires '/', Windows requires a drive letter or '\\'.
+ var (linuxAbsPath, _) = Validate("/home/user", OperatingSystem.Any);
+ var (winAbsPath, _) = Validate("C:\\Music", OperatingSystem.Any);
+ Assert.False(linuxAbsPath);
+ Assert.False(winAbsPath);
+ }
+
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ public void RelativePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.False(isValid);
+ }
+
+ // These are absolute on Windows but relative on Linux โ€” fail because not absolute on both
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\")]
+ [InlineData("\\\\server\\share")]
+ public void WindowsAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.False(isValid);
+ }
+
+ // These are absolute on Linux but relative on Windows โ€” fail because not absolute on both
+ [Theory]
+ [InlineData("/home/user")]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ [InlineData("/")]
+ public void LinuxAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.False(isValid);
+ }
+ }
+
+ public class All
+ {
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ public void RelativePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.False(isValid);
+ }
+
+ // These are absolute on Windows but relative on Linux โ€” fail because not absolute on both
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\")]
+ [InlineData("\\\\server\\share")]
+ public void WindowsAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.False(isValid);
+ }
+
+ // These are absolute on Linux but relative on Windows โ€” fail because not absolute on both
+ [Theory]
+ [InlineData("/home/user")]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ [InlineData("/")]
+ public void LinuxAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.False(isValid);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs
new file mode 100644
index 00000000..a26bb160
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs
@@ -0,0 +1,106 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class GuidAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false)
+ {
+ var attribute = new GuidAttribute(allowEmpty);
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attribute.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ // null is allowed; [Required] dictates whether the field must be defined
+ [Fact]
+ public void Null_Passes()
+ {
+ var (isValid, _) = Validate(null);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Empty_String_Fails_If_AllowEmpty_False()
+ {
+ var (isValid, message) = Validate("00000000-0000-0000-0000-000000000000", allowEmpty: false);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void Empty_Guid_Fails_If_AllowEmpty_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty, allowEmpty: false);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void AllowEmpty_Guid_Defaults_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void AllowEmpty_String_Defaults_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty.ToString());
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void Empty_String_Passes_If_AllowEmpty_True()
+ {
+ var (isValid, _) = Validate(Guid.Empty.ToString(), allowEmpty: true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Empty_Guid_Passes_If_AllowEmpty_True()
+ {
+ var (isValid, _) = Validate(Guid.Empty, allowEmpty: true);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens
+ [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens
+ [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format)
+ [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format
+ [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format
+ [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's
+ public void ValidGuidString_Passes(string value)
+ {
+ var (isValid, _) = Validate(value);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("not-a-guid")] // arbitrary string
+ [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short
+ [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z
+ [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long
+ [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g
+ [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens
+ public void InvalidGuidString_Fails(string value)
+ {
+ var (isValid, errorMessage) = Validate(value);
+ Assert.False(isValid);
+ Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage);
+ }
+
+ [Fact]
+ public void NonStringValue_Fails()
+ {
+ var (isValid, errorMessage) = Validate(42);
+ Assert.False(isValid);
+ Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage);
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs
new file mode 100644
index 00000000..12efb899
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs
@@ -0,0 +1,94 @@
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class NonTraversingPathAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(string value)
+ {
+ var attribute = new NonTraversingPathAttribute();
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attribute.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ // paths can be null or empty; [Required] dictates whether they must be defined
+ [Fact]
+ public void Null_Passes()
+ {
+ var (isValid, _) = Validate(null);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void EmptyString_Passes()
+ {
+ var (isValid, _) = Validate(string.Empty);
+ Assert.True(isValid);
+ }
+
+ public class NonTraversal_Passes
+ {
+ [Theory]
+ // Windows-style
+ [InlineData("C:\\Music\\foo\\Windows")]
+ [InlineData("C:/Music/foo/Windows")]
+ // Unix-style
+ [InlineData("/home/user/foo/etc")]
+ [InlineData("\\home\\user\\foo\\etc")]
+ // UNC (backslash)
+ [InlineData("\\\\server\\share\\foo\\folder")]
+ // UNC (forward slash)
+ [InlineData("//server/foo/share")]
+ // soulseek
+ [InlineData("@foo/bar/baz")]
+ [InlineData("@foo\\bar\\baz")]
+ // filenames
+ [InlineData("@foo/bar/baz/baz../..qux/file.ext")]
+ public void NonTraversalSegment_Passes(string value)
+ {
+ var (isValid, errorMessage) = Validate(value);
+ Assert.True(isValid);
+ Assert.Null(errorMessage);
+ }
+ }
+
+ // Paths containing . or .. segments, which are valid directory names in isolation
+ // but indicate traversal or ambiguity and must be rejected regardless of whether
+ // the path is otherwise absolute or relative.
+ public class Traversal_Fails
+ {
+ [Theory]
+ // Windows-style
+ [InlineData("C:\\Music\\..\\Windows")]
+ [InlineData("C:\\Music\\.\\Artist")]
+ [InlineData("C:/Music/../Windows")]
+ [InlineData("C:/Music/./Artist")]
+ [InlineData("C:\\..")]
+ [InlineData("D:\\a\\b\\..\\c")]
+ // Unix-style
+ [InlineData("/../etc")]
+ [InlineData("/home/user/../etc")]
+ [InlineData("/home/user/./Music")]
+ [InlineData("/home/../../etc")]
+ // UNC (backslash)
+ [InlineData("\\\\server\\..\\Windows")]
+ [InlineData("\\\\server\\share\\..\\other")]
+ [InlineData("\\\\server\\share\\.\\folder")]
+ // UNC (forward slash)
+ [InlineData("//server/../share")]
+ [InlineData("//server/share/../other")]
+ // soulseek
+ [InlineData("@foo/bar/baz/baz/../file.ext")]
+ [InlineData("@foo/bar/baz/./../file.ext")]
+ [InlineData("@foo/bar/baz/./baz/file.ext")]
+ public void TraversalSegment_Fails(string value)
+ {
+ var (isValid, errorMessage) = Validate(value);
+ Assert.False(isValid);
+ Assert.Contains("traversal segments", errorMessage);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs
new file mode 100644
index 00000000..ea74f822
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs
@@ -0,0 +1,317 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Reflection;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class RelativePathAttributeTests
+{
+ private static RelativePathAttribute CreateAttribute(OperatingSystem os, OperatingSystem? injected = null)
+ {
+ var attr = new RelativePathAttribute(os);
+
+ if (injected.HasValue)
+ {
+ var field = typeof(RelativePathAttribute)
+ .GetField("<Injected>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
+ field.SetValue(attr, injected.Value);
+ }
+
+ return attr;
+ }
+
+ private static (bool IsValid, string ErrorMessage) Validate(string value, OperatingSystem os, OperatingSystem? injected = null)
+ {
+ var attr = CreateAttribute(os, injected);
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attr.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ public class Constructor
+ {
+ [Fact]
+ public void AcceptsCurrentOsValue()
+ {
+ var ex = Record.Exception(() => _ = new RelativePathAttribute(OperatingSystem.Current));
+
+ Assert.Null(ex);
+ }
+
+ [Fact]
+ public void AcceptsAnyOsValue()
+ {
+ var ex = Record.Exception(() => _ = new RelativePathAttribute(OperatingSystem.Any));
+
+ Assert.Null(ex);
+ }
+
+ [Fact]
+ public void AcceptsAllOsValue()
+ {
+ var ex = Record.Exception(() => _ = new RelativePathAttribute(OperatingSystem.All));
+
+ Assert.Null(ex);
+ }
+
+ [Fact]
+ public void ThrowsForWindowsOsValue()
+ {
+ Assert.Throws<ArgumentException>(() => new RelativePathAttribute(OperatingSystem.Windows));
+ }
+
+ [Fact]
+ public void ThrowsForLinuxOsValue()
+ {
+ Assert.Throws<ArgumentException>(() => new RelativePathAttribute(OperatingSystem.Linux));
+ }
+
+ [Fact]
+ public void ThrowsForNoneOsValue()
+ {
+ Assert.Throws<ArgumentException>(() => new RelativePathAttribute(OperatingSystem.None));
+ }
+ }
+
+ public class NullOrEmpty
+ {
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForCurrentWithWindowsInjected(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForCurrentWithLinuxInjected(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForAny(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void Passes_ForAll(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.True(isValid);
+ }
+ }
+
+ public class ErrorMessages
+ {
+ [Fact]
+ public void Current_Message_IncludesFieldName()
+ {
+ var (_, msg) = Validate("C:\\Music", OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.Contains("Field", msg);
+ }
+
+ [Fact]
+ public void Current_Message_Text()
+ {
+ var (_, msg) = Validate("C:\\Music", OperatingSystem.Current, OperatingSystem.Windows);
+ // Note: the implementation uses the same message for Current as for Any/All.
+ // "on all operating systems" is misleading here since Current only validates
+ // against the current (or injected) OS.
+ Assert.Equal("The Field field must be a relative path on the current operating system.", msg);
+ }
+
+ [Fact]
+ public void AnyAll_Message_MentionsRelativePath()
+ {
+ var (_, msg) = Validate("C:\\Music", OperatingSystem.Any);
+ Assert.Contains("relative path", msg);
+ }
+ }
+
+ // Current mode: validates using only the injected (or actual current) OS
+ public class Current
+ {
+ public class WithWindowsInjected
+ {
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ [InlineData("...dir")]
+ [InlineData("/Music")] // drive-relative on Windows, not absolute
+ [InlineData("/home/user")] // same โ€” leading slash without drive letter is not absolute on Windows
+ [InlineData("//server/share")] // forward-slash UNC is not recognized as absolute on Windows
+ public void RelativePaths_Pass(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\Music\\Artist\\Album")]
+ [InlineData("C:\\")]
+ [InlineData("Z:\\")]
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\\\server\\share\\folder")]
+ [InlineData("\\\\192.168.1.1\\share")]
+ [InlineData("\\\\server")] // bare UNC (server only, no share) โ€” StartsWith("\\") โ†’ absolute
+ public void AbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows);
+ Assert.False(isValid);
+ }
+ }
+
+ public class WithLinuxInjected
+ {
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ [InlineData("...dir")]
+ [InlineData("C:\\Music")] // backslash paths are relative on Linux
+ [InlineData("C:/Music")] // starts with 'C', not '/' โ€” relative on Linux
+ [InlineData("\\\\server\\share")] // backslash UNC is relative on Linux
+ public void RelativePaths_Pass(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("/")]
+ [InlineData("/home")]
+ [InlineData("/home/user")]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ [InlineData("//192.168.1.1/share")]
+ public void AbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux);
+ Assert.False(isValid);
+ }
+ }
+ }
+
+ // Any and All use identical logic: path must be relative on both Windows and Linux
+ public class Any
+ {
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ [InlineData("...dir")]
+ public void TrulyRelativePaths_Pass(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.True(isValid);
+ }
+
+ // These are absolute on Windows, so they fail even though they're relative on Linux
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\Music\\Artist\\Album")]
+ [InlineData("C:\\")]
+ [InlineData("Z:\\")]
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\\\server\\share\\folder")]
+ public void WindowsAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.False(isValid);
+ }
+
+ // These are absolute on Linux, so they fail even though they're relative on Windows
+ [Theory]
+ [InlineData("/")]
+ [InlineData("/home")]
+ [InlineData("/home/user")]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ [InlineData("//192.168.1.1/share")]
+ public void LinuxAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.Any);
+ Assert.False(isValid);
+ }
+ }
+
+ public class All
+ {
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ [InlineData("music.flac")]
+ [InlineData("My Music")]
+ [InlineData("..")]
+ [InlineData(".hidden")]
+ [InlineData("...dir")]
+ public void TrulyRelativePaths_Pass(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.True(isValid);
+ }
+
+ // These are absolute on Windows, so they fail even though they're relative on Linux
+ [Theory]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\Music\\Artist\\Album")]
+ [InlineData("C:\\")]
+ [InlineData("Z:\\")]
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\\\server\\share\\folder")]
+ public void WindowsAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.False(isValid);
+ }
+
+ // These are absolute on Linux, so they fail even though they're relative on Windows
+ [Theory]
+ [InlineData("/")]
+ [InlineData("/home")]
+ [InlineData("/home/user")]
+ [InlineData("/Music")]
+ [InlineData("//server/share")]
+ [InlineData("//192.168.1.1/share")]
+ public void LinuxAbsolutePaths_Fail(string value)
+ {
+ var (isValid, _) = Validate(value, OperatingSystem.All);
+ Assert.False(isValid);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs
new file mode 100644
index 00000000..dbf8396f
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs
@@ -0,0 +1,422 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Text.RegularExpressions;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class StringAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(string value, Action<StringAttribute> configure = null)
+ {
+ var attr = new StringAttribute();
+ configure?.Invoke(attr);
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attr.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ public class Null
+ {
+ [Fact]
+ public void Passes_When_AllowNull()
+ {
+ var (isValid, message) = Validate(null, a => a.AllowNull = true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Fails_When_Not_AllowNull()
+ {
+ var (isValid, message) = Validate(null, a => a.AllowNull = false);
+ Assert.False(isValid);
+ Assert.Contains("must not be null", message);
+ }
+
+ [Fact]
+ public void NonNull_Passes_Regardless()
+ {
+ var (isValid, message) = Validate("foo", a => a.AllowNull = true);
+ Assert.True(isValid);
+
+ var (isValid2, message2) = Validate("foo", a => a.AllowNull = false);
+ Assert.True(isValid2);
+ }
+ }
+
+ public class Empty
+ {
+ [Fact]
+ public void Empty_Passes_When_AllowEmpty_Is_True()
+ {
+ var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Empty_Fails_When_AllowEmpty_Is_False()
+ {
+ var (isValid, message) = Validate(string.Empty, a => a.AllowEmpty = false);
+ Assert.False(isValid);
+ Assert.Contains("at least one character", message);
+ }
+
+ [Fact]
+ public void NonEmpty_Passes_Regardless()
+ {
+ var (isValid, _) = Validate("hello", a => a.AllowEmpty = false);
+ Assert.True(isValid);
+
+ var (isValid2, _) = Validate("hello", a => a.AllowEmpty = true);
+ Assert.True(isValid2);
+ }
+ }
+
+ public class WhiteSpace
+ {
+ [Fact]
+ public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True()
+ {
+ var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False()
+ {
+ var (isValid, message) = Validate(" ", a => a.AllowWhiteSpace = false);
+ Assert.False(isValid);
+ Assert.Contains("whitespace", message);
+ }
+
+ [Fact]
+ public void NonWhiteSpace_Passes_Regardless()
+ {
+ var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false);
+ Assert.True(isValid);
+
+ var (isValid2, _) = Validate("hello", a => a.AllowWhiteSpace = true);
+ Assert.True(isValid2);
+ }
+ }
+
+ public class DisallowedCharacters
+ {
+ public class Passes
+ {
+ [Fact]
+ public void EmptyString_Passes()
+ {
+ var (isValid, _) = Validate(string.Empty, a => a.DisallowedCharacters = ['!']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void NoDisallowedCharsPresent_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void EmptyDisallowedSet_Passes()
+ {
+ var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Unicode_AllowedChars_Pass()
+ {
+ var (isValid, _) = Validate("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ/้Ÿณๆฅฝ", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.True(isValid);
+ }
+
+ // Case-insensitive matching only folds the declared disallowed chars, not all letters;
+ // a disallowed lower-case letter does not block an entirely different upper-case letter.
+ [Fact]
+ public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter()
+ {
+ var (isValid, _) = Validate("B", a => a.DisallowedCharacters = ['a']);
+ Assert.True(isValid);
+ }
+ }
+
+ public class Fails
+ {
+ [Fact]
+ public void SingleDisallowedChar_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharAtStart_Fails()
+ {
+ var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharAtEnd_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharInMiddle_Fails()
+ {
+ var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void OneOfMultipleDisallowedCharsPresent_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void MultipleDisallowedCharsAllPresent_Fails()
+ {
+ var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharRepeated_Fails()
+ {
+ var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void AllCharsDisallowed_Fails()
+ {
+ var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void Unicode_DisallowedChar_Fails()
+ {
+ var (isValid, _) = Validate("ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ", a => a.DisallowedCharacters = ['ะต']);
+ Assert.False(isValid);
+ }
+
+ // character matching is always case-insensitive
+ [Fact]
+ public void LowerCaseDisallowed_Blocks_UpperCase()
+ {
+ var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void UpperCaseDisallowed_Blocks_LowerCase()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ExactMatch_Fails()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']);
+ Assert.False(isValid);
+ }
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void TheDisallowedChar()
+ {
+ var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.Contains("'!'", errorMessage);
+ }
+
+ [Fact]
+ public void AllPresentDisallowedChars()
+ {
+ var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.Contains("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void EachOccurrenceOfRepeatedChar()
+ {
+ // "he!lo!" has two '!' โ€” both occurrences are listed
+ var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']);
+ Assert.Equal(2, errorMessage.Split("'!'").Length - 1);
+ }
+
+ [Fact]
+ public void OnlyCharsActuallyPresent_NotAllDisallowedChars()
+ {
+ // '@' is disallowed but not in the value โ€” must not appear in the message
+ var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.DoesNotContain("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void ShowsActualChar_NotDisallowedChar()
+ {
+ // 'a' is disallowed (lowercase); value contains 'A' (uppercase).
+ // The message reports what the user supplied ('A'), not the disallowed definition ('a').
+ var (_, errorMessage) = Validate("A", a => a.DisallowedCharacters = ['a']);
+ Assert.Contains("'A'", errorMessage);
+ Assert.DoesNotContain("'a'", errorMessage);
+ }
+ }
+ }
+
+ public class Length
+ {
+ [Fact]
+ public void Within_Range_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => { a.MinimumLength = 3; a.MaximumLength = 10; });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void ExactlyAtMinimumLength_Passes()
+ {
+ var (isValid, _) = Validate("hi", a => a.MinimumLength = 2);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void ExactlyAtMaximumLength_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.MaximumLength = 5);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void BelowMinimumLength_Fails()
+ {
+ var (isValid, _) = Validate("hi", a => a.MinimumLength = 5);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ExceedsMaximumLength_Fails()
+ {
+ var (isValid, _) = Validate("hello world", a => a.MaximumLength = 5);
+ Assert.False(isValid);
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void MinimumLength_Value()
+ {
+ var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; });
+ Assert.Contains("5", message);
+ }
+
+ [Fact]
+ public void MaximumLength_Value()
+ {
+ var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; });
+ Assert.Contains("20", message);
+ }
+ }
+ }
+
+ public class Pattern
+ {
+ [Fact]
+ public void NullPattern_Passes()
+ {
+ // Pattern defaults to null; any value passes the pattern check
+ var (isValid, _) = Validate("hello");
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void ValueMatchingPattern_Fails()
+ {
+ var (isValid, _) = Validate("hello1", a => a.Pattern = new Regex("[0-9]"));
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ValueNotMatchingPattern_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.Pattern = new Regex("[0-9]"));
+ Assert.True(isValid);
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void RegularExpression_Keyword()
+ {
+ var (_, message) = Validate("hello1", a => a.Pattern = new Regex("[0-9]"));
+ Assert.Contains("regular expression", message);
+ }
+ }
+ }
+
+ public class CheckOrdering
+ {
+ // AllowNull is checked before AllowEmpty:
+ // null with both disabled returns the null error, not the empty error.
+ [Fact]
+ public void Null_ReturnsNullError_Not_EmptyError()
+ {
+ var (_, message) = Validate(null, a => { a.AllowNull = false; a.AllowEmpty = false; });
+ Assert.Contains("null", message);
+ Assert.DoesNotContain("character", message);
+ }
+
+ // AllowEmpty is checked before AllowWhiteSpace:
+ // "" with both disabled returns the empty error, not the whitespace error.
+ [Fact]
+ public void Empty_ReturnsEmptyError_Not_WhitespaceError()
+ {
+ var (_, message) = Validate(string.Empty, a => { a.AllowEmpty = false; a.AllowWhiteSpace = false; });
+ Assert.Contains("character", message);
+ Assert.DoesNotContain("whitespace", message);
+ }
+
+ // AllowWhiteSpace is checked before the length check:
+ // a whitespace string that is also below MinimumLength returns the whitespace error.
+ [Fact]
+ public void Whitespace_ReturnsWhitespaceError_Not_LengthError()
+ {
+ var (_, message) = Validate(" ", a => { a.AllowWhiteSpace = false; a.MinimumLength = 10; });
+ Assert.Contains("whitespace", message);
+ Assert.DoesNotContain("between", message);
+ }
+
+ // Length is checked before DisallowedCharacters:
+ // a too-short string that also contains a disallowed character returns the length error.
+ [Fact]
+ public void TooShort_ReturnsLengthError_Not_DisallowedCharsError()
+ {
+ var (_, message) = Validate("hi!", a => { a.MinimumLength = 10; a.DisallowedCharacters = ['!']; });
+ Assert.Contains("between", message);
+ Assert.DoesNotContain("disallowed", message);
+ }
+
+ // DisallowedCharacters is checked before Pattern:
+ // a string with a disallowed character that also matches the pattern returns the disallowed-chars error.
+ [Fact]
+ public void DisallowedChar_ReturnsDisallowedError_Not_PatternError()
+ {
+ var (_, message) = Validate("hello!1", a => { a.DisallowedCharacters = ['!']; a.Pattern = new Regex("[0-9]"); });
+ Assert.Contains("disallowed", message);
+ Assert.DoesNotContain("expression", message);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs
new file mode 100644
index 00000000..7eacb95d
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs
@@ -0,0 +1,40 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Xunit;
+using static slskd.Options;
+
+namespace slskd.Tests.Unit.Core.Options;
+
+public class SharesOptionsTests
+{
+ private static List<ValidationResult> Validate(SharesOptions options)
+ {
+ var context = new ValidationContext(options);
+ var results = new List<ValidationResult>();
+ Validator.TryValidateObject(options, context, results, validateAllProperties: true);
+ return results;
+ }
+
+ public class Directories
+ {
+ public class Digest
+ {
+ [Fact]
+ public void Alias_Uses_First_Closing_Bracket_When_Path_Contains_Brackets()
+ {
+ // [foo]/bar/[baz]/ should digest to alias "foo" and path "/bar/[baz]"
+ var options = new SharesOptions
+ {
+ Directories = [@"[foo]/bar/[baz]/"]
+ };
+
+ // todo: fix this so that it fully validates on all platforms; currently this fails
+ // validation on Windows and would fail on Linux if i were to use backslashes
+ // the assertion for the alias proves we have fixed an aliasing bug so it's fine for now
+ var results = Validate(options);
+
+ Assert.DoesNotContain(results, r => r.ErrorMessage?.Contains("aliases may not contain path separators") == true);
+ }
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
index 7bb0bfdd..d6c30316 100644
--- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
+++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
@@ -155,11 +155,17 @@ namespace slskd.Tests.Unit.Files
OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options
{
- Permissions = new Options.PermissionsOptions
+ Transfers = new Options.TransfersOptions
{
- File = new Options.PermissionsOptions.FileOptions
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
{
- Mode = mode,
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions
+ {
+ Mode = mode,
+ }
+ }
}
}
});
@@ -204,11 +210,17 @@ namespace slskd.Tests.Unit.Files
OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options
{
- Permissions = new Options.PermissionsOptions
+ Transfers = new Options.TransfersOptions
{
- File = new Options.PermissionsOptions.FileOptions
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
{
- Mode = mode,
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions
+ {
+ Mode = mode,
+ }
+ }
}
}
});
@@ -262,11 +274,17 @@ namespace slskd.Tests.Unit.Files
OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options
{
- Permissions = new Options.PermissionsOptions
+ Transfers = new Options.TransfersOptions
{
- File = new Options.PermissionsOptions.FileOptions
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
{
- Mode = mode,
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions
+ {
+ Mode = mode,
+ }
+ }
}
}
});
@@ -316,11 +334,17 @@ namespace slskd.Tests.Unit.Files
OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options
{
- Permissions = new Options.PermissionsOptions
+ Transfers = new Options.TransfersOptions
{
- File = new Options.PermissionsOptions.FileOptions
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
{
- Mode = mode,
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions
+ {
+ Mode = mode,
+ }
+ }
}
}
});
@@ -367,11 +391,17 @@ namespace slskd.Tests.Unit.Files
OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options
{
- Permissions = new Options.PermissionsOptions
+ Transfers = new Options.TransfersOptions
{
- File = new Options.PermissionsOptions.FileOptions
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
{
- Mode = optionsMode,
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions
+ {
+ Mode = optionsMode,
+ }
+ }
}
}
});
@@ -401,11 +431,17 @@ namespace slskd.Tests.Unit.Files
OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options
{
- Permissions = new Options.PermissionsOptions
+ Transfers = new Options.TransfersOptions
{
- File = new Options.PermissionsOptions.FileOptions
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
{
- Mode = optionsMode,
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions
+ {
+ Mode = optionsMode,
+ }
+ }
}
}
});
diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs
new file mode 100644
index 00000000..f608467b
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs
@@ -0,0 +1,321 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using slskd.Transfers.API;
+using Xunit;
+
+namespace slskd.Tests.Unit.Transfers.API.DTO;
+
+public class QueueDownloadBatchRequestTests
+{
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ {
+ var results = new List<ValidationResult>();
+ var isValid = Validator.TryValidateObject(obj, new ValidationContext(obj), results, validateAllProperties: true);
+ return (isValid, results);
+ }
+
+ private static QueueDownloadBatchRequest ValidRequest() => new()
+ {
+ Username = "testuser",
+ Files = [new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }],
+ };
+
+ public class Id_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Id = null });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("not-a-guid")]
+ [InlineData("b5bde3d1-4aba-4d64-b64a")]
+ public void NonGuid_Fails(string value)
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Id = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The Id field must be a valid GUID/UUID", results[0].ErrorMessage);
+ }
+
+ [Theory]
+ [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")]
+ [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")]
+ [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")]
+ public void ValidGuid_Passes(string value)
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Id = value });
+ Assert.True(isValid);
+ }
+ }
+
+ public class SearchId_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { SearchId = null });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("not-a-guid")]
+ [InlineData("b5bde3d1-4aba-4d64-b64a")]
+ public void NonGuid_Fails(string value)
+ {
+ var (isValid, results) = Validate(ValidRequest() with { SearchId = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The SearchId field must be a valid GUID/UUID", results[0].ErrorMessage);
+ }
+
+ [Theory]
+ [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")]
+ [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")]
+ [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")]
+ public void ValidGuid_Passes(string value)
+ {
+ var (isValid, _) = Validate(ValidRequest() with { SearchId = value });
+ Assert.True(isValid);
+ }
+ }
+
+ public class Username_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = null });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Username field is required.");
+ }
+
+ [Fact]
+ public void Empty_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = "" });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Username field is required.");
+ }
+
+ [Fact]
+ public void Whitespace_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = " " });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Username field is required.");
+ }
+
+ [Fact]
+ public void OneChar_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Username = "a" });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void FiveHundredChars_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 500) });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void FiveHundredOneChars_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("between 1 and 500 characters", results[0].ErrorMessage);
+ }
+ }
+
+ public class Files_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Fails_WithRequiredMessage()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Files = null });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The Files field is required.", results[0].ErrorMessage);
+ }
+
+ [Fact]
+ public void EmptyList_Fails_WithMinLengthMessage()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Files = [] });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("minimum length of '1'", results[0].ErrorMessage);
+ }
+ }
+
+ public class Files_Item
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void NullFilename_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required.");
+ }
+
+ [Fact]
+ public void EmptyFilename_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required.");
+ }
+
+ [Fact]
+ public void WhitespaceFilename_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = " ", Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required.");
+ }
+
+ [Fact]
+ public void ValidFilename_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void NegativeSize_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The field Size must be between 0 and 9.223372036854776E+18.", results[0].ErrorMessage);
+ }
+
+ [Fact]
+ public void ZeroSize_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void PositiveSize_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("@foo/bar/../baz/file.mp3")]
+ [InlineData("@foo/bar/./baz/file.mp3")]
+ [InlineData("@foo\\bar\\..\\baz\\file.mp3")]
+ public void TraversalSegmentInFilename_Fails(string value)
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage != null && r.ErrorMessage.Contains("traversal segments"));
+ }
+
+ [Theory]
+ [InlineData("@foo/bar/baz/file.mp3")]
+ [InlineData("@foo/bar/baz/file..ext")]
+ [InlineData("@foo\\bar\\baz\\file.mp3")]
+ public void NonTraversalFilename_Passes(string value)
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 });
+ Assert.True(isValid);
+ }
+ }
+
+ public class Options_Destination
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = null });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ public void RelativePath_Passes(string value)
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("C:\\Music")] // Windows absolute
+ [InlineData("C:/Music")] // Windows absolute, forward slash
+ [InlineData("\\\\server\\share")] // UNC
+ public void AbsolutePath_Fails_Windows(string value)
+ {
+ if (System.OperatingSystem.IsWindows())
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("must be a relative path", results[0].ErrorMessage);
+ }
+ }
+
+ [Theory]
+ [InlineData("/music")] // Unix absolute
+ [InlineData("/home/user/Music")] // Unix absolute, deep
+ [InlineData("//server/share")] // UNC
+ public void AbsolutePath_Fails_Non_Windows(string value)
+ {
+ if (!System.OperatingSystem.IsWindows())
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("must be a relative path", results[0].ErrorMessage);
+ }
+ }
+
+ [Theory]
+ [InlineData("../escape")] // traversal prefix
+ [InlineData("./music")] // current-dir prefix
+ [InlineData("music/../other")] // traversal in middle
+ [InlineData("sub/../../escape")] // double traversal
+ [InlineData("music\\..")] // traversal via backslash
+ public void TraversalSegment_Fails(string value)
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("traversal segments", results[0].ErrorMessage);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs
new file mode 100644
index 00000000..fcf3c45a
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs
@@ -0,0 +1,608 @@
+namespace slskd.Tests.Unit.Transfers.Downloads;
+
+using System;
+using System.IO;
+using System.Linq.Expressions;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+using Moq;
+using slskd.Search;
+using slskd.Transfers;
+using slskd.Transfers.Downloads;
+using Xunit;
+
+public partial class DownloadServiceTests
+{
+ public class DeriveDestination
+ {
+ [Fact]
+ public async Task Explicit_Destination_Takes_Precedence_Over_Subdirectory_Pattern()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } };
+ var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("explicit-dir", result);
+ }
+
+ [Fact]
+ public async Task Explicit_Destination_Tokens_Are_Not_Expanded()
+ {
+ // explicit destination is sanitized but not token-substituted
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "${SOURCE_USERNAME}" } };
+ var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("${SOURCE_USERNAME}", result);
+ }
+
+ [Fact]
+ public async Task Explicit_Destination_Is_Always_Relative()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "/etc/passwd" } };
+ var (service, _) = GetFixture("irrelevant", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.False(FileSafety.IsPathAbsolute(result));
+ }
+
+ [Fact]
+ public async Task Explicit_Destination_Traversal_Segments_Do_Not_Survive()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "../../../etc/passwd" } };
+ var (service, _) = GetFixture("irrelevant", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.False(FileSafety.ContainsTraversalSegments(result));
+ }
+
+ [Fact]
+ public async Task Explicit_Destination_Null_Byte_Replaced()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "down\0loads" } };
+ var (service, _) = GetFixture("irrelevant", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("down_loads", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_USERNAME_Is_Substituted()
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("alice", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive()
+ {
+ var (service, _) = GetFixture("${source_username}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("alice", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore()
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}");
+ var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("al_ice", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore()
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}");
+ var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("al_ice", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore()
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}");
+ var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("al_ice", result);
+ }
+
+ [Theory]
+ [InlineData("al\\..\\ice")]
+ [InlineData("al/../ice")]
+ [InlineData("al\\../ice")]
+ [InlineData("al/..\\ice")]
+ public async Task SOURCE_USERNAME_Traversal_Segment_Periods_Remains_After_Replacing_Slashes_With_Underscore(string username)
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}");
+ var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("al_.._ice", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash()
+ {
+ var (service, _) = GetFixture("${SOURCE_DIRECTORY}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" });
+
+ Assert.Equal("album", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash()
+ {
+ var (service, _) = GetFixture("${SOURCE_DIRECTORY}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" });
+
+ Assert.Equal("album", result);
+ }
+
+ [Fact]
+ public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root()
+ {
+ var (service, _) = GetFixture("${SOURCE_DIRECTORY}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" });
+
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Fact]
+ public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename()
+ {
+ var (service, _) = GetFixture("${SOURCE_PATH}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" });
+
+ Assert.Equal(Path.Combine("@alice", "Music", "album"), result);
+ }
+
+ [Fact]
+ public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root()
+ {
+ var (service, _) = GetFixture("${SOURCE_PATH}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" });
+
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Fact]
+ public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory()
+ {
+ var (service, _) = GetFixture("${SOURCE_PATH}-${SOURCE_DIRECTORY}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("@alice-@alice", result);
+ }
+
+ [Fact]
+ public async Task BATCH_ID_Is_Substituted_When_Batch_Exists()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId };
+ var (service, _) = GetFixture("${BATCH_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal(batchId.ToString(), result);
+ }
+
+ [Fact]
+ public async Task BATCH_ID_Is_Fallback_When_No_Batch()
+ {
+ var (service, _) = GetFixture("${BATCH_ID}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+ Assert.Equal("unknown_batch_id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_ID_Is_Fallback_When_Batch_Id_Is_Empty_Guid()
+ {
+ var batch = new Batch { Id = Guid.Empty };
+ var (service, _) = GetFixture("${BATCH_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = Guid.Empty });
+
+ Assert.Equal("unknown_batch_id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Is_Substituted_When_Batch_Has_External_Id()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "my-ext-id" } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("my-ext-id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch()
+ {
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("unknown_batch_external_id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Null()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_batch_external_id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Whitespace()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_batch_external_id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Forward_Slash_In_Value_Replaced_With_Underscore()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo/bar" } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo_bar", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Backslash_In_Value_Replaced_With_Underscore()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\\bar" } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo_bar", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Null_Byte_In_Value_Replaced_With_Underscore()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\0bar" } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo_bar", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_ID_Is_Substituted_When_Search_Exists()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "some query" };
+ var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal(searchId.ToString(), result);
+ }
+
+ [Fact]
+ public async Task SEARCH_ID_Is_Fallback_When_No_Batch()
+ {
+ // no batch โ†’ SearchId is never consulted
+ var (service, _) = GetFixture("${SEARCH_ID}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("unknown_search_id", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_ID_Is_Fallback_When_Batch_Has_No_SearchId()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = null };
+ var (service, _) = GetFixture("${SEARCH_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_search_id", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_ID_Is_Fallback_When_Search_Not_Found()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() };
+ var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: null);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_search_id", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_ID_Is_Fallback_When_Search_ID_Is_Empty_Guid()
+ {
+ var searchId = Guid.Empty;
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "some query" };
+ var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_search_id", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Is_Substituted_When_Search_Exists()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "foo bar baz" };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo bar baz", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Is_Fallback_When_No_Search()
+ {
+ var (service, _) = GetFixture("${SEARCH_TEXT}");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal("unknown_search_text", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Forward_Slash_In_Value_Replaced_With_Underscore()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "foo/bar" };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo_bar", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Backlash_In_Value_Replaced_With_Underscore()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "foo\\bar" };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo_bar", result);
+ }
+
+ [Fact]
+ public async Task Batch_With_Null_Options_Falls_Through_To_Pattern()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = null };
+ var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("alice", result);
+ }
+
+ [Fact]
+ public async Task Batch_With_Whitespace_Destination_Falls_Through_To_Pattern()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } };
+ var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("alice", result);
+ }
+
+ [Fact]
+ public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output()
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}/downloads");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal(Path.Combine("alice", "downloads"), result);
+ }
+
+ [Fact]
+ public async Task Pattern_Backslash_Separator_Preserved_In_Output()
+ {
+ var (service, _) = GetFixture("${SOURCE_USERNAME}\\downloads");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.Equal(Path.Combine("alice", "downloads"), result);
+ }
+
+ [Fact]
+ public async Task Pattern_Output_Is_Always_Relative()
+ {
+ var (service, _) = GetFixture("/etc/passwd");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.False(FileSafety.IsPathAbsolute(result));
+ }
+
+ [Fact]
+ public async Task Pattern_Traversal_Segments_Do_Not_Survive()
+ {
+ var (service, _) = GetFixture("../../../etc/passwd");
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" });
+
+ Assert.False(FileSafety.ContainsTraversalSegments(result));
+ }
+
+ [Fact]
+ public async Task Username_Containing_Traversal_Is_Safe()
+ {
+ // exact '..' in username must not produce a traversal segment in the final output
+ var (service, _) = GetFixture("${SOURCE_USERNAME}");
+ var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" });
+
+ Assert.False(FileSafety.ContainsTraversalSegments(result));
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Null_Byte_In_Value_Replaced_With_Underscore()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "foo\0bar" };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("foo_bar", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Is_Fallback_When_Search_Not_Found()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: null);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_search_text", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Is_Fallback_When_Batch_Has_No_SearchId()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = null };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_search_text", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty()
+ {
+ 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()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = " " };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_search_text", result);
+ }
+
+ [Fact]
+ public async Task SEARCH_TEXT_Traversal_Segments_Do_Not_Survive()
+ {
+ var searchId = Guid.NewGuid();
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, SearchId = searchId };
+ var search = new Search { Id = searchId, SearchText = "../evil" };
+ var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.False(FileSafety.ContainsTraversalSegments(result));
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Empty_String()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "" } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.Equal("unknown_batch_external_id", result);
+ }
+
+ [Fact]
+ public async Task BATCH_EXTERNAL_ID_Traversal_Segments_Do_Not_Survive()
+ {
+ var batchId = Guid.NewGuid();
+ var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "../evil" } };
+ var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch);
+ var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId });
+
+ Assert.False(FileSafety.ContainsTraversalSegments(result));
+ }
+ }
+
+ private static (DownloadService service, Mocks mocks) GetFixture(
+ string subdirectory = "${SOURCE_USERNAME}",
+ Batch batch = null,
+ Search search = null)
+ {
+ var mocks = new Mocks(subdirectory, batch, search);
+ var service = new DownloadService(
+ mocks.BatchService.Object,
+ mocks.SearchService.Object,
+ mocks.OptionsMonitor,
+ null,
+ new Mock<IDbContextFactory<TransfersDbContext>>().Object,
+ null,
+ null,
+ null,
+ null);
+ return (service, mocks);
+ }
+
+ private class Mocks
+ {
+ public Mocks(string subdirectory = null, Batch batch = null, Search search = null)
+ {
+ OptionsMonitor = new TestOptionsMonitor<Options>(new Options
+ {
+ Transfers = new Options.TransfersOptions
+ {
+ Download = new Options.TransfersOptions.GlobalDownloadOptions
+ {
+ Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions
+ {
+ Subdirectory = subdirectory
+ }
+ }
+ }
+ });
+
+ BatchService.Setup(b => b.FindAsync(It.IsAny<Expression<Func<Batch, bool>>>()))
+ .ReturnsAsync(batch);
+ SearchService.Setup(s => s.FindAsync(It.IsAny<Expression<Func<Search, bool>>>(), It.IsAny<bool>()))
+ .ReturnsAsync(search);
+ }
+
+ public Mock<IBatchService> BatchService { get; } = new();
+ public Mock<ISearchService> SearchService { get; } = new();
+ public TestOptionsMonitor<Options> OptionsMonitor { get; }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj
index d1e76222..7278bd6d 100644
--- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj
+++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj
@@ -7,14 +7,14 @@
<ItemGroup>
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageReference Include="Moq" Version="4.16.1" />
- <PackageReference Include="xunit" Version="2.6.6" />
- <PackageReference Include="xunit.runner.visualstudio" Version="2.5.6">
+ <PackageReference Include="xunit" Version="2.9.3" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="coverlet.msbuild" Version="6.0.0">
+ <PackageReference Include="coverlet.msbuild" Version="10.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>