aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-02-15 16:34:11 -0600
committerGitHub <noreply@github.com>2026-02-15 16:34:11 -0600
commit86d1ebbed867b43655173065441c17720a1e7c58 (patch)
treef2601081f79f40f9c0b1d693980f7a763f9c1ac9 /src
parentc11f9e2fb8aa43ee7921f292079aea9a852768e5 (diff)
parentb469512850279381837bf91cc98a5641de60fe8a (diff)
downloadslskd-86d1ebbed867b43655173065441c17720a1e7c58.tar.gz
Merge pull request #1641 from slskd/enqueue-nulls
Enqueue endpoint hardening
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs24
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs3
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs54
3 files changed, 61 insertions, 20 deletions
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 443a1b44..a95a0bb9 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -35,7 +35,6 @@ namespace slskd.Transfers.API
/// </summary>
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("0")]
- [ApiController]
[Produces("application/json")]
[Consumes("application/json")]
public class TransfersController : ControllerBase
@@ -210,17 +209,28 @@ namespace slskd.Transfers.API
[ProducesResponseType(201)]
[ProducesResponseType(typeof(string), 403)]
[ProducesResponseType(typeof(string), 500)]
-#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
-#pragma warning disable SA1611 // Element parameters should be documented
- public async Task<IActionResult> EnqueueAsync([FromRoute, UrlEncoded, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests, CancellationToken cancellationToken = default)
-#pragma warning restore SA1611 // Element parameters should be documented
-#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
+ public async Task<IActionResult> EnqueueAsync([FromRoute, UrlEncoded, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
+ if (!ModelState.IsValid)
+ {
+ return BadRequest(ModelState.GetReadableString());
+ }
+
+ if (!requests?.Any() ?? true)
+ {
+ return BadRequest("At least one file is required");
+ }
+
+ if (requests.Any(r => r is null))
+ {
+ return BadRequest("One or more records in the request are null");
+ }
+
if (!DownloadRequestLimiter.Wait(0))
{
return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes");
@@ -228,7 +238,7 @@ namespace slskd.Transfers.API
try
{
- var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken);
+ var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)));
return StatusCode(201, new { Enqueued = enqueued, Failed = failed });
}
diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs
index 62e6316c..26113ba8 100644
--- a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using System.ComponentModel.DataAnnotations;
+
namespace slskd.Transfers.API
{
public class QueueDownloadRequest
@@ -22,6 +24,7 @@ namespace slskd.Transfers.API
/// <summary>
/// Gets or sets the filename to download.
/// </summary>
+ [Required]
public string Filename { get; set; }
/// <summary>
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index beeab755..e6a65dcd 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -246,13 +246,18 @@ namespace slskd.Transfers.Downloads
throw new ArgumentException("Username is required", nameof(username));
}
- var fileList = files.ToList();
+ var fileList = files?.ToList() ?? [];
if (fileList.Count == 0)
{
throw new ArgumentException("At least one file is required", nameof(files));
}
+ if (fileList.Any(f => string.IsNullOrEmpty(f.Filename)))
+ {
+ throw new ArgumentException("At least one filename is null or empty", nameof(files));
+ }
+
if (fileList.Count != fileList.Distinct().Count())
{
throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
@@ -328,7 +333,7 @@ namespace slskd.Transfers.Downloads
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => t.Username == username)
.Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State))
- .AsNoTracking()
+ .AsNoTracking() // note: AI wants to remove this, dont.
.ToList();
var existingInProgressRecords = existingRecordsNotYetRemoved
@@ -378,13 +383,10 @@ namespace slskd.Transfers.Downloads
/*
if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already
an existing transfer record covering this file, and we're already enqueued. nothing more to do!
-
- check the tracked download dictionary in Soulseek.NET to see if it knows about this already
- it shouldn't, if the slskd database doesn't. but things could get desynced
*/
existingInProgressRecords.TryGetValue(file.Filename, out var existingInProgressRecord);
- if (existingInProgressRecord is not null || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename))
+ 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);
@@ -392,6 +394,18 @@ namespace slskd.Transfers.Downloads
}
/*
+ check the tracked download dictionary in Soulseek.NET to see if it knows about this already
+ it shouldn't, if the slskd database doesn't. but things could get desynced, which is likely a bug
+ and we'd like to know about it
+ */
+ 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);
+ continue;
+ }
+
+ /*
add the transfer record to the database in the Queued | Locally state, and set the 'Removed'
property of any existing transfer to 'true', allowing the new record to supersede any old record(s)
on the UI
@@ -448,6 +462,14 @@ namespace slskd.Transfers.Downloads
Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username);
+ /*
+ rip off one task for each file in the batch, leaving each to internally wait their turn
+ to proceed with the actual enqueue request and subsequent download, orchestrated by the
+ concurrent enqueue request semaphore
+
+ we don't wait for any of them; as long as the Task is successfully scheduled (Task.Run doesn't throw),
+ we consider it a success.
+ */
var downloadEnqueueTask = Task.Run(async () =>
{
Log.Debug("Awaiting download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
@@ -504,11 +526,14 @@ namespace slskd.Transfers.Downloads
return;
}
- Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message);
+ Exception ex = task.IsCanceled ? new OperationCanceledException("Task was cancelled") : task.Exception;
+ ex = ex?.InnerException ?? ex ?? new Exception("Unknown error");
- if (!TryFail(transferId, exception: task.Exception))
+ Log.Error(ex, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message);
+
+ if (!TryFail(transferId, exception: ex))
{
- Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message);
+ Log.Error(ex, "Failed to clean up transfer {Id} after failed download", transferId);
}
}, cancellationToken: CancellationToken.None); // end downloadTask.Run();
@@ -548,16 +573,19 @@ namespace slskd.Transfers.Downloads
return;
}
- Log.Error(task.Exception, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message);
+ Exception ex = task.IsCanceled ? new OperationCanceledException("Task was cancelled") : task.Exception;
+ ex = ex?.InnerException ?? ex ?? new Exception("Unknown error");
+
+ Log.Error(ex, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message);
- if (!TryFail(transferId, exception: task.Exception))
+ if (!TryFail(transferId, exception: ex))
{
- Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message);
+ Log.Error(ex, "Failed to clean up transfer {Id} after failed enqueue", transferId);
}
}, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run();
Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status);
- Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id);
+ Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transferId);
enqueued.Add(transfer);
}
catch (Exception ex)