From 01f33f56c103d6ba229856abffbf66292bed03ff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Jan 2023 15:53:30 -0600 Subject: tweak startup logic --- src/slskd/Application.cs | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 30fee1be..0da48ae5 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -400,32 +400,38 @@ 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.Agent) + if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum() == 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.Debug) + if (OptionsAtStartup.Relay.Enabled) + { + if (OptionsAtStartup.Relay.Mode.ToEnum() == RelayMode.Debug) + { + Log.Warning("Running in Debug relay mode; connecting to controller"); + _ = Relay.Client.StartAsync(cancellationToken); + } + else + { + Log.Information("Running in Controller relay mode. Listening for incoming Agent connections."); + } + } + + if (OptionsAtStartup.Flags.NoConnect) { - Log.Warning("Running in Debug relay mode; connecting to controller"); - _ = Relay.Client.StartAsync(cancellationToken); + 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); } } -- cgit v1.2.3 From 1b5485df80dd0483729fe4ebdb6280e500ab08b3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Jan 2023 15:56:18 -0600 Subject: tweak again --- src/slskd/Application.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 0da48ae5..01df00a1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -409,15 +409,13 @@ namespace slskd { if (OptionsAtStartup.Relay.Enabled) { + Log.Information("Running in Controller relay mode. Listening for incoming Agent connections."); + if (OptionsAtStartup.Relay.Mode.ToEnum() == RelayMode.Debug) { Log.Warning("Running in Debug relay mode; connecting to controller"); _ = Relay.Client.StartAsync(cancellationToken); } - else - { - Log.Information("Running in Controller relay mode. Listening for incoming Agent connections."); - } } if (OptionsAtStartup.Flags.NoConnect) -- cgit v1.2.3 From b61c047068ec4c8b44ba058d6cb9ebb1cf6c4dff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:21:43 -0600 Subject: fix ApiKeyOnly policy issue --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 2 +- src/slskd/Common/Authentication/AuthPolicy.cs | 2 +- src/slskd/Program.cs | 6 ++++++ 3 files changed, 8 insertions(+), 2 deletions(-) (limited to 'src') 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 /// /// Gets the API key authentication scheme name. /// - public static string AuthenticationScheme { get; } = "API Key"; + public static string AuthenticationScheme { get; } = "ApiKey"; } /// 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); -- cgit v1.2.3 From ee01ea15c674882b4e79da9c0364727f1e86c965 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:22:01 -0600 Subject: log file resolution --- src/slskd/Transfers/Uploads/UploadService.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') 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 -- cgit v1.2.3 From 3ce9de999597db6ae742722c86a7179c5d3282e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:29:23 -0600 Subject: solve for relay debugging in file resolution logic --- src/slskd/Shares/ShareService.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') 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; /// @@ -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.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"); -- cgit v1.2.3 From 8bcfe480bc0ec641dedb384a2af8e5f3866dcbb8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:30:06 -0600 Subject: use named params to avoid issues with positional weirdness --- src/slskd/Relay/API/Controllers/RelayController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index d4fb4810..69087310 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -200,7 +200,7 @@ namespace slskd.Relay // 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(); -- cgit v1.2.3 From c0b9ef897914242f4cb0556f5feae73f34914f9f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:30:38 -0600 Subject: validate filename and stream from multipart uploads --- src/slskd/Relay/API/Controllers/RelayController.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 69087310..a36e643d 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -185,6 +185,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) { -- cgit v1.2.3 From 8e73db196759307c89a7e5da1f87d49be9ba56c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:30:56 -0600 Subject: remove deprecated parts from multipart upload --- src/slskd/Relay/RelayClient.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index d6bde1d7..f506ab8f 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 }, }; -- cgit v1.2.3 From 87f72f7f482953c90ed50eca647f36827cdd64cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 16:14:00 -0600 Subject: polish logging --- src/slskd/Relay/API/Controllers/RelayController.cs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index a36e643d..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"); } @@ -204,7 +205,7 @@ 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 @@ -216,7 +217,7 @@ namespace slskd.Relay 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. @@ -279,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); @@ -290,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); -- cgit v1.2.3 From f734a9a8cce50e4ed638274758dd1ff0f99e14e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 16:14:15 -0600 Subject: polish logging --- src/slskd/Relay/RelayService.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src') 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 /// The operation context. public Task HandleShareUpload(string agentName, Guid id, IEnumerable 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 }); -- cgit v1.2.3 From f07a7758b47388c793d73ca54727db95abfcd229 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 16:14:32 -0600 Subject: localize filename --- src/slskd/Relay/RelayClient.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index f506ab8f..c2d396a8 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -416,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}"); -- cgit v1.2.3 From 94be479de298fd23628d0b9bcfb424f552be5ea1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:06:47 -0600 Subject: fail more gracefully on bad input --- src/slskd/Program.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 28ef7279..183f8426 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) -- cgit v1.2.3 From 7794a480f8320ad20b9dd786409a047b9a3db33a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:07:19 -0600 Subject: clamp secret length to > 16 < 255 --- src/slskd/Program.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 183f8426..969ff53f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -293,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; } -- cgit v1.2.3 From 384a388a2e4496bf35de835b811014d84f58b9fb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:36:15 -0600 Subject: disambiguate docs --- src/slskd/Common/CommonExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') 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 } /// - /// , but for paths normalized to use backslashes. + /// , but for paths normalized to use backslashes. /// /// /// @@ -312,7 +312,7 @@ namespace slskd } /// - /// , but for paths normalized to use backslashes. + /// , but for paths normalized to use backslashes. /// /// /// -- cgit v1.2.3 From 177d12ef77488ae914045962e4d3a4ce24cdbc25 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:36:30 -0600 Subject: handle null nbf claim --- src/slskd/Core/API/DTO/TokenResponse.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 /// /// Gets the value of the Not Before claim from the Access Token. /// - 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()); /// /// Gets the Access Token string. -- cgit v1.2.3 From d682029e6f850040cd38764a491b070bdea3d126 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:36:46 -0600 Subject: run cleanup --- src/slskd/Relay/DummyRelayClient.cs | 18 +- src/slskd/Relay/RelayClient.cs | 404 ++++++++++++++++++------------------ 2 files changed, 221 insertions(+), 201 deletions(-) (limited to 'src') 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 StateMonitor => new ManagedState(); - 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 /// public IStateMonitor StateMonitor { get; } - private ManagedState 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 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(); private bool LoggedIn { get; set; } private TaskCompletionSource LoggedInTaskCompletionSource { get; set; } - private bool Disposed { get; set; } + private IOptionsMonitor OptionsMonitor { get; } + private IShareService Shares { get; } + private CancellationTokenSource StartCancellationTokenSource { get; set; } + private bool StartRequested { get; set; } + private ManagedState State { get; } = new(); + private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1); + + /// + /// Disposes this instance. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } /// /// 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 + /// + /// Disposes this instance. + /// + /// + 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(); + + 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(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(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); + HubConnection.On(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); + HubConnection.On(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); + HubConnection.On(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.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(); + 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(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(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); - HubConnection.On(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); - HubConnection.On(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); - HubConnection.On(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 -- cgit v1.2.3 From c69c289b0b00a15d47e4c98fcf7def63b494051f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:36:56 -0600 Subject: remove async --- src/slskd/Shares/API/Controllers/SharesController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 Get(string id) + public IActionResult Get(string id) { var share = Shares.Hosts.SelectMany(host => host.Shares).FirstOrDefault(share => share.Id == id); -- cgit v1.2.3 From d911856eb26175377f6d7822e35fac394cbecde2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:37:10 -0600 Subject: don't throw ApplicationException --- src/slskd/Shares/SqliteShareRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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); } } } -- cgit v1.2.3 From 054f33802c0fa842cb474def384a579ca8e3322b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:37:45 -0600 Subject: add missing docs --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 1 + src/slskd/Users/API/Controllers/UsersController.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'src') 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 /// /// Initializes a new instance of the class. /// + /// /// public TransfersController( ITransferService transferService, 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; /// @@ -44,6 +43,7 @@ namespace slskd.Users.API /// /// /// + /// public UsersController(ISoulseekClient soulseekClient, IBrowseTracker browseTracker, IUserService userService, IOptionsSnapshot optionsSnapshot) { Client = soulseekClient; -- cgit v1.2.3 From 051340dc0d199983ba3458c828c740c61c4aa1b4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:38:06 -0600 Subject: add todo --- src/slskd/Application.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 01df00a1..48406931 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -753,6 +753,7 @@ namespace slskd private void Client_UserStatusChanged(object sender, UserStatus args) { + // todo: react to watched user status changes } private Task PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename) -- cgit v1.2.3 From 2c751aa3029c707f92e6323d10cb1152efb66de8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:44:06 -0600 Subject: remove whitespace --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 969ff53f..66773cb5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -687,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; } -- cgit v1.2.3 From 8e6e0e17edf8f958b4b5bf072491d8198d9ef64c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 19:49:03 -0600 Subject: include share upload in retry loop --- src/slskd/Relay/RelayClient.cs | 54 +++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index bb121b87..052eef79 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -150,7 +150,36 @@ 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) => { @@ -160,29 +189,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 { -- cgit v1.2.3 From 5133ac9eabc1ddf195002807f97a95ad0ab8d9a0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 20:01:46 -0600 Subject: move brace --- src/slskd/Relay/RelayClient.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 052eef79..5865c6f6 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -150,7 +150,8 @@ namespace slskd.Relay // retry indefinitely await Retry.Do( - task: async () => { + task: async () => + { await HubConnection.StartAsync(StartCancellationTokenSource.Token); State.SetValue(_ => TranslateState(HubConnection.State)); -- cgit v1.2.3