diff options
| author | Daniel <107576740+maskedmaxx@users.noreply.github.com> | 2026-05-20 20:55:17 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-20 20:55:17 -0400 |
| commit | 96b62ac8596a8ba2c028b88964ff76a8aad3e5bf (patch) | |
| tree | b55aa04d606b258b32fd48c1183507a4a16c090d /src/slskd | |
| parent | 61703575cf9038f6a0de89bb5b9be44431439618 (diff) | |
| parent | 03b35a5ababfd7bc2d0af053d8622a14cdd6b8fe (diff) | |
| download | slskd-96b62ac8596a8ba2c028b88964ff76a8aad3e5bf.tar.gz | |
Merge branch 'master' into fix/issue-1726-relay-controller-trailing-slash
Diffstat (limited to 'src/slskd')
25 files changed, 1281 insertions, 374 deletions
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index e0d56511..5ff3e519 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -557,9 +557,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/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 4c9f5e53..1999220f 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } - - // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here - if (FileSafety.ContainsTraversalSegments(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); - } } return ValidationResult.Success; 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/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs index 90ed3d81..1e2616bd 100644 --- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs +++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs @@ -1,4 +1,4 @@ -// <copyright file="DisallowedCharactersAttribute.cs" company="JP Dillingham"> +// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ @@ -30,42 +30,28 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> -namespace slskd.Validation; - -using System.ComponentModel.DataAnnotations; -using System.Linq; - -/// <summary> -/// Validates that the value does not contain any of the <see cref="Disallowed"/> characters. -/// </summary> -public class DisallowedCharactersAttribute : ValidationAttribute +namespace slskd.Validation { - public DisallowedCharactersAttribute(params char[] disallowed) - { - Disallowed = disallowed; - } + using System.ComponentModel.DataAnnotations; /// <summary> - /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>. + /// Validates that the specified path does not contain traversal segments '.' or '..'. /// </summary> - public bool IgnoreCase { get; set; } = true; - - private char[] Disallowed { get; } - - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + public class NonTraversingPathAttribute : ValidationAttribute { - if (value is not null and string str) + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - var invalid = IgnoreCase - ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))) - : str.Where(c => Disallowed.Contains(c)); - - if (invalid.Any()) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + var path = value.ToString(); + + if (FileSafety.ContainsTraversalSegments(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); + } } - } - return ValidationResult.Success; + return ValidationResult.Success; + } } }
\ No newline at end of file diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index edaef1be..64e418b1 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,15 +49,9 @@ namespace slskd.Validation { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } - - // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here - if (FileSafety.ContainsTraversalSegments(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); - } } 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 51b3cab1..83e534a1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,7 +198,6 @@ namespace slskd [Argument('i', "instance-name")] [EnvironmentVariable("INSTANCE_NAME")] [Description("optional; a unique name for this instance")] - [DisallowedCharacters('/', '\\')] [RequiresRestart] public string InstanceName { get; init; } = "default"; @@ -655,7 +654,6 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] - [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } @@ -768,6 +766,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -779,6 +778,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -845,9 +845,15 @@ namespace slskd directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. + // which is resolved by some OS and will cause weird, unintended side effects + bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + 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()) { @@ -2015,6 +2021,7 @@ namespace slskd [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] [AbsolutePath] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 42f43918..d4baf276 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -780,6 +780,7 @@ namespace slskd services.AddSingleton<ITransferService, TransferService>(); services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); + services.AddSingleton<IBatchService, BatchService>(); services.AddSingleton<FileService>(); services.AddSingleton<IRelayService, RelayService>(); 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..c1b7d725 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -0,0 +1,113 @@ +// <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] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Destination { 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..83e91ced 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -56,6 +56,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> @@ -71,12 +76,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 +164,7 @@ namespace slskd.Transfers.Downloads public class DownloadService : IDownloadService { public DownloadService( + IBatchService batchService, IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory<TransfersDbContext> contextFactory, @@ -166,6 +173,7 @@ namespace slskd.Transfers.Downloads IFTPService ftpClient, EventBus eventBus) { + Batches = batchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -178,6 +186,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: @@ -249,12 +262,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 +287,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 +325,7 @@ namespace slskd.Transfers.Downloads } List<Transfer> enqueued = []; - List<string> failed = []; + List<(string Filename, string Message)> failed = []; SemaphoreSlim userSemaphore; Task userSemaphoreWaitTask; @@ -404,7 +423,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 +435,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 +450,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 +626,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)) { @@ -973,9 +992,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 @@ -1028,12 +1049,10 @@ namespace slskd.Transfers.Downloads ? OptionsMonitor.CurrentValue.Permissions.File.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) + // 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 var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: System.IO.Path.Combine( - OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); + baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1128,7 +1147,7 @@ namespace slskd.Transfers.Downloads { // 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()); + destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); } else { @@ -1141,7 +1160,7 @@ namespace slskd.Transfers.Downloads 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, 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..6bacef8c --- /dev/null +++ b/src/slskd/Transfers/Types/BatchOptions.cs @@ -0,0 +1,48 @@ +// <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; } +}
\ 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 72e3c0ef..9bb09f66 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> @@ -632,7 +622,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, }; @@ -731,51 +720,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; } } |
