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 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Network/API/Controllers') 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(); } -- cgit v1.2.3 From 4196d2224a4024a26b9bfbf946197360aeab707b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 12:17:17 -0500 Subject: validate credentials for rest calls --- .../Network/API/Controllers/NetworkController.cs | 61 +++++++++---- src/slskd/Network/NetworkService.cs | 101 ++++++++++++++++----- 2 files changed, 122 insertions(+), 40 deletions(-) (limited to 'src/slskd/Network/API/Controllers') 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 4b295fde2462dd72c3f7df9defb4ea3ddd3a754b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 12:58:25 -0500 Subject: verify filenames --- src/slskd/Network/API/Controllers/NetworkController.cs | 2 +- src/slskd/Network/NetworkService.cs | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) (limited to 'src/slskd/Network/API/Controllers') 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 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/slskd/Network/API/Controllers') 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 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/slskd/Network/API/Controllers') 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/slskd/Network/API/Controllers') 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 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/slskd/Network/API/Controllers') 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 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/slskd/Network/API/Controllers') 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 d614b962a6b0458e9e03c7a4404c680ddae304e9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 18:30:48 -0500 Subject: more refactoring --- .../Network/API/Controllers/NetworkController.cs | 2 +- src/slskd/Network/API/Hubs/NetworkHub.cs | 4 +- src/slskd/Network/NetworkService.cs | 54 +++++++++++----------- src/slskd/Transfers/Uploads/UploadService.cs | 6 +-- 4 files changed, 32 insertions(+), 34 deletions(-) (limited to 'src/slskd/Network/API/Controllers') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index b1a71f34..e30d984c 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -112,7 +112,7 @@ namespace slskd.Network // pass the stream back to the network service, which will in turn pass it to the // upload service, and use it to feed data into the remote upload. await this call, // it will complete when the upload is complete. - await Network.HandleGetFileStreamResponse(id: guid, stream); + await Network.HandleFileStreamResponse(id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 7945a62b..32575e8d 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -97,7 +97,7 @@ namespace slskd.Network public void NotifyUploadFailed(Guid id, Exception exception) { - Network.NotifyFileStreamFailure(id, exception); + Network.NotifyFileStreamException(id, exception); } public void ReturnFileInfo(Guid id, bool exists, long length) @@ -108,7 +108,7 @@ namespace slskd.Network return; } - Network.HandleGetFileInfoResponse(record.Agent.Name, id, (exists, length)); + Network.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } } } \ No newline at end of file diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 7a56eb1c..b36bfb89 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -66,21 +66,21 @@ namespace slskd.Network /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file. - Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000); + Task GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000); /// - /// Safely attempts to close a stream obtained with . + /// Safely attempts to close a stream obtained with . /// /// The unique ID for the stream. /// If the transfer associated with the stream failed, the exception that caused the failure. void TryCloseFileStream(Guid id, Exception exception = null); /// - /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// /// The unique ID for the stream. /// The remote exception that caused the failure. - void NotifyFileStreamFailure(Guid id, Exception exception); + void NotifyFileStreamException(Guid id, Exception exception); /// /// Retrieves information about the specified from the specified . @@ -89,25 +89,23 @@ namespace slskd.Network /// The file for which to retrieve information. /// An optional timeout value. /// A value indicating whether the file exists, and the length in bytes. - Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000); + Task<(bool Exists, long Length)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000); /// - /// Handles the client response for a request. + /// Handles the client response for a request. /// /// The agent that provided the response. /// The ID of the request. /// The client response to the request. - void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); + void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); /// - /// Handles the client response for a request, returning when the corresponding file upload is complete. + /// Handles the client response for a request, returning when the corresponding file upload is complete. /// /// The ID of the request. /// The client response to the request. /// The operation context. - Task HandleGetFileStreamResponse(Guid id, Stream response); - - void HandleGetFileStreamCompletion(string agentName, string filename); + Task HandleFileStreamResponse(Guid id, Stream response); /// /// Registers the specified with the specified . @@ -233,7 +231,7 @@ namespace slskd.Network /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000) + public async Task GetFileStreamAsync(string agentName, string filename, Guid id, int timeout = 3000) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { @@ -247,7 +245,7 @@ namespace slskd.Network // create a wait for the agent response. this wait will be completed in the response handler, // ultimately called from the API controller when the agent makes an HTTP request to return the file - var key = new WaitKey(nameof(GetFileStream), id); + var key = new WaitKey(nameof(GetFileStreamAsync), id); var wait = Waiter.Wait(key, timeout); await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id); @@ -269,24 +267,24 @@ namespace slskd.Network } /// - /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// /// The unique ID for the stream. /// The remote exception that caused the failure. - public void NotifyFileStreamFailure(Guid id, Exception exception) + public void NotifyFileStreamException(Guid id, Exception exception) { - var key = new WaitKey(nameof(GetFileStream), id); + var key = new WaitKey(nameof(GetFileStreamAsync), id); Waiter.Throw(key, exception); } /// - /// Safely attempts to close a stream obtained with . + /// Safely attempts to close a stream obtained with . /// /// The unique ID for the stream. /// If the transfer associated with the stream failed, the exception that caused the failure. public void TryCloseFileStream(Guid id, Exception exception = default) { - var key = new WaitKey(nameof(HandleGetFileStreamResponse), id); + var key = new WaitKey(nameof(HandleFileStreamResponse), id); if (exception != default) { @@ -304,7 +302,7 @@ namespace slskd.Network /// The file for which to retrieve information. /// An optional timeout value. /// A value indicating whether the file exists, and the length in bytes. - public async Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000) + public async Task<(bool Exists, long Length)> GetFileInfoAsync(string agentName, string filename, int timeout = 3000) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { @@ -312,7 +310,7 @@ namespace slskd.Network } var id = Guid.NewGuid(); - var key = new WaitKey(nameof(GetFileInfo), agentName, id); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); try @@ -330,14 +328,14 @@ namespace slskd.Network } /// - /// Handles the client response for a request. + /// Handles the client response for a request. /// /// The agent that provided the response. /// The ID of the request. /// The client response to the request. - public void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) + public void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) { - var key = new WaitKey(nameof(GetFileInfo), agentName, id); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); if (!Waiter.IsWaitingFor(key)) { @@ -350,14 +348,14 @@ namespace slskd.Network } /// - /// Handles the client response for a request, returning when the corresponding file upload is complete. + /// Handles the client response for a request, returning when the corresponding file upload is complete. /// /// The ID of the request. /// The client response to the request. /// The operation context. - public async Task HandleGetFileStreamResponse(Guid id, Stream response) + public async Task HandleFileStreamResponse(Guid id, Stream response) { - var streamKey = new WaitKey(nameof(GetFileStream), id); + var streamKey = new WaitKey(nameof(GetFileStreamAsync), id); if (!Waiter.IsWaitingFor(streamKey)) { @@ -368,7 +366,7 @@ namespace slskd.Network // create a wait (but do not await it) for the completion of the upload to the remote client. we need to await this // to keep execution in the body of the API controller that provided the stream, in order to keep // the stream open for the duration of the remote transfer. omit the id from the key, the caller doesn't know it. - var completionKey = new WaitKey(nameof(HandleGetFileStreamResponse), id); + var completionKey = new WaitKey(nameof(HandleFileStreamResponse), id); var completion = Waiter.WaitIndefinitely(completionKey); // complete the wait that's waiting for the stream, so we can send the stream back to the caller of GetFileStream @@ -385,7 +383,7 @@ namespace slskd.Network // complete the indefinite wait for this upload. this sends execution back to the body of the file // stream response handler, and ultimately back to the API controller. the agent's original HTTP request // will complete. - var key = new WaitKey(nameof(GetFileStream), "completion", agentName, filename); + var key = new WaitKey(nameof(GetFileStreamAsync), "completion", agentName, filename); Waiter.Complete(key); Log.Information("Upload of {File} from agent {Agent} reported as completed", filename, agentName); } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index d3e8b89e..7c5bab0b 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -137,7 +137,7 @@ namespace slskd.Transfers.Uploads } else { - var (exists, length) = await Network.GetFileInfo(agentName: host, filename); + var (exists, length) = await Network.GetFileInfoAsync(agentName: host, filename); if (!exists || length <= 0) { @@ -269,7 +269,7 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStream(agentName: host, filename, id), + inputStreamFactory: () => Network.GetFileStreamAsync(agentName: host, filename, id), options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From 5493a29466b808b3faaeeec5cb8d16584961fc86 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 25 Oct 2022 09:42:34 -0500 Subject: more cleanup and docs --- .../Network/API/Controllers/NetworkController.cs | 15 +- src/slskd/Network/NetworkService.cs | 320 +++++++++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 4 +- 3 files changed, 218 insertions(+), 121 deletions(-) (limited to 'src/slskd/Network/API/Controllers') 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