From 3f6f13bb99deac7c0b5a5b5ddb43cea91fa40e13 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 30 Dec 2022 16:19:28 -0600 Subject: add controller 'downloads' option and docs --- src/slskd/Core/Options.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e23fd640..bc6f14a6 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -500,6 +500,14 @@ namespace slskd [NotNullOrWhiteSpace] [Secret] public string Secret { get; init; } + + /// + /// Gets a value indicating whether to receive completed downloads from the controller. + /// + [Argument(default, "controller-downloads")] + [EnvironmentVariable("CONTROLLER_DOWNLOADS")] + [Description("receive completed downloads from the controller")] + public bool Downloads { get; init; } = false; } /// -- cgit v1.2.3 From 9d14042db13e89e9114ad5420c4881b6af4d293c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 30 Dec 2022 17:20:22 -0600 Subject: add NotifyFileDownloadCompleted --- src/slskd/Relay/API/Hubs/RelayHub.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') 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 /// The unique identifier for the request. /// The operation context. Task RequestFileUpload(string filename, long startOffset, Guid id); + + /// + /// Notifies the agent that the download of the specified is complete and that the file is ready for downloading. + /// + /// The name of the newly downloaded file. + /// The unique identifier for the request. + /// The operation context. + Task NotifyFileDownloadCompleted(string filename, Guid id); } /// -- cgit v1.2.3 From 36b20bee334ded439b2d5f4b5d797ba3ca6d0e6c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 30 Dec 2022 17:21:55 -0600 Subject: add file completion broadcast, helpers for auth --- src/slskd/Relay/RelayService.cs | 64 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index c4fb13a9..e1fa5820 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -54,6 +54,12 @@ namespace slskd.Relay /// IStateMonitor StateMonitor { get; } + /// + /// Notifies connected agents that a file download has completed. + /// + /// The filename of the completed file, relative to the downloads directory. + void BroadcastFileDownloadCompletedNotification(string filename); + /// /// Generates a random authentication challenge token for the specified . /// @@ -225,6 +231,16 @@ namespace slskd.Relay /// A value indicating whether the response is valid. bool TryValidateAuthenticationCredential(string connectionId, string agentName, string credential); + /// + /// Attempts to validate the file download response credential associated with the specified . + /// + /// The token. + /// The name of the responding agent. + /// The name of the file being downloaded. + /// The response credential. + /// A value indicating whether the credential is valid. + bool TryValidateFileDownloadCredential(Guid token, string agentName, string filename, string credential); + /// /// Attempts to validate the file stream response credential associated with the specified . /// @@ -307,6 +323,39 @@ namespace slskd.Relay private string LastOptionsHash { get; set; } private string LastControllerOptionsHash { get; set; } + /// + /// Notifies connected agents that a file download has completed. + /// + /// The filename of the completed file, relative to the downloads directory. + public void BroadcastFileDownloadCompletedNotification(string filename) + { + // 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); + } + } + + // fire and forget, no waiting + _ = RegisteredAgentDictionary.Values.Select(Notify); + } + /// /// Generates a random authentication challenge token for the specified . /// @@ -679,6 +728,19 @@ namespace slskd.Relay return expectedResponse == credential; } + /// + /// Attempts to validate the file download response credential associated with the specified . + /// + /// The token. + /// The name of the responding agent. + /// The name of the file being downloaded. + /// The response credential. + /// A value indicating whether the credential is valid. + public bool TryValidateFileDownloadCredential(Guid token, string agentName, string filename, string credential) + { + return TryValidateCredential(token.ToString(), agentName, credential, GetDownloadTokenCacheKey(filename, token)); + } + /// /// Attempts to validate the file stream response credential associated with the specified . /// @@ -760,6 +822,8 @@ 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"; -- cgit v1.2.3 From 2f554d1ccbb2fa677b810c861c389a6142576573 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 30 Dec 2022 17:22:18 -0600 Subject: broadcast file completions --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 4c3a7298..5a4aa170 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -31,6 +31,7 @@ namespace slskd.Transfers.Downloads using Microsoft.EntityFrameworkCore; using Serilog; using slskd.Integrations.FTP; + using slskd.Relay; /// /// Manages downloads. @@ -41,18 +42,21 @@ namespace slskd.Transfers.Downloads IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory contextFactory, + IRelayService relayService, IFTPService ftpClient) { Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; FTP = ftpClient; + Relay = relayService; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private IFTPService FTP { get; } + private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } @@ -224,6 +228,8 @@ namespace slskd.Transfers.Downloads // argue both ways for that being the correct behavior. revisit this later. MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); + Relay.BroadcastFileDownloadCompletedNotification(file.Filename); + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) { _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); -- cgit v1.2.3 From 32a1e1210ed572f52536c8252229bfa0911f8bab Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 13:22:01 -0600 Subject: tweak handling of filename conflicts --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 5a4aa170..bf1be328 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -504,12 +504,12 @@ namespace slskd.Transfers.Downloads if (File.Exists(destinationFilename)) { - string extensionlessFilename = Path.GetFileNameWithoutExtension(filename); + string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); string extension = Path.GetExtension(filename); while (File.Exists(destinationFilename)) { - string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}.{extension}"; + string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); } } -- cgit v1.2.3 From 3ffff66b0823cc15bcceddb9274639e3b2491588 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 13:22:25 -0600 Subject: return final filename from MoveFile() --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf1be328..d1dfbd20 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -490,7 +490,7 @@ namespace slskd.Transfers.Downloads return new FileStream(localFilename, FileMode.Create); } - private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory) + private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) { var sourceFilename = filename.ToLocalFilename(sourceDirectory); var destinationFilename = filename.ToLocalFilename(destinationDirectory); @@ -520,6 +520,8 @@ namespace slskd.Transfers.Downloads { Directory.Delete(Path.GetDirectoryName(sourceFilename)); } + + return destinationFilename; } } } \ No newline at end of file -- cgit v1.2.3 From e38b44f5ae1f685bfcd32989570c7b0e4a457efe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 13:23:10 -0600 Subject: tweak agent broadcast logic --- src/slskd/Transfers/Downloads/DownloadService.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d1dfbd20..c85ff551 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -226,13 +226,18 @@ namespace slskd.Transfers.Downloads // this would be the ideal place to hook in a generic post-download task processor for now, we'll // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could // argue both ways for that being the correct behavior. revisit this later. - MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); + var finalFilename = MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); - Relay.BroadcastFileDownloadCompletedNotification(file.Filename); + Log.Debug("Moved file to {Destination}", finalFilename); + + if (OptionsMonitor.CurrentValue.Relay.Enabled) + { + _ = Relay.BroadcastFileDownloadCompletedNotificationAsync(finalFilename); + } if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) { - _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); + _ = FTP.UploadAsync(finalFilename); } } catch (OperationCanceledException ex) -- cgit v1.2.3 From 3c7d16890a247a54c4ebe34682d235341d94f8e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 15:55:58 -0600 Subject: tweak broadcast, don't remove download tokens after first use --- src/slskd/Relay/RelayService.cs | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index e1fa5820..47879b19 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -58,7 +58,8 @@ namespace slskd.Relay /// Notifies connected agents that a file download has completed. /// /// The filename of the completed file, relative to the downloads directory. - void BroadcastFileDownloadCompletedNotification(string filename); + /// The operation context. + Task BroadcastFileDownloadCompletedNotificationAsync(string filename); /// /// Generates a random authentication challenge token for the specified . @@ -327,8 +328,22 @@ namespace slskd.Relay /// Notifies connected agents that a file download has completed. /// /// The filename of the completed file, relative to the downloads directory. - public void BroadcastFileDownloadCompletedNotification(string filename) + /// The operation context. + public Task BroadcastFileDownloadCompletedNotificationAsync(string filename) { + if (!OptionsMonitor.CurrentValue.Relay.Enabled || + !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OptionsMonitor.CurrentValue.Relay.Mode.ToEnum())) + { + 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 @@ -352,8 +367,9 @@ namespace slskd.Relay } } - // fire and forget, no waiting - _ = RegisteredAgentDictionary.Values.Select(Notify); + Log.Information("Notifying agents of download completion for {Filename}", filename); + + return Task.WhenAll(RegisteredAgentDictionary.Values.Select(Notify)); } /// @@ -738,7 +754,7 @@ namespace slskd.Relay /// A value indicating whether the credential is valid. public bool TryValidateFileDownloadCredential(Guid token, string agentName, string filename, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetDownloadTokenCacheKey(filename, token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetDownloadTokenCacheKey(filename, token), suppressRemoval: true); } /// @@ -828,7 +844,7 @@ namespace slskd.Relay 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 { @@ -871,7 +887,10 @@ namespace slskd.Relay finally { // tokens can be used exactly once, pass or fail - MemoryCache.Remove(cacheKey); + if (!suppressRemoval) + { + MemoryCache.Remove(cacheKey); + } } } } -- cgit v1.2.3 From 6425c0032b2745ca2bd966f1668aba6415bb6f8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 16:13:28 -0600 Subject: implement download handler --- src/slskd/Relay/API/Controllers/RelayController.cs | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index ae87969e..ec8fef62 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/. // +using Microsoft.Extensions.Options; + namespace slskd.Relay { using System; @@ -40,9 +42,11 @@ namespace slskd.Relay { public RelayController( IRelayService relayService, + IOptionsMonitor 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(); + private IOptionsMonitor 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"); + } + /// /// Uploads a file. /// -- cgit v1.2.3 From 614170cb68d52af7b9e627444f3758b1809190c1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 16:13:46 -0600 Subject: implement download logic --- src/slskd/Relay/RelayClient.cs | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index f1a1c51d..cdc4f9e3 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -392,6 +392,50 @@ namespace slskd.Relay } } + private Task HandleNotifyFileDownloadCompleted(string filename, Guid token) + { + 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.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}"); + } + + 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(); + 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 +535,7 @@ namespace slskd.Relay HubConnection.On(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); HubConnection.On(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); HubConnection.On(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); + HubConnection.On(nameof(IRelayHub.NotifyFileDownloadCompleted), HandleNotifyFileDownloadCompleted); LastOptionsHash = optionsHash; -- cgit v1.2.3 From a9b0a16a9ba7c95044a71cb89b37325011685118 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 16:25:49 -0600 Subject: move auth to headers for all endpoints --- src/slskd/Relay/API/Controllers/RelayController.cs | 25 ++++++++-------------- src/slskd/Relay/RelayClient.cs | 14 ++++++++---- 2 files changed, 19 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index ec8fef62..7e7f3e22 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -152,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; @@ -161,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; @@ -243,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 shares; IFormFile database; try { - agentName = Request.Form["name"].ToString(); - credential = Request.Form["credential"].ToString(); shares = Request.Form["shares"].ToString().FromJson>(); database = Request.Form.Files[0]; } diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index cdc4f9e3..bd9d02ac 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); -- cgit v1.2.3 From 4e7dd7c421969c05d121ad12e67af7690480957a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 16:43:49 -0600 Subject: create directory before downloading --- src/slskd/Relay/RelayClient.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index bd9d02ac..08ea5e23 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -428,6 +428,8 @@ namespace slskd.Relay 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); }, -- cgit v1.2.3 From 6e9e64d55c4130114e5b4fa6ea2869e043043918 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 16:44:09 -0600 Subject: don't download if the option isn't enabled --- src/slskd/Relay/RelayClient.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 08ea5e23..37ac72bb 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -400,6 +400,11 @@ 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 () => -- cgit v1.2.3 From d259789fcb605aa9d87857ba2fba8c35604297c2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Dec 2022 16:44:20 -0600 Subject: change debug suffix --- src/slskd/Relay/RelayClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 37ac72bb..d6bde1d7 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -415,7 +415,7 @@ namespace slskd.Relay { // 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}"); + destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); } await Retry.Do(task: async () => -- cgit v1.2.3