aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs35
-rw-r--r--src/slskd/Common/Authentication/ApiKeyAuthentication.cs2
-rw-r--r--src/slskd/Common/Authentication/AuthPolicy.cs2
-rw-r--r--src/slskd/Common/CommonExtensions.cs4
-rw-r--r--src/slskd/Core/API/DTO/TokenResponse.cs2
-rw-r--r--src/slskd/Program.cs24
-rw-r--r--src/slskd/Relay/API/Controllers/RelayController.cs34
-rw-r--r--src/slskd/Relay/DummyRelayClient.cs18
-rw-r--r--src/slskd/Relay/RelayClient.cs461
-rw-r--r--src/slskd/Relay/RelayService.cs10
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs2
-rw-r--r--src/slskd/Shares/ShareService.cs18
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs2
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs1
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs2
-rw-r--r--src/slskd/Users/API/Controllers/UsersController.cs2
16 files changed, 360 insertions, 259 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 30fee1be..48406931 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -400,32 +400,36 @@ namespace slskd
}
}
- if (OptionsAtStartup.Flags.NoConnect)
- {
- Log.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled");
- }
- else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password))
- {
- Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart.");
- }
- else if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Agent)
+ if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Agent)
{
Log.Information("Running in Agent relay mode; not connecting to the Soulseek server.");
await Relay.Client.StartAsync(cancellationToken);
}
else
{
- if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
+ if (OptionsAtStartup.Relay.Enabled)
{
- Log.Warning("Running in Debug relay mode; connecting to controller");
- _ = Relay.Client.StartAsync(cancellationToken);
+ Log.Information("Running in Controller relay mode. Listening for incoming Agent connections.");
+
+ if (OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
+ {
+ Log.Warning("Running in Debug relay mode; connecting to controller");
+ _ = Relay.Client.StartAsync(cancellationToken);
+ }
+ }
+
+ if (OptionsAtStartup.Flags.NoConnect)
+ {
+ Log.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled");
+ }
+ else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password))
+ {
+ Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart.");
}
else
{
- Log.Information("Running in Controller relay mode. Listening for incoming Agent connections.");
+ await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false);
}
-
- await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false);
}
}
@@ -749,6 +753,7 @@ namespace slskd
private void Client_UserStatusChanged(object sender, UserStatus args)
{
+ // todo: react to watched user status changes
}
private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename)
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/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 3ccc72e9..3dddd3b4 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -302,7 +302,7 @@ namespace slskd
}
/// <summary>
- /// <see cref="Path.GetDirectoryName"/>, but for paths normalized to use backslashes.
+ /// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
@@ -312,7 +312,7 @@ namespace slskd
}
/// <summary>
- /// <see cref="Path.GetFileName"/>, but for paths normalized to use backslashes.
+ /// <see cref="Path.GetFileName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
diff --git a/src/slskd/Core/API/DTO/TokenResponse.cs b/src/slskd/Core/API/DTO/TokenResponse.cs
index 85992917..47cfd335 100644
--- a/src/slskd/Core/API/DTO/TokenResponse.cs
+++ b/src/slskd/Core/API/DTO/TokenResponse.cs
@@ -49,7 +49,7 @@ namespace slskd.Core.API
/// <summary>
/// Gets the value of the Not Before claim from the Access Token.
/// </summary>
- public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf").Value);
+ public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf")?.Value ?? long.MaxValue.ToString());
/// <summary>
/// Gets the Access Token string.
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index d0b670a2..66773cb5 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -243,7 +243,17 @@ namespace slskd
// populate the properties above so that we can override the default config file if needed, and to
// check if the application is being run in command mode (run task and quit).
EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix);
+
+ try
+ {
Arguments.Populate(clearExistingValues: false);
+ }
+ catch (Exception ex)
+ {
+ // this is pretty hacky, but i don't have a good way of trapping errors that bubble up here.
+ Log.Error($"Invalid command line input: {ex.Message.Replace(". See inner exception for details.", string.Empty)}");
+ return;
+ }
// if a user has used one of the arguments above, perform the requested task, then quit
if (ShowVersion)
@@ -283,6 +293,12 @@ namespace slskd
if (GenerateSecret > 0)
{
+ if (GenerateSecret < 16 || GenerateSecret > 255)
+ {
+ Log.Error("Invalid command line input: secret length must be between 16 and 255, inclusive");
+ return;
+ }
+
Log.Information(Cryptography.Random.GetBytes(GenerateSecret).ToBase62());
return;
}
@@ -671,7 +687,7 @@ namespace slskd
}
catch
{
- // the token either isn't a valid API key. use the provided value and let the
+ // the token either isn't a valid API key. use the provided value and let the
// rest of the auth middleware figure out whether it is valid
context.Token = token;
}
@@ -696,6 +712,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/DummyRelayClient.cs b/src/slskd/Relay/DummyRelayClient.cs
index dca4f808..c5bd477c 100644
--- a/src/slskd/Relay/DummyRelayClient.cs
+++ b/src/slskd/Relay/DummyRelayClient.cs
@@ -24,12 +24,26 @@ namespace slskd.Relay
{
public IStateMonitor<RelayClientState> StateMonitor => new ManagedState<RelayClientState>();
- public void Dispose() { }
+ private bool Disposed { get; set; }
+
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ System.GC.SuppressFinalize(this);
+ }
public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task SynchronizeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!Disposed)
+ {
+ Disposed = true;
+ }
+ }
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index d6bde1d7..5865c6f6 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -94,20 +94,29 @@ namespace slskd.Relay
/// </summary>
public IStateMonitor<RelayClientState> StateMonitor { get; }
- private ManagedState<RelayClientState> State { get; } = new();
- private IShareService Shares { get; }
private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1);
- private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1);
- private string LastOptionsHash { get; set; }
- private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private bool Disposed { get; set; }
private IHttpClientFactory HttpClientFactory { get; }
private HubConnection HubConnection { get; set; }
- private bool StartRequested { get; set; }
- private CancellationTokenSource StartCancellationTokenSource { get; set; }
+ private string LastOptionsHash { get; set; }
private ILogger Log { get; } = Serilog.Log.ForContext<RelayClient>();
private bool LoggedIn { get; set; }
private TaskCompletionSource LoggedInTaskCompletionSource { get; set; }
- private bool Disposed { get; set; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private IShareService Shares { get; }
+ private CancellationTokenSource StartCancellationTokenSource { get; set; }
+ private bool StartRequested { get; set; }
+ private ManagedState<RelayClientState> State { get; } = new();
+ private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1);
+
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
/// <summary>
/// Starts the client and connects to the controller.
@@ -141,7 +150,37 @@ namespace slskd.Relay
// retry indefinitely
await Retry.Do(
- task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token),
+ task: async () =>
+ {
+ await HubConnection.StartAsync(StartCancellationTokenSource.Token);
+
+ State.SetValue(_ => TranslateState(HubConnection.State));
+ Log.Information("Relay controller connection established. Awaiting authentication...");
+
+ await LoggedInTaskCompletionSource.Task;
+
+ LoggedIn = true;
+
+ Log.Information("Authenticated. Uploading shares...");
+
+ try
+ {
+ // give the controller time to register the login; there's a race condition here
+ // that should be extremely unlikely, but i've seen it when debugging.
+ await Task.Delay(500);
+
+ await UploadSharesAsync();
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, ex.Message);
+ Log.Error("Disconnecting from the relay controller");
+ await StopAsync();
+ throw;
+ }
+
+ Log.Information("Shares uploaded. Ready to upload files.");
+ },
isRetryable: (attempts, ex) => true,
onFailure: (attempts, ex) =>
{
@@ -151,29 +190,6 @@ namespace slskd.Relay
maxAttempts: int.MaxValue,
maxDelayInMilliseconds: 30000,
StartCancellationTokenSource.Token);
-
- State.SetValue(_ => TranslateState(HubConnection.State));
- Log.Information("Relay controller connection established. Awaiting authentication...");
-
- await LoggedInTaskCompletionSource.Task;
-
- LoggedIn = true;
-
- Log.Information("Authenticated. Uploading shares...");
-
- try
- {
- await UploadSharesAsync();
- }
- catch (Exception ex)
- {
- Log.Error(ex, ex.Message);
- Log.Error("Disconnecting from the relay controller");
- await StopAsync();
- throw;
- }
-
- Log.Information("Shares uploaded. Ready to upload files.");
}
finally
{
@@ -211,85 +227,172 @@ namespace slskd.Relay
return UploadSharesAsync(cancellationToken);
}
- private RelayClientState TranslateState(HubConnectionState hub) => hub switch
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ /// <param name="disposing"></param>
+ protected virtual void Dispose(bool disposing)
{
- HubConnectionState.Disconnected => RelayClientState.Disconnected,
- HubConnectionState.Connected => RelayClientState.Connected,
- HubConnectionState.Connecting => RelayClientState.Connecting,
- HubConnectionState.Reconnecting => RelayClientState.Reconnecting,
- _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"),
- };
+ if (!Disposed)
+ {
+ if (disposing)
+ {
+ _ = HubConnection?.DisposeAsync();
+ }
- private async Task UploadSharesAsync(CancellationToken cancellationToken = default)
+ Disposed = true;
+ }
+ }
+
+ private string ComputeCredential(string token)
{
- if (!LoggedIn)
+ var options = OptionsMonitor.CurrentValue;
+
+ var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48);
+ var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token);
+
+ return Aes.Encrypt(tokenBytes, key).ToBase62();
+ }
+
+ private string ComputeCredential(Guid token) => ComputeCredential(token.ToString());
+
+ private void Configure(Options options)
+ {
+ var mode = options.Relay.Mode.ToEnum<RelayMode>();
+
+ if (mode != RelayMode.Agent && mode != RelayMode.Debug)
{
return;
}
- var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
-
- Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
+ ConfigurationSyncRoot.Wait();
try
{
- Log.Debug("Backing up shares to {Filename}", temp);
- await Shares.DumpAsync(temp);
- Log.Debug("Share backup successful");
+ var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson());
- Log.Debug("Requesting share upload token...");
- var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.BeginShareUpload));
- Log.Debug("Share upload token {Token}", token);
+ if (optionsHash == LastOptionsHash)
+ {
+ return;
+ }
- var stream = new FileStream(temp, FileMode.Open, FileAccess.Read);
+ Log.Debug("Relay options changed. Reconfiguring...");
- using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}");
+ // if the client is attempting a connection, cancel it it's going to be dropped when we create a new instance, but
+ // we need the retry loop around connection to stop.
+ StartCancellationTokenSource?.Cancel();
- 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));
+ HubConnection = new HubConnectionBuilder()
+ .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder =>
+ {
+ builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey);
+ builder.HttpMessageHandlerFactory = (message) =>
+ {
+ if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors)
+ {
+ clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true;
+ }
- using var content = new MultipartFormDataContent
- {
- { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" },
- { new StreamContent(stream), "database", "shares" },
- };
+ return message;
+ };
+ })
+ .WithAutomaticReconnect(new ControllerRetryPolicy(0, 1, 3, 10, 30, 60))
+ .Build();
- request.Content = content;
+ HubConnection.Reconnected += HubConnection_Reconnected;
+ HubConnection.Reconnecting += HubConnection_Reconnecting;
+ HubConnection.Closed += HubConnection_Closed;
- var size = ((double)stream.Length).SizeSuffix();
- var sw = new Stopwatch();
- sw.Start();
+ 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);
- Log.Information("Beginning upload of shares ({Size})", size);
- Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson());
- var response = await CreateHttpClient().SendAsync(request, cancellationToken);
+ LastOptionsHash = optionsHash;
- if (!response.IsSuccessStatusCode)
+ Log.Debug("Relay options reconfigured");
+
+ // if start was requested (if StartAsync() was called externally), restart after re-configuration
+ if (StartRequested)
{
- throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}");
+ Log.Information("Reconnecting the relay controller connection...");
+ _ = StartAsync();
}
-
- sw.Stop();
- Log.Information("Upload of shares succeeded ({Size} in {Duration}ms)", size, sw.ElapsedMilliseconds);
}
finally
{
- File.Delete(temp);
+ ConfigurationSyncRoot.Release();
}
}
- private string ComputeCredential(string token)
+ private HttpClient CreateHttpClient()
{
- var options = OptionsMonitor.CurrentValue;
+ var options = OptionsMonitor.CurrentValue.Relay.Controller;
+ HttpClient client;
- var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48);
- var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token);
+ if (options.IgnoreCertificateErrors)
+ {
+ client = new HttpClient(new HttpClientHandler()
+ {
+ ClientCertificateOptions = ClientCertificateOption.Manual,
+ ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
+ });
+ }
+ else
+ {
+ client = new HttpClient();
+ }
- return Aes.Encrypt(tokenBytes, key).ToBase62();
+ client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue);
+ client.BaseAddress = new(options.Address);
+ return client;
}
- private string ComputeCredential(Guid token) => ComputeCredential(token.ToString());
+ private async Task HandleAuthenticationChallenge(string challengeToken)
+ {
+ try
+ {
+ Log.Debug("Relay controller sent an authentication challenge");
+
+ var options = OptionsMonitor.CurrentValue;
+
+ var agent = options.InstanceName;
+ var response = ComputeCredential(challengeToken);
+
+ Log.Debug("Logging in...");
+ await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response);
+ Log.Debug("Login succeeded.");
+ LoggedInTaskCompletionSource?.TrySetResult();
+ }
+ catch (UnauthorizedAccessException)
+ {
+ await HubConnection.StopAsync();
+ Log.Error("Relay controller authentication failed. Check configuration.");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message);
+ }
+ }
+
+ private async Task HandleFileInfoRequest(string filename, Guid id)
+ {
+ Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id);
+
+ try
+ {
+ var (_, localFilename) = await Shares.ResolveFileAsync(filename);
+
+ var localFileInfo = new FileInfo(localFilename);
+
+ await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message);
+ await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0);
+ }
+ }
private Task HandleFileUploadRequest(string filename, long startOffset, Guid token)
{
@@ -321,8 +424,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 },
};
@@ -352,52 +453,6 @@ namespace slskd.Relay
return Task.CompletedTask;
}
- private async Task HandleFileInfoRequest(string filename, Guid id)
- {
- Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id);
-
- try
- {
- var (_, localFilename) = await Shares.ResolveFileAsync(filename);
-
- var localFileInfo = new FileInfo(localFilename);
-
- await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length);
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message);
- await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0);
- }
- }
-
- private async Task HandleAuthenticationChallenge(string challengeToken)
- {
- try
- {
- Log.Debug("Relay controller sent an authentication challenge");
-
- var options = OptionsMonitor.CurrentValue;
-
- var agent = options.InstanceName;
- var response = ComputeCredential(challengeToken);
-
- Log.Debug("Logging in...");
- await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response);
- Log.Debug("Login succeeded.");
- LoggedInTaskCompletionSource?.TrySetResult();
- }
- catch (UnauthorizedAccessException)
- {
- await HubConnection.StopAsync();
- Log.Error("Relay controller authentication failed. Check configuration.");
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message);
- }
- }
-
private Task HandleNotifyFileDownloadCompleted(string filename, Guid token)
{
if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads)
@@ -413,11 +468,15 @@ namespace slskd.Relay
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.
+ // 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");
}
+ // 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}");
@@ -457,118 +516,93 @@ namespace slskd.Relay
return Task.CompletedTask;
}
- private Task HubConnection_Reconnecting(Exception arg)
- {
- Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message);
- LoggedIn = false;
- State.SetValue(_ => TranslateState(HubConnection.State));
- return Task.CompletedTask;
- }
-
private async Task HubConnection_Reconnected(string arg)
{
Log.Warning("Relay controller connection reconnected");
+
// todo: does this need to log in again? does it retain the same connection id?
LoggedIn = true;
State.SetValue(_ => TranslateState(HubConnection.State));
await UploadSharesAsync();
}
- private HttpClient CreateHttpClient()
+ private Task HubConnection_Reconnecting(Exception arg)
{
- var options = OptionsMonitor.CurrentValue.Relay.Controller;
- HttpClient client;
-
- if (options.IgnoreCertificateErrors)
- {
- client = new HttpClient(new HttpClientHandler()
- {
- ClientCertificateOptions = ClientCertificateOption.Manual,
- ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
- });
- }
- else
- {
- client = new HttpClient();
- }
-
- client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue);
- client.BaseAddress = new(options.Address);
- return client;
+ Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message);
+ LoggedIn = false;
+ State.SetValue(_ => TranslateState(HubConnection.State));
+ return Task.CompletedTask;
}
- private void Configure(Options options)
+ private RelayClientState TranslateState(HubConnectionState hub) => hub switch
{
- var mode = options.Relay.Mode.ToEnum<RelayMode>();
+ HubConnectionState.Disconnected => RelayClientState.Disconnected,
+ HubConnectionState.Connected => RelayClientState.Connected,
+ HubConnectionState.Connecting => RelayClientState.Connecting,
+ HubConnectionState.Reconnecting => RelayClientState.Reconnecting,
+ _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"),
+ };
- if (mode != RelayMode.Agent && mode != RelayMode.Debug)
+ private async Task UploadSharesAsync(CancellationToken cancellationToken = default)
+ {
+ if (!LoggedIn)
{
return;
}
- ConfigurationSyncRoot.Wait();
+ var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
+
+ Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
try
{
- var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson());
-
- if (optionsHash == LastOptionsHash)
- {
- return;
- }
+ Log.Debug("Backing up shares to {Filename}", temp);
+ await Shares.DumpAsync(temp);
+ Log.Debug("Share backup successful");
- Log.Debug("Relay options changed. Reconfiguring...");
+ Log.Debug("Requesting share upload token...");
+ var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.BeginShareUpload));
+ Log.Debug("Share upload token {Token}", token);
- // if the client is attempting a connection, cancel it
- // it's going to be dropped when we create a new instance, but we need
- // the retry loop around connection to stop.
- StartCancellationTokenSource?.Cancel();
+ var stream = new FileStream(temp, FileMode.Open, FileAccess.Read);
- HubConnection = new HubConnectionBuilder()
- .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder =>
- {
- builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey);
- builder.HttpMessageHandlerFactory = (message) =>
- {
- if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors)
- {
- clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true;
- }
+ using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}");
- return message;
- };
- })
- .WithAutomaticReconnect(new ControllerRetryPolicy(0, 1, 3, 10, 30, 60))
- .Build();
+ 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));
- HubConnection.Reconnected += HubConnection_Reconnected;
- HubConnection.Reconnecting += HubConnection_Reconnecting;
- HubConnection.Closed += HubConnection_Closed;
+ using var content = new MultipartFormDataContent
+ {
+ { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" },
+ { new StreamContent(stream), "database", "shares" },
+ };
- 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);
+ request.Content = content;
- LastOptionsHash = optionsHash;
+ var size = ((double)stream.Length).SizeSuffix();
+ var sw = new Stopwatch();
+ sw.Start();
- Log.Debug("Relay options reconfigured");
+ Log.Information("Beginning upload of shares ({Size})", size);
+ Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson());
+ var response = await CreateHttpClient().SendAsync(request, cancellationToken);
- // if start was requested (if StartAsync() was called externally), restart
- // after re-configuration
- if (StartRequested)
+ if (!response.IsSuccessStatusCode)
{
- Log.Information("Reconnecting the relay controller connection...");
- _ = StartAsync();
+ throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}");
}
+
+ sw.Stop();
+ Log.Information("Upload of shares succeeded ({Size} in {Duration}ms)", size, sw.ElapsedMilliseconds);
}
finally
{
- ConfigurationSyncRoot.Release();
+ File.Delete(temp);
}
}
- private class ControllerRetryPolicy : IRetryPolicy
+ private sealed class ControllerRetryPolicy : IRetryPolicy
{
public ControllerRetryPolicy(params int[] intervals)
{
@@ -582,24 +616,5 @@ namespace slskd.Relay
return TimeSpan.FromSeconds(Intervals[Math.Min(retryContext.PreviousRetryCount, Intervals.Length - 1)]);
}
}
-
- protected virtual void Dispose(bool disposing)
- {
- if (!Disposed)
- {
- if (disposing)
- {
- _ = HubConnection?.DisposeAsync();
- }
-
- Disposed = true;
- }
- }
-
- public void Dispose()
- {
- Dispose(disposing: true);
- GC.SuppressFinalize(this);
- }
}
-}
+} \ No newline at end of file
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/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs
index e4f82848..2144a979 100644
--- a/src/slskd/Shares/API/Controllers/SharesController.cs
+++ b/src/slskd/Shares/API/Controllers/SharesController.cs
@@ -74,7 +74,7 @@ namespace slskd.Shares.API
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(Share), 200)]
[ProducesResponseType(404)]
- public async Task<IActionResult> Get(string id)
+ public IActionResult Get(string id)
{
var share = Shares.Hosts.SelectMany(host => host.Shares).FirstOrDefault(share => share.Id == id);
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/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index a4c4dd4c..f10b55e5 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -672,7 +672,7 @@ namespace slskd.Shares
var msg = "The internal share database has been corrupted or lost, and the application cannot continue to run. Please report this in a GitHub issue here: https://github.com/slskd/slskd/issues";
Log.Fatal(msg);
Environment.Exit(1);
- throw new ApplicationException(msg);
+ throw new DataMisalignedException(msg);
}
}
}
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index d664ae5d..aea815af 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -41,6 +41,7 @@ namespace slskd.Transfers.API
/// <summary>
/// Initializes a new instance of the <see cref="TransfersController"/> class.
/// </summary>
+ /// <param name="optionsSnapshot"></param>
/// <param name="transferService"></param>
public TransfersController(
ITransferService transferService,
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
diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs
index fc1ac415..c336dbd3 100644
--- a/src/slskd/Users/API/Controllers/UsersController.cs
+++ b/src/slskd/Users/API/Controllers/UsersController.cs
@@ -25,7 +25,6 @@ namespace slskd.Users.API
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
- using slskd.Relay;
using Soulseek;
/// <summary>
@@ -44,6 +43,7 @@ namespace slskd.Users.API
/// <param name="soulseekClient"></param>
/// <param name="browseTracker"></param>
/// <param name="userService"></param>
+ /// <param name="optionsSnapshot"></param>
public UsersController(ISoulseekClient soulseekClient, IBrowseTracker browseTracker, IUserService userService, IOptionsSnapshot<Options> optionsSnapshot)
{
Client = soulseekClient;