diff options
Diffstat (limited to 'src/slskd/Transfers/Downloads')
| -rw-r--r-- | src/slskd/Transfers/Downloads/BatchService.cs | 140 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 51 |
2 files changed, 175 insertions, 16 deletions
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, |
