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') 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