From 6155ff6cabf276ea084e5641b8a8ea1abe07b81c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 4 Oct 2022 19:36:10 -0500 Subject: add network options --- src/slskd/Core/Options.cs | 85 ++++++++++++++++++++++++++++ src/slskd/Core/Types/NetworkOperationMode.cs | 35 ++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 src/slskd/Core/Types/NetworkOperationMode.cs (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 4c146d32..7debb525 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -200,6 +200,12 @@ namespace slskd [YamlIgnore] public string ConfigurationFile { get; init; } = Program.DefaultConfigurationFile; + /// + /// Gets network options. + /// + [Validate] + public NetworkOptions Network { get; init; } = new NetworkOptions(); + /// /// Gets directory options. /// @@ -347,6 +353,85 @@ namespace slskd public bool LogSQL { get; init; } = false; } + /// + /// Network options. + /// + public class NetworkOptions : IValidatableObject + { + /// + /// Gets the application operation mode. + /// + [Argument('m', "network-operation-mode")] + [EnvironmentVariable("NETWORK_OPERATION_MODE")] + [Description("network operation mode; controller, agent")] + [RequiresRestart] + [Enum(typeof(NetworkOperationMode))] + public string OperationMode { get; init; } = NetworkOperationMode.Controller.ToString().ToLowerInvariant(); + + /// + /// Gets the controller configuration. + /// + public NetworkControllerConfigurationOptions Controller { get; init; } = new NetworkControllerConfigurationOptions(); + + /// + /// Gets the agent configuration. + /// + public Dictionary Agents { get; init; } = new(); + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + var controllerResults = new List(); + var agentResults = new List(); + + if (OperationMode.ToEnum() == NetworkOperationMode.Agent && !Validator.TryValidateObject(Controller, validationContext, controllerResults)) + { + results.AddRange(controllerResults); + } + else if (!Validator.TryValidateObject(Agents, validationContext, results)) + { + results.AddRange(agentResults); + } + + return results; + } + + /// + /// Network controller configuration options. + /// + public class NetworkControllerConfigurationOptions + { + /// + /// Gets the controller address. + /// + [Argument(default, "controller-address")] + [EnvironmentVariable("CONTROLLER_ADDRESS")] + public string Address { get; init; } + + /// + /// Gets the controller secret. + /// + [Argument(default, "controller-secret")] + [EnvironmentVariable("CONTROLLER_SECRET")] + [StringLength(255, MinimumLength = 32)] + [Secret] + public string Secret { get; init; } + } + + /// + /// Network agent configuration options. + /// + public class NetworkAgentConfigurationOptions + { + /// + /// Gets the agent secret. + /// + [StringLength(255, MinimumLength = 32)] + [Secret] + public string Secret { get; init; } + } + } + /// /// Directory options. /// diff --git a/src/slskd/Core/Types/NetworkOperationMode.cs b/src/slskd/Core/Types/NetworkOperationMode.cs new file mode 100644 index 00000000..4b190275 --- /dev/null +++ b/src/slskd/Core/Types/NetworkOperationMode.cs @@ -0,0 +1,35 @@ +// +// 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 +{ + /// + /// The network operation mode. + /// + public enum NetworkOperationMode + { + /// + /// Controller operation mode. + /// + Controller = 0, + + /// + /// Agent operation mode. + /// + Agent = 1, + } +} -- cgit v1.2.3 From 65fe41ecb11e4f1ffe5dc05a77eea60e04d23b37 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 4 Oct 2022 19:36:28 -0500 Subject: wip --- .../Agents/API/Controllers/AgentController.cs | 48 ++++++++++++++ src/slskd/Agents/API/Hubs/AgentHub.cs | 77 ++++++++++++++++++++++ src/slskd/Agents/AgentService.cs | 11 ++++ 3 files changed, 136 insertions(+) create mode 100644 src/slskd/Agents/API/Controllers/AgentController.cs create mode 100644 src/slskd/Agents/API/Hubs/AgentHub.cs create mode 100644 src/slskd/Agents/AgentService.cs (limited to 'src') diff --git a/src/slskd/Agents/API/Controllers/AgentController.cs b/src/slskd/Agents/API/Controllers/AgentController.cs new file mode 100644 index 00000000..dab925a4 --- /dev/null +++ b/src/slskd/Agents/API/Controllers/AgentController.cs @@ -0,0 +1,48 @@ +// +// 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 Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Application. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class AgentController : ControllerBase + { + public AgentController() + { + } + + /// + /// Gets the current state of the application. + /// + /// + [HttpPost("files/{id}")] + [Authorize] + public IActionResult UploadFile(string id) + { + return Ok(id); + } + } +} diff --git a/src/slskd/Agents/API/Hubs/AgentHub.cs b/src/slskd/Agents/API/Hubs/AgentHub.cs new file mode 100644 index 00000000..533621a8 --- /dev/null +++ b/src/slskd/Agents/API/Hubs/AgentHub.cs @@ -0,0 +1,77 @@ +// +// 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.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.SignalR; + using slskd; + + public static class AgentHubMethods + { + public static readonly string RequestFile = "REQUEST_FILE"; + } + + /// + /// Extension methods for the agent SignalR hub. + /// + public static class AgentHubExtensions + { + public static Task RequestFileAsync(this IHubContext hub, Guid id, string filename) + { + // todo: how to send this to a specific user? + return hub.Clients.All.SendAsync(AgentHubMethods.RequestFile, id, filename); + } + } + + /// + /// The agent SignalR hub. + /// + [Authorize] + public class AgentHub : Hub + { + public AgentHub( + IStateMonitor stateMonitor, + IOptionsMonitor optionsMonitor) + { + StateMonitor = stateMonitor; + OptionsMonitor = optionsMonitor; + } + + private IStateMonitor StateMonitor { get; } + private IOptionsMonitor OptionsMonitor { get; } + + public override async Task OnConnectedAsync() + { + // upon connection we need to do a little handshaking to establish + // that this is a registered agent, and which agent it is. whoever is calling + // has an api key or jwt, but users might disable auth, so literally anyone could + // connect. they should at least say who they are, and we'd allow or disallow + // todo: how to authenticate? + // todo: how to identify? + } + + public Task RequestFileAsync(string filename) + { + return Clients.All.SendAsync("foo"); + } + } +} \ No newline at end of file diff --git a/src/slskd/Agents/AgentService.cs b/src/slskd/Agents/AgentService.cs new file mode 100644 index 00000000..8ecb7c71 --- /dev/null +++ b/src/slskd/Agents/AgentService.cs @@ -0,0 +1,11 @@ +namespace slskd.Agents +{ + public interface IAgentService + { + + } + + public class AgentService : IAgentService + { + } +} -- cgit v1.2.3 From 47cdbc6ad812cdbec12ae50a046ea04c39faf5ec Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 6 Oct 2022 19:05:26 -0500 Subject: add Base62Extensions --- src/slskd/Common/Cryptography/Base62Extensions.cs | 215 ++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 src/slskd/Common/Cryptography/Base62Extensions.cs (limited to 'src') diff --git a/src/slskd/Common/Cryptography/Base62Extensions.cs b/src/slskd/Common/Cryptography/Base62Extensions.cs new file mode 100644 index 00000000..b9ab3a72 --- /dev/null +++ b/src/slskd/Common/Cryptography/Base62Extensions.cs @@ -0,0 +1,215 @@ +/* + The MIT License (MIT) + + Copyright (c) 2016 - 2020 JoyMoe Interactive Entertainment Limited + + All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + https://github.com/JoyMoe/Base62.Net + */ +// -- suppress analysis + +namespace slskd.Cryptography +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + + public static class Base62Extensions + { + private const string DefaultCharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + private const string InvertedCharacterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + /// + /// Encode a 2-byte number with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this short original, bool inverted = false) + { + var array = BitConverter.GetBytes(original); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return array.ToBase62(inverted); + } + + /// + /// Encode a 4-byte number with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this int original, bool inverted = false) + { + var array = BitConverter.GetBytes(original); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return array.ToBase62(inverted); + } + + /// + /// Encode a 8-byte number with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this long original, bool inverted = false) + { + var array = BitConverter.GetBytes(original); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return array.ToBase62(inverted); + } + + /// + /// Encode a string with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this string original, bool inverted = false) + { + return Encoding.UTF8.GetBytes(original).ToBase62(inverted); + } + + /// + /// Encode a byte array with Base62 + /// + /// Byte array + /// Use inverted character set + /// Base62 string + public static string ToBase62(this byte[] original, bool inverted = false) + { + var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; + var arr = Array.ConvertAll(original, t => (int)t); + + var converted = BaseConvert(arr, 256, 62); + var builder = new StringBuilder(); + foreach (var t in converted) + { + builder.Append(characterSet[t]); + } + return builder.ToString(); + } + + /// + /// Decode a base62-encoded string + /// + /// Base62 string + /// Use inverted character set + /// Byte array + public static T FromBase62(this string base62, bool inverted = false) + { + var array = base62.FromBase62(inverted); + + switch (Type.GetTypeCode(typeof(T))) + { + case TypeCode.String: + return (T)Convert.ChangeType(Encoding.UTF8.GetString(array), typeof(T), CultureInfo.InvariantCulture); + case TypeCode.Int16: + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return (T)Convert.ChangeType(BitConverter.ToInt16(array, 0), typeof(T), CultureInfo.InvariantCulture); + case TypeCode.Int32: + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return (T)Convert.ChangeType(BitConverter.ToInt32(array, 0), typeof(T), CultureInfo.InvariantCulture); + case TypeCode.Int64: + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return (T)Convert.ChangeType(BitConverter.ToInt64(array, 0), typeof(T), CultureInfo.InvariantCulture); + default: + throw new Exception($"Type of {typeof(T)} does not support."); + } + } + + /// + /// Decode a base62-encoded string + /// + /// Base62 string + /// Use inverted character set + /// Byte array + public static byte[] FromBase62(this string base62, bool inverted = false) + { + if (string.IsNullOrWhiteSpace(base62)) + { + throw new ArgumentNullException(nameof(base62)); + } + + var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; + var arr = Array.ConvertAll(base62.ToCharArray(), characterSet.IndexOf); + + var converted = BaseConvert(arr, 62, 256); + return Array.ConvertAll(converted, Convert.ToByte); + } + + private static int[] BaseConvert(int[] source, int sourceBase, int targetBase) + { + var result = new List(); + var leadingZeroCount = Math.Min(source.TakeWhile(x => x == 0).Count(), source.Length - 1); + int count; + while ((count = source.Length) > 0) + { + var quotient = new List(); + var remainder = 0; + for (var i = 0; i != count; i++) + { + var accumulator = source[i] + remainder * sourceBase; + var digit = accumulator / targetBase; + remainder = accumulator % targetBase; + if (quotient.Count > 0 || digit > 0) + { + quotient.Add(digit); + } + } + + result.Insert(0, remainder); + source = quotient.ToArray(); + } + result.InsertRange(0, Enumerable.Repeat(0, leadingZeroCount)); + return result.ToArray(); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 4d6dc9aa1cb21f74c5bf4efca18ae71ce6af1415 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 6 Oct 2022 19:05:38 -0500 Subject: remove ToBase62String --- src/slskd/Common/CommonExtensions.cs | 21 --------------------- 1 file changed, 21 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 0998d44d..307e1469 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -324,27 +324,6 @@ namespace slskd return sanitized; } - /// - /// Converts the byte array into a base 62 encoded string. - /// - /// The bytes to convert. - /// The converted bytes as a base 62 string. - public static string ToBase62String(this byte[] bytes) - { - const string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - BigInteger dividend = new BigInteger(bytes); - var builder = new StringBuilder(); - - while (dividend != 0) - { - dividend = BigInteger.DivRem(dividend, alphabet.Length, out BigInteger remainder); - builder.Insert(0, alphabet[Math.Abs((int)remainder)]); - } - - return builder.ToString(); - } - /// /// Determines whether the given object is a . /// -- cgit v1.2.3 From 30a789f3acff9fd64442e2342e4b193ee778cb16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 6 Oct 2022 19:05:47 -0500 Subject: rough in AES library --- src/slskd/Common/Cryptography/Aes.cs | 106 +++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/slskd/Common/Cryptography/Aes.cs (limited to 'src') diff --git a/src/slskd/Common/Cryptography/Aes.cs b/src/slskd/Common/Cryptography/Aes.cs new file mode 100644 index 00000000..7cd6cd7e --- /dev/null +++ b/src/slskd/Common/Cryptography/Aes.cs @@ -0,0 +1,106 @@ +// +// 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.Cryptography +{ + using System; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + + /// + /// AES utility methods. + /// + public static class Aes + { + private static readonly int BlockSizeInBits = 128; + private static readonly int BlockSizeInBytes = BlockSizeInBits / 8; + private static readonly int KeySizeInBits = 256; + private static readonly int KeySizeInBytes = KeySizeInBits / 8; + + public static string Decrypt(string cipherText, string keybase62) + { + using var aes = System.Security.Cryptography.Aes.Create(); + + aes.KeySize = KeySizeInBits; + aes.BlockSize = BlockSizeInBits; + + var (key, iv) = DecodeKey(keybase62); + + using var decryptor = aes.CreateDecryptor(key, iv); + using var memoryStream = new MemoryStream(Convert.FromBase64String(cipherText)); + using var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); + using var streamReader = new StreamReader(cryptoStream); + + return streamReader.ReadToEnd(); + } + + public static string Encrypt(string plainText, string keybase62) + { + using var aes = System.Security.Cryptography.Aes.Create(); + + aes.KeySize = KeySizeInBits; + aes.BlockSize = BlockSizeInBits; + + var (key, iv) = DecodeKey(keybase62); + + using var encryptor = aes.CreateEncryptor(key, iv); + using var memoryStream = new MemoryStream(); + using var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); + using var streamWriter = new StreamWriter(cryptoStream); + + streamWriter.Write(plainText); + streamWriter.Close(); + + return Convert.ToBase64String(memoryStream.ToArray()); + } + + public static string GenerateRandomBase62Key() + { + var (key, iv) = GenerateRandomKey(); + return EncodeKey(key, iv); + } + + private static (byte[] Key, byte[] IV) DecodeKey(string keybase62) + { + var bytes = keybase62.FromBase62(); + var mem = new Memory(bytes); + var key = mem.Slice(0, KeySizeInBytes); + var iv = mem.Slice(KeySizeInBytes, BlockSizeInBytes); + + return (key.ToArray(), iv.ToArray()); + } + + private static string EncodeKey(byte[] key, byte[] iv) + { + var bytes = key.Concat(iv).ToArray(); + return bytes.ToBase62(); + } + + private static (byte[] Key, byte[] IV) GenerateRandomKey() + { + using var aes = System.Security.Cryptography.Aes.Create(); + aes.KeySize = KeySizeInBits; + aes.BlockSize = BlockSizeInBits; + + aes.GenerateIV(); + aes.GenerateKey(); + + return (aes.Key, aes.IV); + } + } +} \ No newline at end of file -- cgit v1.2.3 From a1632c18d37fdeb62499000dd9da4b1a1b71256d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 09:12:25 -0500 Subject: add SignalR client --- src/slskd/slskd.csproj | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 1f0973b1..b1d62579 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -46,6 +46,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 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') 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 6bfa979a30e47b6a1626c909a04388fd4bb7ce55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 09:13:16 -0500 Subject: fix more broken base62 --- src/slskd/Core/Options.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7debb525..22e8487c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -30,6 +30,7 @@ namespace slskd using FluentFTP; using NetTools; using slskd.Configuration; + using slskd.Cryptography; using slskd.Validation; using Soulseek.Diagnostics; using Utility.CommandLine; @@ -1330,7 +1331,7 @@ namespace slskd [StringLength(255, MinimumLength = 16)] [Secret] [RequiresRestart] - public string Key { get; init; } = Cryptography.Random.GetBytes(16).ToBase62String(); + public string Key { get; init; } = Cryptography.Random.GetBytes(16).ToBase62(); /// /// Gets the TTL for JWTs, in milliseconds. -- 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') 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 a05e3ad4beecf612d25b854ca5335d0bbd86a3a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 18:24:55 -0500 Subject: temporarily disable check for operation mode --- src/slskd/Application.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index fa7ed516..31949fd5 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -391,6 +391,10 @@ 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 { await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); -- cgit v1.2.3 From 23746d698d850feabdb88b8f304ec3a301e0e5f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 18:25:21 -0500 Subject: temporarily disable validation of network options --- src/slskd/Core/Options.cs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 22e8487c..02000869 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -382,17 +382,17 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); - var controllerResults = new List(); - var agentResults = new List(); - - if (OperationMode.ToEnum() == NetworkOperationMode.Agent && !Validator.TryValidateObject(Controller, validationContext, controllerResults)) - { - results.AddRange(controllerResults); - } - else if (!Validator.TryValidateObject(Agents, validationContext, results)) - { - results.AddRange(agentResults); - } + //var controllerResults = new List(); + //var agentResults = new List(); + + //if (OperationMode.ToEnum() == NetworkOperationMode.Agent && !Validator.TryValidateObject(Controller, validationContext, controllerResults)) + //{ + // results.AddRange(controllerResults); + //} + //else if (!Validator.TryValidateObject(Agents, validationContext, results)) + //{ + // results.AddRange(agentResults); + //} return results; } -- cgit v1.2.3 From 133feb54ef28ffe672b779ad422890887688d23a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 7 Oct 2022 18:25:49 -0500 Subject: rough in agent upload implementation --- .../Agents/API/Controllers/AgentController.cs | 48 ----- .../Agents/API/Controllers/AgentsController.cs | 83 ++++++++ src/slskd/Agents/API/Hubs/AgentHub.cs | 11 +- src/slskd/Agents/AgentService.cs | 218 ++++++++++++++++++++- src/slskd/Transfers/Uploads/UploadService.cs | 14 +- 5 files changed, 315 insertions(+), 59 deletions(-) delete mode 100644 src/slskd/Agents/API/Controllers/AgentController.cs create mode 100644 src/slskd/Agents/API/Controllers/AgentsController.cs (limited to 'src') diff --git a/src/slskd/Agents/API/Controllers/AgentController.cs b/src/slskd/Agents/API/Controllers/AgentController.cs deleted file mode 100644 index dab925a4..00000000 --- a/src/slskd/Agents/API/Controllers/AgentController.cs +++ /dev/null @@ -1,48 +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 Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - - /// - /// Application. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class AgentController : ControllerBase - { - public AgentController() - { - } - - /// - /// Gets the current state of the application. - /// - /// - [HttpPost("files/{id}")] - [Authorize] - public IActionResult UploadFile(string id) - { - return Ok(id); - } - } -} diff --git a/src/slskd/Agents/API/Controllers/AgentsController.cs b/src/slskd/Agents/API/Controllers/AgentsController.cs new file mode 100644 index 00000000..48f70cee --- /dev/null +++ b/src/slskd/Agents/API/Controllers/AgentsController.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.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 index 533621a8..99df6bf8 100644 --- a/src/slskd/Agents/API/Hubs/AgentHub.cs +++ b/src/slskd/Agents/API/Hubs/AgentHub.cs @@ -35,10 +35,10 @@ namespace slskd.Agents /// public static class AgentHubExtensions { - public static Task RequestFileAsync(this IHubContext hub, Guid id, string filename) + public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) { - // todo: how to send this to a specific user? - return hub.Clients.All.SendAsync(AgentHubMethods.RequestFile, id, filename); + // todo: how to send this to the specified agent? + return hub.Clients.All.SendAsync(AgentHubMethods.RequestFile, filename, id); } } @@ -68,10 +68,5 @@ namespace slskd.Agents // todo: how to authenticate? // todo: how to identify? } - - public Task RequestFileAsync(string filename) - { - return Clients.All.SendAsync("foo"); - } } } \ No newline at end of file diff --git a/src/slskd/Agents/AgentService.cs b/src/slskd/Agents/AgentService.cs index 8ecb7c71..5b17d996 100644 --- a/src/slskd/Agents/AgentService.cs +++ b/src/slskd/Agents/AgentService.cs @@ -1,11 +1,227 @@ -namespace slskd.Agents +// +// 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.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + using Microsoft.AspNetCore.SignalR.Client; + using Serilog; + public interface IAgentService { + /// + /// Gets the collection of pending Agent uploads. + /// + ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploads { 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); } 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); + } + + 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 SyncRoot { get; } = new SemaphoreSlim(1, 1); + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Gets the collection of pending Agent uploads. + /// + public ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } = new(); + + /// + /// 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(); + + PendingUploads.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) + { + Console.WriteLine(ex); + } + } + + private void Configure(Options options) + { + SyncRoot.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); + + Console.WriteLine("-------------------------- building hub ------------------------"); + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect() + .Build(); + + HubConnection.On(AgentHubMethods.RequestFile, HandleFileRequest); + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + _ = Task.Run(async () => + { + try + { + await Task.Delay(1000); + Console.WriteLine("------------------- connecting hub -------------------"); + await HubConnection.StartAsync(); + Log.Information("Controller connection established"); + Console.WriteLine("---------------------------- hub connected ----------------------"); + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + }); + //} + + LastOptionsHash = optionsHash; + } + finally + { + SyncRoot.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/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c3cfe2fb..8c7eaffa 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -30,6 +30,7 @@ namespace slskd.Transfers.Uploads using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Agents; using slskd.Shares; using slskd.Users; @@ -43,11 +44,13 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, IShareService shareService, + IAgentService agentService, IDbContextFactory contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; + Agents = agentService; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; @@ -72,6 +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; } /// /// Adds the specified . Supersedes any existing record for the same file and username. @@ -214,14 +218,20 @@ namespace slskd.Transfers.Uploads slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + //using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + + var (stream, completion) = await Agents.GetFileStream(filename); + var completedTransfer = await Client.UploadAsync( username, filename, - fileInfo.FullName, + size: fileInfo.Length, + inputStreamFactory: () => stream, options: topts, cancellationToken: cts.Token); + completion.SetResult(); + // explicitly dispose the rate limiter to prevent updates from it // beyond this point, which may overwrite the final state rateLimiter.Dispose(); -- cgit v1.2.3 From 216572289f0956ab9cb7461cc90b2f2c2c2f89a8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 8 Oct 2022 15:37:55 -0500 Subject: fix bugs in AES enc --- src/slskd/Common/Cryptography/Aes.cs | 68 +++++++++------------- .../Common/Cryptography/AesTests.cs | 33 +++++++++++ 2 files changed, 62 insertions(+), 39 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/Cryptography/AesTests.cs (limited to 'src') diff --git a/src/slskd/Common/Cryptography/Aes.cs b/src/slskd/Common/Cryptography/Aes.cs index 7cd6cd7e..fd071403 100644 --- a/src/slskd/Common/Cryptography/Aes.cs +++ b/src/slskd/Common/Cryptography/Aes.cs @@ -32,75 +32,65 @@ namespace slskd.Cryptography private static readonly int KeySizeInBits = 256; private static readonly int KeySizeInBytes = KeySizeInBits / 8; - public static string Decrypt(string cipherText, string keybase62) + public static byte[] Decrypt(byte[] encryptedBytes, byte[] key) { using var aes = System.Security.Cryptography.Aes.Create(); aes.KeySize = KeySizeInBits; aes.BlockSize = BlockSizeInBits; - var (key, iv) = DecodeKey(keybase62); + var (k, iv) = DecodeKey(key); - using var decryptor = aes.CreateDecryptor(key, iv); - using var memoryStream = new MemoryStream(Convert.FromBase64String(cipherText)); - using var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); - using var streamReader = new StreamReader(cryptoStream); + using var decryptor = aes.CreateDecryptor(k, iv); + using var inputStream = new MemoryStream(encryptedBytes); + using var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read); + using var outputStream = new MemoryStream(); - return streamReader.ReadToEnd(); + cryptoStream.CopyTo(outputStream); + + return outputStream.ToArray(); } - public static string Encrypt(string plainText, string keybase62) + public static byte[] Encrypt(byte[] plainBytes, byte[] key) { using var aes = System.Security.Cryptography.Aes.Create(); aes.KeySize = KeySizeInBits; aes.BlockSize = BlockSizeInBits; - var (key, iv) = DecodeKey(keybase62); + var (k, iv) = DecodeKey(key); - using var encryptor = aes.CreateEncryptor(key, iv); - using var memoryStream = new MemoryStream(); - using var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); - using var streamWriter = new StreamWriter(cryptoStream); + using var encryptor = aes.CreateEncryptor(k, iv); + using var outputStream = new MemoryStream(); + using var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write); - streamWriter.Write(plainText); - streamWriter.Close(); + cryptoStream.Write(plainBytes, 0, plainBytes.Length); + cryptoStream.Flush(); + cryptoStream.Close(); - return Convert.ToBase64String(memoryStream.ToArray()); + return outputStream.ToArray(); } - public static string GenerateRandomBase62Key() + public static byte[] GenerateRandomKey() { - var (key, iv) = GenerateRandomKey(); - return EncodeKey(key, iv); + using var aes = System.Security.Cryptography.Aes.Create(); + aes.KeySize = KeySizeInBits; + aes.BlockSize = BlockSizeInBits; + + aes.GenerateIV(); + aes.GenerateKey(); + + var bytes = aes.Key.Concat(aes.IV).ToArray(); + return bytes; } - private static (byte[] Key, byte[] IV) DecodeKey(string keybase62) + private static (byte[] Key, byte[] IV) DecodeKey(byte[] bytes) { - var bytes = keybase62.FromBase62(); var mem = new Memory(bytes); var key = mem.Slice(0, KeySizeInBytes); var iv = mem.Slice(KeySizeInBytes, BlockSizeInBytes); return (key.ToArray(), iv.ToArray()); } - - private static string EncodeKey(byte[] key, byte[] iv) - { - var bytes = key.Concat(iv).ToArray(); - return bytes.ToBase62(); - } - - private static (byte[] Key, byte[] IV) GenerateRandomKey() - { - using var aes = System.Security.Cryptography.Aes.Create(); - aes.KeySize = KeySizeInBits; - aes.BlockSize = BlockSizeInBits; - - aes.GenerateIV(); - aes.GenerateKey(); - - return (aes.Key, aes.IV); - } } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Cryptography/AesTests.cs b/tests/slskd.Tests.Unit/Common/Cryptography/AesTests.cs new file mode 100644 index 00000000..c6c9be94 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Cryptography/AesTests.cs @@ -0,0 +1,33 @@ +namespace slskd.Tests.Unit.Common.Cryptography +{ + using System.Text; + using slskd.Cryptography; + using Xunit; + + public class AesTests + { + [Fact] + public void Generates_Random_Keys_Of_Expected_Length() + { + var key = Aes.GenerateRandomKey(); + Assert.Equal(48, key.Length); + } + + [Fact] + public void Encrypts_And_Decrypts() + { + var plainText = "hello, world!"; + var plainBytes = Encoding.UTF8.GetBytes(plainText); + + var key = Aes.GenerateRandomKey(); + + var encryptedBytes = Aes.Encrypt(plainBytes, key); + + var decryptedBytes = Aes.Decrypt(encryptedBytes, key); + + var decryptedText = Encoding.UTF8.GetString(decryptedBytes); + + Assert.Equal(plainText, decryptedText); + } + } +} -- cgit v1.2.3 From 6485968c3b04cedbcde2d448caa79d065507e1f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 8 Oct 2022 15:41:01 -0500 Subject: docs for Aes --- src/slskd/Common/Cryptography/Aes.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Cryptography/Aes.cs b/src/slskd/Common/Cryptography/Aes.cs index fd071403..9828d7f8 100644 --- a/src/slskd/Common/Cryptography/Aes.cs +++ b/src/slskd/Common/Cryptography/Aes.cs @@ -32,6 +32,12 @@ namespace slskd.Cryptography private static readonly int KeySizeInBits = 256; private static readonly int KeySizeInBytes = KeySizeInBits / 8; + /// + /// Decrypts the specified with the specified . + /// + /// The encrypted data to decrypt. + /// The encryption key. + /// The decrypted data. public static byte[] Decrypt(byte[] encryptedBytes, byte[] key) { using var aes = System.Security.Cryptography.Aes.Create(); @@ -51,6 +57,12 @@ namespace slskd.Cryptography return outputStream.ToArray(); } + /// + /// Encrypts the specified with the specified . + /// + /// The plain data to encrypt. + /// The encryption key. + /// The encrypted data. public static byte[] Encrypt(byte[] plainBytes, byte[] key) { using var aes = System.Security.Cryptography.Aes.Create(); @@ -71,6 +83,10 @@ namespace slskd.Cryptography return outputStream.ToArray(); } + /// + /// Generates a random key using the default key and block sizes. + /// + /// The generated key. public static byte[] GenerateRandomKey() { using var aes = System.Security.Cryptography.Aes.Create(); -- 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') 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 0422cdddf04d29edb50bf18f74f2697ca25ad47e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 8 Oct 2022 17:06:04 -0500 Subject: enforce 48 character agent secret length --- src/slskd/Core/Options.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index a63154b4..cc155f5f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -424,7 +424,7 @@ namespace slskd /// [Argument(default, "controller-secret")] [EnvironmentVariable("CONTROLLER_SECRET")] - [StringLength(255, MinimumLength = 32)] + [StringLength(48, MinimumLength = 48)] [Secret] public string Secret { get; init; } } @@ -437,7 +437,7 @@ namespace slskd /// /// Gets the agent secret. /// - [StringLength(255, MinimumLength = 32)] + [StringLength(48, MinimumLength = 48)] [Secret] public string Secret { get; init; } } -- cgit v1.2.3 From 5203788c41d652d17f67c3c45658b289a6acf380 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 8 Oct 2022 18:04:37 -0500 Subject: agent auth and registration --- src/slskd/Integrations/FTP/FTPService.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index 32b8b253..11fa9709 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -73,7 +73,7 @@ namespace slskd.Integrations.FTP await Retry.Do( task: () => AttemptUploadAsync(filename), isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.LogInformation("Failed attempt {Attempts} to upload {Filename} to FTP: {Message}", attempts, fileAndParentDirectory, ex.Message), + onFailure: (attempts, ex) => Log.LogInformation("Failed attempt #{Attempts} to upload {Filename} to FTP: {Message}", attempts, fileAndParentDirectory, ex.Message), maxAttempts: FtpOptions.RetryAttempts, maxDelayInMilliseconds: 30000); } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 8c7eaffa..5d49c3e1 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -220,7 +220,7 @@ namespace slskd.Transfers.Uploads //using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - var (stream, completion) = await Agents.GetFileStream(filename); + var (stream, completion) = await Agents.GetUpload("any", filename); var completedTransfer = await Client.UploadAsync( username, -- cgit v1.2.3 From 9af9f9119f32734414fa725a9d742448e937732b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 8 Oct 2022 18:16:34 -0500 Subject: implement auth and registration --- src/slskd/Agents/API/Hubs/AgentHub.cs | 49 ++++++--- src/slskd/Agents/AgentService.cs | 184 +++++++++++++++++++++++++++++----- 2 files changed, 195 insertions(+), 38 deletions(-) (limited to 'src') diff --git a/src/slskd/Agents/API/Hubs/AgentHub.cs b/src/slskd/Agents/API/Hubs/AgentHub.cs index 99df6bf8..20ccdad0 100644 --- a/src/slskd/Agents/API/Hubs/AgentHub.cs +++ b/src/slskd/Agents/API/Hubs/AgentHub.cs @@ -15,19 +15,20 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -using Microsoft.Extensions.Options; - namespace slskd.Agents { using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; - using slskd; + 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"; } /// @@ -49,24 +50,42 @@ namespace slskd.Agents public class AgentHub : Hub { public AgentHub( - IStateMonitor stateMonitor, - IOptionsMonitor optionsMonitor) + IAgentService agentService) { - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; + Agents = agentService; } - private IStateMonitor StateMonitor { get; } - private IOptionsMonitor OptionsMonitor { get; } + private IAgentService Agents { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); public override async Task OnConnectedAsync() { - // upon connection we need to do a little handshaking to establish - // that this is a registered agent, and which agent it is. whoever is calling - // has an api key or jwt, but users might disable auth, so literally anyone could - // connect. they should at least say who they are, and we'd allow or disallow - // todo: how to authenticate? - // todo: how to identify? + 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 index 5b17d996..5749c8c8 100644 --- a/src/slskd/Agents/AgentService.cs +++ b/src/slskd/Agents/AgentService.cs @@ -21,20 +21,29 @@ 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. /// - ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } + ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } + + /// + /// Gets the collection of registered Agents. + /// + ReadOnlyDictionary RegisteredAgents { get; } /// /// Retrieves an upload of the specified from the specified . @@ -44,6 +53,36 @@ namespace slskd.Agents /// 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 @@ -62,19 +101,88 @@ namespace slskd.Agents 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 SyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Gets the collection of pending Agent uploads. + /// 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 . /// - public ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } = new(); + /// 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 . @@ -97,7 +205,7 @@ namespace slskd.Agents // keep the stream open for the duration var completion = new TaskCompletionSource(); - PendingUploads.TryAdd(id, (upload, completion)); + 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); @@ -146,13 +254,42 @@ namespace slskd.Agents } catch (Exception ex) { - Console.WriteLine(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) { - SyncRoot.Wait(); + ConfigurationSyncRoot.Wait(); try { @@ -170,31 +307,32 @@ namespace slskd.Agents HttpClient = HttpClientFactory.CreateClient(); HttpClient.BaseAddress = new(options.Network.Controller.Address); - Console.WriteLine("-------------------------- building hub ------------------------"); HubConnection = new HubConnectionBuilder() .WithUrl($"{options.Network.Controller.Address}/hub/agents") - .WithAutomaticReconnect() + .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) .Build(); - HubConnection.On(AgentHubMethods.RequestFile, HandleFileRequest); 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 () => { - try - { - await Task.Delay(1000); - Console.WriteLine("------------------- connecting hub -------------------"); - await HubConnection.StartAsync(); - Log.Information("Controller connection established"); - Console.WriteLine("---------------------------- hub connected ----------------------"); - } - catch (Exception ex) - { - Console.WriteLine(ex); - } + // 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"); }); //} @@ -202,7 +340,7 @@ namespace slskd.Agents } finally { - SyncRoot.Release(); + ConfigurationSyncRoot.Release(); } } -- 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') 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 bd57bf490ddfe05004de02f30657d1359adc2dcc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 14:31:52 -0500 Subject: use CancellationTokens --- src/slskd/Common/Retry.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index eccb6b62..2f7b24cd 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -19,6 +19,7 @@ namespace slskd { using System; using System.Collections.Generic; + using System.Threading; using System.Threading.Tasks; /// @@ -34,14 +35,15 @@ namespace slskd /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in milliseconds. + /// The token to monitor for cancellation requests. /// The execution context. - public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { await Do(async () => { await task(); return Task.FromResult(null); - }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds); + }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds, cancellationToken); } /// @@ -52,9 +54,10 @@ namespace slskd /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in miliseconds. + /// The token to monitor for cancellation requests. /// The Type of the logic return value. /// The execution context. - public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { isRetryable ??= (_, _) => true; onFailure ??= (_, _) => { }; @@ -63,12 +66,17 @@ namespace slskd for (int attempts = 0; attempts < maxAttempts; attempts++) { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(); + } + try { if (attempts > 0) { var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, maxDelayInMilliseconds); - await Task.Delay(delay + jitter); + await Task.Delay(delay + jitter, cancellationToken); } return await task(); -- cgit v1.2.3 From 991b6e1e29fb1bbd3906ddfde3910998f840b060 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 14:51:14 -0500 Subject: add DualNetworkMode flag --- config/slskd.example.yml | 1 + docs/config.md | 3 ++- src/slskd/Core/Options.cs | 9 +++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7afeb5c8..9c5a7a0a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -10,6 +10,7 @@ # force_share_scan: false # no_version_check: false # log_sql: false +# dual_network_mode: false # network: # mode: controller # # controller config is required when running in 'agent' mode diff --git a/docs/config.md b/docs/config.md index aa09ddec..ce6b9bc5 100644 --- a/docs/config.md +++ b/docs/config.md @@ -769,7 +769,7 @@ Several additional feature flags are provided to change the application's runtim | Flag | Environment Variable | Description | | -------------------- | -------------------------- | ---------------------------------------------------------------- | | `-d\|--debug` | `SLSKD_DEBUG` | Run the application in debug mode. Produces verbose log output. | -| `--experimental` | `SLSKD_EXPERIMENTAL` | Run the application in experimental mode. YMMV. | +| `--experimental` | `SLSKD_EXPERIMENTAL` | Run the application in experimental mode. YMMV. | | `-n\|--no-logo` | `SLSKD_NO_LOGO` | Don't show the application logo on startup | | `-x\|--no-start` | `SLSKD_NO_START` | Bootstrap the application, but don't start | | `--no-connect` | `SLSKD_NO_CONNECT` | Start the application, but don't connect to the server | @@ -777,6 +777,7 @@ Several additional feature flags are provided to change the application's runtim | `--force-share-scan` | `SLSKD_FORCE_SHARE_SCAN` | Force a scan of shared directories on startup | | `--no-version-check` | `SLSKD_NO_VERSION_CHECK` | Don't perform a version check on startup | | `--log-sql` | `SLSKD_LOG_SQL` | Log SQL queries generated by Entity Framework | +| `--dual-network-mode`| `SLSKD_DUAL_NETWORK_MODE` | Run in both Agent and Controller network modes | #### **YAML** ```yaml diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cc155f5f..859e1379 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -362,6 +362,15 @@ namespace slskd [Description("log SQL queries generated by Entity Framework")] [RequiresRestart] public bool LogSQL { get; init; } = false; + + /// + /// Gets a value indicating whether to run in both controller and agent network modes. + /// + [Argument(default, "dual-network-mode")] + [EnvironmentVariable("DUAL_NETWORK_MODE")] + [Description("run in both controller and agent network modes")] + [RequiresRestart] + public bool DualNetworkMode { get; init; } = false; } /// -- 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') 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 0190f96c8ec99404bcce5078917a1786ede510af Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:31:38 -0500 Subject: return the resolved filename, not FileInfo. Add a way to request a scan --- src/slskd/Shares/IShareService.cs | 7 ++++++- src/slskd/Shares/ShareService.cs | 19 +++++++++---------- 2 files changed, 15 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 2a18f5b3..f8e2076d 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -60,7 +60,12 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - Task ResolveFileAsync(string remoteFilename); + Task ResolveFileAsync(string remoteFilename); + + /// + /// Requests that a share scan is performed. + /// + void RequestScan(); /// /// Searches the cache for the specified and returns the matching files. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 09085b72..2b761965 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -173,7 +173,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - public Task ResolveFileAsync(string remoteFilename) + public Task ResolveFileAsync(string remoteFilename) { var resolvedFilename = Repository.FindFilename(remoteFilename.LocalizePath()); @@ -182,16 +182,15 @@ namespace slskd.Shares throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a local file"); } - var fileInfo = new FileInfo(resolvedFilename); - - if (!fileInfo.Exists) - { - // the shared file cache has divered from the physical filesystem; the user needs to perform a scan to reconcile. - State.SetValue(state => state with { ScanPending = true }); - throw new NotFoundException($"The resolved file '{resolvedFilename}' could not be located on disk. A share scan should be performed."); - } + return Task.FromResult(resolvedFilename); + } - return Task.FromResult(fileInfo); + /// + /// Requests that a share scan is performed. + /// + public void RequestScan() + { + State.SetValue(state => state with { ScanPending = true }); } /// -- cgit v1.2.3 From 2c04388bb258ef34ce460f338f9db3429311abca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:33:25 -0500 Subject: retrieve FileInfo locally --- src/slskd/Transfers/Uploads/UploadService.cs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5b0bf749..e7561cbf 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -111,13 +111,21 @@ namespace slskd.Transfers.Uploads /// The operation context. public async Task EnqueueAsync(string username, string filename) { - FileInfo fileInfo = default; + string localFilename = default; + FileInfo localFileInfo = default; Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename); try { - fileInfo = await Shares.ResolveFileAsync(filename.LocalizePath()); + localFilename = await Shares.ResolveFileAsync(filename.LocalizePath()); + + localFileInfo = new FileInfo(filename); + + if (!localFileInfo.Exists) + { + throw new NotFoundException($"The resolved file '{localFilename}' could not be located on disk. A share scan should be performed."); + } } catch (NotFoundException) { @@ -126,12 +134,12 @@ namespace slskd.Transfers.Uploads } // find existing records for this username and file that haven't been removed from the UI - var existingRecords = List(t => t.Username == username && t.Filename == fileInfo.FullName && !t.Removed); + var existingRecords = List(t => t.Username == username && t.Filename == localFileInfo.FullName && !t.Removed); // check whether any of these records is in a non-complete state and bail out if so if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed))) { - Log.Information("Upload {Filename} to {Username} is already queued or in progress", fileInfo.FullName, username); + Log.Information("Upload {Filename} to {Username} is already queued or in progress", localFileInfo.FullName, username); return; } @@ -142,8 +150,8 @@ namespace slskd.Transfers.Uploads Id = id, Username = username, Direction = TransferDirection.Upload, - Filename = fileInfo.FullName, - Size = fileInfo.Length, + Filename = localFileInfo.FullName, + Size = localFileInfo.Length, StartOffset = 0, // potentially updated later during handshaking RequestedAt = DateTime.UtcNow, }; @@ -188,7 +196,7 @@ namespace slskd.Transfers.Uploads var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", fileInfo.FullName, username, args.PreviousState, args.Transfer.State); + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFileInfo.FullName, username, args.PreviousState, args.Transfer.State); if (Application.IsShuttingDown) { @@ -225,7 +233,7 @@ namespace slskd.Transfers.Uploads var completedTransfer = await Client.UploadAsync( username, filename, - size: fileInfo.Length, + size: localFileInfo.Length, inputStreamFactory: () => stream, options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From 30b7cb4d5bdd496ed01ac13cb9841cab7ac6a394 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:48:50 -0500 Subject: add endpoint to allow agents to report failures --- .../Network/API/Controllers/NetworkController.cs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 836921f1..267705a1 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -40,10 +40,6 @@ namespace slskd.Network 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) @@ -79,5 +75,23 @@ namespace slskd.Network return NotFound(); } } + + [HttpDelete("files/{id}")] + [Authorize] + public IActionResult NotifyUploadFailed(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + if (Network.PendingUploads.TryGetValue(guid, out var record)) + { + record.Upload.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); + return NoContent(); + } + + return NotFound(); + } } } -- cgit v1.2.3 From a67bf12a42eb58390a0a51bc2d70bed835404b35 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:56:56 -0500 Subject: don't throw FileNotFoundException --- src/slskd/Transfers/Uploads/UploadQueue.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 2c7e3eac..53e135e8 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers /// The username associated with the file. /// The filename of the file for which the position is to be estimated. /// The estimated queue position of the file. - /// Thrown if the specified filename is not enqueued. + /// Thrown if the specified filename is not enqueued. int EstimatePosition(string username, string filename); /// @@ -251,7 +251,7 @@ namespace slskd.Transfers /// The username associated with the file. /// The filename of the file for which the position is to be estimated. /// The estimated queue position of the file. - /// Thrown if the specified filename is not enqueued. + /// Thrown if the specified filename is not enqueued. public int EstimatePosition(string username, string filename) { var groupName = Users.GetGroup(username); @@ -269,7 +269,7 @@ namespace slskd.Transfers // find this user's uploads if (!Uploads.TryGetValue(username, out var uploadsForUser)) { - throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); + throw new NotFoundException($"File {filename} is not enqueued for user {username}"); } // find the position of the requested file in the user's queue @@ -280,7 +280,7 @@ namespace slskd.Transfers if (localPosition < 0) { - throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); + throw new NotFoundException($"File {filename} is not enqueued for user {username}"); } // start the position to the local position within this user's queue; the user's own files must be completed @@ -321,7 +321,7 @@ namespace slskd.Transfers if (globalPosition < 0) { - throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); + throw new NotFoundException($"File {filename} is not enqueued for user {username}"); } return globalPosition; -- cgit v1.2.3 From 1f1dc6dcac73308d6ee61fb75b9ed8f7383e0e73 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:57:11 -0500 Subject: request scan on file mismatch --- src/slskd/Transfers/Uploads/UploadService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index e7561cbf..ce4a3474 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -124,7 +124,8 @@ namespace slskd.Transfers.Uploads if (!localFileInfo.Exists) { - throw new NotFoundException($"The resolved file '{localFilename}' could not be located on disk. A share scan should be performed."); + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); } } catch (NotFoundException) -- cgit v1.2.3 From 208082c34935aa8fc91d910b86bae611a29392f7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:57:32 -0500 Subject: resolve requested files from share --- src/slskd/Network/NetworkClient.cs | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index be7b6a2c..e37936d7 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -27,6 +27,7 @@ namespace slskd.Network using Microsoft.AspNetCore.SignalR.Client; using Serilog; using slskd.Cryptography; + using slskd.Shares; public interface INetworkClient { @@ -37,9 +38,12 @@ namespace slskd.Network public class NetworkClient : INetworkClient { public NetworkClient( + IShareService shareService, IOptionsMonitor optionsMonitor, IHttpClientFactory httpClientFactory) { + Shares = shareService; + HttpClientFactory = httpClientFactory; OptionsMonitor = optionsMonitor; @@ -48,6 +52,7 @@ namespace slskd.Network Configure(OptionsMonitor.CurrentValue); } + private IShareService Shares { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } @@ -56,6 +61,7 @@ namespace slskd.Network private HubConnection HubConnection { get; set; } private bool StartRequested { get; set; } private CancellationTokenSource StartCancellationTokenSource { get; set; } + private ILogger Log { get; } = Serilog.Log.ForContext(); public async Task StartAsync(CancellationToken cancellationToken = default) { @@ -99,7 +105,17 @@ namespace slskd.Network try { - using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + var localFilename = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(filename); + + if (!localFileInfo.Exists) + { + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + } + + using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); using var content = new MultipartFormDataContent { @@ -114,23 +130,24 @@ namespace slskd.Network 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!"); + Log.Information("Upload of file {Filename} with ID {Id} succeeded.", filename); } } catch (Exception ex) { Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + + // report the failure to the controller. this avoids a failure due to timeout. + _ = HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}")); } } private async Task HandleAuthenticationChallenge(string challengeToken) { - Log.Information("Network controller sent an authentication challenge"); + Log.Debug("Network controller sent an authentication challenge"); try { @@ -142,7 +159,7 @@ namespace slskd.Network var response = Aes.Encrypt(tokenBytes, key).ToBase62(); - Log.Information("Logging in..."); + Log.Debug("Logging in..."); var success = await HubConnection.InvokeAsync("Login", agent, response); if (!success) @@ -150,6 +167,8 @@ namespace slskd.Network await HubConnection.StopAsync(); Log.Error("Network controller authentication failed. Check configuration."); } + + Log.Information("Network controller authentication succeeded."); } catch (Exception ex) { @@ -193,7 +212,7 @@ namespace slskd.Network return; } - Log.Information("Network options changed. Reconfiguring..."); + Log.Debug("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 @@ -224,7 +243,7 @@ namespace slskd.Network LastOptionsHash = optionsHash; - Log.Information("Network options reconfigured"); + Log.Debug("Network options reconfigured"); // if start was requested (if StartAsync() was called externally), restart // after re-configuration -- cgit v1.2.3 From 624602327558e8de8619f89407510d173d98af29 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:58:19 -0500 Subject: connect to controller in background when in dual mode --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e0688848..2705da5d 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -405,7 +405,7 @@ namespace slskd { if (OptionsAtStartup.Flags.DualNetworkMode) { - await NetworkClient.StartAsync(cancellationToken); + _ = NetworkClient.StartAsync(cancellationToken); } await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); @@ -724,7 +724,7 @@ namespace slskd var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); return Task.FromResult((int?)place); } - catch (FileNotFoundException) + catch (NotFoundException) { return Task.FromResult(null); } -- cgit v1.2.3 From 81b7d32006af8bceba30855aee7bd69c4695a9d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:20:18 -0500 Subject: add NetworkException --- src/slskd/Common/Exceptions/NetworkException.cs | 72 +++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/slskd/Common/Exceptions/NetworkException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/NetworkException.cs b/src/slskd/Common/Exceptions/NetworkException.cs new file mode 100644 index 00000000..1fb903bb --- /dev/null +++ b/src/slskd/Common/Exceptions/NetworkException.cs @@ -0,0 +1,72 @@ +// +// 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 +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an error related to the slskd network feature. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class NetworkException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public NetworkException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public NetworkException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public NetworkException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected NetworkException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file -- cgit v1.2.3 From 6e19db2213d491c3d2965c964c40a7129e74f633 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:20:42 -0500 Subject: add UploadShares endpoint --- .../Network/API/Controllers/NetworkController.cs | 33 ++++++++++++++++++---- 1 file changed, 28 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 267705a1..8f863ce4 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -38,7 +38,7 @@ namespace slskd.Network } private INetworkService Network { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); [HttpPost("files/{id}")] [Authorize] @@ -50,7 +50,7 @@ namespace slskd.Network } // get the record for the waiting file - if (Network.PendingUploads.TryGetValue(guid, out var record)) + if (Network.PendingFileUploads.TryGetValue(guid, out var record)) { // get the stream from the multipart upload var stream = Request.Form.Files.First().OpenReadStream(); @@ -58,7 +58,7 @@ namespace slskd.Network // set the result for the stream // this should pass control to the transfer service along with // the stream - record.Upload.SetResult(stream); + record.Stream.SetResult(stream); Console.WriteLine("Stream handed off. Waiting for completion..."); @@ -85,13 +85,36 @@ namespace slskd.Network return BadRequest("Id is not a valid Guid"); } - if (Network.PendingUploads.TryGetValue(guid, out var record)) + if (Network.PendingFileUploads.TryGetValue(guid, out var record)) { - record.Upload.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); + record.Stream.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); return NoContent(); } return NotFound(); } + + [HttpPost("shares/{id}")] + [Authorize] + public IActionResult UploadShares(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + if (!Network.TryGetShareUploadToken(guid, out var agent)) + { + return Unauthorized(); + } + + // todo: save the uploaded file to a temp location + // todo: open the uploaded file as a sqlite database + // todo: load the contents of the file into the local share database + // while modifying the records somehow to indicate which agent + // is hosting it + + return Ok(); + } } } -- cgit v1.2.3 From a8fe7056791ae7e12130fa0ed5e024e99eb40c3e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:20:59 -0500 Subject: add hub method GetShareUploadToken --- src/slskd/Network/API/Hubs/NetworkHub.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 61ac08f0..becbbed0 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -87,5 +87,16 @@ namespace slskd.Network Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! return false; } + + public Guid GetShareUploadToken() + { + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var agent)) + { + return Network.GetShareUploadToken(agent); + } + + // this can happen if the agent attempts to upload before logging in + throw new UnauthorizedAccessException(); + } } } \ No newline at end of file -- cgit v1.2.3 From 34d07fdeb4fd83fbce0f4d9c82125289b8b2a8f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:21:32 -0500 Subject: add methods to orchestrate share uploads --- src/slskd/Network/NetworkService.cs | 107 +++++++++++++++++++++++++++++------- 1 file changed, 87 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 368e6cf4..6c573da0 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -23,11 +23,8 @@ namespace slskd.Network 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; @@ -35,9 +32,9 @@ namespace slskd.Network public interface INetworkService { /// - /// Gets the collection of pending Agent uploads. + /// Gets the collection of pending Agent file uploads. /// - ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads { get; } + ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } /// /// Gets the collection of registered Agents. @@ -51,7 +48,25 @@ namespace slskd.Network /// 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); + Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000); + + /// + /// Retrieves a new share upload token for the specified . + /// + /// + /// The token is cached internally, and is only valid while it remains in the cache. + /// + /// The name of the agent. + /// The generated token. + Guid GetShareUploadToken(string agent); + + /// + /// Attempts to retrieve the specified share upload . + /// + /// The token. + /// The name of the agent attempting to use the token. + /// A value indicating whether the specified token exists. + bool TryGetShareUploadToken(Guid token, out string agent); /// /// Registers the specified name with the specified . @@ -60,16 +75,28 @@ namespace slskd.Network /// The name of the agent. void RegisterAgent(string connectionId, string agent); + /// + /// Attempts to retrieve the registration for the specified . + /// + /// The ID of the agent connection. + /// The agent, if registered. + /// A value indicating whether the registration exists. + bool TryGetAgentRegistration(string connectionId, out string agent); + /// /// Attempts to remove the registration for the specified . /// /// The ID of the connection. + /// The agent, if removed. /// 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 token is cached internally, and is only valid while it remains in the cache. + /// /// The ID of the agent connection. /// The generated token. string GenerateAuthenticationChallengeToken(string connectionId); @@ -88,11 +115,9 @@ namespace slskd.Network { public NetworkService( IOptionsMonitor optionsMonitor, - IHttpClientFactory httpClientFactory, IHubContext networkHub) { NetworkHub = networkHub; - HttpClientFactory = httpClientFactory; OptionsMonitor = optionsMonitor; } @@ -100,25 +125,55 @@ namespace slskd.Network /// /// Gets the collection of pending Agent uploads. /// - public ReadOnlyDictionary Upload, TaskCompletionSource Completion)> PendingUploads => new(PendingUploadDictionary); + public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); /// /// Gets the collection of registered Agents. /// public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); - private ConcurrentDictionary Upload, TaskCompletionSource Completion)> PendingUploadDictionary { get; } = new(); + private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { 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(); + /// + /// Retrieves a new share upload token for the specified . + /// + /// + /// The token is cached internally, and is only valid while it remains in the cache. + /// + /// The name of the agent. + /// The generated token. + public Guid GetShareUploadToken(string agent) + { + var token = Guid.NewGuid(); + MemoryCache.Set(GetShareTokenCacheKey(token), agent, TimeSpan.FromMinutes(1)); + Log.Debug("Cached share upload token {Token} for agent {Agent}", token, agent); + + return token; + } + + /// + /// Attempts to retrieve the specified share upload . + /// + /// The token. + /// The name of the agent attempting to use the token. + /// A value indicating whether the specified token exists. + public bool TryGetShareUploadToken(Guid token, out string agent) + { + agent = null; + + if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agent)) + { + return true; + } + + return false; + } + /// /// Registers the specified name with the specified . /// @@ -127,6 +182,15 @@ namespace slskd.Network public void RegisterAgent(string connectionId, string agent) => RegisteredAgentDictionary.TryAdd(connectionId, agent); + /// + /// Attempts to retrieve the registration for the specified . + /// + /// The ID of the agent connection. + /// The agent, if registered. + /// A value indicating whether the registration exists. + public bool TryGetAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryGetValue(connectionId, out agent); + /// /// Attempts to remove the registration for the specified . /// @@ -147,8 +211,8 @@ namespace slskd.Network // 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); + MemoryCache.Set(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromMinutes(1)); + Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); return token; } @@ -161,7 +225,7 @@ namespace slskd.Network /// A value indicating whether the response is valid. public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) { - if (!MemoryCache.TryGetValue(connectionId, out var challengeToken)) + if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(connectionId), out var challengeToken)) { Log.Debug("Auth challenge for {Id} failed: no challenge token cached for ID", connectionId); return false; @@ -187,7 +251,7 @@ namespace slskd.Network /// 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) + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) { var id = Guid.NewGuid(); @@ -201,7 +265,7 @@ namespace slskd.Network // keep the stream open for the duration var completion = new TaskCompletionSource(); - PendingUploadDictionary.TryAdd(id, (upload, completion)); + PendingFileUploadDictionary.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); @@ -218,5 +282,8 @@ namespace slskd.Network throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); } } + + private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; + private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; } } -- cgit v1.2.3 From 345485ad861ad0b2e643a3dbfc21eac013cd755c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:21:47 -0500 Subject: stub logic to upload shares --- src/slskd/Network/NetworkClient.cs | 57 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index e37936d7..007ce80f 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -62,6 +62,7 @@ namespace slskd.Network private bool StartRequested { get; set; } private CancellationTokenSource StartCancellationTokenSource { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private TaskCompletionSource LoggedIn { get; set; } public async Task StartAsync(CancellationToken cancellationToken = default) { @@ -71,6 +72,7 @@ namespace slskd.Network } StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + LoggedIn = new TaskCompletionSource(); StartRequested = true; Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); @@ -84,7 +86,24 @@ namespace slskd.Network maxDelayInMilliseconds: 30000, StartCancellationTokenSource.Token); - Log.Information("Network controller connection established"); + Log.Information("Network controller connection established. Awaiting authentication..."); + + await LoggedIn.Task; + + Log.Information("Authenticated. Uploading shares..."); + + try + { + await UploadSharesAsync(); + } + catch (Exception ex) + { + Log.Error($"Failed to upload shares to the network controller: {ex.Message}"); + Log.Error("Disconnecting"); + await StopAsync(); + } + + Log.Information("Shares uploaded. Ready to upload files."); } public async Task StopAsync(CancellationToken cancellationToken = default) @@ -99,6 +118,37 @@ namespace slskd.Network } } + public async Task UploadSharesAsync() + { + Log.Debug("Requesting share upload token..."); + var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); + Log.Debug("Share upload token {Token}", token); + + var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_backup_{Path.GetRandomFileName()}.db"); + + // todo: back up shares database to temp location + // todo: upload shares database backup to controller + + using var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "shares" }, + }; + + request.Content = content; + + Log.Information("Beginning upload of shares"); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + throw new NetworkException($"Failed to upload shares to network controller: {response.StatusCode}"); + } + + Log.Information("Upload shares succeeded"); + } + private async Task HandleFileRequest(Guid id, string filename) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -160,7 +210,7 @@ namespace slskd.Network var response = Aes.Encrypt(tokenBytes, key).ToBase62(); Log.Debug("Logging in..."); - var success = await HubConnection.InvokeAsync("Login", agent, response); + var success = await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); if (!success) { @@ -168,7 +218,8 @@ namespace slskd.Network Log.Error("Network controller authentication failed. Check configuration."); } - Log.Information("Network controller authentication succeeded."); + Log.Debug("Login succeeded."); + LoggedIn?.TrySetResult(); } catch (Exception ex) { -- cgit v1.2.3 From a0476551cf8da20cbc51361d20a28a3b12bd4395 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:30:39 -0500 Subject: add BackupTo() --- src/slskd/Shares/IShareService.cs | 8 ++++++-- src/slskd/Shares/ShareService.cs | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index f8e2076d..5144ada8 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -15,8 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -using System.IO; - namespace slskd.Shares { using System.Collections.Generic; @@ -38,6 +36,12 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor { get; } + /// + /// 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. /// diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 2b761965..23917535 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -98,6 +98,15 @@ namespace slskd.Shares private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + /// + /// 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. /// -- cgit v1.2.3 From e35a1445bbe6cddc23c62c7641d887c993fe38a7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:15:24 -0500 Subject: fix bug --- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index ce4a3474..2150194b 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -229,7 +229,7 @@ namespace slskd.Transfers.Uploads //using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - var (stream, completion) = await Network.GetUpload("any", filename); + var (stream, completion) = await Network.GetFileUpload("any", filename); var completedTransfer = await Client.UploadAsync( username, -- cgit v1.2.3 From 35edcb342ded5a9bdc4f0627f0c213b85c033bba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:15:53 -0500 Subject: fix operand order --- src/slskd/Network/API/Hubs/NetworkHub.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index becbbed0..78a658d4 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -79,7 +79,7 @@ namespace slskd.Network if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) { Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); - Network.RegisterAgent(agent, Context.ConnectionId); + Network.RegisterAgent(Context.ConnectionId, agent); return true; } @@ -96,6 +96,7 @@ namespace slskd.Network } // this can happen if the agent attempts to upload before logging in + Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } } -- cgit v1.2.3 From 4bb2484d7b5f3bd1d0e49f8393c4065fa1e59339 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:16:10 -0500 Subject: save to a temp file --- .../Network/API/Controllers/NetworkController.cs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 8f863ce4..69e3d789 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -18,6 +18,7 @@ namespace slskd.Network { using System; + using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; @@ -96,7 +97,7 @@ namespace slskd.Network [HttpPost("shares/{id}")] [Authorize] - public IActionResult UploadShares(string id) + public async Task UploadShares(string id) { if (!Guid.TryParse(id, out var guid)) { @@ -108,11 +109,19 @@ namespace slskd.Network return Unauthorized(); } - // todo: save the uploaded file to a temp location - // todo: open the uploaded file as a sqlite database - // todo: load the contents of the file into the local share database - // while modifying the records somehow to indicate which agent - // is hosting it + var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db"); + + 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(); + + 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 return Ok(); } -- cgit v1.2.3 From 3c3cfe6f2c3c49c05aa4de1e86a81fcb2c8af590 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:16:23 -0500 Subject: implement share upload --- src/slskd/Network/NetworkClient.cs | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 007ce80f..10e33118 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -25,6 +25,7 @@ namespace slskd.Network using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; + using Microsoft.Data.Sqlite; using Serilog; using slskd.Cryptography; using slskd.Shares; @@ -98,9 +99,10 @@ namespace slskd.Network } catch (Exception ex) { - Log.Error($"Failed to upload shares to the network controller: {ex.Message}"); - Log.Error("Disconnecting"); + Log.Error(ex, ex.Message); + Log.Error("Disconnecting from the network controller"); await StopAsync(); + throw; } Log.Information("Shares uploaded. Ready to upload files."); @@ -120,16 +122,34 @@ namespace slskd.Network public async Task UploadSharesAsync() { + var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); + + 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 + Log.Debug("Share backup successful"); + Log.Debug("Requesting share upload token..."); var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); Log.Debug("Share upload token {Token}", token); - var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_backup_{Path.GetRandomFileName()}.db"); + FileStream stream = default; - // todo: back up shares database to temp location - // todo: upload shares database backup to controller + try + { + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + } + 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(); + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + } - using var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); using var content = new MultipartFormDataContent { @@ -191,7 +211,8 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - _ = HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}")); + using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}"); + _ = HttpClient.SendAsync(request); } } -- cgit v1.2.3 From 5281911a0634bd790adef13e7e0de28d40e9ee4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 08:04:47 -0500 Subject: add ShareRepositoryFactory, consolidate a lot of OOP cruft --- .../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') 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 From 465ee43f9e95e9e98b9e039392c94ad92e7f6416 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:35:58 -0500 Subject: add note --- src/slskd/Core/Options.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index c8ccbd69..b75f9356 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -401,6 +401,9 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); + + // todo: can't run in agent mode if instancename is default + //var controllerResults = new List(); //var agentResults = new List(); -- cgit v1.2.3 From 8d0799dc956b6c5b1473e010cdf0e6566e10c72c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:36:19 -0500 Subject: simplify Host --- src/slskd/Shares/Types/Host.cs | 18 ++---------------- src/slskd/Shares/Types/HostState.cs | 35 ----------------------------------- src/slskd/Shares/Types/HostType.cs | 35 ----------------------------------- 3 files changed, 2 insertions(+), 86 deletions(-) delete mode 100644 src/slskd/Shares/Types/HostState.cs delete mode 100644 src/slskd/Shares/Types/HostType.cs (limited to 'src') diff --git a/src/slskd/Shares/Types/Host.cs b/src/slskd/Shares/Types/Host.cs index 3c5c9f9f..50302480 100644 --- a/src/slskd/Shares/Types/Host.cs +++ b/src/slskd/Shares/Types/Host.cs @@ -29,36 +29,22 @@ namespace slskd.Shares /// Initializes a new instance of the class. /// /// The name of the host. - /// The type of the host. /// The collection of hosted shares. - /// The initial state of the host. - public Host(string name, HostType type, IEnumerable shares = null, HostState state = HostState.Offline) + public Host(string name, IEnumerable shares = null) { Name = name; - Type = type; Shares = shares ?? Enumerable.Empty(); - State = state; } /// /// Gets the name of the host. /// - /// Corresponds to the configured of the host. + /// Corresponds to the configured of the host, or "local" for the local host. public string Name { get; } /// /// Gets the collection of hosted shares. /// public IEnumerable Shares { get; init; } - - /// - /// Gets the host state. - /// - public HostState State { get; init; } - - /// - /// Gets the host type. - /// - public HostType Type { get; } } } \ No newline at end of file diff --git a/src/slskd/Shares/Types/HostState.cs b/src/slskd/Shares/Types/HostState.cs deleted file mode 100644 index b10074d3..00000000 --- a/src/slskd/Shares/Types/HostState.cs +++ /dev/null @@ -1,35 +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 -{ - /// - /// The state of a share host. - /// - public enum HostState - { - /// - /// Offline; unable to service requests. - /// - Offline = 0, - - /// - /// Online; able to service requests. - /// - Online = 1, - } -} diff --git a/src/slskd/Shares/Types/HostType.cs b/src/slskd/Shares/Types/HostType.cs deleted file mode 100644 index 6a892dff..00000000 --- a/src/slskd/Shares/Types/HostType.cs +++ /dev/null @@ -1,35 +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 -{ - /// - /// The type of host. - /// - public enum HostType - { - /// - /// Local. - /// - Local = 0, - - /// - /// Remote; shares are hosted by an Agent. - /// - Remote = 1, - } -} -- cgit v1.2.3 From 88e1aac548cdc6a8bd9cad51c288e61f935ea7cf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:39:09 -0500 Subject: add some methods for managing agent hosts --- src/slskd/Shares/IShareService.cs | 20 +++++++++++++++++ src/slskd/Shares/ShareService.cs | 45 +++++++++++++++++++++++++++++++-------- 2 files changed, 56 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index b55db482..f0c474a1 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -31,6 +31,11 @@ namespace slskd.Shares /// IReadOnlyList Hosts { get; } + /// + /// Gets the local share host. + /// + Host LocalHost { get; } + /// /// Gets the state monitor for the service. /// @@ -55,6 +60,14 @@ namespace slskd.Shares /// The operation context. Task DumpAsync(string filename); + /// + /// Returns the share host with the specified . + /// + /// The name of the host. + /// The host, if found. + /// A value indicating whether the host was found. + bool TryGetHost(string name, out Host host); + /// /// Returns the contents of the specified . /// @@ -62,6 +75,13 @@ namespace slskd.Shares /// The contents of the directory. Task ListDirectoryAsync(string directory); + /// + /// Removes the share host with the specified . + /// + /// The name of the host. + /// A value indicating whether the host was removed. + bool TryRemoveHost(string name); + /// /// Resolves the local filename of the specified , if the mask is associated with a /// configured share. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index cc35477e..03b0f2e1 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -51,8 +51,8 @@ namespace slskd.Shares ShareRepositoryFactory = shareRepositoryFactory; - var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); - var repository = ShareRepositoryFactory.CreateFromHost(options.InstanceName); + var host = new Host("local"); + var repository = ShareRepositoryFactory.CreateFromHost(host.Name); Local = (host, repository); @@ -93,6 +93,11 @@ namespace slskd.Shares /// public IReadOnlyList Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly(); + /// + /// Gets the local share host. + /// + public Host LocalHost => Local.Host; + /// /// Gets the state monitor for the service. /// @@ -124,7 +129,6 @@ namespace slskd.Shares updateValueFactory: (_, existing) => (host, existing.Repository)); AllRepositories = HostDictionary.Values - .Where(value => value.Host.State == HostState.Online) .Select(value => value.Repository) .Prepend(Local.Repository); } @@ -192,6 +196,32 @@ namespace slskd.Shares return Task.CompletedTask; } + /// + /// Returns the share host with the specified . + /// + /// The name of the host. + /// The host, if found. + /// A value indicating whether the host was found. + public bool TryGetHost(string name, out Host host) + { + if (HostDictionary.TryGetValue(name, out var record)) + { + host = record.Host; + return true; + } + + host = null; + return false; + } + + /// + /// Removes the share host with the specified . + /// + /// The name of the host. + /// A value indicating whether the host was removed. + public bool TryRemoveHost(string name) + => HostDictionary.TryRemove(name, out _); + /// /// Returns the contents of the specified . /// @@ -264,7 +294,7 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName)); + Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)); Log.Debug("Shared file cache database backup complete"); } @@ -311,7 +341,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { @@ -339,7 +369,7 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { @@ -413,9 +443,6 @@ namespace slskd.Shares Local = (Local.Host with { Shares = shares }, Local.Repository); - // todo: initialize agent hosts - // todo: don't destroy or overwrite existing hosts! - LastOptionsHash = optionsHash; } finally -- cgit v1.2.3 From a3b23e0e1e9b013f79f9e93a1963a865e3c60ede Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:39:52 -0500 Subject: finish implementation of share uploads --- .../Network/API/Controllers/NetworkController.cs | 36 +++++++++++----------- 1 file changed, 18 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index deeddc04..21373749 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -18,10 +18,12 @@ namespace slskd.Network { using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Shares; @@ -86,36 +88,32 @@ namespace slskd.Network } } - [HttpDelete("files/{id}")] + [HttpPost("shares/{id}")] [Authorize] - public IActionResult NotifyUploadFailed(string id) + public async Task UploadShares(string id) { if (!Guid.TryParse(id, out var guid)) { return BadRequest("Id is not a valid Guid"); } - if (Network.PendingFileUploads.TryGetValue(guid, out var record)) + if (!Network.TryGetShareUploadToken(guid, out var agent)) { - record.Stream.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); - return NoContent(); + return Unauthorized(); } - return NotFound(); - } + IEnumerable shares; + IFormFile database; - [HttpPost("shares/{id}")] - [Authorize] - public async Task UploadShares(string id) - { - if (!Guid.TryParse(id, out var guid)) + try { - return BadRequest("Id is not a valid Guid"); + shares = Request.Form["shares"].ToString().FromJson>(); + database = Request.Form.Files[0]; } - - if (!Network.TryGetShareUploadToken(guid, out var agent)) + catch (Exception ex) { - return Unauthorized(); + Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agent, ex.Message); + return BadRequest(); } var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db"); @@ -123,7 +121,7 @@ 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[0].OpenReadStream(); + using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); @@ -133,13 +131,15 @@ namespace slskd.Network if (!repository.TryValidate(out var problems)) { - return BadRequest(string.Join(", ", problems)); + return BadRequest("Invalid database: " + string.Join(", ", problems)); } var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); destinationRepository.RestoreFrom(repository); + Shares.AddOrUpdateHost(new Host(agent, shares)); + return Ok(); } } -- cgit v1.2.3 From e2383ff98d4994fa2215eb47b8b0cd69775e088b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:40:20 -0500 Subject: add a hub method to handle failed uploads --- src/slskd/Network/API/Hubs/NetworkHub.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 78a658d4..6d43e6da 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -99,5 +99,13 @@ namespace slskd.Network Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } + + public void NotifyUploadFailed(Guid id) + { + if (Network.PendingFileUploads.TryGetValue(id, out var record)) + { + record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } } } \ No newline at end of file -- cgit v1.2.3 From da0eab6deb0c59b2cb4a377ba165139783cb2155 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:41:27 -0500 Subject: stub config --- src/slskd/Network/NetworkService.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 6c573da0..8753ae0a 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -23,6 +23,7 @@ namespace slskd.Network using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.IO; + using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Memory; @@ -120,6 +121,9 @@ namespace slskd.Network NetworkHub = networkHub; OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); } /// @@ -138,6 +142,7 @@ namespace slskd.Network private IOptionsMonitor OptionsMonitor { get; } private IHubContext NetworkHub { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); /// /// Retrieves a new share upload token for the specified . @@ -285,5 +290,18 @@ namespace slskd.Network private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; + + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + } + finally + { + SyncRoot.Release(); + } + } } } -- cgit v1.2.3 From 09348537947ff6a2a405754ead0904eaee848203 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:46:30 -0500 Subject: simplify uploads --- src/slskd/Network/NetworkClient.cs | 30 ++++++------------------------ 1 file changed, 6 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 15f114f9..d171e9b9 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -134,30 +134,13 @@ namespace slskd.Network var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); Log.Debug("Share upload token {Token}", token); - FileStream stream = default; + var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - while (true) - { - 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}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); using var content = new MultipartFormDataContent { - { new StreamContent(stream), "shares" }, + { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, + { new StreamContent(stream), "database", "shares" }, }; request.Content = content; @@ -190,7 +173,7 @@ namespace slskd.Network } using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{id}"); using var content = new MultipartFormDataContent { { new StreamContent(stream), "file", filename }, @@ -215,8 +198,7 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}"); - _ = HttpClient.SendAsync(request); + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), id); } } -- cgit v1.2.3 From cdf397d340a1a4c2b4c5077adce997854a0787b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:46:53 -0500 Subject: fix bug in dump --- src/slskd/Shares/SqliteShareRepository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 9b65794e..0a71280d 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -160,10 +160,10 @@ namespace slskd.Shares public void DumpTo(string filename) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection($"Data Source={filename}"); - sourceConn.BackupDatabase(backupConn); - Sqlite. + // very important! don't use pooling for the backup connection or the file will remain locked + using var backupConn = GetConnection($"Data Source={filename};Pooling=False"); + sourceConn.BackupDatabase(backupConn); } /// -- cgit v1.2.3 From 7e34146d679b3b6c1692a41f1ea9ab4547889a43 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 16:01:42 -0500 Subject: fix expression --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2705da5d..22efa5ec 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -396,7 +396,7 @@ 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 || !OptionsAtStartup.Flags.DualNetworkMode) + 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); -- cgit v1.2.3 From e8a67ea0016560aa3f0c73f0b75b4baf86e6c13a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 17:26:59 -0500 Subject: fix an issue with browse caching --- src/slskd/Application.cs | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 22efa5ec..bdb55ca4 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -445,11 +445,13 @@ namespace slskd if (!cacheFileInfo.Exists) { Log.Warning("Browse response not cached. Rebuilding..."); - await CacheBrowseResponse(); + response = await CacheBrowseResponse(); + } + else + { + var stream = new FileStream(cacheFilename, FileMode.Open, FileAccess.Read); + response = new RawBrowseResponse(cacheFileInfo.Length, stream); } - - var stream = new FileStream(cacheFilename, FileMode.Open, FileAccess.Read); - response = new RawBrowseResponse(cacheFileInfo.Length, stream); Log.Information("Sent browse response to {User}", username); @@ -1051,14 +1053,34 @@ namespace slskd } } - private async Task CacheBrowseResponse() + private async Task CacheBrowseResponse() { - var directories = await Shares.BrowseAsync(); - var response = new BrowseResponse(directories); + try + { + var sw = new Stopwatch(); + sw.Start(); + + var directories = await Shares.BrowseAsync(); + var response = new BrowseResponse(directories); + var temp = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var destination = Path.Combine(Program.DataDirectory, "browse.cache"); + + Log.Information("Warming browse response cache..."); + await System.IO.File.WriteAllBytesAsync(temp, response.ToByteArray()); - Log.Information("Warming browse response cache..."); - System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, "browse.cache"), response.ToByteArray()); - Log.Information("Browse response cached successfully"); + Log.Debug("Saved cache to temp file {File}", temp); + + System.IO.File.Move(temp, destination, overwrite: true); + + sw.Stop(); + Log.Information("Browse response cached successfully in {Duration}ms", sw.ElapsedMilliseconds); + return response; + } + catch (Exception ex) + { + Log.Error(ex, "Error caching browse response: {Message}", ex.Message); + throw; + } } private void State_OnChange((State Previous, State Current) state) -- cgit v1.2.3 From b641fc2919ff7af027d621868ca02a3cc25b67ae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 17:40:57 -0500 Subject: resolve host as well as filename --- src/slskd/Shares/IShareService.cs | 4 ++-- src/slskd/Shares/ShareService.cs | 27 ++++++++++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index f0c474a1..34f1bde8 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -87,11 +87,11 @@ namespace slskd.Shares /// configured share. /// /// The fully qualified filename to resolve. - /// The resolved local filename. + /// The resolved host and filename. /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - Task ResolveFileAsync(string remoteFilename); + Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename); /// /// Requests that a share scan is performed. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 03b0f2e1..88105a8f 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -245,18 +245,31 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - public Task ResolveFileAsync(string remoteFilename) + public Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename) { - var resolvedFilename = AllRepositories - .Select(r => r.FindFilename(remoteFilename.LocalizePath())) - .FirstOrDefault(r => !string.IsNullOrEmpty(r)); + string resolvedHost = "local"; + string resolvedFilename = default; - if (string.IsNullOrEmpty(resolvedFilename)) + resolvedFilename = Local.Repository.FindFilename(remoteFilename.LocalizePath()); + + if (!string.IsNullOrEmpty(resolvedFilename)) + { + return Task.FromResult((resolvedHost, resolvedFilename)); + } + + // file not found locally. begin searching other hosts one by one. + // this is the slow, dumb way to do this, but it's plenty fast in this context. + foreach (var host in HostDictionary.Values) { - throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a local file"); + resolvedFilename = host.Repository.FindFilename(remoteFilename.LocalizePath()); + + if (!string.IsNullOrEmpty(resolvedFilename)) + { + return Task.FromResult((host.Host.Name, resolvedFilename)); + } } - return Task.FromResult(resolvedFilename); + throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a physical file"); } /// -- cgit v1.2.3 From dad776edec3b1ae8cc3bdf6620e4b9a97855dbc0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 18:05:35 -0500 Subject: handle local and agent uploads differently --- src/slskd/Transfers/Uploads/UploadService.cs | 45 ++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5e2a6da6..d0a599d8 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -111,6 +111,7 @@ namespace slskd.Transfers.Uploads /// The operation context. public async Task EnqueueAsync(string username, string filename) { + string host = default; string localFilename = default; FileInfo localFileInfo = default; @@ -118,7 +119,7 @@ namespace slskd.Transfers.Uploads try { - localFilename = await Shares.ResolveFileAsync(filename.LocalizePath()); + (host, localFilename) = await Shares.ResolveFileAsync(filename.LocalizePath()); localFileInfo = new FileInfo(filename); @@ -223,31 +224,49 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer); }), + disposeInputStreamOnCompletion: true, governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct), reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act), slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); - //using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + if (host == "local") + { + using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - var (stream, completion) = await Network.GetFileUpload("any", filename); + var completedTransfer = await Client.UploadAsync( + username, + filename, + size: localFileInfo.Length, + inputStreamFactory: () => stream, + options: topts, + cancellationToken: cts.Token); - var completedTransfer = await Client.UploadAsync( - username, - filename, - size: localFileInfo.Length, - inputStreamFactory: () => stream, - options: topts, - cancellationToken: cts.Token); + transfer = transfer.WithSoulseekTransfer(completedTransfer); + } + else + { + var (stream, completion) = await Network.GetFileUpload(agent: host, filename); - completion.SetResult(); + using (stream) + { + var completedTransfer = await Client.UploadAsync( + username, + filename, + size: localFileInfo.Length, + inputStreamFactory: () => stream, + options: topts, + cancellationToken: cts.Token); + + completion.SetResult(); + transfer = transfer.WithSoulseekTransfer(completedTransfer); + } + } // explicitly dispose the rate limiter to prevent updates from it // beyond this point, which may overwrite the final state rateLimiter.Dispose(); - transfer = transfer.WithSoulseekTransfer(completedTransfer); - // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); } -- cgit v1.2.3 From ad5b8ffda4f40b6a36100033fc0d96590802f892 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 18:49:19 -0500 Subject: make uploads work (for now) --- src/slskd/Transfers/Uploads/UploadService.cs | 37 +++++++++++++++++----------- 1 file changed, 23 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index d0a599d8..2d07e501 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -113,7 +113,7 @@ namespace slskd.Transfers.Uploads { string host = default; string localFilename = default; - FileInfo localFileInfo = default; + long localFileLength = default; Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename); @@ -121,12 +121,19 @@ namespace slskd.Transfers.Uploads { (host, localFilename) = await Shares.ResolveFileAsync(filename.LocalizePath()); - localFileInfo = new FileInfo(filename); - - if (!localFileInfo.Exists) + if (host == "local") + { + // if it's local, do a quick check to see if it exists to spare the caller from + // queueing up if the transfer is doomed to fail. for remote files, take a leap of faith. + if (!File.Exists(localFilename)) + { + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + } + } + else { - Shares.RequestScan(); - throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + localFileLength = 9001; } } catch (NotFoundException) @@ -135,13 +142,15 @@ namespace slskd.Transfers.Uploads throw new DownloadEnqueueException($"File not shared."); } + Log.Information("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host); + // find existing records for this username and file that haven't been removed from the UI - var existingRecords = List(t => t.Username == username && t.Filename == localFileInfo.FullName && !t.Removed); + var existingRecords = List(t => t.Username == username && t.Filename == localFilename && !t.Removed); // check whether any of these records is in a non-complete state and bail out if so if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed))) { - Log.Information("Upload {Filename} to {Username} is already queued or in progress", localFileInfo.FullName, username); + Log.Information("Upload {Filename} to {Username} is already queued or in progress", localFilename, username); return; } @@ -152,8 +161,8 @@ namespace slskd.Transfers.Uploads Id = id, Username = username, Direction = TransferDirection.Upload, - Filename = localFileInfo.FullName, - Size = localFileInfo.Length, + Filename = localFilename, + Size = localFileLength, StartOffset = 0, // potentially updated later during handshaking RequestedAt = DateTime.UtcNow, }; @@ -198,7 +207,7 @@ namespace slskd.Transfers.Uploads var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFileInfo.FullName, username, args.PreviousState, args.Transfer.State); + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State); if (Application.IsShuttingDown) { @@ -232,12 +241,12 @@ namespace slskd.Transfers.Uploads if (host == "local") { - using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); + using var stream = new FileStream(localFilename, FileMode.Open, FileAccess.Read); var completedTransfer = await Client.UploadAsync( username, filename, - size: localFileInfo.Length, + size: localFileLength, inputStreamFactory: () => stream, options: topts, cancellationToken: cts.Token); @@ -253,7 +262,7 @@ namespace slskd.Transfers.Uploads var completedTransfer = await Client.UploadAsync( username, filename, - size: localFileInfo.Length, + size: localFileLength, inputStreamFactory: () => stream, options: topts, cancellationToken: cts.Token); -- cgit v1.2.3 From 8663b3fac9597f7b0c6ffd8081b99c761a18b326 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:09:41 -0500 Subject: add file info handling --- src/slskd/Network/API/Hubs/NetworkHub.cs | 16 +++- src/slskd/Network/NetworkClient.cs | 25 +++++- src/slskd/Network/NetworkService.cs | 141 ++++++++++++++++++++++--------- 3 files changed, 139 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 6d43e6da..f79fecf2 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -26,6 +26,7 @@ namespace slskd.Network public static class NetworkHubMethods { public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; @@ -41,6 +42,11 @@ namespace slskd.Network // todo: how to send this to the specified agent? return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); } + + public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) + { + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + } } /// @@ -104,7 +110,15 @@ namespace slskd.Network { if (Network.PendingFileUploads.TryGetValue(id, out var record)) { - record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } + + public void ReturnFileInfo(Guid id, bool exists, long length) + { + if (Network.PendingFileInquiries.TryGetValue(id, out var record)) + { + record.TrySetResult((exists, length)); } } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index d171e9b9..6e4e4dca 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -156,7 +156,7 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private async Task HandleFileRequest(Guid id, string filename) + private async Task HandleFileRequest(string filename, Guid id) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -164,7 +164,7 @@ namespace slskd.Network { var localFilename = await Shares.ResolveFileAsync(filename); - var localFileInfo = new FileInfo(filename); + var localFileInfo = new FileInfo(localFilename); if (!localFileInfo.Exists) { @@ -202,6 +202,25 @@ namespace slskd.Network } } + private async Task HandleFileInfoRequest(string filename, Guid id) + { + Log.Information("Network controller requested file info for {Filename} with ID {Id}", filename, id); + + try + { + var localFilename = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(localFilename); + + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message); + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, false, 0); + } + } + private async Task HandleAuthenticationChallenge(string challengeToken) { Log.Debug("Network controller sent an authentication challenge"); @@ -296,7 +315,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 8753ae0a..d857cac5 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -37,11 +37,25 @@ namespace slskd.Network /// ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } + /// + /// Gets the collection of pending Agent file inquiries. + /// + ReadOnlyDictionary> PendingFileInquiries { get; } + /// /// Gets the collection of registered Agents. /// ReadOnlyDictionary RegisteredAgents { get; } + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// The file for which to retrieve information. + /// An optional timeout value. + /// A value indicating whether the file exists, and the length in bytes. + Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000); + /// /// Retrieves an upload of the specified from the specified . /// @@ -131,12 +145,18 @@ namespace slskd.Network /// public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); + /// + /// Gets the collection of pending Agent file inquiries. + /// + public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); + /// /// Gets the collection of registered Agents. /// public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor OptionsMonitor { get; } @@ -144,6 +164,88 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// The file for which to retrieve information. + /// An optional timeout value. + /// A value indicating whether the file exists, and the length in bytes. + public async Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); + + PendingFileInquiryDictionary.TryAdd(id, tcs); + + try + { + await NetworkHub.RequestFileInfoAsync(agent, filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agent, id); + + var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); + + if (task == tcs.Task) + { + return await tcs.Task; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agent}"); + } + } + finally + { + PendingFileInquiryDictionary.TryRemove(id, out _); + } + } + + /// + /// 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)> GetFileUpload(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(); + + PendingFileUploadDictionary.TryAdd(id, (upload, completion)); + + try + { + 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}"); + } + } + finally + { + PendingFileUploadDictionary.TryRemove(id, out _); + } + } + /// /// Retrieves a new share upload token for the specified . /// @@ -249,45 +351,6 @@ namespace slskd.Network 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)> GetFileUpload(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(); - - PendingFileUploadDictionary.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 string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; -- cgit v1.2.3 From add16a356b84c838d1cc9f2d5821f77d2284de1a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:17:06 -0500 Subject: get length from agent --- src/slskd/Network/NetworkClient.cs | 4 ++-- src/slskd/Transfers/Uploads/UploadService.cs | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 6e4e4dca..355e94d6 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -162,7 +162,7 @@ namespace slskd.Network try { - var localFilename = await Shares.ResolveFileAsync(filename); + var (_, localFilename) = await Shares.ResolveFileAsync(filename); var localFileInfo = new FileInfo(localFilename); @@ -208,7 +208,7 @@ namespace slskd.Network try { - var localFilename = await Shares.ResolveFileAsync(filename); + var (_, localFilename) = await Shares.ResolveFileAsync(filename); var localFileInfo = new FileInfo(localFilename); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 2d07e501..58d93e86 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -133,7 +133,15 @@ namespace slskd.Transfers.Uploads } else { - localFileLength = 9001; + var (exists, length) = await Network.GetFileInfo(agent: host, filename); + + if (!exists || length <= 0) + { + // todo: force a remote scan + throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed."); + } + + localFileLength = length; } } catch (NotFoundException) -- cgit v1.2.3 From ed0531fa2e2ec9f310e8932c39160d19f3e80609 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:24:43 -0500 Subject: handle info requests --- src/slskd/Network/NetworkClient.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 355e94d6..baaa1250 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -316,6 +316,7 @@ namespace slskd.Network HubConnection.Closed += HubConnection_Closed; HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.RequestFileInfo, HandleFileInfoRequest); HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; -- cgit v1.2.3 From 61e74d758708edafa5ffc6202b73e1c79c345c66 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Oct 2022 12:42:22 -0500 Subject: bump Soulseek.NET to 6.0.0 preview --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 228522b1..f496703c 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -66,7 +66,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 6efb85b02a6adef59e38555699d8cf1e7c03179d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Oct 2022 12:43:42 -0500 Subject: use async stream factories --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- src/slskd/Transfers/Uploads/UploadService.cs | 34 ++++++++++++------------ 2 files changed, 19 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8913dee1..2f06b665 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -203,7 +203,7 @@ namespace slskd.Transfers.Downloads var completedTransfer = await Client.DownloadAsync( username: username, remoteFilename: file.Filename, - outputStreamFactory: () => GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete), + outputStreamFactory: () => Task.FromResult(GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete)), size: file.Size, startOffset: 0, token: null, @@ -470,7 +470,7 @@ namespace slskd.Transfers.Downloads } } - private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) + private static Stream GetLocalFileStream(string remoteFilename, string saveDirectory) { var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); var path = Path.GetDirectoryName(localFilename); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 58d93e86..4d6b5d5d 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -249,13 +249,11 @@ namespace slskd.Transfers.Uploads if (host == "local") { - using var stream = new FileStream(localFilename, FileMode.Open, FileAccess.Read); - var completedTransfer = await Client.UploadAsync( username, filename, size: localFileLength, - inputStreamFactory: () => stream, + inputStreamFactory: () => Task.FromResult((Stream)new FileStream(localFilename, FileMode.Open, FileAccess.Read)), options: topts, cancellationToken: cts.Token); @@ -263,21 +261,23 @@ namespace slskd.Transfers.Uploads } else { - var (stream, completion) = await Network.GetFileUpload(agent: host, filename); + TaskCompletionSource uploadCompletion = default; - using (stream) - { - var completedTransfer = await Client.UploadAsync( - username, - filename, - size: localFileLength, - inputStreamFactory: () => stream, - options: topts, - cancellationToken: cts.Token); - - completion.SetResult(); - transfer = transfer.WithSoulseekTransfer(completedTransfer); - } + var completedTransfer = await Client.UploadAsync( + username, + filename, + size: localFileLength, + inputStreamFactory: async () => + { + var (stream, completion) = await Network.GetFileUpload(agent: host, filename); + uploadCompletion = completion; + return stream; + }, + options: topts, + cancellationToken: cts.Token); + + uploadCompletion.SetResult(); + transfer = transfer.WithSoulseekTransfer(completedTransfer); } // explicitly dispose the rate limiter to prevent updates from it -- cgit v1.2.3 From 9379a1fa3af07bab44b81752fe808cb9ca94be7a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Oct 2022 13:48:58 -0500 Subject: set length for local transfers --- src/slskd/Transfers/Uploads/UploadService.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 4d6b5d5d..40718af7 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -125,11 +125,15 @@ namespace slskd.Transfers.Uploads { // if it's local, do a quick check to see if it exists to spare the caller from // queueing up if the transfer is doomed to fail. for remote files, take a leap of faith. - if (!File.Exists(localFilename)) + var info = new FileInfo(localFilename); + + if (!info.Exists) { Shares.RequestScan(); throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); } + + localFileLength = info.Length; } else { -- cgit v1.2.3