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/NetworkService.cs | 364 ++++++++++++++++++++++++++++++++++++ 1 file changed, 364 insertions(+) create mode 100644 src/slskd/Network/NetworkService.cs (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs new file mode 100644 index 00000000..86e0f80a --- /dev/null +++ b/src/slskd/Network/NetworkService.cs @@ -0,0 +1,364 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Network +{ + using System; + using System.Collections.Concurrent; + using System.Collections.ObjectModel; + using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + using Microsoft.AspNetCore.SignalR.Client; + using Microsoft.Extensions.Caching.Memory; + using Serilog; + using slskd.Cryptography; + + public interface INetworkService + { + /// + /// Gets the collection of pending Agent uploads. + /// + ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } + + /// + /// Gets the collection of registered Agents. + /// + ReadOnlyDictionary RegisteredAgents { get; } + + /// + /// 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. + Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000); + + /// + /// Registers the specified name with the specified . + /// + /// The ID of the connection. + /// The name of the agent. + void RegisterAgent(string connectionId, string agent); + + /// + /// Attempts to remove the registration for the specified . + /// + /// The ID of the connection. + /// A value indicating whether a registration was removed. + bool TryRemoveAgentRegistration(string connectionId, out string agent); + + /// + /// Generates a random authentication challenge token for the specified . + /// + /// The ID of the agent connection. + /// The generated token. + string GenerateAuthenticationChallengeToken(string connectionId); + + /// + /// Validates an authentication challenge response. + /// + /// The ID of the agent connection. + /// The agent name. + /// The challenge response provided by the agent. + /// A value indicating whether the response is valid. + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); + } + + public class NetworkService : INetworkService + { + public NetworkService( + IOptionsMonitor optionsMonitor, + IHttpClientFactory httpClientFactory, + IHubContext networkHub) + { + NetworkHub = networkHub; + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + /// + /// Gets the collection of pending Agent uploads. + /// + public ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads => new(PendingUploadDictionary); + + /// + /// Gets the collection of registered Agents. + /// + public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); + + private ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploadDictionary { get; } = new(); + private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); + private IOptionsMonitor OptionsMonitor { get; } + private IHttpClientFactory HttpClientFactory { get; } + private HttpClient HttpClient { get; set; } + private HubConnection HubConnection { get; set; } + private IHubContext NetworkHub { get; set; } + private string LastOptionsHash { get; set; } + private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Registers the specified name with the specified . + /// + /// The ID of the connection. + /// The name of the agent. + public void RegisterAgent(string connectionId, string agent) + => RegisteredAgentDictionary.TryAdd(connectionId, agent); + + /// + /// Attempts to remove the registration for the specified . + /// + /// The ID of the connection. + /// The name of the agent, if a registration was removed. + /// A value indicating whether a registration was removed. + public bool TryRemoveAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryRemove(connectionId, out agent); + + /// + /// Generates a random authentication challenge token for the specified . + /// + /// The ID of the agent connection. + /// The generated token. + public string GenerateAuthenticationChallengeToken(string connectionId) + { + var token = Cryptography.Random.GetBytes(16).ToBase62(); + + // this token is only valid for this connection id for a short time + // this is important to prevent replay-type attacks. + MemoryCache.Set(connectionId, token, TimeSpan.FromMinutes(1)); + Log.Debug("Cached token {Token} for ID {Id}", token, connectionId); + return token; + } + + /// + /// Validates an authentication challenge response. + /// + /// The ID of the agent connection. + /// The agent name. + /// The challenge response provided by the agent. + /// A value indicating whether the response is valid. + public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) + { + if (!MemoryCache.TryGetValue(connectionId, out var challengeToken)) + { + Log.Debug("Auth challenge for {Id} failed: no challenge token cached for ID", connectionId); + return false; + } + + if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agent, out var agentOptions)) + { + Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agent); + return false; + } + + var key = agentOptions.Secret.FromBase62(); + var tokenBytes = ((string)challengeToken).FromBase62(); + var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62(); + + 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)> GetUpload(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(); + + PendingUploadDictionary.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 async Task HandleFileRequest(Guid id, string filename) + { + Log.Information("Controller requested file {Filename} with ID {Id}", filename, id); + + try + { + using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "file", filename }, + }; + + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + Console.WriteLine("Failed"); + Console.WriteLine(response.StatusCode); + } + else + { + Console.WriteLine($"{filename} sent!"); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + } + } + + private async Task HandleAuthenticationChallenge(string challengeToken) + { + Log.Information("Controller sent an authentication challenge"); + + try + { + 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(); + + Log.Information("Logging in..."); + var success = await HubConnection.InvokeAsync("Login", agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Controller authentication failed. Check configuration."); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + } + } + + private void Configure(Options options) + { + ConfigurationSyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); + + if (optionsHash == LastOptionsHash) + { + return; + } + + var mode = options.Network.OperationMode.ToEnum(); + + //if (mode == NetworkOperationMode.Agent + //{ + HttpClient = HttpClientFactory.CreateClient(); + HttpClient.BaseAddress = new(options.Network.Controller.Address); + + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) + .Build(); + + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + + _ = Task.Run(async () => + { + // it takes a bit for the application to become responsive to network calls + await Task.Delay(3000); + + // retry indefinitely + await Retry.Do( + task: () => HubConnection.StartAsync(), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to controller: {Message}", attempts, ex.Message), + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000); + + Log.Information("Controller connection established"); + }); + //} + + LastOptionsHash = optionsHash; + } + finally + { + ConfigurationSyncRoot.Release(); + } + } + + private Task HubConnection_Closed(Exception arg) + { + Log.Warning("Controller connection closed: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnecting(Exception arg) + { + Log.Warning("Controller connection reconnecting: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnected(string arg) + { + Log.Warning("Controller connection reconnected"); + return Task.CompletedTask; + } + } +} -- cgit v1.2.3 From bccd6202d2d3d6e60b6a24423f0ab628b6d7dd39 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 14:51:30 -0500 Subject: split network client from service --- src/slskd/Application.cs | 19 ++- src/slskd/Network/NetworkClient.cs | 243 ++++++++++++++++++++++++++++++++++++ src/slskd/Network/NetworkService.cs | 142 --------------------- src/slskd/Program.cs | 2 + 4 files changed, 260 insertions(+), 146 deletions(-) create mode 100644 src/slskd/Network/NetworkClient.cs (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 31949fd5..e0688848 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -42,6 +42,7 @@ namespace slskd using slskd.Core.API; using slskd.Integrations.Pushbullet; using slskd.Messaging; + using slskd.Network; using slskd.Search; using slskd.Shares; using slskd.Transfers; @@ -87,6 +88,7 @@ namespace slskd IRoomService roomService, IUserService userService, IShareService shareService, + INetworkClient networkClient, IPushbulletService pushbulletService, IHubContext applicationHub, IHubContext logHub) @@ -135,6 +137,8 @@ namespace slskd LogHub = logHub; Program.LogEmitted += (_, log) => LogHub.EmitLogAsync(log); + NetworkClient = networkClient; + Client = soulseekClient; Client.DiagnosticGenerated += Client_DiagnosticGenerated; @@ -174,6 +178,7 @@ namespace slskd private static bool ShuttingDown { get; set; } = false; private ISoulseekClient Client { get; set; } + private INetworkClient NetworkClient { get; set; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } private IConnectionWatchdog ConnectionWatchdog { get; } @@ -391,12 +396,18 @@ namespace slskd { Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } - //else if (OptionsAtStartup.Network.OperationMode.ToEnum() == NetworkOperationMode.Agent) - //{ - // Log.Information("Running in Agent mode; not connecting to the Soulseek server."); - //} + else if (OptionsAtStartup.Network.OperationMode.ToEnum() == NetworkOperationMode.Agent || !OptionsAtStartup.Flags.DualNetworkMode) + { + Log.Information("Running in Agent mode; not connecting to the Soulseek server."); + await NetworkClient.StartAsync(cancellationToken); + } else { + if (OptionsAtStartup.Flags.DualNetworkMode) + { + await NetworkClient.StartAsync(cancellationToken); + } + await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs new file mode 100644 index 00000000..be7b6a2c --- /dev/null +++ b/src/slskd/Network/NetworkClient.cs @@ -0,0 +1,243 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Network +{ + using System; + using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR.Client; + using Serilog; + using slskd.Cryptography; + + public interface INetworkClient + { + Task StartAsync(CancellationToken cancellationToken = default); + Task StopAsync(CancellationToken cancellationToken = default); + } + + public class NetworkClient : INetworkClient + { + public NetworkClient( + IOptionsMonitor optionsMonitor, + IHttpClientFactory httpClientFactory) + { + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private string LastOptionsHash { get; set; } + private IOptionsMonitor OptionsMonitor { get; } + private IHttpClientFactory HttpClientFactory { get; } + private HttpClient HttpClient { get; set; } + private HubConnection HubConnection { get; set; } + private bool StartRequested { get; set; } + private CancellationTokenSource StartCancellationTokenSource { get; set; } + + public async Task StartAsync(CancellationToken cancellationToken = default) + { + if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum() != NetworkOperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) + { + throw new InvalidOperationException($"Network client can only be started when operation mode is {NetworkOperationMode.Agent}"); + } + + StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + StartRequested = true; + + Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); + + // retry indefinitely + await Retry.Do( + task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message), + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000, + StartCancellationTokenSource.Token); + + Log.Information("Network controller connection established"); + } + + public async Task StopAsync(CancellationToken cancellationToken = default) + { + StartRequested = false; + + if (HubConnection != null) + { + await HubConnection.StopAsync(cancellationToken); + + Log.Information("Network controller connection disconnected"); + } + } + + private async Task HandleFileRequest(Guid id, string filename) + { + Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); + + try + { + using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "file", filename }, + }; + + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + Console.WriteLine("Failed"); + Console.WriteLine(response.StatusCode); + } + else + { + Console.WriteLine($"{filename} sent!"); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + } + } + + private async Task HandleAuthenticationChallenge(string challengeToken) + { + Log.Information("Network controller sent an authentication challenge"); + + try + { + 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(); + + Log.Information("Logging in..."); + var success = await HubConnection.InvokeAsync("Login", agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Network controller authentication failed. Check configuration."); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + } + } + + private Task HubConnection_Closed(Exception arg) + { + Log.Warning("Network controller connection closed: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnecting(Exception arg) + { + Log.Warning("Network controller connection reconnecting: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnected(string arg) + { + Log.Warning("Network controller connection reconnected"); + return Task.CompletedTask; + } + + private void Configure(Options options) + { + if (options.Network.OperationMode.ToEnum() != NetworkOperationMode.Agent && !options.Flags.DualNetworkMode) + { + return; + } + + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + + if (optionsHash == LastOptionsHash) + { + return; + } + + Log.Information("Network options changed. Reconfiguring..."); + + // if the client is attempting a connection, cancel it + // it's going to be dropped when we create a new instance, but we need + // the retry loop around connection to stop. + StartCancellationTokenSource?.Cancel(); + + HttpClient = HttpClientFactory.CreateClient(); + HttpClient.BaseAddress = new(options.Network.Controller.Address); + + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect(new[] + { + TimeSpan.FromSeconds(0), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(3), + TimeSpan.FromSeconds(10), + TimeSpan.FromSeconds(30), + }) + .Build(); + + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + + LastOptionsHash = optionsHash; + + Log.Information("Network options reconfigured"); + + // if start was requested (if StartAsync() was called externally), restart + // after re-configuration + if (StartRequested) + { + Log.Information("Reconnecting the network controller connection..."); + _ = StartAsync(); + } + } + finally + { + SyncRoot.Release(); + } + } + } +} diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 86e0f80a..368e6cf4 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -95,9 +95,6 @@ namespace slskd.Network HttpClientFactory = httpClientFactory; OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(options => Configure(options)); - - Configure(OptionsMonitor.CurrentValue); } /// @@ -221,144 +218,5 @@ namespace slskd.Network throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); } } - - private async Task HandleFileRequest(Guid id, string filename) - { - Log.Information("Controller requested file {Filename} with ID {Id}", filename, id); - - try - { - using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); - using var content = new MultipartFormDataContent - { - { new StreamContent(stream), "file", filename }, - }; - - request.Content = content; - - Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); - var response = await HttpClient.SendAsync(request); - - if (!response.IsSuccessStatusCode) - { - Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); - Console.WriteLine("Failed"); - Console.WriteLine(response.StatusCode); - } - else - { - Console.WriteLine($"{filename} sent!"); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); - } - } - - private async Task HandleAuthenticationChallenge(string challengeToken) - { - Log.Information("Controller sent an authentication challenge"); - - try - { - 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(); - - Log.Information("Logging in..."); - var success = await HubConnection.InvokeAsync("Login", agent, response); - - if (!success) - { - await HubConnection.StopAsync(); - Log.Error("Controller authentication failed. Check configuration."); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); - } - } - - private void Configure(Options options) - { - ConfigurationSyncRoot.Wait(); - - try - { - var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); - - if (optionsHash == LastOptionsHash) - { - return; - } - - var mode = options.Network.OperationMode.ToEnum(); - - //if (mode == NetworkOperationMode.Agent - //{ - HttpClient = HttpClientFactory.CreateClient(); - HttpClient.BaseAddress = new(options.Network.Controller.Address); - - HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Network.Controller.Address}/hub/agents") - .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) - .Build(); - - HubConnection.Reconnected += HubConnection_Reconnected; - HubConnection.Reconnecting += HubConnection_Reconnecting; - HubConnection.Closed += HubConnection_Closed; - - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); - HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); - - _ = Task.Run(async () => - { - // it takes a bit for the application to become responsive to network calls - await Task.Delay(3000); - - // retry indefinitely - await Retry.Do( - task: () => HubConnection.StartAsync(), - isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to controller: {Message}", attempts, ex.Message), - maxAttempts: int.MaxValue, - maxDelayInMilliseconds: 30000); - - Log.Information("Controller connection established"); - }); - //} - - LastOptionsHash = optionsHash; - } - finally - { - ConfigurationSyncRoot.Release(); - } - } - - private Task HubConnection_Closed(Exception arg) - { - Log.Warning("Controller connection closed: {Message}", arg.Message); - return Task.CompletedTask; - } - - private Task HubConnection_Reconnecting(Exception arg) - { - Log.Warning("Controller connection reconnecting: {Message}", arg.Message); - return Task.CompletedTask; - } - - private Task HubConnection_Reconnected(string arg) - { - Log.Warning("Controller connection reconnected"); - return Task.CompletedTask; - } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 907090a5..1c0a6852 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -533,7 +533,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 34d07fdeb4fd83fbce0f4d9c82125289b8b2a8f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:21:32 -0500 Subject: add methods to orchestrate share uploads --- src/slskd/Network/NetworkService.cs | 107 +++++++++++++++++++++++++++++------- 1 file changed, 87 insertions(+), 20 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 368e6cf4..6c573da0 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -23,11 +23,8 @@ namespace slskd.Network using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.IO; - using System.Net.Http; - using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; - using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.Caching.Memory; using Serilog; using slskd.Cryptography; @@ -35,9 +32,9 @@ namespace slskd.Network public interface INetworkService { /// - /// Gets the collection of pending Agent uploads. + /// Gets the collection of pending Agent file uploads. /// - ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } + ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } /// /// Gets the collection of registered Agents. @@ -51,7 +48,25 @@ namespace slskd.Network /// The file to retrieve. /// An optional timeout value. /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000); + Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000); + + /// + /// Retrieves a new share upload token for the specified . + /// + /// + /// The token is cached internally, and is only valid while it remains in the cache. + /// + /// The name of the agent. + /// The generated token. + Guid GetShareUploadToken(string agent); + + /// + /// Attempts to retrieve the specified share upload . + /// + /// The token. + /// The name of the agent attempting to use the token. + /// A value indicating whether the specified token exists. + bool TryGetShareUploadToken(Guid token, out string agent); /// /// Registers the specified name with the specified . @@ -60,16 +75,28 @@ namespace slskd.Network /// The name of the agent. void RegisterAgent(string connectionId, string agent); + /// + /// Attempts to retrieve the registration for the specified . + /// + /// The ID of the agent connection. + /// The agent, if registered. + /// A value indicating whether the registration exists. + bool TryGetAgentRegistration(string connectionId, out string agent); + /// /// Attempts to remove the registration for the specified . /// /// The ID of the connection. + /// The agent, if removed. /// A value indicating whether a registration was removed. bool TryRemoveAgentRegistration(string connectionId, out string agent); /// /// Generates a random authentication challenge token for the specified . /// + /// + /// The token is cached internally, and is only valid while it remains in the cache. + /// /// The ID of the agent connection. /// The generated token. string GenerateAuthenticationChallengeToken(string connectionId); @@ -88,11 +115,9 @@ namespace slskd.Network { public NetworkService( IOptionsMonitor optionsMonitor, - IHttpClientFactory httpClientFactory, IHubContext networkHub) { NetworkHub = networkHub; - HttpClientFactory = httpClientFactory; OptionsMonitor = optionsMonitor; } @@ -100,25 +125,55 @@ namespace slskd.Network /// /// Gets the collection of pending Agent uploads. /// - public ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads => new(PendingUploadDictionary); + public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); /// /// Gets the collection of registered Agents. /// public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); - private ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploadDictionary { get; } = new(); + private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor OptionsMonitor { get; } - private IHttpClientFactory HttpClientFactory { get; } - private HttpClient HttpClient { get; set; } - private HubConnection HubConnection { get; set; } private IHubContext NetworkHub { get; set; } - private string LastOptionsHash { get; set; } - private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); private ILogger Log { get; } = Serilog.Log.ForContext(); + /// + /// Retrieves a new share upload token for the specified . + /// + /// + /// The token is cached internally, and is only valid while it remains in the cache. + /// + /// The name of the agent. + /// The generated token. + public Guid GetShareUploadToken(string agent) + { + var token = Guid.NewGuid(); + MemoryCache.Set(GetShareTokenCacheKey(token), agent, TimeSpan.FromMinutes(1)); + Log.Debug("Cached share upload token {Token} for agent {Agent}", token, agent); + + return token; + } + + /// + /// Attempts to retrieve the specified share upload . + /// + /// The token. + /// The name of the agent attempting to use the token. + /// A value indicating whether the specified token exists. + public bool TryGetShareUploadToken(Guid token, out string agent) + { + agent = null; + + if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agent)) + { + return true; + } + + return false; + } + /// /// Registers the specified name with the specified . /// @@ -127,6 +182,15 @@ namespace slskd.Network public void RegisterAgent(string connectionId, string agent) => RegisteredAgentDictionary.TryAdd(connectionId, agent); + /// + /// Attempts to retrieve the registration for the specified . + /// + /// The ID of the agent connection. + /// The agent, if registered. + /// A value indicating whether the registration exists. + public bool TryGetAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryGetValue(connectionId, out agent); + /// /// Attempts to remove the registration for the specified . /// @@ -147,8 +211,8 @@ namespace slskd.Network // this token is only valid for this connection id for a short time // this is important to prevent replay-type attacks. - MemoryCache.Set(connectionId, token, TimeSpan.FromMinutes(1)); - Log.Debug("Cached token {Token} for ID {Id}", token, connectionId); + MemoryCache.Set(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromMinutes(1)); + Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); return token; } @@ -161,7 +225,7 @@ namespace slskd.Network /// A value indicating whether the response is valid. public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) { - if (!MemoryCache.TryGetValue(connectionId, out var challengeToken)) + if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(connectionId), out var challengeToken)) { Log.Debug("Auth challenge for {Id} failed: no challenge token cached for ID", connectionId); return false; @@ -187,7 +251,7 @@ namespace slskd.Network /// 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)> GetUpload(string agent, string filename, int timeout = 3000) + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) { var id = Guid.NewGuid(); @@ -201,7 +265,7 @@ namespace slskd.Network // keep the stream open for the duration var completion = new TaskCompletionSource(); - PendingUploadDictionary.TryAdd(id, (upload, completion)); + 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); @@ -218,5 +282,8 @@ namespace slskd.Network 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 From da0eab6deb0c59b2cb4a377ba165139783cb2155 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:41:27 -0500 Subject: stub config --- src/slskd/Network/NetworkService.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 6c573da0..8753ae0a 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -23,6 +23,7 @@ namespace slskd.Network using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.IO; + using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Memory; @@ -120,6 +121,9 @@ namespace slskd.Network NetworkHub = networkHub; OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); } /// @@ -138,6 +142,7 @@ namespace slskd.Network private IOptionsMonitor OptionsMonitor { get; } private IHubContext NetworkHub { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); /// /// Retrieves a new share upload token for the specified . @@ -285,5 +290,18 @@ namespace slskd.Network private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; + + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + } + finally + { + SyncRoot.Release(); + } + } } } -- 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/NetworkService.cs') 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