aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-10-28 18:07:36 -0500
committerGitHub <noreply@github.com>2022-10-28 18:07:36 -0500
commit889e5ae95c68ccf24c5c3fa0a3ec2dac04d6adbf (patch)
tree9f6a6ba924799c1eaefc37e29f304af049091d83 /src
parent028af934a264a91c831eac3561c5e24833b6ee38 (diff)
parentfc7448e522145b08facec806c59993e724a00b83 (diff)
downloadslskd-889e5ae95c68ccf24c5c3fa0a3ec2dac04d6adbf.tar.gz
Merge pull request #712 from slskd/more-network
More Network improvements
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Cryptography/Pbkdf2.cs15
-rw-r--r--src/slskd/Common/Exceptions/ShareValidationException.cs72
-rw-r--r--src/slskd/Common/Redactor.cs9
-rw-r--r--src/slskd/Common/Validation/UrlAttribute.cs38
-rw-r--r--src/slskd/Core/Options.cs6
-rw-r--r--src/slskd/Network/API/Controllers/NetworkController.cs18
-rw-r--r--src/slskd/Network/API/Hubs/NetworkHub.cs17
-rw-r--r--src/slskd/Network/NetworkClient.cs13
-rw-r--r--src/slskd/Network/NetworkService.cs114
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs6
10 files changed, 265 insertions, 43 deletions
diff --git a/src/slskd/Common/Cryptography/Pbkdf2.cs b/src/slskd/Common/Cryptography/Pbkdf2.cs
index 3c3246d6..15b4a7ed 100644
--- a/src/slskd/Common/Cryptography/Pbkdf2.cs
+++ b/src/slskd/Common/Cryptography/Pbkdf2.cs
@@ -18,6 +18,7 @@
namespace slskd.Cryptography
{
using System.Security.Cryptography;
+ using System.Text;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
/// <summary>
@@ -39,5 +40,19 @@ namespace slskd.Cryptography
rng.GetBytes(salt);
return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32);
}
+
+ /// <summary>
+ /// Gets a variable <paramref name="length"/> key derived from the specified <paramref name="password"/> and <paramref name="salt"/> using PBKDF2/RFC 2898.
+ /// </summary>
+ /// <param name="password">The password from which to derive the key.</param>
+ /// <param name="salt">The value with which to salt the key.</param>
+ /// <param name="length">The desired length of the key, in bytes.</param>
+ /// <returns>The derived key.</returns>
+ public static byte[] GetKey(string password, string salt, int length)
+ {
+ int iterations = 1000;
+
+ return KeyDerivation.Pbkdf2(password, Encoding.UTF8.GetBytes(salt), KeyDerivationPrf.HMACSHA256, iterations, length);
+ }
}
}
diff --git a/src/slskd/Common/Exceptions/ShareValidationException.cs b/src/slskd/Common/Exceptions/ShareValidationException.cs
new file mode 100644
index 00000000..97a3e126
--- /dev/null
+++ b/src/slskd/Common/Exceptions/ShareValidationException.cs
@@ -0,0 +1,72 @@
+// <copyright file="ShareValidationException.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.Serialization;
+
+ /// <summary>
+ /// Represents an error that occurs when multiple share scans are attempted concurrently.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ [Serializable]
+ public class ShareValidationException : SlskdException
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareValidationException"/> class.
+ /// </summary>
+ public ShareValidationException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareValidationException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public ShareValidationException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareValidationException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public ShareValidationException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareValidationException"/> class with serialized data.
+ /// </summary>
+ /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
+ protected ShareValidationException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Redactor.cs b/src/slskd/Common/Redactor.cs
index b2069b12..e819a6a8 100644
--- a/src/slskd/Common/Redactor.cs
+++ b/src/slskd/Common/Redactor.cs
@@ -59,7 +59,14 @@ namespace slskd
}
else
{
- if (value.GetType().IsAssignableTo(typeof(IEnumerable)))
+ if (value.IsDictionary())
+ {
+ foreach (string key in ((IDictionary)value).Keys)
+ {
+ Redact(((IDictionary)value)[key]);
+ }
+ }
+ else if (value.GetType().IsAssignableTo(typeof(IEnumerable)))
{
foreach (var element in (IEnumerable)value)
{
diff --git a/src/slskd/Common/Validation/UrlAttribute.cs b/src/slskd/Common/Validation/UrlAttribute.cs
new file mode 100644
index 00000000..9c980c9b
--- /dev/null
+++ b/src/slskd/Common/Validation/UrlAttribute.cs
@@ -0,0 +1,38 @@
+// <copyright file="UrlAttribute.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Common.Validation
+{
+ using System;
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the value is a valid URL.
+ /// </summary>
+ public class UrlAttribute : ValidationAttribute
+ {
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (!Uri.TryCreate((string)value, default(UriCreationOptions), out _))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must contain a valid URL");
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index b75f9356..af46f23c 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -391,6 +391,7 @@ namespace slskd
/// <summary>
/// Gets the controller configuration.
/// </summary>
+ [Validate]
public NetworkControllerConfigurationOptions Controller { get; init; } = new NetworkControllerConfigurationOptions();
/// <summary>
@@ -429,6 +430,7 @@ namespace slskd
/// </summary>
[Argument(default, "controller-address")]
[EnvironmentVariable("CONTROLLER_ADDRESS")]
+ [Url]
public string Address { get; init; }
/// <summary>
@@ -436,7 +438,7 @@ namespace slskd
/// </summary>
[Argument(default, "controller-secret")]
[EnvironmentVariable("CONTROLLER_SECRET")]
- [StringLength(48, MinimumLength = 48)]
+ [StringLength(255, MinimumLength = 16)]
[Secret]
public string Secret { get; init; }
}
@@ -449,7 +451,7 @@ namespace slskd
/// <summary>
/// Gets the agent secret.
/// </summary>
- [StringLength(48, MinimumLength = 48)]
+ [StringLength(255, MinimumLength = 16)]
[Secret]
public string Secret { get; init; }
}
diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs
index 4cd6437a..624d7a2c 100644
--- a/src/slskd/Network/API/Controllers/NetworkController.cs
+++ b/src/slskd/Network/API/Controllers/NetworkController.cs
@@ -121,7 +121,7 @@ namespace slskd.Network
// pass the stream back to the network service, which will in turn pass it to the
// upload service, and use it to feed data into the remote upload. await this call,
// it will complete when the upload is complete, one way or the other.
- await Network.HandleFileStreamResponse(id: guid, stream);
+ await Network.HandleFileStreamResponse(agentName, id: guid, stream);
Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName);
return Ok();
@@ -174,18 +174,14 @@ namespace slskd.Network
Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp);
- var repository = ShareRepositoryFactory.CreateFromFile(temp);
-
- if (!repository.TryValidate(out var problems))
+ try
{
- return BadRequest("Invalid database: " + string.Join(", ", problems));
+ await Network.HandleShareUpload(agentName, id: guid, shares, temp);
+ }
+ catch (ShareValidationException ex)
+ {
+ return BadRequest(ex.Message);
}
-
- var destinationRepository = ShareRepositoryFactory.CreateFromHost(agentName);
-
- destinationRepository.RestoreFrom(repository);
-
- Shares.AddOrUpdateHost(new Host(agentName, shares));
return Ok();
}
diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs
index 298dd9ec..0ee80f9a 100644
--- a/src/slskd/Network/API/Hubs/NetworkHub.cs
+++ b/src/slskd/Network/API/Hubs/NetworkHub.cs
@@ -79,6 +79,7 @@ namespace slskd.Network
Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId);
Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case!
return false;
+ // todo: throw UnauthorizedAccessException()?
}
public Guid GetShareUploadToken()
@@ -97,12 +98,24 @@ namespace slskd.Network
public void NotifyUploadFailed(Guid id, Exception exception)
{
- Network.NotifyFileStreamException(id, exception);
+ if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record))
+ {
+ Network.NotifyFileStreamException(id, exception);
+ }
+
+ Log.Warning("Agent connection {Id} attempted to report a failed upload, but is not registered.", Context.ConnectionId);
+ throw new UnauthorizedAccessException();
}
public void ReturnFileInfo(Guid id, bool exists, long length)
{
- Network.HandleFileInfoResponse(id, (exists, length));
+ if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record))
+ {
+ Network.HandleFileInfoResponse(record.Agent.Name, id, (exists, length));
+ }
+
+ Log.Warning("Agent connection {Id} attempted to return file information, but is not registered.", Context.ConnectionId);
+ throw new UnauthorizedAccessException();
}
}
} \ No newline at end of file
diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs
index 5d8ab100..1ffd2b1f 100644
--- a/src/slskd/Network/NetworkClient.cs
+++ b/src/slskd/Network/NetworkClient.cs
@@ -155,16 +155,18 @@ namespace slskd.Network
Log.Information("Upload shares succeeded");
}
- private string ComputeCredential(Guid token)
+ private string ComputeCredential(string token)
{
var options = OptionsMonitor.CurrentValue;
- var key = options.Network.Controller.Secret.FromBase62();
- var tokenBytes = token.ToString().FromBase62();
+ var key = Pbkdf2.GetKey(options.Network.Controller.Secret, options.InstanceName, 48);
+ var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token);
return Aes.Encrypt(tokenBytes, key).ToBase62();
}
+ private string ComputeCredential(Guid token) => ComputeCredential(token.ToString());
+
private Task HandleFileRequest(string filename, Guid token)
{
_ = Task.Run(async () =>
@@ -245,10 +247,7 @@ namespace slskd.Network
var options = OptionsMonitor.CurrentValue;
var agent = options.InstanceName;
- var key = options.Network.Controller.Secret.FromBase62();
- var tokenBytes = challengeToken.FromBase62();
-
- var response = Aes.Encrypt(tokenBytes, key).ToBase62();
+ var response = ComputeCredential(challengeToken);
Log.Debug("Logging in...");
var success = await HubConnection.InvokeAsync<bool>(nameof(NetworkHub.Login), agent, response);
diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs
index 100d9448..6515d94d 100644
--- a/src/slskd/Network/NetworkService.cs
+++ b/src/slskd/Network/NetworkService.cs
@@ -21,6 +21,7 @@ namespace slskd.Network
{
using System;
using System.Collections.Concurrent;
+ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
@@ -30,6 +31,7 @@ namespace slskd.Network
using Microsoft.Extensions.Caching.Memory;
using Serilog;
using slskd.Cryptography;
+ using slskd.Shares;
/// <summary>
/// Handles network (controller/agent) interactions.
@@ -58,6 +60,19 @@ namespace slskd.Network
/// Retrieves a new share upload token for the specified <paramref name="agentName"/>.
/// </summary>
/// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks>
+ /// <remarks>
+ /// <para>This is the first step in a multi-step workflow. The entire sequence is:</para>
+ /// <list type="number">
+ /// <item>
+ /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn
+ /// calls <see cref="GenerateShareUploadToken"/>. The token is generated and cached.
+ /// </item>
+ /// <item>
+ /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its
+ /// shared database and a serialized list of locally configured shares, and the controller invokes <see cref="HandleShareUpload"/>.
+ /// </item>
+ /// </list>
+ /// </remarks>
/// <param name="agentName">The name of the agent.</param>
/// <returns>The generated token.</returns>
Guid GenerateShareUploadToken(string agentName);
@@ -132,18 +147,30 @@ namespace slskd.Network
/// <summary>
/// Handles the client response for a <see cref="GetFileInfoAsync"/> request.
/// </summary>
+ /// <param name="agentName">The name of the agent.</param>
/// <param name="id">The ID of the request.</param>
/// <param name="response">The client response to the request.</param>
- void HandleFileInfoResponse(Guid id, (bool Exists, long Length) response);
+ void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response);
/// <summary>
/// Handles the client response for a <see cref="GetFileStreamAsync"/> request, returning when the corresponding file
/// upload is complete.
/// </summary>
+ /// <param name="agentName">The name of the agent.</param>
/// <param name="id">The ID of the request.</param>
/// <param name="response">The client response to the request.</param>
/// <returns>The operation context.</returns>
- Task HandleFileStreamResponse(Guid id, Stream response);
+ Task HandleFileStreamResponse(string agentName, Guid id, Stream response);
+
+ /// <summary>
+ /// Handles incoming share uploads.
+ /// </summary>
+ /// <param name="agentName">The name of the agent.</param>
+ /// <param name="id">The ID obtained by the caller prior to uploading.</param>
+ /// <param name="shares">The list of shares provided.</param>
+ /// <param name="filename">The filename of the temporary file containing the upload.</param>
+ /// <returns>The operation context.</returns>
+ Task HandleShareUpload(string agentName, Guid id, IEnumerable<Share> shares, string filename);
/// <summary>
/// Notifies the caller of <see cref="GetFileStreamAsync"/> of a failure to obtain a file stream from the requested agent.
@@ -162,9 +189,10 @@ namespace slskd.Network
/// <summary>
/// Safely attempts to close a stream obtained with <see cref="GetFileStreamAsync"/>.
/// </summary>
+ /// <param name="agentName">The name of the agent.</param>
/// <param name="id">The unique ID for the stream.</param>
/// <param name="exception">If the transfer associated with the stream failed, the exception that caused the failure.</param>
- void TryCloseFileStream(Guid id, Exception exception = null);
+ void TryCloseFileStream(string agentName, Guid id, Exception exception = null);
/// <summary>
/// Attempts to remove the registration for the specified <paramref name="connectionId"/>.
@@ -218,9 +246,13 @@ namespace slskd.Network
{
public NetworkService(
IWaiter waiter,
+ IShareService shareService,
+ IShareRepositoryFactory shareRepositoryFactory,
IOptionsMonitor<Options> optionsMonitor,
IHubContext<NetworkHub, INetworkHub> networkHub)
{
+ Shares = shareService;
+ ShareRepositoryFactory = shareRepositoryFactory;
Waiter = waiter;
NetworkHub = networkHub;
@@ -243,6 +275,8 @@ namespace slskd.Network
private IOptionsMonitor<Options> OptionsMonitor { get; }
private ConcurrentDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiryDictionary { get; } = new();
private ConcurrentDictionary<string, (string ConnectionId, Agent Agent)> RegisteredAgentDictionary { get; } = new();
+ private IShareRepositoryFactory ShareRepositoryFactory { get; }
+ private IShareService Shares { get; }
private IWaiter Waiter { get; }
private ConcurrentDictionary<WaitKey, Guid> WaitIdDictionary { get; } = new();
@@ -266,6 +300,23 @@ namespace slskd.Network
/// Retrieves a new share upload token for the specified <paramref name="agentName"/>.
/// </summary>
/// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks>
+ /// <remarks>
+ /// <para>This is the first step in a multi-step workflow. The entire sequence is:</para>
+ /// <list type="number">
+ /// <item>
+ /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn
+ /// calls <see cref="GenerateShareUploadToken"/>. The token is generated and cached.
+ /// </item>
+ /// <item>
+ /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its
+ /// shared database and a serialized list of locally configured shares.
+ /// </item>
+ /// <item>
+ /// The HTTP controller saves the database backup to a temporary file, validates it, and then adds (or updates)
+ /// a share host for the agent.
+ /// </item>
+ /// </list>
+ /// </remarks>
/// <param name="agentName">The name of the agent.</param>
/// <returns>The generated token.</returns>
public Guid GenerateShareUploadToken(string agentName)
@@ -309,7 +360,7 @@ namespace slskd.Network
// prepare a wait for the response. we don't cache the token along with the agent here, as all data is exchanged over
// an authenticated SignalR connection
var id = Guid.NewGuid();
- var key = new WaitKey(nameof(GetFileInfoAsync), id);
+ var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id);
var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout);
try
@@ -383,7 +434,7 @@ namespace slskd.Network
// create a wait for the agent response. this wait will be completed in the response handler, ultimately called from
// the API controller when the agent makes an HTTP request to return the file
- var key = new WaitKey(nameof(GetFileStreamAsync), id);
+ var key = new WaitKey(nameof(GetFileStreamAsync), agentName, id);
var wait = Waiter.Wait<Stream>(key, timeout, cancellationToken);
await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id);
@@ -407,15 +458,16 @@ namespace slskd.Network
/// <summary>
/// Handles the client response for a <see cref="GetFileInfoAsync"/> request.
/// </summary>
+ /// <param name="agentName">The name of the agent.</param>
/// <param name="id">The ID of the request.</param>
/// <param name="response">The client response to the request.</param>
- public void HandleFileInfoResponse(Guid id, (bool Exists, long Length) response)
+ public void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response)
{
- var key = new WaitKey(nameof(GetFileInfoAsync), id);
+ var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id);
if (!Waiter.IsWaitingFor(key))
{
- var msg = $"A file info response matching Id {id} was not expected";
+ var msg = $"A file info response from Agent {agentName} matching Id {id} was not expected";
Log.Warning(msg);
throw new NotFoundException(msg);
}
@@ -430,12 +482,13 @@ namespace slskd.Network
/// <remarks>
/// Assumes <see cref="TryValidateFileStreamResponseCredential"/> has previously been used to ensure the Id and agent match.
/// </remarks>
+ /// <param name="agentName">The name of the agent.</param>
/// <param name="id">The ID of the request.</param>
/// <param name="response">The client response to the request.</param>
/// <returns>The operation context.</returns>
- public async Task HandleFileStreamResponse(Guid id, Stream response)
+ public async Task HandleFileStreamResponse(string agentName, Guid id, Stream response)
{
- var streamKey = new WaitKey(nameof(GetFileStreamAsync), id);
+ var streamKey = new WaitKey(nameof(GetFileStreamAsync), agentName, id);
if (!Waiter.IsWaitingFor(streamKey))
{
@@ -447,7 +500,7 @@ namespace slskd.Network
// create a wait (but do not await it) for the completion of the upload to the remote client. we need to await this to
// keep execution in the body of the API controller that provided the stream, in order to keep the stream open for the
// duration of the remote transfer. omit the id from the key, the caller doesn't know it.
- var completionKey = new WaitKey(nameof(HandleFileStreamResponse), id);
+ var completionKey = new WaitKey(nameof(HandleFileStreamResponse), agentName, id);
var completion = Waiter.WaitIndefinitely(completionKey);
// complete the wait that's waiting for the stream, so we can send the stream back to the caller of GetFileStream this
@@ -460,6 +513,32 @@ namespace slskd.Network
}
/// <summary>
+ /// Handles incoming share uploads.
+ /// </summary>
+ /// <param name="agentName">The name of the agent.</param>
+ /// <param name="id">The ID obtained by the caller prior to uploading.</param>
+ /// <param name="shares">The list of shares provided.</param>
+ /// <param name="filename">The filename of the temporary file containing the upload.</param>
+ /// <returns>The operation context.</returns>
+ public Task HandleShareUpload(string agentName, Guid id, IEnumerable<Share> shares, string filename)
+ {
+ var repository = ShareRepositoryFactory.CreateFromFile(filename);
+
+ if (!repository.TryValidate(out var problems))
+ {
+ throw new ShareValidationException("Invalid database: " + string.Join(", ", problems));
+ }
+
+ var destinationRepository = ShareRepositoryFactory.CreateFromHost(agentName);
+
+ destinationRepository.RestoreFrom(repository);
+
+ Shares.AddOrUpdateHost(new Host(agentName, shares));
+
+ return Task.CompletedTask;
+ }
+
+ /// <summary>
/// Notifies the caller of <see cref="GetFileStreamAsync"/> of a failure to obtain a file stream from the requested agent.
/// </summary>
/// <param name="id">The unique ID for the stream.</param>
@@ -481,11 +560,12 @@ namespace slskd.Network
/// <summary>
/// Safely attempts to close a stream obtained with <see cref="GetFileStreamAsync"/>.
/// </summary>
+ /// <param name="agentName">The name of the agent.</param>
/// <param name="id">The unique ID for the stream.</param>
/// <param name="exception">If the transfer associated with the stream failed, the exception that caused the failure.</param>
- public void TryCloseFileStream(Guid id, Exception exception = default)
+ public void TryCloseFileStream(string agentName, Guid id, Exception exception = default)
{
- var key = new WaitKey(nameof(HandleFileStreamResponse), id);
+ var key = new WaitKey(nameof(HandleFileStreamResponse), agentName, id);
if (exception != default)
{
@@ -548,8 +628,8 @@ namespace slskd.Network
return false;
}
- var key = agentOptions.Secret.FromBase62();
- var tokenBytes = ((string)challengeToken).FromBase62();
+ var key = Pbkdf2.GetKey(password: agentOptions.Secret, salt: agentName, length: 48);
+ var tokenBytes = System.Text.Encoding.UTF8.GetBytes((string)challengeToken);
var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62();
return expectedResponse == credential;
@@ -614,8 +694,8 @@ namespace slskd.Network
return false;
}
- var key = agentOptions.Secret.FromBase62();
- var tokenBytes = token.ToString().FromBase62();
+ var key = Pbkdf2.GetKey(password: agentOptions.Secret, salt: agentName, length: 48);
+ var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token);
var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62();
if (expectedCredential != credential)
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 3dd80292..8cc6ee45 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -273,7 +273,7 @@ namespace slskd.Transfers.Uploads
options: topts,
cancellationToken: cts.Token);
- Network.TryCloseFileStream(id);
+ Network.TryCloseFileStream(host, id);
transfer = transfer.WithSoulseekTransfer(completedTransfer);
}
@@ -294,7 +294,7 @@ namespace slskd.Transfers.Uploads
// todo: broadcast
SynchronizedUpdate(transfer, cancellable: false);
- Network.TryCloseFileStream(id, ex);
+ Network.TryCloseFileStream(host, id, ex);
throw;
}
@@ -309,7 +309,7 @@ namespace slskd.Transfers.Uploads
// todo: broadcast
SynchronizedUpdate(transfer, cancellable: false);
- Network.TryCloseFileStream(id, ex);
+ Network.TryCloseFileStream(host, id, ex);
throw;
}
finally