From 4871bdf439421514a53c7b3f111838cfb63ed664 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Oct 2022 18:09:05 -0500 Subject: clean up and tweak --- .../Network/API/Controllers/NetworkController.cs | 118 +++++++++++++-------- src/slskd/Network/NetworkClient.cs | 47 ++++++-- src/slskd/Network/NetworkService.cs | 3 +- 3 files changed, 118 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 624d7a2c..6ecb0005 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -39,36 +39,29 @@ namespace slskd.Network public class NetworkController : ControllerBase { public NetworkController( - INetworkService networkService, - IShareService shareService, - IShareRepositoryFactory shareRepositoryFactory) + INetworkService networkService) { Network = networkService; - Shares = shareService; - - ShareRepositoryFactory = shareRepositoryFactory; } - private IShareRepositoryFactory ShareRepositoryFactory { get; } - private IShareService Shares { get; } - private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private INetworkService Network { get; } - [HttpPost("files/{agentName}/{token}")] + /// + /// Uploads a file. + /// + /// The unique identifier for the request. + /// + [HttpPost("files/{token}")] [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] [DisableFormValueModelBinding] [Authorize] - public async Task UploadFile(string agentName, string token) + public async Task UploadFile(string token) { if (!Guid.TryParse(token, out var guid)) { - return BadRequest("Token is not a valid Guid"); - } - - if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) - { - return Unauthorized(); + return BadRequest("Token is not in a valid format"); } if (!Request.HasFormContentType @@ -78,8 +71,7 @@ namespace slskd.Network return new UnsupportedMediaTypeResult(); } - Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); - + string agentName = default; string credential = default; Stream stream = default; string filename = default; @@ -90,10 +82,14 @@ 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 + // the multipart response contains two sections; the name of the agent, the upload credential, and the file + var agentNameSection = await reader.ReadNextSectionAsync(); + using var sra = new StreamReader(agentNameSection.Body); + agentName = sra.ReadToEnd(); + var credentialSection = await reader.ReadNextSectionAsync(); - using var sr = new StreamReader(credentialSection.Body); - credential = sr.ReadToEnd(); + using var src = new StreamReader(credentialSection.Body); + credential = src.ReadToEnd(); var fileSection = await reader.ReadNextSectionAsync(); var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); @@ -106,10 +102,17 @@ namespace slskd.Network return BadRequest(); } - // 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.RegisteredAgents.Any(a => a.Name == agentName)) + { + return Unauthorized(); + } + + Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + + // 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); @@ -118,9 +121,8 @@ namespace slskd.Network 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, one way or the other. + // 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, one way or the other. await Network.HandleFileStreamResponse(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); @@ -128,25 +130,39 @@ namespace slskd.Network } finally { - stream?.Dispose(); + stream?.TryDispose(); } } - [HttpPost("shares/{agentName}/{token}")] + /// + /// Uploads share information. + /// + /// The unique identifier for the request. + /// + [HttpPost("shares/{token}")] [Authorize] - public async Task UploadShares(string agentName, string token) + public async Task UploadShares(string token) { if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not a valid Guid"); } - string credential; + if (!Request.HasFormContentType + || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader) + || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) + { + return new UnsupportedMediaTypeResult(); + } + + string agentName = default; + string credential = default; IEnumerable shares; IFormFile database; try { + agentName = Request.Form["agent"].ToString(); credential = Request.Form["credential"].ToString(); shares = Request.Form["shares"].ToString().FromJson>(); database = Request.Form.Files[0]; @@ -157,6 +173,11 @@ namespace slskd.Network return BadRequest(); } + if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) + { + return Unauthorized(); + } + if (!Network.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent}"); @@ -165,25 +186,36 @@ namespace slskd.Network var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agentName}_{Path.GetRandomFileName()}.db"); - Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); + try + { + 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(); + using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); + using var inputStream = database.OpenReadStream(); - await inputStream.CopyToAsync(outputStream); + await inputStream.CopyToAsync(outputStream); - Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); + Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); - try - { await Network.HandleShareUpload(agentName, id: guid, shares, temp); + + return Ok(); } catch (ShareValidationException ex) { return BadRequest(ex.Message); } - - return Ok(); + finally + { + try + { + System.IO.File.Delete(temp); + } + catch (Exception ex) + { + Log.Debug(ex, "Failed to remove temporary share upload file: {Message}", ex.Message); + } + } } } -} +} \ No newline at end of file diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 49f483fc..dfb53f86 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -29,14 +29,37 @@ namespace slskd.Network using slskd.Cryptography; using slskd.Shares; + /// + /// Network client (agent). + /// public interface INetworkClient { + /// + /// Starts the client and connects to the controller. + /// + /// + /// Task StartAsync(CancellationToken cancellationToken = default); + + /// + /// Stops the client and disconnects from the controller. + /// + /// + /// Task StopAsync(CancellationToken cancellationToken = default); } + /// + /// Network client (agent). + /// public class NetworkClient : INetworkClient { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// public NetworkClient( IShareService shareService, IOptionsMonitor optionsMonitor, @@ -63,6 +86,11 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); private TaskCompletionSource LoggedIn { get; set; } + /// + /// Starts the client and connects to the controller. + /// + /// + /// public async Task StartAsync(CancellationToken cancellationToken = default) { if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) @@ -106,6 +134,11 @@ namespace slskd.Network Log.Information("Shares uploaded. Ready to upload files."); } + /// + /// Stops the client and disconnects from the controller. + /// + /// + /// public async Task StopAsync(CancellationToken cancellationToken = default) { StartRequested = false; @@ -129,14 +162,15 @@ namespace slskd.Network Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); - var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); + var token = await HubConnection.InvokeAsync(nameof(NetworkHub.BeginShareUpload)); Log.Debug("Share upload token {Token}", token); var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, { new StringContent(ComputeCredential(token)), "credential" }, { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, { new StreamContent(stream), "database", "shares" }, @@ -167,7 +201,7 @@ namespace slskd.Network private string ComputeCredential(Guid token) => ComputeCredential(token.ToString()); - private Task HandleFileRequest(string filename, Guid token) + private Task HandleFileUploadRequest(string filename, Guid token) { _ = Task.Run(async () => { @@ -186,9 +220,10 @@ 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/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, { new StringContent(ComputeCredential(token)), "credential" }, { new StreamContent(stream), "file", filename }, }; @@ -212,7 +247,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), token); + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyFileUploadFailed), token); } }); @@ -334,7 +369,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(nameof(INetworkHub.RequestFile), HandleFileRequest); + HubConnection.On(nameof(INetworkHub.RequestFileUpload), HandleFileUploadRequest); HubConnection.On(nameof(INetworkHub.RequestFileInfo), HandleFileInfoRequest); HubConnection.On(nameof(INetworkHub.Challenge), HandleAuthenticationChallenge); diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 6ecf5f39..44628e1b 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -312,7 +312,8 @@ namespace slskd.Network { var token = Guid.NewGuid(); - MemoryCache.Set(GetShareTokenCacheKey(token), agentName, TimeSpan.FromMinutes(1)); + // allow a generous amount of time, in case it takes a while to upload the response + MemoryCache.Set(GetShareTokenCacheKey(token), agentName, TimeSpan.FromMinutes(5)); Log.Debug("Cached share upload token {Token} for agent {Agent}", token, agentName); return token; -- cgit v1.2.3