diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-30 12:35:38 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-30 12:35:38 -0500 |
| commit | dbe3a9e82036a0db8049f3b884342dc98cc98d58 (patch) | |
| tree | 6fae10d316a7564f788cae6ca19fbc9d0236e36b /src/slskd/Network/API/Controllers/NetworkController.cs | |
| parent | e483a797f8f2a1b50397a6a72cac03430ac5dcb6 (diff) | |
| parent | 4489434a5d5580b8bf74bc0a16512545e0dcb0f6 (diff) | |
| download | slskd-dbe3a9e82036a0db8049f3b884342dc98cc98d58.tar.gz | |
Merge pull request #713 from slskd/more-cleanup
More Network cleanup
Diffstat (limited to 'src/slskd/Network/API/Controllers/NetworkController.cs')
| -rw-r--r-- | src/slskd/Network/API/Controllers/NetworkController.cs | 122 |
1 files changed, 79 insertions, 43 deletions
diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 624d7a2c..276cdcd0 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<NetworkController>(); + private INetworkService Network { get; } - [HttpPost("files/{agentName}/{token}")] + /// <summary> + /// Uploads a file. + /// </summary> + /// <param name="token">The unique identifier for the request.</param> + /// <returns></returns> + [HttpPost("files/{token}")] [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] [DisableFormValueModelBinding] [Authorize] - public async Task<IActionResult> UploadFile(string agentName, string token) + public async Task<IActionResult> 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}")] + /// <summary> + /// Uploads share information. + /// </summary> + /// <param name="token">The unique identifier for the request.</param> + /// <returns></returns> + [HttpPost("shares/{token}")] [Authorize] - public async Task<IActionResult> UploadShares(string agentName, string token) + public async Task<IActionResult> 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<Share> shares; IFormFile database; try { + agentName = Request.Form["name"].ToString(); credential = Request.Form["credential"].ToString(); shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>(); 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}"); @@ -164,26 +185,41 @@ namespace slskd.Network } var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agentName}_{Path.GetRandomFileName()}.db"); + Stream outputStream = default; - 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(); + 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); + await outputStream.FlushAsync(); + + 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 + { + outputStream?.TryDispose(); + 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 |
