diff options
| author | JP Dillingham <jp@dillingham.me> | 2023-01-07 19:36:46 -0600 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2023-01-07 19:36:46 -0600 |
| commit | d682029e6f850040cd38764a491b070bdea3d126 (patch) | |
| tree | 877486c236ead4a7d0944ff13dfb2e65a393b33a /src | |
| parent | 177d12ef77488ae914045962e4d3a4ce24cdbc25 (diff) | |
| download | slskd-d682029e6f850040cd38764a491b070bdea3d126.tar.gz | |
run cleanup
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Relay/DummyRelayClient.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 404 |
2 files changed, 221 insertions, 201 deletions
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 c2d396a8..bb121b87 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. @@ -211,85 +220,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) { @@ -350,52 +446,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) @@ -411,13 +461,13 @@ 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 + // 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 () => @@ -459,118 +509,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) { @@ -584,24 +609,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 |
