diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-12-31 16:50:27 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-12-31 16:50:27 -0600 |
| commit | ce67db39e0fa02a764a13546043e71d25d338219 (patch) | |
| tree | 84c6818063270d78f6655342450012385b8a205f /src/slskd/Relay | |
| parent | 49bc255026aa5ef2c4df0727134b7627808270fc (diff) | |
| parent | d259789fcb605aa9d87857ba2fba8c35604297c2 (diff) | |
| download | slskd-ce67db39e0fa02a764a13546043e71d25d338219.tar.gz | |
Merge pull request #815 from slskd/relay-down
Add the ability to configure Relay Agents to download files downloaded by the controller
Diffstat (limited to 'src/slskd/Relay')
| -rw-r--r-- | src/slskd/Relay/API/Controllers/RelayController.cs | 71 | ||||
| -rw-r--r-- | src/slskd/Relay/API/Hubs/RelayHub.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayService.cs | 87 |
4 files changed, 210 insertions, 22 deletions
diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index ae87969e..7e7f3e22 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd.Relay { using System; @@ -40,9 +42,11 @@ namespace slskd.Relay { public RelayController( IRelayService relayService, + IOptionsMonitor<Options> optionsMonitor, OptionsAtStartup optionsAtStartup) { Relay = relayService; + OptionsMonitor = optionsMonitor; OptionsAtStartup = optionsAtStartup; } @@ -50,6 +54,7 @@ namespace slskd.Relay private IRelayService Relay { get; } private OptionsAtStartup OptionsAtStartup { get; } private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } [HttpPut("")] [Authorize(Policy = AuthPolicy.Any)] @@ -77,6 +82,47 @@ namespace slskd.Relay return NoContent(); } + [HttpGet("downloads/{token}")] + [Authorize(Policy = AuthPolicy.Any)] + public IActionResult DownloadFile([FromRoute]string token) + { + if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) + { + return Forbid(); + } + + if (!Guid.TryParse(token, out var guid)) + { + return BadRequest("Token is not in a valid format"); + } + + var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); + var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); + var filename = Request.Headers["X-Relay-Filename"].FirstOrDefault(); + + if (!Relay.RegisteredAgents.Any(a => a.Name == agentName)) + { + return Unauthorized(); + } + + Log.Information("Handling file download for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + + // note: the token remains valid after the validation attempt, unlike most other endpoints. + // this is done to support retries + if (!Relay.TryValidateFileDownloadCredential(token: guid, agentName, filename, credential)) + { + Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", guid, agentName); + return Unauthorized(); + } + + var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); + + Log.Information("Agent {Agent} authenticated. Sending file {File}", agentName, filename); + + var stream = new FileStream(Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename), FileMode.Open); + return File(stream, "application/octet-stream"); + } + /// <summary> /// Uploads a file. /// </summary> @@ -106,8 +152,9 @@ namespace slskd.Relay return new UnsupportedMediaTypeResult(); } - string agentName = default; - string credential = default; + var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); + var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); + Stream stream = default; string filename = default; @@ -115,17 +162,10 @@ namespace slskd.Relay { try { + // note: while the actual HTTP request is the same as the one we use for uploading shares, we handle it + // differently so that we can capture the stream 'in flight' and avoid any buffering. resist the urge to + // refactor one or the other to make them match! var reader = new MultipartReader(HeaderUtilities.RemoveQuotes(mediaTypeHeader.Boundary).Value, Request.Body); - - // 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 src = new StreamReader(credentialSection.Body); - credential = src.ReadToEnd(); - var fileSection = await reader.ReadNextSectionAsync(); var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); filename = contentDisposition.FileName.Value; @@ -197,15 +237,14 @@ namespace slskd.Relay return new UnsupportedMediaTypeResult(); } - string agentName = default; - string credential = default; + var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); + var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); + 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]; } diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index b76f67b9..d0e9a962 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -54,6 +54,14 @@ namespace slskd.Relay /// <param name="id">The unique identifier for the request.</param> /// <returns>The operation context.</returns> Task RequestFileUpload(string filename, long startOffset, Guid id); + + /// <summary> + /// Notifies the agent that the download of the specified <paramref name="filename"/> is complete and that the file is ready for downloading. + /// </summary> + /// <param name="filename">The name of the newly downloaded file.</param> + /// <param name="id">The unique identifier for the request.</param> + /// <returns>The operation context.</returns> + Task NotifyFileDownloadCompleted(string filename, Guid id); } /// <summary> diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index f1a1c51d..d6bde1d7 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -244,15 +244,17 @@ namespace slskd.Relay var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}"); + + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); + request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); + request.Headers.Add("X-Relay-Credential", ComputeCredential(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" }, }; - request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Content = content; var size = ((double)stream.Length).SizeSuffix(); @@ -312,6 +314,11 @@ namespace slskd.Relay stream.Seek(startOffset, SeekOrigin.Begin); using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/files/{token}"); + + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); + request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); + request.Headers.Add("X-Relay-Credential", ComputeCredential(token)); + using var content = new MultipartFormDataContent { { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, @@ -319,7 +326,6 @@ namespace slskd.Relay { new StreamContent(stream), "file", filename }, }; - request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Content = content; Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); @@ -392,6 +398,57 @@ namespace slskd.Relay } } + private Task HandleNotifyFileDownloadCompleted(string filename, Guid token) + { + if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads) + { + return Task.CompletedTask; + } + + Log.Information("Relay controller sent a download notification for {Filename} ({Token})", filename, token); + + _ = Task.Run(async () => + { + var destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); + + if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug) + { + // if we're debugging, we're referencing the same file for both the controller and agent + // which will lead to an access violation. prefix the destination file to avoid this. + destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); + } + + await Retry.Do(task: async () => + { + using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v0/relay/downloads/{token}"); + + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); + request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); + request.Headers.Add("X-Relay-Credential", ComputeCredential(token)); + request.Headers.Add("X-Relay-Filename", filename); + + using var client = CreateHttpClient(); + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); + + response.EnsureSuccessStatusCode(); + + using var remoteStream = await response.Content.ReadAsStreamAsync(); + + Directory.CreateDirectory(Path.GetDirectoryName(destinationFile)); + using var localStream = new FileStream(destinationFile, FileMode.Create); + await remoteStream.CopyToAsync(localStream); + }, + isRetryable: (_, _) => true, + onFailure: (_, ex) => Log.Error(ex, "Failed to handle file download notification for {Filename} ({Token})", filename, token), + maxAttempts: 3, + maxDelayInMilliseconds: 60000); + + Log.Information("File {Filename} successfully downloaded to {Destination}", filename, destinationFile); + }); + + return Task.CompletedTask; + } + private Task HubConnection_Closed(Exception arg) { Log.Warning("Relay controller connection closed: {Message}", arg.Message); @@ -491,6 +548,7 @@ namespace slskd.Relay HubConnection.On<string, long, Guid>(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); HubConnection.On<string>(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); + HubConnection.On<string, Guid>(nameof(IRelayHub.NotifyFileDownloadCompleted), HandleNotifyFileDownloadCompleted); LastOptionsHash = optionsHash; diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index c4fb13a9..47879b19 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -55,6 +55,13 @@ namespace slskd.Relay IStateMonitor<RelayState> StateMonitor { get; } /// <summary> + /// Notifies connected agents that a file download has completed. + /// </summary> + /// <param name="filename">The filename of the completed file, relative to the downloads directory.</param> + /// <returns>The operation context.</returns> + Task BroadcastFileDownloadCompletedNotificationAsync(string filename); + + /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. /// </summary> /// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks> @@ -226,6 +233,16 @@ namespace slskd.Relay bool TryValidateAuthenticationCredential(string connectionId, string agentName, string credential); /// <summary> + /// Attempts to validate the file download response credential associated with the specified <paramref name="token"/>. + /// </summary> + /// <param name="token">The token.</param> + /// <param name="agentName">The name of the responding agent.</param> + /// <param name="filename">The name of the file being downloaded.</param> + /// <param name="credential">The response credential.</param> + /// <returns>A value indicating whether the credential is valid.</returns> + bool TryValidateFileDownloadCredential(Guid token, string agentName, string filename, string credential); + + /// <summary> /// Attempts to validate the file stream response credential associated with the specified <paramref name="token"/>. /// </summary> /// <param name="token">The token.</param> @@ -308,6 +325,54 @@ namespace slskd.Relay private string LastControllerOptionsHash { get; set; } /// <summary> + /// Notifies connected agents that a file download has completed. + /// </summary> + /// <param name="filename">The filename of the completed file, relative to the downloads directory.</param> + /// <returns>The operation context.</returns> + public Task BroadcastFileDownloadCompletedNotificationAsync(string filename) + { + if (!OptionsMonitor.CurrentValue.Relay.Enabled || + !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>())) + { + return Task.CompletedTask; + } + + var agents = RegisteredAgentDictionary.Values; + + if (!agents.Any()) + { + return Task.CompletedTask; + } + + // ensure filename is relative to the local download directory + // and make sure it doesn't start with a slash + filename = filename + .ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty) + .TrimStart(new[] { '/', '\\' }); + + async Task Notify((string ConnectionId, Agent Agent) record) + { + try + { + var id = Guid.NewGuid(); + + MemoryCache.Set(GetDownloadTokenCacheKey(filename, id), record.Agent.Name, TimeSpan.FromMinutes(10)); + Log.Debug("Cached file download token {Token} for agent {Agent}", id, record.Agent.Name); + + await RelayHub.Clients.Client(record.ConnectionId).NotifyFileDownloadCompleted(filename, id); + } + catch + { + Log.Warning("Failed to notify agent {Agent} of download completion for {Filename}", record.Agent.Name, filename); + } + } + + Log.Information("Notifying agents of download completion for {Filename}", filename); + + return Task.WhenAll(RegisteredAgentDictionary.Values.Select(Notify)); + } + + /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. /// </summary> /// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks> @@ -680,6 +745,19 @@ namespace slskd.Relay } /// <summary> + /// Attempts to validate the file download response credential associated with the specified <paramref name="token"/>. + /// </summary> + /// <param name="token">The token.</param> + /// <param name="agentName">The name of the responding agent.</param> + /// <param name="filename">The name of the file being downloaded.</param> + /// <param name="credential">The response credential.</param> + /// <returns>A value indicating whether the credential is valid.</returns> + public bool TryValidateFileDownloadCredential(Guid token, string agentName, string filename, string credential) + { + return TryValidateCredential(token.ToString(), agentName, credential, GetDownloadTokenCacheKey(filename, token), suppressRemoval: true); + } + + /// <summary> /// Attempts to validate the file stream response credential associated with the specified <paramref name="token"/>. /// </summary> /// <param name="token">The token.</param> @@ -760,11 +838,13 @@ namespace slskd.Relay private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; + private string GetDownloadTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.download"; + private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; - private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey) + private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey, bool suppressRemoval = false) { try { @@ -807,7 +887,10 @@ namespace slskd.Relay finally { // tokens can be used exactly once, pass or fail - MemoryCache.Remove(cacheKey); + if (!suppressRemoval) + { + MemoryCache.Remove(cacheKey); + } } } } |
