From 120c6d0631fbd9a9f2c262171e713fcc6df01ea2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 08:57:09 -0500 Subject: rename Agents namespace to Network --- src/slskd/Network/API/Hubs/NetworkHub.cs | 91 ++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/slskd/Network/API/Hubs/NetworkHub.cs (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 new file mode 100644 index 00000000..61ac08f0 --- /dev/null +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -0,0 +1,91 @@ +// +// 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/. +// + +namespace slskd.Network +{ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.SignalR; + using Serilog; + + public static class NetworkHubMethods + { + public static readonly string RequestFile = "REQUEST_FILE"; + 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); + } + } + + /// + /// The network SignalR hub. + /// + [Authorize] + public class NetworkHub : Hub + { + public NetworkHub( + INetworkService networkService) + { + Network = networkService; + } + + private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + 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)); + } + + public override Task OnDisconnectedAsync(Exception exception) + { + if (Network.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) + { + Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); + } + + return Task.CompletedTask; + } + + public bool Login(string agent, string challengeResponse) + { + if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) + { + Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); + Network.RegisterAgent(agent, Context.ConnectionId); + return true; + } + + Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! + return false; + } + } +} \ No newline at end of file -- cgit v1.2.3 From a8fe7056791ae7e12130fa0ed5e024e99eb40c3e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:20:59 -0500 Subject: add hub method GetShareUploadToken --- src/slskd/Network/API/Hubs/NetworkHub.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (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 61ac08f0..becbbed0 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -87,5 +87,16 @@ namespace slskd.Network Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! return false; } + + public Guid GetShareUploadToken() + { + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var agent)) + { + return Network.GetShareUploadToken(agent); + } + + // this can happen if the agent attempts to upload before logging in + throw new UnauthorizedAccessException(); + } } } \ No newline at end of file -- cgit v1.2.3 From 35edcb342ded5a9bdc4f0627f0c213b85c033bba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:15:53 -0500 Subject: fix operand order --- src/slskd/Network/API/Hubs/NetworkHub.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (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 becbbed0..78a658d4 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -79,7 +79,7 @@ namespace slskd.Network if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) { Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); - Network.RegisterAgent(agent, Context.ConnectionId); + Network.RegisterAgent(Context.ConnectionId, agent); return true; } @@ -96,6 +96,7 @@ namespace slskd.Network } // 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); throw new UnauthorizedAccessException(); } } -- cgit v1.2.3 From e2383ff98d4994fa2215eb47b8b0cd69775e088b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:40:20 -0500 Subject: add a hub method to handle failed uploads --- src/slskd/Network/API/Hubs/NetworkHub.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (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 78a658d4..6d43e6da 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -99,5 +99,13 @@ namespace slskd.Network Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } + + public void NotifyUploadFailed(Guid id) + { + if (Network.PendingFileUploads.TryGetValue(id, out var record)) + { + record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } } } \ No newline at end of file -- cgit v1.2.3 From 8663b3fac9597f7b0c6ffd8081b99c761a18b326 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:09:41 -0500 Subject: add file info handling --- src/slskd/Network/API/Hubs/NetworkHub.cs | 16 +++- src/slskd/Network/NetworkClient.cs | 25 +++++- src/slskd/Network/NetworkService.cs | 141 ++++++++++++++++++++++--------- 3 files changed, 139 insertions(+), 43 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 6d43e6da..f79fecf2 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -26,6 +26,7 @@ namespace slskd.Network 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"; public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; @@ -41,6 +42,11 @@ namespace slskd.Network // 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); + } } /// @@ -104,7 +110,15 @@ namespace slskd.Network { if (Network.PendingFileUploads.TryGetValue(id, out var record)) { - record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } + + public void ReturnFileInfo(Guid id, bool exists, long length) + { + if (Network.PendingFileInquiries.TryGetValue(id, out var record)) + { + record.TrySetResult((exists, length)); } } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index d171e9b9..6e4e4dca 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -156,7 +156,7 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private async Task HandleFileRequest(Guid id, string filename) + private async Task HandleFileRequest(string filename, Guid id) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -164,7 +164,7 @@ namespace slskd.Network { var localFilename = await Shares.ResolveFileAsync(filename); - var localFileInfo = new FileInfo(filename); + var localFileInfo = new FileInfo(localFilename); if (!localFileInfo.Exists) { @@ -202,6 +202,25 @@ namespace slskd.Network } } + private async Task HandleFileInfoRequest(string filename, Guid id) + { + Log.Information("Network controller requested file info for {Filename} with ID {Id}", filename, id); + + try + { + var localFilename = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(localFilename); + + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message); + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, false, 0); + } + } + private async Task HandleAuthenticationChallenge(string challengeToken) { Log.Debug("Network controller sent an authentication challenge"); @@ -296,7 +315,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 8753ae0a..d857cac5 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -37,11 +37,25 @@ namespace slskd.Network /// ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } + /// + /// Gets the collection of pending Agent file inquiries. + /// + ReadOnlyDictionary> PendingFileInquiries { get; } + /// /// Gets the collection of registered Agents. /// ReadOnlyDictionary RegisteredAgents { get; } + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// 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 agent, string filename, int timeout = 3000); + /// /// Retrieves an upload of the specified from the specified . /// @@ -131,12 +145,18 @@ namespace slskd.Network /// public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); + /// + /// Gets the collection of pending Agent file inquiries. + /// + public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); + /// /// Gets the collection of registered Agents. /// public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor OptionsMonitor { get; } @@ -144,6 +164,88 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// 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 agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); + + PendingFileInquiryDictionary.TryAdd(id, tcs); + + try + { + await NetworkHub.RequestFileInfoAsync(agent, filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agent, id); + + var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); + + if (task == tcs.Task) + { + return await tcs.Task; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agent}"); + } + } + finally + { + PendingFileInquiryDictionary.TryRemove(id, out _); + } + } + + /// + /// Retrieves an upload of the specified from the specified . + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// An optional timeout value. + /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + + // create a TCS for the upload stream. this is awaited below and completed in + // the API controller when the agent POSTs the file + var upload = new TaskCompletionSource(); + + // create a TCS for the upload itself. this is awaited by the API controller + // and completed by the transfer service when the upload to the remote user is complete + // the API controller needs to wait until the remote transfer is complete in order to + // keep the stream open for the duration + var completion = new TaskCompletionSource(); + + PendingFileUploadDictionary.TryAdd(id, (upload, completion)); + + try + { + await NetworkHub.RequestFileAsync(agent, filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); + + var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + + if (task == upload.Task) + { + var stream = await upload.Task; + return (stream, completion); + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); + } + } + finally + { + PendingFileUploadDictionary.TryRemove(id, out _); + } + } + /// /// Retrieves a new share upload token for the specified . /// @@ -249,45 +351,6 @@ namespace slskd.Network return expectedResponse == challengeResponse; } - /// - /// Retrieves an upload of the specified from the specified . - /// - /// The agent from which to retrieve the file. - /// The file to retrieve. - /// An optional timeout value. - /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) - { - var id = Guid.NewGuid(); - - // create a TCS for the upload stream. this is awaited below and completed in - // the API controller when the agent POSTs the file - var upload = new TaskCompletionSource(); - - // create a TCS for the upload itself. this is awaited by the API controller - // and completed by the transfer service when the upload to the remote user is complete - // the API controller needs to wait until the remote transfer is complete in order to - // keep the stream open for the duration - var completion = new TaskCompletionSource(); - - PendingFileUploadDictionary.TryAdd(id, (upload, completion)); - - await NetworkHub.RequestFileAsync(agent, filename, id); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); - - if (task == upload.Task) - { - var stream = await upload.Task; - return (stream, completion); - } - else - { - throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); - } - } - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; -- cgit v1.2.3