From 96fda39aeb290524c00a24846c448bdfd2527663 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:21:34 -0500 Subject: prevent downloads from transitioning into terminal state while retries are available (but not if the Soulseek.NET transfer is not dead) --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d4d8004a..0ccf52c3 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -973,9 +973,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 -- cgit v1.2.3 From 3abaadcd87383c22bc380d6c2fd9b05e38e7d353 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:43:50 -0500 Subject: remove StartOffset from Transfers table (unused) --- ...Z2026_04_30_DropTransferStartOffsetMigration.cs | 101 +++++++++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 1 - src/slskd/Transfers/Types/Transfer.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 4 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs (limited to 'src/slskd/Transfers/Downloads') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to drop the unused StartOffset column. +/// +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(); + 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/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0ccf52c3..aba6ca9d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -435,7 +435,6 @@ namespace slskd.Transfers.Downloads 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, }; diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 93a23380..90fbe612 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -30,7 +30,7 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // -namespace slskd.Transfers +namespace slskd.Transfers; { using System; using System.ComponentModel.DataAnnotations; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 13915e82..9bb09f66 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -622,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, }; -- cgit v1.2.3 From 08380a1a150f58839798ca3289aa8b5542f41086 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:37:00 -0500 Subject: shuffle some things around --- src/slskd/Program.cs | 1 + src/slskd/Transfers/Batches/BatchService.cs | 179 ----------------------- src/slskd/Transfers/Downloads/BatchService.cs | 122 +++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++ 4 files changed, 135 insertions(+), 179 deletions(-) delete mode 100644 src/slskd/Transfers/Batches/BatchService.cs create mode 100644 src/slskd/Transfers/Downloads/BatchService.cs (limited to 'src/slskd/Transfers/Downloads') 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(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs deleted file mode 100644 index aadaa820..00000000 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ /dev/null @@ -1,179 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Linq.Expressions; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Serilog; - - /// - /// Manages transfer batches. - /// - public interface IBatchService - { - /// - /// Creates a new batch record. - /// - /// The batch to create. - /// The created batch. - Batch Create(Batch batch); - - /// - /// Finds a single batch matching the specified . - /// - /// The expression to use to match batches. - /// The found batch, or default if not found. - /// Thrown when an expression is not supplied. - Task FindAsync(Expression> expression); - - /// - /// Returns a list of all batches matching the optional . - /// - /// An optional expression used to match batches. - /// The list of batches matching the specified expression, or all batches if no expression is specified. - Task> ListAsync(Expression> expression = null); - - /// - /// Marks all transfers associated with the specified batch as removed. - /// - /// The unique identifier of the batch. - /// Thrown when the batch does not exist. - void Remove(Guid id); - } - - /// - /// Manages transfer batches. - /// - public class BatchService : IBatchService - { - /// - /// Initializes a new instance of the class. - /// - /// The database context factory to use. - public BatchService(IDbContextFactory contextFactory) - { - ContextFactory = contextFactory; - } - - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Creates a new batch record. - /// - /// The batch to create. - /// The created batch. - public Batch Create(Batch batch) - { - if (batch == default) - { - throw new ArgumentNullException(nameof(batch)); - } - - using var context = ContextFactory.CreateDbContext(); - context.Batches.Add(batch); - context.SaveChanges(); - - Log.Debug("Created batch {Id}", batch.Id); - - return batch; - } - - /// - /// Finds a single batch matching the specified . - /// - /// The expression to use to match batches. - /// The found batch, or default if not found. - /// Thrown when an expression is not supplied. - public async Task FindAsync(Expression> 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(); - } - - /// - /// Returns a list of all batches matching the optional . - /// - /// An optional expression used to match batches. - /// The list of batches matching the specified expression, or all batches if no expression is specified. - public async Task> ListAsync(Expression> expression = null) - { - expression ??= b => true; - - using var context = ContextFactory.CreateDbContext(); - - return await context.Batches - .AsNoTracking() - .Include(b => b.Transfers) - .Where(expression) - .ToListAsync(); - } - - /// - /// Marks all transfers associated with the specified batch as removed. - /// - /// The unique identifier of the batch. - /// Thrown when the batch does not exist. - public void Remove(Guid id) - { - using var context = ContextFactory.CreateDbContext(); - - var exists = context.Batches.Any(b => b.Id == id); - - if (!exists) - { - throw new NotFoundException($"No batch with id {id}"); - } - - context.Transfers - .Where(t => t.BatchId == id) - .ExecuteUpdate(s => s.SetProperty(t => t.Removed, true)); - - Log.Debug("Marked transfers for batch {Id} as removed", id); - } - } -} diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs new file mode 100644 index 00000000..7a4ba055 --- /dev/null +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -0,0 +1,122 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers.Downloads; + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Serilog; + +/// +/// Manages transfer batches. +/// +public interface IBatchService +{ + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + Batch Create(Batch batch); + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + Task FindAsync(Expression> expression); +} + +/// +/// Manages transfer batches. +/// +public class BatchService : IBatchService +{ + /// + /// Initializes a new instance of the class. + /// + /// The database context factory to use. + public BatchService(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + public Batch Create(Batch batch) + { + if (batch == default) + { + throw new ArgumentNullException(nameof(batch)); + } + + using var context = ContextFactory.CreateDbContext(); + context.Batches.Add(batch); + context.SaveChanges(); + + Log.Debug("Created batch {Id}", batch.Id); + + return batch; + } + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + public async Task FindAsync(Expression> 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 aba6ca9d..9e898570 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -55,6 +55,11 @@ namespace slskd.Transfers.Downloads /// public interface IDownloadService { + /// + /// Gets download batch service. + /// + IBatchService Batches { get; } + /// /// Adds the specified . Supersedes any existing record for the same file and username. /// @@ -158,6 +163,7 @@ namespace slskd.Transfers.Downloads public class DownloadService : IDownloadService { public DownloadService( + IBatchService batchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory contextFactory, @@ -166,6 +172,7 @@ namespace slskd.Transfers.Downloads IFTPService ftpClient, EventBus eventBus) { + Batches = batchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -177,6 +184,11 @@ namespace slskd.Transfers.Downloads Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); } + /// + /// Gets download batch service. + /// + public IBatchService Batches { get; } + /// /// These tokens give users the ability to cancel transfers via the UI (or API). /// -- cgit v1.2.3 From 6585216de3a191b3260c1960f4a0f29daab6b04a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:48:14 -0500 Subject: populate batchid if supplied --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9e898570..184acb5d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -76,12 +76,13 @@ namespace slskd.Transfers.Downloads /// /// The username of remote user. /// The list of files to enqueue. + /// The optional batch id for the transfers. /// The token to monitor for cancellation. /// The operation context. /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); + Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -261,12 +262,13 @@ namespace slskd.Transfers.Downloads /// /// The username of the remote user. /// The list of files to enqueue. + /// The optional batch id for the transfers. /// The token to monitor for cancellation. /// The operation context. /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) + public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -443,6 +445,7 @@ 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 -- cgit v1.2.3 From 7e61670105fdb1efd164b2d89194a1699a9943db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:13:53 -0500 Subject: make create async --- src/slskd/Transfers/Downloads/BatchService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs index 7a4ba055..29de8e14 100644 --- a/src/slskd/Transfers/Downloads/BatchService.cs +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -49,7 +49,7 @@ public interface IBatchService /// /// The batch to create. /// The created batch. - Batch Create(Batch batch); + Task CreateAsync(Batch batch); /// /// Finds a single batch matching the specified . @@ -82,7 +82,7 @@ public class BatchService : IBatchService /// /// The batch to create. /// The created batch. - public Batch Create(Batch batch) + public async Task CreateAsync(Batch batch) { if (batch == default) { @@ -91,7 +91,7 @@ public class BatchService : IBatchService using var context = ContextFactory.CreateDbContext(); context.Batches.Add(batch); - context.SaveChanges(); + await context.SaveChangesAsync(); Log.Debug("Created batch {Id}", batch.Id); -- cgit v1.2.3 From a61917f50b3874640b1bcd3c536a5ca4f38f10e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:16:19 -0500 Subject: handle conflicts/PK violations, validate more properties --- .../API/Controllers/TransfersController.cs | 9 +++++-- src/slskd/Transfers/Downloads/BatchService.cs | 28 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 7 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 44f7a146..b1275c52 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -282,7 +282,7 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads")] + [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(201)] @@ -362,9 +362,14 @@ namespace slskd.Transfers.API return StatusCode(201, batch); } + 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(); + } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count(), request.Username, ex.Message); + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count, request.Username, ex.Message); return StatusCode(500, ex.Message); } finally diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs index 29de8e14..7ea9a70a 100644 --- a/src/slskd/Transfers/Downloads/BatchService.cs +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -36,6 +36,7 @@ using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Serilog; @@ -89,13 +90,30 @@ public class BatchService : IBatchService throw new ArgumentNullException(nameof(batch)); } - using var context = ContextFactory.CreateDbContext(); - context.Batches.Add(batch); - await context.SaveChangesAsync(); + 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); - Log.Debug("Created batch {Id}", batch.Id); + await context.SaveChangesAsync(); - return batch; + 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; + } } /// -- cgit v1.2.3 From 3fb834ecb2afb7c112e191d03b20f7ae39f7a62e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:20 -0500 Subject: use CombineSafely --- src/slskd/Common/CommonExtensions.cs | 4 ++-- src/slskd/Transfers/Downloads/DownloadService.cs | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 33e59382..5ff3e519 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -393,7 +393,7 @@ namespace slskd [Obsolete("Find something more intelligent to do instead of this")] public static string ToLocalFilename(this string remoteFilename, string baseDirectory) { - return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename()); + return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename()); } /// @@ -467,7 +467,7 @@ namespace slskd var file = parts.Last().ReplaceInvalidFileNameCharacters(); var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); - return Path.Combine(directory, file); + return FileSafety.CombineSafely(directory, file); } /// diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 184acb5d..7d9d9521 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1046,10 +1046,11 @@ namespace slskd.Transfers.Downloads // 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) + // if there is no batch id, sanitize the username and use that var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: System.IO.Path.Combine( + baseDirectory: FileSafety.CombineSafely( OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); + transfer.BatchId.HasValue ? transfer.BatchId.ToString() : transfer.Username.ReplaceInvalidFileNameCharacters())); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1144,7 +1145,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 { -- cgit v1.2.3 From 7cd70a730b6cd57952f2e233378cd6bb244f56b1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:35 -0500 Subject: block downloads of files with traversal segments --- .../Transfers/API/Controllers/TransfersController.cs | 17 ++++++++++++++++- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 50ff7199..1d748f35 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -250,7 +250,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)) @@ -313,6 +318,16 @@ namespace slskd.Transfers.API return BadRequest("One or more files in the request are invalid"); } + if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + { + return BadRequest("One or more files in the request contain a dangerous path traversal segment"); + } + + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + { + return BadRequest("One or more files in the request are duplicates"); + } + Guid? batchId; Guid? searchId; diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 7d9d9521..14048fac 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -287,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)); -- cgit v1.2.3 From d8bebbbe1ead96b99246c88816f846747eed5bb7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:42 -0500 Subject: return a message when failing a file --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 14048fac..89b8a6a7 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -82,7 +82,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); + Task<(List Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -268,7 +268,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) + public async Task<(List 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)) { @@ -325,7 +325,7 @@ namespace slskd.Transfers.Downloads } List enqueued = []; - List failed = []; + List<(string Filename, string Message)> failed = []; SemaphoreSlim userSemaphore; Task userSemaphoreWaitTask; @@ -423,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; } @@ -435,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; } @@ -626,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)) { -- cgit v1.2.3 From 33c37b535d4ce68313b77d3a466933c8b047e825 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 May 2026 18:44:38 -0500 Subject: fix bug handling incomplete filenames --- src/slskd/Transfers/Downloads/DownloadService.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'src/slskd/Transfers/Downloads') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 89b8a6a7..83e91ced 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1049,13 +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) - // if there is no batch id, sanitize the username and use that + // 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: FileSafety.CombineSafely( - OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : transfer.Username.ReplaceInvalidFileNameCharacters())); + 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; @@ -1163,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, -- cgit v1.2.3