From a9cca7683a3f3fde4fb0fa9a713c5d2c738165aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 20 Oct 2022 19:28:21 -0500 Subject: clean up NetworkService --- src/slskd/Network/NetworkService.cs | 311 ++++++++++++++++++------------------ 1 file changed, 156 insertions(+), 155 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index d857cac5..33daf0cb 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -32,89 +33,77 @@ namespace slskd.Network public interface INetworkService { - /// - /// Gets the collection of pending Agent file uploads. - /// - ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } - /// /// Gets the collection of pending Agent file inquiries. /// ReadOnlyDictionary> PendingFileInquiries { get; } /// - /// Gets the collection of registered Agents. + /// Gets the collection of pending Agent file uploads. /// - ReadOnlyDictionary RegisteredAgents { get; } + ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } /// - /// Retrieves information about the specified from the specified . + /// Gets the collection of registered Agents. /// - /// 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); + ReadOnlyCollection RegisteredAgents { get; } /// - /// Retrieves an upload of the specified from the specified . + /// Generates a random authentication challenge token for 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)> GetFileUpload(string agent, string filename, int timeout = 3000); + /// 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(ConnectionId connectionId); /// - /// Retrieves a new share upload token for the specified . + /// 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 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); + Guid GenerateShareUploadToken(string agentName); /// - /// Attempts to retrieve the specified share upload . + /// Retrieves information about the specified from the specified . /// - /// 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); + /// 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 agentName, string filename, int timeout = 3000); /// - /// Registers the specified name with the specified . + /// Retrieves an upload of the specified from the specified . /// - /// The ID of the connection. - /// The name of the agent. - void RegisterAgent(string connectionId, string agent); + /// 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)> GetFileUpload(string agentName, string filename, int timeout = 3000); /// - /// Attempts to retrieve the registration for the specified . + /// Registers the specified with 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); + /// The ID of the connection. + /// The agent. + void RegisterAgent(ConnectionId connectionId, Agent agent); /// /// Attempts to remove the registration for the specified . /// - /// The ID of the connection. - /// The agent, if removed. + /// The connection ID associated with the registration. + /// The registration record, if removed. /// A value indicating whether a registration was removed. - bool TryRemoveAgentRegistration(string connectionId, out string agent); + bool TryDeregisterAgent(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record); /// - /// Generates a random authentication challenge token for the specified . + /// Attempts to retrieve the registration 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); + /// The connection ID associated with the registration. + /// The registration record, if found. + /// A value indicating whether the registration exists. + bool TryGetAgentRegistration(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record); /// /// Validates an authentication challenge response. @@ -123,65 +112,107 @@ namespace slskd.Network /// 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); + bool TryValidateAuthenticationChallengeResponse(ConnectionId connectionId, string agent, string challengeResponse); + + /// + /// 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 TryValidateShareUploadToken(Guid token, string agentName); } public class NetworkService : INetworkService { public NetworkService( IOptionsMonitor optionsMonitor, - IHubContext networkHub) + IHubContext networkHub) { NetworkHub = networkHub; OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(options => Configure(options)); - - Configure(OptionsMonitor.CurrentValue); } /// - /// Gets the collection of pending Agent uploads. + /// Gets the collection of pending Agent file inquiries. /// - public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); + public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); /// - /// Gets the collection of pending Agent file inquiries. + /// Gets the collection of pending Agent uploads. /// - public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); + public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); /// /// Gets the collection of registered Agents. /// - public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); + public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); - private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); - private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); - private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private SemaphoreSlim AgentSyncRoot { get; } = new SemaphoreSlim(1, 1); + private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); + private IHubContext NetworkHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } - private IHubContext NetworkHub { get; set; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); + private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + + /// + /// 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. + public string GenerateAuthenticationChallengeToken(ConnectionId connectionId) + { + 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)); + Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); + return token; + } /// - /// Retrieves information about the specified from the specified . + /// Retrieves a new share upload token for the specified . /// - /// The agent from which to retrieve the file information. + /// 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 GenerateShareUploadToken(string agentName) + { + var token = Guid.NewGuid(); + + MemoryCache.Set(GetShareTokenCacheKey(token), agentName, TimeSpan.FromMinutes(1)); + Log.Debug("Cached share upload token {Token} for agent {Agent}", token, agentName); + + return token; + } + + /// + /// 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) + public async Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000) { var id = Guid.NewGuid(); var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); + if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) + { + throw new NotFoundException($"Agent {agentName} is not registered"); + } + 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); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfoAsync(filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agentName, id); var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); @@ -191,7 +222,7 @@ namespace slskd.Network } else { - throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agent}"); + throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agentName}"); } } finally @@ -201,32 +232,36 @@ namespace slskd.Network } /// - /// Retrieves an upload of the specified from the specified . + /// Retrieves an upload of the specified from the specified . /// - /// The agent from which to retrieve the file. + /// 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) + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agentName, 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 + // 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 + // 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(); + if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) + { + throw new NotFoundException($"Agent {agentName} is not registered"); + } + 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); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFileAsync(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(upload.Task, Task.Delay(timeout)); @@ -237,7 +272,7 @@ namespace slskd.Network } else { - throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agentName}"); } } finally @@ -247,90 +282,52 @@ namespace slskd.Network } /// - /// Retrieves a new share upload token for the specified . + /// Registers the specified name with 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; - } + /// The ID of the connection. + /// The agent. + public void RegisterAgent(ConnectionId connectionId, Agent agent) + => RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); /// - /// Attempts to retrieve the specified share upload . + /// Attempts to remove the registration for the specified . /// - /// 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) + /// The ID of the connection. + /// The registration record, if one was removed. + /// A value indicating whether a registration was removed. + public bool TryDeregisterAgent(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record) { - agent = null; - - if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agent)) + if (TryGetAgentRegistration(connectionId, out var found)) { - return true; + return RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); } + record = default; return false; } - /// - /// 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 retrieve the registration for the specified . /// /// The ID of the agent connection. - /// The agent, if registered. + /// The registration record, if one exists. /// 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 . - /// - /// 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) + public bool TryGetAgentRegistration(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record) { - var token = Cryptography.Random.GetBytes(16).ToBase62(); + var found = RegisteredAgentDictionary.Values.FirstOrDefault(v => v.ConnectionId == connectionId); + record = found; - // 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)); - Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); - return token; + return record != default; } /// /// Validates an authentication challenge response. /// /// The ID of the agent connection. - /// The agent name. + /// 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) + public bool TryValidateAuthenticationChallengeResponse(ConnectionId connectionId, string agentName, string challengeResponse) { if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(connectionId), out var challengeToken)) { @@ -338,9 +335,9 @@ namespace slskd.Network return false; } - if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agent, out var agentOptions)) + if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions)) { - Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agent); + Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agentName); return false; } @@ -351,20 +348,24 @@ namespace slskd.Network return expectedResponse == challengeResponse; } - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; - private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; - - private void Configure(Options options) + /// + /// 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 TryValidateShareUploadToken(Guid token, string agentName) { - SyncRoot.Wait(); - - try - { - } - finally + if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out var cachedAgentName) && (string)cachedAgentName == agentName) { - SyncRoot.Release(); + return true; } + + return false; } + + private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; + + private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; } -} +} \ No newline at end of file -- 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/NetworkService.cs') 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 d51563a445a264800e54af1857b2db776a982c1e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:41:20 -0500 Subject: refactor handling of file info --- src/slskd/Network/NetworkService.cs | 101 ++++++++++++++++++++---------------- 1 file changed, 56 insertions(+), 45 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 7719421f..4809ea50 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 @@ -32,11 +32,6 @@ namespace slskd.Network public interface INetworkService { - /// - /// Gets the collection of pending Agent file inquiries. - /// - ReadOnlyDictionary> PendingFileInquiries { get; } - /// /// Gets the collection of pending Agent file uploads. /// @@ -53,7 +48,7 @@ namespace slskd.Network /// 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(ConnectionId connectionId); + string GenerateAuthenticationChallengeToken(string connectionId); /// /// Retrieves a new share upload token for the specified . @@ -86,7 +81,15 @@ namespace slskd.Network /// /// The ID of the connection. /// The agent. - void RegisterAgent(ConnectionId connectionId, Agent agent); + void RegisterAgent(string connectionId, Agent agent); + + /// + /// 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); /// /// Attempts to remove the registration for the specified . @@ -94,7 +97,7 @@ namespace slskd.Network /// The connection ID associated with the registration. /// The registration record, if removed. /// A value indicating whether a registration was removed. - bool TryDeregisterAgent(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record); + bool TryDeregisterAgent(string connectionId, out (string ConnectionId, Agent Agent) record); /// /// Attempts to retrieve the registration for the specified . @@ -102,7 +105,7 @@ namespace slskd.Network /// The connection ID associated with the registration. /// The registration record, if found. /// A value indicating whether the registration exists. - bool TryGetAgentRegistration(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record); + bool TryGetAgentRegistration(string connectionId, out (string ConnectionId, Agent Agent) record); /// /// Validates an authentication challenge response. @@ -111,33 +114,30 @@ namespace slskd.Network /// The agent name. /// The challenge response provided by the agent. /// A value indicating whether the response is valid. - bool TryValidateAuthenticationChallengeResponse(ConnectionId connectionId, string agent, string challengeResponse); + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); /// /// Attempts to retrieve the specified share upload . /// /// The token. - /// The name of the agent attempting to use the token. + /// The name of the agent associated with the token. /// A value indicating whether the specified token exists. - bool TryValidateShareUploadToken(Guid token, string agentName); + bool TryValidateShareUploadToken(Guid token, out string agentName); } public class NetworkService : INetworkService { public NetworkService( + IWaiter waiter, IOptionsMonitor optionsMonitor, IHubContext networkHub) { + Waiter = waiter; NetworkHub = networkHub; OptionsMonitor = optionsMonitor; } - /// - /// Gets the collection of pending Agent file inquiries. - /// - public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); - /// /// Gets the collection of pending Agent uploads. /// @@ -148,14 +148,14 @@ namespace slskd.Network /// public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); - private SemaphoreSlim AgentSyncRoot { get; } = new SemaphoreSlim(1, 1); + private IWaiter Waiter { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); - private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); /// /// Generates a random authentication challenge token for the specified . @@ -163,7 +163,7 @@ namespace slskd.Network /// The token is cached internally, and is only valid while it remains in the cache. /// The ID of the agent connection. /// The generated token. - public string GenerateAuthenticationChallengeToken(ConnectionId connectionId) + public string GenerateAuthenticationChallengeToken(string connectionId) { var token = Cryptography.Random.GetBytes(32).ToBase62(); @@ -198,36 +198,47 @@ namespace slskd.Network /// 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) { - var id = Guid.NewGuid(); - var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); - if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { throw new NotFoundException($"Agent {agentName} is not registered"); } - PendingFileInquiryDictionary.TryAdd(id, tcs); + var id = Guid.NewGuid(); + var key = new WaitKey(nameof(GetFileInfo), agentName, id); + var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); try { - await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfoAsync(filename, id); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfo(filename, id); Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agentName, 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 {agentName}"); - } + return await wait; } - finally + catch (Exception ex) + { + Log.Error("Failed to fetch file information for {Filename} from Agent {Agent}: {Message}", filename, agentName, ex.Message); + throw; + } + } + + /// + /// 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) + { + var key = new WaitKey(nameof(GetFileInfo), agentName, id); + + if (!Waiter.ContainsKey(key)) { - PendingFileInquiryDictionary.TryRemove(id, out _); + Log.Warning("Agent {Agent} responded to a file info request with Id {Id}, but a response was not expected", agentName, id); + return; } + + 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); } /// @@ -285,7 +296,7 @@ namespace slskd.Network /// /// The ID of the connection. /// The agent. - public void RegisterAgent(ConnectionId connectionId, Agent agent) + public void RegisterAgent(string connectionId, Agent agent) => RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); /// @@ -294,7 +305,7 @@ namespace slskd.Network /// The ID of the connection. /// The registration record, if one was removed. /// A value indicating whether a registration was removed. - public bool TryDeregisterAgent(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record) + public bool TryDeregisterAgent(string connectionId, out (string ConnectionId, Agent Agent) record) { if (TryGetAgentRegistration(connectionId, out var found)) { @@ -311,7 +322,7 @@ namespace slskd.Network /// The ID of the agent connection. /// The registration record, if one exists. /// A value indicating whether the registration exists. - public bool TryGetAgentRegistration(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record) + public bool TryGetAgentRegistration(string connectionId, out (string ConnectionId, Agent Agent) record) { var found = RegisteredAgentDictionary.Values.FirstOrDefault(v => v.ConnectionId == connectionId); record = found; @@ -326,7 +337,7 @@ namespace slskd.Network /// The agent name. /// The challenge response provided by the agent. /// A value indicating whether the response is valid. - public bool TryValidateAuthenticationChallengeResponse(ConnectionId connectionId, string agentName, string challengeResponse) + public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse) { if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(connectionId), out var challengeToken)) { @@ -351,11 +362,11 @@ namespace slskd.Network /// Attempts to retrieve the specified share upload . /// /// The token. - /// The name of the agent attempting to use the token. + /// The name of the agent associated with the token. /// A value indicating whether the specified token exists. - public bool TryValidateShareUploadToken(Guid token, string agentName) + public bool TryValidateShareUploadToken(Guid token, out string agentName) { - if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out var cachedAgentName) && (string)cachedAgentName == agentName) + if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agentName)) { return true; } -- cgit v1.2.3 From 366bad03a8c21181edbb196f312a507ea59c60b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 10:09:29 -0500 Subject: fix bugs --- src/slskd/Network/API/Controllers/NetworkController.cs | 2 +- src/slskd/Network/NetworkService.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 21373749..d2170d45 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -97,7 +97,7 @@ namespace slskd.Network return BadRequest("Id is not a valid Guid"); } - if (!Network.TryGetShareUploadToken(guid, out var agent)) + if (!Network.TryValidateShareUploadToken(guid, out var agent)) { return Unauthorized(); } diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 4809ea50..682985b9 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -270,7 +270,7 @@ namespace slskd.Network try { - await NetworkHub.Clients.Client(record.ConnectionId).RequestFileAsync(filename, id); + 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(upload.Task, Task.Delay(timeout)); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 40718af7..2af3005a 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -137,7 +137,7 @@ namespace slskd.Transfers.Uploads } else { - var (exists, length) = await Network.GetFileInfo(agent: host, filename); + var (exists, length) = await Network.GetFileInfo(agentName: host, filename); if (!exists || length <= 0) { @@ -273,7 +273,7 @@ namespace slskd.Transfers.Uploads size: localFileLength, inputStreamFactory: async () => { - var (stream, completion) = await Network.GetFileUpload(agent: host, filename); + var (stream, completion) = await Network.GetFileUpload(agentName: host, filename); uploadCompletion = completion; return stream; }, -- cgit v1.2.3 From 1e27fdb2e5de7de63fdabcd2b36607658edd2bf7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 09:38:53 -0500 Subject: rename GetFileUpload to GetFile --- src/slskd/Network/NetworkService.cs | 12 ++++++------ src/slskd/Shares/ShareScanner.cs | 1 + src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 682985b9..8f25da5d 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -68,13 +68,13 @@ namespace slskd.Network Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000); /// - /// Retrieves an upload of the specified from the specified . + /// Retrieves a stream 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)> GetFileUpload(string agentName, string filename, int timeout = 3000); + Task<(Stream Stream, TaskCompletionSource Completion)> GetFile(string agentName, string filename, int timeout = 3000); /// /// Registers the specified with the specified . @@ -111,10 +111,10 @@ namespace slskd.Network /// Validates an authentication challenge response. /// /// The ID of the agent connection. - /// The agent name. + /// 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); + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse); /// /// Attempts to retrieve the specified share upload . @@ -242,13 +242,13 @@ namespace slskd.Network } /// - /// Retrieves an upload of the specified from the specified . + /// Retrieves a stream 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 agentName, string filename, int timeout = 3000) + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFile(string agentName, string filename, int timeout = 3000) { var id = Guid.NewGuid(); diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 7a174396..de765308 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -64,6 +64,7 @@ namespace slskd.Shares /// Initializes a new instance of the class. /// /// + /// /// public ShareScanner( int workerCount, diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 2af3005a..64a8f21e 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -273,7 +273,7 @@ namespace slskd.Transfers.Uploads size: localFileLength, inputStreamFactory: async () => { - var (stream, completion) = await Network.GetFileUpload(agentName: host, filename); + var (stream, completion) = await Network.GetFile(agentName: host, filename); uploadCompletion = completion; return stream; }, -- cgit v1.2.3 From 4196d2224a4024a26b9bfbf946197360aeab707b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 12:17:17 -0500 Subject: validate credentials for rest calls --- .../Network/API/Controllers/NetworkController.cs | 61 +++++++++---- src/slskd/Network/NetworkService.cs | 101 ++++++++++++++++----- 2 files changed, 122 insertions(+), 40 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index d2170d45..656178f0 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -52,13 +52,33 @@ namespace slskd.Network private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - [HttpPost("files/{id}")] + [HttpPost("files/{agentName}/{token}")] [Authorize] - public async Task UploadFile(string id) + public async Task UploadFile(string agentName, string token) { - if (!Guid.TryParse(id, out var guid)) + if (!Guid.TryParse(token, out var guid)) { - return BadRequest("Id is not a valid Guid"); + return BadRequest("Token is not a valid Guid"); + } + + string credential; + IFormFile file; + + try + { + credential = Request.Form["credential"].ToString(); + file = Request.Form.Files[0]; + } + catch (Exception ex) + { + Log.Warning("Failed to handle file upload from agent {Agent}: {Message}", agentName, ex.Message); + return BadRequest(); + } + + if (!Network.TryValidateFileUploadCredential(token: guid, agentName, credential)) + { + Log.Warning("Failed to authenticate file upload from caller claiming to be agent {Agent}", agentName); + return Unauthorized(); } // get the record for the waiting file @@ -88,44 +108,47 @@ namespace slskd.Network } } - [HttpPost("shares/{id}")] + [HttpPost("shares/{agentName}/{token}")] [Authorize] - public async Task UploadShares(string id) + public async Task UploadShares(string agentName, string token) { - if (!Guid.TryParse(id, out var guid)) - { - return BadRequest("Id is not a valid Guid"); - } - - if (!Network.TryValidateShareUploadToken(guid, out var agent)) + if (!Guid.TryParse(token, out var guid)) { - return Unauthorized(); + return BadRequest("Token is not a valid Guid"); } + string credential; IEnumerable shares; IFormFile database; try { + credential = Request.Form["credential"].ToString(); shares = Request.Form["shares"].ToString().FromJson>(); database = Request.Form.Files[0]; } catch (Exception ex) { - Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agent, ex.Message); + Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agentName, ex.Message); return BadRequest(); } - var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db"); + if (!Network.TryValidateShareUploadCredential(token: guid, agentName, credential)) + { + Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent}"); + return Unauthorized(); + } + + var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agentName}_{Path.GetRandomFileName()}.db"); - Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); + Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); - Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); + Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); var repository = ShareRepositoryFactory.CreateFromFile(temp); @@ -134,11 +157,11 @@ namespace slskd.Network return BadRequest("Invalid database: " + string.Join(", ", problems)); } - var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agentName); destinationRepository.RestoreFrom(repository); - Shares.AddOrUpdateHost(new Host(agent, shares)); + Shares.AddOrUpdateHost(new Host(agentName, shares)); return Ok(); } diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 8f25da5d..738ea7a5 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -117,12 +117,22 @@ namespace slskd.Network bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse); /// - /// Attempts to retrieve the specified share upload . + /// Attempts to validate the share upload response credential associated with the specified . /// /// The token. - /// The name of the agent associated with the token. - /// A value indicating whether the specified token exists. - bool TryValidateShareUploadToken(Guid token, out string agentName); + /// The name of the responding agent. + /// The response credential. + /// A value indicating whether the credential is valid. + bool TryValidateShareUploadCredential(Guid token, string agentName, string credential); + + /// + /// Attempts to validate the file upload response credential associated with the specified . + /// + /// The token. + /// The name of the responding agent. + /// The response credential. + /// A value indicating whether the credential is valid. + bool TryValidateFileUploadCredential(Guid token, string agentName, string credential); } public class NetworkService : INetworkService @@ -250,7 +260,17 @@ namespace slskd.Network /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFile(string agentName, string filename, int timeout = 3000) { - var id = Guid.NewGuid(); + if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) + { + throw new NotFoundException($"Agent {agentName} is not registered"); + } + + var token = Guid.NewGuid(); + var key = new WaitKey(nameof(GetFile), agentName, token); + var wait = Waiter.Wait(key, timeout); + + MemoryCache.Set(GetFileTokenCacheKey(token), agentName, TimeSpan.FromMinutes(1)); + Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName); // create a TCS for the upload stream. this is awaited below and completed in the API controller when the agent POSTs // the file @@ -261,17 +281,12 @@ namespace slskd.Network // complete in order to keep the stream open for the duration var completion = new TaskCompletionSource(); - if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) - { - throw new NotFoundException($"Agent {agentName} is not registered"); - } - - PendingFileUploadDictionary.TryAdd(id, (upload, completion)); + PendingFileUploadDictionary.TryAdd(token, (upload, completion)); try { - 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); + 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); var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); @@ -287,10 +302,24 @@ namespace slskd.Network } finally { - PendingFileUploadDictionary.TryRemove(id, out _); + PendingFileUploadDictionary.TryRemove(token, out _); } } + public void HandleGetFileResponse(string agentName, Guid id, Stream response) + { + var key = new WaitKey(nameof(GetFile), agentName, id); + + if (!Waiter.ContainsKey(key)) + { + Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); + return; + } + + Waiter.Complete(key, response); + Log.Information("Agent {Agent} responded to a file request with Id {Id}", agentName, id); + } + /// /// Registers the specified name with the specified . /// @@ -359,23 +388,53 @@ namespace slskd.Network } /// - /// Attempts to retrieve the specified share upload . + /// Attempts to validate the share upload response credential associated with the specified . /// /// The token. - /// The name of the agent associated with the token. - /// A value indicating whether the specified token exists. - public bool TryValidateShareUploadToken(Guid token, out string agentName) + /// The name of the responding agent. + /// The response credential. + /// A value indicating whether the credential is valid. + public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential) { - if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agentName)) + return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(token)); + } + + /// + /// Attempts to validate the file upload response credential associated with the specified . + /// + /// The token. + /// The name of the responding agent. + /// The response credential. + /// A value indicating whether the credential is valid. + public bool TryValidateFileUploadCredential(Guid token, string agentName, string credential) + { + return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); + } + + private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey) + { + bool valid = false; + + if (OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions) + && RegisteredAgentDictionary.TryGetValue(agentName, out _) + && MemoryCache.TryGetValue(cacheKey, out var cachedAgentName) + && (string)cachedAgentName == agentName) { - return true; + var key = agentOptions.Secret.FromBase62(); + var tokenBytes = token.ToString().FromBase62(); + var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62(); + + valid = expectedCredential == credential; } - return false; + // tokens can be used exactly once, pass or fail + MemoryCache.Remove(cacheKey); + return valid; } private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; + private string GetFileTokenCacheKey(Guid token) => $"{token}.file"; } } \ No newline at end of file -- cgit v1.2.3 From 066fb9b058450b0a01eac81150bf37bbf85f6205 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 12:52:58 -0500 Subject: make credential validation more debuggable, fix bug --- src/slskd/Network/NetworkService.cs | 52 +++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 13 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 738ea7a5..45da1967 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -396,7 +396,7 @@ namespace slskd.Network /// A value indicating whether the credential is valid. public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); } /// @@ -408,28 +408,54 @@ namespace slskd.Network /// A value indicating whether the credential is valid. public bool TryValidateFileUploadCredential(Guid token, string agentName, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(token)); } private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey) { - bool valid = false; - - if (OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions) - && RegisteredAgentDictionary.TryGetValue(agentName, out _) - && MemoryCache.TryGetValue(cacheKey, out var cachedAgentName) - && (string)cachedAgentName == agentName) + try { + if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions)) + { + Log.Debug("Validation failed: Agent {Agent} not configured", agentName); + return false; + } + + if (!RegisteredAgentDictionary.TryGetValue(agentName, out _)) + { + Log.Debug("Validation failed: Agent {Agent} not registered", agentName); + return false; + } + + if (!MemoryCache.TryGetValue(cacheKey, out var cachedAgentName)) + { + Log.Debug("Validation failed: Cache key {Key} not cached", cacheKey); + return false; + } + + if ((string)cachedAgentName != agentName) + { + Log.Debug("Validation failed: Cached agent {Cached} does not match supplied agent {Agent}", cachedAgentName, agentName); + return false; + } + var key = agentOptions.Secret.FromBase62(); var tokenBytes = token.ToString().FromBase62(); var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62(); - valid = expectedCredential == credential; - } + if (expectedCredential != credential) + { + Log.Debug("Validation failed: Supplied credential {Credential} does not match expected credential {Expected}", credential, expectedCredential); + return false; + } - // tokens can be used exactly once, pass or fail - MemoryCache.Remove(cacheKey); - return valid; + return true; + } + finally + { + // tokens can be used exactly once, pass or fail + MemoryCache.Remove(cacheKey); + } } private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; -- cgit v1.2.3 From 4b295fde2462dd72c3f7df9defb4ea3ddd3a754b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 12:58:25 -0500 Subject: verify filenames --- src/slskd/Network/API/Controllers/NetworkController.cs | 2 +- src/slskd/Network/NetworkService.cs | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 656178f0..cecaa39c 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -75,7 +75,7 @@ namespace slskd.Network return BadRequest(); } - if (!Network.TryValidateFileUploadCredential(token: guid, agentName, credential)) + if (!Network.TryValidateFileUploadCredential(token: guid, agentName, filename: file.FileName, credential)) { Log.Warning("Failed to authenticate file upload from caller claiming to be agent {Agent}", agentName); return Unauthorized(); diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 45da1967..845c284e 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -130,9 +130,10 @@ namespace slskd.Network /// /// The token. /// The name of the responding agent. + /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - bool TryValidateFileUploadCredential(Guid token, string agentName, string credential); + bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential); } public class NetworkService : INetworkService @@ -269,7 +270,7 @@ namespace slskd.Network var key = new WaitKey(nameof(GetFile), agentName, token); var wait = Waiter.Wait(key, timeout); - MemoryCache.Set(GetFileTokenCacheKey(token), agentName, TimeSpan.FromMinutes(1)); + MemoryCache.Set(GetFileTokenCacheKey(filename, token), agentName, TimeSpan.FromMinutes(1)); Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName); // create a TCS for the upload stream. this is awaited below and completed in the API controller when the agent POSTs @@ -404,11 +405,12 @@ namespace slskd.Network /// /// The token. /// The name of the responding agent. + /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - public bool TryValidateFileUploadCredential(Guid token, string agentName, string credential) + public bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(filename, token)); } private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey) @@ -461,6 +463,6 @@ namespace slskd.Network private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; - private string GetFileTokenCacheKey(Guid token) => $"{token}.file"; + private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; } } \ No newline at end of file -- cgit v1.2.3 From 653c05040acab0f7aff9a98cd959a0c54e05e300 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 18:28:43 -0500 Subject: refactor handling of streams --- src/slskd/Network/NetworkService.cs | 196 ++++++++++++++++++++---------------- 1 file changed, 108 insertions(+), 88 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 845c284e..747602fd 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -58,6 +58,15 @@ namespace slskd.Network /// The generated token. Guid GenerateShareUploadToken(string agentName); + /// + /// Retrieves a stream 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. + Task GetFileStream(string agentName, string filename, int timeout = 3000); + /// /// Retrieves information about the specified from the specified . /// @@ -68,13 +77,16 @@ namespace slskd.Network Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000); /// - /// Retrieves a stream of the specified from the specified . + /// Handles the client response for a request. /// - /// 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)> GetFile(string agentName, string filename, int timeout = 3000); + /// 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); + + Task HandleGetFileStreamResponse(string agentName, string filename, Guid id, Stream response); + + void HandleGetFileStreamCompletion(string agentName, string filename); /// /// Registers the specified with the specified . @@ -83,14 +95,6 @@ namespace slskd.Network /// The agent. void RegisterAgent(string connectionId, Agent agent); - /// - /// 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); - /// /// Attempts to remove the registration for the specified . /// @@ -117,23 +121,23 @@ namespace slskd.Network bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse); /// - /// Attempts to validate the share upload response credential associated with the specified . + /// Attempts to validate the file upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. + /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - bool TryValidateShareUploadCredential(Guid token, string agentName, string credential); + bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential); /// - /// Attempts to validate the file upload response credential associated with the specified . + /// Attempts to validate the share upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. - /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential); + bool TryValidateShareUploadCredential(Guid token, string agentName, string credential); } public class NetworkService : INetworkService @@ -159,7 +163,6 @@ namespace slskd.Network /// public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); - private IWaiter Waiter { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } @@ -167,6 +170,7 @@ namespace slskd.Network private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private IWaiter Waiter { get; } /// /// Generates a random authentication challenge token for the specified . @@ -200,6 +204,48 @@ namespace slskd.Network return token; } + /// + /// Retrieves a stream 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 GetFileStream(string agentName, string filename, 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); + + // 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 wait = Waiter.Wait(key, timeout); + + 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 + var stream = await wait; + return stream; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agentName}"); + } + } + /// /// Retrieves information about the specified from the specified . /// @@ -253,72 +299,45 @@ namespace slskd.Network } /// - /// Retrieves a stream of the specified from the specified . + /// Handles the client response for a request, returning when the corresponding file upload is complete. /// - /// 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)> GetFile(string agentName, string filename, int timeout = 3000) + /// 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) { - if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) + var streamKey = new WaitKey(nameof(GetFileStream), agentName, filename, id); + + if (!Waiter.ContainsKey(streamKey)) { - throw new NotFoundException($"Agent {agentName} is not registered"); + Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); + return; } - var token = Guid.NewGuid(); - var key = new WaitKey(nameof(GetFile), agentName, token); - var wait = Waiter.Wait(key, timeout); - - MemoryCache.Set(GetFileTokenCacheKey(filename, token), agentName, TimeSpan.FromMinutes(1)); - Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName); - - // 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 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 completion = Waiter.WaitIndefinitely(completionKey); - // 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(token, (upload, completion)); - - try - { - 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); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + // 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); - 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 {agentName}"); - } - } - finally - { - PendingFileUploadDictionary.TryRemove(token, out _); - } + // wait for the caller of GetFileStream to report that the upload/stream is complete + await completion; } - public void HandleGetFileResponse(string agentName, Guid id, Stream response) + public void HandleGetFileStreamCompletion(string agentName, string filename) { - var key = new WaitKey(nameof(GetFile), agentName, id); - - if (!Waiter.ContainsKey(key)) - { - Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); - return; - } - - Waiter.Complete(key, response); - Log.Information("Agent {Agent} responded to a file request with Id {Id}", agentName, id); + // 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); + Waiter.Complete(key); } /// @@ -389,30 +408,36 @@ namespace slskd.Network } /// - /// Attempts to validate the share upload response credential associated with the specified . + /// Attempts to validate the file upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. + /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential) + public bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(filename, token)); } /// - /// Attempts to validate the file upload response credential associated with the specified . + /// Attempts to validate the share upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. - /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - public bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential) + public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(filename, token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); } + private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; + + private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; + + private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; + private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey) { try @@ -459,10 +484,5 @@ namespace slskd.Network MemoryCache.Remove(cacheKey); } } - - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; - - private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; - private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; } } \ No newline at end of file -- cgit v1.2.3 From 913821a6c012b287603230b2dc93191b9f7cfdc9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 18:36:04 -0500 Subject: add more logs --- src/slskd/Network/NetworkService.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 747602fd..265e5526 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -237,6 +237,7 @@ namespace slskd.Network 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); var stream = await wait; return stream; } @@ -338,6 +339,7 @@ namespace slskd.Network // will complete. var key = new WaitKey(nameof(GetFileStream), "completion", agentName, filename); Waiter.Complete(key); + Log.Information("Upload of {File} from agent {Agent} reported as completed", filename, agentName); } /// -- cgit v1.2.3 From 8d0c182748158a5a954ad9efc1f237c63eafb681 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:37:31 -0500 Subject: add LocalHostName --- src/slskd/Network/NetworkService.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 265e5526..792be99c 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -37,6 +37,11 @@ namespace slskd.Network /// ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } + /// + /// Gets the name of the local host. + /// + string LocalHostName { get; } + /// /// Gets the collection of registered Agents. /// @@ -163,6 +168,11 @@ namespace slskd.Network /// public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); + /// + /// Gets the name of the local host. + /// + public string LocalHostName => "local"; + private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } -- 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/NetworkService.cs') 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/NetworkService.cs') 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 5493a29466b808b3faaeeec5cb8d16584961fc86 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 25 Oct 2022 09:42:34 -0500 Subject: more cleanup and docs --- .../Network/API/Controllers/NetworkController.cs | 15 +- src/slskd/Network/NetworkService.cs | 320 +++++++++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 4 +- 3 files changed, 218 insertions(+), 121 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index e30d984c..4cd6437a 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -20,6 +20,7 @@ namespace slskd.Network using System; using System.Collections.Generic; using System.IO; + using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -65,7 +66,10 @@ namespace slskd.Network return BadRequest("Token is not a valid Guid"); } - // todo: make sure agent is registered and return unauthorized if not + if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) + { + return Unauthorized(); + } if (!Request.HasFormContentType || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader) @@ -86,6 +90,7 @@ namespace slskd.Network { var reader = new MultipartReader(HeaderUtilities.RemoveQuotes(mediaTypeHeader.Boundary).Value, Request.Body); + // the multipart response contains two sections; a credential, and the file var credentialSection = await reader.ReadNextSectionAsync(); using var sr = new StreamReader(credentialSection.Body); credential = sr.ReadToEnd(); @@ -101,7 +106,11 @@ namespace slskd.Network return BadRequest(); } - if (!Network.TryValidateFileUploadCredential(token: guid, agentName, filename, credential)) + // agents must encrypt the Id they were given in the request with the secret they share with the controller, and provide + // the encrypted value as the credential with the request. the validation below verifies a bunch of things, including that + // the encrypted value matches the expected value. the goal here is to ensure that the caller is the same caller that + // received the request, and that the caller knows the shared secret. + if (!Network.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", agentName); return Unauthorized(); @@ -111,7 +120,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. + // it will complete when the upload is complete, one way or the other. await Network.HandleFileStreamResponse(id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index b36bfb89..dffc305d 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -24,12 +24,16 @@ 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; using Serilog; using slskd.Cryptography; + /// + /// Handles network (controller/agent) interactions. + /// public interface INetworkService { /// @@ -58,30 +62,6 @@ namespace slskd.Network /// The generated token. Guid GenerateShareUploadToken(string agentName); - /// - /// Retrieves a stream of the specified from the specified . - /// - /// 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 GetFileStreamAsync(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 NotifyFileStreamException(Guid id, Exception exception); - /// /// Retrieves information about the specified from the specified . /// @@ -91,6 +71,50 @@ namespace slskd.Network /// A value indicating whether the file exists, and the length in bytes. Task<(bool Exists, long Length)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000); + /// + /// Retrieves a stream of the specified from the specified . + /// + /// + /// + /// This is the first step in a multi-step workflow that enables proxying of file uploads through agents. The + /// entire sequence is: + /// + /// + /// + /// Upload service calls and awaits , which requests the file from the remote + /// agent, and waits for the stream to be returned before returning it to the caller. + /// + /// + /// + /// The remote agent makes an HTTP POST request containing a multipart upload including the file, and the + /// API controller invokes and awaits . The stream is passed from + /// this method back to the awaited , and the Upload service passes the + /// stream to Soulseek.NET, streaming the data from the still-open HTTP request through to the remote + /// Soulseek user. + /// + /// + /// If the remote agent can't find or open the requested file, it invokes + /// through the open SignalR connection, and + /// throws with the given exception. If the remote agent fails to respond + /// within the timeout period, throws a . + /// + /// + /// + /// When the Upload is complete (successfully or otherwise), the Upload service invokes + /// , passing an optional if the transfer was not + /// successful. This call signals the waiting to complete, passing + /// control back to the API controller and completing the HTTP POST request from the agent. + /// + /// + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// A unique ID for the stream. + /// An optional timeout value. + /// An optional token to monitor for cancellation requests. + /// The operation context, including a stream containing the requested file. + Task GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000, CancellationToken cancellationToken = default); + /// /// Handles the client response for a request. /// @@ -100,13 +124,28 @@ namespace slskd.Network 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 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. + /// + /// The unique ID for the stream. + /// The remote exception that caused the failure. + void NotifyFileStreamException(Guid id, Exception exception); + /// /// Registers the specified with the specified . /// @@ -114,6 +153,13 @@ namespace slskd.Network /// The agent. void RegisterAgent(string connectionId, Agent agent); + /// + /// 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); + /// /// Attempts to remove the registration for the specified . /// @@ -140,14 +186,14 @@ namespace slskd.Network bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse); /// - /// Attempts to validate the file upload response credential associated with the specified . + /// Attempts to validate the file stream response credential associated with the specified . /// /// The token. /// The name of the responding agent. /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential); + bool TryValidateFileStreamResponseCredential(Guid token, string agentName, string filename, string credential); /// /// Attempts to validate the share upload response credential associated with the specified . @@ -159,6 +205,9 @@ namespace slskd.Network bool TryValidateShareUploadCredential(Guid token, string agentName, string credential); } + /// + /// Handles network (controller/agent) interactions. + /// public class NetworkService : INetworkService { public NetworkService( @@ -173,23 +222,23 @@ namespace slskd.Network } /// - /// Gets the collection of registered Agents. + /// Gets the name of the local host. /// - public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); + public string LocalHostName => "local"; /// - /// Gets the name of the local host. + /// Gets the collection of registered Agents. /// - public string LocalHostName => "local"; + public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); - private ConcurrentDictionary WaitIdDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private IWaiter Waiter { get; } + private ConcurrentDictionary WaitIdDictionary { get; } = new(); /// /// Generates a random authentication challenge token for the specified . @@ -223,35 +272,102 @@ namespace slskd.Network return token; } + /// + /// 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)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000) + { + if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) + { + throw new NotFoundException($"Agent {agentName} is not registered"); + } + + var id = Guid.NewGuid(); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); + var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); + + try + { + await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfo(filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agentName, id); + + return await wait; + } + catch (Exception ex) + { + Log.Error("Failed to fetch file information for {Filename} from Agent {Agent}: {Message}", filename, agentName, ex.Message); + throw; + } + } + /// /// Retrieves a stream of the specified from the specified . /// + /// + /// + /// This is the first step in a multi-step workflow that enables proxying of file uploads through agents. The + /// entire sequence is: + /// + /// + /// + /// Upload service calls and awaits , which requests the file from the remote + /// agent, and waits for the stream to be returned before returning it to the caller. + /// + /// + /// + /// The remote agent makes an HTTP POST request containing a multipart upload including the file, and the + /// API controller invokes and awaits . The stream is passed from + /// this method back to the awaited , and the Upload service passes the + /// stream to Soulseek.NET, streaming the data from the still-open HTTP request through to the remote + /// Soulseek user. + /// + /// + /// If the remote agent can't find or open the requested file, it invokes + /// through the open SignalR connection, and + /// throws with the given exception. If the remote agent fails to respond + /// within the timeout period, throws a . + /// + /// + /// + /// When the Upload is complete (successfully or otherwise), the Upload service invokes + /// , passing an optional if the transfer was not + /// successful. This call signals the waiting to complete, passing + /// control back to the API controller and completing the HTTP POST request from the agent. + /// + /// + /// /// 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 GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000) + /// An optional token to monitor for cancellation requests. + /// The operation context, including a stream containing the requested file. + public async Task GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000, CancellationToken cancellationToken = default) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { throw new NotFoundException($"Agent {agentName} is not registered"); } - // 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 + // 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); - // 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 + // create a wait for the agent response. this wait will be completed in the response handler, ultimately called from + // the API controller when the agent makes an HTTP request to return the file var key = new WaitKey(nameof(GetFileStreamAsync), id); - var wait = Waiter.Wait(key, timeout); + var wait = Waiter.Wait(key, timeout, cancellationToken); 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)); + var task = await Task.WhenAny(wait, Task.Delay(timeout, cancellationToken)); if (task == wait) { @@ -266,67 +382,6 @@ 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 NotifyFileStreamException(Guid id, Exception exception) - { - var key = new WaitKey(nameof(GetFileStreamAsync), 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(HandleFileStreamResponse), id); - - if (exception != default) - { - Waiter.Throw(key, exception); - return; - } - - Waiter.Complete(key); - } - - /// - /// 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)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000) - { - if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) - { - throw new NotFoundException($"Agent {agentName} is not registered"); - } - - var id = Guid.NewGuid(); - var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); - var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); - - try - { - await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfo(filename, id); - Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agentName, id); - - return await wait; - } - catch (Exception ex) - { - Log.Error("Failed to fetch file information for {Filename} from Agent {Agent}: {Message}", filename, agentName, ex.Message); - throw; - } - } - /// /// Handles the client response for a request. /// @@ -348,8 +403,12 @@ 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. /// + /// + /// Assumes has previously been used to ensure the Id and agent match. + /// /// The ID of the request. /// The client response to the request. /// The operation context. @@ -359,35 +418,46 @@ namespace slskd.Network if (!Waiter.IsWaitingFor(streamKey)) { - Log.Warning("A file stream response matching Id {Id} is not expected", id); - return; + var msg = $"A file stream response matching Id {id} is not expected"; + Log.Warning(msg); + throw new NotFoundException(msg); } - // 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. + // create a wait (but do not await it) for the completion of the upload to the remote client. we need to await this to + // keep execution in the body of the API controller that provided the stream, in order to keep the stream open for the + // duration of the remote transfer. omit the id from the key, the caller doesn't know it. var completionKey = new WaitKey(nameof(HandleFileStreamResponse), id); var 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 + // 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); - // wait for the caller of GetFileStream to report that the upload/stream is complete - // this is the wait that keeps the HTTP handler running + // 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; } 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. + // 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. + /// + /// The unique ID for the stream. + /// The remote exception that caused the failure. + public void NotifyFileStreamException(Guid id, Exception exception) + { + var key = new WaitKey(nameof(GetFileStreamAsync), id); + Waiter.Throw(key, exception); + } + /// /// Registers the specified name with the specified . /// @@ -396,6 +466,24 @@ namespace slskd.Network public void RegisterAgent(string connectionId, Agent agent) => RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); + /// + /// 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(HandleFileStreamResponse), id); + + if (exception != default) + { + Waiter.Throw(key, exception); + return; + } + + Waiter.Complete(key); + } + /// /// Attempts to remove the registration for the specified . /// @@ -456,14 +544,14 @@ namespace slskd.Network } /// - /// Attempts to validate the file upload response credential associated with the specified . + /// Attempts to validate the file stream response credential associated with the specified . /// /// The token. /// The name of the responding agent. /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - public bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential) + public bool TryValidateFileStreamResponseCredential(Guid token, string agentName, string filename, string credential) { return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(filename, token)); } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 7c5bab0b..3dd80292 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -251,7 +251,7 @@ namespace slskd.Transfers.Uploads slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); - if (host == Network.LocalHostName) + if (host == Network.LocalHostName + "!") { var completedTransfer = await Client.UploadAsync( username, @@ -269,7 +269,7 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStreamAsync(agentName: host, filename, id), + inputStreamFactory: () => Network.GetFileStreamAsync(agentName: "vdesktop", 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/NetworkService.cs') 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/NetworkService.cs') 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