From 33eb63ce219fb03113819a7442a1e8af403d8785 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 09:12:44 -0500 Subject: fix broken Base62 encoding --- src/slskd/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index fd80d649..29531978 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -264,13 +264,13 @@ namespace slskd if (GenerateCertificate) { - GenerateX509Certificate(password: Cryptography.Random.GetBytes(16).ToBase62String(), filename: $"{AppName}.pfx"); + GenerateX509Certificate(password: Cryptography.Random.GetBytes(16).ToBase62(), filename: $"{AppName}.pfx"); return; } if (GenerateApiKey) { - Log.Information($"API Key: {Cryptography.Random.GetBytes(32).ToBase62String()}"); + Log.Information($"API Key: {Cryptography.Random.GetBytes(32).ToBase62()}"); return; } -- cgit v1.2.3 From b9628fa242944e36752b3d6c1511ab6e08d41589 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 18:24:38 -0500 Subject: add agents --- src/slskd/Program.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 29531978..e2cb5ca9 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -52,6 +52,7 @@ namespace slskd using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; + using slskd.Agents; using slskd.Authentication; using slskd.Configuration; using slskd.Core.API; @@ -524,6 +525,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -739,6 +741,7 @@ namespace slskd endpoints.MapHub("/hub/application"); endpoints.MapHub("/hub/logs"); endpoints.MapHub("/hub/search"); + endpoints.MapHub("/hub/agents"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); -- cgit v1.2.3 From da7063a3be3f3fbad0edd4b6aef44ed87396ba41 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 8 Oct 2022 16:30:22 -0500 Subject: add --generate-agent-secret --- src/slskd/Core/Options.cs | 14 ++++++++++++-- src/slskd/Program.cs | 10 +++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 02000869..a63154b4 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -133,11 +133,21 @@ namespace slskd /// [Argument('k', "generate-api-key")] [Description("generate random API key for HTTP/S")] - [Obsolete("USed only for documentation; see Program for actual implementation")] + [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] [YamlIgnore] public bool GenerateApiKey { get; init; } = false; + /// + /// Gets a value indicating whether to generate a random agent secret. + /// + [Argument('t', "generate-agent-secret")] + [Description("generate random agent secret")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool GenerateAgentSecret { get; init; } = false; + /// /// Gets a value indicating whether the application should run in debug mode. /// @@ -182,7 +192,7 @@ namespace slskd /// /// Gets the path where application data is saved. /// - [Argument(default, "app")] + [Argument('a', "app-dir")] [EnvironmentVariable("APP_DIR")] [Description("path where application data is saved")] [Obsolete("Used only for documentation; see Program for actual implementation")] diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e2cb5ca9..0de677a5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -213,6 +213,9 @@ namespace slskd [Argument('k', "generate-api-key", "generate a random API key")] private static bool GenerateApiKey { get; set; } + [Argument('t', "generate-agent-secret", "generate a random agent secret")] + private static bool GenerateAgentSecret { get; set; } + [Argument('n', "no-logo", "suppress logo on startup")] private static bool NoLogo { get; set; } @@ -275,6 +278,12 @@ namespace slskd return; } + if (GenerateAgentSecret) + { + Log.Information($"Agent Secret: {Aes.GenerateRandomKey().ToBase62()}"); + return; + } + // the application isn't being run in command mode. derive the application directory value // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; @@ -962,7 +971,6 @@ namespace slskd private static void GenerateX509Certificate(string password, string filename) { - Log.Information("Generating X509 certificate..."); filename = Path.Combine(AppContext.BaseDirectory, filename); var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable); -- cgit v1.2.3 From 120c6d0631fbd9a9f2c262171e713fcc6df01ea2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 08:57:09 -0500 Subject: rename Agents namespace to Network --- .../Agents/API/Controllers/AgentsController.cs | 83 ----- src/slskd/Agents/API/Hubs/AgentHub.cs | 91 ----- src/slskd/Agents/AgentService.cs | 365 --------------------- .../Network/API/Controllers/NetworkController.cs | 83 +++++ src/slskd/Network/API/Hubs/NetworkHub.cs | 91 +++++ src/slskd/Network/NetworkService.cs | 364 ++++++++++++++++++++ src/slskd/Program.cs | 7 +- src/slskd/Transfers/Uploads/UploadService.cs | 10 +- 8 files changed, 546 insertions(+), 548 deletions(-) delete mode 100644 src/slskd/Agents/API/Controllers/AgentsController.cs delete mode 100644 src/slskd/Agents/API/Hubs/AgentHub.cs delete mode 100644 src/slskd/Agents/AgentService.cs create mode 100644 src/slskd/Network/API/Controllers/NetworkController.cs create mode 100644 src/slskd/Network/API/Hubs/NetworkHub.cs create mode 100644 src/slskd/Network/NetworkService.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Agents/API/Controllers/AgentsController.cs b/src/slskd/Agents/API/Controllers/AgentsController.cs deleted file mode 100644 index 48f70cee..00000000 --- a/src/slskd/Agents/API/Controllers/AgentsController.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Agents -{ - using System; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Serilog; - - /// - /// Application. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - public class AgentsController : ControllerBase - { - public AgentsController(IAgentService agentService) - { - Agents = agentService; - } - - private IAgentService Agents { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Gets the current state of the application. - /// - /// - [HttpPost("files/{id}")] - [Authorize] - public async Task UploadFile(string id) - { - if (!Guid.TryParse(id, out var guid)) - { - return BadRequest("Id is not a valid Guid"); - } - - // get the record for the waiting file - if (Agents.PendingUploads.TryGetValue(guid, out var record)) - { - // get the stream from the multipart upload - var stream = Request.Form.Files.First().OpenReadStream(); - - // set the result for the stream - // this should pass control to the transfer service along with - // the stream - record.Upload.SetResult(stream); - - Console.WriteLine("Stream handed off. Waiting for completion..."); - - // wait for the transfer service to set the completion result - await record.Completion.Task; - - stream.Dispose(); - Console.WriteLine("Upload complete"); - return Ok(); - } - else - { - Log.Warning("Agent"); - return NotFound(); - } - } - } -} diff --git a/src/slskd/Agents/API/Hubs/AgentHub.cs b/src/slskd/Agents/API/Hubs/AgentHub.cs deleted file mode 100644 index 20ccdad0..00000000 --- a/src/slskd/Agents/API/Hubs/AgentHub.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Agents -{ - using System; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.SignalR; - using Serilog; - - public static class AgentHubMethods - { - public static readonly string RequestFile = "REQUEST_FILE"; - public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; - public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; - public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; - } - - /// - /// Extension methods for the agent SignalR hub. - /// - public static class AgentHubExtensions - { - public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) - { - // todo: how to send this to the specified agent? - return hub.Clients.All.SendAsync(AgentHubMethods.RequestFile, filename, id); - } - } - - /// - /// The agent SignalR hub. - /// - [Authorize] - public class AgentHub : Hub - { - public AgentHub( - IAgentService agentService) - { - Agents = agentService; - } - - private IAgentService Agents { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - public override async Task OnConnectedAsync() - { - Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); - await Clients.Caller.SendAsync(AgentHubMethods.AuthenticationChallenge, Agents.GenerateAuthenticationChallengeToken(Context.ConnectionId)); - } - - public override Task OnDisconnectedAsync(Exception exception) - { - if (Agents.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) - { - Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); - } - - return Task.CompletedTask; - } - - public bool Login(string agent, string challengeResponse) - { - if (Agents.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) - { - Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); - Agents.RegisterAgent(agent, Context.ConnectionId); - return true; - } - - Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); - Agents.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! - return false; - } - } -} \ No newline at end of file diff --git a/src/slskd/Agents/AgentService.cs b/src/slskd/Agents/AgentService.cs deleted file mode 100644 index 5749c8c8..00000000 --- a/src/slskd/Agents/AgentService.cs +++ /dev/null @@ -1,365 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Agents -{ - using System; - using System.Collections.Concurrent; - using System.Collections.ObjectModel; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.AspNetCore.SignalR; - using Microsoft.AspNetCore.SignalR.Client; - using Microsoft.Extensions.Caching.Memory; - using Serilog; - using slskd.Cryptography; - - public interface IAgentService - { - /// - /// Gets the collection of pending Agent uploads. - /// - ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } - - /// - /// Gets the collection of registered Agents. - /// - ReadOnlyDictionary RegisteredAgents { get; } - - /// - /// Retrieves an upload of the specified from the specified . - /// - /// The agent from which to retrieve the file. - /// The file to retrieve. - /// An optional timeout value. - /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000); - - /// - /// Registers the specified name with the specified . - /// - /// The ID of the connection. - /// The name of the agent. - void RegisterAgent(string connectionId, string agent); - - /// - /// Attempts to remove the registration for the specified . - /// - /// The ID of the connection. - /// A value indicating whether a registration was removed. - bool TryRemoveAgentRegistration(string connectionId, out string agent); - - /// - /// Generates a random authentication challenge token for the specified . - /// - /// The ID of the agent connection. - /// The generated token. - string GenerateAuthenticationChallengeToken(string connectionId); - - /// - /// Validates an authentication challenge response. - /// - /// The ID of the agent connection. - /// The agent name. - /// The challenge response provided by the agent. - /// A value indicating whether the response is valid. - bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); - } - - public class AgentService : IAgentService - { - public AgentService( - IOptionsMonitor optionsMonitor, - IHttpClientFactory httpClientFactory, - IHubContext agentHub) - { - AgentHub = agentHub; - HttpClientFactory = httpClientFactory; - - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(options => Configure(options)); - - Configure(OptionsMonitor.CurrentValue); - } - - /// - /// Gets the collection of pending Agent uploads. - /// - public ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads => new(PendingUploadDictionary); - - /// - /// Gets the collection of registered Agents. - /// - public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); - - private ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploadDictionary { get; } = new(); - private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); - private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); - private IOptionsMonitor OptionsMonitor { get; } - private IHttpClientFactory HttpClientFactory { get; } - private HttpClient HttpClient { get; set; } - private HubConnection HubConnection { get; set; } - private IHubContext AgentHub { get; set; } - private string LastOptionsHash { get; set; } - private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Registers the specified name with the specified . - /// - /// The ID of the connection. - /// The name of the agent. - public void RegisterAgent(string connectionId, string agent) - => RegisteredAgentDictionary.TryAdd(connectionId, agent); - - /// - /// Attempts to remove the registration for the specified . - /// - /// The ID of the connection. - /// The name of the agent, if a registration was removed. - /// A value indicating whether a registration was removed. - public bool TryRemoveAgentRegistration(string connectionId, out string agent) - => RegisteredAgentDictionary.TryRemove(connectionId, out agent); - - /// - /// Generates a random authentication challenge token for the specified . - /// - /// The ID of the agent connection. - /// The generated token. - public string GenerateAuthenticationChallengeToken(string connectionId) - { - var token = Cryptography.Random.GetBytes(16).ToBase62(); - - // this token is only valid for this connection id for a short time - // this is important to prevent replay-type attacks. - MemoryCache.Set(connectionId, token, TimeSpan.FromMinutes(1)); - Log.Debug("Cached token {Token} for ID {Id}", token, connectionId); - return token; - } - - /// - /// Validates an authentication challenge response. - /// - /// The ID of the agent connection. - /// The agent name. - /// The challenge response provided by the agent. - /// A value indicating whether the response is valid. - public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) - { - if (!MemoryCache.TryGetValue(connectionId, out var challengeToken)) - { - Log.Debug("Auth challenge for {Id} failed: no challenge token cached for ID", connectionId); - return false; - } - - if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agent, out var agentOptions)) - { - Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agent); - return false; - } - - var key = agentOptions.Secret.FromBase62(); - var tokenBytes = ((string)challengeToken).FromBase62(); - var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62(); - - return expectedResponse == challengeResponse; - } - - /// - /// Retrieves an upload of the specified from the specified . - /// - /// The agent from which to retrieve the file. - /// The file to retrieve. - /// An optional timeout value. - /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000) - { - var id = Guid.NewGuid(); - - // create a TCS for the upload stream. this is awaited below and completed in - // the API controller when the agent POSTs the file - var upload = new TaskCompletionSource(); - - // create a TCS for the upload itself. this is awaited by the API controller - // and completed by the transfer service when the upload to the remote user is complete - // the API controller needs to wait until the remote transfer is complete in order to - // keep the stream open for the duration - var completion = new TaskCompletionSource(); - - PendingUploadDictionary.TryAdd(id, (upload, completion)); - - await AgentHub.RequestFileAsync(agent, filename, id); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); - - if (task == upload.Task) - { - var stream = await upload.Task; - return (stream, completion); - } - else - { - throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); - } - } - - private async Task HandleFileRequest(Guid id, string filename) - { - Log.Information("Controller requested file {Filename} with ID {Id}", filename, id); - - try - { - using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); - using var content = new MultipartFormDataContent - { - { new StreamContent(stream), "file", filename }, - }; - - request.Content = content; - - Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); - var response = await HttpClient.SendAsync(request); - - if (!response.IsSuccessStatusCode) - { - Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); - Console.WriteLine("Failed"); - Console.WriteLine(response.StatusCode); - } - else - { - Console.WriteLine($"{filename} sent!"); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); - } - } - - private async Task HandleAuthenticationChallenge(string challengeToken) - { - Log.Information("Controller sent an authentication challenge"); - - try - { - var options = OptionsMonitor.CurrentValue; - - var agent = options.InstanceName; - var key = options.Network.Controller.Secret.FromBase62(); - var tokenBytes = challengeToken.FromBase62(); - - var response = Aes.Encrypt(tokenBytes, key).ToBase62(); - - Log.Information("Logging in..."); - var success = await HubConnection.InvokeAsync("Login", agent, response); - - if (!success) - { - await HubConnection.StopAsync(); - Log.Error("Controller authentication failed. Check configuration."); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); - } - } - - private void Configure(Options options) - { - ConfigurationSyncRoot.Wait(); - - try - { - var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); - - if (optionsHash == LastOptionsHash) - { - return; - } - - var mode = options.Network.OperationMode.ToEnum(); - - //if (mode == NetworkOperationMode.Agent - //{ - HttpClient = HttpClientFactory.CreateClient(); - HttpClient.BaseAddress = new(options.Network.Controller.Address); - - HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Network.Controller.Address}/hub/agents") - .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) - .Build(); - - HubConnection.Reconnected += HubConnection_Reconnected; - HubConnection.Reconnecting += HubConnection_Reconnecting; - HubConnection.Closed += HubConnection_Closed; - - HubConnection.On(AgentHubMethods.RequestFile, HandleFileRequest); - HubConnection.On(AgentHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); - - _ = Task.Run(async () => - { - // it takes a bit for the application to become responsive to network calls - await Task.Delay(3000); - - // retry indefinitely - await Retry.Do( - task: () => HubConnection.StartAsync(), - isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to controller: {Message}", attempts, ex.Message), - maxAttempts: int.MaxValue, - maxDelayInMilliseconds: 30000); - - Log.Information("Controller connection established"); - }); - //} - - LastOptionsHash = optionsHash; - } - finally - { - ConfigurationSyncRoot.Release(); - } - } - - private Task HubConnection_Closed(Exception arg) - { - Log.Warning("Controller connection closed: {Message}", arg.Message); - return Task.CompletedTask; - } - - private Task HubConnection_Reconnecting(Exception arg) - { - Log.Warning("Controller connection reconnecting: {Message}", arg.Message); - return Task.CompletedTask; - } - - private Task HubConnection_Reconnected(string arg) - { - Log.Warning("Controller connection reconnected"); - return Task.CompletedTask; - } - } -} diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs new file mode 100644 index 00000000..836921f1 --- /dev/null +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -0,0 +1,83 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Network +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Serilog; + + /// + /// Network. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + public class NetworkController : ControllerBase + { + public NetworkController(INetworkService networkService) + { + Network = networkService; + } + + private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Gets the current state of the application. + /// + /// + [HttpPost("files/{id}")] + [Authorize] + public async Task UploadFile(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + // get the record for the waiting file + if (Network.PendingUploads.TryGetValue(guid, out var record)) + { + // get the stream from the multipart upload + var stream = Request.Form.Files.First().OpenReadStream(); + + // set the result for the stream + // this should pass control to the transfer service along with + // the stream + record.Upload.SetResult(stream); + + Console.WriteLine("Stream handed off. Waiting for completion..."); + + // wait for the transfer service to set the completion result + await record.Completion.Task; + + stream.Dispose(); + Console.WriteLine("Upload complete"); + return Ok(); + } + else + { + Log.Warning("Agent"); + return NotFound(); + } + } + } +} diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs new file mode 100644 index 00000000..61ac08f0 --- /dev/null +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -0,0 +1,91 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Network +{ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.SignalR; + using Serilog; + + public static class NetworkHubMethods + { + public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; + public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; + public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; + } + + /// + /// Extension methods for the network SignalR hub. + /// + public static class NetworkHubExtensions + { + public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) + { + // todo: how to send this to the specified agent? + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); + } + } + + /// + /// The network SignalR hub. + /// + [Authorize] + public class NetworkHub : Hub + { + public NetworkHub( + INetworkService networkService) + { + Network = networkService; + } + + private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public override async Task OnConnectedAsync() + { + Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); + await Clients.Caller.SendAsync(NetworkHubMethods.AuthenticationChallenge, Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + } + + public override Task OnDisconnectedAsync(Exception exception) + { + if (Network.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) + { + Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); + } + + return Task.CompletedTask; + } + + public bool Login(string agent, string challengeResponse) + { + if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) + { + Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); + Network.RegisterAgent(agent, Context.ConnectionId); + return true; + } + + Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! + return false; + } + } +} \ No newline at end of file diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs new file mode 100644 index 00000000..86e0f80a --- /dev/null +++ b/src/slskd/Network/NetworkService.cs @@ -0,0 +1,364 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Network +{ + using System; + using System.Collections.Concurrent; + using System.Collections.ObjectModel; + using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + using Microsoft.AspNetCore.SignalR.Client; + using Microsoft.Extensions.Caching.Memory; + using Serilog; + using slskd.Cryptography; + + public interface INetworkService + { + /// + /// Gets the collection of pending Agent uploads. + /// + ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } + + /// + /// Gets the collection of registered Agents. + /// + ReadOnlyDictionary RegisteredAgents { get; } + + /// + /// Retrieves an upload of the specified from the specified . + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// An optional timeout value. + /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. + Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000); + + /// + /// Registers the specified name with the specified . + /// + /// The ID of the connection. + /// The name of the agent. + void RegisterAgent(string connectionId, string agent); + + /// + /// Attempts to remove the registration for the specified . + /// + /// The ID of the connection. + /// A value indicating whether a registration was removed. + bool TryRemoveAgentRegistration(string connectionId, out string agent); + + /// + /// Generates a random authentication challenge token for the specified . + /// + /// The ID of the agent connection. + /// The generated token. + string GenerateAuthenticationChallengeToken(string connectionId); + + /// + /// Validates an authentication challenge response. + /// + /// The ID of the agent connection. + /// The agent name. + /// The challenge response provided by the agent. + /// A value indicating whether the response is valid. + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); + } + + public class NetworkService : INetworkService + { + public NetworkService( + IOptionsMonitor optionsMonitor, + IHttpClientFactory httpClientFactory, + IHubContext networkHub) + { + NetworkHub = networkHub; + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + /// + /// Gets the collection of pending Agent uploads. + /// + public ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads => new(PendingUploadDictionary); + + /// + /// Gets the collection of registered Agents. + /// + public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); + + private ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploadDictionary { get; } = new(); + private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); + private IOptionsMonitor OptionsMonitor { get; } + private IHttpClientFactory HttpClientFactory { get; } + private HttpClient HttpClient { get; set; } + private HubConnection HubConnection { get; set; } + private IHubContext NetworkHub { get; set; } + private string LastOptionsHash { get; set; } + private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Registers the specified name with the specified . + /// + /// The ID of the connection. + /// The name of the agent. + public void RegisterAgent(string connectionId, string agent) + => RegisteredAgentDictionary.TryAdd(connectionId, agent); + + /// + /// Attempts to remove the registration for the specified . + /// + /// The ID of the connection. + /// The name of the agent, if a registration was removed. + /// A value indicating whether a registration was removed. + public bool TryRemoveAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryRemove(connectionId, out agent); + + /// + /// Generates a random authentication challenge token for the specified . + /// + /// The ID of the agent connection. + /// The generated token. + public string GenerateAuthenticationChallengeToken(string connectionId) + { + var token = Cryptography.Random.GetBytes(16).ToBase62(); + + // this token is only valid for this connection id for a short time + // this is important to prevent replay-type attacks. + MemoryCache.Set(connectionId, token, TimeSpan.FromMinutes(1)); + Log.Debug("Cached token {Token} for ID {Id}", token, connectionId); + return token; + } + + /// + /// Validates an authentication challenge response. + /// + /// The ID of the agent connection. + /// The agent name. + /// The challenge response provided by the agent. + /// A value indicating whether the response is valid. + public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) + { + if (!MemoryCache.TryGetValue(connectionId, out var challengeToken)) + { + Log.Debug("Auth challenge for {Id} failed: no challenge token cached for ID", connectionId); + return false; + } + + if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agent, out var agentOptions)) + { + Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agent); + return false; + } + + var key = agentOptions.Secret.FromBase62(); + var tokenBytes = ((string)challengeToken).FromBase62(); + var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62(); + + return expectedResponse == challengeResponse; + } + + /// + /// Retrieves an upload of the specified from the specified . + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// An optional timeout value. + /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + + // create a TCS for the upload stream. this is awaited below and completed in + // the API controller when the agent POSTs the file + var upload = new TaskCompletionSource(); + + // create a TCS for the upload itself. this is awaited by the API controller + // and completed by the transfer service when the upload to the remote user is complete + // the API controller needs to wait until the remote transfer is complete in order to + // keep the stream open for the duration + var completion = new TaskCompletionSource(); + + PendingUploadDictionary.TryAdd(id, (upload, completion)); + + await NetworkHub.RequestFileAsync(agent, filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); + + var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + + if (task == upload.Task) + { + var stream = await upload.Task; + return (stream, completion); + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); + } + } + + private async Task HandleFileRequest(Guid id, string filename) + { + Log.Information("Controller requested file {Filename} with ID {Id}", filename, id); + + try + { + using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "file", filename }, + }; + + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + Console.WriteLine("Failed"); + Console.WriteLine(response.StatusCode); + } + else + { + Console.WriteLine($"{filename} sent!"); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + } + } + + private async Task HandleAuthenticationChallenge(string challengeToken) + { + Log.Information("Controller sent an authentication challenge"); + + try + { + var options = OptionsMonitor.CurrentValue; + + var agent = options.InstanceName; + var key = options.Network.Controller.Secret.FromBase62(); + var tokenBytes = challengeToken.FromBase62(); + + var response = Aes.Encrypt(tokenBytes, key).ToBase62(); + + Log.Information("Logging in..."); + var success = await HubConnection.InvokeAsync("Login", agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Controller authentication failed. Check configuration."); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + } + } + + private void Configure(Options options) + { + ConfigurationSyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); + + if (optionsHash == LastOptionsHash) + { + return; + } + + var mode = options.Network.OperationMode.ToEnum(); + + //if (mode == NetworkOperationMode.Agent + //{ + HttpClient = HttpClientFactory.CreateClient(); + HttpClient.BaseAddress = new(options.Network.Controller.Address); + + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) + .Build(); + + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + + _ = Task.Run(async () => + { + // it takes a bit for the application to become responsive to network calls + await Task.Delay(3000); + + // retry indefinitely + await Retry.Do( + task: () => HubConnection.StartAsync(), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to controller: {Message}", attempts, ex.Message), + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000); + + Log.Information("Controller connection established"); + }); + //} + + LastOptionsHash = optionsHash; + } + finally + { + ConfigurationSyncRoot.Release(); + } + } + + private Task HubConnection_Closed(Exception arg) + { + Log.Warning("Controller connection closed: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnecting(Exception arg) + { + Log.Warning("Controller connection reconnecting: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnected(string arg) + { + Log.Warning("Controller connection reconnected"); + return Task.CompletedTask; + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 0de677a5..907090a5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -32,7 +32,6 @@ namespace slskd using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; @@ -52,7 +51,6 @@ namespace slskd using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; - using slskd.Agents; using slskd.Authentication; using slskd.Configuration; using slskd.Core.API; @@ -60,6 +58,7 @@ namespace slskd using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Messaging; + using slskd.Network; using slskd.Search; using slskd.Search.API; using slskd.Shares; @@ -534,7 +533,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -750,7 +749,7 @@ namespace slskd endpoints.MapHub("/hub/application"); endpoints.MapHub("/hub/logs"); endpoints.MapHub("/hub/search"); - endpoints.MapHub("/hub/agents"); + endpoints.MapHub("/hub/agents"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5d49c3e1..5b0bf749 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -30,7 +30,7 @@ namespace slskd.Transfers.Uploads using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; - using slskd.Agents; + using slskd.Network; using slskd.Shares; using slskd.Users; @@ -44,13 +44,13 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, IShareService shareService, - IAgentService agentService, + INetworkService networkService, IDbContextFactory contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; - Agents = agentService; + Network = networkService; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; @@ -75,7 +75,7 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private IOptionsMonitor OptionsMonitor { get; } - private IAgentService Agents { get; set; } + private INetworkService Network { get; } /// /// Adds the specified . Supersedes any existing record for the same file and username. @@ -220,7 +220,7 @@ namespace slskd.Transfers.Uploads //using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - var (stream, completion) = await Agents.GetUpload("any", filename); + var (stream, completion) = await Network.GetUpload("any", filename); var completedTransfer = await Client.UploadAsync( username, -- cgit v1.2.3 From bccd6202d2d3d6e60b6a24423f0ab628b6d7dd39 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 14:51:30 -0500 Subject: split network client from service --- src/slskd/Application.cs | 19 ++- src/slskd/Network/NetworkClient.cs | 243 ++++++++++++++++++++++++++++++++++++ src/slskd/Network/NetworkService.cs | 142 --------------------- src/slskd/Program.cs | 2 + 4 files changed, 260 insertions(+), 146 deletions(-) create mode 100644 src/slskd/Network/NetworkClient.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 31949fd5..e0688848 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -42,6 +42,7 @@ namespace slskd using slskd.Core.API; using slskd.Integrations.Pushbullet; using slskd.Messaging; + using slskd.Network; using slskd.Search; using slskd.Shares; using slskd.Transfers; @@ -87,6 +88,7 @@ namespace slskd IRoomService roomService, IUserService userService, IShareService shareService, + INetworkClient networkClient, IPushbulletService pushbulletService, IHubContext applicationHub, IHubContext logHub) @@ -135,6 +137,8 @@ namespace slskd LogHub = logHub; Program.LogEmitted += (_, log) => LogHub.EmitLogAsync(log); + NetworkClient = networkClient; + Client = soulseekClient; Client.DiagnosticGenerated += Client_DiagnosticGenerated; @@ -174,6 +178,7 @@ namespace slskd private static bool ShuttingDown { get; set; } = false; private ISoulseekClient Client { get; set; } + private INetworkClient NetworkClient { get; set; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } private IConnectionWatchdog ConnectionWatchdog { get; } @@ -391,12 +396,18 @@ namespace slskd { 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.Network.OperationMode.ToEnum() == NetworkOperationMode.Agent) - //{ - // Log.Information("Running in Agent mode; not connecting to the Soulseek server."); - //} + else if (OptionsAtStartup.Network.OperationMode.ToEnum() == NetworkOperationMode.Agent || !OptionsAtStartup.Flags.DualNetworkMode) + { + Log.Information("Running in Agent mode; not connecting to the Soulseek server."); + await NetworkClient.StartAsync(cancellationToken); + } else { + if (OptionsAtStartup.Flags.DualNetworkMode) + { + await NetworkClient.StartAsync(cancellationToken); + } + await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs new file mode 100644 index 00000000..be7b6a2c --- /dev/null +++ b/src/slskd/Network/NetworkClient.cs @@ -0,0 +1,243 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Network +{ + using System; + using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR.Client; + using Serilog; + using slskd.Cryptography; + + public interface INetworkClient + { + Task StartAsync(CancellationToken cancellationToken = default); + Task StopAsync(CancellationToken cancellationToken = default); + } + + public class NetworkClient : INetworkClient + { + public NetworkClient( + IOptionsMonitor optionsMonitor, + IHttpClientFactory httpClientFactory) + { + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private string LastOptionsHash { get; set; } + private IOptionsMonitor OptionsMonitor { get; } + private IHttpClientFactory HttpClientFactory { get; } + private HttpClient HttpClient { get; set; } + private HubConnection HubConnection { get; set; } + private bool StartRequested { get; set; } + private CancellationTokenSource StartCancellationTokenSource { get; set; } + + public async Task StartAsync(CancellationToken cancellationToken = default) + { + if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum() != NetworkOperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) + { + throw new InvalidOperationException($"Network client can only be started when operation mode is {NetworkOperationMode.Agent}"); + } + + StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + StartRequested = true; + + Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); + + // retry indefinitely + await Retry.Do( + task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message), + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000, + StartCancellationTokenSource.Token); + + Log.Information("Network controller connection established"); + } + + public async Task StopAsync(CancellationToken cancellationToken = default) + { + StartRequested = false; + + if (HubConnection != null) + { + await HubConnection.StopAsync(cancellationToken); + + Log.Information("Network controller connection disconnected"); + } + } + + private async Task HandleFileRequest(Guid id, string filename) + { + Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); + + try + { + using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "file", filename }, + }; + + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + Console.WriteLine("Failed"); + Console.WriteLine(response.StatusCode); + } + else + { + Console.WriteLine($"{filename} sent!"); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + } + } + + private async Task HandleAuthenticationChallenge(string challengeToken) + { + Log.Information("Network controller sent an authentication challenge"); + + try + { + var options = OptionsMonitor.CurrentValue; + + var agent = options.InstanceName; + var key = options.Network.Controller.Secret.FromBase62(); + var tokenBytes = challengeToken.FromBase62(); + + var response = Aes.Encrypt(tokenBytes, key).ToBase62(); + + Log.Information("Logging in..."); + var success = await HubConnection.InvokeAsync("Login", agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Network controller authentication failed. Check configuration."); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + } + } + + private Task HubConnection_Closed(Exception arg) + { + Log.Warning("Network controller connection closed: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnecting(Exception arg) + { + Log.Warning("Network controller connection reconnecting: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnected(string arg) + { + Log.Warning("Network controller connection reconnected"); + return Task.CompletedTask; + } + + private void Configure(Options options) + { + if (options.Network.OperationMode.ToEnum() != NetworkOperationMode.Agent && !options.Flags.DualNetworkMode) + { + return; + } + + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + + if (optionsHash == LastOptionsHash) + { + return; + } + + Log.Information("Network options changed. Reconfiguring..."); + + // 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(); + + HttpClient = HttpClientFactory.CreateClient(); + HttpClient.BaseAddress = new(options.Network.Controller.Address); + + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect(new[] + { + TimeSpan.FromSeconds(0), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(3), + TimeSpan.FromSeconds(10), + TimeSpan.FromSeconds(30), + }) + .Build(); + + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + + LastOptionsHash = optionsHash; + + Log.Information("Network options reconfigured"); + + // if start was requested (if StartAsync() was called externally), restart + // after re-configuration + if (StartRequested) + { + Log.Information("Reconnecting the network controller connection..."); + _ = StartAsync(); + } + } + finally + { + SyncRoot.Release(); + } + } + } +} diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 86e0f80a..368e6cf4 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -95,9 +95,6 @@ namespace slskd.Network HttpClientFactory = httpClientFactory; OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(options => Configure(options)); - - Configure(OptionsMonitor.CurrentValue); } /// @@ -221,144 +218,5 @@ namespace slskd.Network throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); } } - - private async Task HandleFileRequest(Guid id, string filename) - { - Log.Information("Controller requested file {Filename} with ID {Id}", filename, id); - - try - { - using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); - using var content = new MultipartFormDataContent - { - { new StreamContent(stream), "file", filename }, - }; - - request.Content = content; - - Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); - var response = await HttpClient.SendAsync(request); - - if (!response.IsSuccessStatusCode) - { - Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); - Console.WriteLine("Failed"); - Console.WriteLine(response.StatusCode); - } - else - { - Console.WriteLine($"{filename} sent!"); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); - } - } - - private async Task HandleAuthenticationChallenge(string challengeToken) - { - Log.Information("Controller sent an authentication challenge"); - - try - { - var options = OptionsMonitor.CurrentValue; - - var agent = options.InstanceName; - var key = options.Network.Controller.Secret.FromBase62(); - var tokenBytes = challengeToken.FromBase62(); - - var response = Aes.Encrypt(tokenBytes, key).ToBase62(); - - Log.Information("Logging in..."); - var success = await HubConnection.InvokeAsync("Login", agent, response); - - if (!success) - { - await HubConnection.StopAsync(); - Log.Error("Controller authentication failed. Check configuration."); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); - } - } - - private void Configure(Options options) - { - ConfigurationSyncRoot.Wait(); - - try - { - var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); - - if (optionsHash == LastOptionsHash) - { - return; - } - - var mode = options.Network.OperationMode.ToEnum(); - - //if (mode == NetworkOperationMode.Agent - //{ - HttpClient = HttpClientFactory.CreateClient(); - HttpClient.BaseAddress = new(options.Network.Controller.Address); - - HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Network.Controller.Address}/hub/agents") - .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) - .Build(); - - HubConnection.Reconnected += HubConnection_Reconnected; - HubConnection.Reconnecting += HubConnection_Reconnecting; - HubConnection.Closed += HubConnection_Closed; - - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); - HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); - - _ = Task.Run(async () => - { - // it takes a bit for the application to become responsive to network calls - await Task.Delay(3000); - - // retry indefinitely - await Retry.Do( - task: () => HubConnection.StartAsync(), - isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to controller: {Message}", attempts, ex.Message), - maxAttempts: int.MaxValue, - maxDelayInMilliseconds: 30000); - - Log.Information("Controller connection established"); - }); - //} - - LastOptionsHash = optionsHash; - } - finally - { - ConfigurationSyncRoot.Release(); - } - } - - private Task HubConnection_Closed(Exception arg) - { - Log.Warning("Controller connection closed: {Message}", arg.Message); - return Task.CompletedTask; - } - - private Task HubConnection_Reconnecting(Exception arg) - { - Log.Warning("Controller connection reconnecting: {Message}", arg.Message); - return Task.CompletedTask; - } - - private Task HubConnection_Reconnected(string arg) - { - Log.Warning("Controller connection reconnected"); - return Task.CompletedTask; - } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 907090a5..1c0a6852 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -533,7 +533,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From a0a984cebed195a814152de95bed480ea9a3d29d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 14 Oct 2022 18:29:11 -0500 Subject: wip --- .../Network/API/Controllers/NetworkController.cs | 25 ++- src/slskd/Network/NetworkClient.cs | 28 ++-- src/slskd/Program.cs | 5 +- src/slskd/Shares/IReadOnlyShareRepository.cs | 26 --- src/slskd/Shares/IReadWriteShareRepository.cs | 96 ----------- src/slskd/Shares/IShareRepository.cs | 89 +++++++++- src/slskd/Shares/IShareRepositoryFactory.cs | 46 ++++++ src/slskd/Shares/IShareService.cs | 13 +- src/slskd/Shares/ShareConnectionStringFactory.cs | 58 ------- src/slskd/Shares/ShareRepositoryFactory.cs | 74 +++++++++ src/slskd/Shares/ShareScanner.cs | 4 +- src/slskd/Shares/ShareService.cs | 64 ++++--- src/slskd/Shares/SqliteShareRepository.cs | 183 ++++++++++++--------- 13 files changed, 384 insertions(+), 327 deletions(-) delete mode 100644 src/slskd/Shares/IReadOnlyShareRepository.cs delete mode 100644 src/slskd/Shares/IReadWriteShareRepository.cs create mode 100644 src/slskd/Shares/IShareRepositoryFactory.cs delete mode 100644 src/slskd/Shares/ShareConnectionStringFactory.cs create mode 100644 src/slskd/Shares/ShareRepositoryFactory.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 69e3d789..deeddc04 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -24,6 +24,7 @@ namespace slskd.Network using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; + using slskd.Shares; /// /// Network. @@ -33,11 +34,19 @@ namespace slskd.Network [ApiController] public class NetworkController : ControllerBase { - public NetworkController(INetworkService networkService) + public NetworkController( + INetworkService networkService, + IShareService shareService, + IShareRepositoryFactory shareRepositoryFactory) { Network = networkService; + Shares = shareService; + + ShareRepositoryFactory = shareRepositoryFactory; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } + private IShareService Shares { get; } private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -114,14 +123,22 @@ namespace slskd.Network Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = Request.Form.Files.First().OpenReadStream(); + using var inputStream = Request.Form.Files[0].OpenReadStream(); await inputStream.CopyToAsync(outputStream); Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); - // todo: validate database - // todo: add contents of db to local db + var repository = ShareRepositoryFactory.CreateFromFile(temp); + + if (!repository.TryValidate(out var problems)) + { + return BadRequest(string.Join(", ", problems)); + } + + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); + + destinationRepository.RestoreFrom(repository); return Ok(); } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 10e33118..15f114f9 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -127,7 +127,7 @@ namespace slskd.Network Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); Log.Debug("Backing up shares to {Filename}", temp); - Shares.BackupTo($"Data Source={temp};Pooling=False;"); // quite a leaky abstraction + await Shares.DumpAsync(temp); Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); @@ -136,18 +136,22 @@ namespace slskd.Network FileStream stream = default; - try - { - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - } - catch (Exception ex) + while (true) { - // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling - // Pooling=False should be included in the connection string and this shouldn't be an issue, but - // since i don't totally understand the behavior, i'll leave this for now. - Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); - SqliteConnection.ClearAllPools(); - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + try + { + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + break; + } + catch (Exception ex) + { + // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling + // Pooling=False should be included in the connection string and this shouldn't be an issue, but + // since i don't totally understand the behavior, i'll leave this for now. + Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); + SqliteConnection.ClearAllPools(); + await Task.Delay(100); + } } using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c5d0f961..b9d43992 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -528,10 +528,7 @@ namespace slskd services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); - services.AddSingleton(new ShareConnectionStringFactory( - createFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db;Cache=shared", - createFromMemory: (name) => $"file:shares.{name}?mode=memory", - createBackupFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db.bak;")); + services.AddTransient(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs deleted file mode 100644 index fff587ad..00000000 --- a/src/slskd/Shares/IReadOnlyShareRepository.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - /// - /// Read-only persistent storage of shared files and metadata. - /// - public interface IReadOnlyShareRepository : IShareRepository - { - } -} diff --git a/src/slskd/Shares/IReadWriteShareRepository.cs b/src/slskd/Shares/IReadWriteShareRepository.cs deleted file mode 100644 index c6701753..00000000 --- a/src/slskd/Shares/IReadWriteShareRepository.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System; - using Soulseek; - - /// - /// Writeable persistent storage of shared files and metadata. - /// - public interface IReadWriteShareRepository : IShareRepository - { - - /// - /// Creates a new database. - /// - /// - /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case - /// tables are explicitly dropped prior to creation. - /// - /// An optional value that determines whether the existing database should be discarded. - void Create(bool discardExisting = false); - - /// - /// Inserts a directory. - /// - /// The fully qualified local name of the directory. - /// The timestamp to assign to the record. - void InsertDirectory(string name, long timestamp); - - /// - /// Inserts a file. - /// - /// The fully qualified remote path of the file. - /// The fully qualified local path of the file. - /// The timestamp at which the file was last modified, according to the host OS. - /// The Soulseek.File instance representing the file. - /// The timestamp to assign to the record. - void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); - - /// - /// Inserts a scan record at the specified . - /// - /// The timestamp associated with the scan. - /// The options snapshot at the start of the scan. - void InsertScan(long timestamp, Options.SharesOptions options); - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - void BackupTo(string connectionString); - - /// - /// Restores the current database from the database at the specified . - /// - /// The connection string of the source database. - void RestoreFrom(string connectionString); - - /// - /// Deletes directory records with a timestamp prior to the specified . - /// - /// The timestamp before which to delete directories. - /// The number of records deleted. - long PruneDirectories(long olderThanTimestamp); - - /// - /// Deletes file records with a timestamp prior to the specified . - /// - /// The timestamp before which to delete files. - /// The number of records deleted. - long PruneFiles(long olderThanTimestamp); - - /// - /// Updates the scan started at the specified to set the . - /// - /// The timestamp associated with the scan. - /// The timestamp at the conclusion of the scan. - void UpdateScan(long timestamp, long end); - } -} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 87c2c386..0cf5cd80 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -17,6 +17,7 @@ namespace slskd.Shares { + using System; using System.Collections.Generic; using Soulseek; @@ -30,6 +31,12 @@ namespace slskd.Shares /// string ConnectionString { get; } + /// + /// Backs the current database up to the database at the specified . + /// + /// The destination repository. + void BackupTo(IShareRepository repository); + /// /// Counts the number of directories in the database. /// @@ -44,6 +51,22 @@ namespace slskd.Shares /// The number of files. int CountFiles(string parentDirectory = null); + /// + /// Creates a new database. + /// + /// + /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case + /// tables are explicitly dropped prior to creation. + /// + /// An optional value that determines whether the existing database should be discarded. + void Create(bool discardExisting = false); + + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + void DumpTo(string filename); + /// /// Finds the filename of the file matching the specified . /// @@ -51,6 +74,30 @@ namespace slskd.Shares /// The filename, if found. string FindFilename(string maskedFilename); + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. + void InsertDirectory(string name, long timestamp); + + /// + /// Inserts a file. + /// + /// The fully qualified remote path of the file. + /// The fully qualified local path of the file. + /// The timestamp at which the file was last modified, according to the host OS. + /// The Soulseek.File instance representing the file. + /// The timestamp to assign to the record. + void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); + + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + void InsertScan(long timestamp, Options.SharesOptions options); + /// /// Lists all directories. /// @@ -66,6 +113,26 @@ namespace slskd.Shares /// The list of files. IEnumerable ListFiles(string parentDirectory = null, bool includeFullPath = false); + /// + /// Deletes directory records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete directories. + /// The number of records deleted. + long PruneDirectories(long olderThanTimestamp); + + /// + /// Deletes file records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete files. + /// The number of records deleted. + long PruneFiles(long olderThanTimestamp); + + /// + /// Restores the current database from the database at the specified . + /// + /// The destination repository. + void RestoreFrom(IShareRepository repository); + /// /// Searches the database for files matching the specified . /// @@ -74,11 +141,23 @@ namespace slskd.Shares IEnumerable Search(SearchQuery query); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + bool TryValidate(); + + /// + /// Attempts to validate the backing database. /// - /// The connection string of the database to validate. + /// The list of problems, if the database is invalid. /// A value indicating whether the database is valid. - bool TryValidate(string connectionString = null); + bool TryValidate(out IEnumerable problems); + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + void UpdateScan(long timestamp, long end); } -} +} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepositoryFactory.cs b/src/slskd/Shares/IShareRepositoryFactory.cs new file mode 100644 index 00000000..a43f84d9 --- /dev/null +++ b/src/slskd/Shares/IShareRepositoryFactory.cs @@ -0,0 +1,46 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public interface IShareRepositoryFactory + { + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHost(string name); + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHostBackup(string name); + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + IShareRepository CreateFromFile(string filename); + } +} diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 90fa115d..b55db482 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -42,18 +42,19 @@ namespace slskd.Shares /// The host to add or update. void AddOrUpdateHost(Host host); - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - void BackupTo(string connectionString); - /// /// Returns the entire contents of the share. /// /// The entire contents of the share. Task> BrowseAsync(Share share = null); + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + Task DumpAsync(string filename); + /// /// Returns the contents of the specified . /// diff --git a/src/slskd/Shares/ShareConnectionStringFactory.cs b/src/slskd/Shares/ShareConnectionStringFactory.cs deleted file mode 100644 index d9b7492b..00000000 --- a/src/slskd/Shares/ShareConnectionStringFactory.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System; - - /// - /// Creates connection strings for share cache databases. - /// - public class ShareConnectionStringFactory - { - /// - /// Initializes a new instance of the class. - /// - /// The function used to create a connection string for a share cache database. - /// The function used to create an in-memory connection string for a share cache database. - /// The function used to crate a connection string for a share cache backup database. - public ShareConnectionStringFactory( - Func createFromFile, - Func createFromMemory, - Func createBackupFromFile) - { - CreateFromFile = createFromFile; - CreateFromMemory = createFromMemory; - CreateBackupFromFile = createBackupFromFile; - } - - /// - /// Gets a function used to create a connection string for a share cache database. - /// - public Func CreateFromFile { get; } - - /// - /// Gets a function used to create an in-memory connection string for a share cache database. - /// - public Func CreateFromMemory { get; } - - /// - /// Gets a function used to create a connection string for a share cache backup database. - /// - public Func CreateBackupFromFile { get; } - } -} diff --git a/src/slskd/Shares/ShareRepositoryFactory.cs b/src/slskd/Shares/ShareRepositoryFactory.cs new file mode 100644 index 00000000..fc58c397 --- /dev/null +++ b/src/slskd/Shares/ShareRepositoryFactory.cs @@ -0,0 +1,74 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System.IO; + +namespace slskd.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public class SqliteShareRepositoryFactory : IShareRepositoryFactory + { + /// + /// Initializes a new instance of the class. + /// + /// + public SqliteShareRepositoryFactory( + OptionsAtStartup optionsAtStartup) + { + StorageMode = optionsAtStartup.Shares.Cache.StorageMode.ToEnum(); + } + + private StorageMode StorageMode { get; } + + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHost(string name) + { + if (StorageMode == StorageMode.Memory) + { + return new SqliteShareRepository($"Data Source=file:shares.{name}?mode=memory;Cache=shared"); + } + + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.db"); + return new SqliteShareRepository($"Data Source={file};Cache=shared"); + } + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHostBackup(string name) + { + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.bak.db"); + return new SqliteShareRepository($"Data Source={file}"); + } + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + public IShareRepository CreateFromFile(string filename) + => new SqliteShareRepository($"Data Source={filename}"); + } +} diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index f5e7e52d..7a174396 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -67,7 +67,7 @@ namespace slskd.Shares /// public ShareScanner( int workerCount, - IReadWriteShareRepository shareRepository, + IShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; @@ -87,7 +87,7 @@ namespace slskd.Shares private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private CancellationTokenSource CancellationTokenSource { get; set; } - private IReadWriteShareRepository Repository { get; } + private IShareRepository Repository { get; } /// /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a0aec286..cc35477e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,32 +37,22 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// - /// + /// /// /// public ShareService( - ShareConnectionStringFactory shareConnectionStringFactory, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor optionsMonitor, IShareScanner scanner = null) { var options = optionsMonitor.CurrentValue; - ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum(); - if (CacheStorageMode == StorageMode.Memory) - { - ConnectionString = ConnectionStringFactory.CreateFromMemory(options.InstanceName); - } - else - { - ConnectionString = ConnectionStringFactory.CreateFromFile(options.InstanceName); - } - - BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName); + ShareRepositoryFactory = shareRepositoryFactory; var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); - var repository = new SqliteShareRepository(ConnectionString); + var repository = ShareRepositoryFactory.CreateFromHost(options.InstanceName); Local = (host, repository); @@ -108,9 +98,7 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor { get; } - private string ConnectionString { get; } - private string BackupConnectionString { get; } - private ShareConnectionStringFactory ConnectionStringFactory { get; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareScanner Scanner { get; } private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } @@ -119,7 +107,7 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } + private (Host Host, IShareRepository Repository) Local { get; set; } private IEnumerable AllRepositories { get; set; } /// @@ -128,9 +116,11 @@ namespace slskd.Shares /// The host to add or update. public void AddOrUpdateHost(Host host) { + // we assume that if this method is called that the caller has verified that the + // file for the host exists and is valid. HostDictionary.AddOrUpdate( key: host.Name, - addValueFactory: (key) => (host, new SqliteShareRepository(ConnectionStringFactory.CreateFromFile(host.Name))), + addValueFactory: (key) => (host, ShareRepositoryFactory.CreateFromHost(host.Name)), updateValueFactory: (_, existing) => (host, existing.Repository)); AllRepositories = HostDictionary.Values @@ -139,15 +129,6 @@ namespace slskd.Shares .Prepend(Local.Repository); } - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - public void BackupTo(string connectionString) - { - Repository.BackupTo(connectionString); - } - /// /// Returns the entire contents of the share. /// @@ -200,6 +181,17 @@ namespace slskd.Shares return Task.FromResult(results); } + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + public Task DumpAsync(string filename) + { + Local.Repository.DumpTo(filename); + return Task.CompletedTask; + } + /// /// Returns the contents of the specified . /// @@ -272,7 +264,7 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(BackupConnectionString); + Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName)); Log.Debug("Shared file cache database backup complete"); } @@ -319,11 +311,13 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } @@ -337,7 +331,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (Local.Repository.TryValidate(ConnectionString)) + if (Local.Repository.TryValidate(out _)) { // no-op } @@ -345,11 +339,13 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 28788c3f..9b65794e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -28,7 +28,7 @@ namespace slskd.Shares /// /// Persistent storage of shared files and metadata. /// - public class SqliteShareRepository : IReadWriteShareRepository + public class SqliteShareRepository : IShareRepository { /// /// Initializes a new instance of the class. @@ -47,84 +47,13 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Backs the current database up to the database at the specified . /// - /// The connection string of the database to validate. - /// A value indicating whether the database is valid. - public bool TryValidate(string connectionString = null) - { - connectionString ??= ConnectionString; - - // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: - // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' - var schema = new Dictionary() - { - { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, - { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, - { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, - { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, - { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, - { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, - { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, - { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, - { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, - }; - - try - { - Log.Debug("Validating shares database with connection string {String}", connectionString); - - using var conn = new SqliteConnection(connectionString); - conn.Open(); - - using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); - - var reader = cmd.ExecuteReader(); - var rows = 0; - - while (reader.Read()) - { - var table = reader.GetString(0); - var expectedSql = reader.GetString(1); - - if (schema.TryGetValue(table, out var actualSql)) - { - if (actualSql != expectedSql) - { - throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}"); - } - else - { - Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); - } - } - - rows++; - } - - if (rows != schema.Count) - { - throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); - } - - return true; - } - catch (Exception ex) - { - Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); - return false; - } - } - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - public void BackupTo(string connectionString) + /// The destination repository. + public void BackupTo(IShareRepository repository) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(connectionString); + using var backupConn = GetConnection(repository.ConnectionString); sourceConn.BackupDatabase(backupConn); } @@ -224,6 +153,19 @@ namespace slskd.Shares "extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);"); } + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + public void DumpTo(string filename) + { + using var sourceConn = GetConnection(ConnectionString); + using var backupConn = GetConnection($"Data Source={filename}"); + sourceConn.BackupDatabase(backupConn); + + Sqlite. + } + /// /// Finds the filename of the file matching the specified . /// @@ -442,12 +384,12 @@ namespace slskd.Shares } /// - /// Restores the current database from the database at the specified . + /// Restores the current database from the database at the specified . /// - /// The connection string of the source database. - public void RestoreFrom(string connectionString) + /// The destination repository. + public void RestoreFrom(IShareRepository repository) { - using var sourceConn = GetConnection(connectionString); + using var sourceConn = GetConnection(repository.ConnectionString); using var restoreConn = GetConnection(); sourceConn.BackupDatabase(restoreConn); } @@ -504,6 +446,87 @@ namespace slskd.Shares } } + /// + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + public bool TryValidate() + { + return TryValidate(out _); + } + + /// + /// Attempts to validate the backing database. + /// + /// The list of problems, if the database is invalid. + /// A value indicating whether the database is valid. + public bool TryValidate(out IEnumerable problems) + { + var list = new List(); + problems = list; + + // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: + // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' + var schema = new Dictionary() + { + { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, + { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, + { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, + { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, + { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, + { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, + { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, + }; + + try + { + Log.Debug("Validating shares database with connection string {String}", ConnectionString); + + using var conn = new SqliteConnection(ConnectionString); + conn.Open(); + + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); + + var reader = cmd.ExecuteReader(); + var rows = 0; + + while (reader.Read()) + { + var table = reader.GetString(0); + var expectedSql = reader.GetString(1); + + if (schema.TryGetValue(table, out var actualSql)) + { + if (actualSql != expectedSql) + { + list.Add($"Expected {table} schema to be {expectedSql}, found {actualSql}"); + } + else + { + Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); + } + } + + rows++; + } + + if (rows != schema.Count) + { + list.Add($"Expected {schema.Count} tables, found {rows}"); + } + + return !problems.Any(); + } + catch (Exception ex) + { + Log.Debug(ex, $"Failed to validate database: {ex.Message}"); + list.Add($"Failed to validate database: {ex.Message}"); + return false; + } + } + /// /// Updates the scan started at the specified to set the . /// -- cgit v1.2.3