From 595a91654b9b8c7ea9fa564b52769b39cc95d69e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 19 Oct 2022 23:34:14 -0500 Subject: wip --- src/slskd/Network/API/Hubs/NetworkHub.cs | 41 ++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 18 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index f79fecf2..cf1dc463 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -28,32 +28,37 @@ namespace slskd.Network public static readonly string RequestFile = "REQUEST_FILE"; public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; - public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; - public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; } - /// - /// Extension methods for the network SignalR hub. - /// - public static class NetworkHubExtensions - { - public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) - { - // todo: how to send this to the specified agent? - return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); - } + ///// + ///// Extension methods for the network SignalR hub. + ///// + //public static class NetworkHubExtensions + //{ + // public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) + // { + // // todo: how to send this to the specified agent? + // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); + // } - public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) - { - return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); - } + // public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) + // { + // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + // } + //} + + public interface INetworkHub + { + Task RequestFile(string filename, Guid id); + Task RequestFileInfo(string filename, Guid id); + Task AuthenticationChallenge(string token); } /// /// The network SignalR hub. /// [Authorize] - public class NetworkHub : Hub + public class NetworkHub : Hub { public NetworkHub( INetworkService networkService) @@ -67,7 +72,7 @@ namespace slskd.Network public override async Task OnConnectedAsync() { Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); - await Clients.Caller.SendAsync(NetworkHubMethods.AuthenticationChallenge, Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + await Clients.Caller.AuthenticationChallenge(Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); } public override Task OnDisconnectedAsync(Exception exception) -- cgit v1.2.3 From 481d2029d7cadcf5b1985fa912a263d88f2f2cf3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 20 Oct 2022 19:28:33 -0500 Subject: use strongly typed hub --- src/slskd/Network/API/Hubs/NetworkHub.cs | 58 ++++++++++++-------------------- 1 file changed, 21 insertions(+), 37 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index cf1dc463..0013423a 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -20,38 +20,15 @@ namespace slskd.Network using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; using Serilog; - public static class NetworkHubMethods - { - public static readonly string RequestFile = "REQUEST_FILE"; - public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; - public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; - } - - ///// - ///// Extension methods for the network SignalR hub. - ///// - //public static class NetworkHubExtensions - //{ - // public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) - // { - // // todo: how to send this to the specified agent? - // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); - // } - - // public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) - // { - // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); - // } - //} - public interface INetworkHub { - Task RequestFile(string filename, Guid id); - Task RequestFileInfo(string filename, Guid id); - Task AuthenticationChallenge(string token); + Task Challenge(string token); + Task RequestFileAsync(string filename, Guid id); + Task RequestFileInfoAsync(string filename, Guid id); } /// @@ -71,15 +48,17 @@ namespace slskd.Network public override async Task OnConnectedAsync() { - Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); - await Clients.Caller.AuthenticationChallenge(Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + var token = Network.GenerateAuthenticationChallengeToken(Context.ConnectionId); + + Log.Information("Agent connection {Id} established. Sending authentication challenge {Token}...", Context.ConnectionId, token); + await Clients.Caller.Challenge(token); } public override Task OnDisconnectedAsync(Exception exception) { - if (Network.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) + if (Network.TryDeregisterAgent(Context.ConnectionId, out var record)) { - Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); + Log.Warning("Agent {Agent} (connection {Id}) disconnected", record.Agent.Name, Context.ConnectionId); } return Task.CompletedTask; @@ -89,25 +68,30 @@ namespace slskd.Network { if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) { - Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); - Network.RegisterAgent(Context.ConnectionId, agent); + var remoteIp = Context.Features.Get().RemoteIpAddress.ToString(); + var record = new Agent { Name = agent, ConnectedAt = DateTime.UtcNow, IPAddress = remoteIp }; + + Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); + Network.RegisterAgent(Context.ConnectionId, record); return true; } Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); - Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! + Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! return false; } public Guid GetShareUploadToken() { - if (Network.TryGetAgentRegistration(Context.ConnectionId, out var agent)) + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - return Network.GetShareUploadToken(agent); + var token = Network.GenerateShareUploadToken(record.Agent.Name); + Log.Information("Agent {Agent} (connection {Id}) requested share upload token {Token}", record.Agent.Name, record.ConnectionId, token); + return token; } // this can happen if the agent attempts to upload before logging in - Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); + Log.Information("Agent connection {Id} requested a share upload token, but is not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } -- cgit v1.2.3 From 86def502590f9b842ada1636ae428579d094f61d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:38:50 -0500 Subject: add Waiter to DI --- src/slskd/Network/API/Hubs/NetworkHub.cs | 11 +++++++---- src/slskd/Network/NetworkService.cs | 3 +-- src/slskd/Program.cs | 3 ++- 3 files changed, 10 insertions(+), 7 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 0013423a..28a6b0f7 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -27,8 +27,8 @@ namespace slskd.Network public interface INetworkHub { Task Challenge(string token); - Task RequestFileAsync(string filename, Guid id); - Task RequestFileInfoAsync(string filename, Guid id); + Task RequestFile(string filename, Guid id); + Task RequestFileInfo(string filename, Guid id); } /// @@ -105,10 +105,13 @@ namespace slskd.Network public void ReturnFileInfo(Guid id, bool exists, long length) { - if (Network.PendingFileInquiries.TryGetValue(id, out var record)) + if (!Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - record.TrySetResult((exists, length)); + Log.Warning("Agent connection {Id} responded to a file info request with Id {Id}, but is not registered.", Context.ConnectionId, id); + return; } + + Network.HandleGetFileInfoResponse(record.Agent.Name, id, (exists, length)); } } } \ No newline at end of file diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 33daf0cb..7719421f 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -24,7 +24,6 @@ namespace slskd.Network using System.Collections.ObjectModel; using System.IO; using System.Linq; - using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Memory; diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e7ec4f74..197032db 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -70,7 +70,6 @@ namespace slskd using Soulseek; using Utility.CommandLine; using Utility.EnvironmentVariables; - using static slskd.Authentication.ApiKeyAuthenticationHandler; using IOFile = System.IO.File; /// @@ -518,6 +517,8 @@ namespace slskd services.AddSingleton(); services.AddHostedService(p => p.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(); services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); -- cgit v1.2.3 From 81c548029ebed89407c055d62ebec6a503bcdde6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 18:18:55 -0500 Subject: improve stream lifecycle handling --- src/slskd/Network/API/Hubs/NetworkHub.cs | 7 +-- src/slskd/Network/NetworkService.cs | 100 +++++++++++++++++++++---------- 2 files changed, 71 insertions(+), 36 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 28a6b0f7..7945a62b 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -95,12 +95,9 @@ namespace slskd.Network throw new UnauthorizedAccessException(); } - public void NotifyUploadFailed(Guid id) + public void NotifyUploadFailed(Guid id, Exception exception) { - if (Network.PendingFileUploads.TryGetValue(id, out var record)) - { - record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); - } + Network.NotifyFileStreamFailure(id, exception); } public void ReturnFileInfo(Guid id, bool exists, long length) diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 792be99c..7a56eb1c 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -32,11 +32,6 @@ namespace slskd.Network public interface INetworkService { - /// - /// Gets the collection of pending Agent file uploads. - /// - ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } - /// /// Gets the name of the local host. /// @@ -68,9 +63,24 @@ namespace slskd.Network /// /// The agent from which to retrieve the file. /// The file to retrieve. + /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file. - Task GetFileStream(string agentName, string filename, int timeout = 3000); + Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000); + + /// + /// Safely attempts to close a stream obtained with . + /// + /// The unique ID for the stream. + /// If the transfer associated with the stream failed, the exception that caused the failure. + void TryCloseFileStream(Guid id, Exception exception = null); + + /// + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// + /// The unique ID for the stream. + /// The remote exception that caused the failure. + void NotifyFileStreamFailure(Guid id, Exception exception); /// /// Retrieves information about the specified from the specified . @@ -89,7 +99,13 @@ namespace slskd.Network /// The client response to the request. void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); - Task HandleGetFileStreamResponse(string agentName, string filename, Guid id, Stream response); + /// + /// Handles the client response for a request, returning when the corresponding file upload is complete. + /// + /// The ID of the request. + /// The client response to the request. + /// The operation context. + Task HandleGetFileStreamResponse(Guid id, Stream response); void HandleGetFileStreamCompletion(string agentName, string filename); @@ -158,11 +174,6 @@ namespace slskd.Network OptionsMonitor = optionsMonitor; } - /// - /// Gets the collection of pending Agent uploads. - /// - public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); - /// /// Gets the collection of registered Agents. /// @@ -178,7 +189,7 @@ namespace slskd.Network private IHubContext NetworkHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); - private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary WaitIdDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private IWaiter Waiter { get; } @@ -219,35 +230,35 @@ namespace slskd.Network /// /// The agent from which to retrieve the file. /// The file to retrieve. + /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task GetFileStream(string agentName, string filename, int timeout = 3000) + public async Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { throw new NotFoundException($"Agent {agentName} is not registered"); } - var token = Guid.NewGuid(); // cache the id to prevent replay attacks; the agent should respond within the timeout, otherwise // when it does we will no longer know about it - MemoryCache.Set(GetFileTokenCacheKey(filename, token), agentName, TimeSpan.FromMilliseconds(timeout)); - Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName); - - await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, token); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, token); + MemoryCache.Set(GetFileTokenCacheKey(filename, id), agentName, TimeSpan.FromMilliseconds(timeout)); + Log.Debug("Cached file upload token {Token} for agent {Agent}", id, agentName); // 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(GetFileStream), agentName, filename, token); + var key = new WaitKey(nameof(GetFileStream), id); var wait = Waiter.Wait(key, timeout); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, id); + var task = await Task.WhenAny(wait, Task.Delay(timeout)); if (task == wait) { // send the stream back to the caller so it can be used to feed data to the remote client - Log.Information("Agent {Agent} provided file stream for file {Filename} with ID {Id}", agentName, filename, token); + Log.Information("Agent {Agent} provided file stream for file {Filename} with ID {Id}", agentName, filename, id); var stream = await wait; return stream; } @@ -257,6 +268,35 @@ namespace slskd.Network } } + /// + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// + /// The unique ID for the stream. + /// The remote exception that caused the failure. + public void NotifyFileStreamFailure(Guid id, Exception exception) + { + var key = new WaitKey(nameof(GetFileStream), id); + Waiter.Throw(key, exception); + } + + /// + /// Safely attempts to close a stream obtained with . + /// + /// The unique ID for the stream. + /// If the transfer associated with the stream failed, the exception that caused the failure. + public void TryCloseFileStream(Guid id, Exception exception = default) + { + var key = new WaitKey(nameof(HandleGetFileStreamResponse), id); + + if (exception != default) + { + Waiter.Throw(key, exception); + return; + } + + Waiter.Complete(key); + } + /// /// Retrieves information about the specified from the specified . /// @@ -299,7 +339,7 @@ namespace slskd.Network { var key = new WaitKey(nameof(GetFileInfo), agentName, id); - if (!Waiter.ContainsKey(key)) + if (!Waiter.IsWaitingFor(key)) { Log.Warning("Agent {Agent} responded to a file info request with Id {Id}, but a response was not expected", agentName, id); return; @@ -312,33 +352,31 @@ namespace slskd.Network /// /// Handles the client response for a request, returning when the corresponding file upload is complete. /// - /// The agent that provided the response. - /// The name of the file. /// The ID of the request. /// The client response to the request. /// The operation context. - public async Task HandleGetFileStreamResponse(string agentName, string filename, Guid id, Stream response) + public async Task HandleGetFileStreamResponse(Guid id, Stream response) { - var streamKey = new WaitKey(nameof(GetFileStream), agentName, filename, id); + var streamKey = new WaitKey(nameof(GetFileStream), id); - if (!Waiter.ContainsKey(streamKey)) + if (!Waiter.IsWaitingFor(streamKey)) { - Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); + Log.Warning("A file stream response matching Id {Id} is not expected", id); return; } // 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(GetFileStream), "completion", agentName, filename); + var completionKey = new WaitKey(nameof(HandleGetFileStreamResponse), 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 sends execution back to the body of GetFileStream and the upload will begin transferring data Waiter.Complete(streamKey, response); - Log.Information("Agent {Agent} responded to a file request with Id {Id}", agentName, id); // wait for the caller of GetFileStream to report that the upload/stream is complete + // this is the wait that keeps the HTTP handler running await completion; } -- cgit v1.2.3 From d614b962a6b0458e9e03c7a4404c680ddae304e9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 18:30:48 -0500 Subject: more refactoring --- .../Network/API/Controllers/NetworkController.cs | 2 +- src/slskd/Network/API/Hubs/NetworkHub.cs | 4 +- src/slskd/Network/NetworkService.cs | 54 +++++++++++----------- src/slskd/Transfers/Uploads/UploadService.cs | 6 +-- 4 files changed, 32 insertions(+), 34 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index b1a71f34..e30d984c 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -112,7 +112,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. - await Network.HandleGetFileStreamResponse(id: guid, stream); + await Network.HandleFileStreamResponse(id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 7945a62b..32575e8d 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -97,7 +97,7 @@ namespace slskd.Network public void NotifyUploadFailed(Guid id, Exception exception) { - Network.NotifyFileStreamFailure(id, exception); + Network.NotifyFileStreamException(id, exception); } public void ReturnFileInfo(Guid id, bool exists, long length) @@ -108,7 +108,7 @@ namespace slskd.Network return; } - Network.HandleGetFileInfoResponse(record.Agent.Name, id, (exists, length)); + Network.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } } } \ No newline at end of file diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 7a56eb1c..b36bfb89 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -66,21 +66,21 @@ namespace slskd.Network /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file. - Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000); + Task GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000); /// - /// Safely attempts to close a stream obtained with . + /// Safely attempts to close a stream obtained with . /// /// The unique ID for the stream. /// If the transfer associated with the stream failed, the exception that caused the failure. void TryCloseFileStream(Guid id, Exception exception = null); /// - /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// /// The unique ID for the stream. /// The remote exception that caused the failure. - void NotifyFileStreamFailure(Guid id, Exception exception); + void NotifyFileStreamException(Guid id, Exception exception); /// /// Retrieves information about the specified from the specified . @@ -89,25 +89,23 @@ namespace slskd.Network /// The file for which to retrieve information. /// An optional timeout value. /// A value indicating whether the file exists, and the length in bytes. - Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000); + Task<(bool Exists, long Length)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000); /// - /// Handles the client response for a request. + /// Handles the client response for a request. /// /// The agent that provided the response. /// The ID of the request. /// The client response to the request. - void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); + void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); /// - /// Handles the client response for a request, returning when the corresponding file upload is complete. + /// Handles the client response for a request, returning when the corresponding file upload is complete. /// /// The ID of the request. /// The client response to the request. /// The operation context. - Task HandleGetFileStreamResponse(Guid id, Stream response); - - void HandleGetFileStreamCompletion(string agentName, string filename); + Task HandleFileStreamResponse(Guid id, Stream response); /// /// Registers the specified with the specified . @@ -233,7 +231,7 @@ namespace slskd.Network /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000) + public async Task GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { @@ -247,7 +245,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(GetFileStream), id); + var key = new WaitKey(nameof(GetFileStreamAsync), id); var wait = Waiter.Wait(key, timeout); await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id); @@ -269,24 +267,24 @@ namespace slskd.Network } /// - /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// /// The unique ID for the stream. /// The remote exception that caused the failure. - public void NotifyFileStreamFailure(Guid id, Exception exception) + public void NotifyFileStreamException(Guid id, Exception exception) { - var key = new WaitKey(nameof(GetFileStream), id); + var key = new WaitKey(nameof(GetFileStreamAsync), id); Waiter.Throw(key, exception); } /// - /// Safely attempts to close a stream obtained with . + /// Safely attempts to close a stream obtained with . /// /// The unique ID for the stream. /// If the transfer associated with the stream failed, the exception that caused the failure. public void TryCloseFileStream(Guid id, Exception exception = default) { - var key = new WaitKey(nameof(HandleGetFileStreamResponse), id); + var key = new WaitKey(nameof(HandleFileStreamResponse), id); if (exception != default) { @@ -304,7 +302,7 @@ namespace slskd.Network /// The file for which to retrieve information. /// An optional timeout value. /// A value indicating whether the file exists, and the length in bytes. - public async Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000) + public async Task<(bool Exists, long Length)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { @@ -312,7 +310,7 @@ namespace slskd.Network } var id = Guid.NewGuid(); - var key = new WaitKey(nameof(GetFileInfo), agentName, id); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); try @@ -330,14 +328,14 @@ namespace slskd.Network } /// - /// Handles the client response for a request. + /// Handles the client response for a request. /// /// The agent that provided the response. /// The ID of the request. /// The client response to the request. - public void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) + public void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) { - var key = new WaitKey(nameof(GetFileInfo), agentName, id); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); if (!Waiter.IsWaitingFor(key)) { @@ -350,14 +348,14 @@ namespace slskd.Network } /// - /// Handles the client response for a request, returning when the corresponding file upload is complete. + /// Handles the client response for a request, returning when the corresponding file upload is complete. /// /// The ID of the request. /// The client response to the request. /// The operation context. - public async Task HandleGetFileStreamResponse(Guid id, Stream response) + public async Task HandleFileStreamResponse(Guid id, Stream response) { - var streamKey = new WaitKey(nameof(GetFileStream), id); + var streamKey = new WaitKey(nameof(GetFileStreamAsync), id); if (!Waiter.IsWaitingFor(streamKey)) { @@ -368,7 +366,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(HandleGetFileStreamResponse), id); + var completionKey = new WaitKey(nameof(HandleFileStreamResponse), 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 @@ -385,7 +383,7 @@ namespace slskd.Network // complete the indefinite wait for this upload. this sends execution back to the body of the file // stream response handler, and ultimately back to the API controller. the agent's original HTTP request // will complete. - var key = new WaitKey(nameof(GetFileStream), "completion", agentName, filename); + var key = new WaitKey(nameof(GetFileStreamAsync), "completion", agentName, filename); Waiter.Complete(key); Log.Information("Upload of {File} from agent {Agent} reported as completed", filename, agentName); } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index d3e8b89e..7c5bab0b 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -137,7 +137,7 @@ namespace slskd.Transfers.Uploads } else { - var (exists, length) = await Network.GetFileInfo(agentName: host, filename); + var (exists, length) = await Network.GetFileInfoAsync(agentName: host, filename); if (!exists || length <= 0) { @@ -269,7 +269,7 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStream(agentName: host, filename, id), + inputStreamFactory: () => Network.GetFileStreamAsync(agentName: host, filename, id), options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From 7510f1d4165bdff9f3c656cd31b5ba883fb6cb18 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 25 Oct 2022 10:28:25 -0500 Subject: cleanup and docs of file info exchange --- src/slskd/Network/API/Hubs/NetworkHub.cs | 8 +--- src/slskd/Network/NetworkService.cs | 70 +++++++++++++++++++------------- 2 files changed, 42 insertions(+), 36 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 32575e8d..e654f795 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -102,13 +102,7 @@ namespace slskd.Network public void ReturnFileInfo(Guid id, bool exists, long length) { - if (!Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) - { - Log.Warning("Agent connection {Id} responded to a file info request with Id {Id}, but is not registered.", Context.ConnectionId, id); - return; - } - - Network.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); + Network.HandleFileInfoResponse(id, (exists, length)); } } } \ No newline at end of file diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index dffc305d..0a3079ae 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -65,6 +65,20 @@ namespace slskd.Network /// /// Retrieves information about the specified from the specified . /// + /// + /// This is the first step in a mult-step workflow. The entire sequence is: + /// + /// + /// Upload service calls and awaits , which requests the file info from the + /// remote agent, and waits for the response before returning it to the caller. + /// + /// + /// The remote agent sends the response via the SignalR hub, and the hub invokes + /// . The response is passed back to and + /// returned to the caller. + /// + /// + /// /// The agent from which to retrieve the file information. /// The file for which to retrieve information. /// An optional timeout value. @@ -118,10 +132,9 @@ namespace slskd.Network /// /// Handles the client response for a request. /// - /// The agent that provided the response. /// The ID of the request. /// The client response to the request. - void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); + void HandleFileInfoResponse(Guid id, (bool Exists, long Length) response); /// /// Handles the client response for a request, returning when the corresponding file @@ -132,13 +145,6 @@ namespace slskd.Network /// The operation context. Task HandleFileStreamResponse(Guid id, Stream response); - /// - /// Returns a value indicating whether an agent with the specified is registered. - /// - /// The name of the agent. - /// A value indicating whether an agent with the specified name is registered. - bool IsAgentRegistered(string agentName); - /// /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// @@ -275,6 +281,20 @@ namespace slskd.Network /// /// Retrieves information about the specified from the specified . /// + /// + /// This is the first step in a mult-step workflow. The entire sequence is: + /// + /// + /// Upload service calls and awaits , which requests the file info from the + /// remote agent, and waits for the response before returning it to the caller. + /// + /// + /// The remote agent sends the response via the SignalR hub, and the hub invokes + /// . The response is passed back to and + /// returned to the caller. + /// + /// + /// /// The agent from which to retrieve the file information. /// The file for which to retrieve information. /// An optional timeout value. @@ -286,8 +306,10 @@ namespace slskd.Network throw new NotFoundException($"Agent {agentName} is not registered"); } + // 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), agentName, id); + var key = new WaitKey(nameof(GetFileInfoAsync), id); var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); try @@ -353,9 +375,9 @@ namespace slskd.Network throw new NotFoundException($"Agent {agentName} is not registered"); } - // cache the id to prevent replay attacks; the agent should respond within the timeout. this is somewhat redundant - // due to the wait using only the id, however caching the agent name along with the other elements of the request - // allows us to ensure that tokens are used only by the agent they were intended for. + // cache the id to prevent replay attacks; the agent should respond within the timeout. this is somewhat redundant due + // to the wait using only the id, however caching the agent name along with the other elements of the request allows + // us to ensure that tokens are used only by the agent they were intended for. MemoryCache.Set(GetFileTokenCacheKey(filename, id), agentName, TimeSpan.FromMilliseconds(timeout)); Log.Debug("Cached file upload token {Token} for agent {Agent}", id, agentName); @@ -385,21 +407,20 @@ namespace slskd.Network /// /// Handles the client response for a request. /// - /// The agent that provided the response. /// The ID of the request. /// The client response to the request. - public void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) + public void HandleFileInfoResponse(Guid id, (bool Exists, long Length) response) { - var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); + var key = new WaitKey(nameof(GetFileInfoAsync), id); if (!Waiter.IsWaitingFor(key)) { - Log.Warning("Agent {Agent} responded to a file info request with Id {Id}, but a response was not expected", agentName, id); - return; + var msg = $"A file info response matching Id {id} was not expected"; + Log.Warning(msg); + throw new NotFoundException(msg); } Waiter.Complete(key, response); - Log.Information("Agent {Agent} responded to a file info request with Id {Id}: Exists: {Exists}, Length: {Length}", agentName, id, response.Exists, response.Length); } /// @@ -407,7 +428,7 @@ namespace slskd.Network /// upload is complete. /// /// - /// Assumes has previously been used to ensure the Id and agent match. + /// Assumes has previously been used to ensure the Id and agent match. /// /// The ID of the request. /// The client response to the request. @@ -438,15 +459,6 @@ namespace slskd.Network await completion; } - public void HandleGetFileStreamCompletion(string agentName, string filename) - { - // complete the indefinite wait for this upload. this sends execution back to the body of the file stream response - // handler, and ultimately back to the API controller. the agent's original HTTP request will complete. - var key = new WaitKey(nameof(GetFileStreamAsync), "completion", agentName, filename); - Waiter.Complete(key); - Log.Information("Upload of {File} from agent {Agent} reported as completed", filename, agentName); - } - /// /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// -- cgit v1.2.3 From 20b800a3bdd9b0022b0e1870364980068c3d4adf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 Oct 2022 09:56:38 -0500 Subject: tweak auth --- src/slskd/Network/API/Hubs/NetworkHub.cs | 2 +- src/slskd/Network/NetworkService.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src/slskd/Network/API/Hubs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index e654f795..298dd9ec 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -66,7 +66,7 @@ namespace slskd.Network public bool Login(string agent, string challengeResponse) { - if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) + if (Network.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { var remoteIp = Context.Features.Get().RemoteIpAddress.ToString(); var record = new Agent { Name = agent, ConnectedAt = DateTime.UtcNow, IPAddress = remoteIp }; diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 0a3079ae..100d9448 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -187,9 +187,9 @@ namespace slskd.Network /// /// The ID of the agent connection. /// The agent name. - /// The challenge response provided by the agent. + /// The response credential. /// A value indicating whether the response is valid. - bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse); + bool TryValidateAuthenticationCredential(string connectionId, string agentName, string credential); /// /// Attempts to validate the file stream response credential associated with the specified . @@ -257,7 +257,7 @@ namespace slskd.Network var token = Cryptography.Random.GetBytes(32).ToBase62(); // this token is only valid for this connection id for a short time this is important to prevent replay-type attacks. - MemoryCache.Set(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromMinutes(1)); + MemoryCache.Set(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromSeconds(10)); Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); return token; } @@ -532,9 +532,9 @@ namespace slskd.Network /// /// The ID of the agent connection. /// The agent name. - /// The challenge response provided by the agent. + /// The response credential. /// A value indicating whether the response is valid. - public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse) + public bool TryValidateAuthenticationCredential(string connectionId, string agentName, string credential) { if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(connectionId), out var challengeToken)) { @@ -552,7 +552,7 @@ namespace slskd.Network var tokenBytes = ((string)challengeToken).FromBase62(); var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62(); - return expectedResponse == challengeResponse; + return expectedResponse == credential; } /// -- cgit v1.2.3