aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-01-07 18:54:29 -0600
committerGitHub <noreply@github.com>2023-01-07 18:54:29 -0600
commitff5f0ac6c93f2b49ba259e7093fb92fa873116c6 (patch)
tree89a57703213c524f09346aac4fcf3a9ee8b3cf04 /src
parentd5eabb72a5c5a3aed06f0c4b8f66c853468b889b (diff)
parentf07a7758b47388c793d73ca54727db95abfcd229 (diff)
downloadslskd-ff5f0ac6c93f2b49ba259e7093fb92fa873116c6.tar.gz
Merge pull request #827 from slskd/relay-debug
Miscellaneous Relay refactoring and bugfixes
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Authentication/ApiKeyAuthentication.cs2
-rw-r--r--src/slskd/Common/Authentication/AuthPolicy.cs2
-rw-r--r--src/slskd/Program.cs6
-rw-r--r--src/slskd/Relay/API/Controllers/RelayController.cs34
-rw-r--r--src/slskd/Relay/RelayClient.cs6
-rw-r--r--src/slskd/Relay/RelayService.cs10
-rw-r--r--src/slskd/Shares/ShareService.cs18
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs2
8 files changed, 66 insertions, 14 deletions
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
index a41a9d59..7c6c9235 100644
--- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
+++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
@@ -34,7 +34,7 @@ namespace slskd.Authentication
/// <summary>
/// Gets the API key authentication scheme name.
/// </summary>
- public static string AuthenticationScheme { get; } = "API Key";
+ public static string AuthenticationScheme { get; } = "ApiKey";
}
/// <summary>
diff --git a/src/slskd/Common/Authentication/AuthPolicy.cs b/src/slskd/Common/Authentication/AuthPolicy.cs
index 040104da..47d430c9 100644
--- a/src/slskd/Common/Authentication/AuthPolicy.cs
+++ b/src/slskd/Common/Authentication/AuthPolicy.cs
@@ -23,7 +23,7 @@ namespace slskd
public static class AuthPolicy
{
public const string JwtOnly = "Jwt";
- public const string ApiKeyOnly = "ApiKeyOnly";
+ public const string ApiKeyOnly = "ApiKey";
public const string Any = "Any";
}
}
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index d0b670a2..28ef7279 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -696,6 +696,12 @@ namespace slskd
policy.RequireAuthenticatedUser();
});
+ options.AddPolicy(AuthPolicy.ApiKeyOnly, policy =>
+ {
+ policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme);
+ policy.RequireAuthenticatedUser();
+ });
+
options.AddPolicy(AuthPolicy.JwtOnly, policy =>
{
policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme);
diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs
index d4fb4810..f6c6d778 100644
--- a/src/slskd/Relay/API/Controllers/RelayController.cs
+++ b/src/slskd/Relay/API/Controllers/RelayController.cs
@@ -21,6 +21,7 @@ namespace slskd.Relay
{
using System;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
@@ -115,7 +116,7 @@ namespace slskd.Relay
return BadRequest();
}
- Log.Information("Handling file download for token {Token} from a caller claiming to be agent {Agent}", token, agentName);
+ Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName);
// note: the token remains valid after the validation attempt, unlike most other endpoints.
// this is done to support retries
@@ -127,9 +128,9 @@ namespace slskd.Relay
var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
- Log.Information("Agent {Agent} authenticated. Sending file {File}", agentName, filename);
+ Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename);
- var stream = new FileStream(Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename), FileMode.Open);
+ var stream = new FileStream(sourceFile, FileMode.Open);
return File(stream, "application/octet-stream");
}
@@ -185,6 +186,16 @@ namespace slskd.Relay
var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition);
filename = contentDisposition.FileName.Value;
stream = fileSection.Body;
+
+ if (string.IsNullOrEmpty(filename))
+ {
+ throw new ArgumentException("Upload filename is null or empty");
+ }
+
+ if (stream == null || !stream.CanRead)
+ {
+ throw new ArgumentException("Unable to obtain stream from request");
+ }
}
catch (Exception ex)
{
@@ -194,19 +205,19 @@ namespace slskd.Relay
return BadRequest();
}
- Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName);
+ Log.Information("Handling file upload of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, 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 (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential))
+ if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName: agentName, filename: filename, credential: credential))
{
Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", guid, agentName);
return Unauthorized();
}
- Log.Information("File upload of {Filename} ({Token}) from agent {Agent} validated and authenticated. Forwarding file stream.", filename, token, agentName);
+ Log.Information("Agent {Agent} authenticated for token {Token}. Forwarding file stream for {Filename}", agentName, guid, filename);
// pass the stream back to the relay 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.
@@ -269,6 +280,8 @@ namespace slskd.Relay
return BadRequest();
}
+ Log.Information("Handling share upload ({Token}) from a caller claiming to be agent {Agent}", token, agentName);
+
if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential))
{
Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid);
@@ -280,14 +293,19 @@ namespace slskd.Relay
try
{
- Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp);
+ Log.Information("Agent {Agent} authenticated for token {Token}. Beginning download of shares to {Filename}", agentName, guid, temp);
+
+ var sw = new Stopwatch();
+ sw.Start();
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", agentName, temp);
+ sw.Stop();
+
+ Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds);
await Relay.HandleShareUpload(agentName, id: guid, shares, temp);
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index d6bde1d7..c2d396a8 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -321,8 +321,6 @@ namespace slskd.Relay
using var content = new MultipartFormDataContent
{
- { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" },
- { new StringContent(ComputeCredential(token)), "credential" },
{ new StreamContent(stream), "file", filename },
};
@@ -418,6 +416,10 @@ namespace slskd.Relay
destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed");
}
+ // if the controller is Windows and the agent is Linux or vice versa, we need to translate
+ // the filename to the local OS or we're going to get funny results when we go to write the file
+ destinationFile = destinationFile.LocalizePath();
+
await Retry.Do(task: async () =>
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v0/relay/downloads/{token}");
diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs
index 47879b19..1dda50c2 100644
--- a/src/slskd/Relay/RelayService.cs
+++ b/src/slskd/Relay/RelayService.cs
@@ -456,7 +456,7 @@ namespace slskd.Relay
var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id);
var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout);
- Log.Information("Created wait {Key}", key);
+ Log.Debug("Created wait {Key}", key);
try
{
@@ -624,6 +624,8 @@ namespace slskd.Relay
/// <returns>The operation context.</returns>
public Task HandleShareUpload(string agentName, Guid id, IEnumerable<Share> shares, string filename)
{
+ Log.Information("Loading shares from agent {Agent}", agentName);
+
using var repository = ShareRepositoryFactory.CreateFromFile(filename);
if (!repository.TryValidate(out var problems))
@@ -637,6 +639,8 @@ namespace slskd.Relay
Shares.AddOrUpdateHost(new Host(agentName, shares));
+ Log.Information("Shares from agent {Agent} ready.", agentName);
+
return Task.CompletedTask;
}
@@ -694,8 +698,12 @@ namespace slskd.Relay
if (TryGetAgentRegistration(connectionId, out var found))
{
+ Log.Information("Unloading shares for agent {Agent}", found.Agent.Name);
+
Shares.TryRemoveHost(found.Agent.Name);
removed = RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record);
+
+ Log.Information("Shares for agent {Agent} unloaded", found.Agent.Name);
}
State.SetValue(state => state with { Agents = RegisteredAgents });
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index 8f78ed55..bdc18859 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -26,6 +26,7 @@ namespace slskd.Shares
using System.Threading;
using System.Threading.Tasks;
using Serilog;
+ using slskd.Relay;
using Soulseek;
/// <summary>
@@ -269,10 +270,22 @@ namespace slskd.Shares
{
string resolvedFilename = Local.Repository.FindFilename(remoteFilename);
- if (!string.IsNullOrEmpty(resolvedFilename))
+ // when we're debugging the relay (running as both controller and agent on the same instance)
+ // always resolve files from remote hosts, ignoring local. this is a crappy hack, but it is the
+ // least crappy way to maintain sanity while trying to debug this feature.
+ if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
{
+ Log.Warning("Ignoring resolved local file to facilitate Relay debugging.");
+ }
+ else if (!string.IsNullOrEmpty(resolvedFilename))
+ {
+ Log.Debug("Resolved remote file to {ResolvedFilename} on local host", resolvedFilename);
return Task.FromResult((Program.LocalHostName, resolvedFilename));
}
+ else
+ {
+ Log.Debug("Failed to resolve remote file on local host; searching remote hosts: {Hosts}", HostDictionary.Values.Select(h => h.Host.Name));
+ }
// file not found locally. begin searching other hosts one by one.
// this is the slow, dumb way to do this, but it's plenty fast in this context.
@@ -282,8 +295,11 @@ namespace slskd.Shares
if (!string.IsNullOrEmpty(resolvedFilename))
{
+ Log.Debug("Resolved remote file to {ResolvedFilename} on host {Host}", remoteFilename, host.Host.Name);
return Task.FromResult((host.Host.Name, resolvedFilename));
}
+
+ Log.Debug("Failed to resolve remote file on host {Host}", host.Host.Name);
}
throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a physical file");
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index c1184b21..cfbeeb8b 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -121,6 +121,8 @@ namespace slskd.Transfers.Uploads
{
(host, localFilename) = await Shares.ResolveFileAsync(filename);
+ Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename);
+
if (host == Program.LocalHostName)
{
// if it's local, do a quick check to see if it exists to spare the caller from