diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-06-07 18:46:25 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2026-06-07 18:46:25 -0500 |
| commit | 294fcabd3928b420a4dfbd7ddd0dc38ada523165 (patch) | |
| tree | bcc92e42c71f2a9b67f7750c5ecd0a396b5897e5 /src/slskd/Core | |
| parent | 60bc0c0c2ea6d9c80a7f091f022567b1d5e3240a (diff) | |
| parent | 8e152ed6eccd5650179f2875eef4aa21243c8c15 (diff) | |
| download | slskd-294fcabd3928b420a4dfbd7ddd0dc38ada523165.tar.gz | |
Merge remote-tracking branch 'origin/master' into reports
Diffstat (limited to 'src/slskd/Core')
5 files changed, 303 insertions, 64 deletions
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; } |
