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