From 595a91654b9b8c7ea9fa564b52769b39cc95d69e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 19 Oct 2022 23:34:14 -0500 Subject: wip --- src/slskd/Network/API/Hubs/NetworkHub.cs | 41 ++++++++++++++++++-------------- src/slskd/Program.cs | 16 +++++++++---- 2 files changed, 34 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index f79fecf2..cf1dc463 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -28,32 +28,37 @@ namespace slskd.Network public static readonly string RequestFile = "REQUEST_FILE"; public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; - public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; - public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; } - /// - /// Extension methods for the network SignalR hub. - /// - public static class NetworkHubExtensions - { - public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) - { - // todo: how to send this to the specified agent? - return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); - } + ///// + ///// Extension methods for the network SignalR hub. + ///// + //public static class NetworkHubExtensions + //{ + // public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) + // { + // // todo: how to send this to the specified agent? + // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); + // } - public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) - { - return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); - } + // public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) + // { + // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + // } + //} + + public interface INetworkHub + { + Task RequestFile(string filename, Guid id); + Task RequestFileInfo(string filename, Guid id); + Task AuthenticationChallenge(string token); } /// /// The network SignalR hub. /// [Authorize] - public class NetworkHub : Hub + public class NetworkHub : Hub { public NetworkHub( INetworkService networkService) @@ -67,7 +72,7 @@ namespace slskd.Network public override async Task OnConnectedAsync() { Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); - await Clients.Caller.SendAsync(NetworkHubMethods.AuthenticationChallenge, Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + await Clients.Caller.AuthenticationChallenge(Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); } public override Task OnDisconnectedAsync(Exception exception) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b9d43992..e7ec4f74 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -685,11 +685,17 @@ namespace slskd options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; }); - services.AddSignalR().AddJsonProtocol(options => - { - options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter()); - options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - }); + services + .AddSignalR(options => + { + // https://github.com/SignalR/SignalR/issues/1149#issuecomment-973887222 + options.MaximumParallelInvocationsPerClient = 2; + }) + .AddJsonProtocol(options => + { + options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter()); + options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); services.AddHealthChecks(); -- cgit v1.2.3 From 04b545a1077837d01b0eded9478173de48504eaf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 20 Oct 2022 10:07:02 -0500 Subject: add Network types --- src/slskd/Network/Types/Agent.cs | 28 ++++++++++++++++++++++++++++ src/slskd/Network/Types/ConnectionId.cs | 28 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/slskd/Network/Types/Agent.cs create mode 100644 src/slskd/Network/Types/ConnectionId.cs (limited to 'src') diff --git a/src/slskd/Network/Types/Agent.cs b/src/slskd/Network/Types/Agent.cs new file mode 100644 index 00000000..999243c6 --- /dev/null +++ b/src/slskd/Network/Types/Agent.cs @@ -0,0 +1,28 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Network +{ + using System; + + public record Agent + { + public string Name { get; init; } + public string IPAddress { get; init; } + public DateTime ConnectedAt { get; init; } = DateTime.UtcNow; + } +} diff --git a/src/slskd/Network/Types/ConnectionId.cs b/src/slskd/Network/Types/ConnectionId.cs new file mode 100644 index 00000000..9dee0313 --- /dev/null +++ b/src/slskd/Network/Types/ConnectionId.cs @@ -0,0 +1,28 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Network +{ + public record ConnectionId + { + public string Id { get; init; } + + public static implicit operator ConnectionId(string id) => new ConnectionId(id); + public static implicit operator string(ConnectionId connectionId) => connectionId.Id; + public override string ToString() => Id; + } +} \ No newline at end of file -- cgit v1.2.3 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') 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 481d2029d7cadcf5b1985fa912a263d88f2f2cf3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 20 Oct 2022 19:28:33 -0500 Subject: use strongly typed hub --- src/slskd/Network/API/Hubs/NetworkHub.cs | 58 ++++++++++++-------------------- 1 file changed, 21 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index cf1dc463..0013423a 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -20,38 +20,15 @@ namespace slskd.Network using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; using Serilog; - public static class NetworkHubMethods - { - public static readonly string RequestFile = "REQUEST_FILE"; - public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; - public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; - } - - ///// - ///// Extension methods for the network SignalR hub. - ///// - //public static class NetworkHubExtensions - //{ - // public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) - // { - // // todo: how to send this to the specified agent? - // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); - // } - - // public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) - // { - // return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); - // } - //} - public interface INetworkHub { - Task RequestFile(string filename, Guid id); - Task RequestFileInfo(string filename, Guid id); - Task AuthenticationChallenge(string token); + Task Challenge(string token); + Task RequestFileAsync(string filename, Guid id); + Task RequestFileInfoAsync(string filename, Guid id); } /// @@ -71,15 +48,17 @@ namespace slskd.Network public override async Task OnConnectedAsync() { - Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); - await Clients.Caller.AuthenticationChallenge(Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + var token = Network.GenerateAuthenticationChallengeToken(Context.ConnectionId); + + Log.Information("Agent connection {Id} established. Sending authentication challenge {Token}...", Context.ConnectionId, token); + await Clients.Caller.Challenge(token); } public override Task OnDisconnectedAsync(Exception exception) { - if (Network.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) + if (Network.TryDeregisterAgent(Context.ConnectionId, out var record)) { - Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); + Log.Warning("Agent {Agent} (connection {Id}) disconnected", record.Agent.Name, Context.ConnectionId); } return Task.CompletedTask; @@ -89,25 +68,30 @@ namespace slskd.Network { if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) { - Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); - Network.RegisterAgent(Context.ConnectionId, agent); + var remoteIp = Context.Features.Get().RemoteIpAddress.ToString(); + var record = new Agent { Name = agent, ConnectedAt = DateTime.UtcNow, IPAddress = remoteIp }; + + Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); + Network.RegisterAgent(Context.ConnectionId, record); return true; } Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); - Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! + Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! return false; } public Guid GetShareUploadToken() { - if (Network.TryGetAgentRegistration(Context.ConnectionId, out var agent)) + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - return Network.GetShareUploadToken(agent); + var token = Network.GenerateShareUploadToken(record.Agent.Name); + Log.Information("Agent {Agent} (connection {Id}) requested share upload token {Token}", record.Agent.Name, record.ConnectionId, token); + return token; } // this can happen if the agent attempts to upload before logging in - Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); + Log.Information("Agent connection {Id} requested a share upload token, but is not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } -- cgit v1.2.3 From 37736ef3ec612736c3eeaa5c988b26ed3b3a54e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:34:39 -0500 Subject: fix misplaced class --- .../Common/Authentication/ApiKeyAuthentication.cs | 43 +++++++++++----------- 1 file changed, 21 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index d11e00fb..9225b5a8 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -27,7 +27,6 @@ namespace slskd.Authentication using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using NetTools; - using static slskd.Authentication.ApiKeyAuthenticationHandler; /// /// API key authentication. @@ -118,33 +117,33 @@ namespace slskd.Authentication return AuthenticateResult.Success(ticket); } + } + /// + /// API key authentication options. + /// + public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions + { /// - /// API key authentication options. + /// Initializes a new instance of the class. /// - public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions + public ApiKeyAuthenticationOptions() { - /// - /// Initializes a new instance of the class. - /// - public ApiKeyAuthenticationOptions() - { - } + } - /// - /// Gets or sets the route prefix used to identify SignalR authentication attempts. - /// - public string SignalRRoutePrefix { get; set; } + /// + /// Gets or sets the route prefix used to identify SignalR authentication attempts. + /// + public string SignalRRoutePrefix { get; set; } - /// - /// Gets or sets a value indicating whether to support SignalR authentication. - /// - public bool EnableSignalRSupport { get; set; } + /// + /// Gets or sets a value indicating whether to support SignalR authentication. + /// + public bool EnableSignalRSupport { get; set; } - /// - /// Gets or sets the role for authenticated tickets. - /// - public Role Role { get; set; } = Role.Administrator; - } + /// + /// Gets or sets the role for authenticated tickets. + /// + public Role Role { get; set; } = Role.Administrator; } } -- cgit v1.2.3 From d74709e583994d8a4f5505546eba688293acbd18 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:34:47 -0500 Subject: add Waiter --- src/slskd/Common/WaitKey.cs | 106 ++++++++++ src/slskd/Common/Waiter.cs | 462 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 568 insertions(+) create mode 100644 src/slskd/Common/WaitKey.cs create mode 100644 src/slskd/Common/Waiter.cs (limited to 'src') diff --git a/src/slskd/Common/WaitKey.cs b/src/slskd/Common/WaitKey.cs new file mode 100644 index 00000000..302064db --- /dev/null +++ b/src/slskd/Common/WaitKey.cs @@ -0,0 +1,106 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + + /// + /// Uniquely identifies a Wait. + /// + public sealed class WaitKey : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// The parts which make up the key. + public WaitKey(params object[] tokenParts) + { + TokenParts = tokenParts; + Token = string.Join(":", TokenParts); + } + + /// + /// Gets the wait token. + /// + public string Token { get; } + + /// + /// Gets the parts which make up the key. + /// + public object[] TokenParts { get; } + + public static bool operator !=(WaitKey lhs, WaitKey rhs) + { + return !lhs.Equals(rhs); + } + + public static bool operator ==(WaitKey lhs, WaitKey rhs) + { + return lhs.Equals(rhs); + } + + /// + /// Compares the specified to this instance. + /// + /// The object to which to compare. + /// A value indicating whether the specified object is equal to this instance. + public override bool Equals(object obj) + { + try + { + return Equals((WaitKey)obj); + } + catch (InvalidCastException) + { + return false; + } + } + + /// + /// Compares the specified WaitKey to this instance. + /// + /// The WaitKey to which to compare. + /// A value indicating whether the specified WaitKey is equal to this instance. + public bool Equals(WaitKey other) + { + return Token == other.Token; + } + + /// + /// Returns the hash code of this instance. + /// + /// The hash code of this instance. + public override int GetHashCode() + { +#if NETSTANDARD2_0 + return string.IsNullOrEmpty(Token) ? 0 : Token.GetHashCode(); +#else + return string.IsNullOrEmpty(Token) ? 0 : Token.GetHashCode(StringComparison.InvariantCulture); +#endif + } + + /// + /// Returns the string representation of the key. + /// + /// The string representation of the key. + public override string ToString() + { + return Token; + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Waiter.cs b/src/slskd/Common/Waiter.cs new file mode 100644 index 00000000..0c9cca98 --- /dev/null +++ b/src/slskd/Common/Waiter.cs @@ -0,0 +1,462 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Collections.Concurrent; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Enables arbitrary await-able things. + /// + public interface IWaiter : IDisposable + { + /// + /// Gets the default timeout duration. + /// + int DefaultTimeout { get; } + + /// + /// Cancels the oldest wait matching the specified . + /// + /// The unique WaitKey for the wait. + void Cancel(WaitKey key); + + /// + /// Cancels all waits. + /// + void CancelAll(); + + /// + /// Completes the oldest wait matching the specified with the specified . + /// + /// The wait result type. + /// The unique WaitKey for the wait. + /// The wait result. + void Complete(WaitKey key, T result); + + /// + /// Completes the oldest wait matching the specified . + /// + /// The unique WaitKey for the wait. + void Complete(WaitKey key); + + /// + /// Returns a value indicating whether the specified is being waited upon. + /// + /// The unique WaitKey to check. + /// A value indicating whether the specified key is being waited upon. + bool ContainsKey(WaitKey key); + + /// + /// Throws the specified on the oldest wait matching the specified . + /// + /// The unique WaitKey for the wait. + /// The Exception to throw. + void Throw(WaitKey key, Exception exception); + + /// + /// Causes the oldest wait matching the specified to time out. + /// + /// The unique WaitKey for the wait. + void Timeout(WaitKey key); + + /// + /// Adds a new wait for the specified and with the specified . + /// + /// The wait result type. + /// A unique WaitKey for the wait. + /// The wait timeout. + /// The cancellation token for the wait. + /// A Task representing the wait. + Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null); + + /// + /// Adds a new wait for the specified and with the specified . + /// + /// A unique WaitKey for the wait. + /// The wait timeout. + /// The cancellation token for the wait. + /// A Task representing the wait. + Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null); + + /// + /// Adds a new wait for the specified which does not time out. + /// + /// The wait result type. + /// A unique WaitKey for the wait. + /// The cancellation token for the wait. + /// A Task representing the wait. + Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null); + + /// + /// Adds a new wait for the specified which does not time out. + /// + /// A unique WaitKey for the wait. + /// The cancellation token for the wait. + /// A Task representing the wait. + Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null); + } + + /// + /// Enables arbitrary await-able things. + /// + public sealed class Waiter : IWaiter + { + private const int DefaultTimeoutValue = 5000; + + /// + /// Initializes a new instance of the class with the default timeout. + /// + public Waiter() + : this(DefaultTimeoutValue) + { + } + + /// + /// Initializes a new instance of the class with the specified . + /// + /// The default timeout duration for message waits. + public Waiter(int defaultTimeout) + { + DefaultTimeout = defaultTimeout; + } + + /// + /// Gets the default timeout duration, in milliseconds. + /// + public int DefaultTimeout { get; private set; } + + private bool Disposed { get; set; } + private ConcurrentDictionary Locks { get; } = new ConcurrentDictionary(); + private ConcurrentDictionary> Waits { get; } = new ConcurrentDictionary>(); + + /// + /// Cancels the oldest wait matching the specified . + /// + /// The unique WaitKey for the wait. + public void Cancel(WaitKey key) + { + Disposition(key, wait => + wait.TaskCompletionSource.TrySetCanceled()); + } + + /// + /// Cancels all waits. + /// + public void CancelAll() + { + var keys = Waits.Keys.ToList(); + + foreach (var key in keys) + { + Cancel(key); + } + } + + /// + /// Completes the oldest wait matching the specified with the specified . + /// + /// The wait result type. + /// The unique WaitKey for the wait. + /// The wait result. + public void Complete(WaitKey key, T result) + { + Disposition(key, wait => + ((TaskCompletionSource)wait.TaskCompletionSource).TrySetResult(result)); + } + + /// + /// Completes the oldest wait matching the specified . + /// + /// The unique WaitKey for the wait. + public void Complete(WaitKey key) + { + Complete(key, null); + } + + /// + /// Returns a value indicating whether the specified is being waited upon. + /// + /// The unique WaitKey to check. + /// A value indicating whether the specified key is being waited upon. + public bool ContainsKey(WaitKey key) + => Waits.ContainsKey(key); + + /// + /// Disposes this instance. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Disposes this instance. + /// + /// A value indicating whether disposal is in progress. + public void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + CancelAll(); + } + + Disposed = true; + } + } + + /// + /// Throws the specified on the oldest wait matching the specified . + /// + /// The unique WaitKey for the wait. + /// The Exception to throw. + public void Throw(WaitKey key, Exception exception) + { + Disposition(key, wait => + wait.TaskCompletionSource.TrySetException(exception)); + } + + /// + /// Causes the oldest wait matching the specified to time out. + /// + /// The unique WaitKey for the wait. + public void Timeout(WaitKey key) + { + Disposition(key, wait => + wait.TaskCompletionSource.TrySetException(new TimeoutException($"The wait timed out after {wait.Timeout} milliseconds"))); + } + + /// + /// Adds a new wait for the specified and with the specified . + /// + /// A unique WaitKey for the wait. + /// The wait timeout, in milliseconds. + /// The cancellation token for the wait. + /// A Task representing the wait. + public Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null) + { + return Wait(key, timeout, cancellationToken); + } + + /// + /// Adds a new wait for the specified and with the specified . + /// + /// The wait result type. + /// A unique WaitKey for the wait. + /// The wait timeout, in milliseconds. + /// The cancellation token for the wait. + /// A Task representing the wait. + public Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null) + { + timeout ??= DefaultTimeout; + cancellationToken ??= CancellationToken.None; + + var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var wait = new PendingWait( + taskCompletionSource, + timeout.Value, + cancelAction: () => Cancel(key), + timeoutAction: () => Timeout(key), + cancellationToken.Value); + + // obtain a read lock for the key. this is necessary to prevent this code from adding a wait to the ConcurrentQueue + // while the containing dictionary entry is being cleaned up in Disposition(), effectively discarding the new wait. + var recordLock = Locks.GetOrAdd(key, new ReaderWriterLockSlim()); + + recordLock.EnterReadLock(); + + try + { + Waits.AddOrUpdate(key, new ConcurrentQueue(new[] { wait }), (_, queue) => + { + queue.Enqueue(wait); + return queue; + }); + } + finally + { + recordLock.ExitReadLock(); + } + + // defer registration to prevent the wait from being dispositioned prior to being successfully queued this is a + // concern if we are given a timeout of 0, or a cancellation token which is already cancelled + wait.Register(); + return ((TaskCompletionSource)wait.TaskCompletionSource).Task; + } + + /// + /// Adds a new wait for the specified which does not time out. + /// + /// A unique WaitKey for the wait. + /// The cancellation token for the wait. + /// A Task representing the wait. + public Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null) + { + return WaitIndefinitely(key, cancellationToken); + } + + /// + /// Adds a new wait for the specified which does not time out. + /// + /// The wait result type. + /// A unique WaitKey for the wait. + /// The cancellation token for the wait. + /// A Task representing the wait. + public Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null) + { + return Wait(key, int.MaxValue, cancellationToken); + } + + private void Disposition(WaitKey key, Action action) + { + if (Waits.TryGetValue(key, out var queue) && queue.TryDequeue(out var wait)) + { + action(wait); + wait.Dispose(); + + if (Locks.TryGetValue(key, out var recordLock)) + { + // enter a read lock first; TryPeek and TryDequeue are atomic so there's no risky operation until later. + recordLock.EnterUpgradeableReadLock(); + + try + { + // clean up entries in the Waits and Locks dictionaries if the corresponding ConcurrentQueue is empty. + // this is tricky, because we don't want to remove a record if another thread is in the process of + // enqueueing a new wait. + if (queue.IsEmpty) + { + // enter the write lock to prevent Wait() (which obtains a read lock) from enqueing any more waits + // before we can delete the dictionary record. it's ok and expected that Wait() might add this record + // back to the dictionary as soon as this unblocks; we're preventing new waits from being discarded if + // they are added by another thread just prior to the TryRemove() operation below. + recordLock.EnterWriteLock(); + + try + { + // check the queue again to ensure Wait() didn't enqueue anything between the last check and when + // we entered the write lock. this is guarateed to be safe since we now have exclusive access to + // the record and it should be impossible to remove a record containing a non-empty queue + if (queue.IsEmpty) + { + Waits.TryRemove(key, out _); + Locks.TryRemove(key, out _); + } + } + finally + { + recordLock.ExitWriteLock(); + } + } + } + finally + { + recordLock.ExitUpgradeableReadLock(); + } + } + } + } + + /// + /// The composite value for the wait dictionary. + /// + internal class PendingWait : IDisposable + { + /// + /// Initializes a new instance of the class. + /// + /// The task completion source for the wait task. + /// The number of milliseconds after which the wait is to time out. + /// The action to invoke when the task is cancelled. + /// The action to invoke when the task times out. + /// The cancellation token for the wait. + public PendingWait(dynamic taskCompletionSource, int timeout, Action cancelAction, Action timeoutAction, CancellationToken cancellationToken) + { + TaskCompletionSource = taskCompletionSource; + Timeout = timeout; + CancelAction = cancelAction; + TimeoutAction = timeoutAction; + CancellationToken = cancellationToken; + } + + /// + /// Gets the task completion source for the wait task. + /// + public dynamic TaskCompletionSource { get; } + + /// + /// Gets the number of milliseconds after which the wait is to time out. + /// + public int Timeout { get; } + + private Action CancelAction { get; set; } + private CancellationToken CancellationToken { get; set; } + private CancellationTokenRegistration CancellationTokenRegistration { get; set; } + private bool Disposed { get; set; } + private Action TimeoutAction { get; set; } + private CancellationTokenRegistration TimeoutTokenRegistration { get; set; } + private CancellationTokenSource TimeoutTokenSource { get; set; } + + /// + /// Releases the managed and unmanaged resources used by the . + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Register cancellation and timeout actions. + /// + public void Register() + { + CancellationTokenRegistration = CancellationToken.Register(() => CancelAction()); + + TimeoutTokenSource = new CancellationTokenSource(Timeout); + TimeoutTokenRegistration = TimeoutTokenSource.Token.Register(() => TimeoutAction()); + } + + /// + /// Releases the managed and unmanaged resources used by the . + /// + /// A value indicating whether the object is being disposed. + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + CancellationTokenRegistration.Dispose(); + TimeoutTokenSource.Dispose(); + TimeoutTokenRegistration.Dispose(); + } + + Disposed = true; + } + } + } + } +} \ No newline at end of file -- cgit v1.2.3 From 731520d504f7a016ecdf71aafdc7f133613ad236 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:35:42 -0500 Subject: remove ConnectionId --- src/slskd/Network/Types/ConnectionId.cs | 28 ---------------------------- 1 file changed, 28 deletions(-) delete mode 100644 src/slskd/Network/Types/ConnectionId.cs (limited to 'src') diff --git a/src/slskd/Network/Types/ConnectionId.cs b/src/slskd/Network/Types/ConnectionId.cs deleted file mode 100644 index 9dee0313..00000000 --- a/src/slskd/Network/Types/ConnectionId.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Network -{ - public record ConnectionId - { - public string Id { get; init; } - - public static implicit operator ConnectionId(string id) => new ConnectionId(id); - public static implicit operator string(ConnectionId connectionId) => connectionId.Id; - public override string ToString() => Id; - } -} \ No newline at end of file -- cgit v1.2.3 From 6ff9cfb3cb27f149c473850d02fdb51937ca2056 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:36:18 -0500 Subject: handle correct names --- src/slskd/Network/NetworkClient.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index a231dad2..1c2515d2 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -318,9 +318,9 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); - HubConnection.On(NetworkHubMethods.RequestFileInfo, HandleFileInfoRequest); - HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + HubConnection.On(nameof(INetworkHub.RequestFile), HandleFileRequest); + HubConnection.On(nameof(INetworkHub.RequestFileInfo), HandleFileInfoRequest); + HubConnection.On(nameof(INetworkHub.Challenge), HandleAuthenticationChallenge); LastOptionsHash = optionsHash; -- 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') 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') 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') 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') 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 1d927e49a93ad24ba6dbc91f30f185212775ff30 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 12:13:04 -0500 Subject: update routes, provide credentials in rest calls --- src/slskd/Network/NetworkClient.cs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 1c2515d2..6a2a374d 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -134,9 +134,10 @@ namespace slskd.Network var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(ComputeCredential(token)), "credential" }, { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, { new StreamContent(stream), "database", "shares" }, }; @@ -154,9 +155,19 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private async Task HandleFileRequest(string filename, Guid id) + private string ComputeCredential(Guid token) { - Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); + var options = OptionsMonitor.CurrentValue; + + var key = options.Network.Controller.Secret.FromBase62(); + var tokenBytes = token.ToString().FromBase62(); + + return Aes.Encrypt(tokenBytes, key).ToBase62(); + } + + private async Task HandleFileRequest(string filename, Guid token) + { + Log.Information("Network controller requested file {Filename} with ID {Id}", filename, token); try { @@ -171,15 +182,16 @@ namespace slskd.Network } using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{id}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(ComputeCredential(token)), "credential" }, { new StreamContent(stream), "file", filename }, }; request.Content = content; - Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); var response = await CreateHttpClient().SendAsync(request); if (!response.IsSuccessStatusCode) @@ -196,7 +208,7 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), id); + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), token); } } -- 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') 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') 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') 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 6ecaee7f09f8861cd281d81e97c160dadb041021 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 18:28:06 -0500 Subject: report the upload completion separately --- src/slskd/Transfers/Uploads/UploadService.cs | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 64a8f21e..75184564 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -265,22 +265,16 @@ namespace slskd.Transfers.Uploads } else { - TaskCompletionSource uploadCompletion = default; - var completedTransfer = await Client.UploadAsync( username, filename, size: localFileLength, - inputStreamFactory: async () => - { - var (stream, completion) = await Network.GetFile(agentName: host, filename); - uploadCompletion = completion; - return stream; - }, + inputStreamFactory: () => Network.GetFileStream(agentName: host, filename), options: topts, cancellationToken: cts.Token); - uploadCompletion.SetResult(); + Network.HandleGetFileStreamCompletion(agentName: host, filename); + transfer = transfer.WithSoulseekTransfer(completedTransfer); } -- cgit v1.2.3 From 9921a9c17e6c09e04bb3370332b4ade1956b682c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 18:28:26 -0500 Subject: simplify stream handling --- .../Network/API/Controllers/NetworkController.cs | 32 ++++++---------------- 1 file changed, 9 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index cecaa39c..3ae2a6b5 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -81,31 +81,17 @@ namespace slskd.Network return Unauthorized(); } - // get the record for the waiting file - if (Network.PendingFileUploads.TryGetValue(guid, out var record)) - { - // get the stream from the multipart upload - var stream = Request.Form.Files.First().OpenReadStream(); - - // set the result for the stream - // this should pass control to the transfer service along with - // the stream - record.Stream.SetResult(stream); + // get the stream from the multipart upload + var stream = Request.Form.Files.First().OpenReadStream(); - Console.WriteLine("Stream handed off. Waiting for completion..."); + // 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(agentName, filename: file.FileName, id: guid, stream); - // wait for the transfer service to set the completion result - await record.Completion.Task; - - stream.Dispose(); - Console.WriteLine("Upload complete"); - return Ok(); - } - else - { - Log.Warning("Agent"); - return NotFound(); - } + stream.Dispose(); + Console.WriteLine("Upload complete"); + return Ok(); } [HttpPost("shares/{agentName}/{token}")] -- 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') 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') 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 a60490c61a0a035ebb67108da4be38b3c7568681 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 00:23:09 -0500 Subject: wip --- .../DisableFormValueModelBindingAttribute.cs | 39 +++++++++++++ src/slskd/Common/MultipartRequestHelper.cs | 53 +++++++++++++++++ .../Network/API/Controllers/NetworkController.cs | 67 +++++++++++++++++++--- src/slskd/Transfers/Uploads/UploadService.cs | 4 +- 4 files changed, 153 insertions(+), 10 deletions(-) create mode 100644 src/slskd/Common/DisableFormValueModelBindingAttribute.cs create mode 100644 src/slskd/Common/MultipartRequestHelper.cs (limited to 'src') diff --git a/src/slskd/Common/DisableFormValueModelBindingAttribute.cs b/src/slskd/Common/DisableFormValueModelBindingAttribute.cs new file mode 100644 index 00000000..a16b9347 --- /dev/null +++ b/src/slskd/Common/DisableFormValueModelBindingAttribute.cs @@ -0,0 +1,39 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using Microsoft.AspNetCore.Mvc.Filters; + using Microsoft.AspNetCore.Mvc.ModelBinding; + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter + { + public void OnResourceExecuting(ResourceExecutingContext context) + { + var factories = context.ValueProviderFactories; + factories.RemoveType(); + factories.RemoveType(); + factories.RemoveType(); + } + + public void OnResourceExecuted(ResourceExecutedContext context) + { + } + } +} diff --git a/src/slskd/Common/MultipartRequestHelper.cs b/src/slskd/Common/MultipartRequestHelper.cs new file mode 100644 index 00000000..f4c89055 --- /dev/null +++ b/src/slskd/Common/MultipartRequestHelper.cs @@ -0,0 +1,53 @@ +using Microsoft.Net.Http.Headers; +using System.IO; +using System; + +namespace slskd +{ + public static class MultipartRequestHelper + { + // Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq" + // The spec at https://tools.ietf.org/html/rfc2046#section-5.1 states that 70 characters is a reasonable limit. + public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit = 70) + { + var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary).Value; + + if (string.IsNullOrWhiteSpace(boundary)) + { + throw new InvalidDataException("Missing content-type boundary."); + } + + if (boundary.Length > lengthLimit) + { + throw new InvalidDataException( + $"Multipart boundary length limit {lengthLimit} exceeded."); + } + + return boundary; + } + + public static bool IsMultipartContentType(string contentType) + { + return !string.IsNullOrEmpty(contentType) + && contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0; + } + + public static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition) + { + // Content-Disposition: form-data; name="key"; + return contentDisposition != null + && contentDisposition.DispositionType.Equals("form-data") + && string.IsNullOrEmpty(contentDisposition.FileName.Value) + && string.IsNullOrEmpty(contentDisposition.FileNameStar.Value); + } + + public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition) + { + // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg" + return contentDisposition != null + && contentDisposition.DispositionType.Equals("form-data") + && (!string.IsNullOrEmpty(contentDisposition.FileName.Value) + || !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value)); + } + } +} diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 3ae2a6b5..20c2caa0 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -25,6 +25,8 @@ namespace slskd.Network using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.WebUtilities; + using Microsoft.Net.Http.Headers; using Serilog; using slskd.Shares; @@ -53,6 +55,9 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); [HttpPost("files/{agentName}/{token}")] + [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] + [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] + [DisableFormValueModelBinding] [Authorize] public async Task UploadFile(string agentName, string token) { @@ -61,13 +66,23 @@ namespace slskd.Network return BadRequest("Token is not a valid Guid"); } - string credential; - IFormFile file; + string credential = default; + Stream stream = default; + string filename = default; try { - credential = Request.Form["credential"].ToString(); - file = Request.Form.Files[0]; + var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType)); + var reader = new MultipartReader(boundary, Request.Body); + + var credentialSection = await reader.ReadNextSectionAsync(); + using var sr = new StreamReader(credentialSection.Body); + credential = sr.ReadToEnd(); + + var fileSection = await reader.ReadNextSectionAsync(); + ContentDispositionHeaderValue.TryParse(fileSection.ContentDisposition, out var contentDisposition); + filename = contentDisposition.FileName.Value; + stream = fileSection.Body; } catch (Exception ex) { @@ -75,25 +90,61 @@ namespace slskd.Network return BadRequest(); } - if (!Network.TryValidateFileUploadCredential(token: guid, agentName, filename: file.FileName, credential)) + if (!Network.TryValidateFileUploadCredential(token: guid, agentName, filename, credential)) { Log.Warning("Failed to authenticate file upload from caller claiming to be agent {Agent}", agentName); return Unauthorized(); } - // get the stream from the multipart upload - var stream = Request.Form.Files.First().OpenReadStream(); + Console.WriteLine($"credential: {credential}, filename: {filename}, stream pos {stream.Position} len {stream.Length}"); + + Console.WriteLine("Opening request stream..."); + + Console.WriteLine("Stream open. calling handler..."); // 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(agentName, filename: file.FileName, id: guid, stream); + await Network.HandleGetFileStreamResponse(agentName, filename, id: guid, stream); stream.Dispose(); Console.WriteLine("Upload complete"); return Ok(); } + //[DisableFormValueModelBinding] + //[RequestSizeLimit(MaxFileSize)] + //[RequestFormLimits(MultipartBodyLengthLimit = MaxFileSize)] + //public async Task ReceiveFile() + //{ + // if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) + // throw new BadRequestException("Not a multipart request"); + + // var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType)); + // var reader = new MultipartReader(boundary, Request.Body); + + // // note: this is for a single file, you could also process multiple files + // var section = await reader.ReadNextSectionAsync(); + + // if (section == null) + // throw new BadRequestException("No sections in multipart defined"); + + // if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition)) + // throw new BadRequestException("No content disposition in multipart defined"); + + // var fileName = contentDisposition.FileNameStar.ToString(); + // if (string.IsNullOrEmpty(fileName)) + // { + // fileName = contentDisposition.FileName.ToString(); + // } + + // if (string.IsNullOrEmpty(fileName)) + // throw new BadRequestException("No filename defined."); + + // using var fileStream = section.Body; + // await SendFileSomewhere(fileStream); + //} + [HttpPost("shares/{agentName}/{token}")] [Authorize] public async Task UploadShares(string agentName, string token) diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 75184564..a368dc73 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 == "local") + if (host == "locassssl") { var completedTransfer = await Client.UploadAsync( username, @@ -269,7 +269,7 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStream(agentName: host, filename), + inputStreamFactory: () => Network.GetFileStream(agentName: "vdesktop", filename), options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From 5211113da3d95863645cc2925be5d2d64c38101b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 12:21:51 -0500 Subject: refactor stream handling --- .../Network/API/Controllers/NetworkController.cs | 77 +++++++++++++++------- src/slskd/Transfers/Uploads/UploadService.cs | 4 +- 2 files changed, 55 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 3ae2a6b5..1ee311a7 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -25,6 +25,8 @@ namespace slskd.Network using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.WebUtilities; + using Microsoft.Net.Http.Headers; using Serilog; using slskd.Shares; @@ -61,37 +63,64 @@ namespace slskd.Network return BadRequest("Token is not a valid Guid"); } - string credential; - IFormFile file; + // todo: make sure agent is registered and return unauthorized if not - try + if (!HttpContext.Request.HasFormContentType + || !MediaTypeHeaderValue.TryParse(HttpContext.Request.ContentType, out var mediaTypeHeader) + || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) { - credential = Request.Form["credential"].ToString(); - file = Request.Form.Files[0]; + return new UnsupportedMediaTypeResult(); } - catch (Exception ex) + + Log.Debug("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + + string credential = default; + Stream stream = default; + string filename = default; + + try { - Log.Warning("Failed to handle file upload from agent {Agent}: {Message}", agentName, ex.Message); - return BadRequest(); + try + { + var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, Request.Body); + + // the first section contains the credentail + var section = await reader.ReadNextSectionAsync(); + using var sectionReader = new StreamReader(section.Body); + credential = sectionReader.ReadToEnd(); + + // the second section contains the file + section = await reader.ReadNextSectionAsync(); + var contentDisposition = ContentDispositionHeaderValue.Parse(section.ContentDisposition); + filename = contentDisposition.FileName.Value; + stream = section.Body; + } + catch (Exception ex) + { + Log.Warning("Failed to handle file upload for token {Token} from a caller claiming to be agent {Agent}: {Message}", token, agentName, ex.Message); + return BadRequest(); + } + + if (!Network.TryValidateFileUploadCredential(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(); + } + + Log.Information("File upload of {Filename} ({Token}) from agent {Agent} validated and authenticated. Forwarding file stream.", filename, token, agentName); + + // 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(agentName, filename, id: guid, stream); + + Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); + return Ok(); } - - if (!Network.TryValidateFileUploadCredential(token: guid, agentName, filename: file.FileName, credential)) + finally { - Log.Warning("Failed to authenticate file upload from caller claiming to be agent {Agent}", agentName); - return Unauthorized(); + stream?.Dispose(); } - - // get the stream from the multipart upload - var stream = Request.Form.Files.First().OpenReadStream(); - - // 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(agentName, filename: file.FileName, id: guid, stream); - - stream.Dispose(); - Console.WriteLine("Upload complete"); - return Ok(); } [HttpPost("shares/{agentName}/{token}")] diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 75184564..a368dc73 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 == "local") + if (host == "locassssl") { var completedTransfer = await Client.UploadAsync( username, @@ -269,7 +269,7 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStream(agentName: host, filename), + inputStreamFactory: () => Network.GetFileStream(agentName: "vdesktop", filename), options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From 4243b00598a859b7ff2d95a8d1908c1fb1b379ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:17:54 -0500 Subject: display SourceContext when debugging --- src/slskd/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 197032db..c6557083 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -883,11 +883,11 @@ namespace slskd .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( - outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), -- cgit v1.2.3 From 41e9549b155956c3d5a76366ea342e6650cdbc65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:18:16 -0500 Subject: clean up upload helper boilerplate --- .../DisableFormValueModelBindingAttribute.cs | 39 ---------------- .../DisableFormValueModelBindingAttribute.cs | 28 ++++++++++++ src/slskd/Common/MultipartRequestHelper.cs | 53 ---------------------- 3 files changed, 28 insertions(+), 92 deletions(-) delete mode 100644 src/slskd/Common/DisableFormValueModelBindingAttribute.cs create mode 100644 src/slskd/Common/Middleware/DisableFormValueModelBindingAttribute.cs delete mode 100644 src/slskd/Common/MultipartRequestHelper.cs (limited to 'src') diff --git a/src/slskd/Common/DisableFormValueModelBindingAttribute.cs b/src/slskd/Common/DisableFormValueModelBindingAttribute.cs deleted file mode 100644 index a16b9347..00000000 --- a/src/slskd/Common/DisableFormValueModelBindingAttribute.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using Microsoft.AspNetCore.Mvc.Filters; - using Microsoft.AspNetCore.Mvc.ModelBinding; - - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] - public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter - { - public void OnResourceExecuting(ResourceExecutingContext context) - { - var factories = context.ValueProviderFactories; - factories.RemoveType(); - factories.RemoveType(); - factories.RemoveType(); - } - - public void OnResourceExecuted(ResourceExecutedContext context) - { - } - } -} diff --git a/src/slskd/Common/Middleware/DisableFormValueModelBindingAttribute.cs b/src/slskd/Common/Middleware/DisableFormValueModelBindingAttribute.cs new file mode 100644 index 00000000..5f7cef49 --- /dev/null +++ b/src/slskd/Common/Middleware/DisableFormValueModelBindingAttribute.cs @@ -0,0 +1,28 @@ +// https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0 +// -- suppress analysis + +namespace slskd +{ + using System; + using Microsoft.AspNetCore.Mvc.Filters; + using Microsoft.AspNetCore.Mvc.ModelBinding; + + /// + /// Disables form value model binding for decorated controllers and endpoints. This prevents buffering when processing multipart upload requests. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter + { + public void OnResourceExecuting(ResourceExecutingContext context) + { + var factories = context.ValueProviderFactories; + factories.RemoveType(); + factories.RemoveType(); + factories.RemoveType(); + } + + public void OnResourceExecuted(ResourceExecutedContext context) + { + } + } +} diff --git a/src/slskd/Common/MultipartRequestHelper.cs b/src/slskd/Common/MultipartRequestHelper.cs deleted file mode 100644 index f4c89055..00000000 --- a/src/slskd/Common/MultipartRequestHelper.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Microsoft.Net.Http.Headers; -using System.IO; -using System; - -namespace slskd -{ - public static class MultipartRequestHelper - { - // Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq" - // The spec at https://tools.ietf.org/html/rfc2046#section-5.1 states that 70 characters is a reasonable limit. - public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit = 70) - { - var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary).Value; - - if (string.IsNullOrWhiteSpace(boundary)) - { - throw new InvalidDataException("Missing content-type boundary."); - } - - if (boundary.Length > lengthLimit) - { - throw new InvalidDataException( - $"Multipart boundary length limit {lengthLimit} exceeded."); - } - - return boundary; - } - - public static bool IsMultipartContentType(string contentType) - { - return !string.IsNullOrEmpty(contentType) - && contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0; - } - - public static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition) - { - // Content-Disposition: form-data; name="key"; - return contentDisposition != null - && contentDisposition.DispositionType.Equals("form-data") - && string.IsNullOrEmpty(contentDisposition.FileName.Value) - && string.IsNullOrEmpty(contentDisposition.FileNameStar.Value); - } - - public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition) - { - // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg" - return contentDisposition != null - && contentDisposition.DispositionType.Equals("form-data") - && (!string.IsNullOrEmpty(contentDisposition.FileName.Value) - || !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value)); - } - } -} -- cgit v1.2.3 From b41c5ad220a9beae7e5625830f89c09483e56a2c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:21:48 -0500 Subject: remove test code, magic string --- src/slskd/Transfers/Uploads/UploadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index a368dc73..f7131e54 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 == "locassssl") + if (host == Network.LocalHostName) { var completedTransfer = await Client.UploadAsync( username, @@ -269,7 +269,7 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStream(agentName: "vdesktop", filename), + inputStreamFactory: () => Network.GetFileStream(agentName: host, filename), options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From dbca62ae931f9a0e9082c274bfbe9c4c76048cff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:36:40 -0500 Subject: fix boundary calculation --- .../Network/API/Controllers/NetworkController.cs | 56 ++++------------------ 1 file changed, 10 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 5d3f4c77..e7426035 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -20,7 +20,6 @@ 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; @@ -68,14 +67,14 @@ namespace slskd.Network // todo: make sure agent is registered and return unauthorized if not - if (!HttpContext.Request.HasFormContentType - || !MediaTypeHeaderValue.TryParse(HttpContext.Request.ContentType, out var mediaTypeHeader) + if (!Request.HasFormContentType + || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader) || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) { return new UnsupportedMediaTypeResult(); } - Log.Debug("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); string credential = default; Stream stream = default; @@ -85,18 +84,16 @@ namespace slskd.Network { try { - var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, Request.Body); + var reader = new MultipartReader(HeaderUtilities.RemoveQuotes(mediaTypeHeader.Boundary).Value, Request.Body); - // the first section contains the credentail - var section = await reader.ReadNextSectionAsync(); - using var sectionReader = new StreamReader(section.Body); - credential = sectionReader.ReadToEnd(); + var credentialSection = await reader.ReadNextSectionAsync(); + using var sr = new StreamReader(credentialSection.Body); + credential = sr.ReadToEnd(); - // the second section contains the file - section = await reader.ReadNextSectionAsync(); - var contentDisposition = ContentDispositionHeaderValue.Parse(section.ContentDisposition); + var fileSection = await reader.ReadNextSectionAsync(); + var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); filename = contentDisposition.FileName.Value; - stream = section.Body; + stream = fileSection.Body; } catch (Exception ex) { @@ -126,39 +123,6 @@ namespace slskd.Network } } - //[DisableFormValueModelBinding] - //[RequestSizeLimit(MaxFileSize)] - //[RequestFormLimits(MultipartBodyLengthLimit = MaxFileSize)] - //public async Task ReceiveFile() - //{ - // if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) - // throw new BadRequestException("Not a multipart request"); - - // var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType)); - // var reader = new MultipartReader(boundary, Request.Body); - - // // note: this is for a single file, you could also process multiple files - // var section = await reader.ReadNextSectionAsync(); - - // if (section == null) - // throw new BadRequestException("No sections in multipart defined"); - - // if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition)) - // throw new BadRequestException("No content disposition in multipart defined"); - - // var fileName = contentDisposition.FileNameStar.ToString(); - // if (string.IsNullOrEmpty(fileName)) - // { - // fileName = contentDisposition.FileName.ToString(); - // } - - // if (string.IsNullOrEmpty(fileName)) - // throw new BadRequestException("No filename defined."); - - // using var fileStream = section.Body; - // await SendFileSomewhere(fileStream); - //} - [HttpPost("shares/{agentName}/{token}")] [Authorize] public async Task UploadShares(string agentName, string token) -- 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') 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 92fab4ce25ad8b23fc14f946490d05d8d1da9c4c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:55:15 -0500 Subject: run uploads as a separate task --- src/slskd/Network/NetworkClient.cs | 71 ++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 6a2a374d..5d8ab100 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -165,51 +165,56 @@ namespace slskd.Network return Aes.Encrypt(tokenBytes, key).ToBase62(); } - private async Task HandleFileRequest(string filename, Guid token) + private Task HandleFileRequest(string filename, Guid token) { - Log.Information("Network controller requested file {Filename} with ID {Id}", filename, token); - - try + _ = Task.Run(async () => { - var (_, localFilename) = await Shares.ResolveFileAsync(filename); - - var localFileInfo = new FileInfo(localFilename); + Log.Information("Network controller requested file {Filename} with ID {Id}", filename, token); - if (!localFileInfo.Exists) + try { - Shares.RequestScan(); - throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); - } + var (_, localFilename) = await Shares.ResolveFileAsync(filename); - using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); - using var content = new MultipartFormDataContent - { - { new StringContent(ComputeCredential(token)), "credential" }, - { new StreamContent(stream), "file", filename }, - }; + var localFileInfo = new FileInfo(localFilename); - request.Content = content; + if (!localFileInfo.Exists) + { + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + } - Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); - var response = await CreateHttpClient().SendAsync(request); + using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var content = new MultipartFormDataContent + { + { new StringContent(ComputeCredential(token)), "credential" }, + { new StreamContent(stream), "file", filename }, + }; - if (!response.IsSuccessStatusCode) - { - Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); + var response = await CreateHttpClient().SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + } + else + { + Log.Information("Upload of file {Filename} with ID {Id} succeeded.", filename); + } } - else + catch (Exception ex) { - Log.Information("Upload of file {Filename} with ID {Id} succeeded.", filename); + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + + // report the failure to the controller. this avoids a failure due to timeout. + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), token); } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + }); - // report the failure to the controller. this avoids a failure due to timeout. - await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), token); - } + return Task.CompletedTask; } private async Task HandleFileInfoRequest(string filename, Guid id) -- cgit v1.2.3 From d762b5fe648219648581948544cd67542b838342 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Oct 2022 13:55:52 -0500 Subject: add todo --- src/slskd/Transfers/Uploads/UploadService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index f7131e54..01263e19 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -274,6 +274,7 @@ namespace slskd.Transfers.Uploads cancellationToken: cts.Token); Network.HandleGetFileStreamCompletion(agentName: host, filename); + // todo: how to report a failure? the http request will stick open if we dont! transfer = transfer.WithSoulseekTransfer(completedTransfer); } -- cgit v1.2.3 From 5891ce219ac0d89decd3de0dd29ec79b4c77da8e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 10:22:49 -0500 Subject: rename ContainsKey to IsWaitingFor --- src/slskd/Common/Waiter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Waiter.cs b/src/slskd/Common/Waiter.cs index 0c9cca98..58fbcb83 100644 --- a/src/slskd/Common/Waiter.cs +++ b/src/slskd/Common/Waiter.cs @@ -63,7 +63,7 @@ namespace slskd /// /// The unique WaitKey to check. /// A value indicating whether the specified key is being waited upon. - bool ContainsKey(WaitKey key); + bool IsWaitingFor(WaitKey key); /// /// Throws the specified on the oldest wait matching the specified . @@ -197,7 +197,7 @@ namespace slskd /// /// The unique WaitKey to check. /// A value indicating whether the specified key is being waited upon. - public bool ContainsKey(WaitKey key) + public bool IsWaitingFor(WaitKey key) => Waits.ContainsKey(key); /// -- cgit v1.2.3 From 85a03d7bceaa2991291e5faa81a0c869576e324f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 18:17:46 -0500 Subject: close remote stream after transfer --- src/slskd/Transfers/Uploads/UploadService.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 01263e19..d3e8b89e 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 @@ -269,12 +269,11 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStream(agentName: host, filename), + inputStreamFactory: () => Network.GetFileStream(agentName: host, filename, id), options: topts, cancellationToken: cts.Token); - Network.HandleGetFileStreamCompletion(agentName: host, filename); - // todo: how to report a failure? the http request will stick open if we dont! + Network.TryCloseFileStream(id); transfer = transfer.WithSoulseekTransfer(completedTransfer); } @@ -295,6 +294,8 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); + Network.TryCloseFileStream(id, ex); + throw; } catch (Exception ex) @@ -308,6 +309,7 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); + Network.TryCloseFileStream(id, ex); throw; } finally -- cgit v1.2.3 From cfa9d92ce34092e1afe2549de8977fc890c47991 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 18:18:07 -0500 Subject: use only id for stream --- src/slskd/Network/API/Controllers/NetworkController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index e7426035..b1a71f34 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(agentName, filename, id: guid, stream); + await Network.HandleGetFileStreamResponse(id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); -- 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') 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') 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') 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') 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') 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